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