1 /*
2 * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
60 * <p><b>This is NOT part of any supported API.
61 * If you write code that depends on this, you do so at your own risk.
62 * This code and its internal interfaces are subject to change or
63 * deletion without notice.</b>
64 */
65 public class Gen extends JCTree.Visitor {
66 protected static final Context.Key<Gen> genKey = new Context.Key<>();
67
68 private final Log log;
69 private final Symtab syms;
70 private final Check chk;
71 private final Resolve rs;
72 private final TreeMaker make;
73 private final Names names;
74 private final Target target;
75 private final String accessDollar;
76 private final Types types;
77 private final Lower lower;
78 private final Annotate annotate;
79 private final StringConcat concat;
80
81 /** Format of stackmap tables to be generated. */
82 private final Code.StackMapFormat stackMap;
83
84 /** A type that serves as the expected type for all method expressions.
85 */
86 private final Type methodType;
87
88 public static Gen instance(Context context) {
89 Gen instance = context.get(genKey);
90 if (instance == null)
91 instance = new Gen(context);
92 return instance;
93 }
94
95 /** Constant pool writer, set by genClass.
96 */
97 final PoolWriter poolWriter;
98
99 @SuppressWarnings("this-escape")
100 protected Gen(Context context) {
101 context.put(genKey, this);
102
103 names = Names.instance(context);
104 log = Log.instance(context);
105 syms = Symtab.instance(context);
106 chk = Check.instance(context);
107 rs = Resolve.instance(context);
108 make = TreeMaker.instance(context);
109 target = Target.instance(context);
110 types = Types.instance(context);
111 concat = StringConcat.instance(context);
112
113 methodType = new MethodType(null, null, null, syms.methodClass);
114 accessDollar = "access" + target.syntheticNameChar();
115 lower = Lower.instance(context);
116
117 Options options = Options.instance(context);
118 lineDebugInfo =
119 options.isUnset(G_CUSTOM) ||
120 options.isSet(G_CUSTOM, "lines");
121 varDebugInfo =
122 options.isUnset(G_CUSTOM)
123 ? options.isSet(G)
124 : options.isSet(G_CUSTOM, "vars");
125 genCrt = options.isSet(XJCOV);
126 debugCode = options.isSet("debug.code");
127 disableVirtualizedPrivateInvoke = options.isSet("disableVirtualizedPrivateInvoke");
128 poolWriter = new PoolWriter(types, names);
129
130 // ignore cldc because we cannot have both stackmap formats
131 this.stackMap = StackMapFormat.JSR202;
132 annotate = Annotate.instance(context);
133 qualifiedSymbolCache = new HashMap<>();
134 }
135
136 /** Switches
137 */
138 private final boolean lineDebugInfo;
139 private final boolean varDebugInfo;
140 private final boolean genCrt;
141 private final boolean debugCode;
142 private boolean disableVirtualizedPrivateInvoke;
143
144 /** Code buffer, set by genMethod.
145 */
146 private Code code;
147
148 /** Items structure, set by genMethod.
149 */
150 private Items items;
151
152 /** Environment for symbol lookup, set by genClass
153 */
154 private Env<AttrContext> attrEnv;
155
156 /** The top level tree.
157 */
158 private JCCompilationUnit toplevel;
159
160 /** The number of code-gen errors in this class.
161 */
162 private int nerrs = 0;
401 boolean hasFinally(JCTree target, Env<GenContext> env) {
402 while (env.tree != target) {
403 if (env.tree.hasTag(TRY) && env.info.finalize.hasFinalizer())
404 return true;
405 env = env.next;
406 }
407 return false;
408 }
409
410 /* ************************************************************************
411 * Normalizing class-members.
412 *************************************************************************/
413
414 /** Distribute member initializer code into constructors and {@code <clinit>}
415 * method.
416 * @param defs The list of class member declarations.
417 * @param c The enclosing class.
418 */
419 List<JCTree> normalizeDefs(List<JCTree> defs, ClassSymbol c) {
420 ListBuffer<JCStatement> initCode = new ListBuffer<>();
421 ListBuffer<Attribute.TypeCompound> initTAs = new ListBuffer<>();
422 ListBuffer<JCStatement> clinitCode = new ListBuffer<>();
423 ListBuffer<Attribute.TypeCompound> clinitTAs = new ListBuffer<>();
424 ListBuffer<JCTree> methodDefs = new ListBuffer<>();
425 // Sort definitions into three listbuffers:
426 // - initCode for instance initializers
427 // - clinitCode for class initializers
428 // - methodDefs for method definitions
429 for (List<JCTree> l = defs; l.nonEmpty(); l = l.tail) {
430 JCTree def = l.head;
431 switch (def.getTag()) {
432 case BLOCK:
433 JCBlock block = (JCBlock)def;
434 if ((block.flags & STATIC) != 0)
435 clinitCode.append(block);
436 else if ((block.flags & SYNTHETIC) == 0)
437 initCode.append(block);
438 break;
439 case METHODDEF:
440 methodDefs.append(def);
441 break;
442 case VARDEF:
443 JCVariableDecl vdef = (JCVariableDecl) def;
444 VarSymbol sym = vdef.sym;
445 checkDimension(vdef.pos(), sym.type);
446 if (vdef.init != null) {
447 if ((sym.flags() & STATIC) == 0) {
448 // Always initialize instance variables.
449 JCStatement init = make.at(vdef.pos()).
450 Assignment(sym, vdef.init);
451 initCode.append(init);
452 init.endpos = vdef.endpos;
453 initTAs.addAll(getAndRemoveNonFieldTAs(sym));
454 } else if (sym.getConstValue() == null) {
455 // Initialize class (static) variables only if
456 // they are not compile-time constants.
457 JCStatement init = make.at(vdef.pos).
458 Assignment(sym, vdef.init);
459 clinitCode.append(init);
460 init.endpos = vdef.endpos;
461 clinitTAs.addAll(getAndRemoveNonFieldTAs(sym));
462 } else {
463 checkStringConstant(vdef.init.pos(), sym.getConstValue());
464 /* if the init contains a reference to an external class, add it to the
465 * constant's pool
466 */
467 vdef.init.accept(classReferenceVisitor);
468 }
469 }
470 break;
471 default:
472 Assert.error();
473 }
474 }
475 // Insert any instance initializers into all constructors.
476 if (initCode.length() != 0) {
477 List<JCStatement> inits = initCode.toList();
478 initTAs.addAll(c.getInitTypeAttributes());
479 List<Attribute.TypeCompound> initTAlist = initTAs.toList();
480 for (JCTree t : methodDefs) {
481 normalizeMethod((JCMethodDecl)t, inits, initTAlist);
482 }
483 }
484 // If there are class initializers, create a <clinit> method
485 // that contains them as its body.
486 if (clinitCode.length() != 0) {
487 MethodSymbol clinit = new MethodSymbol(
488 STATIC | (c.flags() & STRICTFP),
489 names.clinit,
490 new MethodType(
491 List.nil(), syms.voidType,
492 List.nil(), syms.methodClass),
493 c);
494 c.members().enter(clinit);
495 List<JCStatement> clinitStats = clinitCode.toList();
496 JCBlock block = make.at(clinitStats.head.pos()).Block(0, clinitStats);
497 block.bracePos = TreeInfo.endPos(clinitStats.last());
498 methodDefs.append(make.MethodDef(clinit, block));
499
500 if (!clinitTAs.isEmpty())
501 clinit.appendUniqueTypeAttributes(clinitTAs.toList());
524
525 /** Check a constant value and report if it is a string that is
526 * too large.
527 */
528 private void checkStringConstant(DiagnosticPosition pos, Object constValue) {
529 if (nerrs != 0 || // only complain about a long string once
530 constValue == null ||
531 !(constValue instanceof String str) ||
532 str.length() < PoolWriter.MAX_STRING_LENGTH)
533 return;
534 log.error(pos, Errors.LimitString);
535 nerrs++;
536 }
537
538 /** Insert instance initializer code into constructors prior to the super() call.
539 * @param md The tree potentially representing a
540 * constructor's definition.
541 * @param initCode The list of instance initializer statements.
542 * @param initTAs Type annotations from the initializer expression.
543 */
544 void normalizeMethod(JCMethodDecl md, List<JCStatement> initCode, List<TypeCompound> initTAs) {
545 if (TreeInfo.isConstructor(md) && TreeInfo.hasConstructorCall(md, names._super)) {
546 // We are seeing a constructor that has a super() call.
547 // Find the super() invocation and append the given initializer code.
548 TreeInfo.mapSuperCalls(md.body, supercall -> make.Block(0, initCode.prepend(supercall)));
549
550 if (md.body.bracePos == Position.NOPOS)
551 md.body.bracePos = TreeInfo.endPos(md.body.stats.last());
552
553 md.sym.appendUniqueTypeAttributes(initTAs);
554 }
555 }
556
557 /* ************************************************************************
558 * Traversal methods
559 *************************************************************************/
560
561 /** Visitor argument: The current environment.
562 */
563 Env<GenContext> env;
564
565 /** Visitor argument: The expected type (prototype).
566 */
567 Type pt;
568
569 /** Visitor result: The item representing the computed value.
570 */
571 Item result;
572
573 /** Visitor method: generate code for a definition, catching and reporting
574 * any completion failures.
575 * @param tree The definition to be visited.
576 * @param env The environment current at the definition.
933 // Count up extra parameters
934 if (meth.isConstructor()) {
935 extras++;
936 if (meth.enclClass().isInner() &&
937 !meth.enclClass().isStatic()) {
938 extras++;
939 }
940 } else if ((tree.mods.flags & STATIC) == 0) {
941 extras++;
942 }
943 // System.err.println("Generating " + meth + " in " + meth.owner); //DEBUG
944 if (Code.width(types.erasure(env.enclMethod.sym.type).getParameterTypes()) + extras >
945 ClassFile.MAX_PARAMETERS) {
946 log.error(tree.pos(), Errors.LimitParameters);
947 nerrs++;
948 }
949
950 else if (tree.body != null) {
951 // Create a new code structure and initialize it.
952 int startpcCrt = initCode(tree, env, fatcode);
953
954 try {
955 genStat(tree.body, env);
956 } catch (CodeSizeOverflow e) {
957 // Failed due to code limit, try again with jsr/ret
958 startpcCrt = initCode(tree, env, fatcode);
959 genStat(tree.body, env);
960 }
961
962 if (code.state.stacksize != 0) {
963 log.error(tree.body.pos(), Errors.StackSimError(tree.sym));
964 throw new AssertionError();
965 }
966
967 // If last statement could complete normally, insert a
968 // return at the end.
969 if (code.isAlive()) {
970 code.statBegin(TreeInfo.endPos(tree.body));
971 if (env.enclMethod == null ||
972 env.enclMethod.sym.type.getReturnType().hasTag(VOID)) {
973 code.emitop0(return_);
974 } else {
975 // sometime dead code seems alive (4415991);
976 // generate a small loop instead
977 int startpc = code.entryPoint();
978 CondItem c = items.makeCondItem(goto_);
979 code.resolve(c.jumpTrue(), startpc);
1007 code.compressCatchTable();
1008
1009 // Fill in type annotation positions for exception parameters
1010 code.fillExceptionParameterPositions();
1011 }
1012 }
1013
1014 private int initCode(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) {
1015 MethodSymbol meth = tree.sym;
1016
1017 // Create a new code structure.
1018 meth.code = code = new Code(meth,
1019 fatcode,
1020 lineDebugInfo ? toplevel.lineMap : null,
1021 varDebugInfo,
1022 stackMap,
1023 debugCode,
1024 genCrt ? new CRTable(tree) : null,
1025 syms,
1026 types,
1027 poolWriter);
1028 items = new Items(poolWriter, code, syms, types);
1029 if (code.debugCode) {
1030 System.err.println(meth + " for body " + tree);
1031 }
1032
1033 // If method is not static, create a new local variable address
1034 // for `this'.
1035 if ((tree.mods.flags & STATIC) == 0) {
1036 Type selfType = meth.owner.type;
1037 if (meth.isConstructor() && selfType != syms.objectType)
1038 selfType = UninitializedType.uninitializedThis(selfType);
1039 code.setDefined(
1040 code.newLocal(
1041 new VarSymbol(FINAL, names._this, selfType, meth.owner)));
1042 }
1043
1044 // Mark all parameters as defined from the beginning of
1045 // the method.
1046 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1047 checkDimension(l.head.pos(), l.head.sym.type);
1143 public void visitForLoop(JCForLoop tree) {
1144 int limit = code.nextreg;
1145 genStats(tree.init, env);
1146 genLoop(tree, tree.body, tree.cond, tree.step, true);
1147 code.endScopes(limit);
1148 }
1149 //where
1150 /** Generate code for a loop.
1151 * @param loop The tree representing the loop.
1152 * @param body The loop's body.
1153 * @param cond The loop's controlling condition.
1154 * @param step "Step" statements to be inserted at end of
1155 * each iteration.
1156 * @param testFirst True if the loop test belongs before the body.
1157 */
1158 private void genLoop(JCStatement loop,
1159 JCStatement body,
1160 JCExpression cond,
1161 List<JCExpressionStatement> step,
1162 boolean testFirst) {
1163 Env<GenContext> loopEnv = env.dup(loop, new GenContext());
1164 int startpc = code.entryPoint();
1165 if (testFirst) { //while or for loop
1166 CondItem c;
1167 if (cond != null) {
1168 code.statBegin(cond.pos);
1169 Assert.check(code.isStatementStart());
1170 c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER);
1171 } else {
1172 c = items.makeCondItem(goto_);
1173 }
1174 Chain loopDone = c.jumpFalse();
1175 code.resolve(c.trueJumps);
1176 Assert.check(code.isStatementStart());
1177 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET);
1178 code.resolve(loopEnv.info.cont);
1179 genStats(step, loopEnv);
1180 code.resolve(code.branch(goto_), startpc);
1181 code.resolve(loopDone);
1182 } else {
1201 }
1202
1203 public void visitForeachLoop(JCEnhancedForLoop tree) {
1204 throw new AssertionError(); // should have been removed by Lower.
1205 }
1206
1207 public void visitLabelled(JCLabeledStatement tree) {
1208 Env<GenContext> localEnv = env.dup(tree, new GenContext());
1209 genStat(tree.body, localEnv, CRT_STATEMENT);
1210 code.resolve(localEnv.info.exit);
1211 }
1212
1213 public void visitSwitch(JCSwitch tree) {
1214 handleSwitch(tree, tree.selector, tree.cases, tree.patternSwitch);
1215 }
1216
1217 @Override
1218 public void visitSwitchExpression(JCSwitchExpression tree) {
1219 code.resolvePending();
1220 boolean prevInCondSwitchExpression = inCondSwitchExpression;
1221 try {
1222 inCondSwitchExpression = false;
1223 doHandleSwitchExpression(tree);
1224 } finally {
1225 inCondSwitchExpression = prevInCondSwitchExpression;
1226 }
1227 result = items.makeStackItem(pt);
1228 }
1229
1230 private void doHandleSwitchExpression(JCSwitchExpression tree) {
1231 List<LocalItem> prevStackBeforeSwitchExpression = stackBeforeSwitchExpression;
1232 LocalItem prevSwitchResult = switchResult;
1233 int limit = code.nextreg;
1234 try {
1235 stackBeforeSwitchExpression = List.nil();
1236 switchResult = null;
1237 if (hasTry(tree)) {
1238 //if the switch expression contains try-catch, the catch handlers need to have
1239 //an empty stack. So stash whole stack to local variables, and restore it before
1240 //breaks:
1241 while (code.state.stacksize > 0) {
1242 Type type = code.state.peek();
1243 Name varName = names.fromString(target.syntheticNameChar() +
1244 "stack" +
1245 target.syntheticNameChar() +
1281 hasTry = true;
1282 }
1283
1284 @Override
1285 public void visitClassDef(JCClassDecl tree) {
1286 }
1287
1288 @Override
1289 public void visitLambda(JCLambda tree) {
1290 }
1291 };
1292
1293 HasTryScanner hasTryScanner = new HasTryScanner();
1294
1295 hasTryScanner.scan(tree);
1296 return hasTryScanner.hasTry;
1297 }
1298
1299 private void handleSwitch(JCTree swtch, JCExpression selector, List<JCCase> cases,
1300 boolean patternSwitch) {
1301 int limit = code.nextreg;
1302 Assert.check(!selector.type.hasTag(CLASS));
1303 int switchStart = patternSwitch ? code.entryPoint() : -1;
1304 int startpcCrt = genCrt ? code.curCP() : 0;
1305 Assert.check(code.isStatementStart());
1306 Item sel = genExpr(selector, syms.intType);
1307 if (cases.isEmpty()) {
1308 // We are seeing: switch <sel> {}
1309 sel.load().drop();
1310 if (genCrt)
1311 code.crt.put(TreeInfo.skipParens(selector),
1312 CRT_FLOW_CONTROLLER, startpcCrt, code.curCP());
1313 } else {
1314 // We are seeing a nonempty switch.
1315 sel.load();
1316 if (genCrt)
1317 code.crt.put(TreeInfo.skipParens(selector),
1318 CRT_FLOW_CONTROLLER, startpcCrt, code.curCP());
1319 Env<GenContext> switchEnv = env.dup(swtch, new GenContext());
1320 switchEnv.info.isSwitch = true;
1321
1322 // Compute number of labels and minimum and maximum label values.
1323 // For each case, store its label in an array.
1324 int lo = Integer.MAX_VALUE; // minimum label.
1325 int hi = Integer.MIN_VALUE; // maximum label.
1326 int nlabels = 0; // number of labels.
1327
1328 int[] labels = new int[cases.length()]; // the label array.
1329 int defaultIndex = -1; // the index of the default clause.
1330
1331 List<JCCase> l = cases;
1332 for (int i = 0; i < labels.length; i++) {
1333 if (l.head.labels.head instanceof JCConstantCaseLabel constLabel) {
1334 Assert.check(l.head.labels.size() == 1);
1335 int val = ((Number) constLabel.expr.type.constValue()).intValue();
1336 labels[i] = val;
1337 if (val < lo) lo = val;
1338 if (hi < val) hi = val;
1339 nlabels++;
1340 } else {
1341 Assert.check(defaultIndex == -1);
1342 defaultIndex = i;
1343 }
1344 l = l.tail;
1345 }
1346
1347 // Determine whether to issue a tableswitch or a lookupswitch
1348 // instruction.
1349 long table_space_cost = 4 + ((long) hi - lo + 1); // words
1350 long table_time_cost = 3; // comparisons
1351 long lookup_space_cost = 3 + 2 * (long) nlabels;
1352 long lookup_time_cost = nlabels;
1353 int opcode =
1354 nlabels > 0 &&
1355 table_space_cost + 3 * table_time_cost <=
1356 lookup_space_cost + 3 * lookup_time_cost
1357 ?
1358 tableswitch : lookupswitch;
1359
1360 int startpc = code.curCP(); // the position of the selector operation
1361 code.emitop0(opcode);
1362 code.align(4);
1363 int tableBase = code.curCP(); // the start of the jump table
1364 int[] offsets = null; // a table of offsets for a lookupswitch
1365 code.emit4(-1); // leave space for default offset
1366 if (opcode == tableswitch) {
1367 code.emit4(lo); // minimum label
1368 code.emit4(hi); // maximum label
1369 for (long i = lo; i <= hi; i++) { // leave space for jump table
1370 code.emit4(-1);
1371 }
1372 } else {
1373 code.emit4(nlabels); // number of labels
1374 for (int i = 0; i < nlabels; i++) {
1375 code.emit4(-1); code.emit4(-1); // leave space for lookup table
1376 }
1377 offsets = new int[labels.length];
1378 }
1379 Code.State stateSwitch = code.state.dup();
1380 code.markDead();
1381
1382 // For each case do:
1383 l = cases;
1384 for (int i = 0; i < labels.length; i++) {
1385 JCCase c = l.head;
1386 l = l.tail;
1387
1388 int pc = code.entryPoint(stateSwitch);
1389 // Insert offset directly into code or else into the
1390 // offsets table.
1391 if (i != defaultIndex) {
1392 if (opcode == tableswitch) {
1393 code.put4(
1394 tableBase + 4 * (labels[i] - lo + 3),
1395 pc - startpc);
1396 } else {
1397 offsets[i] = pc - startpc;
1398 }
1399 } else {
1400 code.put4(tableBase, pc - startpc);
1401 }
1402
1403 // Generate code for the statements in this case.
1404 genStats(c.stats, switchEnv, CRT_FLOW_TARGET);
1405 }
1406
1407 if (switchEnv.info.cont != null) {
1408 Assert.check(patternSwitch);
1409 code.resolve(switchEnv.info.cont, switchStart);
1410 }
1411
1412 // Resolve all breaks.
1413 code.resolve(switchEnv.info.exit);
1414
1415 // If we have not set the default offset, we do so now.
1425 if (code.get4(t) == -1)
1426 code.put4(t, defaultOffset);
1427 }
1428 } else {
1429 // Sort non-default offsets and copy into lookup table.
1430 if (defaultIndex >= 0)
1431 for (int i = defaultIndex; i < labels.length - 1; i++) {
1432 labels[i] = labels[i+1];
1433 offsets[i] = offsets[i+1];
1434 }
1435 if (nlabels > 0)
1436 qsort2(labels, offsets, 0, nlabels - 1);
1437 for (int i = 0; i < nlabels; i++) {
1438 int caseidx = tableBase + 8 * (i + 1);
1439 code.put4(caseidx, labels[i]);
1440 code.put4(caseidx + 4, offsets[i]);
1441 }
1442 }
1443
1444 if (swtch instanceof JCSwitchExpression) {
1445 // Emit line position for the end of a switch expression
1446 code.statBegin(TreeInfo.endPos(swtch));
1447 }
1448 }
1449 code.endScopes(limit);
1450 }
1451 //where
1452 /** Sort (int) arrays of keys and values
1453 */
1454 static void qsort2(int[] keys, int[] values, int lo, int hi) {
1455 int i = lo;
1456 int j = hi;
1457 int pivot = keys[(i+j)/2];
1458 do {
1459 while (keys[i] < pivot) i++;
1460 while (pivot < keys[j]) j--;
1461 if (i <= j) {
1462 int temp1 = keys[i];
1463 keys[i] = keys[j];
1464 keys[j] = temp1;
1465 int temp2 = values[i];
1466 values[i] = values[j];
1529 @Override
1530 void afterBody() {
1531 if (tree.finalizer != null && (tree.finalizer.flags & BODY_ONLY_FINALIZE) != 0) {
1532 //for body-only finally, remove the GenFinalizer after try body
1533 //so that the finally is not generated to catch bodies:
1534 tryEnv.info.finalize = null;
1535 }
1536 }
1537
1538 };
1539 tryEnv.info.gaps = new ListBuffer<>();
1540 genTry(tree.body, tree.catchers, tryEnv);
1541 }
1542 //where
1543 /** Generate code for a try or synchronized statement
1544 * @param body The body of the try or synchronized statement.
1545 * @param catchers The list of catch clauses.
1546 * @param env The current environment of the body.
1547 */
1548 void genTry(JCTree body, List<JCCatch> catchers, Env<GenContext> env) {
1549 int limit = code.nextreg;
1550 int startpc = code.curCP();
1551 Code.State stateTry = code.state.dup();
1552 genStat(body, env, CRT_BLOCK);
1553 int endpc = code.curCP();
1554 List<Integer> gaps = env.info.gaps.toList();
1555 code.statBegin(TreeInfo.endPos(body));
1556 genFinalizer(env);
1557 code.statBegin(TreeInfo.endPos(env.tree));
1558 Chain exitChain;
1559 boolean actualTry = env.tree.hasTag(TRY);
1560 if (startpc == endpc && actualTry) {
1561 exitChain = code.branch(dontgoto);
1562 } else {
1563 exitChain = code.branch(goto_);
1564 }
1565 endFinalizerGap(env);
1566 env.info.finalize.afterBody();
1567 boolean hasFinalizer =
1568 env.info.finalize != null &&
1569 env.info.finalize.hasFinalizer();
1570 if (startpc != endpc) for (List<JCCatch> l = catchers; l.nonEmpty(); l = l.tail) {
1571 // start off with exception on stack
1572 code.entryPoint(stateTry, l.head.param.sym.type);
1573 genCatch(l.head, env, startpc, endpc, gaps);
1574 genFinalizer(env);
1575 if (hasFinalizer || l.tail.nonEmpty()) {
1576 code.statBegin(TreeInfo.endPos(env.tree));
1577 exitChain = Code.mergeChains(exitChain,
1578 code.branch(goto_));
1579 }
1580 endFinalizerGap(env);
1581 }
1582 if (hasFinalizer && (startpc != endpc || !actualTry)) {
1583 // Create a new register segment to avoid allocating
1584 // the same variables in finalizers and other statements.
1585 code.newRegSegment();
1586
1587 // Add a catch-all clause.
1588
1589 // start off with exception on stack
1590 int catchallpc = code.entryPoint(stateTry, syms.throwableType);
1591
1592 // Register all exception ranges for catch all clause.
1593 // The range of the catch all clause is from the beginning
1594 // of the try or synchronized block until the present
1595 // code pointer excluding all gaps in the current
1596 // environment's GenContext.
1597 int startseg = startpc;
1598 while (env.info.gaps.nonEmpty()) {
1599 int endseg = env.info.gaps.next().intValue();
1600 registerCatch(body.pos(), startseg, endseg,
1601 catchallpc, 0);
1602 startseg = env.info.gaps.next().intValue();
1603 }
1604 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS));
1605 code.markStatBegin();
1606
1607 Item excVar = makeTemp(syms.throwableType);
1608 excVar.store();
1609 genFinalizer(env);
1610 code.resolvePending();
1611 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.END_POS));
1612 code.markStatBegin();
1613
1614 excVar.load();
1615 registerCatch(body.pos(), startseg,
1616 env.info.gaps.next().intValue(),
1617 catchallpc, 0);
1618 code.emitop0(athrow);
1619 code.markDead();
1620
1621 // If there are jsr's to this finalizer, ...
1622 if (env.info.cont != null) {
1623 // Resolve all jsr's.
1624 code.resolve(env.info.cont);
1625
1626 // Mark statement line number
1627 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS));
1628 code.markStatBegin();
1629
1630 // Save return address.
1631 LocalItem retVar = makeTemp(syms.throwableType);
1632 retVar.store();
1633
1634 // Generate finalizer code.
1635 env.info.finalize.genLast();
1636
1637 // Return.
1740 /** Register a catch clause in the "Exceptions" code-attribute.
1741 */
1742 void registerCatch(DiagnosticPosition pos,
1743 int startpc, int endpc,
1744 int handler_pc, int catch_type) {
1745 char startpc1 = (char)startpc;
1746 char endpc1 = (char)endpc;
1747 char handler_pc1 = (char)handler_pc;
1748 if (startpc1 == startpc &&
1749 endpc1 == endpc &&
1750 handler_pc1 == handler_pc) {
1751 code.addCatch(startpc1, endpc1, handler_pc1,
1752 (char)catch_type);
1753 } else {
1754 log.error(pos, Errors.LimitCodeTooLargeForTryStmt);
1755 nerrs++;
1756 }
1757 }
1758
1759 public void visitIf(JCIf tree) {
1760 int limit = code.nextreg;
1761 Chain thenExit = null;
1762 Assert.check(code.isStatementStart());
1763 CondItem c = genCond(TreeInfo.skipParens(tree.cond),
1764 CRT_FLOW_CONTROLLER);
1765 Chain elseChain = c.jumpFalse();
1766 Assert.check(code.isStatementStart());
1767 if (!c.isFalse()) {
1768 code.resolve(c.trueJumps);
1769 genStat(tree.thenpart, env, CRT_STATEMENT | CRT_FLOW_TARGET);
1770 thenExit = code.branch(goto_);
1771 }
1772 if (elseChain != null) {
1773 code.resolve(elseChain);
1774 if (tree.elsepart != null) {
1775 genStat(tree.elsepart, env,CRT_STATEMENT | CRT_FLOW_TARGET);
1776 }
1777 }
1778 code.resolve(thenExit);
1779 code.endScopes(limit);
1780 Assert.check(code.isStatementStart());
1781 }
1782
1783 public void visitExec(JCExpressionStatement tree) {
1784 // Optimize x++ to ++x and x-- to --x.
2068 nerrs++;
2069 }
2070 int elemcode = Code.arraycode(elemtype);
2071 if (elemcode == 0 || (elemcode == 1 && ndims == 1)) {
2072 code.emitAnewarray(makeRef(pos, elemtype), type);
2073 } else if (elemcode == 1) {
2074 code.emitMultianewarray(ndims, makeRef(pos, type), type);
2075 } else {
2076 code.emitNewarray(elemcode, type);
2077 }
2078 return items.makeStackItem(type);
2079 }
2080
2081 public void visitParens(JCParens tree) {
2082 result = genExpr(tree.expr, tree.expr.type);
2083 }
2084
2085 public void visitAssign(JCAssign tree) {
2086 Item l = genExpr(tree.lhs, tree.lhs.type);
2087 genExpr(tree.rhs, tree.lhs.type).load();
2088 if (tree.rhs.type.hasTag(BOT)) {
2089 /* This is just a case of widening reference conversion that per 5.1.5 simply calls
2090 for "regarding a reference as having some other type in a manner that can be proved
2091 correct at compile time."
2092 */
2093 code.state.forceStackTop(tree.lhs.type);
2094 }
2095 result = items.makeAssignItem(l);
2096 }
2097
2098 public void visitAssignop(JCAssignOp tree) {
2099 OperatorSymbol operator = tree.operator;
2100 Item l;
2101 if (operator.opcode == string_add) {
2102 l = concat.makeConcat(tree);
2103 } else {
2104 // Generate code for first expression
2105 l = genExpr(tree.lhs, tree.lhs.type);
2106
2107 // If we have an increment of -32768 to +32767 of a local
2346 items.makeThisItem().load();
2347 sym = binaryQualifier(sym, env.enclClass.type);
2348 result = items.makeMemberItem(sym, nonVirtualForPrivateAccess(sym));
2349 }
2350 }
2351
2352 //where
2353 private boolean nonVirtualForPrivateAccess(Symbol sym) {
2354 boolean useVirtual = target.hasVirtualPrivateInvoke() &&
2355 !disableVirtualizedPrivateInvoke;
2356 return !useVirtual && ((sym.flags() & PRIVATE) != 0);
2357 }
2358
2359 public void visitSelect(JCFieldAccess tree) {
2360 Symbol sym = tree.sym;
2361
2362 if (tree.name == names._class) {
2363 code.emitLdc((LoadableConstant)checkDimension(tree.pos(), tree.selected.type));
2364 result = items.makeStackItem(pt);
2365 return;
2366 }
2367
2368 Symbol ssym = TreeInfo.symbol(tree.selected);
2369
2370 // Are we selecting via super?
2371 boolean selectSuper =
2372 ssym != null && (ssym.kind == TYP || ssym.name == names._super);
2373
2374 // Are we accessing a member of the superclass in an access method
2375 // resulting from a qualified super?
2376 boolean accessSuper = isAccessSuper(env.enclMethod);
2377
2378 Item base = (selectSuper)
2379 ? items.makeSuperItem()
2380 : genExpr(tree.selected, tree.selected.type);
2381
2382 if (sym.kind == VAR && ((VarSymbol) sym).getConstValue() != null) {
2383 // We are seeing a variable that is constant but its selecting
2384 // expression is not.
2385 if ((sym.flags() & STATIC) != 0) {
2386 if (!selectSuper && (ssym == null || ssym.kind != TYP))
|
1 /*
2 * Copyright (c) 1999, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
60 * <p><b>This is NOT part of any supported API.
61 * If you write code that depends on this, you do so at your own risk.
62 * This code and its internal interfaces are subject to change or
63 * deletion without notice.</b>
64 */
65 public class Gen extends JCTree.Visitor {
66 protected static final Context.Key<Gen> genKey = new Context.Key<>();
67
68 private final Log log;
69 private final Symtab syms;
70 private final Check chk;
71 private final Resolve rs;
72 private final TreeMaker make;
73 private final Names names;
74 private final Target target;
75 private final String accessDollar;
76 private final Types types;
77 private final Lower lower;
78 private final Annotate annotate;
79 private final StringConcat concat;
80 private final LocalProxyVarsGen localProxyVarsGen;
81
82 /** Format of stackmap tables to be generated. */
83 private final Code.StackMapFormat stackMap;
84
85 /** A type that serves as the expected type for all method expressions.
86 */
87 private final Type methodType;
88
89 public static Gen instance(Context context) {
90 Gen instance = context.get(genKey);
91 if (instance == null)
92 instance = new Gen(context);
93 return instance;
94 }
95
96 /** Constant pool writer, set by genClass.
97 */
98 final PoolWriter poolWriter;
99
100 private final UnsetFieldsInfo unsetFieldsInfo;
101
102 @SuppressWarnings("this-escape")
103 protected Gen(Context context) {
104 context.put(genKey, this);
105
106 names = Names.instance(context);
107 log = Log.instance(context);
108 syms = Symtab.instance(context);
109 chk = Check.instance(context);
110 rs = Resolve.instance(context);
111 make = TreeMaker.instance(context);
112 target = Target.instance(context);
113 types = Types.instance(context);
114 concat = StringConcat.instance(context);
115 localProxyVarsGen = LocalProxyVarsGen.instance(context);
116
117 methodType = new MethodType(null, null, null, syms.methodClass);
118 accessDollar = "access" + target.syntheticNameChar();
119 lower = Lower.instance(context);
120
121 Options options = Options.instance(context);
122 lineDebugInfo =
123 options.isUnset(G_CUSTOM) ||
124 options.isSet(G_CUSTOM, "lines");
125 varDebugInfo =
126 options.isUnset(G_CUSTOM)
127 ? options.isSet(G)
128 : options.isSet(G_CUSTOM, "vars");
129 genCrt = options.isSet(XJCOV);
130 debugCode = options.isSet("debug.code");
131 disableVirtualizedPrivateInvoke = options.isSet("disableVirtualizedPrivateInvoke");
132 poolWriter = new PoolWriter(types, names);
133 unsetFieldsInfo = UnsetFieldsInfo.instance(context);
134
135 // ignore cldc because we cannot have both stackmap formats
136 this.stackMap = StackMapFormat.JSR202;
137 annotate = Annotate.instance(context);
138 qualifiedSymbolCache = new HashMap<>();
139 Preview preview = Preview.instance(context);
140 Source source = Source.instance(context);
141 allowValueClasses = preview.isEnabled() && Source.Feature.VALUE_CLASSES.allowedInSource(source);
142 }
143
144 /** Switches
145 */
146 private final boolean lineDebugInfo;
147 private final boolean varDebugInfo;
148 private final boolean genCrt;
149 private final boolean debugCode;
150 private boolean disableVirtualizedPrivateInvoke;
151 private final boolean allowValueClasses;
152
153 /** Code buffer, set by genMethod.
154 */
155 private Code code;
156
157 /** Items structure, set by genMethod.
158 */
159 private Items items;
160
161 /** Environment for symbol lookup, set by genClass
162 */
163 private Env<AttrContext> attrEnv;
164
165 /** The top level tree.
166 */
167 private JCCompilationUnit toplevel;
168
169 /** The number of code-gen errors in this class.
170 */
171 private int nerrs = 0;
410 boolean hasFinally(JCTree target, Env<GenContext> env) {
411 while (env.tree != target) {
412 if (env.tree.hasTag(TRY) && env.info.finalize.hasFinalizer())
413 return true;
414 env = env.next;
415 }
416 return false;
417 }
418
419 /* ************************************************************************
420 * Normalizing class-members.
421 *************************************************************************/
422
423 /** Distribute member initializer code into constructors and {@code <clinit>}
424 * method.
425 * @param defs The list of class member declarations.
426 * @param c The enclosing class.
427 */
428 List<JCTree> normalizeDefs(List<JCTree> defs, ClassSymbol c) {
429 ListBuffer<JCStatement> initCode = new ListBuffer<>();
430 // only used for value classes
431 ListBuffer<JCStatement> initBlocks = new ListBuffer<>();
432 ListBuffer<Attribute.TypeCompound> initTAs = new ListBuffer<>();
433 ListBuffer<JCStatement> clinitCode = new ListBuffer<>();
434 ListBuffer<Attribute.TypeCompound> clinitTAs = new ListBuffer<>();
435 ListBuffer<JCTree> methodDefs = new ListBuffer<>();
436 // Sort definitions into three listbuffers:
437 // - initCode for instance initializers
438 // - clinitCode for class initializers
439 // - methodDefs for method definitions
440 for (List<JCTree> l = defs; l.nonEmpty(); l = l.tail) {
441 JCTree def = l.head;
442 switch (def.getTag()) {
443 case BLOCK:
444 JCBlock block = (JCBlock)def;
445 if ((block.flags & STATIC) != 0)
446 clinitCode.append(block);
447 else if ((block.flags & SYNTHETIC) == 0) {
448 if (c.isValueClass()) {
449 initBlocks.append(block);
450 } else {
451 initCode.append(block);
452 }
453 }
454 break;
455 case METHODDEF:
456 methodDefs.append(def);
457 break;
458 case VARDEF:
459 JCVariableDecl vdef = (JCVariableDecl) def;
460 VarSymbol sym = vdef.sym;
461 checkDimension(vdef.pos(), sym.type);
462 if (vdef.init != null) {
463 if ((sym.flags() & STATIC) == 0) {
464 // Always initialize instance variables.
465 JCStatement init = make.at(vdef.pos()).
466 Assignment(sym, vdef.init);
467 initCode.append(init);
468 init.endpos = vdef.endpos;
469 initTAs.addAll(getAndRemoveNonFieldTAs(sym));
470 } else if (sym.getConstValue() == null) {
471 // Initialize class (static) variables only if
472 // they are not compile-time constants.
473 JCStatement init = make.at(vdef.pos).
474 Assignment(sym, vdef.init);
475 clinitCode.append(init);
476 init.endpos = vdef.endpos;
477 clinitTAs.addAll(getAndRemoveNonFieldTAs(sym));
478 } else {
479 checkStringConstant(vdef.init.pos(), sym.getConstValue());
480 /* if the init contains a reference to an external class, add it to the
481 * constant's pool
482 */
483 vdef.init.accept(classReferenceVisitor);
484 }
485 }
486 break;
487 default:
488 Assert.error();
489 }
490 }
491 // Insert any instance initializers into all constructors.
492 if (initCode.length() != 0 || initBlocks.length() != 0) {
493 initTAs.addAll(c.getInitTypeAttributes());
494 List<Attribute.TypeCompound> initTAlist = initTAs.toList();
495 for (JCTree t : methodDefs) {
496 normalizeMethod((JCMethodDecl)t, initCode.toList(), initBlocks.toList(), initTAlist);
497 }
498 }
499 // If there are class initializers, create a <clinit> method
500 // that contains them as its body.
501 if (clinitCode.length() != 0) {
502 MethodSymbol clinit = new MethodSymbol(
503 STATIC | (c.flags() & STRICTFP),
504 names.clinit,
505 new MethodType(
506 List.nil(), syms.voidType,
507 List.nil(), syms.methodClass),
508 c);
509 c.members().enter(clinit);
510 List<JCStatement> clinitStats = clinitCode.toList();
511 JCBlock block = make.at(clinitStats.head.pos()).Block(0, clinitStats);
512 block.bracePos = TreeInfo.endPos(clinitStats.last());
513 methodDefs.append(make.MethodDef(clinit, block));
514
515 if (!clinitTAs.isEmpty())
516 clinit.appendUniqueTypeAttributes(clinitTAs.toList());
539
540 /** Check a constant value and report if it is a string that is
541 * too large.
542 */
543 private void checkStringConstant(DiagnosticPosition pos, Object constValue) {
544 if (nerrs != 0 || // only complain about a long string once
545 constValue == null ||
546 !(constValue instanceof String str) ||
547 str.length() < PoolWriter.MAX_STRING_LENGTH)
548 return;
549 log.error(pos, Errors.LimitString);
550 nerrs++;
551 }
552
553 /** Insert instance initializer code into constructors prior to the super() call.
554 * @param md The tree potentially representing a
555 * constructor's definition.
556 * @param initCode The list of instance initializer statements.
557 * @param initTAs Type annotations from the initializer expression.
558 */
559 void normalizeMethod(JCMethodDecl md, List<JCStatement> initCode, List<JCStatement> initBlocks, List<TypeCompound> initTAs) {
560 Set<Symbol> fieldsWithInits;
561 List<JCStatement> inits;
562 if ((fieldsWithInits = localProxyVarsGen.initializersAlreadyInConst.get(md)) != null) {
563 ListBuffer<JCStatement> newInitCode = new ListBuffer<>();
564 for (JCStatement init : initCode) {
565 Symbol sym = ((JCIdent)((JCAssign)((JCExpressionStatement)init).expr).lhs).sym;
566 if (!fieldsWithInits.contains(sym)) {
567 newInitCode.add(init);
568 }
569 }
570 inits = newInitCode.toList();
571 localProxyVarsGen.initializersAlreadyInConst.remove(md);
572 } else {
573 inits = initCode;
574 }
575 if (TreeInfo.isConstructor(md) && TreeInfo.hasConstructorCall(md, names._super)) {
576 // We are seeing a constructor that has a super() call.
577 // Find the super() invocation and append the given initializer code.
578 if (allowValueClasses & (md.sym.owner.isValueClass() || ((md.sym.owner.flags_field & RECORD) != 0))) {
579 rewriteInitializersIfNeeded(md, inits);
580 md.body.stats = inits.appendList(md.body.stats);
581 TreeInfo.mapSuperCalls(md.body, supercall -> make.Block(0, initBlocks.prepend(supercall)));
582 } else {
583 TreeInfo.mapSuperCalls(md.body, supercall -> make.Block(0, inits.prepend(supercall)));
584 }
585
586 if (md.body.bracePos == Position.NOPOS)
587 md.body.bracePos = TreeInfo.endPos(md.body.stats.last());
588
589 md.sym.appendUniqueTypeAttributes(initTAs);
590 }
591 }
592
593 void rewriteInitializersIfNeeded(JCMethodDecl md, List<JCStatement> initCode) {
594 if (lower.initializerOuterThis.containsKey(md.sym.owner)) {
595 InitializerVisitor initializerVisitor = new InitializerVisitor(md, lower.initializerOuterThis.get(md.sym.owner));
596 for (JCStatement init : initCode) {
597 initializerVisitor.scan(init);
598 }
599 }
600 }
601
602 public static class InitializerVisitor extends TreeScanner {
603 JCMethodDecl md;
604 Set<JCExpression> exprSet;
605
606 public InitializerVisitor(JCMethodDecl md, Set<JCExpression> exprSet) {
607 this.md = md;
608 this.exprSet = exprSet;
609 }
610
611 @Override
612 public void visitTree(JCTree tree) {}
613
614 @Override
615 public void visitIdent(JCIdent tree) {
616 if (exprSet.contains(tree)) {
617 for (JCVariableDecl param: md.params) {
618 if (param.name == tree.name &&
619 ((param.sym.flags_field & (MANDATED | NOOUTERTHIS)) == (MANDATED | NOOUTERTHIS))) {
620 tree.sym = param.sym;
621 }
622 }
623 }
624 }
625 }
626
627 /* ************************************************************************
628 * Traversal methods
629 *************************************************************************/
630
631 /** Visitor argument: The current environment.
632 */
633 Env<GenContext> env;
634
635 /** Visitor argument: The expected type (prototype).
636 */
637 Type pt;
638
639 /** Visitor result: The item representing the computed value.
640 */
641 Item result;
642
643 /** Visitor method: generate code for a definition, catching and reporting
644 * any completion failures.
645 * @param tree The definition to be visited.
646 * @param env The environment current at the definition.
1003 // Count up extra parameters
1004 if (meth.isConstructor()) {
1005 extras++;
1006 if (meth.enclClass().isInner() &&
1007 !meth.enclClass().isStatic()) {
1008 extras++;
1009 }
1010 } else if ((tree.mods.flags & STATIC) == 0) {
1011 extras++;
1012 }
1013 // System.err.println("Generating " + meth + " in " + meth.owner); //DEBUG
1014 if (Code.width(types.erasure(env.enclMethod.sym.type).getParameterTypes()) + extras >
1015 ClassFile.MAX_PARAMETERS) {
1016 log.error(tree.pos(), Errors.LimitParameters);
1017 nerrs++;
1018 }
1019
1020 else if (tree.body != null) {
1021 // Create a new code structure and initialize it.
1022 int startpcCrt = initCode(tree, env, fatcode);
1023 Set<VarSymbol> prevUnsetFields = code.currentUnsetFields;
1024 if (meth.isConstructor()) {
1025 code.currentUnsetFields = unsetFieldsInfo.getUnsetFields(env.enclClass.sym, tree.body);
1026 code.initialUnsetFields = unsetFieldsInfo.getUnsetFields(env.enclClass.sym, tree.body);
1027 }
1028
1029 try {
1030 genStat(tree.body, env);
1031 } catch (CodeSizeOverflow e) {
1032 // Failed due to code limit, try again with jsr/ret
1033 startpcCrt = initCode(tree, env, fatcode);
1034 genStat(tree.body, env);
1035 } finally {
1036 code.currentUnsetFields = prevUnsetFields;
1037 }
1038
1039 if (code.state.stacksize != 0) {
1040 log.error(tree.body.pos(), Errors.StackSimError(tree.sym));
1041 throw new AssertionError();
1042 }
1043
1044 // If last statement could complete normally, insert a
1045 // return at the end.
1046 if (code.isAlive()) {
1047 code.statBegin(TreeInfo.endPos(tree.body));
1048 if (env.enclMethod == null ||
1049 env.enclMethod.sym.type.getReturnType().hasTag(VOID)) {
1050 code.emitop0(return_);
1051 } else {
1052 // sometime dead code seems alive (4415991);
1053 // generate a small loop instead
1054 int startpc = code.entryPoint();
1055 CondItem c = items.makeCondItem(goto_);
1056 code.resolve(c.jumpTrue(), startpc);
1084 code.compressCatchTable();
1085
1086 // Fill in type annotation positions for exception parameters
1087 code.fillExceptionParameterPositions();
1088 }
1089 }
1090
1091 private int initCode(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) {
1092 MethodSymbol meth = tree.sym;
1093
1094 // Create a new code structure.
1095 meth.code = code = new Code(meth,
1096 fatcode,
1097 lineDebugInfo ? toplevel.lineMap : null,
1098 varDebugInfo,
1099 stackMap,
1100 debugCode,
1101 genCrt ? new CRTable(tree) : null,
1102 syms,
1103 types,
1104 poolWriter,
1105 allowValueClasses);
1106 items = new Items(poolWriter, code, syms, types);
1107 if (code.debugCode) {
1108 System.err.println(meth + " for body " + tree);
1109 }
1110
1111 // If method is not static, create a new local variable address
1112 // for `this'.
1113 if ((tree.mods.flags & STATIC) == 0) {
1114 Type selfType = meth.owner.type;
1115 if (meth.isConstructor() && selfType != syms.objectType)
1116 selfType = UninitializedType.uninitializedThis(selfType);
1117 code.setDefined(
1118 code.newLocal(
1119 new VarSymbol(FINAL, names._this, selfType, meth.owner)));
1120 }
1121
1122 // Mark all parameters as defined from the beginning of
1123 // the method.
1124 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1125 checkDimension(l.head.pos(), l.head.sym.type);
1221 public void visitForLoop(JCForLoop tree) {
1222 int limit = code.nextreg;
1223 genStats(tree.init, env);
1224 genLoop(tree, tree.body, tree.cond, tree.step, true);
1225 code.endScopes(limit);
1226 }
1227 //where
1228 /** Generate code for a loop.
1229 * @param loop The tree representing the loop.
1230 * @param body The loop's body.
1231 * @param cond The loop's controlling condition.
1232 * @param step "Step" statements to be inserted at end of
1233 * each iteration.
1234 * @param testFirst True if the loop test belongs before the body.
1235 */
1236 private void genLoop(JCStatement loop,
1237 JCStatement body,
1238 JCExpression cond,
1239 List<JCExpressionStatement> step,
1240 boolean testFirst) {
1241 Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1242 try {
1243 genLoopHelper(loop, body, cond, step, testFirst);
1244 } finally {
1245 code.currentUnsetFields = prevCodeUnsetFields;
1246 }
1247 }
1248
1249 private void genLoopHelper(JCStatement loop,
1250 JCStatement body,
1251 JCExpression cond,
1252 List<JCExpressionStatement> step,
1253 boolean testFirst) {
1254 Env<GenContext> loopEnv = env.dup(loop, new GenContext());
1255 int startpc = code.entryPoint();
1256 if (testFirst) { //while or for loop
1257 CondItem c;
1258 if (cond != null) {
1259 code.statBegin(cond.pos);
1260 Assert.check(code.isStatementStart());
1261 c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER);
1262 } else {
1263 c = items.makeCondItem(goto_);
1264 }
1265 Chain loopDone = c.jumpFalse();
1266 code.resolve(c.trueJumps);
1267 Assert.check(code.isStatementStart());
1268 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET);
1269 code.resolve(loopEnv.info.cont);
1270 genStats(step, loopEnv);
1271 code.resolve(code.branch(goto_), startpc);
1272 code.resolve(loopDone);
1273 } else {
1292 }
1293
1294 public void visitForeachLoop(JCEnhancedForLoop tree) {
1295 throw new AssertionError(); // should have been removed by Lower.
1296 }
1297
1298 public void visitLabelled(JCLabeledStatement tree) {
1299 Env<GenContext> localEnv = env.dup(tree, new GenContext());
1300 genStat(tree.body, localEnv, CRT_STATEMENT);
1301 code.resolve(localEnv.info.exit);
1302 }
1303
1304 public void visitSwitch(JCSwitch tree) {
1305 handleSwitch(tree, tree.selector, tree.cases, tree.patternSwitch);
1306 }
1307
1308 @Override
1309 public void visitSwitchExpression(JCSwitchExpression tree) {
1310 code.resolvePending();
1311 boolean prevInCondSwitchExpression = inCondSwitchExpression;
1312 Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1313 try {
1314 inCondSwitchExpression = false;
1315 doHandleSwitchExpression(tree);
1316 } finally {
1317 inCondSwitchExpression = prevInCondSwitchExpression;
1318 code.currentUnsetFields = prevCodeUnsetFields;
1319 }
1320 result = items.makeStackItem(pt);
1321 }
1322
1323 private void doHandleSwitchExpression(JCSwitchExpression tree) {
1324 List<LocalItem> prevStackBeforeSwitchExpression = stackBeforeSwitchExpression;
1325 LocalItem prevSwitchResult = switchResult;
1326 int limit = code.nextreg;
1327 try {
1328 stackBeforeSwitchExpression = List.nil();
1329 switchResult = null;
1330 if (hasTry(tree)) {
1331 //if the switch expression contains try-catch, the catch handlers need to have
1332 //an empty stack. So stash whole stack to local variables, and restore it before
1333 //breaks:
1334 while (code.state.stacksize > 0) {
1335 Type type = code.state.peek();
1336 Name varName = names.fromString(target.syntheticNameChar() +
1337 "stack" +
1338 target.syntheticNameChar() +
1374 hasTry = true;
1375 }
1376
1377 @Override
1378 public void visitClassDef(JCClassDecl tree) {
1379 }
1380
1381 @Override
1382 public void visitLambda(JCLambda tree) {
1383 }
1384 };
1385
1386 HasTryScanner hasTryScanner = new HasTryScanner();
1387
1388 hasTryScanner.scan(tree);
1389 return hasTryScanner.hasTry;
1390 }
1391
1392 private void handleSwitch(JCTree swtch, JCExpression selector, List<JCCase> cases,
1393 boolean patternSwitch) {
1394 Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1395 try {
1396 handleSwitchHelper(swtch, selector, cases, patternSwitch);
1397 } finally {
1398 code.currentUnsetFields = prevCodeUnsetFields;
1399 }
1400 }
1401
1402 void handleSwitchHelper(JCTree swtch, JCExpression selector, List<JCCase> cases,
1403 boolean patternSwitch) {
1404 int limit = code.nextreg;
1405 Assert.check(!selector.type.hasTag(CLASS));
1406 int switchStart = patternSwitch ? code.entryPoint() : -1;
1407 int startpcCrt = genCrt ? code.curCP() : 0;
1408 Assert.check(code.isStatementStart());
1409 Item sel = genExpr(selector, syms.intType);
1410 if (cases.isEmpty()) {
1411 // We are seeing: switch <sel> {}
1412 sel.load().drop();
1413 if (genCrt)
1414 code.crt.put(TreeInfo.skipParens(selector),
1415 CRT_FLOW_CONTROLLER, startpcCrt, code.curCP());
1416 } else {
1417 // We are seeing a nonempty switch.
1418 sel.load();
1419 if (genCrt)
1420 code.crt.put(TreeInfo.skipParens(selector),
1421 CRT_FLOW_CONTROLLER, startpcCrt, code.curCP());
1422 Env<GenContext> switchEnv = env.dup(swtch, new GenContext());
1423 switchEnv.info.isSwitch = true;
1424
1425 // Compute number of labels and minimum and maximum label values.
1426 // For each case, store its label in an array.
1427 int lo = Integer.MAX_VALUE; // minimum label.
1428 int hi = Integer.MIN_VALUE; // maximum label.
1429 int nlabels = 0; // number of labels.
1430
1431 int[] labels = new int[cases.length()]; // the label array.
1432 int defaultIndex = -1; // the index of the default clause.
1433
1434 List<JCCase> l = cases;
1435 for (int i = 0; i < labels.length; i++) {
1436 if (l.head.labels.head instanceof JCConstantCaseLabel constLabel) {
1437 Assert.check(l.head.labels.size() == 1);
1438 int val = ((Number) constLabel.expr.type.constValue()).intValue();
1439 labels[i] = val;
1440 if (val < lo) lo = val;
1441 if (hi < val) hi = val;
1442 nlabels++;
1443 } else {
1444 Assert.check(defaultIndex == -1);
1445 defaultIndex = i;
1446 }
1447 l = l.tail;
1448 }
1449
1450 // Determine whether to issue a tableswitch or a lookupswitch
1451 // instruction.
1452 long table_space_cost = 4 + ((long) hi - lo + 1); // words
1453 long table_time_cost = 3; // comparisons
1454 long lookup_space_cost = 3 + 2 * (long) nlabels;
1455 long lookup_time_cost = nlabels;
1456 int opcode =
1457 nlabels > 0 &&
1458 table_space_cost + 3 * table_time_cost <=
1459 lookup_space_cost + 3 * lookup_time_cost
1460 ?
1461 tableswitch : lookupswitch;
1462
1463 int startpc = code.curCP(); // the position of the selector operation
1464 code.emitop0(opcode);
1465 code.align(4);
1466 int tableBase = code.curCP(); // the start of the jump table
1467 int[] offsets = null; // a table of offsets for a lookupswitch
1468 code.emit4(-1); // leave space for default offset
1469 if (opcode == tableswitch) {
1470 code.emit4(lo); // minimum label
1471 code.emit4(hi); // maximum label
1472 for (long i = lo; i <= hi; i++) { // leave space for jump table
1473 code.emit4(-1);
1474 }
1475 } else {
1476 code.emit4(nlabels); // number of labels
1477 for (int i = 0; i < nlabels; i++) {
1478 code.emit4(-1); code.emit4(-1); // leave space for lookup table
1479 }
1480 offsets = new int[labels.length];
1481 }
1482 Code.State stateSwitch = code.state.dup();
1483 code.markDead();
1484
1485 // For each case do:
1486 l = cases;
1487 for (int i = 0; i < labels.length; i++) {
1488 JCCase c = l.head;
1489 l = l.tail;
1490
1491 int pc = code.entryPoint(stateSwitch);
1492 // Insert offset directly into code or else into the
1493 // offsets table.
1494 if (i != defaultIndex) {
1495 if (opcode == tableswitch) {
1496 code.put4(
1497 tableBase + 4 * (labels[i] - lo + 3),
1498 pc - startpc);
1499 } else {
1500 offsets[i] = pc - startpc;
1501 }
1502 } else {
1503 code.put4(tableBase, pc - startpc);
1504 }
1505
1506 // Generate code for the statements in this case.
1507 genStats(c.stats, switchEnv, CRT_FLOW_TARGET);
1508 }
1509
1510 if (switchEnv.info.cont != null) {
1511 Assert.check(patternSwitch);
1512 code.resolve(switchEnv.info.cont, switchStart);
1513 }
1514
1515 // Resolve all breaks.
1516 code.resolve(switchEnv.info.exit);
1517
1518 // If we have not set the default offset, we do so now.
1528 if (code.get4(t) == -1)
1529 code.put4(t, defaultOffset);
1530 }
1531 } else {
1532 // Sort non-default offsets and copy into lookup table.
1533 if (defaultIndex >= 0)
1534 for (int i = defaultIndex; i < labels.length - 1; i++) {
1535 labels[i] = labels[i+1];
1536 offsets[i] = offsets[i+1];
1537 }
1538 if (nlabels > 0)
1539 qsort2(labels, offsets, 0, nlabels - 1);
1540 for (int i = 0; i < nlabels; i++) {
1541 int caseidx = tableBase + 8 * (i + 1);
1542 code.put4(caseidx, labels[i]);
1543 code.put4(caseidx + 4, offsets[i]);
1544 }
1545 }
1546
1547 if (swtch instanceof JCSwitchExpression) {
1548 // Emit line position for the end of a switch expression
1549 code.statBegin(TreeInfo.endPos(swtch));
1550 }
1551 }
1552 code.endScopes(limit);
1553 }
1554 //where
1555 /** Sort (int) arrays of keys and values
1556 */
1557 static void qsort2(int[] keys, int[] values, int lo, int hi) {
1558 int i = lo;
1559 int j = hi;
1560 int pivot = keys[(i+j)/2];
1561 do {
1562 while (keys[i] < pivot) i++;
1563 while (pivot < keys[j]) j--;
1564 if (i <= j) {
1565 int temp1 = keys[i];
1566 keys[i] = keys[j];
1567 keys[j] = temp1;
1568 int temp2 = values[i];
1569 values[i] = values[j];
1632 @Override
1633 void afterBody() {
1634 if (tree.finalizer != null && (tree.finalizer.flags & BODY_ONLY_FINALIZE) != 0) {
1635 //for body-only finally, remove the GenFinalizer after try body
1636 //so that the finally is not generated to catch bodies:
1637 tryEnv.info.finalize = null;
1638 }
1639 }
1640
1641 };
1642 tryEnv.info.gaps = new ListBuffer<>();
1643 genTry(tree.body, tree.catchers, tryEnv);
1644 }
1645 //where
1646 /** Generate code for a try or synchronized statement
1647 * @param body The body of the try or synchronized statement.
1648 * @param catchers The list of catch clauses.
1649 * @param env The current environment of the body.
1650 */
1651 void genTry(JCTree body, List<JCCatch> catchers, Env<GenContext> env) {
1652 Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1653 try {
1654 genTryHelper(body, catchers, env);
1655 } finally {
1656 code.currentUnsetFields = prevCodeUnsetFields;
1657 }
1658 }
1659
1660 void genTryHelper(JCTree body, List<JCCatch> catchers, Env<GenContext> env) {
1661 int limit = code.nextreg;
1662 int startpc = code.curCP();
1663 Code.State stateTry = code.state.dup();
1664 genStat(body, env, CRT_BLOCK);
1665 int endpc = code.curCP();
1666 List<Integer> gaps = env.info.gaps.toList();
1667 code.statBegin(TreeInfo.endPos(body));
1668 genFinalizer(env);
1669 code.statBegin(TreeInfo.endPos(env.tree));
1670 Chain exitChain;
1671 boolean actualTry = env.tree.hasTag(TRY);
1672 if (startpc == endpc && actualTry) {
1673 exitChain = code.branch(dontgoto);
1674 } else {
1675 exitChain = code.branch(goto_);
1676 }
1677 endFinalizerGap(env);
1678 env.info.finalize.afterBody();
1679 boolean hasFinalizer =
1680 env.info.finalize != null &&
1681 env.info.finalize.hasFinalizer();
1682 if (startpc != endpc) for (List<JCCatch> l = catchers; l.nonEmpty(); l = l.tail) {
1683 // start off with exception on stack
1684 code.entryPoint(stateTry, l.head.param.sym.type);
1685 genCatch(l.head, env, startpc, endpc, gaps);
1686 genFinalizer(env);
1687 if (hasFinalizer || l.tail.nonEmpty()) {
1688 code.statBegin(TreeInfo.endPos(env.tree));
1689 exitChain = Code.mergeChains(exitChain,
1690 code.branch(goto_));
1691 }
1692 endFinalizerGap(env);
1693 }
1694 if (hasFinalizer && (startpc != endpc || !actualTry)) {
1695 // Create a new register segment to avoid allocating
1696 // the same variables in finalizers and other statements.
1697 code.newRegSegment();
1698
1699 // Add a catch-all clause.
1700
1701 // start off with exception on stack
1702 int catchallpc = code.entryPoint(stateTry, syms.throwableType);
1703
1704 // Register all exception ranges for catch all clause.
1705 // The range of the catch all clause is from the beginning
1706 // of the try or synchronized block until the present
1707 // code pointer excluding all gaps in the current
1708 // environment's GenContext.
1709 int startseg = startpc;
1710 while (env.info.gaps.nonEmpty()) {
1711 int endseg = env.info.gaps.next().intValue();
1712 registerCatch(body.pos(), startseg, endseg,
1713 catchallpc, 0);
1714 startseg = env.info.gaps.next().intValue();
1715 }
1716 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS));
1717 code.markStatBegin();
1718
1719 Item excVar = makeTemp(syms.throwableType);
1720 excVar.store();
1721 genFinalizer(env);
1722 code.resolvePending();
1723 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.END_POS));
1724 code.markStatBegin();
1725
1726 excVar.load();
1727 registerCatch(body.pos(), startseg,
1728 env.info.gaps.next().intValue(),
1729 catchallpc, 0);
1730 code.emitop0(athrow);
1731 code.markDead();
1732
1733 // If there are jsr's to this finalizer, ...
1734 if (env.info.cont != null) {
1735 // Resolve all jsr's.
1736 code.resolve(env.info.cont);
1737
1738 // Mark statement line number
1739 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS));
1740 code.markStatBegin();
1741
1742 // Save return address.
1743 LocalItem retVar = makeTemp(syms.throwableType);
1744 retVar.store();
1745
1746 // Generate finalizer code.
1747 env.info.finalize.genLast();
1748
1749 // Return.
1852 /** Register a catch clause in the "Exceptions" code-attribute.
1853 */
1854 void registerCatch(DiagnosticPosition pos,
1855 int startpc, int endpc,
1856 int handler_pc, int catch_type) {
1857 char startpc1 = (char)startpc;
1858 char endpc1 = (char)endpc;
1859 char handler_pc1 = (char)handler_pc;
1860 if (startpc1 == startpc &&
1861 endpc1 == endpc &&
1862 handler_pc1 == handler_pc) {
1863 code.addCatch(startpc1, endpc1, handler_pc1,
1864 (char)catch_type);
1865 } else {
1866 log.error(pos, Errors.LimitCodeTooLargeForTryStmt);
1867 nerrs++;
1868 }
1869 }
1870
1871 public void visitIf(JCIf tree) {
1872 Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1873 try {
1874 visitIfHelper(tree);
1875 } finally {
1876 code.currentUnsetFields = prevCodeUnsetFields;
1877 }
1878 }
1879
1880 public void visitIfHelper(JCIf tree) {
1881 int limit = code.nextreg;
1882 Chain thenExit = null;
1883 Assert.check(code.isStatementStart());
1884 CondItem c = genCond(TreeInfo.skipParens(tree.cond),
1885 CRT_FLOW_CONTROLLER);
1886 Chain elseChain = c.jumpFalse();
1887 Assert.check(code.isStatementStart());
1888 if (!c.isFalse()) {
1889 code.resolve(c.trueJumps);
1890 genStat(tree.thenpart, env, CRT_STATEMENT | CRT_FLOW_TARGET);
1891 thenExit = code.branch(goto_);
1892 }
1893 if (elseChain != null) {
1894 code.resolve(elseChain);
1895 if (tree.elsepart != null) {
1896 genStat(tree.elsepart, env,CRT_STATEMENT | CRT_FLOW_TARGET);
1897 }
1898 }
1899 code.resolve(thenExit);
1900 code.endScopes(limit);
1901 Assert.check(code.isStatementStart());
1902 }
1903
1904 public void visitExec(JCExpressionStatement tree) {
1905 // Optimize x++ to ++x and x-- to --x.
2189 nerrs++;
2190 }
2191 int elemcode = Code.arraycode(elemtype);
2192 if (elemcode == 0 || (elemcode == 1 && ndims == 1)) {
2193 code.emitAnewarray(makeRef(pos, elemtype), type);
2194 } else if (elemcode == 1) {
2195 code.emitMultianewarray(ndims, makeRef(pos, type), type);
2196 } else {
2197 code.emitNewarray(elemcode, type);
2198 }
2199 return items.makeStackItem(type);
2200 }
2201
2202 public void visitParens(JCParens tree) {
2203 result = genExpr(tree.expr, tree.expr.type);
2204 }
2205
2206 public void visitAssign(JCAssign tree) {
2207 Item l = genExpr(tree.lhs, tree.lhs.type);
2208 genExpr(tree.rhs, tree.lhs.type).load();
2209 Set<VarSymbol> tmpUnsetSymbols = unsetFieldsInfo.getUnsetFields(env.enclClass.sym, tree);
2210 code.currentUnsetFields = tmpUnsetSymbols != null ? tmpUnsetSymbols : code.currentUnsetFields;
2211 if (tree.rhs.type.hasTag(BOT)) {
2212 /* This is just a case of widening reference conversion that per 5.1.5 simply calls
2213 for "regarding a reference as having some other type in a manner that can be proved
2214 correct at compile time."
2215 */
2216 code.state.forceStackTop(tree.lhs.type);
2217 }
2218 result = items.makeAssignItem(l);
2219 }
2220
2221 public void visitAssignop(JCAssignOp tree) {
2222 OperatorSymbol operator = tree.operator;
2223 Item l;
2224 if (operator.opcode == string_add) {
2225 l = concat.makeConcat(tree);
2226 } else {
2227 // Generate code for first expression
2228 l = genExpr(tree.lhs, tree.lhs.type);
2229
2230 // If we have an increment of -32768 to +32767 of a local
2469 items.makeThisItem().load();
2470 sym = binaryQualifier(sym, env.enclClass.type);
2471 result = items.makeMemberItem(sym, nonVirtualForPrivateAccess(sym));
2472 }
2473 }
2474
2475 //where
2476 private boolean nonVirtualForPrivateAccess(Symbol sym) {
2477 boolean useVirtual = target.hasVirtualPrivateInvoke() &&
2478 !disableVirtualizedPrivateInvoke;
2479 return !useVirtual && ((sym.flags() & PRIVATE) != 0);
2480 }
2481
2482 public void visitSelect(JCFieldAccess tree) {
2483 Symbol sym = tree.sym;
2484
2485 if (tree.name == names._class) {
2486 code.emitLdc((LoadableConstant)checkDimension(tree.pos(), tree.selected.type));
2487 result = items.makeStackItem(pt);
2488 return;
2489 }
2490
2491 Symbol ssym = TreeInfo.symbol(tree.selected);
2492
2493 // Are we selecting via super?
2494 boolean selectSuper =
2495 ssym != null && (ssym.kind == TYP || ssym.name == names._super);
2496
2497 // Are we accessing a member of the superclass in an access method
2498 // resulting from a qualified super?
2499 boolean accessSuper = isAccessSuper(env.enclMethod);
2500
2501 Item base = (selectSuper)
2502 ? items.makeSuperItem()
2503 : genExpr(tree.selected, tree.selected.type);
2504
2505 if (sym.kind == VAR && ((VarSymbol) sym).getConstValue() != null) {
2506 // We are seeing a variable that is constant but its selecting
2507 // expression is not.
2508 if ((sym.flags() & STATIC) != 0) {
2509 if (!selectSuper && (ssym == null || ssym.kind != TYP))
|