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