src/share/classes/com/sun/tools/javac/jvm/Gen.java

Wed, 23 Jan 2013 13:27:24 -0800

author
jjg
date
Wed, 23 Jan 2013 13:27:24 -0800
changeset 1521
71f35e4b93a5
parent 1452
de1ec6fc93fe
child 1555
762d0af062f5
permissions
-rw-r--r--

8006775: JSR 308: Compiler changes in JDK8
Reviewed-by: jjg
Contributed-by: mernst@cs.washington.edu, wmdietl@cs.washington.edu, mpapi@csail.mit.edu, mahmood@notnoop.com

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

mercurial