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