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