1 /*
2 * Copyright (c) 2022, 2026, Oracle and/or its affiliates. All rights reserved.
3 * Copyright (c) 2024, Alibaba Group Holding Limited. All Rights Reserved.
4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 *
6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation. Oracle designates this
9 * particular file as subject to the "Classpath" exception as provided
10 * by Oracle in the LICENSE file that accompanied this code.
11 *
12 * This code is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 * version 2 for more details (a copy is included in the LICENSE file that
16 * accompanied this code).
17 *
18 * You should have received a copy of the GNU General Public License version
19 * 2 along with this work; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 *
22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23 * or visit www.oracle.com if you need additional information or have any
24 * questions.
25 *
26 */
27 package jdk.internal.classfile.impl;
28
29 import java.lang.classfile.Attribute;
30 import java.lang.classfile.Attributes;
31 import java.lang.classfile.Label;
32 import java.lang.classfile.attribute.StackMapTableAttribute;
33 import java.lang.classfile.constantpool.*;
34 import java.lang.constant.ClassDesc;
35 import java.lang.constant.MethodTypeDesc;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.List;
39 import java.util.Objects;
40 import java.util.stream.Collectors;
41
42 import jdk.internal.classfile.impl.WritableField.UnsetField;
43 import jdk.internal.constant.ClassOrInterfaceDescImpl;
44 import jdk.internal.util.Preconditions;
45
46 import static java.lang.classfile.ClassFile.*;
47 import static java.lang.classfile.constantpool.PoolEntry.*;
48 import static java.lang.constant.ConstantDescs.*;
49 import static jdk.internal.classfile.impl.RawBytecodeHelper.*;
50
51 /**
52 * StackMapGenerator is responsible for stack map frames generation.
53 * <p>
54 * Stack map frames are computed from serialized bytecode similar way they are verified during class loading process.
55 * <p>
56 * The {@linkplain #generate() frames computation} consists of following steps:
57 * <ol>
58 * <li>{@linkplain #detectFrames() Detection} of mandatory stack map frames:<ul>
59 * <li>Mandatory stack map frame include all jump and switch instructions targets,
60 * offsets immediately following {@linkplain #noControlFlow(int) "no control flow"}
61 * and all exception table handlers.
62 * <li>Detection is performed in a single fast pass through the bytecode,
63 * with no auxiliary structures construction nor further instructions processing.
64 * </ul>
65 * <li>Generator loop {@linkplain #processMethod() processing bytecode instructions}:<ul>
66 * <li>Generator loop simulates sequence instructions {@linkplain #processBlock(RawBytecodeHelper) processing effect on the actual stack and locals}.
67 * <li>All mandatory {@linkplain Frame frames} detected in the step #1 are {@linkplain Frame#checkAssignableTo(Frame) retro-filled}
68 * (or {@linkplain Frame#merge(Type, Type[], int, Frame) reverse-merged} in subsequent processing)
69 * with the actual stack and locals for all matching jump, switch and exception handler targets.
70 * <li>All frames modified by reverse merges are marked as {@linkplain Frame#dirty dirty} for further processing.
71 * <li>Code blocks with not yet known entry frame content are skipped and related frames are also marked as dirty.
72 * <li>Generator loop process is repeated until all mandatory frames are cleared or until an error state is reached.
73 * <li>Generator loop always passes all instructions at least once to calculate {@linkplain #maxStack max stack}
74 * and {@linkplain #maxLocals max locals} code attributes.
75 * <li>More than one pass is usually not necessary, except for more complex bytecode sequences.<br>
76 * <i>(Note: experimental measurements showed that more than 99% of the cases required only single pass to clear all frames,
77 * less than 1% of the cases required second pass and remaining 0,01% of the cases required third pass to clear all frames.)</i>.
78 * </ul>
79 * <li>Dead code patching to pass class loading verification:<ul>
80 * <li>Dead code blocks are indicated by frames remaining without content after leaving the Generator loop.
81 * <li>Each dead code block is filled with <code>NOP</code> instructions, terminated with
82 * <code>ATHROW</code> instruction, and removed from exception handlers table.
83 * <li>Dead code block entry frame is set to <code>java.lang.Throwable</code> single stack item and no locals.
84 * </ul>
85 * </ol>
86 * <p>
87 * {@linkplain Frame#merge(Type, Type[], int, Frame) Reverse-merge} of the stack map frames
88 * may in some situations require to determine {@linkplain ClassHierarchyImpl class hierarchy} relations.
89 * <p>
90 * Reverse-merge of individual {@linkplain Type types} is performed when a target frame has already been retro-filled
91 * and it is necessary to adjust its existing stack entries and locals to also match actual stack map frame conditions.
92 * Following tables describe how new target stack entry or local type is calculated, based on the actual frame stack entry or local ("from")
93 * and actual value of the target stack entry or local ("to").
94 *
95 * <table border="1">
96 * <caption>Reverse-merge of general type categories</caption>
97 * <tr><th>to \ from<th>TOP<th>PRIMITIVE<th>UNINITIALIZED<th>REFERENCE
98 * <tr><th>TOP<td>TOP<td>TOP<td>TOP<td>TOP
99 * <tr><th>PRIMITIVE<td>TOP<td><a href="#primitives">Reverse-merge of primitive types</a><td>TOP<td>TOP
100 * <tr><th>UNINITIALIZED<td>TOP<td>TOP<td>Is NEW offset matching ? UNINITIALIZED : TOP<td>TOP
101 * <tr><th>REFERENCE<td>TOP<td>TOP<td>TOP<td><a href="#references">Reverse-merge of reference types</a>
102 * </table>
103 * <p>
104 * <table id="primitives" border="1">
105 * <caption>Reverse-merge of primitive types</caption>
106 * <tr><th>to \ from<th>SHORT<th>BYTE<th>BOOLEAN<th>LONG<th>DOUBLE<th>FLOAT<th>INTEGER
107 * <tr><th>SHORT<td>SHORT<td>TOP<td>TOP<td>TOP<td>TOP<td>TOP<td>SHORT
108 * <tr><th>BYTE<td>TOP<td>BYTE<td>TOP<td>TOP<td>TOP<td>TOP<td>BYTE
109 * <tr><th>BOOLEAN<td>TOP<td>TOP<td>BOOLEAN<td>TOP<td>TOP<td>TOP<td>BOOLEAN
110 * <tr><th>LONG<td>TOP<td>TOP<td>TOP<td>LONG<td>TOP<td>TOP<td>TOP
111 * <tr><th>DOUBLE<td>TOP<td>TOP<td>TOP<td>TOP<td>DOUBLE<td>TOP<td>TOP
112 * <tr><th>FLOAT<td>TOP<td>TOP<td>TOP<td>TOP<td>TOP<td>FLOAT<td>TOP
113 * <tr><th>INTEGER<td>TOP<td>TOP<td>TOP<td>TOP<td>TOP<td>TOP<td>INTEGER
114 * </table>
115 * <p>
116 * <table id="references" border="1">
117 * <caption>Reverse merge of reference types</caption>
118 * <tr><th>to \ from<th>NULL<th>j.l.Object<th>j.l.Cloneable<th>j.i.Serializable<th>ARRAY<th>INTERFACE*<th>OBJECT**
119 * <tr><th>NULL<td>NULL<td>j.l.Object<td>j.l.Cloneable<td>j.i.Serializable<td>ARRAY<td>INTERFACE<td>OBJECT
120 * <tr><th>j.l.Object<td>j.l.Object<td>j.l.Object<td>j.l.Object<td>j.l.Object<td>j.l.Object<td>j.l.Object<td>j.l.Object
121 * <tr><th>j.l.Cloneable<td>j.l.Cloneable<td>j.l.Cloneable<td>j.l.Cloneable<td>j.l.Cloneable<td>j.l.Object<td>j.l.Cloneable<td>j.l.Cloneable
122 * <tr><th>j.i.Serializable<td>j.i.Serializable<td>j.i.Serializable<td>j.i.Serializable<td>j.i.Serializable<td>j.l.Object<td>j.i.Serializable<td>j.i.Serializable
123 * <tr><th>ARRAY<td>ARRAY<td>j.l.Object<td>j.l.Object<td>j.l.Object<td><a href="#arrays">Reverse merge of arrays</a><td>j.l.Object<td>j.l.Object
124 * <tr><th>INTERFACE*<td>INTERFACE<td>j.l.Object<td>j.l.Object<td>j.l.Object<td>j.l.Object<td>j.l.Object<td>j.l.Object
125 * <tr><th>OBJECT**<td>OBJECT<td>j.l.Object<td>j.l.Object<td>j.l.Object<td>j.l.Object<td>j.l.Object<td>Resolved common ancestor
126 * <tr><td colspan="8">*any interface reference except for j.l.Cloneable and j.i.Serializable<br>**any object reference except for j.l.Object
127 * </table>
128 * <p id="arrays">
129 * Array types are reverse-merged as reference to array type constructed from reverse-merged components.
130 * Reference to j.l.Object is an alternate result when construction of the array type is not possible (when reverse-merge of components returned TOP or other non-reference and non-primitive type).
131 * <p>
132 * Custom class hierarchy resolver has been implemented as a part of the library to avoid heavy class loading
133 * and to allow stack maps generation even for code with incomplete dependency classpath.
134 * However stack maps generated with {@linkplain ClassHierarchyImpl#resolve(java.lang.constant.ClassDesc) warnings of unresolved dependencies} may later fail to verify during class loading process.
135 * <p>
136 * Focus of the whole algorithm is on high performance and low memory footprint:<ul>
137 * <li>It does not produce, collect nor visit any complex intermediate structures
138 * <i>(beside {@linkplain RawBytecodeHelper traversing} the {@linkplain #bytecode bytecode in binary form}).</i>
139 * <li>It works with only minimal mandatory stack map frames.
140 * <li>It does not spend time on any non-essential verifications.
141 * </ul>
142 */
143
144 public final class StackMapGenerator {
145
146 static StackMapGenerator of(DirectCodeBuilder dcb, BufWriterImpl buf) {
147 return new StackMapGenerator(
148 dcb,
149 buf.thisClass().asSymbol(),
150 dcb.methodInfo.methodName().stringValue(),
151 dcb.methodInfo.methodTypeSymbol(),
152 (dcb.methodInfo.methodFlags() & ACC_STATIC) != 0,
153 dcb.bytecodesBufWriter.bytecodeView(),
154 dcb.constantPool,
155 dcb.context,
156 buf.getStrictInstanceFields(),
157 dcb.handlers);
158 }
159
160 private static final String OBJECT_INITIALIZER_NAME = "<init>";
161 private static final int FLAG_THIS_UNINIT = 0x01;
162 private static final int FRAME_DEFAULT_CAPACITY = 10;
163 private static final int T_BOOLEAN = 4, T_LONG = 11;
164 private static final Frame[] EMPTY_FRAME_ARRAY = {};
165
166 public static final int
167 ITEM_TOP = 0,
168 ITEM_INTEGER = 1,
169 ITEM_FLOAT = 2,
170 ITEM_DOUBLE = 3,
171 ITEM_LONG = 4,
172 ITEM_NULL = 5,
173 ITEM_UNINITIALIZED_THIS = 6,
174 ITEM_OBJECT = 7,
175 ITEM_UNINITIALIZED = 8,
176 ITEM_BOOLEAN = 9,
177 ITEM_BYTE = 10,
178 ITEM_SHORT = 11,
179 ITEM_CHAR = 12,
180 ITEM_LONG_2ND = 13,
181 ITEM_DOUBLE_2ND = 14,
182 ITEM_BOGUS = -1;
183
184 // Ranges represented by these constants are inclusive on both ends
185 public static final int
186 SAME_FRAME_END = 63,
187 SAME_LOCALS_1_STACK_ITEM_FRAME_START = 64,
188 SAME_LOCALS_1_STACK_ITEM_FRAME_END = 127,
189 RESERVED_END = 245,
190 EARLY_LARVAL = 246,
191 SAME_LOCALS_1_STACK_ITEM_EXTENDED = 247,
192 CHOP_FRAME_START = 248,
193 CHOP_FRAME_END = 250,
194 SAME_FRAME_EXTENDED = 251,
195 APPEND_FRAME_START = 252,
196 APPEND_FRAME_END = 254,
197 FULL_FRAME = 255;
198
199 private static final Type[] ARRAY_FROM_BASIC_TYPE = {null, null, null, null,
200 Type.BOOLEAN_ARRAY_TYPE, Type.CHAR_ARRAY_TYPE, Type.FLOAT_ARRAY_TYPE, Type.DOUBLE_ARRAY_TYPE,
201 Type.BYTE_ARRAY_TYPE, Type.SHORT_ARRAY_TYPE, Type.INT_ARRAY_TYPE, Type.LONG_ARRAY_TYPE};
202
203 static record RawExceptionCatch(int start, int end, int handler, Type catchType) {}
204
205 private final Type thisType;
206 private final String methodName;
207 private final MethodTypeDesc methodDesc;
208 private final RawBytecodeHelper.CodeRange bytecode;
209 private final SplitConstantPool cp;
210 private final boolean isStatic;
211 private final LabelContext labelContext;
212 private final List<AbstractPseudoInstruction.ExceptionCatchImpl> handlers;
213 private final List<RawExceptionCatch> rawHandlers;
214 private final ClassHierarchyImpl classHierarchy;
215 private final UnsetField[] strictFieldsToPut; // exact-sized, do not modify this copy!
216 private final boolean patchDeadCode;
217 private Frame[] frames = EMPTY_FRAME_ARRAY;
218 private int framesCount = 0;
219 private final Frame currentFrame;
220 private int maxStack, maxLocals;
221
222 /**
223 * Primary constructor of the <code>Generator</code> class.
224 * New <code>Generator</code> instance must be created for each individual class/method.
225 * Instance contains only immutable results, all the calculations are processed during instance construction.
226 *
227 * @param labelContext <code>LabelContext</code> instance used to resolve or patch <code>ExceptionHandler</code>
228 * labels to bytecode offsets (or vice versa)
229 * @param thisClass class to generate stack maps for
230 * @param methodName method name to generate stack maps for
231 * @param methodDesc method descriptor to generate stack maps for
232 * @param isStatic information whether the method is static
233 * @param bytecode R/W <code>ByteBuffer</code> wrapping method bytecode, the content is altered in case <code>Generator</code> detects and patches dead code
234 * @param cp R/W <code>ConstantPoolBuilder</code> instance used to resolve all involved CP entries and also generate new entries referenced from the generated stack maps
235 * @param handlers R/W <code>ExceptionHandler</code> list used to detect mandatory frame offsets as well as to determine stack maps in exception handlers
236 * and also to be altered when dead code is detected and must be excluded from exception handlers
237 */
238 public StackMapGenerator(LabelContext labelContext,
239 ClassDesc thisClass,
240 String methodName,
241 MethodTypeDesc methodDesc,
242 boolean isStatic,
243 RawBytecodeHelper.CodeRange bytecode,
244 SplitConstantPool cp,
245 ClassFileImpl context,
246 UnsetField[] strictFields,
247 List<AbstractPseudoInstruction.ExceptionCatchImpl> handlers) {
248 this.thisType = Type.referenceType(thisClass);
249 this.methodName = methodName;
250 this.methodDesc = methodDesc;
251 this.isStatic = isStatic;
252 this.bytecode = bytecode;
253 this.cp = cp;
254 this.labelContext = labelContext;
255 this.handlers = handlers;
256 this.rawHandlers = new ArrayList<>(handlers.size());
257 this.classHierarchy = new ClassHierarchyImpl(context.classHierarchyResolver());
258 this.patchDeadCode = context.patchDeadCode();
259 this.currentFrame = new Frame(classHierarchy);
260 if (OBJECT_INITIALIZER_NAME.equals(methodName)) {
261 this.strictFieldsToPut = strictFields;
262 } else {
263 this.strictFieldsToPut = UnsetField.EMPTY_ARRAY;
264 }
265 generate();
266 }
267
268 /**
269 * Calculated maximum number of the locals required
270 * @return maximum number of the locals required
271 */
272 public int maxLocals() {
273 return maxLocals;
274 }
275
276 /**
277 * Calculated maximum stack size required
278 * @return maximum stack size required
279 */
280 public int maxStack() {
281 return maxStack;
282 }
283
284 private Frame getFrame(int offset) {
285 //binary search over frames ordered by offset
286 int low = 0;
287 int high = framesCount - 1;
288 while (low <= high) {
289 int mid = (low + high) >>> 1;
290 var f = frames[mid];
291 if (f.offset < offset)
292 low = mid + 1;
293 else if (f.offset > offset)
294 high = mid - 1;
295 else
296 return f;
297 }
298 return null;
299 }
300
301 private void checkJumpTarget(Frame frame, int target) {
302 frame.checkAssignableTo(getFrame(target));
303 }
304
305 private int exMin, exMax;
306
307 private boolean isAnyFrameDirty() {
308 for (int i = 0; i < framesCount; i++) {
309 if (frames[i].dirty) return true;
310 }
311 return false;
312 }
313
314 private void generate() {
315 exMin = bytecode.length();
316 exMax = -1;
317 if (!handlers.isEmpty()) {
318 generateHandlers();
319 }
320 detectFrames();
321 do {
322 processMethod();
323 } while (isAnyFrameDirty());
324 maxLocals = currentFrame.frameMaxLocals;
325 maxStack = currentFrame.frameMaxStack;
326
327 //dead code patching
328 for (int i = 0; i < framesCount; i++) {
329 var frame = frames[i];
330 if (frame.flags == -1) {
331 deadCodePatching(frame, i);
332 }
333 }
334 }
335
336 private void generateHandlers() {
337 var labelContext = this.labelContext;
338 for (int i = 0; i < handlers.size(); i++) {
339 var exhandler = handlers.get(i);
340 int start_pc = labelContext.labelToBci(exhandler.tryStart());
341 int end_pc = labelContext.labelToBci(exhandler.tryEnd());
342 int handler_pc = labelContext.labelToBci(exhandler.handler());
343 if (start_pc >= 0 && end_pc >= 0 && end_pc > start_pc && handler_pc >= 0) {
344 if (start_pc < exMin) exMin = start_pc;
345 if (end_pc > exMax) exMax = end_pc;
346 var catchType = exhandler.catchType();
347 rawHandlers.add(new RawExceptionCatch(start_pc, end_pc, handler_pc,
348 catchType.isPresent() ? cpIndexToType(catchType.get().index(), cp)
349 : Type.THROWABLE_TYPE));
350 }
351 }
352 }
353
354 private void deadCodePatching(Frame frame, int i) {
355 if (!patchDeadCode) throw generatorError("Unable to generate stack map frame for dead code", frame.offset);
356 //patch frame
357 frame.pushStack(Type.THROWABLE_TYPE);
358 if (maxStack < 1) maxStack = 1;
359 int end = (i < framesCount - 1 ? frames[i + 1].offset : bytecode.length()) - 1;
360 //patch bytecode
361 var arr = bytecode.array();
362 Arrays.fill(arr, frame.offset, end, (byte) NOP);
363 arr[end] = (byte) ATHROW;
364 //patch handlers
365 removeRangeFromExcTable(frame.offset, end + 1);
366 }
367
368 private void removeRangeFromExcTable(int rangeStart, int rangeEnd) {
369 var it = handlers.listIterator();
370 while (it.hasNext()) {
371 var e = it.next();
372 int handlerStart = labelContext.labelToBci(e.tryStart());
373 int handlerEnd = labelContext.labelToBci(e.tryEnd());
374 if (rangeStart >= handlerEnd || rangeEnd <= handlerStart) {
375 //out of range
376 continue;
377 }
378 if (rangeStart <= handlerStart) {
379 if (rangeEnd >= handlerEnd) {
380 //complete removal
381 it.remove();
382 } else {
383 //cut from left
384 Label newStart = labelContext.newLabel();
385 labelContext.setLabelTarget(newStart, rangeEnd);
386 it.set(new AbstractPseudoInstruction.ExceptionCatchImpl(e.handler(), newStart, e.tryEnd(), e.catchType()));
387 }
388 } else if (rangeEnd >= handlerEnd) {
389 //cut from right
390 Label newEnd = labelContext.newLabel();
391 labelContext.setLabelTarget(newEnd, rangeStart);
392 it.set(new AbstractPseudoInstruction.ExceptionCatchImpl(e.handler(), e.tryStart(), newEnd, e.catchType()));
393 } else {
394 //split
395 Label newStart = labelContext.newLabel();
396 labelContext.setLabelTarget(newStart, rangeEnd);
397 Label newEnd = labelContext.newLabel();
398 labelContext.setLabelTarget(newEnd, rangeStart);
399 it.set(new AbstractPseudoInstruction.ExceptionCatchImpl(e.handler(), e.tryStart(), newEnd, e.catchType()));
400 it.add(new AbstractPseudoInstruction.ExceptionCatchImpl(e.handler(), newStart, e.tryEnd(), e.catchType()));
401 }
402 }
403 }
404
405 /**
406 * Getter of the generated <code>StackMapTableAttribute</code> or null if stack map is empty
407 * @return <code>StackMapTableAttribute</code> or null if stack map is empty
408 */
409 public Attribute<? extends StackMapTableAttribute> stackMapTableAttribute() {
410 return framesCount == 0 ? null : new UnboundAttribute.AdHocAttribute<>(Attributes.stackMapTable()) {
411 @Override
412 public void writeBody(BufWriterImpl b) {
413 if (framesCount != (char) framesCount) {
414 throw generatorError("Too many frames: " + framesCount);
415 }
416 b.writeU2(framesCount);
417 Frame prevFrame = new Frame(classHierarchy);
418 prevFrame.setLocalsFromArg(methodName, methodDesc, isStatic, thisType, strictFieldsToPut);
419 prevFrame.trimAndCompress();
420 for (int i = 0; i < framesCount; i++) {
421 var fr = frames[i];
422 fr.trimAndCompress();
423 fr.writeTo(b, prevFrame, cp);
424 prevFrame = fr;
425 }
426 }
427
428 @Override
429 public Utf8Entry attributeName() {
430 return cp.utf8Entry(Attributes.NAME_STACK_MAP_TABLE);
431 }
432 };
433 }
434
435 private static Type cpIndexToType(int index, ConstantPoolBuilder cp) {
436 return Type.referenceType(cp.entryByIndex(index, ClassEntry.class).asSymbol());
437 }
438
439 private void processMethod() {
440 var frames = this.frames;
441 var currentFrame = this.currentFrame;
442 currentFrame.setLocalsFromArg(methodName, methodDesc, isStatic, thisType, strictFieldsToPut);
443 currentFrame.stackSize = 0;
444 currentFrame.offset = -1;
445 int stackmapIndex = 0;
446 var bcs = bytecode.start();
447 boolean ncf = false;
448 while (bcs.next()) {
449 currentFrame.offset = bcs.bci();
450 if (stackmapIndex < framesCount) {
451 int thisOffset = frames[stackmapIndex].offset;
452 if (ncf && thisOffset > bcs.bci()) {
453 throw generatorError("Expecting a stack map frame");
454 }
455 if (thisOffset == bcs.bci()) {
456 Frame nextFrame = frames[stackmapIndex++];
457 if (!ncf) {
458 currentFrame.checkAssignableTo(nextFrame);
459 }
460 while (!nextFrame.dirty) { //skip unmatched frames
461 if (stackmapIndex == framesCount) return; //skip the rest of this round
462 nextFrame = frames[stackmapIndex++];
463 }
464 bcs.reset(nextFrame.offset); //skip code up-to the next frame
465 bcs.next();
466 currentFrame.offset = bcs.bci();
467 currentFrame.copyFrom(nextFrame);
468 nextFrame.dirty = false;
469 } else if (thisOffset < bcs.bci()) {
470 throw generatorError("Bad stack map offset");
471 }
472 } else if (ncf) {
473 throw generatorError("Expecting a stack map frame");
474 }
475 ncf = processBlock(bcs);
476 }
477 }
478
479 private boolean processBlock(RawBytecodeHelper bcs) {
480 int opcode = bcs.opcode();
481 boolean ncf = false;
482 boolean this_uninit = false;
483 boolean verified_exc_handlers = false;
484 int bci = bcs.bci();
485 Type type1, type2, type3, type4;
486 if ((RawBytecodeHelper.isStoreIntoLocal(opcode) || (opcode == PUTFIELD && OBJECT_INITIALIZER_NAME.equals(methodName)))
487 && bci >= exMin && bci < exMax) {
488 processExceptionHandlerTargets(bci, this_uninit);
489 verified_exc_handlers = true;
490 }
491 switch (opcode) {
492 case NOP -> {}
493 case RETURN -> {
494 ncf = true;
495 }
496 case ACONST_NULL ->
497 currentFrame.pushStack(Type.NULL_TYPE);
498 case ICONST_M1, ICONST_0, ICONST_1, ICONST_2, ICONST_3, ICONST_4, ICONST_5, SIPUSH, BIPUSH ->
499 currentFrame.pushStack(Type.INTEGER_TYPE);
500 case LCONST_0, LCONST_1 ->
501 currentFrame.pushStack(Type.LONG_TYPE, Type.LONG2_TYPE);
502 case FCONST_0, FCONST_1, FCONST_2 ->
503 currentFrame.pushStack(Type.FLOAT_TYPE);
504 case DCONST_0, DCONST_1 ->
505 currentFrame.pushStack(Type.DOUBLE_TYPE, Type.DOUBLE2_TYPE);
506 case LDC ->
507 processLdc(bcs.getIndexU1());
508 case LDC_W, LDC2_W ->
509 processLdc(bcs.getIndexU2());
510 case ILOAD ->
511 currentFrame.checkLocal(bcs.getIndex()).pushStack(Type.INTEGER_TYPE);
512 case ILOAD_0, ILOAD_1, ILOAD_2, ILOAD_3 ->
513 currentFrame.checkLocal(opcode - ILOAD_0).pushStack(Type.INTEGER_TYPE);
514 case LLOAD ->
515 currentFrame.checkLocal(bcs.getIndex() + 1).pushStack(Type.LONG_TYPE, Type.LONG2_TYPE);
516 case LLOAD_0, LLOAD_1, LLOAD_2, LLOAD_3 ->
517 currentFrame.checkLocal(opcode - LLOAD_0 + 1).pushStack(Type.LONG_TYPE, Type.LONG2_TYPE);
518 case FLOAD ->
519 currentFrame.checkLocal(bcs.getIndex()).pushStack(Type.FLOAT_TYPE);
520 case FLOAD_0, FLOAD_1, FLOAD_2, FLOAD_3 ->
521 currentFrame.checkLocal(opcode - FLOAD_0).pushStack(Type.FLOAT_TYPE);
522 case DLOAD ->
523 currentFrame.checkLocal(bcs.getIndex() + 1).pushStack(Type.DOUBLE_TYPE, Type.DOUBLE2_TYPE);
524 case DLOAD_0, DLOAD_1, DLOAD_2, DLOAD_3 ->
525 currentFrame.checkLocal(opcode - DLOAD_0 + 1).pushStack(Type.DOUBLE_TYPE, Type.DOUBLE2_TYPE);
526 case ALOAD ->
527 currentFrame.pushStack(currentFrame.getLocal(bcs.getIndex()));
528 case ALOAD_0, ALOAD_1, ALOAD_2, ALOAD_3 ->
529 currentFrame.pushStack(currentFrame.getLocal(opcode - ALOAD_0));
530 case IALOAD, BALOAD, CALOAD, SALOAD ->
531 currentFrame.decStack(2).pushStack(Type.INTEGER_TYPE);
532 case LALOAD ->
533 currentFrame.decStack(2).pushStack(Type.LONG_TYPE, Type.LONG2_TYPE);
534 case FALOAD ->
535 currentFrame.decStack(2).pushStack(Type.FLOAT_TYPE);
536 case DALOAD ->
537 currentFrame.decStack(2).pushStack(Type.DOUBLE_TYPE, Type.DOUBLE2_TYPE);
538 case AALOAD ->
539 currentFrame.pushStack((type1 = currentFrame.decStack(1).popStack()) == Type.NULL_TYPE ? Type.NULL_TYPE : type1.getComponent());
540 case ISTORE ->
541 currentFrame.decStack(1).setLocal(bcs.getIndex(), Type.INTEGER_TYPE);
542 case ISTORE_0, ISTORE_1, ISTORE_2, ISTORE_3 ->
543 currentFrame.decStack(1).setLocal(opcode - ISTORE_0, Type.INTEGER_TYPE);
544 case LSTORE ->
545 currentFrame.decStack(2).setLocal2(bcs.getIndex(), Type.LONG_TYPE, Type.LONG2_TYPE);
546 case LSTORE_0, LSTORE_1, LSTORE_2, LSTORE_3 ->
547 currentFrame.decStack(2).setLocal2(opcode - LSTORE_0, Type.LONG_TYPE, Type.LONG2_TYPE);
548 case FSTORE ->
549 currentFrame.decStack(1).setLocal(bcs.getIndex(), Type.FLOAT_TYPE);
550 case FSTORE_0, FSTORE_1, FSTORE_2, FSTORE_3 ->
551 currentFrame.decStack(1).setLocal(opcode - FSTORE_0, Type.FLOAT_TYPE);
552 case DSTORE ->
553 currentFrame.decStack(2).setLocal2(bcs.getIndex(), Type.DOUBLE_TYPE, Type.DOUBLE2_TYPE);
554 case DSTORE_0, DSTORE_1, DSTORE_2, DSTORE_3 ->
555 currentFrame.decStack(2).setLocal2(opcode - DSTORE_0, Type.DOUBLE_TYPE, Type.DOUBLE2_TYPE);
556 case ASTORE ->
557 currentFrame.setLocal(bcs.getIndex(), currentFrame.popStack());
558 case ASTORE_0, ASTORE_1, ASTORE_2, ASTORE_3 ->
559 currentFrame.setLocal(opcode - ASTORE_0, currentFrame.popStack());
560 case LASTORE, DASTORE ->
561 currentFrame.decStack(4);
562 case IASTORE, BASTORE, CASTORE, SASTORE, FASTORE, AASTORE ->
563 currentFrame.decStack(3);
564 case POP, MONITORENTER, MONITOREXIT ->
565 currentFrame.decStack(1);
566 case POP2 ->
567 currentFrame.decStack(2);
568 case DUP ->
569 currentFrame.pushStack(type1 = currentFrame.popStack()).pushStack(type1);
570 case DUP_X1 -> {
571 type1 = currentFrame.popStack();
572 type2 = currentFrame.popStack();
573 currentFrame.pushStack(type1).pushStack(type2).pushStack(type1);
574 }
575 case DUP_X2 -> {
576 type1 = currentFrame.popStack();
577 type2 = currentFrame.popStack();
578 type3 = currentFrame.popStack();
579 currentFrame.pushStack(type1).pushStack(type3).pushStack(type2).pushStack(type1);
580 }
581 case DUP2 -> {
582 type1 = currentFrame.popStack();
583 type2 = currentFrame.popStack();
584 currentFrame.pushStack(type2).pushStack(type1).pushStack(type2).pushStack(type1);
585 }
586 case DUP2_X1 -> {
587 type1 = currentFrame.popStack();
588 type2 = currentFrame.popStack();
589 type3 = currentFrame.popStack();
590 currentFrame.pushStack(type2).pushStack(type1).pushStack(type3).pushStack(type2).pushStack(type1);
591 }
592 case DUP2_X2 -> {
593 type1 = currentFrame.popStack();
594 type2 = currentFrame.popStack();
595 type3 = currentFrame.popStack();
596 type4 = currentFrame.popStack();
597 currentFrame.pushStack(type2).pushStack(type1).pushStack(type4).pushStack(type3).pushStack(type2).pushStack(type1);
598 }
599 case SWAP -> {
600 type1 = currentFrame.popStack();
601 type2 = currentFrame.popStack();
602 currentFrame.pushStack(type1);
603 currentFrame.pushStack(type2);
604 }
605 case IADD, ISUB, IMUL, IDIV, IREM, ISHL, ISHR, IUSHR, IOR, IXOR, IAND ->
606 currentFrame.decStack(2).pushStack(Type.INTEGER_TYPE);
607 case INEG, ARRAYLENGTH, INSTANCEOF ->
608 currentFrame.decStack(1).pushStack(Type.INTEGER_TYPE);
609 case LADD, LSUB, LMUL, LDIV, LREM, LAND, LOR, LXOR ->
610 currentFrame.decStack(4).pushStack(Type.LONG_TYPE, Type.LONG2_TYPE);
611 case LNEG ->
612 currentFrame.decStack(2).pushStack(Type.LONG_TYPE, Type.LONG2_TYPE);
613 case LSHL, LSHR, LUSHR ->
614 currentFrame.decStack(3).pushStack(Type.LONG_TYPE, Type.LONG2_TYPE);
615 case FADD, FSUB, FMUL, FDIV, FREM ->
616 currentFrame.decStack(2).pushStack(Type.FLOAT_TYPE);
617 case FNEG ->
618 currentFrame.decStack(1).pushStack(Type.FLOAT_TYPE);
619 case DADD, DSUB, DMUL, DDIV, DREM ->
620 currentFrame.decStack(4).pushStack(Type.DOUBLE_TYPE, Type.DOUBLE2_TYPE);
621 case DNEG ->
622 currentFrame.decStack(2).pushStack(Type.DOUBLE_TYPE, Type.DOUBLE2_TYPE);
623 case IINC ->
624 currentFrame.checkLocal(bcs.getIndex());
625 case I2L ->
626 currentFrame.decStack(1).pushStack(Type.LONG_TYPE, Type.LONG2_TYPE);
627 case L2I ->
628 currentFrame.decStack(2).pushStack(Type.INTEGER_TYPE);
629 case I2F ->
630 currentFrame.decStack(1).pushStack(Type.FLOAT_TYPE);
631 case I2D ->
632 currentFrame.decStack(1).pushStack(Type.DOUBLE_TYPE, Type.DOUBLE2_TYPE);
633 case L2F ->
634 currentFrame.decStack(2).pushStack(Type.FLOAT_TYPE);
635 case L2D ->
636 currentFrame.decStack(2).pushStack(Type.DOUBLE_TYPE, Type.DOUBLE2_TYPE);
637 case F2I ->
638 currentFrame.decStack(1).pushStack(Type.INTEGER_TYPE);
639 case F2L ->
640 currentFrame.decStack(1).pushStack(Type.LONG_TYPE, Type.LONG2_TYPE);
641 case F2D ->
642 currentFrame.decStack(1).pushStack(Type.DOUBLE_TYPE, Type.DOUBLE2_TYPE);
643 case D2L ->
644 currentFrame.decStack(2).pushStack(Type.LONG_TYPE, Type.LONG2_TYPE);
645 case D2F ->
646 currentFrame.decStack(2).pushStack(Type.FLOAT_TYPE);
647 case I2B, I2C, I2S ->
648 currentFrame.decStack(1).pushStack(Type.INTEGER_TYPE);
649 case LCMP, DCMPL, DCMPG ->
650 currentFrame.decStack(4).pushStack(Type.INTEGER_TYPE);
651 case FCMPL, FCMPG, D2I ->
652 currentFrame.decStack(2).pushStack(Type.INTEGER_TYPE);
653 case IF_ICMPEQ, IF_ICMPNE, IF_ICMPLT, IF_ICMPGE, IF_ICMPGT, IF_ICMPLE, IF_ACMPEQ, IF_ACMPNE ->
654 checkJumpTarget(currentFrame.decStack(2), bcs.dest());
655 case IFEQ, IFNE, IFLT, IFGE, IFGT, IFLE, IFNULL, IFNONNULL ->
656 checkJumpTarget(currentFrame.decStack(1), bcs.dest());
657 case GOTO -> {
658 checkJumpTarget(currentFrame, bcs.dest());
659 ncf = true;
660 }
661 case GOTO_W -> {
662 checkJumpTarget(currentFrame, bcs.destW());
663 ncf = true;
664 }
665 case TABLESWITCH, LOOKUPSWITCH -> {
666 processSwitch(bcs);
667 ncf = true;
668 }
669 case LRETURN, DRETURN -> {
670 currentFrame.decStack(2);
671 ncf = true;
672 }
673 case IRETURN, FRETURN, ARETURN, ATHROW -> {
674 currentFrame.decStack(1);
675 ncf = true;
676 }
677 case GETSTATIC, PUTSTATIC, GETFIELD, PUTFIELD ->
678 processFieldInstructions(bcs);
679 case INVOKEVIRTUAL, INVOKESPECIAL, INVOKESTATIC, INVOKEINTERFACE, INVOKEDYNAMIC ->
680 this_uninit = processInvokeInstructions(bcs, (bci >= exMin && bci < exMax), this_uninit);
681 case NEW ->
682 currentFrame.pushStack(Type.uninitializedType(bci));
683 case NEWARRAY ->
684 currentFrame.decStack(1).pushStack(getNewarrayType(bcs.getIndex()));
685 case ANEWARRAY ->
686 processAnewarray(bcs.getIndexU2());
687 case CHECKCAST ->
688 currentFrame.decStack(1).pushStack(cpIndexToType(bcs.getIndexU2(), cp));
689 case MULTIANEWARRAY -> {
690 type1 = cpIndexToType(bcs.getIndexU2(), cp);
691 int dim = bcs.getU1Unchecked(bcs.bci() + 3);
692 for (int i = 0; i < dim; i++) {
693 currentFrame.popStack();
694 }
695 currentFrame.pushStack(type1);
696 }
697 case JSR, JSR_W, RET ->
698 throw generatorError("Instructions jsr, jsr_w, or ret must not appear in the class file version >= 51.0");
699 default ->
700 throw generatorError(String.format("Bad instruction: %02x", opcode));
701 }
702 if (!verified_exc_handlers && bci >= exMin && bci < exMax) {
703 processExceptionHandlerTargets(bci, this_uninit);
704 }
705 return ncf;
706 }
707
708 private void processExceptionHandlerTargets(int bci, boolean this_uninit) {
709 for (var ex : rawHandlers) {
710 if (bci == ex.start || (currentFrame.localsOrUnsetsChanged && bci > ex.start && bci < ex.end)) {
711 int flags = currentFrame.flags;
712 if (this_uninit) flags |= FLAG_THIS_UNINIT;
713 Frame newFrame = currentFrame.frameInExceptionHandler(flags, ex.catchType);
714 checkJumpTarget(newFrame, ex.handler);
715 }
716 }
717 currentFrame.localsOrUnsetsChanged = false;
718 }
719
720 private void processLdc(int index) {
721 switch (cp.entryByIndex(index).tag()) {
722 case TAG_UTF8 ->
723 currentFrame.pushStack(Type.OBJECT_TYPE);
724 case TAG_STRING ->
725 currentFrame.pushStack(Type.STRING_TYPE);
726 case TAG_CLASS ->
727 currentFrame.pushStack(Type.CLASS_TYPE);
728 case TAG_INTEGER ->
729 currentFrame.pushStack(Type.INTEGER_TYPE);
730 case TAG_FLOAT ->
731 currentFrame.pushStack(Type.FLOAT_TYPE);
732 case TAG_DOUBLE ->
733 currentFrame.pushStack(Type.DOUBLE_TYPE, Type.DOUBLE2_TYPE);
734 case TAG_LONG ->
735 currentFrame.pushStack(Type.LONG_TYPE, Type.LONG2_TYPE);
736 case TAG_METHOD_HANDLE ->
737 currentFrame.pushStack(Type.METHOD_HANDLE_TYPE);
738 case TAG_METHOD_TYPE ->
739 currentFrame.pushStack(Type.METHOD_TYPE);
740 case TAG_DYNAMIC ->
741 currentFrame.pushStack(cp.entryByIndex(index, ConstantDynamicEntry.class).typeSymbol());
742 default ->
743 throw generatorError("CP entry #%d %s is not loadable constant".formatted(index, cp.entryByIndex(index).tag()));
744 }
745 }
746
747 private void processSwitch(RawBytecodeHelper bcs) {
748 int bci = bcs.bci();
749 int alignedBci = RawBytecodeHelper.align(bci + 1);
750 int defaultOffset = bcs.getIntUnchecked(alignedBci);
751 int keys, delta;
752 currentFrame.popStack();
753 if (bcs.opcode() == TABLESWITCH) {
754 int low = bcs.getIntUnchecked(alignedBci + 4);
755 int high = bcs.getIntUnchecked(alignedBci + 2 * 4);
756 if (low > high) {
757 throw generatorError("low must be less than or equal to high in tableswitch");
758 }
759 keys = high - low + 1;
760 if (keys < 0) {
761 throw generatorError("too many keys in tableswitch");
762 }
763 delta = 1;
764 } else {
765 keys = bcs.getIntUnchecked(alignedBci + 4);
766 if (keys < 0) {
767 throw generatorError("number of keys in lookupswitch less than 0");
768 }
769 delta = 2;
770 for (int i = 0; i < (keys - 1); i++) {
771 int this_key = bcs.getIntUnchecked(alignedBci + (2 + 2 * i) * 4);
772 int next_key = bcs.getIntUnchecked(alignedBci + (2 + 2 * i + 2) * 4);
773 if (this_key >= next_key) {
774 throw generatorError("Bad lookupswitch instruction");
775 }
776 }
777 }
778 int target = bci + defaultOffset;
779 checkJumpTarget(currentFrame, target);
780 for (int i = 0; i < keys; i++) {
781 target = bci + bcs.getIntUnchecked(alignedBci + (3 + i * delta) * 4);
782 checkJumpTarget(currentFrame, target);
783 }
784 }
785
786 private void processFieldInstructions(RawBytecodeHelper bcs) {
787 var nameAndType = cp.entryByIndex(bcs.getIndexU2(), MemberRefEntry.class).nameAndType();
788 var desc = Util.fieldTypeSymbol(nameAndType.type());
789 var currentFrame = this.currentFrame;
790 switch (bcs.opcode()) {
791 case GETSTATIC ->
792 currentFrame.pushStack(desc);
793 case PUTSTATIC -> {
794 currentFrame.decStack(Util.isDoubleSlot(desc) ? 2 : 1);
795 }
796 case GETFIELD -> {
797 currentFrame.decStack(1);
798 currentFrame.pushStack(desc);
799 }
800 case PUTFIELD -> {
801 if (strictFieldsToPut.length > 0) {
802 currentFrame.putStrictField(nameAndType);
803 }
804 currentFrame.decStack(Util.isDoubleSlot(desc) ? 3 : 2);
805 }
806 default -> throw new AssertionError("Should not reach here");
807 }
808 }
809
810 private boolean processInvokeInstructions(RawBytecodeHelper bcs, boolean inTryBlock, boolean thisUninit) {
811 int index = bcs.getIndexU2();
812 int opcode = bcs.opcode();
813 var nameAndType = opcode == INVOKEDYNAMIC
814 ? cp.entryByIndex(index, InvokeDynamicEntry.class).nameAndType()
815 : cp.entryByIndex(index, MemberRefEntry.class).nameAndType();
816 var mDesc = Util.methodTypeSymbol(nameAndType.type());
817 int bci = bcs.bci();
818 var currentFrame = this.currentFrame;
819 currentFrame.decStack(Util.parameterSlots(mDesc));
820 if (opcode != INVOKESTATIC && opcode != INVOKEDYNAMIC) {
821 if (nameAndType.name().equalsString(OBJECT_INITIALIZER_NAME)) {
822 Type type = currentFrame.popStack();
823 if (type == Type.UNITIALIZED_THIS_TYPE) {
824 if (inTryBlock) {
825 processExceptionHandlerTargets(bci, true);
826 }
827 var owner = cp.entryByIndex(index, MemberRefEntry.class).owner();
828 if (!owner.name().equalsString(((ClassOrInterfaceDescImpl) thisType.sym).internalName())
829 && currentFrame.unsetFieldsSize != 0) {
830 throw generatorError("Unset fields mismatch");
831 }
832 currentFrame.initializeObject(type, thisType);
833 currentFrame.unsetFieldsSize = 0;
834 currentFrame.unsetFields = UnsetField.EMPTY_ARRAY;
835 thisUninit = true;
836 } else if (type.tag == ITEM_UNINITIALIZED) {
837 Type new_class_type = cpIndexToType(bcs.getU2(type.bci + 1), cp);
838 if (inTryBlock) {
839 processExceptionHandlerTargets(bci, thisUninit);
840 }
841 currentFrame.initializeObject(type, new_class_type);
842 } else {
843 throw generatorError("Bad operand type when invoking <init>");
844 }
845 } else {
846 currentFrame.decStack(1);
847 }
848 }
849 currentFrame.pushStack(mDesc.returnType());
850 return thisUninit;
851 }
852
853 private Type getNewarrayType(int index) {
854 if (index < T_BOOLEAN || index > T_LONG) throw generatorError("Illegal newarray instruction type %d".formatted(index));
855 return ARRAY_FROM_BASIC_TYPE[index];
856 }
857
858 private void processAnewarray(int index) {
859 currentFrame.popStack();
860 currentFrame.pushStack(cpIndexToType(index, cp).toArray());
861 }
862
863 /**
864 * {@return the generator error with attached details}
865 * @param msg error message
866 */
867 private IllegalArgumentException generatorError(String msg) {
868 return generatorError(msg, currentFrame.offset);
869 }
870
871 /**
872 * {@return the generator error with attached details}
873 * @param msg error message
874 * @param offset bytecode offset where the error occurred
875 */
876 private IllegalArgumentException generatorError(String msg, int offset) {
877 var sb = new StringBuilder("%s at bytecode offset %d of method %s(%s)".formatted(
878 msg,
879 offset,
880 methodName,
881 methodDesc.parameterList().stream().map(ClassDesc::displayName).collect(Collectors.joining(","))));
882 Util.dumpMethod(cp, thisType.sym(), methodName, methodDesc, isStatic ? ACC_STATIC : 0, bytecode, sb::append);
883 return new IllegalArgumentException(sb.toString());
884 }
885
886 /**
887 * Performs detection of mandatory stack map frames in a single bytecode traversing pass
888 * @return detected frames
889 */
890 private void detectFrames() {
891 var bcs = bytecode.start();
892 boolean no_control_flow = false;
893 int opcode, bci = 0;
894 while (bcs.next()) try {
895 opcode = bcs.opcode();
896 bci = bcs.bci();
897 if (no_control_flow) {
898 addFrame(bci);
899 }
900 no_control_flow = switch (opcode) {
901 case GOTO -> {
902 addFrame(bcs.dest());
903 yield true;
904 }
905 case GOTO_W -> {
906 addFrame(bcs.destW());
907 yield true;
908 }
909 case IF_ICMPEQ, IF_ICMPNE, IF_ICMPLT, IF_ICMPGE,
910 IF_ICMPGT, IF_ICMPLE, IFEQ, IFNE,
911 IFLT, IFGE, IFGT, IFLE, IF_ACMPEQ,
912 IF_ACMPNE , IFNULL , IFNONNULL -> {
913 addFrame(bcs.dest());
914 yield false;
915 }
916 case TABLESWITCH, LOOKUPSWITCH -> {
917 int aligned_bci = RawBytecodeHelper.align(bci + 1);
918 int default_ofset = bcs.getIntUnchecked(aligned_bci);
919 int keys, delta;
920 if (bcs.opcode() == TABLESWITCH) {
921 int low = bcs.getIntUnchecked(aligned_bci + 4);
922 int high = bcs.getIntUnchecked(aligned_bci + 2 * 4);
923 keys = high - low + 1;
924 delta = 1;
925 } else {
926 keys = bcs.getIntUnchecked(aligned_bci + 4);
927 delta = 2;
928 }
929 addFrame(bci + default_ofset);
930 for (int i = 0; i < keys; i++) {
931 addFrame(bci + bcs.getIntUnchecked(aligned_bci + (3 + i * delta) * 4));
932 }
933 yield true;
934 }
935 case IRETURN, LRETURN, FRETURN, DRETURN,
936 ARETURN, RETURN, ATHROW -> true;
937 default -> false;
938 };
939 } catch (IllegalArgumentException iae) {
940 throw generatorError("Detected branch target out of bytecode range", bci);
941 }
942 for (int i = 0; i < rawHandlers.size(); i++) try {
943 addFrame(rawHandlers.get(i).handler());
944 } catch (IllegalArgumentException iae) {
945 throw generatorError("Detected exception handler out of bytecode range");
946 }
947 }
948
949 private void addFrame(int offset) {
950 Preconditions.checkIndex(offset, bytecode.length(), RawBytecodeHelper.IAE_FORMATTER);
951 var frames = this.frames;
952 int i = 0, framesCount = this.framesCount;
953 for (; i < framesCount; i++) {
954 var frameOffset = frames[i].offset;
955 if (frameOffset == offset) {
956 return;
957 }
958 if (frameOffset > offset) {
959 break;
960 }
961 }
962 if (framesCount >= frames.length) {
963 int newCapacity = framesCount + 8;
964 this.frames = frames = framesCount == 0 ? new Frame[newCapacity] : Arrays.copyOf(frames, newCapacity);
965 }
966 if (i != framesCount) {
967 System.arraycopy(frames, i, frames, i + 1, framesCount - i);
968 }
969 frames[i] = new Frame(offset, classHierarchy);
970 this.framesCount = framesCount + 1;
971 }
972
973 private final class Frame {
974
975 int offset;
976 int localsSize, stackSize, unsetFieldsSize;
977 int flags;
978 int frameMaxStack = 0, frameMaxLocals = 0;
979 boolean dirty = false;
980 boolean localsOrUnsetsChanged = false;
981
982 private final ClassHierarchyImpl classHierarchy;
983
984 private Type[] locals, stack;
985 private UnsetField[] unsetFields; // sorted, modifiable oversized array
986
987 Frame(ClassHierarchyImpl classHierarchy) {
988 this(-1, 0, 0, 0, 0, null, null, UnsetField.EMPTY_ARRAY, classHierarchy);
989 }
990
991 Frame(int offset, ClassHierarchyImpl classHierarchy) {
992 this(offset, -1, 0, 0, 0, null, null, UnsetField.EMPTY_ARRAY, classHierarchy);
993 }
994
995 Frame(int offset, int flags, int locals_size, int stack_size, int unsetFieldsSize, Type[] locals, Type[] stack, UnsetField[] unsetFields, ClassHierarchyImpl classHierarchy) {
996 this.offset = offset;
997 this.localsSize = locals_size;
998 this.stackSize = stack_size;
999 this.unsetFieldsSize = unsetFieldsSize;
1000 this.flags = flags;
1001 this.locals = locals;
1002 this.stack = stack;
1003 this.unsetFields = unsetFields;
1004 this.classHierarchy = classHierarchy;
1005 }
1006
1007 @Override
1008 public String toString() {
1009 return (dirty ? "frame* @" : "frame @") + offset +
1010 " with locals " + (locals == null ? "[]" : Arrays.asList(locals).subList(0, localsSize)) +
1011 " and stack " + (stack == null ? "[]" : Arrays.asList(stack).subList(0, stackSize)) +
1012 " and unset fields " + (unsetFields == null ? "[]" : Arrays.asList(unsetFields).subList(0, unsetFieldsSize));
1013 }
1014
1015 Frame pushStack(ClassDesc desc) {
1016 if (desc == CD_long) return pushStack(Type.LONG_TYPE, Type.LONG2_TYPE);
1017 if (desc == CD_double) return pushStack(Type.DOUBLE_TYPE, Type.DOUBLE2_TYPE);
1018 return desc == CD_void ? this
1019 : pushStack(
1020 desc.isPrimitive()
1021 ? (desc == CD_float ? Type.FLOAT_TYPE : Type.INTEGER_TYPE)
1022 : Type.referenceType(desc));
1023 }
1024
1025 Frame pushStack(Type type) {
1026 checkStack(stackSize);
1027 stack[stackSize++] = type;
1028 return this;
1029 }
1030
1031 Frame pushStack(Type type1, Type type2) {
1032 checkStack(stackSize + 1);
1033 stack[stackSize++] = type1;
1034 stack[stackSize++] = type2;
1035 return this;
1036 }
1037
1038 Type popStack() {
1039 if (stackSize < 1) throw generatorError("Operand stack underflow");
1040 return stack[--stackSize];
1041 }
1042
1043 Frame decStack(int size) {
1044 stackSize -= size;
1045 if (stackSize < 0) throw generatorError("Operand stack underflow");
1046 return this;
1047 }
1048
1049 Frame frameInExceptionHandler(int flags, Type excType) {
1050 return new Frame(offset, flags, localsSize, 1, unsetFieldsSize,
1051 locals, new Type[] {excType}, unsetFields, classHierarchy);
1052 }
1053
1054 void initializeObject(Type old_object, Type new_object) {
1055 int i;
1056 for (i = 0; i < localsSize; i++) {
1057 if (locals[i].equals(old_object)) {
1058 locals[i] = new_object;
1059 localsOrUnsetsChanged = true;
1060 }
1061 }
1062 for (i = 0; i < stackSize; i++) {
1063 if (stack[i].equals(old_object)) {
1064 stack[i] = new_object;
1065 }
1066 }
1067 if (old_object == Type.UNITIALIZED_THIS_TYPE) {
1068 flags &= ~FLAG_THIS_UNINIT;
1069 assert flags == 0 : flags;
1070 }
1071 }
1072
1073 Frame checkLocal(int index) {
1074 if (index >= frameMaxLocals) frameMaxLocals = index + 1;
1075 if (locals == null) {
1076 locals = new Type[index + FRAME_DEFAULT_CAPACITY];
1077 Arrays.fill(locals, Type.TOP_TYPE);
1078 } else if (index >= locals.length) {
1079 int current = locals.length;
1080 locals = Arrays.copyOf(locals, index + FRAME_DEFAULT_CAPACITY);
1081 Arrays.fill(locals, current, locals.length, Type.TOP_TYPE);
1082 }
1083 return this;
1084 }
1085
1086 void putStrictField(NameAndTypeEntry nat) {
1087 int shift = 0;
1088 var array = unsetFields;
1089 for (int i = 0; i < unsetFieldsSize; i++) {
1090 var f = array[i];
1091 if (f.name().equals(nat.name()) && f.type().equals(nat.type())) {
1092 shift++;
1093 } else if (shift != 0) {
1094 array[i - shift] = array[i];
1095 array[i] = null;
1096 }
1097 }
1098 if (shift > 1) {
1099 throw generatorError(nat + "; discovered " + shift);
1100 } else if (shift == 1) {
1101 localsOrUnsetsChanged = true;
1102 }
1103 unsetFieldsSize -= shift;
1104 }
1105
1106 private void checkStack(int index) {
1107 if (index >= frameMaxStack) frameMaxStack = index + 1;
1108 if (stack == null) {
1109 stack = new Type[index + FRAME_DEFAULT_CAPACITY];
1110 Arrays.fill(stack, Type.TOP_TYPE);
1111 } else if (index >= stack.length) {
1112 int current = stack.length;
1113 stack = Arrays.copyOf(stack, index + FRAME_DEFAULT_CAPACITY);
1114 Arrays.fill(stack, current, stack.length, Type.TOP_TYPE);
1115 }
1116 }
1117
1118 private void setLocalRawInternal(int index, Type type) {
1119 checkLocal(index);
1120 localsOrUnsetsChanged |= !type.equals(locals[index]);
1121 locals[index] = type;
1122 }
1123
1124 void setLocalsFromArg(String name, MethodTypeDesc methodDesc, boolean isStatic, Type thisKlass, UnsetField[] strictFieldsToPut) {
1125 int localsSize = 0;
1126 // Pre-emptively create a locals array that encompass all parameter slots
1127 checkLocal(Util.parameterSlots(methodDesc) + (isStatic ? -1 : 0));
1128 Type type;
1129 Type[] locals = this.locals;
1130 if (!isStatic) {
1131 if (OBJECT_INITIALIZER_NAME.equals(name) && !CD_Object.equals(thisKlass.sym)) {
1132 int strictFieldCount = strictFieldsToPut.length;
1133 this.unsetFields = UnsetField.copyArray(strictFieldsToPut, strictFieldCount);
1134 this.unsetFieldsSize = strictFieldCount;
1135 type = Type.UNITIALIZED_THIS_TYPE;
1136 this.flags = FLAG_THIS_UNINIT;
1137 } else {
1138 this.unsetFields = UnsetField.EMPTY_ARRAY;
1139 this.unsetFieldsSize = 0;
1140 type = thisKlass;
1141 this.flags = 0;
1142 }
1143 locals[localsSize++] = type;
1144 }
1145 for (int i = 0; i < methodDesc.parameterCount(); i++) {
1146 var desc = methodDesc.parameterType(i);
1147 if (desc == CD_long) {
1148 locals[localsSize ] = Type.LONG_TYPE;
1149 locals[localsSize + 1] = Type.LONG2_TYPE;
1150 localsSize += 2;
1151 } else if (desc == CD_double) {
1152 locals[localsSize ] = Type.DOUBLE_TYPE;
1153 locals[localsSize + 1] = Type.DOUBLE2_TYPE;
1154 localsSize += 2;
1155 } else {
1156 if (!desc.isPrimitive()) {
1157 type = Type.referenceType(desc);
1158 } else if (desc == CD_float) {
1159 type = Type.FLOAT_TYPE;
1160 } else {
1161 type = Type.INTEGER_TYPE;
1162 }
1163 locals[localsSize++] = type;
1164 }
1165 }
1166 if (locals != null && localsSize < locals.length) {
1167 Arrays.fill(locals, localsSize, locals.length, Type.TOP_TYPE);
1168 }
1169 this.localsSize = localsSize;
1170 }
1171
1172 void copyFrom(Frame src) {
1173 if (locals != null && src.localsSize < locals.length) Arrays.fill(locals, src.localsSize, locals.length, Type.TOP_TYPE);
1174 localsSize = src.localsSize;
1175 checkLocal(src.localsSize - 1);
1176 if (src.localsSize > 0) System.arraycopy(src.locals, 0, locals, 0, src.localsSize);
1177 if (stack != null && src.stackSize < stack.length) Arrays.fill(stack, src.stackSize, stack.length, Type.TOP_TYPE);
1178 stackSize = src.stackSize;
1179 checkStack(src.stackSize - 1);
1180 if (src.stackSize > 0) System.arraycopy(src.stack, 0, stack, 0, src.stackSize);
1181 unsetFieldsSize = src.unsetFieldsSize;
1182 unsetFields = UnsetField.copyArray(src.unsetFields, src.unsetFieldsSize);
1183 flags = src.flags;
1184 localsOrUnsetsChanged = true;
1185 }
1186
1187 void checkAssignableTo(Frame target) {
1188 int localsSize = this.localsSize;
1189 int stackSize = this.stackSize;
1190 int myUnsetFieldsSize = this.unsetFieldsSize;
1191 if (target.flags == -1) {
1192 target.locals = locals == null ? null : locals.clone();
1193 target.localsSize = localsSize;
1194 if (stackSize > 0) {
1195 target.stack = stack.clone();
1196 target.stackSize = stackSize;
1197 }
1198 target.unsetFields = UnsetField.copyArray(this.unsetFields, myUnsetFieldsSize);
1199 target.unsetFieldsSize = myUnsetFieldsSize;
1200 target.flags = flags;
1201 target.dirty = true;
1202 } else {
1203 if (target.localsSize > localsSize) {
1204 target.localsSize = localsSize;
1205 target.dirty = true;
1206 }
1207 for (int i = 0; i < target.localsSize; i++) {
1208 merge(locals[i], target.locals, i, target);
1209 }
1210 if (stackSize != target.stackSize) {
1211 throw generatorError("Stack size mismatch");
1212 }
1213 for (int i = 0; i < target.stackSize; i++) {
1214 if (merge(stack[i], target.stack, i, target) == Type.TOP_TYPE) {
1215 throw generatorError("Stack content mismatch");
1216 }
1217 }
1218 if (myUnsetFieldsSize != 0) {
1219 mergeUnsetFields(target);
1220 }
1221 }
1222 }
1223
1224 private Type getLocalRawInternal(int index) {
1225 checkLocal(index);
1226 return locals[index];
1227 }
1228
1229 Type getLocal(int index) {
1230 Type ret = getLocalRawInternal(index);
1231 if (index >= localsSize) {
1232 localsSize = index + 1;
1233 }
1234 return ret;
1235 }
1236
1237 void setLocal(int index, Type type) {
1238 Type old = getLocalRawInternal(index);
1239 if (old == Type.DOUBLE_TYPE || old == Type.LONG_TYPE) {
1240 setLocalRawInternal(index + 1, Type.TOP_TYPE);
1241 }
1242 if (old == Type.DOUBLE2_TYPE || old == Type.LONG2_TYPE) {
1243 setLocalRawInternal(index - 1, Type.TOP_TYPE);
1244 }
1245 setLocalRawInternal(index, type);
1246 if (index >= localsSize) {
1247 localsSize = index + 1;
1248 }
1249 }
1250
1251 void setLocal2(int index, Type type1, Type type2) {
1252 Type old = getLocalRawInternal(index + 1);
1253 if (old == Type.DOUBLE_TYPE || old == Type.LONG_TYPE) {
1254 setLocalRawInternal(index + 2, Type.TOP_TYPE);
1255 }
1256 old = getLocalRawInternal(index);
1257 if (old == Type.DOUBLE2_TYPE || old == Type.LONG2_TYPE) {
1258 setLocalRawInternal(index - 1, Type.TOP_TYPE);
1259 }
1260 setLocalRawInternal(index, type1);
1261 setLocalRawInternal(index + 1, type2);
1262 if (index >= localsSize - 1) {
1263 localsSize = index + 2;
1264 }
1265 }
1266
1267 private Type merge(Type me, Type[] toTypes, int i, Frame target) {
1268 var to = toTypes[i];
1269 var newTo = to.mergeFrom(me, classHierarchy);
1270 if (to != newTo && !to.equals(newTo)) {
1271 toTypes[i] = newTo;
1272 target.dirty = true;
1273 }
1274 return newTo;
1275 }
1276
1277 // Merge this frame's unset fields into the target frame
1278 private void mergeUnsetFields(Frame target) {
1279 int myUnsetSize = unsetFieldsSize;
1280 int targetUnsetSize = target.unsetFieldsSize;
1281 var myUnsets = unsetFields;
1282 var targetUnsets = target.unsetFields;
1283 if (UnsetField.matches(myUnsets, myUnsetSize, targetUnsets, targetUnsetSize)) {
1284 return; // no merge
1285 }
1286 // merge sort
1287 var merged = new UnsetField[StackMapGenerator.this.strictFieldsToPut.length];
1288 int mergedSize = 0;
1289 int i = 0;
1290 int j = 0;
1291 while (i < myUnsetSize && j < targetUnsetSize) {
1292 var myCandidate = myUnsets[i];
1293 var targetCandidate = targetUnsets[j];
1294 var cmp = myCandidate.compareTo(targetCandidate);
1295 if (cmp == 0) {
1296 merged[mergedSize++] = myCandidate;
1297 i++;
1298 j++;
1299 } else if (cmp < 0) {
1300 merged[mergedSize++] = myCandidate;
1301 i++;
1302 } else {
1303 merged[mergedSize++] = targetCandidate;
1304 j++;
1305 }
1306 }
1307 if (i < myUnsetSize) {
1308 int len = myUnsetSize - i;
1309 System.arraycopy(myUnsets, i, merged, mergedSize, len);
1310 mergedSize += len;
1311 } else if (j < targetUnsetSize) {
1312 int len = targetUnsetSize - j;
1313 System.arraycopy(targetUnsets, j, merged, mergedSize, len);
1314 mergedSize += len;
1315 }
1316
1317 target.unsetFieldsSize = mergedSize;
1318 target.unsetFields = merged;
1319 target.dirty = true;
1320 }
1321
1322 private static int trimAndCompress(Type[] types, int count) {
1323 while (count > 0 && types[count - 1] == Type.TOP_TYPE) count--;
1324 int compressed = 0;
1325 for (int i = 0; i < count; i++) {
1326 if (!types[i].isCategory2_2nd()) {
1327 if (compressed != i) {
1328 types[compressed] = types[i];
1329 }
1330 compressed++;
1331 }
1332 }
1333 return compressed;
1334 }
1335
1336 void trimAndCompress() {
1337 localsSize = trimAndCompress(locals, localsSize);
1338 stackSize = trimAndCompress(stack, stackSize);
1339 }
1340
1341 boolean hasUninitializedThis() {
1342 int size = this.localsSize;
1343 var localVars = this.locals;
1344 for (int i = 0; i < size; i++) {
1345 if (localVars[i] == Type.UNITIALIZED_THIS_TYPE)
1346 return true;
1347 }
1348 return false;
1349 }
1350
1351 private static boolean equals(Type[] l1, Type[] l2, int commonSize) {
1352 if (l1 == null || l2 == null) return commonSize == 0;
1353 return Arrays.equals(l1, 0, commonSize, l2, 0, commonSize);
1354 }
1355
1356 // In sync with StackMapDecoder::needsLarvalFrameForTransition
1357 private boolean needsLarvalFrame(Frame prevFrame) {
1358 if (UnsetField.matches(unsetFields, unsetFieldsSize, prevFrame.unsetFields, prevFrame.unsetFieldsSize))
1359 return false;
1360 if (!hasUninitializedThis()) {
1361 assert unsetFieldsSize == 0 : this; // Should have been handled by processInvokeInstructions
1362 return false;
1363 }
1364 return true;
1365 }
1366
1367 void writeTo(BufWriterImpl out, Frame prevFrame, ConstantPoolBuilder cp) {
1368 // enclosing frames
1369 if (needsLarvalFrame(prevFrame)) {
1370 out.writeU1U2(EARLY_LARVAL, unsetFieldsSize);
1371 for (int i = 0; i < unsetFieldsSize; i++) {
1372 var f = unsetFields[i];
1373 out.writeIndex(cp.nameAndTypeEntry(f.name(), f.type()));
1374 }
1375 }
1376 // base frame
1377 int localsSize = this.localsSize;
1378 int stackSize = this.stackSize;
1379 int offsetDelta = offset - prevFrame.offset - 1;
1380 if (stackSize == 0) {
1381 int commonLocalsSize = localsSize > prevFrame.localsSize ? prevFrame.localsSize : localsSize;
1382 int diffLocalsSize = localsSize - prevFrame.localsSize;
1383 if (-3 <= diffLocalsSize && diffLocalsSize <= 3 && equals(locals, prevFrame.locals, commonLocalsSize)) {
1384 if (diffLocalsSize == 0 && offsetDelta <= SAME_FRAME_END) { //same frame
1385 out.writeU1(offsetDelta);
1386 } else { //chop, same extended or append frame
1387 out.writeU1U2(SAME_FRAME_EXTENDED + diffLocalsSize, offsetDelta);
1388 for (int i=commonLocalsSize; i<localsSize; i++) locals[i].writeTo(out, cp);
1389 }
1390 return;
1391 }
1392 } else if (stackSize == 1 && localsSize == prevFrame.localsSize && equals(locals, prevFrame.locals, localsSize)) {
1393 if (offsetDelta <= SAME_LOCALS_1_STACK_ITEM_FRAME_END - SAME_LOCALS_1_STACK_ITEM_FRAME_START) { //same locals 1 stack item frame
1394 out.writeU1(SAME_LOCALS_1_STACK_ITEM_FRAME_START + offsetDelta);
1395 } else { //same locals 1 stack item extended frame
1396 out.writeU1U2(SAME_LOCALS_1_STACK_ITEM_EXTENDED, offsetDelta);
1397 }
1398 stack[0].writeTo(out, cp);
1399 return;
1400 }
1401 //full frame
1402 out.writeU1U2U2(FULL_FRAME, offsetDelta, localsSize);
1403 for (int i=0; i<localsSize; i++) locals[i].writeTo(out, cp);
1404 out.writeU2(stackSize);
1405 for (int i=0; i<stackSize; i++) stack[i].writeTo(out, cp);
1406 }
1407 }
1408
1409 private static record Type(int tag, ClassDesc sym, int bci) {
1410
1411 //singleton types
1412 static final Type TOP_TYPE = simpleType(ITEM_TOP),
1413 NULL_TYPE = simpleType(ITEM_NULL),
1414 INTEGER_TYPE = simpleType(ITEM_INTEGER),
1415 FLOAT_TYPE = simpleType(ITEM_FLOAT),
1416 LONG_TYPE = simpleType(ITEM_LONG),
1417 LONG2_TYPE = simpleType(ITEM_LONG_2ND),
1418 DOUBLE_TYPE = simpleType(ITEM_DOUBLE),
1419 BOOLEAN_TYPE = simpleType(ITEM_BOOLEAN),
1420 BYTE_TYPE = simpleType(ITEM_BYTE),
1421 CHAR_TYPE = simpleType(ITEM_CHAR),
1422 SHORT_TYPE = simpleType(ITEM_SHORT),
1423 DOUBLE2_TYPE = simpleType(ITEM_DOUBLE_2ND),
1424 UNITIALIZED_THIS_TYPE = simpleType(ITEM_UNINITIALIZED_THIS);
1425
1426 //frequently used types to reduce footprint
1427 static final Type OBJECT_TYPE = referenceType(CD_Object),
1428 THROWABLE_TYPE = referenceType(CD_Throwable),
1429 INT_ARRAY_TYPE = referenceType(CD_int.arrayType()),
1430 BOOLEAN_ARRAY_TYPE = referenceType(CD_boolean.arrayType()),
1431 BYTE_ARRAY_TYPE = referenceType(CD_byte.arrayType()),
1432 CHAR_ARRAY_TYPE = referenceType(CD_char.arrayType()),
1433 SHORT_ARRAY_TYPE = referenceType(CD_short.arrayType()),
1434 LONG_ARRAY_TYPE = referenceType(CD_long.arrayType()),
1435 DOUBLE_ARRAY_TYPE = referenceType(CD_double.arrayType()),
1436 FLOAT_ARRAY_TYPE = referenceType(CD_float.arrayType()),
1437 STRING_TYPE = referenceType(CD_String),
1438 CLASS_TYPE = referenceType(CD_Class),
1439 METHOD_HANDLE_TYPE = referenceType(CD_MethodHandle),
1440 METHOD_TYPE = referenceType(CD_MethodType);
1441
1442 private static Type simpleType(int tag) {
1443 return new Type(tag, null, 0);
1444 }
1445
1446 static Type referenceType(ClassDesc desc) {
1447 return new Type(ITEM_OBJECT, desc, 0);
1448 }
1449
1450 static Type uninitializedType(int bci) {
1451 return new Type(ITEM_UNINITIALIZED, null, bci);
1452 }
1453
1454 @Override //mandatory override to avoid use of method reference during JDK bootstrap
1455 public boolean equals(Object o) {
1456 return (o instanceof Type t) && t.tag == tag && t.bci == bci && Objects.equals(sym, t.sym);
1457 }
1458
1459 boolean isCategory2_2nd() {
1460 return this == DOUBLE2_TYPE || this == LONG2_TYPE;
1461 }
1462
1463 boolean isReference() {
1464 return tag == ITEM_OBJECT || this == NULL_TYPE;
1465 }
1466
1467 boolean isObject() {
1468 return tag == ITEM_OBJECT && sym.isClassOrInterface();
1469 }
1470
1471 boolean isArray() {
1472 return tag == ITEM_OBJECT && sym.isArray();
1473 }
1474
1475 Type mergeFrom(Type from, ClassHierarchyImpl context) {
1476 if (this == TOP_TYPE || this == from || equals(from)) {
1477 return this;
1478 } else {
1479 return switch (tag) {
1480 case ITEM_BOOLEAN, ITEM_BYTE, ITEM_CHAR, ITEM_SHORT ->
1481 from == INTEGER_TYPE ? this : TOP_TYPE;
1482 default ->
1483 isReference() && from.isReference() ? mergeReferenceFrom(from, context) : TOP_TYPE;
1484 };
1485 }
1486 }
1487
1488 Type mergeComponentFrom(Type from, ClassHierarchyImpl context) {
1489 if (this == TOP_TYPE || this == from || equals(from)) {
1490 return this;
1491 } else {
1492 return switch (tag) {
1493 case ITEM_BOOLEAN, ITEM_BYTE, ITEM_CHAR, ITEM_SHORT ->
1494 TOP_TYPE;
1495 default ->
1496 isReference() && from.isReference() ? mergeReferenceFrom(from, context) : TOP_TYPE;
1497 };
1498 }
1499 }
1500
1501 private static final ClassDesc CD_Cloneable = ClassOrInterfaceDescImpl.ofValidated("Ljava/lang/Cloneable;");
1502 private static final ClassDesc CD_Serializable = ClassOrInterfaceDescImpl.ofValidated("Ljava/io/Serializable;");
1503
1504 private Type mergeReferenceFrom(Type from, ClassHierarchyImpl context) {
1505 if (from == NULL_TYPE) {
1506 return this;
1507 } else if (this == NULL_TYPE) {
1508 return from;
1509 } else if (sym.equals(from.sym)) {
1510 return this;
1511 } else if (isObject()) {
1512 if (CD_Object.equals(sym)) {
1513 return this;
1514 }
1515 if (context.isInterface(sym)) {
1516 if (!from.isArray() || CD_Cloneable.equals(sym) || CD_Serializable.equals(sym)) {
1517 return this;
1518 }
1519 } else if (from.isObject()) {
1520 var anc = context.commonAncestor(sym, from.sym);
1521 return anc == null ? this : Type.referenceType(anc);
1522 }
1523 } else if (isArray() && from.isArray()) {
1524 Type compThis = getComponent();
1525 Type compFrom = from.getComponent();
1526 if (compThis != TOP_TYPE && compFrom != TOP_TYPE) {
1527 return compThis.mergeComponentFrom(compFrom, context).toArray();
1528 }
1529 }
1530 return OBJECT_TYPE;
1531 }
1532
1533 Type toArray() {
1534 return switch (tag) {
1535 case ITEM_BOOLEAN -> BOOLEAN_ARRAY_TYPE;
1536 case ITEM_BYTE -> BYTE_ARRAY_TYPE;
1537 case ITEM_CHAR -> CHAR_ARRAY_TYPE;
1538 case ITEM_SHORT -> SHORT_ARRAY_TYPE;
1539 case ITEM_INTEGER -> INT_ARRAY_TYPE;
1540 case ITEM_LONG -> LONG_ARRAY_TYPE;
1541 case ITEM_FLOAT -> FLOAT_ARRAY_TYPE;
1542 case ITEM_DOUBLE -> DOUBLE_ARRAY_TYPE;
1543 case ITEM_OBJECT -> Type.referenceType(sym.arrayType());
1544 default -> OBJECT_TYPE;
1545 };
1546 }
1547
1548 Type getComponent() {
1549 if (isArray()) {
1550 var comp = sym.componentType();
1551 if (comp.isPrimitive()) {
1552 return switch (comp.descriptorString().charAt(0)) {
1553 case 'Z' -> Type.BOOLEAN_TYPE;
1554 case 'B' -> Type.BYTE_TYPE;
1555 case 'C' -> Type.CHAR_TYPE;
1556 case 'S' -> Type.SHORT_TYPE;
1557 case 'I' -> Type.INTEGER_TYPE;
1558 case 'J' -> Type.LONG_TYPE;
1559 case 'F' -> Type.FLOAT_TYPE;
1560 case 'D' -> Type.DOUBLE_TYPE;
1561 default -> Type.TOP_TYPE;
1562 };
1563 }
1564 return Type.referenceType(comp);
1565 }
1566 return Type.TOP_TYPE;
1567 }
1568
1569 void writeTo(BufWriterImpl bw, ConstantPoolBuilder cp) {
1570 switch (tag) {
1571 case ITEM_OBJECT ->
1572 bw.writeU1U2(tag, cp.classEntry(sym).index());
1573 case ITEM_UNINITIALIZED ->
1574 bw.writeU1U2(tag, bci);
1575 default ->
1576 bw.writeU1(tag);
1577 }
1578 }
1579 }
1580 }