Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2009 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.common.collect.Lists;
23 import com.google.common.collect.Sets;
24 import com.google.javascript.jscomp.ControlFlowGraph.AbstractCfgNodeTraversalCallback;
25 import com.google.javascript.jscomp.ControlFlowGraph.Branch;
26 import com.google.javascript.jscomp.MustBeReachingVariableDef.Definition;
27 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
28 import com.google.javascript.jscomp.NodeTraversal.AbstractShallowCallback;
29 import com.google.javascript.jscomp.NodeTraversal.ScopedCallback;
30 import com.google.javascript.jscomp.Scope.Var;
31 import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge;
32 import com.google.javascript.jscomp.graph.DiGraph.DiGraphNode;
33 import com.google.javascript.rhino.Node;
34 import com.google.javascript.rhino.Token;
35
36 import java.util.Collection;
37 import java.util.List;
38 import java.util.Set;
39
40 /**
41 * Inline variables when possible. Using the information from
42 * {@link MaybeReachingVariableUse} and {@link MustBeReachingVariableDef},
43 * this pass attempts to inline a variable by placing the value at the
44 * definition where the variable is used. The basic requirements for inlining
45 * are the following:
46 *
47 * <ul>
48 * <li> There is exactly one reaching definition at the use of that variable
49 * </li>
50 * <li> There is exactly one use for that definition of the variable
51 * </li>
52 * </ul>
53 *
54 * <p>Other requirements can be found in {@link Candidate#canInline}. Currently
55 * this pass does not operate on the global scope due to compilation time.
56 *
57 */
58 class FlowSensitiveInlineVariables extends AbstractPostOrderCallback
59 implements CompilerPass, ScopedCallback {
60
61 /**
62 * Implementation:
63 *
64 * This pass first perform a traversal to gather a list of Candidates that
65 * could be inlined using {@link GatherCandiates}.
66 *
67 * The second step involves verifying that each candidate is actually safe
68 * to inline with {@link Candidate#canInline(Scope)} and finally perform
69 * inlining using {@link Candidate#inlineVariable()}.
70 *
71 * The reason for the delayed evaluation of the candidates is because we
72 * need two separate dataflow result.
73 */
74 private final AbstractCompiler compiler;
75 private final Set<Var> inlinedNewDependencies = Sets.newHashSet();
76
77 // These two pieces of data is persistent in the whole execution of enter
78 // scope.
79 private ControlFlowGraph<Node> cfg;
80 private List<Candidate> candidates;
81 private MustBeReachingVariableDef reachingDef;
82 private MaybeReachingVariableUse reachingUses;
83
84 private static final Predicate<Node> SIDE_EFFECT_PREDICATE =
85 new Predicate<Node>() {
86 @Override
87 public boolean apply(Node n) {
88 // When the node is null it means, we reached the implicit return
89 // where the function returns (possibly without an return statement)
90 if (n == null) {
91 return false;
92 }
93
94 // TODO(user): We only care about calls to functions that
95 // passes one of the dependent variable to a non-side-effect free
96 // function.
97 if (n.isCall() && NodeUtil.functionCallHasSideEffects(n)) {
98 return true;
99 }
100
101 if (n.isNew() && NodeUtil.constructorCallHasSideEffects(n)) {
102 return true;
103 }
104
105 if (n.isDelProp()) {
106 return true;
107 }
108
109 for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
110 if (!ControlFlowGraph.isEnteringNewCfgNode(c) && apply(c)) {
111 return true;
112 }
113 }
114 return false;
115 }
116 };
117
118 public FlowSensitiveInlineVariables(AbstractCompiler compiler) {
119 this.compiler = compiler;
120 }
121
122 @Override
123 public void enterScope(NodeTraversal t) {
124
125 if (t.inGlobalScope()) {
126 return; // Don't even brother. All global variables are likely escaped.
127 }
128
129 if (LiveVariablesAnalysis.MAX_VARIABLES_TO_ANALYZE <
130 t.getScope().getVarCount()) {
131 return;
132 }
133
134 // Compute the forward reaching definition.
135 ControlFlowAnalysis cfa = new ControlFlowAnalysis(compiler, false, true);
136 // Process the body of the function.
137 Preconditions.checkState(t.getScopeRoot().isFunction());
138 cfa.process(null, t.getScopeRoot().getLastChild());
139 cfg = cfa.getCfg();
140 reachingDef = new MustBeReachingVariableDef(cfg, t.getScope(), compiler);
141 reachingDef.analyze();
142 candidates = Lists.newLinkedList();
143
144 // Using the forward reaching definition search to find all the inline
145 // candidates
146 new NodeTraversal(compiler, new GatherCandiates()).traverse(
147 t.getScopeRoot().getLastChild());
148
149 // Compute the backward reaching use. The CFG can be reused.
150 reachingUses = new MaybeReachingVariableUse(cfg, t.getScope(), compiler);
151 reachingUses.analyze();
152 for (Candidate c : candidates) {
153 if (c.canInline(t.getScope())) {
154 c.inlineVariable();
155
156 // If definition c has dependencies, then inlining it may have
157 // introduced new dependencies for our other inlining candidates.
158 //
159 // MustBeReachingVariableDef uses this dependency graph in its
160 // analysis, so some of these candidates may no longer be valid.
161 // We keep track of when the variable dependency graph changed
162 // so that we can back off appropriately.
163 if (!c.defMetadata.depends.isEmpty()) {
164 inlinedNewDependencies.add(t.getScope().getVar(c.varName));
165 }
166 }
167 }
168 }
169
170 @Override
171 public void exitScope(NodeTraversal t) {}
172
173 @Override
174 public void process(Node externs, Node root) {
175 (new NodeTraversal(compiler, this)).traverseRoots(externs, root);
176 }
177
178 @Override
179 public void visit(NodeTraversal t, Node n, Node parent) {
180 // TODO(user): While the helpers do a subtree traversal on the AST, the
181 // compiler pass itself only traverse the AST to look for function
182 // declarations to perform dataflow analysis on. We could combine
183 // the traversal in DataFlowAnalysis's computeEscaped later to save some
184 // time.
185 }
186
187 /**
188 * Gathers a list of possible candidates for inlining based only on
189 * information from {@link MustBeReachingVariableDef}. The list will be stored
190 * in {@code candidates} and the validity of each inlining Candidate should
191 * be later verified with {@link Candidate#canInline(Scope)} when
192 * {@link MaybeReachingVariableUse} has been performed.
193 */
194 private class GatherCandiates extends AbstractShallowCallback {
195 @Override
196 public void visit(NodeTraversal t, Node n, Node parent) {
197 DiGraphNode<Node, Branch> graphNode = cfg.getDirectedGraphNode(n);
198 if (graphNode == null) {
199 // Not a CFG node.
200 return;
201 }
202 final Node cfgNode = n;
203 AbstractCfgNodeTraversalCallback gatherCb =
204 new AbstractCfgNodeTraversalCallback() {
205
206 @Override
207 public void visit(NodeTraversal t, Node n, Node parent) {
208 if (n.isName()) {
209
210 // n.getParent() isn't null. This just the case where n is the root
211 // node that gatherCb started at.
212 if (parent == null) {
213 return;
214 }
215
216 // Make sure that the name node is purely a read.
217 if ((NodeUtil.isAssignmentOp(parent) && parent.getFirstChild() == n)
218 || parent.isVar() || parent.isInc() || parent.isDec() ||
219 parent.isParamList() || parent.isCatch()) {
220 return;
221 }
222
223 String name = n.getString();
224 if (compiler.getCodingConvention().isExported(name)) {
225 return;
226 }
227
228 Definition def = reachingDef.getDef(name, cfgNode);
229 // TODO(nicksantos): We need to add some notion of @const outer
230 // scope vars. We can inline those just fine.
231 if (def != null &&
232 !reachingDef.dependsOnOuterScopeVars(def)) {
233 candidates.add(new Candidate(name, def, n, cfgNode));
234 }
235 }
236 }
237 };
238
239 NodeTraversal.traverse(compiler, cfgNode, gatherCb);
240 }
241 }
242
243 /**
244 * Models the connection between a definition and a use of that definition.
245 */
246 private class Candidate {
247
248 // Name of the variable.
249 private final String varName;
250
251 // Nodes related to the definition.
252 private Node def;
253 private final Definition defMetadata;
254
255 // Nodes related to the use.
256 private final Node use;
257 private final Node useCfgNode;
258
259 // Number of uses of the variable within the CFG node that represented the
260 // use in the CFG.
261 private int numUseWithinUseCfgNode;
262
263 Candidate(String varName, Definition defMetadata,
264 Node use, Node useCfgNode) {
265 Preconditions.checkArgument(use.isName());
266 this.varName = varName;
267 this.defMetadata = defMetadata;
268 this.use = use;
269 this.useCfgNode = useCfgNode;
270 }
271
272 private Node getDefCfgNode() {
273 return defMetadata.node;
274 }
275
276 private boolean canInline(final Scope scope) {
277 // Cannot inline a parameter.
278 if (getDefCfgNode().isFunction()) {
279 return false;
280 }
281
282 // If one of our dependencies has been inlined, then our dependency
283 // graph is wrong. Re-computing it would take another CFG computation,
284 // so we just back off for now.
285 for (Var dependency : defMetadata.depends) {
286 if (inlinedNewDependencies.contains(dependency)) {
287 return false;
288 }
289 }
290
291 getDefinition(getDefCfgNode());
292 getNumUseInUseCfgNode(useCfgNode);
293
294 // Definition was not found.
295 if (def == null) {
296 return false;
297 }
298
299 // Check that the assignment isn't used as a R-Value.
300 // TODO(user): Certain cases we can still inline.
301 if (def.isAssign() && !NodeUtil.isExprAssign(def.getParent())) {
302 return false;
303 }
304
305 // The right of the definition has side effect:
306 // Example, for x:
307 // x = readProp(b), modifyProp(b); print(x);
308 if (checkRightOf(def, getDefCfgNode(), SIDE_EFFECT_PREDICATE)) {
309 return false;
310 }
311
312 // Similar check as the above but this time, all the sub-expressions
313 // left of the use of the variable.
314 // x = readProp(b); modifyProp(b), print(x);
315 if (checkLeftOf(use, useCfgNode, SIDE_EFFECT_PREDICATE)) {
316 return false;
317 }
318
319 // TODO(user): Side-effect is OK sometimes. As long as there are no
320 // side-effect function down all paths to the use. Once we have all the
321 // side-effect analysis tool.
322 if (NodeUtil.mayHaveSideEffects(def.getLastChild(), compiler)) {
323 return false;
324 }
325
326 // TODO(user): We could inline all the uses if the expression is short.
327
328 // Finally we have to make sure that there are no more than one use
329 // in the program and in the CFG node. Even when it is semantically
330 // correctly inlining twice increases code size.
331 if (numUseWithinUseCfgNode != 1) {
332 return false;
333 }
334
335 // Make sure that the name is not within a loop
336 if (NodeUtil.isWithinLoop(use)) {
337 return false;
338 }
339
340
341 Collection<Node> uses = reachingUses.getUses(varName, getDefCfgNode());
342
343 if (uses.size() != 1) {
344 return false;
345 }
346
347 // We give up inlining stuff with R-Value that has:
348 // 1) GETPROP, GETELEM,
349 // 2) anything that creates a new object.
350 // 3) a direct reference to a catch expression.
351 // Example:
352 // var x = a.b.c; j.c = 1; print(x);
353 // Inlining print(a.b.c) is not safe consider j and be alias to a.b.
354 // TODO(user): We could get more accuracy by looking more in-detail
355 // what j is and what x is trying to into to.
356 // TODO(johnlenz): rework catch expression handling when we
357 // have lexical scope support so catch expressions don't
358 // need to be special cased.
359 if (NodeUtil.has(def.getLastChild(),
360 new Predicate<Node>() {
361 @Override
362 public boolean apply(Node input) {
363 switch (input.getType()) {
364 case Token.GETELEM:
365 case Token.GETPROP:
366 case Token.ARRAYLIT:
367 case Token.OBJECTLIT:
368 case Token.REGEXP:
369 case Token.NEW:
370 return true;
371 case Token.NAME:
372 Var var = scope.getOwnSlot(input.getString());
373 if (var != null
374 && var.getParentNode().isCatch()) {
375 return true;
376 }
377 }
378 return false;
379 }
380 },
381 new Predicate<Node>() {
382 @Override
383 public boolean apply(Node input) {
384 // Recurse if the node is not a function.
385 return !input.isFunction();
386 }
387 })) {
388 return false;
389 }
390
391 // We can skip the side effect check along the paths of two nodes if
392 // they are just next to each other.
393 if (NodeUtil.isStatementBlock(getDefCfgNode().getParent()) &&
394 getDefCfgNode().getNext() != useCfgNode) {
395 // Similar side effect check as above but this time the side effect is
396 // else where along the path.
397 // x = readProp(b); while(modifyProp(b)) {}; print(x);
398 CheckPathsBetweenNodes<Node, ControlFlowGraph.Branch>
399 pathCheck = new CheckPathsBetweenNodes<Node, ControlFlowGraph.Branch>(
400 cfg,
401 cfg.getDirectedGraphNode(getDefCfgNode()),
402 cfg.getDirectedGraphNode(useCfgNode),
403 SIDE_EFFECT_PREDICATE,
404 Predicates.
405 <DiGraphEdge<Node, ControlFlowGraph.Branch>>alwaysTrue(),
406 false);
407 if (pathCheck.somePathsSatisfyPredicate()) {
408 return false;
409 }
410 }
411
412 return true;
413 }
414
415 /**
416 * Actual transformation.
417 */
418 private void inlineVariable() {
419 Node defParent = def.getParent();
420 Node useParent = use.getParent();
421 if (def.isAssign()) {
422 Node rhs = def.getLastChild();
423 rhs.detachFromParent();
424 // Oh yes! I have grandparent to remove this.
425 Preconditions.checkState(defParent.isExprResult());
426 while (defParent.getParent().isLabel()) {
427 defParent = defParent.getParent();
428 }
429 defParent.detachFromParent();
430 useParent.replaceChild(use, rhs);
431 } else if (defParent.isVar()) {
432 Node rhs = def.getLastChild();
433 def.removeChild(rhs);
434 useParent.replaceChild(use, rhs);
435 } else {
436 Preconditions.checkState(false, "No other definitions can be inlined.");
437 }
438 compiler.reportCodeChange();
439 }
440
441 /**
442 * Set the def node
443 *
444 * @param n A node that has a corresponding CFG node in the CFG.
445 */
446 private void getDefinition(Node n) {
447 AbstractCfgNodeTraversalCallback gatherCb =
448 new AbstractCfgNodeTraversalCallback() {
449
450 @Override
451 public void visit(NodeTraversal t, Node n, Node parent) {
452 switch (n.getType()) {
453 case Token.NAME:
454 if (n.getString().equals(varName) && n.hasChildren()) {
455 def = n;
456 }
457 return;
458
459 case Token.ASSIGN:
460 Node lhs = n.getFirstChild();
461 if (lhs.isName() && lhs.getString().equals(varName)) {
462 def = n;
463 }
464 return;
465 }
466 }
467 };
468 NodeTraversal.traverse(compiler, n, gatherCb);
469 }
470
471 /**
472 * Computes the number of uses of the variable varName and store it in
473 * numUseWithinUseCfgNode.
474 */
475 private void getNumUseInUseCfgNode(Node n) {
476
477 AbstractCfgNodeTraversalCallback gatherCb =
478 new AbstractCfgNodeTraversalCallback() {
479
480 @Override
481 public void visit(NodeTraversal t, Node n, Node parent) {
482 if (n.isName() && n.getString().equals(varName) &&
483 // do not count in if it is left child of an assignment operator
484 !(parent.isAssign() &&
485 (parent.getFirstChild() == n))) {
486 numUseWithinUseCfgNode++;
487 }
488 }
489 };
490
491 NodeTraversal.traverse(compiler, n, gatherCb);
492 }
493 }
494
495 /**
496 * Given an expression by its root and sub-expression n, return true if there
497 * the predicate is true for some expression on the right of n.
498 *
499 * Example:
500 *
501 * NotChecked(), NotChecked(), n, Checked(), Checked();
502 */
503 private static boolean checkRightOf(
504 Node n, Node expressionRoot, Predicate<Node> predicate) {
505 for (Node p = n; p != expressionRoot; p = p.getParent()) {
506 for (Node cur = p.getNext(); cur != null; cur = cur.getNext()) {
507 if (predicate.apply(cur)) {
508 return true;
509 }
510 }
511 }
512 return false;
513 }
514
515 /**
516 * Given an expression by its root and sub-expression n, return true if there
517 * the predicate is true for some expression on the left of n.
518 *
519 * Example:
520 *
521 * Checked(), Checked(), n, NotChecked(), NotChecked();
522 */
523 private static boolean checkLeftOf(
524 Node n, Node expressionRoot, Predicate<Node> predicate) {
525 for (Node p = n.getParent(); p != expressionRoot; p = p.getParent()) {
526 for (Node cur = p.getParent().getFirstChild(); cur != p;
527 cur = cur.getNext()) {
528 if (predicate.apply(cur)) {
529 return true;
530 }
531 }
532 }
533 return false;
534 }
535 }