duke@1: /* jjg@815: * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved. duke@1: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. duke@1: * duke@1: * This code is free software; you can redistribute it and/or modify it duke@1: * under the terms of the GNU General Public License version 2 only, as ohair@554: * published by the Free Software Foundation. Oracle designates this duke@1: * particular file as subject to the "Classpath" exception as provided ohair@554: * by Oracle in the LICENSE file that accompanied this code. duke@1: * duke@1: * This code is distributed in the hope that it will be useful, but WITHOUT duke@1: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or duke@1: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License duke@1: * version 2 for more details (a copy is included in the LICENSE file that duke@1: * accompanied this code). duke@1: * duke@1: * You should have received a copy of the GNU General Public License version duke@1: * 2 along with this work; if not, write to the Free Software Foundation, duke@1: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. duke@1: * ohair@554: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA ohair@554: * or visit www.oracle.com if you need additional information or have any ohair@554: * questions. duke@1: */ duke@1: duke@1: package com.sun.tools.javac.jvm; duke@1: import java.util.*; duke@1: jjg@308: import javax.lang.model.element.ElementKind; jjg@308: duke@1: import com.sun.tools.javac.util.*; duke@1: import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; duke@1: import com.sun.tools.javac.util.List; duke@1: import com.sun.tools.javac.code.*; duke@1: import com.sun.tools.javac.comp.*; duke@1: import com.sun.tools.javac.tree.*; duke@1: duke@1: import com.sun.tools.javac.code.Symbol.*; duke@1: import com.sun.tools.javac.code.Type.*; duke@1: import com.sun.tools.javac.jvm.Code.*; duke@1: import com.sun.tools.javac.jvm.Items.*; duke@1: import com.sun.tools.javac.tree.JCTree.*; duke@1: duke@1: import static com.sun.tools.javac.code.Flags.*; duke@1: import static com.sun.tools.javac.code.Kinds.*; duke@1: import static com.sun.tools.javac.code.TypeTags.*; duke@1: import static com.sun.tools.javac.jvm.ByteCodes.*; duke@1: import static com.sun.tools.javac.jvm.CRTFlags.*; jjg@700: import static com.sun.tools.javac.main.OptionName.*; duke@1: duke@1: /** This pass maps flat Java (i.e. without inner classes) to bytecodes. duke@1: * jjg@581: *

This is NOT part of any supported API. jjg@581: * If you write code that depends on this, you do so at your own risk. duke@1: * This code and its internal interfaces are subject to change or duke@1: * deletion without notice. duke@1: */ duke@1: public class Gen extends JCTree.Visitor { duke@1: protected static final Context.Key genKey = duke@1: new Context.Key(); duke@1: duke@1: private final Log log; duke@1: private final Symtab syms; duke@1: private final Check chk; duke@1: private final Resolve rs; duke@1: private final TreeMaker make; jjg@113: private final Names names; duke@1: private final Target target; duke@1: private final Type stringBufferType; duke@1: private final Map stringBufferAppend; duke@1: private Name accessDollar; duke@1: private final Types types; duke@1: duke@1: /** Switch: GJ mode? duke@1: */ duke@1: private final boolean allowGenerics; duke@1: duke@1: /** Set when Miranda method stubs are to be generated. */ duke@1: private final boolean generateIproxies; duke@1: duke@1: /** Format of stackmap tables to be generated. */ duke@1: private final Code.StackMapFormat stackMap; duke@1: duke@1: /** A type that serves as the expected type for all method expressions. duke@1: */ duke@1: private final Type methodType; duke@1: duke@1: public static Gen instance(Context context) { duke@1: Gen instance = context.get(genKey); duke@1: if (instance == null) duke@1: instance = new Gen(context); duke@1: return instance; duke@1: } duke@1: duke@1: protected Gen(Context context) { duke@1: context.put(genKey, this); duke@1: jjg@113: names = Names.instance(context); duke@1: log = Log.instance(context); duke@1: syms = Symtab.instance(context); duke@1: chk = Check.instance(context); duke@1: rs = Resolve.instance(context); duke@1: make = TreeMaker.instance(context); duke@1: target = Target.instance(context); duke@1: types = Types.instance(context); duke@1: methodType = new MethodType(null, null, null, syms.methodClass); duke@1: allowGenerics = Source.instance(context).allowGenerics(); duke@1: stringBufferType = target.useStringBuilder() duke@1: ? syms.stringBuilderType duke@1: : syms.stringBufferType; duke@1: stringBufferAppend = new HashMap(); duke@1: accessDollar = names. duke@1: fromString("access" + target.syntheticNameChar()); duke@1: duke@1: Options options = Options.instance(context); duke@1: lineDebugInfo = jjg@700: options.isUnset(G_CUSTOM) || jjg@700: options.isSet(G_CUSTOM, "lines"); duke@1: varDebugInfo = jjg@700: options.isUnset(G_CUSTOM) jjg@700: ? options.isSet(G) jjg@700: : options.isSet(G_CUSTOM, "vars"); jjg@700: genCrt = options.isSet(XJCOV); jjg@700: debugCode = options.isSet("debugcode"); jjg@700: allowInvokedynamic = target.hasInvokedynamic() || options.isSet("invokedynamic"); duke@1: duke@1: generateIproxies = duke@1: target.requiresIproxy() || jjg@700: options.isSet("miranda"); duke@1: duke@1: if (target.generateStackMapTable()) { duke@1: // ignore cldc because we cannot have both stackmap formats duke@1: this.stackMap = StackMapFormat.JSR202; duke@1: } else { duke@1: if (target.generateCLDCStackmap()) { duke@1: this.stackMap = StackMapFormat.CLDC; duke@1: } else { duke@1: this.stackMap = StackMapFormat.NONE; duke@1: } duke@1: } duke@1: duke@1: // by default, avoid jsr's for simple finalizers duke@1: int setjsrlimit = 50; duke@1: String jsrlimitString = options.get("jsrlimit"); duke@1: if (jsrlimitString != null) { duke@1: try { duke@1: setjsrlimit = Integer.parseInt(jsrlimitString); duke@1: } catch (NumberFormatException ex) { duke@1: // ignore ill-formed numbers for jsrlimit duke@1: } duke@1: } duke@1: this.jsrlimit = setjsrlimit; duke@1: this.useJsrLocally = false; // reset in visitTry duke@1: } duke@1: duke@1: /** Switches duke@1: */ duke@1: private final boolean lineDebugInfo; duke@1: private final boolean varDebugInfo; duke@1: private final boolean genCrt; duke@1: private final boolean debugCode; jrose@267: private final boolean allowInvokedynamic; duke@1: duke@1: /** Default limit of (approximate) size of finalizer to inline. duke@1: * Zero means always use jsr. 100 or greater means never use duke@1: * jsr. duke@1: */ duke@1: private final int jsrlimit; duke@1: duke@1: /** True if jsr is used. duke@1: */ duke@1: private boolean useJsrLocally; duke@1: duke@1: /* Constant pool, reset by genClass. duke@1: */ duke@1: private Pool pool = new Pool(); duke@1: duke@1: /** Code buffer, set by genMethod. duke@1: */ duke@1: private Code code; duke@1: duke@1: /** Items structure, set by genMethod. duke@1: */ duke@1: private Items items; duke@1: duke@1: /** Environment for symbol lookup, set by genClass duke@1: */ duke@1: private Env attrEnv; duke@1: duke@1: /** The top level tree. duke@1: */ duke@1: private JCCompilationUnit toplevel; duke@1: duke@1: /** The number of code-gen errors in this class. duke@1: */ duke@1: private int nerrs = 0; duke@1: duke@1: /** A hash table mapping syntax trees to their ending source positions. duke@1: */ duke@1: private Map endPositions; duke@1: duke@1: /** Generate code to load an integer constant. duke@1: * @param n The integer to be loaded. duke@1: */ duke@1: void loadIntConst(int n) { duke@1: items.makeImmediateItem(syms.intType, n).load(); duke@1: } duke@1: duke@1: /** The opcode that loads a zero constant of a given type code. duke@1: * @param tc The given type code (@see ByteCode). duke@1: */ duke@1: public static int zero(int tc) { duke@1: switch(tc) { duke@1: case INTcode: case BYTEcode: case SHORTcode: case CHARcode: duke@1: return iconst_0; duke@1: case LONGcode: duke@1: return lconst_0; duke@1: case FLOATcode: duke@1: return fconst_0; duke@1: case DOUBLEcode: duke@1: return dconst_0; duke@1: default: duke@1: throw new AssertionError("zero"); duke@1: } duke@1: } duke@1: duke@1: /** The opcode that loads a one constant of a given type code. duke@1: * @param tc The given type code (@see ByteCode). duke@1: */ duke@1: public static int one(int tc) { duke@1: return zero(tc) + 1; duke@1: } duke@1: duke@1: /** Generate code to load -1 of the given type code (either int or long). duke@1: * @param tc The given type code (@see ByteCode). duke@1: */ duke@1: void emitMinusOne(int tc) { duke@1: if (tc == LONGcode) { duke@1: items.makeImmediateItem(syms.longType, new Long(-1)).load(); duke@1: } else { duke@1: code.emitop0(iconst_m1); duke@1: } duke@1: } duke@1: duke@1: /** Construct a symbol to reflect the qualifying type that should duke@1: * appear in the byte code as per JLS 13.1. duke@1: * duke@1: * For target >= 1.2: Clone a method with the qualifier as owner (except duke@1: * for those cases where we need to work around VM bugs). duke@1: * duke@1: * For target <= 1.1: If qualified variable or method is defined in a duke@1: * non-accessible class, clone it with the qualifier class as owner. duke@1: * duke@1: * @param sym The accessed symbol duke@1: * @param site The qualifier's type. duke@1: */ duke@1: Symbol binaryQualifier(Symbol sym, Type site) { duke@1: duke@1: if (site.tag == ARRAY) { duke@1: if (sym == syms.lengthVar || duke@1: sym.owner != syms.arrayClass) duke@1: return sym; duke@1: // array clone can be qualified by the array type in later targets duke@1: Symbol qualifier = target.arrayBinaryCompatibility() duke@1: ? new ClassSymbol(Flags.PUBLIC, site.tsym.name, duke@1: site, syms.noSymbol) duke@1: : syms.objectType.tsym; duke@1: return sym.clone(qualifier); duke@1: } duke@1: duke@1: if (sym.owner == site.tsym || duke@1: (sym.flags() & (STATIC | SYNTHETIC)) == (STATIC | SYNTHETIC)) { duke@1: return sym; duke@1: } duke@1: if (!target.obeyBinaryCompatibility()) duke@1: return rs.isAccessible(attrEnv, (TypeSymbol)sym.owner) duke@1: ? sym duke@1: : sym.clone(site.tsym); duke@1: duke@1: if (!target.interfaceFieldsBinaryCompatibility()) { duke@1: if ((sym.owner.flags() & INTERFACE) != 0 && sym.kind == VAR) duke@1: return sym; duke@1: } duke@1: duke@1: // leave alone methods inherited from Object duke@1: // JLS2 13.1. duke@1: if (sym.owner == syms.objectType.tsym) duke@1: return sym; duke@1: duke@1: if (!target.interfaceObjectOverridesBinaryCompatibility()) { duke@1: if ((sym.owner.flags() & INTERFACE) != 0 && duke@1: syms.objectType.tsym.members().lookup(sym.name).scope != null) duke@1: return sym; duke@1: } duke@1: duke@1: return sym.clone(site.tsym); duke@1: } duke@1: duke@1: /** Insert a reference to given type in the constant pool, duke@1: * checking for an array with too many dimensions; duke@1: * return the reference's index. duke@1: * @param type The type for which a reference is inserted. duke@1: */ duke@1: int makeRef(DiagnosticPosition pos, Type type) { duke@1: checkDimension(pos, type); duke@1: return pool.put(type.tag == CLASS ? (Object)type.tsym : (Object)type); duke@1: } duke@1: duke@1: /** Check if the given type is an array with too many dimensions. duke@1: */ duke@1: private void checkDimension(DiagnosticPosition pos, Type t) { duke@1: switch (t.tag) { duke@1: case METHOD: duke@1: checkDimension(pos, t.getReturnType()); duke@1: for (List args = t.getParameterTypes(); args.nonEmpty(); args = args.tail) duke@1: checkDimension(pos, args.head); duke@1: break; duke@1: case ARRAY: duke@1: if (types.dimensions(t) > ClassFile.MAX_DIMENSIONS) { duke@1: log.error(pos, "limit.dimensions"); duke@1: nerrs++; duke@1: } duke@1: break; duke@1: default: duke@1: break; duke@1: } duke@1: } duke@1: duke@1: /** Create a tempory variable. duke@1: * @param type The variable's type. duke@1: */ duke@1: LocalItem makeTemp(Type type) { duke@1: VarSymbol v = new VarSymbol(Flags.SYNTHETIC, duke@1: names.empty, duke@1: type, duke@1: env.enclMethod.sym); duke@1: code.newLocal(v); duke@1: return items.makeLocalItem(v); duke@1: } duke@1: duke@1: /** Generate code to call a non-private method or constructor. duke@1: * @param pos Position to be used for error reporting. duke@1: * @param site The type of which the method is a member. duke@1: * @param name The method's name. duke@1: * @param argtypes The method's argument types. duke@1: * @param isStatic A flag that indicates whether we call a duke@1: * static or instance method. duke@1: */ duke@1: void callMethod(DiagnosticPosition pos, duke@1: Type site, Name name, List argtypes, duke@1: boolean isStatic) { duke@1: Symbol msym = rs. duke@1: resolveInternalMethod(pos, attrEnv, site, name, argtypes, null); duke@1: if (isStatic) items.makeStaticItem(msym).invoke(); duke@1: else items.makeMemberItem(msym, name == names.init).invoke(); duke@1: } duke@1: duke@1: /** Is the given method definition an access method duke@1: * resulting from a qualified super? This is signified by an odd duke@1: * access code. duke@1: */ duke@1: private boolean isAccessSuper(JCMethodDecl enclMethod) { duke@1: return duke@1: (enclMethod.mods.flags & SYNTHETIC) != 0 && duke@1: isOddAccessName(enclMethod.name); duke@1: } duke@1: duke@1: /** Does given name start with "access$" and end in an odd digit? duke@1: */ duke@1: private boolean isOddAccessName(Name name) { duke@1: return duke@1: name.startsWith(accessDollar) && jjg@113: (name.getByteAt(name.getByteLength() - 1) & 1) == 1; duke@1: } duke@1: duke@1: /* ************************************************************************ duke@1: * Non-local exits duke@1: *************************************************************************/ duke@1: duke@1: /** Generate code to invoke the finalizer associated with given duke@1: * environment. duke@1: * Any calls to finalizers are appended to the environments `cont' chain. duke@1: * Mark beginning of gap in catch all range for finalizer. duke@1: */ duke@1: void genFinalizer(Env env) { duke@1: if (code.isAlive() && env.info.finalize != null) duke@1: env.info.finalize.gen(); duke@1: } duke@1: duke@1: /** Generate code to call all finalizers of structures aborted by duke@1: * a non-local duke@1: * exit. Return target environment of the non-local exit. duke@1: * @param target The tree representing the structure that's aborted duke@1: * @param env The environment current at the non-local exit. duke@1: */ duke@1: Env unwind(JCTree target, Env env) { duke@1: Env env1 = env; duke@1: while (true) { duke@1: genFinalizer(env1); duke@1: if (env1.tree == target) break; duke@1: env1 = env1.next; duke@1: } duke@1: return env1; duke@1: } duke@1: duke@1: /** Mark end of gap in catch-all range for finalizer. duke@1: * @param env the environment which might contain the finalizer duke@1: * (if it does, env.info.gaps != null). duke@1: */ duke@1: void endFinalizerGap(Env env) { duke@1: if (env.info.gaps != null && env.info.gaps.length() % 2 == 1) duke@1: env.info.gaps.append(code.curPc()); duke@1: } duke@1: duke@1: /** Mark end of all gaps in catch-all ranges for finalizers of environments duke@1: * lying between, and including to two environments. duke@1: * @param from the most deeply nested environment to mark duke@1: * @param to the least deeply nested environment to mark duke@1: */ duke@1: void endFinalizerGaps(Env from, Env to) { duke@1: Env last = null; duke@1: while (last != to) { duke@1: endFinalizerGap(from); duke@1: last = from; duke@1: from = from.next; duke@1: } duke@1: } duke@1: duke@1: /** Do any of the structures aborted by a non-local exit have duke@1: * finalizers that require an empty stack? duke@1: * @param target The tree representing the structure that's aborted duke@1: * @param env The environment current at the non-local exit. duke@1: */ duke@1: boolean hasFinally(JCTree target, Env env) { duke@1: while (env.tree != target) { duke@1: if (env.tree.getTag() == JCTree.TRY && env.info.finalize.hasFinalizer()) duke@1: return true; duke@1: env = env.next; duke@1: } duke@1: return false; duke@1: } duke@1: duke@1: /* ************************************************************************ duke@1: * Normalizing class-members. duke@1: *************************************************************************/ duke@1: duke@1: /** Distribute member initializer code into constructors and duke@1: * method. duke@1: * @param defs The list of class member declarations. duke@1: * @param c The enclosing class. duke@1: */ duke@1: List normalizeDefs(List defs, ClassSymbol c) { duke@1: ListBuffer initCode = new ListBuffer(); duke@1: ListBuffer clinitCode = new ListBuffer(); duke@1: ListBuffer methodDefs = new ListBuffer(); duke@1: // Sort definitions into three listbuffers: duke@1: // - initCode for instance initializers duke@1: // - clinitCode for class initializers duke@1: // - methodDefs for method definitions duke@1: for (List l = defs; l.nonEmpty(); l = l.tail) { duke@1: JCTree def = l.head; duke@1: switch (def.getTag()) { duke@1: case JCTree.BLOCK: duke@1: JCBlock block = (JCBlock)def; duke@1: if ((block.flags & STATIC) != 0) duke@1: clinitCode.append(block); duke@1: else duke@1: initCode.append(block); duke@1: break; duke@1: case JCTree.METHODDEF: duke@1: methodDefs.append(def); duke@1: break; duke@1: case JCTree.VARDEF: duke@1: JCVariableDecl vdef = (JCVariableDecl) def; duke@1: VarSymbol sym = vdef.sym; duke@1: checkDimension(vdef.pos(), sym.type); duke@1: if (vdef.init != null) { duke@1: if ((sym.flags() & STATIC) == 0) { duke@1: // Always initialize instance variables. duke@1: JCStatement init = make.at(vdef.pos()). duke@1: Assignment(sym, vdef.init); duke@1: initCode.append(init); duke@1: if (endPositions != null) { duke@1: Integer endPos = endPositions.remove(vdef); duke@1: if (endPos != null) endPositions.put(init, endPos); duke@1: } duke@1: } else if (sym.getConstValue() == null) { duke@1: // Initialize class (static) variables only if duke@1: // they are not compile-time constants. duke@1: JCStatement init = make.at(vdef.pos). duke@1: Assignment(sym, vdef.init); duke@1: clinitCode.append(init); duke@1: if (endPositions != null) { duke@1: Integer endPos = endPositions.remove(vdef); duke@1: if (endPos != null) endPositions.put(init, endPos); duke@1: } duke@1: } else { duke@1: checkStringConstant(vdef.init.pos(), sym.getConstValue()); duke@1: } duke@1: } duke@1: break; duke@1: default: jjg@816: Assert.error(); duke@1: } duke@1: } duke@1: // Insert any instance initializers into all constructors. duke@1: if (initCode.length() != 0) { duke@1: List inits = initCode.toList(); duke@1: for (JCTree t : methodDefs) { duke@1: normalizeMethod((JCMethodDecl)t, inits); duke@1: } duke@1: } duke@1: // If there are class initializers, create a method duke@1: // that contains them as its body. duke@1: if (clinitCode.length() != 0) { duke@1: MethodSymbol clinit = new MethodSymbol( duke@1: STATIC, names.clinit, duke@1: new MethodType( duke@1: List.nil(), syms.voidType, duke@1: List.nil(), syms.methodClass), duke@1: c); duke@1: c.members().enter(clinit); duke@1: List clinitStats = clinitCode.toList(); duke@1: JCBlock block = make.at(clinitStats.head.pos()).Block(0, clinitStats); duke@1: block.endpos = TreeInfo.endPos(clinitStats.last()); duke@1: methodDefs.append(make.MethodDef(clinit, block)); duke@1: } duke@1: // Return all method definitions. duke@1: return methodDefs.toList(); duke@1: } duke@1: duke@1: /** Check a constant value and report if it is a string that is duke@1: * too large. duke@1: */ duke@1: private void checkStringConstant(DiagnosticPosition pos, Object constValue) { duke@1: if (nerrs != 0 || // only complain about a long string once duke@1: constValue == null || duke@1: !(constValue instanceof String) || duke@1: ((String)constValue).length() < Pool.MAX_STRING_LENGTH) duke@1: return; duke@1: log.error(pos, "limit.string"); duke@1: nerrs++; duke@1: } duke@1: duke@1: /** Insert instance initializer code into initial constructor. duke@1: * @param md The tree potentially representing a duke@1: * constructor's definition. duke@1: * @param initCode The list of instance initializer statements. duke@1: */ duke@1: void normalizeMethod(JCMethodDecl md, List initCode) { duke@1: if (md.name == names.init && TreeInfo.isInitialConstructor(md)) { duke@1: // We are seeing a constructor that does not call another duke@1: // constructor of the same class. duke@1: List stats = md.body.stats; duke@1: ListBuffer newstats = new ListBuffer(); duke@1: duke@1: if (stats.nonEmpty()) { duke@1: // Copy initializers of synthetic variables generated in duke@1: // the translation of inner classes. duke@1: while (TreeInfo.isSyntheticInit(stats.head)) { duke@1: newstats.append(stats.head); duke@1: stats = stats.tail; duke@1: } duke@1: // Copy superclass constructor call duke@1: newstats.append(stats.head); duke@1: stats = stats.tail; duke@1: // Copy remaining synthetic initializers. duke@1: while (stats.nonEmpty() && duke@1: TreeInfo.isSyntheticInit(stats.head)) { duke@1: newstats.append(stats.head); duke@1: stats = stats.tail; duke@1: } duke@1: // Now insert the initializer code. duke@1: newstats.appendList(initCode); duke@1: // And copy all remaining statements. duke@1: while (stats.nonEmpty()) { duke@1: newstats.append(stats.head); duke@1: stats = stats.tail; duke@1: } duke@1: } duke@1: md.body.stats = newstats.toList(); duke@1: if (md.body.endpos == Position.NOPOS) duke@1: md.body.endpos = TreeInfo.endPos(md.body.stats.last()); duke@1: } duke@1: } duke@1: duke@1: /* ******************************************************************** duke@1: * Adding miranda methods duke@1: *********************************************************************/ duke@1: duke@1: /** Add abstract methods for all methods defined in one of duke@1: * the interfaces of a given class, duke@1: * provided they are not already implemented in the class. duke@1: * duke@1: * @param c The class whose interfaces are searched for methods duke@1: * for which Miranda methods should be added. duke@1: */ duke@1: void implementInterfaceMethods(ClassSymbol c) { duke@1: implementInterfaceMethods(c, c); duke@1: } duke@1: duke@1: /** Add abstract methods for all methods defined in one of duke@1: * the interfaces of a given class, duke@1: * provided they are not already implemented in the class. duke@1: * duke@1: * @param c The class whose interfaces are searched for methods duke@1: * for which Miranda methods should be added. duke@1: * @param site The class in which a definition may be needed. duke@1: */ duke@1: void implementInterfaceMethods(ClassSymbol c, ClassSymbol site) { duke@1: for (List l = types.interfaces(c.type); l.nonEmpty(); l = l.tail) { duke@1: ClassSymbol i = (ClassSymbol)l.head.tsym; duke@1: for (Scope.Entry e = i.members().elems; duke@1: e != null; duke@1: e = e.sibling) duke@1: { duke@1: if (e.sym.kind == MTH && (e.sym.flags() & STATIC) == 0) duke@1: { duke@1: MethodSymbol absMeth = (MethodSymbol)e.sym; duke@1: MethodSymbol implMeth = absMeth.binaryImplementation(site, types); duke@1: if (implMeth == null) duke@1: addAbstractMethod(site, absMeth); duke@1: else if ((implMeth.flags() & IPROXY) != 0) duke@1: adjustAbstractMethod(site, implMeth, absMeth); duke@1: } duke@1: } duke@1: implementInterfaceMethods(i, site); duke@1: } duke@1: } duke@1: duke@1: /** Add an abstract methods to a class duke@1: * which implicitly implements a method defined in some interface duke@1: * implemented by the class. These methods are called "Miranda methods". duke@1: * Enter the newly created method into its enclosing class scope. duke@1: * Note that it is not entered into the class tree, as the emitter duke@1: * doesn't need to see it there to emit an abstract method. duke@1: * duke@1: * @param c The class to which the Miranda method is added. duke@1: * @param m The interface method symbol for which a Miranda method duke@1: * is added. duke@1: */ duke@1: private void addAbstractMethod(ClassSymbol c, duke@1: MethodSymbol m) { duke@1: MethodSymbol absMeth = new MethodSymbol( duke@1: m.flags() | IPROXY | SYNTHETIC, m.name, duke@1: m.type, // was c.type.memberType(m), but now only !generics supported duke@1: c); duke@1: c.members().enter(absMeth); // add to symbol table duke@1: } duke@1: duke@1: private void adjustAbstractMethod(ClassSymbol c, duke@1: MethodSymbol pm, duke@1: MethodSymbol im) { duke@1: MethodType pmt = (MethodType)pm.type; duke@1: Type imt = types.memberType(c.type, im); duke@1: pmt.thrown = chk.intersect(pmt.getThrownTypes(), imt.getThrownTypes()); duke@1: } duke@1: duke@1: /* ************************************************************************ duke@1: * Traversal methods duke@1: *************************************************************************/ duke@1: duke@1: /** Visitor argument: The current environment. duke@1: */ duke@1: Env env; duke@1: duke@1: /** Visitor argument: The expected type (prototype). duke@1: */ duke@1: Type pt; duke@1: duke@1: /** Visitor result: The item representing the computed value. duke@1: */ duke@1: Item result; duke@1: duke@1: /** Visitor method: generate code for a definition, catching and reporting duke@1: * any completion failures. duke@1: * @param tree The definition to be visited. duke@1: * @param env The environment current at the definition. duke@1: */ duke@1: public void genDef(JCTree tree, Env env) { duke@1: Env prevEnv = this.env; duke@1: try { duke@1: this.env = env; duke@1: tree.accept(this); duke@1: } catch (CompletionFailure ex) { duke@1: chk.completionError(tree.pos(), ex); duke@1: } finally { duke@1: this.env = prevEnv; duke@1: } duke@1: } duke@1: duke@1: /** Derived visitor method: check whether CharacterRangeTable duke@1: * should be emitted, if so, put a new entry into CRTable duke@1: * and call method to generate bytecode. duke@1: * If not, just call method to generate bytecode. duke@1: * @see #genStat(Tree, Env) duke@1: * duke@1: * @param tree The tree to be visited. duke@1: * @param env The environment to use. duke@1: * @param crtFlags The CharacterRangeTable flags duke@1: * indicating type of the entry. duke@1: */ duke@1: public void genStat(JCTree tree, Env env, int crtFlags) { duke@1: if (!genCrt) { duke@1: genStat(tree, env); duke@1: return; duke@1: } duke@1: int startpc = code.curPc(); duke@1: genStat(tree, env); duke@1: if (tree.getTag() == JCTree.BLOCK) crtFlags |= CRT_BLOCK; duke@1: code.crt.put(tree, crtFlags, startpc, code.curPc()); duke@1: } duke@1: duke@1: /** Derived visitor method: generate code for a statement. duke@1: */ duke@1: public void genStat(JCTree tree, Env env) { duke@1: if (code.isAlive()) { duke@1: code.statBegin(tree.pos); duke@1: genDef(tree, env); duke@1: } else if (env.info.isSwitch && tree.getTag() == JCTree.VARDEF) { duke@1: // variables whose declarations are in a switch duke@1: // can be used even if the decl is unreachable. duke@1: code.newLocal(((JCVariableDecl) tree).sym); duke@1: } duke@1: } duke@1: duke@1: /** Derived visitor method: check whether CharacterRangeTable duke@1: * should be emitted, if so, put a new entry into CRTable duke@1: * and call method to generate bytecode. duke@1: * If not, just call method to generate bytecode. duke@1: * @see #genStats(List, Env) duke@1: * duke@1: * @param trees The list of trees to be visited. duke@1: * @param env The environment to use. duke@1: * @param crtFlags The CharacterRangeTable flags duke@1: * indicating type of the entry. duke@1: */ duke@1: public void genStats(List trees, Env env, int crtFlags) { duke@1: if (!genCrt) { duke@1: genStats(trees, env); duke@1: return; duke@1: } duke@1: if (trees.length() == 1) { // mark one statement with the flags duke@1: genStat(trees.head, env, crtFlags | CRT_STATEMENT); duke@1: } else { duke@1: int startpc = code.curPc(); duke@1: genStats(trees, env); duke@1: code.crt.put(trees, crtFlags, startpc, code.curPc()); duke@1: } duke@1: } duke@1: duke@1: /** Derived visitor method: generate code for a list of statements. duke@1: */ duke@1: public void genStats(List trees, Env env) { duke@1: for (List l = trees; l.nonEmpty(); l = l.tail) duke@1: genStat(l.head, env, CRT_STATEMENT); duke@1: } duke@1: duke@1: /** Derived visitor method: check whether CharacterRangeTable duke@1: * should be emitted, if so, put a new entry into CRTable duke@1: * and call method to generate bytecode. duke@1: * If not, just call method to generate bytecode. duke@1: * @see #genCond(Tree,boolean) duke@1: * duke@1: * @param tree The tree to be visited. duke@1: * @param crtFlags The CharacterRangeTable flags duke@1: * indicating type of the entry. duke@1: */ duke@1: public CondItem genCond(JCTree tree, int crtFlags) { duke@1: if (!genCrt) return genCond(tree, false); duke@1: int startpc = code.curPc(); duke@1: CondItem item = genCond(tree, (crtFlags & CRT_FLOW_CONTROLLER) != 0); duke@1: code.crt.put(tree, crtFlags, startpc, code.curPc()); duke@1: return item; duke@1: } duke@1: duke@1: /** Derived visitor method: generate code for a boolean duke@1: * expression in a control-flow context. duke@1: * @param _tree The expression to be visited. duke@1: * @param markBranches The flag to indicate that the condition is duke@1: * a flow controller so produced conditions duke@1: * should contain a proper tree to generate duke@1: * CharacterRangeTable branches for them. duke@1: */ duke@1: public CondItem genCond(JCTree _tree, boolean markBranches) { duke@1: JCTree inner_tree = TreeInfo.skipParens(_tree); duke@1: if (inner_tree.getTag() == JCTree.CONDEXPR) { duke@1: JCConditional tree = (JCConditional)inner_tree; duke@1: CondItem cond = genCond(tree.cond, CRT_FLOW_CONTROLLER); duke@1: if (cond.isTrue()) { duke@1: code.resolve(cond.trueJumps); duke@1: CondItem result = genCond(tree.truepart, CRT_FLOW_TARGET); duke@1: if (markBranches) result.tree = tree.truepart; duke@1: return result; duke@1: } duke@1: if (cond.isFalse()) { duke@1: code.resolve(cond.falseJumps); duke@1: CondItem result = genCond(tree.falsepart, CRT_FLOW_TARGET); duke@1: if (markBranches) result.tree = tree.falsepart; duke@1: return result; duke@1: } duke@1: Chain secondJumps = cond.jumpFalse(); duke@1: code.resolve(cond.trueJumps); duke@1: CondItem first = genCond(tree.truepart, CRT_FLOW_TARGET); duke@1: if (markBranches) first.tree = tree.truepart; duke@1: Chain falseJumps = first.jumpFalse(); duke@1: code.resolve(first.trueJumps); duke@1: Chain trueJumps = code.branch(goto_); duke@1: code.resolve(secondJumps); duke@1: CondItem second = genCond(tree.falsepart, CRT_FLOW_TARGET); duke@1: CondItem result = items.makeCondItem(second.opcode, jjg@507: Code.mergeChains(trueJumps, second.trueJumps), jjg@507: Code.mergeChains(falseJumps, second.falseJumps)); duke@1: if (markBranches) result.tree = tree.falsepart; duke@1: return result; duke@1: } else { duke@1: CondItem result = genExpr(_tree, syms.booleanType).mkCond(); duke@1: if (markBranches) result.tree = _tree; duke@1: return result; duke@1: } duke@1: } duke@1: duke@1: /** Visitor method: generate code for an expression, catching and reporting duke@1: * any completion failures. duke@1: * @param tree The expression to be visited. duke@1: * @param pt The expression's expected type (proto-type). duke@1: */ duke@1: public Item genExpr(JCTree tree, Type pt) { duke@1: Type prevPt = this.pt; duke@1: try { duke@1: if (tree.type.constValue() != null) { duke@1: // Short circuit any expressions which are constants duke@1: checkStringConstant(tree.pos(), tree.type.constValue()); duke@1: result = items.makeImmediateItem(tree.type, tree.type.constValue()); duke@1: } else { duke@1: this.pt = pt; duke@1: tree.accept(this); duke@1: } duke@1: return result.coerce(pt); duke@1: } catch (CompletionFailure ex) { duke@1: chk.completionError(tree.pos(), ex); duke@1: code.state.stacksize = 1; duke@1: return items.makeStackItem(pt); duke@1: } finally { duke@1: this.pt = prevPt; duke@1: } duke@1: } duke@1: duke@1: /** Derived visitor method: generate code for a list of method arguments. duke@1: * @param trees The argument expressions to be visited. duke@1: * @param pts The expression's expected types (i.e. the formal parameter duke@1: * types of the invoked method). duke@1: */ duke@1: public void genArgs(List trees, List pts) { duke@1: for (List l = trees; l.nonEmpty(); l = l.tail) { duke@1: genExpr(l.head, pts.head).load(); duke@1: pts = pts.tail; duke@1: } duke@1: // require lists be of same length jjg@816: Assert.check(pts.isEmpty()); duke@1: } duke@1: duke@1: /* ************************************************************************ duke@1: * Visitor methods for statements and definitions duke@1: *************************************************************************/ duke@1: duke@1: /** Thrown when the byte code size exceeds limit. duke@1: */ duke@1: public static class CodeSizeOverflow extends RuntimeException { duke@1: private static final long serialVersionUID = 0; duke@1: public CodeSizeOverflow() {} duke@1: } duke@1: duke@1: public void visitMethodDef(JCMethodDecl tree) { duke@1: // Create a new local environment that points pack at method duke@1: // definition. duke@1: Env localEnv = env.dup(tree); duke@1: localEnv.enclMethod = tree; duke@1: duke@1: // The expected type of every return statement in this method duke@1: // is the method's return type. duke@1: this.pt = tree.sym.erasure(types).getReturnType(); duke@1: duke@1: checkDimension(tree.pos(), tree.sym.erasure(types)); duke@1: genMethod(tree, localEnv, false); duke@1: } duke@1: //where duke@1: /** Generate code for a method. duke@1: * @param tree The tree representing the method definition. duke@1: * @param env The environment current for the method body. duke@1: * @param fatcode A flag that indicates whether all jumps are duke@1: * within 32K. We first invoke this method under duke@1: * the assumption that fatcode == false, i.e. all duke@1: * jumps are within 32K. If this fails, fatcode duke@1: * is set to true and we try again. duke@1: */ duke@1: void genMethod(JCMethodDecl tree, Env env, boolean fatcode) { duke@1: MethodSymbol meth = tree.sym; duke@1: // System.err.println("Generating " + meth + " in " + meth.owner); //DEBUG duke@1: if (Code.width(types.erasure(env.enclMethod.sym.type).getParameterTypes()) + duke@1: (((tree.mods.flags & STATIC) == 0 || meth.isConstructor()) ? 1 : 0) > duke@1: ClassFile.MAX_PARAMETERS) { duke@1: log.error(tree.pos(), "limit.parameters"); duke@1: nerrs++; duke@1: } duke@1: duke@1: else if (tree.body != null) { duke@1: // Create a new code structure and initialize it. duke@1: int startpcCrt = initCode(tree, env, fatcode); duke@1: duke@1: try { duke@1: genStat(tree.body, env); duke@1: } catch (CodeSizeOverflow e) { duke@1: // Failed due to code limit, try again with jsr/ret duke@1: startpcCrt = initCode(tree, env, fatcode); duke@1: genStat(tree.body, env); duke@1: } duke@1: duke@1: if (code.state.stacksize != 0) { duke@1: log.error(tree.body.pos(), "stack.sim.error", tree); duke@1: throw new AssertionError(); duke@1: } duke@1: duke@1: // If last statement could complete normally, insert a duke@1: // return at the end. duke@1: if (code.isAlive()) { duke@1: code.statBegin(TreeInfo.endPos(tree.body)); duke@1: if (env.enclMethod == null || duke@1: env.enclMethod.sym.type.getReturnType().tag == VOID) { duke@1: code.emitop0(return_); duke@1: } else { duke@1: // sometime dead code seems alive (4415991); duke@1: // generate a small loop instead duke@1: int startpc = code.entryPoint(); duke@1: CondItem c = items.makeCondItem(goto_); duke@1: code.resolve(c.jumpTrue(), startpc); duke@1: } duke@1: } duke@1: if (genCrt) duke@1: code.crt.put(tree.body, duke@1: CRT_BLOCK, duke@1: startpcCrt, duke@1: code.curPc()); duke@1: duke@1: code.endScopes(0); duke@1: duke@1: // If we exceeded limits, panic duke@1: if (code.checkLimits(tree.pos(), log)) { duke@1: nerrs++; duke@1: return; duke@1: } duke@1: duke@1: // If we generated short code but got a long jump, do it again duke@1: // with fatCode = true. duke@1: if (!fatcode && code.fatcode) genMethod(tree, env, true); duke@1: duke@1: // Clean up duke@1: if(stackMap == StackMapFormat.JSR202) { duke@1: code.lastFrame = null; duke@1: code.frameBeforeLast = null; duke@1: } duke@1: } duke@1: } duke@1: duke@1: private int initCode(JCMethodDecl tree, Env env, boolean fatcode) { duke@1: MethodSymbol meth = tree.sym; duke@1: duke@1: // Create a new code structure. duke@1: meth.code = code = new Code(meth, duke@1: fatcode, duke@1: lineDebugInfo ? toplevel.lineMap : null, duke@1: varDebugInfo, duke@1: stackMap, duke@1: debugCode, duke@1: genCrt ? new CRTable(tree, env.toplevel.endPositions) duke@1: : null, duke@1: syms, duke@1: types, duke@1: pool); duke@1: items = new Items(pool, code, syms, types); duke@1: if (code.debugCode) duke@1: System.err.println(meth + " for body " + tree); duke@1: duke@1: // If method is not static, create a new local variable address duke@1: // for `this'. duke@1: if ((tree.mods.flags & STATIC) == 0) { duke@1: Type selfType = meth.owner.type; duke@1: if (meth.isConstructor() && selfType != syms.objectType) duke@1: selfType = UninitializedType.uninitializedThis(selfType); duke@1: code.setDefined( duke@1: code.newLocal( duke@1: new VarSymbol(FINAL, names._this, selfType, meth.owner))); duke@1: } duke@1: duke@1: // Mark all parameters as defined from the beginning of duke@1: // the method. duke@1: for (List l = tree.params; l.nonEmpty(); l = l.tail) { duke@1: checkDimension(l.head.pos(), l.head.sym.type); duke@1: code.setDefined(code.newLocal(l.head.sym)); duke@1: } duke@1: duke@1: // Get ready to generate code for method body. duke@1: int startpcCrt = genCrt ? code.curPc() : 0; duke@1: code.entryPoint(); duke@1: duke@1: // Suppress initial stackmap duke@1: code.pendingStackMap = false; duke@1: duke@1: return startpcCrt; duke@1: } duke@1: duke@1: public void visitVarDef(JCVariableDecl tree) { duke@1: VarSymbol v = tree.sym; duke@1: code.newLocal(v); duke@1: if (tree.init != null) { duke@1: checkStringConstant(tree.init.pos(), v.getConstValue()); duke@1: if (v.getConstValue() == null || varDebugInfo) { duke@1: genExpr(tree.init, v.erasure(types)).load(); duke@1: items.makeLocalItem(v).store(); duke@1: } duke@1: } duke@1: checkDimension(tree.pos(), v.type); duke@1: } duke@1: duke@1: public void visitSkip(JCSkip tree) { duke@1: } duke@1: duke@1: public void visitBlock(JCBlock tree) { duke@1: int limit = code.nextreg; duke@1: Env localEnv = env.dup(tree, new GenContext()); duke@1: genStats(tree.stats, localEnv); duke@1: // End the scope of all block-local variables in variable info. duke@1: if (env.tree.getTag() != JCTree.METHODDEF) { duke@1: code.statBegin(tree.endpos); duke@1: code.endScopes(limit); duke@1: code.pendingStatPos = Position.NOPOS; duke@1: } duke@1: } duke@1: duke@1: public void visitDoLoop(JCDoWhileLoop tree) { duke@1: genLoop(tree, tree.body, tree.cond, List.nil(), false); duke@1: } duke@1: duke@1: public void visitWhileLoop(JCWhileLoop tree) { duke@1: genLoop(tree, tree.body, tree.cond, List.nil(), true); duke@1: } duke@1: duke@1: public void visitForLoop(JCForLoop tree) { duke@1: int limit = code.nextreg; duke@1: genStats(tree.init, env); duke@1: genLoop(tree, tree.body, tree.cond, tree.step, true); duke@1: code.endScopes(limit); duke@1: } duke@1: //where duke@1: /** Generate code for a loop. duke@1: * @param loop The tree representing the loop. duke@1: * @param body The loop's body. duke@1: * @param cond The loop's controling condition. duke@1: * @param step "Step" statements to be inserted at end of duke@1: * each iteration. duke@1: * @param testFirst True if the loop test belongs before the body. duke@1: */ duke@1: private void genLoop(JCStatement loop, duke@1: JCStatement body, duke@1: JCExpression cond, duke@1: List step, duke@1: boolean testFirst) { duke@1: Env loopEnv = env.dup(loop, new GenContext()); duke@1: int startpc = code.entryPoint(); duke@1: if (testFirst) { duke@1: CondItem c; duke@1: if (cond != null) { duke@1: code.statBegin(cond.pos); duke@1: c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER); duke@1: } else { duke@1: c = items.makeCondItem(goto_); duke@1: } duke@1: Chain loopDone = c.jumpFalse(); duke@1: code.resolve(c.trueJumps); duke@1: genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET); duke@1: code.resolve(loopEnv.info.cont); duke@1: genStats(step, loopEnv); duke@1: code.resolve(code.branch(goto_), startpc); duke@1: code.resolve(loopDone); duke@1: } else { duke@1: genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET); duke@1: code.resolve(loopEnv.info.cont); duke@1: genStats(step, loopEnv); duke@1: CondItem c; duke@1: if (cond != null) { duke@1: code.statBegin(cond.pos); duke@1: c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER); duke@1: } else { duke@1: c = items.makeCondItem(goto_); duke@1: } duke@1: code.resolve(c.jumpTrue(), startpc); duke@1: code.resolve(c.falseJumps); duke@1: } duke@1: code.resolve(loopEnv.info.exit); duke@1: } duke@1: duke@1: public void visitForeachLoop(JCEnhancedForLoop tree) { duke@1: throw new AssertionError(); // should have been removed by Lower. duke@1: } duke@1: duke@1: public void visitLabelled(JCLabeledStatement tree) { duke@1: Env localEnv = env.dup(tree, new GenContext()); duke@1: genStat(tree.body, localEnv, CRT_STATEMENT); duke@1: code.resolve(localEnv.info.exit); duke@1: } duke@1: duke@1: public void visitSwitch(JCSwitch tree) { duke@1: int limit = code.nextreg; jjg@816: Assert.check(tree.selector.type.tag != CLASS); duke@1: int startpcCrt = genCrt ? code.curPc() : 0; duke@1: Item sel = genExpr(tree.selector, syms.intType); duke@1: List cases = tree.cases; duke@1: if (cases.isEmpty()) { duke@1: // We are seeing: switch {} duke@1: sel.load().drop(); duke@1: if (genCrt) duke@1: code.crt.put(TreeInfo.skipParens(tree.selector), duke@1: CRT_FLOW_CONTROLLER, startpcCrt, code.curPc()); duke@1: } else { duke@1: // We are seeing a nonempty switch. duke@1: sel.load(); duke@1: if (genCrt) duke@1: code.crt.put(TreeInfo.skipParens(tree.selector), duke@1: CRT_FLOW_CONTROLLER, startpcCrt, code.curPc()); duke@1: Env switchEnv = env.dup(tree, new GenContext()); duke@1: switchEnv.info.isSwitch = true; duke@1: duke@1: // Compute number of labels and minimum and maximum label values. duke@1: // For each case, store its label in an array. duke@1: int lo = Integer.MAX_VALUE; // minimum label. duke@1: int hi = Integer.MIN_VALUE; // maximum label. duke@1: int nlabels = 0; // number of labels. duke@1: duke@1: int[] labels = new int[cases.length()]; // the label array. duke@1: int defaultIndex = -1; // the index of the default clause. duke@1: duke@1: List l = cases; duke@1: for (int i = 0; i < labels.length; i++) { duke@1: if (l.head.pat != null) { duke@1: int val = ((Number)l.head.pat.type.constValue()).intValue(); duke@1: labels[i] = val; duke@1: if (val < lo) lo = val; duke@1: if (hi < val) hi = val; duke@1: nlabels++; duke@1: } else { jjg@816: Assert.check(defaultIndex == -1); duke@1: defaultIndex = i; duke@1: } duke@1: l = l.tail; duke@1: } duke@1: duke@1: // Determine whether to issue a tableswitch or a lookupswitch duke@1: // instruction. duke@1: long table_space_cost = 4 + ((long) hi - lo + 1); // words duke@1: long table_time_cost = 3; // comparisons duke@1: long lookup_space_cost = 3 + 2 * (long) nlabels; duke@1: long lookup_time_cost = nlabels; duke@1: int opcode = duke@1: nlabels > 0 && duke@1: table_space_cost + 3 * table_time_cost <= duke@1: lookup_space_cost + 3 * lookup_time_cost duke@1: ? duke@1: tableswitch : lookupswitch; duke@1: duke@1: int startpc = code.curPc(); // the position of the selector operation duke@1: code.emitop0(opcode); duke@1: code.align(4); duke@1: int tableBase = code.curPc(); // the start of the jump table duke@1: int[] offsets = null; // a table of offsets for a lookupswitch duke@1: code.emit4(-1); // leave space for default offset duke@1: if (opcode == tableswitch) { duke@1: code.emit4(lo); // minimum label duke@1: code.emit4(hi); // maximum label duke@1: for (long i = lo; i <= hi; i++) { // leave space for jump table duke@1: code.emit4(-1); duke@1: } duke@1: } else { duke@1: code.emit4(nlabels); // number of labels duke@1: for (int i = 0; i < nlabels; i++) { duke@1: code.emit4(-1); code.emit4(-1); // leave space for lookup table duke@1: } duke@1: offsets = new int[labels.length]; duke@1: } duke@1: Code.State stateSwitch = code.state.dup(); duke@1: code.markDead(); duke@1: duke@1: // For each case do: duke@1: l = cases; duke@1: for (int i = 0; i < labels.length; i++) { duke@1: JCCase c = l.head; duke@1: l = l.tail; duke@1: duke@1: int pc = code.entryPoint(stateSwitch); duke@1: // Insert offset directly into code or else into the duke@1: // offsets table. duke@1: if (i != defaultIndex) { duke@1: if (opcode == tableswitch) { duke@1: code.put4( duke@1: tableBase + 4 * (labels[i] - lo + 3), duke@1: pc - startpc); duke@1: } else { duke@1: offsets[i] = pc - startpc; duke@1: } duke@1: } else { duke@1: code.put4(tableBase, pc - startpc); duke@1: } duke@1: duke@1: // Generate code for the statements in this case. duke@1: genStats(c.stats, switchEnv, CRT_FLOW_TARGET); duke@1: } duke@1: duke@1: // Resolve all breaks. duke@1: code.resolve(switchEnv.info.exit); duke@1: duke@1: // If we have not set the default offset, we do so now. duke@1: if (code.get4(tableBase) == -1) { duke@1: code.put4(tableBase, code.entryPoint(stateSwitch) - startpc); duke@1: } duke@1: duke@1: if (opcode == tableswitch) { duke@1: // Let any unfilled slots point to the default case. duke@1: int defaultOffset = code.get4(tableBase); duke@1: for (long i = lo; i <= hi; i++) { duke@1: int t = (int)(tableBase + 4 * (i - lo + 3)); duke@1: if (code.get4(t) == -1) duke@1: code.put4(t, defaultOffset); duke@1: } duke@1: } else { duke@1: // Sort non-default offsets and copy into lookup table. duke@1: if (defaultIndex >= 0) duke@1: for (int i = defaultIndex; i < labels.length - 1; i++) { duke@1: labels[i] = labels[i+1]; duke@1: offsets[i] = offsets[i+1]; duke@1: } duke@1: if (nlabels > 0) duke@1: qsort2(labels, offsets, 0, nlabels - 1); duke@1: for (int i = 0; i < nlabels; i++) { duke@1: int caseidx = tableBase + 8 * (i + 1); duke@1: code.put4(caseidx, labels[i]); duke@1: code.put4(caseidx + 4, offsets[i]); duke@1: } duke@1: } duke@1: } duke@1: code.endScopes(limit); duke@1: } duke@1: //where duke@1: /** Sort (int) arrays of keys and values duke@1: */ duke@1: static void qsort2(int[] keys, int[] values, int lo, int hi) { duke@1: int i = lo; duke@1: int j = hi; duke@1: int pivot = keys[(i+j)/2]; duke@1: do { duke@1: while (keys[i] < pivot) i++; duke@1: while (pivot < keys[j]) j--; duke@1: if (i <= j) { duke@1: int temp1 = keys[i]; duke@1: keys[i] = keys[j]; duke@1: keys[j] = temp1; duke@1: int temp2 = values[i]; duke@1: values[i] = values[j]; duke@1: values[j] = temp2; duke@1: i++; duke@1: j--; duke@1: } duke@1: } while (i <= j); duke@1: if (lo < j) qsort2(keys, values, lo, j); duke@1: if (i < hi) qsort2(keys, values, i, hi); duke@1: } duke@1: duke@1: public void visitSynchronized(JCSynchronized tree) { duke@1: int limit = code.nextreg; duke@1: // Generate code to evaluate lock and save in temporary variable. duke@1: final LocalItem lockVar = makeTemp(syms.objectType); duke@1: genExpr(tree.lock, tree.lock.type).load().duplicate(); duke@1: lockVar.store(); duke@1: duke@1: // Generate code to enter monitor. duke@1: code.emitop0(monitorenter); duke@1: code.state.lock(lockVar.reg); duke@1: duke@1: // Generate code for a try statement with given body, no catch clauses duke@1: // in a new environment with the "exit-monitor" operation as finalizer. duke@1: final Env syncEnv = env.dup(tree, new GenContext()); duke@1: syncEnv.info.finalize = new GenFinalizer() { duke@1: void gen() { duke@1: genLast(); jjg@816: Assert.check(syncEnv.info.gaps.length() % 2 == 0); duke@1: syncEnv.info.gaps.append(code.curPc()); duke@1: } duke@1: void genLast() { duke@1: if (code.isAlive()) { duke@1: lockVar.load(); duke@1: code.emitop0(monitorexit); duke@1: code.state.unlock(lockVar.reg); duke@1: } duke@1: } duke@1: }; duke@1: syncEnv.info.gaps = new ListBuffer(); duke@1: genTry(tree.body, List.nil(), syncEnv); duke@1: code.endScopes(limit); duke@1: } duke@1: duke@1: public void visitTry(final JCTry tree) { duke@1: // Generate code for a try statement with given body and catch clauses, duke@1: // in a new environment which calls the finally block if there is one. duke@1: final Env tryEnv = env.dup(tree, new GenContext()); duke@1: final Env oldEnv = env; duke@1: if (!useJsrLocally) { duke@1: useJsrLocally = duke@1: (stackMap == StackMapFormat.NONE) && duke@1: (jsrlimit <= 0 || duke@1: jsrlimit < 100 && duke@1: estimateCodeComplexity(tree.finalizer)>jsrlimit); duke@1: } duke@1: tryEnv.info.finalize = new GenFinalizer() { duke@1: void gen() { duke@1: if (useJsrLocally) { duke@1: if (tree.finalizer != null) { duke@1: Code.State jsrState = code.state.dup(); jjg@507: jsrState.push(Code.jsrReturnValue); duke@1: tryEnv.info.cont = duke@1: new Chain(code.emitJump(jsr), duke@1: tryEnv.info.cont, duke@1: jsrState); duke@1: } jjg@816: Assert.check(tryEnv.info.gaps.length() % 2 == 0); duke@1: tryEnv.info.gaps.append(code.curPc()); duke@1: } else { jjg@816: Assert.check(tryEnv.info.gaps.length() % 2 == 0); duke@1: tryEnv.info.gaps.append(code.curPc()); duke@1: genLast(); duke@1: } duke@1: } duke@1: void genLast() { duke@1: if (tree.finalizer != null) duke@1: genStat(tree.finalizer, oldEnv, CRT_BLOCK); duke@1: } duke@1: boolean hasFinalizer() { duke@1: return tree.finalizer != null; duke@1: } duke@1: }; duke@1: tryEnv.info.gaps = new ListBuffer(); duke@1: genTry(tree.body, tree.catchers, tryEnv); duke@1: } duke@1: //where duke@1: /** Generate code for a try or synchronized statement duke@1: * @param body The body of the try or synchronized statement. duke@1: * @param catchers The lis of catch clauses. duke@1: * @param env the environment current for the body. duke@1: */ duke@1: void genTry(JCTree body, List catchers, Env env) { duke@1: int limit = code.nextreg; duke@1: int startpc = code.curPc(); duke@1: Code.State stateTry = code.state.dup(); duke@1: genStat(body, env, CRT_BLOCK); duke@1: int endpc = code.curPc(); duke@1: boolean hasFinalizer = duke@1: env.info.finalize != null && duke@1: env.info.finalize.hasFinalizer(); duke@1: List gaps = env.info.gaps.toList(); duke@1: code.statBegin(TreeInfo.endPos(body)); duke@1: genFinalizer(env); duke@1: code.statBegin(TreeInfo.endPos(env.tree)); duke@1: Chain exitChain = code.branch(goto_); duke@1: endFinalizerGap(env); duke@1: if (startpc != endpc) for (List l = catchers; l.nonEmpty(); l = l.tail) { duke@1: // start off with exception on stack duke@1: code.entryPoint(stateTry, l.head.param.sym.type); duke@1: genCatch(l.head, env, startpc, endpc, gaps); duke@1: genFinalizer(env); duke@1: if (hasFinalizer || l.tail.nonEmpty()) { duke@1: code.statBegin(TreeInfo.endPos(env.tree)); jjg@507: exitChain = Code.mergeChains(exitChain, duke@1: code.branch(goto_)); duke@1: } duke@1: endFinalizerGap(env); duke@1: } duke@1: if (hasFinalizer) { duke@1: // Create a new register segement to avoid allocating duke@1: // the same variables in finalizers and other statements. duke@1: code.newRegSegment(); duke@1: duke@1: // Add a catch-all clause. duke@1: duke@1: // start off with exception on stack duke@1: int catchallpc = code.entryPoint(stateTry, syms.throwableType); duke@1: duke@1: // Register all exception ranges for catch all clause. duke@1: // The range of the catch all clause is from the beginning duke@1: // of the try or synchronized block until the present duke@1: // code pointer excluding all gaps in the current duke@1: // environment's GenContext. duke@1: int startseg = startpc; duke@1: while (env.info.gaps.nonEmpty()) { duke@1: int endseg = env.info.gaps.next().intValue(); duke@1: registerCatch(body.pos(), startseg, endseg, duke@1: catchallpc, 0); duke@1: startseg = env.info.gaps.next().intValue(); duke@1: } duke@1: code.statBegin(TreeInfo.finalizerPos(env.tree)); duke@1: code.markStatBegin(); duke@1: duke@1: Item excVar = makeTemp(syms.throwableType); duke@1: excVar.store(); duke@1: genFinalizer(env); duke@1: excVar.load(); duke@1: registerCatch(body.pos(), startseg, duke@1: env.info.gaps.next().intValue(), duke@1: catchallpc, 0); duke@1: code.emitop0(athrow); duke@1: code.markDead(); duke@1: duke@1: // If there are jsr's to this finalizer, ... duke@1: if (env.info.cont != null) { duke@1: // Resolve all jsr's. duke@1: code.resolve(env.info.cont); duke@1: duke@1: // Mark statement line number duke@1: code.statBegin(TreeInfo.finalizerPos(env.tree)); duke@1: code.markStatBegin(); duke@1: duke@1: // Save return address. duke@1: LocalItem retVar = makeTemp(syms.throwableType); duke@1: retVar.store(); duke@1: duke@1: // Generate finalizer code. duke@1: env.info.finalize.genLast(); duke@1: duke@1: // Return. duke@1: code.emitop1w(ret, retVar.reg); duke@1: code.markDead(); duke@1: } duke@1: } duke@1: duke@1: // Resolve all breaks. duke@1: code.resolve(exitChain); duke@1: duke@1: code.endScopes(limit); duke@1: } duke@1: duke@1: /** Generate code for a catch clause. duke@1: * @param tree The catch clause. duke@1: * @param env The environment current in the enclosing try. duke@1: * @param startpc Start pc of try-block. duke@1: * @param endpc End pc of try-block. duke@1: */ duke@1: void genCatch(JCCatch tree, duke@1: Env env, duke@1: int startpc, int endpc, duke@1: List gaps) { duke@1: if (startpc != endpc) { mcimadamore@550: List subClauses = TreeInfo.isMultiCatch(tree) ? darcy@969: ((JCTypeUnion)tree.param.vartype).alternatives : mcimadamore@641: List.of(tree.param.vartype); mcimadamore@641: while (gaps.nonEmpty()) { mcimadamore@641: for (JCExpression subCatch : subClauses) { mcimadamore@641: int catchType = makeRef(tree.pos(), subCatch.type); mcimadamore@641: int end = gaps.head.intValue(); mcimadamore@550: registerCatch(tree.pos(), mcimadamore@550: startpc, end, code.curPc(), mcimadamore@550: catchType); mcimadamore@550: } mcimadamore@641: gaps = gaps.tail; mcimadamore@641: startpc = gaps.head.intValue(); mcimadamore@641: gaps = gaps.tail; mcimadamore@641: } mcimadamore@641: if (startpc < endpc) { mcimadamore@641: for (JCExpression subCatch : subClauses) { mcimadamore@641: int catchType = makeRef(tree.pos(), subCatch.type); mcimadamore@550: registerCatch(tree.pos(), mcimadamore@550: startpc, endpc, code.curPc(), mcimadamore@550: catchType); mcimadamore@641: } duke@1: } duke@1: VarSymbol exparam = tree.param.sym; duke@1: code.statBegin(tree.pos); duke@1: code.markStatBegin(); duke@1: int limit = code.nextreg; duke@1: int exlocal = code.newLocal(exparam); duke@1: items.makeLocalItem(exparam).store(); duke@1: code.statBegin(TreeInfo.firstStatPos(tree.body)); duke@1: genStat(tree.body, env, CRT_BLOCK); duke@1: code.endScopes(limit); duke@1: code.statBegin(TreeInfo.endPos(tree.body)); duke@1: } duke@1: } duke@1: duke@1: /** Register a catch clause in the "Exceptions" code-attribute. duke@1: */ duke@1: void registerCatch(DiagnosticPosition pos, duke@1: int startpc, int endpc, duke@1: int handler_pc, int catch_type) { duke@1: if (startpc != endpc) { duke@1: char startpc1 = (char)startpc; duke@1: char endpc1 = (char)endpc; duke@1: char handler_pc1 = (char)handler_pc; duke@1: if (startpc1 == startpc && duke@1: endpc1 == endpc && duke@1: handler_pc1 == handler_pc) { duke@1: code.addCatch(startpc1, endpc1, handler_pc1, duke@1: (char)catch_type); duke@1: } else { duke@1: if (!useJsrLocally && !target.generateStackMapTable()) { duke@1: useJsrLocally = true; duke@1: throw new CodeSizeOverflow(); duke@1: } else { duke@1: log.error(pos, "limit.code.too.large.for.try.stmt"); duke@1: nerrs++; duke@1: } duke@1: } duke@1: } duke@1: } duke@1: duke@1: /** Very roughly estimate the number of instructions needed for duke@1: * the given tree. duke@1: */ duke@1: int estimateCodeComplexity(JCTree tree) { duke@1: if (tree == null) return 0; duke@1: class ComplexityScanner extends TreeScanner { duke@1: int complexity = 0; duke@1: public void scan(JCTree tree) { duke@1: if (complexity > jsrlimit) return; duke@1: super.scan(tree); duke@1: } duke@1: public void visitClassDef(JCClassDecl tree) {} duke@1: public void visitDoLoop(JCDoWhileLoop tree) duke@1: { super.visitDoLoop(tree); complexity++; } duke@1: public void visitWhileLoop(JCWhileLoop tree) duke@1: { super.visitWhileLoop(tree); complexity++; } duke@1: public void visitForLoop(JCForLoop tree) duke@1: { super.visitForLoop(tree); complexity++; } duke@1: public void visitSwitch(JCSwitch tree) duke@1: { super.visitSwitch(tree); complexity+=5; } duke@1: public void visitCase(JCCase tree) duke@1: { super.visitCase(tree); complexity++; } duke@1: public void visitSynchronized(JCSynchronized tree) duke@1: { super.visitSynchronized(tree); complexity+=6; } duke@1: public void visitTry(JCTry tree) duke@1: { super.visitTry(tree); duke@1: if (tree.finalizer != null) complexity+=6; } duke@1: public void visitCatch(JCCatch tree) duke@1: { super.visitCatch(tree); complexity+=2; } duke@1: public void visitConditional(JCConditional tree) duke@1: { super.visitConditional(tree); complexity+=2; } duke@1: public void visitIf(JCIf tree) duke@1: { super.visitIf(tree); complexity+=2; } duke@1: // note: for break, continue, and return we don't take unwind() into account. duke@1: public void visitBreak(JCBreak tree) duke@1: { super.visitBreak(tree); complexity+=1; } duke@1: public void visitContinue(JCContinue tree) duke@1: { super.visitContinue(tree); complexity+=1; } duke@1: public void visitReturn(JCReturn tree) duke@1: { super.visitReturn(tree); complexity+=1; } duke@1: public void visitThrow(JCThrow tree) duke@1: { super.visitThrow(tree); complexity+=1; } duke@1: public void visitAssert(JCAssert tree) duke@1: { super.visitAssert(tree); complexity+=5; } duke@1: public void visitApply(JCMethodInvocation tree) duke@1: { super.visitApply(tree); complexity+=2; } duke@1: public void visitNewClass(JCNewClass tree) duke@1: { scan(tree.encl); scan(tree.args); complexity+=2; } duke@1: public void visitNewArray(JCNewArray tree) duke@1: { super.visitNewArray(tree); complexity+=5; } duke@1: public void visitAssign(JCAssign tree) duke@1: { super.visitAssign(tree); complexity+=1; } duke@1: public void visitAssignop(JCAssignOp tree) duke@1: { super.visitAssignop(tree); complexity+=2; } duke@1: public void visitUnary(JCUnary tree) duke@1: { complexity+=1; duke@1: if (tree.type.constValue() == null) super.visitUnary(tree); } duke@1: public void visitBinary(JCBinary tree) duke@1: { complexity+=1; duke@1: if (tree.type.constValue() == null) super.visitBinary(tree); } duke@1: public void visitTypeTest(JCInstanceOf tree) duke@1: { super.visitTypeTest(tree); complexity+=1; } duke@1: public void visitIndexed(JCArrayAccess tree) duke@1: { super.visitIndexed(tree); complexity+=1; } duke@1: public void visitSelect(JCFieldAccess tree) duke@1: { super.visitSelect(tree); duke@1: if (tree.sym.kind == VAR) complexity+=1; } duke@1: public void visitIdent(JCIdent tree) { duke@1: if (tree.sym.kind == VAR) { duke@1: complexity+=1; duke@1: if (tree.type.constValue() == null && duke@1: tree.sym.owner.kind == TYP) duke@1: complexity+=1; duke@1: } duke@1: } duke@1: public void visitLiteral(JCLiteral tree) duke@1: { complexity+=1; } duke@1: public void visitTree(JCTree tree) {} duke@1: public void visitWildcard(JCWildcard tree) { duke@1: throw new AssertionError(this.getClass().getName()); duke@1: } duke@1: } duke@1: ComplexityScanner scanner = new ComplexityScanner(); duke@1: tree.accept(scanner); duke@1: return scanner.complexity; duke@1: } duke@1: duke@1: public void visitIf(JCIf tree) { duke@1: int limit = code.nextreg; duke@1: Chain thenExit = null; duke@1: CondItem c = genCond(TreeInfo.skipParens(tree.cond), duke@1: CRT_FLOW_CONTROLLER); duke@1: Chain elseChain = c.jumpFalse(); duke@1: if (!c.isFalse()) { duke@1: code.resolve(c.trueJumps); duke@1: genStat(tree.thenpart, env, CRT_STATEMENT | CRT_FLOW_TARGET); duke@1: thenExit = code.branch(goto_); duke@1: } duke@1: if (elseChain != null) { duke@1: code.resolve(elseChain); duke@1: if (tree.elsepart != null) duke@1: genStat(tree.elsepart, env,CRT_STATEMENT | CRT_FLOW_TARGET); duke@1: } duke@1: code.resolve(thenExit); duke@1: code.endScopes(limit); duke@1: } duke@1: duke@1: public void visitExec(JCExpressionStatement tree) { duke@1: // Optimize x++ to ++x and x-- to --x. duke@1: JCExpression e = tree.expr; duke@1: switch (e.getTag()) { duke@1: case JCTree.POSTINC: duke@1: ((JCUnary) e).setTag(JCTree.PREINC); duke@1: break; duke@1: case JCTree.POSTDEC: duke@1: ((JCUnary) e).setTag(JCTree.PREDEC); duke@1: break; duke@1: } duke@1: genExpr(tree.expr, tree.expr.type).drop(); duke@1: } duke@1: duke@1: public void visitBreak(JCBreak tree) { duke@1: Env targetEnv = unwind(tree.target, env); jjg@816: Assert.check(code.state.stacksize == 0); duke@1: targetEnv.info.addExit(code.branch(goto_)); duke@1: endFinalizerGaps(env, targetEnv); duke@1: } duke@1: duke@1: public void visitContinue(JCContinue tree) { duke@1: Env targetEnv = unwind(tree.target, env); jjg@816: Assert.check(code.state.stacksize == 0); duke@1: targetEnv.info.addCont(code.branch(goto_)); duke@1: endFinalizerGaps(env, targetEnv); duke@1: } duke@1: duke@1: public void visitReturn(JCReturn tree) { duke@1: int limit = code.nextreg; duke@1: final Env targetEnv; duke@1: if (tree.expr != null) { duke@1: Item r = genExpr(tree.expr, pt).load(); duke@1: if (hasFinally(env.enclMethod, env)) { duke@1: r = makeTemp(pt); duke@1: r.store(); duke@1: } duke@1: targetEnv = unwind(env.enclMethod, env); duke@1: r.load(); duke@1: code.emitop0(ireturn + Code.truncate(Code.typecode(pt))); duke@1: } else { duke@1: targetEnv = unwind(env.enclMethod, env); duke@1: code.emitop0(return_); duke@1: } duke@1: endFinalizerGaps(env, targetEnv); duke@1: code.endScopes(limit); duke@1: } duke@1: duke@1: public void visitThrow(JCThrow tree) { duke@1: genExpr(tree.expr, tree.expr.type).load(); duke@1: code.emitop0(athrow); duke@1: } duke@1: duke@1: /* ************************************************************************ duke@1: * Visitor methods for expressions duke@1: *************************************************************************/ duke@1: duke@1: public void visitApply(JCMethodInvocation tree) { duke@1: // Generate code for method. duke@1: Item m = genExpr(tree.meth, methodType); duke@1: // Generate code for all arguments, where the expected types are duke@1: // the parameters of the method's external type (that is, any implicit duke@1: // outer instance of a super(...) call appears as first parameter). duke@1: genArgs(tree.args, duke@1: TreeInfo.symbol(tree.meth).externalType(types).getParameterTypes()); duke@1: result = m.invoke(); duke@1: } duke@1: duke@1: public void visitConditional(JCConditional tree) { duke@1: Chain thenExit = null; duke@1: CondItem c = genCond(tree.cond, CRT_FLOW_CONTROLLER); duke@1: Chain elseChain = c.jumpFalse(); duke@1: if (!c.isFalse()) { duke@1: code.resolve(c.trueJumps); duke@1: int startpc = genCrt ? code.curPc() : 0; duke@1: genExpr(tree.truepart, pt).load(); duke@1: code.state.forceStackTop(tree.type); duke@1: if (genCrt) code.crt.put(tree.truepart, CRT_FLOW_TARGET, duke@1: startpc, code.curPc()); duke@1: thenExit = code.branch(goto_); duke@1: } duke@1: if (elseChain != null) { duke@1: code.resolve(elseChain); duke@1: int startpc = genCrt ? code.curPc() : 0; duke@1: genExpr(tree.falsepart, pt).load(); duke@1: code.state.forceStackTop(tree.type); duke@1: if (genCrt) code.crt.put(tree.falsepart, CRT_FLOW_TARGET, duke@1: startpc, code.curPc()); duke@1: } duke@1: code.resolve(thenExit); duke@1: result = items.makeStackItem(pt); duke@1: } duke@1: duke@1: public void visitNewClass(JCNewClass tree) { duke@1: // Enclosing instances or anonymous classes should have been eliminated duke@1: // by now. jjg@816: Assert.check(tree.encl == null && tree.def == null); duke@1: duke@1: code.emitop2(new_, makeRef(tree.pos(), tree.type)); duke@1: code.emitop0(dup); duke@1: duke@1: // Generate code for all arguments, where the expected types are duke@1: // the parameters of the constructor's external type (that is, duke@1: // any implicit outer instance appears as first parameter). duke@1: genArgs(tree.args, tree.constructor.externalType(types).getParameterTypes()); duke@1: duke@1: items.makeMemberItem(tree.constructor, true).invoke(); duke@1: result = items.makeStackItem(tree.type); duke@1: } duke@1: duke@1: public void visitNewArray(JCNewArray tree) { jjg@308: duke@1: if (tree.elems != null) { duke@1: Type elemtype = types.elemtype(tree.type); duke@1: loadIntConst(tree.elems.length()); duke@1: Item arr = makeNewArray(tree.pos(), tree.type, 1); duke@1: int i = 0; duke@1: for (List l = tree.elems; l.nonEmpty(); l = l.tail) { duke@1: arr.duplicate(); duke@1: loadIntConst(i); duke@1: i++; duke@1: genExpr(l.head, elemtype).load(); duke@1: items.makeIndexedItem(elemtype).store(); duke@1: } duke@1: result = arr; duke@1: } else { duke@1: for (List l = tree.dims; l.nonEmpty(); l = l.tail) { duke@1: genExpr(l.head, syms.intType).load(); duke@1: } duke@1: result = makeNewArray(tree.pos(), tree.type, tree.dims.length()); duke@1: } duke@1: } duke@1: //where duke@1: /** Generate code to create an array with given element type and number duke@1: * of dimensions. duke@1: */ duke@1: Item makeNewArray(DiagnosticPosition pos, Type type, int ndims) { duke@1: Type elemtype = types.elemtype(type); jjg@782: if (types.dimensions(type) > ClassFile.MAX_DIMENSIONS) { duke@1: log.error(pos, "limit.dimensions"); duke@1: nerrs++; duke@1: } duke@1: int elemcode = Code.arraycode(elemtype); duke@1: if (elemcode == 0 || (elemcode == 1 && ndims == 1)) { duke@1: code.emitAnewarray(makeRef(pos, elemtype), type); duke@1: } else if (elemcode == 1) { duke@1: code.emitMultianewarray(ndims, makeRef(pos, type), type); duke@1: } else { duke@1: code.emitNewarray(elemcode, type); duke@1: } duke@1: return items.makeStackItem(type); duke@1: } duke@1: duke@1: public void visitParens(JCParens tree) { duke@1: result = genExpr(tree.expr, tree.expr.type); duke@1: } duke@1: duke@1: public void visitAssign(JCAssign tree) { duke@1: Item l = genExpr(tree.lhs, tree.lhs.type); duke@1: genExpr(tree.rhs, tree.lhs.type).load(); duke@1: result = items.makeAssignItem(l); duke@1: } duke@1: duke@1: public void visitAssignop(JCAssignOp tree) { duke@1: OperatorSymbol operator = (OperatorSymbol) tree.operator; duke@1: Item l; duke@1: if (operator.opcode == string_add) { duke@1: // Generate code to make a string buffer duke@1: makeStringBuffer(tree.pos()); duke@1: duke@1: // Generate code for first string, possibly save one duke@1: // copy under buffer duke@1: l = genExpr(tree.lhs, tree.lhs.type); duke@1: if (l.width() > 0) { duke@1: code.emitop0(dup_x1 + 3 * (l.width() - 1)); duke@1: } duke@1: duke@1: // Load first string and append to buffer. duke@1: l.load(); duke@1: appendString(tree.lhs); duke@1: duke@1: // Append all other strings to buffer. duke@1: appendStrings(tree.rhs); duke@1: duke@1: // Convert buffer to string. duke@1: bufferToString(tree.pos()); duke@1: } else { duke@1: // Generate code for first expression duke@1: l = genExpr(tree.lhs, tree.lhs.type); duke@1: duke@1: // If we have an increment of -32768 to +32767 of a local duke@1: // int variable we can use an incr instruction instead of duke@1: // proceeding further. duke@1: if ((tree.getTag() == JCTree.PLUS_ASG || tree.getTag() == JCTree.MINUS_ASG) && duke@1: l instanceof LocalItem && duke@1: tree.lhs.type.tag <= INT && duke@1: tree.rhs.type.tag <= INT && duke@1: tree.rhs.type.constValue() != null) { duke@1: int ival = ((Number) tree.rhs.type.constValue()).intValue(); duke@1: if (tree.getTag() == JCTree.MINUS_ASG) ival = -ival; duke@1: ((LocalItem)l).incr(ival); duke@1: result = l; duke@1: return; duke@1: } duke@1: // Otherwise, duplicate expression, load one copy duke@1: // and complete binary operation. duke@1: l.duplicate(); duke@1: l.coerce(operator.type.getParameterTypes().head).load(); duke@1: completeBinop(tree.lhs, tree.rhs, operator).coerce(tree.lhs.type); duke@1: } duke@1: result = items.makeAssignItem(l); duke@1: } duke@1: duke@1: public void visitUnary(JCUnary tree) { duke@1: OperatorSymbol operator = (OperatorSymbol)tree.operator; duke@1: if (tree.getTag() == JCTree.NOT) { duke@1: CondItem od = genCond(tree.arg, false); duke@1: result = od.negate(); duke@1: } else { duke@1: Item od = genExpr(tree.arg, operator.type.getParameterTypes().head); duke@1: switch (tree.getTag()) { duke@1: case JCTree.POS: duke@1: result = od.load(); duke@1: break; duke@1: case JCTree.NEG: duke@1: result = od.load(); duke@1: code.emitop0(operator.opcode); duke@1: break; duke@1: case JCTree.COMPL: duke@1: result = od.load(); duke@1: emitMinusOne(od.typecode); duke@1: code.emitop0(operator.opcode); duke@1: break; duke@1: case JCTree.PREINC: case JCTree.PREDEC: duke@1: od.duplicate(); duke@1: if (od instanceof LocalItem && duke@1: (operator.opcode == iadd || operator.opcode == isub)) { duke@1: ((LocalItem)od).incr(tree.getTag() == JCTree.PREINC ? 1 : -1); duke@1: result = od; duke@1: } else { duke@1: od.load(); duke@1: code.emitop0(one(od.typecode)); duke@1: code.emitop0(operator.opcode); duke@1: // Perform narrowing primitive conversion if byte, duke@1: // char, or short. Fix for 4304655. duke@1: if (od.typecode != INTcode && duke@1: Code.truncate(od.typecode) == INTcode) duke@1: code.emitop0(int2byte + od.typecode - BYTEcode); duke@1: result = items.makeAssignItem(od); duke@1: } duke@1: break; duke@1: case JCTree.POSTINC: case JCTree.POSTDEC: duke@1: od.duplicate(); duke@1: if (od instanceof LocalItem && duke@1: (operator.opcode == iadd || operator.opcode == isub)) { duke@1: Item res = od.load(); duke@1: ((LocalItem)od).incr(tree.getTag() == JCTree.POSTINC ? 1 : -1); duke@1: result = res; duke@1: } else { duke@1: Item res = od.load(); duke@1: od.stash(od.typecode); duke@1: code.emitop0(one(od.typecode)); duke@1: code.emitop0(operator.opcode); duke@1: // Perform narrowing primitive conversion if byte, duke@1: // char, or short. Fix for 4304655. duke@1: if (od.typecode != INTcode && duke@1: Code.truncate(od.typecode) == INTcode) duke@1: code.emitop0(int2byte + od.typecode - BYTEcode); duke@1: od.store(); duke@1: result = res; duke@1: } duke@1: break; duke@1: case JCTree.NULLCHK: duke@1: result = od.load(); duke@1: code.emitop0(dup); duke@1: genNullCheck(tree.pos()); duke@1: break; duke@1: default: jjg@816: Assert.error(); duke@1: } duke@1: } duke@1: } duke@1: duke@1: /** Generate a null check from the object value at stack top. */ duke@1: private void genNullCheck(DiagnosticPosition pos) { duke@1: callMethod(pos, syms.objectType, names.getClass, duke@1: List.nil(), false); duke@1: code.emitop0(pop); duke@1: } duke@1: duke@1: public void visitBinary(JCBinary tree) { duke@1: OperatorSymbol operator = (OperatorSymbol)tree.operator; duke@1: if (operator.opcode == string_add) { duke@1: // Create a string buffer. duke@1: makeStringBuffer(tree.pos()); duke@1: // Append all strings to buffer. duke@1: appendStrings(tree); duke@1: // Convert buffer to string. duke@1: bufferToString(tree.pos()); duke@1: result = items.makeStackItem(syms.stringType); duke@1: } else if (tree.getTag() == JCTree.AND) { duke@1: CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER); duke@1: if (!lcond.isFalse()) { duke@1: Chain falseJumps = lcond.jumpFalse(); duke@1: code.resolve(lcond.trueJumps); duke@1: CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET); duke@1: result = items. duke@1: makeCondItem(rcond.opcode, duke@1: rcond.trueJumps, jjg@507: Code.mergeChains(falseJumps, duke@1: rcond.falseJumps)); duke@1: } else { duke@1: result = lcond; duke@1: } duke@1: } else if (tree.getTag() == JCTree.OR) { duke@1: CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER); duke@1: if (!lcond.isTrue()) { duke@1: Chain trueJumps = lcond.jumpTrue(); duke@1: code.resolve(lcond.falseJumps); duke@1: CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET); duke@1: result = items. duke@1: makeCondItem(rcond.opcode, jjg@507: Code.mergeChains(trueJumps, rcond.trueJumps), duke@1: rcond.falseJumps); duke@1: } else { duke@1: result = lcond; duke@1: } duke@1: } else { duke@1: Item od = genExpr(tree.lhs, operator.type.getParameterTypes().head); duke@1: od.load(); duke@1: result = completeBinop(tree.lhs, tree.rhs, operator); duke@1: } duke@1: } duke@1: //where duke@1: /** Make a new string buffer. duke@1: */ duke@1: void makeStringBuffer(DiagnosticPosition pos) { duke@1: code.emitop2(new_, makeRef(pos, stringBufferType)); duke@1: code.emitop0(dup); duke@1: callMethod( duke@1: pos, stringBufferType, names.init, List.nil(), false); duke@1: } duke@1: duke@1: /** Append value (on tos) to string buffer (on tos - 1). duke@1: */ duke@1: void appendString(JCTree tree) { duke@1: Type t = tree.type.baseType(); duke@1: if (t.tag > lastBaseTag && t.tsym != syms.stringType.tsym) { duke@1: t = syms.objectType; duke@1: } duke@1: items.makeMemberItem(getStringBufferAppend(tree, t), false).invoke(); duke@1: } duke@1: Symbol getStringBufferAppend(JCTree tree, Type t) { jjg@816: Assert.checkNull(t.constValue()); duke@1: Symbol method = stringBufferAppend.get(t); duke@1: if (method == null) { duke@1: method = rs.resolveInternalMethod(tree.pos(), duke@1: attrEnv, duke@1: stringBufferType, duke@1: names.append, duke@1: List.of(t), duke@1: null); duke@1: stringBufferAppend.put(t, method); duke@1: } duke@1: return method; duke@1: } duke@1: duke@1: /** Add all strings in tree to string buffer. duke@1: */ duke@1: void appendStrings(JCTree tree) { duke@1: tree = TreeInfo.skipParens(tree); duke@1: if (tree.getTag() == JCTree.PLUS && tree.type.constValue() == null) { duke@1: JCBinary op = (JCBinary) tree; duke@1: if (op.operator.kind == MTH && duke@1: ((OperatorSymbol) op.operator).opcode == string_add) { duke@1: appendStrings(op.lhs); duke@1: appendStrings(op.rhs); duke@1: return; duke@1: } duke@1: } duke@1: genExpr(tree, tree.type).load(); duke@1: appendString(tree); duke@1: } duke@1: duke@1: /** Convert string buffer on tos to string. duke@1: */ duke@1: void bufferToString(DiagnosticPosition pos) { duke@1: callMethod( duke@1: pos, duke@1: stringBufferType, duke@1: names.toString, duke@1: List.nil(), duke@1: false); duke@1: } duke@1: duke@1: /** Complete generating code for operation, with left operand duke@1: * already on stack. duke@1: * @param lhs The tree representing the left operand. duke@1: * @param rhs The tree representing the right operand. duke@1: * @param operator The operator symbol. duke@1: */ duke@1: Item completeBinop(JCTree lhs, JCTree rhs, OperatorSymbol operator) { duke@1: MethodType optype = (MethodType)operator.type; duke@1: int opcode = operator.opcode; duke@1: if (opcode >= if_icmpeq && opcode <= if_icmple && duke@1: rhs.type.constValue() instanceof Number && duke@1: ((Number) rhs.type.constValue()).intValue() == 0) { duke@1: opcode = opcode + (ifeq - if_icmpeq); duke@1: } else if (opcode >= if_acmpeq && opcode <= if_acmpne && duke@1: TreeInfo.isNull(rhs)) { duke@1: opcode = opcode + (if_acmp_null - if_acmpeq); duke@1: } else { duke@1: // The expected type of the right operand is duke@1: // the second parameter type of the operator, except for duke@1: // shifts with long shiftcount, where we convert the opcode duke@1: // to a short shift and the expected type to int. duke@1: Type rtype = operator.erasure(types).getParameterTypes().tail.head; duke@1: if (opcode >= ishll && opcode <= lushrl) { duke@1: opcode = opcode + (ishl - ishll); duke@1: rtype = syms.intType; duke@1: } duke@1: // Generate code for right operand and load. duke@1: genExpr(rhs, rtype).load(); duke@1: // If there are two consecutive opcode instructions, duke@1: // emit the first now. duke@1: if (opcode >= (1 << preShift)) { duke@1: code.emitop0(opcode >> preShift); duke@1: opcode = opcode & 0xFF; duke@1: } duke@1: } duke@1: if (opcode >= ifeq && opcode <= if_acmpne || duke@1: opcode == if_acmp_null || opcode == if_acmp_nonnull) { duke@1: return items.makeCondItem(opcode); duke@1: } else { duke@1: code.emitop0(opcode); duke@1: return items.makeStackItem(optype.restype); duke@1: } duke@1: } duke@1: duke@1: public void visitTypeCast(JCTypeCast tree) { duke@1: result = genExpr(tree.expr, tree.clazz.type).load(); duke@1: // Additional code is only needed if we cast to a reference type duke@1: // which is not statically a supertype of the expression's type. duke@1: // For basic types, the coerce(...) in genExpr(...) will do duke@1: // the conversion. duke@1: if (tree.clazz.type.tag > lastBaseTag && duke@1: types.asSuper(tree.expr.type, tree.clazz.type.tsym) == null) { duke@1: code.emitop2(checkcast, makeRef(tree.pos(), tree.clazz.type)); duke@1: } duke@1: } duke@1: duke@1: public void visitWildcard(JCWildcard tree) { duke@1: throw new AssertionError(this.getClass().getName()); duke@1: } duke@1: duke@1: public void visitTypeTest(JCInstanceOf tree) { duke@1: genExpr(tree.expr, tree.expr.type).load(); duke@1: code.emitop2(instanceof_, makeRef(tree.pos(), tree.clazz.type)); duke@1: result = items.makeStackItem(syms.booleanType); duke@1: } duke@1: duke@1: public void visitIndexed(JCArrayAccess tree) { duke@1: genExpr(tree.indexed, tree.indexed.type).load(); duke@1: genExpr(tree.index, syms.intType).load(); duke@1: result = items.makeIndexedItem(tree.type); duke@1: } duke@1: duke@1: public void visitIdent(JCIdent tree) { duke@1: Symbol sym = tree.sym; duke@1: if (tree.name == names._this || tree.name == names._super) { duke@1: Item res = tree.name == names._this duke@1: ? items.makeThisItem() duke@1: : items.makeSuperItem(); duke@1: if (sym.kind == MTH) { duke@1: // Generate code to address the constructor. duke@1: res.load(); duke@1: res = items.makeMemberItem(sym, true); duke@1: } duke@1: result = res; duke@1: } else if (sym.kind == VAR && sym.owner.kind == MTH) { duke@1: result = items.makeLocalItem((VarSymbol)sym); duke@1: } else if ((sym.flags() & STATIC) != 0) { duke@1: if (!isAccessSuper(env.enclMethod)) duke@1: sym = binaryQualifier(sym, env.enclClass.type); duke@1: result = items.makeStaticItem(sym); duke@1: } else { duke@1: items.makeThisItem().load(); duke@1: sym = binaryQualifier(sym, env.enclClass.type); duke@1: result = items.makeMemberItem(sym, (sym.flags() & PRIVATE) != 0); duke@1: } duke@1: } duke@1: duke@1: public void visitSelect(JCFieldAccess tree) { duke@1: Symbol sym = tree.sym; duke@1: duke@1: if (tree.name == names._class) { jjg@816: Assert.check(target.hasClassLiterals()); duke@1: code.emitop2(ldc2, makeRef(tree.pos(), tree.selected.type)); duke@1: result = items.makeStackItem(pt); duke@1: return; duke@1: } duke@1: duke@1: Symbol ssym = TreeInfo.symbol(tree.selected); duke@1: duke@1: // Are we selecting via super? duke@1: boolean selectSuper = duke@1: ssym != null && (ssym.kind == TYP || ssym.name == names._super); duke@1: duke@1: // Are we accessing a member of the superclass in an access method duke@1: // resulting from a qualified super? duke@1: boolean accessSuper = isAccessSuper(env.enclMethod); duke@1: duke@1: Item base = (selectSuper) duke@1: ? items.makeSuperItem() duke@1: : genExpr(tree.selected, tree.selected.type); duke@1: duke@1: if (sym.kind == VAR && ((VarSymbol) sym).getConstValue() != null) { duke@1: // We are seeing a variable that is constant but its selecting duke@1: // expression is not. duke@1: if ((sym.flags() & STATIC) != 0) { duke@1: if (!selectSuper && (ssym == null || ssym.kind != TYP)) duke@1: base = base.load(); duke@1: base.drop(); duke@1: } else { duke@1: base.load(); duke@1: genNullCheck(tree.selected.pos()); duke@1: } duke@1: result = items. duke@1: makeImmediateItem(sym.type, ((VarSymbol) sym).getConstValue()); duke@1: } else { duke@1: if (!accessSuper) duke@1: sym = binaryQualifier(sym, tree.selected.type); duke@1: if ((sym.flags() & STATIC) != 0) { duke@1: if (!selectSuper && (ssym == null || ssym.kind != TYP)) duke@1: base = base.load(); duke@1: base.drop(); duke@1: result = items.makeStaticItem(sym); duke@1: } else { duke@1: base.load(); duke@1: if (sym == syms.lengthVar) { duke@1: code.emitop0(arraylength); duke@1: result = items.makeStackItem(syms.intType); duke@1: } else { duke@1: result = items. duke@1: makeMemberItem(sym, duke@1: (sym.flags() & PRIVATE) != 0 || duke@1: selectSuper || accessSuper); duke@1: } duke@1: } duke@1: } duke@1: } duke@1: duke@1: public void visitLiteral(JCLiteral tree) { duke@1: if (tree.type.tag == TypeTags.BOT) { duke@1: code.emitop0(aconst_null); duke@1: if (types.dimensions(pt) > 1) { duke@1: code.emitop2(checkcast, makeRef(tree.pos(), pt)); duke@1: result = items.makeStackItem(pt); duke@1: } else { duke@1: result = items.makeStackItem(tree.type); duke@1: } duke@1: } duke@1: else duke@1: result = items.makeImmediateItem(tree.type, tree.value); duke@1: } duke@1: duke@1: public void visitLetExpr(LetExpr tree) { duke@1: int limit = code.nextreg; duke@1: genStats(tree.defs, env); duke@1: result = genExpr(tree.expr, tree.expr.type).load(); duke@1: code.endScopes(limit); duke@1: } duke@1: duke@1: /* ************************************************************************ duke@1: * main method duke@1: *************************************************************************/ duke@1: duke@1: /** Generate code for a class definition. duke@1: * @param env The attribution environment that belongs to the duke@1: * outermost class containing this class definition. duke@1: * We need this for resolving some additional symbols. duke@1: * @param cdef The tree representing the class definition. duke@1: * @return True if code is generated with no errors. duke@1: */ duke@1: public boolean genClass(Env env, JCClassDecl cdef) { duke@1: try { duke@1: attrEnv = env; duke@1: ClassSymbol c = cdef.sym; duke@1: this.toplevel = env.toplevel; duke@1: this.endPositions = toplevel.endPositions; duke@1: // If this is a class definition requiring Miranda methods, duke@1: // add them. duke@1: if (generateIproxies && duke@1: (c.flags() & (INTERFACE|ABSTRACT)) == ABSTRACT duke@1: && !allowGenerics // no Miranda methods available with generics duke@1: ) duke@1: implementInterfaceMethods(c); duke@1: cdef.defs = normalizeDefs(cdef.defs, c); duke@1: c.pool = pool; duke@1: pool.reset(); duke@1: Env localEnv = duke@1: new Env(cdef, new GenContext()); duke@1: localEnv.toplevel = env.toplevel; duke@1: localEnv.enclClass = cdef; duke@1: for (List l = cdef.defs; l.nonEmpty(); l = l.tail) { duke@1: genDef(l.head, localEnv); duke@1: } duke@1: if (pool.numEntries() > Pool.MAX_ENTRIES) { duke@1: log.error(cdef.pos(), "limit.pool"); duke@1: nerrs++; duke@1: } duke@1: if (nerrs != 0) { duke@1: // if errors, discard code duke@1: for (List l = cdef.defs; l.nonEmpty(); l = l.tail) { duke@1: if (l.head.getTag() == JCTree.METHODDEF) duke@1: ((JCMethodDecl) l.head).sym.code = null; duke@1: } duke@1: } duke@1: cdef.defs = List.nil(); // discard trees duke@1: return nerrs == 0; duke@1: } finally { duke@1: // note: this method does NOT support recursion. duke@1: attrEnv = null; duke@1: this.env = null; duke@1: toplevel = null; duke@1: endPositions = null; duke@1: nerrs = 0; duke@1: } duke@1: } duke@1: duke@1: /* ************************************************************************ duke@1: * Auxiliary classes duke@1: *************************************************************************/ duke@1: duke@1: /** An abstract class for finalizer generation. duke@1: */ duke@1: abstract class GenFinalizer { duke@1: /** Generate code to clean up when unwinding. */ duke@1: abstract void gen(); duke@1: duke@1: /** Generate code to clean up at last. */ duke@1: abstract void genLast(); duke@1: duke@1: /** Does this finalizer have some nontrivial cleanup to perform? */ duke@1: boolean hasFinalizer() { return true; } duke@1: } duke@1: duke@1: /** code generation contexts, duke@1: * to be used as type parameter for environments. duke@1: */ duke@1: static class GenContext { duke@1: duke@1: /** A chain for all unresolved jumps that exit the current environment. duke@1: */ duke@1: Chain exit = null; duke@1: duke@1: /** A chain for all unresolved jumps that continue in the duke@1: * current environment. duke@1: */ duke@1: Chain cont = null; duke@1: duke@1: /** A closure that generates the finalizer of the current environment. duke@1: * Only set for Synchronized and Try contexts. duke@1: */ duke@1: GenFinalizer finalize = null; duke@1: duke@1: /** Is this a switch statement? If so, allocate registers duke@1: * even when the variable declaration is unreachable. duke@1: */ duke@1: boolean isSwitch = false; duke@1: duke@1: /** A list buffer containing all gaps in the finalizer range, duke@1: * where a catch all exception should not apply. duke@1: */ duke@1: ListBuffer gaps = null; duke@1: duke@1: /** Add given chain to exit chain. duke@1: */ duke@1: void addExit(Chain c) { duke@1: exit = Code.mergeChains(c, exit); duke@1: } duke@1: duke@1: /** Add given chain to cont chain. duke@1: */ duke@1: void addCont(Chain c) { duke@1: cont = Code.mergeChains(c, cont); duke@1: } duke@1: } duke@1: }