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