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.GET_MAP;
  33 import static jdk.nashorn.internal.codegen.CompilerConstants.GET_STRING;
  34 import static jdk.nashorn.internal.codegen.CompilerConstants.QUICK_PREFIX;
  35 import static jdk.nashorn.internal.codegen.CompilerConstants.REGEX_PREFIX;
  36 import static jdk.nashorn.internal.codegen.CompilerConstants.RETURN;
  37 import static jdk.nashorn.internal.codegen.CompilerConstants.SCOPE;
  38 import static jdk.nashorn.internal.codegen.CompilerConstants.SPLIT_ARRAY_ARG;
  39 import static jdk.nashorn.internal.codegen.CompilerConstants.SPLIT_PREFIX;
  40 import static jdk.nashorn.internal.codegen.CompilerConstants.THIS;
  41 import static jdk.nashorn.internal.codegen.CompilerConstants.VARARGS;
  42 import static jdk.nashorn.internal.codegen.CompilerConstants.constructorNoLookup;
  43 import static jdk.nashorn.internal.codegen.CompilerConstants.interfaceCallNoLookup;
  44 import static jdk.nashorn.internal.codegen.CompilerConstants.methodDescriptor;
  45 import static jdk.nashorn.internal.codegen.CompilerConstants.staticCallNoLookup;
  46 import static jdk.nashorn.internal.codegen.CompilerConstants.staticField;
  47 import static jdk.nashorn.internal.codegen.CompilerConstants.typeDescriptor;
  48 import static jdk.nashorn.internal.ir.Symbol.IS_INTERNAL;
  49 import static jdk.nashorn.internal.ir.Symbol.IS_TEMP;
  50 import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_FAST_SCOPE;
  51 import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_SCOPE;
  52 import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_STRICT;
  53 
  54 import java.io.PrintWriter;
  55 import java.util.ArrayList;
  56 import java.util.Arrays;
  57 import java.util.EnumSet;
  58 import java.util.Iterator;
  59 import java.util.LinkedList;
  60 import java.util.List;
  61 import java.util.Locale;
  62 import java.util.TreeMap;
  63 
  64 import jdk.nashorn.internal.codegen.ClassEmitter.Flag;
  65 import jdk.nashorn.internal.codegen.CompilerConstants.Call;
  66 import jdk.nashorn.internal.codegen.RuntimeCallSite.SpecializedRuntimeNode;
  67 import jdk.nashorn.internal.codegen.types.ArrayType;
  68 import jdk.nashorn.internal.codegen.types.Type;
  69 import jdk.nashorn.internal.ir.AccessNode;
  70 import jdk.nashorn.internal.ir.BaseNode;
  71 import jdk.nashorn.internal.ir.BinaryNode;
  72 import jdk.nashorn.internal.ir.Block;
  73 import jdk.nashorn.internal.ir.BreakNode;
  74 import jdk.nashorn.internal.ir.BreakableNode;
  75 import jdk.nashorn.internal.ir.CallNode;
  76 import jdk.nashorn.internal.ir.CaseNode;
  77 import jdk.nashorn.internal.ir.CatchNode;
  78 import jdk.nashorn.internal.ir.ContinueNode;
  79 import jdk.nashorn.internal.ir.EmptyNode;
  80 import jdk.nashorn.internal.ir.ExecuteNode;
  81 import jdk.nashorn.internal.ir.ForNode;
  82 import jdk.nashorn.internal.ir.FunctionNode;
  83 import jdk.nashorn.internal.ir.LexicalContext;
  84 import jdk.nashorn.internal.ir.FunctionNode.CompilationState;
  85 import jdk.nashorn.internal.ir.IdentNode;
  86 import jdk.nashorn.internal.ir.IfNode;
  87 import jdk.nashorn.internal.ir.IndexNode;
  88 import jdk.nashorn.internal.ir.LexicalContextNode;
  89 import jdk.nashorn.internal.ir.LiteralNode;
  90 import jdk.nashorn.internal.ir.LiteralNode.ArrayLiteralNode;
  91 import jdk.nashorn.internal.ir.LiteralNode.ArrayLiteralNode.ArrayUnit;
  92 import jdk.nashorn.internal.ir.LoopNode;
  93 import jdk.nashorn.internal.ir.Node;
  94 import jdk.nashorn.internal.ir.ObjectNode;
  95 import jdk.nashorn.internal.ir.PropertyNode;
  96 import jdk.nashorn.internal.ir.ReturnNode;
  97 import jdk.nashorn.internal.ir.RuntimeNode;
  98 import jdk.nashorn.internal.ir.RuntimeNode.Request;
  99 import jdk.nashorn.internal.ir.SplitNode;
 100 import jdk.nashorn.internal.ir.Statement;
 101 import jdk.nashorn.internal.ir.SwitchNode;
 102 import jdk.nashorn.internal.ir.Symbol;
 103 import jdk.nashorn.internal.ir.TernaryNode;
 104 import jdk.nashorn.internal.ir.ThrowNode;
 105 import jdk.nashorn.internal.ir.TryNode;
 106 import jdk.nashorn.internal.ir.UnaryNode;
 107 import jdk.nashorn.internal.ir.VarNode;
 108 import jdk.nashorn.internal.ir.WhileNode;
 109 import jdk.nashorn.internal.ir.WithNode;
 110 import jdk.nashorn.internal.ir.debug.ASTWriter;
 111 import jdk.nashorn.internal.ir.visitor.NodeOperatorVisitor;
 112 import jdk.nashorn.internal.ir.visitor.NodeVisitor;
 113 import jdk.nashorn.internal.parser.Lexer.RegexToken;
 114 import jdk.nashorn.internal.parser.TokenType;
 115 import jdk.nashorn.internal.runtime.Context;
 116 import jdk.nashorn.internal.runtime.Debug;
 117 import jdk.nashorn.internal.runtime.DebugLogger;
 118 import jdk.nashorn.internal.runtime.ECMAException;
 119 import jdk.nashorn.internal.runtime.JSType;
 120 import jdk.nashorn.internal.runtime.Property;
 121 import jdk.nashorn.internal.runtime.PropertyMap;
 122 import jdk.nashorn.internal.runtime.RecompilableScriptFunctionData;
 123 import jdk.nashorn.internal.runtime.Scope;
 124 import jdk.nashorn.internal.runtime.ScriptFunction;
 125 import jdk.nashorn.internal.runtime.ScriptObject;
 126 import jdk.nashorn.internal.runtime.ScriptRuntime;
 127 import jdk.nashorn.internal.runtime.Source;
 128 import jdk.nashorn.internal.runtime.Undefined;
 129 import jdk.nashorn.internal.runtime.linker.LinkerCallSite;
 130 
 131 /**
 132  * This is the lowest tier of the code generator. It takes lowered ASTs emitted
 133  * from Lower and emits Java byte code. The byte code emission logic is broken
 134  * out into MethodEmitter. MethodEmitter works internally with a type stack, and
 135  * keeps track of the contents of the byte code stack. This way we avoid a large
 136  * number of special cases on the form
 137  * <pre>
 138  * if (type == INT) {
 139  *     visitInsn(ILOAD, slot);
 140  * } else if (type == DOUBLE) {
 141  *     visitInsn(DOUBLE, slot);
 142  * }
 143  * </pre>
 144  * This quickly became apparent when the code generator was generalized to work
 145  * with all types, and not just numbers or objects.
 146  * <p>
 147  * The CodeGenerator visits nodes only once, tags them as resolved and emits
 148  * bytecode for them.
 149  */
 150 final class CodeGenerator extends NodeOperatorVisitor<CodeGeneratorLexicalContext> {
 151 
 152     /** Name of the Global object, cannot be referred to as .class, @see CodeGenerator */
 153     private static final String GLOBAL_OBJECT = Compiler.OBJECTS_PACKAGE + '/' + "Global";
 154 
 155     /** Name of the ScriptFunctionImpl, cannot be referred to as .class @see FunctionObjectCreator */
 156     private static final String SCRIPTFUNCTION_IMPL_OBJECT = Compiler.OBJECTS_PACKAGE + '/' + "ScriptFunctionImpl";
 157 
 158     /** Constant data & installation. The only reason the compiler keeps this is because it is assigned
 159      *  by reflection in class installation */
 160     private final Compiler compiler;
 161 
 162     /** Call site flags given to the code generator to be used for all generated call sites */
 163     private final int callSiteFlags;
 164 
 165     /** How many regexp fields have been emitted */
 166     private int regexFieldCount;
 167 
 168     /** Line number for last statement. If we encounter a new line number, line number bytecode information
 169      *  needs to be generated */
 170     private int lastLineNumber = -1;
 171 
 172     /** When should we stop caching regexp expressions in fields to limit bytecode size? */
 173     private static final int MAX_REGEX_FIELDS = 2 * 1024;
 174 
 175     /** Current method emitter */
 176     private MethodEmitter method;
 177 
 178     /** Current compile unit */
 179     private CompileUnit unit;
 180 
 181     private static final DebugLogger LOG   = new DebugLogger("codegen", "nashorn.codegen.debug");
 182 
 183 
 184     /**
 185      * Constructor.
 186      *
 187      * @param compiler
 188      */
 189     CodeGenerator(final Compiler compiler) {
 190         super(new CodeGeneratorLexicalContext());
 191         this.compiler      = compiler;
 192         this.callSiteFlags = compiler.getEnv()._callsite_flags;
 193     }
 194 
 195     /**
 196      * Gets the call site flags, adding the strict flag if the current function
 197      * being generated is in strict mode
 198      *
 199      * @return the correct flags for a call site in the current function
 200      */
 201     int getCallSiteFlags() {
 202         return lc.getCurrentFunction().isStrict() ? callSiteFlags | CALLSITE_STRICT : callSiteFlags;
 203     }
 204 
 205     /**
 206      * Load an identity node
 207      *
 208      * @param identNode an identity node to load
 209      * @return the method generator used
 210      */
 211     private MethodEmitter loadIdent(final IdentNode identNode) {
 212         final Symbol symbol = identNode.getSymbol();
 213 
 214         if (!symbol.isScope()) {
 215             assert symbol.hasSlot() || symbol.isParam();
 216             return method.load(symbol);
 217         }
 218 
 219         final String name   = symbol.getName();
 220         final Source source = lc.getCurrentFunction().getSource();
 221 
 222         if (CompilerConstants.__FILE__.name().equals(name)) {
 223             return method.load(source.getName());
 224         } else if (CompilerConstants.__DIR__.name().equals(name)) {
 225             return method.load(source.getBase());
 226         } else if (CompilerConstants.__LINE__.name().equals(name)) {
 227             return method.load(source.getLine(identNode.position())).convert(Type.OBJECT);
 228         } else {
 229             assert identNode.getSymbol().isScope() : identNode + " is not in scope!";
 230 
 231             final int flags = CALLSITE_SCOPE | getCallSiteFlags();
 232             method.loadCompilerConstant(SCOPE);
 233 
 234             if (isFastScope(symbol)) {
 235                 // Only generate shared scope getter for fast-scope symbols so we know we can dial in correct scope.
 236                 if (symbol.getUseCount() > SharedScopeCall.FAST_SCOPE_GET_THRESHOLD) {
 237                     return loadSharedScopeVar(identNode.getType(), symbol, flags);
 238                 }
 239                 return loadFastScopeVar(identNode.getType(), symbol, flags, identNode.isFunction());
 240             }
 241             return method.dynamicGet(identNode.getType(), identNode.getName(), flags, identNode.isFunction());
 242         }
 243     }
 244 
 245     /**
 246      * Check if this symbol can be accessed directly with a putfield or getfield or dynamic load
 247      *
 248      * @param function function to check for fast scope
 249      * @return true if fast scope
 250      */
 251     private boolean isFastScope(final Symbol symbol) {
 252         if (!symbol.isScope()) {
 253             return false;
 254         }
 255 
 256         if (!lc.inDynamicScope()) {
 257             // If there's no with or eval in context, and the symbol is marked as scoped, it is fast scoped. Such a
 258             // symbol must either be global, or its defining block must need scope.
 259             assert symbol.isGlobal() || lc.getDefiningBlock(symbol).needsScope() : symbol.getName();
 260             return true;
 261         }
 262 
 263         if (symbol.isGlobal()) {
 264             // Shortcut: if there's a with or eval in context, globals can't be fast scoped
 265             return false;
 266         }
 267 
 268         // Otherwise, check if there's a dynamic scope between use of the symbol and its definition
 269         final String name = symbol.getName();
 270         boolean previousWasBlock = false;
 271         for (final Iterator<LexicalContextNode> it = lc.getAllNodes(); it.hasNext();) {
 272             final LexicalContextNode node = it.next();
 273             if (node instanceof Block) {
 274                 // If this block defines the symbol, then we can fast scope the symbol.
 275                 final Block block = (Block)node;
 276                 if (block.getExistingSymbol(name) == symbol) {
 277                     assert block.needsScope();
 278                     return true;
 279                 }
 280                 previousWasBlock = true;
 281             } else {
 282                 if ((node instanceof WithNode && previousWasBlock) || (node instanceof FunctionNode && CodeGeneratorLexicalContext.isFunctionDynamicScope((FunctionNode)node))) {
 283                     // If we hit a scope that can have symbols introduced into it at run time before finding the defining
 284                     // block, the symbol can't be fast scoped. A WithNode only counts if we've immediately seen a block
 285                     // before - its block. Otherwise, we are currently processing the WithNode's expression, and that's
 286                     // obviously not subjected to introducing new symbols.
 287                     return false;
 288                 }
 289                 previousWasBlock = false;
 290             }
 291         }
 292         // Should've found the symbol defined in a block
 293         throw new AssertionError();
 294     }
 295 
 296     private MethodEmitter loadSharedScopeVar(final Type valueType, final Symbol symbol, final int flags) {
 297         method.load(isFastScope(symbol) ? getScopeProtoDepth(lc.getCurrentBlock(), symbol) : -1);
 298         final SharedScopeCall scopeCall = lc.getScopeGet(unit, valueType, symbol, flags | CALLSITE_FAST_SCOPE);
 299         return scopeCall.generateInvoke(method);
 300     }
 301 
 302     private MethodEmitter loadFastScopeVar(final Type valueType, final Symbol symbol, final int flags, final boolean isMethod) {
 303         loadFastScopeProto(symbol, false);
 304         return method.dynamicGet(valueType, symbol.getName(), flags | CALLSITE_FAST_SCOPE, isMethod);
 305     }
 306 
 307     private MethodEmitter storeFastScopeVar(final Type valueType, final Symbol symbol, final int flags) {
 308         loadFastScopeProto(symbol, true);
 309         method.dynamicSet(valueType, symbol.getName(), flags | CALLSITE_FAST_SCOPE);
 310         return method;
 311     }
 312 
 313     private int getScopeProtoDepth(final Block startingBlock, final Symbol symbol) {
 314         int depth = 0;
 315         final String name = symbol.getName();
 316         for(final Iterator<Block> blocks = lc.getBlocks(startingBlock); blocks.hasNext();) {
 317             final Block currentBlock = blocks.next();
 318             if (currentBlock.getExistingSymbol(name) == symbol) {
 319                 return depth;
 320             }
 321             if (currentBlock.needsScope()) {
 322                 ++depth;
 323             }
 324         }
 325         return -1;
 326     }
 327 
 328     private void loadFastScopeProto(final Symbol symbol, final boolean swap) {
 329         final int depth = getScopeProtoDepth(lc.getCurrentBlock(), symbol);
 330         assert depth != -1;
 331         if (depth > 0) {
 332             if (swap) {
 333                 method.swap();
 334             }
 335             for (int i = 0; i < depth; i++) {
 336                 method.invoke(ScriptObject.GET_PROTO);
 337             }
 338             if (swap) {
 339                 method.swap();
 340             }
 341         }
 342     }
 343 
 344     /**
 345      * Generate code that loads this node to the stack. This method is only
 346      * public to be accessible from the maps sub package. Do not call externally
 347      *
 348      * @param node node to load
 349      *
 350      * @return the method emitter used
 351      */
 352     MethodEmitter load(final Node node) {
 353         return load(node, false);
 354     }
 355 
 356     private MethodEmitter load(final Node node, final boolean baseAlreadyOnStack) {
 357         final Symbol symbol = node.getSymbol();
 358 
 359         // If we lack symbols, we just generate what we see.
 360         if (symbol == null) {
 361             node.accept(this);
 362             return method;
 363         }
 364 
 365         /*
 366          * The load may be of type IdentNode, e.g. "x", AccessNode, e.g. "x.y"
 367          * or IndexNode e.g. "x[y]". Both AccessNodes and IndexNodes are
 368          * BaseNodes and the logic for loading the base object is reused
 369          */
 370         final CodeGenerator codegen = this;
 371 
 372         node.accept(new NodeVisitor<LexicalContext>(new LexicalContext()) {
 373             @Override
 374             public boolean enterIdentNode(final IdentNode identNode) {
 375                 loadIdent(identNode);
 376                 return false;
 377             }
 378 
 379             @Override
 380             public boolean enterAccessNode(final AccessNode accessNode) {
 381                 if (!baseAlreadyOnStack) {
 382                     load(accessNode.getBase()).convert(Type.OBJECT);
 383                 }
 384                 assert method.peekType().isObject();
 385                 method.dynamicGet(node.getType(), accessNode.getProperty().getName(), getCallSiteFlags(), accessNode.isFunction());
 386                 return false;
 387             }
 388 
 389             @Override
 390             public boolean enterIndexNode(final IndexNode indexNode) {
 391                 if (!baseAlreadyOnStack) {
 392                     load(indexNode.getBase()).convert(Type.OBJECT);
 393                     load(indexNode.getIndex());
 394                 }
 395                 method.dynamicGetIndex(node.getType(), getCallSiteFlags(), indexNode.isFunction());
 396                 return false;
 397             }
 398 
 399             @Override
 400             public boolean enterFunctionNode(FunctionNode functionNode) {
 401                 // function nodes will always leave a constructed function object on stack, no need to load the symbol
 402                 // separately as in enterDefault()
 403                 functionNode.accept(codegen);
 404                 return false;
 405             }
 406 
 407             @Override
 408             public boolean enterDefault(final Node otherNode) {
 409                 otherNode.accept(codegen); // generate code for whatever we are looking at.
 410                 method.load(symbol); // load the final symbol to the stack (or nop if no slot, then result is already there)
 411                 return false;
 412             }
 413         });
 414 
 415         return method;
 416     }
 417 
 418     @Override
 419     public boolean enterAccessNode(final AccessNode accessNode) {
 420         load(accessNode);
 421         return false;
 422     }
 423 
 424     /**
 425      * Initialize a specific set of vars to undefined. This has to be done at
 426      * the start of each method for local variables that aren't passed as
 427      * parameters.
 428      *
 429      * @param symbols list of symbols.
 430      */
 431     private void initSymbols(final Iterable<Symbol> symbols) {
 432         final LinkedList<Symbol> numbers = new LinkedList<>();
 433         final LinkedList<Symbol> objects = new LinkedList<>();
 434 
 435         for (final Symbol symbol : symbols) {
 436             /*
 437              * The following symbols are guaranteed to be defined and thus safe
 438              * from having undefined written to them: parameters internals this
 439              *
 440              * Otherwise we must, unless we perform control/escape analysis,
 441              * assign them undefined.
 442              */
 443             final boolean isInternal = symbol.isParam() || symbol.isInternal() || symbol.isThis() || !symbol.canBeUndefined();
 444 
 445             if (symbol.hasSlot() && !isInternal) {
 446                 assert symbol.getSymbolType().isNumber() || symbol.getSymbolType().isObject() : "no potentially undefined narrower local vars than doubles are allowed: " + symbol + " in " + lc.getCurrentFunction();
 447                 if (symbol.getSymbolType().isNumber()) {
 448                     numbers.add(symbol);
 449                 } else if (symbol.getSymbolType().isObject()) {
 450                     objects.add(symbol);
 451                 }
 452             }
 453         }
 454 
 455         initSymbols(numbers, Type.NUMBER);
 456         initSymbols(objects, Type.OBJECT);
 457     }
 458 
 459     private void initSymbols(final LinkedList<Symbol> symbols, final Type type) {
 460         if (symbols.isEmpty()) {
 461             return;
 462         }
 463 
 464         method.loadUndefined(type);
 465         while (!symbols.isEmpty()) {
 466             final Symbol symbol = symbols.removeFirst();
 467             if (!symbols.isEmpty()) {
 468                 method.dup();
 469             }
 470             method.store(symbol);
 471         }
 472     }
 473 
 474     /**
 475      * Create symbol debug information.
 476      *
 477      * @param block block containing symbols.
 478      */
 479     private void symbolInfo(final Block block) {
 480         for (final Symbol symbol : block.getSymbols()) {
 481             if (symbol.hasSlot()) {
 482                 method.localVariable(symbol, block.getEntryLabel(), block.getBreakLabel());
 483             }
 484         }
 485     }
 486 
 487     @Override
 488     public boolean enterBlock(final Block block) {
 489         method.label(block.getEntryLabel());
 490         initLocals(block);
 491 
 492         return true;
 493     }
 494 
 495     @Override
 496     public Node leaveBlock(final Block block) {
 497         method.label(block.getBreakLabel());
 498         symbolInfo(block);
 499 
 500         if (block.needsScope() && !block.isTerminal()) {
 501             popBlockScope(block);
 502         }
 503         return block;
 504     }
 505 
 506     private void popBlockScope(final Block block) {
 507         final Label exitLabel     = new Label("block_exit");
 508         final Label recoveryLabel = new Label("block_catch");
 509         final Label skipLabel     = new Label("skip_catch");
 510 
 511         /* pop scope a la try-finally */
 512         method.loadCompilerConstant(SCOPE);
 513         method.invoke(ScriptObject.GET_PROTO);
 514         method.storeCompilerConstant(SCOPE);
 515         method._goto(skipLabel);
 516         method.label(exitLabel);
 517 
 518         method._catch(recoveryLabel);
 519         method.loadCompilerConstant(SCOPE);
 520         method.invoke(ScriptObject.GET_PROTO);
 521         method.storeCompilerConstant(SCOPE);
 522         method.athrow();
 523         method.label(skipLabel);
 524         method._try(block.getEntryLabel(), exitLabel, recoveryLabel, Throwable.class);
 525     }
 526 
 527     @Override
 528     public boolean enterBreakNode(final BreakNode breakNode) {
 529         lineNumber(breakNode);
 530 
 531         final BreakableNode breakFrom = lc.getBreakable(breakNode.getLabel());
 532         for (int i = 0; i < lc.getScopeNestingLevelTo(breakFrom); i++) {
 533             closeWith();
 534         }
 535         method.splitAwareGoto(lc, breakFrom.getBreakLabel());
 536 
 537         return false;
 538     }
 539 
 540     private int loadArgs(final List<Node> args) {
 541         return loadArgs(args, null, false, args.size());
 542     }
 543 
 544     private int loadArgs(final List<Node> args, final String signature, final boolean isVarArg, final int argCount) {
 545         // arg have already been converted to objects here.
 546         if (isVarArg || argCount > LinkerCallSite.ARGLIMIT) {
 547             loadArgsArray(args);
 548             return 1;
 549         }
 550 
 551         // pad with undefined if size is too short. argCount is the real number of args
 552         int n = 0;
 553         final Type[] params = signature == null ? null : Type.getMethodArguments(signature);
 554         for (final Node arg : args) {
 555             assert arg != null;
 556             load(arg);
 557             if (n >= argCount) {
 558                 method.pop(); // we had to load the arg for its side effects
 559             } else if (params != null) {
 560                 method.convert(params[n]);
 561             }
 562             n++;
 563         }
 564 
 565         while (n < argCount) {
 566             method.loadUndefined(Type.OBJECT);
 567             n++;
 568         }
 569 
 570         return argCount;
 571     }
 572 
 573     @Override
 574     public boolean enterCallNode(final CallNode callNode) {
 575         lineNumber(callNode);
 576 
 577         final List<Node>   args            = callNode.getArgs();
 578         final Node         function        = callNode.getFunction();
 579         final Block        currentBlock    = lc.getCurrentBlock();
 580         final CodeGeneratorLexicalContext codegenLexicalContext = lc;
 581 
 582         function.accept(new NodeVisitor<LexicalContext>(new LexicalContext()) {
 583 
 584             private MethodEmitter sharedScopeCall(final IdentNode identNode, final int flags) {
 585                 final Symbol symbol = identNode.getSymbol();
 586                 int    scopeCallFlags = flags;
 587                 method.loadCompilerConstant(SCOPE);
 588                 if (isFastScope(symbol)) {
 589                     method.load(getScopeProtoDepth(currentBlock, symbol));
 590                     scopeCallFlags |= CALLSITE_FAST_SCOPE;
 591                 } else {
 592                     method.load(-1); // Bypass fast-scope code in shared callsite
 593                 }
 594                 loadArgs(args);
 595                 final Type[] paramTypes = method.getTypesFromStack(args.size());
 596                 final SharedScopeCall scopeCall = codegenLexicalContext.getScopeCall(unit, symbol, identNode.getType(), callNode.getType(), paramTypes, scopeCallFlags);
 597                 return scopeCall.generateInvoke(method);
 598             }
 599 
 600             private void scopeCall(final IdentNode node, final int flags) {
 601                 load(node);
 602                 method.convert(Type.OBJECT); // foo() makes no sense if foo == 3
 603                 // ScriptFunction will see CALLSITE_SCOPE and will bind scope accordingly.
 604                 method.loadNull(); //the 'this'
 605                 method.dynamicCall(callNode.getType(), 2 + loadArgs(args), flags);
 606             }
 607 
 608             private void evalCall(final IdentNode node, final int flags) {
 609                 load(node);
 610                 method.convert(Type.OBJECT); // foo() makes no sense if foo == 3
 611 
 612                 final Label not_eval  = new Label("not_eval");
 613                 final Label eval_done = new Label("eval_done");
 614 
 615                 // check if this is the real built-in eval
 616                 method.dup();
 617                 globalIsEval();
 618 
 619                 method.ifeq(not_eval);
 620                 // We don't need ScriptFunction object for 'eval'
 621                 method.pop();
 622 
 623                 method.loadCompilerConstant(SCOPE); // Load up self (scope).
 624 
 625                 final CallNode.EvalArgs evalArgs = callNode.getEvalArgs();
 626                 // load evaluated code
 627                 load(evalArgs.getCode());
 628                 method.convert(Type.OBJECT);
 629                 // special/extra 'eval' arguments
 630                 load(evalArgs.getThis());
 631                 method.load(evalArgs.getLocation());
 632                 method.load(evalArgs.getStrictMode());
 633                 method.convert(Type.OBJECT);
 634 
 635                 // direct call to Global.directEval
 636                 globalDirectEval();
 637                 method.convert(callNode.getType());
 638                 method._goto(eval_done);
 639 
 640                 method.label(not_eval);
 641                 // This is some scope 'eval' or global eval replaced by user
 642                 // but not the built-in ECMAScript 'eval' function call
 643                 method.loadNull();
 644                 method.dynamicCall(callNode.getType(), 2 + loadArgs(args), flags);
 645 
 646                 method.label(eval_done);
 647             }
 648 
 649             @Override
 650             public boolean enterIdentNode(final IdentNode node) {
 651                 final Symbol symbol = node.getSymbol();
 652 
 653                 if (symbol.isScope()) {
 654                     final int flags = getCallSiteFlags() | CALLSITE_SCOPE;
 655                     final int useCount = symbol.getUseCount();
 656 
 657                     // Threshold for generating shared scope callsite is lower for fast scope symbols because we know
 658                     // we can dial in the correct scope. However, we also need to enable it for non-fast scopes to
 659                     // support huge scripts like mandreel.js.
 660                     if (callNode.isEval()) {
 661                         evalCall(node, flags);
 662                     } else if (useCount <= SharedScopeCall.FAST_SCOPE_CALL_THRESHOLD
 663                             || (!isFastScope(symbol) && useCount <= SharedScopeCall.SLOW_SCOPE_CALL_THRESHOLD)
 664                             || CodeGenerator.this.lc.inDynamicScope()) {
 665                         scopeCall(node, flags);
 666                     } else {
 667                         sharedScopeCall(node, flags);
 668                     }
 669                     assert method.peekType().equals(callNode.getType()) : method.peekType() + "!=" + callNode.getType();
 670                 } else {
 671                     enterDefault(node);
 672                 }
 673 
 674                 return false;
 675             }
 676 
 677             @Override
 678             public boolean enterAccessNode(final AccessNode node) {
 679                 load(node.getBase());
 680                 method.convert(Type.OBJECT);
 681                 method.dup();
 682                 method.dynamicGet(node.getType(), node.getProperty().getName(), getCallSiteFlags(), true);
 683                 method.swap();
 684                 method.dynamicCall(callNode.getType(), 2 + loadArgs(args), getCallSiteFlags());
 685                 assert method.peekType().equals(callNode.getType());
 686 
 687                 return false;
 688             }
 689 
 690             @Override
 691             public boolean enterFunctionNode(final FunctionNode origCallee) {
 692                 // NOTE: visiting the callee will leave a constructed ScriptFunction object on the stack if
 693                 // callee.needsCallee() == true
 694                 final FunctionNode callee = (FunctionNode)origCallee.accept(CodeGenerator.this);
 695 
 696                 final boolean      isVarArg = callee.isVarArg();
 697                 final int          argCount = isVarArg ? -1 : callee.getParameters().size();
 698 
 699                 final String signature = new FunctionSignature(true, callee.needsCallee(), callee.getReturnType(), isVarArg ? null : callee.getParameters()).toString();
 700 
 701                 if (callee.isStrict()) { // self is undefined
 702                     method.loadUndefined(Type.OBJECT);
 703                 } else { // get global from scope (which is the self)
 704                     globalInstance();
 705                 }
 706                 loadArgs(args, signature, isVarArg, argCount);
 707                 assert callee.getCompileUnit() != null : "no compile unit for " + callee.getName() + " " + Debug.id(callee) + " " + callNode;
 708                 method.invokestatic(callee.getCompileUnit().getUnitClassName(), callee.getName(), signature);
 709                 assert method.peekType().equals(callee.getReturnType()) : method.peekType() + " != " + callee.getReturnType();
 710                 return false;
 711             }
 712 
 713             @Override
 714             public boolean enterIndexNode(final IndexNode node) {
 715                 load(node.getBase());
 716                 method.convert(Type.OBJECT);
 717                 method.dup();
 718                 load(node.getIndex());
 719                 final Type indexType = node.getIndex().getType();
 720                 if (indexType.isObject() || indexType.isBoolean()) {
 721                     method.convert(Type.OBJECT); //TODO
 722                 }
 723                 method.dynamicGetIndex(node.getType(), getCallSiteFlags(), true);
 724                 method.swap();
 725                 method.dynamicCall(callNode.getType(), 2 + loadArgs(args), getCallSiteFlags());
 726                 assert method.peekType().equals(callNode.getType());
 727 
 728                 return false;
 729             }
 730 
 731             @Override
 732             protected boolean enterDefault(final Node node) {
 733                 // Load up function.
 734                 load(function);
 735                 method.convert(Type.OBJECT); //TODO, e.g. booleans can be used as functions
 736                 method.loadNull(); // ScriptFunction will figure out the correct this when it sees CALLSITE_SCOPE
 737                 method.dynamicCall(callNode.getType(), 2 + loadArgs(args), getCallSiteFlags() | CALLSITE_SCOPE);
 738                 assert method.peekType().equals(callNode.getType());
 739 
 740                 return false;
 741             }
 742         });
 743 
 744         method.store(callNode.getSymbol());
 745 
 746         return false;
 747     }
 748 
 749     @Override
 750     public boolean enterContinueNode(final ContinueNode continueNode) {
 751         lineNumber(continueNode);
 752 
 753         final LoopNode continueTo = lc.getContinueTo(continueNode.getLabel());
 754         for (int i = 0; i < lc.getScopeNestingLevelTo(continueTo); i++) {
 755             closeWith();
 756         }
 757         method.splitAwareGoto(lc, continueTo.getContinueLabel());
 758 
 759         return false;
 760     }
 761 
 762     @Override
 763     public boolean enterEmptyNode(final EmptyNode emptyNode) {
 764         lineNumber(emptyNode);
 765 
 766         return false;
 767     }
 768 
 769     @Override
 770     public boolean enterExecuteNode(final ExecuteNode executeNode) {
 771         lineNumber(executeNode);
 772 
 773         final Node expression = executeNode.getExpression();
 774         expression.accept(this);
 775 
 776         return false;
 777     }
 778 
 779     @Override
 780     public boolean enterForNode(final ForNode forNode) {
 781         lineNumber(forNode);
 782 
 783         if (forNode.isForIn()) {
 784             enterForIn(forNode);
 785         } else {
 786             enterFor(forNode);
 787         }
 788 
 789         return false;
 790     }
 791 
 792     private void enterFor(final ForNode forNode) {
 793         final Node  init   = forNode.getInit();
 794         final Node  test   = forNode.getTest();
 795         final Block body   = forNode.getBody();
 796         final Node  modify = forNode.getModify();
 797 
 798         if (init != null) {
 799             init.accept(this);
 800         }
 801 
 802         final Label loopLabel = new Label("loop");
 803         final Label testLabel = new Label("test");
 804 
 805         method._goto(testLabel);
 806         method.label(loopLabel);
 807         body.accept(this);
 808         method.label(forNode.getContinueLabel());
 809 
 810         if (!body.isTerminal() && modify != null) {
 811             load(modify);
 812         }
 813 
 814         method.label(testLabel);
 815         if (test != null) {
 816             new BranchOptimizer(this, method).execute(test, loopLabel, true);
 817         } else {
 818             method._goto(loopLabel);
 819         }
 820 
 821         method.label(forNode.getBreakLabel());
 822     }
 823 
 824     private void enterForIn(final ForNode forNode) {
 825         final Block body   = forNode.getBody();
 826         final Node  modify = forNode.getModify();
 827 
 828         final Symbol iter      = forNode.getIterator();
 829         final Label  loopLabel = new Label("loop");
 830 
 831         Node init = forNode.getInit();
 832 
 833         // We have to evaluate the optional initializer expression
 834         // of the iterator variable of the for-in statement.
 835         if (init instanceof VarNode) {
 836             init.accept(this);
 837             init = ((VarNode)init).getName();
 838         }
 839 
 840         load(modify);
 841         assert modify.getType().isObject();
 842         method.invoke(forNode.isForEach() ? ScriptRuntime.TO_VALUE_ITERATOR : ScriptRuntime.TO_PROPERTY_ITERATOR);
 843         method.store(iter);
 844         method._goto(forNode.getContinueLabel());
 845         method.label(loopLabel);
 846 
 847         new Store<Node>(init) {
 848             @Override
 849             protected void storeNonDiscard() {
 850                 return;
 851             }
 852             @Override
 853             protected void evaluate() {
 854                 method.load(iter);
 855                 method.invoke(interfaceCallNoLookup(Iterator.class, "next", Object.class));
 856             }
 857         }.store();
 858 
 859         body.accept(this);
 860 
 861         method.label(forNode.getContinueLabel());
 862         method.load(iter);
 863         method.invoke(interfaceCallNoLookup(Iterator.class, "hasNext", boolean.class));
 864         method.ifne(loopLabel);
 865         method.label(forNode.getBreakLabel());
 866     }
 867 
 868     /**
 869      * Initialize the slots in a frame to undefined.
 870      *
 871      * @param block block with local vars.
 872      */
 873     private void initLocals(final Block block) {
 874         lc.nextFreeSlot(block);
 875 
 876         final boolean isFunctionBody = lc.isFunctionBody();
 877 
 878         final FunctionNode function = lc.getCurrentFunction();
 879         if (isFunctionBody) {
 880             /* Fix the predefined slots so they have numbers >= 0, like varargs. */
 881             if (function.needsParentScope()) {
 882                 initParentScope();
 883             }
 884             if (function.needsArguments()) {
 885                 initArguments(function);
 886             }
 887         }
 888 
 889         /*
 890          * Determine if block needs scope, if not, just do initSymbols for this block.
 891          */
 892         if (block.needsScope()) {
 893             /*
 894              * Determine if function is varargs and consequently variables have to
 895              * be in the scope.
 896              */
 897             final boolean varsInScope = function.allVarsInScope();
 898 
 899             // TODO for LET we can do better: if *block* does not contain any eval/with, we don't need its vars in scope.
 900 
 901             final List<String> nameList = new ArrayList<>();
 902             final List<Symbol> locals   = new ArrayList<>();
 903 
 904             // Initalize symbols and values
 905             final List<Symbol> newSymbols = new ArrayList<>();
 906             final List<Symbol> values     = new ArrayList<>();
 907 
 908             final boolean hasArguments = function.needsArguments();
 909 
 910             for (final Symbol symbol : block.getSymbols()) {
 911 
 912                 if (symbol.isInternal() || symbol.isThis() || symbol.isTemp()) {
 913                     continue;
 914                 }
 915 
 916                 if (symbol.isVar()) {
 917                     if (varsInScope || symbol.isScope()) {
 918                         nameList.add(symbol.getName());
 919                         newSymbols.add(symbol);
 920                         values.add(null);
 921                         assert symbol.isScope()   : "scope for " + symbol + " should have been set in Lower already " + function.getName();
 922                         assert !symbol.hasSlot()  : "slot for " + symbol + " should have been removed in Lower already" + function.getName();
 923                     } else {
 924                         assert symbol.hasSlot() : symbol + " should have a slot only, no scope";
 925                         locals.add(symbol);
 926                     }
 927                 } else if (symbol.isParam() && (varsInScope || hasArguments || symbol.isScope())) {
 928                     nameList.add(symbol.getName());
 929                     newSymbols.add(symbol);
 930                     values.add(hasArguments ? null : symbol);
 931                     assert symbol.isScope()   : "scope for " + symbol + " should have been set in Lower already " + function.getName() + " varsInScope="+varsInScope+" hasArguments="+hasArguments+" symbol.isScope()=" + symbol.isScope();
 932                     assert !(hasArguments && symbol.hasSlot())  : "slot for " + symbol + " should have been removed in Lower already " + function.getName();
 933                 }
 934             }
 935 
 936             // we may have locals that need to be initialized
 937             initSymbols(locals);
 938 
 939             /*
 940              * Create a new object based on the symbols and values, generate
 941              * bootstrap code for object
 942              */
 943             final FieldObjectCreator<Symbol> foc = new FieldObjectCreator<Symbol>(this, nameList, newSymbols, values, true, hasArguments) {
 944                 @Override
 945                 protected Type getValueType(final Symbol value) {
 946                     return value.getSymbolType();
 947                 }
 948 
 949                 @Override
 950                 protected void loadValue(final Symbol value) {
 951                     method.load(value);
 952                 }
 953 
 954                 @Override
 955                 protected void loadScope(MethodEmitter m) {
 956                     if (function.needsParentScope()) {
 957                         m.loadCompilerConstant(SCOPE);
 958                     } else {
 959                         m.loadNull();
 960                     }
 961                 }
 962             };
 963             foc.makeObject(method);
 964 
 965             // runScript(): merge scope into global
 966             if (isFunctionBody && function.isProgram()) {
 967                 method.invoke(ScriptRuntime.MERGE_SCOPE);
 968             }
 969 
 970             method.storeCompilerConstant(SCOPE);
 971         } else {
 972             // Since we don't have a scope, parameters didn't get assigned array indices by the FieldObjectCreator, so
 973             // we need to assign them separately here.
 974             int nextParam = 0;
 975             if (isFunctionBody && function.isVarArg()) {
 976                 for (final IdentNode param : function.getParameters()) {
 977                     param.getSymbol().setFieldIndex(nextParam++);
 978                 }
 979             }
 980 
 981             initSymbols(block.getSymbols());
 982         }
 983 
 984         // Debugging: print symbols? @see --print-symbols flag
 985         printSymbols(block, (isFunctionBody ? "Function " : "Block in ") + (function.getIdent() == null ? "<anonymous>" : function.getIdent().getName()));
 986     }
 987 
 988     private void initArguments(final FunctionNode function) {
 989         method.loadCompilerConstant(VARARGS);
 990         if (function.needsCallee()) {
 991             method.loadCompilerConstant(CALLEE);
 992         } else {
 993             // If function is strict mode, "arguments.callee" is not populated, so we don't necessarily need the
 994             // caller.
 995             assert function.isStrict();
 996             method.loadNull();
 997         }
 998         method.load(function.getParameters().size());
 999         globalAllocateArguments();
1000         method.storeCompilerConstant(ARGUMENTS);
1001     }
1002 
1003     private void initParentScope() {
1004         method.loadCompilerConstant(CALLEE);
1005         method.invoke(ScriptFunction.GET_SCOPE);
1006         method.storeCompilerConstant(SCOPE);
1007     }
1008 
1009     @Override
1010     public boolean enterFunctionNode(final FunctionNode functionNode) {
1011         if (functionNode.isLazy()) {
1012             // Must do it now; can't postpone it until leaveFunctionNode()
1013             newFunctionObject(functionNode, functionNode);
1014             return false;
1015         }
1016 
1017         LOG.info("=== BEGIN ", functionNode.getName());
1018 
1019         assert functionNode.getCompileUnit() != null : "no compile unit for " + functionNode.getName() + " " + Debug.id(functionNode);
1020         unit = lc.pushCompileUnit(functionNode.getCompileUnit());
1021         assert lc.hasCompileUnits();
1022 
1023         method = lc.pushMethodEmitter(unit.getClassEmitter().method(functionNode));
1024         // Mark end for variable tables.
1025         method.begin();
1026 
1027         return true;
1028     }
1029 
1030     @Override
1031     public Node leaveFunctionNode(final FunctionNode functionNode) {
1032         try {
1033             method.end(); // wrap up this method
1034             unit   = lc.popCompileUnit(functionNode.getCompileUnit());
1035             method = lc.popMethodEmitter(method);
1036             LOG.info("=== END ", functionNode.getName());
1037 
1038             final FunctionNode newFunctionNode = functionNode.setState(lc, CompilationState.EMITTED);
1039 
1040             newFunctionObject(newFunctionNode, functionNode);
1041             return newFunctionNode;
1042         } catch (final Throwable t) {
1043             Context.printStackTrace(t);
1044             final VerifyError e = new VerifyError("Code generation bug in \"" + functionNode.getName() + "\": likely stack misaligned: " + t + " " + functionNode.getSource().getName());
1045             e.initCause(t);
1046             throw e;
1047         }
1048     }
1049 
1050     @Override
1051     public boolean enterIdentNode(final IdentNode identNode) {
1052         return false;
1053     }
1054 
1055     @Override
1056     public boolean enterIfNode(final IfNode ifNode) {
1057         lineNumber(ifNode);
1058 
1059         final Node  test = ifNode.getTest();
1060         final Block pass = ifNode.getPass();
1061         final Block fail = ifNode.getFail();
1062 
1063         final Label failLabel  = new Label("if_fail");
1064         final Label afterLabel = fail == null ? failLabel : new Label("if_done");
1065 
1066         new BranchOptimizer(this, method).execute(test, failLabel, false);
1067 
1068         boolean passTerminal = false;
1069         boolean failTerminal = false;
1070 
1071         pass.accept(this);
1072         if (!pass.hasTerminalFlags()) {
1073             method._goto(afterLabel); //don't fallthru to fail block
1074         } else {
1075             passTerminal = pass.isTerminal();
1076         }
1077 
1078         if (fail != null) {
1079             method.label(failLabel);
1080             fail.accept(this);
1081             failTerminal = fail.isTerminal();
1082         }
1083 
1084         //if if terminates, put the after label there
1085         if (!passTerminal || !failTerminal) {
1086             method.label(afterLabel);
1087         }
1088 
1089         return false;
1090     }
1091 
1092     @Override
1093     public boolean enterIndexNode(final IndexNode indexNode) {
1094         load(indexNode);
1095         return false;
1096     }
1097 
1098     private void lineNumber(final Statement statement) {
1099         final int lineNumber = statement.getLineNumber();
1100         if (lineNumber != lastLineNumber) {
1101             method.lineNumber(statement.getLineNumber());
1102         }
1103         lastLineNumber = lineNumber;
1104     }
1105 
1106     /**
1107      * Load a list of nodes as an array of a specific type
1108      * The array will contain the visited nodes.
1109      *
1110      * @param arrayLiteralNode the array of contents
1111      * @param arrayType        the type of the array, e.g. ARRAY_NUMBER or ARRAY_OBJECT
1112      *
1113      * @return the method generator that was used
1114      */
1115     private MethodEmitter loadArray(final ArrayLiteralNode arrayLiteralNode, final ArrayType arrayType) {
1116         assert arrayType == Type.INT_ARRAY || arrayType == Type.NUMBER_ARRAY || arrayType == Type.OBJECT_ARRAY;
1117 
1118         final Node[]          nodes    = arrayLiteralNode.getValue();
1119         final Object          presets  = arrayLiteralNode.getPresets();
1120         final int[]           postsets = arrayLiteralNode.getPostsets();
1121         final Class<?>        type     = arrayType.getTypeClass();
1122         final List<ArrayUnit> units    = arrayLiteralNode.getUnits();
1123 
1124         loadConstant(presets);
1125 
1126         final Type elementType = arrayType.getElementType();
1127 
1128         if (units != null) {
1129             final MethodEmitter savedMethod = method;
1130 
1131             for (final ArrayUnit arrayUnit : units) {
1132                 unit = lc.pushCompileUnit(arrayUnit.getCompileUnit());
1133 
1134                 final String className = unit.getUnitClassName();
1135                 final String name      = lc.getCurrentFunction().uniqueName(SPLIT_PREFIX.symbolName());
1136                 final String signature = methodDescriptor(type, Object.class, ScriptFunction.class, ScriptObject.class, type);
1137 
1138                 final MethodEmitter me = unit.getClassEmitter().method(EnumSet.of(Flag.PUBLIC, Flag.STATIC), name, signature);
1139                 method = lc.pushMethodEmitter(me);
1140 
1141                 method.setFunctionNode(lc.getCurrentFunction());
1142                 method.begin();
1143 
1144                 fixScopeSlot();
1145 
1146                 method.load(arrayType, SPLIT_ARRAY_ARG.slot());
1147 
1148                 for (int i = arrayUnit.getLo(); i < arrayUnit.getHi(); i++) {
1149                     storeElement(nodes, elementType, postsets[i]);
1150                 }
1151 
1152                 method._return();
1153                 method.end();
1154                 method = lc.popMethodEmitter(me);
1155 
1156                 assert method == savedMethod;
1157                 method.loadCompilerConstant(THIS);
1158                 method.swap();
1159                 method.loadCompilerConstant(CALLEE);
1160                 method.swap();
1161                 method.loadCompilerConstant(SCOPE);
1162                 method.swap();
1163                 method.invokestatic(className, name, signature);
1164 
1165                 unit = lc.popCompileUnit(unit);
1166             }
1167 
1168             return method;
1169         }
1170 
1171         for (final int postset : postsets) {
1172             storeElement(nodes, elementType, postset);
1173         }
1174 
1175         return method;
1176     }
1177 
1178     private void storeElement(final Node[] nodes, final Type elementType, final int index) {
1179         method.dup();
1180         method.load(index);
1181 
1182         final Node element = nodes[index];
1183 
1184         if (element == null) {
1185             method.loadEmpty(elementType);
1186         } else {
1187             assert elementType.isEquivalentTo(element.getType()) : "array element type doesn't match array type";
1188             load(element);
1189         }
1190 
1191         method.arraystore();
1192     }
1193 
1194     private MethodEmitter loadArgsArray(final List<Node> args) {
1195         final Object[] array = new Object[args.size()];
1196         loadConstant(array);
1197 
1198         for (int i = 0; i < args.size(); i++) {
1199             method.dup();
1200             method.load(i);
1201             load(args.get(i)).convert(Type.OBJECT); //has to be upcast to object or we fail
1202             method.arraystore();
1203         }
1204 
1205         return method;
1206     }
1207 
1208     /**
1209      * Load a constant from the constant array. This is only public to be callable from the objects
1210      * subpackage. Do not call directly.
1211      *
1212      * @param string string to load
1213      */
1214     void loadConstant(final String string) {
1215         final String       unitClassName = unit.getUnitClassName();
1216         final ClassEmitter classEmitter  = unit.getClassEmitter();
1217         final int          index         = compiler.getConstantData().add(string);
1218 
1219         method.load(index);
1220         method.invokestatic(unitClassName, GET_STRING.symbolName(), methodDescriptor(String.class, int.class));
1221         classEmitter.needGetConstantMethod(String.class);
1222     }
1223 
1224     /**
1225      * Load a constant from the constant array. This is only public to be callable from the objects
1226      * subpackage. Do not call directly.
1227      *
1228      * @param object object to load
1229      */
1230     void loadConstant(final Object object) {
1231         final String       unitClassName = unit.getUnitClassName();
1232         final ClassEmitter classEmitter  = unit.getClassEmitter();
1233         final int          index         = compiler.getConstantData().add(object);
1234         final Class<?>     cls           = object.getClass();
1235 
1236         if (cls == PropertyMap.class) {
1237             method.load(index);
1238             method.invokestatic(unitClassName, GET_MAP.symbolName(), methodDescriptor(PropertyMap.class, int.class));
1239             classEmitter.needGetConstantMethod(PropertyMap.class);
1240         } else if (cls.isArray()) {
1241             method.load(index);
1242             final String methodName = ClassEmitter.getArrayMethodName(cls);
1243             method.invokestatic(unitClassName, methodName, methodDescriptor(cls, int.class));
1244             classEmitter.needGetConstantMethod(cls);
1245         } else {
1246             method.loadConstants().load(index).arrayload();
1247             if (cls != Object.class) {
1248                 method.checkcast(cls);
1249             }
1250         }
1251     }
1252 
1253     // literal values
1254     private MethodEmitter load(final LiteralNode<?> node) {
1255         final Object value = node.getValue();
1256 
1257         if (value == null) {
1258             method.loadNull();
1259         } else if (value instanceof Undefined) {
1260             method.loadUndefined(Type.OBJECT);
1261         } else if (value instanceof String) {
1262             final String string = (String)value;
1263 
1264             if (string.length() > (MethodEmitter.LARGE_STRING_THRESHOLD / 3)) { // 3 == max bytes per encoded char
1265                 loadConstant(string);
1266             } else {
1267                 method.load(string);
1268             }
1269         } else if (value instanceof RegexToken) {
1270             loadRegex((RegexToken)value);
1271         } else if (value instanceof Boolean) {
1272             method.load((Boolean)value);
1273         } else if (value instanceof Integer) {
1274             method.load((Integer)value);
1275         } else if (value instanceof Long) {
1276             method.load((Long)value);
1277         } else if (value instanceof Double) {
1278             method.load((Double)value);
1279         } else if (node instanceof ArrayLiteralNode) {
1280             final ArrayType type = (ArrayType)node.getType();
1281             loadArray((ArrayLiteralNode)node, type);
1282             globalAllocateArray(type);
1283         } else {
1284             assert false : "Unknown literal for " + node.getClass() + " " + value.getClass() + " " + value;
1285         }
1286 
1287         return method;
1288     }
1289 
1290     private MethodEmitter loadRegexToken(final RegexToken value) {
1291         method.load(value.getExpression());
1292         method.load(value.getOptions());
1293         return globalNewRegExp();
1294     }
1295 
1296     private MethodEmitter loadRegex(final RegexToken regexToken) {
1297         if (regexFieldCount > MAX_REGEX_FIELDS) {
1298             return loadRegexToken(regexToken);
1299         }
1300         // emit field
1301         final String       regexName    = lc.getCurrentFunction().uniqueName(REGEX_PREFIX.symbolName());
1302         final ClassEmitter classEmitter = unit.getClassEmitter();
1303 
1304         classEmitter.field(EnumSet.of(PRIVATE, STATIC), regexName, Object.class);
1305         regexFieldCount++;
1306 
1307         // get field, if null create new regex, finally clone regex object
1308         method.getStatic(unit.getUnitClassName(), regexName, typeDescriptor(Object.class));
1309         method.dup();
1310         final Label cachedLabel = new Label("cached");
1311         method.ifnonnull(cachedLabel);
1312 
1313         method.pop();
1314         loadRegexToken(regexToken);
1315         method.dup();
1316         method.putStatic(unit.getUnitClassName(), regexName, typeDescriptor(Object.class));
1317 
1318         method.label(cachedLabel);
1319         globalRegExpCopy();
1320 
1321         return method;
1322     }
1323 
1324     @SuppressWarnings("rawtypes")
1325     @Override
1326     public boolean enterLiteralNode(final LiteralNode literalNode) {
1327         assert literalNode.getSymbol() != null : literalNode + " has no symbol";
1328         load(literalNode).store(literalNode.getSymbol());
1329         return false;
1330     }
1331 
1332     @Override
1333     public boolean enterObjectNode(final ObjectNode objectNode) {
1334         final List<Node> elements = objectNode.getElements();
1335         final int        size     = elements.size();
1336 
1337         final List<String> keys    = new ArrayList<>();
1338         final List<Symbol> symbols = new ArrayList<>();
1339         final List<Node>   values  = new ArrayList<>();
1340 
1341         boolean hasGettersSetters = false;
1342 
1343         for (int i = 0; i < size; i++) {
1344             final PropertyNode propertyNode = (PropertyNode)elements.get(i);
1345             final Node         value        = propertyNode.getValue();
1346             final String       key          = propertyNode.getKeyName();
1347             final Symbol       symbol       = value == null ? null : propertyNode.getSymbol();
1348 
1349             if (value == null) {
1350                 hasGettersSetters = true;
1351             }
1352 
1353             keys.add(key);
1354             symbols.add(symbol);
1355             values.add(value);
1356         }
1357 
1358         new FieldObjectCreator<Node>(this, keys, symbols, values) {
1359             @Override
1360             protected Type getValueType(final Node node) {
1361                 return node.getType();
1362             }
1363 
1364             @Override
1365             protected void loadValue(final Node node) {
1366                 load(node);
1367             }
1368 
1369             /**
1370              * Ensure that the properties start out as object types so that
1371              * we can do putfield initializations instead of dynamicSetIndex
1372              * which would be the case to determine initial property type
1373              * otherwise.
1374              *
1375              * Use case, it's very expensive to do a million var x = {a:obj, b:obj}
1376              * just to have to invalidate them immediately on initialization
1377              *
1378              * see NASHORN-594
1379              */
1380             @Override
1381             protected MapCreator newMapCreator(final Class<?> fieldObjectClass) {
1382                 return new MapCreator(fieldObjectClass, keys, symbols) {
1383                     @Override
1384                     protected int getPropertyFlags(final Symbol symbol, final boolean isVarArg) {
1385                         return super.getPropertyFlags(symbol, isVarArg) | Property.IS_ALWAYS_OBJECT;
1386                     }
1387                 };
1388             }
1389 
1390         }.makeObject(method);
1391 
1392         method.dup();
1393         globalObjectPrototype();
1394         method.invoke(ScriptObject.SET_PROTO);
1395 
1396         if (!hasGettersSetters) {
1397             method.store(objectNode.getSymbol());
1398             return false;
1399         }
1400 
1401         for (final Node element : elements) {
1402             final PropertyNode propertyNode = (PropertyNode)element;
1403             final Object       key          = propertyNode.getKey();
1404             final FunctionNode getter       = propertyNode.getGetter();
1405             final FunctionNode setter       = propertyNode.getSetter();
1406 
1407             if (getter == null && setter == null) {
1408                 continue;
1409             }
1410 
1411             method.dup().loadKey(key);
1412 
1413             if (getter == null) {
1414                 method.loadNull();
1415             } else {
1416                 getter.accept(this);
1417             }
1418 
1419             if (setter == null) {
1420                 method.loadNull();
1421             } else {
1422                 setter.accept(this);
1423             }
1424 
1425             method.invoke(ScriptObject.SET_USER_ACCESSORS);
1426         }
1427 
1428         method.store(objectNode.getSymbol());
1429 
1430         return false;
1431     }
1432 
1433     @Override
1434     public boolean enterReturnNode(final ReturnNode returnNode) {
1435         lineNumber(returnNode);
1436 
1437         method.registerReturn();
1438 
1439         final Type returnType = lc.getCurrentFunction().getReturnType();
1440 
1441         final Node expression = returnNode.getExpression();
1442         if (expression != null) {
1443             load(expression);
1444         } else {
1445             method.loadUndefined(returnType);
1446         }
1447 
1448         method._return(returnType);
1449 
1450         return false;
1451     }
1452 
1453     private static boolean isNullLiteral(final Node node) {
1454         return node instanceof LiteralNode<?> && ((LiteralNode<?>) node).isNull();
1455     }
1456 
1457     private boolean nullCheck(final RuntimeNode runtimeNode, final List<Node> args, final String signature) {
1458         final Request request = runtimeNode.getRequest();
1459 
1460         if (!Request.isEQ(request) && !Request.isNE(request)) {
1461             return false;
1462         }
1463 
1464         assert args.size() == 2 : "EQ or NE or TYPEOF need two args";
1465 
1466         Node lhs = args.get(0);
1467         Node rhs = args.get(1);
1468 
1469         if (isNullLiteral(lhs)) {
1470             final Node tmp = lhs;
1471             lhs = rhs;
1472             rhs = tmp;
1473         }
1474 
1475         if (isNullLiteral(rhs)) {
1476             final Label trueLabel  = new Label("trueLabel");
1477             final Label falseLabel = new Label("falseLabel");
1478             final Label endLabel   = new Label("end");
1479 
1480             load(lhs);
1481             method.dup();
1482             if (Request.isEQ(request)) {
1483                 method.ifnull(trueLabel);
1484             } else if (Request.isNE(request)) {
1485                 method.ifnonnull(trueLabel);
1486             } else {
1487                 assert false : "Invalid request " + request;
1488             }
1489 
1490             method.label(falseLabel);
1491             load(rhs);
1492             method.invokestatic(CompilerConstants.className(ScriptRuntime.class), request.toString(), signature);
1493             method._goto(endLabel);
1494 
1495             method.label(trueLabel);
1496             // if NE (not strict) this can be "undefined != null" which is supposed to be false
1497             if (request == Request.NE) {
1498                 method.loadUndefined(Type.OBJECT);
1499                 final Label isUndefined = new Label("isUndefined");
1500                 final Label afterUndefinedCheck = new Label("afterUndefinedCheck");
1501                 method.if_acmpeq(isUndefined);
1502                 // not undefined
1503                 method.load(true);
1504                 method._goto(afterUndefinedCheck);
1505                 method.label(isUndefined);
1506                 method.load(false);
1507                 method.label(afterUndefinedCheck);
1508             } else {
1509                 method.pop();
1510                 method.load(true);
1511             }
1512             method.label(endLabel);
1513             method.convert(runtimeNode.getType());
1514             method.store(runtimeNode.getSymbol());
1515 
1516             return true;
1517         }
1518 
1519         return false;
1520     }
1521 
1522     private boolean specializationCheck(final RuntimeNode.Request request, final Node node, final List<Node> args) {
1523         if (!request.canSpecialize()) {
1524             return false;
1525         }
1526 
1527         assert args.size() == 2;
1528         final Type returnType = node.getType();
1529 
1530         load(args.get(0));
1531         load(args.get(1));
1532 
1533         Request finalRequest = request;
1534 
1535         //if the request is a comparison, i.e. one that can be reversed
1536         //it keeps its semantic, but make sure that the object comes in
1537         //last
1538         final Request reverse = Request.reverse(request);
1539         if (method.peekType().isObject() && reverse != null) { //rhs is object
1540             if (!method.peekType(1).isObject()) { //lhs is not object
1541                 method.swap(); //prefer object as lhs
1542                 finalRequest = reverse;
1543             }
1544         }
1545 
1546         method.dynamicRuntimeCall(
1547                 new SpecializedRuntimeNode(
1548                     finalRequest,
1549                     new Type[] {
1550                         method.peekType(1),
1551                         method.peekType()
1552                     },
1553                     returnType).getInitialName(),
1554                 returnType,
1555                 finalRequest);
1556 
1557         method.convert(node.getType());
1558         method.store(node.getSymbol());
1559 
1560         return true;
1561     }
1562 
1563     private static boolean isReducible(final Request request) {
1564         return Request.isComparison(request) || request == Request.ADD;
1565     }
1566 
1567     @Override
1568     public boolean enterRuntimeNode(final RuntimeNode runtimeNode) {
1569         /*
1570          * First check if this should be something other than a runtime node
1571          * AccessSpecializer might have changed the type
1572          *
1573          * TODO - remove this - Access Specializer will always know after Attr/Lower
1574          */
1575         if (runtimeNode.isPrimitive() && !runtimeNode.isFinal() && isReducible(runtimeNode.getRequest())) {
1576             final Node lhs = runtimeNode.getArgs().get(0);
1577             assert runtimeNode.getArgs().size() > 1 : runtimeNode + " must have two args";
1578             final Node rhs = runtimeNode.getArgs().get(1);
1579 
1580             final Type   type   = runtimeNode.getType();
1581             final Symbol symbol = runtimeNode.getSymbol();
1582 
1583             switch (runtimeNode.getRequest()) {
1584             case EQ:
1585             case EQ_STRICT:
1586                 return enterCmp(lhs, rhs, Condition.EQ, type, symbol);
1587             case NE:
1588             case NE_STRICT:
1589                 return enterCmp(lhs, rhs, Condition.NE, type, symbol);
1590             case LE:
1591                 return enterCmp(lhs, rhs, Condition.LE, type, symbol);
1592             case LT:
1593                 return enterCmp(lhs, rhs, Condition.LT, type, symbol);
1594             case GE:
1595                 return enterCmp(lhs, rhs, Condition.GE, type, symbol);
1596             case GT:
1597                 return enterCmp(lhs, rhs, Condition.GT, type, symbol);
1598             case ADD:
1599                 Type widest = Type.widest(lhs.getType(), rhs.getType());
1600                 load(lhs);
1601                 method.convert(widest);
1602                 load(rhs);
1603                 method.convert(widest);
1604                 method.add();
1605                 method.convert(type);
1606                 method.store(symbol);
1607                 return false;
1608             default:
1609                 // it's ok to send this one on with only primitive arguments, maybe INSTANCEOF(true, true) or similar
1610                 // assert false : runtimeNode + " has all primitive arguments. This is an inconsistent state";
1611                 break;
1612             }
1613         }
1614 
1615         // Get the request arguments.
1616         final List<Node> args = runtimeNode.getArgs();
1617 
1618         if (nullCheck(runtimeNode, args, new FunctionSignature(false, false, runtimeNode.getType(), args).toString())) {
1619             return false;
1620         }
1621 
1622         if (!runtimeNode.isFinal() && specializationCheck(runtimeNode.getRequest(), runtimeNode, args)) {
1623             return false;
1624         }
1625 
1626         for (final Node arg : runtimeNode.getArgs()) {
1627             load(arg).convert(Type.OBJECT); //TODO this should not be necessary below Lower
1628         }
1629 
1630         method.invokestatic(
1631             CompilerConstants.className(ScriptRuntime.class),
1632             runtimeNode.getRequest().toString(),
1633             new FunctionSignature(
1634                 false,
1635                 false,
1636                 runtimeNode.getType(),
1637                 runtimeNode.getArgs().size()).toString());
1638         method.convert(runtimeNode.getType());
1639         method.store(runtimeNode.getSymbol());
1640 
1641         return false;
1642     }
1643 
1644     @Override
1645     public boolean enterSplitNode(final SplitNode splitNode) {
1646         lineNumber(splitNode);
1647 
1648         final CompileUnit splitCompileUnit = splitNode.getCompileUnit();
1649 
1650         final FunctionNode fn   = lc.getCurrentFunction();
1651         final String className  = splitCompileUnit.getUnitClassName();
1652         final String name       = splitNode.getName();
1653 
1654         final Class<?>   rtype          = fn.getReturnType().getTypeClass();
1655         final boolean    needsArguments = fn.needsArguments();
1656         final Class<?>[] ptypes         = needsArguments ?
1657                 new Class<?>[] {ScriptFunction.class, Object.class, ScriptObject.class, Object.class} :
1658                 new Class<?>[] {ScriptFunction.class, Object.class, ScriptObject.class};
1659 
1660         final MethodEmitter caller = method;
1661         unit = lc.pushCompileUnit(splitCompileUnit);
1662 
1663         final Call splitCall = staticCallNoLookup(
1664             className,
1665             name,
1666             methodDescriptor(rtype, ptypes));
1667 
1668         final MethodEmitter splitEmitter =
1669                 splitCompileUnit.getClassEmitter().method(
1670                         splitNode,
1671                         name,
1672                         rtype,
1673                         ptypes);
1674 
1675         method = lc.pushMethodEmitter(splitEmitter);
1676         method.setFunctionNode(fn);
1677 
1678         if (fn.needsCallee()) {
1679             caller.loadCompilerConstant(CALLEE);
1680         } else {
1681             caller.loadNull();
1682         }
1683         caller.loadCompilerConstant(THIS);
1684         caller.loadCompilerConstant(SCOPE);
1685         if (needsArguments) {
1686             caller.loadCompilerConstant(ARGUMENTS);
1687         }
1688         caller.invoke(splitCall);
1689         caller.storeCompilerConstant(RETURN);
1690 
1691         method.begin();
1692 
1693         method.loadUndefined(fn.getReturnType());
1694         method.storeCompilerConstant(RETURN);
1695 
1696         fixScopeSlot();
1697 
1698         return true;
1699     }
1700 
1701     private void fixScopeSlot() {
1702         if (lc.getCurrentFunction().compilerConstant(SCOPE).getSlot() != SCOPE.slot()) {
1703             // TODO hack to move the scope to the expected slot (that's needed because split methods reuse the same slots as the root method)
1704             method.load(Type.typeFor(ScriptObject.class), SCOPE.slot());
1705             method.storeCompilerConstant(SCOPE);
1706         }
1707     }
1708 
1709     @Override
1710     public Node leaveSplitNode(final SplitNode splitNode) {
1711         assert method instanceof SplitMethodEmitter;
1712         final boolean     hasReturn = method.hasReturn();
1713         final List<Label> targets   = method.getExternalTargets();
1714 
1715         try {
1716             // Wrap up this method.
1717 
1718             method.loadCompilerConstant(RETURN);
1719             method._return(lc.getCurrentFunction().getReturnType());
1720             method.end();
1721 
1722             unit   = lc.popCompileUnit(splitNode.getCompileUnit());
1723             method = lc.popMethodEmitter(method);
1724 
1725         } catch (final Throwable t) {
1726             Context.printStackTrace(t);
1727             final VerifyError e = new VerifyError("Code generation bug in \"" + splitNode.getName() + "\": likely stack misaligned: " + t + " " + lc.getCurrentFunction().getSource().getName());
1728             e.initCause(t);
1729             throw e;
1730         }
1731 
1732         // Handle return from split method if there was one.
1733         final MethodEmitter caller = method;
1734         final int     targetCount = targets.size();
1735 
1736         //no external jump targets or return in switch node
1737         if (!hasReturn && targets.isEmpty()) {
1738             return splitNode;
1739         }
1740 
1741         caller.loadCompilerConstant(SCOPE);
1742         caller.checkcast(Scope.class);
1743         caller.invoke(Scope.GET_SPLIT_STATE);
1744 
1745         final Label breakLabel = new Label("no_split_state");
1746         // Split state is -1 for no split state, 0 for return, 1..n+1 for break/continue
1747 
1748         //the common case is that we don't need a switch
1749         if (targetCount == 0) {
1750             assert hasReturn;
1751             caller.ifne(breakLabel);
1752             //has to be zero
1753             caller.label(new Label("split_return"));
1754             method.loadCompilerConstant(RETURN);
1755             caller._return(lc.getCurrentFunction().getReturnType());
1756             caller.label(breakLabel);
1757         } else {
1758             assert !targets.isEmpty();
1759 
1760             final int     low         = hasReturn ? 0 : 1;
1761             final int     labelCount  = targetCount + 1 - low;
1762             final Label[] labels      = new Label[labelCount];
1763 
1764             for (int i = 0; i < labelCount; i++) {
1765                 labels[i] = new Label(i == 0 ? "split_return" : "split_" + targets.get(i - 1));
1766             }
1767             caller.tableswitch(low, targetCount, breakLabel, labels);
1768             for (int i = low; i <= targetCount; i++) {
1769                 caller.label(labels[i - low]);
1770                 if (i == 0) {
1771                     caller.loadCompilerConstant(RETURN);
1772                     caller._return(lc.getCurrentFunction().getReturnType());
1773                 } else {
1774                     // Clear split state.
1775                     caller.loadCompilerConstant(SCOPE);
1776                     caller.checkcast(Scope.class);
1777                     caller.load(-1);
1778                     caller.invoke(Scope.SET_SPLIT_STATE);
1779                     caller.splitAwareGoto(lc, targets.get(i - 1));
1780                 }
1781             }
1782             caller.label(breakLabel);
1783         }
1784 
1785         return splitNode;
1786     }
1787 
1788     @Override
1789     public boolean enterSwitchNode(final SwitchNode switchNode) {
1790         lineNumber(switchNode);
1791 
1792         final Node           expression  = switchNode.getExpression();
1793         final Symbol         tag         = switchNode.getTag();
1794         final boolean        allInteger  = tag.getSymbolType().isInteger();
1795         final List<CaseNode> cases       = switchNode.getCases();
1796         final CaseNode       defaultCase = switchNode.getDefaultCase();
1797         final Label          breakLabel  = switchNode.getBreakLabel();
1798 
1799         Label defaultLabel = breakLabel;
1800         boolean hasDefault = false;
1801 
1802         if (defaultCase != null) {
1803             defaultLabel = defaultCase.getEntry();
1804             hasDefault = true;
1805         }
1806 
1807         if (cases.isEmpty()) {
1808             method.label(breakLabel);
1809             return false;
1810         }
1811 
1812         if (allInteger) {
1813             // Tree for sorting values.
1814             final TreeMap<Integer, Label> tree = new TreeMap<>();
1815 
1816             // Build up sorted tree.
1817             for (final CaseNode caseNode : cases) {
1818                 final Node test = caseNode.getTest();
1819 
1820                 if (test != null) {
1821                     final Integer value = (Integer)((LiteralNode<?>)test).getValue();
1822                     final Label   entry = caseNode.getEntry();
1823 
1824                     // Take first duplicate.
1825                     if (!(tree.containsKey(value))) {
1826                         tree.put(value, entry);
1827                     }
1828                 }
1829             }
1830 
1831             // Copy values and labels to arrays.
1832             final int       size   = tree.size();
1833             final Integer[] values = tree.keySet().toArray(new Integer[size]);
1834             final Label[]   labels = tree.values().toArray(new Label[size]);
1835 
1836             // Discern low, high and range.
1837             final int lo    = values[0];
1838             final int hi    = values[size - 1];
1839             final int range = hi - lo + 1;
1840 
1841             // Find an unused value for default.
1842             int deflt = Integer.MIN_VALUE;
1843             for (final int value : values) {
1844                 if (deflt == value) {
1845                     deflt++;
1846                 } else if (deflt < value) {
1847                     break;
1848                 }
1849             }
1850 
1851             // Load switch expression.
1852             load(expression);
1853             final Type type = expression.getType();
1854 
1855             // If expression not int see if we can convert, if not use deflt to trigger default.
1856             if (!type.isInteger()) {
1857                 method.load(deflt);
1858                 method.invoke(staticCallNoLookup(ScriptRuntime.class, "switchTagAsInt", int.class, type.getTypeClass(), int.class));
1859             }
1860 
1861             // If reasonable size and not too sparse (80%), use table otherwise use lookup.
1862             if (range > 0 && range < 4096 && range < (size * 5 / 4)) {
1863                 final Label[] table = new Label[range];
1864                 Arrays.fill(table, defaultLabel);
1865 
1866                 for (int i = 0; i < size; i++) {
1867                     final int value = values[i];
1868                     table[value - lo] = labels[i];
1869                 }
1870 
1871                 method.tableswitch(lo, hi, defaultLabel, table);
1872             } else {
1873                 final int[] ints = new int[size];
1874                 for (int i = 0; i < size; i++) {
1875                     ints[i] = values[i];
1876                 }
1877 
1878                 method.lookupswitch(defaultLabel, ints, labels);
1879             }
1880         } else {
1881             load(expression);
1882 
1883             if (expression.getType().isInteger()) {
1884                 method.convert(Type.NUMBER).dup();
1885                 method.store(tag);
1886                 method.conditionalJump(Condition.NE, true, defaultLabel);
1887             } else {
1888                 method.store(tag);
1889             }
1890 
1891             for (final CaseNode caseNode : cases) {
1892                 final Node test = caseNode.getTest();
1893 
1894                 if (test != null) {
1895                     method.load(tag);
1896                     load(test);
1897                     method.invoke(ScriptRuntime.EQ_STRICT);
1898                     method.ifne(caseNode.getEntry());
1899                 }
1900             }
1901 
1902             method._goto(hasDefault ? defaultLabel : breakLabel);
1903         }
1904 
1905         for (final CaseNode caseNode : cases) {
1906             method.label(caseNode.getEntry());
1907             caseNode.getBody().accept(this);
1908         }
1909 
1910         if (!switchNode.isTerminal()) {
1911             method.label(breakLabel);
1912         }
1913 
1914         return false;
1915     }
1916 
1917     @Override
1918     public boolean enterThrowNode(final ThrowNode throwNode) {
1919         lineNumber(throwNode);
1920 
1921         if (throwNode.isSyntheticRethrow()) {
1922             //do not wrap whatever this is in an ecma exception, just rethrow it
1923             load(throwNode.getExpression());
1924             method.athrow();
1925             return false;
1926         }
1927 
1928         method._new(ECMAException.class).dup();
1929 
1930         final Source source     = lc.getCurrentFunction().getSource();
1931 
1932         final Node   expression = throwNode.getExpression();
1933         final int    position   = throwNode.position();
1934         final int    line       = source.getLine(position);
1935         final int    column     = source.getColumn(position);
1936 
1937         load(expression);
1938         assert expression.getType().isObject();
1939 
1940         method.load(source.getName());
1941         method.load(line);
1942         method.load(column);
1943         method.invoke(ECMAException.THROW_INIT);
1944 
1945         method.athrow();
1946 
1947         return false;
1948     }
1949 
1950     @Override
1951     public boolean enterTryNode(final TryNode tryNode) {
1952         lineNumber(tryNode);
1953 
1954         final Block       body        = tryNode.getBody();
1955         final List<Block> catchBlocks = tryNode.getCatchBlocks();
1956         final Symbol      symbol      = tryNode.getException();
1957         final Label       entry       = new Label("try");
1958         final Label       recovery    = new Label("catch");
1959         final Label       exit        = tryNode.getExit();
1960         final Label       skip        = new Label("skip");
1961 
1962         method.label(entry);
1963 
1964         body.accept(this);
1965 
1966         if (!body.hasTerminalFlags()) {
1967             method._goto(skip);
1968         }
1969 
1970         method.label(exit);
1971 
1972         method._catch(recovery);
1973         method.store(symbol);
1974 
1975         for (int i = 0; i < catchBlocks.size(); i++) {
1976             final Block catchBlock = catchBlocks.get(i);
1977 
1978             //TODO this is very ugly - try not to call enter/leave methods directly
1979             //better to use the implicit lexical context scoping given by the visitor's
1980             //accept method.
1981             lc.push(catchBlock);
1982             enterBlock(catchBlock);
1983 
1984             final CatchNode catchNode          = (CatchNode)catchBlocks.get(i).getStatements().get(0);
1985             final IdentNode exception          = catchNode.getException();
1986             final Node      exceptionCondition = catchNode.getExceptionCondition();
1987             final Block     catchBody          = catchNode.getBody();
1988 
1989             new Store<IdentNode>(exception) {
1990                 @Override
1991                 protected void storeNonDiscard() {
1992                     return;
1993                 }
1994 
1995                 @Override
1996                 protected void evaluate() {
1997                     if (catchNode.isSyntheticRethrow()) {
1998                         method.load(symbol);
1999                         return;
2000                     }
2001                     /*
2002                      * If caught object is an instance of ECMAException, then
2003                      * bind obj.thrown to the script catch var. Or else bind the
2004                      * caught object itself to the script catch var.
2005                      */
2006                     final Label notEcmaException = new Label("no_ecma_exception");
2007                     method.load(symbol).dup()._instanceof(ECMAException.class).ifeq(notEcmaException);
2008                     method.checkcast(ECMAException.class); //TODO is this necessary?
2009                     method.getField(ECMAException.THROWN);
2010                     method.label(notEcmaException);
2011                 }
2012             }.store();
2013 
2014             final Label next;
2015 
2016             if (exceptionCondition != null) {
2017                 next = new Label("next");
2018                 load(exceptionCondition).convert(Type.BOOLEAN).ifeq(next);
2019             } else {
2020                 next = null;
2021             }
2022 
2023             catchBody.accept(this);
2024 
2025             if (i + 1 != catchBlocks.size() && !catchBody.hasTerminalFlags()) {
2026                 method._goto(skip);
2027             }
2028 
2029             if (next != null) {
2030                 if (i + 1 == catchBlocks.size()) {
2031                     // no next catch block - rethrow if condition failed
2032                     method._goto(skip);
2033                     method.label(next);
2034                     method.load(symbol).athrow();
2035                 } else {
2036                     method.label(next);
2037                 }
2038             }
2039 
2040             leaveBlock(catchBlock);
2041             lc.pop(catchBlock);
2042         }
2043 
2044         method.label(skip);
2045         method._try(entry, exit, recovery, Throwable.class);
2046 
2047         // Finally body is always inlined elsewhere so it doesn't need to be emitted
2048 
2049         return false;
2050     }
2051 
2052     @Override
2053     public boolean enterVarNode(final VarNode varNode) {
2054 
2055         final Node init = varNode.getInit();
2056 
2057         if (init == null) {
2058             return false;
2059         }
2060 
2061         lineNumber(varNode);
2062 
2063         final Symbol varSymbol = varNode.getSymbol();
2064         assert varSymbol != null : "variable node " + varNode + " requires a symbol";
2065 
2066         assert method != null;
2067 
2068         final boolean needsScope = varSymbol.isScope();
2069         if (needsScope) {
2070             method.loadCompilerConstant(SCOPE);
2071         }
2072         load(init);
2073 
2074         if (needsScope) {
2075             int flags = CALLSITE_SCOPE | getCallSiteFlags();
2076             final IdentNode identNode = varNode.getName();
2077             final Type type = identNode.getType();
2078             if (isFastScope(varSymbol)) {
2079                 storeFastScopeVar(type, varSymbol, flags);
2080             } else {
2081                 method.dynamicSet(type, identNode.getName(), flags);
2082             }
2083         } else {
2084             assert varNode.getType() == varNode.getName().getType() : "varNode type=" + varNode.getType() + " nametype=" + varNode.getName().getType() + " inittype=" + init.getType();
2085 
2086             method.convert(varNode.getType()); // aw: convert moved here
2087             method.store(varSymbol);
2088         }
2089 
2090         return false;
2091     }
2092 
2093     @Override
2094     public boolean enterWhileNode(final WhileNode whileNode) {
2095         lineNumber(whileNode);
2096 
2097         final Node  test          = whileNode.getTest();
2098         final Block body          = whileNode.getBody();
2099         final Label breakLabel    = whileNode.getBreakLabel();
2100         final Label continueLabel = whileNode.getContinueLabel();
2101         final Label loopLabel     = new Label("loop");
2102 
2103         if (!whileNode.isDoWhile()) {
2104             method._goto(continueLabel);
2105         }
2106 
2107         method.label(loopLabel);
2108         body.accept(this);
2109         if (!whileNode.isTerminal()) {
2110             method.label(continueLabel);
2111             new BranchOptimizer(this, method).execute(test, loopLabel, true);
2112             method.label(breakLabel);
2113         }
2114 
2115         return false;
2116     }
2117 
2118     private void closeWith() {
2119         if (method.hasScope()) {
2120             method.loadCompilerConstant(SCOPE);
2121             method.invoke(ScriptRuntime.CLOSE_WITH);
2122             method.storeCompilerConstant(SCOPE);
2123         }
2124     }
2125 
2126     @Override
2127     public boolean enterWithNode(final WithNode withNode) {
2128         final Node expression = withNode.getExpression();
2129         final Node body       = withNode.getBody();
2130 
2131         // It is possible to have a "pathological" case where the with block does not reference *any* identifiers. It's
2132         // pointless, but legal. In that case, if nothing else in the method forced the assignment of a slot to the
2133         // scope object, its' possible that it won't have a slot assigned. In this case we'll only evaluate expression
2134         // for its side effect and visit the body, and not bother opening and closing a WithObject.
2135         final boolean hasScope = method.hasScope();
2136 
2137         final Label tryLabel;
2138         if (hasScope) {
2139             tryLabel = new Label("with_try");
2140             method.label(tryLabel);
2141             method.loadCompilerConstant(SCOPE);
2142         } else {
2143             tryLabel = null;
2144         }
2145 
2146         load(expression);
2147         assert expression.getType().isObject() : "with expression needs to be object: " + expression;
2148 
2149         if (hasScope) {
2150             // Construct a WithObject if we have a scope
2151             method.invoke(ScriptRuntime.OPEN_WITH);
2152             method.storeCompilerConstant(SCOPE);
2153         } else {
2154             // We just loaded the expression for its side effect; discard it
2155             method.pop();
2156         }
2157 
2158 
2159         // Always process body
2160         body.accept(this);
2161 
2162         if (hasScope) {
2163             // Ensure we always close the WithObject
2164             final Label endLabel   = new Label("with_end");
2165             final Label catchLabel = new Label("with_catch");
2166             final Label exitLabel  = new Label("with_exit");
2167 
2168             if (!body.isTerminal()) {
2169                 closeWith();
2170                 method._goto(exitLabel);
2171             }
2172 
2173             method.label(endLabel);
2174 
2175             method._catch(catchLabel);
2176             closeWith();
2177             method.athrow();
2178 
2179             method.label(exitLabel);
2180 
2181             method._try(tryLabel, endLabel, catchLabel);
2182         }
2183         return false;
2184     }
2185 
2186     @Override
2187     public boolean enterADD(final UnaryNode unaryNode) {
2188         load(unaryNode.rhs());
2189         assert unaryNode.rhs().getType().isNumber() : unaryNode.rhs().getType() + " "+ unaryNode.getSymbol();
2190         method.store(unaryNode.getSymbol());
2191 
2192         return false;
2193     }
2194 
2195     @Override
2196     public boolean enterBIT_NOT(final UnaryNode unaryNode) {
2197         load(unaryNode.rhs()).convert(Type.INT).load(-1).xor().store(unaryNode.getSymbol());
2198         return false;
2199     }
2200 
2201     // do this better with convert calls to method. TODO
2202     @Override
2203     public boolean enterCONVERT(final UnaryNode unaryNode) {
2204         final Node rhs = unaryNode.rhs();
2205         final Type to  = unaryNode.getType();
2206 
2207         if (to.isObject() && rhs instanceof LiteralNode) {
2208             final LiteralNode<?> literalNode = (LiteralNode<?>)rhs;
2209             final Object value = literalNode.getValue();
2210 
2211             if (value instanceof Number) {
2212                 assert !to.isArray() : "type hygiene - cannot convert number to array: (" + to.getTypeClass().getSimpleName() + ')' + value;
2213                 if (value instanceof Integer) {
2214                     method.load((Integer)value);
2215                 } else if (value instanceof Long) {
2216                     method.load((Long)value);
2217                 } else if (value instanceof Double) {
2218                     method.load((Double)value);
2219                 } else {
2220                     assert false;
2221                 }
2222                 method.convert(Type.OBJECT);
2223             } else if (value instanceof Boolean) {
2224                 method.getField(staticField(Boolean.class, value.toString().toUpperCase(Locale.ENGLISH), Boolean.class));
2225             } else {
2226                 load(rhs);
2227                 method.convert(unaryNode.getType());
2228             }
2229         } else {
2230             load(rhs);
2231             method.convert(unaryNode.getType());
2232         }
2233 
2234         method.store(unaryNode.getSymbol());
2235 
2236         return false;
2237     }
2238 
2239     @Override
2240     public boolean enterDECINC(final UnaryNode unaryNode) {
2241         final Node      rhs         = unaryNode.rhs();
2242         final Type      type        = unaryNode.getType();
2243         final TokenType tokenType   = unaryNode.tokenType();
2244         final boolean   isPostfix   = tokenType == TokenType.DECPOSTFIX || tokenType == TokenType.INCPOSTFIX;
2245         final boolean   isIncrement = tokenType == TokenType.INCPREFIX || tokenType == TokenType.INCPOSTFIX;
2246 
2247         assert !type.isObject();
2248 
2249         new SelfModifyingStore<UnaryNode>(unaryNode, rhs) {
2250 
2251             @Override
2252             protected void evaluate() {
2253                 load(rhs, true);
2254 
2255                 method.convert(type);
2256                 if (!isPostfix) {
2257                     if (type.isInteger()) {
2258                         method.load(isIncrement ? 1 : -1);
2259                     } else if (type.isLong()) {
2260                         method.load(isIncrement ? 1L : -1L);
2261                     } else {
2262                         method.load(isIncrement ? 1.0 : -1.0);
2263                     }
2264                     method.add();
2265                 }
2266             }
2267 
2268             @Override
2269             protected void storeNonDiscard() {
2270                 super.storeNonDiscard();
2271                 if (isPostfix) {
2272                     if (type.isInteger()) {
2273                         method.load(isIncrement ? 1 : -1);
2274                     } else if (type.isLong()) {
2275                         method.load(isIncrement ? 1L : 1L);
2276                     } else {
2277                         method.load(isIncrement ? 1.0 : -1.0);
2278                     }
2279                     method.add();
2280                 }
2281             }
2282         }.store();
2283 
2284         return false;
2285     }
2286 
2287     @Override
2288     public boolean enterDISCARD(final UnaryNode unaryNode) {
2289         final Node rhs = unaryNode.rhs();
2290 
2291         lc.pushDiscard(rhs);
2292         load(rhs);
2293 
2294         if (lc.getCurrentDiscard() == rhs) {
2295             assert !rhs.isAssignment();
2296             method.pop();
2297             lc.popDiscard();
2298         }
2299 
2300         return false;
2301     }
2302 
2303     @Override
2304     public boolean enterNEW(final UnaryNode unaryNode) {
2305         final CallNode callNode = (CallNode)unaryNode.rhs();
2306         final List<Node> args   = callNode.getArgs();
2307 
2308         // Load function reference.
2309         load(callNode.getFunction()).convert(Type.OBJECT); // must detect type error
2310 
2311         method.dynamicNew(1 + loadArgs(args), getCallSiteFlags());
2312         method.store(unaryNode.getSymbol());
2313 
2314         return false;
2315     }
2316 
2317     @Override
2318     public boolean enterNOT(final UnaryNode unaryNode) {
2319         final Node rhs = unaryNode.rhs();
2320 
2321         load(rhs);
2322 
2323         final Label trueLabel  = new Label("true");
2324         final Label afterLabel = new Label("after");
2325 
2326         method.convert(Type.BOOLEAN);
2327         method.ifne(trueLabel);
2328         method.load(true);
2329         method._goto(afterLabel);
2330         method.label(trueLabel);
2331         method.load(false);
2332         method.label(afterLabel);
2333         method.store(unaryNode.getSymbol());
2334 
2335         return false;
2336     }
2337 
2338     @Override
2339     public boolean enterSUB(final UnaryNode unaryNode) {
2340         load(unaryNode.rhs()).neg().store(unaryNode.getSymbol());
2341 
2342         return false;
2343     }
2344 
2345     private Node enterNumericAdd(final Node lhs, final Node rhs, final Type type, final Symbol symbol) {
2346         assert lhs.getType().equals(rhs.getType()) && lhs.getType().equals(type) : lhs.getType() + " != " + rhs.getType() + " != " + type + " " + new ASTWriter(lhs) + " " + new ASTWriter(rhs);
2347         load(lhs);
2348         load(rhs);
2349         method.add(); //if the symbol is optimistic, it always needs to be written, not on the stack?
2350         method.store(symbol);
2351         return null;
2352     }
2353 
2354     @Override
2355     public boolean enterADD(final BinaryNode binaryNode) {
2356         final Node lhs = binaryNode.lhs();
2357         final Node rhs = binaryNode.rhs();
2358 
2359         final Type type = binaryNode.getType();
2360         if (type.isNumeric()) {
2361             enterNumericAdd(lhs, rhs, type, binaryNode.getSymbol());
2362         } else {
2363             load(lhs).convert(Type.OBJECT);
2364             load(rhs).convert(Type.OBJECT);
2365             method.add();
2366             method.store(binaryNode.getSymbol());
2367         }
2368 
2369         return false;
2370     }
2371 
2372     private boolean enterAND_OR(final BinaryNode binaryNode) {
2373         final Node lhs = binaryNode.lhs();
2374         final Node rhs = binaryNode.rhs();
2375 
2376         final Label skip = new Label("skip");
2377 
2378         load(lhs).convert(Type.OBJECT).dup().convert(Type.BOOLEAN);
2379 
2380         if (binaryNode.tokenType() == TokenType.AND) {
2381             method.ifeq(skip);
2382         } else {
2383             method.ifne(skip);
2384         }
2385 
2386         method.pop();
2387         load(rhs).convert(Type.OBJECT);
2388         method.label(skip);
2389         method.store(binaryNode.getSymbol());
2390 
2391         return false;
2392     }
2393 
2394     @Override
2395     public boolean enterAND(final BinaryNode binaryNode) {
2396         return enterAND_OR(binaryNode);
2397     }
2398 
2399     @Override
2400     public boolean enterASSIGN(final BinaryNode binaryNode) {
2401         final Node lhs = binaryNode.lhs();
2402         final Node rhs = binaryNode.rhs();
2403 
2404         final Type lhsType = lhs.getType();
2405         final Type rhsType = rhs.getType();
2406 
2407         if (!lhsType.isEquivalentTo(rhsType)) {
2408             //this is OK if scoped, only locals are wrong
2409             assert !(lhs instanceof IdentNode) || lhs.getSymbol().isScope() : new ASTWriter(binaryNode);
2410         }
2411 
2412         new Store<BinaryNode>(binaryNode, lhs) {
2413             @Override
2414             protected void evaluate() {
2415                 load(rhs);
2416             }
2417         }.store();
2418 
2419         return false;
2420     }
2421 
2422     /**
2423      * Helper class for assignment ops, e.g. *=, += and so on..
2424      */
2425     private abstract class AssignOp extends SelfModifyingStore<BinaryNode> {
2426 
2427         /** The type of the resulting operation */
2428         private final Type opType;
2429 
2430         /**
2431          * Constructor
2432          *
2433          * @param node the assign op node
2434          */
2435         AssignOp(final BinaryNode node) {
2436             this(node.getType(), node);
2437         }
2438 
2439         /**
2440          * Constructor
2441          *
2442          * @param opType type of the computation - overriding the type of the node
2443          * @param node the assign op node
2444          */
2445         AssignOp(final Type opType, final BinaryNode node) {
2446             super(node, node.lhs());
2447             this.opType = opType;
2448         }
2449 
2450         protected abstract void op();
2451 
2452         @Override
2453         protected void evaluate() {
2454             load(assignNode.lhs(), true).convert(opType);
2455             load(assignNode.rhs()).convert(opType);
2456             op();
2457             method.convert(assignNode.getType());
2458         }
2459     }
2460 
2461     @Override
2462     public boolean enterASSIGN_ADD(final BinaryNode binaryNode) {
2463         assert RuntimeNode.Request.ADD.canSpecialize();
2464         final Type lhsType = binaryNode.lhs().getType();
2465         final Type rhsType = binaryNode.rhs().getType();
2466         final boolean specialize = binaryNode.getType() == Type.OBJECT;
2467 
2468         new AssignOp(binaryNode) {
2469 
2470             @Override
2471             protected void op() {
2472                 if (specialize) {
2473                     method.dynamicRuntimeCall(
2474                             new SpecializedRuntimeNode(
2475                                 Request.ADD,
2476                                 new Type[] {
2477                                     lhsType,
2478                                     rhsType,
2479                                 },
2480                                 Type.OBJECT).getInitialName(),
2481                             Type.OBJECT,
2482                             Request.ADD);
2483                 } else {
2484                     method.add();
2485                 }
2486             }
2487 
2488             @Override
2489             protected void evaluate() {
2490                 super.evaluate();
2491             }
2492         }.store();
2493 
2494         return false;
2495     }
2496 
2497     @Override
2498     public boolean enterASSIGN_BIT_AND(final BinaryNode binaryNode) {
2499         new AssignOp(Type.INT, binaryNode) {
2500             @Override
2501             protected void op() {
2502                 method.and();
2503             }
2504         }.store();
2505 
2506         return false;
2507     }
2508 
2509     @Override
2510     public boolean enterASSIGN_BIT_OR(final BinaryNode binaryNode) {
2511         new AssignOp(Type.INT, binaryNode) {
2512             @Override
2513             protected void op() {
2514                 method.or();
2515             }
2516         }.store();
2517 
2518         return false;
2519     }
2520 
2521     @Override
2522     public boolean enterASSIGN_BIT_XOR(final BinaryNode binaryNode) {
2523         new AssignOp(Type.INT, binaryNode) {
2524             @Override
2525             protected void op() {
2526                 method.xor();
2527             }
2528         }.store();
2529 
2530         return false;
2531     }
2532 
2533     @Override
2534     public boolean enterASSIGN_DIV(final BinaryNode binaryNode) {
2535         new AssignOp(binaryNode) {
2536             @Override
2537             protected void op() {
2538                 method.div();
2539             }
2540         }.store();
2541 
2542         return false;
2543     }
2544 
2545     @Override
2546     public boolean enterASSIGN_MOD(final BinaryNode binaryNode) {
2547         new AssignOp(binaryNode) {
2548             @Override
2549             protected void op() {
2550                 method.rem();
2551             }
2552         }.store();
2553 
2554         return false;
2555     }
2556 
2557     @Override
2558     public boolean enterASSIGN_MUL(final BinaryNode binaryNode) {
2559         new AssignOp(binaryNode) {
2560             @Override
2561             protected void op() {
2562                 method.mul();
2563             }
2564         }.store();
2565 
2566         return false;
2567     }
2568 
2569     @Override
2570     public boolean enterASSIGN_SAR(final BinaryNode binaryNode) {
2571         new AssignOp(Type.INT, binaryNode) {
2572             @Override
2573             protected void op() {
2574                 method.sar();
2575             }
2576         }.store();
2577 
2578         return false;
2579     }
2580 
2581     @Override
2582     public boolean enterASSIGN_SHL(final BinaryNode binaryNode) {
2583         new AssignOp(Type.INT, binaryNode) {
2584             @Override
2585             protected void op() {
2586                 method.shl();
2587             }
2588         }.store();
2589 
2590         return false;
2591     }
2592 
2593     @Override
2594     public boolean enterASSIGN_SHR(final BinaryNode binaryNode) {
2595         new AssignOp(Type.INT, binaryNode) {
2596             @Override
2597             protected void op() {
2598                 method.shr();
2599                 method.convert(Type.LONG).load(JSType.MAX_UINT).and();
2600             }
2601         }.store();
2602 
2603         return false;
2604     }
2605 
2606     @Override
2607     public boolean enterASSIGN_SUB(final BinaryNode binaryNode) {
2608         new AssignOp(binaryNode) {
2609             @Override
2610             protected void op() {
2611                 method.sub();
2612             }
2613         }.store();
2614 
2615         return false;
2616     }
2617 
2618     /**
2619      * Helper class for binary arithmetic ops
2620      */
2621     private abstract class BinaryArith {
2622 
2623         protected abstract void op();
2624 
2625         protected void evaluate(final BinaryNode node) {
2626             load(node.lhs());
2627             load(node.rhs());
2628             op();
2629             method.store(node.getSymbol());
2630         }
2631     }
2632 
2633     @Override
2634     public boolean enterBIT_AND(final BinaryNode binaryNode) {
2635         new BinaryArith() {
2636             @Override
2637             protected void op() {
2638                 method.and();
2639             }
2640         }.evaluate(binaryNode);
2641 
2642         return false;
2643     }
2644 
2645     @Override
2646     public boolean enterBIT_OR(final BinaryNode binaryNode) {
2647         new BinaryArith() {
2648             @Override
2649             protected void op() {
2650                 method.or();
2651             }
2652         }.evaluate(binaryNode);
2653 
2654         return false;
2655     }
2656 
2657     @Override
2658     public boolean enterBIT_XOR(final BinaryNode binaryNode) {
2659         new BinaryArith() {
2660             @Override
2661             protected void op() {
2662                 method.xor();
2663             }
2664         }.evaluate(binaryNode);
2665 
2666         return false;
2667     }
2668 
2669     private boolean enterComma(final BinaryNode binaryNode) {
2670         final Node lhs = binaryNode.lhs();
2671         final Node rhs = binaryNode.rhs();
2672 
2673         load(lhs);
2674         load(rhs);
2675         method.store(binaryNode.getSymbol());
2676 
2677         return false;
2678     }
2679 
2680     @Override
2681     public boolean enterCOMMARIGHT(final BinaryNode binaryNode) {
2682         return enterComma(binaryNode);
2683     }
2684 
2685     @Override
2686     public boolean enterCOMMALEFT(final BinaryNode binaryNode) {
2687         return enterComma(binaryNode);
2688     }
2689 
2690     @Override
2691     public boolean enterDIV(final BinaryNode binaryNode) {
2692         new BinaryArith() {
2693             @Override
2694             protected void op() {
2695                 method.div();
2696             }
2697         }.evaluate(binaryNode);
2698 
2699         return false;
2700     }
2701 
2702     private boolean enterCmp(final Node lhs, final Node rhs, final Condition cond, final Type type, final Symbol symbol) {
2703         final Type lhsType = lhs.getType();
2704         final Type rhsType = rhs.getType();
2705 
2706         final Type widest = Type.widest(lhsType, rhsType);
2707         assert widest.isNumeric() || widest.isBoolean() : widest;
2708 
2709         load(lhs);
2710         method.convert(widest);
2711         load(rhs);
2712         method.convert(widest);
2713 
2714         final Label trueLabel  = new Label("trueLabel");
2715         final Label afterLabel = new Label("skip");
2716 
2717         method.conditionalJump(cond, trueLabel);
2718 
2719         method.load(Boolean.FALSE);
2720         method._goto(afterLabel);
2721         method.label(trueLabel);
2722         method.load(Boolean.TRUE);
2723         method.label(afterLabel);
2724 
2725         method.convert(type);
2726         method.store(symbol);
2727 
2728         return false;
2729     }
2730 
2731     private boolean enterCmp(final BinaryNode binaryNode, final Condition cond) {
2732         return enterCmp(binaryNode.lhs(), binaryNode.rhs(), cond, binaryNode.getType(), binaryNode.getSymbol());
2733     }
2734 
2735     @Override
2736     public boolean enterEQ(final BinaryNode binaryNode) {
2737         return enterCmp(binaryNode, Condition.EQ);
2738     }
2739 
2740     @Override
2741     public boolean enterEQ_STRICT(final BinaryNode binaryNode) {
2742         return enterCmp(binaryNode, Condition.EQ);
2743     }
2744 
2745     @Override
2746     public boolean enterGE(final BinaryNode binaryNode) {
2747         return enterCmp(binaryNode, Condition.GE);
2748     }
2749 
2750     @Override
2751     public boolean enterGT(final BinaryNode binaryNode) {
2752         return enterCmp(binaryNode, Condition.GT);
2753     }
2754 
2755     @Override
2756     public boolean enterLE(final BinaryNode binaryNode) {
2757         return enterCmp(binaryNode, Condition.LE);
2758     }
2759 
2760     @Override
2761     public boolean enterLT(final BinaryNode binaryNode) {
2762         return enterCmp(binaryNode, Condition.LT);
2763     }
2764 
2765     @Override
2766     public boolean enterMOD(final BinaryNode binaryNode) {
2767         new BinaryArith() {
2768             @Override
2769             protected void op() {
2770                 method.rem();
2771             }
2772         }.evaluate(binaryNode);
2773 
2774         return false;
2775     }
2776 
2777     @Override
2778     public boolean enterMUL(final BinaryNode binaryNode) {
2779         new BinaryArith() {
2780             @Override
2781             protected void op() {
2782                 method.mul();
2783             }
2784         }.evaluate(binaryNode);
2785 
2786         return false;
2787     }
2788 
2789     @Override
2790     public boolean enterNE(final BinaryNode binaryNode) {
2791         return enterCmp(binaryNode, Condition.NE);
2792     }
2793 
2794     @Override
2795     public boolean enterNE_STRICT(final BinaryNode binaryNode) {
2796         return enterCmp(binaryNode, Condition.NE);
2797     }
2798 
2799     @Override
2800     public boolean enterOR(final BinaryNode binaryNode) {
2801         return enterAND_OR(binaryNode);
2802     }
2803 
2804     @Override
2805     public boolean enterSAR(final BinaryNode binaryNode) {
2806         new BinaryArith() {
2807             @Override
2808             protected void op() {
2809                 method.sar();
2810             }
2811         }.evaluate(binaryNode);
2812 
2813         return false;
2814     }
2815 
2816     @Override
2817     public boolean enterSHL(final BinaryNode binaryNode) {
2818         new BinaryArith() {
2819             @Override
2820             protected void op() {
2821                 method.shl();
2822             }
2823         }.evaluate(binaryNode);
2824 
2825         return false;
2826     }
2827 
2828     @Override
2829     public boolean enterSHR(final BinaryNode binaryNode) {
2830         new BinaryArith() {
2831             @Override
2832             protected void op() {
2833                 method.shr();
2834                 method.convert(Type.LONG).load(JSType.MAX_UINT).and();
2835             }
2836         }.evaluate(binaryNode);
2837 
2838         return false;
2839     }
2840 
2841     @Override
2842     public boolean enterSUB(final BinaryNode binaryNode) {
2843         new BinaryArith() {
2844             @Override
2845             protected void op() {
2846                 method.sub();
2847             }
2848         }.evaluate(binaryNode);
2849 
2850         return false;
2851     }
2852 
2853     @Override
2854     public boolean enterTernaryNode(final TernaryNode ternaryNode) {
2855         final Node lhs   = ternaryNode.lhs();
2856         final Node rhs   = ternaryNode.rhs();
2857         final Node third = ternaryNode.third();
2858 
2859         final Symbol symbol     = ternaryNode.getSymbol();
2860         final Label  falseLabel = new Label("ternary_false");
2861         final Label  exitLabel  = new Label("ternary_exit");
2862 
2863         Type widest = Type.widest(rhs.getType(), third.getType());
2864         if (rhs.getType().isArray() || third.getType().isArray()) { //loadArray creates a Java array type on the stack, calls global allocate, which creates a native array type
2865             widest = Type.OBJECT;
2866         }
2867 
2868         load(lhs);
2869         assert lhs.getType().isBoolean() : "lhs in ternary must be boolean";
2870 
2871         // we still keep the conversion here as the AccessSpecializer can have separated the types, e.g. var y = x ? x=55 : 17
2872         // will left as (Object)x=55 : (Object)17 by Lower. Then the first term can be {I}x=55 of type int, which breaks the
2873         // symmetry for the temporary slot for this TernaryNode. This is evidence that we assign types and explicit conversions
2874         // to early, or Apply the AccessSpecializer too late. We are mostly probably looking for a separate type pass to
2875         // do this property. Then we never need any conversions in CodeGenerator
2876         method.ifeq(falseLabel);
2877         load(rhs);
2878         method.convert(widest);
2879         method._goto(exitLabel);
2880         method.label(falseLabel);
2881         load(third);
2882         method.convert(widest);
2883         method.label(exitLabel);
2884         method.store(symbol);
2885 
2886         return false;
2887     }
2888 
2889     /**
2890      * Generate all shared scope calls generated during codegen.
2891      */
2892     protected void generateScopeCalls() {
2893         for (final SharedScopeCall scopeAccess : lc.getScopeCalls()) {
2894             scopeAccess.generateScopeCall();
2895         }
2896     }
2897 
2898     /**
2899      * Debug code used to print symbols
2900      *
2901      * @param block the block we are in
2902      * @param ident identifier for block or function where applicable
2903      */
2904     @SuppressWarnings("resource")
2905     private void printSymbols(final Block block, final String ident) {
2906         if (!compiler.getEnv()._print_symbols) {
2907             return;
2908         }
2909 
2910         final PrintWriter out = compiler.getEnv().getErr();
2911         out.println("[BLOCK in '" + ident + "']");
2912         if (!block.printSymbols(out)) {
2913             out.println("<no symbols>");
2914         }
2915         out.println();
2916     }
2917 
2918 
2919     /**
2920      * The difference between a store and a self modifying store is that
2921      * the latter may load part of the target on the stack, e.g. the base
2922      * of an AccessNode or the base and index of an IndexNode. These are used
2923      * both as target and as an extra source. Previously it was problematic
2924      * for self modifying stores if the target/lhs didn't belong to one
2925      * of three trivial categories: IdentNode, AcessNodes, IndexNodes. In that
2926      * case it was evaluated and tagged as "resolved", which meant at the second
2927      * time the lhs of this store was read (e.g. in a = a (second) + b for a += b,
2928      * it would be evaluated to a nop in the scope and cause stack underflow
2929      *
2930      * see NASHORN-703
2931      *
2932      * @param <T>
2933      */
2934     private abstract class SelfModifyingStore<T extends Node> extends Store<T> {
2935         protected SelfModifyingStore(final T assignNode, final Node target) {
2936             super(assignNode, target);
2937         }
2938 
2939         @Override
2940         protected boolean isSelfModifying() {
2941             return true;
2942         }
2943     }
2944 
2945     /**
2946      * Helper class to generate stores
2947      */
2948     private abstract class Store<T extends Node> {
2949 
2950         /** An assignment node, e.g. x += y */
2951         protected final T assignNode;
2952 
2953         /** The target node to store to, e.g. x */
2954         private final Node target;
2955 
2956         /** How deep on the stack do the arguments go if this generates an indy call */
2957         private int depth;
2958 
2959         /** If we have too many arguments, we need temporary storage, this is stored in 'quick' */
2960         private Symbol quick;
2961 
2962         /**
2963          * Constructor
2964          *
2965          * @param assignNode the node representing the whole assignment
2966          * @param target     the target node of the assignment (destination)
2967          */
2968         protected Store(final T assignNode, final Node target) {
2969             this.assignNode = assignNode;
2970             this.target = target;
2971         }
2972 
2973         /**
2974          * Constructor
2975          *
2976          * @param assignNode the node representing the whole assignment
2977          */
2978         protected Store(final T assignNode) {
2979             this(assignNode, assignNode);
2980         }
2981 
2982         /**
2983          * Is this a self modifying store operation, e.g. *= or ++
2984          * @return true if self modifying store
2985          */
2986         protected boolean isSelfModifying() {
2987             return false;
2988         }
2989 
2990         private void prologue() {
2991             final Symbol targetSymbol = target.getSymbol();
2992             final Symbol scopeSymbol  = lc.getCurrentFunction().compilerConstant(SCOPE);
2993 
2994             /**
2995              * This loads the parts of the target, e.g base and index. they are kept
2996              * on the stack throughout the store and used at the end to execute it
2997              */
2998 
2999             target.accept(new NodeVisitor<LexicalContext>(new LexicalContext()) {
3000                 @Override
3001                 public boolean enterIdentNode(final IdentNode node) {
3002                     if (targetSymbol.isScope()) {
3003                         method.load(scopeSymbol);
3004                         depth++;
3005                     }
3006                     return false;
3007                 }
3008 
3009                 private void enterBaseNode() {
3010                     assert target instanceof BaseNode : "error - base node " + target + " must be instanceof BaseNode";
3011                     final BaseNode baseNode = (BaseNode)target;
3012                     final Node     base     = baseNode.getBase();
3013 
3014                     load(base);
3015                     method.convert(Type.OBJECT);
3016                     depth += Type.OBJECT.getSlots();
3017 
3018                     if (isSelfModifying()) {
3019                         method.dup();
3020                     }
3021                 }
3022 
3023                 @Override
3024                 public boolean enterAccessNode(final AccessNode node) {
3025                     enterBaseNode();
3026                     return false;
3027                 }
3028 
3029                 @Override
3030                 public boolean enterIndexNode(final IndexNode node) {
3031                     enterBaseNode();
3032 
3033                     final Node index = node.getIndex();
3034                     // could be boolean here as well
3035                     load(index);
3036                     if (!index.getType().isNumeric()) {
3037                         method.convert(Type.OBJECT);
3038                     }
3039                     depth += index.getType().getSlots();
3040 
3041                     if (isSelfModifying()) {
3042                         //convert "base base index" to "base index base index"
3043                         method.dup(1);
3044                     }
3045 
3046                     return false;
3047                 }
3048 
3049             });
3050         }
3051 
3052         private Symbol quickSymbol(final Type type) {
3053             return quickSymbol(type, QUICK_PREFIX.symbolName());
3054         }
3055 
3056         /**
3057          * Quick symbol generates an extra local variable, always using the same
3058          * slot, one that is available after the end of the frame.
3059          *
3060          * @param type the type of the symbol
3061          * @param prefix the prefix for the variable name for the symbol
3062          *
3063          * @return the quick symbol
3064          */
3065         private Symbol quickSymbol(final Type type, final String prefix) {
3066             final String name = lc.getCurrentFunction().uniqueName(prefix);
3067             final Symbol symbol = new Symbol(name, IS_TEMP | IS_INTERNAL);
3068 
3069             symbol.setType(type);
3070 
3071             symbol.setSlot(lc.quickSlot(symbol));
3072 
3073             return symbol;
3074         }
3075 
3076         // store the result that "lives on" after the op, e.g. "i" in i++ postfix.
3077         protected void storeNonDiscard() {
3078             if (lc.getCurrentDiscard() == assignNode) {
3079                 assert assignNode.isAssignment();
3080                 lc.popDiscard();
3081                 return;
3082             }
3083 
3084             final Symbol symbol = assignNode.getSymbol();
3085             if (symbol.hasSlot()) {
3086                 method.dup().store(symbol);
3087                 return;
3088             }
3089 
3090             if (method.dup(depth) == null) {
3091                 method.dup();
3092                 this.quick = quickSymbol(method.peekType());
3093                 method.store(quick);
3094             }
3095         }
3096 
3097         private void epilogue() {
3098             /**
3099              * Take the original target args from the stack and use them
3100              * together with the value to be stored to emit the store code
3101              *
3102              * The case that targetSymbol is in scope (!hasSlot) and we actually
3103              * need to do a conversion on non-equivalent types exists, but is
3104              * very rare. See for example test/script/basic/access-specializer.js
3105              */
3106             method.convert(target.getType());
3107 
3108             target.accept(new NodeVisitor<LexicalContext>(new LexicalContext()) {
3109                 @Override
3110                 protected boolean enterDefault(Node node) {
3111                     throw new AssertionError("Unexpected node " + node + " in store epilogue");
3112                 }
3113 
3114                 @Override
3115                 public boolean enterUnaryNode(final UnaryNode node) {
3116                     if (node.tokenType() == TokenType.CONVERT && node.getSymbol() != null) {
3117                         method.convert(node.rhs().getType());
3118                     }
3119                     return true;
3120                 }
3121 
3122                 @Override
3123                 public boolean enterIdentNode(final IdentNode node) {
3124                     final Symbol symbol = node.getSymbol();
3125                     assert symbol != null;
3126                     if (symbol.isScope()) {
3127                         if (isFastScope(symbol)) {
3128                             storeFastScopeVar(node.getType(), symbol, CALLSITE_SCOPE | getCallSiteFlags());
3129                         } else {
3130                             method.dynamicSet(node.getType(), node.getName(), CALLSITE_SCOPE | getCallSiteFlags());
3131                         }
3132                     } else {
3133                         method.store(symbol);
3134                     }
3135                     return false;
3136 
3137                 }
3138 
3139                 @Override
3140                 public boolean enterAccessNode(final AccessNode node) {
3141                     method.dynamicSet(node.getProperty().getType(), node.getProperty().getName(), getCallSiteFlags());
3142                     return false;
3143                 }
3144 
3145                 @Override
3146                 public boolean enterIndexNode(final IndexNode node) {
3147                     method.dynamicSetIndex(getCallSiteFlags());
3148                     return false;
3149                 }
3150             });
3151 
3152 
3153             // whatever is on the stack now is the final answer
3154         }
3155 
3156         protected abstract void evaluate();
3157 
3158         void store() {
3159             prologue();
3160             evaluate(); // leaves an operation of whatever the operationType was on the stack
3161             storeNonDiscard();
3162             epilogue();
3163             if (quick != null) {
3164                 method.load(quick);
3165             }
3166         }
3167     }
3168 
3169     private void newFunctionObject(final FunctionNode functionNode, final FunctionNode originalFunctionNode) {
3170         assert lc.peek() == functionNode;
3171         // We don't emit a ScriptFunction on stack for:
3172         // 1. the outermost compiled function (as there's no code being generated in its outer context that'd need it
3173         //    as a callee), and
3174         // 2. for functions that are immediately called upon definition and they don't need a callee, e.g. (function(){})().
3175         //    Such immediately-called functions are invoked using INVOKESTATIC (see enterFunctionNode() of the embedded
3176         //    visitor of enterCallNode() for details), and if they don't need a callee, they don't have it on their
3177         //    static method's parameter list.
3178         if (lc.getOutermostFunction() == functionNode ||
3179                 (!functionNode.needsCallee()) && lc.isFunctionDefinedInCurrentCall(originalFunctionNode)) {
3180             return;
3181         }
3182 
3183         final boolean isLazy  = functionNode.isLazy();
3184 
3185         new ObjectCreator(this, new ArrayList<String>(), new ArrayList<Symbol>(), false, false) {
3186             @Override
3187             protected void makeObject(final MethodEmitter m) {
3188                 final String className = SCRIPTFUNCTION_IMPL_OBJECT;
3189 
3190                 m._new(className).dup();
3191                 loadConstant(new RecompilableScriptFunctionData(functionNode, compiler.getCodeInstaller(), Compiler.binaryName(getClassName()), makeMap()));
3192 
3193                 if (isLazy || functionNode.needsParentScope()) {
3194                     m.loadCompilerConstant(SCOPE);
3195                 } else {
3196                     m.loadNull();
3197                 }
3198                 m.invoke(constructorNoLookup(className, RecompilableScriptFunctionData.class, ScriptObject.class));
3199             }
3200         }.makeObject(method);
3201     }
3202 
3203     /*
3204      * Globals are special. We cannot refer to any Global (or NativeObject) class by .class, as they are different
3205      * for different contexts. As far as I can tell, the only NativeObject that we need to deal with like this
3206      * is from the code pipeline is Global
3207      */
3208     private MethodEmitter globalInstance() {
3209         return method.invokestatic(GLOBAL_OBJECT, "instance", "()L" + GLOBAL_OBJECT + ';');
3210     }
3211 
3212     private MethodEmitter globalObjectPrototype() {
3213         return method.invokestatic(GLOBAL_OBJECT, "objectPrototype", methodDescriptor(ScriptObject.class));
3214     }
3215 
3216     private MethodEmitter globalAllocateArguments() {
3217         return method.invokestatic(GLOBAL_OBJECT, "allocateArguments", methodDescriptor(ScriptObject.class, Object[].class, Object.class, int.class));
3218     }
3219 
3220     private MethodEmitter globalNewRegExp() {
3221         return method.invokestatic(GLOBAL_OBJECT, "newRegExp", methodDescriptor(Object.class, String.class, String.class));
3222     }
3223 
3224     private MethodEmitter globalRegExpCopy() {
3225         return method.invokestatic(GLOBAL_OBJECT, "regExpCopy", methodDescriptor(Object.class, Object.class));
3226     }
3227 
3228     private MethodEmitter globalAllocateArray(final ArrayType type) {
3229         //make sure the native array is treated as an array type
3230         return method.invokestatic(GLOBAL_OBJECT, "allocate", "(" + type.getDescriptor() + ")Ljdk/nashorn/internal/objects/NativeArray;");
3231     }
3232 
3233     private MethodEmitter globalIsEval() {
3234         return method.invokestatic(GLOBAL_OBJECT, "isEval", methodDescriptor(boolean.class, Object.class));
3235     }
3236 
3237     private MethodEmitter globalDirectEval() {
3238         return method.invokestatic(GLOBAL_OBJECT, "directEval",
3239                 methodDescriptor(Object.class, Object.class, Object.class, Object.class, Object.class, Object.class));
3240     }
3241 }
--- EOF ---