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