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