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