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