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.CREATE_PROGRAM_FUNCTION;
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.SCOPE;
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.interfaceCallNoLookup;
import static jdk.nashorn.internal.codegen.CompilerConstants.methodDescriptor;
import static jdk.nashorn.internal.codegen.CompilerConstants.staticCallNoLookup;
import static jdk.nashorn.internal.codegen.CompilerConstants.typeDescriptor;
import static jdk.nashorn.internal.codegen.CompilerConstants.virtualCallNoLookup;
import static jdk.nashorn.internal.ir.Symbol.HAS_SLOT;
import static jdk.nashorn.internal.ir.Symbol.IS_INTERNAL;
import static jdk.nashorn.internal.runtime.UnwarrantedOptimismException.INVALID_PROGRAM_POINT;
import static jdk.nashorn.internal.runtime.UnwarrantedOptimismException.isValid;
import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_APPLY_TO_CALL;
import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_DECLARE;
import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_FAST_SCOPE;
import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_OPTIMISTIC;
import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_PROGRAM_POINT_SHIFT;
import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_SCOPE;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.Supplier;
import jdk.nashorn.internal.AssertsEnabled;
import jdk.nashorn.internal.IntDeque;
import jdk.nashorn.internal.codegen.ClassEmitter.Flag;
import jdk.nashorn.internal.codegen.CompilerConstants.Call;
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.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.GetSplitState;
import jdk.nashorn.internal.ir.IdentNode;
import jdk.nashorn.internal.ir.IfNode;
import jdk.nashorn.internal.ir.IndexNode;
import jdk.nashorn.internal.ir.JoinPredecessorExpression;
import jdk.nashorn.internal.ir.JumpStatement;
import jdk.nashorn.internal.ir.JumpToInlinedFinally;
import jdk.nashorn.internal.ir.LabelNode;
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.PrimitiveLiteralNode;
import jdk.nashorn.internal.ir.LocalVariableConversion;
import jdk.nashorn.internal.ir.LoopNode;
import jdk.nashorn.internal.ir.Node;
import jdk.nashorn.internal.ir.ObjectNode;
import jdk.nashorn.internal.ir.Optimistic;
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.SetSplitState;
import jdk.nashorn.internal.ir.SplitReturn;
import jdk.nashorn.internal.ir.Splittable;
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.visitor.NodeOperatorVisitor;
import jdk.nashorn.internal.ir.visitor.SimpleNodeVisitor;
import jdk.nashorn.internal.objects.Global;
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.ECMAException;
import jdk.nashorn.internal.runtime.JSType;
import jdk.nashorn.internal.runtime.OptimisticReturnFilters;
import jdk.nashorn.internal.runtime.PropertyMap;
import jdk.nashorn.internal.runtime.RecompilableScriptFunctionData;
import jdk.nashorn.internal.runtime.RewriteException;
import jdk.nashorn.internal.runtime.Scope;
import jdk.nashorn.internal.runtime.ScriptEnvironment;
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.UnwarrantedOptimismException;
import jdk.nashorn.internal.runtime.arrays.ArrayData;
import jdk.nashorn.internal.runtime.linker.LinkerCallSite;
import jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor;
import jdk.nashorn.internal.runtime.logging.DebugLogger;
import jdk.nashorn.internal.runtime.logging.Loggable;
import jdk.nashorn.internal.runtime.logging.Logger;
import jdk.nashorn.internal.runtime.options.Options;
@Logger(name="codegen")
final class CodeGenerator extends NodeOperatorVisitor<CodeGeneratorLexicalContext> implements Loggable {
private static final Type SCOPE_TYPE = Type.typeFor(ScriptObject.class);
private static final String GLOBAL_OBJECT = Type.getInternalName(Global.class);
private static final Call CREATE_REWRITE_EXCEPTION = CompilerConstants.staticCallNoLookup(RewriteException.class,
"create", RewriteException.class, UnwarrantedOptimismException.class, Object[].class, String[].class);
private static final Call CREATE_REWRITE_EXCEPTION_REST_OF = CompilerConstants.staticCallNoLookup(RewriteException.class,
"create", RewriteException.class, UnwarrantedOptimismException.class, Object[].class, String[].class, int[].class);
private static final Call ENSURE_INT = CompilerConstants.staticCallNoLookup(OptimisticReturnFilters.class,
"ensureInt", int.class, Object.class, int.class);
private static final Call ENSURE_NUMBER = CompilerConstants.staticCallNoLookup(OptimisticReturnFilters.class,
"ensureNumber", double.class, Object.class, int.class);
private static final Call CREATE_FUNCTION_OBJECT = CompilerConstants.staticCallNoLookup(ScriptFunction.class,
"create", ScriptFunction.class, Object[].class, int.class, ScriptObject.class);
private static final Call CREATE_FUNCTION_OBJECT_NO_SCOPE = CompilerConstants.staticCallNoLookup(ScriptFunction.class,
"create", ScriptFunction.class, Object[].class, int.class);
private static final Call TO_NUMBER_FOR_EQ = CompilerConstants.staticCallNoLookup(JSType.class,
"toNumberForEq", double.class, Object.class);
private static final Call TO_NUMBER_FOR_STRICT_EQ = CompilerConstants.staticCallNoLookup(JSType.class,
"toNumberForStrictEq", double.class, Object.class);
private static final Class<?> ITERATOR_CLASS = Iterator.class;
static {
assert ITERATOR_CLASS == CompilerConstants.ITERATOR_PREFIX.type();
}
private static final Type ITERATOR_TYPE = Type.typeFor(ITERATOR_CLASS);
private static final Type EXCEPTION_TYPE = Type.typeFor(CompilerConstants.EXCEPTION_PREFIX.type());
private static final Integer INT_ZERO = 0;
private final Compiler compiler;
private final boolean evalCode;
private final int callSiteFlags;
private int regexFieldCount;
private int lastLineNumber = -1;
private static final int MAX_REGEX_FIELDS = 2 * 1024;
private MethodEmitter method;
private CompileUnit unit;
private final DebugLogger log;
static final int OBJECT_SPILL_THRESHOLD = Options.getIntProperty("nashorn.spill.threshold", 256);
private final Set<String> emittedMethods = new HashSet<>();
private ContinuationInfo continuationInfo;
private final Deque<Label> scopeEntryLabels = new ArrayDeque<>();
private static final Label METHOD_BOUNDARY = new Label("");
private final Deque<Label> catchLabels = new ArrayDeque<>();
private final IntDeque labeledBlockBreakLiveLocals = new IntDeque();
private final int[] continuationEntryPoints;
private final Deque<FieldObjectCreator<?>> scopeObjectCreators = new ArrayDeque<>();
CodeGenerator(final Compiler compiler, final int[] continuationEntryPoints) {
super(new CodeGeneratorLexicalContext());
this.compiler = compiler;
this.evalCode = compiler.getSource().isEvalCode();
this.continuationEntryPoints = continuationEntryPoints;
this.callSiteFlags = compiler.getScriptEnvironment()._callsite_flags;
this.log = initLogger(compiler.getContext());
}
@Override
public DebugLogger getLogger() {
return log;
}
@Override
public DebugLogger initLogger(final Context context) {
return context.getLogger(this.getClass());
}
int getCallSiteFlags() {
return lc.getCurrentFunction().getCallSiteFlags() | callSiteFlags;
}
private int getScopeCallSiteFlags(final Symbol symbol) {
assert symbol.isScope();
final int flags = getCallSiteFlags() | CALLSITE_SCOPE;
if (isEvalCode() && symbol.isGlobal()) {
return flags;
}
return isFastScope(symbol) ? flags | CALLSITE_FAST_SCOPE : flags;
}
boolean isEvalCode() {
return evalCode;
}
boolean useDualFields() {
return compiler.getContext().useDualFields();
}
private MethodEmitter loadIdent(final IdentNode identNode, final TypeBounds resultBounds) {
checkTemporalDeadZone(identNode);
final Symbol symbol = identNode.getSymbol();
if (!symbol.isScope()) {
final Type type = identNode.getType();
if(type == Type.UNDEFINED) {
return method.loadUndefined(resultBounds.widest);
}
assert symbol.hasSlot() || symbol.isParam();
return method.load(identNode);
}
assert identNode.getSymbol().isScope() : identNode + " is not in scope!";
final int flags = getScopeCallSiteFlags(symbol);
if (!isFastScope(symbol)) {
new LoadScopeVar(identNode, resultBounds, flags).emit();
} else if (identNode.isCompileTimePropertyName() || symbol.getUseCount() < SharedScopeCall.SHARED_GET_THRESHOLD) {
new LoadFastScopeVar(identNode, resultBounds, flags).emit();
} else {
new OptimisticOperation(identNode, resultBounds) {
@Override
void loadStack() {
method.loadCompilerConstant(SCOPE);
final int depth = getScopeProtoDepth(lc.getCurrentBlock(), symbol);
assert depth >= 0;
method.load(depth);
method.load(getProgramPoint());
}
@Override
void consumeStack() {
final Type resultType = isOptimistic ? getOptimisticCoercedType() : resultBounds.widest;
lc.getScopeGet(unit, symbol, resultType, flags, isOptimistic).generateInvoke(method);
}
}.emit();
}
return method;
}
private void checkTemporalDeadZone(final IdentNode identNode) {
if (identNode.isDead()) {
method.load(identNode.getSymbol().getName()).invoke(ScriptRuntime.THROW_REFERENCE_ERROR);
}
}
private void checkAssignTarget(final Expression expression) {
if (expression instanceof IdentNode && ((IdentNode)expression).getSymbol().isConst()) {
method.load(((IdentNode)expression).getSymbol().getName()).invoke(ScriptRuntime.THROW_CONST_TYPE_ERROR);
}
}
private boolean isRestOf() {
return continuationEntryPoints != null;
}
private boolean isCurrentContinuationEntryPoint(final int programPoint) {
return isRestOf() && getCurrentContinuationEntryPoint() == programPoint;
}
private int[] getContinuationEntryPoints() {
return isRestOf() ? continuationEntryPoints : null;
}
private int getCurrentContinuationEntryPoint() {
return isRestOf() ? continuationEntryPoints[0] : INVALID_PROGRAM_POINT;
}
private boolean isContinuationEntryPoint(final int programPoint) {
if (isRestOf()) {
assert continuationEntryPoints != null;
for (final int cep : continuationEntryPoints) {
if (cep == programPoint) {
return true;
}
}
}
return false;
}
private boolean isFastScope(final Symbol symbol) {
if (!symbol.isScope()) {
return false;
}
if (!lc.inDynamicScope()) {
assert symbol.isGlobal() || lc.getDefiningBlock(symbol).needsScope() : symbol.getName();
return true;
}
if (symbol.isGlobal()) {
return false;
}
final String name = symbol.getName();
boolean previousWasBlock = false;
for (final Iterator<LexicalContextNode> it = lc.getAllNodes(); it.hasNext();) {
final LexicalContextNode node = it.next();
if (node instanceof Block) {
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 && ((FunctionNode)node).needsDynamicScope()) {
return false;
}
previousWasBlock = false;
}
}
throw new AssertionError();
}
private class LoadScopeVar extends OptimisticOperation {
final IdentNode identNode;
private final int flags;
LoadScopeVar(final IdentNode identNode, final TypeBounds resultBounds, final int flags) {
super(identNode, resultBounds);
this.identNode = identNode;
this.flags = flags;
}
@Override
void loadStack() {
method.loadCompilerConstant(SCOPE);
getProto();
}
void getProto() {
}
@Override
void consumeStack() {
if(identNode.isCompileTimePropertyName()) {
method.dynamicGet(Type.OBJECT, identNode.getSymbol().getName(), flags, identNode.isFunction(), false);
replaceCompileTimeProperty();
} else {
dynamicGet(identNode.getSymbol().getName(), flags, identNode.isFunction(), false);
}
}
}
private class LoadFastScopeVar extends LoadScopeVar {
LoadFastScopeVar(final IdentNode identNode, final TypeBounds resultBounds, final int flags) {
super(identNode, resultBounds, flags);
}
@Override
void getProto() {
loadFastScopeProto(identNode.getSymbol(), false);
}
}
private MethodEmitter storeFastScopeVar(final Symbol symbol, final int flags) {
loadFastScopeProto(symbol, true);
method.dynamicSet(symbol.getName(), flags, false);
return method;
}
private int getScopeProtoDepth(final Block startingBlock, final Symbol symbol) {
final FunctionNode fn = lc.getCurrentFunction();
final int externalDepth = compiler.getScriptFunctionData(fn.getId()).getExternalSymbolDepth(symbol.getName());
final int internalDepth = FindScopeDepths.findInternalDepth(lc, fn, startingBlock, symbol);
final int scopesToStart = FindScopeDepths.findScopesToStart(lc, fn, startingBlock);
int depth = 0;
if (internalDepth == -1) {
depth = scopesToStart + externalDepth;
} else {
assert internalDepth <= scopesToStart;
depth = internalDepth;
}
return depth;
}
private void loadFastScopeProto(final Symbol symbol, final boolean swap) {
final int depth = getScopeProtoDepth(lc.getCurrentBlock(), symbol);
assert depth != -1 : "Couldn't find scope depth for symbol " + symbol.getName() + " in " + lc.getCurrentFunction();
if (depth > 0) {
if (swap) {
method.swap();
}
invokeGetProto(depth);
if (swap) {
method.swap();
}
}
}
private void invokeGetProto(final int depth) {
assert depth > 0;
if (depth > 1) {
method.load(depth);
method.invoke(ScriptObject.GET_PROTO_DEPTH);
} else {
method.invoke(ScriptObject.GET_PROTO);
}
}
private MethodEmitter loadExpressionUnbounded(final Expression expr) {
return loadExpression(expr, TypeBounds.UNBOUNDED);
}
private MethodEmitter loadExpressionAsObject(final Expression expr) {
return loadExpression(expr, TypeBounds.OBJECT);
}
MethodEmitter loadExpressionAsBoolean(final Expression expr) {
return loadExpression(expr, TypeBounds.BOOLEAN);
}
private static boolean noToPrimitiveConversion(final Type source, final Type target) {
return source.isJSPrimitive() || !target.isJSPrimitive() || target.isBoolean();
}
MethodEmitter loadBinaryOperands(final BinaryNode binaryNode) {
return loadBinaryOperands(binaryNode.lhs(), binaryNode.rhs(), TypeBounds.UNBOUNDED.notWiderThan(binaryNode.getWidestOperandType()), false, false);
}
private MethodEmitter loadBinaryOperands(final Expression lhs, final Expression rhs, final TypeBounds explicitOperandBounds, final boolean baseAlreadyOnStack, final boolean forceConversionSeparation) {
final Type lhsType = undefinedToNumber(lhs.getType());
final Type rhsType = undefinedToNumber(rhs.getType());
final Type narrowestOperandType = Type.narrowest(Type.widest(lhsType, rhsType), explicitOperandBounds.widest);
final TypeBounds operandBounds = explicitOperandBounds.notNarrowerThan(narrowestOperandType);
if (noToPrimitiveConversion(lhsType, explicitOperandBounds.widest) || rhs.isLocal()) {
if (forceConversionSeparation) {
final TypeBounds safeConvertBounds = TypeBounds.UNBOUNDED.notNarrowerThan(narrowestOperandType);
loadExpression(lhs, safeConvertBounds, baseAlreadyOnStack);
method.convert(operandBounds.within(method.peekType()));
loadExpression(rhs, safeConvertBounds, false);
method.convert(operandBounds.within(method.peekType()));
} else {
loadExpression(lhs, operandBounds, baseAlreadyOnStack);
loadExpression(rhs, operandBounds, false);
}
} else {
final TypeBounds safeConvertBounds = TypeBounds.UNBOUNDED.notNarrowerThan(narrowestOperandType);
loadExpression(lhs, safeConvertBounds, baseAlreadyOnStack);
final Type lhsLoadedType = method.peekType();
loadExpression(rhs, safeConvertBounds, false);
final Type convertedLhsType = operandBounds.within(method.peekType());
if (convertedLhsType != lhsLoadedType) {
method.swap().convert(convertedLhsType).swap();
}
method.convert(operandBounds.within(method.peekType()));
}
assert Type.generic(method.peekType()) == operandBounds.narrowest;
assert Type.generic(method.peekType(1)) == operandBounds.narrowest;
return method;
}
MethodEmitter loadComparisonOperands(final BinaryNode cmp) {
final Expression lhs = cmp.lhs();
final Expression rhs = cmp.rhs();
final Type lhsType = lhs.getType();
final Type rhsType = rhs.getType();
assert !(lhsType.isObject() && rhsType.isObject());
if (lhsType.isObject() || rhsType.isObject()) {
final boolean canReorder = lhsType.isPrimitive() || rhs.isLocal();
final boolean canCombineLoadAndConvert = canReorder && cmp.isRelational();
loadExpression(lhs, canCombineLoadAndConvert && !lhs.isOptimistic() ? TypeBounds.NUMBER : TypeBounds.UNBOUNDED);
final Type lhsLoadedType = method.peekType();
final TokenType tt = cmp.tokenType();
if (canReorder) {
emitObjectToNumberComparisonConversion(method, tt);
loadExpression(rhs, canCombineLoadAndConvert && !rhs.isOptimistic() ? TypeBounds.NUMBER : TypeBounds.UNBOUNDED);
} else {
loadExpression(rhs, TypeBounds.UNBOUNDED);
if (lhsLoadedType != Type.NUMBER) {
method.swap();
emitObjectToNumberComparisonConversion(method, tt);
method.swap();
}
}
emitObjectToNumberComparisonConversion(method, tt);
return method;
}
return loadBinaryOperands(cmp);
}
private static void emitObjectToNumberComparisonConversion(final MethodEmitter method, final TokenType tt) {
switch(tt) {
case EQ:
case NE:
if (method.peekType().isObject()) {
TO_NUMBER_FOR_EQ.invoke(method);
return;
}
break;
case EQ_STRICT:
case NE_STRICT:
if (method.peekType().isObject()) {
TO_NUMBER_FOR_STRICT_EQ.invoke(method);
return;
}
break;
default:
break;
}
method.convert(Type.NUMBER);
}
private static Type undefinedToNumber(final Type type) {
return type == Type.UNDEFINED ? Type.NUMBER : type;
}
private static final class TypeBounds {
final Type narrowest;
final Type widest;
static final TypeBounds UNBOUNDED = new TypeBounds(Type.UNKNOWN, Type.OBJECT);
static final TypeBounds INT = exact(Type.INT);
static final TypeBounds NUMBER = exact(Type.NUMBER);
static final TypeBounds OBJECT = exact(Type.OBJECT);
static final TypeBounds BOOLEAN = exact(Type.BOOLEAN);
static TypeBounds exact(final Type type) {
return new TypeBounds(type, type);
}
TypeBounds(final Type narrowest, final Type widest) {
assert widest != null && widest != Type.UNDEFINED && widest != Type.UNKNOWN : widest;
assert narrowest != null && narrowest != Type.UNDEFINED : narrowest;
assert !narrowest.widerThan(widest) : narrowest + " wider than " + widest;
assert !widest.narrowerThan(narrowest);
this.narrowest = Type.generic(narrowest);
this.widest = Type.generic(widest);
}
TypeBounds notNarrowerThan(final Type type) {
return maybeNew(Type.narrowest(Type.widest(narrowest, type), widest), widest);
}
TypeBounds notWiderThan(final Type type) {
return maybeNew(Type.narrowest(narrowest, type), Type.narrowest(widest, type));
}
boolean canBeNarrowerThan(final Type type) {
return narrowest.narrowerThan(type);
}
TypeBounds maybeNew(final Type newNarrowest, final Type newWidest) {
if(newNarrowest == narrowest && newWidest == widest) {
return this;
}
return new TypeBounds(newNarrowest, newWidest);
}
TypeBounds booleanToInt() {
return maybeNew(CodeGenerator.booleanToInt(narrowest), CodeGenerator.booleanToInt(widest));
}
TypeBounds objectToNumber() {
return maybeNew(CodeGenerator.objectToNumber(narrowest), CodeGenerator.objectToNumber(widest));
}
Type within(final Type type) {
if(type.narrowerThan(narrowest)) {
return narrowest;
}
if(type.widerThan(widest)) {
return widest;
}
return type;
}
@Override
public String toString() {
return "[" + narrowest + ", " + widest + "]";
}
}
private static Type booleanToInt(final Type t) {
return t == Type.BOOLEAN ? Type.INT : t;
}
private static Type objectToNumber(final Type t) {
return t.isObject() ? Type.NUMBER : t;
}
MethodEmitter loadExpressionAsType(final Expression expr, final Type type) {
if(type == Type.BOOLEAN) {
return loadExpressionAsBoolean(expr);
} else if(type == Type.UNDEFINED) {
assert expr.getType() == Type.UNDEFINED;
return loadExpressionAsObject(expr);
}
return loadExpression(expr, TypeBounds.UNBOUNDED.notNarrowerThan(type)).convert(type);
}
private MethodEmitter loadExpression(final Expression expr, final TypeBounds resultBounds) {
return loadExpression(expr, resultBounds, false);
}
private MethodEmitter loadExpression(final Expression expr, final TypeBounds resultBounds, final boolean baseAlreadyOnStack) {
final CodeGenerator codegen = this;
final boolean isCurrentDiscard = codegen.lc.isCurrentDiscard(expr);
expr.accept(new NodeOperatorVisitor<LexicalContext>(new LexicalContext()) {
@Override
public boolean enterIdentNode(final IdentNode identNode) {
loadIdent(identNode, resultBounds);
return false;
}
@Override
public boolean enterAccessNode(final AccessNode accessNode) {
new OptimisticOperation(accessNode, resultBounds) {
@Override
void loadStack() {
if (!baseAlreadyOnStack) {
loadExpressionAsObject(accessNode.getBase());
}
assert method.peekType().isObject();
}
@Override
void consumeStack() {
final int flags = getCallSiteFlags();
dynamicGet(accessNode.getProperty(), flags, accessNode.isFunction(), accessNode.isIndex());
}
}.emit(baseAlreadyOnStack ? 1 : 0);
return false;
}
@Override
public boolean enterIndexNode(final IndexNode indexNode) {
new OptimisticOperation(indexNode, resultBounds) {
@Override
void loadStack() {
if (!baseAlreadyOnStack) {
loadExpressionAsObject(indexNode.getBase());
loadExpressionUnbounded(indexNode.getIndex());
}
}
@Override
void consumeStack() {
final int flags = getCallSiteFlags();
dynamicGetIndex(flags, indexNode.isFunction());
}
}.emit(baseAlreadyOnStack ? 2 : 0);
return false;
}
@Override
public boolean enterFunctionNode(final FunctionNode functionNode) {
lc.pop(functionNode);
functionNode.accept(codegen);
lc.push(functionNode);
return false;
}
@Override
public boolean enterASSIGN(final BinaryNode binaryNode) {
checkAssignTarget(binaryNode.lhs());
loadASSIGN(binaryNode);
return false;
}
@Override
public boolean enterASSIGN_ADD(final BinaryNode binaryNode) {
checkAssignTarget(binaryNode.lhs());
loadASSIGN_ADD(binaryNode);
return false;
}
@Override
public boolean enterASSIGN_BIT_AND(final BinaryNode binaryNode) {
checkAssignTarget(binaryNode.lhs());
loadASSIGN_BIT_AND(binaryNode);
return false;
}
@Override
public boolean enterASSIGN_BIT_OR(final BinaryNode binaryNode) {
checkAssignTarget(binaryNode.lhs());
loadASSIGN_BIT_OR(binaryNode);
return false;
}
@Override
public boolean enterASSIGN_BIT_XOR(final BinaryNode binaryNode) {
checkAssignTarget(binaryNode.lhs());
loadASSIGN_BIT_XOR(binaryNode);
return false;
}
@Override
public boolean enterASSIGN_DIV(final BinaryNode binaryNode) {
checkAssignTarget(binaryNode.lhs());
loadASSIGN_DIV(binaryNode);
return false;
}
@Override
public boolean enterASSIGN_MOD(final BinaryNode binaryNode) {
checkAssignTarget(binaryNode.lhs());
loadASSIGN_MOD(binaryNode);
return false;
}
@Override
public boolean enterASSIGN_MUL(final BinaryNode binaryNode) {
checkAssignTarget(binaryNode.lhs());
loadASSIGN_MUL(binaryNode);
return false;
}
@Override
public boolean enterASSIGN_SAR(final BinaryNode binaryNode) {
checkAssignTarget(binaryNode.lhs());
loadASSIGN_SAR(binaryNode);
return false;
}
@Override
public boolean enterASSIGN_SHL(final BinaryNode binaryNode) {
checkAssignTarget(binaryNode.lhs());
loadASSIGN_SHL(binaryNode);
return false;
}
@Override
public boolean enterASSIGN_SHR(final BinaryNode binaryNode) {
checkAssignTarget(binaryNode.lhs());
loadASSIGN_SHR(binaryNode);
return false;
}
@Override
public boolean enterASSIGN_SUB(final BinaryNode binaryNode) {
checkAssignTarget(binaryNode.lhs());
loadASSIGN_SUB(binaryNode);
return false;
}
@Override
public boolean enterCallNode(final CallNode callNode) {
return loadCallNode(callNode, resultBounds);
}
@Override
public boolean enterLiteralNode(final LiteralNode<?> literalNode) {
loadLiteral(literalNode, resultBounds);
return false;
}
@Override
public boolean enterTernaryNode(final TernaryNode ternaryNode) {
loadTernaryNode(ternaryNode, resultBounds);
return false;
}
@Override
public boolean enterADD(final BinaryNode binaryNode) {
loadADD(binaryNode, resultBounds);
return false;
}
@Override
public boolean enterNEG(final UnaryNode unaryNode) {
loadSUB(unaryNode, resultBounds);
return false;
}
@Override
public boolean enterSUB(final BinaryNode binaryNode) {
loadSUB(binaryNode, resultBounds);
return false;
}
@Override
public boolean enterMUL(final BinaryNode binaryNode) {
loadMUL(binaryNode, resultBounds);
return false;
}
@Override
public boolean enterDIV(final BinaryNode binaryNode) {
loadDIV(binaryNode, resultBounds);
return false;
}
@Override
public boolean enterMOD(final BinaryNode binaryNode) {
loadMOD(binaryNode, resultBounds);
return false;
}
@Override
public boolean enterSAR(final BinaryNode binaryNode) {
loadSAR(binaryNode);
return false;
}
@Override
public boolean enterSHL(final BinaryNode binaryNode) {
loadSHL(binaryNode);
return false;
}
@Override
public boolean enterSHR(final BinaryNode binaryNode) {
loadSHR(binaryNode);
return false;
}
@Override
public boolean enterCOMMALEFT(final BinaryNode binaryNode) {
loadCOMMALEFT(binaryNode, resultBounds);
return false;
}
@Override
public boolean enterCOMMARIGHT(final BinaryNode binaryNode) {
loadCOMMARIGHT(binaryNode, resultBounds);
return false;
}
@Override
public boolean enterAND(final BinaryNode binaryNode) {
loadAND_OR(binaryNode, resultBounds, true);
return false;
}
@Override
public boolean enterOR(final BinaryNode binaryNode) {
loadAND_OR(binaryNode, resultBounds, false);
return false;
}
@Override
public boolean enterNOT(final UnaryNode unaryNode) {
loadNOT(unaryNode);
return false;
}
@Override
public boolean enterPOS(final UnaryNode unaryNode) {
loadADD(unaryNode, resultBounds);
return false;
}
@Override
public boolean enterBIT_NOT(final UnaryNode unaryNode) {
loadBIT_NOT(unaryNode);
return false;
}
@Override
public boolean enterBIT_AND(final BinaryNode binaryNode) {
loadBIT_AND(binaryNode);
return false;
}
@Override
public boolean enterBIT_OR(final BinaryNode binaryNode) {
loadBIT_OR(binaryNode);
return false;
}
@Override
public boolean enterBIT_XOR(final BinaryNode binaryNode) {
loadBIT_XOR(binaryNode);
return false;
}
@Override
public boolean enterVOID(final UnaryNode unaryNode) {
loadVOID(unaryNode, resultBounds);
return false;
}
@Override
public boolean enterDELETE(final UnaryNode unaryNode) {
loadDELETE(unaryNode);
return false;
}
@Override
public boolean enterEQ(final BinaryNode binaryNode) {
loadCmp(binaryNode, Condition.EQ);
return false;
}
@Override
public boolean enterEQ_STRICT(final BinaryNode binaryNode) {
loadCmp(binaryNode, Condition.EQ);
return false;
}
@Override
public boolean enterGE(final BinaryNode binaryNode) {
loadCmp(binaryNode, Condition.GE);
return false;
}
@Override
public boolean enterGT(final BinaryNode binaryNode) {
loadCmp(binaryNode, Condition.GT);
return false;
}
@Override
public boolean enterLE(final BinaryNode binaryNode) {
loadCmp(binaryNode, Condition.LE);
return false;
}
@Override
public boolean enterLT(final BinaryNode binaryNode) {
loadCmp(binaryNode, Condition.LT);
return false;
}
@Override
public boolean enterNE(final BinaryNode binaryNode) {
loadCmp(binaryNode, Condition.NE);
return false;
}
@Override
public boolean enterNE_STRICT(final BinaryNode binaryNode) {
loadCmp(binaryNode, Condition.NE);
return false;
}
@Override
public boolean enterObjectNode(final ObjectNode objectNode) {
loadObjectNode(objectNode);
return false;
}
@Override
public boolean enterRuntimeNode(final RuntimeNode runtimeNode) {
loadRuntimeNode(runtimeNode);
return false;
}
@Override
public boolean enterNEW(final UnaryNode unaryNode) {
loadNEW(unaryNode);
return false;
}
@Override
public boolean enterDECINC(final UnaryNode unaryNode) {
checkAssignTarget(unaryNode.getExpression());
loadDECINC(unaryNode);
return false;
}
@Override
public boolean enterJoinPredecessorExpression(final JoinPredecessorExpression joinExpr) {
loadMaybeDiscard(joinExpr, joinExpr.getExpression(), resultBounds);
return false;
}
@Override
public boolean enterGetSplitState(final GetSplitState getSplitState) {
method.loadScope();
method.invoke(Scope.GET_SPLIT_STATE);
return false;
}
@Override
public boolean enterDefault(final Node otherNode) {
throw new AssertionError(otherNode.getClass().getName());
}
});
if(!isCurrentDiscard) {
coerceStackTop(resultBounds);
}
return method;
}
private MethodEmitter coerceStackTop(final TypeBounds typeBounds) {
return method.convert(typeBounds.within(method.peekType()));
}
private void closeBlockVariables(final Block block) {
for (final Symbol symbol : block.getSymbols()) {
if (symbol.isBytecodeLocal()) {
method.closeLocalVariable(symbol, block.getBreakLabel());
}
}
}
@Override
public boolean enterBlock(final Block block) {
final Label entryLabel = block.getEntryLabel();
if (entryLabel.isBreakTarget()) {
assert !method.isReachable();
method.breakLabel(entryLabel, lc.getUsedSlotCount());
} else {
method.label(entryLabel);
}
if(!method.isReachable()) {
return false;
}
if(lc.isFunctionBody() && emittedMethods.contains(lc.getCurrentFunction().getName())) {
return false;
}
initLocals(block);
assert lc.getUsedSlotCount() == method.getFirstTemp();
return true;
}
boolean useOptimisticTypes() {
return !lc.inSplitLiteral() && compiler.useOptimisticTypes();
}
@Override
public Node leaveBlock(final Block block) {
popBlockScope(block);
method.beforeJoinPoint(block);
closeBlockVariables(block);
lc.releaseSlots();
assert !method.isReachable() || (lc.isFunctionBody() ? 0 : lc.getUsedSlotCount()) == method.getFirstTemp() :
"reachable="+method.isReachable() +
" isFunctionBody=" + lc.isFunctionBody() +
" usedSlotCount=" + lc.getUsedSlotCount() +
" firstTemp=" + method.getFirstTemp();
return block;
}
private void popBlockScope(final Block block) {
final Label breakLabel = block.getBreakLabel();
if (block.providesScopeCreator()) {
scopeObjectCreators.pop();
}
if(!block.needsScope() || lc.isFunctionBody()) {
emitBlockBreakLabel(breakLabel);
return;
}
final Label beginTryLabel = scopeEntryLabels.pop();
final Label recoveryLabel = new Label("block_popscope_catch");
emitBlockBreakLabel(breakLabel);
final boolean bodyCanThrow = breakLabel.isAfter(beginTryLabel);
if(bodyCanThrow) {
method._try(beginTryLabel, breakLabel, recoveryLabel);
}
Label afterCatchLabel = null;
if(method.isReachable()) {
popScope();
if(bodyCanThrow) {
afterCatchLabel = new Label("block_after_catch");
method._goto(afterCatchLabel);
}
}
if(bodyCanThrow) {
assert !method.isReachable();
method._catch(recoveryLabel);
popScopeException();
method.athrow();
}
if(afterCatchLabel != null) {
method.label(afterCatchLabel);
}
}
private void emitBlockBreakLabel(final Label breakLabel) {
final LabelNode labelNode = lc.getCurrentBlockLabelNode();
if(labelNode != null) {
assert labelNode.getLocalVariableConversion() == null || method.isReachable();
method.beforeJoinPoint(labelNode);
method.breakLabel(breakLabel, labeledBlockBreakLiveLocals.pop());
} else {
method.label(breakLabel);
}
}
private void popScope() {
popScopes(1);
}
private void popScopeException() {
popScope();
final ContinuationInfo ci = getContinuationInfo();
if(ci != null) {
final Label catchLabel = ci.catchLabel;
if(catchLabel != METHOD_BOUNDARY && catchLabel == catchLabels.peek()) {
++ci.exceptionScopePops;
}
}
}
private void popScopesUntil(final LexicalContextNode until) {
popScopes(lc.getScopeNestingLevelTo(until));
}
private void popScopes(final int count) {
if(count == 0) {
return;
}
assert count > 0;
if (!method.hasScope()) {
return;
}
method.loadCompilerConstant(SCOPE);
invokeGetProto(count);
method.storeCompilerConstant(SCOPE);
}
@Override
public boolean enterBreakNode(final BreakNode breakNode) {
return enterJumpStatement(breakNode);
}
@Override
public boolean enterJumpToInlinedFinally(final JumpToInlinedFinally jumpToInlinedFinally) {
return enterJumpStatement(jumpToInlinedFinally);
}
private boolean enterJumpStatement(final JumpStatement jump) {
if(!method.isReachable()) {
return false;
}
enterStatement(jump);
method.beforeJoinPoint(jump);
popScopesUntil(jump.getPopScopeLimit(lc));
final Label targetLabel = jump.getTargetLabel(lc);
targetLabel.markAsBreakTarget();
method._goto(targetLabel);
return false;
}
private int loadArgs(final List<Expression> args) {
final int argCount = args.size();
if (argCount > LinkerCallSite.ARGLIMIT) {
loadArgsArray(args);
return 1;
}
for (final Expression arg : args) {
assert arg != null;
loadExpressionUnbounded(arg);
}
return argCount;
}
private boolean loadCallNode(final CallNode callNode, final TypeBounds resultBounds) {
lineNumber(callNode.getLineNumber());
final List<Expression> args = callNode.getArgs();
final Expression function = callNode.getFunction();
final Block currentBlock = lc.getCurrentBlock();
final CodeGeneratorLexicalContext codegenLexicalContext = lc;
function.accept(new SimpleNodeVisitor() {
private MethodEmitter sharedScopeCall(final IdentNode identNode, final int flags) {
final Symbol symbol = identNode.getSymbol();
assert isFastScope(symbol);
new OptimisticOperation(callNode, resultBounds) {
@Override
void loadStack() {
method.loadCompilerConstant(SCOPE);
final int depth = getScopeProtoDepth(currentBlock, symbol);
assert depth >= 0;
method.load(depth);
method.load(getProgramPoint());
loadArgs(args);
}
@Override
void consumeStack() {
final Type[] paramTypes = method.getTypesFromStack(args.size());
for(int i = 0; i < paramTypes.length; ++i) {
paramTypes[i] = Type.generic(paramTypes[i]);
}
final Type resultType = isOptimistic ? getOptimisticCoercedType() : resultBounds.widest;
final SharedScopeCall scopeCall = codegenLexicalContext.getScopeCall(unit, symbol,
identNode.getType(), resultType, paramTypes, flags, isOptimistic);
scopeCall.generateInvoke(method);
}
}.emit();
return method;
}
private void scopeCall(final IdentNode ident, final int flags) {
new OptimisticOperation(callNode, resultBounds) {
int argsCount;
@Override
void loadStack() {
loadExpressionAsObject(ident);
method.loadUndefined(Type.OBJECT);
argsCount = loadArgs(args);
}
@Override
void consumeStack() {
dynamicCall(2 + argsCount, flags, ident.getName());
}
}.emit();
}
private void evalCall(final IdentNode ident, final int flags) {
final Label invoke_direct_eval = new Label("invoke_direct_eval");
final Label is_not_eval = new Label("is_not_eval");
final Label eval_done = new Label("eval_done");
new OptimisticOperation(callNode, resultBounds) {
int argsCount;
@Override
void loadStack() {
loadExpressionAsObject(ident.setIsNotFunction());
globalIsEval();
method.ifeq(is_not_eval);
method.loadCompilerConstant(SCOPE);
final List<Expression> evalArgs = callNode.getEvalArgs().getArgs();
loadExpressionAsObject(evalArgs.get(0));
final int numArgs = evalArgs.size();
for (int i = 1; i < numArgs; i++) {
loadAndDiscard(evalArgs.get(i));
}
method._goto(invoke_direct_eval);
method.label(is_not_eval);
loadExpressionAsObject(ident);
method.loadNull();
argsCount = loadArgs(callNode.getArgs());
}
@Override
void consumeStack() {
dynamicCall(2 + argsCount, flags, "eval");
method._goto(eval_done);
method.label(invoke_direct_eval);
method.loadCompilerConstant(THIS);
method.load(callNode.getEvalArgs().getLocation());
method.load(CodeGenerator.this.lc.getCurrentFunction().isStrict());
globalDirectEval();
convertOptimisticReturnValue();
coerceStackTop(resultBounds);
}
}.emit();
method.label(eval_done);
}
@Override
public boolean enterIdentNode(final IdentNode node) {
final Symbol symbol = node.getSymbol();
if (symbol.isScope()) {
final int flags = getScopeCallSiteFlags(symbol);
final int useCount = symbol.getUseCount();
if (callNode.isEval()) {
evalCall(node, flags);
} else if (!isFastScope(symbol) || symbol.getUseCount() < SharedScopeCall.SHARED_CALL_THRESHOLD) {
scopeCall(node, flags);
} else {
sharedScopeCall(node, flags);
}
assert method.peekType().equals(resultBounds.within(callNode.getType())) : method.peekType() + " != " + resultBounds + "(" + callNode.getType() + ")";
} else {
enterDefault(node);
}
return false;
}
@Override
public boolean enterAccessNode(final AccessNode node) {
final int flags = getCallSiteFlags() | (callNode.isApplyToCall() ? CALLSITE_APPLY_TO_CALL : 0);
new OptimisticOperation(callNode, resultBounds) {
int argCount;
@Override
void loadStack() {
loadExpressionAsObject(node.getBase());
method.dup();
assert !node.isOptimistic();
method.dynamicGet(node.getType(), node.getProperty(), flags, true, node.isIndex());
method.swap();
argCount = loadArgs(args);
}
@Override
void consumeStack() {
dynamicCall(2 + argCount, flags, node.toString(false));
}
}.emit();
return false;
}
@Override
public boolean enterFunctionNode(final FunctionNode origCallee) {
new OptimisticOperation(callNode, resultBounds) {
FunctionNode callee;
int argsCount;
@Override
void loadStack() {
callee = (FunctionNode)origCallee.accept(CodeGenerator.this);
if (callee.isStrict()) {
method.loadUndefined(Type.OBJECT);
} else {
globalInstance();
}
argsCount = loadArgs(args);
}
@Override
void consumeStack() {
dynamicCall(2 + argsCount, getCallSiteFlags(), null);
}
}.emit();
return false;
}
@Override
public boolean enterIndexNode(final IndexNode node) {
new OptimisticOperation(callNode, resultBounds) {
int argsCount;
@Override
void loadStack() {
loadExpressionAsObject(node.getBase());
method.dup();
final Type indexType = node.getIndex().getType();
if (indexType.isObject() || indexType.isBoolean()) {
loadExpressionAsObject(node.getIndex());
} else {
loadExpressionUnbounded(node.getIndex());
}
assert !node.isOptimistic();
method.dynamicGetIndex(node.getType(), getCallSiteFlags(), true);
method.swap();
argsCount = loadArgs(args);
}
@Override
void consumeStack() {
dynamicCall(2 + argsCount, getCallSiteFlags(), node.toString(false));
}
}.emit();
return false;
}
@Override
protected boolean enterDefault(final Node node) {
new OptimisticOperation(callNode, resultBounds) {
int argsCount;
@Override
void loadStack() {
loadExpressionAsObject(function);
method.loadUndefined(Type.OBJECT);
argsCount = loadArgs(args);
}
@Override
void consumeStack() {
final int flags = getCallSiteFlags() | CALLSITE_SCOPE;
dynamicCall(2 + argsCount, flags, node.toString(false));
}
}.emit();
return false;
}
});
return false;
}
static int nonOptimisticFlags(final int flags) {
return flags & ~(CALLSITE_OPTIMISTIC | -1 << CALLSITE_PROGRAM_POINT_SHIFT);
}
@Override
public boolean enterContinueNode(final ContinueNode continueNode) {
return enterJumpStatement(continueNode);
}
@Override
public boolean enterEmptyNode(final EmptyNode emptyNode) {
return false;
}
@Override
public boolean enterExpressionStatement(final ExpressionStatement expressionStatement) {
if(!method.isReachable()) {
return false;
}
enterStatement(expressionStatement);
loadAndDiscard(expressionStatement.getExpression());
assert method.getStackSize() == 0 : "stack not empty in " + expressionStatement;
return false;
}
@Override
public boolean enterBlockStatement(final BlockStatement blockStatement) {
if(!method.isReachable()) {
return false;
}
enterStatement(blockStatement);
blockStatement.getBlock().accept(this);
return false;
}
@Override
public boolean enterForNode(final ForNode forNode) {
if(!method.isReachable()) {
return false;
}
enterStatement(forNode);
if (forNode.isForInOrOf()) {
enterForIn(forNode);
} else {
final Expression init = forNode.getInit();
if (init != null) {
loadAndDiscard(init);
}
enterForOrWhile(forNode, forNode.getModify());
}
return false;
}
private void enterForIn(final ForNode forNode) {
loadExpression(forNode.getModify(), TypeBounds.OBJECT);
if (forNode.isForEach()) {
method.invoke(ScriptRuntime.TO_VALUE_ITERATOR);
} else if (forNode.isForIn()) {
method.invoke(ScriptRuntime.TO_PROPERTY_ITERATOR);
} else if (forNode.isForOf()) {
method.invoke(ScriptRuntime.TO_ES6_ITERATOR);
} else {
throw new IllegalArgumentException("Unexpected for node");
}
final Symbol iterSymbol = forNode.getIterator();
final int iterSlot = iterSymbol.getSlot(Type.OBJECT);
method.store(iterSymbol, ITERATOR_TYPE);
method.beforeJoinPoint(forNode);
final Label continueLabel = forNode.getContinueLabel();
final Label breakLabel = forNode.getBreakLabel();
method.label(continueLabel);
method.load(ITERATOR_TYPE, iterSlot);
method.invoke(interfaceCallNoLookup(ITERATOR_CLASS, "hasNext", boolean.class));
final JoinPredecessorExpression test = forNode.getTest();
final Block body = forNode.getBody();
if(LocalVariableConversion.hasLiveConversion(test)) {
final Label afterConversion = new Label("for_in_after_test_conv");
method.ifne(afterConversion);
method.beforeJoinPoint(test);
method._goto(breakLabel);
method.label(afterConversion);
} else {
method.ifeq(breakLabel);
}
new Store<Expression>(forNode.getInit()) {
@Override
protected void storeNonDiscard() {
}
@Override
protected void evaluate() {
new OptimisticOperation((Optimistic)forNode.getInit(), TypeBounds.UNBOUNDED) {
@Override
void loadStack() {
method.load(ITERATOR_TYPE, iterSlot);
}
@Override
void consumeStack() {
method.invoke(interfaceCallNoLookup(ITERATOR_CLASS, "next", Object.class));
convertOptimisticReturnValue();
}
}.emit();
}
}.store();
body.accept(this);
if (forNode.needsScopeCreator() && lc.getCurrentBlock().providesScopeCreator()) {
final FieldObjectCreator<?> creator = scopeObjectCreators.peek();
assert creator != null;
creator.createForInIterationScope(method);
method.storeCompilerConstant(SCOPE);
}
if(method.isReachable()) {
method._goto(continueLabel);
}
method.label(breakLabel);
}
private void initLocals(final Block block) {
lc.onEnterBlock(block);
final boolean isFunctionBody = lc.isFunctionBody();
final FunctionNode function = lc.getCurrentFunction();
if (isFunctionBody) {
initializeMethodParameters(function);
if(!function.isVarArg()) {
expandParameterSlots(function);
}
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);
}
}
if (block.needsScope()) {
final boolean varsInScope = function.allVarsInScope();
final boolean hasArguments = function.needsArguments();
final List<MapTuple<Symbol>> tuples = new ArrayList<>();
final Iterator<IdentNode> paramIter = function.getParameters().iterator();
for (final Symbol symbol : block.getSymbols()) {
if (symbol.isInternal() || symbol.isThis()) {
continue;
}
if (symbol.isVar()) {
assert !varsInScope || symbol.isScope();
if (varsInScope || symbol.isScope()) {
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();
tuples.add(new MapTuple<Symbol>(symbol.getName(), symbol, null));
} else {
assert symbol.hasSlot() || symbol.slotCount() == 0 : symbol + " should have a slot only, no scope";
}
} else if (symbol.isParam() && (varsInScope || hasArguments || symbol.isScope())) {
assert symbol.isScope() : "scope for " + symbol + " should have been set in AssignSymbols 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();
final Type paramType;
final Symbol paramSymbol;
if (hasArguments) {
assert !symbol.hasSlot() : "slot for " + symbol + " should have been removed in Lower already ";
paramSymbol = null;
paramType = null;
} else {
paramSymbol = symbol;
for(;;) {
final IdentNode nextParam = paramIter.next();
if(nextParam.getName().equals(symbol.getName())) {
paramType = nextParam.getType();
break;
}
}
}
tuples.add(new MapTuple<Symbol>(symbol.getName(), symbol, paramType, paramSymbol) {
@Override
public Class<?> getValueType() {
if (!useDualFields() || value == null || paramType == null || paramType.isBoolean()) {
return Object.class;
}
return paramType.getTypeClass();
}
});
}
}
final FieldObjectCreator<Symbol> creator = new FieldObjectCreator<Symbol>(this, tuples, true, hasArguments) {
@Override
protected void loadValue(final Symbol value, final Type type) {
method.load(value, type);
}
};
creator.makeObject(method);
if (block.providesScopeCreator()) {
scopeObjectCreators.push(creator);
}
if (isFunctionBody && function.isProgram()) {
method.invoke(ScriptRuntime.MERGE_SCOPE);
}
method.storeCompilerConstant(SCOPE);
if(!isFunctionBody) {
final Label scopeEntryLabel = new Label("scope_entry");
scopeEntryLabels.push(scopeEntryLabel);
method.label(scopeEntryLabel);
}
} else if (isFunctionBody && function.isVarArg()) {
int nextParam = 0;
for (final IdentNode param : function.getParameters()) {
param.getSymbol().setFieldIndex(nextParam++);
}
}
printSymbols(block, function, (isFunctionBody ? "Function " : "Block in ") + (function.getIdent() == null ? "<anonymous>" : function.getIdent().getName()));
}
private void initializeMethodParameters(final FunctionNode function) {
final Label functionStart = new Label("fn_start");
method.label(functionStart);
int nextSlot = 0;
if(function.needsCallee()) {
initializeInternalFunctionParameter(CALLEE, function, functionStart, nextSlot++);
}
initializeInternalFunctionParameter(THIS, function, functionStart, nextSlot++);
if(function.isVarArg()) {
initializeInternalFunctionParameter(VARARGS, function, functionStart, nextSlot++);
} else {
for(final IdentNode param: function.getParameters()) {
final Symbol symbol = param.getSymbol();
if(symbol.isBytecodeLocal()) {
method.initializeMethodParameter(symbol, param.getType(), functionStart);
}
}
}
}
private void initializeInternalFunctionParameter(final CompilerConstants cc, final FunctionNode fn, final Label functionStart, final int slot) {
final Symbol symbol = initializeInternalFunctionOrSplitParameter(cc, fn, functionStart, slot);
assert symbol.getFirstSlot() == slot;
}
private Symbol initializeInternalFunctionOrSplitParameter(final CompilerConstants cc, final FunctionNode fn, final Label functionStart, final int slot) {
final Symbol symbol = fn.getBody().getExistingSymbol(cc.symbolName());
final Type type = Type.typeFor(cc.type());
method.initializeMethodParameter(symbol, type, functionStart);
method.onLocalStore(type, slot);
return symbol;
}
private void expandParameterSlots(final FunctionNode function) {
final List<IdentNode> parameters = function.getParameters();
int currentIncomingSlot = function.needsCallee() ? 2 : 1;
for(final IdentNode parameter: parameters) {
currentIncomingSlot += parameter.getType().getSlots();
}
for(int i = parameters.size(); i-- > 0;) {
final IdentNode parameter = parameters.get(i);
final Type parameterType = parameter.getType();
final int typeWidth = parameterType.getSlots();
currentIncomingSlot -= typeWidth;
final Symbol symbol = parameter.getSymbol();
final int slotCount = symbol.slotCount();
assert slotCount > 0;
assert symbol.isBytecodeLocal() || slotCount == typeWidth;
method.onLocalStore(parameterType, currentIncomingSlot);
if(currentIncomingSlot != symbol.getSlot(parameterType)) {
method.load(parameterType, currentIncomingSlot);
method.store(symbol, parameterType);
}
}
}
private void initArguments(final FunctionNode function) {
method.loadCompilerConstant(VARARGS);
if (function.needsCallee()) {
method.loadCompilerConstant(CALLEE);
} else {
assert function.isStrict();
method.loadNull();
}
method.load(function.getParameters().size());
globalAllocateArguments();
method.storeCompilerConstant(ARGUMENTS);
}
private boolean skipFunction(final FunctionNode functionNode) {
final ScriptEnvironment env = compiler.getScriptEnvironment();
final boolean lazy = env._lazy_compilation;
final boolean onDemand = compiler.isOnDemandCompilation();
if((onDemand || lazy) && lc.getOutermostFunction() != functionNode) {
return true;
}
return !onDemand && lazy && env._optimistic_types && functionNode.isProgram();
}
@Override
public boolean enterFunctionNode(final FunctionNode functionNode) {
if (skipFunction(functionNode)) {
newFunctionObject(functionNode, false);
return false;
}
final String fnName = functionNode.getName();
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();
final ClassEmitter classEmitter = unit.getClassEmitter();
pushMethodEmitter(isRestOf() ? classEmitter.restOfMethod(functionNode) : classEmitter.method(functionNode));
method.setPreventUndefinedLoad();
if(useOptimisticTypes()) {
lc.pushUnwarrantedOptimismHandlers();
}
lastLineNumber = -1;
method.begin();
if (isRestOf()) {
assert continuationInfo == null;
continuationInfo = new ContinuationInfo();
method.gotoLoopStart(continuationInfo.getHandlerLabel());
}
}
return true;
}
private void pushMethodEmitter(final MethodEmitter newMethod) {
method = lc.pushMethodEmitter(newMethod);
catchLabels.push(METHOD_BOUNDARY);
}
private void popMethodEmitter() {
method = lc.popMethodEmitter(method);
assert catchLabels.peek() == METHOD_BOUNDARY;
catchLabels.pop();
}
@Override
public Node leaveFunctionNode(final FunctionNode functionNode) {
try {
final boolean markOptimistic;
if (emittedMethods.add(functionNode.getName())) {
markOptimistic = generateUnwarrantedOptimismExceptionHandlers(functionNode);
generateContinuationHandler();
method.end();
unit = lc.popCompileUnit(functionNode.getCompileUnit());
popMethodEmitter();
log.info("=== END ", functionNode.getName());
} else {
markOptimistic = false;
}
FunctionNode newFunctionNode = functionNode;
if (markOptimistic) {
newFunctionNode = newFunctionNode.setFlag(lc, FunctionNode.IS_DEOPTIMIZABLE);
}
newFunctionObject(newFunctionNode, true);
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 enterIfNode(final IfNode ifNode) {
if(!method.isReachable()) {
return false;
}
enterStatement(ifNode);
final Expression test = ifNode.getTest();
final Block pass = ifNode.getPass();
final Block fail = ifNode.getFail();
if (Expression.isAlwaysTrue(test)) {
loadAndDiscard(test);
pass.accept(this);
return false;
} else if (Expression.isAlwaysFalse(test)) {
loadAndDiscard(test);
if (fail != null) {
fail.accept(this);
}
return false;
}
final boolean hasFailConversion = LocalVariableConversion.hasLiveConversion(ifNode);
final Label failLabel = new Label("if_fail");
final Label afterLabel = (fail == null && !hasFailConversion) ? null : new Label("if_done");
emitBranch(test, failLabel, false);
pass.accept(this);
if(method.isReachable() && afterLabel != null) {
method._goto(afterLabel);
}
method.label(failLabel);
if (fail != null) {
fail.accept(this);
} else if(hasFailConversion) {
method.beforeJoinPoint(ifNode);
}
if(afterLabel != null && afterLabel.isReachable()) {
method.label(afterLabel);
}
return false;
}
private void emitBranch(final Expression test, final Label label, final boolean jumpWhenTrue) {
new BranchOptimizer(this, method).execute(test, label, jumpWhenTrue);
}
private void enterStatement(final Statement statement) {
lineNumber(statement);
}
private void lineNumber(final Statement statement) {
lineNumber(statement.getLineNumber());
}
private void lineNumber(final int lineNumber) {
if (lineNumber != lastLineNumber && lineNumber != Node.NO_LINE_NUMBER) {
method.lineNumber(lineNumber);
lastLineNumber = lineNumber;
}
}
int getLastLineNumber() {
return lastLineNumber;
}
private void loadArray(final ArrayLiteralNode arrayLiteralNode, final ArrayType arrayType) {
assert arrayType == Type.INT_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 List<Splittable.SplitRange> ranges = arrayLiteralNode.getSplitRanges();
loadConstant(presets);
final Type elementType = arrayType.getElementType();
if (ranges != null) {
loadSplitLiteral(new SplitLiteralCreator() {
@Override
public void populateRange(final MethodEmitter method, final Type type, final int slot, final int start, final int end) {
for (int i = start; i < end; i++) {
method.load(type, slot);
storeElement(nodes, elementType, postsets[i]);
}
method.load(type, slot);
}
}, ranges, arrayType);
return;
}
if(postsets.length > 0) {
final int arraySlot = method.getUsedSlotsWithLiveTemporaries();
method.storeTemp(arrayType, arraySlot);
for (final int postset : postsets) {
method.load(arrayType, arraySlot);
storeElement(nodes, elementType, postset);
}
method.load(arrayType, arraySlot);
}
}
private void storeElement(final Expression[] nodes, final Type elementType, final int index) {
method.load(index);
final Expression element = nodes[index];
if (element == null) {
method.loadEmpty(elementType);
} else {
loadExpressionAsType(element, elementType);
}
method.arraystore();
}
private MethodEmitter loadArgsArray(final List<Expression> args) {
final Object[] array = new Object[args.size()];
loadConstant(array);
for (int i = 0; i < args.size(); i++) {
method.dup();
method.load(i);
loadExpression(args.get(i), TypeBounds.OBJECT);
method.arraystore();
}
return method;
}
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);
}
void loadConstant(final Object object) {
loadConstant(object, unit, method);
}
private void loadConstant(final Object object, final CompileUnit compileUnit, final MethodEmitter methodEmitter) {
final String unitClassName = compileUnit.getUnitClassName();
final ClassEmitter classEmitter = compileUnit.getClassEmitter();
final int index = compiler.getConstantData().add(object);
final Class<?> cls = object.getClass();
if (cls == PropertyMap.class) {
methodEmitter.load(index);
methodEmitter.invokestatic(unitClassName, GET_MAP.symbolName(), methodDescriptor(PropertyMap.class, int.class));
classEmitter.needGetConstantMethod(PropertyMap.class);
} else if (cls.isArray()) {
methodEmitter.load(index);
final String methodName = ClassEmitter.getArrayMethodName(cls);
methodEmitter.invokestatic(unitClassName, methodName, methodDescriptor(cls, int.class));
classEmitter.needGetConstantMethod(cls);
} else {
methodEmitter.loadConstants().load(index).arrayload();
if (object instanceof ArrayData) {
methodEmitter.checkcast(ArrayData.class);
methodEmitter.invoke(virtualCallNoLookup(ArrayData.class, "copy", ArrayData.class));
} else if (cls != Object.class) {
methodEmitter.checkcast(cls);
}
}
}
private void loadConstantsAndIndex(final Object object, final MethodEmitter methodEmitter) {
methodEmitter.loadConstants().load(compiler.getConstantData().add(object));
}
private void loadLiteral(final LiteralNode<?> node, final TypeBounds resultBounds) {
final Object value = node.getValue();
if (value == null) {
method.loadNull();
} else if (value instanceof Undefined) {
method.loadUndefined(resultBounds.within(Type.OBJECT));
} else if (value instanceof String) {
final String string = (String)value;
if (string.length() > MethodEmitter.LARGE_STRING_THRESHOLD / 3) {
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) {
if(!resultBounds.canBeNarrowerThan(Type.OBJECT)) {
method.load((Integer)value);
method.convert(Type.OBJECT);
} else if(!resultBounds.canBeNarrowerThan(Type.NUMBER)) {
method.load(((Integer)value).doubleValue());
} else {
method.load((Integer)value);
}
} else if (value instanceof Double) {
if(!resultBounds.canBeNarrowerThan(Type.OBJECT)) {
method.load((Double)value);
method.convert(Type.OBJECT);
} else {
method.load((Double)value);
}
} else if (node instanceof ArrayLiteralNode) {
final ArrayLiteralNode arrayLiteral = (ArrayLiteralNode)node;
final ArrayType atype = arrayLiteral.getArrayType();
loadArray(arrayLiteral, atype);
globalAllocateArray(atype);
} else {
throw new UnsupportedOperationException("Unknown literal for " + node.getClass() + " " + value.getClass() + " " + value);
}
}
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);
}
final String regexName = lc.getCurrentFunction().uniqueName(REGEX_PREFIX.symbolName());
final ClassEmitter classEmitter = unit.getClassEmitter();
classEmitter.field(EnumSet.of(PRIVATE, STATIC), regexName, Object.class);
regexFieldCount++;
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;
}
private static boolean propertyValueContains(final Expression value, final int pp) {
return new Supplier<Boolean>() {
boolean contains;
@Override
public Boolean get() {
value.accept(new SimpleNodeVisitor() {
@Override
public boolean enterFunctionNode(final FunctionNode functionNode) {
return false;
}
@Override
public boolean enterDefault(final Node node) {
if (contains) {
return false;
}
if (node instanceof Optimistic && ((Optimistic)node).getProgramPoint() == pp) {
contains = true;
return false;
}
return true;
}
});
return contains;
}
}.get();
}
private void loadObjectNode(final ObjectNode objectNode) {
final List<PropertyNode> elements = objectNode.getElements();
final List<MapTuple<Expression>> tuples = new ArrayList<>();
final List<PropertyNode> specialProperties = new ArrayList<>();
final int ccp = getCurrentContinuationEntryPoint();
final List<Splittable.SplitRange> ranges = objectNode.getSplitRanges();
Expression protoNode = null;
boolean restOfProperty = false;
for (final PropertyNode propertyNode : elements) {
final Expression value = propertyNode.getValue();
final String key = propertyNode.getKeyName();
final boolean isComputedOrAccessor = propertyNode.isComputed() || value == null;
final Symbol symbol = isComputedOrAccessor ? null : new Symbol(key, 0);
if (isComputedOrAccessor) {
specialProperties.add(propertyNode);
} else if (propertyNode.getKey() instanceof IdentNode &&
key.equals(ScriptObject.PROTO_PROPERTY_NAME)) {
protoNode = value;
continue;
}
restOfProperty |=
value != null &&
isValid(ccp) &&
propertyValueContains(value, ccp);
final Class<?> valueType = (!useDualFields() || isComputedOrAccessor || value.getType().isBoolean()) ? Object.class : value.getType().getTypeClass();
tuples.add(new MapTuple<Expression>(key, symbol, Type.typeFor(valueType), value) {
@Override
public Class<?> getValueType() {
return type.getTypeClass();
}
});
}
final ObjectCreator<?> oc;
if (elements.size() > OBJECT_SPILL_THRESHOLD) {
oc = new SpillObjectCreator(this, tuples);
} else {
oc = new FieldObjectCreator<Expression>(this, tuples) {
@Override
protected void loadValue(final Expression node, final Type type) {
loadExpressionAsType(node, Type.generic(type));
}};
}
if (ranges != null) {
oc.createObject(method);
loadSplitLiteral(oc, ranges, Type.typeFor(oc.getAllocatorClass()));
} else {
oc.makeObject(method);
}
if (restOfProperty) {
final ContinuationInfo ci = getContinuationInfo();
ci.setObjectLiteralMap(method.getStackSize(), oc.getMap());
}
method.dup();
if (protoNode != null) {
loadExpressionAsObject(protoNode);
method.convert(Type.OBJECT);
method.invoke(ScriptObject.SET_PROTO_FROM_LITERAL);
} else {
method.invoke(ScriptObject.SET_GLOBAL_OBJECT_PROTO);
}
for (final PropertyNode propertyNode : specialProperties) {
method.dup();
if (propertyNode.isComputed()) {
assert propertyNode.getKeyName() == null;
loadExpressionAsObject(propertyNode.getKey());
} else {
method.loadKey(propertyNode.getKey());
}
if (propertyNode.getValue() != null) {
loadExpressionAsObject(propertyNode.getValue());
method.load(0);
method.invoke(ScriptObject.GENERIC_SET);
} else {
final FunctionNode getter = propertyNode.getGetter();
final FunctionNode setter = propertyNode.getSetter();
assert getter != null || setter != null;
if (getter == null) {
method.loadNull();
} else {
getter.accept(this);
}
if (setter == null) {
method.loadNull();
} else {
setter.accept(this);
}
method.invoke(ScriptObject.SET_USER_ACCESSORS);
}
}
}
@Override
public boolean enterReturnNode(final ReturnNode returnNode) {
if(!method.isReachable()) {
return false;
}
enterStatement(returnNode);
final Type returnType = lc.getCurrentFunction().getReturnType();
final Expression expression = returnNode.getExpression();
if (expression != null) {
loadExpressionUnbounded(expression);
} else {
method.loadUndefined(returnType);
}
method._return(returnType);
return false;
}
private boolean undefinedCheck(final RuntimeNode runtimeNode, final List<Expression> args) {
final Request request = runtimeNode.getRequest();
if (!Request.isUndefinedCheck(request)) {
return false;
}
final Expression lhs = args.get(0);
final Expression rhs = args.get(1);
final Symbol lhsSymbol = lhs instanceof IdentNode ? ((IdentNode)lhs).getSymbol() : null;
final Symbol rhsSymbol = rhs instanceof IdentNode ? ((IdentNode)rhs).getSymbol() : null;
assert lhsSymbol != null || rhsSymbol != null;
final Symbol undefinedSymbol;
if (isUndefinedSymbol(lhsSymbol)) {
undefinedSymbol = lhsSymbol;
} else {
assert isUndefinedSymbol(rhsSymbol);
undefinedSymbol = rhsSymbol;
}
assert undefinedSymbol != null;
if (!undefinedSymbol.isScope()) {
return false;
}
if (lhsSymbol == undefinedSymbol && lhs.getType().isPrimitive()) {
return false;
}
if(containsOptimisticExpression(lhs)) {
return false;
}
if (!compiler.isGlobalSymbol(lc.getCurrentFunction(), "undefined")) {
return false;
}
final boolean isUndefinedCheck = request == Request.IS_UNDEFINED;
final Expression expr = undefinedSymbol == lhsSymbol ? rhs : lhs;
if (expr.getType().isPrimitive()) {
loadAndDiscard(expr);
method.load(!isUndefinedCheck);
} else {
final Label checkTrue = new Label("ud_check_true");
final Label end = new Label("end");
loadExpressionAsObject(expr);
method.loadUndefined(Type.OBJECT);
method.if_acmpeq(checkTrue);
method.load(!isUndefinedCheck);
method._goto(end);
method.label(checkTrue);
method.load(isUndefinedCheck);
method.label(end);
}
return true;
}
private static boolean isUndefinedSymbol(final Symbol symbol) {
return symbol != null && "undefined".equals(symbol.getName());
}
private static boolean isNullLiteral(final Node node) {
return node instanceof LiteralNode<?> && ((LiteralNode<?>) node).isNull();
}
private boolean nullCheck(final RuntimeNode runtimeNode, final List<Expression> args) {
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;
}
if (!isNullLiteral(rhs)) {
return false;
}
if (!lhs.getType().isObject()) {
return false;
}
if(containsOptimisticExpression(lhs)) {
return false;
}
final Label trueLabel = new Label("trueLabel");
final Label falseLabel = new Label("falseLabel");
final Label endLabel = new Label("end");
loadExpressionUnbounded(lhs);
final Label popLabel;
if (!Request.isStrict(request)) {
method.dup();
popLabel = new Label("pop");
} else {
popLabel = null;
}
if (Request.isEQ(request)) {
method.ifnull(!Request.isStrict(request) ? popLabel : trueLabel);
if (!Request.isStrict(request)) {
method.loadUndefined(Type.OBJECT);
method.if_acmpeq(trueLabel);
}
method.label(falseLabel);
method.load(false);
method._goto(endLabel);
if (!Request.isStrict(request)) {
method.label(popLabel);
method.pop();
}
method.label(trueLabel);
method.load(true);
method.label(endLabel);
} else if (Request.isNE(request)) {
method.ifnull(!Request.isStrict(request) ? popLabel : falseLabel);
if (!Request.isStrict(request)) {
method.loadUndefined(Type.OBJECT);
method.if_acmpeq(falseLabel);
}
method.label(trueLabel);
method.load(true);
method._goto(endLabel);
if (!Request.isStrict(request)) {
method.label(popLabel);
method.pop();
}
method.label(falseLabel);
method.load(false);
method.label(endLabel);
}
assert runtimeNode.getType().isBoolean();
method.convert(runtimeNode.getType());
return true;
}
private boolean containsOptimisticExpression(final Expression rootExpr) {
if(!useOptimisticTypes()) {
return false;
}
return new Supplier<Boolean>() {
boolean contains;
@Override
public Boolean get() {
rootExpr.accept(new SimpleNodeVisitor() {
@Override
public boolean enterFunctionNode(final FunctionNode functionNode) {
return false;
}
@Override
public boolean enterDefault(final Node node) {
if(!contains && node instanceof Optimistic) {
final int pp = ((Optimistic)node).getProgramPoint();
contains = isValid(pp);
}
return !contains;
}
});
return contains;
}
}.get();
}
private void loadRuntimeNode(final RuntimeNode runtimeNode) {
final List<Expression> args = new ArrayList<>(runtimeNode.getArgs());
if (nullCheck(runtimeNode, args)) {
return;
} else if(undefinedCheck(runtimeNode, args)) {
return;
}
final RuntimeNode newRuntimeNode;
final Request request = runtimeNode.getRequest();
if (Request.isUndefinedCheck(request)) {
newRuntimeNode = runtimeNode.setRequest(request == Request.IS_UNDEFINED ? Request.EQ_STRICT : Request.NE_STRICT);
} else {
newRuntimeNode = runtimeNode;
}
for (final Expression arg : args) {
loadExpression(arg, TypeBounds.OBJECT);
}
method.invokestatic(
CompilerConstants.className(ScriptRuntime.class),
newRuntimeNode.getRequest().toString(),
new FunctionSignature(
false,
false,
newRuntimeNode.getType(),
args.size()).toString());
method.convert(newRuntimeNode.getType());
}
private void defineCommonSplitMethodParameters() {
defineSplitMethodParameter(0, CALLEE);
defineSplitMethodParameter(1, THIS);
defineSplitMethodParameter(2, SCOPE);
}
private void defineSplitMethodParameter(final int slot, final CompilerConstants cc) {
defineSplitMethodParameter(slot, Type.typeFor(cc.type()));
}
private void defineSplitMethodParameter(final int slot, final Type type) {
method.defineBlockLocalVariable(slot, slot + type.getSlots());
method.onLocalStore(type, slot);
}
private void loadSplitLiteral(final SplitLiteralCreator creator, final List<Splittable.SplitRange> ranges, final Type literalType) {
assert ranges != null;
final MethodEmitter savedMethod = method;
final FunctionNode currentFunction = lc.getCurrentFunction();
for (final Splittable.SplitRange splitRange : ranges) {
unit = lc.pushCompileUnit(splitRange.getCompileUnit());
assert unit != null;
final String className = unit.getUnitClassName();
final String name = currentFunction.uniqueName(SPLIT_PREFIX.symbolName());
final Class<?> clazz = literalType.getTypeClass();
final String signature = methodDescriptor(clazz, ScriptFunction.class, Object.class, ScriptObject.class, clazz);
pushMethodEmitter(unit.getClassEmitter().method(EnumSet.of(Flag.PUBLIC, Flag.STATIC), name, signature));
method.setFunctionNode(currentFunction);
method.begin();
defineCommonSplitMethodParameters();
defineSplitMethodParameter(CompilerConstants.SPLIT_ARRAY_ARG.slot(), literalType);
final int literalSlot = fixScopeSlot(currentFunction, 3);
lc.enterSplitLiteral();
creator.populateRange(method, literalType, literalSlot, splitRange.getLow(), splitRange.getHigh());
method._return();
lc.exitSplitLiteral();
method.end();
lc.releaseSlots();
popMethodEmitter();
assert method == savedMethod;
method.loadCompilerConstant(CALLEE).swap();
method.loadCompilerConstant(THIS).swap();
method.loadCompilerConstant(SCOPE).swap();
method.invokestatic(className, name, signature);
unit = lc.popCompileUnit(unit);
}
}
private int fixScopeSlot(final FunctionNode functionNode, final int extraSlot) {
final int actualScopeSlot = functionNode.compilerConstant(SCOPE).getSlot(SCOPE_TYPE);
final int defaultScopeSlot = SCOPE.slot();
int newExtraSlot = extraSlot;
if (actualScopeSlot != defaultScopeSlot) {
if (actualScopeSlot == extraSlot) {
newExtraSlot = extraSlot + 1;
method.defineBlockLocalVariable(newExtraSlot, newExtraSlot + 1);
method.load(Type.OBJECT, extraSlot);
method.storeHidden(Type.OBJECT, newExtraSlot);
} else {
method.defineBlockLocalVariable(actualScopeSlot, actualScopeSlot + 1);
}
method.load(SCOPE_TYPE, defaultScopeSlot);
method.storeCompilerConstant(SCOPE);
}
return newExtraSlot;
}
@Override
public boolean enterSplitReturn(final SplitReturn splitReturn) {
if (method.isReachable()) {
method.loadUndefined(lc.getCurrentFunction().getReturnType())._return();
}
return false;
}
@Override
public boolean enterSetSplitState(final SetSplitState setSplitState) {
if (method.isReachable()) {
method.setSplitState(setSplitState.getState());
}
return false;
}
@Override
public boolean enterSwitchNode(final SwitchNode switchNode) {
if(!method.isReachable()) {
return false;
}
enterStatement(switchNode);
final Expression expression = switchNode.getExpression();
final List<CaseNode> cases = switchNode.getCases();
if (cases.isEmpty()) {
loadAndDiscard(expression);
return false;
}
final CaseNode defaultCase = switchNode.getDefaultCase();
final Label breakLabel = switchNode.getBreakLabel();
final int liveLocalsOnBreak = method.getUsedSlotsWithLiveTemporaries();
if (defaultCase != null && cases.size() == 1) {
assert cases.get(0) == defaultCase;
loadAndDiscard(expression);
defaultCase.getBody().accept(this);
method.breakLabel(breakLabel, liveLocalsOnBreak);
return false;
}
Label defaultLabel = defaultCase != null ? defaultCase.getEntry() : breakLabel;
final boolean hasSkipConversion = LocalVariableConversion.hasLiveConversion(switchNode);
if (switchNode.isUniqueInteger()) {
final TreeMap<Integer, Label> tree = new TreeMap<>();
for (final CaseNode caseNode : cases) {
final Node test = caseNode.getTest();
if (test != null) {
final Integer value = (Integer)((LiteralNode<?>)test).getValue();
final Label entry = caseNode.getEntry();
if (!tree.containsKey(value)) {
tree.put(value, entry);
}
}
}
final int size = tree.size();
final Integer[] values = tree.keySet().toArray(new Integer[0]);
final Label[] labels = tree.values().toArray(new Label[0]);
final int lo = values[0];
final int hi = values[size - 1];
final long range = (long)hi - (long)lo + 1;
int deflt = Integer.MIN_VALUE;
for (final int value : values) {
if (deflt == value) {
deflt++;
} else if (deflt < value) {
break;
}
}
loadExpressionUnbounded(expression);
final Type type = expression.getType();
if (!type.isInteger()) {
method.load(deflt);
final Class<?> exprClass = type.getTypeClass();
method.invoke(staticCallNoLookup(ScriptRuntime.class, "switchTagAsInt", int.class, exprClass.isPrimitive()? exprClass : Object.class, int.class));
}
if(hasSkipConversion) {
assert defaultLabel == breakLabel;
defaultLabel = new Label("switch_skip");
}
if (range + 1 <= (size * 2) && range <= Integer.MAX_VALUE) {
final Label[] table = new Label[(int)range];
Arrays.fill(table, defaultLabel);
for (int i = 0; i < size; i++) {
final int value = values[i];
table[value - lo] = labels[i];
}
method.tableswitch(lo, hi, defaultLabel, table);
} else {
final int[] ints = new int[size];
for (int i = 0; i < size; i++) {
ints[i] = values[i];
}
method.lookupswitch(defaultLabel, ints, labels);
}
if(hasSkipConversion) {
method.label(defaultLabel);
method.beforeJoinPoint(switchNode);
method._goto(breakLabel);
}
} else {
final Symbol tagSymbol = switchNode.getTag();
final int tagSlot = tagSymbol.getSlot(Type.OBJECT);
loadExpressionAsObject(expression);
method.store(tagSymbol, Type.OBJECT);
for (final CaseNode caseNode : cases) {
final Expression test = caseNode.getTest();
if (test != null) {
method.load(Type.OBJECT, tagSlot);
loadExpressionAsObject(test);
method.invoke(ScriptRuntime.EQ_STRICT);
method.ifne(caseNode.getEntry());
}
}
if (defaultCase != null) {
method._goto(defaultLabel);
} else {
method.beforeJoinPoint(switchNode);
method._goto(breakLabel);
}
}
assert !method.isReachable();
for (final CaseNode caseNode : cases) {
final Label fallThroughLabel;
if(caseNode.getLocalVariableConversion() != null && method.isReachable()) {
fallThroughLabel = new Label("fallthrough");
method._goto(fallThroughLabel);
} else {
fallThroughLabel = null;
}
method.label(caseNode.getEntry());
method.beforeJoinPoint(caseNode);
if(fallThroughLabel != null) {
method.label(fallThroughLabel);
}
caseNode.getBody().accept(this);
}
method.breakLabel(breakLabel, liveLocalsOnBreak);
return false;
}
@Override
public boolean enterThrowNode(final ThrowNode throwNode) {
if(!method.isReachable()) {
return false;
}
enterStatement(throwNode);
if (throwNode.isSyntheticRethrow()) {
method.beforeJoinPoint(throwNode);
final IdentNode exceptionExpr = (IdentNode)throwNode.getExpression();
final Symbol exceptionSymbol = exceptionExpr.getSymbol();
method.load(exceptionSymbol, EXCEPTION_TYPE);
method.checkcast(EXCEPTION_TYPE.getTypeClass());
method.athrow();
return false;
}
final Source source = getCurrentSource();
final Expression expression = throwNode.getExpression();
final int position = throwNode.position();
final int line = throwNode.getLineNumber();
final int column = source.getColumn(position);
loadExpressionAsObject(expression);
method.load(source.getName());
method.load(line);
method.load(column);
method.invoke(ECMAException.CREATE);
method.beforeJoinPoint(throwNode);
method.athrow();
return false;
}
private Source getCurrentSource() {
return lc.getCurrentFunction().getSource();
}
@Override
public boolean enterTryNode(final TryNode tryNode) {
if(!method.isReachable()) {
return false;
}
enterStatement(tryNode);
final Block body = tryNode.getBody();
final List<Block> catchBlocks = tryNode.getCatchBlocks();
final Symbol vmException = tryNode.getException();
final Label entry = new Label("try");
final Label recovery = new Label("catch");
final Label exit = new Label("end_try");
final Label skip = new Label("skip");
method.canThrow(recovery);
method.beforeTry(tryNode, recovery);
method.label(entry);
catchLabels.push(recovery);
try {
body.accept(this);
} finally {
assert catchLabels.peek() == recovery;
catchLabels.pop();
}
method.label(exit);
final boolean bodyCanThrow = exit.isAfter(entry);
if(!bodyCanThrow) {
return false;
}
method._try(entry, exit, recovery, Throwable.class);
if (method.isReachable()) {
method._goto(skip);
}
for (final Block inlinedFinally : tryNode.getInlinedFinallies()) {
TryNode.getLabelledInlinedFinallyBlock(inlinedFinally).accept(this);
assert !method.isReachable();
}
method._catch(recovery);
method.store(vmException, EXCEPTION_TYPE);
final int catchBlockCount = catchBlocks.size();
final Label afterCatch = new Label("after_catch");
for (int i = 0; i < catchBlockCount; i++) {
assert method.isReachable();
final Block catchBlock = catchBlocks.get(i);
lc.push(catchBlock);
enterBlock(catchBlock);
final CatchNode catchNode = (CatchNode)catchBlocks.get(i).getStatements().get(0);
final IdentNode exception = catchNode.getExceptionIdentifier();
final Expression exceptionCondition = catchNode.getExceptionCondition();
final Block catchBody = catchNode.getBody();
new Store<IdentNode>(exception) {
@Override
protected void storeNonDiscard() {
}
@Override
protected void evaluate() {
if (catchNode.isSyntheticRethrow()) {
method.load(vmException, EXCEPTION_TYPE);
return;
}
final Label notEcmaException = new Label("no_ecma_exception");
method.load(vmException, EXCEPTION_TYPE).dup()._instanceof(ECMAException.class).ifeq(notEcmaException);
method.checkcast(ECMAException.class);
method.getField(ECMAException.THROWN);
method.label(notEcmaException);
}
}.store();
final boolean isConditionalCatch = exceptionCondition != null;
final Label nextCatch;
if (isConditionalCatch) {
loadExpressionAsBoolean(exceptionCondition);
nextCatch = new Label("next_catch");
nextCatch.markAsBreakTarget();
method.ifeq(nextCatch);
} else {
nextCatch = null;
}
catchBody.accept(this);
leaveBlock(catchBlock);
lc.pop(catchBlock);
if(nextCatch != null) {
if(method.isReachable()) {
method._goto(afterCatch);
}
method.breakLabel(nextCatch, lc.getUsedSlotCount());
}
}
method.label(afterCatch);
if(method.isReachable()) {
method.markDeadLocalVariable(vmException);
}
method.label(skip);
assert tryNode.getFinallyBody() == null;
return false;
}
@Override
public boolean enterVarNode(final VarNode varNode) {
if(!method.isReachable()) {
return false;
}
final Expression init = varNode.getInit();
final IdentNode identNode = varNode.getName();
final Symbol identSymbol = identNode.getSymbol();
assert identSymbol != null : "variable node " + varNode + " requires a name with a symbol";
final boolean needsScope = identSymbol.isScope();
if (init == null) {
if (needsScope && varNode.isLet()) {
method.loadCompilerConstant(SCOPE);
method.loadUndefined(Type.OBJECT);
final int flags = getScopeCallSiteFlags(identSymbol) | CALLSITE_DECLARE;
assert isFastScope(identSymbol);
storeFastScopeVar(identSymbol, flags);
}
return false;
}
enterStatement(varNode);
assert method != null;
if (needsScope) {
method.loadCompilerConstant(SCOPE);
loadExpressionUnbounded(init);
final int flags = getScopeCallSiteFlags(identSymbol) | (varNode.isBlockScoped() ? CALLSITE_DECLARE : 0);
if (isFastScope(identSymbol)) {
storeFastScopeVar(identSymbol, flags);
} else {
method.dynamicSet(identNode.getName(), flags, false);
}
} else {
final Type identType = identNode.getType();
if(identType == Type.UNDEFINED) {
assert init.getType() == Type.UNDEFINED || identNode.getSymbol().slotCount() == 0;
loadAndDiscard(init);
return false;
}
loadExpressionAsType(init, identType);
storeIdentWithCatchConversion(identNode, identType);
}
return false;
}
private void storeIdentWithCatchConversion(final IdentNode identNode, final Type type) {
final LocalVariableConversion conversion = identNode.getLocalVariableConversion();
final Symbol symbol = identNode.getSymbol();
if(conversion != null && conversion.isLive()) {
assert symbol == conversion.getSymbol();
assert symbol.isBytecodeLocal();
assert conversion.getNext() == null;
assert conversion.getFrom() == type;
final Label catchLabel = catchLabels.peek();
assert catchLabel != METHOD_BOUNDARY;
assert catchLabel.isReachable();
final Type joinType = conversion.getTo();
final Label.Stack catchStack = catchLabel.getStack();
final int joinSlot = symbol.getSlot(joinType);
if(catchStack.getUsedSlotsWithLiveTemporaries() > joinSlot) {
method.dup();
method.convert(joinType);
method.store(symbol, joinType);
catchLabel.getStack().onLocalStore(joinType, joinSlot, true);
method.canThrow(catchLabel);
method.store(symbol, type, false);
return;
}
}
method.store(symbol, type, true);
}
@Override
public boolean enterWhileNode(final WhileNode whileNode) {
if(!method.isReachable()) {
return false;
}
if(whileNode.isDoWhile()) {
enterDoWhile(whileNode);
} else {
enterStatement(whileNode);
enterForOrWhile(whileNode, null);
}
return false;
}
private void enterForOrWhile(final LoopNode loopNode, final JoinPredecessorExpression modify) {
final int liveLocalsOnBreak = method.getUsedSlotsWithLiveTemporaries();
final JoinPredecessorExpression test = loopNode.getTest();
if(Expression.isAlwaysFalse(test)) {
loadAndDiscard(test);
return;
}
method.beforeJoinPoint(loopNode);
final Label continueLabel = loopNode.getContinueLabel();
final Label repeatLabel = modify != null ? new Label("for_repeat") : continueLabel;
method.label(repeatLabel);
final int liveLocalsOnContinue = method.getUsedSlotsWithLiveTemporaries();
final Block body = loopNode.getBody();
final Label breakLabel = loopNode.getBreakLabel();
final boolean testHasLiveConversion = test != null && LocalVariableConversion.hasLiveConversion(test);
if(Expression.isAlwaysTrue(test)) {
if(test != null) {
loadAndDiscard(test);
if(testHasLiveConversion) {
method.beforeJoinPoint(test);
}
}
} else if (test != null) {
if (testHasLiveConversion) {
emitBranch(test.getExpression(), body.getEntryLabel(), true);
method.beforeJoinPoint(test);
method._goto(breakLabel);
} else {
emitBranch(test.getExpression(), breakLabel, false);
}
}
body.accept(this);
if(repeatLabel != continueLabel) {
emitContinueLabel(continueLabel, liveLocalsOnContinue);
}
if (loopNode.hasPerIterationScope() && lc.getCurrentBlock().needsScope()) {
method.loadCompilerConstant(SCOPE);
method.invoke(virtualCallNoLookup(ScriptObject.class, "copy", ScriptObject.class));
method.storeCompilerConstant(SCOPE);
}
if(method.isReachable()) {
if(modify != null) {
lineNumber(loopNode);
loadAndDiscard(modify);
method.beforeJoinPoint(modify);
}
method._goto(repeatLabel);
}
method.breakLabel(breakLabel, liveLocalsOnBreak);
}
private void emitContinueLabel(final Label continueLabel, final int liveLocals) {
final boolean reachable = method.isReachable();
method.breakLabel(continueLabel, liveLocals);
if(!reachable) {
method.undefineLocalVariables(lc.getUsedSlotCount(), false);
}
}
private void enterDoWhile(final WhileNode whileNode) {
final int liveLocalsOnContinueOrBreak = method.getUsedSlotsWithLiveTemporaries();
method.beforeJoinPoint(whileNode);
final Block body = whileNode.getBody();
body.accept(this);
emitContinueLabel(whileNode.getContinueLabel(), liveLocalsOnContinueOrBreak);
if(method.isReachable()) {
lineNumber(whileNode);
final JoinPredecessorExpression test = whileNode.getTest();
final Label bodyEntryLabel = body.getEntryLabel();
final boolean testHasLiveConversion = LocalVariableConversion.hasLiveConversion(test);
if(Expression.isAlwaysFalse(test)) {
loadAndDiscard(test);
if(testHasLiveConversion) {
method.beforeJoinPoint(test);
}
} else if(testHasLiveConversion) {
final Label beforeExit = new Label("do_while_preexit");
emitBranch(test.getExpression(), beforeExit, false);
method.beforeJoinPoint(test);
method._goto(bodyEntryLabel);
method.label(beforeExit);
method.beforeJoinPoint(test);
} else {
emitBranch(test.getExpression(), bodyEntryLabel, true);
}
}
method.breakLabel(whileNode.getBreakLabel(), liveLocalsOnContinueOrBreak);
}
@Override
public boolean enterWithNode(final WithNode withNode) {
if(!method.isReachable()) {
return false;
}
enterStatement(withNode);
final Expression expression = withNode.getExpression();
final Block body = withNode.getBody();
final boolean hasScope = method.hasScope();
if (hasScope) {
method.loadCompilerConstant(SCOPE);
}
loadExpressionAsObject(expression);
final Label tryLabel;
if (hasScope) {
method.invoke(ScriptRuntime.OPEN_WITH);
method.storeCompilerConstant(SCOPE);
tryLabel = new Label("with_try");
method.label(tryLabel);
} else {
globalCheckObjectCoercible();
tryLabel = null;
}
body.accept(this);
if (hasScope) {
final Label endLabel = new Label("with_end");
final Label catchLabel = new Label("with_catch");
final Label exitLabel = new Label("with_exit");
method.label(endLabel);
final boolean bodyCanThrow = endLabel.isAfter(tryLabel);
if(bodyCanThrow) {
method._try(tryLabel, endLabel, catchLabel);
}
final boolean reachable = method.isReachable();
if(reachable) {
popScope();
if(bodyCanThrow) {
method._goto(exitLabel);
}
}
if(bodyCanThrow) {
method._catch(catchLabel);
popScopeException();
method.athrow();
if(reachable) {
method.label(exitLabel);
}
}
}
return false;
}
private void loadADD(final UnaryNode unaryNode, final TypeBounds resultBounds) {
loadExpression(unaryNode.getExpression(), resultBounds.booleanToInt().notWiderThan(Type.NUMBER));
if(method.peekType() == Type.BOOLEAN) {
method.convert(Type.INT);
}
}
private void loadBIT_NOT(final UnaryNode unaryNode) {
loadExpression(unaryNode.getExpression(), TypeBounds.INT).load(-1).xor();
}
private void loadDECINC(final UnaryNode unaryNode) {
final Expression operand = unaryNode.getExpression();
final Type type = unaryNode.getType();
final TypeBounds typeBounds = new TypeBounds(type, Type.NUMBER);
final TokenType tokenType = unaryNode.tokenType();
final boolean isPostfix = tokenType == TokenType.DECPOSTFIX || tokenType == TokenType.INCPOSTFIX;
final boolean isIncrement = tokenType == TokenType.INCPREFIX || tokenType == TokenType.INCPOSTFIX;
assert !type.isObject();
new SelfModifyingStore<UnaryNode>(unaryNode, operand) {
private void loadRhs() {
loadExpression(operand, typeBounds, true);
}
@Override
protected void evaluate() {
if(isPostfix) {
loadRhs();
} else {
new OptimisticOperation(unaryNode, typeBounds) {
@Override
void loadStack() {
loadRhs();
loadMinusOne();
}
@Override
void consumeStack() {
doDecInc(getProgramPoint());
}
}.emit(getOptimisticIgnoreCountForSelfModifyingExpression(operand));
}
}
@Override
protected void storeNonDiscard() {
super.storeNonDiscard();
if (isPostfix) {
new OptimisticOperation(unaryNode, typeBounds) {
@Override
void loadStack() {
loadMinusOne();
}
@Override
void consumeStack() {
doDecInc(getProgramPoint());
}
}.emit(1);
}
}
private void loadMinusOne() {
if (type.isInteger()) {
method.load(isIncrement ? 1 : -1);
} else {
method.load(isIncrement ? 1.0 : -1.0);
}
}
private void doDecInc(final int programPoint) {
method.add(programPoint);
}
}.store();
}
private static int getOptimisticIgnoreCountForSelfModifyingExpression(final Expression target) {
return target instanceof AccessNode ? 1 : target instanceof IndexNode ? 2 : 0;
}
private void loadAndDiscard(final Expression expr) {
if(expr instanceof PrimitiveLiteralNode | isLocalVariable(expr)) {
assert !lc.isCurrentDiscard(expr);
return;
}
lc.pushDiscard(expr);
loadExpression(expr, TypeBounds.UNBOUNDED);
if (lc.popDiscardIfCurrent(expr)) {
assert !expr.isAssignment();
method.pop();
}
}
private void loadMaybeDiscard(final Expression parent, final Expression expr, final TypeBounds resultBounds) {
loadMaybeDiscard(lc.popDiscardIfCurrent(parent), expr, resultBounds);
}
private void loadMaybeDiscard(final boolean discard, final Expression expr, final TypeBounds resultBounds) {
if (discard) {
loadAndDiscard(expr);
} else {
loadExpression(expr, resultBounds);
}
}
private void loadNEW(final UnaryNode unaryNode) {
final CallNode callNode = (CallNode)unaryNode.getExpression();
final List<Expression> args = callNode.getArgs();
final Expression func = callNode.getFunction();
loadExpressionAsObject(func);
method.dynamicNew(1 + loadArgs(args), getCallSiteFlags(), func.toString(false));
}
private void loadNOT(final UnaryNode unaryNode) {
final Expression expr = unaryNode.getExpression();
if(expr instanceof UnaryNode && expr.isTokenType(TokenType.NOT)) {
loadExpressionAsBoolean(((UnaryNode)expr).getExpression());
} else {
final Label trueLabel = new Label("true");
final Label afterLabel = new Label("after");
emitBranch(expr, trueLabel, true);
method.load(true);
method._goto(afterLabel);
method.label(trueLabel);
method.load(false);
method.label(afterLabel);
}
}
private void loadSUB(final UnaryNode unaryNode, final TypeBounds resultBounds) {
final Type type = unaryNode.getType();
assert type.isNumeric();
final TypeBounds numericBounds = resultBounds.booleanToInt();
new OptimisticOperation(unaryNode, numericBounds) {
@Override
void loadStack() {
final Expression expr = unaryNode.getExpression();
loadExpression(expr, numericBounds.notWiderThan(Type.NUMBER));
}
@Override
void consumeStack() {
if(type.isNumber()) {
method.convert(type);
}
method.neg(getProgramPoint());
}
}.emit();
}
public void loadVOID(final UnaryNode unaryNode, final TypeBounds resultBounds) {
loadAndDiscard(unaryNode.getExpression());
if (!lc.popDiscardIfCurrent(unaryNode)) {
method.loadUndefined(resultBounds.widest);
}
}
public void loadDELETE(final UnaryNode unaryNode) {
final Expression expression = unaryNode.getExpression();
if (expression instanceof IdentNode) {
final IdentNode ident = (IdentNode)expression;
final Symbol symbol = ident.getSymbol();
final String name = ident.getName();
if (symbol.isThis()) {
if (!lc.popDiscardIfCurrent(unaryNode)) {
method.load(true);
}
} else if (lc.getCurrentFunction().isStrict()) {
method.load(name);
method.invoke(ScriptRuntime.STRICT_FAIL_DELETE);
} else if (!symbol.isScope() && (symbol.isParam() || (symbol.isVar() && !symbol.isProgramLevel()))) {
if (!lc.popDiscardIfCurrent(unaryNode)) {
method.load(false);
}
} else {
method.loadCompilerConstant(SCOPE);
method.load(name);
if ((symbol.isGlobal() && !symbol.isFunctionDeclaration()) || symbol.isProgramLevel()) {
method.invoke(ScriptRuntime.SLOW_DELETE);
} else {
method.load(false);
method.invoke(ScriptObject.DELETE);
}
}
} else if (expression instanceof BaseNode) {
loadExpressionAsObject(((BaseNode)expression).getBase());
if (expression instanceof AccessNode) {
final AccessNode accessNode = (AccessNode) expression;
method.dynamicRemove(accessNode.getProperty(), getCallSiteFlags(), accessNode.isIndex());
} else if (expression instanceof IndexNode) {
loadExpressionAsObject(((IndexNode) expression).getIndex());
method.dynamicRemoveIndex(getCallSiteFlags());
} else {
throw new AssertionError(expression.getClass().getName());
}
} else {
throw new AssertionError(expression.getClass().getName());
}
}
public void loadADD(final BinaryNode binaryNode, final TypeBounds resultBounds) {
new OptimisticOperation(binaryNode, resultBounds) {
@Override
void loadStack() {
final TypeBounds operandBounds;
final boolean isOptimistic = isValid(getProgramPoint());
boolean forceConversionSeparation = false;
if(isOptimistic) {
operandBounds = new TypeBounds(binaryNode.getType(), Type.OBJECT);
} else {
final Type widestOperationType = binaryNode.getWidestOperationType();
operandBounds = new TypeBounds(Type.narrowest(binaryNode.getWidestOperandType(), resultBounds.widest), widestOperationType);
forceConversionSeparation = widestOperationType.narrowerThan(resultBounds.widest);
}
loadBinaryOperands(binaryNode.lhs(), binaryNode.rhs(), operandBounds, false, forceConversionSeparation);
}
@Override
void consumeStack() {
method.add(getProgramPoint());
}
}.emit();
}
private void loadAND_OR(final BinaryNode binaryNode, final TypeBounds resultBounds, final boolean isAnd) {
final Type narrowestOperandType = Type.widestReturnType(binaryNode.lhs().getType(), binaryNode.rhs().getType());
final boolean isCurrentDiscard = lc.popDiscardIfCurrent(binaryNode);
final Label skip = new Label("skip");
if(narrowestOperandType == Type.BOOLEAN) {
final Label onTrue = new Label("andor_true");
emitBranch(binaryNode, onTrue, true);
if (isCurrentDiscard) {
method.label(onTrue);
} else {
method.load(false);
method._goto(skip);
method.label(onTrue);
method.load(true);
method.label(skip);
}
return;
}
final TypeBounds outBounds = resultBounds.notNarrowerThan(narrowestOperandType);
final JoinPredecessorExpression lhs = (JoinPredecessorExpression)binaryNode.lhs();
final boolean lhsConvert = LocalVariableConversion.hasLiveConversion(lhs);
final Label evalRhs = lhsConvert ? new Label("eval_rhs") : null;
loadExpression(lhs, outBounds);
if (!isCurrentDiscard) {
method.dup();
}
method.convert(Type.BOOLEAN);
if (isAnd) {
if(lhsConvert) {
method.ifne(evalRhs);
} else {
method.ifeq(skip);
}
} else if(lhsConvert) {
method.ifeq(evalRhs);
} else {
method.ifne(skip);
}
if(lhsConvert) {
method.beforeJoinPoint(lhs);
method._goto(skip);
method.label(evalRhs);
}
if (!isCurrentDiscard) {
method.pop();
}
final JoinPredecessorExpression rhs = (JoinPredecessorExpression)binaryNode.rhs();
loadMaybeDiscard(isCurrentDiscard, rhs, outBounds);
method.beforeJoinPoint(rhs);
method.label(skip);
}
private static boolean isLocalVariable(final Expression lhs) {
return lhs instanceof IdentNode && isLocalVariable((IdentNode)lhs);
}
private static boolean isLocalVariable(final IdentNode lhs) {
return lhs.getSymbol().isBytecodeLocal();
}
private void loadASSIGN(final BinaryNode binaryNode) {
final Expression lhs = binaryNode.lhs();
final Expression rhs = binaryNode.rhs();
final Type rhsType = rhs.getType();
if(lhs instanceof IdentNode) {
final Symbol symbol = ((IdentNode)lhs).getSymbol();
if(!symbol.isScope() && !symbol.hasSlotFor(rhsType) && lc.popDiscardIfCurrent(binaryNode)) {
loadAndDiscard(rhs);
method.markDeadLocalVariable(symbol);
return;
}
}
new Store<BinaryNode>(binaryNode, lhs) {
@Override
protected void evaluate() {
loadExpressionAsType(rhs, rhsType);
}
}.store();
}
private abstract class BinaryOptimisticSelfAssignment extends SelfModifyingStore<BinaryNode> {
BinaryOptimisticSelfAssignment(final BinaryNode node) {
super(node, node.lhs());
}
protected abstract void op(OptimisticOperation oo);
@Override
protected void evaluate() {
final Expression lhs = assignNode.lhs();
final Expression rhs = assignNode.rhs();
final Type widestOperationType = assignNode.getWidestOperationType();
final TypeBounds bounds = new TypeBounds(assignNode.getType(), widestOperationType);
new OptimisticOperation(assignNode, bounds) {
@Override
void loadStack() {
final boolean forceConversionSeparation;
if (isValid(getProgramPoint()) || widestOperationType == Type.NUMBER) {
forceConversionSeparation = false;
} else {
final Type operandType = Type.widest(booleanToInt(objectToNumber(lhs.getType())), booleanToInt(objectToNumber(rhs.getType())));
forceConversionSeparation = operandType.narrowerThan(widestOperationType);
}
loadBinaryOperands(lhs, rhs, bounds, true, forceConversionSeparation);
}
@Override
void consumeStack() {
op(this);
}
}.emit(getOptimisticIgnoreCountForSelfModifyingExpression(lhs));
method.convert(assignNode.getType());
}
}
private abstract class BinarySelfAssignment extends SelfModifyingStore<BinaryNode> {
BinarySelfAssignment(final BinaryNode node) {
super(node, node.lhs());
}
protected abstract void op();
@Override
protected void evaluate() {
loadBinaryOperands(assignNode.lhs(), assignNode.rhs(), TypeBounds.UNBOUNDED.notWiderThan(assignNode.getWidestOperandType()), true, false);
op();
}
}
private void loadASSIGN_ADD(final BinaryNode binaryNode) {
new BinaryOptimisticSelfAssignment(binaryNode) {
@Override
protected void op(final OptimisticOperation oo) {
assert !(binaryNode.getType().isObject() && oo.isOptimistic);
method.add(oo.getProgramPoint());
}
}.store();
}
private void loadASSIGN_BIT_AND(final BinaryNode binaryNode) {
new BinarySelfAssignment(binaryNode) {
@Override
protected void op() {
method.and();
}
}.store();
}
private void loadASSIGN_BIT_OR(final BinaryNode binaryNode) {
new BinarySelfAssignment(binaryNode) {
@Override
protected void op() {
method.or();
}
}.store();
}
private void loadASSIGN_BIT_XOR(final BinaryNode binaryNode) {
new BinarySelfAssignment(binaryNode) {
@Override
protected void op() {
method.xor();
}
}.store();
}
private void loadASSIGN_DIV(final BinaryNode binaryNode) {
new BinaryOptimisticSelfAssignment(binaryNode) {
@Override
protected void op(final OptimisticOperation oo) {
method.div(oo.getProgramPoint());
}
}.store();
}
private void loadASSIGN_MOD(final BinaryNode binaryNode) {
new BinaryOptimisticSelfAssignment(binaryNode) {
@Override
protected void op(final OptimisticOperation oo) {
method.rem(oo.getProgramPoint());
}
}.store();
}
private void loadASSIGN_MUL(final BinaryNode binaryNode) {
new BinaryOptimisticSelfAssignment(binaryNode) {
@Override
protected void op(final OptimisticOperation oo) {
method.mul(oo.getProgramPoint());
}
}.store();
}
private void loadASSIGN_SAR(final BinaryNode binaryNode) {
new BinarySelfAssignment(binaryNode) {
@Override
protected void op() {
method.sar();
}
}.store();
}
private void loadASSIGN_SHL(final BinaryNode binaryNode) {
new BinarySelfAssignment(binaryNode) {
@Override
protected void op() {
method.shl();
}
}.store();
}
private void loadASSIGN_SHR(final BinaryNode binaryNode) {
new SelfModifyingStore<BinaryNode>(binaryNode, binaryNode.lhs()) {
@Override
protected void evaluate() {
new OptimisticOperation(assignNode, new TypeBounds(Type.INT, Type.NUMBER)) {
@Override
void loadStack() {
assert assignNode.getWidestOperandType() == Type.INT;
if (isRhsZero(binaryNode)) {
loadExpression(binaryNode.lhs(), TypeBounds.INT, true);
} else {
loadBinaryOperands(binaryNode.lhs(), binaryNode.rhs(), TypeBounds.INT, true, false);
method.shr();
}
}
@Override
void consumeStack() {
if (isOptimistic(binaryNode)) {
toUint32Optimistic(binaryNode.getProgramPoint());
} else {
toUint32Double();
}
}
}.emit(getOptimisticIgnoreCountForSelfModifyingExpression(binaryNode.lhs()));
method.convert(assignNode.getType());
}
}.store();
}
private void doSHR(final BinaryNode binaryNode) {
new OptimisticOperation(binaryNode, new TypeBounds(Type.INT, Type.NUMBER)) {
@Override
void loadStack() {
if (isRhsZero(binaryNode)) {
loadExpressionAsType(binaryNode.lhs(), Type.INT);
} else {
loadBinaryOperands(binaryNode);
method.shr();
}
}
@Override
void consumeStack() {
if (isOptimistic(binaryNode)) {
toUint32Optimistic(binaryNode.getProgramPoint());
} else {
toUint32Double();
}
}
}.emit();
}
private void toUint32Optimistic(final int programPoint) {
method.load(programPoint);
JSType.TO_UINT32_OPTIMISTIC.invoke(method);
}
private void toUint32Double() {
JSType.TO_UINT32_DOUBLE.invoke(method);
}
private void loadASSIGN_SUB(final BinaryNode binaryNode) {
new BinaryOptimisticSelfAssignment(binaryNode) {
@Override
protected void op(final OptimisticOperation oo) {
method.sub(oo.getProgramPoint());
}
}.store();
}
private abstract class BinaryArith {
protected abstract void op(int programPoint);
protected void evaluate(final BinaryNode node, final TypeBounds resultBounds) {
final TypeBounds numericBounds = resultBounds.booleanToInt().objectToNumber();
new OptimisticOperation(node, numericBounds) {
@Override
void loadStack() {
final TypeBounds operandBounds;
boolean forceConversionSeparation = false;
if(numericBounds.narrowest == Type.NUMBER) {
assert numericBounds.widest == Type.NUMBER;
operandBounds = numericBounds;
} else {
final boolean isOptimistic = isValid(getProgramPoint());
if(isOptimistic || node.isTokenType(TokenType.DIV) || node.isTokenType(TokenType.MOD)) {
operandBounds = new TypeBounds(node.getType(), Type.NUMBER);
} else {
operandBounds = new TypeBounds(Type.narrowest(node.getWidestOperandType(),
numericBounds.widest), Type.NUMBER);
forceConversionSeparation = true;
}
}
loadBinaryOperands(node.lhs(), node.rhs(), operandBounds, false, forceConversionSeparation);
}
@Override
void consumeStack() {
op(getProgramPoint());
}
}.emit();
}
}
private void loadBIT_AND(final BinaryNode binaryNode) {
loadBinaryOperands(binaryNode);
method.and();
}
private void loadBIT_OR(final BinaryNode binaryNode) {
if (isRhsZero(binaryNode)) {
loadExpressionAsType(binaryNode.lhs(), Type.INT);
} else {
loadBinaryOperands(binaryNode);
method.or();
}
}
private static boolean isRhsZero(final BinaryNode binaryNode) {
final Expression rhs = binaryNode.rhs();
return rhs instanceof LiteralNode && INT_ZERO.equals(((LiteralNode<?>)rhs).getValue());
}
private void loadBIT_XOR(final BinaryNode binaryNode) {
loadBinaryOperands(binaryNode);
method.xor();
}
private void loadCOMMARIGHT(final BinaryNode binaryNode, final TypeBounds resultBounds) {
loadAndDiscard(binaryNode.lhs());
loadMaybeDiscard(binaryNode, binaryNode.rhs(), resultBounds);
}
private void loadCOMMALEFT(final BinaryNode binaryNode, final TypeBounds resultBounds) {
loadMaybeDiscard(binaryNode, binaryNode.lhs(), resultBounds);
loadAndDiscard(binaryNode.rhs());
}
private void loadDIV(final BinaryNode binaryNode, final TypeBounds resultBounds) {
new BinaryArith() {
@Override
protected void op(final int programPoint) {
method.div(programPoint);
}
}.evaluate(binaryNode, resultBounds);
}
private void loadCmp(final BinaryNode binaryNode, final Condition cond) {
loadComparisonOperands(binaryNode);
final Label trueLabel = new Label("trueLabel");
final Label afterLabel = new Label("skip");
method.conditionalJump(cond, trueLabel);
method.load(Boolean.FALSE);
method._goto(afterLabel);
method.label(trueLabel);
method.load(Boolean.TRUE);
method.label(afterLabel);
}
private void loadMOD(final BinaryNode binaryNode, final TypeBounds resultBounds) {
new BinaryArith() {
@Override
protected void op(final int programPoint) {
method.rem(programPoint);
}
}.evaluate(binaryNode, resultBounds);
}
private void loadMUL(final BinaryNode binaryNode, final TypeBounds resultBounds) {
new BinaryArith() {
@Override
protected void op(final int programPoint) {
method.mul(programPoint);
}
}.evaluate(binaryNode, resultBounds);
}
private void loadSAR(final BinaryNode binaryNode) {
loadBinaryOperands(binaryNode);
method.sar();
}
private void loadSHL(final BinaryNode binaryNode) {
loadBinaryOperands(binaryNode);
method.shl();
}
private void loadSHR(final BinaryNode binaryNode) {
doSHR(binaryNode);
}
private void loadSUB(final BinaryNode binaryNode, final TypeBounds resultBounds) {
new BinaryArith() {
@Override
protected void op(final int programPoint) {
method.sub(programPoint);
}
}.evaluate(binaryNode, resultBounds);
}
@Override
public boolean enterLabelNode(final LabelNode labelNode) {
labeledBlockBreakLiveLocals.push(lc.getUsedSlotCount());
return true;
}
@Override
protected boolean enterDefault(final Node node) {
throw new AssertionError("Code generator entered node of type " + node.getClass().getName());
}
private void loadTernaryNode(final TernaryNode ternaryNode, final TypeBounds resultBounds) {
final Expression test = ternaryNode.getTest();
final JoinPredecessorExpression trueExpr = ternaryNode.getTrueExpression();
final JoinPredecessorExpression falseExpr = ternaryNode.getFalseExpression();
final Label falseLabel = new Label("ternary_false");
final Label exitLabel = new Label("ternary_exit");
final Type outNarrowest = Type.narrowest(resultBounds.widest, Type.generic(Type.widestReturnType(trueExpr.getType(), falseExpr.getType())));
final TypeBounds outBounds = resultBounds.notNarrowerThan(outNarrowest);
emitBranch(test, falseLabel, false);
final boolean isCurrentDiscard = lc.popDiscardIfCurrent(ternaryNode);
loadMaybeDiscard(isCurrentDiscard, trueExpr.getExpression(), outBounds);
assert isCurrentDiscard || Type.generic(method.peekType()) == outBounds.narrowest;
method.beforeJoinPoint(trueExpr);
method._goto(exitLabel);
method.label(falseLabel);
loadMaybeDiscard(isCurrentDiscard, falseExpr.getExpression(), outBounds);
assert isCurrentDiscard || Type.generic(method.peekType()) == outBounds.narrowest;
method.beforeJoinPoint(falseExpr);
method.label(exitLabel);
}
void generateScopeCalls() {
for (final SharedScopeCall scopeAccess : lc.getScopeCalls()) {
scopeAccess.generateScopeCall();
}
}
private void printSymbols(final Block block, final FunctionNode function, final String ident) {
if (compiler.getScriptEnvironment()._print_symbols || function.getDebugFlag(FunctionNode.DEBUG_PRINT_SYMBOLS)) {
final PrintWriter out = compiler.getScriptEnvironment().getErr();
out.println("[BLOCK in '" + ident + "']");
if (!block.printSymbols(out)) {
out.println("<no symbols>");
}
out.println();
}
}
private abstract class SelfModifyingStore<T extends Expression> extends Store<T> {
protected SelfModifyingStore(final T assignNode, final Expression target) {
super(assignNode, target);
}
@Override
protected boolean isSelfModifying() {
return true;
}
}
private abstract class Store<T extends Expression> {
protected final T assignNode;
private final Expression target;
private int depth;
private IdentNode quick;
protected Store(final T assignNode, final Expression target) {
this.assignNode = assignNode;
this.target = target;
}
protected Store(final T assignNode) {
this(assignNode, assignNode);
}
protected boolean isSelfModifying() {
return false;
}
private void prologue() {
target.accept(new SimpleNodeVisitor() {
@Override
public boolean enterIdentNode(final IdentNode node) {
if (node.getSymbol().isScope()) {
method.loadCompilerConstant(SCOPE);
depth += Type.SCOPE.getSlots();
assert depth == 1;
}
return false;
}
private void enterBaseNode() {
assert target instanceof BaseNode : "error - base node " + target + " must be instanceof BaseNode";
final BaseNode baseNode = (BaseNode)target;
final Expression base = baseNode.getBase();
loadExpressionAsObject(base);
depth += Type.OBJECT.getSlots();
assert depth == 1;
if (isSelfModifying()) {
method.dup();
}
}
@Override
public boolean enterAccessNode(final AccessNode node) {
enterBaseNode();
return false;
}
@Override
public boolean enterIndexNode(final IndexNode node) {
enterBaseNode();
final Expression index = node.getIndex();
if (!index.getType().isNumeric()) {
loadExpressionAsObject(index);
} else {
loadExpressionUnbounded(index);
}
depth += index.getType().getSlots();
if (isSelfModifying()) {
method.dup(1);
}
return false;
}
});
}
private IdentNode quickLocalVariable(final Type type) {
final String name = lc.getCurrentFunction().uniqueName(QUICK_PREFIX.symbolName());
final Symbol symbol = new Symbol(name, IS_INTERNAL | HAS_SLOT);
symbol.setHasSlotFor(type);
symbol.setFirstSlot(lc.quickSlot(type));
final IdentNode quickIdent = IdentNode.createInternalIdentifier(symbol).setType(type);
return quickIdent;
}
protected void storeNonDiscard() {
if (lc.popDiscardIfCurrent(assignNode)) {
assert assignNode.isAssignment();
return;
}
if (method.dup(depth) == null) {
method.dup();
final Type quickType = method.peekType();
this.quick = quickLocalVariable(quickType);
final Symbol quickSymbol = quick.getSymbol();
method.storeTemp(quickType, quickSymbol.getFirstSlot());
}
}
private void epilogue() {
target.accept(new SimpleNodeVisitor() {
@Override
protected boolean enterDefault(final Node node) {
throw new AssertionError("Unexpected node " + node + " in store epilogue");
}
@Override
public boolean enterIdentNode(final IdentNode node) {
final Symbol symbol = node.getSymbol();
assert symbol != null;
if (symbol.isScope()) {
final int flags = getScopeCallSiteFlags(symbol) | (node.isDeclaredHere() ? CALLSITE_DECLARE : 0);
if (isFastScope(symbol)) {
storeFastScopeVar(symbol, flags);
} else {
method.dynamicSet(node.getName(), flags, false);
}
} else {
final Type storeType = assignNode.getType();
assert storeType != Type.LONG;
if (symbol.hasSlotFor(storeType)) {
method.convert(storeType);
}
storeIdentWithCatchConversion(node, storeType);
}
return false;
}
@Override
public boolean enterAccessNode(final AccessNode node) {
method.dynamicSet(node.getProperty(), getCallSiteFlags(), node.isIndex());
return false;
}
@Override
public boolean enterIndexNode(final IndexNode node) {
method.dynamicSetIndex(getCallSiteFlags());
return false;
}
});
}
protected abstract void evaluate();
void store() {
if (target instanceof IdentNode) {
checkTemporalDeadZone((IdentNode)target);
}
prologue();
evaluate();
storeNonDiscard();
epilogue();
if (quick != null) {
method.load(quick);
}
}
}
private void newFunctionObject(final FunctionNode functionNode, final boolean addInitializer) {
assert lc.peek() == functionNode;
final RecompilableScriptFunctionData data = compiler.getScriptFunctionData(functionNode.getId());
if (functionNode.isProgram() && !compiler.isOnDemandCompilation()) {
final MethodEmitter createFunction = functionNode.getCompileUnit().getClassEmitter().method(
EnumSet.of(Flag.PUBLIC, Flag.STATIC), CREATE_PROGRAM_FUNCTION.symbolName(),
ScriptFunction.class, ScriptObject.class);
createFunction.begin();
loadConstantsAndIndex(data, createFunction);
createFunction.load(SCOPE_TYPE, 0);
createFunction.invoke(CREATE_FUNCTION_OBJECT);
createFunction._return();
createFunction.end();
}
if (addInitializer && !compiler.isOnDemandCompilation()) {
functionNode.getCompileUnit().addFunctionInitializer(data, functionNode);
}
if (lc.getOutermostFunction() == functionNode) {
return;
}
loadConstantsAndIndex(data, method);
if (functionNode.needsParentScope()) {
method.loadCompilerConstant(SCOPE);
method.invoke(CREATE_FUNCTION_OBJECT);
} else {
method.invoke(CREATE_FUNCTION_OBJECT_NO_SCOPE);
}
}
private MethodEmitter globalInstance() {
return method.invokestatic(GLOBAL_OBJECT, "instance", "()L" + GLOBAL_OBJECT + ';');
}
private MethodEmitter globalAllocateArguments() {
return method.invokestatic(GLOBAL_OBJECT, "allocateArguments", methodDescriptor(ScriptObject.class, Object[].class, Object.class, int.class));
}
private MethodEmitter globalNewRegExp() {
return method.invokestatic(GLOBAL_OBJECT, "newRegExp", methodDescriptor(Object.class, String.class, String.class));
}
private MethodEmitter globalRegExpCopy() {
return method.invokestatic(GLOBAL_OBJECT, "regExpCopy", methodDescriptor(Object.class, Object.class));
}
private MethodEmitter globalAllocateArray(final ArrayType type) {
return method.invokestatic(GLOBAL_OBJECT, "allocate", "(" + type.getDescriptor() + ")Ljdk/nashorn/internal/objects/NativeArray;");
}
private MethodEmitter globalIsEval() {
return method.invokestatic(GLOBAL_OBJECT, "isEval", methodDescriptor(boolean.class, Object.class));
}
private MethodEmitter globalReplaceLocationPropertyPlaceholder() {
return method.invokestatic(GLOBAL_OBJECT, "replaceLocationPropertyPlaceholder", methodDescriptor(Object.class, Object.class, Object.class));
}
private MethodEmitter globalCheckObjectCoercible() {
return method.invokestatic(GLOBAL_OBJECT, "checkObjectCoercible", methodDescriptor(void.class, Object.class));
}
private MethodEmitter globalDirectEval() {
return method.invokestatic(GLOBAL_OBJECT, "directEval",
methodDescriptor(Object.class, Object.class, Object.class, Object.class, Object.class, boolean.class));
}
private abstract class OptimisticOperation {
final boolean isOptimistic;
private final Expression expression;
private final Optimistic optimistic;
private final TypeBounds resultBounds;
OptimisticOperation(final Optimistic optimistic, final TypeBounds resultBounds) {
this.optimistic = optimistic;
this.expression = (Expression)optimistic;
this.resultBounds = resultBounds;
this.isOptimistic = isOptimistic(optimistic)
&& resultBounds.within(Type.generic(((Expression)optimistic).getType())).narrowerThan(resultBounds.widest);
assert !this.isOptimistic || useOptimisticTypes();
}
MethodEmitter emit() {
return emit(0);
}
MethodEmitter emit(final int ignoredArgCount) {
final int programPoint = optimistic.getProgramPoint();
final boolean optimisticOrContinuation = isOptimistic || isContinuationEntryPoint(programPoint);
final boolean currentContinuationEntryPoint = isCurrentContinuationEntryPoint(programPoint);
final int stackSizeOnEntry = method.getStackSize() - ignoredArgCount;
storeStack(ignoredArgCount, optimisticOrContinuation);
loadStack();
final int liveLocalsCount = storeStack(method.getStackSize() - stackSizeOnEntry, optimisticOrContinuation);
assert optimisticOrContinuation == (liveLocalsCount != -1);
final Label beginTry;
final Label catchLabel;
final Label afterConsumeStack = isOptimistic || currentContinuationEntryPoint ? new Label("after_consume_stack") : null;
if(isOptimistic) {
beginTry = new Label("try_optimistic");
final String catchLabelName = (afterConsumeStack == null ? "" : afterConsumeStack.toString()) + "_handler";
catchLabel = new Label(catchLabelName);
method.label(beginTry);
} else {
beginTry = catchLabel = null;
}
consumeStack();
if(isOptimistic) {
method._try(beginTry, afterConsumeStack, catchLabel, UnwarrantedOptimismException.class);
}
if(isOptimistic || currentContinuationEntryPoint) {
method.label(afterConsumeStack);
final int[] localLoads = method.getLocalLoadsOnStack(0, stackSizeOnEntry);
assert everyStackValueIsLocalLoad(localLoads) : Arrays.toString(localLoads) + ", " + stackSizeOnEntry + ", " + ignoredArgCount;
final List<Type> localTypesList = method.getLocalVariableTypes();
final int usedLocals = method.getUsedSlotsWithLiveTemporaries();
final List<Type> localTypes = method.getWidestLiveLocals(localTypesList.subList(0, usedLocals));
assert everyLocalLoadIsValid(localLoads, usedLocals) : Arrays.toString(localLoads) + " ~ " + localTypes;
if(isOptimistic) {
addUnwarrantedOptimismHandlerLabel(localTypes, catchLabel);
}
if(currentContinuationEntryPoint) {
final ContinuationInfo ci = getContinuationInfo();
assert ci != null : "no continuation info found for " + lc.getCurrentFunction();
assert !ci.hasTargetLabel();
ci.setTargetLabel(afterConsumeStack);
ci.getHandlerLabel().markAsOptimisticContinuationHandlerFor(afterConsumeStack);
ci.lvarCount = localTypes.size();
ci.setStackStoreSpec(localLoads);
ci.setStackTypes(Arrays.copyOf(method.getTypesFromStack(method.getStackSize()), stackSizeOnEntry));
assert ci.getStackStoreSpec().length == ci.getStackTypes().length;
ci.setReturnValueType(method.peekType());
ci.lineNumber = getLastLineNumber();
ci.catchLabel = catchLabels.peek();
}
}
return method;
}
private int storeStack(final int ignoreArgCount, final boolean optimisticOrContinuation) {
if(!optimisticOrContinuation) {
return -1;
}
final int stackSize = method.getStackSize();
final Type[] stackTypes = method.getTypesFromStack(stackSize);
final int[] localLoadsOnStack = method.getLocalLoadsOnStack(0, stackSize);
final int usedSlots = method.getUsedSlotsWithLiveTemporaries();
final int firstIgnored = stackSize - ignoreArgCount;
int firstNonLoad = 0;
while(firstNonLoad < firstIgnored && localLoadsOnStack[firstNonLoad] != Label.Stack.NON_LOAD) {
firstNonLoad++;
}
if(firstNonLoad >= firstIgnored) {
return usedSlots;
}
int tempSlotsNeeded = 0;
for(int i = firstNonLoad; i < stackSize; ++i) {
if(localLoadsOnStack[i] == Label.Stack.NON_LOAD) {
tempSlotsNeeded += stackTypes[i].getSlots();
}
}
int lastTempSlot = usedSlots + tempSlotsNeeded;
int ignoreSlotCount = 0;
for(int i = stackSize; i -- > firstNonLoad;) {
final int loadSlot = localLoadsOnStack[i];
if(loadSlot == Label.Stack.NON_LOAD) {
final Type type = stackTypes[i];
final int slots = type.getSlots();
lastTempSlot -= slots;
if(i >= firstIgnored) {
ignoreSlotCount += slots;
}
method.storeTemp(type, lastTempSlot);
} else {
method.pop();
}
}
assert lastTempSlot == usedSlots;
final List<Type> localTypesList = method.getLocalVariableTypes();
for(int i = firstNonLoad; i < stackSize; ++i) {
final int loadSlot = localLoadsOnStack[i];
final Type stackType = stackTypes[i];
final boolean isLoad = loadSlot != Label.Stack.NON_LOAD;
final int lvarSlot = isLoad ? loadSlot : lastTempSlot;
final Type lvarType = localTypesList.get(lvarSlot);
method.load(lvarType, lvarSlot);
if(isLoad) {
method.convert(stackType);
} else {
assert lvarType == stackType;
lastTempSlot += lvarType.getSlots();
}
}
assert lastTempSlot == usedSlots + tempSlotsNeeded;
return lastTempSlot - ignoreSlotCount;
}
private void addUnwarrantedOptimismHandlerLabel(final List<Type> localTypes, final Label label) {
final String lvarTypesDescriptor = getLvarTypesDescriptor(localTypes);
final Map<String, Collection<Label>> unwarrantedOptimismHandlers = lc.getUnwarrantedOptimismHandlers();
Collection<Label> labels = unwarrantedOptimismHandlers.get(lvarTypesDescriptor);
if(labels == null) {
labels = new LinkedList<>();
unwarrantedOptimismHandlers.put(lvarTypesDescriptor, labels);
}
method.markLabelAsOptimisticCatchHandler(label, localTypes.size());
labels.add(label);
}
abstract void loadStack();
abstract void consumeStack();
MethodEmitter dynamicGet(final String name, final int flags, final boolean isMethod, final boolean isIndex) {
if(isOptimistic) {
return method.dynamicGet(getOptimisticCoercedType(), name, getOptimisticFlags(flags), isMethod, isIndex);
}
return method.dynamicGet(resultBounds.within(expression.getType()), name, nonOptimisticFlags(flags), isMethod, isIndex);
}
MethodEmitter dynamicGetIndex(final int flags, final boolean isMethod) {
if(isOptimistic) {
return method.dynamicGetIndex(getOptimisticCoercedType(), getOptimisticFlags(flags), isMethod);
}
return method.dynamicGetIndex(resultBounds.within(expression.getType()), nonOptimisticFlags(flags), isMethod);
}
MethodEmitter dynamicCall(final int argCount, final int flags, final String msg) {
if (isOptimistic) {
return method.dynamicCall(getOptimisticCoercedType(), argCount, getOptimisticFlags(flags), msg);
}
return method.dynamicCall(resultBounds.within(expression.getType()), argCount, nonOptimisticFlags(flags), msg);
}
int getOptimisticFlags(final int flags) {
return flags | CALLSITE_OPTIMISTIC | (optimistic.getProgramPoint() << CALLSITE_PROGRAM_POINT_SHIFT);
}
int getProgramPoint() {
return isOptimistic ? optimistic.getProgramPoint() : INVALID_PROGRAM_POINT;
}
void convertOptimisticReturnValue() {
if (isOptimistic) {
final Type optimisticType = getOptimisticCoercedType();
if(!optimisticType.isObject()) {
method.load(optimistic.getProgramPoint());
if(optimisticType.isInteger()) {
method.invoke(ENSURE_INT);
} else if(optimisticType.isNumber()) {
method.invoke(ENSURE_NUMBER);
} else {
throw new AssertionError(optimisticType);
}
}
}
}
void replaceCompileTimeProperty() {
final IdentNode identNode = (IdentNode)expression;
final String name = identNode.getSymbol().getName();
if (CompilerConstants.__FILE__.name().equals(name)) {
replaceCompileTimeProperty(getCurrentSource().getName());
} else if (CompilerConstants.__DIR__.name().equals(name)) {
replaceCompileTimeProperty(getCurrentSource().getBase());
} else if (CompilerConstants.__LINE__.name().equals(name)) {
replaceCompileTimeProperty(getCurrentSource().getLine(identNode.position()));
}
}
private void replaceCompileTimeProperty(final Object propertyValue) {
assert method.peekType().isObject();
if(propertyValue instanceof String || propertyValue == null) {
method.load((String)propertyValue);
} else if(propertyValue instanceof Integer) {
method.load(((Integer)propertyValue));
method.convert(Type.OBJECT);
} else {
throw new AssertionError();
}
globalReplaceLocationPropertyPlaceholder();
convertOptimisticReturnValue();
}
Type getOptimisticCoercedType() {
final Type optimisticType = expression.getType();
assert resultBounds.widest.widerThan(optimisticType);
final Type narrowest = resultBounds.narrowest;
if(narrowest.isBoolean() || narrowest.narrowerThan(optimisticType)) {
assert !optimisticType.isObject();
return optimisticType;
}
assert !narrowest.isObject();
return narrowest;
}
}
private static boolean isOptimistic(final Optimistic optimistic) {
if(!optimistic.canBeOptimistic()) {
return false;
}
final Expression expr = (Expression)optimistic;
return expr.getType().narrowerThan(expr.getWidestOperationType());
}
private static boolean everyLocalLoadIsValid(final int[] loads, final int localCount) {
for (final int load : loads) {
if(load < 0 || load >= localCount) {
return false;
}
}
return true;
}
private static boolean everyStackValueIsLocalLoad(final int[] loads) {
for (final int load : loads) {
if(load == Label.Stack.NON_LOAD) {
return false;
}
}
return true;
}
private String getLvarTypesDescriptor(final List<Type> localVarTypes) {
final int count = localVarTypes.size();
final StringBuilder desc = new StringBuilder(count);
for(int i = 0; i < count;) {
i += appendType(desc, localVarTypes.get(i));
}
return method.markSymbolBoundariesInLvarTypesDescriptor(desc.toString());
}
private static int appendType(final StringBuilder b, final Type t) {
b.append(t.getBytecodeStackType());
return t.getSlots();
}
private static int countSymbolsInLvarTypeDescriptor(final String lvarTypeDescriptor) {
int count = 0;
for(int i = 0; i < lvarTypeDescriptor.length(); ++i) {
if(Character.isUpperCase(lvarTypeDescriptor.charAt(i))) {
++count;
}
}
return count;
}
private boolean generateUnwarrantedOptimismExceptionHandlers(final FunctionNode fn) {
if(!useOptimisticTypes()) {
return false;
}
final Map<String, Collection<Label>> unwarrantedOptimismHandlers = lc.popUnwarrantedOptimismHandlers();
if(unwarrantedOptimismHandlers.isEmpty()) {
return false;
}
method.lineNumber(0);
final List<OptimismExceptionHandlerSpec> handlerSpecs = new ArrayList<>(unwarrantedOptimismHandlers.size() * 4/3);
for(final String spec: unwarrantedOptimismHandlers.keySet()) {
handlerSpecs.add(new OptimismExceptionHandlerSpec(spec, true));
}
Collections.sort(handlerSpecs, Collections.reverseOrder());
final Map<String, Label> delegationLabels = new HashMap<>();
for(int handlerIndex = 0; handlerIndex < handlerSpecs.size(); ++handlerIndex) {
final OptimismExceptionHandlerSpec spec = handlerSpecs.get(handlerIndex);
final String lvarSpec = spec.lvarSpec;
if(spec.catchTarget) {
assert !method.isReachable();
method._catch(unwarrantedOptimismHandlers.get(lvarSpec));
method.load(countSymbolsInLvarTypeDescriptor(lvarSpec));
method.newarray(Type.OBJECT_ARRAY);
}
if(spec.delegationTarget) {
method.label(delegationLabels.get(lvarSpec));
}
final boolean lastHandler = handlerIndex == handlerSpecs.size() - 1;
int lvarIndex;
final int firstArrayIndex;
final int firstLvarIndex;
Label delegationLabel;
final String commonLvarSpec;
if(lastHandler) {
lvarIndex = 0;
firstLvarIndex = 0;
firstArrayIndex = 0;
delegationLabel = null;
commonLvarSpec = null;
} else {
final int nextHandlerIndex = handlerIndex + 1;
final String nextLvarSpec = handlerSpecs.get(nextHandlerIndex).lvarSpec;
commonLvarSpec = commonPrefix(lvarSpec, nextLvarSpec);
assert Character.isUpperCase(commonLvarSpec.charAt(commonLvarSpec.length() - 1));
{
boolean addNewHandler = true;
int commonHandlerIndex = nextHandlerIndex;
for(; commonHandlerIndex < handlerSpecs.size(); ++commonHandlerIndex) {
final OptimismExceptionHandlerSpec forwardHandlerSpec = handlerSpecs.get(commonHandlerIndex);
final String forwardLvarSpec = forwardHandlerSpec.lvarSpec;
if(forwardLvarSpec.equals(commonLvarSpec)) {
addNewHandler = false;
forwardHandlerSpec.delegationTarget = true;
break;
} else if(!forwardLvarSpec.startsWith(commonLvarSpec)) {
break;
}
}
if(addNewHandler) {
handlerSpecs.add(commonHandlerIndex, new OptimismExceptionHandlerSpec(commonLvarSpec, false));
}
}
firstArrayIndex = countSymbolsInLvarTypeDescriptor(commonLvarSpec);
lvarIndex = 0;
for(int j = 0; j < commonLvarSpec.length(); ++j) {
lvarIndex += CodeGeneratorLexicalContext.getTypeForSlotDescriptor(commonLvarSpec.charAt(j)).getSlots();
}
firstLvarIndex = lvarIndex;
delegationLabel = delegationLabels.get(commonLvarSpec);
if(delegationLabel == null) {
delegationLabel = new Label("uo_pa_" + commonLvarSpec);
delegationLabels.put(commonLvarSpec, delegationLabel);
}
}
int args = 0;
boolean symbolHadValue = false;
for(int typeIndex = commonLvarSpec == null ? 0 : commonLvarSpec.length(); typeIndex < lvarSpec.length(); ++typeIndex) {
final char typeDesc = lvarSpec.charAt(typeIndex);
final Type lvarType = CodeGeneratorLexicalContext.getTypeForSlotDescriptor(typeDesc);
if (!lvarType.isUnknown()) {
method.load(lvarType, lvarIndex);
symbolHadValue = true;
args++;
} else if(typeDesc == 'U' && !symbolHadValue) {
if(method.peekType() == Type.UNDEFINED) {
method.dup();
} else {
method.loadUndefined(Type.OBJECT);
}
args++;
}
if(Character.isUpperCase(typeDesc)) {
symbolHadValue = false;
}
lvarIndex += lvarType.getSlots();
}
assert args > 0;
method.dynamicArrayPopulatorCall(args + 1, firstArrayIndex);
if(delegationLabel != null) {
assert !lastHandler;
assert commonLvarSpec != null;
method.undefineLocalVariables(firstLvarIndex, true);
final OptimismExceptionHandlerSpec nextSpec = handlerSpecs.get(handlerIndex + 1);
if(!nextSpec.lvarSpec.equals(commonLvarSpec) || nextSpec.catchTarget) {
method._goto(delegationLabel);
}
} else {
assert lastHandler;
loadConstant(getByteCodeSymbolNames(fn));
if (isRestOf()) {
loadConstant(getContinuationEntryPoints());
method.invoke(CREATE_REWRITE_EXCEPTION_REST_OF);
} else {
method.invoke(CREATE_REWRITE_EXCEPTION);
}
method.athrow();
}
}
return true;
}
private static String[] getByteCodeSymbolNames(final FunctionNode fn) {
final List<String> names = new ArrayList<>();
for (final Symbol symbol: fn.getBody().getSymbols()) {
if (symbol.hasSlot()) {
if (symbol.isScope()) {
assert symbol.isParam();
names.add(null);
} else {
names.add(symbol.getName());
}
}
}
return names.toArray(new String[0]);
}
private static String commonPrefix(final String s1, final String s2) {
final int l1 = s1.length();
final int l = Math.min(l1, s2.length());
int lms = -1;
for(int i = 0; i < l; ++i) {
final char c1 = s1.charAt(i);
if(c1 != s2.charAt(i)) {
return s1.substring(0, lms + 1);
} else if(Character.isUpperCase(c1)) {
lms = i;
}
}
return l == l1 ? s1 : s2;
}
private static class OptimismExceptionHandlerSpec implements Comparable<OptimismExceptionHandlerSpec> {
private final String lvarSpec;
private final boolean catchTarget;
private boolean delegationTarget;
OptimismExceptionHandlerSpec(final String lvarSpec, final boolean catchTarget) {
this.lvarSpec = lvarSpec;
this.catchTarget = catchTarget;
if(!catchTarget) {
delegationTarget = true;
}
}
@Override
public int compareTo(final OptimismExceptionHandlerSpec o) {
return lvarSpec.compareTo(o.lvarSpec);
}
@Override
public String toString() {
final StringBuilder b = new StringBuilder(64).append("[HandlerSpec ").append(lvarSpec);
if(catchTarget) {
b.append(", catchTarget");
}
if(delegationTarget) {
b.append(", delegationTarget");
}
return b.append("]").toString();
}
}
private static class ContinuationInfo {
private final Label handlerLabel;
private Label targetLabel;
int lvarCount;
private int[] stackStoreSpec;
private Type[] stackTypes;
private Type returnValueType;
private Map<Integer, PropertyMap> objectLiteralMaps;
private int lineNumber;
private Label catchLabel;
private int exceptionScopePops;
ContinuationInfo() {
this.handlerLabel = new Label("continuation_handler");
}
Label getHandlerLabel() {
return handlerLabel;
}
boolean hasTargetLabel() {
return targetLabel != null;
}
Label getTargetLabel() {
return targetLabel;
}
void setTargetLabel(final Label targetLabel) {
this.targetLabel = targetLabel;
}
int[] getStackStoreSpec() {
return stackStoreSpec.clone();
}
void setStackStoreSpec(final int[] stackStoreSpec) {
this.stackStoreSpec = stackStoreSpec;
}
Type[] getStackTypes() {
return stackTypes.clone();
}
void setStackTypes(final Type[] stackTypes) {
this.stackTypes = stackTypes;
}
Type getReturnValueType() {
return returnValueType;
}
void setReturnValueType(final Type returnValueType) {
this.returnValueType = returnValueType;
}
void setObjectLiteralMap(final int objectLiteralStackDepth, final PropertyMap objectLiteralMap) {
if (objectLiteralMaps == null) {
objectLiteralMaps = new HashMap<>();
}
objectLiteralMaps.put(objectLiteralStackDepth, objectLiteralMap);
}
PropertyMap getObjectLiteralMap(final int stackDepth) {
return objectLiteralMaps == null ? null : objectLiteralMaps.get(stackDepth);
}
@Override
public String toString() {
return "[localVariableTypes=" + targetLabel.getStack().getLocalVariableTypesCopy() + ", stackStoreSpec=" +
Arrays.toString(stackStoreSpec) + ", returnValueType=" + returnValueType + "]";
}
}
private ContinuationInfo getContinuationInfo() {
return continuationInfo;
}
private void generateContinuationHandler() {
if (!isRestOf()) {
return;
}
final ContinuationInfo ci = getContinuationInfo();
method.label(ci.getHandlerLabel());
method.lineNumber(0);
final Label.Stack stack = ci.getTargetLabel().getStack();
final List<Type> lvarTypes = stack.getLocalVariableTypesCopy();
final BitSet symbolBoundary = stack.getSymbolBoundaryCopy();
final int lvarCount = ci.lvarCount;
final Type rewriteExceptionType = Type.typeFor(RewriteException.class);
method.load(rewriteExceptionType, 0);
method.storeTemp(rewriteExceptionType, lvarCount);
method.load(rewriteExceptionType, 0);
method.invoke(RewriteException.GET_BYTECODE_SLOTS);
int arrayIndex = 0;
for(int lvarIndex = 0; lvarIndex < lvarCount;) {
final Type lvarType = lvarTypes.get(lvarIndex);
if(!lvarType.isUnknown()) {
method.dup();
method.load(arrayIndex).arrayload();
final Class<?> typeClass = lvarType.getTypeClass();
if(typeClass == long[].class) {
method.load(rewriteExceptionType, lvarCount);
method.invoke(RewriteException.TO_LONG_ARRAY);
} else if(typeClass == double[].class) {
method.load(rewriteExceptionType, lvarCount);
method.invoke(RewriteException.TO_DOUBLE_ARRAY);
} else if(typeClass == Object[].class) {
method.load(rewriteExceptionType, lvarCount);
method.invoke(RewriteException.TO_OBJECT_ARRAY);
} else {
if(!(typeClass.isPrimitive() || typeClass == Object.class)) {
method.loadType(Type.getInternalName(typeClass));
method.invoke(RewriteException.INSTANCE_OR_NULL);
}
method.convert(lvarType);
}
method.storeHidden(lvarType, lvarIndex, false);
}
final int nextLvarIndex = lvarIndex + lvarType.getSlots();
if(symbolBoundary.get(nextLvarIndex - 1)) {
++arrayIndex;
}
lvarIndex = nextLvarIndex;
}
if (AssertsEnabled.assertsEnabled()) {
method.load(arrayIndex);
method.invoke(RewriteException.ASSERT_ARRAY_LENGTH);
} else {
method.pop();
}
final int[] stackStoreSpec = ci.getStackStoreSpec();
final Type[] stackTypes = ci.getStackTypes();
final boolean isStackEmpty = stackStoreSpec.length == 0;
int replacedObjectLiteralMaps = 0;
if(!isStackEmpty) {
for(int i = 0; i < stackStoreSpec.length; ++i) {
final int slot = stackStoreSpec[i];
method.load(lvarTypes.get(slot), slot);
method.convert(stackTypes[i]);
final PropertyMap map = ci.getObjectLiteralMap(i);
if (map != null) {
method.dup();
assert ScriptObject.class.isAssignableFrom(method.peekType().getTypeClass()) : method.peekType().getTypeClass() + " is not a script object";
loadConstant(map);
method.invoke(ScriptObject.SET_MAP);
replacedObjectLiteralMaps++;
}
}
}
assert ci.objectLiteralMaps == null || ci.objectLiteralMaps.size() == replacedObjectLiteralMaps;
method.load(rewriteExceptionType, lvarCount);
method.loadNull();
method.storeHidden(Type.OBJECT, lvarCount);
method.markDeadSlots(lvarCount, Type.OBJECT.getSlots());
method.invoke(RewriteException.GET_RETURN_VALUE);
final Type returnValueType = ci.getReturnValueType();
boolean needsCatch = false;
final Label targetCatchLabel = ci.catchLabel;
Label _try = null;
if(returnValueType.isPrimitive()) {
method.lineNumber(ci.lineNumber);
if(targetCatchLabel != METHOD_BOUNDARY) {
_try = new Label("");
method.label(_try);
needsCatch = true;
}
}
method.convert(returnValueType);
final int scopePopCount = needsCatch ? ci.exceptionScopePops : 0;
final Label catchLabel = scopePopCount > 0 ? new Label("") : targetCatchLabel;
if(needsCatch) {
final Label _end_try = new Label("");
method.label(_end_try);
method._try(_try, _end_try, catchLabel);
}
method._goto(ci.getTargetLabel());
if(catchLabel != targetCatchLabel) {
method.lineNumber(0);
assert scopePopCount > 0;
method._catch(catchLabel);
popScopes(scopePopCount);
method.uncheckedGoto(targetCatchLabel);
}
}
interface SplitLiteralCreator {
void populateRange(MethodEmitter method, Type type, int slot, int start, int end);
}
}