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