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