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