LocalVariableTypesCalculator.java revision 1014:2c5ba6bd48a7
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            final JoinPredecessorExpression iterable = forNode.getModify();
555            iterable.accept(this);
556            enterTestFirstLoop(forNode, null, init,
557                    // If we're iterating over property names, and we can discern from the runtime environment
558                    // of the compilation that the object being iterated over must use strings for property
559                    // names (e.g., it is a native JS object or array), then we'll not bother trying to treat
560                    // the property names optimistically.
561                    !forNode.isForEach() && compiler.hasStringPropertyIterator(iterable.getExpression()));
562        } else {
563            if(init != null) {
564                init.accept(this);
565            }
566            enterTestFirstLoop(forNode, forNode.getModify(), null, false);
567        }
568        return false;
569    }
570
571    @Override
572    public boolean enterFunctionNode(final FunctionNode functionNode) {
573        if(alreadyEnteredTopLevelFunction) {
574            return false;
575        }
576        int pos = 0;
577        if(!functionNode.isVarArg()) {
578            for (final IdentNode param : functionNode.getParameters()) {
579                final Symbol symbol = param.getSymbol();
580                // Parameter is not necessarily bytecode local as it can be scoped due to nested context use, but it
581                // must have a slot if we aren't in a function with vararg signature.
582                assert symbol.hasSlot();
583                final Type callSiteParamType = compiler.getParamType(functionNode, pos);
584                final LvarType paramType = callSiteParamType == null ? LvarType.OBJECT : toLvarType(callSiteParamType);
585                setType(symbol, paramType);
586                // Make sure parameter slot for its incoming value is not marked dead. NOTE: this is a heuristic. Right
587                // now, CodeGenerator.expandParameters() relies on the fact that every parameter's final slot width will
588                // be at least the same as incoming width, therefore even if a parameter is never read, we'll still keep
589                // its slot.
590                symbolIsUsed(symbol);
591                setIdentifierLvarType(param, paramType);
592                pos++;
593            }
594        }
595        setCompilerConstantAsObject(functionNode, CompilerConstants.THIS);
596
597        // TODO: coarse-grained. If we wanted to solve it completely precisely,
598        // we'd also need to push/pop its type when handling WithNode (so that
599        // it can go back to undefined after a 'with' block.
600        if(functionNode.hasScopeBlock() || functionNode.needsParentScope()) {
601            setCompilerConstantAsObject(functionNode, CompilerConstants.SCOPE);
602        }
603        if(functionNode.needsCallee()) {
604            setCompilerConstantAsObject(functionNode, CompilerConstants.CALLEE);
605        }
606        if(functionNode.needsArguments()) {
607            setCompilerConstantAsObject(functionNode, CompilerConstants.ARGUMENTS);
608        }
609
610        alreadyEnteredTopLevelFunction = true;
611        return true;
612    }
613
614    @Override
615    public boolean enterIdentNode(final IdentNode identNode) {
616        final Symbol symbol = identNode.getSymbol();
617        if(symbol.isBytecodeLocal()) {
618            symbolIsUsed(symbol);
619            setIdentifierLvarType(identNode, getLocalVariableType(symbol));
620        }
621        return false;
622    }
623
624    @Override
625    public boolean enterIfNode(final IfNode ifNode) {
626        if(!reachable) {
627            return false;
628        }
629
630        final Expression test = ifNode.getTest();
631        final Block pass = ifNode.getPass();
632        final Block fail = ifNode.getFail();
633
634        test.accept(this);
635
636        final Map<Symbol, LvarType> afterTestLvarTypes = localVariableTypes;
637        if(!isAlwaysFalse(test)) {
638            pass.accept(this);
639        }
640        final Map<Symbol, LvarType> passLvarTypes = localVariableTypes;
641        final boolean reachableFromPass = reachable;
642
643        reachable = true;
644        localVariableTypes = afterTestLvarTypes;
645        if(!isAlwaysTrue(test) && fail != null) {
646            fail.accept(this);
647            final boolean reachableFromFail = reachable;
648            reachable |= reachableFromPass;
649            if(!reachable) {
650                return false;
651            }
652
653            if(reachableFromFail) {
654                if(reachableFromPass) {
655                    final Map<Symbol, LvarType> failLvarTypes = localVariableTypes;
656                    localVariableTypes = getUnionTypes(passLvarTypes, failLvarTypes);
657                    setConversion(pass, passLvarTypes, localVariableTypes);
658                    setConversion(fail, failLvarTypes, localVariableTypes);
659                }
660                return false;
661            }
662        }
663
664        if(reachableFromPass) {
665            localVariableTypes = getUnionTypes(afterTestLvarTypes, passLvarTypes);
666            // IfNode itself is associated with conversions that might need to be performed after the test if there's no
667            // else branch. E.g.
668            // if(x = 1, cond) { x = 1.0 } must widen "x = 1" to a double.
669            setConversion(pass, passLvarTypes, localVariableTypes);
670            setConversion(ifNode, afterTestLvarTypes, localVariableTypes);
671        } else {
672            localVariableTypes = afterTestLvarTypes;
673        }
674
675        return false;
676    }
677
678    @Override
679    public boolean enterPropertyNode(final PropertyNode propertyNode) {
680        // Avoid falsely adding property keys to the control flow graph
681        if(propertyNode.getValue() != null) {
682            propertyNode.getValue().accept(this);
683        }
684        return false;
685    }
686
687    @Override
688    public boolean enterReturnNode(final ReturnNode returnNode) {
689        final Expression returnExpr = returnNode.getExpression();
690        final Type returnExprType;
691        if(returnExpr != null) {
692            returnExpr.accept(this);
693            returnExprType = getType(returnExpr);
694        } else {
695            returnExprType = Type.UNDEFINED;
696        }
697        returnType = Type.widestReturnType(returnType, returnExprType);
698        doesNotContinueSequentially();
699        return false;
700    }
701
702    @Override
703    public boolean enterSplitNode(final SplitNode splitNode) {
704        // Need to visit inside of split nodes. While it's true that they don't have local variables, we need to visit
705        // breaks, continues, and returns in them.
706        if(topSplit == null) {
707            topSplit = splitNode;
708        }
709        split = true;
710        setType(getCompilerConstantSymbol(lc.getCurrentFunction(), CompilerConstants.RETURN), LvarType.UNDEFINED);
711        return true;
712    }
713
714    @Override
715    public boolean enterSwitchNode(final SwitchNode switchNode) {
716        if(!reachable) {
717            return false;
718        }
719
720        final Expression expr = switchNode.getExpression();
721        expr.accept(this);
722
723        final List<CaseNode> cases = switchNode.getCases();
724        if(cases.isEmpty()) {
725            return false;
726        }
727
728        // Control flow is different for all-integer cases where we dispatch by switch table, and for all other cases
729        // where we do sequential comparison. Note that CaseNode objects act as join points.
730        final boolean isInteger = switchNode.isInteger();
731        final Label breakLabel = switchNode.getBreakLabel();
732        final boolean hasDefault = switchNode.getDefaultCase() != null;
733
734        boolean tagUsed = false;
735        for(final CaseNode caseNode: cases) {
736            final Expression test = caseNode.getTest();
737            if(!isInteger && test != null) {
738                test.accept(this);
739                if(!tagUsed) {
740                    symbolIsUsed(switchNode.getTag(), LvarType.OBJECT);
741                    tagUsed = true;
742                }
743            }
744            // CaseNode carries the conversions that need to be performed on its entry from the test.
745            // CodeGenerator ensures these are only emitted when arriving on the branch and not through a
746            // fallthrough.
747            jumpToLabel(caseNode, caseNode.getBody().getEntryLabel());
748        }
749        if(!hasDefault) {
750            // No default case means we can arrive at the break label without entering any cases. In that case
751            // SwitchNode will carry the conversions that need to be performed before it does that jump.
752            jumpToLabel(switchNode, breakLabel);
753        }
754
755        // All cases are arrived at through jumps
756        doesNotContinueSequentially();
757
758        Block previousBlock = null;
759        for(final CaseNode caseNode: cases) {
760            final Block body = caseNode.getBody();
761            final Label entryLabel = body.getEntryLabel();
762            if(previousBlock != null && reachable) {
763                jumpToLabel(previousBlock, entryLabel);
764            }
765            joinOnLabel(entryLabel);
766            assert reachable == true;
767            body.accept(this);
768            previousBlock = body;
769        }
770        if(previousBlock != null && reachable) {
771            jumpToLabel(previousBlock, breakLabel);
772        }
773        leaveBreakable(switchNode);
774        return false;
775    }
776
777    @Override
778    public boolean enterTernaryNode(final TernaryNode ternaryNode) {
779        final Expression test = ternaryNode.getTest();
780        final Expression trueExpr = ternaryNode.getTrueExpression();
781        final Expression falseExpr = ternaryNode.getFalseExpression();
782
783        test.accept(this);
784
785        final Map<Symbol, LvarType> testExitLvarTypes = localVariableTypes;
786        if(!isAlwaysFalse(test)) {
787            trueExpr.accept(this);
788        }
789        final Map<Symbol, LvarType> trueExitLvarTypes = localVariableTypes;
790        localVariableTypes = testExitLvarTypes;
791        if(!isAlwaysTrue(test)) {
792            falseExpr.accept(this);
793        }
794        final Map<Symbol, LvarType> falseExitLvarTypes = localVariableTypes;
795        localVariableTypes = getUnionTypes(trueExitLvarTypes, falseExitLvarTypes);
796        setConversion((JoinPredecessor)trueExpr, trueExitLvarTypes, localVariableTypes);
797        setConversion((JoinPredecessor)falseExpr, falseExitLvarTypes, localVariableTypes);
798        return false;
799    }
800
801    private void enterTestFirstLoop(final LoopNode loopNode, final JoinPredecessorExpression modify,
802            final Expression iteratorValues, final boolean iteratorValuesAreObject) {
803        final JoinPredecessorExpression test = loopNode.getTest();
804        if(isAlwaysFalse(test)) {
805            test.accept(this);
806            return;
807        }
808
809        final Label continueLabel = loopNode.getContinueLabel();
810        final Label breakLabel = loopNode.getBreakLabel();
811
812        final Label repeatLabel = modify == null ? continueLabel : new Label("");
813        final Map<Symbol, LvarType> beforeLoopTypes = localVariableTypes;
814        for(;;) {
815            jumpToLabel(loopNode, repeatLabel, beforeLoopTypes);
816            final Map<Symbol, LvarType> beforeRepeatTypes = localVariableTypes;
817            if(test != null) {
818                test.accept(this);
819            }
820            if(!isAlwaysTrue(test)) {
821                jumpToLabel(test, breakLabel);
822            }
823            if(iteratorValues instanceof IdentNode) {
824                final IdentNode ident = (IdentNode)iteratorValues;
825                // Receives iterator values; the optimistic type of the iterator values is tracked on the
826                // identifier, but we override optimism if it's known that the object being iterated over will
827                // never have primitive property names.
828                onAssignment(ident, iteratorValuesAreObject ? LvarType.OBJECT :
829                    toLvarType(compiler.getOptimisticType(ident)));
830            }
831            final Block body = loopNode.getBody();
832            body.accept(this);
833            if(reachable) {
834                jumpToLabel(body, continueLabel);
835            }
836            joinOnLabel(continueLabel);
837            if(!reachable) {
838                break;
839            }
840            if(modify != null) {
841                modify.accept(this);
842                jumpToLabel(modify, repeatLabel);
843                joinOnLabel(repeatLabel);
844            }
845            if(localVariableTypes.equals(beforeRepeatTypes)) {
846                break;
847            }
848            // Reset the join points and repeat the analysis
849            resetJoinPoint(continueLabel);
850            resetJoinPoint(breakLabel);
851            resetJoinPoint(repeatLabel);
852        }
853
854        if(isAlwaysTrue(test) && iteratorValues == null) {
855            doesNotContinueSequentially();
856        }
857
858        leaveBreakable(loopNode);
859    }
860
861    @Override
862    public boolean enterThrowNode(final ThrowNode throwNode) {
863        if(!reachable) {
864            return false;
865        }
866
867        throwNode.getExpression().accept(this);
868        jumpToCatchBlock(throwNode);
869        doesNotContinueSequentially();
870        return false;
871    }
872
873    @Override
874    public boolean enterTryNode(final TryNode tryNode) {
875        if(!reachable) {
876            return false;
877        }
878
879        // This is the label for the join point at the entry of the catch blocks.
880        final Label catchLabel = new Label("");
881        catchLabels.push(catchLabel);
882
883        // Presume that even the start of the try block can immediately go to the catch
884        jumpToLabel(tryNode, catchLabel);
885
886        final Block body = tryNode.getBody();
887        body.accept(this);
888        catchLabels.pop();
889
890        // Final exit label for the whole try/catch construct (after the try block and after all catches).
891        final Label endLabel = new Label("");
892
893        boolean canExit = false;
894        if(reachable) {
895            jumpToLabel(body, endLabel);
896            canExit = true;
897        }
898        doesNotContinueSequentially();
899
900        joinOnLabel(catchLabel);
901        for(final CatchNode catchNode: tryNode.getCatches()) {
902            final IdentNode exception = catchNode.getException();
903            onAssignment(exception, LvarType.OBJECT);
904            final Expression condition = catchNode.getExceptionCondition();
905            if(condition != null) {
906                condition.accept(this);
907            }
908            final Map<Symbol, LvarType> afterConditionTypes = localVariableTypes;
909            final Block catchBody = catchNode.getBody();
910            // TODO: currently, we consider that the catch blocks are always reachable from the try block as currently
911            // we lack enough analysis to prove that no statement before a break/continue/return in the try block can
912            // throw an exception.
913            reachable = true;
914            catchBody.accept(this);
915            final Symbol exceptionSymbol = exception.getSymbol();
916            if(reachable) {
917                localVariableTypes = cloneMap(localVariableTypes);
918                localVariableTypes.remove(exceptionSymbol);
919                jumpToLabel(catchBody, endLabel);
920                canExit = true;
921            }
922            localVariableTypes = cloneMap(afterConditionTypes);
923            localVariableTypes.remove(exceptionSymbol);
924        }
925        // NOTE: if we had one or more conditional catch blocks with no unconditional catch block following them, then
926        // there will be an unconditional rethrow, so the join point can never be reached from the last
927        // conditionExpression.
928        doesNotContinueSequentially();
929
930        if(canExit) {
931            joinOnLabel(endLabel);
932        }
933
934        return false;
935    }
936
937
938    @Override
939    public boolean enterUnaryNode(final UnaryNode unaryNode) {
940        final Expression expr = unaryNode.getExpression();
941        expr.accept(this);
942
943        if(unaryNode.isSelfModifying()) {
944            if(expr instanceof IdentNode) {
945                onSelfAssignment((IdentNode)expr, unaryNode);
946            }
947        }
948        return false;
949    }
950
951    @Override
952    public boolean enterVarNode(final VarNode varNode) {
953        final Expression init = varNode.getInit();
954        if(init != null) {
955            init.accept(this);
956            onAssignment(varNode.getName(), init);
957        }
958        return false;
959    }
960
961    @Override
962    public boolean enterWhileNode(final WhileNode whileNode) {
963        if(!reachable) {
964            return false;
965        }
966        if(whileNode.isDoWhile()) {
967            enterDoWhileLoop(whileNode);
968        } else {
969            enterTestFirstLoop(whileNode, null, null, false);
970        }
971        return false;
972    }
973
974    private Map<Symbol, LvarType> getBreakTargetTypes(final BreakableNode target) {
975        // Remove symbols defined in the the blocks that are being broken out of.
976        Map<Symbol, LvarType> types = localVariableTypes;
977        for(final Iterator<LexicalContextNode> it = lc.getAllNodes(); it.hasNext();) {
978            final LexicalContextNode node = it.next();
979            if(node instanceof Block) {
980                for(final Symbol symbol: ((Block)node).getSymbols()) {
981                    if(localVariableTypes.containsKey(symbol)) {
982                        if(types == localVariableTypes) {
983                            types = cloneMap(localVariableTypes);
984                        }
985                        types.remove(symbol);
986                    }
987                }
988            }
989            if(node == target) {
990                break;
991            }
992        }
993        return types;
994    }
995
996    private LvarType getLocalVariableType(final Symbol symbol) {
997        final LvarType type = getLocalVariableTypeOrNull(symbol);
998        assert type != null;
999        return type;
1000    }
1001
1002    private LvarType getLocalVariableTypeOrNull(final Symbol symbol) {
1003        return localVariableTypes.get(symbol);
1004    }
1005
1006    private JumpTarget getOrCreateJumpTarget(final Label label) {
1007        JumpTarget jumpTarget = jumpTargets.get(label);
1008        if(jumpTarget == null) {
1009            jumpTarget = createJumpTarget(label);
1010        }
1011        return jumpTarget;
1012    }
1013
1014
1015    /**
1016     * If there's a join point associated with a label, insert the join point into the flow.
1017     * @param label the label to insert a join point for.
1018     */
1019    private void joinOnLabel(final Label label) {
1020        final JumpTarget jumpTarget = jumpTargets.remove(label);
1021        if(jumpTarget == null) {
1022            return;
1023        }
1024        assert !jumpTarget.origins.isEmpty();
1025        reachable = true;
1026        localVariableTypes = getUnionTypes(jumpTarget.types, localVariableTypes);
1027        for(final JumpOrigin jumpOrigin: jumpTarget.origins) {
1028            setConversion(jumpOrigin.node, jumpOrigin.types, localVariableTypes);
1029        }
1030    }
1031
1032    /**
1033     * If we're in a try/catch block, add an edge from the specified node to the try node's pre-catch label.
1034     */
1035    private void jumpToCatchBlock(final JoinPredecessor jumpOrigin) {
1036        final Label currentCatchLabel = catchLabels.peek();
1037        if(currentCatchLabel != null) {
1038            jumpToLabel(jumpOrigin, currentCatchLabel);
1039        }
1040    }
1041
1042    private void jumpToLabel(final JoinPredecessor jumpOrigin, final Label label) {
1043        jumpToLabel(jumpOrigin, label, localVariableTypes);
1044    }
1045
1046    private void jumpToLabel(final JoinPredecessor jumpOrigin, final Label label, final Map<Symbol, LvarType> types) {
1047        getOrCreateJumpTarget(label).addOrigin(jumpOrigin, types);
1048    }
1049
1050    @Override
1051    public Node leaveBlock(final Block block) {
1052        if(lc.isFunctionBody()) {
1053            if(reachable) {
1054                // reachable==true means we can reach the end of the function without an explicit return statement. We
1055                // need to insert a synthetic one then. This logic used to be in Lower.leaveBlock(), but Lower's
1056                // reachability analysis (through Terminal.isTerminal() flags) is not precise enough so
1057                // Lower$BlockLexicalContext.afterSetStatements will sometimes think the control flow terminates even
1058                // when it didn't. Example: function() { switch((z)) { default: {break; } throw x; } }.
1059                createSyntheticReturn(block);
1060                assert !reachable;
1061            }
1062            // We must calculate the return type here (and not in leaveFunctionNode) as it can affect the liveness of
1063            // the :return symbol and thus affect conversion type liveness calculations for it.
1064            calculateReturnType();
1065        }
1066
1067        boolean cloned = false;
1068        for(final Symbol symbol: block.getSymbols()) {
1069            // Undefine the symbol outside the block
1070            if(localVariableTypes.containsKey(symbol)) {
1071                if(!cloned) {
1072                    localVariableTypes = cloneMap(localVariableTypes);
1073                    cloned = true;
1074                }
1075                localVariableTypes.remove(symbol);
1076            }
1077
1078            if(symbol.hasSlot()) {
1079                final SymbolConversions conversions = symbolConversions.get(symbol);
1080                if(conversions != null) {
1081                    // Potentially make some currently dead types live if they're needed as a source of a type
1082                    // conversion at a join.
1083                    conversions.calculateTypeLiveness(symbol);
1084                }
1085                if(symbol.slotCount() == 0) {
1086                    // This is a local variable that is never read. It won't need a slot.
1087                    symbol.setNeedsSlot(false);
1088                }
1089            }
1090        }
1091
1092        if(reachable) {
1093            // TODO: this is totally backwards. Block should not be breakable, LabelNode should be breakable.
1094            final LabelNode labelNode = lc.getCurrentBlockLabelNode();
1095            if(labelNode != null) {
1096                jumpToLabel(labelNode, block.getBreakLabel());
1097            }
1098        }
1099        leaveBreakable(block);
1100        return block;
1101    }
1102
1103    private void calculateReturnType() {
1104        // NOTE: if return type is unknown, then the function does not explicitly return a value. Such a function under
1105        // ECMAScript rules returns Undefined, which has Type.OBJECT. We might consider an optimization in the future
1106        // where we can return void functions.
1107        if(returnType.isUnknown()) {
1108            returnType = Type.OBJECT;
1109        }
1110
1111        if(split) {
1112            // If the function is split, the ":return" symbol is used and needs a slot. Note we can't mark the return
1113            // symbol as used in enterSplitNode, as we don't know the final return type of the function earlier than
1114            // here.
1115            final Symbol retSymbol = getCompilerConstantSymbol(lc.getCurrentFunction(), CompilerConstants.RETURN);
1116            retSymbol.setHasSlotFor(returnType);
1117            retSymbol.setNeedsSlot(true);
1118        }
1119    }
1120
1121    private void createSyntheticReturn(final Block body) {
1122        final FunctionNode functionNode = lc.getCurrentFunction();
1123        final long token = functionNode.getToken();
1124        final int finish = functionNode.getFinish();
1125        final List<Statement> statements = body.getStatements();
1126        final int lineNumber = statements.isEmpty() ? functionNode.getLineNumber() : statements.get(statements.size() - 1).getLineNumber();
1127        final IdentNode returnExpr;
1128        if(functionNode.isProgram()) {
1129            returnExpr = new IdentNode(token, finish, RETURN.symbolName()).setSymbol(getCompilerConstantSymbol(functionNode, RETURN));
1130        } else {
1131            returnExpr = null;
1132        }
1133        syntheticReturn = new ReturnNode(lineNumber, token, finish, returnExpr);
1134        syntheticReturn.accept(this);
1135    }
1136
1137    /**
1138     * Leave a breakable node. If there's a join point associated with its break label (meaning there was at least one
1139     * break statement to the end of the node), insert the join point into the flow.
1140     * @param breakable the breakable node being left.
1141     */
1142    private void leaveBreakable(final BreakableNode breakable) {
1143        joinOnLabel(breakable.getBreakLabel());
1144    }
1145
1146    @Override
1147    public Node leaveFunctionNode(final FunctionNode functionNode) {
1148        // Sets the return type of the function and also performs the bottom-up pass of applying type and conversion
1149        // information to nodes as well as doing the calculation on nested functions as required.
1150        FunctionNode newFunction = functionNode;
1151        final NodeVisitor<LexicalContext> applyChangesVisitor = new NodeVisitor<LexicalContext>(new LexicalContext()) {
1152            private boolean inOuterFunction = true;
1153            private final Deque<JoinPredecessor> joinPredecessors = new ArrayDeque<>();
1154
1155            @Override
1156            protected boolean enterDefault(final Node node) {
1157                if(!inOuterFunction) {
1158                    return false;
1159                }
1160                if(node instanceof JoinPredecessor) {
1161                    joinPredecessors.push((JoinPredecessor)node);
1162                }
1163                return inOuterFunction;
1164            }
1165
1166            @Override
1167            public boolean enterFunctionNode(final FunctionNode fn) {
1168                if(compiler.isOnDemandCompilation()) {
1169                    // Only calculate nested function local variable types if we're doing eager compilation
1170                    return false;
1171                }
1172                inOuterFunction = false;
1173                return true;
1174            }
1175
1176            @SuppressWarnings("fallthrough")
1177            @Override
1178            public Node leaveBinaryNode(final BinaryNode binaryNode) {
1179                if(binaryNode.isComparison()) {
1180                    final Expression lhs = binaryNode.lhs();
1181                    final Expression rhs = binaryNode.rhs();
1182
1183                    Type cmpWidest = Type.widest(lhs.getType(), rhs.getType());
1184                    boolean newRuntimeNode = false, finalized = false;
1185                    final TokenType tt = binaryNode.tokenType();
1186                    switch (tt) {
1187                    case EQ_STRICT:
1188                    case NE_STRICT:
1189                        // Specialize comparison with undefined
1190                        final Expression undefinedNode = createIsUndefined(binaryNode, lhs, rhs,
1191                                tt == TokenType.EQ_STRICT ? Request.IS_UNDEFINED : Request.IS_NOT_UNDEFINED);
1192                        if(undefinedNode != binaryNode) {
1193                            return undefinedNode;
1194                        }
1195                        // Specialize comparison of boolean with non-boolean
1196                        if (lhs.getType().isBoolean() != rhs.getType().isBoolean()) {
1197                            newRuntimeNode = true;
1198                            cmpWidest = Type.OBJECT;
1199                            finalized = true;
1200                        }
1201                        // fallthrough
1202                    default:
1203                        if (newRuntimeNode || cmpWidest.isObject()) {
1204                            return new RuntimeNode(binaryNode).setIsFinal(finalized);
1205                        }
1206                    }
1207                } else if(binaryNode.isOptimisticUndecidedType()) {
1208                    // At this point, we can assign a static type to the optimistic binary ADD operator as now we know
1209                    // the types of its operands.
1210                    return binaryNode.decideType();
1211                }
1212                return binaryNode;
1213            }
1214
1215            @Override
1216            protected Node leaveDefault(final Node node) {
1217                if(node instanceof JoinPredecessor) {
1218                    final JoinPredecessor original = joinPredecessors.pop();
1219                    assert original.getClass() == node.getClass() : original.getClass().getName() + "!=" + node.getClass().getName();
1220                    return (Node)setLocalVariableConversion(original, (JoinPredecessor)node);
1221                }
1222                return node;
1223            }
1224
1225            @Override
1226            public Node leaveBlock(final Block block) {
1227                if(inOuterFunction && syntheticReturn != null && lc.isFunctionBody()) {
1228                    final ArrayList<Statement> stmts = new ArrayList<>(block.getStatements());
1229                    stmts.add((ReturnNode)syntheticReturn.accept(this));
1230                    return block.setStatements(lc, stmts);
1231                }
1232                return super.leaveBlock(block);
1233            }
1234
1235            @Override
1236            public Node leaveFunctionNode(final FunctionNode nestedFunctionNode) {
1237                inOuterFunction = true;
1238                final FunctionNode newNestedFunction = (FunctionNode)nestedFunctionNode.accept(
1239                        new LocalVariableTypesCalculator(compiler));
1240                lc.replace(nestedFunctionNode, newNestedFunction);
1241                return newNestedFunction;
1242            }
1243
1244            @Override
1245            public Node leaveIdentNode(final IdentNode identNode) {
1246                final IdentNode original = (IdentNode)joinPredecessors.pop();
1247                final Symbol symbol = identNode.getSymbol();
1248                if(symbol == null) {
1249                    assert identNode.isPropertyName();
1250                    return identNode;
1251                } else if(symbol.hasSlot()) {
1252                    assert !symbol.isScope() || symbol.isParam(); // Only params can be slotted and scoped.
1253                    assert original.getName().equals(identNode.getName());
1254                    final LvarType lvarType = identifierLvarTypes.remove(original);
1255                    if(lvarType != null) {
1256                        return setLocalVariableConversion(original, identNode.setType(lvarType.type));
1257                    }
1258                    // If there's no type, then the identifier must've been in unreachable code. In that case, it can't
1259                    // have assigned conversions either.
1260                    assert localVariableConversions.get(original) == null;
1261                } else {
1262                    assert identIsDeadAndHasNoLiveConversions(original);
1263                }
1264                return identNode;
1265            }
1266
1267            @Override
1268            public Node leaveLiteralNode(final LiteralNode<?> literalNode) {
1269                //for e.g. ArrayLiteralNodes the initial types may have been narrowed due to the
1270                //introduction of optimistic behavior - hence ensure that all literal nodes are
1271                //reinitialized
1272                return literalNode.initialize(lc);
1273            }
1274
1275            @Override
1276            public Node leaveRuntimeNode(final RuntimeNode runtimeNode) {
1277                final Request request = runtimeNode.getRequest();
1278                final boolean isEqStrict = request == Request.EQ_STRICT;
1279                if(isEqStrict || request == Request.NE_STRICT) {
1280                    return createIsUndefined(runtimeNode, runtimeNode.getArgs().get(0), runtimeNode.getArgs().get(1),
1281                            isEqStrict ? Request.IS_UNDEFINED : Request.IS_NOT_UNDEFINED);
1282                }
1283                return runtimeNode;
1284            }
1285
1286            @SuppressWarnings("unchecked")
1287            private <T extends JoinPredecessor> T setLocalVariableConversion(final JoinPredecessor original, final T jp) {
1288                // NOTE: can't use Map.remove() as our copy-on-write AST semantics means some nodes appear twice (in
1289                // finally blocks), so we need to be able to access conversions for them multiple times.
1290                return (T)jp.setLocalVariableConversion(lc, localVariableConversions.get(original));
1291            }
1292        };
1293
1294        newFunction = newFunction.setBody(lc, (Block)newFunction.getBody().accept(applyChangesVisitor));
1295        newFunction = newFunction.setReturnType(lc, returnType);
1296
1297
1298        newFunction = newFunction.setState(lc, CompilationState.LOCAL_VARIABLE_TYPES_CALCULATED);
1299        newFunction = newFunction.setParameters(lc, newFunction.visitParameters(applyChangesVisitor));
1300        return newFunction;
1301    }
1302
1303    private static Expression createIsUndefined(final Expression parent, final Expression lhs, final Expression rhs, final Request request) {
1304        if (isUndefinedIdent(lhs) || isUndefinedIdent(rhs)) {
1305            return new RuntimeNode(parent, request, lhs, rhs);
1306        }
1307        return parent;
1308    }
1309
1310    private static boolean isUndefinedIdent(final Expression expr) {
1311        return expr instanceof IdentNode && "undefined".equals(((IdentNode)expr).getName());
1312    }
1313
1314    private boolean identIsDeadAndHasNoLiveConversions(final IdentNode identNode) {
1315        final LocalVariableConversion conv = localVariableConversions.get(identNode);
1316        return conv == null || !conv.isLive();
1317    }
1318
1319    private void onAssignment(final IdentNode identNode, final Expression rhs) {
1320        onAssignment(identNode, toLvarType(getType(rhs)));
1321    }
1322
1323    private void onAssignment(final IdentNode identNode, final LvarType type) {
1324        final Symbol symbol = identNode.getSymbol();
1325        assert symbol != null : identNode.getName();
1326        if(!symbol.isBytecodeLocal()) {
1327            return;
1328        }
1329        assert type != null;
1330        final LvarType finalType;
1331        if(type == LvarType.UNDEFINED && getLocalVariableType(symbol) != LvarType.UNDEFINED) {
1332            // Explicit assignment of a known undefined local variable to a local variable that is not undefined will
1333            // materialize that undefined in the assignment target. Note that assigning known undefined to known
1334            // undefined will *not* initialize the variable, e.g. "var x; var y = x;" compiles to no-op.
1335            finalType = LvarType.OBJECT;
1336            symbol.setFlag(Symbol.HAS_OBJECT_VALUE);
1337        } else {
1338            finalType = type;
1339        }
1340        setType(symbol, finalType);
1341        // Explicit assignment of an undefined value. Make sure the variable can store an object
1342        // TODO: if we communicated the fact to codegen with a flag on the IdentNode that the value was already
1343        // undefined before the assignment, we could just ignore it. In general, we could ignore an assignment if we
1344        // know that the value assigned is the same as the current value of the variable, but we'd need constant
1345        // propagation for that.
1346        setIdentifierLvarType(identNode, finalType);
1347        // For purposes of type calculation, we consider an assignment to a local variable to be followed by
1348        // the catch nodes of the current (if any) try block. This will effectively enforce that narrower
1349        // assignments to a local variable in a try block will also have to store a widened value as well. Code
1350        // within the try block will be able to keep loading the narrower value, but after the try block only
1351        // the widest value will remain live.
1352        // Rationale for this is that if there's an use for that variable in any of the catch blocks, or
1353        // following the catch blocks, they must use the widest type.
1354        // Example:
1355        /*
1356            Originally:
1357            ===========
1358            var x;
1359            try {
1360              x = 1; <-- stores into int slot for x
1361              f(x); <-- loads the int slot for x
1362              x = 3.14 <-- stores into the double slot for x
1363              f(x); <-- loads the double slot for x
1364              x = 1; <-- stores into int slot for x
1365              f(x); <-- loads the int slot for x
1366            } finally {
1367              f(x); <-- loads the double slot for x, but can be reached by a path where x is int, so we need
1368                           to go back and ensure that double values are also always stored along with int
1369                           values.
1370            }
1371
1372            After correction:
1373            =================
1374
1375            var x;
1376            try {
1377              x = 1; <-- stores into both int and double slots for x
1378              f(x); <-- loads the int slot for x
1379              x = 3.14 <-- stores into the double slot for x
1380              f(x); <-- loads the double slot for x
1381              x = 1; <-- stores into both int and double slots for x
1382              f(x); <-- loads the int slot for x
1383            } finally {
1384              f(x); <-- loads the double slot for x
1385            }
1386         */
1387        jumpToCatchBlock(identNode);
1388    }
1389
1390    private void onSelfAssignment(final IdentNode identNode, final Expression assignment) {
1391        final Symbol symbol = identNode.getSymbol();
1392        assert symbol != null : identNode.getName();
1393        if(!symbol.isBytecodeLocal()) {
1394            return;
1395        }
1396        final LvarType type = toLvarType(getType(assignment));
1397        // Self-assignment never produce either a boolean or undefined
1398        assert type != null && type != LvarType.UNDEFINED && type != LvarType.BOOLEAN;
1399        setType(symbol, type);
1400        jumpToCatchBlock(identNode);
1401    }
1402
1403    private void resetJoinPoint(final Label label) {
1404        jumpTargets.remove(label);
1405    }
1406
1407    private void setCompilerConstantAsObject(final FunctionNode functionNode, final CompilerConstants cc) {
1408        final Symbol symbol = getCompilerConstantSymbol(functionNode, cc);
1409        setType(symbol, LvarType.OBJECT);
1410        // never mark compiler constants as dead
1411        symbolIsUsed(symbol);
1412    }
1413
1414    private static Symbol getCompilerConstantSymbol(final FunctionNode functionNode, final CompilerConstants cc) {
1415        return functionNode.getBody().getExistingSymbol(cc.symbolName());
1416    }
1417
1418    private void setConversion(final JoinPredecessor node, final Map<Symbol, LvarType> branchLvarTypes, final Map<Symbol, LvarType> joinLvarTypes) {
1419        if(node == null) {
1420            return;
1421        }
1422        if(branchLvarTypes.isEmpty() || joinLvarTypes.isEmpty()) {
1423            localVariableConversions.remove(node);
1424        }
1425
1426        LocalVariableConversion conversion = null;
1427        if(node instanceof IdentNode) {
1428            // conversions on variable assignment in try block are special cases, as they only apply to the variable
1429            // being assigned and all other conversions should be ignored.
1430            final Symbol symbol = ((IdentNode)node).getSymbol();
1431            conversion = createConversion(symbol, branchLvarTypes.get(symbol), joinLvarTypes, null);
1432        } else {
1433            for(final Map.Entry<Symbol, LvarType> entry: branchLvarTypes.entrySet()) {
1434                final Symbol symbol = entry.getKey();
1435                final LvarType branchLvarType = entry.getValue();
1436                conversion = createConversion(symbol, branchLvarType, joinLvarTypes, conversion);
1437            }
1438        }
1439        if(conversion != null) {
1440            localVariableConversions.put(node, conversion);
1441        } else {
1442            localVariableConversions.remove(node);
1443        }
1444    }
1445
1446    private void setIdentifierLvarType(final IdentNode identNode, final LvarType type) {
1447        assert type != null;
1448        identifierLvarTypes.put(identNode, type);
1449    }
1450
1451    /**
1452     * Marks a local variable as having a specific type from this point onward. Invoked by stores to local variables.
1453     * @param symbol the symbol representing the variable
1454     * @param type the type
1455     */
1456    private void setType(final Symbol symbol, final LvarType type) {
1457        if(getLocalVariableTypeOrNull(symbol) == type) {
1458            return;
1459        }
1460        assert symbol.hasSlot();
1461        assert !symbol.isGlobal();
1462        localVariableTypes = localVariableTypes.isEmpty() ? new IdentityHashMap<Symbol, LvarType>() : cloneMap(localVariableTypes);
1463        localVariableTypes.put(symbol, type);
1464    }
1465
1466    /**
1467     * Set a flag in the symbol marking it as needing to be able to store a value of a particular type. Every symbol for
1468     * a local variable will be assigned between 1 and 6 local variable slots for storing all types it is known to need
1469     * to store.
1470     * @param symbol the symbol
1471     */
1472    private void symbolIsUsed(final Symbol symbol) {
1473        symbolIsUsed(symbol, getLocalVariableType(symbol));
1474    }
1475
1476    private Type getType(final Expression expr) {
1477        return expr.getType(getSymbolToType());
1478    }
1479
1480    private Function<Symbol, Type> getSymbolToType() {
1481        // BinaryNode uses identity of the function to cache type calculations. Therefore, we must use different
1482        // function instances for different localVariableTypes instances.
1483        if(symbolToType.isStale()) {
1484            symbolToType = new SymbolToType();
1485        }
1486        return symbolToType;
1487    }
1488
1489    private class SymbolToType implements Function<Symbol, Type> {
1490        private final Object boundTypes = localVariableTypes;
1491        @Override
1492        public Type apply(final Symbol t) {
1493            return getLocalVariableType(t).type;
1494        }
1495
1496        boolean isStale() {
1497            return boundTypes != localVariableTypes;
1498        }
1499    }
1500}
1501