/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.internal.codegen;
import static jdk.nashorn.internal.codegen.ClassEmitter.Flag.PRIVATE;
import static jdk.nashorn.internal.codegen.ClassEmitter.Flag.STATIC;
import static jdk.nashorn.internal.codegen.CompilerConstants.ARGUMENTS;
import static jdk.nashorn.internal.codegen.CompilerConstants.CALLEE;
import static jdk.nashorn.internal.codegen.CompilerConstants.GET_MAP;
import static jdk.nashorn.internal.codegen.CompilerConstants.GET_STRING;
import static jdk.nashorn.internal.codegen.CompilerConstants.QUICK_PREFIX;
import static jdk.nashorn.internal.codegen.CompilerConstants.REGEX_PREFIX;
import static jdk.nashorn.internal.codegen.CompilerConstants.RETURN;
import static jdk.nashorn.internal.codegen.CompilerConstants.SCOPE;
import static jdk.nashorn.internal.codegen.CompilerConstants.SPLIT_ARRAY_ARG;
import static jdk.nashorn.internal.codegen.CompilerConstants.SPLIT_PREFIX;
import static jdk.nashorn.internal.codegen.CompilerConstants.THIS;
import static jdk.nashorn.internal.codegen.CompilerConstants.VARARGS;
import static jdk.nashorn.internal.codegen.CompilerConstants.constructorNoLookup;
import static jdk.nashorn.internal.codegen.CompilerConstants.interfaceCallNoLookup;
import static jdk.nashorn.internal.codegen.CompilerConstants.methodDescriptor;
import static jdk.nashorn.internal.codegen.CompilerConstants.staticCallNoLookup;
import static jdk.nashorn.internal.codegen.CompilerConstants.staticField;
import static jdk.nashorn.internal.codegen.CompilerConstants.typeDescriptor;
import static jdk.nashorn.internal.codegen.CompilerConstants.virtualCallNoLookup;
import static jdk.nashorn.internal.ir.Symbol.IS_INTERNAL;
import static jdk.nashorn.internal.ir.Symbol.IS_TEMP;
import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_FAST_SCOPE;
import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_SCOPE;
import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_STRICT;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.TreeMap;
import jdk.nashorn.internal.codegen.ClassEmitter.Flag;
import jdk.nashorn.internal.codegen.CompilerConstants.Call;
import jdk.nashorn.internal.codegen.RuntimeCallSite.SpecializedRuntimeNode;
import jdk.nashorn.internal.codegen.types.ArrayType;
import jdk.nashorn.internal.codegen.types.Type;
import jdk.nashorn.internal.ir.AccessNode;
import jdk.nashorn.internal.ir.BaseNode;
import jdk.nashorn.internal.ir.BinaryNode;
import jdk.nashorn.internal.ir.Block;
import jdk.nashorn.internal.ir.BlockStatement;
import jdk.nashorn.internal.ir.BreakNode;
import jdk.nashorn.internal.ir.BreakableNode;
import jdk.nashorn.internal.ir.CallNode;
import jdk.nashorn.internal.ir.CaseNode;
import jdk.nashorn.internal.ir.CatchNode;
import jdk.nashorn.internal.ir.ContinueNode;
import jdk.nashorn.internal.ir.EmptyNode;
import jdk.nashorn.internal.ir.Expression;
import jdk.nashorn.internal.ir.ExpressionStatement;
import jdk.nashorn.internal.ir.ForNode;
import jdk.nashorn.internal.ir.FunctionNode;
import jdk.nashorn.internal.ir.FunctionNode.CompilationState;
import jdk.nashorn.internal.ir.IdentNode;
import jdk.nashorn.internal.ir.IfNode;
import jdk.nashorn.internal.ir.IndexNode;
import jdk.nashorn.internal.ir.LexicalContext;
import jdk.nashorn.internal.ir.LexicalContextNode;
import jdk.nashorn.internal.ir.LiteralNode;
import jdk.nashorn.internal.ir.LiteralNode.ArrayLiteralNode;
import jdk.nashorn.internal.ir.LiteralNode.ArrayLiteralNode.ArrayUnit;
import jdk.nashorn.internal.ir.LoopNode;
import jdk.nashorn.internal.ir.Node;
import jdk.nashorn.internal.ir.ObjectNode;
import jdk.nashorn.internal.ir.PropertyNode;
import jdk.nashorn.internal.ir.ReturnNode;
import jdk.nashorn.internal.ir.RuntimeNode;
import jdk.nashorn.internal.ir.RuntimeNode.Request;
import jdk.nashorn.internal.ir.SplitNode;
import jdk.nashorn.internal.ir.Statement;
import jdk.nashorn.internal.ir.SwitchNode;
import jdk.nashorn.internal.ir.Symbol;
import jdk.nashorn.internal.ir.TernaryNode;
import jdk.nashorn.internal.ir.ThrowNode;
import jdk.nashorn.internal.ir.TryNode;
import jdk.nashorn.internal.ir.UnaryNode;
import jdk.nashorn.internal.ir.VarNode;
import jdk.nashorn.internal.ir.WhileNode;
import jdk.nashorn.internal.ir.WithNode;
import jdk.nashorn.internal.ir.debug.ASTWriter;
import jdk.nashorn.internal.ir.visitor.NodeOperatorVisitor;
import jdk.nashorn.internal.ir.visitor.NodeVisitor;
import jdk.nashorn.internal.objects.Global;
import jdk.nashorn.internal.objects.ScriptFunctionImpl;
import jdk.nashorn.internal.parser.Lexer.RegexToken;
import jdk.nashorn.internal.parser.TokenType;
import jdk.nashorn.internal.runtime.Context;
import jdk.nashorn.internal.runtime.Debug;
import jdk.nashorn.internal.runtime.DebugLogger;
import jdk.nashorn.internal.runtime.ECMAException;
import jdk.nashorn.internal.runtime.JSType;
import jdk.nashorn.internal.runtime.Property;
import jdk.nashorn.internal.runtime.PropertyMap;
import jdk.nashorn.internal.runtime.RecompilableScriptFunctionData;
import jdk.nashorn.internal.runtime.Scope;
import jdk.nashorn.internal.runtime.ScriptFunction;
import jdk.nashorn.internal.runtime.ScriptObject;
import jdk.nashorn.internal.runtime.ScriptRuntime;
import jdk.nashorn.internal.runtime.Source;
import jdk.nashorn.internal.runtime.Undefined;
import jdk.nashorn.internal.runtime.arrays.ArrayData;
import jdk.nashorn.internal.runtime.linker.LinkerCallSite;
/**
* This is the lowest tier of the code generator. It takes lowered ASTs emitted
* from Lower and emits Java byte code. The byte code emission logic is broken
* out into MethodEmitter. MethodEmitter works internally with a type stack, and
* keeps track of the contents of the byte code stack. This way we avoid a large
* number of special cases on the form
*
* This quickly became apparent when the code generator was generalized to work
* with all types, and not just numbers or objects.
*
* The CodeGenerator visits nodes only once, tags them as resolved and emits
* bytecode for them.
*/
final class CodeGenerator extends NodeOperatorVisitor {
private static final String GLOBAL_OBJECT = Type.getInternalName(Global.class);
private static final String SCRIPTFUNCTION_IMPL_OBJECT = Type.getInternalName(ScriptFunctionImpl.class);
/** Constant data & installation. The only reason the compiler keeps this is because it is assigned
* by reflection in class installation */
private final Compiler compiler;
/** Call site flags given to the code generator to be used for all generated call sites */
private final int callSiteFlags;
/** How many regexp fields have been emitted */
private int regexFieldCount;
/** Line number for last statement. If we encounter a new line number, line number bytecode information
* needs to be generated */
private int lastLineNumber = -1;
/** When should we stop caching regexp expressions in fields to limit bytecode size? */
private static final int MAX_REGEX_FIELDS = 2 * 1024;
/** Current method emitter */
private MethodEmitter method;
/** Current compile unit */
private CompileUnit unit;
private static final DebugLogger LOG = new DebugLogger("codegen", "nashorn.codegen.debug");
/** From what size should we use spill instead of fields for JavaScript objects? */
private static final int OBJECT_SPILL_THRESHOLD = 300;
private final Set emittedMethods = new HashSet<>();
/**
* Constructor.
*
* @param compiler
*/
CodeGenerator(final Compiler compiler) {
super(new CodeGeneratorLexicalContext());
this.compiler = compiler;
this.callSiteFlags = compiler.getEnv()._callsite_flags;
}
/**
* Gets the call site flags, adding the strict flag if the current function
* being generated is in strict mode
*
* @return the correct flags for a call site in the current function
*/
int getCallSiteFlags() {
return lc.getCurrentFunction().isStrict() ? callSiteFlags | CALLSITE_STRICT : callSiteFlags;
}
/**
* Load an identity node
*
* @param identNode an identity node to load
* @return the method generator used
*/
private MethodEmitter loadIdent(final IdentNode identNode) {
final Symbol symbol = identNode.getSymbol();
if (!symbol.isScope()) {
assert symbol.hasSlot() || symbol.isParam();
return method.load(symbol);
}
final String name = symbol.getName();
final Source source = lc.getCurrentFunction().getSource();
if (CompilerConstants.__FILE__.name().equals(name)) {
return method.load(source.getName());
} else if (CompilerConstants.__DIR__.name().equals(name)) {
return method.load(source.getBase());
} else if (CompilerConstants.__LINE__.name().equals(name)) {
return method.load(source.getLine(identNode.position())).convert(Type.OBJECT);
} else {
assert identNode.getSymbol().isScope() : identNode + " is not in scope!";
final int flags = CALLSITE_SCOPE | getCallSiteFlags();
method.loadCompilerConstant(SCOPE);
if (isFastScope(symbol)) {
// Only generate shared scope getter for fast-scope symbols so we know we can dial in correct scope.
if (symbol.getUseCount() > SharedScopeCall.FAST_SCOPE_GET_THRESHOLD) {
return loadSharedScopeVar(identNode.getType(), symbol, flags);
}
return loadFastScopeVar(identNode.getType(), symbol, flags, identNode.isFunction());
}
return method.dynamicGet(identNode.getType(), identNode.getName(), flags, identNode.isFunction());
}
}
/**
* Check if this symbol can be accessed directly with a putfield or getfield or dynamic load
*
* @param symbol symbol to check for fast scope
* @return true if fast scope
*/
private boolean isFastScope(final Symbol symbol) {
if (!symbol.isScope()) {
return false;
}
if (!lc.inDynamicScope()) {
// If there's no with or eval in context, and the symbol is marked as scoped, it is fast scoped. Such a
// symbol must either be global, or its defining block must need scope.
assert symbol.isGlobal() || lc.getDefiningBlock(symbol).needsScope() : symbol.getName();
return true;
}
if (symbol.isGlobal()) {
// Shortcut: if there's a with or eval in context, globals can't be fast scoped
return false;
}
// Otherwise, check if there's a dynamic scope between use of the symbol and its definition
final String name = symbol.getName();
boolean previousWasBlock = false;
for (final Iterator it = lc.getAllNodes(); it.hasNext();) {
final LexicalContextNode node = it.next();
if (node instanceof Block) {
// If this block defines the symbol, then we can fast scope the symbol.
final Block block = (Block)node;
if (block.getExistingSymbol(name) == symbol) {
assert block.needsScope();
return true;
}
previousWasBlock = true;
} else {
if ((node instanceof WithNode && previousWasBlock) || (node instanceof FunctionNode && CodeGeneratorLexicalContext.isFunctionDynamicScope((FunctionNode)node))) {
// If we hit a scope that can have symbols introduced into it at run time before finding the defining
// block, the symbol can't be fast scoped. A WithNode only counts if we've immediately seen a block
// before - its block. Otherwise, we are currently processing the WithNode's expression, and that's
// obviously not subjected to introducing new symbols.
return false;
}
previousWasBlock = false;
}
}
// Should've found the symbol defined in a block
throw new AssertionError();
}
private MethodEmitter loadSharedScopeVar(final Type valueType, final Symbol symbol, final int flags) {
method.load(isFastScope(symbol) ? getScopeProtoDepth(lc.getCurrentBlock(), symbol) : -1);
final SharedScopeCall scopeCall = lc.getScopeGet(unit, valueType, symbol, flags | CALLSITE_FAST_SCOPE);
return scopeCall.generateInvoke(method);
}
private MethodEmitter loadFastScopeVar(final Type valueType, final Symbol symbol, final int flags, final boolean isMethod) {
loadFastScopeProto(symbol, false);
return method.dynamicGet(valueType, symbol.getName(), flags | CALLSITE_FAST_SCOPE, isMethod);
}
private MethodEmitter storeFastScopeVar(final Type valueType, final Symbol symbol, final int flags) {
loadFastScopeProto(symbol, true);
method.dynamicSet(valueType, symbol.getName(), flags | CALLSITE_FAST_SCOPE);
return method;
}
private int getScopeProtoDepth(final Block startingBlock, final Symbol symbol) {
int depth = 0;
final String name = symbol.getName();
for(final Iterator blocks = lc.getBlocks(startingBlock); blocks.hasNext();) {
final Block currentBlock = blocks.next();
if (currentBlock.getExistingSymbol(name) == symbol) {
return depth;
}
if (currentBlock.needsScope()) {
++depth;
}
}
return -1;
}
private void loadFastScopeProto(final Symbol symbol, final boolean swap) {
final int depth = getScopeProtoDepth(lc.getCurrentBlock(), symbol);
assert depth != -1;
if (depth > 0) {
if (swap) {
method.swap();
}
for (int i = 0; i < depth; i++) {
method.invoke(ScriptObject.GET_PROTO);
}
if (swap) {
method.swap();
}
}
}
/**
* Generate code that loads this node to the stack. This method is only
* public to be accessible from the maps sub package. Do not call externally
*
* @param node node to load
*
* @return the method emitter used
*/
MethodEmitter load(final Expression node) {
return load(node, false);
}
private MethodEmitter load(final Expression node, final boolean baseAlreadyOnStack) {
final Symbol symbol = node.getSymbol();
// If we lack symbols, we just generate what we see.
if (symbol == null) {
node.accept(this);
return method;
}
/*
* The load may be of type IdentNode, e.g. "x", AccessNode, e.g. "x.y"
* or IndexNode e.g. "x[y]". Both AccessNodes and IndexNodes are
* BaseNodes and the logic for loading the base object is reused
*/
final CodeGenerator codegen = this;
node.accept(new NodeVisitor(new LexicalContext()) {
@Override
public boolean enterIdentNode(final IdentNode identNode) {
loadIdent(identNode);
return false;
}
@Override
public boolean enterAccessNode(final AccessNode accessNode) {
if (!baseAlreadyOnStack) {
load(accessNode.getBase()).convert(Type.OBJECT);
}
assert method.peekType().isObject();
method.dynamicGet(node.getType(), accessNode.getProperty().getName(), getCallSiteFlags(), accessNode.isFunction());
return false;
}
@Override
public boolean enterIndexNode(final IndexNode indexNode) {
if (!baseAlreadyOnStack) {
load(indexNode.getBase()).convert(Type.OBJECT);
load(indexNode.getIndex());
}
method.dynamicGetIndex(node.getType(), getCallSiteFlags(), indexNode.isFunction());
return false;
}
@Override
public boolean enterFunctionNode(FunctionNode functionNode) {
// function nodes will always leave a constructed function object on stack, no need to load the symbol
// separately as in enterDefault()
functionNode.accept(codegen);
return false;
}
@Override
public boolean enterDefault(final Node otherNode) {
otherNode.accept(codegen); // generate code for whatever we are looking at.
method.load(symbol); // load the final symbol to the stack (or nop if no slot, then result is already there)
return false;
}
});
return method;
}
@Override
public boolean enterAccessNode(final AccessNode accessNode) {
load(accessNode);
return false;
}
/**
* Initialize a specific set of vars to undefined. This has to be done at
* the start of each method for local variables that aren't passed as
* parameters.
*
* @param symbols list of symbols.
*/
private void initSymbols(final Iterable symbols) {
final LinkedList numbers = new LinkedList<>();
final LinkedList objects = new LinkedList<>();
for (final Symbol symbol : symbols) {
/*
* The following symbols are guaranteed to be defined and thus safe
* from having undefined written to them: parameters internals this
*
* Otherwise we must, unless we perform control/escape analysis,
* assign them undefined.
*/
final boolean isInternal = symbol.isParam() || symbol.isInternal() || symbol.isThis() || !symbol.canBeUndefined();
if (symbol.hasSlot() && !isInternal) {
assert symbol.getSymbolType().isNumber() || symbol.getSymbolType().isObject() : "no potentially undefined narrower local vars than doubles are allowed: " + symbol + " in " + lc.getCurrentFunction();
if (symbol.getSymbolType().isNumber()) {
numbers.add(symbol);
} else if (symbol.getSymbolType().isObject()) {
objects.add(symbol);
}
}
}
initSymbols(numbers, Type.NUMBER);
initSymbols(objects, Type.OBJECT);
}
private void initSymbols(final LinkedList symbols, final Type type) {
final Iterator it = symbols.iterator();
if(it.hasNext()) {
method.loadUndefined(type);
boolean hasNext;
do {
final Symbol symbol = it.next();
hasNext = it.hasNext();
if(hasNext) {
method.dup();
}
method.store(symbol);
} while(hasNext);
}
}
/**
* Create symbol debug information.
*
* @param block block containing symbols.
*/
private void symbolInfo(final Block block) {
for (final Symbol symbol : block.getSymbols()) {
if (symbol.hasSlot()) {
method.localVariable(symbol, block.getEntryLabel(), block.getBreakLabel());
}
}
}
@Override
public boolean enterBlock(final Block block) {
if(lc.isFunctionBody() && emittedMethods.contains(lc.getCurrentFunction().getName())) {
return false;
}
method.label(block.getEntryLabel());
initLocals(block);
return true;
}
@Override
public Node leaveBlock(final Block block) {
method.label(block.getBreakLabel());
symbolInfo(block);
if (block.needsScope() && !block.isTerminal()) {
popBlockScope(block);
}
return block;
}
private void popBlockScope(final Block block) {
final Label exitLabel = new Label("block_exit");
final Label recoveryLabel = new Label("block_catch");
final Label skipLabel = new Label("skip_catch");
/* pop scope a la try-finally */
method.loadCompilerConstant(SCOPE);
method.invoke(ScriptObject.GET_PROTO);
method.storeCompilerConstant(SCOPE);
method._goto(skipLabel);
method.label(exitLabel);
method._catch(recoveryLabel);
method.loadCompilerConstant(SCOPE);
method.invoke(ScriptObject.GET_PROTO);
method.storeCompilerConstant(SCOPE);
method.athrow();
method.label(skipLabel);
method._try(block.getEntryLabel(), exitLabel, recoveryLabel, Throwable.class);
}
@Override
public boolean enterBreakNode(final BreakNode breakNode) {
lineNumber(breakNode);
final BreakableNode breakFrom = lc.getBreakable(breakNode.getLabel());
for (int i = 0; i < lc.getScopeNestingLevelTo(breakFrom); i++) {
closeWith();
}
method.splitAwareGoto(lc, breakFrom.getBreakLabel());
return false;
}
private int loadArgs(final List args) {
return loadArgs(args, null, false, args.size());
}
private int loadArgs(final List args, final String signature, final boolean isVarArg, final int argCount) {
// arg have already been converted to objects here.
if (isVarArg || argCount > LinkerCallSite.ARGLIMIT) {
loadArgsArray(args);
return 1;
}
// pad with undefined if size is too short. argCount is the real number of args
int n = 0;
final Type[] params = signature == null ? null : Type.getMethodArguments(signature);
for (final Expression arg : args) {
assert arg != null;
load(arg);
if (n >= argCount) {
method.pop(); // we had to load the arg for its side effects
} else if (params != null) {
method.convert(params[n]);
}
n++;
}
while (n < argCount) {
method.loadUndefined(Type.OBJECT);
n++;
}
return argCount;
}
@Override
public boolean enterCallNode(final CallNode callNode) {
lineNumber(callNode.getLineNumber());
final List args = callNode.getArgs();
final Expression function = callNode.getFunction();
final Block currentBlock = lc.getCurrentBlock();
final CodeGeneratorLexicalContext codegenLexicalContext = lc;
final Type callNodeType = callNode.getType();
function.accept(new NodeVisitor(new LexicalContext()) {
private MethodEmitter sharedScopeCall(final IdentNode identNode, final int flags) {
final Symbol symbol = identNode.getSymbol();
int scopeCallFlags = flags;
method.loadCompilerConstant(SCOPE);
if (isFastScope(symbol)) {
method.load(getScopeProtoDepth(currentBlock, symbol));
scopeCallFlags |= CALLSITE_FAST_SCOPE;
} else {
method.load(-1); // Bypass fast-scope code in shared callsite
}
loadArgs(args);
final Type[] paramTypes = method.getTypesFromStack(args.size());
final SharedScopeCall scopeCall = codegenLexicalContext.getScopeCall(unit, symbol, identNode.getType(), callNodeType, paramTypes, scopeCallFlags);
return scopeCall.generateInvoke(method);
}
private void scopeCall(final IdentNode node, final int flags) {
load(node);
method.convert(Type.OBJECT); // foo() makes no sense if foo == 3
// ScriptFunction will see CALLSITE_SCOPE and will bind scope accordingly.
method.loadNull(); //the 'this'
method.dynamicCall(callNodeType, 2 + loadArgs(args), flags);
}
private void evalCall(final IdentNode node, final int flags) {
load(node);
method.convert(Type.OBJECT); // foo() makes no sense if foo == 3
final Label not_eval = new Label("not_eval");
final Label eval_done = new Label("eval_done");
// check if this is the real built-in eval
method.dup();
globalIsEval();
method.ifeq(not_eval);
// We don't need ScriptFunction object for 'eval'
method.pop();
method.loadCompilerConstant(SCOPE); // Load up self (scope).
final CallNode.EvalArgs evalArgs = callNode.getEvalArgs();
// load evaluated code
load(evalArgs.getCode());
method.convert(Type.OBJECT);
// special/extra 'eval' arguments
load(evalArgs.getThis());
method.load(evalArgs.getLocation());
method.load(evalArgs.getStrictMode());
method.convert(Type.OBJECT);
// direct call to Global.directEval
globalDirectEval();
method.convert(callNodeType);
method._goto(eval_done);
method.label(not_eval);
// This is some scope 'eval' or global eval replaced by user
// but not the built-in ECMAScript 'eval' function call
method.loadNull();
method.dynamicCall(callNodeType, 2 + loadArgs(args), flags);
method.label(eval_done);
}
@Override
public boolean enterIdentNode(final IdentNode node) {
final Symbol symbol = node.getSymbol();
if (symbol.isScope()) {
final int flags = getCallSiteFlags() | CALLSITE_SCOPE;
final int useCount = symbol.getUseCount();
// Threshold for generating shared scope callsite is lower for fast scope symbols because we know
// we can dial in the correct scope. However, we also need to enable it for non-fast scopes to
// support huge scripts like mandreel.js.
if (callNode.isEval()) {
evalCall(node, flags);
} else if (useCount <= SharedScopeCall.FAST_SCOPE_CALL_THRESHOLD
|| (!isFastScope(symbol) && useCount <= SharedScopeCall.SLOW_SCOPE_CALL_THRESHOLD)
|| CodeGenerator.this.lc.inDynamicScope()) {
scopeCall(node, flags);
} else {
sharedScopeCall(node, flags);
}
assert method.peekType().equals(callNodeType) : method.peekType() + "!=" + callNode.getType();
} else {
enterDefault(node);
}
return false;
}
@Override
public boolean enterAccessNode(final AccessNode node) {
load(node.getBase());
method.convert(Type.OBJECT);
method.dup();
method.dynamicGet(node.getType(), node.getProperty().getName(), getCallSiteFlags(), true);
method.swap();
method.dynamicCall(callNodeType, 2 + loadArgs(args), getCallSiteFlags());
assert method.peekType().equals(callNodeType);
return false;
}
@Override
public boolean enterFunctionNode(final FunctionNode origCallee) {
// NOTE: visiting the callee will leave a constructed ScriptFunction object on the stack if
// callee.needsCallee() == true
final FunctionNode callee = (FunctionNode)origCallee.accept(CodeGenerator.this);
final boolean isVarArg = callee.isVarArg();
final int argCount = isVarArg ? -1 : callee.getParameters().size();
final String signature = new FunctionSignature(true, callee.needsCallee(), callee.getReturnType(), isVarArg ? null : callee.getParameters()).toString();
if (callee.isStrict()) { // self is undefined
method.loadUndefined(Type.OBJECT);
} else { // get global from scope (which is the self)
globalInstance();
}
loadArgs(args, signature, isVarArg, argCount);
assert callee.getCompileUnit() != null : "no compile unit for " + callee.getName() + " " + Debug.id(callee) + " " + callNode;
method.invokestatic(callee.getCompileUnit().getUnitClassName(), callee.getName(), signature);
assert method.peekType().equals(callee.getReturnType()) : method.peekType() + " != " + callee.getReturnType();
method.convert(callNodeType);
return false;
}
@Override
public boolean enterIndexNode(final IndexNode node) {
load(node.getBase());
method.convert(Type.OBJECT);
method.dup();
load(node.getIndex());
final Type indexType = node.getIndex().getType();
if (indexType.isObject() || indexType.isBoolean()) {
method.convert(Type.OBJECT); //TODO
}
method.dynamicGetIndex(node.getType(), getCallSiteFlags(), true);
method.swap();
method.dynamicCall(callNodeType, 2 + loadArgs(args), getCallSiteFlags());
assert method.peekType().equals(callNode.getType());
return false;
}
@Override
protected boolean enterDefault(final Node node) {
// Load up function.
load(function);
method.convert(Type.OBJECT); //TODO, e.g. booleans can be used as functions
method.loadNull(); // ScriptFunction will figure out the correct this when it sees CALLSITE_SCOPE
method.dynamicCall(callNodeType, 2 + loadArgs(args), getCallSiteFlags() | CALLSITE_SCOPE);
assert method.peekType().equals(callNode.getType());
return false;
}
});
method.store(callNode.getSymbol());
return false;
}
@Override
public boolean enterContinueNode(final ContinueNode continueNode) {
lineNumber(continueNode);
final LoopNode continueTo = lc.getContinueTo(continueNode.getLabel());
for (int i = 0; i < lc.getScopeNestingLevelTo(continueTo); i++) {
closeWith();
}
method.splitAwareGoto(lc, continueTo.getContinueLabel());
return false;
}
@Override
public boolean enterEmptyNode(final EmptyNode emptyNode) {
lineNumber(emptyNode);
return false;
}
@Override
public boolean enterExpressionStatement(final ExpressionStatement expressionStatement) {
lineNumber(expressionStatement);
expressionStatement.getExpression().accept(this);
return false;
}
@Override
public boolean enterBlockStatement(final BlockStatement blockStatement) {
lineNumber(blockStatement);
blockStatement.getBlock().accept(this);
return false;
}
@Override
public boolean enterForNode(final ForNode forNode) {
lineNumber(forNode);
if (forNode.isForIn()) {
enterForIn(forNode);
} else {
enterFor(forNode);
}
return false;
}
private void enterFor(final ForNode forNode) {
final Expression init = forNode.getInit();
final Expression test = forNode.getTest();
final Block body = forNode.getBody();
final Expression modify = forNode.getModify();
if (init != null) {
init.accept(this);
}
final Label loopLabel = new Label("loop");
final Label testLabel = new Label("test");
method._goto(testLabel);
method.label(loopLabel);
body.accept(this);
method.label(forNode.getContinueLabel());
if (!body.isTerminal() && modify != null) {
load(modify);
}
method.label(testLabel);
if (test != null) {
new BranchOptimizer(this, method).execute(test, loopLabel, true);
} else {
method._goto(loopLabel);
}
method.label(forNode.getBreakLabel());
}
private void enterForIn(final ForNode forNode) {
final Block body = forNode.getBody();
final Expression modify = forNode.getModify();
final Symbol iter = forNode.getIterator();
final Label loopLabel = new Label("loop");
final Expression init = forNode.getInit();
load(modify);
assert modify.getType().isObject();
method.invoke(forNode.isForEach() ? ScriptRuntime.TO_VALUE_ITERATOR : ScriptRuntime.TO_PROPERTY_ITERATOR);
method.store(iter);
method._goto(forNode.getContinueLabel());
method.label(loopLabel);
new Store(init) {
@Override
protected void storeNonDiscard() {
return;
}
@Override
protected void evaluate() {
method.load(iter);
method.invoke(interfaceCallNoLookup(Iterator.class, "next", Object.class));
}
}.store();
body.accept(this);
method.label(forNode.getContinueLabel());
method.load(iter);
method.invoke(interfaceCallNoLookup(Iterator.class, "hasNext", boolean.class));
method.ifne(loopLabel);
method.label(forNode.getBreakLabel());
}
/**
* Initialize the slots in a frame to undefined.
*
* @param block block with local vars.
*/
private void initLocals(final Block block) {
lc.nextFreeSlot(block);
final boolean isFunctionBody = lc.isFunctionBody();
final FunctionNode function = lc.getCurrentFunction();
if (isFunctionBody) {
if(method.hasScope()) {
if (function.needsParentScope()) {
method.loadCompilerConstant(CALLEE);
method.invoke(ScriptFunction.GET_SCOPE);
} else {
assert function.hasScopeBlock();
method.loadNull();
}
method.storeCompilerConstant(SCOPE);
}
if (function.needsArguments()) {
initArguments(function);
}
}
/*
* Determine if block needs scope, if not, just do initSymbols for this block.
*/
if (block.needsScope()) {
/*
* Determine if function is varargs and consequently variables have to
* be in the scope.
*/
final boolean varsInScope = function.allVarsInScope();
// TODO for LET we can do better: if *block* does not contain any eval/with, we don't need its vars in scope.
final List nameList = new ArrayList<>();
final List locals = new ArrayList<>();
// Initalize symbols and values
final List newSymbols = new ArrayList<>();
final List values = new ArrayList<>();
final boolean hasArguments = function.needsArguments();
for (final Symbol symbol : block.getSymbols()) {
if (symbol.isInternal() || symbol.isThis() || symbol.isTemp()) {
continue;
}
if (symbol.isVar()) {
if (varsInScope || symbol.isScope()) {
nameList.add(symbol.getName());
newSymbols.add(symbol);
values.add(null);
assert symbol.isScope() : "scope for " + symbol + " should have been set in Lower already " + function.getName();
assert !symbol.hasSlot() : "slot for " + symbol + " should have been removed in Lower already" + function.getName();
} else {
assert symbol.hasSlot() : symbol + " should have a slot only, no scope";
locals.add(symbol);
}
} else if (symbol.isParam() && (varsInScope || hasArguments || symbol.isScope())) {
nameList.add(symbol.getName());
newSymbols.add(symbol);
values.add(hasArguments ? null : symbol);
assert symbol.isScope() : "scope for " + symbol + " should have been set in Lower already " + function.getName() + " varsInScope="+varsInScope+" hasArguments="+hasArguments+" symbol.isScope()=" + symbol.isScope();
assert !(hasArguments && symbol.hasSlot()) : "slot for " + symbol + " should have been removed in Lower already " + function.getName();
}
}
// we may have locals that need to be initialized
initSymbols(locals);
/*
* Create a new object based on the symbols and values, generate
* bootstrap code for object
*/
new FieldObjectCreator(this, nameList, newSymbols, values, true, hasArguments) {
@Override
protected void loadValue(final Symbol value) {
method.load(value);
}
}.makeObject(method);
// runScript(): merge scope into global
if (isFunctionBody && function.isProgram()) {
method.invoke(ScriptRuntime.MERGE_SCOPE);
}
method.storeCompilerConstant(SCOPE);
} else {
// Since we don't have a scope, parameters didn't get assigned array indices by the FieldObjectCreator, so
// we need to assign them separately here.
int nextParam = 0;
if (isFunctionBody && function.isVarArg()) {
for (final IdentNode param : function.getParameters()) {
param.getSymbol().setFieldIndex(nextParam++);
}
}
initSymbols(block.getSymbols());
}
// Debugging: print symbols? @see --print-symbols flag
printSymbols(block, (isFunctionBody ? "Function " : "Block in ") + (function.getIdent() == null ? "" : function.getIdent().getName()));
}
private void initArguments(final FunctionNode function) {
method.loadCompilerConstant(VARARGS);
if (function.needsCallee()) {
method.loadCompilerConstant(CALLEE);
} else {
// If function is strict mode, "arguments.callee" is not populated, so we don't necessarily need the
// caller.
assert function.isStrict();
method.loadNull();
}
method.load(function.getParameters().size());
globalAllocateArguments();
method.storeCompilerConstant(ARGUMENTS);
}
@Override
public boolean enterFunctionNode(final FunctionNode functionNode) {
if (functionNode.isLazy()) {
// Must do it now; can't postpone it until leaveFunctionNode()
newFunctionObject(functionNode, functionNode);
return false;
}
final String fnName = functionNode.getName();
// NOTE: we only emit the method for a function with the given name once. We can have multiple functions with
// the same name as a result of inlining finally blocks. However, in the future -- with type specialization,
// notably -- we might need to check for both name *and* signature. Of course, even that might not be
// sufficient; the function might have a code dependency on the type of the variables in its enclosing scopes,
// and the type of such a variable can be different in catch and finally blocks. So, in the future we will have
// to decide to either generate a unique method for each inlined copy of the function, maybe figure out its
// exact type closure and deduplicate based on that, or just decide that functions in finally blocks aren't
// worth it, and generate one method with most generic type closure.
if(!emittedMethods.contains(fnName)) {
LOG.info("=== BEGIN ", fnName);
assert functionNode.getCompileUnit() != null : "no compile unit for " + fnName + " " + Debug.id(functionNode);
unit = lc.pushCompileUnit(functionNode.getCompileUnit());
assert lc.hasCompileUnits();
method = lc.pushMethodEmitter(unit.getClassEmitter().method(functionNode));
// new method - reset last line number
lastLineNumber = -1;
// Mark end for variable tables.
method.begin();
}
return true;
}
@Override
public Node leaveFunctionNode(final FunctionNode functionNode) {
try {
if(emittedMethods.add(functionNode.getName())) {
method.end(); // wrap up this method
unit = lc.popCompileUnit(functionNode.getCompileUnit());
method = lc.popMethodEmitter(method);
LOG.info("=== END ", functionNode.getName());
}
final FunctionNode newFunctionNode = functionNode.setState(lc, CompilationState.EMITTED);
newFunctionObject(newFunctionNode, functionNode);
return newFunctionNode;
} catch (final Throwable t) {
Context.printStackTrace(t);
final VerifyError e = new VerifyError("Code generation bug in \"" + functionNode.getName() + "\": likely stack misaligned: " + t + " " + functionNode.getSource().getName());
e.initCause(t);
throw e;
}
}
@Override
public boolean enterIdentNode(final IdentNode identNode) {
return false;
}
@Override
public boolean enterIfNode(final IfNode ifNode) {
lineNumber(ifNode);
final Expression test = ifNode.getTest();
final Block pass = ifNode.getPass();
final Block fail = ifNode.getFail();
final Label failLabel = new Label("if_fail");
final Label afterLabel = fail == null ? failLabel : new Label("if_done");
new BranchOptimizer(this, method).execute(test, failLabel, false);
boolean passTerminal = false;
boolean failTerminal = false;
pass.accept(this);
if (!pass.hasTerminalFlags()) {
method._goto(afterLabel); //don't fallthru to fail block
} else {
passTerminal = pass.isTerminal();
}
if (fail != null) {
method.label(failLabel);
fail.accept(this);
failTerminal = fail.isTerminal();
}
//if if terminates, put the after label there
if (!passTerminal || !failTerminal) {
method.label(afterLabel);
}
return false;
}
@Override
public boolean enterIndexNode(final IndexNode indexNode) {
load(indexNode);
return false;
}
private void lineNumber(final Statement statement) {
lineNumber(statement.getLineNumber());
}
private void lineNumber(int lineNumber) {
if (lineNumber != lastLineNumber) {
method.lineNumber(lineNumber);
}
lastLineNumber = lineNumber;
}
/**
* Load a list of nodes as an array of a specific type
* The array will contain the visited nodes.
*
* @param arrayLiteralNode the array of contents
* @param arrayType the type of the array, e.g. ARRAY_NUMBER or ARRAY_OBJECT
*
* @return the method generator that was used
*/
private MethodEmitter loadArray(final ArrayLiteralNode arrayLiteralNode, final ArrayType arrayType) {
assert arrayType == Type.INT_ARRAY || arrayType == Type.LONG_ARRAY || arrayType == Type.NUMBER_ARRAY || arrayType == Type.OBJECT_ARRAY;
final Expression[] nodes = arrayLiteralNode.getValue();
final Object presets = arrayLiteralNode.getPresets();
final int[] postsets = arrayLiteralNode.getPostsets();
final Class> type = arrayType.getTypeClass();
final List units = arrayLiteralNode.getUnits();
loadConstant(presets);
final Type elementType = arrayType.getElementType();
if (units != null) {
final MethodEmitter savedMethod = method;
final FunctionNode currentFunction = lc.getCurrentFunction();
for (final ArrayUnit arrayUnit : units) {
unit = lc.pushCompileUnit(arrayUnit.getCompileUnit());
final String className = unit.getUnitClassName();
final String name = currentFunction.uniqueName(SPLIT_PREFIX.symbolName());
final String signature = methodDescriptor(type, ScriptFunction.class, Object.class, ScriptObject.class, type);
final MethodEmitter me = unit.getClassEmitter().method(EnumSet.of(Flag.PUBLIC, Flag.STATIC), name, signature);
method = lc.pushMethodEmitter(me);
method.setFunctionNode(currentFunction);
method.begin();
fixScopeSlot(currentFunction);
method.load(arrayType, SPLIT_ARRAY_ARG.slot());
for (int i = arrayUnit.getLo(); i < arrayUnit.getHi(); i++) {
storeElement(nodes, elementType, postsets[i]);
}
method._return();
method.end();
method = lc.popMethodEmitter(me);
assert method == savedMethod;
method.loadCompilerConstant(CALLEE);
method.swap();
method.loadCompilerConstant(THIS);
method.swap();
method.loadCompilerConstant(SCOPE);
method.swap();
method.invokestatic(className, name, signature);
unit = lc.popCompileUnit(unit);
}
return method;
}
for (final int postset : postsets) {
storeElement(nodes, elementType, postset);
}
return method;
}
private void storeElement(final Expression[] nodes, final Type elementType, final int index) {
method.dup();
method.load(index);
final Expression element = nodes[index];
if (element == null) {
method.loadEmpty(elementType);
} else {
assert elementType.isEquivalentTo(element.getType()) : "array element type doesn't match array type";
load(element);
}
method.arraystore();
}
private MethodEmitter loadArgsArray(final List args) {
final Object[] array = new Object[args.size()];
loadConstant(array);
for (int i = 0; i < args.size(); i++) {
method.dup();
method.load(i);
load(args.get(i)).convert(Type.OBJECT); //has to be upcast to object or we fail
method.arraystore();
}
return method;
}
/**
* Load a constant from the constant array. This is only public to be callable from the objects
* subpackage. Do not call directly.
*
* @param string string to load
*/
void loadConstant(final String string) {
final String unitClassName = unit.getUnitClassName();
final ClassEmitter classEmitter = unit.getClassEmitter();
final int index = compiler.getConstantData().add(string);
method.load(index);
method.invokestatic(unitClassName, GET_STRING.symbolName(), methodDescriptor(String.class, int.class));
classEmitter.needGetConstantMethod(String.class);
}
/**
* Load a constant from the constant array. This is only public to be callable from the objects
* subpackage. Do not call directly.
*
* @param object object to load
*/
void loadConstant(final Object object) {
final String unitClassName = unit.getUnitClassName();
final ClassEmitter classEmitter = unit.getClassEmitter();
final int index = compiler.getConstantData().add(object);
final Class> cls = object.getClass();
if (cls == PropertyMap.class) {
method.load(index);
method.invokestatic(unitClassName, GET_MAP.symbolName(), methodDescriptor(PropertyMap.class, int.class));
classEmitter.needGetConstantMethod(PropertyMap.class);
} else if (cls.isArray()) {
method.load(index);
final String methodName = ClassEmitter.getArrayMethodName(cls);
method.invokestatic(unitClassName, methodName, methodDescriptor(cls, int.class));
classEmitter.needGetConstantMethod(cls);
} else {
method.loadConstants().load(index).arrayload();
if (object instanceof ArrayData) {
// avoid cast to non-public ArrayData subclass
method.checkcast(ArrayData.class);
method.invoke(virtualCallNoLookup(ArrayData.class, "copy", ArrayData.class));
} else if (cls != Object.class) {
method.checkcast(cls);
}
}
}
// literal values
private MethodEmitter load(final LiteralNode> node) {
final Object value = node.getValue();
if (value == null) {
method.loadNull();
} else if (value instanceof Undefined) {
method.loadUndefined(Type.OBJECT);
} else if (value instanceof String) {
final String string = (String)value;
if (string.length() > (MethodEmitter.LARGE_STRING_THRESHOLD / 3)) { // 3 == max bytes per encoded char
loadConstant(string);
} else {
method.load(string);
}
} else if (value instanceof RegexToken) {
loadRegex((RegexToken)value);
} else if (value instanceof Boolean) {
method.load((Boolean)value);
} else if (value instanceof Integer) {
method.load((Integer)value);
} else if (value instanceof Long) {
method.load((Long)value);
} else if (value instanceof Double) {
method.load((Double)value);
} else if (node instanceof ArrayLiteralNode) {
final ArrayType type = (ArrayType)node.getType();
loadArray((ArrayLiteralNode)node, type);
globalAllocateArray(type);
} else {
assert false : "Unknown literal for " + node.getClass() + " " + value.getClass() + " " + value;
}
return method;
}
private MethodEmitter loadRegexToken(final RegexToken value) {
method.load(value.getExpression());
method.load(value.getOptions());
return globalNewRegExp();
}
private MethodEmitter loadRegex(final RegexToken regexToken) {
if (regexFieldCount > MAX_REGEX_FIELDS) {
return loadRegexToken(regexToken);
}
// emit field
final String regexName = lc.getCurrentFunction().uniqueName(REGEX_PREFIX.symbolName());
final ClassEmitter classEmitter = unit.getClassEmitter();
classEmitter.field(EnumSet.of(PRIVATE, STATIC), regexName, Object.class);
regexFieldCount++;
// get field, if null create new regex, finally clone regex object
method.getStatic(unit.getUnitClassName(), regexName, typeDescriptor(Object.class));
method.dup();
final Label cachedLabel = new Label("cached");
method.ifnonnull(cachedLabel);
method.pop();
loadRegexToken(regexToken);
method.dup();
method.putStatic(unit.getUnitClassName(), regexName, typeDescriptor(Object.class));
method.label(cachedLabel);
globalRegExpCopy();
return method;
}
@Override
public boolean enterLiteralNode(final LiteralNode> literalNode) {
assert literalNode.getSymbol() != null : literalNode + " has no symbol";
load(literalNode).store(literalNode.getSymbol());
return false;
}
@Override
public boolean enterObjectNode(final ObjectNode objectNode) {
final List elements = objectNode.getElements();
final List keys = new ArrayList<>();
final List symbols = new ArrayList<>();
final List values = new ArrayList<>();
boolean hasGettersSetters = false;
Expression protoNode = null;
for (PropertyNode propertyNode: elements) {
final Expression value = propertyNode.getValue();
final String key = propertyNode.getKeyName();
final Symbol symbol = value == null ? null : propertyNode.getKey().getSymbol();
if (value == null) {
hasGettersSetters = true;
} else if (key.equals(ScriptObject.PROTO_PROPERTY_NAME)) {
protoNode = value;
continue;
}
keys.add(key);
symbols.add(symbol);
values.add(value);
}
if (elements.size() > OBJECT_SPILL_THRESHOLD) {
new SpillObjectCreator(this, keys, symbols, values).makeObject(method);
} else {
new FieldObjectCreator(this, keys, symbols, values) {
@Override
protected void loadValue(final Expression node) {
load(node);
}
/**
* Ensure that the properties start out as object types so that
* we can do putfield initializations instead of dynamicSetIndex
* which would be the case to determine initial property type
* otherwise.
*
* Use case, it's very expensive to do a million var x = {a:obj, b:obj}
* just to have to invalidate them immediately on initialization
*
* see NASHORN-594
*/
@Override
protected MapCreator newMapCreator(final Class> fieldObjectClass) {
return new MapCreator(fieldObjectClass, keys, symbols) {
@Override
protected int getPropertyFlags(final Symbol symbol, final boolean hasArguments) {
return super.getPropertyFlags(symbol, hasArguments) | Property.IS_ALWAYS_OBJECT;
}
};
}
}.makeObject(method);
}
method.dup();
if (protoNode != null) {
load(protoNode);
method.invoke(ScriptObject.SET_PROTO_CHECK);
} else {
globalObjectPrototype();
method.invoke(ScriptObject.SET_PROTO);
}
if (hasGettersSetters) {
for (final PropertyNode propertyNode : elements) {
final FunctionNode getter = propertyNode.getGetter();
final FunctionNode setter = propertyNode.getSetter();
if (getter == null && setter == null) {
continue;
}
method.dup().loadKey(propertyNode.getKey());
if (getter == null) {
method.loadNull();
} else {
getter.accept(this);
}
if (setter == null) {
method.loadNull();
} else {
setter.accept(this);
}
method.invoke(ScriptObject.SET_USER_ACCESSORS);
}
}
method.store(objectNode.getSymbol());
return false;
}
@Override
public boolean enterReturnNode(final ReturnNode returnNode) {
lineNumber(returnNode);
method.registerReturn();
final Type returnType = lc.getCurrentFunction().getReturnType();
final Expression expression = returnNode.getExpression();
if (expression != null) {
load(expression);
} else {
method.loadUndefined(returnType);
}
method._return(returnType);
return false;
}
private static boolean isNullLiteral(final Node node) {
return node instanceof LiteralNode> && ((LiteralNode>) node).isNull();
}
private boolean nullCheck(final RuntimeNode runtimeNode, final List args, final String signature) {
final Request request = runtimeNode.getRequest();
if (!Request.isEQ(request) && !Request.isNE(request)) {
return false;
}
assert args.size() == 2 : "EQ or NE or TYPEOF need two args";
Expression lhs = args.get(0);
Expression rhs = args.get(1);
if (isNullLiteral(lhs)) {
final Expression tmp = lhs;
lhs = rhs;
rhs = tmp;
}
// this is a null literal check, so if there is implicit coercion
// involved like {D}x=null, we will fail - this is very rare
if (isNullLiteral(rhs) && lhs.getType().isObject()) {
final Label trueLabel = new Label("trueLabel");
final Label falseLabel = new Label("falseLabel");
final Label endLabel = new Label("end");
load(lhs);
method.dup();
if (Request.isEQ(request)) {
method.ifnull(trueLabel);
} else if (Request.isNE(request)) {
method.ifnonnull(trueLabel);
} else {
assert false : "Invalid request " + request;
}
method.label(falseLabel);
load(rhs);
method.invokestatic(CompilerConstants.className(ScriptRuntime.class), request.toString(), signature);
method._goto(endLabel);
method.label(trueLabel);
// if NE (not strict) this can be "undefined != null" which is supposed to be false
if (request == Request.NE) {
method.loadUndefined(Type.OBJECT);
final Label isUndefined = new Label("isUndefined");
final Label afterUndefinedCheck = new Label("afterUndefinedCheck");
method.if_acmpeq(isUndefined);
// not undefined
method.load(true);
method._goto(afterUndefinedCheck);
method.label(isUndefined);
method.load(false);
method.label(afterUndefinedCheck);
} else {
method.pop();
method.load(true);
}
method.label(endLabel);
method.convert(runtimeNode.getType());
method.store(runtimeNode.getSymbol());
return true;
}
return false;
}
private boolean specializationCheck(final RuntimeNode.Request request, final Expression node, final List args) {
if (!request.canSpecialize()) {
return false;
}
assert args.size() == 2;
final Type returnType = node.getType();
load(args.get(0));
load(args.get(1));
Request finalRequest = request;
//if the request is a comparison, i.e. one that can be reversed
//it keeps its semantic, but make sure that the object comes in
//last
final Request reverse = Request.reverse(request);
if (method.peekType().isObject() && reverse != null) { //rhs is object
if (!method.peekType(1).isObject()) { //lhs is not object
method.swap(); //prefer object as lhs
finalRequest = reverse;
}
}
method.dynamicRuntimeCall(
new SpecializedRuntimeNode(
finalRequest,
new Type[] {
method.peekType(1),
method.peekType()
},
returnType).getInitialName(),
returnType,
finalRequest);
method.convert(node.getType());
method.store(node.getSymbol());
return true;
}
private static boolean isReducible(final Request request) {
return Request.isComparison(request) || request == Request.ADD;
}
@Override
public boolean enterRuntimeNode(final RuntimeNode runtimeNode) {
/*
* First check if this should be something other than a runtime node
* AccessSpecializer might have changed the type
*
* TODO - remove this - Access Specializer will always know after Attr/Lower
*/
final List args = runtimeNode.getArgs();
if (runtimeNode.isPrimitive() && !runtimeNode.isFinal() && isReducible(runtimeNode.getRequest())) {
final Expression lhs = args.get(0);
assert args.size() > 1 : runtimeNode + " must have two args";
final Expression rhs = args.get(1);
final Type type = runtimeNode.getType();
final Symbol symbol = runtimeNode.getSymbol();
switch (runtimeNode.getRequest()) {
case EQ:
case EQ_STRICT:
return enterCmp(lhs, rhs, Condition.EQ, type, symbol);
case NE:
case NE_STRICT:
return enterCmp(lhs, rhs, Condition.NE, type, symbol);
case LE:
return enterCmp(lhs, rhs, Condition.LE, type, symbol);
case LT:
return enterCmp(lhs, rhs, Condition.LT, type, symbol);
case GE:
return enterCmp(lhs, rhs, Condition.GE, type, symbol);
case GT:
return enterCmp(lhs, rhs, Condition.GT, type, symbol);
case ADD:
Type widest = Type.widest(lhs.getType(), rhs.getType());
load(lhs);
method.convert(widest);
load(rhs);
method.convert(widest);
method.add();
method.convert(type);
method.store(symbol);
return false;
default:
// it's ok to send this one on with only primitive arguments, maybe INSTANCEOF(true, true) or similar
// assert false : runtimeNode + " has all primitive arguments. This is an inconsistent state";
break;
}
}
if (nullCheck(runtimeNode, args, new FunctionSignature(false, false, runtimeNode.getType(), args).toString())) {
return false;
}
if (!runtimeNode.isFinal() && specializationCheck(runtimeNode.getRequest(), runtimeNode, args)) {
return false;
}
for (final Expression arg : args) {
load(arg).convert(Type.OBJECT); //TODO this should not be necessary below Lower
}
method.invokestatic(
CompilerConstants.className(ScriptRuntime.class),
runtimeNode.getRequest().toString(),
new FunctionSignature(
false,
false,
runtimeNode.getType(),
args.size()).toString());
method.convert(runtimeNode.getType());
method.store(runtimeNode.getSymbol());
return false;
}
@Override
public boolean enterSplitNode(final SplitNode splitNode) {
final CompileUnit splitCompileUnit = splitNode.getCompileUnit();
final FunctionNode fn = lc.getCurrentFunction();
final String className = splitCompileUnit.getUnitClassName();
final String name = splitNode.getName();
final Class> rtype = fn.getReturnType().getTypeClass();
final boolean needsArguments = fn.needsArguments();
final Class>[] ptypes = needsArguments ?
new Class>[] {ScriptFunction.class, Object.class, ScriptObject.class, Object.class} :
new Class>[] {ScriptFunction.class, Object.class, ScriptObject.class};
final MethodEmitter caller = method;
unit = lc.pushCompileUnit(splitCompileUnit);
final Call splitCall = staticCallNoLookup(
className,
name,
methodDescriptor(rtype, ptypes));
final MethodEmitter splitEmitter =
splitCompileUnit.getClassEmitter().method(
splitNode,
name,
rtype,
ptypes);
method = lc.pushMethodEmitter(splitEmitter);
method.setFunctionNode(fn);
assert fn.needsCallee() : "split function should require callee";
caller.loadCompilerConstant(CALLEE);
caller.loadCompilerConstant(THIS);
caller.loadCompilerConstant(SCOPE);
if (needsArguments) {
caller.loadCompilerConstant(ARGUMENTS);
}
caller.invoke(splitCall);
caller.storeCompilerConstant(RETURN);
method.begin();
// Copy scope to its target slot as first thing because the original slot could be used by return symbol.
fixScopeSlot(fn);
method.loadUndefined(fn.getReturnType());
method.storeCompilerConstant(RETURN);
return true;
}
private void fixScopeSlot(final FunctionNode functionNode) {
// TODO hack to move the scope to the expected slot (needed because split methods reuse the same slots as the root method)
if (functionNode.compilerConstant(SCOPE).getSlot() != SCOPE.slot()) {
method.load(Type.typeFor(ScriptObject.class), SCOPE.slot());
method.storeCompilerConstant(SCOPE);
}
}
@Override
public Node leaveSplitNode(final SplitNode splitNode) {
assert method instanceof SplitMethodEmitter;
final boolean hasReturn = method.hasReturn();
final List