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