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