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