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