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