1 /* 2 * Copyright (c) 1999, 2021, 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 // only used for value classes 428 ListBuffer<JCStatement> initBlocks = new ListBuffer<>(); 429 ListBuffer<Attribute.TypeCompound> initTAs = new ListBuffer<>(); 430 ListBuffer<JCStatement> clinitCode = new ListBuffer<>(); 431 ListBuffer<Attribute.TypeCompound> clinitTAs = new ListBuffer<>(); 432 ListBuffer<JCTree> methodDefs = new ListBuffer<>(); 433 // Sort definitions into three listbuffers: 434 // - initCode for instance initializers 435 // - clinitCode for class initializers 436 // - methodDefs for method definitions 437 for (List<JCTree> l = defs; l.nonEmpty(); l = l.tail) { 438 JCTree def = l.head; 439 switch (def.getTag()) { 440 case BLOCK: 441 JCBlock block = (JCBlock)def; 442 if ((block.flags & STATIC) != 0) 443 clinitCode.append(block); 444 else if ((block.flags & SYNTHETIC) == 0) { 445 if (c.isValueClass()) { 446 initBlocks.append(block); 447 } else { 448 initCode.append(block); 449 } 450 } 451 break; 452 case METHODDEF: 453 methodDefs.append(def); 454 break; 455 case VARDEF: 456 JCVariableDecl vdef = (JCVariableDecl) def; 457 VarSymbol sym = vdef.sym; 458 checkDimension(vdef.pos(), sym.type); 459 if (vdef.init != null) { 460 if ((sym.flags() & STATIC) == 0) { 461 // Always initialize instance variables. 462 JCStatement init = make.at(vdef.pos()). 463 Assignment(sym, vdef.init); 464 initCode.append(init); 465 endPosTable.replaceTree(vdef, init); 466 initTAs.addAll(getAndRemoveNonFieldTAs(sym)); 467 } else if (sym.getConstValue() == null) { 468 // Initialize class (static) variables only if 469 // they are not compile-time constants. 470 JCStatement init = make.at(vdef.pos). 471 Assignment(sym, vdef.init); 472 clinitCode.append(init); 473 endPosTable.replaceTree(vdef, init); 474 clinitTAs.addAll(getAndRemoveNonFieldTAs(sym)); 475 } else { 476 checkStringConstant(vdef.init.pos(), sym.getConstValue()); 477 /* if the init contains a reference to an external class, add it to the 478 * constant's pool 479 */ 480 vdef.init.accept(classReferenceVisitor); 481 } 482 } 483 break; 484 default: 485 Assert.error(); 486 } 487 } 488 // Insert any instance initializers into all constructors. 489 if (initCode.length() != 0 || initBlocks.length() != 0) { 490 initTAs.addAll(c.getInitTypeAttributes()); 491 List<Attribute.TypeCompound> initTAlist = initTAs.toList(); 492 for (JCTree t : methodDefs) { 493 normalizeMethod((JCMethodDecl)t, initCode.toList(), initBlocks.toList(), initTAlist); 494 } 495 } 496 // If there are class initializers, create a <clinit> method 497 // that contains them as its body. 498 if (clinitCode.length() != 0) { 499 MethodSymbol clinit = new MethodSymbol( 500 STATIC | (c.flags() & STRICTFP), 501 names.clinit, 502 new MethodType( 503 List.nil(), syms.voidType, 504 List.nil(), syms.methodClass), 505 c); 506 c.members().enter(clinit); 507 List<JCStatement> clinitStats = clinitCode.toList(); 508 JCBlock block = make.at(clinitStats.head.pos()).Block(0, clinitStats); 509 block.endpos = TreeInfo.endPos(clinitStats.last()); 510 methodDefs.append(make.MethodDef(clinit, block)); 511 512 if (!clinitTAs.isEmpty()) 513 clinit.appendUniqueTypeAttributes(clinitTAs.toList()); 514 if (!c.getClassInitTypeAttributes().isEmpty()) 515 clinit.appendUniqueTypeAttributes(c.getClassInitTypeAttributes()); 516 } 517 // Return all method definitions. 518 return methodDefs.toList(); 519 } 520 521 private List<Attribute.TypeCompound> getAndRemoveNonFieldTAs(VarSymbol sym) { 522 List<TypeCompound> tas = sym.getRawTypeAttributes(); 523 ListBuffer<Attribute.TypeCompound> fieldTAs = new ListBuffer<>(); 524 ListBuffer<Attribute.TypeCompound> nonfieldTAs = new ListBuffer<>(); 525 for (TypeCompound ta : tas) { 526 Assert.check(ta.getPosition().type != TargetType.UNKNOWN); 527 if (ta.getPosition().type == TargetType.FIELD) { 528 fieldTAs.add(ta); 529 } else { 530 nonfieldTAs.add(ta); 531 } 532 } 533 sym.setTypeAttributes(fieldTAs.toList()); 534 return nonfieldTAs.toList(); 535 } 536 537 /** Check a constant value and report if it is a string that is 538 * too large. 539 */ 540 private void checkStringConstant(DiagnosticPosition pos, Object constValue) { 541 if (nerrs != 0 || // only complain about a long string once 542 constValue == null || 543 !(constValue instanceof String str) || 544 str.length() < PoolWriter.MAX_STRING_LENGTH) 545 return; 546 log.error(pos, Errors.LimitString); 547 nerrs++; 548 } 549 550 /** Insert instance initializer code into constructors prior to the super() call. 551 * @param md The tree potentially representing a 552 * constructor's definition. 553 * @param initCode The list of instance initializer statements. 554 * @param initTAs Type annotations from the initializer expression. 555 */ 556 void normalizeMethod(JCMethodDecl md, List<JCStatement> initCode, List<JCStatement> initBlocks, List<TypeCompound> initTAs) { 557 if (TreeInfo.isConstructor(md) && TreeInfo.hasConstructorCall(md, names._super)) { 558 // We are seeing a constructor that has a super() call. 559 // Find the super() invocation and append the given initializer code. 560 if (md.sym.owner.isValueClass()) { 561 rewriteInitializersIfNeeded(md, initCode); 562 TreeInfo.mapSuperCalls(md.body, supercall -> make.Block(0, initCode.append(supercall).appendList(initBlocks))); 563 } else { 564 TreeInfo.mapSuperCalls(md.body, supercall -> make.Block(0, initCode.prepend(supercall))); 565 } 566 567 if (md.body.endpos == Position.NOPOS) 568 md.body.endpos = TreeInfo.endPos(md.body.stats.last()); 569 570 md.sym.appendUniqueTypeAttributes(initTAs); 571 } 572 } 573 574 void rewriteInitializersIfNeeded(JCMethodDecl md, List<JCStatement> initCode) { 575 if (lower.initializerOuterThis.containsKey(md.sym.owner)) { 576 InitializerVisitor initializerVisitor = new InitializerVisitor(md, lower.initializerOuterThis.get(md.sym.owner)); 577 for (JCStatement init : initCode) { 578 initializerVisitor.scan(init); 579 } 580 } 581 } 582 583 class InitializerVisitor extends TreeScanner { 584 JCMethodDecl md; 585 Set<JCExpression> exprSet; 586 587 InitializerVisitor(JCMethodDecl md, Set<JCExpression> exprSet) { 588 this.md = md; 589 this.exprSet = exprSet; 590 } 591 592 @Override 593 public void visitTree(JCTree tree) {} 594 595 @Override 596 public void visitIdent(JCIdent tree) { 597 if (exprSet.contains(tree)) { 598 for (JCVariableDecl param: md.params) { 599 if (param.name == tree.name && 600 ((param.sym.flags_field & (MANDATED | NOOUTERTHIS)) == (MANDATED | NOOUTERTHIS))) { 601 tree.sym = param.sym; 602 } 603 } 604 } 605 } 606 } 607 608 /* ************************************************************************ 609 * Traversal methods 610 *************************************************************************/ 611 612 /** Visitor argument: The current environment. 613 */ 614 Env<GenContext> env; 615 616 /** Visitor argument: The expected type (prototype). 617 */ 618 Type pt; 619 620 /** Visitor result: The item representing the computed value. 621 */ 622 Item result; 623 624 /** Visitor method: generate code for a definition, catching and reporting 625 * any completion failures. 626 * @param tree The definition to be visited. 627 * @param env The environment current at the definition. 628 */ 629 public void genDef(JCTree tree, Env<GenContext> env) { 630 Env<GenContext> prevEnv = this.env; 631 try { 632 this.env = env; 633 tree.accept(this); 634 } catch (CompletionFailure ex) { 635 chk.completionError(tree.pos(), ex); 636 } finally { 637 this.env = prevEnv; 638 } 639 } 640 641 /** Derived visitor method: check whether CharacterRangeTable 642 * should be emitted, if so, put a new entry into CRTable 643 * and call method to generate bytecode. 644 * If not, just call method to generate bytecode. 645 * @see #genStat(JCTree, Env) 646 * 647 * @param tree The tree to be visited. 648 * @param env The environment to use. 649 * @param crtFlags The CharacterRangeTable flags 650 * indicating type of the entry. 651 */ 652 public void genStat(JCTree tree, Env<GenContext> env, int crtFlags) { 653 if (!genCrt) { 654 genStat(tree, env); 655 return; 656 } 657 int startpc = code.curCP(); 658 genStat(tree, env); 659 if (tree.hasTag(Tag.BLOCK)) crtFlags |= CRT_BLOCK; 660 code.crt.put(tree, crtFlags, startpc, code.curCP()); 661 } 662 663 /** Derived visitor method: generate code for a statement. 664 */ 665 public void genStat(JCTree tree, Env<GenContext> env) { 666 if (code.isAlive()) { 667 code.statBegin(tree.pos); 668 genDef(tree, env); 669 } else if (env.info.isSwitch && tree.hasTag(VARDEF)) { 670 // variables whose declarations are in a switch 671 // can be used even if the decl is unreachable. 672 code.newLocal(((JCVariableDecl) tree).sym); 673 } 674 } 675 676 /** Derived visitor method: check whether CharacterRangeTable 677 * should be emitted, if so, put a new entry into CRTable 678 * and call method to generate bytecode. 679 * If not, just call method to generate bytecode. 680 * @see #genStats(List, Env) 681 * 682 * @param trees The list of trees to be visited. 683 * @param env The environment to use. 684 * @param crtFlags The CharacterRangeTable flags 685 * indicating type of the entry. 686 */ 687 public void genStats(List<JCStatement> trees, Env<GenContext> env, int crtFlags) { 688 if (!genCrt) { 689 genStats(trees, env); 690 return; 691 } 692 if (trees.length() == 1) { // mark one statement with the flags 693 genStat(trees.head, env, crtFlags | CRT_STATEMENT); 694 } else { 695 int startpc = code.curCP(); 696 genStats(trees, env); 697 code.crt.put(trees, crtFlags, startpc, code.curCP()); 698 } 699 } 700 701 /** Derived visitor method: generate code for a list of statements. 702 */ 703 public void genStats(List<? extends JCTree> trees, Env<GenContext> env) { 704 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail) 705 genStat(l.head, env, CRT_STATEMENT); 706 } 707 708 /** Derived visitor method: check whether CharacterRangeTable 709 * should be emitted, if so, put a new entry into CRTable 710 * and call method to generate bytecode. 711 * If not, just call method to generate bytecode. 712 * @see #genCond(JCTree,boolean) 713 * 714 * @param tree The tree to be visited. 715 * @param crtFlags The CharacterRangeTable flags 716 * indicating type of the entry. 717 */ 718 public CondItem genCond(JCTree tree, int crtFlags) { 719 if (!genCrt) return genCond(tree, false); 720 int startpc = code.curCP(); 721 CondItem item = genCond(tree, (crtFlags & CRT_FLOW_CONTROLLER) != 0); 722 code.crt.put(tree, crtFlags, startpc, code.curCP()); 723 return item; 724 } 725 726 /** Derived visitor method: generate code for a boolean 727 * expression in a control-flow context. 728 * @param _tree The expression to be visited. 729 * @param markBranches The flag to indicate that the condition is 730 * a flow controller so produced conditions 731 * should contain a proper tree to generate 732 * CharacterRangeTable branches for them. 733 */ 734 public CondItem genCond(JCTree _tree, boolean markBranches) { 735 JCTree inner_tree = TreeInfo.skipParens(_tree); 736 if (inner_tree.hasTag(CONDEXPR)) { 737 JCConditional tree = (JCConditional)inner_tree; 738 CondItem cond = genCond(tree.cond, CRT_FLOW_CONTROLLER); 739 if (cond.isTrue()) { 740 code.resolve(cond.trueJumps); 741 CondItem result = genCond(tree.truepart, CRT_FLOW_TARGET); 742 if (markBranches) result.tree = tree.truepart; 743 return result; 744 } 745 if (cond.isFalse()) { 746 code.resolve(cond.falseJumps); 747 CondItem result = genCond(tree.falsepart, CRT_FLOW_TARGET); 748 if (markBranches) result.tree = tree.falsepart; 749 return result; 750 } 751 Chain secondJumps = cond.jumpFalse(); 752 code.resolve(cond.trueJumps); 753 CondItem first = genCond(tree.truepart, CRT_FLOW_TARGET); 754 if (markBranches) first.tree = tree.truepart; 755 Chain falseJumps = first.jumpFalse(); 756 code.resolve(first.trueJumps); 757 Chain trueJumps = code.branch(goto_); 758 code.resolve(secondJumps); 759 CondItem second = genCond(tree.falsepart, CRT_FLOW_TARGET); 760 CondItem result = items.makeCondItem(second.opcode, 761 Code.mergeChains(trueJumps, second.trueJumps), 762 Code.mergeChains(falseJumps, second.falseJumps)); 763 if (markBranches) result.tree = tree.falsepart; 764 return result; 765 } else if (inner_tree.hasTag(SWITCH_EXPRESSION)) { 766 code.resolvePending(); 767 768 boolean prevInCondSwitchExpression = inCondSwitchExpression; 769 Chain prevSwitchExpressionTrueChain = switchExpressionTrueChain; 770 Chain prevSwitchExpressionFalseChain = switchExpressionFalseChain; 771 try { 772 inCondSwitchExpression = true; 773 switchExpressionTrueChain = null; 774 switchExpressionFalseChain = null; 775 try { 776 doHandleSwitchExpression((JCSwitchExpression) inner_tree); 777 } catch (CompletionFailure ex) { 778 chk.completionError(_tree.pos(), ex); 779 code.state.stacksize = 1; 780 } 781 CondItem result = items.makeCondItem(goto_, 782 switchExpressionTrueChain, 783 switchExpressionFalseChain); 784 if (markBranches) result.tree = _tree; 785 return result; 786 } finally { 787 inCondSwitchExpression = prevInCondSwitchExpression; 788 switchExpressionTrueChain = prevSwitchExpressionTrueChain; 789 switchExpressionFalseChain = prevSwitchExpressionFalseChain; 790 } 791 } else if (inner_tree.hasTag(LETEXPR) && ((LetExpr) inner_tree).needsCond) { 792 code.resolvePending(); 793 794 LetExpr tree = (LetExpr) inner_tree; 795 int limit = code.nextreg; 796 int prevLetExprStart = code.setLetExprStackPos(code.state.stacksize); 797 try { 798 genStats(tree.defs, env); 799 } finally { 800 code.setLetExprStackPos(prevLetExprStart); 801 } 802 CondItem result = genCond(tree.expr, markBranches); 803 code.endScopes(limit); 804 return result; 805 } else { 806 CondItem result = genExpr(_tree, syms.booleanType).mkCond(); 807 if (markBranches) result.tree = _tree; 808 return result; 809 } 810 } 811 812 public Code getCode() { 813 return code; 814 } 815 816 public Items getItems() { 817 return items; 818 } 819 820 public Env<AttrContext> getAttrEnv() { 821 return attrEnv; 822 } 823 824 /** Visitor class for expressions which might be constant expressions. 825 * This class is a subset of TreeScanner. Intended to visit trees pruned by 826 * Lower as long as constant expressions looking for references to any 827 * ClassSymbol. Any such reference will be added to the constant pool so 828 * automated tools can detect class dependencies better. 829 */ 830 class ClassReferenceVisitor extends JCTree.Visitor { 831 832 @Override 833 public void visitTree(JCTree tree) {} 834 835 @Override 836 public void visitBinary(JCBinary tree) { 837 tree.lhs.accept(this); 838 tree.rhs.accept(this); 839 } 840 841 @Override 842 public void visitSelect(JCFieldAccess tree) { 843 if (tree.selected.type.hasTag(CLASS)) { 844 makeRef(tree.selected.pos(), tree.selected.type); 845 } 846 } 847 848 @Override 849 public void visitIdent(JCIdent tree) { 850 if (tree.sym.owner instanceof ClassSymbol classSymbol) { 851 poolWriter.putClass(classSymbol); 852 } 853 } 854 855 @Override 856 public void visitConditional(JCConditional tree) { 857 tree.cond.accept(this); 858 tree.truepart.accept(this); 859 tree.falsepart.accept(this); 860 } 861 862 @Override 863 public void visitUnary(JCUnary tree) { 864 tree.arg.accept(this); 865 } 866 867 @Override 868 public void visitParens(JCParens tree) { 869 tree.expr.accept(this); 870 } 871 872 @Override 873 public void visitTypeCast(JCTypeCast tree) { 874 tree.expr.accept(this); 875 } 876 } 877 878 private ClassReferenceVisitor classReferenceVisitor = new ClassReferenceVisitor(); 879 880 /** Visitor method: generate code for an expression, catching and reporting 881 * any completion failures. 882 * @param tree The expression to be visited. 883 * @param pt The expression's expected type (proto-type). 884 */ 885 public Item genExpr(JCTree tree, Type pt) { 886 if (!code.isAlive()) { 887 return items.makeStackItem(pt); 888 } 889 890 Type prevPt = this.pt; 891 try { 892 if (tree.type.constValue() != null) { 893 // Short circuit any expressions which are constants 894 tree.accept(classReferenceVisitor); 895 checkStringConstant(tree.pos(), tree.type.constValue()); 896 Symbol sym = TreeInfo.symbol(tree); 897 if (sym != null && isConstantDynamic(sym)) { 898 result = items.makeDynamicItem(sym); 899 } else { 900 result = items.makeImmediateItem(tree.type, tree.type.constValue()); 901 } 902 } else { 903 this.pt = pt; 904 tree.accept(this); 905 } 906 return result.coerce(pt); 907 } catch (CompletionFailure ex) { 908 chk.completionError(tree.pos(), ex); 909 code.state.stacksize = 1; 910 return items.makeStackItem(pt); 911 } finally { 912 this.pt = prevPt; 913 } 914 } 915 916 public boolean isConstantDynamic(Symbol sym) { 917 return sym.kind == VAR && 918 sym instanceof DynamicVarSymbol dynamicVarSymbol && 919 dynamicVarSymbol.isDynamic(); 920 } 921 922 /** Derived visitor method: generate code for a list of method arguments. 923 * @param trees The argument expressions to be visited. 924 * @param pts The expression's expected types (i.e. the formal parameter 925 * types of the invoked method). 926 */ 927 public void genArgs(List<JCExpression> trees, List<Type> pts) { 928 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) { 929 genExpr(l.head, pts.head).load(); 930 pts = pts.tail; 931 } 932 // require lists be of same length 933 Assert.check(pts.isEmpty()); 934 } 935 936 /* ************************************************************************ 937 * Visitor methods for statements and definitions 938 *************************************************************************/ 939 940 /** Thrown when the byte code size exceeds limit. 941 */ 942 public static class CodeSizeOverflow extends RuntimeException { 943 private static final long serialVersionUID = 0; 944 public CodeSizeOverflow() {} 945 } 946 947 public void visitMethodDef(JCMethodDecl tree) { 948 // Create a new local environment that points pack at method 949 // definition. 950 Env<GenContext> localEnv = env.dup(tree); 951 localEnv.enclMethod = tree; 952 // The expected type of every return statement in this method 953 // is the method's return type. 954 this.pt = tree.sym.erasure(types).getReturnType(); 955 956 checkDimension(tree.pos(), tree.sym.erasure(types)); 957 genMethod(tree, localEnv, false); 958 } 959 //where 960 /** Generate code for a method. 961 * @param tree The tree representing the method definition. 962 * @param env The environment current for the method body. 963 * @param fatcode A flag that indicates whether all jumps are 964 * within 32K. We first invoke this method under 965 * the assumption that fatcode == false, i.e. all 966 * jumps are within 32K. If this fails, fatcode 967 * is set to true and we try again. 968 */ 969 void genMethod(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) { 970 MethodSymbol meth = tree.sym; 971 int extras = 0; 972 // Count up extra parameters 973 if (meth.isConstructor()) { 974 extras++; 975 if (meth.enclClass().isInner() && 976 !meth.enclClass().isStatic()) { 977 extras++; 978 } 979 } else if ((tree.mods.flags & STATIC) == 0) { 980 extras++; 981 } 982 // System.err.println("Generating " + meth + " in " + meth.owner); //DEBUG 983 if (Code.width(types.erasure(env.enclMethod.sym.type).getParameterTypes()) + extras > 984 ClassFile.MAX_PARAMETERS) { 985 log.error(tree.pos(), Errors.LimitParameters); 986 nerrs++; 987 } 988 989 else if (tree.body != null) { 990 // Create a new code structure and initialize it. 991 int startpcCrt = initCode(tree, env, fatcode); 992 993 try { 994 genStat(tree.body, env); 995 } catch (CodeSizeOverflow e) { 996 // Failed due to code limit, try again with jsr/ret 997 startpcCrt = initCode(tree, env, fatcode); 998 genStat(tree.body, env); 999 } 1000 1001 if (code.state.stacksize != 0) { 1002 log.error(tree.body.pos(), Errors.StackSimError(tree.sym)); 1003 throw new AssertionError(); 1004 } 1005 1006 // If last statement could complete normally, insert a 1007 // return at the end. 1008 if (code.isAlive()) { 1009 code.statBegin(TreeInfo.endPos(tree.body)); 1010 if (env.enclMethod == null || 1011 env.enclMethod.sym.type.getReturnType().hasTag(VOID)) { 1012 code.emitop0(return_); 1013 } else { 1014 // sometime dead code seems alive (4415991); 1015 // generate a small loop instead 1016 int startpc = code.entryPoint(); 1017 CondItem c = items.makeCondItem(goto_); 1018 code.resolve(c.jumpTrue(), startpc); 1019 } 1020 } 1021 if (genCrt) 1022 code.crt.put(tree.body, 1023 CRT_BLOCK, 1024 startpcCrt, 1025 code.curCP()); 1026 1027 code.endScopes(0); 1028 1029 // If we exceeded limits, panic 1030 if (code.checkLimits(tree.pos(), log)) { 1031 nerrs++; 1032 return; 1033 } 1034 1035 // If we generated short code but got a long jump, do it again 1036 // with fatCode = true. 1037 if (!fatcode && code.fatcode) genMethod(tree, env, true); 1038 1039 // Clean up 1040 if(stackMap == StackMapFormat.JSR202) { 1041 code.lastFrame = null; 1042 code.frameBeforeLast = null; 1043 } 1044 1045 // Compress exception table 1046 code.compressCatchTable(); 1047 1048 // Fill in type annotation positions for exception parameters 1049 code.fillExceptionParameterPositions(); 1050 } 1051 } 1052 1053 private int initCode(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) { 1054 MethodSymbol meth = tree.sym; 1055 1056 // Create a new code structure. 1057 meth.code = code = new Code(meth, 1058 fatcode, 1059 lineDebugInfo ? toplevel.lineMap : null, 1060 varDebugInfo, 1061 stackMap, 1062 debugCode, 1063 genCrt ? new CRTable(tree, env.toplevel.endPositions) 1064 : null, 1065 syms, 1066 types, 1067 poolWriter); 1068 items = new Items(poolWriter, code, syms, types); 1069 if (code.debugCode) { 1070 System.err.println(meth + " for body " + tree); 1071 } 1072 1073 // If method is not static, create a new local variable address 1074 // for `this'. 1075 if ((tree.mods.flags & STATIC) == 0) { 1076 Type selfType = meth.owner.type; 1077 if (meth.isConstructor() && selfType != syms.objectType) 1078 selfType = UninitializedType.uninitializedThis(selfType); 1079 code.setDefined( 1080 code.newLocal( 1081 new VarSymbol(FINAL, names._this, selfType, meth.owner))); 1082 } 1083 1084 // Mark all parameters as defined from the beginning of 1085 // the method. 1086 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) { 1087 checkDimension(l.head.pos(), l.head.sym.type); 1088 code.setDefined(code.newLocal(l.head.sym)); 1089 } 1090 1091 // Get ready to generate code for method body. 1092 int startpcCrt = genCrt ? code.curCP() : 0; 1093 code.entryPoint(); 1094 1095 // Suppress initial stackmap 1096 code.pendingStackMap = false; 1097 1098 return startpcCrt; 1099 } 1100 1101 public void visitVarDef(JCVariableDecl tree) { 1102 VarSymbol v = tree.sym; 1103 if (tree.init != null) { 1104 checkStringConstant(tree.init.pos(), v.getConstValue()); 1105 if (v.getConstValue() == null || varDebugInfo) { 1106 Assert.check(code.isStatementStart()); 1107 code.newLocal(v); 1108 genExpr(tree.init, v.erasure(types)).load(); 1109 items.makeLocalItem(v).store(); 1110 Assert.check(code.isStatementStart()); 1111 } 1112 } else { 1113 code.newLocal(v); 1114 } 1115 checkDimension(tree.pos(), v.type); 1116 } 1117 1118 public void visitSkip(JCSkip tree) { 1119 } 1120 1121 public void visitBlock(JCBlock tree) { 1122 /* this method is heavily invoked, as expected, for deeply nested blocks, if blocks doesn't happen to have 1123 * patterns there will be an unnecessary tax on memory consumption every time this method is executed, for this 1124 * reason we have created helper methods and here at a higher level we just discriminate depending on the 1125 * presence, or not, of patterns in a given block 1126 */ 1127 if (tree.patternMatchingCatch != null) { 1128 visitBlockWithPatterns(tree); 1129 } else { 1130 internalVisitBlock(tree); 1131 } 1132 } 1133 1134 private void visitBlockWithPatterns(JCBlock tree) { 1135 PatternMatchingCatchConfiguration prevConfiguration = patternMatchingCatchConfiguration; 1136 try { 1137 patternMatchingCatchConfiguration = 1138 new PatternMatchingCatchConfiguration(tree.patternMatchingCatch.calls2Handle(), 1139 new ListBuffer<int[]>(), 1140 tree.patternMatchingCatch.handler(), 1141 code.state.dup()); 1142 internalVisitBlock(tree); 1143 } finally { 1144 generatePatternMatchingCatch(env); 1145 patternMatchingCatchConfiguration = prevConfiguration; 1146 } 1147 } 1148 1149 private void generatePatternMatchingCatch(Env<GenContext> env) { 1150 if (patternMatchingCatchConfiguration.handler != null && 1151 !patternMatchingCatchConfiguration.ranges.isEmpty()) { 1152 Chain skipCatch = code.branch(goto_); 1153 JCCatch handler = patternMatchingCatchConfiguration.handler(); 1154 code.entryPoint(patternMatchingCatchConfiguration.startState(), 1155 handler.param.sym.type); 1156 genPatternMatchingCatch(handler, 1157 env, 1158 patternMatchingCatchConfiguration.ranges.toList()); 1159 code.resolve(skipCatch); 1160 } 1161 } 1162 1163 private void internalVisitBlock(JCBlock tree) { 1164 int limit = code.nextreg; 1165 Env<GenContext> localEnv = env.dup(tree, new GenContext()); 1166 genStats(tree.stats, localEnv); 1167 // End the scope of all block-local variables in variable info. 1168 if (!env.tree.hasTag(METHODDEF)) { 1169 code.statBegin(tree.endpos); 1170 code.endScopes(limit); 1171 code.pendingStatPos = Position.NOPOS; 1172 } 1173 } 1174 1175 public void visitDoLoop(JCDoWhileLoop tree) { 1176 genLoop(tree, tree.body, tree.cond, List.nil(), false); 1177 } 1178 1179 public void visitWhileLoop(JCWhileLoop tree) { 1180 genLoop(tree, tree.body, tree.cond, List.nil(), true); 1181 } 1182 1183 public void visitForLoop(JCForLoop tree) { 1184 int limit = code.nextreg; 1185 genStats(tree.init, env); 1186 genLoop(tree, tree.body, tree.cond, tree.step, true); 1187 code.endScopes(limit); 1188 } 1189 //where 1190 /** Generate code for a loop. 1191 * @param loop The tree representing the loop. 1192 * @param body The loop's body. 1193 * @param cond The loop's controlling condition. 1194 * @param step "Step" statements to be inserted at end of 1195 * each iteration. 1196 * @param testFirst True if the loop test belongs before the body. 1197 */ 1198 private void genLoop(JCStatement loop, 1199 JCStatement body, 1200 JCExpression cond, 1201 List<JCExpressionStatement> step, 1202 boolean testFirst) { 1203 Env<GenContext> loopEnv = env.dup(loop, new GenContext()); 1204 int startpc = code.entryPoint(); 1205 if (testFirst) { //while or for loop 1206 CondItem c; 1207 if (cond != null) { 1208 code.statBegin(cond.pos); 1209 Assert.check(code.isStatementStart()); 1210 c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER); 1211 } else { 1212 c = items.makeCondItem(goto_); 1213 } 1214 Chain loopDone = c.jumpFalse(); 1215 code.resolve(c.trueJumps); 1216 Assert.check(code.isStatementStart()); 1217 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET); 1218 code.resolve(loopEnv.info.cont); 1219 genStats(step, loopEnv); 1220 code.resolve(code.branch(goto_), startpc); 1221 code.resolve(loopDone); 1222 } else { 1223 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET); 1224 code.resolve(loopEnv.info.cont); 1225 genStats(step, loopEnv); 1226 if (code.isAlive()) { 1227 CondItem c; 1228 if (cond != null) { 1229 code.statBegin(cond.pos); 1230 Assert.check(code.isStatementStart()); 1231 c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER); 1232 } else { 1233 c = items.makeCondItem(goto_); 1234 } 1235 code.resolve(c.jumpTrue(), startpc); 1236 Assert.check(code.isStatementStart()); 1237 code.resolve(c.falseJumps); 1238 } 1239 } 1240 Chain exit = loopEnv.info.exit; 1241 if (exit != null) { 1242 code.resolve(exit); 1243 exit.state.defined.excludeFrom(code.nextreg); 1244 } 1245 } 1246 1247 public void visitForeachLoop(JCEnhancedForLoop tree) { 1248 throw new AssertionError(); // should have been removed by Lower. 1249 } 1250 1251 public void visitLabelled(JCLabeledStatement tree) { 1252 Env<GenContext> localEnv = env.dup(tree, new GenContext()); 1253 genStat(tree.body, localEnv, CRT_STATEMENT); 1254 Chain exit = localEnv.info.exit; 1255 if (exit != null) { 1256 code.resolve(exit); 1257 exit.state.defined.excludeFrom(code.nextreg); 1258 } 1259 } 1260 1261 public void visitSwitch(JCSwitch tree) { 1262 handleSwitch(tree, tree.selector, tree.cases, tree.patternSwitch); 1263 } 1264 1265 @Override 1266 public void visitSwitchExpression(JCSwitchExpression tree) { 1267 code.resolvePending(); 1268 boolean prevInCondSwitchExpression = inCondSwitchExpression; 1269 try { 1270 inCondSwitchExpression = false; 1271 doHandleSwitchExpression(tree); 1272 } finally { 1273 inCondSwitchExpression = prevInCondSwitchExpression; 1274 } 1275 result = items.makeStackItem(pt); 1276 } 1277 1278 private void doHandleSwitchExpression(JCSwitchExpression tree) { 1279 List<LocalItem> prevStackBeforeSwitchExpression = stackBeforeSwitchExpression; 1280 LocalItem prevSwitchResult = switchResult; 1281 int limit = code.nextreg; 1282 try { 1283 stackBeforeSwitchExpression = List.nil(); 1284 switchResult = null; 1285 if (hasTry(tree)) { 1286 //if the switch expression contains try-catch, the catch handlers need to have 1287 //an empty stack. So stash whole stack to local variables, and restore it before 1288 //breaks: 1289 while (code.state.stacksize > 0) { 1290 Type type = code.state.peek(); 1291 Name varName = names.fromString(target.syntheticNameChar() + 1292 "stack" + 1293 target.syntheticNameChar() + 1294 tree.pos + 1295 target.syntheticNameChar() + 1296 code.state.stacksize); 1297 VarSymbol var = new VarSymbol(Flags.SYNTHETIC, varName, type, 1298 this.env.enclMethod.sym); 1299 LocalItem item = items.new LocalItem(type, code.newLocal(var)); 1300 stackBeforeSwitchExpression = stackBeforeSwitchExpression.prepend(item); 1301 item.store(); 1302 } 1303 switchResult = makeTemp(tree.type); 1304 } 1305 int prevLetExprStart = code.setLetExprStackPos(code.state.stacksize); 1306 try { 1307 handleSwitch(tree, tree.selector, tree.cases, tree.patternSwitch); 1308 } finally { 1309 code.setLetExprStackPos(prevLetExprStart); 1310 } 1311 } finally { 1312 stackBeforeSwitchExpression = prevStackBeforeSwitchExpression; 1313 switchResult = prevSwitchResult; 1314 code.endScopes(limit); 1315 } 1316 } 1317 //where: 1318 private boolean hasTry(JCSwitchExpression tree) { 1319 class HasTryScanner extends TreeScanner { 1320 private boolean hasTry; 1321 1322 @Override 1323 public void visitTry(JCTry tree) { 1324 hasTry = true; 1325 } 1326 1327 @Override 1328 public void visitSynchronized(JCSynchronized tree) { 1329 hasTry = true; 1330 } 1331 1332 @Override 1333 public void visitClassDef(JCClassDecl tree) { 1334 } 1335 1336 @Override 1337 public void visitLambda(JCLambda tree) { 1338 } 1339 }; 1340 1341 HasTryScanner hasTryScanner = new HasTryScanner(); 1342 1343 hasTryScanner.scan(tree); 1344 return hasTryScanner.hasTry; 1345 } 1346 1347 private void handleSwitch(JCTree swtch, JCExpression selector, List<JCCase> cases, 1348 boolean patternSwitch) { 1349 int limit = code.nextreg; 1350 Assert.check(!selector.type.hasTag(CLASS)); 1351 int switchStart = patternSwitch ? code.entryPoint() : -1; 1352 int startpcCrt = genCrt ? code.curCP() : 0; 1353 Assert.check(code.isStatementStart()); 1354 Item sel = genExpr(selector, syms.intType); 1355 if (cases.isEmpty()) { 1356 // We are seeing: switch <sel> {} 1357 sel.load().drop(); 1358 if (genCrt) 1359 code.crt.put(TreeInfo.skipParens(selector), 1360 CRT_FLOW_CONTROLLER, startpcCrt, code.curCP()); 1361 } else { 1362 // We are seeing a nonempty switch. 1363 sel.load(); 1364 if (genCrt) 1365 code.crt.put(TreeInfo.skipParens(selector), 1366 CRT_FLOW_CONTROLLER, startpcCrt, code.curCP()); 1367 Env<GenContext> switchEnv = env.dup(swtch, new GenContext()); 1368 switchEnv.info.isSwitch = true; 1369 1370 // Compute number of labels and minimum and maximum label values. 1371 // For each case, store its label in an array. 1372 int lo = Integer.MAX_VALUE; // minimum label. 1373 int hi = Integer.MIN_VALUE; // maximum label. 1374 int nlabels = 0; // number of labels. 1375 1376 int[] labels = new int[cases.length()]; // the label array. 1377 int defaultIndex = -1; // the index of the default clause. 1378 1379 List<JCCase> l = cases; 1380 for (int i = 0; i < labels.length; i++) { 1381 if (l.head.labels.head instanceof JCConstantCaseLabel constLabel) { 1382 Assert.check(l.head.labels.size() == 1); 1383 int val = ((Number) constLabel.expr.type.constValue()).intValue(); 1384 labels[i] = val; 1385 if (val < lo) lo = val; 1386 if (hi < val) hi = val; 1387 nlabels++; 1388 } else { 1389 Assert.check(defaultIndex == -1); 1390 defaultIndex = i; 1391 } 1392 l = l.tail; 1393 } 1394 1395 // Determine whether to issue a tableswitch or a lookupswitch 1396 // instruction. 1397 long table_space_cost = 4 + ((long) hi - lo + 1); // words 1398 long table_time_cost = 3; // comparisons 1399 long lookup_space_cost = 3 + 2 * (long) nlabels; 1400 long lookup_time_cost = nlabels; 1401 int opcode = 1402 nlabels > 0 && 1403 table_space_cost + 3 * table_time_cost <= 1404 lookup_space_cost + 3 * lookup_time_cost 1405 ? 1406 tableswitch : lookupswitch; 1407 1408 int startpc = code.curCP(); // the position of the selector operation 1409 code.emitop0(opcode); 1410 code.align(4); 1411 int tableBase = code.curCP(); // the start of the jump table 1412 int[] offsets = null; // a table of offsets for a lookupswitch 1413 code.emit4(-1); // leave space for default offset 1414 if (opcode == tableswitch) { 1415 code.emit4(lo); // minimum label 1416 code.emit4(hi); // maximum label 1417 for (long i = lo; i <= hi; i++) { // leave space for jump table 1418 code.emit4(-1); 1419 } 1420 } else { 1421 code.emit4(nlabels); // number of labels 1422 for (int i = 0; i < nlabels; i++) { 1423 code.emit4(-1); code.emit4(-1); // leave space for lookup table 1424 } 1425 offsets = new int[labels.length]; 1426 } 1427 Code.State stateSwitch = code.state.dup(); 1428 code.markDead(); 1429 1430 // For each case do: 1431 l = cases; 1432 for (int i = 0; i < labels.length; i++) { 1433 JCCase c = l.head; 1434 l = l.tail; 1435 1436 int pc = code.entryPoint(stateSwitch); 1437 // Insert offset directly into code or else into the 1438 // offsets table. 1439 if (i != defaultIndex) { 1440 if (opcode == tableswitch) { 1441 code.put4( 1442 tableBase + 4 * (labels[i] - lo + 3), 1443 pc - startpc); 1444 } else { 1445 offsets[i] = pc - startpc; 1446 } 1447 } else { 1448 code.put4(tableBase, pc - startpc); 1449 } 1450 1451 // Generate code for the statements in this case. 1452 genStats(c.stats, switchEnv, CRT_FLOW_TARGET); 1453 } 1454 1455 if (switchEnv.info.cont != null) { 1456 Assert.check(patternSwitch); 1457 code.resolve(switchEnv.info.cont, switchStart); 1458 } 1459 1460 // Resolve all breaks. 1461 Chain exit = switchEnv.info.exit; 1462 if (exit != null) { 1463 code.resolve(exit); 1464 exit.state.defined.excludeFrom(limit); 1465 } 1466 1467 // If we have not set the default offset, we do so now. 1468 if (code.get4(tableBase) == -1) { 1469 code.put4(tableBase, code.entryPoint(stateSwitch) - startpc); 1470 } 1471 1472 if (opcode == tableswitch) { 1473 // Let any unfilled slots point to the default case. 1474 int defaultOffset = code.get4(tableBase); 1475 for (long i = lo; i <= hi; i++) { 1476 int t = (int)(tableBase + 4 * (i - lo + 3)); 1477 if (code.get4(t) == -1) 1478 code.put4(t, defaultOffset); 1479 } 1480 } else { 1481 // Sort non-default offsets and copy into lookup table. 1482 if (defaultIndex >= 0) 1483 for (int i = defaultIndex; i < labels.length - 1; i++) { 1484 labels[i] = labels[i+1]; 1485 offsets[i] = offsets[i+1]; 1486 } 1487 if (nlabels > 0) 1488 qsort2(labels, offsets, 0, nlabels - 1); 1489 for (int i = 0; i < nlabels; i++) { 1490 int caseidx = tableBase + 8 * (i + 1); 1491 code.put4(caseidx, labels[i]); 1492 code.put4(caseidx + 4, offsets[i]); 1493 } 1494 } 1495 1496 if (swtch instanceof JCSwitchExpression) { 1497 // Emit line position for the end of a switch expression 1498 code.statBegin(TreeInfo.endPos(swtch)); 1499 } 1500 } 1501 code.endScopes(limit); 1502 } 1503 //where 1504 /** Sort (int) arrays of keys and values 1505 */ 1506 static void qsort2(int[] keys, int[] values, int lo, int hi) { 1507 int i = lo; 1508 int j = hi; 1509 int pivot = keys[(i+j)/2]; 1510 do { 1511 while (keys[i] < pivot) i++; 1512 while (pivot < keys[j]) j--; 1513 if (i <= j) { 1514 int temp1 = keys[i]; 1515 keys[i] = keys[j]; 1516 keys[j] = temp1; 1517 int temp2 = values[i]; 1518 values[i] = values[j]; 1519 values[j] = temp2; 1520 i++; 1521 j--; 1522 } 1523 } while (i <= j); 1524 if (lo < j) qsort2(keys, values, lo, j); 1525 if (i < hi) qsort2(keys, values, i, hi); 1526 } 1527 1528 public void visitSynchronized(JCSynchronized tree) { 1529 int limit = code.nextreg; 1530 // Generate code to evaluate lock and save in temporary variable. 1531 final LocalItem lockVar = makeTemp(syms.objectType); 1532 Assert.check(code.isStatementStart()); 1533 genExpr(tree.lock, tree.lock.type).load().duplicate(); 1534 lockVar.store(); 1535 1536 // Generate code to enter monitor. 1537 code.emitop0(monitorenter); 1538 code.state.lock(lockVar.reg); 1539 1540 // Generate code for a try statement with given body, no catch clauses 1541 // in a new environment with the "exit-monitor" operation as finalizer. 1542 final Env<GenContext> syncEnv = env.dup(tree, new GenContext()); 1543 syncEnv.info.finalize = new GenFinalizer() { 1544 void gen() { 1545 genLast(); 1546 Assert.check(syncEnv.info.gaps.length() % 2 == 0); 1547 syncEnv.info.gaps.append(code.curCP()); 1548 } 1549 void genLast() { 1550 if (code.isAlive()) { 1551 lockVar.load(); 1552 code.emitop0(monitorexit); 1553 code.state.unlock(lockVar.reg); 1554 } 1555 } 1556 }; 1557 syncEnv.info.gaps = new ListBuffer<>(); 1558 genTry(tree.body, List.nil(), syncEnv); 1559 code.endScopes(limit); 1560 } 1561 1562 public void visitTry(final JCTry tree) { 1563 // Generate code for a try statement with given body and catch clauses, 1564 // in a new environment which calls the finally block if there is one. 1565 final Env<GenContext> tryEnv = env.dup(tree, new GenContext()); 1566 final Env<GenContext> oldEnv = env; 1567 tryEnv.info.finalize = new GenFinalizer() { 1568 void gen() { 1569 Assert.check(tryEnv.info.gaps.length() % 2 == 0); 1570 tryEnv.info.gaps.append(code.curCP()); 1571 genLast(); 1572 } 1573 void genLast() { 1574 if (tree.finalizer != null) 1575 genStat(tree.finalizer, oldEnv, CRT_BLOCK); 1576 } 1577 boolean hasFinalizer() { 1578 return tree.finalizer != null; 1579 } 1580 1581 @Override 1582 void afterBody() { 1583 if (tree.finalizer != null && (tree.finalizer.flags & BODY_ONLY_FINALIZE) != 0) { 1584 //for body-only finally, remove the GenFinalizer after try body 1585 //so that the finally is not generated to catch bodies: 1586 tryEnv.info.finalize = null; 1587 } 1588 } 1589 1590 }; 1591 tryEnv.info.gaps = new ListBuffer<>(); 1592 genTry(tree.body, tree.catchers, tryEnv); 1593 } 1594 //where 1595 /** Generate code for a try or synchronized statement 1596 * @param body The body of the try or synchronized statement. 1597 * @param catchers The list of catch clauses. 1598 * @param env The current environment of the body. 1599 */ 1600 void genTry(JCTree body, List<JCCatch> catchers, Env<GenContext> env) { 1601 int limit = code.nextreg; 1602 int startpc = code.curCP(); 1603 Code.State stateTry = code.state.dup(); 1604 genStat(body, env, CRT_BLOCK); 1605 int endpc = code.curCP(); 1606 List<Integer> gaps = env.info.gaps.toList(); 1607 code.statBegin(TreeInfo.endPos(body)); 1608 genFinalizer(env); 1609 code.statBegin(TreeInfo.endPos(env.tree)); 1610 Chain exitChain; 1611 boolean actualTry = env.tree.hasTag(TRY); 1612 if (startpc == endpc && actualTry) { 1613 exitChain = code.branch(dontgoto); 1614 } else { 1615 exitChain = code.branch(goto_); 1616 } 1617 endFinalizerGap(env); 1618 env.info.finalize.afterBody(); 1619 boolean hasFinalizer = 1620 env.info.finalize != null && 1621 env.info.finalize.hasFinalizer(); 1622 if (startpc != endpc) for (List<JCCatch> l = catchers; l.nonEmpty(); l = l.tail) { 1623 // start off with exception on stack 1624 code.entryPoint(stateTry, l.head.param.sym.type); 1625 genCatch(l.head, env, startpc, endpc, gaps); 1626 genFinalizer(env); 1627 if (hasFinalizer || l.tail.nonEmpty()) { 1628 code.statBegin(TreeInfo.endPos(env.tree)); 1629 exitChain = Code.mergeChains(exitChain, 1630 code.branch(goto_)); 1631 } 1632 endFinalizerGap(env); 1633 } 1634 if (hasFinalizer && (startpc != endpc || !actualTry)) { 1635 // Create a new register segment to avoid allocating 1636 // the same variables in finalizers and other statements. 1637 code.newRegSegment(); 1638 1639 // Add a catch-all clause. 1640 1641 // start off with exception on stack 1642 int catchallpc = code.entryPoint(stateTry, syms.throwableType); 1643 1644 // Register all exception ranges for catch all clause. 1645 // The range of the catch all clause is from the beginning 1646 // of the try or synchronized block until the present 1647 // code pointer excluding all gaps in the current 1648 // environment's GenContext. 1649 int startseg = startpc; 1650 while (env.info.gaps.nonEmpty()) { 1651 int endseg = env.info.gaps.next().intValue(); 1652 registerCatch(body.pos(), startseg, endseg, 1653 catchallpc, 0); 1654 startseg = env.info.gaps.next().intValue(); 1655 } 1656 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS)); 1657 code.markStatBegin(); 1658 1659 Item excVar = makeTemp(syms.throwableType); 1660 excVar.store(); 1661 genFinalizer(env); 1662 code.resolvePending(); 1663 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.END_POS)); 1664 code.markStatBegin(); 1665 1666 excVar.load(); 1667 registerCatch(body.pos(), startseg, 1668 env.info.gaps.next().intValue(), 1669 catchallpc, 0); 1670 code.emitop0(athrow); 1671 code.markDead(); 1672 1673 // If there are jsr's to this finalizer, ... 1674 if (env.info.cont != null) { 1675 // Resolve all jsr's. 1676 code.resolve(env.info.cont); 1677 1678 // Mark statement line number 1679 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS)); 1680 code.markStatBegin(); 1681 1682 // Save return address. 1683 LocalItem retVar = makeTemp(syms.throwableType); 1684 retVar.store(); 1685 1686 // Generate finalizer code. 1687 env.info.finalize.genLast(); 1688 1689 // Return. 1690 code.emitop1w(ret, retVar.reg); 1691 code.markDead(); 1692 } 1693 } 1694 // Resolve all breaks. 1695 code.resolve(exitChain); 1696 1697 code.endScopes(limit); 1698 } 1699 1700 /** Generate code for a catch clause. 1701 * @param tree The catch clause. 1702 * @param env The environment current in the enclosing try. 1703 * @param startpc Start pc of try-block. 1704 * @param endpc End pc of try-block. 1705 */ 1706 void genCatch(JCCatch tree, 1707 Env<GenContext> env, 1708 int startpc, int endpc, 1709 List<Integer> gaps) { 1710 if (startpc != endpc) { 1711 List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypeExprs 1712 = catchTypesWithAnnotations(tree); 1713 while (gaps.nonEmpty()) { 1714 for (Pair<List<Attribute.TypeCompound>, JCExpression> subCatch1 : catchTypeExprs) { 1715 JCExpression subCatch = subCatch1.snd; 1716 int catchType = makeRef(tree.pos(), subCatch.type); 1717 int end = gaps.head.intValue(); 1718 registerCatch(tree.pos(), 1719 startpc, end, code.curCP(), 1720 catchType); 1721 for (Attribute.TypeCompound tc : subCatch1.fst) { 1722 tc.position.setCatchInfo(catchType, startpc); 1723 } 1724 } 1725 gaps = gaps.tail; 1726 startpc = gaps.head.intValue(); 1727 gaps = gaps.tail; 1728 } 1729 if (startpc < endpc) { 1730 for (Pair<List<Attribute.TypeCompound>, JCExpression> subCatch1 : catchTypeExprs) { 1731 JCExpression subCatch = subCatch1.snd; 1732 int catchType = makeRef(tree.pos(), subCatch.type); 1733 registerCatch(tree.pos(), 1734 startpc, endpc, code.curCP(), 1735 catchType); 1736 for (Attribute.TypeCompound tc : subCatch1.fst) { 1737 tc.position.setCatchInfo(catchType, startpc); 1738 } 1739 } 1740 } 1741 genCatchBlock(tree, env); 1742 } 1743 } 1744 void genPatternMatchingCatch(JCCatch tree, 1745 Env<GenContext> env, 1746 List<int[]> ranges) { 1747 for (int[] range : ranges) { 1748 JCExpression subCatch = tree.param.vartype; 1749 int catchType = makeRef(tree.pos(), subCatch.type); 1750 registerCatch(tree.pos(), 1751 range[0], range[1], code.curCP(), 1752 catchType); 1753 } 1754 genCatchBlock(tree, env); 1755 } 1756 void genCatchBlock(JCCatch tree, Env<GenContext> env) { 1757 VarSymbol exparam = tree.param.sym; 1758 code.statBegin(tree.pos); 1759 code.markStatBegin(); 1760 int limit = code.nextreg; 1761 code.newLocal(exparam); 1762 items.makeLocalItem(exparam).store(); 1763 code.statBegin(TreeInfo.firstStatPos(tree.body)); 1764 genStat(tree.body, env, CRT_BLOCK); 1765 code.endScopes(limit); 1766 code.statBegin(TreeInfo.endPos(tree.body)); 1767 } 1768 // where 1769 List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypesWithAnnotations(JCCatch tree) { 1770 return TreeInfo.isMultiCatch(tree) ? 1771 catchTypesWithAnnotationsFromMulticatch((JCTypeUnion)tree.param.vartype, tree.param.sym.getRawTypeAttributes()) : 1772 List.of(new Pair<>(tree.param.sym.getRawTypeAttributes(), tree.param.vartype)); 1773 } 1774 // where 1775 List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypesWithAnnotationsFromMulticatch(JCTypeUnion tree, List<TypeCompound> first) { 1776 List<JCExpression> alts = tree.alternatives; 1777 List<Pair<List<TypeCompound>, JCExpression>> res = List.of(new Pair<>(first, alts.head)); 1778 alts = alts.tail; 1779 1780 while(alts != null && alts.head != null) { 1781 JCExpression alt = alts.head; 1782 if (alt instanceof JCAnnotatedType annotatedType) { 1783 res = res.prepend(new Pair<>(annotate.fromAnnotations(annotatedType.annotations), alt)); 1784 } else { 1785 res = res.prepend(new Pair<>(List.nil(), alt)); 1786 } 1787 alts = alts.tail; 1788 } 1789 return res.reverse(); 1790 } 1791 1792 /** Register a catch clause in the "Exceptions" code-attribute. 1793 */ 1794 void registerCatch(DiagnosticPosition pos, 1795 int startpc, int endpc, 1796 int handler_pc, int catch_type) { 1797 char startpc1 = (char)startpc; 1798 char endpc1 = (char)endpc; 1799 char handler_pc1 = (char)handler_pc; 1800 if (startpc1 == startpc && 1801 endpc1 == endpc && 1802 handler_pc1 == handler_pc) { 1803 code.addCatch(startpc1, endpc1, handler_pc1, 1804 (char)catch_type); 1805 } else { 1806 log.error(pos, Errors.LimitCodeTooLargeForTryStmt); 1807 nerrs++; 1808 } 1809 } 1810 1811 public void visitIf(JCIf tree) { 1812 int limit = code.nextreg; 1813 Chain thenExit = null; 1814 Assert.check(code.isStatementStart()); 1815 CondItem c = genCond(TreeInfo.skipParens(tree.cond), 1816 CRT_FLOW_CONTROLLER); 1817 Chain elseChain = c.jumpFalse(); 1818 Assert.check(code.isStatementStart()); 1819 if (!c.isFalse()) { 1820 code.resolve(c.trueJumps); 1821 genStat(tree.thenpart, env, CRT_STATEMENT | CRT_FLOW_TARGET); 1822 thenExit = code.branch(goto_); 1823 } 1824 if (elseChain != null) { 1825 code.resolve(elseChain); 1826 if (tree.elsepart != null) { 1827 genStat(tree.elsepart, env,CRT_STATEMENT | CRT_FLOW_TARGET); 1828 } 1829 } 1830 code.resolve(thenExit); 1831 code.endScopes(limit); 1832 Assert.check(code.isStatementStart()); 1833 } 1834 1835 public void visitExec(JCExpressionStatement tree) { 1836 // Optimize x++ to ++x and x-- to --x. 1837 JCExpression e = tree.expr; 1838 switch (e.getTag()) { 1839 case POSTINC: 1840 ((JCUnary) e).setTag(PREINC); 1841 break; 1842 case POSTDEC: 1843 ((JCUnary) e).setTag(PREDEC); 1844 break; 1845 } 1846 Assert.check(code.isStatementStart()); 1847 genExpr(tree.expr, tree.expr.type).drop(); 1848 Assert.check(code.isStatementStart()); 1849 } 1850 1851 public void visitBreak(JCBreak tree) { 1852 Assert.check(code.isStatementStart()); 1853 final Env<GenContext> targetEnv = unwindBreak(tree.target); 1854 targetEnv.info.addExit(code.branch(goto_)); 1855 endFinalizerGaps(env, targetEnv); 1856 } 1857 1858 public void visitYield(JCYield tree) { 1859 Assert.check(code.isStatementStart()); 1860 final Env<GenContext> targetEnv; 1861 if (inCondSwitchExpression) { 1862 CondItem value = genCond(tree.value, CRT_FLOW_TARGET); 1863 Chain falseJumps = value.jumpFalse(); 1864 1865 code.resolve(value.trueJumps); 1866 Env<GenContext> localEnv = unwindBreak(tree.target); 1867 reloadStackBeforeSwitchExpr(); 1868 Chain trueJumps = code.branch(goto_); 1869 1870 endFinalizerGaps(env, localEnv); 1871 1872 code.resolve(falseJumps); 1873 targetEnv = unwindBreak(tree.target); 1874 reloadStackBeforeSwitchExpr(); 1875 falseJumps = code.branch(goto_); 1876 1877 if (switchExpressionTrueChain == null) { 1878 switchExpressionTrueChain = trueJumps; 1879 } else { 1880 switchExpressionTrueChain = 1881 Code.mergeChains(switchExpressionTrueChain, trueJumps); 1882 } 1883 if (switchExpressionFalseChain == null) { 1884 switchExpressionFalseChain = falseJumps; 1885 } else { 1886 switchExpressionFalseChain = 1887 Code.mergeChains(switchExpressionFalseChain, falseJumps); 1888 } 1889 } else { 1890 genExpr(tree.value, pt).load(); 1891 if (switchResult != null) 1892 switchResult.store(); 1893 1894 targetEnv = unwindBreak(tree.target); 1895 1896 if (code.isAlive()) { 1897 reloadStackBeforeSwitchExpr(); 1898 if (switchResult != null) 1899 switchResult.load(); 1900 1901 code.state.forceStackTop(tree.target.type); 1902 targetEnv.info.addExit(code.branch(goto_)); 1903 code.markDead(); 1904 } 1905 } 1906 endFinalizerGaps(env, targetEnv); 1907 } 1908 //where: 1909 /** As side-effect, might mark code as dead disabling any further emission. 1910 */ 1911 private Env<GenContext> unwindBreak(JCTree target) { 1912 int tmpPos = code.pendingStatPos; 1913 Env<GenContext> targetEnv = unwind(target, env); 1914 code.pendingStatPos = tmpPos; 1915 return targetEnv; 1916 } 1917 1918 private void reloadStackBeforeSwitchExpr() { 1919 for (LocalItem li : stackBeforeSwitchExpression) 1920 li.load(); 1921 } 1922 1923 public void visitContinue(JCContinue tree) { 1924 int tmpPos = code.pendingStatPos; 1925 Env<GenContext> targetEnv = unwind(tree.target, env); 1926 code.pendingStatPos = tmpPos; 1927 Assert.check(code.isStatementStart()); 1928 targetEnv.info.addCont(code.branch(goto_)); 1929 endFinalizerGaps(env, targetEnv); 1930 } 1931 1932 public void visitReturn(JCReturn tree) { 1933 int limit = code.nextreg; 1934 final Env<GenContext> targetEnv; 1935 1936 /* Save and then restore the location of the return in case a finally 1937 * is expanded (with unwind()) in the middle of our bytecodes. 1938 */ 1939 int tmpPos = code.pendingStatPos; 1940 if (tree.expr != null) { 1941 Assert.check(code.isStatementStart()); 1942 Item r = genExpr(tree.expr, pt).load(); 1943 if (hasFinally(env.enclMethod, env)) { 1944 r = makeTemp(pt); 1945 r.store(); 1946 } 1947 targetEnv = unwind(env.enclMethod, env); 1948 code.pendingStatPos = tmpPos; 1949 r.load(); 1950 code.emitop0(ireturn + Code.truncate(Code.typecode(pt))); 1951 } else { 1952 targetEnv = unwind(env.enclMethod, env); 1953 code.pendingStatPos = tmpPos; 1954 code.emitop0(return_); 1955 } 1956 endFinalizerGaps(env, targetEnv); 1957 code.endScopes(limit); 1958 } 1959 1960 public void visitThrow(JCThrow tree) { 1961 Assert.check(code.isStatementStart()); 1962 genExpr(tree.expr, tree.expr.type).load(); 1963 code.emitop0(athrow); 1964 Assert.check(code.isStatementStart()); 1965 } 1966 1967 /* ************************************************************************ 1968 * Visitor methods for expressions 1969 *************************************************************************/ 1970 1971 public void visitApply(JCMethodInvocation tree) { 1972 setTypeAnnotationPositions(tree.pos); 1973 // Generate code for method. 1974 Item m = genExpr(tree.meth, methodType); 1975 // Generate code for all arguments, where the expected types are 1976 // the parameters of the method's external type (that is, any implicit 1977 // outer instance of a super(...) call appears as first parameter). 1978 MethodSymbol msym = (MethodSymbol)TreeInfo.symbol(tree.meth); 1979 genArgs(tree.args, 1980 msym.externalType(types).getParameterTypes()); 1981 if (!msym.isDynamic()) { 1982 code.statBegin(tree.pos); 1983 } 1984 if (patternMatchingCatchConfiguration.invocations().contains(tree)) { 1985 int start = code.curCP(); 1986 result = m.invoke(); 1987 patternMatchingCatchConfiguration.ranges().add(new int[] {start, code.curCP()}); 1988 } else { 1989 if (msym.isConstructor() && TreeInfo.isConstructorCall(tree)) { 1990 //if this is a this(...) or super(...) call, there is a pending 1991 //"uninitialized this" before this call. One catch handler cannot 1992 //handle exceptions that may come from places with "uninitialized this" 1993 //and (initialized) this, hence generate one set of handlers here 1994 //for the "uninitialized this" case, and another set of handlers 1995 //will be generated at the end of the method for the initialized this, 1996 //if needed: 1997 generatePatternMatchingCatch(env); 1998 result = m.invoke(); 1999 patternMatchingCatchConfiguration = 2000 patternMatchingCatchConfiguration.restart(code.state.dup()); 2001 } else { 2002 result = m.invoke(); 2003 } 2004 } 2005 } 2006 2007 public void visitConditional(JCConditional tree) { 2008 Chain thenExit = null; 2009 code.statBegin(tree.cond.pos); 2010 CondItem c = genCond(tree.cond, CRT_FLOW_CONTROLLER); 2011 Chain elseChain = c.jumpFalse(); 2012 if (!c.isFalse()) { 2013 code.resolve(c.trueJumps); 2014 int startpc = genCrt ? code.curCP() : 0; 2015 code.statBegin(tree.truepart.pos); 2016 genExpr(tree.truepart, pt).load(); 2017 code.state.forceStackTop(tree.type); 2018 if (genCrt) code.crt.put(tree.truepart, CRT_FLOW_TARGET, 2019 startpc, code.curCP()); 2020 thenExit = code.branch(goto_); 2021 } 2022 if (elseChain != null) { 2023 code.resolve(elseChain); 2024 int startpc = genCrt ? code.curCP() : 0; 2025 code.statBegin(tree.falsepart.pos); 2026 genExpr(tree.falsepart, pt).load(); 2027 code.state.forceStackTop(tree.type); 2028 if (genCrt) code.crt.put(tree.falsepart, CRT_FLOW_TARGET, 2029 startpc, code.curCP()); 2030 } 2031 code.resolve(thenExit); 2032 result = items.makeStackItem(pt); 2033 } 2034 2035 private void setTypeAnnotationPositions(int treePos) { 2036 MethodSymbol meth = code.meth; 2037 boolean initOrClinit = code.meth.getKind() == javax.lang.model.element.ElementKind.CONSTRUCTOR 2038 || code.meth.getKind() == javax.lang.model.element.ElementKind.STATIC_INIT; 2039 2040 for (Attribute.TypeCompound ta : meth.getRawTypeAttributes()) { 2041 if (ta.hasUnknownPosition()) 2042 ta.tryFixPosition(); 2043 2044 if (ta.position.matchesPos(treePos)) 2045 ta.position.updatePosOffset(code.cp); 2046 } 2047 2048 if (!initOrClinit) 2049 return; 2050 2051 for (Attribute.TypeCompound ta : meth.owner.getRawTypeAttributes()) { 2052 if (ta.hasUnknownPosition()) 2053 ta.tryFixPosition(); 2054 2055 if (ta.position.matchesPos(treePos)) 2056 ta.position.updatePosOffset(code.cp); 2057 } 2058 2059 ClassSymbol clazz = meth.enclClass(); 2060 for (Symbol s : new com.sun.tools.javac.model.FilteredMemberList(clazz.members())) { 2061 if (!s.getKind().isField()) 2062 continue; 2063 2064 for (Attribute.TypeCompound ta : s.getRawTypeAttributes()) { 2065 if (ta.hasUnknownPosition()) 2066 ta.tryFixPosition(); 2067 2068 if (ta.position.matchesPos(treePos)) 2069 ta.position.updatePosOffset(code.cp); 2070 } 2071 } 2072 } 2073 2074 public void visitNewClass(JCNewClass tree) { 2075 // Enclosing instances or anonymous classes should have been eliminated 2076 // by now. 2077 Assert.check(tree.encl == null && tree.def == null); 2078 setTypeAnnotationPositions(tree.pos); 2079 2080 code.emitop2(new_, checkDimension(tree.pos(), tree.type), PoolWriter::putClass); 2081 code.emitop0(dup); 2082 2083 // Generate code for all arguments, where the expected types are 2084 // the parameters of the constructor's external type (that is, 2085 // any implicit outer instance appears as first parameter). 2086 genArgs(tree.args, tree.constructor.externalType(types).getParameterTypes()); 2087 2088 items.makeMemberItem(tree.constructor, true).invoke(); 2089 result = items.makeStackItem(tree.type); 2090 } 2091 2092 public void visitNewArray(JCNewArray tree) { 2093 setTypeAnnotationPositions(tree.pos); 2094 2095 if (tree.elems != null) { 2096 Type elemtype = types.elemtype(tree.type); 2097 loadIntConst(tree.elems.length()); 2098 Item arr = makeNewArray(tree.pos(), tree.type, 1); 2099 int i = 0; 2100 for (List<JCExpression> l = tree.elems; l.nonEmpty(); l = l.tail) { 2101 arr.duplicate(); 2102 loadIntConst(i); 2103 i++; 2104 genExpr(l.head, elemtype).load(); 2105 items.makeIndexedItem(elemtype).store(); 2106 } 2107 result = arr; 2108 } else { 2109 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) { 2110 genExpr(l.head, syms.intType).load(); 2111 } 2112 result = makeNewArray(tree.pos(), tree.type, tree.dims.length()); 2113 } 2114 } 2115 //where 2116 /** Generate code to create an array with given element type and number 2117 * of dimensions. 2118 */ 2119 Item makeNewArray(DiagnosticPosition pos, Type type, int ndims) { 2120 Type elemtype = types.elemtype(type); 2121 if (types.dimensions(type) > ClassFile.MAX_DIMENSIONS) { 2122 log.error(pos, Errors.LimitDimensions); 2123 nerrs++; 2124 } 2125 int elemcode = Code.arraycode(elemtype); 2126 if (elemcode == 0 || (elemcode == 1 && ndims == 1)) { 2127 code.emitAnewarray(makeRef(pos, elemtype), type); 2128 } else if (elemcode == 1) { 2129 code.emitMultianewarray(ndims, makeRef(pos, type), type); 2130 } else { 2131 code.emitNewarray(elemcode, type); 2132 } 2133 return items.makeStackItem(type); 2134 } 2135 2136 public void visitParens(JCParens tree) { 2137 result = genExpr(tree.expr, tree.expr.type); 2138 } 2139 2140 public void visitAssign(JCAssign tree) { 2141 Item l = genExpr(tree.lhs, tree.lhs.type); 2142 genExpr(tree.rhs, tree.lhs.type).load(); 2143 if (tree.rhs.type.hasTag(BOT)) { 2144 /* This is just a case of widening reference conversion that per 5.1.5 simply calls 2145 for "regarding a reference as having some other type in a manner that can be proved 2146 correct at compile time." 2147 */ 2148 code.state.forceStackTop(tree.lhs.type); 2149 } 2150 result = items.makeAssignItem(l); 2151 } 2152 2153 public void visitAssignop(JCAssignOp tree) { 2154 OperatorSymbol operator = tree.operator; 2155 Item l; 2156 if (operator.opcode == string_add) { 2157 l = concat.makeConcat(tree); 2158 } else { 2159 // Generate code for first expression 2160 l = genExpr(tree.lhs, tree.lhs.type); 2161 2162 // If we have an increment of -32768 to +32767 of a local 2163 // int variable we can use an incr instruction instead of 2164 // proceeding further. 2165 if ((tree.hasTag(PLUS_ASG) || tree.hasTag(MINUS_ASG)) && 2166 l instanceof LocalItem localItem && 2167 tree.lhs.type.getTag().isSubRangeOf(INT) && 2168 tree.rhs.type.getTag().isSubRangeOf(INT) && 2169 tree.rhs.type.constValue() != null) { 2170 int ival = ((Number) tree.rhs.type.constValue()).intValue(); 2171 if (tree.hasTag(MINUS_ASG)) ival = -ival; 2172 localItem.incr(ival); 2173 result = l; 2174 return; 2175 } 2176 // Otherwise, duplicate expression, load one copy 2177 // and complete binary operation. 2178 l.duplicate(); 2179 l.coerce(operator.type.getParameterTypes().head).load(); 2180 completeBinop(tree.lhs, tree.rhs, operator).coerce(tree.lhs.type); 2181 } 2182 result = items.makeAssignItem(l); 2183 } 2184 2185 public void visitUnary(JCUnary tree) { 2186 OperatorSymbol operator = tree.operator; 2187 if (tree.hasTag(NOT)) { 2188 CondItem od = genCond(tree.arg, false); 2189 result = od.negate(); 2190 } else { 2191 Item od = genExpr(tree.arg, operator.type.getParameterTypes().head); 2192 switch (tree.getTag()) { 2193 case POS: 2194 result = od.load(); 2195 break; 2196 case NEG: 2197 result = od.load(); 2198 code.emitop0(operator.opcode); 2199 break; 2200 case COMPL: 2201 result = od.load(); 2202 emitMinusOne(od.typecode); 2203 code.emitop0(operator.opcode); 2204 break; 2205 case PREINC: case PREDEC: 2206 od.duplicate(); 2207 if (od instanceof LocalItem localItem && 2208 (operator.opcode == iadd || operator.opcode == isub)) { 2209 localItem.incr(tree.hasTag(PREINC) ? 1 : -1); 2210 result = od; 2211 } else { 2212 od.load(); 2213 code.emitop0(one(od.typecode)); 2214 code.emitop0(operator.opcode); 2215 // Perform narrowing primitive conversion if byte, 2216 // char, or short. Fix for 4304655. 2217 if (od.typecode != INTcode && 2218 Code.truncate(od.typecode) == INTcode) 2219 code.emitop0(int2byte + od.typecode - BYTEcode); 2220 result = items.makeAssignItem(od); 2221 } 2222 break; 2223 case POSTINC: case POSTDEC: 2224 od.duplicate(); 2225 if (od instanceof LocalItem localItem && 2226 (operator.opcode == iadd || operator.opcode == isub)) { 2227 Item res = od.load(); 2228 localItem.incr(tree.hasTag(POSTINC) ? 1 : -1); 2229 result = res; 2230 } else { 2231 Item res = od.load(); 2232 od.stash(od.typecode); 2233 code.emitop0(one(od.typecode)); 2234 code.emitop0(operator.opcode); 2235 // Perform narrowing primitive conversion if byte, 2236 // char, or short. Fix for 4304655. 2237 if (od.typecode != INTcode && 2238 Code.truncate(od.typecode) == INTcode) 2239 code.emitop0(int2byte + od.typecode - BYTEcode); 2240 od.store(); 2241 result = res; 2242 } 2243 break; 2244 case NULLCHK: 2245 result = od.load(); 2246 code.emitop0(dup); 2247 genNullCheck(tree); 2248 break; 2249 default: 2250 Assert.error(); 2251 } 2252 } 2253 } 2254 2255 /** Generate a null check from the object value at stack top. */ 2256 private void genNullCheck(JCTree tree) { 2257 code.statBegin(tree.pos); 2258 callMethod(tree.pos(), syms.objectsType, names.requireNonNull, 2259 List.of(syms.objectType), true); 2260 code.emitop0(pop); 2261 } 2262 2263 public void visitBinary(JCBinary tree) { 2264 OperatorSymbol operator = tree.operator; 2265 if (operator.opcode == string_add) { 2266 result = concat.makeConcat(tree); 2267 } else if (tree.hasTag(AND)) { 2268 CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER); 2269 if (!lcond.isFalse()) { 2270 Chain falseJumps = lcond.jumpFalse(); 2271 code.resolve(lcond.trueJumps); 2272 CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET); 2273 result = items. 2274 makeCondItem(rcond.opcode, 2275 rcond.trueJumps, 2276 Code.mergeChains(falseJumps, 2277 rcond.falseJumps)); 2278 } else { 2279 result = lcond; 2280 } 2281 } else if (tree.hasTag(OR)) { 2282 CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER); 2283 if (!lcond.isTrue()) { 2284 Chain trueJumps = lcond.jumpTrue(); 2285 code.resolve(lcond.falseJumps); 2286 CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET); 2287 result = items. 2288 makeCondItem(rcond.opcode, 2289 Code.mergeChains(trueJumps, rcond.trueJumps), 2290 rcond.falseJumps); 2291 } else { 2292 result = lcond; 2293 } 2294 } else { 2295 Item od = genExpr(tree.lhs, operator.type.getParameterTypes().head); 2296 od.load(); 2297 result = completeBinop(tree.lhs, tree.rhs, operator); 2298 } 2299 } 2300 2301 2302 /** Complete generating code for operation, with left operand 2303 * already on stack. 2304 * @param lhs The tree representing the left operand. 2305 * @param rhs The tree representing the right operand. 2306 * @param operator The operator symbol. 2307 */ 2308 Item completeBinop(JCTree lhs, JCTree rhs, OperatorSymbol operator) { 2309 MethodType optype = (MethodType)operator.type; 2310 int opcode = operator.opcode; 2311 if (opcode >= if_icmpeq && opcode <= if_icmple && 2312 rhs.type.constValue() instanceof Number number && 2313 number.intValue() == 0) { 2314 opcode = opcode + (ifeq - if_icmpeq); 2315 } else if (opcode >= if_acmpeq && opcode <= if_acmpne && 2316 TreeInfo.isNull(rhs)) { 2317 opcode = opcode + (if_acmp_null - if_acmpeq); 2318 } else { 2319 // The expected type of the right operand is 2320 // the second parameter type of the operator, except for 2321 // shifts with long shiftcount, where we convert the opcode 2322 // to a short shift and the expected type to int. 2323 Type rtype = operator.erasure(types).getParameterTypes().tail.head; 2324 if (opcode >= ishll && opcode <= lushrl) { 2325 opcode = opcode + (ishl - ishll); 2326 rtype = syms.intType; 2327 } 2328 // Generate code for right operand and load. 2329 genExpr(rhs, rtype).load(); 2330 // If there are two consecutive opcode instructions, 2331 // emit the first now. 2332 if (opcode >= (1 << preShift)) { 2333 code.emitop0(opcode >> preShift); 2334 opcode = opcode & 0xFF; 2335 } 2336 } 2337 if (opcode >= ifeq && opcode <= if_acmpne || 2338 opcode == if_acmp_null || opcode == if_acmp_nonnull) { 2339 return items.makeCondItem(opcode); 2340 } else { 2341 code.emitop0(opcode); 2342 return items.makeStackItem(optype.restype); 2343 } 2344 } 2345 2346 public void visitTypeCast(JCTypeCast tree) { 2347 result = genExpr(tree.expr, tree.clazz.type).load(); 2348 setTypeAnnotationPositions(tree.pos); 2349 // Additional code is only needed if we cast to a reference type 2350 // which is not statically a supertype of the expression's type. 2351 // For basic types, the coerce(...) in genExpr(...) will do 2352 // the conversion. 2353 if (!tree.clazz.type.isPrimitive() && 2354 !types.isSameType(tree.expr.type, tree.clazz.type) && 2355 types.asSuper(tree.expr.type, tree.clazz.type.tsym) == null) { 2356 code.emitop2(checkcast, checkDimension(tree.pos(), tree.clazz.type), PoolWriter::putClass); 2357 } 2358 } 2359 2360 public void visitWildcard(JCWildcard tree) { 2361 throw new AssertionError(this.getClass().getName()); 2362 } 2363 2364 public void visitTypeTest(JCInstanceOf tree) { 2365 genExpr(tree.expr, tree.expr.type).load(); 2366 setTypeAnnotationPositions(tree.pos); 2367 code.emitop2(instanceof_, makeRef(tree.pos(), tree.pattern.type)); 2368 result = items.makeStackItem(syms.booleanType); 2369 } 2370 2371 public void visitIndexed(JCArrayAccess tree) { 2372 genExpr(tree.indexed, tree.indexed.type).load(); 2373 genExpr(tree.index, syms.intType).load(); 2374 result = items.makeIndexedItem(tree.type); 2375 } 2376 2377 public void visitIdent(JCIdent tree) { 2378 Symbol sym = tree.sym; 2379 if (tree.name == names._this || tree.name == names._super) { 2380 Item res = tree.name == names._this 2381 ? items.makeThisItem() 2382 : items.makeSuperItem(); 2383 if (sym.kind == MTH) { 2384 // Generate code to address the constructor. 2385 res.load(); 2386 res = items.makeMemberItem(sym, true); 2387 } 2388 result = res; 2389 } else if (isInvokeDynamic(sym) || isConstantDynamic(sym)) { 2390 if (isConstantDynamic(sym)) { 2391 setTypeAnnotationPositions(tree.pos); 2392 } 2393 result = items.makeDynamicItem(sym); 2394 } else if (sym.kind == VAR && (sym.owner.kind == MTH || sym.owner.kind == VAR)) { 2395 result = items.makeLocalItem((VarSymbol)sym); 2396 } else if ((sym.flags() & STATIC) != 0) { 2397 if (!isAccessSuper(env.enclMethod)) 2398 sym = binaryQualifier(sym, env.enclClass.type); 2399 result = items.makeStaticItem(sym); 2400 } else { 2401 items.makeThisItem().load(); 2402 sym = binaryQualifier(sym, env.enclClass.type); 2403 result = items.makeMemberItem(sym, nonVirtualForPrivateAccess(sym)); 2404 } 2405 } 2406 2407 //where 2408 private boolean nonVirtualForPrivateAccess(Symbol sym) { 2409 boolean useVirtual = target.hasVirtualPrivateInvoke() && 2410 !disableVirtualizedPrivateInvoke; 2411 return !useVirtual && ((sym.flags() & PRIVATE) != 0); 2412 } 2413 2414 public void visitSelect(JCFieldAccess tree) { 2415 Symbol sym = tree.sym; 2416 2417 if (tree.name == names._class) { 2418 code.emitLdc((LoadableConstant)checkDimension(tree.pos(), tree.selected.type)); 2419 result = items.makeStackItem(pt); 2420 return; 2421 } 2422 2423 Symbol ssym = TreeInfo.symbol(tree.selected); 2424 2425 // Are we selecting via super? 2426 boolean selectSuper = 2427 ssym != null && (ssym.kind == TYP || ssym.name == names._super); 2428 2429 // Are we accessing a member of the superclass in an access method 2430 // resulting from a qualified super? 2431 boolean accessSuper = isAccessSuper(env.enclMethod); 2432 2433 Item base = (selectSuper) 2434 ? items.makeSuperItem() 2435 : genExpr(tree.selected, tree.selected.type); 2436 2437 if (sym.kind == VAR && ((VarSymbol) sym).getConstValue() != null) { 2438 // We are seeing a variable that is constant but its selecting 2439 // expression is not. 2440 if ((sym.flags() & STATIC) != 0) { 2441 if (!selectSuper && (ssym == null || ssym.kind != TYP)) 2442 base = base.load(); 2443 base.drop(); 2444 } else { 2445 base.load(); 2446 genNullCheck(tree.selected); 2447 } 2448 result = items. 2449 makeImmediateItem(sym.type, ((VarSymbol) sym).getConstValue()); 2450 } else { 2451 if (isInvokeDynamic(sym)) { 2452 result = items.makeDynamicItem(sym); 2453 return; 2454 } else { 2455 sym = binaryQualifier(sym, tree.selected.type); 2456 } 2457 if ((sym.flags() & STATIC) != 0) { 2458 if (!selectSuper && (ssym == null || ssym.kind != TYP)) 2459 base = base.load(); 2460 base.drop(); 2461 result = items.makeStaticItem(sym); 2462 } else { 2463 base.load(); 2464 if (sym == syms.lengthVar) { 2465 code.emitop0(arraylength); 2466 result = items.makeStackItem(syms.intType); 2467 } else { 2468 result = items. 2469 makeMemberItem(sym, 2470 nonVirtualForPrivateAccess(sym) || 2471 selectSuper || accessSuper); 2472 } 2473 } 2474 } 2475 } 2476 2477 public boolean isInvokeDynamic(Symbol sym) { 2478 return sym.kind == MTH && ((MethodSymbol)sym).isDynamic(); 2479 } 2480 2481 public void visitLiteral(JCLiteral tree) { 2482 if (tree.type.hasTag(BOT)) { 2483 code.emitop0(aconst_null); 2484 result = items.makeStackItem(tree.type); 2485 } 2486 else 2487 result = items.makeImmediateItem(tree.type, tree.value); 2488 } 2489 2490 public void visitLetExpr(LetExpr tree) { 2491 code.resolvePending(); 2492 2493 int limit = code.nextreg; 2494 int prevLetExprStart = code.setLetExprStackPos(code.state.stacksize); 2495 try { 2496 genStats(tree.defs, env); 2497 } finally { 2498 code.setLetExprStackPos(prevLetExprStart); 2499 } 2500 result = genExpr(tree.expr, tree.expr.type).load(); 2501 code.endScopes(limit); 2502 } 2503 2504 private void generateReferencesToPrunedTree(ClassSymbol classSymbol) { 2505 List<JCTree> prunedInfo = lower.prunedTree.get(classSymbol); 2506 if (prunedInfo != null) { 2507 for (JCTree prunedTree: prunedInfo) { 2508 prunedTree.accept(classReferenceVisitor); 2509 } 2510 } 2511 } 2512 2513 /* ************************************************************************ 2514 * main method 2515 *************************************************************************/ 2516 2517 /** Generate code for a class definition. 2518 * @param env The attribution environment that belongs to the 2519 * outermost class containing this class definition. 2520 * We need this for resolving some additional symbols. 2521 * @param cdef The tree representing the class definition. 2522 * @return True if code is generated with no errors. 2523 */ 2524 public boolean genClass(Env<AttrContext> env, JCClassDecl cdef) { 2525 try { 2526 attrEnv = env; 2527 ClassSymbol c = cdef.sym; 2528 this.toplevel = env.toplevel; 2529 this.endPosTable = toplevel.endPositions; 2530 /* method normalizeDefs() can add references to external classes into the constant pool 2531 */ 2532 cdef.defs = normalizeDefs(cdef.defs, c); 2533 generateReferencesToPrunedTree(c); 2534 Env<GenContext> localEnv = new Env<>(cdef, new GenContext()); 2535 localEnv.toplevel = env.toplevel; 2536 localEnv.enclClass = cdef; 2537 2538 for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) { 2539 genDef(l.head, localEnv); 2540 } 2541 if (poolWriter.size() > PoolWriter.MAX_ENTRIES) { 2542 log.error(cdef.pos(), Errors.LimitPool); 2543 nerrs++; 2544 } 2545 if (nerrs != 0) { 2546 // if errors, discard code 2547 for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) { 2548 if (l.head.hasTag(METHODDEF)) 2549 ((JCMethodDecl) l.head).sym.code = null; 2550 } 2551 } 2552 cdef.defs = List.nil(); // discard trees 2553 return nerrs == 0; 2554 } finally { 2555 // note: this method does NOT support recursion. 2556 attrEnv = null; 2557 this.env = null; 2558 toplevel = null; 2559 endPosTable = null; 2560 nerrs = 0; 2561 qualifiedSymbolCache.clear(); 2562 } 2563 } 2564 2565 /* ************************************************************************ 2566 * Auxiliary classes 2567 *************************************************************************/ 2568 2569 /** An abstract class for finalizer generation. 2570 */ 2571 abstract class GenFinalizer { 2572 /** Generate code to clean up when unwinding. */ 2573 abstract void gen(); 2574 2575 /** Generate code to clean up at last. */ 2576 abstract void genLast(); 2577 2578 /** Does this finalizer have some nontrivial cleanup to perform? */ 2579 boolean hasFinalizer() { return true; } 2580 2581 /** Should be invoked after the try's body has been visited. */ 2582 void afterBody() {} 2583 } 2584 2585 /** code generation contexts, 2586 * to be used as type parameter for environments. 2587 */ 2588 static class GenContext { 2589 2590 /** A chain for all unresolved jumps that exit the current environment. 2591 */ 2592 Chain exit = null; 2593 2594 /** A chain for all unresolved jumps that continue in the 2595 * current environment. 2596 */ 2597 Chain cont = null; 2598 2599 /** A closure that generates the finalizer of the current environment. 2600 * Only set for Synchronized and Try contexts. 2601 */ 2602 GenFinalizer finalize = null; 2603 2604 /** Is this a switch statement? If so, allocate registers 2605 * even when the variable declaration is unreachable. 2606 */ 2607 boolean isSwitch = false; 2608 2609 /** A list buffer containing all gaps in the finalizer range, 2610 * where a catch all exception should not apply. 2611 */ 2612 ListBuffer<Integer> gaps = null; 2613 2614 /** Add given chain to exit chain. 2615 */ 2616 void addExit(Chain c) { 2617 exit = Code.mergeChains(c, exit); 2618 } 2619 2620 /** Add given chain to cont chain. 2621 */ 2622 void addCont(Chain c) { 2623 cont = Code.mergeChains(c, cont); 2624 } 2625 } 2626 2627 record PatternMatchingCatchConfiguration(Set<JCMethodInvocation> invocations, 2628 ListBuffer<int[]> ranges, 2629 JCCatch handler, 2630 State startState) { 2631 public PatternMatchingCatchConfiguration restart(State newState) { 2632 return new PatternMatchingCatchConfiguration(invocations(), 2633 new ListBuffer<int[]>(), 2634 handler(), 2635 newState); 2636 } 2637 } 2638 }