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