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

Wed, 21 Jan 2015 18:43:01 +0000

author
coffeys
date
Wed, 21 Jan 2015 18:43:01 +0000
changeset 2711
0ba07c272e33
parent 2709
dca7f60e618d
parent 2657
d42678403377
child 2789
36ed04994588
permissions
-rw-r--r--

Merge

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

mercurial