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