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