Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2005 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 package com.google.javascript.jscomp;
17
18 import com.google.common.base.Preconditions;
19 import com.google.common.base.Supplier;
20 import com.google.common.collect.Maps;
21 import com.google.common.collect.Sets;
22 import com.google.javascript.jscomp.FunctionInjector.CanInlineResult;
23 import com.google.javascript.jscomp.FunctionInjector.InliningMode;
24 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
25 import com.google.javascript.jscomp.NodeTraversal.Callback;
26 import com.google.javascript.rhino.Node;
27 import com.google.javascript.rhino.Token;
28
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.Iterator;
32 import java.util.Map;
33 import java.util.Map.Entry;
34 import java.util.Set;
35
36
37
38 /**
39 * Inlines functions that are divided into two types: "direct call node
40 * replacement" (aka "direct") and as a block of statements (aka block).
41 * Function that can be inlined "directly" functions consist of a single
42 * return statement, everything else is must be inlined as a "block". These
43 * functions must meet these general requirements:
44 * - it is not recursive
45 * - the function does not contain another function -- these may be
46 * intentional to to limit the scope of closures.
47 * - function is called only once OR the size of the inline function is smaller
48 * than the call itself.
49 * - the function name is not referenced in any other manner
50 *
51 * "directly" inlined functions must meet these additional requirements:
52 * - consists of a single return statement
53 *
54 */
55 class InlineFunctions implements SpecializationAwareCompilerPass {
56
57 // TODO(nicksantos): This needs to be completely rewritten to use scopes
58 // to do variable lookups. Right now, it assumes that all functions are
59 // uniquely named variables. There's currently a stopgap scope-check
60 // to ensure that this doesn't produce invalid code. But in the long run,
61 // this needs a major refactor.
62 private final Map<String, FunctionState> fns = Maps.newHashMap();
63 private final Map<Node, String> anonFns = Maps.newHashMap();
64
65 private final AbstractCompiler compiler;
66
67 private final FunctionInjector injector;
68
69 private final boolean blockFunctionInliningEnabled;
70 private final boolean inlineGlobalFunctions;
71 private final boolean inlineLocalFunctions;
72 private final boolean assumeMinimumCapture;
73
74 private SpecializeModule.SpecializationState specializationState;
75
76 InlineFunctions(AbstractCompiler compiler,
77 Supplier<String> safeNameIdSupplier,
78 boolean inlineGlobalFunctions,
79 boolean inlineLocalFunctions,
80 boolean blockFunctionInliningEnabled,
81 boolean assumeStrictThis,
82 boolean assumeMinimumCapture) {
83 Preconditions.checkArgument(compiler != null);
84 Preconditions.checkArgument(safeNameIdSupplier != null);
85 this.compiler = compiler;
86
87 this.inlineGlobalFunctions = inlineGlobalFunctions;
88 this.inlineLocalFunctions = inlineLocalFunctions;
89 this.blockFunctionInliningEnabled = blockFunctionInliningEnabled;
90 this.assumeMinimumCapture = assumeMinimumCapture;
91
92 this.injector = new FunctionInjector(
93 compiler, safeNameIdSupplier,
94 true, assumeStrictThis, assumeMinimumCapture);
95 }
96
97 FunctionState getOrCreateFunctionState(String fnName) {
98 FunctionState fs = fns.get(fnName);
99 if (fs == null) {
100 fs = new FunctionState();
101 fns.put(fnName, fs);
102 }
103 return fs;
104 }
105
106 @Override
107 public void enableSpecialization(SpecializeModule.SpecializationState
108 specializationState) {
109 this.specializationState = specializationState;
110 }
111
112 @Override
113 public void process(Node externs, Node root) {
114 Preconditions.checkState(compiler.getLifeCycleStage().isNormalized());
115
116 NodeTraversal.traverse(compiler, root, new FindCandidateFunctions());
117 if (fns.isEmpty()) {
118 return; // Nothing left to do.
119 }
120 NodeTraversal.traverse(compiler, root,
121 new FindCandidatesReferences(fns, anonFns));
122 trimCanidatesNotMeetingMinimumRequirements();
123 if (fns.isEmpty()) {
124 return; // Nothing left to do.
125 }
126
127 // Store the set of function names eligible for inlining and use this to
128 // prevent function names from being moved into temporaries during
129 // expression decomposition. If this movement were allowed it would prevent
130 // the Inline callback from finding the function calls.
131 //
132 // This pass already assumes these are constants, so this is safe for anyone
133 // using function inlining.
134 //
135 Set<String> fnNames = Sets.newHashSet(fns.keySet());
136 injector.setKnownConstants(fnNames);
137
138 trimCanidatesUsingOnCost();
139 if (fns.isEmpty()) {
140 return; // Nothing left to do.
141 }
142 resolveInlineConflicts();
143 decomposeExpressions();
144 NodeTraversal.traverse(compiler, root,
145 new CallVisitor(
146 fns, anonFns, new Inline(injector, specializationState)));
147
148 removeInlinedFunctions();
149 }
150
151 /**
152 * Find functions that might be inlined.
153 */
154 private class FindCandidateFunctions implements Callback {
155 private int callsSeen = 0;
156
157 @Override
158 public boolean shouldTraverse(
159 NodeTraversal nodeTraversal, Node n, Node parent) {
160 // Don't traverse into function bodies
161 // if we aren't inlining local functions.
162 return inlineLocalFunctions || nodeTraversal.inGlobalScope();
163 }
164
165 @Override
166 public void visit(NodeTraversal t, Node n, Node parent) {
167 if ((t.inGlobalScope() && inlineGlobalFunctions)
168 || (!t.inGlobalScope() && inlineLocalFunctions)) {
169 findNamedFunctions(t, n, parent);
170
171 findFunctionExpressions(t, n);
172 }
173 }
174
175 public void findNamedFunctions(NodeTraversal t, Node n, Node parent) {
176 if (!NodeUtil.isStatement(n)) {
177 // There aren't any interesting functions here.
178 return;
179 }
180
181 switch (n.getType()) {
182 // Functions expressions in the form of:
183 // var fooFn = function(x) { return ... }
184 case Token.VAR:
185 Preconditions.checkState(n.hasOneChild());
186 Node nameNode = n.getFirstChild();
187 if (nameNode.isName() && nameNode.hasChildren()
188 && nameNode.getFirstChild().isFunction()) {
189 maybeAddFunction(new FunctionVar(n), t.getModule());
190 }
191 break;
192
193 // Named functions
194 // function Foo(x) { return ... }
195 case Token.FUNCTION:
196 Preconditions.checkState(NodeUtil.isStatementBlock(parent)
197 || parent.isLabel());
198 if (!NodeUtil.isFunctionExpression(n)) {
199 Function fn = new NamedFunction(n);
200 maybeAddFunction(fn, t.getModule());
201 }
202 break;
203 }
204 }
205
206 /**
207 * Find function expressions that are called directly in the form of
208 * (function(a,b,...){...})(a,b,...)
209 * or
210 * (function(a,b,...){...}).call(this,a,b, ...)
211 */
212 public void findFunctionExpressions(NodeTraversal t, Node n) {
213 switch (n.getType()) {
214 // Functions expressions in the form of:
215 // (function(){})();
216 case Token.CALL:
217 Node fnNode = null;
218 if (n.getFirstChild().isFunction()) {
219 fnNode = n.getFirstChild();
220 } else if (NodeUtil.isFunctionObjectCall(n)) {
221 Node fnIdentifingNode = n.getFirstChild().getFirstChild();
222 if (fnIdentifingNode.isFunction()) {
223 fnNode = fnIdentifingNode;
224 }
225 }
226
227 // If a interesting function was discovered, add it.
228 if (fnNode != null) {
229 Function fn = new FunctionExpression(fnNode, callsSeen++);
230 maybeAddFunction(fn, t.getModule());
231 anonFns.put(fnNode, fn.getName());
232 }
233 break;
234 }
235 }
236 }
237
238 /**
239 * Updates the FunctionState object for the given function. Checks if the
240 * given function matches the criteria for an inlinable function.
241 */
242 private void maybeAddFunction(Function fn, JSModule module) {
243 String name = fn.getName();
244 FunctionState fs = getOrCreateFunctionState(name);
245
246 // TODO(johnlenz): Maybe "smarten" FunctionState by adding this logic
247 // to it?
248
249 // If the function has multiple definitions, don't inline it.
250 if (fs.hasExistingFunctionDefinition()) {
251 fs.setInline(false);
252 } else {
253 // verify the function hasn't already been marked as "don't inline"
254 if (fs.canInline()) {
255 // store it for use when inlining.
256 fs.setFn(fn);
257 if (injector.isDirectCallNodeReplacementPossible(
258 fn.getFunctionNode())) {
259 fs.inlineDirectly(true);
260 }
261
262 // verify the function meets all the requirements.
263 // TODO(johnlenz): Minimum requirement checks are about 5% of the
264 // run-time cost of this pass.
265 if (!isCandidateFunction(fn)) {
266 // It doesn't meet the requirements.
267 fs.setInline(false);
268 }
269
270 // Set the module and gather names that need temporaries.
271 if (fs.canInline()) {
272 fs.setModule(module);
273
274 Node fnNode = fn.getFunctionNode();
275 Set<String> namesToAlias =
276 FunctionArgumentInjector.findModifiedParameters(fnNode);
277 if (!namesToAlias.isEmpty()) {
278 fs.inlineDirectly(false);
279 fs.setNamesToAlias(namesToAlias);
280 }
281
282 Node block = NodeUtil.getFunctionBody(fnNode);
283 if (NodeUtil.referencesThis(block)) {
284 fs.setReferencesThis(true);
285 }
286
287 if (NodeUtil.containsFunction(block)) {
288 fs.setHasInnerFunctions(true);
289 // If there are inner functions, we can inline into global scope
290 // if there are no local vars or named functions.
291 // TODO(johnlenz): this can be improved by looking at the possible
292 // values for locals. If there are simple values, or constants
293 // we could still inline.
294 if (!assumeMinimumCapture && hasLocalNames(fnNode)) {
295 fs.setInline(false);
296 }
297 }
298 }
299
300 // Check if block inlining is allowed.
301 if (fs.canInline() && !fs.canInlineDirectly()) {
302 if (!blockFunctionInliningEnabled) {
303 fs.setInline(false);
304 }
305 }
306 }
307 }
308 }
309
310 /**
311 * @param fnNode The function to inspect.
312 * @return Whether the function has parameters, var, or function declarations.
313 */
314 private boolean hasLocalNames(Node fnNode) {
315 Node block = NodeUtil.getFunctionBody(fnNode);
316 return NodeUtil.getFunctionParameters(fnNode).hasChildren()
317 || NodeUtil.has(
318 block,
319 new NodeUtil.MatchDeclaration(),
320 new NodeUtil.MatchShallowStatement());
321 }
322
323 /**
324 * Returns the function the traversal is currently traversing, or null
325 * if in the global scope.
326 */
327 private static Node getContainingFunction(NodeTraversal t) {
328 return (t.inGlobalScope()) ? null : t.getScopeRoot();
329 }
330
331 /**
332 * Checks if the given function matches the criteria for an inlinable
333 * function.
334 */
335 private boolean isCandidateFunction(Function fn) {
336 // Don't inline exported functions.
337 String fnName = fn.getName();
338 if (compiler.getCodingConvention().isExported(fnName)) {
339 // TODO(johnlenz): Should we allow internal references to be inlined?
340 // An exported name can be replaced externally, any inlined instance
341 // would not reflect this change.
342 // To allow inlining we need to be able to distinguish between exports
343 // that are used in a read-only fashion and those that can be replaced
344 // by external definitions.
345 return false;
346 }
347
348 // Don't inline this special function
349 if (RenameProperties.RENAME_PROPERTY_FUNCTION_NAME.equals(fnName)) {
350 return false;
351 }
352
353 // Don't inline if we are specializing and the function can't be fixed up
354 if (specializationState != null &&
355 !specializationState.canFixupFunction(fn.getFunctionNode())) {
356 return false;
357 }
358
359 Node fnNode = fn.getFunctionNode();
360 return injector.doesFunctionMeetMinimumRequirements(fnName, fnNode);
361 }
362
363 /**
364 * @see CallVisitor
365 */
366 private interface CallVisitorCallback {
367 public void visitCallSite(
368 NodeTraversal t, Node callNode, Node parent, FunctionState fs);
369 }
370
371 /**
372 * Visit call sites for functions in functionMap.
373 */
374 private static class CallVisitor extends AbstractPostOrderCallback {
375
376 protected CallVisitorCallback callback;
377 private Map<String, FunctionState> functionMap;
378 private Map<Node, String> anonFunctionMap;
379
380 CallVisitor(Map<String, FunctionState> fns,
381 Map<Node, String> anonFns,
382 CallVisitorCallback callback) {
383 this.functionMap = fns;
384 this.anonFunctionMap = anonFns;
385 this.callback = callback;
386 }
387
388 @Override
389 public void visit(NodeTraversal t, Node n, Node parent) {
390 switch (n.getType()) {
391 // Function calls
392 case Token.CALL:
393 Node child = n.getFirstChild();
394 String name = null;
395 // NOTE: The normalization pass insures that local names do not
396 // collide with global names.
397 if (child.isName()) {
398 name = child.getString();
399 } else if (child.isFunction()) {
400 name = anonFunctionMap.get(child);
401 } else if (NodeUtil.isFunctionObjectCall(n)) {
402 Preconditions.checkState(NodeUtil.isGet(child));
403 Node fnIdentifingNode = child.getFirstChild();
404 if (fnIdentifingNode.isName()) {
405 name = fnIdentifingNode.getString();
406 } else if (fnIdentifingNode.isFunction()) {
407 name = anonFunctionMap.get(fnIdentifingNode);
408 }
409 }
410
411 if (name != null) {
412 FunctionState fs = functionMap.get(name);
413 // Only visit call-sites for functions that can be inlined.
414 if (fs != null) {
415 callback.visitCallSite(t, n, parent, fs);
416 }
417 }
418 break;
419 }
420 }
421 }
422
423 /**
424 * @return Whether the name is used in a way that might be a candidate
425 * for inlining.
426 */
427 static boolean isCandidateUsage(Node name) {
428 Node parent = name.getParent();
429 Preconditions.checkState(name.isName());
430 if (parent.isVar() || parent.isFunction()) {
431 // This is a declaration. Duplicate declarations are handle during
432 // function candidate gathering.
433 return true;
434 }
435
436 if (parent.isCall() && parent.getFirstChild() == name) {
437 // This is a normal reference to the function.
438 return true;
439 }
440
441 // Check for a ".call" to the named function:
442 // CALL
443 // GETPROP/GETELEM
444 // NAME
445 // STRING == "call"
446 // This-Value
447 // Function-parameter-1
448 // ...
449 if (NodeUtil.isGet(parent)
450 && name == parent.getFirstChild()
451 && name.getNext().isString()
452 && name.getNext().getString().equals("call")) {
453 Node gramps = name.getAncestor(2);
454 if (gramps.isCall()
455 && gramps.getFirstChild() == parent) {
456 // Yep, a ".call".
457 return true;
458 }
459 }
460 return false;
461 }
462
463 /**
464 * Find references to functions that are inlinable.
465 */
466 private class FindCandidatesReferences
467 extends CallVisitor
468 implements CallVisitorCallback {
469 FindCandidatesReferences(
470 Map<String, FunctionState> fns,
471 Map<Node, String> anonFns) {
472 super(fns, anonFns, null);
473 this.callback = this;
474 }
475
476 @Override
477 public void visit(NodeTraversal t, Node n, Node parent) {
478 super.visit(t, n, parent);
479 if (n.isName()) {
480 checkNameUsage(n, parent);
481 }
482 }
483
484 @Override
485 public void visitCallSite(
486 NodeTraversal t, Node callNode, Node parent, FunctionState fs) {
487 maybeAddReference(t, fs, callNode, t.getModule());
488 }
489
490 void maybeAddReference(NodeTraversal t, FunctionState fs,
491 Node callNode, JSModule module) {
492 if (!fs.canInline()) {
493 return;
494 }
495
496 boolean referenceAdded = false;
497 InliningMode mode = fs.canInlineDirectly()
498 ? InliningMode.DIRECT : InliningMode.BLOCK;
499 referenceAdded = maybeAddReferenceUsingMode(
500 t, fs, callNode, module, mode);
501 if (!referenceAdded &&
502 mode == InliningMode.DIRECT && blockFunctionInliningEnabled) {
503 // This reference can not be directly inlined, see if
504 // block replacement inlining is possible.
505 mode = InliningMode.BLOCK;
506 referenceAdded = maybeAddReferenceUsingMode(
507 t, fs, callNode, module, mode);
508 }
509
510 if (!referenceAdded) {
511 // Don't try to remove a function if we can't inline all
512 // the references.
513 fs.setRemove(false);
514 }
515 }
516
517 private boolean maybeAddReferenceUsingMode(
518 NodeTraversal t, FunctionState fs, Node callNode,
519 JSModule module, InliningMode mode) {
520
521 if (specializationState != null) {
522 // If we're specializing, make sure we can fixup
523 // the containing function before inlining
524 Node containingFunction = getContainingFunction(t);
525 if (containingFunction != null && !specializationState.canFixupFunction(
526 containingFunction)) {
527 return false;
528 }
529 }
530
531 CanInlineResult result = injector.canInlineReferenceToFunction(
532 t, callNode, fs.getFn().getFunctionNode(),
533 fs.getNamesToAlias(), mode, fs.getReferencesThis(),
534 fs.hasInnerFunctions());
535 if (result != CanInlineResult.NO) {
536 // Yeah!
537 boolean decompose =
538 (result == CanInlineResult.AFTER_PREPARATION);
539 fs.addReference(new Reference(callNode, module, mode, decompose));
540 return true;
541 }
542
543 return false;
544 }
545
546 /**
547 * Find functions that can be inlined.
548 */
549 private void checkNameUsage(Node n, Node parent) {
550 Preconditions.checkState(n.isName());
551
552 if (isCandidateUsage(n)) {
553 return;
554 }
555
556 // Other refs to a function name remove its candidacy for inlining
557 String name = n.getString();
558 FunctionState fs = fns.get(name);
559 if (fs == null) {
560 return;
561 }
562
563 // Unlike normal call/new parameters, references passed to
564 // JSCompiler_ObjectPropertyString are not aliases of a value, but
565 // a reference to the name itself, as such the value of the name is
566 // unknown and can not be inlined.
567 if (parent.isNew()) {
568 Node target = parent.getFirstChild();
569 if (target.isName() && target.getString().equals(
570 ObjectPropertyStringPreprocess.EXTERN_OBJECT_PROPERTY_STRING)) {
571 // This method is going to be replaced so don't inline it anywhere.
572 fs.setInline(false);
573 }
574 }
575
576 // If the name is being assigned to it can not be inlined.
577 if (parent.isAssign() && parent.getFirstChild() == n) {
578 // e.g. bar = something; <== we can't inline "bar"
579 // so mark the function as uninlinable.
580 // TODO(johnlenz): Should we just remove it from fns here?
581 fs.setInline(false);
582 } else {
583 // e.g. var fn = bar; <== we can't inline "bar"
584 // As this reference can't be inlined mark the function as
585 // unremovable.
586 fs.setRemove(false);
587 }
588 }
589 }
590
591 /**
592 * Inline functions at the call sites.
593 */
594 private static class Inline implements CallVisitorCallback {
595 private final FunctionInjector injector;
596 private final SpecializeModule.SpecializationState specializationState;
597
598 Inline(FunctionInjector injector,
599 SpecializeModule.SpecializationState specializationState) {
600 this.injector = injector;
601 this.specializationState = specializationState;
602 }
603
604 @Override
605 public void visitCallSite(
606 NodeTraversal t, Node callNode, Node parent, FunctionState fs) {
607 Preconditions.checkState(fs.hasExistingFunctionDefinition());
608 if (fs.canInline()) {
609 Reference ref = fs.getReference(callNode);
610 // There are two cases ref can be null: if the call site was introduce
611 // because it was part of a function that was inlined during this pass
612 // or if the call site was trimmed from the list of references because
613 // the function couldn't be inlined at this location.
614 if (ref != null) {
615 if (specializationState != null) {
616 Node containingFunction = getContainingFunction(t);
617
618 if (containingFunction != null) {
619 // Report that the function was specialized so that
620 // {@link SpecializeModule} can fix it up.
621 specializationState.reportSpecializedFunction(containingFunction);
622 }
623 }
624
625 inlineFunction(t, callNode, fs, ref.mode);
626 // Keep track of references that have been inlined so that
627 // we can verify that none have been missed.
628 ref.inlined = true;
629 }
630 }
631 }
632
633 /**
634 * Inline a function into the call site.
635 */
636 private void inlineFunction(
637 NodeTraversal t, Node callNode, FunctionState fs, InliningMode mode) {
638 Function fn = fs.getFn();
639 String fnName = fn.getName();
640 Node fnNode = fs.getSafeFnNode();
641
642 injector.inline(callNode, fnName, fnNode, mode);
643 t.getCompiler().reportCodeChange();
644 t.getCompiler().addToDebugLog("Inlined function: " + fn.getName());
645 }
646 }
647
648 /**
649 * Remove entries that aren't a valid inline candidates, from the list of
650 * encountered names.
651 */
652 private void trimCanidatesNotMeetingMinimumRequirements() {
653 Iterator<Entry<String, FunctionState>> i;
654 for (i = fns.entrySet().iterator(); i.hasNext();) {
655 FunctionState fs = i.next().getValue();
656 if (!fs.hasExistingFunctionDefinition() || !fs.canInline()) {
657 i.remove();
658 }
659 }
660 }
661
662 /**
663 * Remove entries from the list of candidates that can't be inlined.
664 */
665 void trimCanidatesUsingOnCost() {
666 Iterator<Entry<String, FunctionState>> i;
667 for (i = fns.entrySet().iterator(); i.hasNext();) {
668 FunctionState fs = i.next().getValue();
669 if (fs.hasReferences()) {
670 // Only inline function if it decreases the code size.
671 boolean lowersCost = mimimizeCost(fs);
672 if (!lowersCost) {
673 // It shouldn't be inlined; remove it from the list.
674 i.remove();
675 }
676 } else if (!fs.canRemove()) {
677 // Don't bother tracking functions without references that can't be
678 // removed.
679 i.remove();
680 }
681 }
682 }
683
684 /**
685 * Determines if the function is worth inlining and potentially
686 * trims references that increase the cost.
687 * @return Whether inlining the references lowers the overall cost.
688 */
689 private boolean mimimizeCost(FunctionState fs) {
690 if (!inliningLowersCost(fs)) {
691 // Try again without Block inlining references
692 if (fs.hasBlockInliningReferences()) {
693 fs.setRemove(false);
694 fs.removeBlockInliningReferences();
695 if (!fs.hasReferences() || !inliningLowersCost(fs)) {
696 return false;
697 }
698 } else {
699 return false;
700 }
701 }
702 return true;
703 }
704
705 /**
706 * @return Whether inlining the function reduces code size.
707 */
708 private boolean inliningLowersCost(FunctionState fs) {
709 return injector.inliningLowersCost(
710 fs.getModule(),
711 fs.getFn().getFunctionNode(),
712 fs.getReferences(),
713 fs.getNamesToAlias(),
714 fs.canRemove(),
715 fs.getReferencesThis());
716 }
717
718
719 /**
720 * Size base inlining calculations are thrown off when a function that is
721 * being inlined also contains calls to functions that are slated for
722 * inlining.
723 *
724 * Specifically, a clone of the FUNCTION node tree is used when the function
725 * is inlined. Calls in this new tree are not included in the list of function
726 * references so they won't be inlined (which is what we want). Here we mark
727 * those functions as non-removable (as they will have new references in the
728 * cloned node trees).
729 *
730 * This prevents a function that would only be inlined because it is
731 * referenced once from being inlined into multiple call sites because
732 * the calling function has been inlined in multiple locations or the
733 * function being removed while there are still references.
734 */
735 private void resolveInlineConflicts() {
736 for (FunctionState fs : fns.values()) {
737 resolveInlineConflictsForFunction(fs);
738 }
739 }
740
741 /**
742 * @see #resolveInlineConflicts
743 */
744 private void resolveInlineConflictsForFunction(FunctionState fs) {
745 // Functions that aren't referenced don't cause conflicts.
746 if (!fs.hasReferences() || !fs.canInline()) {
747 return;
748 }
749
750 Node fnNode = fs.getFn().getFunctionNode();
751 Set<String> names = findCalledFunctions(fnNode);
752 if (!names.isEmpty()) {
753 // Prevent the removal of the referenced functions.
754 for (String name : names) {
755 FunctionState fsCalled = fns.get(name);
756 if (fsCalled != null && fsCalled.canRemove()) {
757 fsCalled.setRemove(false);
758 // For functions that can no longer be removed, check if they should
759 // still be inlined.
760 if (!mimimizeCost(fsCalled)) {
761 // It can't be inlined remove it from the list.
762 fsCalled.setInline(false);
763 }
764 }
765 }
766
767 // Make a copy of the Node, so it isn't changed by other inlines.
768 fs.setSafeFnNode(fs.getFn().getFunctionNode().cloneTree());
769 }
770 }
771
772 /**
773 * This functions that may be called directly.
774 */
775 private Set<String> findCalledFunctions(Node node) {
776 Set<String> changed = Sets.newHashSet();
777 findCalledFunctions(NodeUtil.getFunctionBody(node), changed);
778 return changed;
779 }
780
781 /**
782 * @see #findCalledFunctions(Node)
783 */
784 private void findCalledFunctions(
785 Node node, Set<String> changed) {
786 Preconditions.checkArgument(changed != null);
787 // For each referenced function, add a new reference
788 if (node.isName()) {
789 if (isCandidateUsage(node)) {
790 changed.add(node.getString());
791 }
792 }
793
794 for (Node c = node.getFirstChild(); c != null; c = c.getNext()) {
795 findCalledFunctions(c, changed);
796 }
797 }
798
799 /**
800 * For any call-site that needs it, prepare the call-site for inlining
801 * by rewriting the containing expression.
802 */
803 private void decomposeExpressions() {
804 for (FunctionState fs : fns.values()) {
805 if (fs.canInline()) {
806 for (Reference ref : fs.getReferences()) {
807 if (ref.requiresDecomposition) {
808 injector.maybePrepareCall(ref.callNode);
809 }
810 }
811 }
812 }
813 }
814
815 /**
816 * Removed inlined functions that no longer have any references.
817 */
818 void removeInlinedFunctions() {
819 for (FunctionState fs : fns.values()) {
820 if (fs.canRemove()) {
821 Function fn = fs.getFn();
822 Preconditions.checkState(fs.canInline());
823 Preconditions.checkState(fn != null);
824 verifyAllReferencesInlined(fs);
825
826 if (specializationState != null) {
827 specializationState.reportRemovedFunction(
828 fn.getFunctionNode(), fn.getDeclaringBlock());
829 }
830
831 fn.remove();
832 compiler.reportCodeChange();
833 }
834 }
835 }
836
837 /**
838 * Sanity check to verify, that expression rewriting didn't
839 * make a call inaccessible.
840 */
841 void verifyAllReferencesInlined(FunctionState fs) {
842 for (Reference ref : fs.getReferences()) {
843 if (!ref.inlined) {
844 throw new IllegalStateException("Call site missed.\n call: "
845 + ref.callNode.toStringTree() + "\n parent: "
846 + ref.callNode.getParent().toStringTree());
847 }
848 }
849 }
850
851 /**
852 * Use to track the decisions that have been make about a function.
853 */
854 private static class FunctionState {
855 private Function fn = null;
856 private Node safeFnNode = null;
857 private boolean inline = true;
858 private boolean remove = true;
859 private boolean inlineDirectly = false;
860 private boolean referencesThis = false;
861 private boolean hasInnerFunctions = false;
862 private Map<Node, Reference> references = null;
863 private JSModule module = null;
864 private Set<String> namesToAlias = null;
865
866 boolean hasExistingFunctionDefinition() {
867 return (fn != null);
868 }
869
870 public void setReferencesThis(boolean referencesThis) {
871 this.referencesThis = referencesThis;
872 }
873
874 public boolean getReferencesThis() {
875 return this.referencesThis;
876 }
877
878 public void setHasInnerFunctions(boolean hasInnerFunctions) {
879 this.hasInnerFunctions = hasInnerFunctions;
880 }
881
882
883 public boolean hasInnerFunctions() {
884 return hasInnerFunctions;
885 }
886
887 void removeBlockInliningReferences() {
888 Iterator<Entry<Node, Reference>> i;
889 for (i = getReferencesInternal().entrySet().iterator(); i.hasNext();) {
890 Entry<Node, Reference> entry = i.next();
891 if (entry.getValue().mode == InliningMode.BLOCK) {
892 i.remove();
893 }
894 }
895 }
896
897 public boolean hasBlockInliningReferences() {
898 for (Reference r : getReferencesInternal().values()) {
899 if (r.mode == InliningMode.BLOCK) {
900 return true;
901 }
902 }
903 return false;
904 }
905
906 public Function getFn() {
907 return fn;
908 }
909
910 public void setFn(Function fn) {
911 Preconditions.checkState(this.fn == null);
912 this.fn = fn;
913 }
914
915 public Node getSafeFnNode() {
916 return (safeFnNode != null) ? safeFnNode : fn.getFunctionNode();
917 }
918
919 public void setSafeFnNode(Node safeFnNode) {
920 this.safeFnNode = safeFnNode;
921 }
922
923 public boolean canInline() {
924 return inline;
925 }
926
927 public void setInline(boolean inline) {
928 this.inline = inline;
929 if (inline == false) {
930 // No need to keep references to function that can't be inlined.
931 references = null;
932 // Don't remove functions that we aren't inlining.
933 remove = false;
934 }
935 }
936
937 public boolean canRemove() {
938 return remove;
939 }
940
941 public void setRemove(boolean remove) {
942 this.remove = remove;
943 }
944
945 public boolean canInlineDirectly() {
946 return inlineDirectly;
947 }
948
949 public void inlineDirectly(boolean directReplacement) {
950 this.inlineDirectly = directReplacement;
951 }
952
953 public boolean hasReferences() {
954 return (references != null && !references.isEmpty());
955 }
956
957 private Map<Node, Reference> getReferencesInternal() {
958 if (references == null) {
959 return Collections.emptyMap();
960 }
961 return references;
962 }
963
964 public void addReference(Reference ref) {
965 if (references == null) {
966 references = Maps.newLinkedHashMap();
967 }
968 references.put(ref.callNode, ref);
969 }
970
971 public Collection<Reference> getReferences() {
972 return getReferencesInternal().values();
973 }
974
975 public Reference getReference(Node n) {
976 return getReferencesInternal().get(n);
977 }
978
979 public Set<String> getNamesToAlias() {
980 if (namesToAlias == null) {
981 return Collections.emptySet();
982 }
983 return Collections.unmodifiableSet(namesToAlias);
984 }
985
986 public void setNamesToAlias(Set<String> names) {
987 namesToAlias = names;
988 }
989
990 public void setModule(JSModule module) {
991 this.module = module;
992 }
993
994 public JSModule getModule() {
995 return module;
996 }
997 }
998
999 /**
1000 * Interface for dealing with function declarations and function
1001 * expressions equally
1002 */
1003 private static interface Function {
1004 /** Gets the name of the function */
1005 public String getName();
1006
1007 /** Gets the function node */
1008 public Node getFunctionNode();
1009
1010 /** Removes itself from the JavaScript */
1011 public void remove();
1012
1013 public Node getDeclaringBlock();
1014 }
1015
1016 /** NamedFunction implementation of the Function interface */
1017 private static class NamedFunction implements Function {
1018 private final Node fn;
1019
1020 public NamedFunction(Node fn) {
1021 this.fn = fn;
1022 }
1023
1024 @Override
1025 public String getName() {
1026 return fn.getFirstChild().getString();
1027 }
1028
1029 @Override
1030 public Node getFunctionNode() {
1031 return fn;
1032 }
1033
1034 @Override
1035 public void remove() {
1036 NodeUtil.removeChild(fn.getParent(), fn);
1037 }
1038
1039 @Override
1040 public Node getDeclaringBlock() {
1041 return fn.getParent();
1042 }
1043 }
1044
1045 /** FunctionVar implementation of the Function interface */
1046 private static class FunctionVar implements Function {
1047 private final Node var;
1048
1049 public FunctionVar(Node var) {
1050 this.var = var;
1051 }
1052
1053 @Override
1054 public String getName() {
1055 return var.getFirstChild().getString();
1056 }
1057
1058 @Override
1059 public Node getFunctionNode() {
1060 return var.getFirstChild().getFirstChild();
1061 }
1062
1063 @Override
1064 public void remove() {
1065 NodeUtil.removeChild(var.getParent(), var);
1066 }
1067
1068 @Override
1069 public Node getDeclaringBlock() {
1070 return var.getParent();
1071 }
1072 }
1073
1074 /** FunctionExpression implementation of the Function interface */
1075 private static class FunctionExpression implements Function {
1076 private final Node fn;
1077 private final String fakeName;
1078
1079 public FunctionExpression(Node fn, int index) {
1080 this.fn = fn;
1081 // A number is not a valid function JavaScript identifier
1082 // so we don't need to worry about collisions.
1083 this.fakeName = String.valueOf(index);
1084 }
1085
1086 @Override
1087 public String getName() {
1088 return fakeName;
1089 }
1090
1091 @Override
1092 public Node getFunctionNode() {
1093 return fn;
1094 }
1095
1096 @Override
1097 public void remove() {
1098 // Nothing to do. The function is removed with the call.
1099 }
1100
1101 @Override
1102 public Node getDeclaringBlock() {
1103 return null;
1104 }
1105
1106 }
1107
1108 class Reference extends FunctionInjector.Reference {
1109 final boolean requiresDecomposition;
1110 boolean inlined = false;
1111 Reference(
1112 Node callNode, JSModule module, InliningMode mode, boolean decompose) {
1113 super(callNode, module, mode);
1114 this.requiresDecomposition = decompose;
1115 }
1116 }
1117 }