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

Mon, 14 Nov 2011 15:11:10 -0800

author
ksrini
date
Mon, 14 Nov 2011 15:11:10 -0800
changeset 1138
7375d4979bd3
parent 1127
ca49d50318dc
child 1157
3809292620c9
permissions
-rw-r--r--

7106166: (javac) re-factor EndPos parser
Reviewed-by: jjg

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

mercurial