Gen.java revision 2772:3bdbc3b8aa14
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 26package com.sun.tools.javac.jvm; 27 28import java.util.*; 29 30import com.sun.tools.javac.util.*; 31import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 32import com.sun.tools.javac.util.List; 33import com.sun.tools.javac.code.*; 34import com.sun.tools.javac.code.Attribute.TypeCompound; 35import com.sun.tools.javac.code.Symbol.VarSymbol; 36import com.sun.tools.javac.comp.*; 37import com.sun.tools.javac.tree.*; 38 39import com.sun.tools.javac.code.Symbol.*; 40import com.sun.tools.javac.code.Type.*; 41import com.sun.tools.javac.jvm.Code.*; 42import com.sun.tools.javac.jvm.Items.*; 43import com.sun.tools.javac.tree.EndPosTable; 44import com.sun.tools.javac.tree.JCTree.*; 45 46import static com.sun.tools.javac.code.Flags.*; 47import static com.sun.tools.javac.code.Kinds.Kind.*; 48import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE; 49import static com.sun.tools.javac.code.TypeTag.*; 50import static com.sun.tools.javac.jvm.ByteCodes.*; 51import static com.sun.tools.javac.jvm.CRTFlags.*; 52import static com.sun.tools.javac.main.Option.*; 53import 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 */ 62public 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 code.resolve(loopEnv.info.exit); 1100 if (loopEnv.info.exit != null) { 1101 loopEnv.info.exit.state.defined.excludeFrom(code.nextreg); 1102 } 1103 } 1104 1105 public void visitForeachLoop(JCEnhancedForLoop tree) { 1106 throw new AssertionError(); // should have been removed by Lower. 1107 } 1108 1109 public void visitLabelled(JCLabeledStatement tree) { 1110 Env<GenContext> localEnv = env.dup(tree, new GenContext()); 1111 genStat(tree.body, localEnv, CRT_STATEMENT); 1112 code.resolve(localEnv.info.exit); 1113 } 1114 1115 public void visitSwitch(JCSwitch tree) { 1116 int limit = code.nextreg; 1117 Assert.check(!tree.selector.type.hasTag(CLASS)); 1118 int startpcCrt = genCrt ? code.curCP() : 0; 1119 Item sel = genExpr(tree.selector, syms.intType); 1120 List<JCCase> cases = tree.cases; 1121 if (cases.isEmpty()) { 1122 // We are seeing: switch <sel> {} 1123 sel.load().drop(); 1124 if (genCrt) 1125 code.crt.put(TreeInfo.skipParens(tree.selector), 1126 CRT_FLOW_CONTROLLER, startpcCrt, code.curCP()); 1127 } else { 1128 // We are seeing a nonempty switch. 1129 sel.load(); 1130 if (genCrt) 1131 code.crt.put(TreeInfo.skipParens(tree.selector), 1132 CRT_FLOW_CONTROLLER, startpcCrt, code.curCP()); 1133 Env<GenContext> switchEnv = env.dup(tree, new GenContext()); 1134 switchEnv.info.isSwitch = true; 1135 1136 // Compute number of labels and minimum and maximum label values. 1137 // For each case, store its label in an array. 1138 int lo = Integer.MAX_VALUE; // minimum label. 1139 int hi = Integer.MIN_VALUE; // maximum label. 1140 int nlabels = 0; // number of labels. 1141 1142 int[] labels = new int[cases.length()]; // the label array. 1143 int defaultIndex = -1; // the index of the default clause. 1144 1145 List<JCCase> l = cases; 1146 for (int i = 0; i < labels.length; i++) { 1147 if (l.head.pat != null) { 1148 int val = ((Number)l.head.pat.type.constValue()).intValue(); 1149 labels[i] = val; 1150 if (val < lo) lo = val; 1151 if (hi < val) hi = val; 1152 nlabels++; 1153 } else { 1154 Assert.check(defaultIndex == -1); 1155 defaultIndex = i; 1156 } 1157 l = l.tail; 1158 } 1159 1160 // Determine whether to issue a tableswitch or a lookupswitch 1161 // instruction. 1162 long table_space_cost = 4 + ((long) hi - lo + 1); // words 1163 long table_time_cost = 3; // comparisons 1164 long lookup_space_cost = 3 + 2 * (long) nlabels; 1165 long lookup_time_cost = nlabels; 1166 int opcode = 1167 nlabels > 0 && 1168 table_space_cost + 3 * table_time_cost <= 1169 lookup_space_cost + 3 * lookup_time_cost 1170 ? 1171 tableswitch : lookupswitch; 1172 1173 int startpc = code.curCP(); // the position of the selector operation 1174 code.emitop0(opcode); 1175 code.align(4); 1176 int tableBase = code.curCP(); // the start of the jump table 1177 int[] offsets = null; // a table of offsets for a lookupswitch 1178 code.emit4(-1); // leave space for default offset 1179 if (opcode == tableswitch) { 1180 code.emit4(lo); // minimum label 1181 code.emit4(hi); // maximum label 1182 for (long i = lo; i <= hi; i++) { // leave space for jump table 1183 code.emit4(-1); 1184 } 1185 } else { 1186 code.emit4(nlabels); // number of labels 1187 for (int i = 0; i < nlabels; i++) { 1188 code.emit4(-1); code.emit4(-1); // leave space for lookup table 1189 } 1190 offsets = new int[labels.length]; 1191 } 1192 Code.State stateSwitch = code.state.dup(); 1193 code.markDead(); 1194 1195 // For each case do: 1196 l = cases; 1197 for (int i = 0; i < labels.length; i++) { 1198 JCCase c = l.head; 1199 l = l.tail; 1200 1201 int pc = code.entryPoint(stateSwitch); 1202 // Insert offset directly into code or else into the 1203 // offsets table. 1204 if (i != defaultIndex) { 1205 if (opcode == tableswitch) { 1206 code.put4( 1207 tableBase + 4 * (labels[i] - lo + 3), 1208 pc - startpc); 1209 } else { 1210 offsets[i] = pc - startpc; 1211 } 1212 } else { 1213 code.put4(tableBase, pc - startpc); 1214 } 1215 1216 // Generate code for the statements in this case. 1217 genStats(c.stats, switchEnv, CRT_FLOW_TARGET); 1218 } 1219 1220 // Resolve all breaks. 1221 code.resolve(switchEnv.info.exit); 1222 1223 // If we have not set the default offset, we do so now. 1224 if (code.get4(tableBase) == -1) { 1225 code.put4(tableBase, code.entryPoint(stateSwitch) - startpc); 1226 } 1227 1228 if (opcode == tableswitch) { 1229 // Let any unfilled slots point to the default case. 1230 int defaultOffset = code.get4(tableBase); 1231 for (long i = lo; i <= hi; i++) { 1232 int t = (int)(tableBase + 4 * (i - lo + 3)); 1233 if (code.get4(t) == -1) 1234 code.put4(t, defaultOffset); 1235 } 1236 } else { 1237 // Sort non-default offsets and copy into lookup table. 1238 if (defaultIndex >= 0) 1239 for (int i = defaultIndex; i < labels.length - 1; i++) { 1240 labels[i] = labels[i+1]; 1241 offsets[i] = offsets[i+1]; 1242 } 1243 if (nlabels > 0) 1244 qsort2(labels, offsets, 0, nlabels - 1); 1245 for (int i = 0; i < nlabels; i++) { 1246 int caseidx = tableBase + 8 * (i + 1); 1247 code.put4(caseidx, labels[i]); 1248 code.put4(caseidx + 4, offsets[i]); 1249 } 1250 } 1251 } 1252 code.endScopes(limit); 1253 } 1254//where 1255 /** Sort (int) arrays of keys and values 1256 */ 1257 static void qsort2(int[] keys, int[] values, int lo, int hi) { 1258 int i = lo; 1259 int j = hi; 1260 int pivot = keys[(i+j)/2]; 1261 do { 1262 while (keys[i] < pivot) i++; 1263 while (pivot < keys[j]) j--; 1264 if (i <= j) { 1265 int temp1 = keys[i]; 1266 keys[i] = keys[j]; 1267 keys[j] = temp1; 1268 int temp2 = values[i]; 1269 values[i] = values[j]; 1270 values[j] = temp2; 1271 i++; 1272 j--; 1273 } 1274 } while (i <= j); 1275 if (lo < j) qsort2(keys, values, lo, j); 1276 if (i < hi) qsort2(keys, values, i, hi); 1277 } 1278 1279 public void visitSynchronized(JCSynchronized tree) { 1280 int limit = code.nextreg; 1281 // Generate code to evaluate lock and save in temporary variable. 1282 final LocalItem lockVar = makeTemp(syms.objectType); 1283 genExpr(tree.lock, tree.lock.type).load().duplicate(); 1284 lockVar.store(); 1285 1286 // Generate code to enter monitor. 1287 code.emitop0(monitorenter); 1288 code.state.lock(lockVar.reg); 1289 1290 // Generate code for a try statement with given body, no catch clauses 1291 // in a new environment with the "exit-monitor" operation as finalizer. 1292 final Env<GenContext> syncEnv = env.dup(tree, new GenContext()); 1293 syncEnv.info.finalize = new GenFinalizer() { 1294 void gen() { 1295 genLast(); 1296 Assert.check(syncEnv.info.gaps.length() % 2 == 0); 1297 syncEnv.info.gaps.append(code.curCP()); 1298 } 1299 void genLast() { 1300 if (code.isAlive()) { 1301 lockVar.load(); 1302 code.emitop0(monitorexit); 1303 code.state.unlock(lockVar.reg); 1304 } 1305 } 1306 }; 1307 syncEnv.info.gaps = new ListBuffer<>(); 1308 genTry(tree.body, List.<JCCatch>nil(), syncEnv); 1309 code.endScopes(limit); 1310 } 1311 1312 public void visitTry(final JCTry tree) { 1313 // Generate code for a try statement with given body and catch clauses, 1314 // in a new environment which calls the finally block if there is one. 1315 final Env<GenContext> tryEnv = env.dup(tree, new GenContext()); 1316 final Env<GenContext> oldEnv = env; 1317 if (!useJsrLocally) { 1318 useJsrLocally = 1319 (stackMap == StackMapFormat.NONE) && 1320 (jsrlimit <= 0 || 1321 jsrlimit < 100 && 1322 estimateCodeComplexity(tree.finalizer)>jsrlimit); 1323 } 1324 tryEnv.info.finalize = new GenFinalizer() { 1325 void gen() { 1326 if (useJsrLocally) { 1327 if (tree.finalizer != null) { 1328 Code.State jsrState = code.state.dup(); 1329 jsrState.push(Code.jsrReturnValue); 1330 tryEnv.info.cont = 1331 new Chain(code.emitJump(jsr), 1332 tryEnv.info.cont, 1333 jsrState); 1334 } 1335 Assert.check(tryEnv.info.gaps.length() % 2 == 0); 1336 tryEnv.info.gaps.append(code.curCP()); 1337 } else { 1338 Assert.check(tryEnv.info.gaps.length() % 2 == 0); 1339 tryEnv.info.gaps.append(code.curCP()); 1340 genLast(); 1341 } 1342 } 1343 void genLast() { 1344 if (tree.finalizer != null) 1345 genStat(tree.finalizer, oldEnv, CRT_BLOCK); 1346 } 1347 boolean hasFinalizer() { 1348 return tree.finalizer != null; 1349 } 1350 }; 1351 tryEnv.info.gaps = new ListBuffer<>(); 1352 genTry(tree.body, tree.catchers, tryEnv); 1353 } 1354 //where 1355 /** Generate code for a try or synchronized statement 1356 * @param body The body of the try or synchronized statement. 1357 * @param catchers The lis of catch clauses. 1358 * @param env the environment current for the body. 1359 */ 1360 void genTry(JCTree body, List<JCCatch> catchers, Env<GenContext> env) { 1361 int limit = code.nextreg; 1362 int startpc = code.curCP(); 1363 Code.State stateTry = code.state.dup(); 1364 genStat(body, env, CRT_BLOCK); 1365 int endpc = code.curCP(); 1366 boolean hasFinalizer = 1367 env.info.finalize != null && 1368 env.info.finalize.hasFinalizer(); 1369 List<Integer> gaps = env.info.gaps.toList(); 1370 code.statBegin(TreeInfo.endPos(body)); 1371 genFinalizer(env); 1372 code.statBegin(TreeInfo.endPos(env.tree)); 1373 Chain exitChain = code.branch(goto_); 1374 endFinalizerGap(env); 1375 if (startpc != endpc) for (List<JCCatch> l = catchers; l.nonEmpty(); l = l.tail) { 1376 // start off with exception on stack 1377 code.entryPoint(stateTry, l.head.param.sym.type); 1378 genCatch(l.head, env, startpc, endpc, gaps); 1379 genFinalizer(env); 1380 if (hasFinalizer || l.tail.nonEmpty()) { 1381 code.statBegin(TreeInfo.endPos(env.tree)); 1382 exitChain = Code.mergeChains(exitChain, 1383 code.branch(goto_)); 1384 } 1385 endFinalizerGap(env); 1386 } 1387 if (hasFinalizer) { 1388 // Create a new register segement to avoid allocating 1389 // the same variables in finalizers and other statements. 1390 code.newRegSegment(); 1391 1392 // Add a catch-all clause. 1393 1394 // start off with exception on stack 1395 int catchallpc = code.entryPoint(stateTry, syms.throwableType); 1396 1397 // Register all exception ranges for catch all clause. 1398 // The range of the catch all clause is from the beginning 1399 // of the try or synchronized block until the present 1400 // code pointer excluding all gaps in the current 1401 // environment's GenContext. 1402 int startseg = startpc; 1403 while (env.info.gaps.nonEmpty()) { 1404 int endseg = env.info.gaps.next().intValue(); 1405 registerCatch(body.pos(), startseg, endseg, 1406 catchallpc, 0); 1407 startseg = env.info.gaps.next().intValue(); 1408 } 1409 code.statBegin(TreeInfo.finalizerPos(env.tree)); 1410 code.markStatBegin(); 1411 1412 Item excVar = makeTemp(syms.throwableType); 1413 excVar.store(); 1414 genFinalizer(env); 1415 excVar.load(); 1416 registerCatch(body.pos(), startseg, 1417 env.info.gaps.next().intValue(), 1418 catchallpc, 0); 1419 code.emitop0(athrow); 1420 code.markDead(); 1421 1422 // If there are jsr's to this finalizer, ... 1423 if (env.info.cont != null) { 1424 // Resolve all jsr's. 1425 code.resolve(env.info.cont); 1426 1427 // Mark statement line number 1428 code.statBegin(TreeInfo.finalizerPos(env.tree)); 1429 code.markStatBegin(); 1430 1431 // Save return address. 1432 LocalItem retVar = makeTemp(syms.throwableType); 1433 retVar.store(); 1434 1435 // Generate finalizer code. 1436 env.info.finalize.genLast(); 1437 1438 // Return. 1439 code.emitop1w(ret, retVar.reg); 1440 code.markDead(); 1441 } 1442 } 1443 // Resolve all breaks. 1444 code.resolve(exitChain); 1445 1446 code.endScopes(limit); 1447 } 1448 1449 /** Generate code for a catch clause. 1450 * @param tree The catch clause. 1451 * @param env The environment current in the enclosing try. 1452 * @param startpc Start pc of try-block. 1453 * @param endpc End pc of try-block. 1454 */ 1455 void genCatch(JCCatch tree, 1456 Env<GenContext> env, 1457 int startpc, int endpc, 1458 List<Integer> gaps) { 1459 if (startpc != endpc) { 1460 List<JCExpression> subClauses = TreeInfo.isMultiCatch(tree) ? 1461 ((JCTypeUnion)tree.param.vartype).alternatives : 1462 List.of(tree.param.vartype); 1463 while (gaps.nonEmpty()) { 1464 for (JCExpression subCatch : subClauses) { 1465 int catchType = makeRef(tree.pos(), subCatch.type); 1466 int end = gaps.head.intValue(); 1467 registerCatch(tree.pos(), 1468 startpc, end, code.curCP(), 1469 catchType); 1470 if (subCatch.type.isAnnotated()) { 1471 for (Attribute.TypeCompound tc : 1472 subCatch.type.getAnnotationMirrors()) { 1473 tc.position.setCatchInfo(catchType, startpc); 1474 } 1475 } 1476 } 1477 gaps = gaps.tail; 1478 startpc = gaps.head.intValue(); 1479 gaps = gaps.tail; 1480 } 1481 if (startpc < endpc) { 1482 for (JCExpression subCatch : subClauses) { 1483 int catchType = makeRef(tree.pos(), subCatch.type); 1484 registerCatch(tree.pos(), 1485 startpc, endpc, code.curCP(), 1486 catchType); 1487 if (subCatch.type.isAnnotated()) { 1488 for (Attribute.TypeCompound tc : 1489 subCatch.type.getAnnotationMirrors()) { 1490 tc.position.setCatchInfo(catchType, startpc); 1491 } 1492 } 1493 } 1494 } 1495 VarSymbol exparam = tree.param.sym; 1496 code.statBegin(tree.pos); 1497 code.markStatBegin(); 1498 int limit = code.nextreg; 1499 int exlocal = code.newLocal(exparam); 1500 items.makeLocalItem(exparam).store(); 1501 code.statBegin(TreeInfo.firstStatPos(tree.body)); 1502 genStat(tree.body, env, CRT_BLOCK); 1503 code.endScopes(limit); 1504 code.statBegin(TreeInfo.endPos(tree.body)); 1505 } 1506 } 1507 1508 /** Register a catch clause in the "Exceptions" code-attribute. 1509 */ 1510 void registerCatch(DiagnosticPosition pos, 1511 int startpc, int endpc, 1512 int handler_pc, int catch_type) { 1513 char startpc1 = (char)startpc; 1514 char endpc1 = (char)endpc; 1515 char handler_pc1 = (char)handler_pc; 1516 if (startpc1 == startpc && 1517 endpc1 == endpc && 1518 handler_pc1 == handler_pc) { 1519 code.addCatch(startpc1, endpc1, handler_pc1, 1520 (char)catch_type); 1521 } else { 1522 log.error(pos, "limit.code.too.large.for.try.stmt"); 1523 nerrs++; 1524 } 1525 } 1526 1527 /** Very roughly estimate the number of instructions needed for 1528 * the given tree. 1529 */ 1530 int estimateCodeComplexity(JCTree tree) { 1531 if (tree == null) return 0; 1532 class ComplexityScanner extends TreeScanner { 1533 int complexity = 0; 1534 public void scan(JCTree tree) { 1535 if (complexity > jsrlimit) return; 1536 super.scan(tree); 1537 } 1538 public void visitClassDef(JCClassDecl tree) {} 1539 public void visitDoLoop(JCDoWhileLoop tree) 1540 { super.visitDoLoop(tree); complexity++; } 1541 public void visitWhileLoop(JCWhileLoop tree) 1542 { super.visitWhileLoop(tree); complexity++; } 1543 public void visitForLoop(JCForLoop tree) 1544 { super.visitForLoop(tree); complexity++; } 1545 public void visitSwitch(JCSwitch tree) 1546 { super.visitSwitch(tree); complexity+=5; } 1547 public void visitCase(JCCase tree) 1548 { super.visitCase(tree); complexity++; } 1549 public void visitSynchronized(JCSynchronized tree) 1550 { super.visitSynchronized(tree); complexity+=6; } 1551 public void visitTry(JCTry tree) 1552 { super.visitTry(tree); 1553 if (tree.finalizer != null) complexity+=6; } 1554 public void visitCatch(JCCatch tree) 1555 { super.visitCatch(tree); complexity+=2; } 1556 public void visitConditional(JCConditional tree) 1557 { super.visitConditional(tree); complexity+=2; } 1558 public void visitIf(JCIf tree) 1559 { super.visitIf(tree); complexity+=2; } 1560 // note: for break, continue, and return we don't take unwind() into account. 1561 public void visitBreak(JCBreak tree) 1562 { super.visitBreak(tree); complexity+=1; } 1563 public void visitContinue(JCContinue tree) 1564 { super.visitContinue(tree); complexity+=1; } 1565 public void visitReturn(JCReturn tree) 1566 { super.visitReturn(tree); complexity+=1; } 1567 public void visitThrow(JCThrow tree) 1568 { super.visitThrow(tree); complexity+=1; } 1569 public void visitAssert(JCAssert tree) 1570 { super.visitAssert(tree); complexity+=5; } 1571 public void visitApply(JCMethodInvocation tree) 1572 { super.visitApply(tree); complexity+=2; } 1573 public void visitNewClass(JCNewClass tree) 1574 { scan(tree.encl); scan(tree.args); complexity+=2; } 1575 public void visitNewArray(JCNewArray tree) 1576 { super.visitNewArray(tree); complexity+=5; } 1577 public void visitAssign(JCAssign tree) 1578 { super.visitAssign(tree); complexity+=1; } 1579 public void visitAssignop(JCAssignOp tree) 1580 { super.visitAssignop(tree); complexity+=2; } 1581 public void visitUnary(JCUnary tree) 1582 { complexity+=1; 1583 if (tree.type.constValue() == null) super.visitUnary(tree); } 1584 public void visitBinary(JCBinary tree) 1585 { complexity+=1; 1586 if (tree.type.constValue() == null) super.visitBinary(tree); } 1587 public void visitTypeTest(JCInstanceOf tree) 1588 { super.visitTypeTest(tree); complexity+=1; } 1589 public void visitIndexed(JCArrayAccess tree) 1590 { super.visitIndexed(tree); complexity+=1; } 1591 public void visitSelect(JCFieldAccess tree) 1592 { super.visitSelect(tree); 1593 if (tree.sym.kind == VAR) complexity+=1; } 1594 public void visitIdent(JCIdent tree) { 1595 if (tree.sym.kind == VAR) { 1596 complexity+=1; 1597 if (tree.type.constValue() == null && 1598 tree.sym.owner.kind == TYP) 1599 complexity+=1; 1600 } 1601 } 1602 public void visitLiteral(JCLiteral tree) 1603 { complexity+=1; } 1604 public void visitTree(JCTree tree) {} 1605 public void visitWildcard(JCWildcard tree) { 1606 throw new AssertionError(this.getClass().getName()); 1607 } 1608 } 1609 ComplexityScanner scanner = new ComplexityScanner(); 1610 tree.accept(scanner); 1611 return scanner.complexity; 1612 } 1613 1614 public void visitIf(JCIf tree) { 1615 int limit = code.nextreg; 1616 Chain thenExit = null; 1617 CondItem c = genCond(TreeInfo.skipParens(tree.cond), 1618 CRT_FLOW_CONTROLLER); 1619 Chain elseChain = c.jumpFalse(); 1620 if (!c.isFalse()) { 1621 code.resolve(c.trueJumps); 1622 genStat(tree.thenpart, env, CRT_STATEMENT | CRT_FLOW_TARGET); 1623 thenExit = code.branch(goto_); 1624 } 1625 if (elseChain != null) { 1626 code.resolve(elseChain); 1627 if (tree.elsepart != null) { 1628 genStat(tree.elsepart, env,CRT_STATEMENT | CRT_FLOW_TARGET); 1629 } 1630 } 1631 code.resolve(thenExit); 1632 code.endScopes(limit); 1633 } 1634 1635 public void visitExec(JCExpressionStatement tree) { 1636 // Optimize x++ to ++x and x-- to --x. 1637 JCExpression e = tree.expr; 1638 switch (e.getTag()) { 1639 case POSTINC: 1640 ((JCUnary) e).setTag(PREINC); 1641 break; 1642 case POSTDEC: 1643 ((JCUnary) e).setTag(PREDEC); 1644 break; 1645 } 1646 genExpr(tree.expr, tree.expr.type).drop(); 1647 } 1648 1649 public void visitBreak(JCBreak tree) { 1650 Env<GenContext> targetEnv = unwind(tree.target, env); 1651 Assert.check(code.state.stacksize == 0); 1652 targetEnv.info.addExit(code.branch(goto_)); 1653 endFinalizerGaps(env, targetEnv); 1654 } 1655 1656 public void visitContinue(JCContinue tree) { 1657 Env<GenContext> targetEnv = unwind(tree.target, env); 1658 Assert.check(code.state.stacksize == 0); 1659 targetEnv.info.addCont(code.branch(goto_)); 1660 endFinalizerGaps(env, targetEnv); 1661 } 1662 1663 public void visitReturn(JCReturn tree) { 1664 int limit = code.nextreg; 1665 final Env<GenContext> targetEnv; 1666 if (tree.expr != null) { 1667 Item r = genExpr(tree.expr, pt).load(); 1668 if (hasFinally(env.enclMethod, env)) { 1669 r = makeTemp(pt); 1670 r.store(); 1671 } 1672 targetEnv = unwind(env.enclMethod, env); 1673 r.load(); 1674 code.emitop0(ireturn + Code.truncate(Code.typecode(pt))); 1675 } else { 1676 /* If we have a statement like: 1677 * 1678 * return; 1679 * 1680 * we need to store the code.pendingStatPos value before generating 1681 * the finalizer. 1682 */ 1683 int tmpPos = code.pendingStatPos; 1684 targetEnv = unwind(env.enclMethod, env); 1685 code.pendingStatPos = tmpPos; 1686 code.emitop0(return_); 1687 } 1688 endFinalizerGaps(env, targetEnv); 1689 code.endScopes(limit); 1690 } 1691 1692 public void visitThrow(JCThrow tree) { 1693 genExpr(tree.expr, tree.expr.type).load(); 1694 code.emitop0(athrow); 1695 } 1696 1697/* ************************************************************************ 1698 * Visitor methods for expressions 1699 *************************************************************************/ 1700 1701 public void visitApply(JCMethodInvocation tree) { 1702 setTypeAnnotationPositions(tree.pos); 1703 // Generate code for method. 1704 Item m = genExpr(tree.meth, methodType); 1705 // Generate code for all arguments, where the expected types are 1706 // the parameters of the method's external type (that is, any implicit 1707 // outer instance of a super(...) call appears as first parameter). 1708 MethodSymbol msym = (MethodSymbol)TreeInfo.symbol(tree.meth); 1709 genArgs(tree.args, 1710 msym.externalType(types).getParameterTypes()); 1711 if (!msym.isDynamic()) { 1712 code.statBegin(tree.pos); 1713 } 1714 result = m.invoke(); 1715 } 1716 1717 public void visitConditional(JCConditional tree) { 1718 Chain thenExit = null; 1719 CondItem c = genCond(tree.cond, CRT_FLOW_CONTROLLER); 1720 Chain elseChain = c.jumpFalse(); 1721 if (!c.isFalse()) { 1722 code.resolve(c.trueJumps); 1723 int startpc = genCrt ? code.curCP() : 0; 1724 code.statBegin(tree.truepart.pos); 1725 genExpr(tree.truepart, pt).load(); 1726 code.state.forceStackTop(tree.type); 1727 if (genCrt) code.crt.put(tree.truepart, CRT_FLOW_TARGET, 1728 startpc, code.curCP()); 1729 thenExit = code.branch(goto_); 1730 } 1731 if (elseChain != null) { 1732 code.resolve(elseChain); 1733 int startpc = genCrt ? code.curCP() : 0; 1734 code.statBegin(tree.falsepart.pos); 1735 genExpr(tree.falsepart, pt).load(); 1736 code.state.forceStackTop(tree.type); 1737 if (genCrt) code.crt.put(tree.falsepart, CRT_FLOW_TARGET, 1738 startpc, code.curCP()); 1739 } 1740 code.resolve(thenExit); 1741 result = items.makeStackItem(pt); 1742 } 1743 1744 private void setTypeAnnotationPositions(int treePos) { 1745 MethodSymbol meth = code.meth; 1746 boolean initOrClinit = code.meth.getKind() == javax.lang.model.element.ElementKind.CONSTRUCTOR 1747 || code.meth.getKind() == javax.lang.model.element.ElementKind.STATIC_INIT; 1748 1749 for (Attribute.TypeCompound ta : meth.getRawTypeAttributes()) { 1750 if (ta.hasUnknownPosition()) 1751 ta.tryFixPosition(); 1752 1753 if (ta.position.matchesPos(treePos)) 1754 ta.position.updatePosOffset(code.cp); 1755 } 1756 1757 if (!initOrClinit) 1758 return; 1759 1760 for (Attribute.TypeCompound ta : meth.owner.getRawTypeAttributes()) { 1761 if (ta.hasUnknownPosition()) 1762 ta.tryFixPosition(); 1763 1764 if (ta.position.matchesPos(treePos)) 1765 ta.position.updatePosOffset(code.cp); 1766 } 1767 1768 ClassSymbol clazz = meth.enclClass(); 1769 for (Symbol s : new com.sun.tools.javac.model.FilteredMemberList(clazz.members())) { 1770 if (!s.getKind().isField()) 1771 continue; 1772 1773 for (Attribute.TypeCompound ta : s.getRawTypeAttributes()) { 1774 if (ta.hasUnknownPosition()) 1775 ta.tryFixPosition(); 1776 1777 if (ta.position.matchesPos(treePos)) 1778 ta.position.updatePosOffset(code.cp); 1779 } 1780 } 1781 } 1782 1783 public void visitNewClass(JCNewClass tree) { 1784 // Enclosing instances or anonymous classes should have been eliminated 1785 // by now. 1786 Assert.check(tree.encl == null && tree.def == null); 1787 setTypeAnnotationPositions(tree.pos); 1788 1789 code.emitop2(new_, makeRef(tree.pos(), tree.type)); 1790 code.emitop0(dup); 1791 1792 // Generate code for all arguments, where the expected types are 1793 // the parameters of the constructor's external type (that is, 1794 // any implicit outer instance appears as first parameter). 1795 genArgs(tree.args, tree.constructor.externalType(types).getParameterTypes()); 1796 1797 items.makeMemberItem(tree.constructor, true).invoke(); 1798 result = items.makeStackItem(tree.type); 1799 } 1800 1801 public void visitNewArray(JCNewArray tree) { 1802 setTypeAnnotationPositions(tree.pos); 1803 1804 if (tree.elems != null) { 1805 Type elemtype = types.elemtype(tree.type); 1806 loadIntConst(tree.elems.length()); 1807 Item arr = makeNewArray(tree.pos(), tree.type, 1); 1808 int i = 0; 1809 for (List<JCExpression> l = tree.elems; l.nonEmpty(); l = l.tail) { 1810 arr.duplicate(); 1811 loadIntConst(i); 1812 i++; 1813 genExpr(l.head, elemtype).load(); 1814 items.makeIndexedItem(elemtype).store(); 1815 } 1816 result = arr; 1817 } else { 1818 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) { 1819 genExpr(l.head, syms.intType).load(); 1820 } 1821 result = makeNewArray(tree.pos(), tree.type, tree.dims.length()); 1822 } 1823 } 1824//where 1825 /** Generate code to create an array with given element type and number 1826 * of dimensions. 1827 */ 1828 Item makeNewArray(DiagnosticPosition pos, Type type, int ndims) { 1829 Type elemtype = types.elemtype(type); 1830 if (types.dimensions(type) > ClassFile.MAX_DIMENSIONS) { 1831 log.error(pos, "limit.dimensions"); 1832 nerrs++; 1833 } 1834 int elemcode = Code.arraycode(elemtype); 1835 if (elemcode == 0 || (elemcode == 1 && ndims == 1)) { 1836 code.emitAnewarray(makeRef(pos, elemtype), type); 1837 } else if (elemcode == 1) { 1838 code.emitMultianewarray(ndims, makeRef(pos, type), type); 1839 } else { 1840 code.emitNewarray(elemcode, type); 1841 } 1842 return items.makeStackItem(type); 1843 } 1844 1845 public void visitParens(JCParens tree) { 1846 result = genExpr(tree.expr, tree.expr.type); 1847 } 1848 1849 public void visitAssign(JCAssign tree) { 1850 Item l = genExpr(tree.lhs, tree.lhs.type); 1851 genExpr(tree.rhs, tree.lhs.type).load(); 1852 result = items.makeAssignItem(l); 1853 } 1854 1855 public void visitAssignop(JCAssignOp tree) { 1856 OperatorSymbol operator = (OperatorSymbol) tree.operator; 1857 Item l; 1858 if (operator.opcode == string_add) { 1859 // Generate code to make a string buffer 1860 makeStringBuffer(tree.pos()); 1861 1862 // Generate code for first string, possibly save one 1863 // copy under buffer 1864 l = genExpr(tree.lhs, tree.lhs.type); 1865 if (l.width() > 0) { 1866 code.emitop0(dup_x1 + 3 * (l.width() - 1)); 1867 } 1868 1869 // Load first string and append to buffer. 1870 l.load(); 1871 appendString(tree.lhs); 1872 1873 // Append all other strings to buffer. 1874 appendStrings(tree.rhs); 1875 1876 // Convert buffer to string. 1877 bufferToString(tree.pos()); 1878 } else { 1879 // Generate code for first expression 1880 l = genExpr(tree.lhs, tree.lhs.type); 1881 1882 // If we have an increment of -32768 to +32767 of a local 1883 // int variable we can use an incr instruction instead of 1884 // proceeding further. 1885 if ((tree.hasTag(PLUS_ASG) || tree.hasTag(MINUS_ASG)) && 1886 l instanceof LocalItem && 1887 tree.lhs.type.getTag().isSubRangeOf(INT) && 1888 tree.rhs.type.getTag().isSubRangeOf(INT) && 1889 tree.rhs.type.constValue() != null) { 1890 int ival = ((Number) tree.rhs.type.constValue()).intValue(); 1891 if (tree.hasTag(MINUS_ASG)) ival = -ival; 1892 ((LocalItem)l).incr(ival); 1893 result = l; 1894 return; 1895 } 1896 // Otherwise, duplicate expression, load one copy 1897 // and complete binary operation. 1898 l.duplicate(); 1899 l.coerce(operator.type.getParameterTypes().head).load(); 1900 completeBinop(tree.lhs, tree.rhs, operator).coerce(tree.lhs.type); 1901 } 1902 result = items.makeAssignItem(l); 1903 } 1904 1905 public void visitUnary(JCUnary tree) { 1906 OperatorSymbol operator = (OperatorSymbol)tree.operator; 1907 if (tree.hasTag(NOT)) { 1908 CondItem od = genCond(tree.arg, false); 1909 result = od.negate(); 1910 } else { 1911 Item od = genExpr(tree.arg, operator.type.getParameterTypes().head); 1912 switch (tree.getTag()) { 1913 case POS: 1914 result = od.load(); 1915 break; 1916 case NEG: 1917 result = od.load(); 1918 code.emitop0(operator.opcode); 1919 break; 1920 case COMPL: 1921 result = od.load(); 1922 emitMinusOne(od.typecode); 1923 code.emitop0(operator.opcode); 1924 break; 1925 case PREINC: case PREDEC: 1926 od.duplicate(); 1927 if (od instanceof LocalItem && 1928 (operator.opcode == iadd || operator.opcode == isub)) { 1929 ((LocalItem)od).incr(tree.hasTag(PREINC) ? 1 : -1); 1930 result = od; 1931 } else { 1932 od.load(); 1933 code.emitop0(one(od.typecode)); 1934 code.emitop0(operator.opcode); 1935 // Perform narrowing primitive conversion if byte, 1936 // char, or short. Fix for 4304655. 1937 if (od.typecode != INTcode && 1938 Code.truncate(od.typecode) == INTcode) 1939 code.emitop0(int2byte + od.typecode - BYTEcode); 1940 result = items.makeAssignItem(od); 1941 } 1942 break; 1943 case POSTINC: case POSTDEC: 1944 od.duplicate(); 1945 if (od instanceof LocalItem && 1946 (operator.opcode == iadd || operator.opcode == isub)) { 1947 Item res = od.load(); 1948 ((LocalItem)od).incr(tree.hasTag(POSTINC) ? 1 : -1); 1949 result = res; 1950 } else { 1951 Item res = od.load(); 1952 od.stash(od.typecode); 1953 code.emitop0(one(od.typecode)); 1954 code.emitop0(operator.opcode); 1955 // Perform narrowing primitive conversion if byte, 1956 // char, or short. Fix for 4304655. 1957 if (od.typecode != INTcode && 1958 Code.truncate(od.typecode) == INTcode) 1959 code.emitop0(int2byte + od.typecode - BYTEcode); 1960 od.store(); 1961 result = res; 1962 } 1963 break; 1964 case NULLCHK: 1965 result = od.load(); 1966 code.emitop0(dup); 1967 genNullCheck(tree.pos()); 1968 break; 1969 default: 1970 Assert.error(); 1971 } 1972 } 1973 } 1974 1975 /** Generate a null check from the object value at stack top. */ 1976 private void genNullCheck(DiagnosticPosition pos) { 1977 callMethod(pos, syms.objectType, names.getClass, 1978 List.<Type>nil(), false); 1979 code.emitop0(pop); 1980 } 1981 1982 public void visitBinary(JCBinary tree) { 1983 OperatorSymbol operator = (OperatorSymbol)tree.operator; 1984 if (operator.opcode == string_add) { 1985 // Create a string buffer. 1986 makeStringBuffer(tree.pos()); 1987 // Append all strings to buffer. 1988 appendStrings(tree); 1989 // Convert buffer to string. 1990 bufferToString(tree.pos()); 1991 result = items.makeStackItem(syms.stringType); 1992 } else if (tree.hasTag(AND)) { 1993 CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER); 1994 if (!lcond.isFalse()) { 1995 Chain falseJumps = lcond.jumpFalse(); 1996 code.resolve(lcond.trueJumps); 1997 CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET); 1998 result = items. 1999 makeCondItem(rcond.opcode, 2000 rcond.trueJumps, 2001 Code.mergeChains(falseJumps, 2002 rcond.falseJumps)); 2003 } else { 2004 result = lcond; 2005 } 2006 } else if (tree.hasTag(OR)) { 2007 CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER); 2008 if (!lcond.isTrue()) { 2009 Chain trueJumps = lcond.jumpTrue(); 2010 code.resolve(lcond.falseJumps); 2011 CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET); 2012 result = items. 2013 makeCondItem(rcond.opcode, 2014 Code.mergeChains(trueJumps, rcond.trueJumps), 2015 rcond.falseJumps); 2016 } else { 2017 result = lcond; 2018 } 2019 } else { 2020 Item od = genExpr(tree.lhs, operator.type.getParameterTypes().head); 2021 od.load(); 2022 result = completeBinop(tree.lhs, tree.rhs, operator); 2023 } 2024 } 2025//where 2026 /** Make a new string buffer. 2027 */ 2028 void makeStringBuffer(DiagnosticPosition pos) { 2029 code.emitop2(new_, makeRef(pos, stringBufferType)); 2030 code.emitop0(dup); 2031 callMethod( 2032 pos, stringBufferType, names.init, List.<Type>nil(), false); 2033 } 2034 2035 /** Append value (on tos) to string buffer (on tos - 1). 2036 */ 2037 void appendString(JCTree tree) { 2038 Type t = tree.type.baseType(); 2039 if (!t.isPrimitive() && t.tsym != syms.stringType.tsym) { 2040 t = syms.objectType; 2041 } 2042 items.makeMemberItem(getStringBufferAppend(tree, t), false).invoke(); 2043 } 2044 Symbol getStringBufferAppend(JCTree tree, Type t) { 2045 Assert.checkNull(t.constValue()); 2046 Symbol method = stringBufferAppend.get(t); 2047 if (method == null) { 2048 method = rs.resolveInternalMethod(tree.pos(), 2049 attrEnv, 2050 stringBufferType, 2051 names.append, 2052 List.of(t), 2053 null); 2054 stringBufferAppend.put(t, method); 2055 } 2056 return method; 2057 } 2058 2059 /** Add all strings in tree to string buffer. 2060 */ 2061 void appendStrings(JCTree tree) { 2062 tree = TreeInfo.skipParens(tree); 2063 if (tree.hasTag(PLUS) && tree.type.constValue() == null) { 2064 JCBinary op = (JCBinary) tree; 2065 if (op.operator.kind == MTH && 2066 ((OperatorSymbol) op.operator).opcode == string_add) { 2067 appendStrings(op.lhs); 2068 appendStrings(op.rhs); 2069 return; 2070 } 2071 } 2072 genExpr(tree, tree.type).load(); 2073 appendString(tree); 2074 } 2075 2076 /** Convert string buffer on tos to string. 2077 */ 2078 void bufferToString(DiagnosticPosition pos) { 2079 callMethod( 2080 pos, 2081 stringBufferType, 2082 names.toString, 2083 List.<Type>nil(), 2084 false); 2085 } 2086 2087 /** Complete generating code for operation, with left operand 2088 * already on stack. 2089 * @param lhs The tree representing the left operand. 2090 * @param rhs The tree representing the right operand. 2091 * @param operator The operator symbol. 2092 */ 2093 Item completeBinop(JCTree lhs, JCTree rhs, OperatorSymbol operator) { 2094 MethodType optype = (MethodType)operator.type; 2095 int opcode = operator.opcode; 2096 if (opcode >= if_icmpeq && opcode <= if_icmple && 2097 rhs.type.constValue() instanceof Number && 2098 ((Number) rhs.type.constValue()).intValue() == 0) { 2099 opcode = opcode + (ifeq - if_icmpeq); 2100 } else if (opcode >= if_acmpeq && opcode <= if_acmpne && 2101 TreeInfo.isNull(rhs)) { 2102 opcode = opcode + (if_acmp_null - if_acmpeq); 2103 } else { 2104 // The expected type of the right operand is 2105 // the second parameter type of the operator, except for 2106 // shifts with long shiftcount, where we convert the opcode 2107 // to a short shift and the expected type to int. 2108 Type rtype = operator.erasure(types).getParameterTypes().tail.head; 2109 if (opcode >= ishll && opcode <= lushrl) { 2110 opcode = opcode + (ishl - ishll); 2111 rtype = syms.intType; 2112 } 2113 // Generate code for right operand and load. 2114 genExpr(rhs, rtype).load(); 2115 // If there are two consecutive opcode instructions, 2116 // emit the first now. 2117 if (opcode >= (1 << preShift)) { 2118 code.emitop0(opcode >> preShift); 2119 opcode = opcode & 0xFF; 2120 } 2121 } 2122 if (opcode >= ifeq && opcode <= if_acmpne || 2123 opcode == if_acmp_null || opcode == if_acmp_nonnull) { 2124 return items.makeCondItem(opcode); 2125 } else { 2126 code.emitop0(opcode); 2127 return items.makeStackItem(optype.restype); 2128 } 2129 } 2130 2131 public void visitTypeCast(JCTypeCast tree) { 2132 setTypeAnnotationPositions(tree.pos); 2133 result = genExpr(tree.expr, tree.clazz.type).load(); 2134 // Additional code is only needed if we cast to a reference type 2135 // which is not statically a supertype of the expression's type. 2136 // For basic types, the coerce(...) in genExpr(...) will do 2137 // the conversion. 2138 if (!tree.clazz.type.isPrimitive() && 2139 types.asSuper(tree.expr.type, tree.clazz.type.tsym) == null) { 2140 code.emitop2(checkcast, makeRef(tree.pos(), tree.clazz.type)); 2141 } 2142 } 2143 2144 public void visitWildcard(JCWildcard tree) { 2145 throw new AssertionError(this.getClass().getName()); 2146 } 2147 2148 public void visitTypeTest(JCInstanceOf tree) { 2149 setTypeAnnotationPositions(tree.pos); 2150 genExpr(tree.expr, tree.expr.type).load(); 2151 code.emitop2(instanceof_, makeRef(tree.pos(), tree.clazz.type)); 2152 result = items.makeStackItem(syms.booleanType); 2153 } 2154 2155 public void visitIndexed(JCArrayAccess tree) { 2156 genExpr(tree.indexed, tree.indexed.type).load(); 2157 genExpr(tree.index, syms.intType).load(); 2158 result = items.makeIndexedItem(tree.type); 2159 } 2160 2161 public void visitIdent(JCIdent tree) { 2162 Symbol sym = tree.sym; 2163 if (tree.name == names._this || tree.name == names._super) { 2164 Item res = tree.name == names._this 2165 ? items.makeThisItem() 2166 : items.makeSuperItem(); 2167 if (sym.kind == MTH) { 2168 // Generate code to address the constructor. 2169 res.load(); 2170 res = items.makeMemberItem(sym, true); 2171 } 2172 result = res; 2173 } else if (sym.kind == VAR && sym.owner.kind == MTH) { 2174 result = items.makeLocalItem((VarSymbol)sym); 2175 } else if (isInvokeDynamic(sym)) { 2176 result = items.makeDynamicItem(sym); 2177 } else if ((sym.flags() & STATIC) != 0) { 2178 if (!isAccessSuper(env.enclMethod)) 2179 sym = binaryQualifier(sym, env.enclClass.type); 2180 result = items.makeStaticItem(sym); 2181 } else { 2182 items.makeThisItem().load(); 2183 sym = binaryQualifier(sym, env.enclClass.type); 2184 result = items.makeMemberItem(sym, (sym.flags() & PRIVATE) != 0); 2185 } 2186 } 2187 2188 public void visitSelect(JCFieldAccess tree) { 2189 Symbol sym = tree.sym; 2190 2191 if (tree.name == names._class) { 2192 code.emitLdc(makeRef(tree.pos(), tree.selected.type)); 2193 result = items.makeStackItem(pt); 2194 return; 2195 } 2196 2197 Symbol ssym = TreeInfo.symbol(tree.selected); 2198 2199 // Are we selecting via super? 2200 boolean selectSuper = 2201 ssym != null && (ssym.kind == TYP || ssym.name == names._super); 2202 2203 // Are we accessing a member of the superclass in an access method 2204 // resulting from a qualified super? 2205 boolean accessSuper = isAccessSuper(env.enclMethod); 2206 2207 Item base = (selectSuper) 2208 ? items.makeSuperItem() 2209 : genExpr(tree.selected, tree.selected.type); 2210 2211 if (sym.kind == VAR && ((VarSymbol) sym).getConstValue() != null) { 2212 // We are seeing a variable that is constant but its selecting 2213 // expression is not. 2214 if ((sym.flags() & STATIC) != 0) { 2215 if (!selectSuper && (ssym == null || ssym.kind != TYP)) 2216 base = base.load(); 2217 base.drop(); 2218 } else { 2219 base.load(); 2220 genNullCheck(tree.selected.pos()); 2221 } 2222 result = items. 2223 makeImmediateItem(sym.type, ((VarSymbol) sym).getConstValue()); 2224 } else { 2225 if (isInvokeDynamic(sym)) { 2226 result = items.makeDynamicItem(sym); 2227 return; 2228 } else { 2229 sym = binaryQualifier(sym, tree.selected.type); 2230 } 2231 if ((sym.flags() & STATIC) != 0) { 2232 if (!selectSuper && (ssym == null || ssym.kind != TYP)) 2233 base = base.load(); 2234 base.drop(); 2235 result = items.makeStaticItem(sym); 2236 } else { 2237 base.load(); 2238 if (sym == syms.lengthVar) { 2239 code.emitop0(arraylength); 2240 result = items.makeStackItem(syms.intType); 2241 } else { 2242 result = items. 2243 makeMemberItem(sym, 2244 (sym.flags() & PRIVATE) != 0 || 2245 selectSuper || accessSuper); 2246 } 2247 } 2248 } 2249 } 2250 2251 public boolean isInvokeDynamic(Symbol sym) { 2252 return sym.kind == MTH && ((MethodSymbol)sym).isDynamic(); 2253 } 2254 2255 public void visitLiteral(JCLiteral tree) { 2256 if (tree.type.hasTag(BOT)) { 2257 code.emitop0(aconst_null); 2258 if (types.dimensions(pt) > 1) { 2259 code.emitop2(checkcast, makeRef(tree.pos(), pt)); 2260 result = items.makeStackItem(pt); 2261 } else { 2262 result = items.makeStackItem(tree.type); 2263 } 2264 } 2265 else 2266 result = items.makeImmediateItem(tree.type, tree.value); 2267 } 2268 2269 public void visitLetExpr(LetExpr tree) { 2270 int limit = code.nextreg; 2271 genStats(tree.defs, env); 2272 result = genExpr(tree.expr, tree.expr.type).load(); 2273 code.endScopes(limit); 2274 } 2275 2276 private void generateReferencesToPrunedTree(ClassSymbol classSymbol, Pool pool) { 2277 List<JCTree> prunedInfo = lower.prunedTree.get(classSymbol); 2278 if (prunedInfo != null) { 2279 for (JCTree prunedTree: prunedInfo) { 2280 prunedTree.accept(classReferenceVisitor); 2281 } 2282 } 2283 } 2284 2285/* ************************************************************************ 2286 * main method 2287 *************************************************************************/ 2288 2289 /** Generate code for a class definition. 2290 * @param env The attribution environment that belongs to the 2291 * outermost class containing this class definition. 2292 * We need this for resolving some additional symbols. 2293 * @param cdef The tree representing the class definition. 2294 * @return True if code is generated with no errors. 2295 */ 2296 public boolean genClass(Env<AttrContext> env, JCClassDecl cdef) { 2297 try { 2298 attrEnv = env; 2299 ClassSymbol c = cdef.sym; 2300 this.toplevel = env.toplevel; 2301 this.endPosTable = toplevel.endPositions; 2302 cdef.defs = normalizeDefs(cdef.defs, c); 2303 c.pool = pool; 2304 pool.reset(); 2305 generateReferencesToPrunedTree(c, pool); 2306 Env<GenContext> localEnv = new Env<>(cdef, new GenContext()); 2307 localEnv.toplevel = env.toplevel; 2308 localEnv.enclClass = cdef; 2309 2310 for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) { 2311 genDef(l.head, localEnv); 2312 } 2313 if (pool.numEntries() > Pool.MAX_ENTRIES) { 2314 log.error(cdef.pos(), "limit.pool"); 2315 nerrs++; 2316 } 2317 if (nerrs != 0) { 2318 // if errors, discard code 2319 for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) { 2320 if (l.head.hasTag(METHODDEF)) 2321 ((JCMethodDecl) l.head).sym.code = null; 2322 } 2323 } 2324 cdef.defs = List.nil(); // discard trees 2325 return nerrs == 0; 2326 } finally { 2327 // note: this method does NOT support recursion. 2328 attrEnv = null; 2329 this.env = null; 2330 toplevel = null; 2331 endPosTable = null; 2332 nerrs = 0; 2333 } 2334 } 2335 2336/* ************************************************************************ 2337 * Auxiliary classes 2338 *************************************************************************/ 2339 2340 /** An abstract class for finalizer generation. 2341 */ 2342 abstract class GenFinalizer { 2343 /** Generate code to clean up when unwinding. */ 2344 abstract void gen(); 2345 2346 /** Generate code to clean up at last. */ 2347 abstract void genLast(); 2348 2349 /** Does this finalizer have some nontrivial cleanup to perform? */ 2350 boolean hasFinalizer() { return true; } 2351 } 2352 2353 /** code generation contexts, 2354 * to be used as type parameter for environments. 2355 */ 2356 static class GenContext { 2357 2358 /** A chain for all unresolved jumps that exit the current environment. 2359 */ 2360 Chain exit = null; 2361 2362 /** A chain for all unresolved jumps that continue in the 2363 * current environment. 2364 */ 2365 Chain cont = null; 2366 2367 /** A closure that generates the finalizer of the current environment. 2368 * Only set for Synchronized and Try contexts. 2369 */ 2370 GenFinalizer finalize = null; 2371 2372 /** Is this a switch statement? If so, allocate registers 2373 * even when the variable declaration is unreachable. 2374 */ 2375 boolean isSwitch = false; 2376 2377 /** A list buffer containing all gaps in the finalizer range, 2378 * where a catch all exception should not apply. 2379 */ 2380 ListBuffer<Integer> gaps = null; 2381 2382 /** Add given chain to exit chain. 2383 */ 2384 void addExit(Chain c) { 2385 exit = Code.mergeChains(c, exit); 2386 } 2387 2388 /** Add given chain to cont chain. 2389 */ 2390 void addCont(Chain c) { 2391 cont = Code.mergeChains(c, cont); 2392 } 2393 } 2394 2395} 2396