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