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