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