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

Wed, 20 Jan 2010 16:12:26 -0800

author
jjg
date
Wed, 20 Jan 2010 16:12:26 -0800
changeset 478
0eaf89e08564
parent 323
14b1a8ede954
child 487
f65d652cb6af
permissions
-rw-r--r--

6918127: improve handling of TypeAnnotationPosition fields
Reviewed-by: jjg, darcy
Contributed-by: mali@csail.mit.edu, mernst@cs.washington.edu

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

mercurial