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

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