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

Fri, 06 Sep 2013 09:53:24 +0100

author
vromero
date
Fri, 06 Sep 2013 09:53:24 +0100
changeset 2009
7c7b4aea6d50
parent 1929
99b60bcf3862
child 2027
4932bb04c4b8
permissions
-rw-r--r--

8024039: javac, previous solution for JDK-8022186 was incorrect
Reviewed-by: jjg

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

mercurial