Debian Codegraph @

src/com/google/javascript/jscomp/CoalesceVariableNames.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.Joiner;
20 import com.google.common.base.Preconditions;
21 import com.google.common.collect.Lists;
22 import com.google.common.collect.Sets;
23 import com.google.javascript.jscomp.ControlFlowGraph.AbstractCfgNodeTraversalCallback;
24 import com.google.javascript.jscomp.ControlFlowGraph.Branch;
25 import com.google.javascript.jscomp.DataFlowAnalysis.FlowState;
26 import com.google.javascript.jscomp.LiveVariablesAnalysis.LiveVariableLattice;
27 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
28 import com.google.javascript.jscomp.NodeTraversal.ScopedCallback;
29 import com.google.javascript.jscomp.Scope.Var;
30 import com.google.javascript.jscomp.graph.DiGraph.DiGraphNode;
31 import com.google.javascript.jscomp.graph.GraphColoring;
32 import com.google.javascript.jscomp.graph.GraphColoring.GreedyGraphColoring;
33 import com.google.javascript.jscomp.graph.GraphNode;
34 import com.google.javascript.jscomp.graph.LinkedUndirectedGraph;
35 import com.google.javascript.jscomp.graph.UndiGraph;
36 import com.google.javascript.rhino.IR;
37 import com.google.javascript.rhino.Node;
38 import java.util.Comparator;
39 import java.util.Deque;
40 import java.util.Iterator;
41 import java.util.Set;
42
43 /**
44 * Reuse variable names if possible.
45 *
46 * <p>For example, from <code>var x = 1; print(x); var y = 2; print(y); </code>
47 * to <code>var x = 1; print(x); x = 2; print(x)</code>. The benefits are
48 * slightly shorter code because of the removed <code>var<code> declaration,
49 * less unique variables in hope for better renaming, and finally better gzip
50 * compression.
51 *
52 * <p>The pass operates similar to a typical register allocator found in an
53 * optimizing compiler by first computing live ranges with
54 * {@link LiveVariablesAnalysis} and a variable interference graph. Then it uses
55 * graph coloring in {@link GraphColoring} to determine which two variables can
56 * be merge together safely.
57 *
58 */
59 class CoalesceVariableNames extends AbstractPostOrderCallback implements
60 CompilerPass, ScopedCallback {
61
62 private final AbstractCompiler compiler;
63 private final Deque<GraphColoring<Var, Void>> colorings;
64 private final boolean usePseudoNames;
65
66 private static final Comparator<Var> coloringTieBreaker =
67 new Comparator<Var>() {
68 @Override
69 public int compare(Var v1, Var v2) {
70 return v1.index - v2.index;
71 }
72 };
73
74 /**
75 * @param usePseudoNames For debug purposes, when merging variable foo and bar
76 * to foo, rename both variable to foo_bar.
77 */
78 CoalesceVariableNames(AbstractCompiler compiler, boolean usePseudoNames) {
79 Preconditions.checkState(!compiler.getLifeCycleStage().isNormalized());
80
81 this.compiler = compiler;
82 colorings = Lists.newLinkedList();
83 this.usePseudoNames = usePseudoNames;
84 }
85
86 @Override
87 public void process(Node externs, Node root) {
88 NodeTraversal.traverse(compiler, root, this);
89 }
90
91 private static boolean shouldOptimizeScope(Scope scope) {
92 // TODO(user): We CAN do this in the global scope, just need to be
93 // careful when something is exported. Liveness uses bit-vector for live
94 // sets so I don't see compilation time will be a problem for running this
95 // pass in the global scope.
96 if (scope.isGlobal()) {
97 return false;
98 }
99
100 if (LiveVariablesAnalysis.MAX_VARIABLES_TO_ANALYZE <
101 scope.getVarCount()) {
102 return false;
103 }
104
105 return true;
106 }
107
108 @Override
109 public void enterScope(NodeTraversal t) {
110 Scope scope = t.getScope();
111 if (!shouldOptimizeScope(scope)) {
112 return;
113 }
114
115 ControlFlowGraph<Node> cfg = t.getControlFlowGraph();
116 LiveVariablesAnalysis liveness =
117 new LiveVariablesAnalysis(cfg, scope, compiler);
118 // If the function has exactly 2 params, mark them as escaped. This is
119 // a work-around for an IE bug where it throws an exception if you
120 // write to the parameters of the callback in a sort(). See:
121 // http://code.google.com/p/closure-compiler/issues/detail?id=58
122 if (scope.getRootNode().getFirstChild().getNext().getChildCount() == 2) {
123 liveness.markAllParametersEscaped();
124 }
125 liveness.analyze();
126
127 UndiGraph<Var, Void> interferenceGraph =
128 computeVariableNamesInterferenceGraph(
129 t, cfg, liveness.getEscapedLocals());
130
131 GraphColoring<Var, Void> coloring =
132 new GreedyGraphColoring<Var, Void>(interferenceGraph,
133 coloringTieBreaker);
134
135 coloring.color();
136 colorings.push(coloring);
137 }
138
139 @Override
140 public void exitScope(NodeTraversal t) {
141 if (!shouldOptimizeScope(t.getScope())) {
142 return;
143 }
144 colorings.pop();
145 }
146
147 @Override
148 public void visit(NodeTraversal t, Node n, Node parent) {
149 if (colorings.isEmpty() || !n.isName() ||
150 parent.isFunction()) {
151 // Don't rename named functions.
152 return;
153 }
154 Var var = t.getScope().getVar(n.getString());
155 GraphNode<Var, ?> vNode = colorings.peek().getGraph().getNode(var);
156 if (vNode == null) {
157 // This is not a local.
158 return;
159 }
160 Var coalescedVar = colorings.peek().getPartitionSuperNode(var);
161
162 if (!usePseudoNames) {
163 if (vNode.getValue().equals(coalescedVar)) {
164 // The coalesced name is itself, nothing to do.
165 return;
166 }
167
168 // Rename.
169 n.setString(coalescedVar.name);
170 compiler.reportCodeChange();
171
172 if (parent.isVar()) {
173 removeVarDeclaration(n);
174 }
175 } else {
176 // This code block is slow but since usePseudoName is for debugging,
177 // we should not sacrifice performance for non-debugging compilation to
178 // make this fast.
179 String pseudoName = null;
180 Set<String> allMergedNames = Sets.newTreeSet();
181 for (Iterator<Var> i = t.getScope().getVars(); i.hasNext();) {
182 Var iVar = i.next();
183
184 // Look for all the variables that can be merged (in the graph by now)
185 // and it is merged with the current coalescedVar.
186 if (colorings.peek().getGraph().getNode(iVar) != null &&
187 coalescedVar.equals(colorings.peek().getPartitionSuperNode(iVar))) {
188 allMergedNames.add(iVar.name);
189 }
190 }
191
192 // Keep its original name.
193 if (allMergedNames.size() == 1) {
194 return;
195 }
196
197 pseudoName = Joiner.on("_").join(allMergedNames);
198
199 while (t.getScope().isDeclared(pseudoName, true)) {
200 pseudoName += "$";
201 }
202
203 n.setString(pseudoName);
204 compiler.reportCodeChange();
205
206 if (!vNode.getValue().equals(coalescedVar) && parent.isVar()) {
207 removeVarDeclaration(n);
208 }
209 }
210 }
211
212 private UndiGraph<Var, Void> computeVariableNamesInterferenceGraph(
213 NodeTraversal t, ControlFlowGraph<Node> cfg, Set<Var> escaped) {
214 UndiGraph<Var, Void> interferenceGraph =
215 LinkedUndirectedGraph.create();
216 Scope scope = t.getScope();
217
218 // First create a node for each non-escaped variable.
219 for (Iterator<Var> i = scope.getVars(); i.hasNext();) {
220 Var v = i.next();
221 if (!escaped.contains(v)) {
222
223 // TODO(user): In theory, we CAN coalesce function names just like
224 // any variables. Our Liveness analysis captures this just like it as
225 // described in the specification. However, we saw some zipped and
226 // and unzipped size increase after this. We are not totally sure why
227 // that is but, for now, we will respect the dead functions and not play
228 // around with it.
229 if (!v.getParentNode().isFunction()) {
230 interferenceGraph.createNode(v);
231 }
232 }
233 }
234
235 // Go through each variable and try to connect them.
236 for (Iterator<Var> i1 = scope.getVars(); i1.hasNext();) {
237 Var v1 = i1.next();
238
239 NEXT_VAR_PAIR:
240 for (Iterator<Var> i2 = scope.getVars(); i2.hasNext();) {
241 Var v2 = i2.next();
242
243 // Skip duplicate pairs.
244 if (v1.index >= v2.index) {
245 continue;
246 }
247
248 if (!interferenceGraph.hasNode(v1) ||
249 !interferenceGraph.hasNode(v2)) {
250 // Skip nodes that were not added. They are globals and escaped
251 // locals. Also avoid merging a variable with itself.
252 continue NEXT_VAR_PAIR;
253 }
254
255 if (v1.getParentNode().isParamList() &&
256 v2.getParentNode().isParamList()) {
257 interferenceGraph.connectIfNotFound(v1, null, v2);
258 continue NEXT_VAR_PAIR;
259 }
260
261 // Go through every CFG node in the program and look at
262 // this variable pair. If they are both live at the same
263 // time, add an edge between them and continue to the next pair.
264 NEXT_CROSS_CFG_NODE:
265 for (DiGraphNode<Node, Branch> cfgNode : cfg.getDirectedGraphNodes()) {
266 if (cfg.isImplicitReturn(cfgNode)) {
267 continue NEXT_CROSS_CFG_NODE;
268 }
269
270 FlowState<LiveVariableLattice> state = cfgNode.getAnnotation();
271 // Check the live states and add edge when possible.
272 if ((state.getIn().isLive(v1) && state.getIn().isLive(v2)) ||
273 (state.getOut().isLive(v1) && state.getOut().isLive(v2))) {
274 interferenceGraph.connectIfNotFound(v1, null, v2);
275 continue NEXT_VAR_PAIR;
276 }
277 }
278
279 // v1 and v2 might not have an edge between them! woohoo. there's
280 // one last sanity check that we have to do: we have to check
281 // if there's a collision *within* the cfg node.
282 NEXT_INTRA_CFG_NODE:
283 for (DiGraphNode<Node, Branch> cfgNode : cfg.getDirectedGraphNodes()) {
284 if (cfg.isImplicitReturn(cfgNode)) {
285 continue NEXT_INTRA_CFG_NODE;
286 }
287
288 FlowState<LiveVariableLattice> state = cfgNode.getAnnotation();
289 boolean v1OutLive = state.getOut().isLive(v1);
290 boolean v2OutLive = state.getOut().isLive(v2);
291 CombinedLiveRangeChecker checker = new CombinedLiveRangeChecker(
292 new LiveRangeChecker(v1, v2OutLive ? null : v2),
293 new LiveRangeChecker(v2, v1OutLive ? null : v1));
294 NodeTraversal.traverse(
295 compiler,
296 cfgNode.getValue(),
297 checker);
298 if (checker.connectIfCrossed(interferenceGraph)) {
299 continue NEXT_VAR_PAIR;
300 }
301 }
302 }
303 }
304 return interferenceGraph;
305 }
306
307 /**
308 * A simple wrapper calls to call two AbstractCfgNodeTraversalCallback
309 * callback during the same traversal. Both traversals must have the same
310 * "shouldTraverse" conditions.
311 */
312 private static class CombinedLiveRangeChecker
313 extends AbstractCfgNodeTraversalCallback {
314
315 private final LiveRangeChecker callback1;
316 private final LiveRangeChecker callback2;
317
318 CombinedLiveRangeChecker(
319 LiveRangeChecker callback1,
320 LiveRangeChecker callback2) {
321 this.callback1 = callback1;
322 this.callback2 = callback2;
323 }
324
325 @Override
326 public void visit(NodeTraversal t, Node n, Node parent) {
327 if (LiveRangeChecker.shouldVisit(n)) {
328 callback1.visit(t, n, parent);
329 callback2.visit(t, n, parent);
330 }
331 }
332
333 boolean connectIfCrossed(UndiGraph<Var, Void> interferenceGraph) {
334 if (callback1.crossed || callback2.crossed) {
335 Var v1 = callback1.getDef();
336 Var v2 = callback2.getDef();
337 interferenceGraph.connectIfNotFound(v1, null, v2);
338 return true;
339 }
340 return false;
341 }
342 }
343
344 /**
345 * Tries to remove variable declaration if the variable has been coalesced
346 * with another variable that has already been declared.
347 */
348 private void removeVarDeclaration(Node name) {
349 Node var = name.getParent();
350 Node parent = var.getParent();
351
352 // Special case when we are in FOR-IN loop.
353 if (NodeUtil.isForIn(parent)) {
354 var.removeChild(name);
355 parent.replaceChild(var, name);
356 } else if (var.hasOneChild()) {
357 // The removal is easy when there is only one variable in the VAR node.
358 if (name.hasChildren()) {
359 Node value = name.removeFirstChild();
360 var.removeChild(name);
361 Node assign = IR.assign(name, value).srcref(name);
362
363 // We don't need to wrapped it with EXPR node if it is within a FOR.
364 if (!parent.isFor()) {
365 assign = NodeUtil.newExpr(assign);
366 }
367 parent.replaceChild(var, assign);
368
369 } else {
370 // In a FOR( ; ; ) node, we must replace it with an EMPTY or else it
371 // becomes a FOR-IN node.
372 NodeUtil.removeChild(parent, var);
373 }
374 } else {
375 if (!name.hasChildren()) {
376 var.removeChild(name);
377 }
378 // We are going to leave duplicated declaration otherwise.
379 }
380 }
381
382 private static class LiveRangeChecker
383 extends AbstractCfgNodeTraversalCallback {
384 boolean defFound = false;
385 boolean crossed = false;
386 private final Var def;
387 private final Var use;
388
389 public LiveRangeChecker(Var def, Var use) {
390 this.def = def;
391 this.use = use;
392 }
393
394 Var getDef() {
395 return def;
396 }
397
398 /**
399 * @return Whether any LiveRangeChecker would be interested in the node.
400 */
401 public static boolean shouldVisit(Node n) {
402 return (n.isName()
403 || (n.hasChildren() && n.getFirstChild().isName()));
404 }
405
406 @Override
407 public void visit(NodeTraversal t, Node n, Node parent) {
408 if (!defFound && isAssignTo(def, n, parent)) {
409 defFound = true;
410 }
411
412 if (defFound && (use == null || isReadFrom(use, n))) {
413 crossed = true;
414 }
415 }
416
417 private static boolean isAssignTo(Var var, Node n, Node parent) {
418 if (n.isName() && var.getName().equals(n.getString()) &&
419 parent != null) {
420 if (parent.isParamList()) {
421 // In a function declaration, the formal parameters are assigned.
422 return true;
423 } else if (parent.isVar()) {
424 // If this is a VAR declaration, if the name node has a child, we are
425 // assigning to that name.
426 return n.hasChildren();
427 }
428 return false; // Definitely a read.
429 } else {
430 // Lastly, any assignmentOP is also an assign.
431 Node name = n.getFirstChild();
432 return name != null && name.isName() &&
433 var.getName().equals(name.getString()) &&
434 NodeUtil.isAssignmentOp(n);
435 }
436 }
437
438 private static boolean isReadFrom(Var var, Node name) {
439 return name != null && name.isName() &&
440 var.getName().equals(name.getString()) &&
441 !NodeUtil.isVarOrSimpleAssignLhs(name, name.getParent());
442 }
443 }
444 }