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