Debian Codegraph @

src/com/google/javascript/jscomp/PhaseOptimizer.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.annotations.VisibleForTesting;
20 import com.google.common.base.Preconditions;
21 import com.google.common.collect.ImmutableList;
22 import com.google.common.collect.Lists;
23 import com.google.common.collect.Sets;
24 import com.google.javascript.rhino.Node;
25
26 import java.util.Collections;
27 import java.util.HashSet;
28 import java.util.List;
29 import java.util.Set;
30 import java.util.logging.Logger;
31
32 /**
33 * Optimizes the order of compiler passes.
34 * @author [email protected] (Nick Santos)
35 */
36 class PhaseOptimizer implements CompilerPass {
37
38 // This ordering is computed offline by running with compute_phase_ordering.
39 @VisibleForTesting
40 static final List<String> OPTIMAL_ORDER = ImmutableList.of(
41 "deadAssignmentsElimination",
42 "inlineFunctions",
43 "removeUnusedPrototypeProperties",
44 "removeUnreachableCode",
45 "removeUnusedVars",
46 "minimizeExitPoints",
47 "inlineVariables",
48 "collapseObjectLiterals",
49 "peepholeOptimizations");
50
51 static final int MAX_LOOPS = 100;
52 static final String OPTIMIZE_LOOP_ERROR =
53 "Fixed point loop exceeded the maximum number of iterations.";
54
55 // Only used by Loop/process, but enum types can't be local
56 enum State {
57 RUN_PASSES_NOT_RUN_IN_PREV_ITER,
58 RUN_PASSES_THAT_CHANGED_STH_IN_PREV_ITER
59 }
60
61 private static final Logger logger =
62 Logger.getLogger(PhaseOptimizer.class.getName());
63
64 private final List<CompilerPass> passes = Lists.newArrayList();
65
66 private final AbstractCompiler compiler;
67 private final PerformanceTracker tracker;
68 private boolean loopMutex = false;
69 private PassFactory sanityCheck = null;
70 private boolean printAstHashcodes = false;
71
72 private double progress = 0.0;
73 private double progressStep = 0.0;
74
75 // The following static properties are only used for computing optimal
76 // phase orderings. They should not be touched by normal compiler runs.
77 private static boolean randomizeLoops = false;
78 private static List<List<String>> loopsRun = Lists.newArrayList();
79
80 private final ProgressRange progressRange;
81
82 /**
83 * @param compiler the compiler that owns/creates this.
84 * @param tracker an optional performance tracker
85 * @param progressRange the progress range for the process function or null
86 * if progress should not be reported.
87 */
88 PhaseOptimizer(AbstractCompiler compiler, PerformanceTracker tracker,
89 ProgressRange progressRange) {
90 this.compiler = compiler;
91 this.tracker = tracker;
92 this.progressRange = progressRange;
93 }
94
95 /**
96 * Randomizes loops. This should only be used when computing optimal phase
97 * orderings.
98 */
99 static void randomizeLoops() {
100 randomizeLoops = true;
101 }
102
103 /**
104 * Get the phase ordering of loops during this run.
105 * Returns an empty list when the loops are not randomized.
106 */
107 static List<List<String>> getLoopsRun() {
108 return loopsRun;
109 }
110
111 /**
112 * Clears the phase ordering of loops during this run.
113 */
114 static void clearLoopsRun() {
115 loopsRun.clear();
116 }
117
118 /**
119 * Add the passes generated by the given factories to the compile sequence.
120 *
121 * Automatically pulls multi-run passes into fixed point loops. If there
122 * are 1 or more multi-run passes in a row, they will run together in
123 * the same fixed point loop. The passes will run until they are finished
124 * making changes.
125 *
126 * The PhaseOptimizer is free to tweak the order and frequency of multi-run
127 * passes in a fixed-point loop.
128 */
129 void consume(List<PassFactory> factories) {
130 Loop currentLoop = new Loop();
131 boolean isCurrentLoopPopulated = false;
132 for (PassFactory factory : factories) {
133 if (factory.isOneTimePass()) {
134 if (isCurrentLoopPopulated) {
135 passes.add(currentLoop);
136 currentLoop = new Loop();
137 isCurrentLoopPopulated = false;
138 }
139 addOneTimePass(factory);
140 } else {
141 currentLoop.addLoopedPass(factory);
142 isCurrentLoopPopulated = true;
143 }
144 }
145
146 if (isCurrentLoopPopulated) {
147 passes.add(currentLoop);
148 }
149 }
150
151 /**
152 * Add the pass generated by the given factory to the compile sequence.
153 * This pass will be run once.
154 */
155 void addOneTimePass(PassFactory factory) {
156 passes.add(new NamedPass(factory));
157 }
158
159 /**
160 * Add a loop to the compile sequence. This loop will continue running
161 * until the AST stops changing.
162 * @return The loop structure. Pass suppliers should be added to the loop.
163 */
164 Loop addFixedPointLoop() {
165 Loop loop = new Loop();
166 passes.add(loop);
167 return loop;
168 }
169
170 /**
171 * Adds a sanity checker to be run after every pass. Intended for development.
172 */
173 void setSanityCheck(PassFactory sanityCheck) {
174 this.sanityCheck = sanityCheck;
175 }
176
177 /**
178 * Sets the hashcode of the AST to be logged every pass. Intended for development.
179 */
180 void setPrintAstHashcodes(boolean printAstHashcodes) {
181 this.printAstHashcodes = printAstHashcodes;
182 }
183
184 /**
185 * Run all the passes in the optimizer.
186 */
187 @Override
188 public void process(Node externs, Node root) {
189 progress = 0.0;
190 progressStep = 0.0;
191 if (progressRange != null) {
192 progressStep = (progressRange.maxValue - progressRange.initialValue)
193 / passes.size();
194 progress = progressRange.initialValue;
195 }
196
197 for (CompilerPass pass : passes) {
198 pass.process(externs, root);
199 if (hasHaltingErrors()) {
200 return;
201 }
202 }
203 }
204
205 private void maybePrintAstHashcodes(String passName, Node root) {
206 if (printAstHashcodes) {
207 String hashCodeMsg = "AST hashCode after " + passName + ": " +
208 compiler.toSource(root).hashCode();
209 System.err.println(hashCodeMsg);
210 compiler.addToDebugLog(hashCodeMsg);
211 }
212 }
213
214 /**
215 * Runs the sanity check if it is available.
216 */
217 void maybeSanityCheck(Node externs, Node root) {
218 if (sanityCheck != null) {
219 sanityCheck.create(compiler).process(externs, root);
220 }
221 }
222
223 private boolean hasHaltingErrors() {
224 return compiler.hasHaltingErrors();
225 }
226
227 /**
228 * A single compiler pass.
229 */
230 class NamedPass implements CompilerPass {
231 final String name;
232 private final PassFactory factory;
233 private Tracer tracer;
234
235 NamedPass(PassFactory factory) {
236 this.name = factory.getName();
237 this.factory = factory;
238 }
239
240 @Override
241 public void process(Node externs, Node root) {
242 logger.fine(name);
243 if (tracker != null) {
244 tracker.recordPassStart(name, factory.isOneTimePass());
245 }
246 tracer = new Tracer("JSCompiler");
247 // Delay the creation of the actual pass until *after* all previous passes
248 // have been processed.
249 // Some precondition checks rely on this, eg, in CoalesceVariableNames.
250 factory.create(compiler).process(externs, root);
251 try {
252 if (progressRange == null) {
253 compiler.setProgress(-1, name);
254 } else {
255 progress += progressStep;
256 compiler.setProgress(progress, name);
257 }
258 if (tracker != null) {
259 tracker.recordPassStop(name, tracer.stop());
260 }
261 maybePrintAstHashcodes(name, root);
262 maybeSanityCheck(externs, root);
263 } catch (Exception e) {
264 // TODO(johnlenz): Remove this once the normalization checks report
265 // errors instead of exceptions.
266 throw new RuntimeException("Sanity check failed for " + name, e);
267 }
268 }
269 }
270
271 /**
272 * Runs a set of compiler passes until they reach a fixed point.
273 *
274 * Notice that this is a non-static class, because it includes the closure
275 * of PhaseOptimizer.
276 */
277 class Loop implements CompilerPass {
278 private final List<NamedPass> myPasses = Lists.newArrayList();
279 private final Set<String> myNames = Sets.newHashSet();
280 private CodeChangeHandler recentChange = new CodeChangeHandler();
281
282 void addLoopedPass(PassFactory factory) {
283 String name = factory.getName();
284 Preconditions.checkArgument(!myNames.contains(name),
285 "Already a pass with name '%s' in this loop", name);
286 myNames.add(name);
287 myPasses.add(new NamedPass(factory));
288 }
289
290 @Override
291 public void process(Node externs, Node root) {
292 Preconditions.checkState(!loopMutex, "Nested loops are forbidden");
293 loopMutex = true;
294 if (randomizeLoops) {
295 randomizePasses();
296 } else {
297 optimizePasses();
298 }
299
300 compiler.addChangeHandler(recentChange);
301 // Contains a pass iff it made changes the last time it was run.
302 Set<NamedPass> madeChanges = new HashSet<NamedPass>();
303 // Contains a pass iff it was run during the last inner loop.
304 Set<NamedPass> runInPrevIter = new HashSet<NamedPass>();
305 State s = State.RUN_PASSES_NOT_RUN_IN_PREV_ITER;
306 boolean lastIterMadeChanges;
307 int count = 0;
308
309 try {
310 while (true) {
311 if (count++ > MAX_LOOPS) {
312 compiler.throwInternalError(OPTIMIZE_LOOP_ERROR, null);
313 }
314 lastIterMadeChanges = false;
315 for (NamedPass pass : myPasses) {
316 recentChange.reset();
317 if ((s == State.RUN_PASSES_NOT_RUN_IN_PREV_ITER &&
318 !runInPrevIter.contains(pass)) ||
319 (s == State.RUN_PASSES_THAT_CHANGED_STH_IN_PREV_ITER &&
320 madeChanges.contains(pass))) {
321 pass.process(externs, root);
322 runInPrevIter.add(pass);
323 if (hasHaltingErrors()) {
324 return;
325 } else if (recentChange.hasCodeChanged()) {
326 madeChanges.add(pass);
327 lastIterMadeChanges = true;
328 } else {
329 madeChanges.remove(pass);
330 }
331 } else {
332 runInPrevIter.remove(pass);
333 }
334 }
335 if (s == State.RUN_PASSES_NOT_RUN_IN_PREV_ITER) {
336 if (lastIterMadeChanges) {
337 s = State.RUN_PASSES_THAT_CHANGED_STH_IN_PREV_ITER;
338 } else {
339 return;
340 }
341 } else if (!lastIterMadeChanges) {
342 s = State.RUN_PASSES_NOT_RUN_IN_PREV_ITER;
343 }
344 }
345 } finally {
346 loopMutex = false;
347 compiler.removeChangeHandler(recentChange);
348 }
349 }
350
351 /** Re-arrange the passes in a random order. */
352 private void randomizePasses() {
353 Collections.shuffle(myPasses);
354 }
355
356 /** Re-arrange the passes in an optimal order. */
357 private void optimizePasses() {
358 // It's important that this ordering is deterministic, so that
359 // multiple compiles with the same input produce exactly the same
360 // results.
361 //
362 // To do this, grab any passes we recognize, and move them to the end
363 // in an "optimal" order.
364 List<NamedPass> optimalPasses = Lists.newArrayList();
365 for (String passName : OPTIMAL_ORDER) {
366 for (NamedPass pass : myPasses) {
367 if (pass.name.equals(passName)) {
368 optimalPasses.add(pass);
369 break;
370 }
371 }
372 }
373
374 myPasses.removeAll(optimalPasses);
375 myPasses.addAll(optimalPasses);
376 }
377 }
378
379 static class ProgressRange {
380 public final double initialValue;
381 public final double maxValue;
382
383 public ProgressRange(double initialValue, double maxValue) {
384 this.initialValue = initialValue;
385 this.maxValue = maxValue;
386 }
387 }
388 }