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

Thu, 31 Aug 2017 15:17:03 +0800

author
aoqi
date
Thu, 31 Aug 2017 15:17:03 +0800
changeset 2525
2eb010b6cb22
parent 2406
372fd7283bf0
parent 0
959103a6100f
child 2702
9ca8d8713094
permissions
-rw-r--r--

merge

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

mercurial