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