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