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