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