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

Thu, 24 May 2018 16:48:51 +0800

author
aoqi
date
Thu, 24 May 2018 16:48:51 +0800
changeset 3295
859dc787b52b
parent 3000
4044eb07194d
parent 2893
ca5783d9a597
child 3446
e468915bad3a
permissions
-rw-r--r--

Merge

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

mercurial