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