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