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