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