Debian Codegraph @

src/com/google/javascript/jscomp/DeadAssignmentsElimination.java

raw symbols SCIP
1 /*
2 * Copyright 2008 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp;
18
19 import com.google.common.base.Preconditions;
20 import com.google.common.base.Predicate;
21 import com.google.common.base.Predicates;
22 import com.google.javascript.jscomp.ControlFlowGraph.Branch;
23 import com.google.javascript.jscomp.DataFlowAnalysis.FlowState;
24 import com.google.javascript.jscomp.LiveVariablesAnalysis.LiveVariableLattice;
25 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
26 import com.google.javascript.jscomp.NodeTraversal.ScopedCallback;
27 import com.google.javascript.jscomp.Scope.Var;
28 import com.google.javascript.jscomp.graph.DiGraph.DiGraphNode;
29 import com.google.javascript.rhino.IR;
30 import com.google.javascript.rhino.Node;
31 import com.google.javascript.rhino.Token;
32
33 /**
34 * Removes local variable assignments that are useless based on information from
35 * {@link LiveVariablesAnalysis}. If there is an assignment to variable
36 * {@code x} and {@code x} is dead after this assignment, we know that the
37 * current content of {@code x} will not be read and this assignment is useless.
38 *
39 */
40 class DeadAssignmentsElimination extends AbstractPostOrderCallback implements
41 CompilerPass, ScopedCallback {
42
43 private final AbstractCompiler compiler;
44 private LiveVariablesAnalysis liveness;
45
46 // Matches all assignment operators and increment/decrement operators.
47 // Does *not* match VAR initialization, since RemoveUnusedVariables
48 // will already remove variables that are initialized but unused.
49 private static final Predicate<Node> matchRemovableAssigns =
50 new Predicate<Node>() {
51 @Override
52 public boolean apply(Node n) {
53 return (NodeUtil.isAssignmentOp(n) &&
54 n.getFirstChild().isName()) ||
55 n.isInc() || n.isDec();
56 }
57 };
58
59 public DeadAssignmentsElimination(AbstractCompiler compiler) {
60 this.compiler = compiler;
61 }
62
63 @Override
64 public void process(Node externs, Node root) {
65 Preconditions.checkNotNull(externs);
66 Preconditions.checkNotNull(root);
67 NodeTraversal.traverse(compiler, root, this);
68 }
69
70 @Override
71 public void enterScope(NodeTraversal t) {
72 Scope scope = t.getScope();
73 // Global scope _SHOULD_ work, however, liveness won't finish without
74 // -Xmx1024 in closure. We might have to look at coding conventions for
75 // exported variables as well.
76 if (scope.isGlobal()) {
77 return;
78 }
79
80 if (LiveVariablesAnalysis.MAX_VARIABLES_TO_ANALYZE <
81 t.getScope().getVarCount()) {
82 return;
83 }
84
85 // We are not going to do any dead assignment elimination in when there is
86 // at least one inner function because in most browsers, when there is a
87 // closure, ALL the variables are saved (escaped).
88 Node fnBlock = t.getScopeRoot().getLastChild();
89 if (NodeUtil.containsFunction(fnBlock)) {
90 return;
91 }
92
93 // We don't do any dead assignment elimination if there are no assigns
94 // to eliminate. :)
95 if (!NodeUtil.has(fnBlock, matchRemovableAssigns,
96 Predicates.<Node>alwaysTrue())) {
97 return;
98 }
99
100 // Computes liveness information first.
101 ControlFlowGraph<Node> cfg = t.getControlFlowGraph();
102 liveness = new LiveVariablesAnalysis(cfg, scope, compiler);
103 liveness.analyze();
104 tryRemoveDeadAssignments(t, cfg);
105 }
106
107 @Override
108 public void exitScope(NodeTraversal t) {
109 }
110
111 @Override
112 public void visit(NodeTraversal t, Node n, Node parent) {
113 }
114
115 /**
116 * Try to remove useless assignments from a control flow graph that has been
117 * annotated with liveness information.
118 *
119 * @param t The node traversal.
120 * @param cfg The control flow graph of the program annotated with liveness
121 * information.
122 */
123 private void tryRemoveDeadAssignments(NodeTraversal t,
124 ControlFlowGraph<Node> cfg) {
125 Iterable<DiGraphNode<Node, Branch>> nodes = cfg.getDirectedGraphNodes();
126
127 for (DiGraphNode<Node, Branch> cfgNode : nodes) {
128 FlowState<LiveVariableLattice> state =
129 cfgNode.getAnnotation();
130 Node n = cfgNode.getValue();
131 if (n == null) {
132 continue;
133 }
134 switch (n.getType()) {
135 case Token.IF:
136 case Token.WHILE:
137 case Token.DO:
138 tryRemoveAssignment(t, NodeUtil.getConditionExpression(n), state);
139 continue;
140 case Token.FOR:
141 if (!NodeUtil.isForIn(n)) {
142 tryRemoveAssignment(
143 t, NodeUtil.getConditionExpression(n), state);
144 }
145 continue;
146 case Token.SWITCH:
147 case Token.CASE:
148 case Token.RETURN:
149 if (n.hasChildren()) {
150 tryRemoveAssignment(t, n.getFirstChild(), state);
151 }
152 continue;
153 // TODO(user): case Token.VAR: Remove var a=1;a=2;.....
154 }
155
156 tryRemoveAssignment(t, n, state);
157 }
158 }
159
160 private void tryRemoveAssignment(NodeTraversal t, Node n,
161 FlowState<LiveVariableLattice> state) {
162 tryRemoveAssignment(t, n, n, state);
163 }
164
165 /**
166 * Determines if any local variables are dead after the instruction {@code n}
167 * and are assigned within the subtree of {@code n}. Removes those assignments
168 * if there are any.
169 *
170 * @param n Target instruction.
171 * @param exprRoot The CFG node where the liveness information in state is
172 * still correct.
173 * @param state The liveness information at {@code n}.
174 */
175 private void tryRemoveAssignment(NodeTraversal t, Node n, Node exprRoot,
176 FlowState<LiveVariableLattice> state) {
177
178 Node parent = n.getParent();
179
180 if (NodeUtil.isAssignmentOp(n) ||
181 n.isInc() || n.isDec()) {
182
183 Node lhs = n.getFirstChild();
184 Node rhs = lhs.getNext();
185
186 // Recurse first. Example: dead_x = dead_y = 1; We try to clean up dead_y
187 // first.
188 if (rhs != null) {
189 tryRemoveAssignment(t, rhs, exprRoot, state);
190 rhs = lhs.getNext();
191 }
192
193 Scope scope = t.getScope();
194 if (!lhs.isName()) {
195 return; // Not a local variable assignment.
196 }
197 String name = lhs.getString();
198 if (!scope.isDeclared(name, false)) {
199 return;
200 }
201 Var var = scope.getVar(name);
202
203 if (liveness.getEscapedLocals().contains(var)) {
204 return; // Local variable that might be escaped due to closures.
205 }
206
207 // If we have an identity assignment such as a=a, always remove it
208 // regardless of what the liveness results because it
209 // does not change the result afterward.
210 if (rhs != null &&
211 rhs.isName() &&
212 rhs.getString().equals(var.name) &&
213 n.isAssign()) {
214 n.removeChild(rhs);
215 n.getParent().replaceChild(n, rhs);
216 compiler.reportCodeChange();
217 return;
218 }
219
220 if (state.getOut().isLive(var)) {
221 return; // Variable not dead.
222 }
223
224 if (state.getIn().isLive(var) &&
225 isVariableStillLiveWithinExpression(n, exprRoot, var.name)) {
226 // The variable is killed here but it is also live before it.
227 // This is possible if we have say:
228 // if (X = a && a = C) {..} ; .......; a = S;
229 // In this case we are safe to remove "a = C" because it is dead.
230 // However if we have:
231 // if (a = C && X = a) {..} ; .......; a = S;
232 // removing "a = C" is NOT correct, although the live set at the node
233 // is exactly the same.
234 // TODO(user): We need more fine grain CFA or we need to keep track
235 // of GEN sets when we recurse here.
236 return;
237 }
238
239 if (n.isAssign()) {
240 n.removeChild(rhs);
241 n.getParent().replaceChild(n, rhs);
242 } else if (NodeUtil.isAssignmentOp(n)) {
243 n.removeChild(rhs);
244 n.removeChild(lhs);
245 Node op = new Node(NodeUtil.getOpFromAssignmentOp(n), lhs, rhs);
246 parent.replaceChild(n, op);
247 } else if (n.isInc() || n.isDec()) {
248 if (parent.isExprResult()) {
249 parent.replaceChild(n,
250 IR.voidNode(IR.number(0).srcref(n)));
251 } else if(n.isComma() && n != parent.getLastChild()) {
252 parent.removeChild(n);
253 } else if (parent.isFor() && !NodeUtil.isForIn(parent) &&
254 NodeUtil.getConditionExpression(parent) != n) {
255 parent.replaceChild(n, IR.empty());
256 } else {
257 // Cannot replace x = a++ with x = a because that's not valid
258 // when a is not a number.
259 return;
260 }
261 } else {
262 // Not reachable.
263 Preconditions.checkState(false, "Unknown statement");
264 }
265
266 compiler.reportCodeChange();
267 return;
268
269 } else {
270 for (Node c = n.getFirstChild(); c != null;) {
271 Node next = c.getNext();
272 if (!ControlFlowGraph.isEnteringNewCfgNode(c)) {
273 tryRemoveAssignment(t, c, exprRoot, state);
274 }
275 c = next;
276 }
277 return;
278 }
279 }
280
281 /**
282 * Given a variable, node n in the tree and a sub-tree denoted by exprRoot as
283 * the root, this function returns true if there exists a read of that
284 * variable before a write to that variable that is on the right side of n.
285 *
286 * For example, suppose the node is x = 1:
287 *
288 * y = 1, x = 1; // false, there is no reads at all.
289 * y = 1, x = 1, print(x) // true, there is a read right of n.
290 * y = 1, x = 1, x = 2, print(x) // false, there is a read right of n but
291 * // it is after a write.
292 *
293 * @param n The current node we should look at.
294 * @param exprRoot The node
295 */
296 private boolean isVariableStillLiveWithinExpression(
297 Node n, Node exprRoot, String variable) {
298 while (n != exprRoot) {
299 VariableLiveness state = VariableLiveness.MAYBE_LIVE;
300 switch (n.getParent().getType()) {
301 case Token.OR:
302 case Token.AND:
303 // If the currently node is the first child of
304 // AND/OR, be conservative only consider the READs
305 // of the second operand.
306 if (n.getNext() != null) {
307 state = isVariableReadBeforeKill(
308 n.getNext(), variable);
309 if (state == VariableLiveness.KILL) {
310 state = VariableLiveness.MAYBE_LIVE;
311 }
312 }
313 break;
314
315 case Token.HOOK:
316 // If current node is the condition, check each following
317 // branch, otherwise it is a conditional branch and the
318 // other branch can be ignored.
319 if (n.getNext() != null && n.getNext().getNext() != null) {
320 state = checkHookBranchReadBeforeKill(
321 n.getNext(), n.getNext().getNext(), variable);
322 }
323 break;
324
325 default:
326 for(Node sibling = n.getNext(); sibling != null;
327 sibling = sibling.getNext()) {
328 state = isVariableReadBeforeKill(sibling, variable);
329 if (state != VariableLiveness.MAYBE_LIVE) {
330 break;
331 }
332 }
333 }
334
335 // If we see a READ or KILL there is no need to continue.
336 if (state == VariableLiveness.READ) {
337 return true;
338 } else if (state == VariableLiveness.KILL) {
339 return false;
340 }
341 n = n.getParent();
342 }
343 return false;
344 }
345
346 // The current liveness of the variable
347 private enum VariableLiveness {
348 MAYBE_LIVE, // May be still live in the current expression tree.
349 READ, // Known there is a read left of it.
350 KILL, // Known there is a write before any read.
351 }
352
353 /**
354 * Give an expression and a variable. It returns READ, if the first
355 * reference of that variable is a read. It returns KILL, if the first
356 * reference of that variable is an assignment. It returns MAY_LIVE otherwise.
357 */
358 private VariableLiveness isVariableReadBeforeKill(
359 Node n, String variable) {
360 if (ControlFlowGraph.isEnteringNewCfgNode(n)) { // Not a FUNCTION
361 return VariableLiveness.MAYBE_LIVE;
362 }
363
364 if (n.isName() && variable.equals(n.getString())) {
365 if (NodeUtil.isVarOrSimpleAssignLhs(n, n.getParent())) {
366 Preconditions.checkState(n.getParent().isAssign());
367 // The expression to which the assignment is made is evaluated before
368 // the RHS is evaluated (normal left to right evaluation) but the KILL
369 // occurs after the RHS is evaluated.
370 Node rhs = n.getNext();
371 VariableLiveness state = isVariableReadBeforeKill(rhs, variable);
372 if (state == VariableLiveness.READ) {
373 return state;
374 }
375 return VariableLiveness.KILL;
376 } else {
377 return VariableLiveness.READ;
378 }
379 }
380
381 switch (n.getType()) {
382 // Conditionals
383 case Token.OR:
384 case Token.AND:
385 VariableLiveness v1 = isVariableReadBeforeKill(
386 n.getFirstChild(), variable);
387 VariableLiveness v2 = isVariableReadBeforeKill(
388 n.getLastChild(), variable);
389 // With a AND/OR the first branch always runs, but the second is
390 // may not.
391 if (v1 != VariableLiveness.MAYBE_LIVE) {
392 return v1;
393 } else if (v2 == VariableLiveness.READ) {
394 return VariableLiveness.READ;
395 } else {
396 return VariableLiveness.MAYBE_LIVE;
397 }
398 case Token.HOOK:
399 VariableLiveness first = isVariableReadBeforeKill(
400 n.getFirstChild(), variable);
401 if (first != VariableLiveness.MAYBE_LIVE) {
402 return first;
403 }
404 return checkHookBranchReadBeforeKill(
405 n.getFirstChild().getNext(), n.getLastChild(), variable);
406
407 default:
408 // Expressions are evaluated left-right, depth first.
409 for (Node child = n.getFirstChild();
410 child != null; child = child.getNext()) {
411 VariableLiveness state = isVariableReadBeforeKill(child, variable);
412 if (state != VariableLiveness.MAYBE_LIVE) {
413 return state;
414 }
415 }
416 }
417
418 return VariableLiveness.MAYBE_LIVE;
419 }
420
421 private VariableLiveness checkHookBranchReadBeforeKill(
422 Node trueCase, Node falseCase, String variable) {
423 VariableLiveness v1 = isVariableReadBeforeKill(
424 trueCase, variable);
425 VariableLiveness v2 = isVariableReadBeforeKill(
426 falseCase, variable);
427 // With a hook it is unknown which branch will run, so
428 // we must be conservative. A read by either is a READ, and
429 // a KILL is only considered if both KILL.
430 if (v1 == VariableLiveness.READ || v2 == VariableLiveness.READ) {
431 return VariableLiveness.READ;
432 } else if (v1 == VariableLiveness.KILL && v2 == VariableLiveness.KILL) {
433 return VariableLiveness.KILL;
434 } else {
435 return VariableLiveness.MAYBE_LIVE;
436 }
437 }
438 }