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

Sun, 17 Feb 2013 16:44:55 -0500

author
dholmes
date
Sun, 17 Feb 2013 16:44:55 -0500
changeset 1571
af8417e590f4
parent 1555
762d0af062f5
child 1670
29c6984a1673
permissions
-rw-r--r--

Merge

     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 | (c.flags() & STRICTFP),
   517                 names.clinit,
   518                 new MethodType(
   519                     List.<Type>nil(), syms.voidType,
   520                     List.<Type>nil(), syms.methodClass),
   521                 c);
   522             c.members().enter(clinit);
   523             List<JCStatement> clinitStats = clinitCode.toList();
   524             JCBlock block = make.at(clinitStats.head.pos()).Block(0, clinitStats);
   525             block.endpos = TreeInfo.endPos(clinitStats.last());
   526             methodDefs.append(make.MethodDef(clinit, block));
   527         }
   528         // Return all method definitions.
   529         return methodDefs.toList();
   530     }
   532     /** Check a constant value and report if it is a string that is
   533      *  too large.
   534      */
   535     private void checkStringConstant(DiagnosticPosition pos, Object constValue) {
   536         if (nerrs != 0 || // only complain about a long string once
   537             constValue == null ||
   538             !(constValue instanceof String) ||
   539             ((String)constValue).length() < Pool.MAX_STRING_LENGTH)
   540             return;
   541         log.error(pos, "limit.string");
   542         nerrs++;
   543     }
   545     /** Insert instance initializer code into initial constructor.
   546      *  @param md        The tree potentially representing a
   547      *                   constructor's definition.
   548      *  @param initCode  The list of instance initializer statements.
   549      */
   550     void normalizeMethod(JCMethodDecl md, List<JCStatement> initCode) {
   551         if (md.name == names.init && TreeInfo.isInitialConstructor(md)) {
   552             // We are seeing a constructor that does not call another
   553             // constructor of the same class.
   554             List<JCStatement> stats = md.body.stats;
   555             ListBuffer<JCStatement> newstats = new ListBuffer<JCStatement>();
   557             if (stats.nonEmpty()) {
   558                 // Copy initializers of synthetic variables generated in
   559                 // the translation of inner classes.
   560                 while (TreeInfo.isSyntheticInit(stats.head)) {
   561                     newstats.append(stats.head);
   562                     stats = stats.tail;
   563                 }
   564                 // Copy superclass constructor call
   565                 newstats.append(stats.head);
   566                 stats = stats.tail;
   567                 // Copy remaining synthetic initializers.
   568                 while (stats.nonEmpty() &&
   569                        TreeInfo.isSyntheticInit(stats.head)) {
   570                     newstats.append(stats.head);
   571                     stats = stats.tail;
   572                 }
   573                 // Now insert the initializer code.
   574                 newstats.appendList(initCode);
   575                 // And copy all remaining statements.
   576                 while (stats.nonEmpty()) {
   577                     newstats.append(stats.head);
   578                     stats = stats.tail;
   579                 }
   580             }
   581             md.body.stats = newstats.toList();
   582             if (md.body.endpos == Position.NOPOS)
   583                 md.body.endpos = TreeInfo.endPos(md.body.stats.last());
   584         }
   585     }
   587 /* ********************************************************************
   588  * Adding miranda methods
   589  *********************************************************************/
   591     /** Add abstract methods for all methods defined in one of
   592      *  the interfaces of a given class,
   593      *  provided they are not already implemented in the class.
   594      *
   595      *  @param c      The class whose interfaces are searched for methods
   596      *                for which Miranda methods should be added.
   597      */
   598     void implementInterfaceMethods(ClassSymbol c) {
   599         implementInterfaceMethods(c, c);
   600     }
   602     /** Add abstract methods for all methods defined in one of
   603      *  the interfaces of a given class,
   604      *  provided they are not already implemented in the class.
   605      *
   606      *  @param c      The class whose interfaces are searched for methods
   607      *                for which Miranda methods should be added.
   608      *  @param site   The class in which a definition may be needed.
   609      */
   610     void implementInterfaceMethods(ClassSymbol c, ClassSymbol site) {
   611         for (List<Type> l = types.interfaces(c.type); l.nonEmpty(); l = l.tail) {
   612             ClassSymbol i = (ClassSymbol)l.head.tsym;
   613             for (Scope.Entry e = i.members().elems;
   614                  e != null;
   615                  e = e.sibling)
   616             {
   617                 if (e.sym.kind == MTH && (e.sym.flags() & STATIC) == 0)
   618                 {
   619                     MethodSymbol absMeth = (MethodSymbol)e.sym;
   620                     MethodSymbol implMeth = absMeth.binaryImplementation(site, types);
   621                     if (implMeth == null)
   622                         addAbstractMethod(site, absMeth);
   623                     else if ((implMeth.flags() & IPROXY) != 0)
   624                         adjustAbstractMethod(site, implMeth, absMeth);
   625                 }
   626             }
   627             implementInterfaceMethods(i, site);
   628         }
   629     }
   631     /** Add an abstract methods to a class
   632      *  which implicitly implements a method defined in some interface
   633      *  implemented by the class. These methods are called "Miranda methods".
   634      *  Enter the newly created method into its enclosing class scope.
   635      *  Note that it is not entered into the class tree, as the emitter
   636      *  doesn't need to see it there to emit an abstract method.
   637      *
   638      *  @param c      The class to which the Miranda method is added.
   639      *  @param m      The interface method symbol for which a Miranda method
   640      *                is added.
   641      */
   642     private void addAbstractMethod(ClassSymbol c,
   643                                    MethodSymbol m) {
   644         MethodSymbol absMeth = new MethodSymbol(
   645             m.flags() | IPROXY | SYNTHETIC, m.name,
   646             m.type, // was c.type.memberType(m), but now only !generics supported
   647             c);
   648         c.members().enter(absMeth); // add to symbol table
   649     }
   651     private void adjustAbstractMethod(ClassSymbol c,
   652                                       MethodSymbol pm,
   653                                       MethodSymbol im) {
   654         MethodType pmt = (MethodType)pm.type;
   655         Type imt = types.memberType(c.type, im);
   656         pmt.thrown = chk.intersect(pmt.getThrownTypes(), imt.getThrownTypes());
   657     }
   659 /* ************************************************************************
   660  * Traversal methods
   661  *************************************************************************/
   663     /** Visitor argument: The current environment.
   664      */
   665     Env<GenContext> env;
   667     /** Visitor argument: The expected type (prototype).
   668      */
   669     Type pt;
   671     /** Visitor result: The item representing the computed value.
   672      */
   673     Item result;
   675     /** Visitor method: generate code for a definition, catching and reporting
   676      *  any completion failures.
   677      *  @param tree    The definition to be visited.
   678      *  @param env     The environment current at the definition.
   679      */
   680     public void genDef(JCTree tree, Env<GenContext> env) {
   681         Env<GenContext> prevEnv = this.env;
   682         try {
   683             this.env = env;
   684             tree.accept(this);
   685         } catch (CompletionFailure ex) {
   686             chk.completionError(tree.pos(), ex);
   687         } finally {
   688             this.env = prevEnv;
   689         }
   690     }
   692     /** Derived visitor method: check whether CharacterRangeTable
   693      *  should be emitted, if so, put a new entry into CRTable
   694      *  and call method to generate bytecode.
   695      *  If not, just call method to generate bytecode.
   696      *  @see    #genStat(JCTree, Env)
   697      *
   698      *  @param  tree     The tree to be visited.
   699      *  @param  env      The environment to use.
   700      *  @param  crtFlags The CharacterRangeTable flags
   701      *                   indicating type of the entry.
   702      */
   703     public void genStat(JCTree tree, Env<GenContext> env, int crtFlags) {
   704         if (!genCrt) {
   705             genStat(tree, env);
   706             return;
   707         }
   708         int startpc = code.curPc();
   709         genStat(tree, env);
   710         if (tree.hasTag(Tag.BLOCK)) crtFlags |= CRT_BLOCK;
   711         code.crt.put(tree, crtFlags, startpc, code.curPc());
   712     }
   714     /** Derived visitor method: generate code for a statement.
   715      */
   716     public void genStat(JCTree tree, Env<GenContext> env) {
   717         if (code.isAlive()) {
   718             code.statBegin(tree.pos);
   719             genDef(tree, env);
   720         } else if (env.info.isSwitch && tree.hasTag(VARDEF)) {
   721             // variables whose declarations are in a switch
   722             // can be used even if the decl is unreachable.
   723             code.newLocal(((JCVariableDecl) tree).sym);
   724         }
   725     }
   727     /** Derived visitor method: check whether CharacterRangeTable
   728      *  should be emitted, if so, put a new entry into CRTable
   729      *  and call method to generate bytecode.
   730      *  If not, just call method to generate bytecode.
   731      *  @see    #genStats(List, Env)
   732      *
   733      *  @param  trees    The list of trees to be visited.
   734      *  @param  env      The environment to use.
   735      *  @param  crtFlags The CharacterRangeTable flags
   736      *                   indicating type of the entry.
   737      */
   738     public void genStats(List<JCStatement> trees, Env<GenContext> env, int crtFlags) {
   739         if (!genCrt) {
   740             genStats(trees, env);
   741             return;
   742         }
   743         if (trees.length() == 1) {        // mark one statement with the flags
   744             genStat(trees.head, env, crtFlags | CRT_STATEMENT);
   745         } else {
   746             int startpc = code.curPc();
   747             genStats(trees, env);
   748             code.crt.put(trees, crtFlags, startpc, code.curPc());
   749         }
   750     }
   752     /** Derived visitor method: generate code for a list of statements.
   753      */
   754     public void genStats(List<? extends JCTree> trees, Env<GenContext> env) {
   755         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
   756             genStat(l.head, env, CRT_STATEMENT);
   757     }
   759     /** Derived visitor method: check whether CharacterRangeTable
   760      *  should be emitted, if so, put a new entry into CRTable
   761      *  and call method to generate bytecode.
   762      *  If not, just call method to generate bytecode.
   763      *  @see    #genCond(JCTree,boolean)
   764      *
   765      *  @param  tree     The tree to be visited.
   766      *  @param  crtFlags The CharacterRangeTable flags
   767      *                   indicating type of the entry.
   768      */
   769     public CondItem genCond(JCTree tree, int crtFlags) {
   770         if (!genCrt) return genCond(tree, false);
   771         int startpc = code.curPc();
   772         CondItem item = genCond(tree, (crtFlags & CRT_FLOW_CONTROLLER) != 0);
   773         code.crt.put(tree, crtFlags, startpc, code.curPc());
   774         return item;
   775     }
   777     /** Derived visitor method: generate code for a boolean
   778      *  expression in a control-flow context.
   779      *  @param _tree         The expression to be visited.
   780      *  @param markBranches The flag to indicate that the condition is
   781      *                      a flow controller so produced conditions
   782      *                      should contain a proper tree to generate
   783      *                      CharacterRangeTable branches for them.
   784      */
   785     public CondItem genCond(JCTree _tree, boolean markBranches) {
   786         JCTree inner_tree = TreeInfo.skipParens(_tree);
   787         if (inner_tree.hasTag(CONDEXPR)) {
   788             JCConditional tree = (JCConditional)inner_tree;
   789             CondItem cond = genCond(tree.cond, CRT_FLOW_CONTROLLER);
   790             if (cond.isTrue()) {
   791                 code.resolve(cond.trueJumps);
   792                 CondItem result = genCond(tree.truepart, CRT_FLOW_TARGET);
   793                 if (markBranches) result.tree = tree.truepart;
   794                 return result;
   795             }
   796             if (cond.isFalse()) {
   797                 code.resolve(cond.falseJumps);
   798                 CondItem result = genCond(tree.falsepart, CRT_FLOW_TARGET);
   799                 if (markBranches) result.tree = tree.falsepart;
   800                 return result;
   801             }
   802             Chain secondJumps = cond.jumpFalse();
   803             code.resolve(cond.trueJumps);
   804             CondItem first = genCond(tree.truepart, CRT_FLOW_TARGET);
   805             if (markBranches) first.tree = tree.truepart;
   806             Chain falseJumps = first.jumpFalse();
   807             code.resolve(first.trueJumps);
   808             Chain trueJumps = code.branch(goto_);
   809             code.resolve(secondJumps);
   810             CondItem second = genCond(tree.falsepart, CRT_FLOW_TARGET);
   811             CondItem result = items.makeCondItem(second.opcode,
   812                                       Code.mergeChains(trueJumps, second.trueJumps),
   813                                       Code.mergeChains(falseJumps, second.falseJumps));
   814             if (markBranches) result.tree = tree.falsepart;
   815             return result;
   816         } else {
   817             CondItem result = genExpr(_tree, syms.booleanType).mkCond();
   818             if (markBranches) result.tree = _tree;
   819             return result;
   820         }
   821     }
   823     /** Visitor class for expressions which might be constant expressions.
   824      *  This class is a subset of TreeScanner. Intended to visit trees pruned by
   825      *  Lower as long as constant expressions looking for references to any
   826      *  ClassSymbol. Any such reference will be added to the constant pool so
   827      *  automated tools can detect class dependencies better.
   828      */
   829     class ClassReferenceVisitor extends JCTree.Visitor {
   831         @Override
   832         public void visitTree(JCTree tree) {}
   834         @Override
   835         public void visitBinary(JCBinary tree) {
   836             tree.lhs.accept(this);
   837             tree.rhs.accept(this);
   838         }
   840         @Override
   841         public void visitSelect(JCFieldAccess tree) {
   842             if (tree.selected.type.hasTag(CLASS)) {
   843                 makeRef(tree.selected.pos(), tree.selected.type);
   844             }
   845         }
   847         @Override
   848         public void visitIdent(JCIdent tree) {
   849             if (tree.sym.owner instanceof ClassSymbol) {
   850                 pool.put(tree.sym.owner);
   851             }
   852         }
   854         @Override
   855         public void visitConditional(JCConditional tree) {
   856             tree.cond.accept(this);
   857             tree.truepart.accept(this);
   858             tree.falsepart.accept(this);
   859         }
   861         @Override
   862         public void visitUnary(JCUnary tree) {
   863             tree.arg.accept(this);
   864         }
   866         @Override
   867         public void visitParens(JCParens tree) {
   868             tree.expr.accept(this);
   869         }
   871         @Override
   872         public void visitTypeCast(JCTypeCast tree) {
   873             tree.expr.accept(this);
   874         }
   875     }
   877     private ClassReferenceVisitor classReferenceVisitor = new ClassReferenceVisitor();
   879     /** Visitor method: generate code for an expression, catching and reporting
   880      *  any completion failures.
   881      *  @param tree    The expression to be visited.
   882      *  @param pt      The expression's expected type (proto-type).
   883      */
   884     public Item genExpr(JCTree tree, Type pt) {
   885         Type prevPt = this.pt;
   886         try {
   887             if (tree.type.constValue() != null) {
   888                 // Short circuit any expressions which are constants
   889                 tree.accept(classReferenceVisitor);
   890                 checkStringConstant(tree.pos(), tree.type.constValue());
   891                 result = items.makeImmediateItem(tree.type, tree.type.constValue());
   892             } else {
   893                 this.pt = pt;
   894                 tree.accept(this);
   895             }
   896             return result.coerce(pt);
   897         } catch (CompletionFailure ex) {
   898             chk.completionError(tree.pos(), ex);
   899             code.state.stacksize = 1;
   900             return items.makeStackItem(pt);
   901         } finally {
   902             this.pt = prevPt;
   903         }
   904     }
   906     /** Derived visitor method: generate code for a list of method arguments.
   907      *  @param trees    The argument expressions to be visited.
   908      *  @param pts      The expression's expected types (i.e. the formal parameter
   909      *                  types of the invoked method).
   910      */
   911     public void genArgs(List<JCExpression> trees, List<Type> pts) {
   912         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) {
   913             genExpr(l.head, pts.head).load();
   914             pts = pts.tail;
   915         }
   916         // require lists be of same length
   917         Assert.check(pts.isEmpty());
   918     }
   920 /* ************************************************************************
   921  * Visitor methods for statements and definitions
   922  *************************************************************************/
   924     /** Thrown when the byte code size exceeds limit.
   925      */
   926     public static class CodeSizeOverflow extends RuntimeException {
   927         private static final long serialVersionUID = 0;
   928         public CodeSizeOverflow() {}
   929     }
   931     public void visitMethodDef(JCMethodDecl tree) {
   932         // Create a new local environment that points pack at method
   933         // definition.
   934         Env<GenContext> localEnv = env.dup(tree);
   935         localEnv.enclMethod = tree;
   937         // The expected type of every return statement in this method
   938         // is the method's return type.
   939         this.pt = tree.sym.erasure(types).getReturnType();
   941         checkDimension(tree.pos(), tree.sym.erasure(types));
   942         genMethod(tree, localEnv, false);
   943     }
   944 //where
   945         /** Generate code for a method.
   946          *  @param tree     The tree representing the method definition.
   947          *  @param env      The environment current for the method body.
   948          *  @param fatcode  A flag that indicates whether all jumps are
   949          *                  within 32K.  We first invoke this method under
   950          *                  the assumption that fatcode == false, i.e. all
   951          *                  jumps are within 32K.  If this fails, fatcode
   952          *                  is set to true and we try again.
   953          */
   954         void genMethod(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) {
   955             MethodSymbol meth = tree.sym;
   956 //      System.err.println("Generating " + meth + " in " + meth.owner); //DEBUG
   957             if (Code.width(types.erasure(env.enclMethod.sym.type).getParameterTypes())  +
   958                 (((tree.mods.flags & STATIC) == 0 || meth.isConstructor()) ? 1 : 0) >
   959                 ClassFile.MAX_PARAMETERS) {
   960                 log.error(tree.pos(), "limit.parameters");
   961                 nerrs++;
   962             }
   964             else if (tree.body != null) {
   965                 // Create a new code structure and initialize it.
   966                 int startpcCrt = initCode(tree, env, fatcode);
   968                 try {
   969                     genStat(tree.body, env);
   970                 } catch (CodeSizeOverflow e) {
   971                     // Failed due to code limit, try again with jsr/ret
   972                     startpcCrt = initCode(tree, env, fatcode);
   973                     genStat(tree.body, env);
   974                 }
   976                 if (code.state.stacksize != 0) {
   977                     log.error(tree.body.pos(), "stack.sim.error", tree);
   978                     throw new AssertionError();
   979                 }
   981                 // If last statement could complete normally, insert a
   982                 // return at the end.
   983                 if (code.isAlive()) {
   984                     code.statBegin(TreeInfo.endPos(tree.body));
   985                     if (env.enclMethod == null ||
   986                         env.enclMethod.sym.type.getReturnType().hasTag(VOID)) {
   987                         code.emitop0(return_);
   988                     } else {
   989                         // sometime dead code seems alive (4415991);
   990                         // generate a small loop instead
   991                         int startpc = code.entryPoint();
   992                         CondItem c = items.makeCondItem(goto_);
   993                         code.resolve(c.jumpTrue(), startpc);
   994                     }
   995                 }
   996                 if (genCrt)
   997                     code.crt.put(tree.body,
   998                                  CRT_BLOCK,
   999                                  startpcCrt,
  1000                                  code.curPc());
  1002                 code.endScopes(0);
  1004                 // If we exceeded limits, panic
  1005                 if (code.checkLimits(tree.pos(), log)) {
  1006                     nerrs++;
  1007                     return;
  1010                 // If we generated short code but got a long jump, do it again
  1011                 // with fatCode = true.
  1012                 if (!fatcode && code.fatcode) genMethod(tree, env, true);
  1014                 // Clean up
  1015                 if(stackMap == StackMapFormat.JSR202) {
  1016                     code.lastFrame = null;
  1017                     code.frameBeforeLast = null;
  1020                 // Compress exception table
  1021                 code.compressCatchTable();
  1023                 // Fill in type annotation positions for exception parameters
  1024                 code.fillExceptionParameterPositions();
  1028         private int initCode(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) {
  1029             MethodSymbol meth = tree.sym;
  1031             // Create a new code structure.
  1032             meth.code = code = new Code(meth,
  1033                                         fatcode,
  1034                                         lineDebugInfo ? toplevel.lineMap : null,
  1035                                         varDebugInfo,
  1036                                         stackMap,
  1037                                         debugCode,
  1038                                         genCrt ? new CRTable(tree, env.toplevel.endPositions)
  1039                                                : null,
  1040                                         syms,
  1041                                         types,
  1042                                         pool);
  1043             items = new Items(pool, code, syms, types);
  1044             if (code.debugCode)
  1045                 System.err.println(meth + " for body " + tree);
  1047             // If method is not static, create a new local variable address
  1048             // for `this'.
  1049             if ((tree.mods.flags & STATIC) == 0) {
  1050                 Type selfType = meth.owner.type;
  1051                 if (meth.isConstructor() && selfType != syms.objectType)
  1052                     selfType = UninitializedType.uninitializedThis(selfType);
  1053                 code.setDefined(
  1054                         code.newLocal(
  1055                             new VarSymbol(FINAL, names._this, selfType, meth.owner)));
  1058             // Mark all parameters as defined from the beginning of
  1059             // the method.
  1060             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
  1061                 checkDimension(l.head.pos(), l.head.sym.type);
  1062                 code.setDefined(code.newLocal(l.head.sym));
  1065             // Get ready to generate code for method body.
  1066             int startpcCrt = genCrt ? code.curPc() : 0;
  1067             code.entryPoint();
  1069             // Suppress initial stackmap
  1070             code.pendingStackMap = false;
  1072             return startpcCrt;
  1075     public void visitVarDef(JCVariableDecl tree) {
  1076         VarSymbol v = tree.sym;
  1077         code.newLocal(v);
  1078         if (tree.init != null) {
  1079             checkStringConstant(tree.init.pos(), v.getConstValue());
  1080             if (v.getConstValue() == null || varDebugInfo) {
  1081                 genExpr(tree.init, v.erasure(types)).load();
  1082                 items.makeLocalItem(v).store();
  1085         checkDimension(tree.pos(), v.type);
  1088     public void visitSkip(JCSkip tree) {
  1091     public void visitBlock(JCBlock tree) {
  1092         int limit = code.nextreg;
  1093         Env<GenContext> localEnv = env.dup(tree, new GenContext());
  1094         genStats(tree.stats, localEnv);
  1095         // End the scope of all block-local variables in variable info.
  1096         if (!env.tree.hasTag(METHODDEF)) {
  1097             code.statBegin(tree.endpos);
  1098             code.endScopes(limit);
  1099             code.pendingStatPos = Position.NOPOS;
  1103     public void visitDoLoop(JCDoWhileLoop tree) {
  1104         genLoop(tree, tree.body, tree.cond, List.<JCExpressionStatement>nil(), false);
  1107     public void visitWhileLoop(JCWhileLoop tree) {
  1108         genLoop(tree, tree.body, tree.cond, List.<JCExpressionStatement>nil(), true);
  1111     public void visitForLoop(JCForLoop tree) {
  1112         int limit = code.nextreg;
  1113         genStats(tree.init, env);
  1114         genLoop(tree, tree.body, tree.cond, tree.step, true);
  1115         code.endScopes(limit);
  1117     //where
  1118         /** Generate code for a loop.
  1119          *  @param loop       The tree representing the loop.
  1120          *  @param body       The loop's body.
  1121          *  @param cond       The loop's controling condition.
  1122          *  @param step       "Step" statements to be inserted at end of
  1123          *                    each iteration.
  1124          *  @param testFirst  True if the loop test belongs before the body.
  1125          */
  1126         private void genLoop(JCStatement loop,
  1127                              JCStatement body,
  1128                              JCExpression cond,
  1129                              List<JCExpressionStatement> step,
  1130                              boolean testFirst) {
  1131             Env<GenContext> loopEnv = env.dup(loop, new GenContext());
  1132             int startpc = code.entryPoint();
  1133             if (testFirst) {
  1134                 CondItem c;
  1135                 if (cond != null) {
  1136                     code.statBegin(cond.pos);
  1137                     c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER);
  1138                 } else {
  1139                     c = items.makeCondItem(goto_);
  1141                 Chain loopDone = c.jumpFalse();
  1142                 code.resolve(c.trueJumps);
  1143                 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET);
  1144                 code.resolve(loopEnv.info.cont);
  1145                 genStats(step, loopEnv);
  1146                 code.resolve(code.branch(goto_), startpc);
  1147                 code.resolve(loopDone);
  1148             } else {
  1149                 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET);
  1150                 code.resolve(loopEnv.info.cont);
  1151                 genStats(step, loopEnv);
  1152                 CondItem c;
  1153                 if (cond != null) {
  1154                     code.statBegin(cond.pos);
  1155                     c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER);
  1156                 } else {
  1157                     c = items.makeCondItem(goto_);
  1159                 code.resolve(c.jumpTrue(), startpc);
  1160                 code.resolve(c.falseJumps);
  1162             code.resolve(loopEnv.info.exit);
  1165     public void visitForeachLoop(JCEnhancedForLoop tree) {
  1166         throw new AssertionError(); // should have been removed by Lower.
  1169     public void visitLabelled(JCLabeledStatement tree) {
  1170         Env<GenContext> localEnv = env.dup(tree, new GenContext());
  1171         genStat(tree.body, localEnv, CRT_STATEMENT);
  1172         code.resolve(localEnv.info.exit);
  1175     public void visitSwitch(JCSwitch tree) {
  1176         int limit = code.nextreg;
  1177         Assert.check(!tree.selector.type.hasTag(CLASS));
  1178         int startpcCrt = genCrt ? code.curPc() : 0;
  1179         Item sel = genExpr(tree.selector, syms.intType);
  1180         List<JCCase> cases = tree.cases;
  1181         if (cases.isEmpty()) {
  1182             // We are seeing:  switch <sel> {}
  1183             sel.load().drop();
  1184             if (genCrt)
  1185                 code.crt.put(TreeInfo.skipParens(tree.selector),
  1186                              CRT_FLOW_CONTROLLER, startpcCrt, code.curPc());
  1187         } else {
  1188             // We are seeing a nonempty switch.
  1189             sel.load();
  1190             if (genCrt)
  1191                 code.crt.put(TreeInfo.skipParens(tree.selector),
  1192                              CRT_FLOW_CONTROLLER, startpcCrt, code.curPc());
  1193             Env<GenContext> switchEnv = env.dup(tree, new GenContext());
  1194             switchEnv.info.isSwitch = true;
  1196             // Compute number of labels and minimum and maximum label values.
  1197             // For each case, store its label in an array.
  1198             int lo = Integer.MAX_VALUE;  // minimum label.
  1199             int hi = Integer.MIN_VALUE;  // maximum label.
  1200             int nlabels = 0;               // number of labels.
  1202             int[] labels = new int[cases.length()];  // the label array.
  1203             int defaultIndex = -1;     // the index of the default clause.
  1205             List<JCCase> l = cases;
  1206             for (int i = 0; i < labels.length; i++) {
  1207                 if (l.head.pat != null) {
  1208                     int val = ((Number)l.head.pat.type.constValue()).intValue();
  1209                     labels[i] = val;
  1210                     if (val < lo) lo = val;
  1211                     if (hi < val) hi = val;
  1212                     nlabels++;
  1213                 } else {
  1214                     Assert.check(defaultIndex == -1);
  1215                     defaultIndex = i;
  1217                 l = l.tail;
  1220             // Determine whether to issue a tableswitch or a lookupswitch
  1221             // instruction.
  1222             long table_space_cost = 4 + ((long) hi - lo + 1); // words
  1223             long table_time_cost = 3; // comparisons
  1224             long lookup_space_cost = 3 + 2 * (long) nlabels;
  1225             long lookup_time_cost = nlabels;
  1226             int opcode =
  1227                 nlabels > 0 &&
  1228                 table_space_cost + 3 * table_time_cost <=
  1229                 lookup_space_cost + 3 * lookup_time_cost
  1231                 tableswitch : lookupswitch;
  1233             int startpc = code.curPc();    // the position of the selector operation
  1234             code.emitop0(opcode);
  1235             code.align(4);
  1236             int tableBase = code.curPc();  // the start of the jump table
  1237             int[] offsets = null;          // a table of offsets for a lookupswitch
  1238             code.emit4(-1);                // leave space for default offset
  1239             if (opcode == tableswitch) {
  1240                 code.emit4(lo);            // minimum label
  1241                 code.emit4(hi);            // maximum label
  1242                 for (long i = lo; i <= hi; i++) {  // leave space for jump table
  1243                     code.emit4(-1);
  1245             } else {
  1246                 code.emit4(nlabels);    // number of labels
  1247                 for (int i = 0; i < nlabels; i++) {
  1248                     code.emit4(-1); code.emit4(-1); // leave space for lookup table
  1250                 offsets = new int[labels.length];
  1252             Code.State stateSwitch = code.state.dup();
  1253             code.markDead();
  1255             // For each case do:
  1256             l = cases;
  1257             for (int i = 0; i < labels.length; i++) {
  1258                 JCCase c = l.head;
  1259                 l = l.tail;
  1261                 int pc = code.entryPoint(stateSwitch);
  1262                 // Insert offset directly into code or else into the
  1263                 // offsets table.
  1264                 if (i != defaultIndex) {
  1265                     if (opcode == tableswitch) {
  1266                         code.put4(
  1267                             tableBase + 4 * (labels[i] - lo + 3),
  1268                             pc - startpc);
  1269                     } else {
  1270                         offsets[i] = pc - startpc;
  1272                 } else {
  1273                     code.put4(tableBase, pc - startpc);
  1276                 // Generate code for the statements in this case.
  1277                 genStats(c.stats, switchEnv, CRT_FLOW_TARGET);
  1280             // Resolve all breaks.
  1281             code.resolve(switchEnv.info.exit);
  1283             // If we have not set the default offset, we do so now.
  1284             if (code.get4(tableBase) == -1) {
  1285                 code.put4(tableBase, code.entryPoint(stateSwitch) - startpc);
  1288             if (opcode == tableswitch) {
  1289                 // Let any unfilled slots point to the default case.
  1290                 int defaultOffset = code.get4(tableBase);
  1291                 for (long i = lo; i <= hi; i++) {
  1292                     int t = (int)(tableBase + 4 * (i - lo + 3));
  1293                     if (code.get4(t) == -1)
  1294                         code.put4(t, defaultOffset);
  1296             } else {
  1297                 // Sort non-default offsets and copy into lookup table.
  1298                 if (defaultIndex >= 0)
  1299                     for (int i = defaultIndex; i < labels.length - 1; i++) {
  1300                         labels[i] = labels[i+1];
  1301                         offsets[i] = offsets[i+1];
  1303                 if (nlabels > 0)
  1304                     qsort2(labels, offsets, 0, nlabels - 1);
  1305                 for (int i = 0; i < nlabels; i++) {
  1306                     int caseidx = tableBase + 8 * (i + 1);
  1307                     code.put4(caseidx, labels[i]);
  1308                     code.put4(caseidx + 4, offsets[i]);
  1312         code.endScopes(limit);
  1314 //where
  1315         /** Sort (int) arrays of keys and values
  1316          */
  1317        static void qsort2(int[] keys, int[] values, int lo, int hi) {
  1318             int i = lo;
  1319             int j = hi;
  1320             int pivot = keys[(i+j)/2];
  1321             do {
  1322                 while (keys[i] < pivot) i++;
  1323                 while (pivot < keys[j]) j--;
  1324                 if (i <= j) {
  1325                     int temp1 = keys[i];
  1326                     keys[i] = keys[j];
  1327                     keys[j] = temp1;
  1328                     int temp2 = values[i];
  1329                     values[i] = values[j];
  1330                     values[j] = temp2;
  1331                     i++;
  1332                     j--;
  1334             } while (i <= j);
  1335             if (lo < j) qsort2(keys, values, lo, j);
  1336             if (i < hi) qsort2(keys, values, i, hi);
  1339     public void visitSynchronized(JCSynchronized tree) {
  1340         int limit = code.nextreg;
  1341         // Generate code to evaluate lock and save in temporary variable.
  1342         final LocalItem lockVar = makeTemp(syms.objectType);
  1343         genExpr(tree.lock, tree.lock.type).load().duplicate();
  1344         lockVar.store();
  1346         // Generate code to enter monitor.
  1347         code.emitop0(monitorenter);
  1348         code.state.lock(lockVar.reg);
  1350         // Generate code for a try statement with given body, no catch clauses
  1351         // in a new environment with the "exit-monitor" operation as finalizer.
  1352         final Env<GenContext> syncEnv = env.dup(tree, new GenContext());
  1353         syncEnv.info.finalize = new GenFinalizer() {
  1354             void gen() {
  1355                 genLast();
  1356                 Assert.check(syncEnv.info.gaps.length() % 2 == 0);
  1357                 syncEnv.info.gaps.append(code.curPc());
  1359             void genLast() {
  1360                 if (code.isAlive()) {
  1361                     lockVar.load();
  1362                     code.emitop0(monitorexit);
  1363                     code.state.unlock(lockVar.reg);
  1366         };
  1367         syncEnv.info.gaps = new ListBuffer<Integer>();
  1368         genTry(tree.body, List.<JCCatch>nil(), syncEnv);
  1369         code.endScopes(limit);
  1372     public void visitTry(final JCTry tree) {
  1373         // Generate code for a try statement with given body and catch clauses,
  1374         // in a new environment which calls the finally block if there is one.
  1375         final Env<GenContext> tryEnv = env.dup(tree, new GenContext());
  1376         final Env<GenContext> oldEnv = env;
  1377         if (!useJsrLocally) {
  1378             useJsrLocally =
  1379                 (stackMap == StackMapFormat.NONE) &&
  1380                 (jsrlimit <= 0 ||
  1381                 jsrlimit < 100 &&
  1382                 estimateCodeComplexity(tree.finalizer)>jsrlimit);
  1384         tryEnv.info.finalize = new GenFinalizer() {
  1385             void gen() {
  1386                 if (useJsrLocally) {
  1387                     if (tree.finalizer != null) {
  1388                         Code.State jsrState = code.state.dup();
  1389                         jsrState.push(Code.jsrReturnValue);
  1390                         tryEnv.info.cont =
  1391                             new Chain(code.emitJump(jsr),
  1392                                       tryEnv.info.cont,
  1393                                       jsrState);
  1395                     Assert.check(tryEnv.info.gaps.length() % 2 == 0);
  1396                     tryEnv.info.gaps.append(code.curPc());
  1397                 } else {
  1398                     Assert.check(tryEnv.info.gaps.length() % 2 == 0);
  1399                     tryEnv.info.gaps.append(code.curPc());
  1400                     genLast();
  1403             void genLast() {
  1404                 if (tree.finalizer != null)
  1405                     genStat(tree.finalizer, oldEnv, CRT_BLOCK);
  1407             boolean hasFinalizer() {
  1408                 return tree.finalizer != null;
  1410         };
  1411         tryEnv.info.gaps = new ListBuffer<Integer>();
  1412         genTry(tree.body, tree.catchers, tryEnv);
  1414     //where
  1415         /** Generate code for a try or synchronized statement
  1416          *  @param body      The body of the try or synchronized statement.
  1417          *  @param catchers  The lis of catch clauses.
  1418          *  @param env       the environment current for the body.
  1419          */
  1420         void genTry(JCTree body, List<JCCatch> catchers, Env<GenContext> env) {
  1421             int limit = code.nextreg;
  1422             int startpc = code.curPc();
  1423             Code.State stateTry = code.state.dup();
  1424             genStat(body, env, CRT_BLOCK);
  1425             int endpc = code.curPc();
  1426             boolean hasFinalizer =
  1427                 env.info.finalize != null &&
  1428                 env.info.finalize.hasFinalizer();
  1429             List<Integer> gaps = env.info.gaps.toList();
  1430             code.statBegin(TreeInfo.endPos(body));
  1431             genFinalizer(env);
  1432             code.statBegin(TreeInfo.endPos(env.tree));
  1433             Chain exitChain = code.branch(goto_);
  1434             endFinalizerGap(env);
  1435             if (startpc != endpc) for (List<JCCatch> l = catchers; l.nonEmpty(); l = l.tail) {
  1436                 // start off with exception on stack
  1437                 code.entryPoint(stateTry, l.head.param.sym.type);
  1438                 genCatch(l.head, env, startpc, endpc, gaps);
  1439                 genFinalizer(env);
  1440                 if (hasFinalizer || l.tail.nonEmpty()) {
  1441                     code.statBegin(TreeInfo.endPos(env.tree));
  1442                     exitChain = Code.mergeChains(exitChain,
  1443                                                  code.branch(goto_));
  1445                 endFinalizerGap(env);
  1447             if (hasFinalizer) {
  1448                 // Create a new register segement to avoid allocating
  1449                 // the same variables in finalizers and other statements.
  1450                 code.newRegSegment();
  1452                 // Add a catch-all clause.
  1454                 // start off with exception on stack
  1455                 int catchallpc = code.entryPoint(stateTry, syms.throwableType);
  1457                 // Register all exception ranges for catch all clause.
  1458                 // The range of the catch all clause is from the beginning
  1459                 // of the try or synchronized block until the present
  1460                 // code pointer excluding all gaps in the current
  1461                 // environment's GenContext.
  1462                 int startseg = startpc;
  1463                 while (env.info.gaps.nonEmpty()) {
  1464                     int endseg = env.info.gaps.next().intValue();
  1465                     registerCatch(body.pos(), startseg, endseg,
  1466                                   catchallpc, 0);
  1467                     startseg = env.info.gaps.next().intValue();
  1469                 code.statBegin(TreeInfo.finalizerPos(env.tree));
  1470                 code.markStatBegin();
  1472                 Item excVar = makeTemp(syms.throwableType);
  1473                 excVar.store();
  1474                 genFinalizer(env);
  1475                 excVar.load();
  1476                 registerCatch(body.pos(), startseg,
  1477                               env.info.gaps.next().intValue(),
  1478                               catchallpc, 0);
  1479                 code.emitop0(athrow);
  1480                 code.markDead();
  1482                 // If there are jsr's to this finalizer, ...
  1483                 if (env.info.cont != null) {
  1484                     // Resolve all jsr's.
  1485                     code.resolve(env.info.cont);
  1487                     // Mark statement line number
  1488                     code.statBegin(TreeInfo.finalizerPos(env.tree));
  1489                     code.markStatBegin();
  1491                     // Save return address.
  1492                     LocalItem retVar = makeTemp(syms.throwableType);
  1493                     retVar.store();
  1495                     // Generate finalizer code.
  1496                     env.info.finalize.genLast();
  1498                     // Return.
  1499                     code.emitop1w(ret, retVar.reg);
  1500                     code.markDead();
  1503             // Resolve all breaks.
  1504             code.resolve(exitChain);
  1506             code.endScopes(limit);
  1509         /** Generate code for a catch clause.
  1510          *  @param tree     The catch clause.
  1511          *  @param env      The environment current in the enclosing try.
  1512          *  @param startpc  Start pc of try-block.
  1513          *  @param endpc    End pc of try-block.
  1514          */
  1515         void genCatch(JCCatch tree,
  1516                       Env<GenContext> env,
  1517                       int startpc, int endpc,
  1518                       List<Integer> gaps) {
  1519             if (startpc != endpc) {
  1520                 List<JCExpression> subClauses = TreeInfo.isMultiCatch(tree) ?
  1521                         ((JCTypeUnion)tree.param.vartype).alternatives :
  1522                         List.of(tree.param.vartype);
  1523                 while (gaps.nonEmpty()) {
  1524                     for (JCExpression subCatch : subClauses) {
  1525                         int catchType = makeRef(tree.pos(), subCatch.type);
  1526                         int end = gaps.head.intValue();
  1527                         registerCatch(tree.pos(),
  1528                                       startpc,  end, code.curPc(),
  1529                                       catchType);
  1531                     gaps = gaps.tail;
  1532                     startpc = gaps.head.intValue();
  1533                     gaps = gaps.tail;
  1535                 if (startpc < endpc) {
  1536                     for (JCExpression subCatch : subClauses) {
  1537                         int catchType = makeRef(tree.pos(), subCatch.type);
  1538                         registerCatch(tree.pos(),
  1539                                       startpc, endpc, code.curPc(),
  1540                                       catchType);
  1543                 VarSymbol exparam = tree.param.sym;
  1544                 code.statBegin(tree.pos);
  1545                 code.markStatBegin();
  1546                 int limit = code.nextreg;
  1547                 int exlocal = code.newLocal(exparam);
  1548                 items.makeLocalItem(exparam).store();
  1549                 code.statBegin(TreeInfo.firstStatPos(tree.body));
  1550                 genStat(tree.body, env, CRT_BLOCK);
  1551                 code.endScopes(limit);
  1552                 code.statBegin(TreeInfo.endPos(tree.body));
  1556         /** Register a catch clause in the "Exceptions" code-attribute.
  1557          */
  1558         void registerCatch(DiagnosticPosition pos,
  1559                            int startpc, int endpc,
  1560                            int handler_pc, int catch_type) {
  1561             char startpc1 = (char)startpc;
  1562             char endpc1 = (char)endpc;
  1563             char handler_pc1 = (char)handler_pc;
  1564             if (startpc1 == startpc &&
  1565                 endpc1 == endpc &&
  1566                 handler_pc1 == handler_pc) {
  1567                 code.addCatch(startpc1, endpc1, handler_pc1,
  1568                               (char)catch_type);
  1569             } else {
  1570                 if (!useJsrLocally && !target.generateStackMapTable()) {
  1571                     useJsrLocally = true;
  1572                     throw new CodeSizeOverflow();
  1573                 } else {
  1574                     log.error(pos, "limit.code.too.large.for.try.stmt");
  1575                     nerrs++;
  1580     /** Very roughly estimate the number of instructions needed for
  1581      *  the given tree.
  1582      */
  1583     int estimateCodeComplexity(JCTree tree) {
  1584         if (tree == null) return 0;
  1585         class ComplexityScanner extends TreeScanner {
  1586             int complexity = 0;
  1587             public void scan(JCTree tree) {
  1588                 if (complexity > jsrlimit) return;
  1589                 super.scan(tree);
  1591             public void visitClassDef(JCClassDecl tree) {}
  1592             public void visitDoLoop(JCDoWhileLoop tree)
  1593                 { super.visitDoLoop(tree); complexity++; }
  1594             public void visitWhileLoop(JCWhileLoop tree)
  1595                 { super.visitWhileLoop(tree); complexity++; }
  1596             public void visitForLoop(JCForLoop tree)
  1597                 { super.visitForLoop(tree); complexity++; }
  1598             public void visitSwitch(JCSwitch tree)
  1599                 { super.visitSwitch(tree); complexity+=5; }
  1600             public void visitCase(JCCase tree)
  1601                 { super.visitCase(tree); complexity++; }
  1602             public void visitSynchronized(JCSynchronized tree)
  1603                 { super.visitSynchronized(tree); complexity+=6; }
  1604             public void visitTry(JCTry tree)
  1605                 { super.visitTry(tree);
  1606                   if (tree.finalizer != null) complexity+=6; }
  1607             public void visitCatch(JCCatch tree)
  1608                 { super.visitCatch(tree); complexity+=2; }
  1609             public void visitConditional(JCConditional tree)
  1610                 { super.visitConditional(tree); complexity+=2; }
  1611             public void visitIf(JCIf tree)
  1612                 { super.visitIf(tree); complexity+=2; }
  1613             // note: for break, continue, and return we don't take unwind() into account.
  1614             public void visitBreak(JCBreak tree)
  1615                 { super.visitBreak(tree); complexity+=1; }
  1616             public void visitContinue(JCContinue tree)
  1617                 { super.visitContinue(tree); complexity+=1; }
  1618             public void visitReturn(JCReturn tree)
  1619                 { super.visitReturn(tree); complexity+=1; }
  1620             public void visitThrow(JCThrow tree)
  1621                 { super.visitThrow(tree); complexity+=1; }
  1622             public void visitAssert(JCAssert tree)
  1623                 { super.visitAssert(tree); complexity+=5; }
  1624             public void visitApply(JCMethodInvocation tree)
  1625                 { super.visitApply(tree); complexity+=2; }
  1626             public void visitNewClass(JCNewClass tree)
  1627                 { scan(tree.encl); scan(tree.args); complexity+=2; }
  1628             public void visitNewArray(JCNewArray tree)
  1629                 { super.visitNewArray(tree); complexity+=5; }
  1630             public void visitAssign(JCAssign tree)
  1631                 { super.visitAssign(tree); complexity+=1; }
  1632             public void visitAssignop(JCAssignOp tree)
  1633                 { super.visitAssignop(tree); complexity+=2; }
  1634             public void visitUnary(JCUnary tree)
  1635                 { complexity+=1;
  1636                   if (tree.type.constValue() == null) super.visitUnary(tree); }
  1637             public void visitBinary(JCBinary tree)
  1638                 { complexity+=1;
  1639                   if (tree.type.constValue() == null) super.visitBinary(tree); }
  1640             public void visitTypeTest(JCInstanceOf tree)
  1641                 { super.visitTypeTest(tree); complexity+=1; }
  1642             public void visitIndexed(JCArrayAccess tree)
  1643                 { super.visitIndexed(tree); complexity+=1; }
  1644             public void visitSelect(JCFieldAccess tree)
  1645                 { super.visitSelect(tree);
  1646                   if (tree.sym.kind == VAR) complexity+=1; }
  1647             public void visitIdent(JCIdent tree) {
  1648                 if (tree.sym.kind == VAR) {
  1649                     complexity+=1;
  1650                     if (tree.type.constValue() == null &&
  1651                         tree.sym.owner.kind == TYP)
  1652                         complexity+=1;
  1655             public void visitLiteral(JCLiteral tree)
  1656                 { complexity+=1; }
  1657             public void visitTree(JCTree tree) {}
  1658             public void visitWildcard(JCWildcard tree) {
  1659                 throw new AssertionError(this.getClass().getName());
  1662         ComplexityScanner scanner = new ComplexityScanner();
  1663         tree.accept(scanner);
  1664         return scanner.complexity;
  1667     public void visitIf(JCIf tree) {
  1668         int limit = code.nextreg;
  1669         Chain thenExit = null;
  1670         CondItem c = genCond(TreeInfo.skipParens(tree.cond),
  1671                              CRT_FLOW_CONTROLLER);
  1672         Chain elseChain = c.jumpFalse();
  1673         if (!c.isFalse()) {
  1674             code.resolve(c.trueJumps);
  1675             genStat(tree.thenpart, env, CRT_STATEMENT | CRT_FLOW_TARGET);
  1676             thenExit = code.branch(goto_);
  1678         if (elseChain != null) {
  1679             code.resolve(elseChain);
  1680             if (tree.elsepart != null)
  1681                 genStat(tree.elsepart, env,CRT_STATEMENT | CRT_FLOW_TARGET);
  1683         code.resolve(thenExit);
  1684         code.endScopes(limit);
  1687     public void visitExec(JCExpressionStatement tree) {
  1688         // Optimize x++ to ++x and x-- to --x.
  1689         JCExpression e = tree.expr;
  1690         switch (e.getTag()) {
  1691             case POSTINC:
  1692                 ((JCUnary) e).setTag(PREINC);
  1693                 break;
  1694             case POSTDEC:
  1695                 ((JCUnary) e).setTag(PREDEC);
  1696                 break;
  1698         genExpr(tree.expr, tree.expr.type).drop();
  1701     public void visitBreak(JCBreak tree) {
  1702         Env<GenContext> targetEnv = unwind(tree.target, env);
  1703         Assert.check(code.state.stacksize == 0);
  1704         targetEnv.info.addExit(code.branch(goto_));
  1705         endFinalizerGaps(env, targetEnv);
  1708     public void visitContinue(JCContinue tree) {
  1709         Env<GenContext> targetEnv = unwind(tree.target, env);
  1710         Assert.check(code.state.stacksize == 0);
  1711         targetEnv.info.addCont(code.branch(goto_));
  1712         endFinalizerGaps(env, targetEnv);
  1715     public void visitReturn(JCReturn tree) {
  1716         int limit = code.nextreg;
  1717         final Env<GenContext> targetEnv;
  1718         if (tree.expr != null) {
  1719             Item r = genExpr(tree.expr, pt).load();
  1720             if (hasFinally(env.enclMethod, env)) {
  1721                 r = makeTemp(pt);
  1722                 r.store();
  1724             targetEnv = unwind(env.enclMethod, env);
  1725             r.load();
  1726             code.emitop0(ireturn + Code.truncate(Code.typecode(pt)));
  1727         } else {
  1728             targetEnv = unwind(env.enclMethod, env);
  1729             code.emitop0(return_);
  1731         endFinalizerGaps(env, targetEnv);
  1732         code.endScopes(limit);
  1735     public void visitThrow(JCThrow tree) {
  1736         genExpr(tree.expr, tree.expr.type).load();
  1737         code.emitop0(athrow);
  1740 /* ************************************************************************
  1741  * Visitor methods for expressions
  1742  *************************************************************************/
  1744     public void visitApply(JCMethodInvocation tree) {
  1745         setTypeAnnotationPositions(tree.pos);
  1746         // Generate code for method.
  1747         Item m = genExpr(tree.meth, methodType);
  1748         // Generate code for all arguments, where the expected types are
  1749         // the parameters of the method's external type (that is, any implicit
  1750         // outer instance of a super(...) call appears as first parameter).
  1751         genArgs(tree.args,
  1752                 TreeInfo.symbol(tree.meth).externalType(types).getParameterTypes());
  1753         code.statBegin(tree.pos);
  1754         code.markStatBegin();
  1755         result = m.invoke();
  1758     public void visitConditional(JCConditional tree) {
  1759         Chain thenExit = null;
  1760         CondItem c = genCond(tree.cond, CRT_FLOW_CONTROLLER);
  1761         Chain elseChain = c.jumpFalse();
  1762         if (!c.isFalse()) {
  1763             code.resolve(c.trueJumps);
  1764             int startpc = genCrt ? code.curPc() : 0;
  1765             genExpr(tree.truepart, pt).load();
  1766             code.state.forceStackTop(tree.type);
  1767             if (genCrt) code.crt.put(tree.truepart, CRT_FLOW_TARGET,
  1768                                      startpc, code.curPc());
  1769             thenExit = code.branch(goto_);
  1771         if (elseChain != null) {
  1772             code.resolve(elseChain);
  1773             int startpc = genCrt ? code.curPc() : 0;
  1774             genExpr(tree.falsepart, pt).load();
  1775             code.state.forceStackTop(tree.type);
  1776             if (genCrt) code.crt.put(tree.falsepart, CRT_FLOW_TARGET,
  1777                                      startpc, code.curPc());
  1779         code.resolve(thenExit);
  1780         result = items.makeStackItem(pt);
  1783    private void setTypeAnnotationPositions(int treePos) {
  1784        MethodSymbol meth = code.meth;
  1786        for (Attribute.TypeCompound ta : meth.getRawTypeAttributes()) {
  1787            if (ta.position.pos == treePos) {
  1788                ta.position.offset = code.cp;
  1789                ta.position.lvarOffset = new int[] { code.cp };
  1790                ta.position.isValidOffset = true;
  1794        if (code.meth.getKind() != javax.lang.model.element.ElementKind.CONSTRUCTOR
  1795                && code.meth.getKind() != javax.lang.model.element.ElementKind.STATIC_INIT)
  1796            return;
  1798        for (Attribute.TypeCompound ta : meth.owner.getRawTypeAttributes()) {
  1799            if (ta.position.pos == treePos) {
  1800                ta.position.offset = code.cp;
  1801                ta.position.lvarOffset = new int[] { code.cp };
  1802                ta.position.isValidOffset = true;
  1806        ClassSymbol clazz = meth.enclClass();
  1807        for (Symbol s : new com.sun.tools.javac.model.FilteredMemberList(clazz.members())) {
  1808            if (!s.getKind().isField())
  1809                continue;
  1810            for (Attribute.TypeCompound ta : s.getRawTypeAttributes()) {
  1811                if (ta.position.pos == treePos) {
  1812                    ta.position.offset = code.cp;
  1813                    ta.position.lvarOffset = new int[] { code.cp };
  1814                    ta.position.isValidOffset = true;
  1820     public void visitNewClass(JCNewClass tree) {
  1821         // Enclosing instances or anonymous classes should have been eliminated
  1822         // by now.
  1823         Assert.check(tree.encl == null && tree.def == null);
  1824         setTypeAnnotationPositions(tree.pos);
  1826         code.emitop2(new_, makeRef(tree.pos(), tree.type));
  1827         code.emitop0(dup);
  1829         // Generate code for all arguments, where the expected types are
  1830         // the parameters of the constructor's external type (that is,
  1831         // any implicit outer instance appears as first parameter).
  1832         genArgs(tree.args, tree.constructor.externalType(types).getParameterTypes());
  1834         items.makeMemberItem(tree.constructor, true).invoke();
  1835         result = items.makeStackItem(tree.type);
  1838     public void visitNewArray(JCNewArray tree) {
  1839         setTypeAnnotationPositions(tree.pos);
  1841         if (tree.elems != null) {
  1842             Type elemtype = types.elemtype(tree.type);
  1843             loadIntConst(tree.elems.length());
  1844             Item arr = makeNewArray(tree.pos(), tree.type, 1);
  1845             int i = 0;
  1846             for (List<JCExpression> l = tree.elems; l.nonEmpty(); l = l.tail) {
  1847                 arr.duplicate();
  1848                 loadIntConst(i);
  1849                 i++;
  1850                 genExpr(l.head, elemtype).load();
  1851                 items.makeIndexedItem(elemtype).store();
  1853             result = arr;
  1854         } else {
  1855             for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
  1856                 genExpr(l.head, syms.intType).load();
  1858             result = makeNewArray(tree.pos(), tree.type, tree.dims.length());
  1861 //where
  1862         /** Generate code to create an array with given element type and number
  1863          *  of dimensions.
  1864          */
  1865         Item makeNewArray(DiagnosticPosition pos, Type type, int ndims) {
  1866             Type elemtype = types.elemtype(type);
  1867             if (types.dimensions(type) > ClassFile.MAX_DIMENSIONS) {
  1868                 log.error(pos, "limit.dimensions");
  1869                 nerrs++;
  1871             int elemcode = Code.arraycode(elemtype);
  1872             if (elemcode == 0 || (elemcode == 1 && ndims == 1)) {
  1873                 code.emitAnewarray(makeRef(pos, elemtype), type);
  1874             } else if (elemcode == 1) {
  1875                 code.emitMultianewarray(ndims, makeRef(pos, type), type);
  1876             } else {
  1877                 code.emitNewarray(elemcode, type);
  1879             return items.makeStackItem(type);
  1882     public void visitParens(JCParens tree) {
  1883         result = genExpr(tree.expr, tree.expr.type);
  1886     public void visitAssign(JCAssign tree) {
  1887         Item l = genExpr(tree.lhs, tree.lhs.type);
  1888         genExpr(tree.rhs, tree.lhs.type).load();
  1889         result = items.makeAssignItem(l);
  1892     public void visitAssignop(JCAssignOp tree) {
  1893         OperatorSymbol operator = (OperatorSymbol) tree.operator;
  1894         Item l;
  1895         if (operator.opcode == string_add) {
  1896             // Generate code to make a string buffer
  1897             makeStringBuffer(tree.pos());
  1899             // Generate code for first string, possibly save one
  1900             // copy under buffer
  1901             l = genExpr(tree.lhs, tree.lhs.type);
  1902             if (l.width() > 0) {
  1903                 code.emitop0(dup_x1 + 3 * (l.width() - 1));
  1906             // Load first string and append to buffer.
  1907             l.load();
  1908             appendString(tree.lhs);
  1910             // Append all other strings to buffer.
  1911             appendStrings(tree.rhs);
  1913             // Convert buffer to string.
  1914             bufferToString(tree.pos());
  1915         } else {
  1916             // Generate code for first expression
  1917             l = genExpr(tree.lhs, tree.lhs.type);
  1919             // If we have an increment of -32768 to +32767 of a local
  1920             // int variable we can use an incr instruction instead of
  1921             // proceeding further.
  1922             if ((tree.hasTag(PLUS_ASG) || tree.hasTag(MINUS_ASG)) &&
  1923                 l instanceof LocalItem &&
  1924                 tree.lhs.type.getTag().isSubRangeOf(INT) &&
  1925                 tree.rhs.type.getTag().isSubRangeOf(INT) &&
  1926                 tree.rhs.type.constValue() != null) {
  1927                 int ival = ((Number) tree.rhs.type.constValue()).intValue();
  1928                 if (tree.hasTag(MINUS_ASG)) ival = -ival;
  1929                 ((LocalItem)l).incr(ival);
  1930                 result = l;
  1931                 return;
  1933             // Otherwise, duplicate expression, load one copy
  1934             // and complete binary operation.
  1935             l.duplicate();
  1936             l.coerce(operator.type.getParameterTypes().head).load();
  1937             completeBinop(tree.lhs, tree.rhs, operator).coerce(tree.lhs.type);
  1939         result = items.makeAssignItem(l);
  1942     public void visitUnary(JCUnary tree) {
  1943         OperatorSymbol operator = (OperatorSymbol)tree.operator;
  1944         if (tree.hasTag(NOT)) {
  1945             CondItem od = genCond(tree.arg, false);
  1946             result = od.negate();
  1947         } else {
  1948             Item od = genExpr(tree.arg, operator.type.getParameterTypes().head);
  1949             switch (tree.getTag()) {
  1950             case POS:
  1951                 result = od.load();
  1952                 break;
  1953             case NEG:
  1954                 result = od.load();
  1955                 code.emitop0(operator.opcode);
  1956                 break;
  1957             case COMPL:
  1958                 result = od.load();
  1959                 emitMinusOne(od.typecode);
  1960                 code.emitop0(operator.opcode);
  1961                 break;
  1962             case PREINC: case PREDEC:
  1963                 od.duplicate();
  1964                 if (od instanceof LocalItem &&
  1965                     (operator.opcode == iadd || operator.opcode == isub)) {
  1966                     ((LocalItem)od).incr(tree.hasTag(PREINC) ? 1 : -1);
  1967                     result = od;
  1968                 } else {
  1969                     od.load();
  1970                     code.emitop0(one(od.typecode));
  1971                     code.emitop0(operator.opcode);
  1972                     // Perform narrowing primitive conversion if byte,
  1973                     // char, or short.  Fix for 4304655.
  1974                     if (od.typecode != INTcode &&
  1975                         Code.truncate(od.typecode) == INTcode)
  1976                       code.emitop0(int2byte + od.typecode - BYTEcode);
  1977                     result = items.makeAssignItem(od);
  1979                 break;
  1980             case POSTINC: case POSTDEC:
  1981                 od.duplicate();
  1982                 if (od instanceof LocalItem &&
  1983                     (operator.opcode == iadd || operator.opcode == isub)) {
  1984                     Item res = od.load();
  1985                     ((LocalItem)od).incr(tree.hasTag(POSTINC) ? 1 : -1);
  1986                     result = res;
  1987                 } else {
  1988                     Item res = od.load();
  1989                     od.stash(od.typecode);
  1990                     code.emitop0(one(od.typecode));
  1991                     code.emitop0(operator.opcode);
  1992                     // Perform narrowing primitive conversion if byte,
  1993                     // char, or short.  Fix for 4304655.
  1994                     if (od.typecode != INTcode &&
  1995                         Code.truncate(od.typecode) == INTcode)
  1996                       code.emitop0(int2byte + od.typecode - BYTEcode);
  1997                     od.store();
  1998                     result = res;
  2000                 break;
  2001             case NULLCHK:
  2002                 result = od.load();
  2003                 code.emitop0(dup);
  2004                 genNullCheck(tree.pos());
  2005                 break;
  2006             default:
  2007                 Assert.error();
  2012     /** Generate a null check from the object value at stack top. */
  2013     private void genNullCheck(DiagnosticPosition pos) {
  2014         callMethod(pos, syms.objectType, names.getClass,
  2015                    List.<Type>nil(), false);
  2016         code.emitop0(pop);
  2019     public void visitBinary(JCBinary tree) {
  2020         OperatorSymbol operator = (OperatorSymbol)tree.operator;
  2021         if (operator.opcode == string_add) {
  2022             // Create a string buffer.
  2023             makeStringBuffer(tree.pos());
  2024             // Append all strings to buffer.
  2025             appendStrings(tree);
  2026             // Convert buffer to string.
  2027             bufferToString(tree.pos());
  2028             result = items.makeStackItem(syms.stringType);
  2029         } else if (tree.hasTag(AND)) {
  2030             CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER);
  2031             if (!lcond.isFalse()) {
  2032                 Chain falseJumps = lcond.jumpFalse();
  2033                 code.resolve(lcond.trueJumps);
  2034                 CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET);
  2035                 result = items.
  2036                     makeCondItem(rcond.opcode,
  2037                                  rcond.trueJumps,
  2038                                  Code.mergeChains(falseJumps,
  2039                                                   rcond.falseJumps));
  2040             } else {
  2041                 result = lcond;
  2043         } else if (tree.hasTag(OR)) {
  2044             CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER);
  2045             if (!lcond.isTrue()) {
  2046                 Chain trueJumps = lcond.jumpTrue();
  2047                 code.resolve(lcond.falseJumps);
  2048                 CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET);
  2049                 result = items.
  2050                     makeCondItem(rcond.opcode,
  2051                                  Code.mergeChains(trueJumps, rcond.trueJumps),
  2052                                  rcond.falseJumps);
  2053             } else {
  2054                 result = lcond;
  2056         } else {
  2057             Item od = genExpr(tree.lhs, operator.type.getParameterTypes().head);
  2058             od.load();
  2059             result = completeBinop(tree.lhs, tree.rhs, operator);
  2062 //where
  2063         /** Make a new string buffer.
  2064          */
  2065         void makeStringBuffer(DiagnosticPosition pos) {
  2066             code.emitop2(new_, makeRef(pos, stringBufferType));
  2067             code.emitop0(dup);
  2068             callMethod(
  2069                 pos, stringBufferType, names.init, List.<Type>nil(), false);
  2072         /** Append value (on tos) to string buffer (on tos - 1).
  2073          */
  2074         void appendString(JCTree tree) {
  2075             Type t = tree.type.baseType();
  2076             if (!t.isPrimitive() && t.tsym != syms.stringType.tsym) {
  2077                 t = syms.objectType;
  2079             items.makeMemberItem(getStringBufferAppend(tree, t), false).invoke();
  2081         Symbol getStringBufferAppend(JCTree tree, Type t) {
  2082             Assert.checkNull(t.constValue());
  2083             Symbol method = stringBufferAppend.get(t);
  2084             if (method == null) {
  2085                 method = rs.resolveInternalMethod(tree.pos(),
  2086                                                   attrEnv,
  2087                                                   stringBufferType,
  2088                                                   names.append,
  2089                                                   List.of(t),
  2090                                                   null);
  2091                 stringBufferAppend.put(t, method);
  2093             return method;
  2096         /** Add all strings in tree to string buffer.
  2097          */
  2098         void appendStrings(JCTree tree) {
  2099             tree = TreeInfo.skipParens(tree);
  2100             if (tree.hasTag(PLUS) && tree.type.constValue() == null) {
  2101                 JCBinary op = (JCBinary) tree;
  2102                 if (op.operator.kind == MTH &&
  2103                     ((OperatorSymbol) op.operator).opcode == string_add) {
  2104                     appendStrings(op.lhs);
  2105                     appendStrings(op.rhs);
  2106                     return;
  2109             genExpr(tree, tree.type).load();
  2110             appendString(tree);
  2113         /** Convert string buffer on tos to string.
  2114          */
  2115         void bufferToString(DiagnosticPosition pos) {
  2116             callMethod(
  2117                 pos,
  2118                 stringBufferType,
  2119                 names.toString,
  2120                 List.<Type>nil(),
  2121                 false);
  2124         /** Complete generating code for operation, with left operand
  2125          *  already on stack.
  2126          *  @param lhs       The tree representing the left operand.
  2127          *  @param rhs       The tree representing the right operand.
  2128          *  @param operator  The operator symbol.
  2129          */
  2130         Item completeBinop(JCTree lhs, JCTree rhs, OperatorSymbol operator) {
  2131             MethodType optype = (MethodType)operator.type;
  2132             int opcode = operator.opcode;
  2133             if (opcode >= if_icmpeq && opcode <= if_icmple &&
  2134                 rhs.type.constValue() instanceof Number &&
  2135                 ((Number) rhs.type.constValue()).intValue() == 0) {
  2136                 opcode = opcode + (ifeq - if_icmpeq);
  2137             } else if (opcode >= if_acmpeq && opcode <= if_acmpne &&
  2138                        TreeInfo.isNull(rhs)) {
  2139                 opcode = opcode + (if_acmp_null - if_acmpeq);
  2140             } else {
  2141                 // The expected type of the right operand is
  2142                 // the second parameter type of the operator, except for
  2143                 // shifts with long shiftcount, where we convert the opcode
  2144                 // to a short shift and the expected type to int.
  2145                 Type rtype = operator.erasure(types).getParameterTypes().tail.head;
  2146                 if (opcode >= ishll && opcode <= lushrl) {
  2147                     opcode = opcode + (ishl - ishll);
  2148                     rtype = syms.intType;
  2150                 // Generate code for right operand and load.
  2151                 genExpr(rhs, rtype).load();
  2152                 // If there are two consecutive opcode instructions,
  2153                 // emit the first now.
  2154                 if (opcode >= (1 << preShift)) {
  2155                     code.emitop0(opcode >> preShift);
  2156                     opcode = opcode & 0xFF;
  2159             if (opcode >= ifeq && opcode <= if_acmpne ||
  2160                 opcode == if_acmp_null || opcode == if_acmp_nonnull) {
  2161                 return items.makeCondItem(opcode);
  2162             } else {
  2163                 code.emitop0(opcode);
  2164                 return items.makeStackItem(optype.restype);
  2168     public void visitTypeCast(JCTypeCast tree) {
  2169         setTypeAnnotationPositions(tree.pos);
  2170         result = genExpr(tree.expr, tree.clazz.type).load();
  2171         // Additional code is only needed if we cast to a reference type
  2172         // which is not statically a supertype of the expression's type.
  2173         // For basic types, the coerce(...) in genExpr(...) will do
  2174         // the conversion.
  2175         if (!tree.clazz.type.isPrimitive() &&
  2176             types.asSuper(tree.expr.type, tree.clazz.type.tsym) == null) {
  2177             code.emitop2(checkcast, makeRef(tree.pos(), tree.clazz.type));
  2181     public void visitWildcard(JCWildcard tree) {
  2182         throw new AssertionError(this.getClass().getName());
  2185     public void visitTypeTest(JCInstanceOf tree) {
  2186         setTypeAnnotationPositions(tree.pos);
  2187         genExpr(tree.expr, tree.expr.type).load();
  2188         code.emitop2(instanceof_, makeRef(tree.pos(), tree.clazz.type));
  2189         result = items.makeStackItem(syms.booleanType);
  2192     public void visitIndexed(JCArrayAccess tree) {
  2193         genExpr(tree.indexed, tree.indexed.type).load();
  2194         genExpr(tree.index, syms.intType).load();
  2195         result = items.makeIndexedItem(tree.type);
  2198     public void visitIdent(JCIdent tree) {
  2199         Symbol sym = tree.sym;
  2200         if (tree.name == names._this || tree.name == names._super) {
  2201             Item res = tree.name == names._this
  2202                 ? items.makeThisItem()
  2203                 : items.makeSuperItem();
  2204             if (sym.kind == MTH) {
  2205                 // Generate code to address the constructor.
  2206                 res.load();
  2207                 res = items.makeMemberItem(sym, true);
  2209             result = res;
  2210         } else if (sym.kind == VAR && sym.owner.kind == MTH) {
  2211             result = items.makeLocalItem((VarSymbol)sym);
  2212         } else if (isInvokeDynamic(sym)) {
  2213             result = items.makeDynamicItem(sym);
  2214         } else if ((sym.flags() & STATIC) != 0) {
  2215             if (!isAccessSuper(env.enclMethod))
  2216                 sym = binaryQualifier(sym, env.enclClass.type);
  2217             result = items.makeStaticItem(sym);
  2218         } else {
  2219             items.makeThisItem().load();
  2220             sym = binaryQualifier(sym, env.enclClass.type);
  2221             result = items.makeMemberItem(sym, (sym.flags() & PRIVATE) != 0);
  2225     public void visitSelect(JCFieldAccess tree) {
  2226         Symbol sym = tree.sym;
  2228         if (tree.name == names._class) {
  2229             Assert.check(target.hasClassLiterals());
  2230             code.emitop2(ldc2, makeRef(tree.pos(), tree.selected.type));
  2231             result = items.makeStackItem(pt);
  2232             return;
  2235         Symbol ssym = TreeInfo.symbol(tree.selected);
  2237         // Are we selecting via super?
  2238         boolean selectSuper =
  2239             ssym != null && (ssym.kind == TYP || ssym.name == names._super);
  2241         // Are we accessing a member of the superclass in an access method
  2242         // resulting from a qualified super?
  2243         boolean accessSuper = isAccessSuper(env.enclMethod);
  2245         Item base = (selectSuper)
  2246             ? items.makeSuperItem()
  2247             : genExpr(tree.selected, tree.selected.type);
  2249         if (sym.kind == VAR && ((VarSymbol) sym).getConstValue() != null) {
  2250             // We are seeing a variable that is constant but its selecting
  2251             // expression is not.
  2252             if ((sym.flags() & STATIC) != 0) {
  2253                 if (!selectSuper && (ssym == null || ssym.kind != TYP))
  2254                     base = base.load();
  2255                 base.drop();
  2256             } else {
  2257                 base.load();
  2258                 genNullCheck(tree.selected.pos());
  2260             result = items.
  2261                 makeImmediateItem(sym.type, ((VarSymbol) sym).getConstValue());
  2262         } else {
  2263             if (isInvokeDynamic(sym)) {
  2264                 result = items.makeDynamicItem(sym);
  2265                 return;
  2266             } else if (!accessSuper) {
  2267                 sym = binaryQualifier(sym, tree.selected.type);
  2269             if ((sym.flags() & STATIC) != 0) {
  2270                 if (!selectSuper && (ssym == null || ssym.kind != TYP))
  2271                     base = base.load();
  2272                 base.drop();
  2273                 result = items.makeStaticItem(sym);
  2274             } else {
  2275                 base.load();
  2276                 if (sym == syms.lengthVar) {
  2277                     code.emitop0(arraylength);
  2278                     result = items.makeStackItem(syms.intType);
  2279                 } else {
  2280                     result = items.
  2281                         makeMemberItem(sym,
  2282                                        (sym.flags() & PRIVATE) != 0 ||
  2283                                        selectSuper || accessSuper);
  2289     public boolean isInvokeDynamic(Symbol sym) {
  2290         return sym.kind == MTH && ((MethodSymbol)sym).isDynamic();
  2293     public void visitLiteral(JCLiteral tree) {
  2294         if (tree.type.hasTag(BOT)) {
  2295             code.emitop0(aconst_null);
  2296             if (types.dimensions(pt) > 1) {
  2297                 code.emitop2(checkcast, makeRef(tree.pos(), pt));
  2298                 result = items.makeStackItem(pt);
  2299             } else {
  2300                 result = items.makeStackItem(tree.type);
  2303         else
  2304             result = items.makeImmediateItem(tree.type, tree.value);
  2307     public void visitLetExpr(LetExpr tree) {
  2308         int limit = code.nextreg;
  2309         genStats(tree.defs, env);
  2310         result = genExpr(tree.expr, tree.expr.type).load();
  2311         code.endScopes(limit);
  2314     private void generateReferencesToPrunedTree(ClassSymbol classSymbol, Pool pool) {
  2315         List<JCTree> prunedInfo = lower.prunedTree.get(classSymbol);
  2316         if (prunedInfo != null) {
  2317             for (JCTree prunedTree: prunedInfo) {
  2318                 prunedTree.accept(classReferenceVisitor);
  2323 /* ************************************************************************
  2324  * main method
  2325  *************************************************************************/
  2327     /** Generate code for a class definition.
  2328      *  @param env   The attribution environment that belongs to the
  2329      *               outermost class containing this class definition.
  2330      *               We need this for resolving some additional symbols.
  2331      *  @param cdef  The tree representing the class definition.
  2332      *  @return      True if code is generated with no errors.
  2333      */
  2334     public boolean genClass(Env<AttrContext> env, JCClassDecl cdef) {
  2335         try {
  2336             attrEnv = env;
  2337             ClassSymbol c = cdef.sym;
  2338             this.toplevel = env.toplevel;
  2339             this.endPosTable = toplevel.endPositions;
  2340             // If this is a class definition requiring Miranda methods,
  2341             // add them.
  2342             if (generateIproxies &&
  2343                 (c.flags() & (INTERFACE|ABSTRACT)) == ABSTRACT
  2344                 && !allowGenerics // no Miranda methods available with generics
  2346                 implementInterfaceMethods(c);
  2347             cdef.defs = normalizeDefs(cdef.defs, c);
  2348             c.pool = pool;
  2349             pool.reset();
  2350             generateReferencesToPrunedTree(c, pool);
  2351             Env<GenContext> localEnv =
  2352                 new Env<GenContext>(cdef, new GenContext());
  2353             localEnv.toplevel = env.toplevel;
  2354             localEnv.enclClass = cdef;
  2355             for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) {
  2356                 genDef(l.head, localEnv);
  2358             if (pool.numEntries() > Pool.MAX_ENTRIES) {
  2359                 log.error(cdef.pos(), "limit.pool");
  2360                 nerrs++;
  2362             if (nerrs != 0) {
  2363                 // if errors, discard code
  2364                 for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) {
  2365                     if (l.head.hasTag(METHODDEF))
  2366                         ((JCMethodDecl) l.head).sym.code = null;
  2369             cdef.defs = List.nil(); // discard trees
  2370             return nerrs == 0;
  2371         } finally {
  2372             // note: this method does NOT support recursion.
  2373             attrEnv = null;
  2374             this.env = null;
  2375             toplevel = null;
  2376             endPosTable = null;
  2377             nerrs = 0;
  2381 /* ************************************************************************
  2382  * Auxiliary classes
  2383  *************************************************************************/
  2385     /** An abstract class for finalizer generation.
  2386      */
  2387     abstract class GenFinalizer {
  2388         /** Generate code to clean up when unwinding. */
  2389         abstract void gen();
  2391         /** Generate code to clean up at last. */
  2392         abstract void genLast();
  2394         /** Does this finalizer have some nontrivial cleanup to perform? */
  2395         boolean hasFinalizer() { return true; }
  2398     /** code generation contexts,
  2399      *  to be used as type parameter for environments.
  2400      */
  2401     static class GenContext {
  2403         /** A chain for all unresolved jumps that exit the current environment.
  2404          */
  2405         Chain exit = null;
  2407         /** A chain for all unresolved jumps that continue in the
  2408          *  current environment.
  2409          */
  2410         Chain cont = null;
  2412         /** A closure that generates the finalizer of the current environment.
  2413          *  Only set for Synchronized and Try contexts.
  2414          */
  2415         GenFinalizer finalize = null;
  2417         /** Is this a switch statement?  If so, allocate registers
  2418          * even when the variable declaration is unreachable.
  2419          */
  2420         boolean isSwitch = false;
  2422         /** A list buffer containing all gaps in the finalizer range,
  2423          *  where a catch all exception should not apply.
  2424          */
  2425         ListBuffer<Integer> gaps = null;
  2427         /** Add given chain to exit chain.
  2428          */
  2429         void addExit(Chain c)  {
  2430             exit = Code.mergeChains(c, exit);
  2433         /** Add given chain to cont chain.
  2434          */
  2435         void addCont(Chain c) {
  2436             cont = Code.mergeChains(c, cont);

mercurial