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 23 * questions. 24 */ 25 26 package com.sun.tools.javac.jvm; 27 28 import java.util.HashMap; 29 import java.util.Map; 30 import java.util.Set; 31 32 import com.sun.tools.javac.jvm.PoolConstant.LoadableConstant; 33 import com.sun.tools.javac.tree.TreeInfo.PosKind; 34 import com.sun.tools.javac.util.*; 35 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 36 import com.sun.tools.javac.util.List; 37 import com.sun.tools.javac.code.*; 38 import com.sun.tools.javac.code.Attribute.TypeCompound; 39 import com.sun.tools.javac.code.Symbol.VarSymbol; 40 import com.sun.tools.javac.comp.*; 41 import com.sun.tools.javac.tree.*; 42 43 import com.sun.tools.javac.code.Symbol.*; 44 import com.sun.tools.javac.code.Type.*; 45 import com.sun.tools.javac.jvm.Code.*; 46 import com.sun.tools.javac.jvm.Items.*; 47 import com.sun.tools.javac.resources.CompilerProperties.Errors; 48 import com.sun.tools.javac.tree.EndPosTable; 49 import com.sun.tools.javac.tree.JCTree.*; 50 51 import static com.sun.tools.javac.code.Flags.*; 52 import static com.sun.tools.javac.code.Kinds.Kind.*; 53 import static com.sun.tools.javac.code.TypeTag.*; 54 import static com.sun.tools.javac.jvm.ByteCodes.*; 55 import static com.sun.tools.javac.jvm.CRTFlags.*; 56 import static com.sun.tools.javac.main.Option.*; 57 import static com.sun.tools.javac.tree.JCTree.Tag.*; 58 59 /** This pass maps flat Java (i.e. without inner classes) to bytecodes. 60 * 61 * <p><b>This is NOT part of any supported API. 62 * If you write code that depends on this, you do so at your own risk. 63 * This code and its internal interfaces are subject to change or 64 * deletion without notice.</b> 65 */ 66 public class Gen extends JCTree.Visitor { 67 protected static final Context.Key<Gen> genKey = new Context.Key<>(); 68 69 private final Log log; 70 private final Symtab syms; 71 private final Check chk; 72 private final Resolve rs; 73 private final TreeMaker make; 74 private final Names names; 75 private final Target target; 76 private final String accessDollar; 77 private final Types types; 78 private final Lower lower; 79 private final Annotate annotate; 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; 164 165 /** An object containing mappings of syntax trees to their 166 * ending source positions. 167 */ 168 EndPosTable endPosTable; 169 170 boolean inCondSwitchExpression; 171 Chain switchExpressionTrueChain; 172 Chain switchExpressionFalseChain; 173 List<LocalItem> stackBeforeSwitchExpression; 174 LocalItem switchResult; 175 PatternMatchingCatchConfiguration patternMatchingCatchConfiguration = 176 new PatternMatchingCatchConfiguration(Set.of(), null, null, null); 177 178 /** Cache the symbol to reflect the qualifying type. 179 * key: corresponding type 180 * value: qualified symbol 181 */ 182 Map<Type, Symbol> qualifiedSymbolCache; 183 184 /** Generate code to load an integer constant. 185 * @param n The integer to be loaded. 186 */ 187 void loadIntConst(int n) { 188 items.makeImmediateItem(syms.intType, n).load(); 189 } 190 191 /** The opcode that loads a zero constant of a given type code. 192 * @param tc The given type code (@see ByteCode). 193 */ 194 public static int zero(int tc) { 195 switch(tc) { 196 case INTcode: case BYTEcode: case SHORTcode: case CHARcode: 197 return iconst_0; 198 case LONGcode: 199 return lconst_0; 200 case FLOATcode: 201 return fconst_0; 202 case DOUBLEcode: 203 return dconst_0; 204 default: 205 throw new AssertionError("zero"); 206 } 207 } 208 209 /** The opcode that loads a one constant of a given type code. 210 * @param tc The given type code (@see ByteCode). 211 */ 212 public static int one(int tc) { 213 return zero(tc) + 1; 214 } 215 216 /** Generate code to load -1 of the given type code (either int or long). 217 * @param tc The given type code (@see ByteCode). 218 */ 219 void emitMinusOne(int tc) { 220 if (tc == LONGcode) { 221 items.makeImmediateItem(syms.longType, Long.valueOf(-1)).load(); 222 } else { 223 code.emitop0(iconst_m1); 224 } 225 } 226 227 /** Construct a symbol to reflect the qualifying type that should 228 * appear in the byte code as per JLS 13.1. 229 * 230 * For {@literal target >= 1.2}: Clone a method with the qualifier as owner (except 231 * for those cases where we need to work around VM bugs). 232 * 233 * For {@literal target <= 1.1}: If qualified variable or method is defined in a 234 * non-accessible class, clone it with the qualifier class as owner. 235 * 236 * @param sym The accessed symbol 237 * @param site The qualifier's type. 238 */ 239 Symbol binaryQualifier(Symbol sym, Type site) { 240 241 if (site.hasTag(ARRAY)) { 242 if (sym == syms.lengthVar || 243 sym.owner != syms.arrayClass) 244 return sym; 245 // array clone can be qualified by the array type in later targets 246 Symbol qualifier; 247 if ((qualifier = qualifiedSymbolCache.get(site)) == null) { 248 qualifier = new ClassSymbol(Flags.PUBLIC, site.tsym.name, site, syms.noSymbol); 249 qualifiedSymbolCache.put(site, qualifier); 250 } 251 return sym.clone(qualifier); 252 } 253 254 if (sym.owner == site.tsym || 255 (sym.flags() & (STATIC | SYNTHETIC)) == (STATIC | SYNTHETIC)) { 256 return sym; 257 } 258 259 // leave alone methods inherited from Object 260 // JLS 13.1. 261 if (sym.owner == syms.objectType.tsym) 262 return sym; 263 264 return sym.clone(site.tsym); 265 } 266 267 /** Insert a reference to given type in the constant pool, 268 * checking for an array with too many dimensions; 269 * return the reference's index. 270 * @param type The type for which a reference is inserted. 271 */ 272 int makeRef(DiagnosticPosition pos, Type type) { 273 return poolWriter.putClass(checkDimension(pos, type)); 274 } 275 276 /** Check if the given type is an array with too many dimensions. 277 */ 278 private Type checkDimension(DiagnosticPosition pos, Type t) { 279 checkDimensionInternal(pos, t); 280 return t; 281 } 282 283 private void checkDimensionInternal(DiagnosticPosition pos, Type t) { 284 switch (t.getTag()) { 285 case METHOD: 286 checkDimension(pos, t.getReturnType()); 287 for (List<Type> args = t.getParameterTypes(); args.nonEmpty(); args = args.tail) 288 checkDimension(pos, args.head); 289 break; 290 case ARRAY: 291 if (types.dimensions(t) > ClassFile.MAX_DIMENSIONS) { 292 log.error(pos, Errors.LimitDimensions); 293 nerrs++; 294 } 295 break; 296 default: 297 break; 298 } 299 } 300 301 /** Create a temporary variable. 302 * @param type The variable's type. 303 */ 304 LocalItem makeTemp(Type type) { 305 VarSymbol v = new VarSymbol(Flags.SYNTHETIC, 306 names.empty, 307 type, 308 env.enclMethod.sym); 309 code.newLocal(v); 310 return items.makeLocalItem(v); 311 } 312 313 /** Generate code to call a non-private method or constructor. 314 * @param pos Position to be used for error reporting. 315 * @param site The type of which the method is a member. 316 * @param name The method's name. 317 * @param argtypes The method's argument types. 318 * @param isStatic A flag that indicates whether we call a 319 * static or instance method. 320 */ 321 void callMethod(DiagnosticPosition pos, 322 Type site, Name name, List<Type> argtypes, 323 boolean isStatic) { 324 Symbol msym = rs. 325 resolveInternalMethod(pos, attrEnv, site, name, argtypes, null); 326 if (isStatic) items.makeStaticItem(msym).invoke(); 327 else items.makeMemberItem(msym, name == names.init).invoke(); 328 } 329 330 /** Is the given method definition an access method 331 * resulting from a qualified super? This is signified by an odd 332 * access code. 333 */ 334 private boolean isAccessSuper(JCMethodDecl enclMethod) { 335 return 336 (enclMethod.mods.flags & SYNTHETIC) != 0 && 337 isOddAccessName(enclMethod.name); 338 } 339 340 /** Does given name start with "access$" and end in an odd digit? 341 */ 342 private boolean isOddAccessName(Name name) { 343 final String string = name.toString(); 344 return 345 string.startsWith(accessDollar) && 346 (string.charAt(string.length() - 1) & 1) != 0; 347 } 348 349 /* ************************************************************************ 350 * Non-local exits 351 *************************************************************************/ 352 353 /** Generate code to invoke the finalizer associated with given 354 * environment. 355 * Any calls to finalizers are appended to the environments `cont' chain. 356 * Mark beginning of gap in catch all range for finalizer. 357 */ 358 void genFinalizer(Env<GenContext> env) { 359 if (code.isAlive() && env.info.finalize != null) 360 env.info.finalize.gen(); 361 } 362 363 /** Generate code to call all finalizers of structures aborted by 364 * a non-local 365 * exit. Return target environment of the non-local exit. 366 * @param target The tree representing the structure that's aborted 367 * @param env The environment current at the non-local exit. 368 */ 369 Env<GenContext> unwind(JCTree target, Env<GenContext> env) { 370 Env<GenContext> env1 = env; 371 while (true) { 372 genFinalizer(env1); 373 if (env1.tree == target) break; 374 env1 = env1.next; 375 } 376 return env1; 377 } 378 379 /** Mark end of gap in catch-all range for finalizer. 380 * @param env the environment which might contain the finalizer 381 * (if it does, env.info.gaps != null). 382 */ 383 void endFinalizerGap(Env<GenContext> env) { 384 if (env.info.gaps != null && env.info.gaps.length() % 2 == 1) 385 env.info.gaps.append(code.curCP()); 386 } 387 388 /** Mark end of all gaps in catch-all ranges for finalizers of environments 389 * lying between, and including to two environments. 390 * @param from the most deeply nested environment to mark 391 * @param to the least deeply nested environment to mark 392 */ 393 void endFinalizerGaps(Env<GenContext> from, Env<GenContext> to) { 394 Env<GenContext> last = null; 395 while (last != to) { 396 endFinalizerGap(from); 397 last = from; 398 from = from.next; 399 } 400 } 401 402 /** Do any of the structures aborted by a non-local exit have 403 * finalizers that require an empty stack? 404 * @param target The tree representing the structure that's aborted 405 * @param env The environment current at the non-local exit. 406 */ 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()); 508 if (!c.getClassInitTypeAttributes().isEmpty()) 509 clinit.appendUniqueTypeAttributes(c.getClassInitTypeAttributes()); 510 } 511 // Return all method definitions. 512 return methodDefs.toList(); 513 } 514 515 private List<Attribute.TypeCompound> getAndRemoveNonFieldTAs(VarSymbol sym) { 516 List<TypeCompound> tas = sym.getRawTypeAttributes(); 517 ListBuffer<Attribute.TypeCompound> fieldTAs = new ListBuffer<>(); 518 ListBuffer<Attribute.TypeCompound> nonfieldTAs = new ListBuffer<>(); 519 for (TypeCompound ta : tas) { 520 Assert.check(ta.getPosition().type != TargetType.UNKNOWN); 521 if (ta.getPosition().type == TargetType.FIELD) { 522 fieldTAs.add(ta); 523 } else { 524 nonfieldTAs.add(ta); 525 } 526 } 527 sym.setTypeAttributes(fieldTAs.toList()); 528 return nonfieldTAs.toList(); 529 } 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. 583 */ 584 public void genDef(JCTree tree, Env<GenContext> env) { 585 Env<GenContext> prevEnv = this.env; 586 try { 587 this.env = env; 588 tree.accept(this); 589 } catch (CompletionFailure ex) { 590 chk.completionError(tree.pos(), ex); 591 } finally { 592 this.env = prevEnv; 593 } 594 } 595 596 /** Derived visitor method: check whether CharacterRangeTable 597 * should be emitted, if so, put a new entry into CRTable 598 * and call method to generate bytecode. 599 * If not, just call method to generate bytecode. 600 * @see #genStat(JCTree, Env) 601 * 602 * @param tree The tree to be visited. 603 * @param env The environment to use. 604 * @param crtFlags The CharacterRangeTable flags 605 * indicating type of the entry. 606 */ 607 public void genStat(JCTree tree, Env<GenContext> env, int crtFlags) { 608 if (!genCrt) { 609 genStat(tree, env); 610 return; 611 } 612 int startpc = code.curCP(); 613 genStat(tree, env); 614 if (tree.hasTag(Tag.BLOCK)) crtFlags |= CRT_BLOCK; 615 code.crt.put(tree, crtFlags, startpc, code.curCP()); 616 } 617 618 /** Derived visitor method: generate code for a statement. 619 */ 620 public void genStat(JCTree tree, Env<GenContext> env) { 621 if (code.isAlive()) { 622 code.statBegin(tree.pos); 623 genDef(tree, env); 624 } else if (env.info.isSwitch && tree.hasTag(VARDEF)) { 625 // variables whose declarations are in a switch 626 // can be used even if the decl is unreachable. 627 code.newLocal(((JCVariableDecl) tree).sym); 628 } 629 } 630 631 /** Derived visitor method: check whether CharacterRangeTable 632 * should be emitted, if so, put a new entry into CRTable 633 * and call method to generate bytecode. 634 * If not, just call method to generate bytecode. 635 * @see #genStats(List, Env) 636 * 637 * @param trees The list of trees to be visited. 638 * @param env The environment to use. 639 * @param crtFlags The CharacterRangeTable flags 640 * indicating type of the entry. 641 */ 642 public void genStats(List<JCStatement> trees, Env<GenContext> env, int crtFlags) { 643 if (!genCrt) { 644 genStats(trees, env); 645 return; 646 } 647 if (trees.length() == 1) { // mark one statement with the flags 648 genStat(trees.head, env, crtFlags | CRT_STATEMENT); 649 } else { 650 int startpc = code.curCP(); 651 genStats(trees, env); 652 code.crt.put(trees, crtFlags, startpc, code.curCP()); 653 } 654 } 655 656 /** Derived visitor method: generate code for a list of statements. 657 */ 658 public void genStats(List<? extends JCTree> trees, Env<GenContext> env) { 659 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail) 660 genStat(l.head, env, CRT_STATEMENT); 661 } 662 663 /** Derived visitor method: check whether CharacterRangeTable 664 * should be emitted, if so, put a new entry into CRTable 665 * and call method to generate bytecode. 666 * If not, just call method to generate bytecode. 667 * @see #genCond(JCTree,boolean) 668 * 669 * @param tree The tree to be visited. 670 * @param crtFlags The CharacterRangeTable flags 671 * indicating type of the entry. 672 */ 673 public CondItem genCond(JCTree tree, int crtFlags) { 674 if (!genCrt) return genCond(tree, false); 675 int startpc = code.curCP(); 676 CondItem item = genCond(tree, (crtFlags & CRT_FLOW_CONTROLLER) != 0); 677 code.crt.put(tree, crtFlags, startpc, code.curCP()); 678 return item; 679 } 680 681 /** Derived visitor method: generate code for a boolean 682 * expression in a control-flow context. 683 * @param _tree The expression to be visited. 684 * @param markBranches The flag to indicate that the condition is 685 * a flow controller so produced conditions 686 * should contain a proper tree to generate 687 * CharacterRangeTable branches for them. 688 */ 689 public CondItem genCond(JCTree _tree, boolean markBranches) { 690 JCTree inner_tree = TreeInfo.skipParens(_tree); 691 if (inner_tree.hasTag(CONDEXPR)) { 692 JCConditional tree = (JCConditional)inner_tree; 693 CondItem cond = genCond(tree.cond, CRT_FLOW_CONTROLLER); 694 if (cond.isTrue()) { 695 code.resolve(cond.trueJumps); 696 CondItem result = genCond(tree.truepart, CRT_FLOW_TARGET); 697 if (markBranches) result.tree = tree.truepart; 698 return result; 699 } 700 if (cond.isFalse()) { 701 code.resolve(cond.falseJumps); 702 CondItem result = genCond(tree.falsepart, CRT_FLOW_TARGET); 703 if (markBranches) result.tree = tree.falsepart; 704 return result; 705 } 706 Chain secondJumps = cond.jumpFalse(); 707 code.resolve(cond.trueJumps); 708 CondItem first = genCond(tree.truepart, CRT_FLOW_TARGET); 709 if (markBranches) first.tree = tree.truepart; 710 Chain falseJumps = first.jumpFalse(); 711 code.resolve(first.trueJumps); 712 Chain trueJumps = code.branch(goto_); 713 code.resolve(secondJumps); 714 CondItem second = genCond(tree.falsepart, CRT_FLOW_TARGET); 715 CondItem result = items.makeCondItem(second.opcode, 716 Code.mergeChains(trueJumps, second.trueJumps), 717 Code.mergeChains(falseJumps, second.falseJumps)); 718 if (markBranches) result.tree = tree.falsepart; 719 return result; 720 } else if (inner_tree.hasTag(SWITCH_EXPRESSION)) { 721 code.resolvePending(); 722 723 boolean prevInCondSwitchExpression = inCondSwitchExpression; 724 Chain prevSwitchExpressionTrueChain = switchExpressionTrueChain; 725 Chain prevSwitchExpressionFalseChain = switchExpressionFalseChain; 726 try { 727 inCondSwitchExpression = true; 728 switchExpressionTrueChain = null; 729 switchExpressionFalseChain = null; 730 try { 731 doHandleSwitchExpression((JCSwitchExpression) inner_tree); 732 } catch (CompletionFailure ex) { 733 chk.completionError(_tree.pos(), ex); 734 code.state.stacksize = 1; 735 } 736 CondItem result = items.makeCondItem(goto_, 737 switchExpressionTrueChain, 738 switchExpressionFalseChain); 739 if (markBranches) result.tree = _tree; 740 return result; 741 } finally { 742 inCondSwitchExpression = prevInCondSwitchExpression; 743 switchExpressionTrueChain = prevSwitchExpressionTrueChain; 744 switchExpressionFalseChain = prevSwitchExpressionFalseChain; 745 } 746 } else if (inner_tree.hasTag(LETEXPR) && ((LetExpr) inner_tree).needsCond) { 747 code.resolvePending(); 748 749 LetExpr tree = (LetExpr) inner_tree; 750 int limit = code.nextreg; 751 int prevLetExprStart = code.setLetExprStackPos(code.state.stacksize); 752 try { 753 genStats(tree.defs, env); 754 } finally { 755 code.setLetExprStackPos(prevLetExprStart); 756 } 757 CondItem result = genCond(tree.expr, markBranches); 758 code.endScopes(limit); 759 //make sure variables defined in the let expression are not included 760 //in the defined variables for jumps that go outside of this let 761 //expression: 762 undefineVariablesInChain(result.falseJumps, limit); 763 undefineVariablesInChain(result.trueJumps, limit); 764 return result; 765 } else { 766 CondItem result = genExpr(_tree, syms.booleanType).mkCond(); 767 if (markBranches) result.tree = _tree; 768 return result; 769 } 770 } 771 //where: 772 private void undefineVariablesInChain(Chain toClear, int limit) { 773 while (toClear != null) { 774 toClear.state.defined.excludeFrom(limit); 775 toClear = toClear.next; 776 } 777 } 778 779 public Code getCode() { 780 return code; 781 } 782 783 public Items getItems() { 784 return items; 785 } 786 787 public Env<AttrContext> getAttrEnv() { 788 return attrEnv; 789 } 790 791 /** Visitor class for expressions which might be constant expressions. 792 * This class is a subset of TreeScanner. Intended to visit trees pruned by 793 * Lower as long as constant expressions looking for references to any 794 * ClassSymbol. Any such reference will be added to the constant pool so 795 * automated tools can detect class dependencies better. 796 */ 797 class ClassReferenceVisitor extends JCTree.Visitor { 798 799 @Override 800 public void visitTree(JCTree tree) {} 801 802 @Override 803 public void visitBinary(JCBinary tree) { 804 tree.lhs.accept(this); 805 tree.rhs.accept(this); 806 } 807 808 @Override 809 public void visitSelect(JCFieldAccess tree) { 810 if (tree.selected.type.hasTag(CLASS)) { 811 makeRef(tree.selected.pos(), tree.selected.type); 812 } 813 } 814 815 @Override 816 public void visitIdent(JCIdent tree) { 817 if (tree.sym.owner instanceof ClassSymbol classSymbol) { 818 poolWriter.putClass(classSymbol); 819 } 820 } 821 822 @Override 823 public void visitConditional(JCConditional tree) { 824 tree.cond.accept(this); 825 tree.truepart.accept(this); 826 tree.falsepart.accept(this); 827 } 828 829 @Override 830 public void visitUnary(JCUnary tree) { 831 tree.arg.accept(this); 832 } 833 834 @Override 835 public void visitParens(JCParens tree) { 836 tree.expr.accept(this); 837 } 838 839 @Override 840 public void visitTypeCast(JCTypeCast tree) { 841 tree.expr.accept(this); 842 } 843 } 844 845 private ClassReferenceVisitor classReferenceVisitor = new ClassReferenceVisitor(); 846 847 /** Visitor method: generate code for an expression, catching and reporting 848 * any completion failures. 849 * @param tree The expression to be visited. 850 * @param pt The expression's expected type (proto-type). 851 */ 852 public Item genExpr(JCTree tree, Type pt) { 853 if (!code.isAlive()) { 854 return items.makeStackItem(pt); 855 } 856 857 Type prevPt = this.pt; 858 try { 859 if (tree.type.constValue() != null) { 860 // Short circuit any expressions which are constants 861 tree.accept(classReferenceVisitor); 862 checkStringConstant(tree.pos(), tree.type.constValue()); 863 Symbol sym = TreeInfo.symbol(tree); 864 if (sym != null && isConstantDynamic(sym)) { 865 result = items.makeDynamicItem(sym); 866 } else { 867 result = items.makeImmediateItem(tree.type, tree.type.constValue()); 868 } 869 } else { 870 this.pt = pt; 871 tree.accept(this); 872 } 873 return result.coerce(pt); 874 } catch (CompletionFailure ex) { 875 chk.completionError(tree.pos(), ex); 876 code.state.stacksize = 1; 877 return items.makeStackItem(pt); 878 } finally { 879 this.pt = prevPt; 880 } 881 } 882 883 public boolean isConstantDynamic(Symbol sym) { 884 return sym.kind == VAR && 885 sym instanceof DynamicVarSymbol dynamicVarSymbol && 886 dynamicVarSymbol.isDynamic(); 887 } 888 889 /** Derived visitor method: generate code for a list of method arguments. 890 * @param trees The argument expressions to be visited. 891 * @param pts The expression's expected types (i.e. the formal parameter 892 * types of the invoked method). 893 */ 894 public void genArgs(List<JCExpression> trees, List<Type> pts) { 895 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) { 896 genExpr(l.head, pts.head).load(); 897 pts = pts.tail; 898 } 899 // require lists be of same length 900 Assert.check(pts.isEmpty()); 901 } 902 903 /* ************************************************************************ 904 * Visitor methods for statements and definitions 905 *************************************************************************/ 906 907 /** Thrown when the byte code size exceeds limit. 908 */ 909 public static class CodeSizeOverflow extends RuntimeException { 910 private static final long serialVersionUID = 0; 911 public CodeSizeOverflow() {} 912 } 913 914 public void visitMethodDef(JCMethodDecl tree) { 915 // Create a new local environment that points pack at method 916 // definition. 917 Env<GenContext> localEnv = env.dup(tree); 918 localEnv.enclMethod = tree; 919 // The expected type of every return statement in this method 920 // is the method's return type. 921 this.pt = tree.sym.erasure(types).getReturnType(); 922 923 checkDimension(tree.pos(), tree.sym.erasure(types)); 924 genMethod(tree, localEnv, false); 925 } 926 //where 927 /** Generate code for a method. 928 * @param tree The tree representing the method definition. 929 * @param env The environment current for the method body. 930 * @param fatcode A flag that indicates whether all jumps are 931 * within 32K. We first invoke this method under 932 * the assumption that fatcode == false, i.e. all 933 * jumps are within 32K. If this fails, fatcode 934 * is set to true and we try again. 935 */ 936 void genMethod(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) { 937 MethodSymbol meth = tree.sym; 938 int extras = 0; 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); 986 } 987 } 988 if (genCrt) 989 code.crt.put(tree.body, 990 CRT_BLOCK, 991 startpcCrt, 992 code.curCP()); 993 994 code.endScopes(0); 995 996 // If we exceeded limits, panic 997 if (code.checkLimits(tree.pos(), log)) { 998 nerrs++; 999 return; 1000 } 1001 1002 // If we generated short code but got a long jump, do it again 1003 // with fatCode = true. 1004 if (!fatcode && code.fatcode) genMethod(tree, env, true); 1005 1006 // Clean up 1007 if(stackMap == StackMapFormat.JSR202) { 1008 code.lastFrame = null; 1009 code.frameBeforeLast = null; 1010 } 1011 1012 // Compress exception table 1013 code.compressCatchTable(); 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); 1055 code.setDefined(code.newLocal(l.head.sym)); 1056 } 1057 1058 // Get ready to generate code for method body. 1059 int startpcCrt = genCrt ? code.curCP() : 0; 1060 code.entryPoint(); 1061 1062 // Suppress initial stackmap 1063 code.pendingStackMap = false; 1064 1065 return startpcCrt; 1066 } 1067 1068 public void visitVarDef(JCVariableDecl tree) { 1069 VarSymbol v = tree.sym; 1070 if (tree.init != null) { 1071 checkStringConstant(tree.init.pos(), v.getConstValue()); 1072 if (v.getConstValue() == null || varDebugInfo) { 1073 Assert.check(code.isStatementStart()); 1074 code.newLocal(v); 1075 genExpr(tree.init, v.erasure(types)).load(); 1076 items.makeLocalItem(v).store(); 1077 Assert.check(code.isStatementStart()); 1078 } 1079 } else { 1080 code.newLocal(v); 1081 } 1082 checkDimension(tree.pos(), v.type); 1083 } 1084 1085 public void visitSkip(JCSkip tree) { 1086 } 1087 1088 public void visitBlock(JCBlock tree) { 1089 /* this method is heavily invoked, as expected, for deeply nested blocks, if blocks doesn't happen to have 1090 * patterns there will be an unnecessary tax on memory consumption every time this method is executed, for this 1091 * reason we have created helper methods and here at a higher level we just discriminate depending on the 1092 * presence, or not, of patterns in a given block 1093 */ 1094 if (tree.patternMatchingCatch != null) { 1095 visitBlockWithPatterns(tree); 1096 } else { 1097 internalVisitBlock(tree); 1098 } 1099 } 1100 1101 private void visitBlockWithPatterns(JCBlock tree) { 1102 PatternMatchingCatchConfiguration prevConfiguration = patternMatchingCatchConfiguration; 1103 try { 1104 patternMatchingCatchConfiguration = 1105 new PatternMatchingCatchConfiguration(tree.patternMatchingCatch.calls2Handle(), 1106 new ListBuffer<int[]>(), 1107 tree.patternMatchingCatch.handler(), 1108 code.state.dup()); 1109 internalVisitBlock(tree); 1110 } finally { 1111 generatePatternMatchingCatch(env); 1112 patternMatchingCatchConfiguration = prevConfiguration; 1113 } 1114 } 1115 1116 private void generatePatternMatchingCatch(Env<GenContext> env) { 1117 if (patternMatchingCatchConfiguration.handler != null && 1118 !patternMatchingCatchConfiguration.ranges.isEmpty()) { 1119 Chain skipCatch = code.branch(goto_); 1120 JCCatch handler = patternMatchingCatchConfiguration.handler(); 1121 code.entryPoint(patternMatchingCatchConfiguration.startState(), 1122 handler.param.sym.type); 1123 genPatternMatchingCatch(handler, 1124 env, 1125 patternMatchingCatchConfiguration.ranges.toList()); 1126 code.resolve(skipCatch); 1127 } 1128 } 1129 1130 private void internalVisitBlock(JCBlock tree) { 1131 int limit = code.nextreg; 1132 Env<GenContext> localEnv = env.dup(tree, new GenContext()); 1133 genStats(tree.stats, localEnv); 1134 // End the scope of all block-local variables in variable info. 1135 if (!env.tree.hasTag(METHODDEF)) { 1136 code.statBegin(tree.bracePos); 1137 code.endScopes(limit); 1138 code.pendingStatPos = Position.NOPOS; 1139 } 1140 } 1141 1142 public void visitDoLoop(JCDoWhileLoop tree) { 1143 genLoop(tree, tree.body, tree.cond, List.nil(), false); 1144 } 1145 1146 public void visitWhileLoop(JCWhileLoop tree) { 1147 genLoop(tree, tree.body, tree.cond, List.nil(), true); 1148 } 1149 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 { 1190 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET); 1191 code.resolve(loopEnv.info.cont); 1192 genStats(step, loopEnv); 1193 if (code.isAlive()) { 1194 CondItem c; 1195 if (cond != null) { 1196 code.statBegin(cond.pos); 1197 Assert.check(code.isStatementStart()); 1198 c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER); 1199 } else { 1200 c = items.makeCondItem(goto_); 1201 } 1202 code.resolve(c.jumpTrue(), startpc); 1203 Assert.check(code.isStatementStart()); 1204 code.resolve(c.falseJumps); 1205 } 1206 } 1207 code.resolve(loopEnv.info.exit); 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() + 1253 tree.pos + 1254 target.syntheticNameChar() + 1255 code.state.stacksize); 1256 VarSymbol var = new VarSymbol(Flags.SYNTHETIC, varName, type, 1257 this.env.enclMethod.sym); 1258 LocalItem item = items.new LocalItem(type, code.newLocal(var)); 1259 stackBeforeSwitchExpression = stackBeforeSwitchExpression.prepend(item); 1260 item.store(); 1261 } 1262 switchResult = makeTemp(tree.type); 1263 } 1264 int prevLetExprStart = code.setLetExprStackPos(code.state.stacksize); 1265 try { 1266 handleSwitch(tree, tree.selector, tree.cases, tree.patternSwitch); 1267 } finally { 1268 code.setLetExprStackPos(prevLetExprStart); 1269 } 1270 } finally { 1271 stackBeforeSwitchExpression = prevStackBeforeSwitchExpression; 1272 switchResult = prevSwitchResult; 1273 code.endScopes(limit); 1274 } 1275 } 1276 //where: 1277 private boolean hasTry(JCSwitchExpression tree) { 1278 class HasTryScanner extends TreeScanner { 1279 private boolean hasTry; 1280 1281 @Override 1282 public void visitTry(JCTry tree) { 1283 hasTry = true; 1284 } 1285 1286 @Override 1287 public void visitSynchronized(JCSynchronized tree) { 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. 1423 if (code.get4(tableBase) == -1) { 1424 code.put4(tableBase, code.entryPoint(stateSwitch) - startpc); 1425 } 1426 1427 if (opcode == tableswitch) { 1428 // Let any unfilled slots point to the default case. 1429 int defaultOffset = code.get4(tableBase); 1430 for (long i = lo; i <= hi; i++) { 1431 int t = (int)(tableBase + 4 * (i - lo + 3)); 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]; 1474 values[j] = temp2; 1475 i++; 1476 j--; 1477 } 1478 } while (i <= j); 1479 if (lo < j) qsort2(keys, values, lo, j); 1480 if (i < hi) qsort2(keys, values, i, hi); 1481 } 1482 1483 public void visitSynchronized(JCSynchronized tree) { 1484 int limit = code.nextreg; 1485 // Generate code to evaluate lock and save in temporary variable. 1486 final LocalItem lockVar = makeTemp(syms.objectType); 1487 Assert.check(code.isStatementStart()); 1488 genExpr(tree.lock, tree.lock.type).load().duplicate(); 1489 lockVar.store(); 1490 1491 // Generate code to enter monitor. 1492 code.emitop0(monitorenter); 1493 code.state.lock(lockVar.reg); 1494 1495 // Generate code for a try statement with given body, no catch clauses 1496 // in a new environment with the "exit-monitor" operation as finalizer. 1497 final Env<GenContext> syncEnv = env.dup(tree, new GenContext()); 1498 syncEnv.info.finalize = new GenFinalizer() { 1499 void gen() { 1500 genLast(); 1501 Assert.check(syncEnv.info.gaps.length() % 2 == 0); 1502 syncEnv.info.gaps.append(code.curCP()); 1503 } 1504 void genLast() { 1505 if (code.isAlive()) { 1506 lockVar.load(); 1507 code.emitop0(monitorexit); 1508 code.state.unlock(lockVar.reg); 1509 } 1510 } 1511 }; 1512 syncEnv.info.gaps = new ListBuffer<>(); 1513 genTry(tree.body, List.nil(), syncEnv); 1514 code.endScopes(limit); 1515 } 1516 1517 public void visitTry(final JCTry tree) { 1518 // Generate code for a try statement with given body and catch clauses, 1519 // in a new environment which calls the finally block if there is one. 1520 final Env<GenContext> tryEnv = env.dup(tree, new GenContext()); 1521 final Env<GenContext> oldEnv = env; 1522 tryEnv.info.finalize = new GenFinalizer() { 1523 void gen() { 1524 Assert.check(tryEnv.info.gaps.length() % 2 == 0); 1525 tryEnv.info.gaps.append(code.curCP()); 1526 genLast(); 1527 } 1528 void genLast() { 1529 if (tree.finalizer != null) 1530 genStat(tree.finalizer, oldEnv, CRT_BLOCK); 1531 } 1532 boolean hasFinalizer() { 1533 return tree.finalizer != null; 1534 } 1535 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. 1645 code.emitop1w(ret, retVar.reg); 1646 code.markDead(); 1647 } 1648 } 1649 // Resolve all breaks. 1650 code.resolve(exitChain); 1651 1652 code.endScopes(limit); 1653 } 1654 1655 /** Generate code for a catch clause. 1656 * @param tree The catch clause. 1657 * @param env The environment current in the enclosing try. 1658 * @param startpc Start pc of try-block. 1659 * @param endpc End pc of try-block. 1660 */ 1661 void genCatch(JCCatch tree, 1662 Env<GenContext> env, 1663 int startpc, int endpc, 1664 List<Integer> gaps) { 1665 if (startpc != endpc) { 1666 List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypeExprs 1667 = catchTypesWithAnnotations(tree); 1668 while (gaps.nonEmpty()) { 1669 for (Pair<List<Attribute.TypeCompound>, JCExpression> subCatch1 : catchTypeExprs) { 1670 JCExpression subCatch = subCatch1.snd; 1671 int catchType = makeRef(tree.pos(), subCatch.type); 1672 int end = gaps.head.intValue(); 1673 registerCatch(tree.pos(), 1674 startpc, end, code.curCP(), 1675 catchType); 1676 for (Attribute.TypeCompound tc : subCatch1.fst) { 1677 tc.position.setCatchInfo(catchType, startpc); 1678 } 1679 } 1680 gaps = gaps.tail; 1681 startpc = gaps.head.intValue(); 1682 gaps = gaps.tail; 1683 } 1684 if (startpc < endpc) { 1685 for (Pair<List<Attribute.TypeCompound>, JCExpression> subCatch1 : catchTypeExprs) { 1686 JCExpression subCatch = subCatch1.snd; 1687 int catchType = makeRef(tree.pos(), subCatch.type); 1688 registerCatch(tree.pos(), 1689 startpc, endpc, code.curCP(), 1690 catchType); 1691 for (Attribute.TypeCompound tc : subCatch1.fst) { 1692 tc.position.setCatchInfo(catchType, startpc); 1693 } 1694 } 1695 } 1696 genCatchBlock(tree, env); 1697 } 1698 } 1699 void genPatternMatchingCatch(JCCatch tree, 1700 Env<GenContext> env, 1701 List<int[]> ranges) { 1702 for (int[] range : ranges) { 1703 JCExpression subCatch = tree.param.vartype; 1704 int catchType = makeRef(tree.pos(), subCatch.type); 1705 registerCatch(tree.pos(), 1706 range[0], range[1], code.curCP(), 1707 catchType); 1708 } 1709 genCatchBlock(tree, env); 1710 } 1711 void genCatchBlock(JCCatch tree, Env<GenContext> env) { 1712 VarSymbol exparam = tree.param.sym; 1713 code.statBegin(tree.pos); 1714 code.markStatBegin(); 1715 int limit = code.nextreg; 1716 code.newLocal(exparam); 1717 items.makeLocalItem(exparam).store(); 1718 code.statBegin(TreeInfo.firstStatPos(tree.body)); 1719 genStat(tree.body, env, CRT_BLOCK); 1720 code.endScopes(limit); 1721 code.statBegin(TreeInfo.endPos(tree.body)); 1722 } 1723 // where 1724 List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypesWithAnnotations(JCCatch tree) { 1725 return TreeInfo.isMultiCatch(tree) ? 1726 catchTypesWithAnnotationsFromMulticatch((JCTypeUnion)tree.param.vartype, tree.param.sym.getRawTypeAttributes()) : 1727 List.of(new Pair<>(tree.param.sym.getRawTypeAttributes(), tree.param.vartype)); 1728 } 1729 // where 1730 List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypesWithAnnotationsFromMulticatch(JCTypeUnion tree, List<TypeCompound> first) { 1731 List<JCExpression> alts = tree.alternatives; 1732 List<Pair<List<TypeCompound>, JCExpression>> res = List.of(new Pair<>(first, alts.head)); 1733 alts = alts.tail; 1734 1735 while(alts != null && alts.head != null) { 1736 JCExpression alt = alts.head; 1737 if (alt instanceof JCAnnotatedType annotatedType) { 1738 res = res.prepend(new Pair<>(annotate.fromAnnotations(annotatedType.annotations), alt)); 1739 } else { 1740 res = res.prepend(new Pair<>(List.nil(), alt)); 1741 } 1742 alts = alts.tail; 1743 } 1744 return res.reverse(); 1745 } 1746 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. 1792 JCExpression e = tree.expr; 1793 switch (e.getTag()) { 1794 case POSTINC: 1795 ((JCUnary) e).setTag(PREINC); 1796 break; 1797 case POSTDEC: 1798 ((JCUnary) e).setTag(PREDEC); 1799 break; 1800 } 1801 Assert.check(code.isStatementStart()); 1802 genExpr(tree.expr, tree.expr.type).drop(); 1803 Assert.check(code.isStatementStart()); 1804 } 1805 1806 public void visitBreak(JCBreak tree) { 1807 Assert.check(code.isStatementStart()); 1808 final Env<GenContext> targetEnv = unwindBreak(tree.target); 1809 targetEnv.info.addExit(code.branch(goto_)); 1810 endFinalizerGaps(env, targetEnv); 1811 } 1812 1813 public void visitYield(JCYield tree) { 1814 Assert.check(code.isStatementStart()); 1815 final Env<GenContext> targetEnv; 1816 if (inCondSwitchExpression) { 1817 CondItem value = genCond(tree.value, CRT_FLOW_TARGET); 1818 Chain falseJumps = value.jumpFalse(); 1819 1820 code.resolve(value.trueJumps); 1821 Env<GenContext> localEnv = unwindBreak(tree.target); 1822 reloadStackBeforeSwitchExpr(); 1823 Chain trueJumps = code.branch(goto_); 1824 1825 endFinalizerGaps(env, localEnv); 1826 1827 code.resolve(falseJumps); 1828 targetEnv = unwindBreak(tree.target); 1829 reloadStackBeforeSwitchExpr(); 1830 falseJumps = code.branch(goto_); 1831 1832 if (switchExpressionTrueChain == null) { 1833 switchExpressionTrueChain = trueJumps; 1834 } else { 1835 switchExpressionTrueChain = 1836 Code.mergeChains(switchExpressionTrueChain, trueJumps); 1837 } 1838 if (switchExpressionFalseChain == null) { 1839 switchExpressionFalseChain = falseJumps; 1840 } else { 1841 switchExpressionFalseChain = 1842 Code.mergeChains(switchExpressionFalseChain, falseJumps); 1843 } 1844 } else { 1845 genExpr(tree.value, pt).load(); 1846 if (switchResult != null) 1847 switchResult.store(); 1848 1849 targetEnv = unwindBreak(tree.target); 1850 1851 if (code.isAlive()) { 1852 reloadStackBeforeSwitchExpr(); 1853 if (switchResult != null) 1854 switchResult.load(); 1855 1856 targetEnv.info.addExit(code.branch(goto_)); 1857 code.markDead(); 1858 } 1859 } 1860 endFinalizerGaps(env, targetEnv); 1861 } 1862 //where: 1863 /** As side-effect, might mark code as dead disabling any further emission. 1864 */ 1865 private Env<GenContext> unwindBreak(JCTree target) { 1866 int tmpPos = code.pendingStatPos; 1867 Env<GenContext> targetEnv = unwind(target, env); 1868 code.pendingStatPos = tmpPos; 1869 return targetEnv; 1870 } 1871 1872 private void reloadStackBeforeSwitchExpr() { 1873 for (LocalItem li : stackBeforeSwitchExpression) 1874 li.load(); 1875 } 1876 1877 public void visitContinue(JCContinue tree) { 1878 int tmpPos = code.pendingStatPos; 1879 Env<GenContext> targetEnv = unwind(tree.target, env); 1880 code.pendingStatPos = tmpPos; 1881 Assert.check(code.isStatementStart()); 1882 targetEnv.info.addCont(code.branch(goto_)); 1883 endFinalizerGaps(env, targetEnv); 1884 } 1885 1886 public void visitReturn(JCReturn tree) { 1887 int limit = code.nextreg; 1888 final Env<GenContext> targetEnv; 1889 1890 /* Save and then restore the location of the return in case a finally 1891 * is expanded (with unwind()) in the middle of our bytecodes. 1892 */ 1893 int tmpPos = code.pendingStatPos; 1894 if (tree.expr != null) { 1895 Assert.check(code.isStatementStart()); 1896 Item r = genExpr(tree.expr, pt).load(); 1897 if (hasFinally(env.enclMethod, env)) { 1898 r = makeTemp(pt); 1899 r.store(); 1900 } 1901 targetEnv = unwind(env.enclMethod, env); 1902 code.pendingStatPos = tmpPos; 1903 r.load(); 1904 code.emitop0(ireturn + Code.truncate(Code.typecode(pt))); 1905 } else { 1906 targetEnv = unwind(env.enclMethod, env); 1907 code.pendingStatPos = tmpPos; 1908 code.emitop0(return_); 1909 } 1910 endFinalizerGaps(env, targetEnv); 1911 code.endScopes(limit); 1912 } 1913 1914 public void visitThrow(JCThrow tree) { 1915 Assert.check(code.isStatementStart()); 1916 genExpr(tree.expr, tree.expr.type).load(); 1917 code.emitop0(athrow); 1918 Assert.check(code.isStatementStart()); 1919 } 1920 1921 /* ************************************************************************ 1922 * Visitor methods for expressions 1923 *************************************************************************/ 1924 1925 public void visitApply(JCMethodInvocation tree) { 1926 setTypeAnnotationPositions(tree.pos); 1927 // Generate code for method. 1928 Item m = genExpr(tree.meth, methodType); 1929 // Generate code for all arguments, where the expected types are 1930 // the parameters of the method's external type (that is, any implicit 1931 // outer instance of a super(...) call appears as first parameter). 1932 MethodSymbol msym = (MethodSymbol)TreeInfo.symbol(tree.meth); 1933 genArgs(tree.args, 1934 msym.externalType(types).getParameterTypes()); 1935 if (!msym.isDynamic()) { 1936 code.statBegin(tree.pos); 1937 } 1938 if (patternMatchingCatchConfiguration.invocations().contains(tree)) { 1939 int start = code.curCP(); 1940 result = m.invoke(); 1941 patternMatchingCatchConfiguration.ranges().add(new int[] {start, code.curCP()}); 1942 } else { 1943 if (msym.isConstructor() && TreeInfo.isConstructorCall(tree)) { 1944 //if this is a this(...) or super(...) call, there is a pending 1945 //"uninitialized this" before this call. One catch handler cannot 1946 //handle exceptions that may come from places with "uninitialized this" 1947 //and (initialized) this, hence generate one set of handlers here 1948 //for the "uninitialized this" case, and another set of handlers 1949 //will be generated at the end of the method for the initialized this, 1950 //if needed: 1951 generatePatternMatchingCatch(env); 1952 result = m.invoke(); 1953 patternMatchingCatchConfiguration = 1954 patternMatchingCatchConfiguration.restart(code.state.dup()); 1955 } else { 1956 result = m.invoke(); 1957 } 1958 } 1959 } 1960 1961 public void visitConditional(JCConditional tree) { 1962 Chain thenExit = null; 1963 code.statBegin(tree.cond.pos); 1964 CondItem c = genCond(tree.cond, CRT_FLOW_CONTROLLER); 1965 Chain elseChain = c.jumpFalse(); 1966 if (!c.isFalse()) { 1967 code.resolve(c.trueJumps); 1968 int startpc = genCrt ? code.curCP() : 0; 1969 code.statBegin(tree.truepart.pos); 1970 genExpr(tree.truepart, pt).load(); 1971 if (genCrt) code.crt.put(tree.truepart, CRT_FLOW_TARGET, 1972 startpc, code.curCP()); 1973 thenExit = code.branch(goto_); 1974 } 1975 if (elseChain != null) { 1976 code.resolve(elseChain); 1977 int startpc = genCrt ? code.curCP() : 0; 1978 code.statBegin(tree.falsepart.pos); 1979 genExpr(tree.falsepart, pt).load(); 1980 if (genCrt) code.crt.put(tree.falsepart, CRT_FLOW_TARGET, 1981 startpc, code.curCP()); 1982 } 1983 code.resolve(thenExit); 1984 result = items.makeStackItem(pt); 1985 } 1986 1987 private void setTypeAnnotationPositions(int treePos) { 1988 MethodSymbol meth = code.meth; 1989 boolean initOrClinit = code.meth.getKind() == javax.lang.model.element.ElementKind.CONSTRUCTOR 1990 || code.meth.getKind() == javax.lang.model.element.ElementKind.STATIC_INIT; 1991 1992 for (Attribute.TypeCompound ta : meth.getRawTypeAttributes()) { 1993 if (ta.hasUnknownPosition()) 1994 ta.tryFixPosition(); 1995 1996 if (ta.position.matchesPos(treePos)) 1997 ta.position.updatePosOffset(code.cp); 1998 } 1999 2000 if (!initOrClinit) 2001 return; 2002 2003 for (Attribute.TypeCompound ta : meth.owner.getRawTypeAttributes()) { 2004 if (ta.hasUnknownPosition()) 2005 ta.tryFixPosition(); 2006 2007 if (ta.position.matchesPos(treePos)) 2008 ta.position.updatePosOffset(code.cp); 2009 } 2010 2011 ClassSymbol clazz = meth.enclClass(); 2012 for (Symbol s : new com.sun.tools.javac.model.FilteredMemberList(clazz.members())) { 2013 if (!s.getKind().isField()) 2014 continue; 2015 2016 for (Attribute.TypeCompound ta : s.getRawTypeAttributes()) { 2017 if (ta.hasUnknownPosition()) 2018 ta.tryFixPosition(); 2019 2020 if (ta.position.matchesPos(treePos)) 2021 ta.position.updatePosOffset(code.cp); 2022 } 2023 } 2024 } 2025 2026 public void visitNewClass(JCNewClass tree) { 2027 // Enclosing instances or anonymous classes should have been eliminated 2028 // by now. 2029 Assert.check(tree.encl == null && tree.def == null); 2030 setTypeAnnotationPositions(tree.pos); 2031 2032 code.emitop2(new_, checkDimension(tree.pos(), tree.type), PoolWriter::putClass); 2033 code.emitop0(dup); 2034 2035 // Generate code for all arguments, where the expected types are 2036 // the parameters of the constructor's external type (that is, 2037 // any implicit outer instance appears as first parameter). 2038 genArgs(tree.args, tree.constructor.externalType(types).getParameterTypes()); 2039 2040 items.makeMemberItem(tree.constructor, true).invoke(); 2041 result = items.makeStackItem(tree.type); 2042 } 2043 2044 public void visitNewArray(JCNewArray tree) { 2045 setTypeAnnotationPositions(tree.pos); 2046 2047 if (tree.elems != null) { 2048 Type elemtype = types.elemtype(tree.type); 2049 loadIntConst(tree.elems.length()); 2050 Item arr = makeNewArray(tree.pos(), tree.type, 1); 2051 int i = 0; 2052 for (List<JCExpression> l = tree.elems; l.nonEmpty(); l = l.tail) { 2053 arr.duplicate(); 2054 loadIntConst(i); 2055 i++; 2056 genExpr(l.head, elemtype).load(); 2057 items.makeIndexedItem(elemtype).store(); 2058 } 2059 result = arr; 2060 } else { 2061 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) { 2062 genExpr(l.head, syms.intType).load(); 2063 } 2064 result = makeNewArray(tree.pos(), tree.type, tree.dims.length()); 2065 } 2066 } 2067 //where 2068 /** Generate code to create an array with given element type and number 2069 * of dimensions. 2070 */ 2071 Item makeNewArray(DiagnosticPosition pos, Type type, int ndims) { 2072 Type elemtype = types.elemtype(type); 2073 if (types.dimensions(type) > ClassFile.MAX_DIMENSIONS) { 2074 log.error(pos, Errors.LimitDimensions); 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 2115 // int variable we can use an incr instruction instead of 2116 // proceeding further. 2117 if ((tree.hasTag(PLUS_ASG) || tree.hasTag(MINUS_ASG)) && 2118 l instanceof LocalItem localItem && 2119 tree.lhs.type.getTag().isSubRangeOf(INT) && 2120 tree.rhs.type.getTag().isSubRangeOf(INT) && 2121 tree.rhs.type.constValue() != null) { 2122 int ival = ((Number) tree.rhs.type.constValue()).intValue(); 2123 if (tree.hasTag(MINUS_ASG)) ival = -ival; 2124 localItem.incr(ival); 2125 result = l; 2126 return; 2127 } 2128 // Otherwise, duplicate expression, load one copy 2129 // and complete binary operation. 2130 l.duplicate(); 2131 l.coerce(operator.type.getParameterTypes().head).load(); 2132 completeBinop(tree.lhs, tree.rhs, operator).coerce(tree.lhs.type); 2133 } 2134 result = items.makeAssignItem(l); 2135 } 2136 2137 public void visitUnary(JCUnary tree) { 2138 OperatorSymbol operator = tree.operator; 2139 if (tree.hasTag(NOT)) { 2140 CondItem od = genCond(tree.arg, false); 2141 result = od.negate(); 2142 } else { 2143 Item od = genExpr(tree.arg, operator.type.getParameterTypes().head); 2144 switch (tree.getTag()) { 2145 case POS: 2146 result = od.load(); 2147 break; 2148 case NEG: 2149 result = od.load(); 2150 code.emitop0(operator.opcode); 2151 break; 2152 case COMPL: 2153 result = od.load(); 2154 emitMinusOne(od.typecode); 2155 code.emitop0(operator.opcode); 2156 break; 2157 case PREINC: case PREDEC: 2158 od.duplicate(); 2159 if (od instanceof LocalItem localItem && 2160 (operator.opcode == iadd || operator.opcode == isub)) { 2161 localItem.incr(tree.hasTag(PREINC) ? 1 : -1); 2162 result = od; 2163 } else { 2164 od.load(); 2165 code.emitop0(one(od.typecode)); 2166 code.emitop0(operator.opcode); 2167 // Perform narrowing primitive conversion if byte, 2168 // char, or short. Fix for 4304655. 2169 if (od.typecode != INTcode && 2170 Code.truncate(od.typecode) == INTcode) 2171 code.emitop0(int2byte + od.typecode - BYTEcode); 2172 result = items.makeAssignItem(od); 2173 } 2174 break; 2175 case POSTINC: case POSTDEC: 2176 od.duplicate(); 2177 if (od instanceof LocalItem localItem && 2178 (operator.opcode == iadd || operator.opcode == isub)) { 2179 Item res = od.load(); 2180 localItem.incr(tree.hasTag(POSTINC) ? 1 : -1); 2181 result = res; 2182 } else { 2183 Item res = od.load(); 2184 od.stash(od.typecode); 2185 code.emitop0(one(od.typecode)); 2186 code.emitop0(operator.opcode); 2187 // Perform narrowing primitive conversion if byte, 2188 // char, or short. Fix for 4304655. 2189 if (od.typecode != INTcode && 2190 Code.truncate(od.typecode) == INTcode) 2191 code.emitop0(int2byte + od.typecode - BYTEcode); 2192 od.store(); 2193 result = res; 2194 } 2195 break; 2196 case NULLCHK: 2197 result = od.load(); 2198 code.emitop0(dup); 2199 genNullCheck(tree); 2200 break; 2201 default: 2202 Assert.error(); 2203 } 2204 } 2205 } 2206 2207 /** Generate a null check from the object value at stack top. */ 2208 private void genNullCheck(JCTree tree) { 2209 code.statBegin(tree.pos); 2210 callMethod(tree.pos(), syms.objectsType, names.requireNonNull, 2211 List.of(syms.objectType), true); 2212 code.emitop0(pop); 2213 } 2214 2215 public void visitBinary(JCBinary tree) { 2216 OperatorSymbol operator = tree.operator; 2217 if (operator.opcode == string_add) { 2218 result = concat.makeConcat(tree); 2219 } else if (tree.hasTag(AND)) { 2220 CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER); 2221 if (!lcond.isFalse()) { 2222 Chain falseJumps = lcond.jumpFalse(); 2223 code.resolve(lcond.trueJumps); 2224 CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET); 2225 result = items. 2226 makeCondItem(rcond.opcode, 2227 rcond.trueJumps, 2228 Code.mergeChains(falseJumps, 2229 rcond.falseJumps)); 2230 } else { 2231 result = lcond; 2232 } 2233 } else if (tree.hasTag(OR)) { 2234 CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER); 2235 if (!lcond.isTrue()) { 2236 Chain trueJumps = lcond.jumpTrue(); 2237 code.resolve(lcond.falseJumps); 2238 CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET); 2239 result = items. 2240 makeCondItem(rcond.opcode, 2241 Code.mergeChains(trueJumps, rcond.trueJumps), 2242 rcond.falseJumps); 2243 } else { 2244 result = lcond; 2245 } 2246 } else { 2247 Item od = genExpr(tree.lhs, operator.type.getParameterTypes().head); 2248 od.load(); 2249 result = completeBinop(tree.lhs, tree.rhs, operator); 2250 } 2251 } 2252 2253 2254 /** Complete generating code for operation, with left operand 2255 * already on stack. 2256 * @param lhs The tree representing the left operand. 2257 * @param rhs The tree representing the right operand. 2258 * @param operator The operator symbol. 2259 */ 2260 Item completeBinop(JCTree lhs, JCTree rhs, OperatorSymbol operator) { 2261 MethodType optype = (MethodType)operator.type; 2262 int opcode = operator.opcode; 2263 if (opcode >= if_icmpeq && opcode <= if_icmple && 2264 rhs.type.constValue() instanceof Number number && 2265 number.intValue() == 0) { 2266 opcode = opcode + (ifeq - if_icmpeq); 2267 } else if (opcode >= if_acmpeq && opcode <= if_acmpne && 2268 TreeInfo.isNull(rhs)) { 2269 opcode = opcode + (if_acmp_null - if_acmpeq); 2270 } else { 2271 // The expected type of the right operand is 2272 // the second parameter type of the operator, except for 2273 // shifts with long shiftcount, where we convert the opcode 2274 // to a short shift and the expected type to int. 2275 Type rtype = operator.erasure(types).getParameterTypes().tail.head; 2276 if (opcode >= ishll && opcode <= lushrl) { 2277 opcode = opcode + (ishl - ishll); 2278 rtype = syms.intType; 2279 } 2280 // Generate code for right operand and load. 2281 genExpr(rhs, rtype).load(); 2282 // If there are two consecutive opcode instructions, 2283 // emit the first now. 2284 if (opcode >= (1 << preShift)) { 2285 code.emitop0(opcode >> preShift); 2286 opcode = opcode & 0xFF; 2287 } 2288 } 2289 if (opcode >= ifeq && opcode <= if_acmpne || 2290 opcode == if_acmp_null || opcode == if_acmp_nonnull) { 2291 return items.makeCondItem(opcode); 2292 } else { 2293 code.emitop0(opcode); 2294 return items.makeStackItem(optype.restype); 2295 } 2296 } 2297 2298 public void visitTypeCast(JCTypeCast tree) { 2299 result = genExpr(tree.expr, tree.clazz.type).load(); 2300 setTypeAnnotationPositions(tree.pos); 2301 // Additional code is only needed if we cast to a reference type 2302 // which is not statically a supertype of the expression's type. 2303 // For basic types, the coerce(...) in genExpr(...) will do 2304 // the conversion. 2305 if (!tree.clazz.type.isPrimitive() && 2306 !types.isSameType(tree.expr.type, tree.clazz.type) && 2307 types.asSuper(tree.expr.type, tree.clazz.type.tsym) == null) { 2308 code.emitop2(checkcast, checkDimension(tree.pos(), tree.clazz.type), PoolWriter::putClass); 2309 } 2310 } 2311 2312 public void visitWildcard(JCWildcard tree) { 2313 throw new AssertionError(this.getClass().getName()); 2314 } 2315 2316 public void visitTypeTest(JCInstanceOf tree) { 2317 genExpr(tree.expr, tree.expr.type).load(); 2318 setTypeAnnotationPositions(tree.pos); 2319 code.emitop2(instanceof_, makeRef(tree.pos(), tree.pattern.type)); 2320 result = items.makeStackItem(syms.booleanType); 2321 } 2322 2323 public void visitIndexed(JCArrayAccess tree) { 2324 genExpr(tree.indexed, tree.indexed.type).load(); 2325 genExpr(tree.index, syms.intType).load(); 2326 result = items.makeIndexedItem(tree.type); 2327 } 2328 2329 public void visitIdent(JCIdent tree) { 2330 Symbol sym = tree.sym; 2331 if (tree.name == names._this || tree.name == names._super) { 2332 Item res = tree.name == names._this 2333 ? items.makeThisItem() 2334 : items.makeSuperItem(); 2335 if (sym.kind == MTH) { 2336 // Generate code to address the constructor. 2337 res.load(); 2338 res = items.makeMemberItem(sym, true); 2339 } 2340 result = res; 2341 } else if (isInvokeDynamic(sym) || isConstantDynamic(sym)) { 2342 if (isConstantDynamic(sym)) { 2343 setTypeAnnotationPositions(tree.pos); 2344 } 2345 result = items.makeDynamicItem(sym); 2346 } else if (sym.kind == VAR && (sym.owner.kind == MTH || sym.owner.kind == VAR)) { 2347 result = items.makeLocalItem((VarSymbol)sym); 2348 } else if ((sym.flags() & STATIC) != 0) { 2349 if (!isAccessSuper(env.enclMethod)) 2350 sym = binaryQualifier(sym, env.enclClass.type); 2351 result = items.makeStaticItem(sym); 2352 } else { 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)) 2394 base = base.load(); 2395 base.drop(); 2396 } else { 2397 base.load(); 2398 genNullCheck(tree.selected); 2399 } 2400 result = items. 2401 makeImmediateItem(sym.type, ((VarSymbol) sym).getConstValue()); 2402 } else { 2403 if (isInvokeDynamic(sym)) { 2404 result = items.makeDynamicItem(sym); 2405 return; 2406 } else { 2407 sym = binaryQualifier(sym, tree.selected.type); 2408 } 2409 if ((sym.flags() & STATIC) != 0) { 2410 if (!selectSuper && (ssym == null || ssym.kind != TYP)) 2411 base = base.load(); 2412 base.drop(); 2413 result = items.makeStaticItem(sym); 2414 } else { 2415 base.load(); 2416 if (sym == syms.lengthVar) { 2417 code.emitop0(arraylength); 2418 result = items.makeStackItem(syms.intType); 2419 } else { 2420 result = items. 2421 makeMemberItem(sym, 2422 nonVirtualForPrivateAccess(sym) || 2423 selectSuper || accessSuper); 2424 } 2425 } 2426 } 2427 } 2428 2429 public boolean isInvokeDynamic(Symbol sym) { 2430 return sym.kind == MTH && ((MethodSymbol)sym).isDynamic(); 2431 } 2432 2433 public void visitLiteral(JCLiteral tree) { 2434 if (tree.type.hasTag(BOT)) { 2435 code.emitop0(aconst_null); 2436 result = items.makeStackItem(tree.type); 2437 } 2438 else 2439 result = items.makeImmediateItem(tree.type, tree.value); 2440 } 2441 2442 public void visitLetExpr(LetExpr tree) { 2443 code.resolvePending(); 2444 2445 int limit = code.nextreg; 2446 int prevLetExprStart = code.setLetExprStackPos(code.state.stacksize); 2447 try { 2448 genStats(tree.defs, env); 2449 } finally { 2450 code.setLetExprStackPos(prevLetExprStart); 2451 } 2452 result = genExpr(tree.expr, tree.expr.type).load(); 2453 code.endScopes(limit); 2454 } 2455 2456 private void generateReferencesToPrunedTree(ClassSymbol classSymbol) { 2457 List<JCTree> prunedInfo = lower.prunedTree.get(classSymbol); 2458 if (prunedInfo != null) { 2459 for (JCTree prunedTree: prunedInfo) { 2460 prunedTree.accept(classReferenceVisitor); 2461 } 2462 } 2463 } 2464 2465 /* ************************************************************************ 2466 * main method 2467 *************************************************************************/ 2468 2469 /** Generate code for a class definition. 2470 * @param env The attribution environment that belongs to the 2471 * outermost class containing this class definition. 2472 * We need this for resolving some additional symbols. 2473 * @param cdef The tree representing the class definition. 2474 * @return True if code is generated with no errors. 2475 */ 2476 public boolean genClass(Env<AttrContext> env, JCClassDecl cdef) { 2477 try { 2478 attrEnv = env; 2479 ClassSymbol c = cdef.sym; 2480 this.toplevel = env.toplevel; 2481 this.endPosTable = toplevel.endPositions; 2482 /* method normalizeDefs() can add references to external classes into the constant pool 2483 */ 2484 cdef.defs = normalizeDefs(cdef.defs, c); 2485 generateReferencesToPrunedTree(c); 2486 Env<GenContext> localEnv = new Env<>(cdef, new GenContext()); 2487 localEnv.toplevel = env.toplevel; 2488 localEnv.enclClass = cdef; 2489 2490 for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) { 2491 genDef(l.head, localEnv); 2492 } 2493 if (poolWriter.size() > PoolWriter.MAX_ENTRIES) { 2494 log.error(cdef.pos(), Errors.LimitPool); 2495 nerrs++; 2496 } 2497 if (nerrs != 0) { 2498 // if errors, discard code 2499 for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) { 2500 if (l.head.hasTag(METHODDEF)) 2501 ((JCMethodDecl) l.head).sym.code = null; 2502 } 2503 } 2504 cdef.defs = List.nil(); // discard trees 2505 return nerrs == 0; 2506 } finally { 2507 // note: this method does NOT support recursion. 2508 attrEnv = null; 2509 this.env = null; 2510 toplevel = null; 2511 endPosTable = null; 2512 nerrs = 0; 2513 qualifiedSymbolCache.clear(); 2514 } 2515 } 2516 2517 /* ************************************************************************ 2518 * Auxiliary classes 2519 *************************************************************************/ 2520 2521 /** An abstract class for finalizer generation. 2522 */ 2523 abstract class GenFinalizer { 2524 /** Generate code to clean up when unwinding. */ 2525 abstract void gen(); 2526 2527 /** Generate code to clean up at last. */ 2528 abstract void genLast(); 2529 2530 /** Does this finalizer have some nontrivial cleanup to perform? */ 2531 boolean hasFinalizer() { return true; } 2532 2533 /** Should be invoked after the try's body has been visited. */ 2534 void afterBody() {} 2535 } 2536 2537 /** code generation contexts, 2538 * to be used as type parameter for environments. 2539 */ 2540 final class GenContext { 2541 2542 /** 2543 * The top defined local variables for exit or continue branches to merge into. 2544 * It may contain uninitialized variables to be initialized by branched code, 2545 * so we cannot use Code.State.defined bits. 2546 */ 2547 final int limit; 2548 2549 /** A chain for all unresolved jumps that exit the current environment. 2550 */ 2551 Chain exit = null; 2552 2553 /** A chain for all unresolved jumps that continue in the 2554 * current environment. 2555 */ 2556 Chain cont = null; 2557 2558 /** A closure that generates the finalizer of the current environment. 2559 * Only set for Synchronized and Try contexts. 2560 */ 2561 GenFinalizer finalize = null; 2562 2563 /** Is this a switch statement? If so, allocate registers 2564 * even when the variable declaration is unreachable. 2565 */ 2566 boolean isSwitch = false; 2567 2568 /** A list buffer containing all gaps in the finalizer range, 2569 * where a catch all exception should not apply. 2570 */ 2571 ListBuffer<Integer> gaps = null; 2572 2573 GenContext() { 2574 var code = Gen.this.code; 2575 this.limit = code == null ? 0 : code.nextreg; 2576 } 2577 2578 /** Add given chain to exit chain. 2579 */ 2580 void addExit(Chain c) { 2581 if (c != null) { 2582 c.state.defined.excludeFrom(limit); 2583 } 2584 exit = Code.mergeChains(c, exit); 2585 } 2586 2587 /** Add given chain to cont chain. 2588 */ 2589 void addCont(Chain c) { 2590 if (c != null) { 2591 c.state.defined.excludeFrom(limit); 2592 } 2593 cont = Code.mergeChains(c, cont); 2594 } 2595 } 2596 2597 record PatternMatchingCatchConfiguration(Set<JCMethodInvocation> invocations, 2598 ListBuffer<int[]> ranges, 2599 JCCatch handler, 2600 State startState) { 2601 public PatternMatchingCatchConfiguration restart(State newState) { 2602 return new PatternMatchingCatchConfiguration(invocations(), 2603 new ListBuffer<int[]>(), 2604 handler(), 2605 newState); 2606 } 2607 } 2608 }