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

Fri, 30 Nov 2012 15:14:36 +0000

author
mcimadamore
date
Fri, 30 Nov 2012 15:14:36 +0000
changeset 1435
9b26c96f5138
parent 1432
969c96b980b7
child 1452
de1ec6fc93fe
permissions
-rw-r--r--

8004101: Add checks for method reference well-formedness
Summary: Bring method reference type-checking in sync with latest EDR
Reviewed-by: jjg

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

mercurial