LocalVariableTypesCalculator.java revision 1088:7e62d98d4625
1/* 2 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26package jdk.nashorn.internal.codegen; 27 28import static jdk.nashorn.internal.codegen.CompilerConstants.RETURN; 29import static jdk.nashorn.internal.ir.Expression.isAlwaysFalse; 30import static jdk.nashorn.internal.ir.Expression.isAlwaysTrue; 31import java.util.ArrayDeque; 32import java.util.ArrayList; 33import java.util.Collections; 34import java.util.Deque; 35import java.util.HashSet; 36import java.util.IdentityHashMap; 37import java.util.Iterator; 38import java.util.LinkedList; 39import java.util.List; 40import java.util.Map; 41import java.util.Set; 42import java.util.function.Function; 43import jdk.nashorn.internal.codegen.types.Type; 44import jdk.nashorn.internal.ir.AccessNode; 45import jdk.nashorn.internal.ir.BaseNode; 46import jdk.nashorn.internal.ir.BinaryNode; 47import jdk.nashorn.internal.ir.Block; 48import jdk.nashorn.internal.ir.BreakNode; 49import jdk.nashorn.internal.ir.BreakableNode; 50import jdk.nashorn.internal.ir.CaseNode; 51import jdk.nashorn.internal.ir.CatchNode; 52import jdk.nashorn.internal.ir.ContinueNode; 53import jdk.nashorn.internal.ir.Expression; 54import jdk.nashorn.internal.ir.ForNode; 55import jdk.nashorn.internal.ir.FunctionNode; 56import jdk.nashorn.internal.ir.FunctionNode.CompilationState; 57import jdk.nashorn.internal.ir.IdentNode; 58import jdk.nashorn.internal.ir.IfNode; 59import jdk.nashorn.internal.ir.IndexNode; 60import jdk.nashorn.internal.ir.JoinPredecessor; 61import jdk.nashorn.internal.ir.JoinPredecessorExpression; 62import jdk.nashorn.internal.ir.JumpStatement; 63import jdk.nashorn.internal.ir.LabelNode; 64import jdk.nashorn.internal.ir.LexicalContext; 65import jdk.nashorn.internal.ir.LexicalContextNode; 66import jdk.nashorn.internal.ir.LiteralNode; 67import jdk.nashorn.internal.ir.LocalVariableConversion; 68import jdk.nashorn.internal.ir.LoopNode; 69import jdk.nashorn.internal.ir.Node; 70import jdk.nashorn.internal.ir.PropertyNode; 71import jdk.nashorn.internal.ir.ReturnNode; 72import jdk.nashorn.internal.ir.RuntimeNode; 73import jdk.nashorn.internal.ir.RuntimeNode.Request; 74import jdk.nashorn.internal.ir.SplitReturn; 75import jdk.nashorn.internal.ir.Statement; 76import jdk.nashorn.internal.ir.SwitchNode; 77import jdk.nashorn.internal.ir.Symbol; 78import jdk.nashorn.internal.ir.TernaryNode; 79import jdk.nashorn.internal.ir.ThrowNode; 80import jdk.nashorn.internal.ir.TryNode; 81import jdk.nashorn.internal.ir.UnaryNode; 82import jdk.nashorn.internal.ir.VarNode; 83import jdk.nashorn.internal.ir.WhileNode; 84import jdk.nashorn.internal.ir.visitor.NodeVisitor; 85import jdk.nashorn.internal.parser.Token; 86import jdk.nashorn.internal.parser.TokenType; 87 88/** 89 * Calculates types for local variables. For purposes of local variable type calculation, the only types used are 90 * Undefined, boolean, int, long, double, and Object. The calculation eagerly widens types of local variable to their 91 * widest at control flow join points. 92 * TODO: investigate a more sophisticated solution that uses use/def information to only widens the type of a local 93 * variable to its widest used type after the join point. That would eliminate some widenings of undefined variables to 94 * object, most notably those used only in loops. We need a full liveness analysis for that. Currently, we can establish 95 * per-type liveness, which eliminates most of unwanted dead widenings. 96 */ 97final class LocalVariableTypesCalculator extends NodeVisitor<LexicalContext>{ 98 99 private static class JumpOrigin { 100 final JoinPredecessor node; 101 final Map<Symbol, LvarType> types; 102 103 JumpOrigin(final JoinPredecessor node, final Map<Symbol, LvarType> types) { 104 this.node = node; 105 this.types = types; 106 } 107 } 108 109 private static class JumpTarget { 110 private final List<JumpOrigin> origins = new LinkedList<>(); 111 private Map<Symbol, LvarType> types = Collections.emptyMap(); 112 113 void addOrigin(final JoinPredecessor originNode, final Map<Symbol, LvarType> originTypes) { 114 origins.add(new JumpOrigin(originNode, originTypes)); 115 this.types = getUnionTypes(this.types, originTypes); 116 } 117 } 118 private enum LvarType { 119 UNDEFINED(Type.UNDEFINED), 120 BOOLEAN(Type.BOOLEAN), 121 INT(Type.INT), 122 LONG(Type.LONG), 123 DOUBLE(Type.NUMBER), 124 OBJECT(Type.OBJECT); 125 126 private final Type type; 127 private LvarType(final Type type) { 128 this.type = type; 129 } 130 } 131 132 private static final Map<Type, LvarType> TO_LVAR_TYPE = new IdentityHashMap<>(); 133 134 static { 135 for(final LvarType lvarType: LvarType.values()) { 136 TO_LVAR_TYPE.put(lvarType.type, lvarType); 137 } 138 } 139 140 @SuppressWarnings("unchecked") 141 private static IdentityHashMap<Symbol, LvarType> cloneMap(final Map<Symbol, LvarType> map) { 142 return (IdentityHashMap<Symbol, LvarType>)((IdentityHashMap<?,?>)map).clone(); 143 } 144 145 private LocalVariableConversion createConversion(final Symbol symbol, final LvarType branchLvarType, 146 final Map<Symbol, LvarType> joinLvarTypes, final LocalVariableConversion next) { 147 final LvarType targetType = joinLvarTypes.get(symbol); 148 assert targetType != null; 149 if(targetType == branchLvarType) { 150 return next; 151 } 152 // NOTE: we could naively just use symbolIsUsed(symbol, branchLvarType) here, but that'd be wrong. While 153 // technically a conversion will read the value of the symbol with that type, but it will also write it to a new 154 // type, and that type might be dead (we can't know yet). For this reason, we don't treat conversion reads as 155 // real uses until we know their target type is live. If we didn't do this, and just did a symbolIsUsed here, 156 // we'd introduce false live variables which could nevertheless turn into dead ones in a subsequent 157 // deoptimization, causing a shift in the list of live locals that'd cause erroneous restoration of 158 // continuations (since RewriteException's byteCodeSlots carries an array and not a name-value map). 159 160 symbolIsConverted(symbol, branchLvarType, targetType); 161 //symbolIsUsed(symbol, branchLvarType); 162 return new LocalVariableConversion(symbol, branchLvarType.type, targetType.type, next); 163 } 164 165 private static Map<Symbol, LvarType> getUnionTypes(final Map<Symbol, LvarType> types1, final Map<Symbol, LvarType> types2) { 166 if(types1 == types2 || types1.isEmpty()) { 167 return types2; 168 } else if(types2.isEmpty()) { 169 return types1; 170 } 171 final Set<Symbol> commonSymbols = new HashSet<>(types1.keySet()); 172 commonSymbols.retainAll(types2.keySet()); 173 // We have a chance of returning an unmodified set if both sets have the same keys and one is strictly wider 174 // than the other. 175 final int commonSize = commonSymbols.size(); 176 final int types1Size = types1.size(); 177 final int types2Size = types2.size(); 178 if(commonSize == types1Size && commonSize == types2Size) { 179 boolean matches1 = true, matches2 = true; 180 Map<Symbol, LvarType> union = null; 181 for(final Symbol symbol: commonSymbols) { 182 final LvarType type1 = types1.get(symbol); 183 final LvarType type2 = types2.get(symbol); 184 final LvarType widest = widestLvarType(type1, type2); 185 if(widest != type1 && matches1) { 186 matches1 = false; 187 if(!matches2) { 188 union = cloneMap(types1); 189 } 190 } 191 if (widest != type2 && matches2) { 192 matches2 = false; 193 if(!matches1) { 194 union = cloneMap(types2); 195 } 196 } 197 if(!(matches1 || matches2) && union != null) { //remove overly enthusiastic "union can be null" warning 198 assert union != null; 199 union.put(symbol, widest); 200 } 201 } 202 return matches1 ? types1 : matches2 ? types2 : union; 203 } 204 // General case 205 final Map<Symbol, LvarType> union; 206 if(types1Size > types2Size) { 207 union = cloneMap(types1); 208 union.putAll(types2); 209 } else { 210 union = cloneMap(types2); 211 union.putAll(types1); 212 } 213 for(final Symbol symbol: commonSymbols) { 214 final LvarType type1 = types1.get(symbol); 215 final LvarType type2 = types2.get(symbol); 216 union.put(symbol, widestLvarType(type1, type2)); 217 } 218 return union; 219 } 220 221 private static void symbolIsUsed(final Symbol symbol, final LvarType type) { 222 if(type != LvarType.UNDEFINED) { 223 symbol.setHasSlotFor(type.type); 224 } 225 } 226 227 private static class SymbolConversions { 228 private static byte I2L = 1 << 0; 229 private static byte I2D = 1 << 1; 230 private static byte I2O = 1 << 2; 231 private static byte L2D = 1 << 3; 232 private static byte L2O = 1 << 4; 233 private static byte D2O = 1 << 5; 234 235 private byte conversions; 236 237 void recordConversion(final LvarType from, final LvarType to) { 238 switch (from) { 239 case UNDEFINED: 240 return; 241 case INT: 242 case BOOLEAN: 243 switch (to) { 244 case LONG: 245 recordConversion(I2L); 246 return; 247 case DOUBLE: 248 recordConversion(I2D); 249 return; 250 case OBJECT: 251 recordConversion(I2O); 252 return; 253 default: 254 illegalConversion(from, to); 255 return; 256 } 257 case LONG: 258 switch (to) { 259 case DOUBLE: 260 recordConversion(L2D); 261 return; 262 case OBJECT: 263 recordConversion(L2O); 264 return; 265 default: 266 illegalConversion(from, to); 267 return; 268 } 269 case DOUBLE: 270 if(to == LvarType.OBJECT) { 271 recordConversion(D2O); 272 } 273 return; 274 default: 275 illegalConversion(from, to); 276 } 277 } 278 279 private static void illegalConversion(final LvarType from, final LvarType to) { 280 throw new AssertionError("Invalid conversion from " + from + " to " + to); 281 } 282 283 void recordConversion(final byte convFlag) { 284 conversions = (byte)(conversions | convFlag); 285 } 286 287 boolean hasConversion(final byte convFlag) { 288 return (conversions & convFlag) != 0; 289 } 290 291 void calculateTypeLiveness(final Symbol symbol) { 292 if(symbol.hasSlotFor(Type.OBJECT)) { 293 if(hasConversion(D2O)) { 294 symbol.setHasSlotFor(Type.NUMBER); 295 } 296 if(hasConversion(L2O)) { 297 symbol.setHasSlotFor(Type.LONG); 298 } 299 if(hasConversion(I2O)) { 300 symbol.setHasSlotFor(Type.INT); 301 } 302 } 303 if(symbol.hasSlotFor(Type.NUMBER)) { 304 if(hasConversion(L2D)) { 305 symbol.setHasSlotFor(Type.LONG); 306 } 307 if(hasConversion(I2D)) { 308 symbol.setHasSlotFor(Type.INT); 309 } 310 } 311 if(symbol.hasSlotFor(Type.LONG)) { 312 if(hasConversion(I2L)) { 313 symbol.setHasSlotFor(Type.INT); 314 } 315 } 316 } 317 } 318 319 private void symbolIsConverted(final Symbol symbol, final LvarType from, final LvarType to) { 320 SymbolConversions conversions = symbolConversions.get(symbol); 321 if(conversions == null) { 322 conversions = new SymbolConversions(); 323 symbolConversions.put(symbol, conversions); 324 } 325 conversions.recordConversion(from, to); 326 } 327 328 private static LvarType toLvarType(final Type type) { 329 assert type != null; 330 final LvarType lvarType = TO_LVAR_TYPE.get(type); 331 if(lvarType != null) { 332 return lvarType; 333 } 334 assert type.isObject(); 335 return LvarType.OBJECT; 336 } 337 private static LvarType widestLvarType(final LvarType t1, final LvarType t2) { 338 if(t1 == t2) { 339 return t1; 340 } 341 // Undefined or boolean to anything always widens to object. 342 if(t1.ordinal() < LvarType.INT.ordinal() || t2.ordinal() < LvarType.INT.ordinal()) { 343 return LvarType.OBJECT; 344 } 345 // NOTE: we allow "widening" of long to double even though it can lose precision. ECMAScript doesn't have an 346 // Int64 type anyway, so this loss of precision is actually more conformant to the specification... 347 return LvarType.values()[Math.max(t1.ordinal(), t2.ordinal())]; 348 } 349 private final Compiler compiler; 350 private final Map<Label, JumpTarget> jumpTargets = new IdentityHashMap<>(); 351 // Local variable type mapping at the currently evaluated point. No map instance is ever modified; setLvarType() always 352 // allocates a new map. Immutability of maps allows for cheap snapshots by just keeping the reference to the current 353 // value. 354 private Map<Symbol, LvarType> localVariableTypes = new IdentityHashMap<>(); 355 356 // Whether the current point in the AST is reachable code 357 private boolean reachable = true; 358 // Return type of the function 359 private Type returnType = Type.UNKNOWN; 360 // Synthetic return node that we must insert at the end of the function if it's end is reachable. 361 private ReturnNode syntheticReturn; 362 363 private boolean alreadyEnteredTopLevelFunction; 364 365 // LvarType and conversion information gathered during the top-down pass; applied to nodes in the bottom-up pass. 366 private final Map<JoinPredecessor, LocalVariableConversion> localVariableConversions = new IdentityHashMap<>(); 367 368 private final Map<IdentNode, LvarType> identifierLvarTypes = new IdentityHashMap<>(); 369 private final Map<Symbol, SymbolConversions> symbolConversions = new IdentityHashMap<>(); 370 371 private SymbolToType symbolToType = new SymbolToType(); 372 373 // Stack of open labels for starts of catch blocks, one for every currently traversed try block; for inserting 374 // control flow edges to them. Note that we currently don't insert actual control flow edges, but instead edges that 375 // help us with type calculations. This means that some operations that can result in an exception being thrown 376 // aren't considered (function calls, side effecting property getters and setters etc.), while some operations that 377 // don't result in control flow transfers do originate an edge to the catch blocks (namely, assignments to local 378 // variables). 379 private final Deque<Label> catchLabels = new ArrayDeque<>(); 380 381 LocalVariableTypesCalculator(final Compiler compiler) { 382 super(new LexicalContext()); 383 this.compiler = compiler; 384 } 385 386 private JumpTarget createJumpTarget(final Label label) { 387 assert !jumpTargets.containsKey(label); 388 final JumpTarget jumpTarget = new JumpTarget(); 389 jumpTargets.put(label, jumpTarget); 390 return jumpTarget; 391 } 392 393 private void doesNotContinueSequentially() { 394 reachable = false; 395 localVariableTypes = Collections.emptyMap(); 396 } 397 398 399 @Override 400 public boolean enterBinaryNode(final BinaryNode binaryNode) { 401 final Expression lhs = binaryNode.lhs(); 402 final Expression rhs = binaryNode.rhs(); 403 final boolean isAssignment = binaryNode.isAssignment(); 404 405 final TokenType tokenType = Token.descType(binaryNode.getToken()); 406 if(tokenType.isLeftAssociative()) { 407 assert !isAssignment; 408 final boolean isLogical = binaryNode.isLogical(); 409 final Label joinLabel = isLogical ? new Label("") : null; 410 lhs.accept(this); 411 if(isLogical) { 412 jumpToLabel((JoinPredecessor)lhs, joinLabel); 413 } 414 rhs.accept(this); 415 if(isLogical) { 416 jumpToLabel((JoinPredecessor)rhs, joinLabel); 417 } 418 joinOnLabel(joinLabel); 419 } else { 420 rhs.accept(this); 421 if(isAssignment) { 422 if(lhs instanceof BaseNode) { 423 ((BaseNode)lhs).getBase().accept(this); 424 if(lhs instanceof IndexNode) { 425 ((IndexNode)lhs).getIndex().accept(this); 426 } else { 427 assert lhs instanceof AccessNode; 428 } 429 } else { 430 assert lhs instanceof IdentNode; 431 if(binaryNode.isSelfModifying()) { 432 ((IdentNode)lhs).accept(this); 433 } 434 } 435 } else { 436 lhs.accept(this); 437 } 438 } 439 440 if(isAssignment && lhs instanceof IdentNode) { 441 if(binaryNode.isSelfModifying()) { 442 onSelfAssignment((IdentNode)lhs, binaryNode); 443 } else { 444 onAssignment((IdentNode)lhs, rhs); 445 } 446 } 447 return false; 448 } 449 450 @Override 451 public boolean enterBlock(final Block block) { 452 for(final Symbol symbol: block.getSymbols()) { 453 if(symbol.isBytecodeLocal() && getLocalVariableTypeOrNull(symbol) == null) { 454 setType(symbol, LvarType.UNDEFINED); 455 } 456 } 457 return true; 458 } 459 460 @Override 461 public boolean enterBreakNode(final BreakNode breakNode) { 462 return enterJumpStatement(breakNode); 463 } 464 465 @Override 466 public boolean enterContinueNode(final ContinueNode continueNode) { 467 return enterJumpStatement(continueNode); 468 } 469 470 private boolean enterJumpStatement(final JumpStatement jump) { 471 if(!reachable) { 472 return false; 473 } 474 final BreakableNode target = jump.getTarget(lc); 475 jumpToLabel(jump, jump.getTargetLabel(target), getBreakTargetTypes(target)); 476 doesNotContinueSequentially(); 477 return false; 478 } 479 480 @Override 481 protected boolean enterDefault(final Node node) { 482 return reachable; 483 } 484 485 private void enterDoWhileLoop(final WhileNode loopNode) { 486 final JoinPredecessorExpression test = loopNode.getTest(); 487 final Block body = loopNode.getBody(); 488 final Label continueLabel = loopNode.getContinueLabel(); 489 final Label breakLabel = loopNode.getBreakLabel(); 490 final Map<Symbol, LvarType> beforeLoopTypes = localVariableTypes; 491 final Label repeatLabel = new Label(""); 492 for(;;) { 493 jumpToLabel(loopNode, repeatLabel, beforeLoopTypes); 494 final Map<Symbol, LvarType> beforeRepeatTypes = localVariableTypes; 495 body.accept(this); 496 if(reachable) { 497 jumpToLabel(body, continueLabel); 498 } 499 joinOnLabel(continueLabel); 500 if(!reachable) { 501 break; 502 } 503 test.accept(this); 504 jumpToLabel(test, breakLabel); 505 if(isAlwaysFalse(test)) { 506 break; 507 } 508 jumpToLabel(test, repeatLabel); 509 joinOnLabel(repeatLabel); 510 if(localVariableTypes.equals(beforeRepeatTypes)) { 511 break; 512 } 513 resetJoinPoint(continueLabel); 514 resetJoinPoint(breakLabel); 515 resetJoinPoint(repeatLabel); 516 } 517 518 if(isAlwaysTrue(test)) { 519 doesNotContinueSequentially(); 520 } 521 522 leaveBreakable(loopNode); 523 } 524 525 @Override 526 public boolean enterForNode(final ForNode forNode) { 527 if(!reachable) { 528 return false; 529 } 530 531 final Expression init = forNode.getInit(); 532 if(forNode.isForIn()) { 533 final JoinPredecessorExpression iterable = forNode.getModify(); 534 iterable.accept(this); 535 enterTestFirstLoop(forNode, null, init, 536 // If we're iterating over property names, and we can discern from the runtime environment 537 // of the compilation that the object being iterated over must use strings for property 538 // names (e.g., it is a native JS object or array), then we'll not bother trying to treat 539 // the property names optimistically. 540 !compiler.useOptimisticTypes() || (!forNode.isForEach() && compiler.hasStringPropertyIterator(iterable.getExpression()))); 541 } else { 542 if(init != null) { 543 init.accept(this); 544 } 545 enterTestFirstLoop(forNode, forNode.getModify(), null, false); 546 } 547 return false; 548 } 549 550 @Override 551 public boolean enterFunctionNode(final FunctionNode functionNode) { 552 if(alreadyEnteredTopLevelFunction) { 553 return false; 554 } 555 int pos = 0; 556 if(!functionNode.isVarArg()) { 557 for (final IdentNode param : functionNode.getParameters()) { 558 final Symbol symbol = param.getSymbol(); 559 // Parameter is not necessarily bytecode local as it can be scoped due to nested context use, but it 560 // must have a slot if we aren't in a function with vararg signature. 561 assert symbol.hasSlot(); 562 final Type callSiteParamType = compiler.getParamType(functionNode, pos); 563 final LvarType paramType = callSiteParamType == null ? LvarType.OBJECT : toLvarType(callSiteParamType); 564 setType(symbol, paramType); 565 // Make sure parameter slot for its incoming value is not marked dead. NOTE: this is a heuristic. Right 566 // now, CodeGenerator.expandParameters() relies on the fact that every parameter's final slot width will 567 // be at least the same as incoming width, therefore even if a parameter is never read, we'll still keep 568 // its slot. 569 symbolIsUsed(symbol); 570 setIdentifierLvarType(param, paramType); 571 pos++; 572 } 573 } 574 setCompilerConstantAsObject(functionNode, CompilerConstants.THIS); 575 576 // TODO: coarse-grained. If we wanted to solve it completely precisely, 577 // we'd also need to push/pop its type when handling WithNode (so that 578 // it can go back to undefined after a 'with' block. 579 if(functionNode.hasScopeBlock() || functionNode.needsParentScope()) { 580 setCompilerConstantAsObject(functionNode, CompilerConstants.SCOPE); 581 } 582 if(functionNode.needsCallee()) { 583 setCompilerConstantAsObject(functionNode, CompilerConstants.CALLEE); 584 } 585 if(functionNode.needsArguments()) { 586 setCompilerConstantAsObject(functionNode, CompilerConstants.ARGUMENTS); 587 } 588 589 alreadyEnteredTopLevelFunction = true; 590 return true; 591 } 592 593 @Override 594 public boolean enterIdentNode(final IdentNode identNode) { 595 final Symbol symbol = identNode.getSymbol(); 596 if(symbol.isBytecodeLocal()) { 597 symbolIsUsed(symbol); 598 setIdentifierLvarType(identNode, getLocalVariableType(symbol)); 599 } 600 return false; 601 } 602 603 @Override 604 public boolean enterIfNode(final IfNode ifNode) { 605 if(!reachable) { 606 return false; 607 } 608 609 final Expression test = ifNode.getTest(); 610 final Block pass = ifNode.getPass(); 611 final Block fail = ifNode.getFail(); 612 613 test.accept(this); 614 615 final Map<Symbol, LvarType> afterTestLvarTypes = localVariableTypes; 616 if(!isAlwaysFalse(test)) { 617 pass.accept(this); 618 } 619 final Map<Symbol, LvarType> passLvarTypes = localVariableTypes; 620 final boolean reachableFromPass = reachable; 621 622 reachable = true; 623 localVariableTypes = afterTestLvarTypes; 624 if(!isAlwaysTrue(test) && fail != null) { 625 fail.accept(this); 626 final boolean reachableFromFail = reachable; 627 reachable |= reachableFromPass; 628 if(!reachable) { 629 return false; 630 } 631 632 if(reachableFromFail) { 633 if(reachableFromPass) { 634 final Map<Symbol, LvarType> failLvarTypes = localVariableTypes; 635 localVariableTypes = getUnionTypes(passLvarTypes, failLvarTypes); 636 setConversion(pass, passLvarTypes, localVariableTypes); 637 setConversion(fail, failLvarTypes, localVariableTypes); 638 } 639 return false; 640 } 641 } 642 643 if(reachableFromPass) { 644 localVariableTypes = getUnionTypes(afterTestLvarTypes, passLvarTypes); 645 // IfNode itself is associated with conversions that might need to be performed after the test if there's no 646 // else branch. E.g. 647 // if(x = 1, cond) { x = 1.0 } must widen "x = 1" to a double. 648 setConversion(pass, passLvarTypes, localVariableTypes); 649 setConversion(ifNode, afterTestLvarTypes, localVariableTypes); 650 } else { 651 localVariableTypes = afterTestLvarTypes; 652 } 653 654 return false; 655 } 656 657 @Override 658 public boolean enterPropertyNode(final PropertyNode propertyNode) { 659 // Avoid falsely adding property keys to the control flow graph 660 if(propertyNode.getValue() != null) { 661 propertyNode.getValue().accept(this); 662 } 663 return false; 664 } 665 666 @Override 667 public boolean enterReturnNode(final ReturnNode returnNode) { 668 if(!reachable) { 669 return false; 670 } 671 672 final Expression returnExpr = returnNode.getExpression(); 673 final Type returnExprType; 674 if(returnExpr != null) { 675 returnExpr.accept(this); 676 returnExprType = getType(returnExpr); 677 } else { 678 returnExprType = Type.UNDEFINED; 679 } 680 returnType = Type.widestReturnType(returnType, returnExprType); 681 doesNotContinueSequentially(); 682 return false; 683 } 684 685 @Override 686 public boolean enterSplitReturn(final SplitReturn splitReturn) { 687 doesNotContinueSequentially(); 688 return false; 689 } 690 691 @Override 692 public boolean enterSwitchNode(final SwitchNode switchNode) { 693 if(!reachable) { 694 return false; 695 } 696 697 final Expression expr = switchNode.getExpression(); 698 expr.accept(this); 699 700 final List<CaseNode> cases = switchNode.getCases(); 701 if(cases.isEmpty()) { 702 return false; 703 } 704 705 // Control flow is different for all-integer cases where we dispatch by switch table, and for all other cases 706 // where we do sequential comparison. Note that CaseNode objects act as join points. 707 final boolean isInteger = switchNode.isInteger(); 708 final Label breakLabel = switchNode.getBreakLabel(); 709 final boolean hasDefault = switchNode.getDefaultCase() != null; 710 711 boolean tagUsed = false; 712 for(final CaseNode caseNode: cases) { 713 final Expression test = caseNode.getTest(); 714 if(!isInteger && test != null) { 715 test.accept(this); 716 if(!tagUsed) { 717 symbolIsUsed(switchNode.getTag(), LvarType.OBJECT); 718 tagUsed = true; 719 } 720 } 721 // CaseNode carries the conversions that need to be performed on its entry from the test. 722 // CodeGenerator ensures these are only emitted when arriving on the branch and not through a 723 // fallthrough. 724 jumpToLabel(caseNode, caseNode.getBody().getEntryLabel()); 725 } 726 if(!hasDefault) { 727 // No default case means we can arrive at the break label without entering any cases. In that case 728 // SwitchNode will carry the conversions that need to be performed before it does that jump. 729 jumpToLabel(switchNode, breakLabel); 730 } 731 732 // All cases are arrived at through jumps 733 doesNotContinueSequentially(); 734 735 Block previousBlock = null; 736 for(final CaseNode caseNode: cases) { 737 final Block body = caseNode.getBody(); 738 final Label entryLabel = body.getEntryLabel(); 739 if(previousBlock != null && reachable) { 740 jumpToLabel(previousBlock, entryLabel); 741 } 742 joinOnLabel(entryLabel); 743 assert reachable == true; 744 body.accept(this); 745 previousBlock = body; 746 } 747 if(previousBlock != null && reachable) { 748 jumpToLabel(previousBlock, breakLabel); 749 } 750 leaveBreakable(switchNode); 751 return false; 752 } 753 754 @Override 755 public boolean enterTernaryNode(final TernaryNode ternaryNode) { 756 final Expression test = ternaryNode.getTest(); 757 final Expression trueExpr = ternaryNode.getTrueExpression(); 758 final Expression falseExpr = ternaryNode.getFalseExpression(); 759 760 test.accept(this); 761 762 final Map<Symbol, LvarType> testExitLvarTypes = localVariableTypes; 763 if(!isAlwaysFalse(test)) { 764 trueExpr.accept(this); 765 } 766 final Map<Symbol, LvarType> trueExitLvarTypes = localVariableTypes; 767 localVariableTypes = testExitLvarTypes; 768 if(!isAlwaysTrue(test)) { 769 falseExpr.accept(this); 770 } 771 final Map<Symbol, LvarType> falseExitLvarTypes = localVariableTypes; 772 localVariableTypes = getUnionTypes(trueExitLvarTypes, falseExitLvarTypes); 773 setConversion((JoinPredecessor)trueExpr, trueExitLvarTypes, localVariableTypes); 774 setConversion((JoinPredecessor)falseExpr, falseExitLvarTypes, localVariableTypes); 775 return false; 776 } 777 778 private void enterTestFirstLoop(final LoopNode loopNode, final JoinPredecessorExpression modify, 779 final Expression iteratorValues, final boolean iteratorValuesAreObject) { 780 final JoinPredecessorExpression test = loopNode.getTest(); 781 if(isAlwaysFalse(test)) { 782 test.accept(this); 783 return; 784 } 785 786 final Label continueLabel = loopNode.getContinueLabel(); 787 final Label breakLabel = loopNode.getBreakLabel(); 788 789 final Label repeatLabel = modify == null ? continueLabel : new Label(""); 790 final Map<Symbol, LvarType> beforeLoopTypes = localVariableTypes; 791 for(;;) { 792 jumpToLabel(loopNode, repeatLabel, beforeLoopTypes); 793 final Map<Symbol, LvarType> beforeRepeatTypes = localVariableTypes; 794 if(test != null) { 795 test.accept(this); 796 } 797 if(!isAlwaysTrue(test)) { 798 jumpToLabel(test, breakLabel); 799 } 800 if(iteratorValues instanceof IdentNode) { 801 final IdentNode ident = (IdentNode)iteratorValues; 802 // Receives iterator values; the optimistic type of the iterator values is tracked on the 803 // identifier, but we override optimism if it's known that the object being iterated over will 804 // never have primitive property names. 805 onAssignment(ident, iteratorValuesAreObject ? LvarType.OBJECT : 806 toLvarType(compiler.getOptimisticType(ident))); 807 } 808 final Block body = loopNode.getBody(); 809 body.accept(this); 810 if(reachable) { 811 jumpToLabel(body, continueLabel); 812 } 813 joinOnLabel(continueLabel); 814 if(!reachable) { 815 break; 816 } 817 if(modify != null) { 818 modify.accept(this); 819 jumpToLabel(modify, repeatLabel); 820 joinOnLabel(repeatLabel); 821 } 822 if(localVariableTypes.equals(beforeRepeatTypes)) { 823 break; 824 } 825 // Reset the join points and repeat the analysis 826 resetJoinPoint(continueLabel); 827 resetJoinPoint(breakLabel); 828 resetJoinPoint(repeatLabel); 829 } 830 831 if(isAlwaysTrue(test) && iteratorValues == null) { 832 doesNotContinueSequentially(); 833 } 834 835 leaveBreakable(loopNode); 836 } 837 838 @Override 839 public boolean enterThrowNode(final ThrowNode throwNode) { 840 if(!reachable) { 841 return false; 842 } 843 844 throwNode.getExpression().accept(this); 845 jumpToCatchBlock(throwNode); 846 doesNotContinueSequentially(); 847 return false; 848 } 849 850 @Override 851 public boolean enterTryNode(final TryNode tryNode) { 852 if(!reachable) { 853 return false; 854 } 855 856 // This is the label for the join point at the entry of the catch blocks. 857 final Label catchLabel = new Label(""); 858 catchLabels.push(catchLabel); 859 860 // Presume that even the start of the try block can immediately go to the catch 861 jumpToLabel(tryNode, catchLabel); 862 863 final Block body = tryNode.getBody(); 864 body.accept(this); 865 catchLabels.pop(); 866 867 // Final exit label for the whole try/catch construct (after the try block and after all catches). 868 final Label endLabel = new Label(""); 869 870 boolean canExit = false; 871 if(reachable) { 872 jumpToLabel(body, endLabel); 873 canExit = true; 874 } 875 doesNotContinueSequentially(); 876 877 joinOnLabel(catchLabel); 878 for(final CatchNode catchNode: tryNode.getCatches()) { 879 final IdentNode exception = catchNode.getException(); 880 onAssignment(exception, LvarType.OBJECT); 881 final Expression condition = catchNode.getExceptionCondition(); 882 if(condition != null) { 883 condition.accept(this); 884 } 885 final Map<Symbol, LvarType> afterConditionTypes = localVariableTypes; 886 final Block catchBody = catchNode.getBody(); 887 // TODO: currently, we consider that the catch blocks are always reachable from the try block as currently 888 // we lack enough analysis to prove that no statement before a break/continue/return in the try block can 889 // throw an exception. 890 reachable = true; 891 catchBody.accept(this); 892 final Symbol exceptionSymbol = exception.getSymbol(); 893 if(reachable) { 894 localVariableTypes = cloneMap(localVariableTypes); 895 localVariableTypes.remove(exceptionSymbol); 896 jumpToLabel(catchBody, endLabel); 897 canExit = true; 898 } 899 localVariableTypes = cloneMap(afterConditionTypes); 900 localVariableTypes.remove(exceptionSymbol); 901 } 902 // NOTE: if we had one or more conditional catch blocks with no unconditional catch block following them, then 903 // there will be an unconditional rethrow, so the join point can never be reached from the last 904 // conditionExpression. 905 doesNotContinueSequentially(); 906 907 if(canExit) { 908 joinOnLabel(endLabel); 909 } 910 911 return false; 912 } 913 914 915 @Override 916 public boolean enterUnaryNode(final UnaryNode unaryNode) { 917 final Expression expr = unaryNode.getExpression(); 918 expr.accept(this); 919 920 if(unaryNode.isSelfModifying()) { 921 if(expr instanceof IdentNode) { 922 onSelfAssignment((IdentNode)expr, unaryNode); 923 } 924 } 925 return false; 926 } 927 928 @Override 929 public boolean enterVarNode(final VarNode varNode) { 930 if (!reachable) { 931 return false; 932 } 933 final Expression init = varNode.getInit(); 934 if(init != null) { 935 init.accept(this); 936 onAssignment(varNode.getName(), init); 937 } 938 return false; 939 } 940 941 @Override 942 public boolean enterWhileNode(final WhileNode whileNode) { 943 if(!reachable) { 944 return false; 945 } 946 if(whileNode.isDoWhile()) { 947 enterDoWhileLoop(whileNode); 948 } else { 949 enterTestFirstLoop(whileNode, null, null, false); 950 } 951 return false; 952 } 953 954 private Map<Symbol, LvarType> getBreakTargetTypes(final BreakableNode target) { 955 // Remove symbols defined in the the blocks that are being broken out of. 956 Map<Symbol, LvarType> types = localVariableTypes; 957 for(final Iterator<LexicalContextNode> it = lc.getAllNodes(); it.hasNext();) { 958 final LexicalContextNode node = it.next(); 959 if(node instanceof Block) { 960 for(final Symbol symbol: ((Block)node).getSymbols()) { 961 if(localVariableTypes.containsKey(symbol)) { 962 if(types == localVariableTypes) { 963 types = cloneMap(localVariableTypes); 964 } 965 types.remove(symbol); 966 } 967 } 968 } 969 if(node == target) { 970 break; 971 } 972 } 973 return types; 974 } 975 976 private LvarType getLocalVariableType(final Symbol symbol) { 977 final LvarType type = getLocalVariableTypeOrNull(symbol); 978 assert type != null; 979 return type; 980 } 981 982 private LvarType getLocalVariableTypeOrNull(final Symbol symbol) { 983 return localVariableTypes.get(symbol); 984 } 985 986 private JumpTarget getOrCreateJumpTarget(final Label label) { 987 JumpTarget jumpTarget = jumpTargets.get(label); 988 if(jumpTarget == null) { 989 jumpTarget = createJumpTarget(label); 990 } 991 return jumpTarget; 992 } 993 994 995 /** 996 * If there's a join point associated with a label, insert the join point into the flow. 997 * @param label the label to insert a join point for. 998 */ 999 private void joinOnLabel(final Label label) { 1000 final JumpTarget jumpTarget = jumpTargets.remove(label); 1001 if(jumpTarget == null) { 1002 return; 1003 } 1004 assert !jumpTarget.origins.isEmpty(); 1005 reachable = true; 1006 localVariableTypes = getUnionTypes(jumpTarget.types, localVariableTypes); 1007 for(final JumpOrigin jumpOrigin: jumpTarget.origins) { 1008 setConversion(jumpOrigin.node, jumpOrigin.types, localVariableTypes); 1009 } 1010 } 1011 1012 /** 1013 * If we're in a try/catch block, add an edge from the specified node to the try node's pre-catch label. 1014 */ 1015 private void jumpToCatchBlock(final JoinPredecessor jumpOrigin) { 1016 final Label currentCatchLabel = catchLabels.peek(); 1017 if(currentCatchLabel != null) { 1018 jumpToLabel(jumpOrigin, currentCatchLabel); 1019 } 1020 } 1021 1022 private void jumpToLabel(final JoinPredecessor jumpOrigin, final Label label) { 1023 jumpToLabel(jumpOrigin, label, localVariableTypes); 1024 } 1025 1026 private void jumpToLabel(final JoinPredecessor jumpOrigin, final Label label, final Map<Symbol, LvarType> types) { 1027 getOrCreateJumpTarget(label).addOrigin(jumpOrigin, types); 1028 } 1029 1030 @Override 1031 public Node leaveBlock(final Block block) { 1032 if(lc.isFunctionBody()) { 1033 if(reachable) { 1034 // reachable==true means we can reach the end of the function without an explicit return statement. We 1035 // need to insert a synthetic one then. This logic used to be in Lower.leaveBlock(), but Lower's 1036 // reachability analysis (through Terminal.isTerminal() flags) is not precise enough so 1037 // Lower$BlockLexicalContext.afterSetStatements will sometimes think the control flow terminates even 1038 // when it didn't. Example: function() { switch((z)) { default: {break; } throw x; } }. 1039 createSyntheticReturn(block); 1040 assert !reachable; 1041 } 1042 // We must calculate the return type here (and not in leaveFunctionNode) as it can affect the liveness of 1043 // the :return symbol and thus affect conversion type liveness calculations for it. 1044 calculateReturnType(); 1045 } 1046 1047 boolean cloned = false; 1048 for(final Symbol symbol: block.getSymbols()) { 1049 // Undefine the symbol outside the block 1050 if(localVariableTypes.containsKey(symbol)) { 1051 if(!cloned) { 1052 localVariableTypes = cloneMap(localVariableTypes); 1053 cloned = true; 1054 } 1055 localVariableTypes.remove(symbol); 1056 } 1057 1058 if(symbol.hasSlot()) { 1059 final SymbolConversions conversions = symbolConversions.get(symbol); 1060 if(conversions != null) { 1061 // Potentially make some currently dead types live if they're needed as a source of a type 1062 // conversion at a join. 1063 conversions.calculateTypeLiveness(symbol); 1064 } 1065 if(symbol.slotCount() == 0) { 1066 // This is a local variable that is never read. It won't need a slot. 1067 symbol.setNeedsSlot(false); 1068 } 1069 } 1070 } 1071 1072 if(reachable) { 1073 // TODO: this is totally backwards. Block should not be breakable, LabelNode should be breakable. 1074 final LabelNode labelNode = lc.getCurrentBlockLabelNode(); 1075 if(labelNode != null) { 1076 jumpToLabel(labelNode, block.getBreakLabel()); 1077 } 1078 } 1079 leaveBreakable(block); 1080 return block; 1081 } 1082 1083 private void calculateReturnType() { 1084 // NOTE: if return type is unknown, then the function does not explicitly return a value. Such a function under 1085 // ECMAScript rules returns Undefined, which has Type.OBJECT. We might consider an optimization in the future 1086 // where we can return void functions. 1087 if(returnType.isUnknown()) { 1088 returnType = Type.OBJECT; 1089 } 1090 } 1091 1092 private void createSyntheticReturn(final Block body) { 1093 final FunctionNode functionNode = lc.getCurrentFunction(); 1094 final long token = functionNode.getToken(); 1095 final int finish = functionNode.getFinish(); 1096 final List<Statement> statements = body.getStatements(); 1097 final int lineNumber = statements.isEmpty() ? functionNode.getLineNumber() : statements.get(statements.size() - 1).getLineNumber(); 1098 final IdentNode returnExpr; 1099 if(functionNode.isProgram()) { 1100 returnExpr = new IdentNode(token, finish, RETURN.symbolName()).setSymbol(getCompilerConstantSymbol(functionNode, RETURN)); 1101 } else { 1102 returnExpr = null; 1103 } 1104 syntheticReturn = new ReturnNode(lineNumber, token, finish, returnExpr); 1105 syntheticReturn.accept(this); 1106 } 1107 1108 /** 1109 * Leave a breakable node. If there's a join point associated with its break label (meaning there was at least one 1110 * break statement to the end of the node), insert the join point into the flow. 1111 * @param breakable the breakable node being left. 1112 */ 1113 private void leaveBreakable(final BreakableNode breakable) { 1114 joinOnLabel(breakable.getBreakLabel()); 1115 } 1116 1117 @Override 1118 public Node leaveFunctionNode(final FunctionNode functionNode) { 1119 // Sets the return type of the function and also performs the bottom-up pass of applying type and conversion 1120 // information to nodes as well as doing the calculation on nested functions as required. 1121 FunctionNode newFunction = functionNode; 1122 final NodeVisitor<LexicalContext> applyChangesVisitor = new NodeVisitor<LexicalContext>(new LexicalContext()) { 1123 private boolean inOuterFunction = true; 1124 private final Deque<JoinPredecessor> joinPredecessors = new ArrayDeque<>(); 1125 1126 @Override 1127 protected boolean enterDefault(final Node node) { 1128 if(!inOuterFunction) { 1129 return false; 1130 } 1131 if(node instanceof JoinPredecessor) { 1132 joinPredecessors.push((JoinPredecessor)node); 1133 } 1134 return inOuterFunction; 1135 } 1136 1137 @Override 1138 public boolean enterFunctionNode(final FunctionNode fn) { 1139 if(compiler.isOnDemandCompilation()) { 1140 // Only calculate nested function local variable types if we're doing eager compilation 1141 return false; 1142 } 1143 inOuterFunction = false; 1144 return true; 1145 } 1146 1147 @SuppressWarnings("fallthrough") 1148 @Override 1149 public Node leaveBinaryNode(final BinaryNode binaryNode) { 1150 if(binaryNode.isComparison()) { 1151 final Expression lhs = binaryNode.lhs(); 1152 final Expression rhs = binaryNode.rhs(); 1153 1154 Type cmpWidest = Type.widest(lhs.getType(), rhs.getType()); 1155 boolean newRuntimeNode = false, finalized = false; 1156 final TokenType tt = binaryNode.tokenType(); 1157 switch (tt) { 1158 case EQ_STRICT: 1159 case NE_STRICT: 1160 // Specialize comparison with undefined 1161 final Expression undefinedNode = createIsUndefined(binaryNode, lhs, rhs, 1162 tt == TokenType.EQ_STRICT ? Request.IS_UNDEFINED : Request.IS_NOT_UNDEFINED); 1163 if(undefinedNode != binaryNode) { 1164 return undefinedNode; 1165 } 1166 // Specialize comparison of boolean with non-boolean 1167 if (lhs.getType().isBoolean() != rhs.getType().isBoolean()) { 1168 newRuntimeNode = true; 1169 cmpWidest = Type.OBJECT; 1170 finalized = true; 1171 } 1172 // fallthrough 1173 default: 1174 if (newRuntimeNode || cmpWidest.isObject()) { 1175 return new RuntimeNode(binaryNode).setIsFinal(finalized); 1176 } 1177 } 1178 } else if(binaryNode.isOptimisticUndecidedType()) { 1179 // At this point, we can assign a static type to the optimistic binary ADD operator as now we know 1180 // the types of its operands. 1181 return binaryNode.decideType(); 1182 } 1183 return binaryNode; 1184 } 1185 1186 @Override 1187 protected Node leaveDefault(final Node node) { 1188 if(node instanceof JoinPredecessor) { 1189 final JoinPredecessor original = joinPredecessors.pop(); 1190 assert original.getClass() == node.getClass() : original.getClass().getName() + "!=" + node.getClass().getName(); 1191 return (Node)setLocalVariableConversion(original, (JoinPredecessor)node); 1192 } 1193 return node; 1194 } 1195 1196 @Override 1197 public Node leaveBlock(final Block block) { 1198 if(inOuterFunction && syntheticReturn != null && lc.isFunctionBody()) { 1199 final ArrayList<Statement> stmts = new ArrayList<>(block.getStatements()); 1200 stmts.add((ReturnNode)syntheticReturn.accept(this)); 1201 return block.setStatements(lc, stmts); 1202 } 1203 return super.leaveBlock(block); 1204 } 1205 1206 @Override 1207 public Node leaveFunctionNode(final FunctionNode nestedFunctionNode) { 1208 inOuterFunction = true; 1209 final FunctionNode newNestedFunction = (FunctionNode)nestedFunctionNode.accept( 1210 new LocalVariableTypesCalculator(compiler)); 1211 lc.replace(nestedFunctionNode, newNestedFunction); 1212 return newNestedFunction; 1213 } 1214 1215 @Override 1216 public Node leaveIdentNode(final IdentNode identNode) { 1217 final IdentNode original = (IdentNode)joinPredecessors.pop(); 1218 final Symbol symbol = identNode.getSymbol(); 1219 if(symbol == null) { 1220 assert identNode.isPropertyName(); 1221 return identNode; 1222 } else if(symbol.hasSlot()) { 1223 assert !symbol.isScope() || symbol.isParam(); // Only params can be slotted and scoped. 1224 assert original.getName().equals(identNode.getName()); 1225 final LvarType lvarType = identifierLvarTypes.remove(original); 1226 if(lvarType != null) { 1227 return setLocalVariableConversion(original, identNode.setType(lvarType.type)); 1228 } 1229 // If there's no type, then the identifier must've been in unreachable code. In that case, it can't 1230 // have assigned conversions either. 1231 assert localVariableConversions.get(original) == null; 1232 } else { 1233 assert identIsDeadAndHasNoLiveConversions(original); 1234 } 1235 return identNode; 1236 } 1237 1238 @Override 1239 public Node leaveLiteralNode(final LiteralNode<?> literalNode) { 1240 //for e.g. ArrayLiteralNodes the initial types may have been narrowed due to the 1241 //introduction of optimistic behavior - hence ensure that all literal nodes are 1242 //reinitialized 1243 return literalNode.initialize(lc); 1244 } 1245 1246 @Override 1247 public Node leaveRuntimeNode(final RuntimeNode runtimeNode) { 1248 final Request request = runtimeNode.getRequest(); 1249 final boolean isEqStrict = request == Request.EQ_STRICT; 1250 if(isEqStrict || request == Request.NE_STRICT) { 1251 return createIsUndefined(runtimeNode, runtimeNode.getArgs().get(0), runtimeNode.getArgs().get(1), 1252 isEqStrict ? Request.IS_UNDEFINED : Request.IS_NOT_UNDEFINED); 1253 } 1254 return runtimeNode; 1255 } 1256 1257 @SuppressWarnings("unchecked") 1258 private <T extends JoinPredecessor> T setLocalVariableConversion(final JoinPredecessor original, final T jp) { 1259 // NOTE: can't use Map.remove() as our copy-on-write AST semantics means some nodes appear twice (in 1260 // finally blocks), so we need to be able to access conversions for them multiple times. 1261 return (T)jp.setLocalVariableConversion(lc, localVariableConversions.get(original)); 1262 } 1263 }; 1264 1265 newFunction = newFunction.setBody(lc, (Block)newFunction.getBody().accept(applyChangesVisitor)); 1266 newFunction = newFunction.setReturnType(lc, returnType); 1267 1268 1269 newFunction = newFunction.setState(lc, CompilationState.LOCAL_VARIABLE_TYPES_CALCULATED); 1270 newFunction = newFunction.setParameters(lc, newFunction.visitParameters(applyChangesVisitor)); 1271 return newFunction; 1272 } 1273 1274 private static Expression createIsUndefined(final Expression parent, final Expression lhs, final Expression rhs, final Request request) { 1275 if (isUndefinedIdent(lhs) || isUndefinedIdent(rhs)) { 1276 return new RuntimeNode(parent, request, lhs, rhs); 1277 } 1278 return parent; 1279 } 1280 1281 private static boolean isUndefinedIdent(final Expression expr) { 1282 return expr instanceof IdentNode && "undefined".equals(((IdentNode)expr).getName()); 1283 } 1284 1285 private boolean identIsDeadAndHasNoLiveConversions(final IdentNode identNode) { 1286 final LocalVariableConversion conv = localVariableConversions.get(identNode); 1287 return conv == null || !conv.isLive(); 1288 } 1289 1290 private void onAssignment(final IdentNode identNode, final Expression rhs) { 1291 onAssignment(identNode, toLvarType(getType(rhs))); 1292 } 1293 1294 private void onAssignment(final IdentNode identNode, final LvarType type) { 1295 final Symbol symbol = identNode.getSymbol(); 1296 assert symbol != null : identNode.getName(); 1297 if(!symbol.isBytecodeLocal()) { 1298 return; 1299 } 1300 assert type != null; 1301 final LvarType finalType; 1302 if(type == LvarType.UNDEFINED && getLocalVariableType(symbol) != LvarType.UNDEFINED) { 1303 // Explicit assignment of a known undefined local variable to a local variable that is not undefined will 1304 // materialize that undefined in the assignment target. Note that assigning known undefined to known 1305 // undefined will *not* initialize the variable, e.g. "var x; var y = x;" compiles to no-op. 1306 finalType = LvarType.OBJECT; 1307 symbol.setFlag(Symbol.HAS_OBJECT_VALUE); 1308 } else { 1309 finalType = type; 1310 } 1311 setType(symbol, finalType); 1312 // Explicit assignment of an undefined value. Make sure the variable can store an object 1313 // TODO: if we communicated the fact to codegen with a flag on the IdentNode that the value was already 1314 // undefined before the assignment, we could just ignore it. In general, we could ignore an assignment if we 1315 // know that the value assigned is the same as the current value of the variable, but we'd need constant 1316 // propagation for that. 1317 setIdentifierLvarType(identNode, finalType); 1318 // For purposes of type calculation, we consider an assignment to a local variable to be followed by 1319 // the catch nodes of the current (if any) try block. This will effectively enforce that narrower 1320 // assignments to a local variable in a try block will also have to store a widened value as well. Code 1321 // within the try block will be able to keep loading the narrower value, but after the try block only 1322 // the widest value will remain live. 1323 // Rationale for this is that if there's an use for that variable in any of the catch blocks, or 1324 // following the catch blocks, they must use the widest type. 1325 // Example: 1326 /* 1327 Originally: 1328 =========== 1329 var x; 1330 try { 1331 x = 1; <-- stores into int slot for x 1332 f(x); <-- loads the int slot for x 1333 x = 3.14 <-- stores into the double slot for x 1334 f(x); <-- loads the double slot for x 1335 x = 1; <-- stores into int slot for x 1336 f(x); <-- loads the int slot for x 1337 } finally { 1338 f(x); <-- loads the double slot for x, but can be reached by a path where x is int, so we need 1339 to go back and ensure that double values are also always stored along with int 1340 values. 1341 } 1342 1343 After correction: 1344 ================= 1345 1346 var x; 1347 try { 1348 x = 1; <-- stores into both int and double slots for x 1349 f(x); <-- loads the int slot for x 1350 x = 3.14 <-- stores into the double slot for x 1351 f(x); <-- loads the double slot for x 1352 x = 1; <-- stores into both int and double slots for x 1353 f(x); <-- loads the int slot for x 1354 } finally { 1355 f(x); <-- loads the double slot for x 1356 } 1357 */ 1358 jumpToCatchBlock(identNode); 1359 } 1360 1361 private void onSelfAssignment(final IdentNode identNode, final Expression assignment) { 1362 final Symbol symbol = identNode.getSymbol(); 1363 assert symbol != null : identNode.getName(); 1364 if(!symbol.isBytecodeLocal()) { 1365 return; 1366 } 1367 final LvarType type = toLvarType(getType(assignment)); 1368 // Self-assignment never produce either a boolean or undefined 1369 assert type != null && type != LvarType.UNDEFINED && type != LvarType.BOOLEAN; 1370 setType(symbol, type); 1371 jumpToCatchBlock(identNode); 1372 } 1373 1374 private void resetJoinPoint(final Label label) { 1375 jumpTargets.remove(label); 1376 } 1377 1378 private void setCompilerConstantAsObject(final FunctionNode functionNode, final CompilerConstants cc) { 1379 final Symbol symbol = getCompilerConstantSymbol(functionNode, cc); 1380 setType(symbol, LvarType.OBJECT); 1381 // never mark compiler constants as dead 1382 symbolIsUsed(symbol); 1383 } 1384 1385 private static Symbol getCompilerConstantSymbol(final FunctionNode functionNode, final CompilerConstants cc) { 1386 return functionNode.getBody().getExistingSymbol(cc.symbolName()); 1387 } 1388 1389 private void setConversion(final JoinPredecessor node, final Map<Symbol, LvarType> branchLvarTypes, final Map<Symbol, LvarType> joinLvarTypes) { 1390 if(node == null) { 1391 return; 1392 } 1393 if(branchLvarTypes.isEmpty() || joinLvarTypes.isEmpty()) { 1394 localVariableConversions.remove(node); 1395 } 1396 1397 LocalVariableConversion conversion = null; 1398 if(node instanceof IdentNode) { 1399 // conversions on variable assignment in try block are special cases, as they only apply to the variable 1400 // being assigned and all other conversions should be ignored. 1401 final Symbol symbol = ((IdentNode)node).getSymbol(); 1402 conversion = createConversion(symbol, branchLvarTypes.get(symbol), joinLvarTypes, null); 1403 } else { 1404 for(final Map.Entry<Symbol, LvarType> entry: branchLvarTypes.entrySet()) { 1405 final Symbol symbol = entry.getKey(); 1406 final LvarType branchLvarType = entry.getValue(); 1407 conversion = createConversion(symbol, branchLvarType, joinLvarTypes, conversion); 1408 } 1409 } 1410 if(conversion != null) { 1411 localVariableConversions.put(node, conversion); 1412 } else { 1413 localVariableConversions.remove(node); 1414 } 1415 } 1416 1417 private void setIdentifierLvarType(final IdentNode identNode, final LvarType type) { 1418 assert type != null; 1419 identifierLvarTypes.put(identNode, type); 1420 } 1421 1422 /** 1423 * Marks a local variable as having a specific type from this point onward. Invoked by stores to local variables. 1424 * @param symbol the symbol representing the variable 1425 * @param type the type 1426 */ 1427 @SuppressWarnings("unused") 1428 private void setType(final Symbol symbol, final LvarType type) { 1429 if(getLocalVariableTypeOrNull(symbol) == type) { 1430 return; 1431 } 1432 assert symbol.hasSlot(); 1433 assert !symbol.isGlobal(); 1434 localVariableTypes = localVariableTypes.isEmpty() ? new IdentityHashMap<Symbol, LvarType>() : cloneMap(localVariableTypes); 1435 localVariableTypes.put(symbol, type); 1436 } 1437 1438 /** 1439 * Set a flag in the symbol marking it as needing to be able to store a value of a particular type. Every symbol for 1440 * a local variable will be assigned between 1 and 6 local variable slots for storing all types it is known to need 1441 * to store. 1442 * @param symbol the symbol 1443 */ 1444 private void symbolIsUsed(final Symbol symbol) { 1445 symbolIsUsed(symbol, getLocalVariableType(symbol)); 1446 } 1447 1448 private Type getType(final Expression expr) { 1449 return expr.getType(getSymbolToType()); 1450 } 1451 1452 private Function<Symbol, Type> getSymbolToType() { 1453 // BinaryNode uses identity of the function to cache type calculations. Therefore, we must use different 1454 // function instances for different localVariableTypes instances. 1455 if(symbolToType.isStale()) { 1456 symbolToType = new SymbolToType(); 1457 } 1458 return symbolToType; 1459 } 1460 1461 private class SymbolToType implements Function<Symbol, Type> { 1462 private final Object boundTypes = localVariableTypes; 1463 @Override 1464 public Type apply(final Symbol t) { 1465 return getLocalVariableType(t).type; 1466 } 1467 1468 boolean isStale() { 1469 return boundTypes != localVariableTypes; 1470 } 1471 } 1472} 1473