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