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