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