CodeGenerator.java revision 1655:3ac5d360070e
1/*
2 * Copyright (c) 2010, 2016, 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 jdk.nashorn.internal.codegen;
27
28import static jdk.nashorn.internal.codegen.ClassEmitter.Flag.PRIVATE;
29import static jdk.nashorn.internal.codegen.ClassEmitter.Flag.STATIC;
30import static jdk.nashorn.internal.codegen.CompilerConstants.ARGUMENTS;
31import static jdk.nashorn.internal.codegen.CompilerConstants.CALLEE;
32import static jdk.nashorn.internal.codegen.CompilerConstants.CREATE_PROGRAM_FUNCTION;
33import static jdk.nashorn.internal.codegen.CompilerConstants.GET_MAP;
34import static jdk.nashorn.internal.codegen.CompilerConstants.GET_STRING;
35import static jdk.nashorn.internal.codegen.CompilerConstants.QUICK_PREFIX;
36import static jdk.nashorn.internal.codegen.CompilerConstants.REGEX_PREFIX;
37import static jdk.nashorn.internal.codegen.CompilerConstants.SCOPE;
38import static jdk.nashorn.internal.codegen.CompilerConstants.SPLIT_PREFIX;
39import static jdk.nashorn.internal.codegen.CompilerConstants.THIS;
40import static jdk.nashorn.internal.codegen.CompilerConstants.VARARGS;
41import static jdk.nashorn.internal.codegen.CompilerConstants.interfaceCallNoLookup;
42import static jdk.nashorn.internal.codegen.CompilerConstants.methodDescriptor;
43import static jdk.nashorn.internal.codegen.CompilerConstants.staticCallNoLookup;
44import static jdk.nashorn.internal.codegen.CompilerConstants.typeDescriptor;
45import static jdk.nashorn.internal.codegen.CompilerConstants.virtualCallNoLookup;
46import static jdk.nashorn.internal.ir.Symbol.HAS_SLOT;
47import static jdk.nashorn.internal.ir.Symbol.IS_INTERNAL;
48import static jdk.nashorn.internal.runtime.UnwarrantedOptimismException.INVALID_PROGRAM_POINT;
49import static jdk.nashorn.internal.runtime.UnwarrantedOptimismException.isValid;
50import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_APPLY_TO_CALL;
51import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_DECLARE;
52import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_FAST_SCOPE;
53import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_OPTIMISTIC;
54import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_PROGRAM_POINT_SHIFT;
55import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_SCOPE;
56
57import java.io.PrintWriter;
58import java.util.ArrayDeque;
59import java.util.ArrayList;
60import java.util.Arrays;
61import java.util.BitSet;
62import java.util.Collection;
63import java.util.Collections;
64import java.util.Deque;
65import java.util.EnumSet;
66import java.util.HashMap;
67import java.util.HashSet;
68import java.util.Iterator;
69import java.util.LinkedList;
70import java.util.List;
71import java.util.Map;
72import java.util.Set;
73import java.util.TreeMap;
74import java.util.function.Supplier;
75import jdk.nashorn.internal.AssertsEnabled;
76import jdk.nashorn.internal.IntDeque;
77import jdk.nashorn.internal.codegen.ClassEmitter.Flag;
78import jdk.nashorn.internal.codegen.CompilerConstants.Call;
79import jdk.nashorn.internal.codegen.types.ArrayType;
80import jdk.nashorn.internal.codegen.types.Type;
81import jdk.nashorn.internal.ir.AccessNode;
82import jdk.nashorn.internal.ir.BaseNode;
83import jdk.nashorn.internal.ir.BinaryNode;
84import jdk.nashorn.internal.ir.Block;
85import jdk.nashorn.internal.ir.BlockStatement;
86import jdk.nashorn.internal.ir.BreakNode;
87import jdk.nashorn.internal.ir.CallNode;
88import jdk.nashorn.internal.ir.CaseNode;
89import jdk.nashorn.internal.ir.CatchNode;
90import jdk.nashorn.internal.ir.ContinueNode;
91import jdk.nashorn.internal.ir.EmptyNode;
92import jdk.nashorn.internal.ir.Expression;
93import jdk.nashorn.internal.ir.ExpressionStatement;
94import jdk.nashorn.internal.ir.ForNode;
95import jdk.nashorn.internal.ir.FunctionNode;
96import jdk.nashorn.internal.ir.GetSplitState;
97import jdk.nashorn.internal.ir.IdentNode;
98import jdk.nashorn.internal.ir.IfNode;
99import jdk.nashorn.internal.ir.IndexNode;
100import jdk.nashorn.internal.ir.JoinPredecessorExpression;
101import jdk.nashorn.internal.ir.JumpStatement;
102import jdk.nashorn.internal.ir.JumpToInlinedFinally;
103import jdk.nashorn.internal.ir.LabelNode;
104import jdk.nashorn.internal.ir.LexicalContext;
105import jdk.nashorn.internal.ir.LexicalContextNode;
106import jdk.nashorn.internal.ir.LiteralNode;
107import jdk.nashorn.internal.ir.LiteralNode.ArrayLiteralNode;
108import jdk.nashorn.internal.ir.LiteralNode.PrimitiveLiteralNode;
109import jdk.nashorn.internal.ir.LocalVariableConversion;
110import jdk.nashorn.internal.ir.LoopNode;
111import jdk.nashorn.internal.ir.Node;
112import jdk.nashorn.internal.ir.ObjectNode;
113import jdk.nashorn.internal.ir.Optimistic;
114import jdk.nashorn.internal.ir.PropertyNode;
115import jdk.nashorn.internal.ir.ReturnNode;
116import jdk.nashorn.internal.ir.RuntimeNode;
117import jdk.nashorn.internal.ir.RuntimeNode.Request;
118import jdk.nashorn.internal.ir.SetSplitState;
119import jdk.nashorn.internal.ir.SplitReturn;
120import jdk.nashorn.internal.ir.Splittable;
121import jdk.nashorn.internal.ir.Statement;
122import jdk.nashorn.internal.ir.SwitchNode;
123import jdk.nashorn.internal.ir.Symbol;
124import jdk.nashorn.internal.ir.TernaryNode;
125import jdk.nashorn.internal.ir.ThrowNode;
126import jdk.nashorn.internal.ir.TryNode;
127import jdk.nashorn.internal.ir.UnaryNode;
128import jdk.nashorn.internal.ir.VarNode;
129import jdk.nashorn.internal.ir.WhileNode;
130import jdk.nashorn.internal.ir.WithNode;
131import jdk.nashorn.internal.ir.visitor.NodeOperatorVisitor;
132import jdk.nashorn.internal.ir.visitor.SimpleNodeVisitor;
133import jdk.nashorn.internal.objects.Global;
134import jdk.nashorn.internal.parser.Lexer.RegexToken;
135import jdk.nashorn.internal.parser.TokenType;
136import jdk.nashorn.internal.runtime.Context;
137import jdk.nashorn.internal.runtime.Debug;
138import jdk.nashorn.internal.runtime.ECMAException;
139import jdk.nashorn.internal.runtime.JSType;
140import jdk.nashorn.internal.runtime.OptimisticReturnFilters;
141import jdk.nashorn.internal.runtime.PropertyMap;
142import jdk.nashorn.internal.runtime.RecompilableScriptFunctionData;
143import jdk.nashorn.internal.runtime.RewriteException;
144import jdk.nashorn.internal.runtime.Scope;
145import jdk.nashorn.internal.runtime.ScriptEnvironment;
146import jdk.nashorn.internal.runtime.ScriptFunction;
147import jdk.nashorn.internal.runtime.ScriptObject;
148import jdk.nashorn.internal.runtime.ScriptRuntime;
149import jdk.nashorn.internal.runtime.Source;
150import jdk.nashorn.internal.runtime.Undefined;
151import jdk.nashorn.internal.runtime.UnwarrantedOptimismException;
152import jdk.nashorn.internal.runtime.arrays.ArrayData;
153import jdk.nashorn.internal.runtime.linker.LinkerCallSite;
154import jdk.nashorn.internal.runtime.logging.DebugLogger;
155import jdk.nashorn.internal.runtime.logging.Loggable;
156import jdk.nashorn.internal.runtime.logging.Logger;
157import jdk.nashorn.internal.runtime.options.Options;
158
159/**
160 * This is the lowest tier of the code generator. It takes lowered ASTs emitted
161 * from Lower and emits Java byte code. The byte code emission logic is broken
162 * out into MethodEmitter. MethodEmitter works internally with a type stack, and
163 * keeps track of the contents of the byte code stack. This way we avoid a large
164 * number of special cases on the form
165 * <pre>
166 * if (type == INT) {
167 *     visitInsn(ILOAD, slot);
168 * } else if (type == DOUBLE) {
169 *     visitInsn(DOUBLE, slot);
170 * }
171 * </pre>
172 * This quickly became apparent when the code generator was generalized to work
173 * with all types, and not just numbers or objects.
174 * <p>
175 * The CodeGenerator visits nodes only once and emits bytecode for them.
176 */
177@Logger(name="codegen")
178final class CodeGenerator extends NodeOperatorVisitor<CodeGeneratorLexicalContext> implements Loggable {
179
180    private static final Type SCOPE_TYPE = Type.typeFor(ScriptObject.class);
181
182    private static final String GLOBAL_OBJECT = Type.getInternalName(Global.class);
183
184    private static final Call CREATE_REWRITE_EXCEPTION = CompilerConstants.staticCallNoLookup(RewriteException.class,
185            "create", RewriteException.class, UnwarrantedOptimismException.class, Object[].class, String[].class);
186    private static final Call CREATE_REWRITE_EXCEPTION_REST_OF = CompilerConstants.staticCallNoLookup(RewriteException.class,
187            "create", RewriteException.class, UnwarrantedOptimismException.class, Object[].class, String[].class, int[].class);
188
189    private static final Call ENSURE_INT = CompilerConstants.staticCallNoLookup(OptimisticReturnFilters.class,
190            "ensureInt", int.class, Object.class, int.class);
191    private static final Call ENSURE_NUMBER = CompilerConstants.staticCallNoLookup(OptimisticReturnFilters.class,
192            "ensureNumber", double.class, Object.class, int.class);
193
194    private static final Call CREATE_FUNCTION_OBJECT = CompilerConstants.staticCallNoLookup(ScriptFunction.class,
195            "create", ScriptFunction.class, Object[].class, int.class, ScriptObject.class);
196    private static final Call CREATE_FUNCTION_OBJECT_NO_SCOPE = CompilerConstants.staticCallNoLookup(ScriptFunction.class,
197            "create", ScriptFunction.class, Object[].class, int.class);
198
199    private static final Call TO_NUMBER_FOR_EQ = CompilerConstants.staticCallNoLookup(JSType.class,
200            "toNumberForEq", double.class, Object.class);
201    private static final Call TO_NUMBER_FOR_STRICT_EQ = CompilerConstants.staticCallNoLookup(JSType.class,
202            "toNumberForStrictEq", double.class, Object.class);
203
204
205    private static final Class<?> ITERATOR_CLASS = Iterator.class;
206    static {
207        assert ITERATOR_CLASS == CompilerConstants.ITERATOR_PREFIX.type();
208    }
209    private static final Type ITERATOR_TYPE = Type.typeFor(ITERATOR_CLASS);
210    private static final Type EXCEPTION_TYPE = Type.typeFor(CompilerConstants.EXCEPTION_PREFIX.type());
211
212    private static final Integer INT_ZERO = 0;
213
214    /** Constant data & installation. The only reason the compiler keeps this is because it is assigned
215     *  by reflection in class installation */
216    private final Compiler compiler;
217
218    /** Is the current code submitted by 'eval' call? */
219    private final boolean evalCode;
220
221    /** Call site flags given to the code generator to be used for all generated call sites */
222    private final int callSiteFlags;
223
224    /** How many regexp fields have been emitted */
225    private int regexFieldCount;
226
227    /** Line number for last statement. If we encounter a new line number, line number bytecode information
228     *  needs to be generated */
229    private int lastLineNumber = -1;
230
231    /** When should we stop caching regexp expressions in fields to limit bytecode size? */
232    private static final int MAX_REGEX_FIELDS = 2 * 1024;
233
234    /** Current method emitter */
235    private MethodEmitter method;
236
237    /** Current compile unit */
238    private CompileUnit unit;
239
240    private final DebugLogger log;
241
242    /** From what size should we use spill instead of fields for JavaScript objects? */
243    static final int OBJECT_SPILL_THRESHOLD = Options.getIntProperty("nashorn.spill.threshold", 256);
244
245    private final Set<String> emittedMethods = new HashSet<>();
246
247    // Function Id -> ContinuationInfo. Used by compilation of rest-of function only.
248    private ContinuationInfo continuationInfo;
249
250    private final Deque<Label> scopeEntryLabels = new ArrayDeque<>();
251
252    private static final Label METHOD_BOUNDARY = new Label("");
253    private final Deque<Label> catchLabels = new ArrayDeque<>();
254    // Number of live locals on entry to (and thus also break from) labeled blocks.
255    private final IntDeque labeledBlockBreakLiveLocals = new IntDeque();
256
257    //is this a rest of compilation
258    private final int[] continuationEntryPoints;
259
260    // Scope object creators needed for for-of and for-in loops
261    private Deque<FieldObjectCreator<?>> scopeObjectCreators = new ArrayDeque<>();
262
263    /**
264     * Constructor.
265     *
266     * @param compiler
267     */
268    CodeGenerator(final Compiler compiler, final int[] continuationEntryPoints) {
269        super(new CodeGeneratorLexicalContext());
270        this.compiler                = compiler;
271        this.evalCode                = compiler.getSource().isEvalCode();
272        this.continuationEntryPoints = continuationEntryPoints;
273        this.callSiteFlags           = compiler.getScriptEnvironment()._callsite_flags;
274        this.log                     = initLogger(compiler.getContext());
275    }
276
277    @Override
278    public DebugLogger getLogger() {
279        return log;
280    }
281
282    @Override
283    public DebugLogger initLogger(final Context context) {
284        return context.getLogger(this.getClass());
285    }
286
287    /**
288     * Gets the call site flags, adding the strict flag if the current function
289     * being generated is in strict mode
290     *
291     * @return the correct flags for a call site in the current function
292     */
293    int getCallSiteFlags() {
294        return lc.getCurrentFunction().getCallSiteFlags() | callSiteFlags;
295    }
296
297    /**
298     * Gets the flags for a scope call site.
299     * @param symbol a scope symbol
300     * @return the correct flags for the scope call site
301     */
302    private int getScopeCallSiteFlags(final Symbol symbol) {
303        assert symbol.isScope();
304        final int flags = getCallSiteFlags() | CALLSITE_SCOPE;
305        if (isEvalCode() && symbol.isGlobal()) {
306            return flags; // Don't set fast-scope flag on non-declared globals in eval code - see JDK-8077955.
307        }
308        return isFastScope(symbol) ? flags | CALLSITE_FAST_SCOPE : flags;
309    }
310
311    /**
312     * Are we generating code for 'eval' code?
313     * @return true if currently compiled code is 'eval' code.
314     */
315    boolean isEvalCode() {
316        return evalCode;
317    }
318
319    /**
320     * Are we using dual primitive/object field representation?
321     * @return true if using dual field representation, false for object-only fields
322     */
323    boolean useDualFields() {
324        return compiler.getContext().useDualFields();
325    }
326
327    /**
328     * Load an identity node
329     *
330     * @param identNode an identity node to load
331     * @return the method generator used
332     */
333    private MethodEmitter loadIdent(final IdentNode identNode, final TypeBounds resultBounds) {
334        checkTemporalDeadZone(identNode);
335        final Symbol symbol = identNode.getSymbol();
336
337        if (!symbol.isScope()) {
338            final Type type = identNode.getType();
339            if(type == Type.UNDEFINED) {
340                return method.loadUndefined(resultBounds.widest);
341            }
342
343            assert symbol.hasSlot() || symbol.isParam();
344            return method.load(identNode);
345        }
346
347        assert identNode.getSymbol().isScope() : identNode + " is not in scope!";
348        final int flags = getScopeCallSiteFlags(symbol);
349        if (isFastScope(symbol)) {
350            // Only generate shared scope getter for fast-scope symbols so we know we can dial in correct scope.
351            if (symbol.getUseCount() > SharedScopeCall.FAST_SCOPE_GET_THRESHOLD && !identNode.isOptimistic()) {
352                // As shared scope vars are only used with non-optimistic identifiers, we switch from using TypeBounds to
353                // just a single definitive type, resultBounds.widest.
354                new OptimisticOperation(identNode, TypeBounds.OBJECT) {
355                    @Override
356                    void loadStack() {
357                        method.loadCompilerConstant(SCOPE);
358                    }
359
360                    @Override
361                    void consumeStack() {
362                        loadSharedScopeVar(resultBounds.widest, symbol, flags);
363                    }
364                }.emit();
365            } else {
366                new LoadFastScopeVar(identNode, resultBounds, flags).emit();
367            }
368        } else {
369            //slow scope load, we have no proto depth
370            new LoadScopeVar(identNode, resultBounds, flags).emit();
371        }
372
373        return method;
374    }
375
376    // Any access to LET and CONST variables before their declaration must throw ReferenceError.
377    // This is called the temporal dead zone (TDZ). See https://gist.github.com/rwaldron/f0807a758aa03bcdd58a
378    private void checkTemporalDeadZone(final IdentNode identNode) {
379        if (identNode.isDead()) {
380            method.load(identNode.getSymbol().getName()).invoke(ScriptRuntime.THROW_REFERENCE_ERROR);
381        }
382    }
383
384    // Runtime check for assignment to ES6 const
385    private void checkAssignTarget(final Expression expression) {
386        if (expression instanceof IdentNode && ((IdentNode)expression).getSymbol().isConst()) {
387            method.load(((IdentNode)expression).getSymbol().getName()).invoke(ScriptRuntime.THROW_CONST_TYPE_ERROR);
388        }
389    }
390
391    private boolean isRestOf() {
392        return continuationEntryPoints != null;
393    }
394
395    private boolean isCurrentContinuationEntryPoint(final int programPoint) {
396        return isRestOf() && getCurrentContinuationEntryPoint() == programPoint;
397    }
398
399    private int[] getContinuationEntryPoints() {
400        return isRestOf() ? continuationEntryPoints : null;
401    }
402
403    private int getCurrentContinuationEntryPoint() {
404        return isRestOf() ? continuationEntryPoints[0] : INVALID_PROGRAM_POINT;
405    }
406
407    private boolean isContinuationEntryPoint(final int programPoint) {
408        if (isRestOf()) {
409            assert continuationEntryPoints != null;
410            for (final int cep : continuationEntryPoints) {
411                if (cep == programPoint) {
412                    return true;
413                }
414            }
415        }
416        return false;
417    }
418
419    /**
420     * Check if this symbol can be accessed directly with a putfield or getfield or dynamic load
421     *
422     * @param symbol symbol to check for fast scope
423     * @return true if fast scope
424     */
425    private boolean isFastScope(final Symbol symbol) {
426        if (!symbol.isScope()) {
427            return false;
428        }
429
430        if (!lc.inDynamicScope()) {
431            // If there's no with or eval in context, and the symbol is marked as scoped, it is fast scoped. Such a
432            // symbol must either be global, or its defining block must need scope.
433            assert symbol.isGlobal() || lc.getDefiningBlock(symbol).needsScope() : symbol.getName();
434            return true;
435        }
436
437        if (symbol.isGlobal()) {
438            // Shortcut: if there's a with or eval in context, globals can't be fast scoped
439            return false;
440        }
441
442        // Otherwise, check if there's a dynamic scope between use of the symbol and its definition
443        final String name = symbol.getName();
444        boolean previousWasBlock = false;
445        for (final Iterator<LexicalContextNode> it = lc.getAllNodes(); it.hasNext();) {
446            final LexicalContextNode node = it.next();
447            if (node instanceof Block) {
448                // If this block defines the symbol, then we can fast scope the symbol.
449                final Block block = (Block)node;
450                if (block.getExistingSymbol(name) == symbol) {
451                    assert block.needsScope();
452                    return true;
453                }
454                previousWasBlock = true;
455            } else {
456                if (node instanceof WithNode && previousWasBlock || node instanceof FunctionNode && ((FunctionNode)node).needsDynamicScope()) {
457                    // If we hit a scope that can have symbols introduced into it at run time before finding the defining
458                    // block, the symbol can't be fast scoped. A WithNode only counts if we've immediately seen a block
459                    // before - its block. Otherwise, we are currently processing the WithNode's expression, and that's
460                    // obviously not subjected to introducing new symbols.
461                    return false;
462                }
463                previousWasBlock = false;
464            }
465        }
466        // Should've found the symbol defined in a block
467        throw new AssertionError();
468    }
469
470    private MethodEmitter loadSharedScopeVar(final Type valueType, final Symbol symbol, final int flags) {
471        assert isFastScope(symbol);
472        method.load(getScopeProtoDepth(lc.getCurrentBlock(), symbol));
473        return lc.getScopeGet(unit, symbol, valueType, flags).generateInvoke(method);
474    }
475
476    private class LoadScopeVar extends OptimisticOperation {
477        final IdentNode identNode;
478        private final int flags;
479
480        LoadScopeVar(final IdentNode identNode, final TypeBounds resultBounds, final int flags) {
481            super(identNode, resultBounds);
482            this.identNode = identNode;
483            this.flags = flags;
484        }
485
486        @Override
487        void loadStack() {
488            method.loadCompilerConstant(SCOPE);
489            getProto();
490        }
491
492        void getProto() {
493            //empty
494        }
495
496        @Override
497        void consumeStack() {
498            // If this is either __FILE__, __DIR__, or __LINE__ then load the property initially as Object as we'd convert
499            // it anyway for replaceLocationPropertyPlaceholder.
500            if(identNode.isCompileTimePropertyName()) {
501                method.dynamicGet(Type.OBJECT, identNode.getSymbol().getName(), flags, identNode.isFunction(), false);
502                replaceCompileTimeProperty();
503            } else {
504                dynamicGet(identNode.getSymbol().getName(), flags, identNode.isFunction(), false);
505            }
506        }
507    }
508
509    private class LoadFastScopeVar extends LoadScopeVar {
510        LoadFastScopeVar(final IdentNode identNode, final TypeBounds resultBounds, final int flags) {
511            super(identNode, resultBounds, flags);
512        }
513
514        @Override
515        void getProto() {
516            loadFastScopeProto(identNode.getSymbol(), false);
517        }
518    }
519
520    private MethodEmitter storeFastScopeVar(final Symbol symbol, final int flags) {
521        loadFastScopeProto(symbol, true);
522        method.dynamicSet(symbol.getName(), flags, false);
523        return method;
524    }
525
526    private int getScopeProtoDepth(final Block startingBlock, final Symbol symbol) {
527        //walk up the chain from starting block and when we bump into the current function boundary, add the external
528        //information.
529        final FunctionNode fn   = lc.getCurrentFunction();
530        final int externalDepth = compiler.getScriptFunctionData(fn.getId()).getExternalSymbolDepth(symbol.getName());
531
532        //count the number of scopes from this place to the start of the function
533
534        final int internalDepth = FindScopeDepths.findInternalDepth(lc, fn, startingBlock, symbol);
535        final int scopesToStart = FindScopeDepths.findScopesToStart(lc, fn, startingBlock);
536        int depth = 0;
537        if (internalDepth == -1) {
538            depth = scopesToStart + externalDepth;
539        } else {
540            assert internalDepth <= scopesToStart;
541            depth = internalDepth;
542        }
543
544        return depth;
545    }
546
547    private void loadFastScopeProto(final Symbol symbol, final boolean swap) {
548        final int depth = getScopeProtoDepth(lc.getCurrentBlock(), symbol);
549        assert depth != -1 : "Couldn't find scope depth for symbol " + symbol.getName() + " in " + lc.getCurrentFunction();
550        if (depth > 0) {
551            if (swap) {
552                method.swap();
553            }
554            if (depth > 1) {
555                method.load(depth);
556                method.invoke(ScriptObject.GET_PROTO_DEPTH);
557            } else {
558                method.invoke(ScriptObject.GET_PROTO);
559            }
560            if (swap) {
561                method.swap();
562            }
563        }
564    }
565
566    /**
567     * Generate code that loads this node to the stack, not constraining its type
568     *
569     * @param expr node to load
570     *
571     * @return the method emitter used
572     */
573    private MethodEmitter loadExpressionUnbounded(final Expression expr) {
574        return loadExpression(expr, TypeBounds.UNBOUNDED);
575    }
576
577    private MethodEmitter loadExpressionAsObject(final Expression expr) {
578        return loadExpression(expr, TypeBounds.OBJECT);
579    }
580
581    MethodEmitter loadExpressionAsBoolean(final Expression expr) {
582        return loadExpression(expr, TypeBounds.BOOLEAN);
583    }
584
585    // Test whether conversion from source to target involves a call of ES 9.1 ToPrimitive
586    // with possible side effects from calling an object's toString or valueOf methods.
587    private static boolean noToPrimitiveConversion(final Type source, final Type target) {
588        // Object to boolean conversion does not cause ToPrimitive call
589        return source.isJSPrimitive() || !target.isJSPrimitive() || target.isBoolean();
590    }
591
592    MethodEmitter loadBinaryOperands(final BinaryNode binaryNode) {
593        return loadBinaryOperands(binaryNode.lhs(), binaryNode.rhs(), TypeBounds.UNBOUNDED.notWiderThan(binaryNode.getWidestOperandType()), false, false);
594    }
595
596    private MethodEmitter loadBinaryOperands(final Expression lhs, final Expression rhs, final TypeBounds explicitOperandBounds, final boolean baseAlreadyOnStack, final boolean forceConversionSeparation) {
597        // ECMAScript 5.1 specification (sections 11.5-11.11 and 11.13) prescribes that when evaluating a binary
598        // expression "LEFT op RIGHT", the order of operations must be: LOAD LEFT, LOAD RIGHT, CONVERT LEFT, CONVERT
599        // RIGHT, EXECUTE OP. Unfortunately, doing it in this order defeats potential optimizations that arise when we
600        // can combine a LOAD with a CONVERT operation (e.g. use a dynamic getter with the conversion target type as its
601        // return value). What we do here is reorder LOAD RIGHT and CONVERT LEFT when possible; it is possible only when
602        // we can prove that executing CONVERT LEFT can't have a side effect that changes the value of LOAD RIGHT.
603        // Basically, if we know that either LEFT already is a primitive value, or does not have to be converted to
604        // a primitive value, or RIGHT is an expression that loads without side effects, then we can do the
605        // reordering and collapse LOAD/CONVERT into a single operation; otherwise we need to do the more costly
606        // separate operations to preserve specification semantics.
607
608        // Operands' load type should not be narrower than the narrowest of the individual operand types, nor narrower
609        // than the lower explicit bound, but it should also not be wider than
610        final Type lhsType = undefinedToNumber(lhs.getType());
611        final Type rhsType = undefinedToNumber(rhs.getType());
612        final Type narrowestOperandType = Type.narrowest(Type.widest(lhsType, rhsType), explicitOperandBounds.widest);
613        final TypeBounds operandBounds = explicitOperandBounds.notNarrowerThan(narrowestOperandType);
614        if (noToPrimitiveConversion(lhsType, explicitOperandBounds.widest) || rhs.isLocal()) {
615            // Can reorder. We might still need to separate conversion, but at least we can do it with reordering
616            if (forceConversionSeparation) {
617                // Can reorder, but can't move conversion into the operand as the operation depends on operands
618                // exact types for its overflow guarantees. E.g. with {L}{%I}expr1 {L}* {L}{%I}expr2 we are not allowed
619                // to merge {L}{%I} into {%L}, as that can cause subsequent overflows; test for JDK-8058610 contains
620                // concrete cases where this could happen.
621                final TypeBounds safeConvertBounds = TypeBounds.UNBOUNDED.notNarrowerThan(narrowestOperandType);
622                loadExpression(lhs, safeConvertBounds, baseAlreadyOnStack);
623                method.convert(operandBounds.within(method.peekType()));
624                loadExpression(rhs, safeConvertBounds, false);
625                method.convert(operandBounds.within(method.peekType()));
626            } else {
627                // Can reorder and move conversion into the operand. Combine load and convert into single operations.
628                loadExpression(lhs, operandBounds, baseAlreadyOnStack);
629                loadExpression(rhs, operandBounds, false);
630            }
631        } else {
632            // Can't reorder. Load and convert separately.
633            final TypeBounds safeConvertBounds = TypeBounds.UNBOUNDED.notNarrowerThan(narrowestOperandType);
634            loadExpression(lhs, safeConvertBounds, baseAlreadyOnStack);
635            final Type lhsLoadedType = method.peekType();
636            loadExpression(rhs, safeConvertBounds, false);
637            final Type convertedLhsType = operandBounds.within(method.peekType());
638            if (convertedLhsType != lhsLoadedType) {
639                // Do it conditionally, so that if conversion is a no-op we don't introduce a SWAP, SWAP.
640                method.swap().convert(convertedLhsType).swap();
641            }
642            method.convert(operandBounds.within(method.peekType()));
643        }
644        assert Type.generic(method.peekType()) == operandBounds.narrowest;
645        assert Type.generic(method.peekType(1)) == operandBounds.narrowest;
646
647        return method;
648    }
649
650    /**
651     * Similar to {@link #loadBinaryOperands(BinaryNode)} but used specifically for loading operands of
652     * relational and equality comparison operators where at least one argument is non-object. (When both
653     * arguments are objects, we use {@link ScriptRuntime#EQ(Object, Object)}, {@link ScriptRuntime#LT(Object, Object)}
654     * etc. methods instead. Additionally, {@code ScriptRuntime} methods are used for strict (in)equality comparison
655     * of a boolean to anything that isn't a boolean.) This method handles the special case where one argument
656     * is an object and another is a primitive. Naively, these could also be delegated to {@code ScriptRuntime} methods
657     * by boxing the primitive. However, in all such cases the comparison is performed on numeric values, so it is
658     * possible to strength-reduce the operation by taking the number value of the object argument instead and
659     * comparing that to the primitive value ("primitive" will always be int, long, double, or boolean, and booleans
660     * compare as ints in these cases, so they're essentially numbers too). This method will emit code for loading
661     * arguments for such strength-reduced comparison. When both arguments are primitives, it just delegates to
662     * {@link #loadBinaryOperands(BinaryNode)}.
663     *
664     * @param cmp the comparison operation for which the operands need to be loaded on stack.
665     * @return the current method emitter.
666     */
667    MethodEmitter loadComparisonOperands(final BinaryNode cmp) {
668        final Expression lhs = cmp.lhs();
669        final Expression rhs = cmp.rhs();
670        final Type lhsType = lhs.getType();
671        final Type rhsType = rhs.getType();
672
673        // Only used when not both are object, for that we have ScriptRuntime.LT etc.
674        assert !(lhsType.isObject() && rhsType.isObject());
675
676        if (lhsType.isObject() || rhsType.isObject()) {
677            // We can reorder CONVERT LEFT and LOAD RIGHT only if either the left is a primitive, or the right
678            // is a local. This is more strict than loadBinaryNode reorder criteria, as it can allow JS primitive
679            // types too (notably: String is a JS primitive, but not a JVM primitive). We disallow String otherwise
680            // we would prematurely convert it to number when comparing to an optimistic expression, e.g. in
681            // "Hello" === String("Hello") the RHS starts out as an optimistic-int function call. If we allowed
682            // reordering, we'd end up with ToNumber("Hello") === {I%}String("Hello") that is obviously incorrect.
683            final boolean canReorder = lhsType.isPrimitive() || rhs.isLocal();
684            // If reordering is allowed, and we're using a relational operator (that is, <, <=, >, >=) and not an
685            // (in)equality operator, then we encourage combining of LOAD and CONVERT into a single operation.
686            // This is because relational operators' semantics prescribes vanilla ToNumber() conversion, while
687            // (in)equality operators need the specialized JSType.toNumberFor[Strict]Equals. E.g. in the code snippet
688            // "i < obj.size" (where i is primitive and obj.size is statically an object), ".size" will thus be allowed
689            // to compile as:
690            //   invokedynamic GET_PROPERTY:size(Object;)D
691            // instead of the more costly:
692            //   invokedynamic GET_PROPERTY:size(Object;)Object
693            //   invokestatic JSType.toNumber(Object)D
694            // Note also that even if this is allowed, we're only using it on operands that are non-optimistic, as
695            // otherwise the logic for determining effective optimistic-ness would turn an optimistic double return
696            // into a freely coercible one, which would be wrong.
697            final boolean canCombineLoadAndConvert = canReorder && cmp.isRelational();
698
699            // LOAD LEFT
700            loadExpression(lhs, canCombineLoadAndConvert && !lhs.isOptimistic() ? TypeBounds.NUMBER : TypeBounds.UNBOUNDED);
701
702            final Type lhsLoadedType = method.peekType();
703            final TokenType tt = cmp.tokenType();
704            if (canReorder) {
705                // Can reorder CONVERT LEFT and LOAD RIGHT
706                emitObjectToNumberComparisonConversion(method, tt);
707                loadExpression(rhs, canCombineLoadAndConvert && !rhs.isOptimistic() ? TypeBounds.NUMBER : TypeBounds.UNBOUNDED);
708            } else {
709                // Can't reorder CONVERT LEFT and LOAD RIGHT
710                loadExpression(rhs, TypeBounds.UNBOUNDED);
711                if (lhsLoadedType != Type.NUMBER) {
712                    method.swap();
713                    emitObjectToNumberComparisonConversion(method, tt);
714                    method.swap();
715                }
716            }
717
718            // CONVERT RIGHT
719            emitObjectToNumberComparisonConversion(method, tt);
720            return method;
721        }
722        // For primitive operands, just don't do anything special.
723        return loadBinaryOperands(cmp);
724    }
725
726    private static void emitObjectToNumberComparisonConversion(final MethodEmitter method, final TokenType tt) {
727        switch(tt) {
728        case EQ:
729        case NE:
730            if (method.peekType().isObject()) {
731                TO_NUMBER_FOR_EQ.invoke(method);
732                return;
733            }
734            break;
735        case EQ_STRICT:
736        case NE_STRICT:
737            if (method.peekType().isObject()) {
738                TO_NUMBER_FOR_STRICT_EQ.invoke(method);
739                return;
740            }
741            break;
742        default:
743            break;
744        }
745        method.convert(Type.NUMBER);
746    }
747
748    private static Type undefinedToNumber(final Type type) {
749        return type == Type.UNDEFINED ? Type.NUMBER : type;
750    }
751
752    private static final class TypeBounds {
753        final Type narrowest;
754        final Type widest;
755
756        static final TypeBounds UNBOUNDED = new TypeBounds(Type.UNKNOWN, Type.OBJECT);
757        static final TypeBounds INT = exact(Type.INT);
758        static final TypeBounds NUMBER = exact(Type.NUMBER);
759        static final TypeBounds OBJECT = exact(Type.OBJECT);
760        static final TypeBounds BOOLEAN = exact(Type.BOOLEAN);
761
762        static TypeBounds exact(final Type type) {
763            return new TypeBounds(type, type);
764        }
765
766        TypeBounds(final Type narrowest, final Type widest) {
767            assert widest    != null && widest    != Type.UNDEFINED && widest != Type.UNKNOWN : widest;
768            assert narrowest != null && narrowest != Type.UNDEFINED : narrowest;
769            assert !narrowest.widerThan(widest) : narrowest + " wider than " + widest;
770            assert !widest.narrowerThan(narrowest);
771            this.narrowest = Type.generic(narrowest);
772            this.widest = Type.generic(widest);
773        }
774
775        TypeBounds notNarrowerThan(final Type type) {
776            return maybeNew(Type.narrowest(Type.widest(narrowest, type), widest), widest);
777        }
778
779        TypeBounds notWiderThan(final Type type) {
780            return maybeNew(Type.narrowest(narrowest, type), Type.narrowest(widest, type));
781        }
782
783        boolean canBeNarrowerThan(final Type type) {
784            return narrowest.narrowerThan(type);
785        }
786
787        TypeBounds maybeNew(final Type newNarrowest, final Type newWidest) {
788            if(newNarrowest == narrowest && newWidest == widest) {
789                return this;
790            }
791            return new TypeBounds(newNarrowest, newWidest);
792        }
793
794        TypeBounds booleanToInt() {
795            return maybeNew(CodeGenerator.booleanToInt(narrowest), CodeGenerator.booleanToInt(widest));
796        }
797
798        TypeBounds objectToNumber() {
799            return maybeNew(CodeGenerator.objectToNumber(narrowest), CodeGenerator.objectToNumber(widest));
800        }
801
802        Type within(final Type type) {
803            if(type.narrowerThan(narrowest)) {
804                return narrowest;
805            }
806            if(type.widerThan(widest)) {
807                return widest;
808            }
809            return type;
810        }
811
812        @Override
813        public String toString() {
814            return "[" + narrowest + ", " + widest + "]";
815        }
816    }
817
818    private static Type booleanToInt(final Type t) {
819        return t == Type.BOOLEAN ? Type.INT : t;
820    }
821
822    private static Type objectToNumber(final Type t) {
823        return t.isObject() ? Type.NUMBER : t;
824    }
825
826    MethodEmitter loadExpressionAsType(final Expression expr, final Type type) {
827        if(type == Type.BOOLEAN) {
828            return loadExpressionAsBoolean(expr);
829        } else if(type == Type.UNDEFINED) {
830            assert expr.getType() == Type.UNDEFINED;
831            return loadExpressionAsObject(expr);
832        }
833        // having no upper bound preserves semantics of optimistic operations in the expression (by not having them
834        // converted early) and then applies explicit conversion afterwards.
835        return loadExpression(expr, TypeBounds.UNBOUNDED.notNarrowerThan(type)).convert(type);
836    }
837
838    private MethodEmitter loadExpression(final Expression expr, final TypeBounds resultBounds) {
839        return loadExpression(expr, resultBounds, false);
840    }
841
842    /**
843     * Emits code for evaluating an expression and leaving its value on top of the stack, narrowing or widening it if
844     * necessary.
845     * @param expr the expression to load
846     * @param resultBounds the incoming type bounds. The value on the top of the stack is guaranteed to not be of narrower
847     * type than the narrowest bound, or wider type than the widest bound after it is loaded.
848     * @param baseAlreadyOnStack true if the base of an access or index node is already on the stack. Used to avoid
849     * double evaluation of bases in self-assignment expressions to access and index nodes. {@code Type.OBJECT} is used
850     * to indicate the widest possible type.
851     * @return the method emitter
852     */
853    private MethodEmitter loadExpression(final Expression expr, final TypeBounds resultBounds, final boolean baseAlreadyOnStack) {
854
855        /*
856         * The load may be of type IdentNode, e.g. "x", AccessNode, e.g. "x.y"
857         * or IndexNode e.g. "x[y]". Both AccessNodes and IndexNodes are
858         * BaseNodes and the logic for loading the base object is reused
859         */
860        final CodeGenerator codegen = this;
861
862        final boolean isCurrentDiscard = codegen.lc.isCurrentDiscard(expr);
863        expr.accept(new NodeOperatorVisitor<LexicalContext>(new LexicalContext()) {
864            @Override
865            public boolean enterIdentNode(final IdentNode identNode) {
866                loadIdent(identNode, resultBounds);
867                return false;
868            }
869
870            @Override
871            public boolean enterAccessNode(final AccessNode accessNode) {
872                new OptimisticOperation(accessNode, resultBounds) {
873                    @Override
874                    void loadStack() {
875                        if (!baseAlreadyOnStack) {
876                            loadExpressionAsObject(accessNode.getBase());
877                        }
878                        assert method.peekType().isObject();
879                    }
880                    @Override
881                    void consumeStack() {
882                        final int flags = getCallSiteFlags();
883                        dynamicGet(accessNode.getProperty(), flags, accessNode.isFunction(), accessNode.isIndex());
884                    }
885                }.emit(baseAlreadyOnStack ? 1 : 0);
886                return false;
887            }
888
889            @Override
890            public boolean enterIndexNode(final IndexNode indexNode) {
891                new OptimisticOperation(indexNode, resultBounds) {
892                    @Override
893                    void loadStack() {
894                        if (!baseAlreadyOnStack) {
895                            loadExpressionAsObject(indexNode.getBase());
896                            loadExpressionUnbounded(indexNode.getIndex());
897                        }
898                    }
899                    @Override
900                    void consumeStack() {
901                        final int flags = getCallSiteFlags();
902                        dynamicGetIndex(flags, indexNode.isFunction());
903                    }
904                }.emit(baseAlreadyOnStack ? 2 : 0);
905                return false;
906            }
907
908            @Override
909            public boolean enterFunctionNode(final FunctionNode functionNode) {
910                // function nodes will always leave a constructed function object on stack, no need to load the symbol
911                // separately as in enterDefault()
912                lc.pop(functionNode);
913                functionNode.accept(codegen);
914                // NOTE: functionNode.accept() will produce a different FunctionNode that we discard. This incidentally
915                // doesn't cause problems as we're never touching FunctionNode again after it's visited here - codegen
916                // is the last element in the compilation pipeline, the AST it produces is not used externally. So, we
917                // re-push the original functionNode.
918                lc.push(functionNode);
919                return false;
920            }
921
922            @Override
923            public boolean enterASSIGN(final BinaryNode binaryNode) {
924                checkAssignTarget(binaryNode.lhs());
925                loadASSIGN(binaryNode);
926                return false;
927            }
928
929            @Override
930            public boolean enterASSIGN_ADD(final BinaryNode binaryNode) {
931                checkAssignTarget(binaryNode.lhs());
932                loadASSIGN_ADD(binaryNode);
933                return false;
934            }
935
936            @Override
937            public boolean enterASSIGN_BIT_AND(final BinaryNode binaryNode) {
938                checkAssignTarget(binaryNode.lhs());
939                loadASSIGN_BIT_AND(binaryNode);
940                return false;
941            }
942
943            @Override
944            public boolean enterASSIGN_BIT_OR(final BinaryNode binaryNode) {
945                checkAssignTarget(binaryNode.lhs());
946                loadASSIGN_BIT_OR(binaryNode);
947                return false;
948            }
949
950            @Override
951            public boolean enterASSIGN_BIT_XOR(final BinaryNode binaryNode) {
952                checkAssignTarget(binaryNode.lhs());
953                loadASSIGN_BIT_XOR(binaryNode);
954                return false;
955            }
956
957            @Override
958            public boolean enterASSIGN_DIV(final BinaryNode binaryNode) {
959                checkAssignTarget(binaryNode.lhs());
960                loadASSIGN_DIV(binaryNode);
961                return false;
962            }
963
964            @Override
965            public boolean enterASSIGN_MOD(final BinaryNode binaryNode) {
966                checkAssignTarget(binaryNode.lhs());
967                loadASSIGN_MOD(binaryNode);
968                return false;
969            }
970
971            @Override
972            public boolean enterASSIGN_MUL(final BinaryNode binaryNode) {
973                checkAssignTarget(binaryNode.lhs());
974                loadASSIGN_MUL(binaryNode);
975                return false;
976            }
977
978            @Override
979            public boolean enterASSIGN_SAR(final BinaryNode binaryNode) {
980                checkAssignTarget(binaryNode.lhs());
981                loadASSIGN_SAR(binaryNode);
982                return false;
983            }
984
985            @Override
986            public boolean enterASSIGN_SHL(final BinaryNode binaryNode) {
987                checkAssignTarget(binaryNode.lhs());
988                loadASSIGN_SHL(binaryNode);
989                return false;
990            }
991
992            @Override
993            public boolean enterASSIGN_SHR(final BinaryNode binaryNode) {
994                checkAssignTarget(binaryNode.lhs());
995                loadASSIGN_SHR(binaryNode);
996                return false;
997            }
998
999            @Override
1000            public boolean enterASSIGN_SUB(final BinaryNode binaryNode) {
1001                checkAssignTarget(binaryNode.lhs());
1002                loadASSIGN_SUB(binaryNode);
1003                return false;
1004            }
1005
1006            @Override
1007            public boolean enterCallNode(final CallNode callNode) {
1008                return loadCallNode(callNode, resultBounds);
1009            }
1010
1011            @Override
1012            public boolean enterLiteralNode(final LiteralNode<?> literalNode) {
1013                loadLiteral(literalNode, resultBounds);
1014                return false;
1015            }
1016
1017            @Override
1018            public boolean enterTernaryNode(final TernaryNode ternaryNode) {
1019                loadTernaryNode(ternaryNode, resultBounds);
1020                return false;
1021            }
1022
1023            @Override
1024            public boolean enterADD(final BinaryNode binaryNode) {
1025                loadADD(binaryNode, resultBounds);
1026                return false;
1027            }
1028
1029            @Override
1030            public boolean enterSUB(final UnaryNode unaryNode) {
1031                loadSUB(unaryNode, resultBounds);
1032                return false;
1033            }
1034
1035            @Override
1036            public boolean enterSUB(final BinaryNode binaryNode) {
1037                loadSUB(binaryNode, resultBounds);
1038                return false;
1039            }
1040
1041            @Override
1042            public boolean enterMUL(final BinaryNode binaryNode) {
1043                loadMUL(binaryNode, resultBounds);
1044                return false;
1045            }
1046
1047            @Override
1048            public boolean enterDIV(final BinaryNode binaryNode) {
1049                loadDIV(binaryNode, resultBounds);
1050                return false;
1051            }
1052
1053            @Override
1054            public boolean enterMOD(final BinaryNode binaryNode) {
1055                loadMOD(binaryNode, resultBounds);
1056                return false;
1057            }
1058
1059            @Override
1060            public boolean enterSAR(final BinaryNode binaryNode) {
1061                loadSAR(binaryNode);
1062                return false;
1063            }
1064
1065            @Override
1066            public boolean enterSHL(final BinaryNode binaryNode) {
1067                loadSHL(binaryNode);
1068                return false;
1069            }
1070
1071            @Override
1072            public boolean enterSHR(final BinaryNode binaryNode) {
1073                loadSHR(binaryNode);
1074                return false;
1075            }
1076
1077            @Override
1078            public boolean enterCOMMALEFT(final BinaryNode binaryNode) {
1079                loadCOMMALEFT(binaryNode, resultBounds);
1080                return false;
1081            }
1082
1083            @Override
1084            public boolean enterCOMMARIGHT(final BinaryNode binaryNode) {
1085                loadCOMMARIGHT(binaryNode, resultBounds);
1086                return false;
1087            }
1088
1089            @Override
1090            public boolean enterAND(final BinaryNode binaryNode) {
1091                loadAND_OR(binaryNode, resultBounds, true);
1092                return false;
1093            }
1094
1095            @Override
1096            public boolean enterOR(final BinaryNode binaryNode) {
1097                loadAND_OR(binaryNode, resultBounds, false);
1098                return false;
1099            }
1100
1101            @Override
1102            public boolean enterNOT(final UnaryNode unaryNode) {
1103                loadNOT(unaryNode);
1104                return false;
1105            }
1106
1107            @Override
1108            public boolean enterADD(final UnaryNode unaryNode) {
1109                loadADD(unaryNode, resultBounds);
1110                return false;
1111            }
1112
1113            @Override
1114            public boolean enterBIT_NOT(final UnaryNode unaryNode) {
1115                loadBIT_NOT(unaryNode);
1116                return false;
1117            }
1118
1119            @Override
1120            public boolean enterBIT_AND(final BinaryNode binaryNode) {
1121                loadBIT_AND(binaryNode);
1122                return false;
1123            }
1124
1125            @Override
1126            public boolean enterBIT_OR(final BinaryNode binaryNode) {
1127                loadBIT_OR(binaryNode);
1128                return false;
1129            }
1130
1131            @Override
1132            public boolean enterBIT_XOR(final BinaryNode binaryNode) {
1133                loadBIT_XOR(binaryNode);
1134                return false;
1135            }
1136
1137            @Override
1138            public boolean enterVOID(final UnaryNode unaryNode) {
1139                loadVOID(unaryNode, resultBounds);
1140                return false;
1141            }
1142
1143            @Override
1144            public boolean enterEQ(final BinaryNode binaryNode) {
1145                loadCmp(binaryNode, Condition.EQ);
1146                return false;
1147            }
1148
1149            @Override
1150            public boolean enterEQ_STRICT(final BinaryNode binaryNode) {
1151                loadCmp(binaryNode, Condition.EQ);
1152                return false;
1153            }
1154
1155            @Override
1156            public boolean enterGE(final BinaryNode binaryNode) {
1157                loadCmp(binaryNode, Condition.GE);
1158                return false;
1159            }
1160
1161            @Override
1162            public boolean enterGT(final BinaryNode binaryNode) {
1163                loadCmp(binaryNode, Condition.GT);
1164                return false;
1165            }
1166
1167            @Override
1168            public boolean enterLE(final BinaryNode binaryNode) {
1169                loadCmp(binaryNode, Condition.LE);
1170                return false;
1171            }
1172
1173            @Override
1174            public boolean enterLT(final BinaryNode binaryNode) {
1175                loadCmp(binaryNode, Condition.LT);
1176                return false;
1177            }
1178
1179            @Override
1180            public boolean enterNE(final BinaryNode binaryNode) {
1181                loadCmp(binaryNode, Condition.NE);
1182                return false;
1183            }
1184
1185            @Override
1186            public boolean enterNE_STRICT(final BinaryNode binaryNode) {
1187                loadCmp(binaryNode, Condition.NE);
1188                return false;
1189            }
1190
1191            @Override
1192            public boolean enterObjectNode(final ObjectNode objectNode) {
1193                loadObjectNode(objectNode);
1194                return false;
1195            }
1196
1197            @Override
1198            public boolean enterRuntimeNode(final RuntimeNode runtimeNode) {
1199                loadRuntimeNode(runtimeNode);
1200                return false;
1201            }
1202
1203            @Override
1204            public boolean enterNEW(final UnaryNode unaryNode) {
1205                loadNEW(unaryNode);
1206                return false;
1207            }
1208
1209            @Override
1210            public boolean enterDECINC(final UnaryNode unaryNode) {
1211                checkAssignTarget(unaryNode.getExpression());
1212                loadDECINC(unaryNode);
1213                return false;
1214            }
1215
1216            @Override
1217            public boolean enterJoinPredecessorExpression(final JoinPredecessorExpression joinExpr) {
1218                loadMaybeDiscard(joinExpr, joinExpr.getExpression(), resultBounds);
1219                return false;
1220            }
1221
1222            @Override
1223            public boolean enterGetSplitState(final GetSplitState getSplitState) {
1224                method.loadScope();
1225                method.invoke(Scope.GET_SPLIT_STATE);
1226                return false;
1227            }
1228
1229            @Override
1230            public boolean enterDefault(final Node otherNode) {
1231                // Must have handled all expressions that can legally be encountered.
1232                throw new AssertionError(otherNode.getClass().getName());
1233            }
1234        });
1235        if(!isCurrentDiscard) {
1236            coerceStackTop(resultBounds);
1237        }
1238        return method;
1239    }
1240
1241    private MethodEmitter coerceStackTop(final TypeBounds typeBounds) {
1242        return method.convert(typeBounds.within(method.peekType()));
1243    }
1244
1245    /**
1246     * Closes any still open entries for this block's local variables in the bytecode local variable table.
1247     *
1248     * @param block block containing symbols.
1249     */
1250    private void closeBlockVariables(final Block block) {
1251        for (final Symbol symbol : block.getSymbols()) {
1252            if (symbol.isBytecodeLocal()) {
1253                method.closeLocalVariable(symbol, block.getBreakLabel());
1254            }
1255        }
1256    }
1257
1258    @Override
1259    public boolean enterBlock(final Block block) {
1260        final Label entryLabel = block.getEntryLabel();
1261        if (entryLabel.isBreakTarget()) {
1262            // Entry label is a break target only for an inlined finally block.
1263            assert !method.isReachable();
1264            method.breakLabel(entryLabel, lc.getUsedSlotCount());
1265        } else {
1266            method.label(entryLabel);
1267        }
1268        if(!method.isReachable()) {
1269            return false;
1270        }
1271        if(lc.isFunctionBody() && emittedMethods.contains(lc.getCurrentFunction().getName())) {
1272            return false;
1273        }
1274        initLocals(block);
1275
1276        assert lc.getUsedSlotCount() == method.getFirstTemp();
1277        return true;
1278    }
1279
1280    boolean useOptimisticTypes() {
1281        return !lc.inSplitNode() && compiler.useOptimisticTypes();
1282    }
1283
1284    @Override
1285    public Node leaveBlock(final Block block) {
1286        popBlockScope(block);
1287        method.beforeJoinPoint(block);
1288
1289        closeBlockVariables(block);
1290        lc.releaseSlots();
1291        assert !method.isReachable() || (lc.isFunctionBody() ? 0 : lc.getUsedSlotCount()) == method.getFirstTemp() :
1292            "reachable="+method.isReachable() +
1293            " isFunctionBody=" + lc.isFunctionBody() +
1294            " usedSlotCount=" + lc.getUsedSlotCount() +
1295            " firstTemp=" + method.getFirstTemp();
1296
1297        return block;
1298    }
1299
1300    private void popBlockScope(final Block block) {
1301        final Label breakLabel = block.getBreakLabel();
1302
1303        if (block.providesScopeCreator()) {
1304            scopeObjectCreators.pop();
1305        }
1306        if(!block.needsScope() || lc.isFunctionBody()) {
1307            emitBlockBreakLabel(breakLabel);
1308            return;
1309        }
1310
1311        final Label beginTryLabel = scopeEntryLabels.pop();
1312        final Label recoveryLabel = new Label("block_popscope_catch");
1313        emitBlockBreakLabel(breakLabel);
1314        final boolean bodyCanThrow = breakLabel.isAfter(beginTryLabel);
1315        if(bodyCanThrow) {
1316            method._try(beginTryLabel, breakLabel, recoveryLabel);
1317        }
1318
1319        Label afterCatchLabel = null;
1320
1321        if(method.isReachable()) {
1322            popScope();
1323            if(bodyCanThrow) {
1324                afterCatchLabel = new Label("block_after_catch");
1325                method._goto(afterCatchLabel);
1326            }
1327        }
1328
1329        if(bodyCanThrow) {
1330            assert !method.isReachable();
1331            method._catch(recoveryLabel);
1332            popScopeException();
1333            method.athrow();
1334        }
1335        if(afterCatchLabel != null) {
1336            method.label(afterCatchLabel);
1337        }
1338    }
1339
1340    private void emitBlockBreakLabel(final Label breakLabel) {
1341        // TODO: this is totally backwards. Block should not be breakable, LabelNode should be breakable.
1342        final LabelNode labelNode = lc.getCurrentBlockLabelNode();
1343        if(labelNode != null) {
1344            // Only have conversions if we're reachable
1345            assert labelNode.getLocalVariableConversion() == null || method.isReachable();
1346            method.beforeJoinPoint(labelNode);
1347            method.breakLabel(breakLabel, labeledBlockBreakLiveLocals.pop());
1348        } else {
1349            method.label(breakLabel);
1350        }
1351    }
1352
1353    private void popScope() {
1354        popScopes(1);
1355    }
1356
1357    /**
1358     * Pop scope as part of an exception handler. Similar to {@code popScope()} but also takes care of adjusting the
1359     * number of scopes that needs to be popped in case a rest-of continuation handler encounters an exception while
1360     * performing a ToPrimitive conversion.
1361     */
1362    private void popScopeException() {
1363        popScope();
1364        final ContinuationInfo ci = getContinuationInfo();
1365        if(ci != null) {
1366            final Label catchLabel = ci.catchLabel;
1367            if(catchLabel != METHOD_BOUNDARY && catchLabel == catchLabels.peek()) {
1368                ++ci.exceptionScopePops;
1369            }
1370        }
1371    }
1372
1373    private void popScopesUntil(final LexicalContextNode until) {
1374        popScopes(lc.getScopeNestingLevelTo(until));
1375    }
1376
1377    private void popScopes(final int count) {
1378        if(count == 0) {
1379            return;
1380        }
1381        assert count > 0; // together with count == 0 check, asserts nonnegative count
1382        if (!method.hasScope()) {
1383            // We can sometimes invoke this method even if the method has no slot for the scope object. Typical example:
1384            // for(;;) { with({}) { break; } }. WithNode normally creates a scope, but if it uses no identifiers and
1385            // nothing else forces creation of a scope in the method, we just won't have the :scope local variable.
1386            return;
1387        }
1388        method.loadCompilerConstant(SCOPE);
1389        if (count > 1) {
1390            method.load(count);
1391            method.invoke(ScriptObject.GET_PROTO_DEPTH);
1392        } else {
1393            method.invoke(ScriptObject.GET_PROTO);
1394        }
1395        method.storeCompilerConstant(SCOPE);
1396    }
1397
1398    @Override
1399    public boolean enterBreakNode(final BreakNode breakNode) {
1400        return enterJumpStatement(breakNode);
1401    }
1402
1403    @Override
1404    public boolean enterJumpToInlinedFinally(final JumpToInlinedFinally jumpToInlinedFinally) {
1405        return enterJumpStatement(jumpToInlinedFinally);
1406    }
1407
1408    private boolean enterJumpStatement(final JumpStatement jump) {
1409        if(!method.isReachable()) {
1410            return false;
1411        }
1412        enterStatement(jump);
1413
1414        method.beforeJoinPoint(jump);
1415        popScopesUntil(jump.getPopScopeLimit(lc));
1416        final Label targetLabel = jump.getTargetLabel(lc);
1417        targetLabel.markAsBreakTarget();
1418        method._goto(targetLabel);
1419
1420        return false;
1421    }
1422
1423    private int loadArgs(final List<Expression> args) {
1424        final int argCount = args.size();
1425        // arg have already been converted to objects here.
1426        if (argCount > LinkerCallSite.ARGLIMIT) {
1427            loadArgsArray(args);
1428            return 1;
1429        }
1430
1431        for (final Expression arg : args) {
1432            assert arg != null;
1433            loadExpressionUnbounded(arg);
1434        }
1435        return argCount;
1436    }
1437
1438    private boolean loadCallNode(final CallNode callNode, final TypeBounds resultBounds) {
1439        lineNumber(callNode.getLineNumber());
1440
1441        final List<Expression> args = callNode.getArgs();
1442        final Expression function = callNode.getFunction();
1443        final Block currentBlock = lc.getCurrentBlock();
1444        final CodeGeneratorLexicalContext codegenLexicalContext = lc;
1445
1446        function.accept(new SimpleNodeVisitor() {
1447            private MethodEmitter sharedScopeCall(final IdentNode identNode, final int flags) {
1448                final Symbol symbol = identNode.getSymbol();
1449                final boolean isFastScope = isFastScope(symbol);
1450                new OptimisticOperation(callNode, resultBounds) {
1451                    @Override
1452                    void loadStack() {
1453                        method.loadCompilerConstant(SCOPE);
1454                        if (isFastScope) {
1455                            method.load(getScopeProtoDepth(currentBlock, symbol));
1456                        } else {
1457                            method.load(-1); // Bypass fast-scope code in shared callsite
1458                        }
1459                        loadArgs(args);
1460                    }
1461                    @Override
1462                    void consumeStack() {
1463                        final Type[] paramTypes = method.getTypesFromStack(args.size());
1464                        // We have trouble finding e.g. in Type.typeFor(asm.Type) because it can't see the Context class
1465                        // loader, so we need to weaken reference signatures to Object.
1466                        for(int i = 0; i < paramTypes.length; ++i) {
1467                            paramTypes[i] = Type.generic(paramTypes[i]);
1468                        }
1469                        // As shared scope calls are only used in non-optimistic compilation, we switch from using
1470                        // TypeBounds to just a single definitive type, resultBounds.widest.
1471                        final SharedScopeCall scopeCall = codegenLexicalContext.getScopeCall(unit, symbol,
1472                                identNode.getType(), resultBounds.widest, paramTypes, flags);
1473                        scopeCall.generateInvoke(method);
1474                    }
1475                }.emit();
1476                return method;
1477            }
1478
1479            private void scopeCall(final IdentNode ident, final int flags) {
1480                new OptimisticOperation(callNode, resultBounds) {
1481                    int argsCount;
1482                    @Override
1483                    void loadStack() {
1484                        loadExpressionAsObject(ident); // foo() makes no sense if foo == 3
1485                        // ScriptFunction will see CALLSITE_SCOPE and will bind scope accordingly.
1486                        method.loadUndefined(Type.OBJECT); //the 'this'
1487                        argsCount = loadArgs(args);
1488                    }
1489                    @Override
1490                    void consumeStack() {
1491                        dynamicCall(2 + argsCount, flags, ident.getName());
1492                    }
1493                }.emit();
1494            }
1495
1496            private void evalCall(final IdentNode ident, final int flags) {
1497                final Label invoke_direct_eval  = new Label("invoke_direct_eval");
1498                final Label is_not_eval  = new Label("is_not_eval");
1499                final Label eval_done = new Label("eval_done");
1500
1501                new OptimisticOperation(callNode, resultBounds) {
1502                    int argsCount;
1503                    @Override
1504                    void loadStack() {
1505                        /*
1506                         * We want to load 'eval' to check if it is indeed global builtin eval.
1507                         * If this eval call is inside a 'with' statement, GET_METHOD_PROPERTY
1508                         * would be generated if ident is a "isFunction". But, that would result in a
1509                         * bound function from WithObject. We don't want that as bound function as that
1510                         * won't be detected as builtin eval. So, we make ident as "not a function" which
1511                         * results in GET_PROPERTY being generated and so WithObject
1512                         * would return unbounded eval function.
1513                         *
1514                         * Example:
1515                         *
1516                         *  var global = this;
1517                         *  function func() {
1518                         *      with({ eval: global.eval) { eval("var x = 10;") }
1519                         *  }
1520                         */
1521                        loadExpressionAsObject(ident.setIsNotFunction()); // Type.OBJECT as foo() makes no sense if foo == 3
1522                        globalIsEval();
1523                        method.ifeq(is_not_eval);
1524
1525                        // Load up self (scope).
1526                        method.loadCompilerConstant(SCOPE);
1527                        final List<Expression> evalArgs = callNode.getEvalArgs().getArgs();
1528                        // load evaluated code
1529                        loadExpressionAsObject(evalArgs.get(0));
1530                        // load second and subsequent args for side-effect
1531                        final int numArgs = evalArgs.size();
1532                        for (int i = 1; i < numArgs; i++) {
1533                            loadAndDiscard(evalArgs.get(i));
1534                        }
1535                        method._goto(invoke_direct_eval);
1536
1537                        method.label(is_not_eval);
1538                        // load this time but with GET_METHOD_PROPERTY
1539                        loadExpressionAsObject(ident); // Type.OBJECT as foo() makes no sense if foo == 3
1540                        // This is some scope 'eval' or global eval replaced by user
1541                        // but not the built-in ECMAScript 'eval' function call
1542                        method.loadNull();
1543                        argsCount = loadArgs(callNode.getArgs());
1544                    }
1545
1546                    @Override
1547                    void consumeStack() {
1548                        // Ordinary call
1549                        dynamicCall(2 + argsCount, flags, "eval");
1550                        method._goto(eval_done);
1551
1552                        method.label(invoke_direct_eval);
1553                        // Special/extra 'eval' arguments. These can be loaded late (in consumeStack) as we know none of
1554                        // them can ever be optimistic.
1555                        method.loadCompilerConstant(THIS);
1556                        method.load(callNode.getEvalArgs().getLocation());
1557                        method.load(CodeGenerator.this.lc.getCurrentFunction().isStrict());
1558                        // direct call to Global.directEval
1559                        globalDirectEval();
1560                        convertOptimisticReturnValue();
1561                        coerceStackTop(resultBounds);
1562                    }
1563                }.emit();
1564
1565                method.label(eval_done);
1566            }
1567
1568            @Override
1569            public boolean enterIdentNode(final IdentNode node) {
1570                final Symbol symbol = node.getSymbol();
1571
1572                if (symbol.isScope()) {
1573                    final int flags = getScopeCallSiteFlags(symbol);
1574                    final int useCount = symbol.getUseCount();
1575
1576                    // Threshold for generating shared scope callsite is lower for fast scope symbols because we know
1577                    // we can dial in the correct scope. However, we also need to enable it for non-fast scopes to
1578                    // support huge scripts like mandreel.js.
1579                    if (callNode.isEval()) {
1580                        evalCall(node, flags);
1581                    } else if (useCount <= SharedScopeCall.FAST_SCOPE_CALL_THRESHOLD
1582                            || !isFastScope(symbol) && useCount <= SharedScopeCall.SLOW_SCOPE_CALL_THRESHOLD
1583                            || CodeGenerator.this.lc.inDynamicScope()
1584                            || callNode.isOptimistic()) {
1585                        scopeCall(node, flags);
1586                    } else {
1587                        sharedScopeCall(node, flags);
1588                    }
1589                    assert method.peekType().equals(resultBounds.within(callNode.getType())) : method.peekType() + " != " + resultBounds + "(" + callNode.getType() + ")";
1590                } else {
1591                    enterDefault(node);
1592                }
1593
1594                return false;
1595            }
1596
1597            @Override
1598            public boolean enterAccessNode(final AccessNode node) {
1599                //check if this is an apply to call node. only real applies, that haven't been
1600                //shadowed from their way to the global scope counts
1601
1602                //call nodes have program points.
1603
1604                final int flags = getCallSiteFlags() | (callNode.isApplyToCall() ? CALLSITE_APPLY_TO_CALL : 0);
1605
1606                new OptimisticOperation(callNode, resultBounds) {
1607                    int argCount;
1608                    @Override
1609                    void loadStack() {
1610                        loadExpressionAsObject(node.getBase());
1611                        method.dup();
1612                        // NOTE: not using a nested OptimisticOperation on this dynamicGet, as we expect to get back
1613                        // a callable object. Nobody in their right mind would optimistically type this call site.
1614                        assert !node.isOptimistic();
1615                        method.dynamicGet(node.getType(), node.getProperty(), flags, true, node.isIndex());
1616                        method.swap();
1617                        argCount = loadArgs(args);
1618                    }
1619                    @Override
1620                    void consumeStack() {
1621                        dynamicCall(2 + argCount, flags, node.toString(false));
1622                    }
1623                }.emit();
1624
1625                return false;
1626            }
1627
1628            @Override
1629            public boolean enterFunctionNode(final FunctionNode origCallee) {
1630                new OptimisticOperation(callNode, resultBounds) {
1631                    FunctionNode callee;
1632                    int argsCount;
1633                    @Override
1634                    void loadStack() {
1635                        callee = (FunctionNode)origCallee.accept(CodeGenerator.this);
1636                        if (callee.isStrict()) { // "this" is undefined
1637                            method.loadUndefined(Type.OBJECT);
1638                        } else { // get global from scope (which is the self)
1639                            globalInstance();
1640                        }
1641                        argsCount = loadArgs(args);
1642                    }
1643
1644                    @Override
1645                    void consumeStack() {
1646                        dynamicCall(2 + argsCount, getCallSiteFlags(), null);
1647                    }
1648                }.emit();
1649                return false;
1650            }
1651
1652            @Override
1653            public boolean enterIndexNode(final IndexNode node) {
1654                new OptimisticOperation(callNode, resultBounds) {
1655                    int argsCount;
1656                    @Override
1657                    void loadStack() {
1658                        loadExpressionAsObject(node.getBase());
1659                        method.dup();
1660                        final Type indexType = node.getIndex().getType();
1661                        if (indexType.isObject() || indexType.isBoolean()) {
1662                            loadExpressionAsObject(node.getIndex()); //TODO boolean
1663                        } else {
1664                            loadExpressionUnbounded(node.getIndex());
1665                        }
1666                        // NOTE: not using a nested OptimisticOperation on this dynamicGetIndex, as we expect to get
1667                        // back a callable object. Nobody in their right mind would optimistically type this call site.
1668                        assert !node.isOptimistic();
1669                        method.dynamicGetIndex(node.getType(), getCallSiteFlags(), true);
1670                        method.swap();
1671                        argsCount = loadArgs(args);
1672                    }
1673                    @Override
1674                    void consumeStack() {
1675                        dynamicCall(2 + argsCount, getCallSiteFlags(), node.toString(false));
1676                    }
1677                }.emit();
1678                return false;
1679            }
1680
1681            @Override
1682            protected boolean enterDefault(final Node node) {
1683                new OptimisticOperation(callNode, resultBounds) {
1684                    int argsCount;
1685                    @Override
1686                    void loadStack() {
1687                        // Load up function.
1688                        loadExpressionAsObject(function); //TODO, e.g. booleans can be used as functions
1689                        method.loadUndefined(Type.OBJECT); // ScriptFunction will figure out the correct this when it sees CALLSITE_SCOPE
1690                        argsCount = loadArgs(args);
1691                        }
1692                        @Override
1693                        void consumeStack() {
1694                            final int flags = getCallSiteFlags() | CALLSITE_SCOPE;
1695                            dynamicCall(2 + argsCount, flags, node.toString(false));
1696                        }
1697                }.emit();
1698                return false;
1699            }
1700        });
1701
1702        return false;
1703    }
1704
1705    /**
1706     * Returns the flags with optimistic flag and program point removed.
1707     * @param flags the flags that need optimism stripped from them.
1708     * @return flags without optimism
1709     */
1710    static int nonOptimisticFlags(final int flags) {
1711        return flags & ~(CALLSITE_OPTIMISTIC | -1 << CALLSITE_PROGRAM_POINT_SHIFT);
1712    }
1713
1714    @Override
1715    public boolean enterContinueNode(final ContinueNode continueNode) {
1716        return enterJumpStatement(continueNode);
1717    }
1718
1719    @Override
1720    public boolean enterEmptyNode(final EmptyNode emptyNode) {
1721        // Don't even record the line number, it's irrelevant as there's no code.
1722        return false;
1723    }
1724
1725    @Override
1726    public boolean enterExpressionStatement(final ExpressionStatement expressionStatement) {
1727        if(!method.isReachable()) {
1728            return false;
1729        }
1730        enterStatement(expressionStatement);
1731
1732        loadAndDiscard(expressionStatement.getExpression());
1733        assert method.getStackSize() == 0 : "stack not empty in " + expressionStatement;
1734
1735        return false;
1736    }
1737
1738    @Override
1739    public boolean enterBlockStatement(final BlockStatement blockStatement) {
1740        if(!method.isReachable()) {
1741            return false;
1742        }
1743        enterStatement(blockStatement);
1744
1745        blockStatement.getBlock().accept(this);
1746
1747        return false;
1748    }
1749
1750    @Override
1751    public boolean enterForNode(final ForNode forNode) {
1752        if(!method.isReachable()) {
1753            return false;
1754        }
1755        enterStatement(forNode);
1756        if (forNode.isForInOrOf()) {
1757            enterForIn(forNode);
1758        } else {
1759            final Expression init = forNode.getInit();
1760            if (init != null) {
1761                loadAndDiscard(init);
1762            }
1763            enterForOrWhile(forNode, forNode.getModify());
1764        }
1765
1766        return false;
1767    }
1768
1769    private void enterForIn(final ForNode forNode) {
1770        loadExpression(forNode.getModify(), TypeBounds.OBJECT);
1771        if (forNode.isForEach()) {
1772            method.invoke(ScriptRuntime.TO_VALUE_ITERATOR);
1773        } else if (forNode.isForIn()) {
1774            method.invoke(ScriptRuntime.TO_PROPERTY_ITERATOR);
1775        } else if (forNode.isForOf()) {
1776            method.invoke(ScriptRuntime.TO_ES6_ITERATOR);
1777        } else {
1778            throw new IllegalArgumentException("Unexpected for node");
1779        }
1780        final Symbol iterSymbol = forNode.getIterator();
1781        final int iterSlot = iterSymbol.getSlot(Type.OBJECT);
1782        method.store(iterSymbol, ITERATOR_TYPE);
1783
1784        method.beforeJoinPoint(forNode);
1785
1786        final Label continueLabel = forNode.getContinueLabel();
1787        final Label breakLabel    = forNode.getBreakLabel();
1788
1789        method.label(continueLabel);
1790        method.load(ITERATOR_TYPE, iterSlot);
1791        method.invoke(interfaceCallNoLookup(ITERATOR_CLASS, "hasNext", boolean.class));
1792        final JoinPredecessorExpression test = forNode.getTest();
1793        final Block body = forNode.getBody();
1794        if(LocalVariableConversion.hasLiveConversion(test)) {
1795            final Label afterConversion = new Label("for_in_after_test_conv");
1796            method.ifne(afterConversion);
1797            method.beforeJoinPoint(test);
1798            method._goto(breakLabel);
1799            method.label(afterConversion);
1800        } else {
1801            method.ifeq(breakLabel);
1802        }
1803
1804        new Store<Expression>(forNode.getInit()) {
1805            @Override
1806            protected void storeNonDiscard() {
1807                // This expression is neither part of a discard, nor needs to be left on the stack after it was
1808                // stored, so we override storeNonDiscard to be a no-op.
1809            }
1810
1811            @Override
1812            protected void evaluate() {
1813                new OptimisticOperation((Optimistic)forNode.getInit(), TypeBounds.UNBOUNDED) {
1814                    @Override
1815                    void loadStack() {
1816                        method.load(ITERATOR_TYPE, iterSlot);
1817                    }
1818
1819                    @Override
1820                    void consumeStack() {
1821                        method.invoke(interfaceCallNoLookup(ITERATOR_CLASS, "next", Object.class));
1822                        convertOptimisticReturnValue();
1823                    }
1824                }.emit();
1825            }
1826        }.store();
1827        body.accept(this);
1828
1829        if (forNode.needsScopeCreator() && lc.getCurrentBlock().providesScopeCreator()) {
1830            // for-in loops with lexical declaration need a new scope for each iteration.
1831            final FieldObjectCreator<?> creator = scopeObjectCreators.peek();
1832            assert creator != null;
1833            creator.createForInIterationScope(method);
1834            method.storeCompilerConstant(SCOPE);
1835        }
1836
1837        if(method.isReachable()) {
1838            method._goto(continueLabel);
1839        }
1840        method.label(breakLabel);
1841    }
1842
1843    /**
1844     * Initialize the slots in a frame to undefined.
1845     *
1846     * @param block block with local vars.
1847     */
1848    private void initLocals(final Block block) {
1849        lc.onEnterBlock(block);
1850
1851        final boolean isFunctionBody = lc.isFunctionBody();
1852        final FunctionNode function = lc.getCurrentFunction();
1853        if (isFunctionBody) {
1854            initializeMethodParameters(function);
1855            if(!function.isVarArg()) {
1856                expandParameterSlots(function);
1857            }
1858            if (method.hasScope()) {
1859                if (function.needsParentScope()) {
1860                    method.loadCompilerConstant(CALLEE);
1861                    method.invoke(ScriptFunction.GET_SCOPE);
1862                } else {
1863                    assert function.hasScopeBlock();
1864                    method.loadNull();
1865                }
1866                method.storeCompilerConstant(SCOPE);
1867            }
1868            if (function.needsArguments()) {
1869                initArguments(function);
1870            }
1871        }
1872
1873        /*
1874         * Determine if block needs scope, if not, just do initSymbols for this block.
1875         */
1876        if (block.needsScope()) {
1877            /*
1878             * Determine if function is varargs and consequently variables have to
1879             * be in the scope.
1880             */
1881            final boolean varsInScope = function.allVarsInScope();
1882
1883            // TODO for LET we can do better: if *block* does not contain any eval/with, we don't need its vars in scope.
1884
1885            final boolean hasArguments = function.needsArguments();
1886            final List<MapTuple<Symbol>> tuples = new ArrayList<>();
1887            final Iterator<IdentNode> paramIter = function.getParameters().iterator();
1888            for (final Symbol symbol : block.getSymbols()) {
1889                if (symbol.isInternal() || symbol.isThis()) {
1890                    continue;
1891                }
1892
1893                if (symbol.isVar()) {
1894                    assert !varsInScope || symbol.isScope();
1895                    if (varsInScope || symbol.isScope()) {
1896                        assert symbol.isScope()   : "scope for " + symbol + " should have been set in Lower already " + function.getName();
1897                        assert !symbol.hasSlot()  : "slot for " + symbol + " should have been removed in Lower already" + function.getName();
1898
1899                        //this tuple will not be put fielded, as it has no value, just a symbol
1900                        tuples.add(new MapTuple<Symbol>(symbol.getName(), symbol, null));
1901                    } else {
1902                        assert symbol.hasSlot() || symbol.slotCount() == 0 : symbol + " should have a slot only, no scope";
1903                    }
1904                } else if (symbol.isParam() && (varsInScope || hasArguments || symbol.isScope())) {
1905                    assert symbol.isScope()   : "scope for " + symbol + " should have been set in AssignSymbols already " + function.getName() + " varsInScope="+varsInScope+" hasArguments="+hasArguments+" symbol.isScope()=" + symbol.isScope();
1906                    assert !(hasArguments && symbol.hasSlot())  : "slot for " + symbol + " should have been removed in Lower already " + function.getName();
1907
1908                    final Type   paramType;
1909                    final Symbol paramSymbol;
1910
1911                    if (hasArguments) {
1912                        assert !symbol.hasSlot()  : "slot for " + symbol + " should have been removed in Lower already ";
1913                        paramSymbol = null;
1914                        paramType   = null;
1915                    } else {
1916                        paramSymbol = symbol;
1917                        // NOTE: We're relying on the fact here that Block.symbols is a LinkedHashMap, hence it will
1918                        // return symbols in the order they were defined, and parameters are defined in the same order
1919                        // they appear in the function. That's why we can have a single pass over the parameter list
1920                        // with an iterator, always just scanning forward for the next parameter that matches the symbol
1921                        // name.
1922                        for(;;) {
1923                            final IdentNode nextParam = paramIter.next();
1924                            if(nextParam.getName().equals(symbol.getName())) {
1925                                paramType = nextParam.getType();
1926                                break;
1927                            }
1928                        }
1929                    }
1930
1931                    tuples.add(new MapTuple<Symbol>(symbol.getName(), symbol, paramType, paramSymbol) {
1932                        //this symbol will be put fielded, we can't initialize it as undefined with a known type
1933                        @Override
1934                        public Class<?> getValueType() {
1935                            if (!useDualFields() ||  value == null || paramType == null || paramType.isBoolean()) {
1936                                return Object.class;
1937                            }
1938                            return paramType.getTypeClass();
1939                        }
1940                    });
1941                }
1942            }
1943
1944            /*
1945             * Create a new object based on the symbols and values, generate
1946             * bootstrap code for object
1947             */
1948            final FieldObjectCreator<Symbol> creator = new FieldObjectCreator<Symbol>(this, tuples, true, hasArguments) {
1949                @Override
1950                protected void loadValue(final Symbol value, final Type type) {
1951                    method.load(value, type);
1952                }
1953            };
1954            creator.makeObject(method);
1955            if (block.providesScopeCreator()) {
1956                scopeObjectCreators.push(creator);
1957            }
1958            // program function: merge scope into global
1959            if (isFunctionBody && function.isProgram()) {
1960                method.invoke(ScriptRuntime.MERGE_SCOPE);
1961            }
1962
1963            method.storeCompilerConstant(SCOPE);
1964            if(!isFunctionBody) {
1965                // Function body doesn't need a try/catch to restore scope, as it'd be a dead store anyway. Allowing it
1966                // actually causes issues with UnwarrantedOptimismException handlers as ASM will sort this handler to
1967                // the top of the exception handler table, so it'll be triggered instead of the UOE handlers.
1968                final Label scopeEntryLabel = new Label("scope_entry");
1969                scopeEntryLabels.push(scopeEntryLabel);
1970                method.label(scopeEntryLabel);
1971            }
1972        } else if (isFunctionBody && function.isVarArg()) {
1973            // Since we don't have a scope, parameters didn't get assigned array indices by the FieldObjectCreator, so
1974            // we need to assign them separately here.
1975            int nextParam = 0;
1976            for (final IdentNode param : function.getParameters()) {
1977                param.getSymbol().setFieldIndex(nextParam++);
1978            }
1979        }
1980
1981        // Debugging: print symbols? @see --print-symbols flag
1982        printSymbols(block, function, (isFunctionBody ? "Function " : "Block in ") + (function.getIdent() == null ? "<anonymous>" : function.getIdent().getName()));
1983    }
1984
1985    /**
1986     * Incoming method parameters are always declared on method entry; declare them in the local variable table.
1987     * @param function function for which code is being generated.
1988     */
1989    private void initializeMethodParameters(final FunctionNode function) {
1990        final Label functionStart = new Label("fn_start");
1991        method.label(functionStart);
1992        int nextSlot = 0;
1993        if(function.needsCallee()) {
1994            initializeInternalFunctionParameter(CALLEE, function, functionStart, nextSlot++);
1995        }
1996        initializeInternalFunctionParameter(THIS, function, functionStart, nextSlot++);
1997        if(function.isVarArg()) {
1998            initializeInternalFunctionParameter(VARARGS, function, functionStart, nextSlot++);
1999        } else {
2000            for(final IdentNode param: function.getParameters()) {
2001                final Symbol symbol = param.getSymbol();
2002                if(symbol.isBytecodeLocal()) {
2003                    method.initializeMethodParameter(symbol, param.getType(), functionStart);
2004                }
2005            }
2006        }
2007    }
2008
2009    private void initializeInternalFunctionParameter(final CompilerConstants cc, final FunctionNode fn, final Label functionStart, final int slot) {
2010        final Symbol symbol = initializeInternalFunctionOrSplitParameter(cc, fn, functionStart, slot);
2011        // Internal function params (:callee, this, and :varargs) are never expanded to multiple slots
2012        assert symbol.getFirstSlot() == slot;
2013    }
2014
2015    private Symbol initializeInternalFunctionOrSplitParameter(final CompilerConstants cc, final FunctionNode fn, final Label functionStart, final int slot) {
2016        final Symbol symbol = fn.getBody().getExistingSymbol(cc.symbolName());
2017        final Type type = Type.typeFor(cc.type());
2018        method.initializeMethodParameter(symbol, type, functionStart);
2019        method.onLocalStore(type, slot);
2020        return symbol;
2021    }
2022
2023    /**
2024     * Parameters come into the method packed into local variable slots next to each other. Nashorn on the other hand
2025     * can use 1-6 slots for a local variable depending on all the types it needs to store. When this method is invoked,
2026     * the symbols are already allocated such wider slots, but the values are still in tightly packed incoming slots,
2027     * and we need to spread them into their new locations.
2028     * @param function the function for which parameter-spreading code needs to be emitted
2029     */
2030    private void expandParameterSlots(final FunctionNode function) {
2031        final List<IdentNode> parameters = function.getParameters();
2032        // Calculate the total number of incoming parameter slots
2033        int currentIncomingSlot = function.needsCallee() ? 2 : 1;
2034        for(final IdentNode parameter: parameters) {
2035            currentIncomingSlot += parameter.getType().getSlots();
2036        }
2037        // Starting from last parameter going backwards, move the parameter values into their new slots.
2038        for(int i = parameters.size(); i-- > 0;) {
2039            final IdentNode parameter = parameters.get(i);
2040            final Type parameterType = parameter.getType();
2041            final int typeWidth = parameterType.getSlots();
2042            currentIncomingSlot -= typeWidth;
2043            final Symbol symbol = parameter.getSymbol();
2044            final int slotCount = symbol.slotCount();
2045            assert slotCount > 0;
2046            // Scoped parameters must not hold more than one value
2047            assert symbol.isBytecodeLocal() || slotCount == typeWidth;
2048
2049            // Mark it as having its value stored into it by the method invocation.
2050            method.onLocalStore(parameterType, currentIncomingSlot);
2051            if(currentIncomingSlot != symbol.getSlot(parameterType)) {
2052                method.load(parameterType, currentIncomingSlot);
2053                method.store(symbol, parameterType);
2054            }
2055        }
2056    }
2057
2058    private void initArguments(final FunctionNode function) {
2059        method.loadCompilerConstant(VARARGS);
2060        if (function.needsCallee()) {
2061            method.loadCompilerConstant(CALLEE);
2062        } else {
2063            // If function is strict mode, "arguments.callee" is not populated, so we don't necessarily need the
2064            // caller.
2065            assert function.isStrict();
2066            method.loadNull();
2067        }
2068        method.load(function.getParameters().size());
2069        globalAllocateArguments();
2070        method.storeCompilerConstant(ARGUMENTS);
2071    }
2072
2073    private boolean skipFunction(final FunctionNode functionNode) {
2074        final ScriptEnvironment env = compiler.getScriptEnvironment();
2075        final boolean lazy = env._lazy_compilation;
2076        final boolean onDemand = compiler.isOnDemandCompilation();
2077
2078        // If this is on-demand or lazy compilation, don't compile a nested (not topmost) function.
2079        if((onDemand || lazy) && lc.getOutermostFunction() != functionNode) {
2080            return true;
2081        }
2082
2083        // If lazy compiling with optimistic types, don't compile the program eagerly either. It will soon be
2084        // invalidated anyway. In presence of a class cache, this further means that an obsoleted program version
2085        // lingers around. Also, currently loading previously persisted optimistic types information only works if
2086        // we're on-demand compiling a function, so with this strategy the :program method can also have the warmup
2087        // benefit of using previously persisted types.
2088        //
2089        // NOTE that this means the first compiled class will effectively just have a :createProgramFunction method, and
2090        // the RecompilableScriptFunctionData (RSFD) object in its constants array. It won't even have the :program
2091        // method. This is by design. It does mean that we're wasting one compiler execution (and we could minimize this
2092        // by just running it up to scope depth calculation, which creates the RSFDs and then this limited codegen).
2093        // We could emit an initial separate compile unit with the initial version of :program in it to better utilize
2094        // the compilation pipeline, but that would need more invasive changes, as currently the assumption that
2095        // :program is emitted into the first compilation unit of the function lives in many places.
2096        return !onDemand && lazy && env._optimistic_types && functionNode.isProgram();
2097    }
2098
2099    @Override
2100    public boolean enterFunctionNode(final FunctionNode functionNode) {
2101        if (skipFunction(functionNode)) {
2102            // In case we are not generating code for the function, we must create or retrieve the function object and
2103            // load it on the stack here.
2104            newFunctionObject(functionNode, false);
2105            return false;
2106        }
2107
2108        final String fnName = functionNode.getName();
2109
2110        // NOTE: we only emit the method for a function with the given name once. We can have multiple functions with
2111        // the same name as a result of inlining finally blocks. However, in the future -- with type specialization,
2112        // notably -- we might need to check for both name *and* signature. Of course, even that might not be
2113        // sufficient; the function might have a code dependency on the type of the variables in its enclosing scopes,
2114        // and the type of such a variable can be different in catch and finally blocks. So, in the future we will have
2115        // to decide to either generate a unique method for each inlined copy of the function, maybe figure out its
2116        // exact type closure and deduplicate based on that, or just decide that functions in finally blocks aren't
2117        // worth it, and generate one method with most generic type closure.
2118        if (!emittedMethods.contains(fnName)) {
2119            log.info("=== BEGIN ", fnName);
2120
2121            assert functionNode.getCompileUnit() != null : "no compile unit for " + fnName + " " + Debug.id(functionNode);
2122            unit = lc.pushCompileUnit(functionNode.getCompileUnit());
2123            assert lc.hasCompileUnits();
2124
2125            final ClassEmitter classEmitter = unit.getClassEmitter();
2126            pushMethodEmitter(isRestOf() ? classEmitter.restOfMethod(functionNode) : classEmitter.method(functionNode));
2127            method.setPreventUndefinedLoad();
2128            if(useOptimisticTypes()) {
2129                lc.pushUnwarrantedOptimismHandlers();
2130            }
2131
2132            // new method - reset last line number
2133            lastLineNumber = -1;
2134
2135            method.begin();
2136
2137            if (isRestOf()) {
2138                assert continuationInfo == null;
2139                continuationInfo = new ContinuationInfo();
2140                method.gotoLoopStart(continuationInfo.getHandlerLabel());
2141            }
2142        }
2143
2144        return true;
2145    }
2146
2147    private void pushMethodEmitter(final MethodEmitter newMethod) {
2148        method = lc.pushMethodEmitter(newMethod);
2149        catchLabels.push(METHOD_BOUNDARY);
2150    }
2151
2152    private void popMethodEmitter() {
2153        method = lc.popMethodEmitter(method);
2154        assert catchLabels.peek() == METHOD_BOUNDARY;
2155        catchLabels.pop();
2156    }
2157
2158    @Override
2159    public Node leaveFunctionNode(final FunctionNode functionNode) {
2160        try {
2161            final boolean markOptimistic;
2162            if (emittedMethods.add(functionNode.getName())) {
2163                markOptimistic = generateUnwarrantedOptimismExceptionHandlers(functionNode);
2164                generateContinuationHandler();
2165                method.end(); // wrap up this method
2166                unit   = lc.popCompileUnit(functionNode.getCompileUnit());
2167                popMethodEmitter();
2168                log.info("=== END ", functionNode.getName());
2169            } else {
2170                markOptimistic = false;
2171            }
2172
2173            FunctionNode newFunctionNode = functionNode;
2174            if (markOptimistic) {
2175                newFunctionNode = newFunctionNode.setFlag(lc, FunctionNode.IS_DEOPTIMIZABLE);
2176            }
2177
2178            newFunctionObject(newFunctionNode, true);
2179            return newFunctionNode;
2180        } catch (final Throwable t) {
2181            Context.printStackTrace(t);
2182            final VerifyError e = new VerifyError("Code generation bug in \"" + functionNode.getName() + "\": likely stack misaligned: " + t + " " + functionNode.getSource().getName());
2183            e.initCause(t);
2184            throw e;
2185        }
2186    }
2187
2188    @Override
2189    public boolean enterIfNode(final IfNode ifNode) {
2190        if(!method.isReachable()) {
2191            return false;
2192        }
2193        enterStatement(ifNode);
2194
2195        final Expression test = ifNode.getTest();
2196        final Block pass = ifNode.getPass();
2197        final Block fail = ifNode.getFail();
2198
2199        if (Expression.isAlwaysTrue(test)) {
2200            loadAndDiscard(test);
2201            pass.accept(this);
2202            return false;
2203        } else if (Expression.isAlwaysFalse(test)) {
2204            loadAndDiscard(test);
2205            if (fail != null) {
2206                fail.accept(this);
2207            }
2208            return false;
2209        }
2210
2211        final boolean hasFailConversion = LocalVariableConversion.hasLiveConversion(ifNode);
2212
2213        final Label failLabel  = new Label("if_fail");
2214        final Label afterLabel = (fail == null && !hasFailConversion) ? null : new Label("if_done");
2215
2216        emitBranch(test, failLabel, false);
2217
2218        pass.accept(this);
2219        if(method.isReachable() && afterLabel != null) {
2220            method._goto(afterLabel); //don't fallthru to fail block
2221        }
2222        method.label(failLabel);
2223
2224        if (fail != null) {
2225            fail.accept(this);
2226        } else if(hasFailConversion) {
2227            method.beforeJoinPoint(ifNode);
2228        }
2229
2230        if(afterLabel != null && afterLabel.isReachable()) {
2231            method.label(afterLabel);
2232        }
2233
2234        return false;
2235    }
2236
2237    private void emitBranch(final Expression test, final Label label, final boolean jumpWhenTrue) {
2238        new BranchOptimizer(this, method).execute(test, label, jumpWhenTrue);
2239    }
2240
2241    private void enterStatement(final Statement statement) {
2242        lineNumber(statement);
2243    }
2244
2245    private void lineNumber(final Statement statement) {
2246        lineNumber(statement.getLineNumber());
2247    }
2248
2249    private void lineNumber(final int lineNumber) {
2250        if (lineNumber != lastLineNumber && lineNumber != Node.NO_LINE_NUMBER) {
2251            method.lineNumber(lineNumber);
2252            lastLineNumber = lineNumber;
2253        }
2254    }
2255
2256    int getLastLineNumber() {
2257        return lastLineNumber;
2258    }
2259
2260    /**
2261     * Load a list of nodes as an array of a specific type
2262     * The array will contain the visited nodes.
2263     *
2264     * @param arrayLiteralNode the array of contents
2265     * @param arrayType        the type of the array, e.g. ARRAY_NUMBER or ARRAY_OBJECT
2266     */
2267    private void loadArray(final ArrayLiteralNode arrayLiteralNode, final ArrayType arrayType) {
2268        assert arrayType == Type.INT_ARRAY || arrayType == Type.NUMBER_ARRAY || arrayType == Type.OBJECT_ARRAY;
2269
2270        final Expression[]     nodes    = arrayLiteralNode.getValue();
2271        final Object           presets  = arrayLiteralNode.getPresets();
2272        final int[]            postsets = arrayLiteralNode.getPostsets();
2273        final List<Splittable.SplitRange> ranges   = arrayLiteralNode.getSplitRanges();
2274
2275        loadConstant(presets);
2276
2277        final Type elementType = arrayType.getElementType();
2278
2279        if (ranges != null) {
2280
2281            loadSplitLiteral(new SplitLiteralCreator() {
2282                @Override
2283                public void populateRange(final MethodEmitter method, final Type type, final int slot, final int start, final int end) {
2284                    for (int i = start; i < end; i++) {
2285                        method.load(type, slot);
2286                        storeElement(nodes, elementType, postsets[i]);
2287                    }
2288                    method.load(type, slot);
2289                }
2290            }, ranges, arrayType);
2291
2292            return;
2293        }
2294
2295        if(postsets.length > 0) {
2296            final int arraySlot = method.getUsedSlotsWithLiveTemporaries();
2297            method.storeTemp(arrayType, arraySlot);
2298            for (final int postset : postsets) {
2299                method.load(arrayType, arraySlot);
2300                storeElement(nodes, elementType, postset);
2301            }
2302            method.load(arrayType, arraySlot);
2303        }
2304    }
2305
2306    private void storeElement(final Expression[] nodes, final Type elementType, final int index) {
2307        method.load(index);
2308
2309        final Expression element = nodes[index];
2310
2311        if (element == null) {
2312            method.loadEmpty(elementType);
2313        } else {
2314            loadExpressionAsType(element, elementType);
2315        }
2316
2317        method.arraystore();
2318    }
2319
2320    private MethodEmitter loadArgsArray(final List<Expression> args) {
2321        final Object[] array = new Object[args.size()];
2322        loadConstant(array);
2323
2324        for (int i = 0; i < args.size(); i++) {
2325            method.dup();
2326            method.load(i);
2327            loadExpression(args.get(i), TypeBounds.OBJECT); // variable arity methods always take objects
2328            method.arraystore();
2329        }
2330
2331        return method;
2332    }
2333
2334    /**
2335     * Load a constant from the constant array. This is only public to be callable from the objects
2336     * subpackage. Do not call directly.
2337     *
2338     * @param string string to load
2339     */
2340    void loadConstant(final String string) {
2341        final String       unitClassName = unit.getUnitClassName();
2342        final ClassEmitter classEmitter  = unit.getClassEmitter();
2343        final int          index         = compiler.getConstantData().add(string);
2344
2345        method.load(index);
2346        method.invokestatic(unitClassName, GET_STRING.symbolName(), methodDescriptor(String.class, int.class));
2347        classEmitter.needGetConstantMethod(String.class);
2348    }
2349
2350    /**
2351     * Load a constant from the constant array. This is only public to be callable from the objects
2352     * subpackage. Do not call directly.
2353     *
2354     * @param object object to load
2355     */
2356    void loadConstant(final Object object) {
2357        loadConstant(object, unit, method);
2358    }
2359
2360    private void loadConstant(final Object object, final CompileUnit compileUnit, final MethodEmitter methodEmitter) {
2361        final String       unitClassName = compileUnit.getUnitClassName();
2362        final ClassEmitter classEmitter  = compileUnit.getClassEmitter();
2363        final int          index         = compiler.getConstantData().add(object);
2364        final Class<?>     cls           = object.getClass();
2365
2366        if (cls == PropertyMap.class) {
2367            methodEmitter.load(index);
2368            methodEmitter.invokestatic(unitClassName, GET_MAP.symbolName(), methodDescriptor(PropertyMap.class, int.class));
2369            classEmitter.needGetConstantMethod(PropertyMap.class);
2370        } else if (cls.isArray()) {
2371            methodEmitter.load(index);
2372            final String methodName = ClassEmitter.getArrayMethodName(cls);
2373            methodEmitter.invokestatic(unitClassName, methodName, methodDescriptor(cls, int.class));
2374            classEmitter.needGetConstantMethod(cls);
2375        } else {
2376            methodEmitter.loadConstants().load(index).arrayload();
2377            if (object instanceof ArrayData) {
2378                methodEmitter.checkcast(ArrayData.class);
2379                methodEmitter.invoke(virtualCallNoLookup(ArrayData.class, "copy", ArrayData.class));
2380            } else if (cls != Object.class) {
2381                methodEmitter.checkcast(cls);
2382            }
2383        }
2384    }
2385
2386    private void loadConstantsAndIndex(final Object object, final MethodEmitter methodEmitter) {
2387        methodEmitter.loadConstants().load(compiler.getConstantData().add(object));
2388    }
2389
2390    // literal values
2391    private void loadLiteral(final LiteralNode<?> node, final TypeBounds resultBounds) {
2392        final Object value = node.getValue();
2393
2394        if (value == null) {
2395            method.loadNull();
2396        } else if (value instanceof Undefined) {
2397            method.loadUndefined(resultBounds.within(Type.OBJECT));
2398        } else if (value instanceof String) {
2399            final String string = (String)value;
2400
2401            if (string.length() > MethodEmitter.LARGE_STRING_THRESHOLD / 3) { // 3 == max bytes per encoded char
2402                loadConstant(string);
2403            } else {
2404                method.load(string);
2405            }
2406        } else if (value instanceof RegexToken) {
2407            loadRegex((RegexToken)value);
2408        } else if (value instanceof Boolean) {
2409            method.load((Boolean)value);
2410        } else if (value instanceof Integer) {
2411            if(!resultBounds.canBeNarrowerThan(Type.OBJECT)) {
2412                method.load((Integer)value);
2413                method.convert(Type.OBJECT);
2414            } else if(!resultBounds.canBeNarrowerThan(Type.NUMBER)) {
2415                method.load(((Integer)value).doubleValue());
2416            } else {
2417                method.load((Integer)value);
2418            }
2419        } else if (value instanceof Double) {
2420            if(!resultBounds.canBeNarrowerThan(Type.OBJECT)) {
2421                method.load((Double)value);
2422                method.convert(Type.OBJECT);
2423            } else {
2424                method.load((Double)value);
2425            }
2426        } else if (node instanceof ArrayLiteralNode) {
2427            final ArrayLiteralNode arrayLiteral = (ArrayLiteralNode)node;
2428            final ArrayType atype = arrayLiteral.getArrayType();
2429            loadArray(arrayLiteral, atype);
2430            globalAllocateArray(atype);
2431        } else {
2432            throw new UnsupportedOperationException("Unknown literal for " + node.getClass() + " " + value.getClass() + " " + value);
2433        }
2434    }
2435
2436    private MethodEmitter loadRegexToken(final RegexToken value) {
2437        method.load(value.getExpression());
2438        method.load(value.getOptions());
2439        return globalNewRegExp();
2440    }
2441
2442    private MethodEmitter loadRegex(final RegexToken regexToken) {
2443        if (regexFieldCount > MAX_REGEX_FIELDS) {
2444            return loadRegexToken(regexToken);
2445        }
2446        // emit field
2447        final String       regexName    = lc.getCurrentFunction().uniqueName(REGEX_PREFIX.symbolName());
2448        final ClassEmitter classEmitter = unit.getClassEmitter();
2449
2450        classEmitter.field(EnumSet.of(PRIVATE, STATIC), regexName, Object.class);
2451        regexFieldCount++;
2452
2453        // get field, if null create new regex, finally clone regex object
2454        method.getStatic(unit.getUnitClassName(), regexName, typeDescriptor(Object.class));
2455        method.dup();
2456        final Label cachedLabel = new Label("cached");
2457        method.ifnonnull(cachedLabel);
2458
2459        method.pop();
2460        loadRegexToken(regexToken);
2461        method.dup();
2462        method.putStatic(unit.getUnitClassName(), regexName, typeDescriptor(Object.class));
2463
2464        method.label(cachedLabel);
2465        globalRegExpCopy();
2466
2467        return method;
2468    }
2469
2470    /**
2471     * Check if a property value contains a particular program point
2472     * @param value value
2473     * @param pp    program point
2474     * @return true if it's there.
2475     */
2476    private static boolean propertyValueContains(final Expression value, final int pp) {
2477        return new Supplier<Boolean>() {
2478            boolean contains;
2479
2480            @Override
2481            public Boolean get() {
2482                value.accept(new SimpleNodeVisitor() {
2483                    @Override
2484                    public boolean enterFunctionNode(final FunctionNode functionNode) {
2485                        return false;
2486                    }
2487
2488                    @Override
2489                    public boolean enterObjectNode(final ObjectNode objectNode) {
2490                        return false;
2491                    }
2492
2493                    @Override
2494                    public boolean enterDefault(final Node node) {
2495                        if (contains) {
2496                            return false;
2497                        }
2498                        if (node instanceof Optimistic && ((Optimistic)node).getProgramPoint() == pp) {
2499                            contains = true;
2500                            return false;
2501                        }
2502                        return true;
2503                    }
2504                });
2505
2506                return contains;
2507            }
2508        }.get();
2509    }
2510
2511    private void loadObjectNode(final ObjectNode objectNode) {
2512        final List<PropertyNode> elements = objectNode.getElements();
2513
2514        final List<MapTuple<Expression>> tuples = new ArrayList<>();
2515        final List<PropertyNode> gettersSetters = new ArrayList<>();
2516        final int ccp = getCurrentContinuationEntryPoint();
2517        final List<Splittable.SplitRange> ranges = objectNode.getSplitRanges();
2518
2519        Expression protoNode = null;
2520        boolean restOfProperty = false;
2521
2522        for (final PropertyNode propertyNode : elements) {
2523            final Expression value = propertyNode.getValue();
2524            final String key = propertyNode.getKeyName();
2525            // Just use a pseudo-symbol. We just need something non null; use the name and zero flags.
2526            final Symbol symbol = value == null ? null : new Symbol(key, 0);
2527
2528            if (value == null) {
2529                gettersSetters.add(propertyNode);
2530            } else if (propertyNode.getKey() instanceof IdentNode &&
2531                       key.equals(ScriptObject.PROTO_PROPERTY_NAME)) {
2532                // ES6 draft compliant __proto__ inside object literal
2533                // Identifier key and name is __proto__
2534                protoNode = value;
2535                continue;
2536            }
2537
2538            restOfProperty |=
2539                value != null &&
2540                isValid(ccp) &&
2541                propertyValueContains(value, ccp);
2542
2543            //for literals, a value of null means object type, i.e. the value null or getter setter function
2544            //(I think)
2545            final Class<?> valueType = (!useDualFields() || value == null || value.getType().isBoolean()) ? Object.class : value.getType().getTypeClass();
2546            tuples.add(new MapTuple<Expression>(key, symbol, Type.typeFor(valueType), value) {
2547                @Override
2548                public Class<?> getValueType() {
2549                    return type.getTypeClass();
2550                }
2551            });
2552        }
2553
2554        final ObjectCreator<?> oc;
2555        if (elements.size() > OBJECT_SPILL_THRESHOLD) {
2556            oc = new SpillObjectCreator(this, tuples);
2557        } else {
2558            oc = new FieldObjectCreator<Expression>(this, tuples) {
2559                @Override
2560                protected void loadValue(final Expression node, final Type type) {
2561                    loadExpressionAsType(node, type);
2562                }};
2563        }
2564
2565        if (ranges != null) {
2566            oc.createObject(method);
2567            loadSplitLiteral(oc, ranges, Type.typeFor(oc.getAllocatorClass()));
2568        } else {
2569            oc.makeObject(method);
2570        }
2571
2572        //if this is a rest of method and our continuation point was found as one of the values
2573        //in the properties above, we need to reset the map to oc.getMap() in the continuation
2574        //handler
2575        if (restOfProperty) {
2576            final ContinuationInfo ci = getContinuationInfo();
2577            // Can be set at most once for a single rest-of method
2578            assert ci.getObjectLiteralMap() == null;
2579            ci.setObjectLiteralMap(oc.getMap());
2580            ci.setObjectLiteralStackDepth(method.getStackSize());
2581        }
2582
2583        method.dup();
2584        if (protoNode != null) {
2585            loadExpressionAsObject(protoNode);
2586            // take care of { __proto__: 34 } or some such!
2587            method.convert(Type.OBJECT);
2588            method.invoke(ScriptObject.SET_PROTO_FROM_LITERAL);
2589        } else {
2590            method.invoke(ScriptObject.SET_GLOBAL_OBJECT_PROTO);
2591        }
2592
2593        for (final PropertyNode propertyNode : gettersSetters) {
2594            final FunctionNode getter = propertyNode.getGetter();
2595            final FunctionNode setter = propertyNode.getSetter();
2596
2597            assert getter != null || setter != null;
2598
2599            method.dup().loadKey(propertyNode.getKey());
2600            if (getter == null) {
2601                method.loadNull();
2602            } else {
2603                getter.accept(this);
2604            }
2605
2606            if (setter == null) {
2607                method.loadNull();
2608            } else {
2609                setter.accept(this);
2610            }
2611
2612            method.invoke(ScriptObject.SET_USER_ACCESSORS);
2613        }
2614    }
2615
2616    @Override
2617    public boolean enterReturnNode(final ReturnNode returnNode) {
2618        if(!method.isReachable()) {
2619            return false;
2620        }
2621        enterStatement(returnNode);
2622
2623        final Type returnType = lc.getCurrentFunction().getReturnType();
2624
2625        final Expression expression = returnNode.getExpression();
2626        if (expression != null) {
2627            loadExpressionUnbounded(expression);
2628        } else {
2629            method.loadUndefined(returnType);
2630        }
2631
2632        method._return(returnType);
2633
2634        return false;
2635    }
2636
2637    private boolean undefinedCheck(final RuntimeNode runtimeNode, final List<Expression> args) {
2638        final Request request = runtimeNode.getRequest();
2639
2640        if (!Request.isUndefinedCheck(request)) {
2641            return false;
2642        }
2643
2644        final Expression lhs = args.get(0);
2645        final Expression rhs = args.get(1);
2646
2647        final Symbol lhsSymbol = lhs instanceof IdentNode ? ((IdentNode)lhs).getSymbol() : null;
2648        final Symbol rhsSymbol = rhs instanceof IdentNode ? ((IdentNode)rhs).getSymbol() : null;
2649        // One must be a "undefined" identifier, otherwise we can't get here
2650        assert lhsSymbol != null || rhsSymbol != null;
2651
2652        final Symbol undefinedSymbol;
2653        if (isUndefinedSymbol(lhsSymbol)) {
2654            undefinedSymbol = lhsSymbol;
2655        } else {
2656            assert isUndefinedSymbol(rhsSymbol);
2657            undefinedSymbol = rhsSymbol;
2658        }
2659
2660        assert undefinedSymbol != null; //remove warning
2661        if (!undefinedSymbol.isScope()) {
2662            return false; //disallow undefined as local var or parameter
2663        }
2664
2665        if (lhsSymbol == undefinedSymbol && lhs.getType().isPrimitive()) {
2666            //we load the undefined first. never mind, because this will deoptimize anyway
2667            return false;
2668        }
2669
2670        if(isDeoptimizedExpression(lhs)) {
2671            // This is actually related to "lhs.getType().isPrimitive()" above: any expression being deoptimized in
2672            // the current chain of rest-of compilations used to have a type narrower than Object (so it was primitive).
2673            // We must not perform undefined check specialization for them, as then we'd violate the basic rule of
2674            // "Thou shalt not alter the stack shape between a deoptimized method and any of its (transitive) rest-ofs."
2675            return false;
2676        }
2677
2678        //make sure that undefined has not been overridden or scoped as a local var
2679        //between us and global
2680        if (!compiler.isGlobalSymbol(lc.getCurrentFunction(), "undefined")) {
2681            return false;
2682        }
2683
2684        final boolean isUndefinedCheck = request == Request.IS_UNDEFINED;
2685        final Expression expr = undefinedSymbol == lhsSymbol ? rhs : lhs;
2686        if (expr.getType().isPrimitive()) {
2687            loadAndDiscard(expr); //throw away lhs, but it still needs to be evaluated for side effects, even if not in scope, as it can be optimistic
2688            method.load(!isUndefinedCheck);
2689        } else {
2690            final Label checkTrue  = new Label("ud_check_true");
2691            final Label end        = new Label("end");
2692            loadExpressionAsObject(expr);
2693            method.loadUndefined(Type.OBJECT);
2694            method.if_acmpeq(checkTrue);
2695            method.load(!isUndefinedCheck);
2696            method._goto(end);
2697            method.label(checkTrue);
2698            method.load(isUndefinedCheck);
2699            method.label(end);
2700        }
2701
2702        return true;
2703    }
2704
2705    private static boolean isUndefinedSymbol(final Symbol symbol) {
2706        return symbol != null && "undefined".equals(symbol.getName());
2707    }
2708
2709    private static boolean isNullLiteral(final Node node) {
2710        return node instanceof LiteralNode<?> && ((LiteralNode<?>) node).isNull();
2711    }
2712
2713    private boolean nullCheck(final RuntimeNode runtimeNode, final List<Expression> args) {
2714        final Request request = runtimeNode.getRequest();
2715
2716        if (!Request.isEQ(request) && !Request.isNE(request)) {
2717            return false;
2718        }
2719
2720        assert args.size() == 2 : "EQ or NE or TYPEOF need two args";
2721
2722        Expression lhs = args.get(0);
2723        Expression rhs = args.get(1);
2724
2725        if (isNullLiteral(lhs)) {
2726            final Expression tmp = lhs;
2727            lhs = rhs;
2728            rhs = tmp;
2729        }
2730
2731        if (!isNullLiteral(rhs)) {
2732            return false;
2733        }
2734
2735        if (!lhs.getType().isObject()) {
2736            return false;
2737        }
2738
2739        if(isDeoptimizedExpression(lhs)) {
2740            // This is actually related to "!lhs.getType().isObject()" above: any expression being deoptimized in
2741            // the current chain of rest-of compilations used to have a type narrower than Object. We must not
2742            // perform null check specialization for them, as then we'd no longer be loading aconst_null on stack
2743            // and thus violate the basic rule of "Thou shalt not alter the stack shape between a deoptimized
2744            // method and any of its (transitive) rest-ofs."
2745            // NOTE also that if we had a representation for well-known constants (e.g. null, 0, 1, -1, etc.) in
2746            // Label$Stack.localLoads then this wouldn't be an issue, as we would never (somewhat ridiculously)
2747            // allocate a temporary local to hold the result of aconst_null before attempting an optimistic
2748            // operation.
2749            return false;
2750        }
2751
2752        // this is a null literal check, so if there is implicit coercion
2753        // involved like {D}x=null, we will fail - this is very rare
2754        final Label trueLabel  = new Label("trueLabel");
2755        final Label falseLabel = new Label("falseLabel");
2756        final Label endLabel   = new Label("end");
2757
2758        loadExpressionUnbounded(lhs);    //lhs
2759        final Label popLabel;
2760        if (!Request.isStrict(request)) {
2761            method.dup(); //lhs lhs
2762            popLabel = new Label("pop");
2763        } else {
2764            popLabel = null;
2765        }
2766
2767        if (Request.isEQ(request)) {
2768            method.ifnull(!Request.isStrict(request) ? popLabel : trueLabel);
2769            if (!Request.isStrict(request)) {
2770                method.loadUndefined(Type.OBJECT);
2771                method.if_acmpeq(trueLabel);
2772            }
2773            method.label(falseLabel);
2774            method.load(false);
2775            method._goto(endLabel);
2776            if (!Request.isStrict(request)) {
2777                method.label(popLabel);
2778                method.pop();
2779            }
2780            method.label(trueLabel);
2781            method.load(true);
2782            method.label(endLabel);
2783        } else if (Request.isNE(request)) {
2784            method.ifnull(!Request.isStrict(request) ? popLabel : falseLabel);
2785            if (!Request.isStrict(request)) {
2786                method.loadUndefined(Type.OBJECT);
2787                method.if_acmpeq(falseLabel);
2788            }
2789            method.label(trueLabel);
2790            method.load(true);
2791            method._goto(endLabel);
2792            if (!Request.isStrict(request)) {
2793                method.label(popLabel);
2794                method.pop();
2795            }
2796            method.label(falseLabel);
2797            method.load(false);
2798            method.label(endLabel);
2799        }
2800
2801        assert runtimeNode.getType().isBoolean();
2802        method.convert(runtimeNode.getType());
2803
2804        return true;
2805    }
2806
2807    /**
2808     * Was this expression or any of its subexpressions deoptimized in the current recompilation chain of rest-of methods?
2809     * @param rootExpr the expression being tested
2810     * @return true if the expression or any of its subexpressions was deoptimized in the current recompilation chain.
2811     */
2812    private boolean isDeoptimizedExpression(final Expression rootExpr) {
2813        if(!isRestOf()) {
2814            return false;
2815        }
2816        return new Supplier<Boolean>() {
2817            boolean contains;
2818            @Override
2819            public Boolean get() {
2820                rootExpr.accept(new SimpleNodeVisitor() {
2821                    @Override
2822                    public boolean enterFunctionNode(final FunctionNode functionNode) {
2823                        return false;
2824                    }
2825                    @Override
2826                    public boolean enterDefault(final Node node) {
2827                        if(!contains && node instanceof Optimistic) {
2828                            final int pp = ((Optimistic)node).getProgramPoint();
2829                            contains = isValid(pp) && isContinuationEntryPoint(pp);
2830                        }
2831                        return !contains;
2832                    }
2833                });
2834                return contains;
2835            }
2836        }.get();
2837    }
2838
2839    private void loadRuntimeNode(final RuntimeNode runtimeNode) {
2840        final List<Expression> args = new ArrayList<>(runtimeNode.getArgs());
2841        if (nullCheck(runtimeNode, args)) {
2842           return;
2843        } else if(undefinedCheck(runtimeNode, args)) {
2844            return;
2845        }
2846        // Revert a false undefined check to a strict equality check
2847        final RuntimeNode newRuntimeNode;
2848        final Request request = runtimeNode.getRequest();
2849        if (Request.isUndefinedCheck(request)) {
2850            newRuntimeNode = runtimeNode.setRequest(request == Request.IS_UNDEFINED ? Request.EQ_STRICT : Request.NE_STRICT);
2851        } else {
2852            newRuntimeNode = runtimeNode;
2853        }
2854
2855        for (final Expression arg : args) {
2856            loadExpression(arg, TypeBounds.OBJECT);
2857        }
2858
2859        method.invokestatic(
2860                CompilerConstants.className(ScriptRuntime.class),
2861                newRuntimeNode.getRequest().toString(),
2862                new FunctionSignature(
2863                    false,
2864                    false,
2865                    newRuntimeNode.getType(),
2866                    args.size()).toString());
2867
2868        method.convert(newRuntimeNode.getType());
2869    }
2870
2871    private void defineCommonSplitMethodParameters() {
2872        defineSplitMethodParameter(0, CALLEE);
2873        defineSplitMethodParameter(1, THIS);
2874        defineSplitMethodParameter(2, SCOPE);
2875    }
2876
2877    private void defineSplitMethodParameter(final int slot, final CompilerConstants cc) {
2878        defineSplitMethodParameter(slot, Type.typeFor(cc.type()));
2879    }
2880
2881    private void defineSplitMethodParameter(final int slot, final Type type) {
2882        method.defineBlockLocalVariable(slot, slot + type.getSlots());
2883        method.onLocalStore(type, slot);
2884    }
2885
2886    private void loadSplitLiteral(final SplitLiteralCreator creator, final List<Splittable.SplitRange> ranges, final Type literalType) {
2887        assert ranges != null;
2888
2889        // final Type literalType = Type.typeFor(literalClass);
2890        final MethodEmitter savedMethod     = method;
2891        final FunctionNode  currentFunction = lc.getCurrentFunction();
2892
2893        for (final Splittable.SplitRange splitRange : ranges) {
2894            unit = lc.pushCompileUnit(splitRange.getCompileUnit());
2895
2896            assert unit != null;
2897            final String className = unit.getUnitClassName();
2898            final String name      = currentFunction.uniqueName(SPLIT_PREFIX.symbolName());
2899            final Class<?> clazz   = literalType.getTypeClass();
2900            final String signature = methodDescriptor(clazz, ScriptFunction.class, Object.class, ScriptObject.class, clazz);
2901
2902            pushMethodEmitter(unit.getClassEmitter().method(EnumSet.of(Flag.PUBLIC, Flag.STATIC), name, signature));
2903
2904            method.setFunctionNode(currentFunction);
2905            method.begin();
2906
2907            defineCommonSplitMethodParameters();
2908            defineSplitMethodParameter(CompilerConstants.SPLIT_ARRAY_ARG.slot(), literalType);
2909
2910            // NOTE: when this is no longer needed, SplitIntoFunctions will no longer have to add IS_SPLIT
2911            // to synthetic functions, and FunctionNode.needsCallee() will no longer need to test for isSplit().
2912            final int literalSlot = fixScopeSlot(currentFunction, 3);
2913
2914            lc.enterSplitNode();
2915
2916            creator.populateRange(method, literalType, literalSlot, splitRange.getLow(), splitRange.getHigh());
2917
2918            method._return();
2919            lc.exitSplitNode();
2920            method.end();
2921            lc.releaseSlots();
2922            popMethodEmitter();
2923
2924            assert method == savedMethod;
2925            method.loadCompilerConstant(CALLEE).swap();
2926            method.loadCompilerConstant(THIS).swap();
2927            method.loadCompilerConstant(SCOPE).swap();
2928            method.invokestatic(className, name, signature);
2929
2930            unit = lc.popCompileUnit(unit);
2931        }
2932    }
2933
2934    private int fixScopeSlot(final FunctionNode functionNode, final int extraSlot) {
2935        // TODO hack to move the scope to the expected slot (needed because split methods reuse the same slots as the root method)
2936        final int actualScopeSlot = functionNode.compilerConstant(SCOPE).getSlot(SCOPE_TYPE);
2937        final int defaultScopeSlot = SCOPE.slot();
2938        int newExtraSlot = extraSlot;
2939        if (actualScopeSlot != defaultScopeSlot) {
2940            if (actualScopeSlot == extraSlot) {
2941                newExtraSlot = extraSlot + 1;
2942                method.defineBlockLocalVariable(newExtraSlot, newExtraSlot + 1);
2943                method.load(Type.OBJECT, extraSlot);
2944                method.storeHidden(Type.OBJECT, newExtraSlot);
2945            } else {
2946                method.defineBlockLocalVariable(actualScopeSlot, actualScopeSlot + 1);
2947            }
2948            method.load(SCOPE_TYPE, defaultScopeSlot);
2949            method.storeCompilerConstant(SCOPE);
2950        }
2951        return newExtraSlot;
2952    }
2953
2954    @Override
2955    public boolean enterSplitReturn(final SplitReturn splitReturn) {
2956        if (method.isReachable()) {
2957            method.loadUndefined(lc.getCurrentFunction().getReturnType())._return();
2958        }
2959        return false;
2960    }
2961
2962    @Override
2963    public boolean enterSetSplitState(final SetSplitState setSplitState) {
2964        if (method.isReachable()) {
2965            method.setSplitState(setSplitState.getState());
2966        }
2967        return false;
2968    }
2969
2970    @Override
2971    public boolean enterSwitchNode(final SwitchNode switchNode) {
2972        if(!method.isReachable()) {
2973            return false;
2974        }
2975        enterStatement(switchNode);
2976
2977        final Expression     expression  = switchNode.getExpression();
2978        final List<CaseNode> cases       = switchNode.getCases();
2979
2980        if (cases.isEmpty()) {
2981            // still evaluate expression for side-effects.
2982            loadAndDiscard(expression);
2983            return false;
2984        }
2985
2986        final CaseNode defaultCase       = switchNode.getDefaultCase();
2987        final Label    breakLabel        = switchNode.getBreakLabel();
2988        final int      liveLocalsOnBreak = method.getUsedSlotsWithLiveTemporaries();
2989
2990        if (defaultCase != null && cases.size() == 1) {
2991            // default case only
2992            assert cases.get(0) == defaultCase;
2993            loadAndDiscard(expression);
2994            defaultCase.getBody().accept(this);
2995            method.breakLabel(breakLabel, liveLocalsOnBreak);
2996            return false;
2997        }
2998
2999        // NOTE: it can still change in the tableswitch/lookupswitch case if there's no default case
3000        // but we need to add a synthetic default case for local variable conversions
3001        Label defaultLabel = defaultCase != null ? defaultCase.getEntry() : breakLabel;
3002        final boolean hasSkipConversion = LocalVariableConversion.hasLiveConversion(switchNode);
3003
3004        if (switchNode.isUniqueInteger()) {
3005            // Tree for sorting values.
3006            final TreeMap<Integer, Label> tree = new TreeMap<>();
3007
3008            // Build up sorted tree.
3009            for (final CaseNode caseNode : cases) {
3010                final Node test = caseNode.getTest();
3011
3012                if (test != null) {
3013                    final Integer value = (Integer)((LiteralNode<?>)test).getValue();
3014                    final Label   entry = caseNode.getEntry();
3015
3016                    // Take first duplicate.
3017                    if (!tree.containsKey(value)) {
3018                        tree.put(value, entry);
3019                    }
3020                }
3021            }
3022
3023            // Copy values and labels to arrays.
3024            final int       size   = tree.size();
3025            final Integer[] values = tree.keySet().toArray(new Integer[0]);
3026            final Label[]   labels = tree.values().toArray(new Label[0]);
3027
3028            // Discern low, high and range.
3029            final int lo    = values[0];
3030            final int hi    = values[size - 1];
3031            final long range = (long)hi - (long)lo + 1;
3032
3033            // Find an unused value for default.
3034            int deflt = Integer.MIN_VALUE;
3035            for (final int value : values) {
3036                if (deflt == value) {
3037                    deflt++;
3038                } else if (deflt < value) {
3039                    break;
3040                }
3041            }
3042
3043            // Load switch expression.
3044            loadExpressionUnbounded(expression);
3045            final Type type = expression.getType();
3046
3047            // If expression not int see if we can convert, if not use deflt to trigger default.
3048            if (!type.isInteger()) {
3049                method.load(deflt);
3050                final Class<?> exprClass = type.getTypeClass();
3051                method.invoke(staticCallNoLookup(ScriptRuntime.class, "switchTagAsInt", int.class, exprClass.isPrimitive()? exprClass : Object.class, int.class));
3052            }
3053
3054            if(hasSkipConversion) {
3055                assert defaultLabel == breakLabel;
3056                defaultLabel = new Label("switch_skip");
3057            }
3058            // TABLESWITCH needs (range + 3) 32-bit values; LOOKUPSWITCH needs ((size * 2) + 2). Choose the one with
3059            // smaller representation, favor TABLESWITCH when they're equal size.
3060            if (range + 1 <= (size * 2) && range <= Integer.MAX_VALUE) {
3061                final Label[] table = new Label[(int)range];
3062                Arrays.fill(table, defaultLabel);
3063                for (int i = 0; i < size; i++) {
3064                    final int value = values[i];
3065                    table[value - lo] = labels[i];
3066                }
3067
3068                method.tableswitch(lo, hi, defaultLabel, table);
3069            } else {
3070                final int[] ints = new int[size];
3071                for (int i = 0; i < size; i++) {
3072                    ints[i] = values[i];
3073                }
3074
3075                method.lookupswitch(defaultLabel, ints, labels);
3076            }
3077            // This is a synthetic "default case" used in absence of actual default case, created if we need to apply
3078            // local variable conversions if neither case is taken.
3079            if(hasSkipConversion) {
3080                method.label(defaultLabel);
3081                method.beforeJoinPoint(switchNode);
3082                method._goto(breakLabel);
3083            }
3084        } else {
3085            final Symbol tagSymbol = switchNode.getTag();
3086            // TODO: we could have non-object tag
3087            final int tagSlot = tagSymbol.getSlot(Type.OBJECT);
3088            loadExpressionAsObject(expression);
3089            method.store(tagSymbol, Type.OBJECT);
3090
3091            for (final CaseNode caseNode : cases) {
3092                final Expression test = caseNode.getTest();
3093
3094                if (test != null) {
3095                    method.load(Type.OBJECT, tagSlot);
3096                    loadExpressionAsObject(test);
3097                    method.invoke(ScriptRuntime.EQ_STRICT);
3098                    method.ifne(caseNode.getEntry());
3099                }
3100            }
3101
3102            if (defaultCase != null) {
3103                method._goto(defaultLabel);
3104            } else {
3105                method.beforeJoinPoint(switchNode);
3106                method._goto(breakLabel);
3107            }
3108        }
3109
3110        // First case is only reachable through jump
3111        assert !method.isReachable();
3112
3113        for (final CaseNode caseNode : cases) {
3114            final Label fallThroughLabel;
3115            if(caseNode.getLocalVariableConversion() != null && method.isReachable()) {
3116                fallThroughLabel = new Label("fallthrough");
3117                method._goto(fallThroughLabel);
3118            } else {
3119                fallThroughLabel = null;
3120            }
3121            method.label(caseNode.getEntry());
3122            method.beforeJoinPoint(caseNode);
3123            if(fallThroughLabel != null) {
3124                method.label(fallThroughLabel);
3125            }
3126            caseNode.getBody().accept(this);
3127        }
3128
3129        method.breakLabel(breakLabel, liveLocalsOnBreak);
3130
3131        return false;
3132    }
3133
3134    @Override
3135    public boolean enterThrowNode(final ThrowNode throwNode) {
3136        if(!method.isReachable()) {
3137            return false;
3138        }
3139        enterStatement(throwNode);
3140
3141        if (throwNode.isSyntheticRethrow()) {
3142            method.beforeJoinPoint(throwNode);
3143
3144            //do not wrap whatever this is in an ecma exception, just rethrow it
3145            final IdentNode exceptionExpr = (IdentNode)throwNode.getExpression();
3146            final Symbol exceptionSymbol = exceptionExpr.getSymbol();
3147            method.load(exceptionSymbol, EXCEPTION_TYPE);
3148            method.checkcast(EXCEPTION_TYPE.getTypeClass());
3149            method.athrow();
3150            return false;
3151        }
3152
3153        final Source     source     = getCurrentSource();
3154        final Expression expression = throwNode.getExpression();
3155        final int        position   = throwNode.position();
3156        final int        line       = throwNode.getLineNumber();
3157        final int        column     = source.getColumn(position);
3158
3159        // NOTE: we first evaluate the expression, and only after it was evaluated do we create the new ECMAException
3160        // object and then somewhat cumbersomely move it beneath the evaluated expression on the stack. The reason for
3161        // this is that if expression is optimistic (or contains an optimistic subexpression), we'd potentially access
3162        // the not-yet-<init>ialized object on the stack from the UnwarrantedOptimismException handler, and bytecode
3163        // verifier forbids that.
3164        loadExpressionAsObject(expression);
3165
3166        method.load(source.getName());
3167        method.load(line);
3168        method.load(column);
3169        method.invoke(ECMAException.CREATE);
3170
3171        method.beforeJoinPoint(throwNode);
3172        method.athrow();
3173
3174        return false;
3175    }
3176
3177    private Source getCurrentSource() {
3178        return lc.getCurrentFunction().getSource();
3179    }
3180
3181    @Override
3182    public boolean enterTryNode(final TryNode tryNode) {
3183        if(!method.isReachable()) {
3184            return false;
3185        }
3186        enterStatement(tryNode);
3187
3188        final Block       body        = tryNode.getBody();
3189        final List<Block> catchBlocks = tryNode.getCatchBlocks();
3190        final Symbol      vmException = tryNode.getException();
3191        final Label       entry       = new Label("try");
3192        final Label       recovery    = new Label("catch");
3193        final Label       exit        = new Label("end_try");
3194        final Label       skip        = new Label("skip");
3195
3196        method.canThrow(recovery);
3197        // Effect any conversions that might be observed at the entry of the catch node before entering the try node.
3198        // This is because even the first instruction in the try block must be presumed to be able to transfer control
3199        // to the catch block. Note that this doesn't kill the original values; in this regard it works a lot like
3200        // conversions of assignments within the try block.
3201        method.beforeTry(tryNode, recovery);
3202        method.label(entry);
3203        catchLabels.push(recovery);
3204        try {
3205            body.accept(this);
3206        } finally {
3207            assert catchLabels.peek() == recovery;
3208            catchLabels.pop();
3209        }
3210
3211        method.label(exit);
3212        final boolean bodyCanThrow = exit.isAfter(entry);
3213        if(!bodyCanThrow) {
3214            // The body can't throw an exception; don't even bother emitting the catch handlers, they're all dead code.
3215            return false;
3216        }
3217
3218        method._try(entry, exit, recovery, Throwable.class);
3219
3220        if (method.isReachable()) {
3221            method._goto(skip);
3222        }
3223
3224        for (final Block inlinedFinally : tryNode.getInlinedFinallies()) {
3225            TryNode.getLabelledInlinedFinallyBlock(inlinedFinally).accept(this);
3226            // All inlined finallies end with a jump or a return
3227            assert !method.isReachable();
3228        }
3229
3230
3231        method._catch(recovery);
3232        method.store(vmException, EXCEPTION_TYPE);
3233
3234        final int catchBlockCount = catchBlocks.size();
3235        final Label afterCatch = new Label("after_catch");
3236        for (int i = 0; i < catchBlockCount; i++) {
3237            assert method.isReachable();
3238            final Block catchBlock = catchBlocks.get(i);
3239
3240            // Because of the peculiarities of the flow control, we need to use an explicit push/enterBlock/leaveBlock
3241            // here.
3242            lc.push(catchBlock);
3243            enterBlock(catchBlock);
3244
3245            final CatchNode  catchNode          = (CatchNode)catchBlocks.get(i).getStatements().get(0);
3246            final IdentNode  exception          = catchNode.getException();
3247            final Expression exceptionCondition = catchNode.getExceptionCondition();
3248            final Block      catchBody          = catchNode.getBody();
3249
3250            new Store<IdentNode>(exception) {
3251                @Override
3252                protected void storeNonDiscard() {
3253                    // This expression is neither part of a discard, nor needs to be left on the stack after it was
3254                    // stored, so we override storeNonDiscard to be a no-op.
3255                }
3256
3257                @Override
3258                protected void evaluate() {
3259                    if (catchNode.isSyntheticRethrow()) {
3260                        method.load(vmException, EXCEPTION_TYPE);
3261                        return;
3262                    }
3263                    /*
3264                     * If caught object is an instance of ECMAException, then
3265                     * bind obj.thrown to the script catch var. Or else bind the
3266                     * caught object itself to the script catch var.
3267                     */
3268                    final Label notEcmaException = new Label("no_ecma_exception");
3269                    method.load(vmException, EXCEPTION_TYPE).dup()._instanceof(ECMAException.class).ifeq(notEcmaException);
3270                    method.checkcast(ECMAException.class); //TODO is this necessary?
3271                    method.getField(ECMAException.THROWN);
3272                    method.label(notEcmaException);
3273                }
3274            }.store();
3275
3276            final boolean isConditionalCatch = exceptionCondition != null;
3277            final Label nextCatch;
3278            if (isConditionalCatch) {
3279                loadExpressionAsBoolean(exceptionCondition);
3280                nextCatch = new Label("next_catch");
3281                nextCatch.markAsBreakTarget();
3282                method.ifeq(nextCatch);
3283            } else {
3284                nextCatch = null;
3285            }
3286
3287            catchBody.accept(this);
3288            leaveBlock(catchBlock);
3289            lc.pop(catchBlock);
3290            if(nextCatch != null) {
3291                if(method.isReachable()) {
3292                    method._goto(afterCatch);
3293                }
3294                method.breakLabel(nextCatch, lc.getUsedSlotCount());
3295            }
3296        }
3297
3298        // afterCatch could be the same as skip, except that we need to establish that the vmException is dead.
3299        method.label(afterCatch);
3300        if(method.isReachable()) {
3301            method.markDeadLocalVariable(vmException);
3302        }
3303        method.label(skip);
3304
3305        // Finally body is always inlined elsewhere so it doesn't need to be emitted
3306        assert tryNode.getFinallyBody() == null;
3307
3308        return false;
3309    }
3310
3311    @Override
3312    public boolean enterVarNode(final VarNode varNode) {
3313        if(!method.isReachable()) {
3314            return false;
3315        }
3316        final Expression init = varNode.getInit();
3317        final IdentNode identNode = varNode.getName();
3318        final Symbol identSymbol = identNode.getSymbol();
3319        assert identSymbol != null : "variable node " + varNode + " requires a name with a symbol";
3320        final boolean needsScope = identSymbol.isScope();
3321
3322        if (init == null) {
3323            // Block-scoped variables need a DECLARE flag to signal end of temporal dead zone (TDZ).
3324            // However, don't do this for CONST which always has an initializer except in the special case of
3325            // for-in/of loops, in which it is initialized in the loop header and should be left untouched here.
3326            if (needsScope && varNode.isLet()) {
3327                method.loadCompilerConstant(SCOPE);
3328                method.loadUndefined(Type.OBJECT);
3329                final int flags = getScopeCallSiteFlags(identSymbol) | CALLSITE_DECLARE;
3330                assert isFastScope(identSymbol);
3331                storeFastScopeVar(identSymbol, flags);
3332            }
3333            return false;
3334        }
3335
3336        enterStatement(varNode);
3337        assert method != null;
3338
3339        if (needsScope) {
3340            method.loadCompilerConstant(SCOPE);
3341            loadExpressionUnbounded(init);
3342            // block scoped variables need a DECLARE flag to signal end of temporal dead zone (TDZ)
3343            final int flags = getScopeCallSiteFlags(identSymbol) | (varNode.isBlockScoped() ? CALLSITE_DECLARE : 0);
3344            if (isFastScope(identSymbol)) {
3345                storeFastScopeVar(identSymbol, flags);
3346            } else {
3347                method.dynamicSet(identNode.getName(), flags, false);
3348            }
3349        } else {
3350            final Type identType = identNode.getType();
3351            if(identType == Type.UNDEFINED) {
3352                // The initializer is either itself undefined (explicit assignment of undefined to undefined),
3353                // or the left hand side is a dead variable.
3354                assert init.getType() == Type.UNDEFINED || identNode.getSymbol().slotCount() == 0;
3355                loadAndDiscard(init);
3356                return false;
3357            }
3358            loadExpressionAsType(init, identType);
3359            storeIdentWithCatchConversion(identNode, identType);
3360        }
3361
3362        return false;
3363    }
3364
3365    private void storeIdentWithCatchConversion(final IdentNode identNode, final Type type) {
3366        // Assignments happening in try/catch blocks need to ensure that they also store a possibly wider typed value
3367        // that will be live at the exit from the try block
3368        final LocalVariableConversion conversion = identNode.getLocalVariableConversion();
3369        final Symbol symbol = identNode.getSymbol();
3370        if(conversion != null && conversion.isLive()) {
3371            assert symbol == conversion.getSymbol();
3372            assert symbol.isBytecodeLocal();
3373            // Only a single conversion from the target type to the join type is expected.
3374            assert conversion.getNext() == null;
3375            assert conversion.getFrom() == type;
3376            // We must propagate potential type change to the catch block
3377            final Label catchLabel = catchLabels.peek();
3378            assert catchLabel != METHOD_BOUNDARY; // ident conversion only exists in try blocks
3379            assert catchLabel.isReachable();
3380            final Type joinType = conversion.getTo();
3381            final Label.Stack catchStack = catchLabel.getStack();
3382            final int joinSlot = symbol.getSlot(joinType);
3383            // With nested try/catch blocks (incl. synthetic ones for finally), we can have a supposed conversion for
3384            // the exception symbol in the nested catch, but it isn't live in the outer catch block, so prevent doing
3385            // conversions for it. E.g. in "try { try { ... } catch(e) { e = 1; } } catch(e2) { ... }", we must not
3386            // introduce an I->O conversion on "e = 1" assignment as "e" is not live in "catch(e2)".
3387            if(catchStack.getUsedSlotsWithLiveTemporaries() > joinSlot) {
3388                method.dup();
3389                method.convert(joinType);
3390                method.store(symbol, joinType);
3391                catchLabel.getStack().onLocalStore(joinType, joinSlot, true);
3392                method.canThrow(catchLabel);
3393                // Store but keep the previous store live too.
3394                method.store(symbol, type, false);
3395                return;
3396            }
3397        }
3398
3399        method.store(symbol, type, true);
3400    }
3401
3402    @Override
3403    public boolean enterWhileNode(final WhileNode whileNode) {
3404        if(!method.isReachable()) {
3405            return false;
3406        }
3407        if(whileNode.isDoWhile()) {
3408            enterDoWhile(whileNode);
3409        } else {
3410            enterStatement(whileNode);
3411            enterForOrWhile(whileNode, null);
3412        }
3413        return false;
3414    }
3415
3416    private void enterForOrWhile(final LoopNode loopNode, final JoinPredecessorExpression modify) {
3417        // NOTE: the usual pattern for compiling test-first loops is "GOTO test; body; test; IFNE body". We use the less
3418        // conventional "test; IFEQ break; body; GOTO test; break;". It has one extra unconditional GOTO in each repeat
3419        // of the loop, but it's not a problem for modern JIT compilers. We do this because our local variable type
3420        // tracking is unfortunately not really prepared for out-of-order execution, e.g. compiling the following
3421        // contrived but legal JavaScript code snippet would fail because the test changes the type of "i" from object
3422        // to double: var i = {valueOf: function() { return 1} }; while(--i >= 0) { ... }
3423        // Instead of adding more complexity to the local variable type tracking, we instead choose to emit this
3424        // different code shape.
3425        final int liveLocalsOnBreak = method.getUsedSlotsWithLiveTemporaries();
3426        final JoinPredecessorExpression test = loopNode.getTest();
3427        if(Expression.isAlwaysFalse(test)) {
3428            loadAndDiscard(test);
3429            return;
3430        }
3431
3432        method.beforeJoinPoint(loopNode);
3433
3434        final Label continueLabel = loopNode.getContinueLabel();
3435        final Label repeatLabel = modify != null ? new Label("for_repeat") : continueLabel;
3436        method.label(repeatLabel);
3437        final int liveLocalsOnContinue = method.getUsedSlotsWithLiveTemporaries();
3438
3439        final Block   body                  = loopNode.getBody();
3440        final Label   breakLabel            = loopNode.getBreakLabel();
3441        final boolean testHasLiveConversion = test != null && LocalVariableConversion.hasLiveConversion(test);
3442
3443        if(Expression.isAlwaysTrue(test)) {
3444            if(test != null) {
3445                loadAndDiscard(test);
3446                if(testHasLiveConversion) {
3447                    method.beforeJoinPoint(test);
3448                }
3449            }
3450        } else if (test != null) {
3451            if (testHasLiveConversion) {
3452                emitBranch(test.getExpression(), body.getEntryLabel(), true);
3453                method.beforeJoinPoint(test);
3454                method._goto(breakLabel);
3455            } else {
3456                emitBranch(test.getExpression(), breakLabel, false);
3457            }
3458        }
3459
3460        body.accept(this);
3461        if(repeatLabel != continueLabel) {
3462            emitContinueLabel(continueLabel, liveLocalsOnContinue);
3463        }
3464
3465        if (loopNode.hasPerIterationScope() && lc.getCurrentBlock().needsScope()) {
3466            // ES6 for loops with LET init need a new scope for each iteration. We just create a shallow copy here.
3467            method.loadCompilerConstant(SCOPE);
3468            method.invoke(virtualCallNoLookup(ScriptObject.class, "copy", ScriptObject.class));
3469            method.storeCompilerConstant(SCOPE);
3470        }
3471
3472        if(method.isReachable()) {
3473            if(modify != null) {
3474                lineNumber(loopNode);
3475                loadAndDiscard(modify);
3476                method.beforeJoinPoint(modify);
3477            }
3478            method._goto(repeatLabel);
3479        }
3480
3481        method.breakLabel(breakLabel, liveLocalsOnBreak);
3482    }
3483
3484    private void emitContinueLabel(final Label continueLabel, final int liveLocals) {
3485        final boolean reachable = method.isReachable();
3486        method.breakLabel(continueLabel, liveLocals);
3487        // If we reach here only through a continue statement (e.g. body does not exit normally) then the
3488        // continueLabel can have extra non-temp symbols (e.g. exception from a try/catch contained in the body). We
3489        // must make sure those are thrown away.
3490        if(!reachable) {
3491            method.undefineLocalVariables(lc.getUsedSlotCount(), false);
3492        }
3493    }
3494
3495    private void enterDoWhile(final WhileNode whileNode) {
3496        final int liveLocalsOnContinueOrBreak = method.getUsedSlotsWithLiveTemporaries();
3497        method.beforeJoinPoint(whileNode);
3498
3499        final Block body = whileNode.getBody();
3500        body.accept(this);
3501
3502        emitContinueLabel(whileNode.getContinueLabel(), liveLocalsOnContinueOrBreak);
3503        if(method.isReachable()) {
3504            lineNumber(whileNode);
3505            final JoinPredecessorExpression test = whileNode.getTest();
3506            final Label bodyEntryLabel = body.getEntryLabel();
3507            final boolean testHasLiveConversion = LocalVariableConversion.hasLiveConversion(test);
3508            if(Expression.isAlwaysFalse(test)) {
3509                loadAndDiscard(test);
3510                if(testHasLiveConversion) {
3511                    method.beforeJoinPoint(test);
3512                }
3513            } else if(testHasLiveConversion) {
3514                // If we have conversions after the test in do-while, they need to be effected on both branches.
3515                final Label beforeExit = new Label("do_while_preexit");
3516                emitBranch(test.getExpression(), beforeExit, false);
3517                method.beforeJoinPoint(test);
3518                method._goto(bodyEntryLabel);
3519                method.label(beforeExit);
3520                method.beforeJoinPoint(test);
3521            } else {
3522                emitBranch(test.getExpression(), bodyEntryLabel, true);
3523            }
3524        }
3525        method.breakLabel(whileNode.getBreakLabel(), liveLocalsOnContinueOrBreak);
3526    }
3527
3528
3529    @Override
3530    public boolean enterWithNode(final WithNode withNode) {
3531        if(!method.isReachable()) {
3532            return false;
3533        }
3534        enterStatement(withNode);
3535        final Expression expression = withNode.getExpression();
3536        final Block      body       = withNode.getBody();
3537
3538        // It is possible to have a "pathological" case where the with block does not reference *any* identifiers. It's
3539        // pointless, but legal. In that case, if nothing else in the method forced the assignment of a slot to the
3540        // scope object, its' possible that it won't have a slot assigned. In this case we'll only evaluate expression
3541        // for its side effect and visit the body, and not bother opening and closing a WithObject.
3542        final boolean hasScope = method.hasScope();
3543
3544        if (hasScope) {
3545            method.loadCompilerConstant(SCOPE);
3546        }
3547
3548        loadExpressionAsObject(expression);
3549
3550        final Label tryLabel;
3551        if (hasScope) {
3552            // Construct a WithObject if we have a scope
3553            method.invoke(ScriptRuntime.OPEN_WITH);
3554            method.storeCompilerConstant(SCOPE);
3555            tryLabel = new Label("with_try");
3556            method.label(tryLabel);
3557        } else {
3558            // We just loaded the expression for its side effect and to check
3559            // for null or undefined value.
3560            globalCheckObjectCoercible();
3561            tryLabel = null;
3562        }
3563
3564        // Always process body
3565        body.accept(this);
3566
3567        if (hasScope) {
3568            // Ensure we always close the WithObject
3569            final Label endLabel   = new Label("with_end");
3570            final Label catchLabel = new Label("with_catch");
3571            final Label exitLabel  = new Label("with_exit");
3572
3573            method.label(endLabel);
3574            // Somewhat conservatively presume that if the body is not empty, it can throw an exception. In any case,
3575            // we must prevent trying to emit a try-catch for empty range, as it causes a verification error.
3576            final boolean bodyCanThrow = endLabel.isAfter(tryLabel);
3577            if(bodyCanThrow) {
3578                method._try(tryLabel, endLabel, catchLabel);
3579            }
3580
3581            final boolean reachable = method.isReachable();
3582            if(reachable) {
3583                popScope();
3584                if(bodyCanThrow) {
3585                    method._goto(exitLabel);
3586                }
3587            }
3588
3589            if(bodyCanThrow) {
3590                method._catch(catchLabel);
3591                popScopeException();
3592                method.athrow();
3593                if(reachable) {
3594                    method.label(exitLabel);
3595                }
3596            }
3597        }
3598        return false;
3599    }
3600
3601    private void loadADD(final UnaryNode unaryNode, final TypeBounds resultBounds) {
3602        loadExpression(unaryNode.getExpression(), resultBounds.booleanToInt().notWiderThan(Type.NUMBER));
3603        if(method.peekType() == Type.BOOLEAN) {
3604            // It's a no-op in bytecode, but we must make sure it is treated as an int for purposes of type signatures
3605            method.convert(Type.INT);
3606        }
3607    }
3608
3609    private void loadBIT_NOT(final UnaryNode unaryNode) {
3610        loadExpression(unaryNode.getExpression(), TypeBounds.INT).load(-1).xor();
3611    }
3612
3613    private void loadDECINC(final UnaryNode unaryNode) {
3614        final Expression operand     = unaryNode.getExpression();
3615        final Type       type        = unaryNode.getType();
3616        final TypeBounds typeBounds  = new TypeBounds(type, Type.NUMBER);
3617        final TokenType  tokenType   = unaryNode.tokenType();
3618        final boolean    isPostfix   = tokenType == TokenType.DECPOSTFIX || tokenType == TokenType.INCPOSTFIX;
3619        final boolean    isIncrement = tokenType == TokenType.INCPREFIX || tokenType == TokenType.INCPOSTFIX;
3620
3621        assert !type.isObject();
3622
3623        new SelfModifyingStore<UnaryNode>(unaryNode, operand) {
3624
3625            private void loadRhs() {
3626                loadExpression(operand, typeBounds, true);
3627            }
3628
3629            @Override
3630            protected void evaluate() {
3631                if(isPostfix) {
3632                    loadRhs();
3633                } else {
3634                    new OptimisticOperation(unaryNode, typeBounds) {
3635                        @Override
3636                        void loadStack() {
3637                            loadRhs();
3638                            loadMinusOne();
3639                        }
3640                        @Override
3641                        void consumeStack() {
3642                            doDecInc(getProgramPoint());
3643                        }
3644                    }.emit(getOptimisticIgnoreCountForSelfModifyingExpression(operand));
3645                }
3646            }
3647
3648            @Override
3649            protected void storeNonDiscard() {
3650                super.storeNonDiscard();
3651                if (isPostfix) {
3652                    new OptimisticOperation(unaryNode, typeBounds) {
3653                        @Override
3654                        void loadStack() {
3655                            loadMinusOne();
3656                        }
3657                        @Override
3658                        void consumeStack() {
3659                            doDecInc(getProgramPoint());
3660                        }
3661                    }.emit(1); // 1 for non-incremented result on the top of the stack pushed in evaluate()
3662                }
3663            }
3664
3665            private void loadMinusOne() {
3666                if (type.isInteger()) {
3667                    method.load(isIncrement ? 1 : -1);
3668                } else {
3669                    method.load(isIncrement ? 1.0 : -1.0);
3670                }
3671            }
3672
3673            private void doDecInc(final int programPoint) {
3674                method.add(programPoint);
3675            }
3676        }.store();
3677    }
3678
3679    private static int getOptimisticIgnoreCountForSelfModifyingExpression(final Expression target) {
3680        return target instanceof AccessNode ? 1 : target instanceof IndexNode ? 2 : 0;
3681    }
3682
3683    private void loadAndDiscard(final Expression expr) {
3684        // TODO: move checks for discarding to actual expression load code (e.g. as we do with void). That way we might
3685        // be able to eliminate even more checks.
3686        if(expr instanceof PrimitiveLiteralNode | isLocalVariable(expr)) {
3687            assert !lc.isCurrentDiscard(expr);
3688            // Don't bother evaluating expressions without side effects. Typical usage is "void 0" for reliably generating
3689            // undefined.
3690            return;
3691        }
3692
3693        lc.pushDiscard(expr);
3694        loadExpression(expr, TypeBounds.UNBOUNDED);
3695        if (lc.popDiscardIfCurrent(expr)) {
3696            assert !expr.isAssignment();
3697            // NOTE: if we had a way to load with type void, we could avoid popping
3698            method.pop();
3699        }
3700    }
3701
3702    /**
3703     * Loads the expression with the specified type bounds, but if the parent expression is the current discard,
3704     * then instead loads and discards the expression.
3705     * @param parent the parent expression that's tested for being the current discard
3706     * @param expr the expression that's either normally loaded or discard-loaded
3707     * @param resultBounds result bounds for when loading the expression normally
3708     */
3709    private void loadMaybeDiscard(final Expression parent, final Expression expr, final TypeBounds resultBounds) {
3710        loadMaybeDiscard(lc.popDiscardIfCurrent(parent), expr, resultBounds);
3711    }
3712
3713    /**
3714     * Loads the expression with the specified type bounds, or loads and discards the expression, depending on the
3715     * value of the discard flag. Useful as a helper for expressions with control flow where you often can't combine
3716     * testing for being the current discard and loading the subexpressions.
3717     * @param discard if true, the expression is loaded and discarded
3718     * @param expr the expression that's either normally loaded or discard-loaded
3719     * @param resultBounds result bounds for when loading the expression normally
3720     */
3721    private void loadMaybeDiscard(final boolean discard, final Expression expr, final TypeBounds resultBounds) {
3722        if (discard) {
3723            loadAndDiscard(expr);
3724        } else {
3725            loadExpression(expr, resultBounds);
3726        }
3727    }
3728
3729    private void loadNEW(final UnaryNode unaryNode) {
3730        final CallNode callNode = (CallNode)unaryNode.getExpression();
3731        final List<Expression> args   = callNode.getArgs();
3732
3733        final Expression func = callNode.getFunction();
3734        // Load function reference.
3735        loadExpressionAsObject(func); // must detect type error
3736
3737        method.dynamicNew(1 + loadArgs(args), getCallSiteFlags(), func.toString(false));
3738    }
3739
3740    private void loadNOT(final UnaryNode unaryNode) {
3741        final Expression expr = unaryNode.getExpression();
3742        if(expr instanceof UnaryNode && expr.isTokenType(TokenType.NOT)) {
3743            // !!x is idiomatic boolean cast in JavaScript
3744            loadExpressionAsBoolean(((UnaryNode)expr).getExpression());
3745        } else {
3746            final Label trueLabel  = new Label("true");
3747            final Label afterLabel = new Label("after");
3748
3749            emitBranch(expr, trueLabel, true);
3750            method.load(true);
3751            method._goto(afterLabel);
3752            method.label(trueLabel);
3753            method.load(false);
3754            method.label(afterLabel);
3755        }
3756    }
3757
3758    private void loadSUB(final UnaryNode unaryNode, final TypeBounds resultBounds) {
3759        final Type type = unaryNode.getType();
3760        assert type.isNumeric();
3761        final TypeBounds numericBounds = resultBounds.booleanToInt();
3762        new OptimisticOperation(unaryNode, numericBounds) {
3763            @Override
3764            void loadStack() {
3765                final Expression expr = unaryNode.getExpression();
3766                loadExpression(expr, numericBounds.notWiderThan(Type.NUMBER));
3767            }
3768            @Override
3769            void consumeStack() {
3770                // Must do an explicit conversion to the operation's type when it's double so that we correctly handle
3771                // negation of an int 0 to a double -0. With this, we get the correct negation of a local variable after
3772                // it deoptimized, e.g. "iload_2; i2d; dneg". Without this, we get "iload_2; ineg; i2d".
3773                if(type.isNumber()) {
3774                    method.convert(type);
3775                }
3776                method.neg(getProgramPoint());
3777            }
3778        }.emit();
3779    }
3780
3781    public void loadVOID(final UnaryNode unaryNode, final TypeBounds resultBounds) {
3782        loadAndDiscard(unaryNode.getExpression());
3783        if (!lc.popDiscardIfCurrent(unaryNode)) {
3784            method.loadUndefined(resultBounds.widest);
3785        }
3786    }
3787
3788    public void loadADD(final BinaryNode binaryNode, final TypeBounds resultBounds) {
3789        new OptimisticOperation(binaryNode, resultBounds) {
3790            @Override
3791            void loadStack() {
3792                final TypeBounds operandBounds;
3793                final boolean isOptimistic = isValid(getProgramPoint());
3794                boolean forceConversionSeparation = false;
3795                if(isOptimistic) {
3796                    operandBounds = new TypeBounds(binaryNode.getType(), Type.OBJECT);
3797                } else {
3798                    // Non-optimistic, non-FP +. Allow it to overflow.
3799                    final Type widestOperationType = binaryNode.getWidestOperationType();
3800                    operandBounds = new TypeBounds(Type.narrowest(binaryNode.getWidestOperandType(), resultBounds.widest), widestOperationType);
3801                    forceConversionSeparation = widestOperationType.narrowerThan(resultBounds.widest);
3802                }
3803                loadBinaryOperands(binaryNode.lhs(), binaryNode.rhs(), operandBounds, false, forceConversionSeparation);
3804            }
3805
3806            @Override
3807            void consumeStack() {
3808                method.add(getProgramPoint());
3809            }
3810        }.emit();
3811    }
3812
3813    private void loadAND_OR(final BinaryNode binaryNode, final TypeBounds resultBounds, final boolean isAnd) {
3814        final Type narrowestOperandType = Type.widestReturnType(binaryNode.lhs().getType(), binaryNode.rhs().getType());
3815
3816        final boolean isCurrentDiscard = lc.popDiscardIfCurrent(binaryNode);
3817
3818        final Label skip = new Label("skip");
3819        if(narrowestOperandType == Type.BOOLEAN) {
3820            // optimize all-boolean logical expressions
3821            final Label onTrue = new Label("andor_true");
3822            emitBranch(binaryNode, onTrue, true);
3823            if (isCurrentDiscard) {
3824                method.label(onTrue);
3825            } else {
3826                method.load(false);
3827                method._goto(skip);
3828                method.label(onTrue);
3829                method.load(true);
3830                method.label(skip);
3831            }
3832            return;
3833        }
3834
3835        final TypeBounds outBounds = resultBounds.notNarrowerThan(narrowestOperandType);
3836        final JoinPredecessorExpression lhs = (JoinPredecessorExpression)binaryNode.lhs();
3837        final boolean lhsConvert = LocalVariableConversion.hasLiveConversion(lhs);
3838        final Label evalRhs = lhsConvert ? new Label("eval_rhs") : null;
3839
3840        loadExpression(lhs, outBounds);
3841        if (!isCurrentDiscard) {
3842            method.dup();
3843        }
3844        method.convert(Type.BOOLEAN);
3845        if (isAnd) {
3846            if(lhsConvert) {
3847                method.ifne(evalRhs);
3848            } else {
3849                method.ifeq(skip);
3850            }
3851        } else if(lhsConvert) {
3852            method.ifeq(evalRhs);
3853        } else {
3854            method.ifne(skip);
3855        }
3856
3857        if(lhsConvert) {
3858            method.beforeJoinPoint(lhs);
3859            method._goto(skip);
3860            method.label(evalRhs);
3861        }
3862
3863        if (!isCurrentDiscard) {
3864            method.pop();
3865        }
3866        final JoinPredecessorExpression rhs = (JoinPredecessorExpression)binaryNode.rhs();
3867        loadMaybeDiscard(isCurrentDiscard, rhs, outBounds);
3868        method.beforeJoinPoint(rhs);
3869        method.label(skip);
3870    }
3871
3872    private static boolean isLocalVariable(final Expression lhs) {
3873        return lhs instanceof IdentNode && isLocalVariable((IdentNode)lhs);
3874    }
3875
3876    private static boolean isLocalVariable(final IdentNode lhs) {
3877        return lhs.getSymbol().isBytecodeLocal();
3878    }
3879
3880    // NOTE: does not use resultBounds as the assignment is driven by the type of the RHS
3881    private void loadASSIGN(final BinaryNode binaryNode) {
3882        final Expression lhs = binaryNode.lhs();
3883        final Expression rhs = binaryNode.rhs();
3884
3885        final Type rhsType = rhs.getType();
3886        // Detect dead assignments
3887        if(lhs instanceof IdentNode) {
3888            final Symbol symbol = ((IdentNode)lhs).getSymbol();
3889            if(!symbol.isScope() && !symbol.hasSlotFor(rhsType) && lc.popDiscardIfCurrent(binaryNode)) {
3890                loadAndDiscard(rhs);
3891                method.markDeadLocalVariable(symbol);
3892                return;
3893            }
3894        }
3895
3896        new Store<BinaryNode>(binaryNode, lhs) {
3897            @Override
3898            protected void evaluate() {
3899                // NOTE: we're loading with "at least as wide as" so optimistic operations on the right hand side
3900                // remain optimistic, and then explicitly convert to the required type if needed.
3901                loadExpressionAsType(rhs, rhsType);
3902            }
3903        }.store();
3904    }
3905
3906    /**
3907     * Binary self-assignment that can be optimistic: +=, -=, *=, and /=.
3908     */
3909    private abstract class BinaryOptimisticSelfAssignment extends SelfModifyingStore<BinaryNode> {
3910
3911        /**
3912         * Constructor
3913         *
3914         * @param node the assign op node
3915         */
3916        BinaryOptimisticSelfAssignment(final BinaryNode node) {
3917            super(node, node.lhs());
3918        }
3919
3920        protected abstract void op(OptimisticOperation oo);
3921
3922        @Override
3923        protected void evaluate() {
3924            final Expression lhs = assignNode.lhs();
3925            final Expression rhs = assignNode.rhs();
3926            final Type widestOperationType = assignNode.getWidestOperationType();
3927            final TypeBounds bounds = new TypeBounds(assignNode.getType(), widestOperationType);
3928            new OptimisticOperation(assignNode, bounds) {
3929                @Override
3930                void loadStack() {
3931                    final boolean forceConversionSeparation;
3932                    if (isValid(getProgramPoint()) || widestOperationType == Type.NUMBER) {
3933                        forceConversionSeparation = false;
3934                    } else {
3935                        final Type operandType = Type.widest(booleanToInt(objectToNumber(lhs.getType())), booleanToInt(objectToNumber(rhs.getType())));
3936                        forceConversionSeparation = operandType.narrowerThan(widestOperationType);
3937                    }
3938                    loadBinaryOperands(lhs, rhs, bounds, true, forceConversionSeparation);
3939                }
3940                @Override
3941                void consumeStack() {
3942                    op(this);
3943                }
3944            }.emit(getOptimisticIgnoreCountForSelfModifyingExpression(lhs));
3945            method.convert(assignNode.getType());
3946        }
3947    }
3948
3949    /**
3950     * Non-optimistic binary self-assignment operation. Basically, everything except +=, -=, *=, and /=.
3951     */
3952    private abstract class BinarySelfAssignment extends SelfModifyingStore<BinaryNode> {
3953        BinarySelfAssignment(final BinaryNode node) {
3954            super(node, node.lhs());
3955        }
3956
3957        protected abstract void op();
3958
3959        @Override
3960        protected void evaluate() {
3961            loadBinaryOperands(assignNode.lhs(), assignNode.rhs(), TypeBounds.UNBOUNDED.notWiderThan(assignNode.getWidestOperandType()), true, false);
3962            op();
3963        }
3964    }
3965
3966    private void loadASSIGN_ADD(final BinaryNode binaryNode) {
3967        new BinaryOptimisticSelfAssignment(binaryNode) {
3968            @Override
3969            protected void op(final OptimisticOperation oo) {
3970                assert !(binaryNode.getType().isObject() && oo.isOptimistic);
3971                method.add(oo.getProgramPoint());
3972            }
3973        }.store();
3974    }
3975
3976    private void loadASSIGN_BIT_AND(final BinaryNode binaryNode) {
3977        new BinarySelfAssignment(binaryNode) {
3978            @Override
3979            protected void op() {
3980                method.and();
3981            }
3982        }.store();
3983    }
3984
3985    private void loadASSIGN_BIT_OR(final BinaryNode binaryNode) {
3986        new BinarySelfAssignment(binaryNode) {
3987            @Override
3988            protected void op() {
3989                method.or();
3990            }
3991        }.store();
3992    }
3993
3994    private void loadASSIGN_BIT_XOR(final BinaryNode binaryNode) {
3995        new BinarySelfAssignment(binaryNode) {
3996            @Override
3997            protected void op() {
3998                method.xor();
3999            }
4000        }.store();
4001    }
4002
4003    private void loadASSIGN_DIV(final BinaryNode binaryNode) {
4004        new BinaryOptimisticSelfAssignment(binaryNode) {
4005            @Override
4006            protected void op(final OptimisticOperation oo) {
4007                method.div(oo.getProgramPoint());
4008            }
4009        }.store();
4010    }
4011
4012    private void loadASSIGN_MOD(final BinaryNode binaryNode) {
4013        new BinaryOptimisticSelfAssignment(binaryNode) {
4014            @Override
4015            protected void op(final OptimisticOperation oo) {
4016                method.rem(oo.getProgramPoint());
4017            }
4018        }.store();
4019    }
4020
4021    private void loadASSIGN_MUL(final BinaryNode binaryNode) {
4022        new BinaryOptimisticSelfAssignment(binaryNode) {
4023            @Override
4024            protected void op(final OptimisticOperation oo) {
4025                method.mul(oo.getProgramPoint());
4026            }
4027        }.store();
4028    }
4029
4030    private void loadASSIGN_SAR(final BinaryNode binaryNode) {
4031        new BinarySelfAssignment(binaryNode) {
4032            @Override
4033            protected void op() {
4034                method.sar();
4035            }
4036        }.store();
4037    }
4038
4039    private void loadASSIGN_SHL(final BinaryNode binaryNode) {
4040        new BinarySelfAssignment(binaryNode) {
4041            @Override
4042            protected void op() {
4043                method.shl();
4044            }
4045        }.store();
4046    }
4047
4048    private void loadASSIGN_SHR(final BinaryNode binaryNode) {
4049        new SelfModifyingStore<BinaryNode>(binaryNode, binaryNode.lhs()) {
4050            @Override
4051            protected void evaluate() {
4052                new OptimisticOperation(assignNode, new TypeBounds(Type.INT, Type.NUMBER)) {
4053                    @Override
4054                    void loadStack() {
4055                        assert assignNode.getWidestOperandType() == Type.INT;
4056                        if (isRhsZero(binaryNode)) {
4057                            loadExpressionAsType(binaryNode.lhs(), Type.INT);
4058                        } else {
4059                            loadBinaryOperands(binaryNode.lhs(), binaryNode.rhs(), TypeBounds.INT, true, false);
4060                            method.shr();
4061                        }
4062                    }
4063
4064                    @Override
4065                    void consumeStack() {
4066                        if (isOptimistic(binaryNode)) {
4067                            toUint32Optimistic(binaryNode.getProgramPoint());
4068                        } else {
4069                            toUint32Double();
4070                        }
4071                    }
4072                }.emit(getOptimisticIgnoreCountForSelfModifyingExpression(binaryNode.lhs()));
4073                method.convert(assignNode.getType());
4074            }
4075        }.store();
4076    }
4077
4078    private void doSHR(final BinaryNode binaryNode) {
4079        new OptimisticOperation(binaryNode, new TypeBounds(Type.INT, Type.NUMBER)) {
4080            @Override
4081            void loadStack() {
4082                if (isRhsZero(binaryNode)) {
4083                    loadExpressionAsType(binaryNode.lhs(), Type.INT);
4084                } else {
4085                    loadBinaryOperands(binaryNode);
4086                    method.shr();
4087                }
4088            }
4089
4090            @Override
4091            void consumeStack() {
4092                if (isOptimistic(binaryNode)) {
4093                    toUint32Optimistic(binaryNode.getProgramPoint());
4094                } else {
4095                    toUint32Double();
4096                }
4097            }
4098        }.emit();
4099
4100    }
4101
4102    private void toUint32Optimistic(final int programPoint) {
4103        method.load(programPoint);
4104        JSType.TO_UINT32_OPTIMISTIC.invoke(method);
4105    }
4106
4107    private void toUint32Double() {
4108        JSType.TO_UINT32_DOUBLE.invoke(method);
4109    }
4110
4111    private void loadASSIGN_SUB(final BinaryNode binaryNode) {
4112        new BinaryOptimisticSelfAssignment(binaryNode) {
4113            @Override
4114            protected void op(final OptimisticOperation oo) {
4115                method.sub(oo.getProgramPoint());
4116            }
4117        }.store();
4118    }
4119
4120    /**
4121     * Helper class for binary arithmetic ops
4122     */
4123    private abstract class BinaryArith {
4124        protected abstract void op(int programPoint);
4125
4126        protected void evaluate(final BinaryNode node, final TypeBounds resultBounds) {
4127            final TypeBounds numericBounds = resultBounds.booleanToInt().objectToNumber();
4128            new OptimisticOperation(node, numericBounds) {
4129                @Override
4130                void loadStack() {
4131                    final TypeBounds operandBounds;
4132                    boolean forceConversionSeparation = false;
4133                    if(numericBounds.narrowest == Type.NUMBER) {
4134                        // Result should be double always. Propagate it into the operands so we don't have lots of I2D
4135                        // and L2D after operand evaluation.
4136                        assert numericBounds.widest == Type.NUMBER;
4137                        operandBounds = numericBounds;
4138                    } else {
4139                        final boolean isOptimistic = isValid(getProgramPoint());
4140                        if(isOptimistic || node.isTokenType(TokenType.DIV) || node.isTokenType(TokenType.MOD)) {
4141                            operandBounds = new TypeBounds(node.getType(), Type.NUMBER);
4142                        } else {
4143                            // Non-optimistic, non-FP subtraction or multiplication. Allow them to overflow.
4144                            operandBounds = new TypeBounds(Type.narrowest(node.getWidestOperandType(),
4145                                    numericBounds.widest), Type.NUMBER);
4146                            forceConversionSeparation = true;
4147                        }
4148                    }
4149                    loadBinaryOperands(node.lhs(), node.rhs(), operandBounds, false, forceConversionSeparation);
4150                }
4151
4152                @Override
4153                void consumeStack() {
4154                    op(getProgramPoint());
4155                }
4156            }.emit();
4157        }
4158    }
4159
4160    private void loadBIT_AND(final BinaryNode binaryNode) {
4161        loadBinaryOperands(binaryNode);
4162        method.and();
4163    }
4164
4165    private void loadBIT_OR(final BinaryNode binaryNode) {
4166        // Optimize x|0 to (int)x
4167        if (isRhsZero(binaryNode)) {
4168            loadExpressionAsType(binaryNode.lhs(), Type.INT);
4169        } else {
4170            loadBinaryOperands(binaryNode);
4171            method.or();
4172        }
4173    }
4174
4175    private static boolean isRhsZero(final BinaryNode binaryNode) {
4176        final Expression rhs = binaryNode.rhs();
4177        return rhs instanceof LiteralNode && INT_ZERO.equals(((LiteralNode<?>)rhs).getValue());
4178    }
4179
4180    private void loadBIT_XOR(final BinaryNode binaryNode) {
4181        loadBinaryOperands(binaryNode);
4182        method.xor();
4183    }
4184
4185    private void loadCOMMARIGHT(final BinaryNode binaryNode, final TypeBounds resultBounds) {
4186        loadAndDiscard(binaryNode.lhs());
4187        loadMaybeDiscard(binaryNode, binaryNode.rhs(), resultBounds);
4188    }
4189
4190    private void loadCOMMALEFT(final BinaryNode binaryNode, final TypeBounds resultBounds) {
4191        loadMaybeDiscard(binaryNode, binaryNode.lhs(), resultBounds);
4192        loadAndDiscard(binaryNode.rhs());
4193    }
4194
4195    private void loadDIV(final BinaryNode binaryNode, final TypeBounds resultBounds) {
4196        new BinaryArith() {
4197            @Override
4198            protected void op(final int programPoint) {
4199                method.div(programPoint);
4200            }
4201        }.evaluate(binaryNode, resultBounds);
4202    }
4203
4204    private void loadCmp(final BinaryNode binaryNode, final Condition cond) {
4205        loadComparisonOperands(binaryNode);
4206
4207        final Label trueLabel  = new Label("trueLabel");
4208        final Label afterLabel = new Label("skip");
4209
4210        method.conditionalJump(cond, trueLabel);
4211
4212        method.load(Boolean.FALSE);
4213        method._goto(afterLabel);
4214        method.label(trueLabel);
4215        method.load(Boolean.TRUE);
4216        method.label(afterLabel);
4217    }
4218
4219    private void loadMOD(final BinaryNode binaryNode, final TypeBounds resultBounds) {
4220        new BinaryArith() {
4221            @Override
4222            protected void op(final int programPoint) {
4223                method.rem(programPoint);
4224            }
4225        }.evaluate(binaryNode, resultBounds);
4226    }
4227
4228    private void loadMUL(final BinaryNode binaryNode, final TypeBounds resultBounds) {
4229        new BinaryArith() {
4230            @Override
4231            protected void op(final int programPoint) {
4232                method.mul(programPoint);
4233            }
4234        }.evaluate(binaryNode, resultBounds);
4235    }
4236
4237    private void loadSAR(final BinaryNode binaryNode) {
4238        loadBinaryOperands(binaryNode);
4239        method.sar();
4240    }
4241
4242    private void loadSHL(final BinaryNode binaryNode) {
4243        loadBinaryOperands(binaryNode);
4244        method.shl();
4245    }
4246
4247    private void loadSHR(final BinaryNode binaryNode) {
4248        doSHR(binaryNode);
4249    }
4250
4251    private void loadSUB(final BinaryNode binaryNode, final TypeBounds resultBounds) {
4252        new BinaryArith() {
4253            @Override
4254            protected void op(final int programPoint) {
4255                method.sub(programPoint);
4256            }
4257        }.evaluate(binaryNode, resultBounds);
4258    }
4259
4260    @Override
4261    public boolean enterLabelNode(final LabelNode labelNode) {
4262        labeledBlockBreakLiveLocals.push(lc.getUsedSlotCount());
4263        return true;
4264    }
4265
4266    @Override
4267    protected boolean enterDefault(final Node node) {
4268        throw new AssertionError("Code generator entered node of type " + node.getClass().getName());
4269    }
4270
4271    private void loadTernaryNode(final TernaryNode ternaryNode, final TypeBounds resultBounds) {
4272        final Expression test = ternaryNode.getTest();
4273        final JoinPredecessorExpression trueExpr  = ternaryNode.getTrueExpression();
4274        final JoinPredecessorExpression falseExpr = ternaryNode.getFalseExpression();
4275
4276        final Label falseLabel = new Label("ternary_false");
4277        final Label exitLabel  = new Label("ternary_exit");
4278
4279        final Type outNarrowest = Type.narrowest(resultBounds.widest, Type.generic(Type.widestReturnType(trueExpr.getType(), falseExpr.getType())));
4280        final TypeBounds outBounds = resultBounds.notNarrowerThan(outNarrowest);
4281
4282        emitBranch(test, falseLabel, false);
4283
4284        final boolean isCurrentDiscard = lc.popDiscardIfCurrent(ternaryNode);
4285        loadMaybeDiscard(isCurrentDiscard, trueExpr.getExpression(), outBounds);
4286        assert isCurrentDiscard || Type.generic(method.peekType()) == outBounds.narrowest;
4287        method.beforeJoinPoint(trueExpr);
4288        method._goto(exitLabel);
4289        method.label(falseLabel);
4290        loadMaybeDiscard(isCurrentDiscard, falseExpr.getExpression(), outBounds);
4291        assert isCurrentDiscard || Type.generic(method.peekType()) == outBounds.narrowest;
4292        method.beforeJoinPoint(falseExpr);
4293        method.label(exitLabel);
4294    }
4295
4296    /**
4297     * Generate all shared scope calls generated during codegen.
4298     */
4299    void generateScopeCalls() {
4300        for (final SharedScopeCall scopeAccess : lc.getScopeCalls()) {
4301            scopeAccess.generateScopeCall();
4302        }
4303    }
4304
4305    /**
4306     * Debug code used to print symbols
4307     *
4308     * @param block the block we are in
4309     * @param function the function we are in
4310     * @param ident identifier for block or function where applicable
4311     */
4312    private void printSymbols(final Block block, final FunctionNode function, final String ident) {
4313        if (compiler.getScriptEnvironment()._print_symbols || function.getFlag(FunctionNode.IS_PRINT_SYMBOLS)) {
4314            final PrintWriter out = compiler.getScriptEnvironment().getErr();
4315            out.println("[BLOCK in '" + ident + "']");
4316            if (!block.printSymbols(out)) {
4317                out.println("<no symbols>");
4318            }
4319            out.println();
4320        }
4321    }
4322
4323
4324    /**
4325     * The difference between a store and a self modifying store is that
4326     * the latter may load part of the target on the stack, e.g. the base
4327     * of an AccessNode or the base and index of an IndexNode. These are used
4328     * both as target and as an extra source. Previously it was problematic
4329     * for self modifying stores if the target/lhs didn't belong to one
4330     * of three trivial categories: IdentNode, AcessNodes, IndexNodes. In that
4331     * case it was evaluated and tagged as "resolved", which meant at the second
4332     * time the lhs of this store was read (e.g. in a = a (second) + b for a += b,
4333     * it would be evaluated to a nop in the scope and cause stack underflow
4334     *
4335     * see NASHORN-703
4336     *
4337     * @param <T>
4338     */
4339    private abstract class SelfModifyingStore<T extends Expression> extends Store<T> {
4340        protected SelfModifyingStore(final T assignNode, final Expression target) {
4341            super(assignNode, target);
4342        }
4343
4344        @Override
4345        protected boolean isSelfModifying() {
4346            return true;
4347        }
4348    }
4349
4350    /**
4351     * Helper class to generate stores
4352     */
4353    private abstract class Store<T extends Expression> {
4354
4355        /** An assignment node, e.g. x += y */
4356        protected final T assignNode;
4357
4358        /** The target node to store to, e.g. x */
4359        private final Expression target;
4360
4361        /** How deep on the stack do the arguments go if this generates an indy call */
4362        private int depth;
4363
4364        /** If we have too many arguments, we need temporary storage, this is stored in 'quick' */
4365        private IdentNode quick;
4366
4367        /**
4368         * Constructor
4369         *
4370         * @param assignNode the node representing the whole assignment
4371         * @param target     the target node of the assignment (destination)
4372         */
4373        protected Store(final T assignNode, final Expression target) {
4374            this.assignNode = assignNode;
4375            this.target = target;
4376        }
4377
4378        /**
4379         * Constructor
4380         *
4381         * @param assignNode the node representing the whole assignment
4382         */
4383        protected Store(final T assignNode) {
4384            this(assignNode, assignNode);
4385        }
4386
4387        /**
4388         * Is this a self modifying store operation, e.g. *= or ++
4389         * @return true if self modifying store
4390         */
4391        protected boolean isSelfModifying() {
4392            return false;
4393        }
4394
4395        private void prologue() {
4396            /*
4397             * This loads the parts of the target, e.g base and index. they are kept
4398             * on the stack throughout the store and used at the end to execute it
4399             */
4400
4401            target.accept(new SimpleNodeVisitor() {
4402                @Override
4403                public boolean enterIdentNode(final IdentNode node) {
4404                    if (node.getSymbol().isScope()) {
4405                        method.loadCompilerConstant(SCOPE);
4406                        depth += Type.SCOPE.getSlots();
4407                        assert depth == 1;
4408                    }
4409                    return false;
4410                }
4411
4412                private void enterBaseNode() {
4413                    assert target instanceof BaseNode : "error - base node " + target + " must be instanceof BaseNode";
4414                    final BaseNode   baseNode = (BaseNode)target;
4415                    final Expression base     = baseNode.getBase();
4416
4417                    loadExpressionAsObject(base);
4418                    depth += Type.OBJECT.getSlots();
4419                    assert depth == 1;
4420
4421                    if (isSelfModifying()) {
4422                        method.dup();
4423                    }
4424                }
4425
4426                @Override
4427                public boolean enterAccessNode(final AccessNode node) {
4428                    enterBaseNode();
4429                    return false;
4430                }
4431
4432                @Override
4433                public boolean enterIndexNode(final IndexNode node) {
4434                    enterBaseNode();
4435
4436                    final Expression index = node.getIndex();
4437                    if (!index.getType().isNumeric()) {
4438                        // could be boolean here as well
4439                        loadExpressionAsObject(index);
4440                    } else {
4441                        loadExpressionUnbounded(index);
4442                    }
4443                    depth += index.getType().getSlots();
4444
4445                    if (isSelfModifying()) {
4446                        //convert "base base index" to "base index base index"
4447                        method.dup(1);
4448                    }
4449
4450                    return false;
4451                }
4452
4453            });
4454        }
4455
4456        /**
4457         * Generates an extra local variable, always using the same slot, one that is available after the end of the
4458         * frame.
4459         *
4460         * @param type the type of the variable
4461         *
4462         * @return the quick variable
4463         */
4464        private IdentNode quickLocalVariable(final Type type) {
4465            final String name = lc.getCurrentFunction().uniqueName(QUICK_PREFIX.symbolName());
4466            final Symbol symbol = new Symbol(name, IS_INTERNAL | HAS_SLOT);
4467            symbol.setHasSlotFor(type);
4468            symbol.setFirstSlot(lc.quickSlot(type));
4469
4470            final IdentNode quickIdent = IdentNode.createInternalIdentifier(symbol).setType(type);
4471
4472            return quickIdent;
4473        }
4474
4475        // store the result that "lives on" after the op, e.g. "i" in i++ postfix.
4476        protected void storeNonDiscard() {
4477            if (lc.popDiscardIfCurrent(assignNode)) {
4478                assert assignNode.isAssignment();
4479                return;
4480            }
4481
4482            if (method.dup(depth) == null) {
4483                method.dup();
4484                final Type quickType = method.peekType();
4485                this.quick = quickLocalVariable(quickType);
4486                final Symbol quickSymbol = quick.getSymbol();
4487                method.storeTemp(quickType, quickSymbol.getFirstSlot());
4488            }
4489        }
4490
4491        private void epilogue() {
4492            /**
4493             * Take the original target args from the stack and use them
4494             * together with the value to be stored to emit the store code
4495             *
4496             * The case that targetSymbol is in scope (!hasSlot) and we actually
4497             * need to do a conversion on non-equivalent types exists, but is
4498             * very rare. See for example test/script/basic/access-specializer.js
4499             */
4500            target.accept(new SimpleNodeVisitor() {
4501                @Override
4502                protected boolean enterDefault(final Node node) {
4503                    throw new AssertionError("Unexpected node " + node + " in store epilogue");
4504                }
4505
4506                @Override
4507                public boolean enterIdentNode(final IdentNode node) {
4508                    final Symbol symbol = node.getSymbol();
4509                    assert symbol != null;
4510                    if (symbol.isScope()) {
4511                        final int flags = getScopeCallSiteFlags(symbol) | (node.isDeclaredHere() ? CALLSITE_DECLARE : 0);
4512                        if (isFastScope(symbol)) {
4513                            storeFastScopeVar(symbol, flags);
4514                        } else {
4515                            method.dynamicSet(node.getName(), flags, false);
4516                        }
4517                    } else {
4518                        final Type storeType = assignNode.getType();
4519                        assert storeType != Type.LONG;
4520                        if (symbol.hasSlotFor(storeType)) {
4521                            // Only emit a convert for a store known to be live; converts for dead stores can
4522                            // give us an unnecessary ClassCastException.
4523                            method.convert(storeType);
4524                        }
4525                        storeIdentWithCatchConversion(node, storeType);
4526                    }
4527                    return false;
4528
4529                }
4530
4531                @Override
4532                public boolean enterAccessNode(final AccessNode node) {
4533                    method.dynamicSet(node.getProperty(), getCallSiteFlags(), node.isIndex());
4534                    return false;
4535                }
4536
4537                @Override
4538                public boolean enterIndexNode(final IndexNode node) {
4539                    method.dynamicSetIndex(getCallSiteFlags());
4540                    return false;
4541                }
4542            });
4543
4544
4545            // whatever is on the stack now is the final answer
4546        }
4547
4548        protected abstract void evaluate();
4549
4550        void store() {
4551            if (target instanceof IdentNode) {
4552                checkTemporalDeadZone((IdentNode)target);
4553            }
4554            prologue();
4555            evaluate(); // leaves an operation of whatever the operationType was on the stack
4556            storeNonDiscard();
4557            epilogue();
4558            if (quick != null) {
4559                method.load(quick);
4560            }
4561        }
4562    }
4563
4564    private void newFunctionObject(final FunctionNode functionNode, final boolean addInitializer) {
4565        assert lc.peek() == functionNode;
4566
4567        final RecompilableScriptFunctionData data = compiler.getScriptFunctionData(functionNode.getId());
4568
4569        if (functionNode.isProgram() && !compiler.isOnDemandCompilation()) {
4570            final MethodEmitter createFunction = functionNode.getCompileUnit().getClassEmitter().method(
4571                    EnumSet.of(Flag.PUBLIC, Flag.STATIC), CREATE_PROGRAM_FUNCTION.symbolName(),
4572                    ScriptFunction.class, ScriptObject.class);
4573            createFunction.begin();
4574            loadConstantsAndIndex(data, createFunction);
4575            createFunction.load(SCOPE_TYPE, 0);
4576            createFunction.invoke(CREATE_FUNCTION_OBJECT);
4577            createFunction._return();
4578            createFunction.end();
4579        }
4580
4581        if (addInitializer && !compiler.isOnDemandCompilation()) {
4582            functionNode.getCompileUnit().addFunctionInitializer(data, functionNode);
4583        }
4584
4585        // We don't emit a ScriptFunction on stack for the outermost compiled function (as there's no code being
4586        // generated in its outer context that'd need it as a callee).
4587        if (lc.getOutermostFunction() == functionNode) {
4588            return;
4589        }
4590
4591        loadConstantsAndIndex(data, method);
4592
4593        if (functionNode.needsParentScope()) {
4594            method.loadCompilerConstant(SCOPE);
4595            method.invoke(CREATE_FUNCTION_OBJECT);
4596        } else {
4597            method.invoke(CREATE_FUNCTION_OBJECT_NO_SCOPE);
4598        }
4599    }
4600
4601    // calls on Global class.
4602    private MethodEmitter globalInstance() {
4603        return method.invokestatic(GLOBAL_OBJECT, "instance", "()L" + GLOBAL_OBJECT + ';');
4604    }
4605
4606    private MethodEmitter globalAllocateArguments() {
4607        return method.invokestatic(GLOBAL_OBJECT, "allocateArguments", methodDescriptor(ScriptObject.class, Object[].class, Object.class, int.class));
4608    }
4609
4610    private MethodEmitter globalNewRegExp() {
4611        return method.invokestatic(GLOBAL_OBJECT, "newRegExp", methodDescriptor(Object.class, String.class, String.class));
4612    }
4613
4614    private MethodEmitter globalRegExpCopy() {
4615        return method.invokestatic(GLOBAL_OBJECT, "regExpCopy", methodDescriptor(Object.class, Object.class));
4616    }
4617
4618    private MethodEmitter globalAllocateArray(final ArrayType type) {
4619        //make sure the native array is treated as an array type
4620        return method.invokestatic(GLOBAL_OBJECT, "allocate", "(" + type.getDescriptor() + ")Ljdk/nashorn/internal/objects/NativeArray;");
4621    }
4622
4623    private MethodEmitter globalIsEval() {
4624        return method.invokestatic(GLOBAL_OBJECT, "isEval", methodDescriptor(boolean.class, Object.class));
4625    }
4626
4627    private MethodEmitter globalReplaceLocationPropertyPlaceholder() {
4628        return method.invokestatic(GLOBAL_OBJECT, "replaceLocationPropertyPlaceholder", methodDescriptor(Object.class, Object.class, Object.class));
4629    }
4630
4631    private MethodEmitter globalCheckObjectCoercible() {
4632        return method.invokestatic(GLOBAL_OBJECT, "checkObjectCoercible", methodDescriptor(void.class, Object.class));
4633    }
4634
4635    private MethodEmitter globalDirectEval() {
4636        return method.invokestatic(GLOBAL_OBJECT, "directEval",
4637                methodDescriptor(Object.class, Object.class, Object.class, Object.class, Object.class, boolean.class));
4638    }
4639
4640    private abstract class OptimisticOperation {
4641        private final boolean isOptimistic;
4642        // expression and optimistic are the same reference
4643        private final Expression expression;
4644        private final Optimistic optimistic;
4645        private final TypeBounds resultBounds;
4646
4647        OptimisticOperation(final Optimistic optimistic, final TypeBounds resultBounds) {
4648            this.optimistic = optimistic;
4649            this.expression = (Expression)optimistic;
4650            this.resultBounds = resultBounds;
4651            this.isOptimistic = isOptimistic(optimistic) && useOptimisticTypes() &&
4652                    // Operation is only effectively optimistic if its type, after being coerced into the result bounds
4653                    // is narrower than the upper bound.
4654                    resultBounds.within(Type.generic(((Expression)optimistic).getType())).narrowerThan(resultBounds.widest);
4655        }
4656
4657        MethodEmitter emit() {
4658            return emit(0);
4659        }
4660
4661        MethodEmitter emit(final int ignoredArgCount) {
4662            final int     programPoint                  = optimistic.getProgramPoint();
4663            final boolean optimisticOrContinuation      = isOptimistic || isContinuationEntryPoint(programPoint);
4664            final boolean currentContinuationEntryPoint = isCurrentContinuationEntryPoint(programPoint);
4665            final int     stackSizeOnEntry              = method.getStackSize() - ignoredArgCount;
4666
4667            // First store the values on the stack opportunistically into local variables. Doing it before loadStack()
4668            // allows us to not have to pop/load any arguments that are pushed onto it by loadStack() in the second
4669            // storeStack().
4670            storeStack(ignoredArgCount, optimisticOrContinuation);
4671
4672            // Now, load the stack
4673            loadStack();
4674
4675            // Now store the values on the stack ultimately into local variables. In vast majority of cases, this is
4676            // (aside from creating the local types map) a no-op, as the first opportunistic stack store will already
4677            // store all variables. However, there can be operations in the loadStack() that invalidate some of the
4678            // stack stores, e.g. in "x[i] = x[++i]", "++i" will invalidate the already stored value for "i". In such
4679            // unfortunate cases this second storeStack() will restore the invariant that everything on the stack is
4680            // stored into a local variable, although at the cost of doing a store/load on the loaded arguments as well.
4681            final int liveLocalsCount = storeStack(method.getStackSize() - stackSizeOnEntry, optimisticOrContinuation);
4682            assert optimisticOrContinuation == (liveLocalsCount != -1);
4683
4684            final Label beginTry;
4685            final Label catchLabel;
4686            final Label afterConsumeStack = isOptimistic || currentContinuationEntryPoint ? new Label("after_consume_stack") : null;
4687            if(isOptimistic) {
4688                beginTry = new Label("try_optimistic");
4689                final String catchLabelName = (afterConsumeStack == null ? "" : afterConsumeStack.toString()) + "_handler";
4690                catchLabel = new Label(catchLabelName);
4691                method.label(beginTry);
4692            } else {
4693                beginTry = catchLabel = null;
4694            }
4695
4696            consumeStack();
4697
4698            if(isOptimistic) {
4699                method._try(beginTry, afterConsumeStack, catchLabel, UnwarrantedOptimismException.class);
4700            }
4701
4702            if(isOptimistic || currentContinuationEntryPoint) {
4703                method.label(afterConsumeStack);
4704
4705                final int[] localLoads = method.getLocalLoadsOnStack(0, stackSizeOnEntry);
4706                assert everyStackValueIsLocalLoad(localLoads) : Arrays.toString(localLoads) + ", " + stackSizeOnEntry + ", " + ignoredArgCount;
4707                final List<Type> localTypesList = method.getLocalVariableTypes();
4708                final int usedLocals = method.getUsedSlotsWithLiveTemporaries();
4709                final List<Type> localTypes = method.getWidestLiveLocals(localTypesList.subList(0, usedLocals));
4710                assert everyLocalLoadIsValid(localLoads, usedLocals) : Arrays.toString(localLoads) + " ~ " + localTypes;
4711
4712                if(isOptimistic) {
4713                    addUnwarrantedOptimismHandlerLabel(localTypes, catchLabel);
4714                }
4715                if(currentContinuationEntryPoint) {
4716                    final ContinuationInfo ci = getContinuationInfo();
4717                    assert ci != null : "no continuation info found for " + lc.getCurrentFunction();
4718                    assert !ci.hasTargetLabel(); // No duplicate program points
4719                    ci.setTargetLabel(afterConsumeStack);
4720                    ci.getHandlerLabel().markAsOptimisticContinuationHandlerFor(afterConsumeStack);
4721                    // Can't rely on targetLabel.stack.localVariableTypes.length, as it can be higher due to effectively
4722                    // dead local variables.
4723                    ci.lvarCount = localTypes.size();
4724                    ci.setStackStoreSpec(localLoads);
4725                    ci.setStackTypes(Arrays.copyOf(method.getTypesFromStack(method.getStackSize()), stackSizeOnEntry));
4726                    assert ci.getStackStoreSpec().length == ci.getStackTypes().length;
4727                    ci.setReturnValueType(method.peekType());
4728                    ci.lineNumber = getLastLineNumber();
4729                    ci.catchLabel = catchLabels.peek();
4730                }
4731            }
4732            return method;
4733        }
4734
4735        /**
4736         * Stores the current contents of the stack into local variables so they are not lost before invoking something that
4737         * can result in an {@code UnwarantedOptimizationException}.
4738         * @param ignoreArgCount the number of topmost arguments on stack to ignore when deciding on the shape of the catch
4739         * block. Those are used in the situations when we could not place the call to {@code storeStack} early enough
4740         * (before emitting code for pushing the arguments that the optimistic call will pop). This is admittedly a
4741         * deficiency in the design of the code generator when it deals with self-assignments and we should probably look
4742         * into fixing it.
4743         * @return types of the significant local variables after the stack was stored (types for local variables used
4744         * for temporary storage of ignored arguments are not returned).
4745         * @param optimisticOrContinuation if false, this method should not execute
4746         * a label for a catch block for the {@code UnwarantedOptimizationException}, suitable for capturing the
4747         * currently live local variables, tailored to their types.
4748         */
4749        private int storeStack(final int ignoreArgCount, final boolean optimisticOrContinuation) {
4750            if(!optimisticOrContinuation) {
4751                return -1; // NOTE: correct value to return is lc.getUsedSlotCount(), but it wouldn't be used anyway
4752            }
4753
4754            final int stackSize = method.getStackSize();
4755            final Type[] stackTypes = method.getTypesFromStack(stackSize);
4756            final int[] localLoadsOnStack = method.getLocalLoadsOnStack(0, stackSize);
4757            final int usedSlots = method.getUsedSlotsWithLiveTemporaries();
4758
4759            final int firstIgnored = stackSize - ignoreArgCount;
4760            // Find the first value on the stack (from the bottom) that is not a load from a local variable.
4761            int firstNonLoad = 0;
4762            while(firstNonLoad < firstIgnored && localLoadsOnStack[firstNonLoad] != Label.Stack.NON_LOAD) {
4763                firstNonLoad++;
4764            }
4765
4766            // Only do the store/load if first non-load is not an ignored argument. Otherwise, do nothing and return
4767            // the number of used slots as the number of live local variables.
4768            if(firstNonLoad >= firstIgnored) {
4769                return usedSlots;
4770            }
4771
4772            // Find the number of new temporary local variables that we need; it's the number of values on the stack that
4773            // are not direct loads of existing local variables.
4774            int tempSlotsNeeded = 0;
4775            for(int i = firstNonLoad; i < stackSize; ++i) {
4776                if(localLoadsOnStack[i] == Label.Stack.NON_LOAD) {
4777                    tempSlotsNeeded += stackTypes[i].getSlots();
4778                }
4779            }
4780
4781            // Ensure all values on the stack that weren't directly loaded from a local variable are stored in a local
4782            // variable. We're starting from highest local variable index, so that in case ignoreArgCount > 0 the ignored
4783            // ones end up at the end of the local variable table.
4784            int lastTempSlot = usedSlots + tempSlotsNeeded;
4785            int ignoreSlotCount = 0;
4786            for(int i = stackSize; i -- > firstNonLoad;) {
4787                final int loadSlot = localLoadsOnStack[i];
4788                if(loadSlot == Label.Stack.NON_LOAD) {
4789                    final Type type = stackTypes[i];
4790                    final int slots = type.getSlots();
4791                    lastTempSlot -= slots;
4792                    if(i >= firstIgnored) {
4793                        ignoreSlotCount += slots;
4794                    }
4795                    method.storeTemp(type, lastTempSlot);
4796                } else {
4797                    method.pop();
4798                }
4799            }
4800            assert lastTempSlot == usedSlots; // used all temporary locals
4801
4802            final List<Type> localTypesList = method.getLocalVariableTypes();
4803
4804            // Load values back on stack.
4805            for(int i = firstNonLoad; i < stackSize; ++i) {
4806                final int loadSlot = localLoadsOnStack[i];
4807                final Type stackType = stackTypes[i];
4808                final boolean isLoad = loadSlot != Label.Stack.NON_LOAD;
4809                final int lvarSlot = isLoad ? loadSlot : lastTempSlot;
4810                final Type lvarType = localTypesList.get(lvarSlot);
4811                method.load(lvarType, lvarSlot);
4812                if(isLoad) {
4813                    // Conversion operators (I2L etc.) preserve "load"-ness of the value despite the fact that, in the
4814                    // strict sense they are creating a derived value from the loaded value. This special behavior of
4815                    // on-stack conversion operators is necessary to accommodate for differences in local variable types
4816                    // after deoptimization; having a conversion operator throw away "load"-ness would create different
4817                    // local variable table shapes between optimism-failed code and its deoptimized rest-of method).
4818                    // After we load the value back, we need to redo the conversion to the stack type if stack type is
4819                    // different.
4820                    // NOTE: this would only strictly be necessary for widening conversions (I2L, L2D, I2D), and not for
4821                    // narrowing ones (L2I, D2L, D2I) as only widening conversions are the ones that can get eliminated
4822                    // in a deoptimized method, as their original input argument got widened. Maybe experiment with
4823                    // throwing away "load"-ness for narrowing conversions in MethodEmitter.convert()?
4824                    method.convert(stackType);
4825                } else {
4826                    // temporary stores never needs a convert, as their type is always the same as the stack type.
4827                    assert lvarType == stackType;
4828                    lastTempSlot += lvarType.getSlots();
4829                }
4830            }
4831            // used all temporaries
4832            assert lastTempSlot == usedSlots + tempSlotsNeeded;
4833
4834            return lastTempSlot - ignoreSlotCount;
4835        }
4836
4837        private void addUnwarrantedOptimismHandlerLabel(final List<Type> localTypes, final Label label) {
4838            final String lvarTypesDescriptor = getLvarTypesDescriptor(localTypes);
4839            final Map<String, Collection<Label>> unwarrantedOptimismHandlers = lc.getUnwarrantedOptimismHandlers();
4840            Collection<Label> labels = unwarrantedOptimismHandlers.get(lvarTypesDescriptor);
4841            if(labels == null) {
4842                labels = new LinkedList<>();
4843                unwarrantedOptimismHandlers.put(lvarTypesDescriptor, labels);
4844            }
4845            method.markLabelAsOptimisticCatchHandler(label, localTypes.size());
4846            labels.add(label);
4847        }
4848
4849        abstract void loadStack();
4850
4851        // Make sure that whatever indy call site you emit from this method uses {@code getCallSiteFlagsOptimistic(node)}
4852        // or otherwise ensure optimistic flag is correctly set in the call site, otherwise it doesn't make much sense
4853        // to use OptimisticExpression for emitting it.
4854        abstract void consumeStack();
4855
4856        /**
4857         * Emits the correct dynamic getter code. Normally just delegates to method emitter, except when the target
4858         * expression is optimistic, and the desired type is narrower than the optimistic type. In that case, it'll emit a
4859         * dynamic getter with its original optimistic type, and explicitly insert a narrowing conversion. This way we can
4860         * preserve the optimism of the values even if they're subsequently immediately coerced into a narrower type. This
4861         * is beneficial because in this case we can still presume that since the original getter was optimistic, the
4862         * conversion has no side effects.
4863         * @param name the name of the property being get
4864         * @param flags call site flags
4865         * @param isMethod whether we're preferably retrieving a function
4866         * @return the current method emitter
4867         */
4868        MethodEmitter dynamicGet(final String name, final int flags, final boolean isMethod, final boolean isIndex) {
4869            if(isOptimistic) {
4870                return method.dynamicGet(getOptimisticCoercedType(), name, getOptimisticFlags(flags), isMethod, isIndex);
4871            }
4872            return method.dynamicGet(resultBounds.within(expression.getType()), name, nonOptimisticFlags(flags), isMethod, isIndex);
4873        }
4874
4875        MethodEmitter dynamicGetIndex(final int flags, final boolean isMethod) {
4876            if(isOptimistic) {
4877                return method.dynamicGetIndex(getOptimisticCoercedType(), getOptimisticFlags(flags), isMethod);
4878            }
4879            return method.dynamicGetIndex(resultBounds.within(expression.getType()), nonOptimisticFlags(flags), isMethod);
4880        }
4881
4882        MethodEmitter dynamicCall(final int argCount, final int flags, final String msg) {
4883            if (isOptimistic) {
4884                return method.dynamicCall(getOptimisticCoercedType(), argCount, getOptimisticFlags(flags), msg);
4885            }
4886            return method.dynamicCall(resultBounds.within(expression.getType()), argCount, nonOptimisticFlags(flags), msg);
4887        }
4888
4889        int getOptimisticFlags(final int flags) {
4890            return flags | CALLSITE_OPTIMISTIC | (optimistic.getProgramPoint() << CALLSITE_PROGRAM_POINT_SHIFT); //encode program point in high bits
4891        }
4892
4893        int getProgramPoint() {
4894            return isOptimistic ? optimistic.getProgramPoint() : INVALID_PROGRAM_POINT;
4895        }
4896
4897        void convertOptimisticReturnValue() {
4898            if (isOptimistic) {
4899                final Type optimisticType = getOptimisticCoercedType();
4900                if(!optimisticType.isObject()) {
4901                    method.load(optimistic.getProgramPoint());
4902                    if(optimisticType.isInteger()) {
4903                        method.invoke(ENSURE_INT);
4904                    } else if(optimisticType.isNumber()) {
4905                        method.invoke(ENSURE_NUMBER);
4906                    } else {
4907                        throw new AssertionError(optimisticType);
4908                    }
4909                }
4910            }
4911        }
4912
4913        void replaceCompileTimeProperty() {
4914            final IdentNode identNode = (IdentNode)expression;
4915            final String name = identNode.getSymbol().getName();
4916            if (CompilerConstants.__FILE__.name().equals(name)) {
4917                replaceCompileTimeProperty(getCurrentSource().getName());
4918            } else if (CompilerConstants.__DIR__.name().equals(name)) {
4919                replaceCompileTimeProperty(getCurrentSource().getBase());
4920            } else if (CompilerConstants.__LINE__.name().equals(name)) {
4921                replaceCompileTimeProperty(getCurrentSource().getLine(identNode.position()));
4922            }
4923        }
4924
4925        /**
4926         * When an ident with name __FILE__, __DIR__, or __LINE__ is loaded, we'll try to look it up as any other
4927         * identifier. However, if it gets all the way up to the Global object, it will send back a special value that
4928         * represents a placeholder for these compile-time location properties. This method will generate code that loads
4929         * the value of the compile-time location property and then invokes a method in Global that will replace the
4930         * placeholder with the value. Effectively, if the symbol for these properties is defined anywhere in the lexical
4931         * scope, they take precedence, but if they aren't, then they resolve to the compile-time location property.
4932         * @param propertyValue the actual value of the property
4933         */
4934        private void replaceCompileTimeProperty(final Object propertyValue) {
4935            assert method.peekType().isObject();
4936            if(propertyValue instanceof String || propertyValue == null) {
4937                method.load((String)propertyValue);
4938            } else if(propertyValue instanceof Integer) {
4939                method.load(((Integer)propertyValue));
4940                method.convert(Type.OBJECT);
4941            } else {
4942                throw new AssertionError();
4943            }
4944            globalReplaceLocationPropertyPlaceholder();
4945            convertOptimisticReturnValue();
4946        }
4947
4948        /**
4949         * Returns the type that should be used as the return type of the dynamic invocation that is emitted as the code
4950         * for the current optimistic operation. If the type bounds is exact boolean or narrower than the expression's
4951         * optimistic type, then the optimistic type is returned, otherwise the coercing type. Effectively, this method
4952         * allows for moving the coercion into the optimistic type when it won't adversely affect the optimistic
4953         * evaluation semantics, and for preserving the optimistic type and doing a separate coercion when it would
4954         * affect it.
4955         * @return
4956         */
4957        private Type getOptimisticCoercedType() {
4958            final Type optimisticType = expression.getType();
4959            assert resultBounds.widest.widerThan(optimisticType);
4960            final Type narrowest = resultBounds.narrowest;
4961
4962            if(narrowest.isBoolean() || narrowest.narrowerThan(optimisticType)) {
4963                assert !optimisticType.isObject();
4964                return optimisticType;
4965            }
4966            assert !narrowest.isObject();
4967            return narrowest;
4968        }
4969    }
4970
4971    private static boolean isOptimistic(final Optimistic optimistic) {
4972        if(!optimistic.canBeOptimistic()) {
4973            return false;
4974        }
4975        final Expression expr = (Expression)optimistic;
4976        return expr.getType().narrowerThan(expr.getWidestOperationType());
4977    }
4978
4979    private static boolean everyLocalLoadIsValid(final int[] loads, final int localCount) {
4980        for (final int load : loads) {
4981            if(load < 0 || load >= localCount) {
4982                return false;
4983            }
4984        }
4985        return true;
4986    }
4987
4988    private static boolean everyStackValueIsLocalLoad(final int[] loads) {
4989        for (final int load : loads) {
4990            if(load == Label.Stack.NON_LOAD) {
4991                return false;
4992            }
4993        }
4994        return true;
4995    }
4996
4997    private String getLvarTypesDescriptor(final List<Type> localVarTypes) {
4998        final int count = localVarTypes.size();
4999        final StringBuilder desc = new StringBuilder(count);
5000        for(int i = 0; i < count;) {
5001            i += appendType(desc, localVarTypes.get(i));
5002        }
5003        return method.markSymbolBoundariesInLvarTypesDescriptor(desc.toString());
5004    }
5005
5006    private static int appendType(final StringBuilder b, final Type t) {
5007        b.append(t.getBytecodeStackType());
5008        return t.getSlots();
5009    }
5010
5011    private static int countSymbolsInLvarTypeDescriptor(final String lvarTypeDescriptor) {
5012        int count = 0;
5013        for(int i = 0; i < lvarTypeDescriptor.length(); ++i) {
5014            if(Character.isUpperCase(lvarTypeDescriptor.charAt(i))) {
5015                ++count;
5016            }
5017        }
5018        return count;
5019
5020    }
5021    /**
5022     * Generates all the required {@code UnwarrantedOptimismException} handlers for the current function. The employed
5023     * strategy strives to maximize code reuse. Every handler constructs an array to hold the local variables, then
5024     * fills in some trailing part of the local variables (those for which it has a unique suffix in the descriptor),
5025     * then jumps to a handler for a prefix that's shared with other handlers. A handler that fills up locals up to
5026     * position 0 will not jump to a prefix handler (as it has no prefix), but instead end with constructing and
5027     * throwing a {@code RewriteException}. Since we lexicographically sort the entries, we only need to check every
5028     * entry to its immediately preceding one for longest matching prefix.
5029     * @return true if there is at least one exception handler
5030     */
5031    private boolean generateUnwarrantedOptimismExceptionHandlers(final FunctionNode fn) {
5032        if(!useOptimisticTypes()) {
5033            return false;
5034        }
5035
5036        // Take the mapping of lvarSpecs -> labels, and turn them into a descending lexicographically sorted list of
5037        // handler specifications.
5038        final Map<String, Collection<Label>> unwarrantedOptimismHandlers = lc.popUnwarrantedOptimismHandlers();
5039        if(unwarrantedOptimismHandlers.isEmpty()) {
5040            return false;
5041        }
5042
5043        method.lineNumber(0);
5044
5045        final List<OptimismExceptionHandlerSpec> handlerSpecs = new ArrayList<>(unwarrantedOptimismHandlers.size() * 4/3);
5046        for(final String spec: unwarrantedOptimismHandlers.keySet()) {
5047            handlerSpecs.add(new OptimismExceptionHandlerSpec(spec, true));
5048        }
5049        Collections.sort(handlerSpecs, Collections.reverseOrder());
5050
5051        // Map of local variable specifications to labels for populating the array for that local variable spec.
5052        final Map<String, Label> delegationLabels = new HashMap<>();
5053
5054        // Do everything in a single pass over the handlerSpecs list. Note that the list can actually grow as we're
5055        // passing through it as we might add new prefix handlers into it, so can't hoist size() outside of the loop.
5056        for(int handlerIndex = 0; handlerIndex < handlerSpecs.size(); ++handlerIndex) {
5057            final OptimismExceptionHandlerSpec spec = handlerSpecs.get(handlerIndex);
5058            final String lvarSpec = spec.lvarSpec;
5059            if(spec.catchTarget) {
5060                assert !method.isReachable();
5061                // Start a catch block and assign the labels for this lvarSpec with it.
5062                method._catch(unwarrantedOptimismHandlers.get(lvarSpec));
5063                // This spec is a catch target, so emit array creation code. The length of the array is the number of
5064                // symbols - the number of uppercase characters.
5065                method.load(countSymbolsInLvarTypeDescriptor(lvarSpec));
5066                method.newarray(Type.OBJECT_ARRAY);
5067            }
5068            if(spec.delegationTarget) {
5069                // If another handler can delegate to this handler as its prefix, then put a jump target here for the
5070                // shared code (after the array creation code, which is never shared).
5071                method.label(delegationLabels.get(lvarSpec)); // label must exist
5072            }
5073
5074            final boolean lastHandler = handlerIndex == handlerSpecs.size() - 1;
5075
5076            int lvarIndex;
5077            final int firstArrayIndex;
5078            final int firstLvarIndex;
5079            Label delegationLabel;
5080            final String commonLvarSpec;
5081            if(lastHandler) {
5082                // Last handler block, doesn't delegate to anything.
5083                lvarIndex = 0;
5084                firstLvarIndex = 0;
5085                firstArrayIndex = 0;
5086                delegationLabel = null;
5087                commonLvarSpec = null;
5088            } else {
5089                // Not yet the last handler block, will definitely delegate to another handler; let's figure out which
5090                // one. It can be an already declared handler further down the list, or it might need to declare a new
5091                // prefix handler.
5092
5093                // Since we're lexicographically ordered, the common prefix handler is defined by the common prefix of
5094                // this handler and the next handler on the list.
5095                final int nextHandlerIndex = handlerIndex + 1;
5096                final String nextLvarSpec = handlerSpecs.get(nextHandlerIndex).lvarSpec;
5097                commonLvarSpec = commonPrefix(lvarSpec, nextLvarSpec);
5098                // We don't chop symbols in half
5099                assert Character.isUpperCase(commonLvarSpec.charAt(commonLvarSpec.length() - 1));
5100
5101                // Let's find if we already have a declaration for such handler, or we need to insert it.
5102                {
5103                    boolean addNewHandler = true;
5104                    int commonHandlerIndex = nextHandlerIndex;
5105                    for(; commonHandlerIndex < handlerSpecs.size(); ++commonHandlerIndex) {
5106                        final OptimismExceptionHandlerSpec forwardHandlerSpec = handlerSpecs.get(commonHandlerIndex);
5107                        final String forwardLvarSpec = forwardHandlerSpec.lvarSpec;
5108                        if(forwardLvarSpec.equals(commonLvarSpec)) {
5109                            // We already have a handler for the common prefix.
5110                            addNewHandler = false;
5111                            // Make sure we mark it as a delegation target.
5112                            forwardHandlerSpec.delegationTarget = true;
5113                            break;
5114                        } else if(!forwardLvarSpec.startsWith(commonLvarSpec)) {
5115                            break;
5116                        }
5117                    }
5118                    if(addNewHandler) {
5119                        // We need to insert a common prefix handler. Note handlers created with catchTarget == false
5120                        // will automatically have delegationTarget == true (because that's the only reason for their
5121                        // existence).
5122                        handlerSpecs.add(commonHandlerIndex, new OptimismExceptionHandlerSpec(commonLvarSpec, false));
5123                    }
5124                }
5125
5126                firstArrayIndex = countSymbolsInLvarTypeDescriptor(commonLvarSpec);
5127                lvarIndex = 0;
5128                for(int j = 0; j < commonLvarSpec.length(); ++j) {
5129                    lvarIndex += CodeGeneratorLexicalContext.getTypeForSlotDescriptor(commonLvarSpec.charAt(j)).getSlots();
5130                }
5131                firstLvarIndex = lvarIndex;
5132
5133                // Create a delegation label if not already present
5134                delegationLabel = delegationLabels.get(commonLvarSpec);
5135                if(delegationLabel == null) {
5136                    // uo_pa == "unwarranted optimism, populate array"
5137                    delegationLabel = new Label("uo_pa_" + commonLvarSpec);
5138                    delegationLabels.put(commonLvarSpec, delegationLabel);
5139                }
5140            }
5141
5142            // Load local variables handled by this handler on stack
5143            int args = 0;
5144            boolean symbolHadValue = false;
5145            for(int typeIndex = commonLvarSpec == null ? 0 : commonLvarSpec.length(); typeIndex < lvarSpec.length(); ++typeIndex) {
5146                final char typeDesc = lvarSpec.charAt(typeIndex);
5147                final Type lvarType = CodeGeneratorLexicalContext.getTypeForSlotDescriptor(typeDesc);
5148                if (!lvarType.isUnknown()) {
5149                    method.load(lvarType, lvarIndex);
5150                    symbolHadValue = true;
5151                    args++;
5152                } else if(typeDesc == 'U' && !symbolHadValue) {
5153                    // Symbol boundary with undefined last value. Check if all previous values for this symbol were also
5154                    // undefined; if so, emit one explicit Undefined. This serves to ensure that we're emiting exactly
5155                    // one value for every symbol that uses local slots. While we could in theory ignore symbols that
5156                    // are undefined (in other words, dead) at the point where this exception was thrown, unfortunately
5157                    // we can't do it in practice. The reason for this is that currently our liveness analysis is
5158                    // coarse (it can determine whether a symbol has not been read with a particular type anywhere in
5159                    // the function being compiled, but that's it), and a symbol being promoted to Object due to a
5160                    // deoptimization will suddenly show up as "live for Object type", and previously dead U->O
5161                    // conversions on loop entries will suddenly become alive in the deoptimized method which will then
5162                    // expect a value for that slot in its continuation handler. If we had precise liveness analysis, we
5163                    // could go back to excluding known dead symbols from the payload of the RewriteException.
5164                    if(method.peekType() == Type.UNDEFINED) {
5165                        method.dup();
5166                    } else {
5167                        method.loadUndefined(Type.OBJECT);
5168                    }
5169                    args++;
5170                }
5171                if(Character.isUpperCase(typeDesc)) {
5172                    // Reached symbol boundary; reset flag for the next symbol.
5173                    symbolHadValue = false;
5174                }
5175                lvarIndex += lvarType.getSlots();
5176            }
5177            assert args > 0;
5178            // Delegate actual storing into array to an array populator utility method.
5179            //on the stack:
5180            // object array to be populated
5181            // start index
5182            // a lot of types
5183            method.dynamicArrayPopulatorCall(args + 1, firstArrayIndex);
5184            if(delegationLabel != null) {
5185                // We cascade to a prefix handler to fill out the rest of the local variables and throw the
5186                // RewriteException.
5187                assert !lastHandler;
5188                assert commonLvarSpec != null;
5189                // Must undefine the local variables that we have already processed for the sake of correct join on the
5190                // delegate label
5191                method.undefineLocalVariables(firstLvarIndex, true);
5192                final OptimismExceptionHandlerSpec nextSpec = handlerSpecs.get(handlerIndex + 1);
5193                // If the delegate immediately follows, and it's not a catch target (so it doesn't have array setup
5194                // code) don't bother emitting a jump, as we'd just jump to the next instruction.
5195                if(!nextSpec.lvarSpec.equals(commonLvarSpec) || nextSpec.catchTarget) {
5196                    method._goto(delegationLabel);
5197                }
5198            } else {
5199                assert lastHandler;
5200                // Nothing to delegate to, so this handler must create and throw the RewriteException.
5201                // At this point we have the UnwarrantedOptimismException and the Object[] with local variables on
5202                // stack. We need to create a RewriteException, push two references to it below the constructor
5203                // arguments, invoke the constructor, and throw the exception.
5204                loadConstant(getByteCodeSymbolNames(fn));
5205                if (isRestOf()) {
5206                    loadConstant(getContinuationEntryPoints());
5207                    method.invoke(CREATE_REWRITE_EXCEPTION_REST_OF);
5208                } else {
5209                    method.invoke(CREATE_REWRITE_EXCEPTION);
5210                }
5211                method.athrow();
5212            }
5213        }
5214        return true;
5215    }
5216
5217    private static String[] getByteCodeSymbolNames(final FunctionNode fn) {
5218        // Only names of local variables on the function level are captured. This information is used to reduce
5219        // deoptimizations, so as much as we can capture will help. We rely on the fact that function wide variables are
5220        // all live all the time, so the array passed to rewrite exception contains one element for every slotted symbol
5221        // here.
5222        final List<String> names = new ArrayList<>();
5223        for (final Symbol symbol: fn.getBody().getSymbols()) {
5224            if (symbol.hasSlot()) {
5225                if (symbol.isScope()) {
5226                    // slot + scope can only be true for parameters
5227                    assert symbol.isParam();
5228                    names.add(null);
5229                } else {
5230                    names.add(symbol.getName());
5231                }
5232            }
5233        }
5234        return names.toArray(new String[0]);
5235    }
5236
5237    private static String commonPrefix(final String s1, final String s2) {
5238        final int l1 = s1.length();
5239        final int l = Math.min(l1, s2.length());
5240        int lms = -1; // last matching symbol
5241        for(int i = 0; i < l; ++i) {
5242            final char c1 = s1.charAt(i);
5243            if(c1 != s2.charAt(i)) {
5244                return s1.substring(0, lms + 1);
5245            } else if(Character.isUpperCase(c1)) {
5246                lms = i;
5247            }
5248        }
5249        return l == l1 ? s1 : s2;
5250    }
5251
5252    private static class OptimismExceptionHandlerSpec implements Comparable<OptimismExceptionHandlerSpec> {
5253        private final String lvarSpec;
5254        private final boolean catchTarget;
5255        private boolean delegationTarget;
5256
5257        OptimismExceptionHandlerSpec(final String lvarSpec, final boolean catchTarget) {
5258            this.lvarSpec = lvarSpec;
5259            this.catchTarget = catchTarget;
5260            if(!catchTarget) {
5261                delegationTarget = true;
5262            }
5263        }
5264
5265        @Override
5266        public int compareTo(final OptimismExceptionHandlerSpec o) {
5267            return lvarSpec.compareTo(o.lvarSpec);
5268        }
5269
5270        @Override
5271        public String toString() {
5272            final StringBuilder b = new StringBuilder(64).append("[HandlerSpec ").append(lvarSpec);
5273            if(catchTarget) {
5274                b.append(", catchTarget");
5275            }
5276            if(delegationTarget) {
5277                b.append(", delegationTarget");
5278            }
5279            return b.append("]").toString();
5280        }
5281    }
5282
5283    private static class ContinuationInfo {
5284        private final Label handlerLabel;
5285        private Label targetLabel; // Label for the target instruction.
5286        int lvarCount;
5287        // Indices of local variables that need to be loaded on the stack when this node completes
5288        private int[] stackStoreSpec;
5289        // Types of values loaded on the stack
5290        private Type[] stackTypes;
5291        // If non-null, this node should perform the requisite type conversion
5292        private Type returnValueType;
5293        // If we are in the middle of an object literal initialization, we need to update the map
5294        private PropertyMap objectLiteralMap;
5295        // Object literal stack depth for object literal - not necessarily top if property is a tree
5296        private int objectLiteralStackDepth = -1;
5297        // The line number at the continuation point
5298        private int lineNumber;
5299        // The active catch label, in case the continuation point is in a try/catch block
5300        private Label catchLabel;
5301        // The number of scopes that need to be popped before control is transferred to the catch label.
5302        private int exceptionScopePops;
5303
5304        ContinuationInfo() {
5305            this.handlerLabel = new Label("continuation_handler");
5306        }
5307
5308        Label getHandlerLabel() {
5309            return handlerLabel;
5310        }
5311
5312        boolean hasTargetLabel() {
5313            return targetLabel != null;
5314        }
5315
5316        Label getTargetLabel() {
5317            return targetLabel;
5318        }
5319
5320        void setTargetLabel(final Label targetLabel) {
5321            this.targetLabel = targetLabel;
5322        }
5323
5324        int[] getStackStoreSpec() {
5325            return stackStoreSpec.clone();
5326        }
5327
5328        void setStackStoreSpec(final int[] stackStoreSpec) {
5329            this.stackStoreSpec = stackStoreSpec;
5330        }
5331
5332        Type[] getStackTypes() {
5333            return stackTypes.clone();
5334        }
5335
5336        void setStackTypes(final Type[] stackTypes) {
5337            this.stackTypes = stackTypes;
5338        }
5339
5340        Type getReturnValueType() {
5341            return returnValueType;
5342        }
5343
5344        void setReturnValueType(final Type returnValueType) {
5345            this.returnValueType = returnValueType;
5346        }
5347
5348        int getObjectLiteralStackDepth() {
5349            return objectLiteralStackDepth;
5350        }
5351
5352        void setObjectLiteralStackDepth(final int objectLiteralStackDepth) {
5353            this.objectLiteralStackDepth = objectLiteralStackDepth;
5354        }
5355
5356        PropertyMap getObjectLiteralMap() {
5357            return objectLiteralMap;
5358        }
5359
5360        void setObjectLiteralMap(final PropertyMap objectLiteralMap) {
5361            this.objectLiteralMap = objectLiteralMap;
5362        }
5363
5364        @Override
5365        public String toString() {
5366             return "[localVariableTypes=" + targetLabel.getStack().getLocalVariableTypesCopy() + ", stackStoreSpec=" +
5367                     Arrays.toString(stackStoreSpec) + ", returnValueType=" + returnValueType + "]";
5368        }
5369    }
5370
5371    private ContinuationInfo getContinuationInfo() {
5372        return continuationInfo;
5373    }
5374
5375    private void generateContinuationHandler() {
5376        if (!isRestOf()) {
5377            return;
5378        }
5379
5380        final ContinuationInfo ci = getContinuationInfo();
5381        method.label(ci.getHandlerLabel());
5382
5383        // There should never be an exception thrown from the continuation handler, but in case there is (meaning,
5384        // Nashorn has a bug), then line number 0 will be an indication of where it came from (line numbers are Uint16).
5385        method.lineNumber(0);
5386
5387        final Label.Stack stack = ci.getTargetLabel().getStack();
5388        final List<Type> lvarTypes = stack.getLocalVariableTypesCopy();
5389        final BitSet symbolBoundary = stack.getSymbolBoundaryCopy();
5390        final int lvarCount = ci.lvarCount;
5391
5392        final Type rewriteExceptionType = Type.typeFor(RewriteException.class);
5393        // Store the RewriteException into an unused local variable slot.
5394        method.load(rewriteExceptionType, 0);
5395        method.storeTemp(rewriteExceptionType, lvarCount);
5396        // Get local variable array
5397        method.load(rewriteExceptionType, 0);
5398        method.invoke(RewriteException.GET_BYTECODE_SLOTS);
5399        // Store local variables. Note that deoptimization might introduce new value types for existing local variables,
5400        // so we must use both liveLocals and symbolBoundary, as in some cases (when the continuation is inside of a try
5401        // block) we need to store the incoming value into multiple slots. The optimism exception handlers will have
5402        // exactly one array element for every symbol that uses bytecode storage. If in the originating method the value
5403        // was undefined, there will be an explicit Undefined value in the array.
5404        int arrayIndex = 0;
5405        for(int lvarIndex = 0; lvarIndex < lvarCount;) {
5406            final Type lvarType = lvarTypes.get(lvarIndex);
5407            if(!lvarType.isUnknown()) {
5408                method.dup();
5409                method.load(arrayIndex).arrayload();
5410                final Class<?> typeClass = lvarType.getTypeClass();
5411                // Deoptimization in array initializers can cause arrays to undergo component type widening
5412                if(typeClass == long[].class) {
5413                    method.load(rewriteExceptionType, lvarCount);
5414                    method.invoke(RewriteException.TO_LONG_ARRAY);
5415                } else if(typeClass == double[].class) {
5416                    method.load(rewriteExceptionType, lvarCount);
5417                    method.invoke(RewriteException.TO_DOUBLE_ARRAY);
5418                } else if(typeClass == Object[].class) {
5419                    method.load(rewriteExceptionType, lvarCount);
5420                    method.invoke(RewriteException.TO_OBJECT_ARRAY);
5421                } else {
5422                    if(!(typeClass.isPrimitive() || typeClass == Object.class)) {
5423                        // NOTE: this can only happen with dead stores. E.g. for the program "1; []; f();" in which the
5424                        // call to f() will deoptimize the call site, but it'll expect :return to have the type
5425                        // NativeArray. However, in the more optimal version, :return's only live type is int, therefore
5426                        // "{O}:return = []" is a dead store, and the variable will be sent into the continuation as
5427                        // Undefined, however NativeArray can't hold Undefined instance.
5428                        method.loadType(Type.getInternalName(typeClass));
5429                        method.invoke(RewriteException.INSTANCE_OR_NULL);
5430                    }
5431                    method.convert(lvarType);
5432                }
5433                method.storeHidden(lvarType, lvarIndex, false);
5434            }
5435            final int nextLvarIndex = lvarIndex + lvarType.getSlots();
5436            if(symbolBoundary.get(nextLvarIndex - 1)) {
5437                ++arrayIndex;
5438            }
5439            lvarIndex = nextLvarIndex;
5440        }
5441        if (AssertsEnabled.assertsEnabled()) {
5442            method.load(arrayIndex);
5443            method.invoke(RewriteException.ASSERT_ARRAY_LENGTH);
5444        } else {
5445            method.pop();
5446        }
5447
5448        final int[]   stackStoreSpec = ci.getStackStoreSpec();
5449        final Type[]  stackTypes     = ci.getStackTypes();
5450        final boolean isStackEmpty   = stackStoreSpec.length == 0;
5451        boolean replacedObjectLiteralMap = false;
5452        if(!isStackEmpty) {
5453            // Load arguments on the stack
5454            final int objectLiteralStackDepth = ci.getObjectLiteralStackDepth();
5455            for(int i = 0; i < stackStoreSpec.length; ++i) {
5456                final int slot = stackStoreSpec[i];
5457                method.load(lvarTypes.get(slot), slot);
5458                method.convert(stackTypes[i]);
5459                // stack: s0=object literal being initialized
5460                // change map of s0 so that the property we are initializing when we failed
5461                // is now ci.returnValueType
5462                if (i == objectLiteralStackDepth) {
5463                    method.dup();
5464                    assert ci.getObjectLiteralMap() != null;
5465                    assert ScriptObject.class.isAssignableFrom(method.peekType().getTypeClass()) : method.peekType().getTypeClass() + " is not a script object";
5466                    loadConstant(ci.getObjectLiteralMap());
5467                    method.invoke(ScriptObject.SET_MAP);
5468                    replacedObjectLiteralMap = true;
5469                }
5470            }
5471        }
5472        // Must have emitted the code for replacing the map of an object literal if we have a set object literal stack depth
5473        assert ci.getObjectLiteralStackDepth() == -1 || replacedObjectLiteralMap;
5474        // Load RewriteException back.
5475        method.load(rewriteExceptionType, lvarCount);
5476        // Get rid of the stored reference
5477        method.loadNull();
5478        method.storeHidden(Type.OBJECT, lvarCount);
5479        // Mark it dead
5480        method.markDeadSlots(lvarCount, Type.OBJECT.getSlots());
5481
5482        // Load return value on the stack
5483        method.invoke(RewriteException.GET_RETURN_VALUE);
5484
5485        final Type returnValueType = ci.getReturnValueType();
5486
5487        // Set up an exception handler for primitive type conversion of return value if needed
5488        boolean needsCatch = false;
5489        final Label targetCatchLabel = ci.catchLabel;
5490        Label _try = null;
5491        if(returnValueType.isPrimitive()) {
5492            // If the conversion throws an exception, we want to report the line number of the continuation point.
5493            method.lineNumber(ci.lineNumber);
5494
5495            if(targetCatchLabel != METHOD_BOUNDARY) {
5496                _try = new Label("");
5497                method.label(_try);
5498                needsCatch = true;
5499            }
5500        }
5501
5502        // Convert return value
5503        method.convert(returnValueType);
5504
5505        final int scopePopCount = needsCatch ? ci.exceptionScopePops : 0;
5506
5507        // Declare a try/catch for the conversion. If no scopes need to be popped until the target catch block, just
5508        // jump into it. Otherwise, we'll need to create a scope-popping catch block below.
5509        final Label catchLabel = scopePopCount > 0 ? new Label("") : targetCatchLabel;
5510        if(needsCatch) {
5511            final Label _end_try = new Label("");
5512            method.label(_end_try);
5513            method._try(_try, _end_try, catchLabel);
5514        }
5515
5516        // Jump to continuation point
5517        method._goto(ci.getTargetLabel());
5518
5519        // Make a scope-popping exception delegate if needed
5520        if(catchLabel != targetCatchLabel) {
5521            method.lineNumber(0);
5522            assert scopePopCount > 0;
5523            method._catch(catchLabel);
5524            popScopes(scopePopCount);
5525            method.uncheckedGoto(targetCatchLabel);
5526        }
5527    }
5528
5529    /**
5530     * Interface implemented by object creators that support splitting over multiple methods.
5531     */
5532    interface SplitLiteralCreator {
5533        /**
5534         * Generate code to populate a range of the literal object. A reference to the object
5535         * should be left on the stack when the method terminates.
5536         *
5537         * @param method the method emitter
5538         * @param type the type of the literal object
5539         * @param slot the local slot containing the literal object
5540         * @param start the start index (inclusive)
5541         * @param end the end index (exclusive)
5542         */
5543        void populateRange(MethodEmitter method, Type type, int slot, int start, int end);
5544    }
5545}
5546