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