Debian Codegraph @

src/com/google/javascript/jscomp/FunctionInjector.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 package com.google.javascript.jscomp;
17
18 import com.google.common.base.Preconditions;
19 import com.google.common.base.Predicate;
20 import com.google.common.base.Predicates;
21 import com.google.common.base.Supplier;
22 import com.google.common.collect.Sets;
23 import com.google.javascript.jscomp.ExpressionDecomposer.DecompositionType;
24 import com.google.javascript.rhino.Node;
25 import com.google.javascript.rhino.Token;
26
27 import java.util.Collection;
28 import java.util.Map;
29 import java.util.Set;
30
31 /**
32 * A set of utility functions that replaces CALL with a specified
33 * FUNCTION body, replacing and aliasing function parameters as
34 * necessary.
35 *
36 * @author [email protected] (John Lenz)
37 */
38 class FunctionInjector {
39
40 private final AbstractCompiler compiler;
41 private final Supplier<String> safeNameIdSupplier;
42 private final boolean allowDecomposition;
43 private Set<String> knownConstants = Sets.newHashSet();
44 private final boolean assumeStrictThis;
45 private final boolean assumeMinimumCapture;
46
47 /**
48 * @param allowDecomposition Whether an effort should be made to break down
49 * expressions into simpler expressions to allow functions to be injected
50 * where they would otherwise be disallowed.
51 */
52 public FunctionInjector(
53 AbstractCompiler compiler,
54 Supplier<String> safeNameIdSupplier,
55 boolean allowDecomposition,
56 boolean assumeStrictThis,
57 boolean assumeMinimumCapture) {
58 Preconditions.checkNotNull(compiler);
59 Preconditions.checkNotNull(safeNameIdSupplier);
60 this.compiler = compiler;
61 this.safeNameIdSupplier = safeNameIdSupplier;
62 this.allowDecomposition = allowDecomposition;
63 this.assumeStrictThis = assumeStrictThis;
64 this.assumeMinimumCapture = assumeMinimumCapture;
65 }
66
67 /** The type of inlining to perform. */
68 enum InliningMode {
69 /**
70 * Directly replace the call expression. Only functions of meeting
71 * strict preconditions can be inlined.
72 */
73 DIRECT,
74
75 /**
76 * Replaces the call expression with a block of statements. Conditions
77 * on the function are looser in mode, but stricter on the call site.
78 */
79 BLOCK
80 }
81
82 /** Holds a reference to the call node of a function call */
83 static class Reference {
84 final Node callNode;
85 final JSModule module;
86 final InliningMode mode;
87
88 Reference(Node callNode, JSModule module, InliningMode mode){
89 this.callNode = callNode;
90 this.module = module;
91 this.mode = mode;
92 }
93 }
94
95 /**
96 * In order to estimate the cost of lining, we make the assumption that
97 * Identifiers are reduced 2 characters. For the call arguments, the important
98 * thing is that the cost is assumed to be the same in the call and the
99 * function, so the actual length doesn't matter in most cases.
100 */
101 private static final int NAME_COST_ESTIMATE =
102 InlineCostEstimator.ESTIMATED_IDENTIFIER_COST;
103
104 /** The cost of a argument separator (a comma). */
105 private static final int COMMA_COST = 1;
106
107 /** The cost of the parentheses needed to make a call.*/
108 private static final int PAREN_COST = 2;
109
110
111 /**
112 * @param fnName The name of this function. This either the name of the
113 * variable to which the function is assigned or the name from the FUNCTION
114 * node.
115 * @param fnNode The FUNCTION node of the function to inspect.
116 * @return Whether the function node meets the minimum requirements for
117 * inlining.
118 */
119 boolean doesFunctionMeetMinimumRequirements(
120 final String fnName, Node fnNode) {
121 Node block = NodeUtil.getFunctionBody(fnNode);
122
123 // Basic restrictions on functions that can be inlined:
124 // 0) The function is inlinable by convention
125 // 1) It contains a reference to itself.
126 // 2) It uses its parameters indirectly using "arguments" (it isn't
127 // handled yet.
128 // 3) It references "eval". Inline a function containing eval can have
129 // large performance implications.
130
131 if (!compiler.getCodingConvention().isInlinableFunction(fnNode)) {
132 return false;
133 }
134
135 final String fnRecursionName = fnNode.getFirstChild().getString();
136 Preconditions.checkState(fnRecursionName != null);
137
138 // If the function references "arguments" directly in the function
139 boolean referencesArguments = NodeUtil.isNameReferenced(
140 block, "arguments", NodeUtil.MATCH_NOT_FUNCTION);
141
142 // or it references "eval" or one of its names anywhere.
143 Predicate<Node> p = new Predicate<Node>(){
144 @Override
145 public boolean apply(Node n) {
146 if (n.isName()) {
147 return n.getString().equals("eval")
148 || (!fnName.isEmpty()
149 && n.getString().equals(fnName))
150 || (!fnRecursionName.isEmpty()
151 && n.getString().equals(fnRecursionName));
152 }
153 return false;
154 }
155 };
156
157 return !referencesArguments
158 && !NodeUtil.has(block, p, Predicates.<Node>alwaysTrue());
159 }
160
161 /**
162 * @param t The traversal use to reach the call site.
163 * @param callNode The CALL node.
164 * @param fnNode The function to evaluate for inlining.
165 * @param needAliases A set of function parameter names that can not be
166 * used without aliasing. Returned by getUnsafeParameterNames().
167 * @param mode Inlining mode to be used.
168 * @param referencesThis Whether fnNode contains references to its this
169 * object.
170 * @param containsFunctions Whether fnNode contains inner functions.
171 * @return Whether the inlining can occur.
172 */
173 CanInlineResult canInlineReferenceToFunction(NodeTraversal t,
174 Node callNode, Node fnNode, Set<String> needAliases,
175 InliningMode mode, boolean referencesThis, boolean containsFunctions) {
176 // TODO(johnlenz): This function takes too many parameter, without
177 // context. Modify the API to take a structure describing the function.
178
179 // Allow direct function calls or "fn.call" style calls.
180 if (!isSupportedCallType(callNode)) {
181 return CanInlineResult.NO;
182 }
183
184 // Limit where functions that contain functions can be inline. Introducing
185 // an inner function into another function can capture a variable and cause
186 // a memory leak. This isn't a problem in the global scope as those values
187 // last until explicitly cleared.
188 if (containsFunctions) {
189 if (!assumeMinimumCapture && !t.inGlobalScope()) {
190 // TODO(johnlenz): Allow inlining into any scope without local names or
191 // inner functions.
192 return CanInlineResult.NO;
193 } else if (NodeUtil.isWithinLoop(callNode)) {
194 // An inner closure maybe relying on a local value holding a value for a
195 // single iteration through a loop.
196 return CanInlineResult.NO;
197 }
198 }
199
200 // TODO(johnlenz): Add support for 'apply'
201 if (referencesThis && !NodeUtil.isFunctionObjectCall(callNode)) {
202 // TODO(johnlenz): Allow 'this' references to be replaced with a
203 // global 'this' object.
204 return CanInlineResult.NO;
205 }
206
207 if (mode == InliningMode.DIRECT) {
208 return canInlineReferenceDirectly(callNode, fnNode);
209 } else {
210 return canInlineReferenceAsStatementBlock(
211 t, callNode, fnNode, needAliases);
212 }
213 }
214
215 /**
216 * Only ".call" calls and direct calls to functions are supported.
217 * @param callNode The call evaluate.
218 * @return Whether the call is of a type that is supported.
219 */
220 private boolean isSupportedCallType(Node callNode) {
221 if (!callNode.getFirstChild().isName()) {
222 if (NodeUtil.isFunctionObjectCall(callNode)) {
223 if (!assumeStrictThis) {
224 Node thisValue = callNode.getFirstChild().getNext();
225 if (thisValue == null || !thisValue.isThis()) {
226 return false;
227 }
228 }
229 } else if (NodeUtil.isFunctionObjectApply(callNode)) {
230 return false;
231 }
232 }
233
234 return true;
235 }
236
237 /**
238 * Inline a function into the call site.
239 */
240 Node inline(
241 Node callNode, String fnName, Node fnNode, InliningMode mode) {
242 Preconditions.checkState(compiler.getLifeCycleStage().isNormalized());
243
244 if (mode == InliningMode.DIRECT) {
245 return inlineReturnValue(callNode, fnNode);
246 } else {
247 return inlineFunction(callNode, fnNode, fnName);
248 }
249 }
250
251 /**
252 * Inline a function that fulfills the requirements of
253 * canInlineReferenceDirectly into the call site, replacing only the CALL
254 * node.
255 */
256 private Node inlineReturnValue(Node callNode, Node fnNode) {
257 Node block = fnNode.getLastChild();
258 Node callParentNode = callNode.getParent();
259
260 // NOTE: As the normalize pass guarantees globals aren't being
261 // shadowed and an expression can't introduce new names, there is
262 // no need to check for conflicts.
263
264 // Create an argName -> expression map, checking for side effects.
265 Map<String, Node> argMap =
266 FunctionArgumentInjector.getFunctionCallParameterMap(
267 fnNode, callNode, this.safeNameIdSupplier);
268
269 Node newExpression;
270 if (!block.hasChildren()) {
271 Node srcLocation = block;
272 newExpression = NodeUtil.newUndefinedNode(srcLocation);
273 } else {
274 Node returnNode = block.getFirstChild();
275 Preconditions.checkArgument(returnNode.isReturn());
276
277 // Clone the return node first.
278 Node safeReturnNode = returnNode.cloneTree();
279 Node inlineResult = FunctionArgumentInjector.inject(
280 null, safeReturnNode, null, argMap);
281 Preconditions.checkArgument(safeReturnNode == inlineResult);
282 newExpression = safeReturnNode.removeFirstChild();
283 }
284
285 callParentNode.replaceChild(callNode, newExpression);
286 return newExpression;
287 }
288
289 /**
290 * Supported call site types.
291 */
292 private enum CallSiteType {
293
294 /**
295 * Used for a call site for which there does not exist a method
296 * to inline it.
297 */
298 UNSUPPORTED() {
299 @Override
300 public void prepare(FunctionInjector injector, Node callNode) {
301 throw new IllegalStateException("unexpected");
302 }
303 },
304
305 /**
306 * A call as a statement. For example: "foo();".
307 * EXPR_RESULT
308 * CALL
309 */
310 SIMPLE_CALL() {
311 @Override
312 public void prepare(FunctionInjector injector, Node callNode) {
313 // Nothing to do.
314 }
315 },
316
317 /**
318 * An assignment, where the result of the call is assigned to a simple
319 * name. For example: "a = foo();".
320 * EXPR_RESULT
321 * NAME A
322 * CALL
323 * FOO
324 */
325 SIMPLE_ASSIGNMENT() {
326 @Override
327 public void prepare(FunctionInjector injector, Node callNode) {
328 // Nothing to do.
329 }
330 },
331 /**
332 * An var declaration and initialization, where the result of the call is
333 * assigned to the declared name
334 * name. For example: "a = foo();".
335 * VAR
336 * NAME A
337 * CALL
338 * FOO
339 */
340 VAR_DECL_SIMPLE_ASSIGNMENT() {
341 @Override
342 public void prepare(FunctionInjector injector, Node callNode) {
343 // Nothing to do.
344 }
345 },
346 /**
347 * An arbitrary expression, the root of which is a EXPR_RESULT, IF,
348 * RETURN, SWITCH or VAR. The call must be the first side-effect in
349 * the expression.
350 *
351 * Examples include:
352 * "if (foo()) {..."
353 * "return foo();"
354 * "var a = 1 + foo();"
355 * "a = 1 + foo()"
356 * "foo() ? 1:0"
357 * "foo() && x"
358 */
359 EXPRESSION() {
360 @Override
361 public void prepare(FunctionInjector injector, Node callNode) {
362 injector.getDecomposer().moveExpression(callNode);
363
364 // Reclassify after move
365 CallSiteType callSiteType = injector.classifyCallSite(callNode);
366 Preconditions.checkState(this != callSiteType);
367 callSiteType.prepare(injector, callNode);
368 }
369 },
370
371 /**
372 * An arbitrary expression, the root of which is a EXPR_RESULT, IF,
373 * RETURN, SWITCH or VAR. Where the call is not the first side-effect in
374 * the expression.
375 */
376 DECOMPOSABLE_EXPRESSION() {
377 @Override
378 public void prepare(FunctionInjector injector, Node callNode) {
379 injector.getDecomposer().maybeExposeExpression(callNode);
380
381 // Reclassify after decomposition
382 CallSiteType callSiteType = injector.classifyCallSite(callNode);
383 Preconditions.checkState(this != callSiteType);
384 callSiteType.prepare(injector, callNode);
385 }
386 };
387
388 public abstract void prepare(FunctionInjector injector, Node callNode);
389 }
390
391 /**
392 * Determine which, if any, of the supported types the call site is.
393 */
394 private CallSiteType classifyCallSite(Node callNode) {
395 Node parent = callNode.getParent();
396 Node grandParent = parent.getParent();
397
398 // Verify the call site:
399 if (NodeUtil.isExprCall(parent)) {
400 // This is a simple call? Example: "foo();".
401 return CallSiteType.SIMPLE_CALL;
402 } else if (NodeUtil.isExprAssign(grandParent)
403 && !NodeUtil.isVarOrSimpleAssignLhs(callNode, parent)
404 && parent.getFirstChild().isName()
405 && !NodeUtil.isConstantName(parent.getFirstChild())) {
406 // This is a simple assignment. Example: "x = foo();"
407 return CallSiteType.SIMPLE_ASSIGNMENT;
408 } else if (parent.isName()
409 && !NodeUtil.isConstantName(parent)
410 && grandParent.isVar()
411 && grandParent.hasOneChild()) {
412 // This is a var declaration. Example: "var x = foo();"
413 // TODO(johnlenz): Should we be checking for constants on the
414 // left-hand-side of the assignments and handling them as EXPRESSION?
415 return CallSiteType.VAR_DECL_SIMPLE_ASSIGNMENT;
416 } else {
417 Node expressionRoot = ExpressionDecomposer.findExpressionRoot(callNode);
418 if (expressionRoot != null) {
419 ExpressionDecomposer decomposer = new ExpressionDecomposer(
420 compiler, safeNameIdSupplier, knownConstants);
421 DecompositionType type = decomposer.canExposeExpression(
422 callNode);
423 if (type == DecompositionType.MOVABLE) {
424 return CallSiteType.EXPRESSION;
425 } else if (type == DecompositionType.DECOMPOSABLE) {
426 return CallSiteType.DECOMPOSABLE_EXPRESSION;
427 } else {
428 Preconditions.checkState(type == DecompositionType.UNDECOMPOSABLE);
429 }
430 }
431 }
432
433 return CallSiteType.UNSUPPORTED;
434 }
435
436 private ExpressionDecomposer getDecomposer() {
437 return new ExpressionDecomposer(
438 compiler, safeNameIdSupplier, knownConstants);
439 }
440
441 /**
442 * If required, rewrite the statement containing the call expression.
443 * @see ExpressionDecomposer#canExposeExpression
444 */
445 void maybePrepareCall(Node callNode) {
446 CallSiteType callSiteType = classifyCallSite(callNode);
447 callSiteType.prepare(this, callNode);
448 }
449
450 /**
451 * Inline a function which fulfills the requirements of
452 * canInlineReferenceAsStatementBlock into the call site, replacing the
453 * parent expression.
454 */
455 private Node inlineFunction(
456 Node callNode, Node fnNode, String fnName) {
457 Node parent = callNode.getParent();
458 Node grandParent = parent.getParent();
459
460 // TODO(johnlenz): Consider storing the callSite classification in the
461 // reference object and passing it in here.
462 CallSiteType callSiteType = classifyCallSite(callNode);
463 Preconditions.checkArgument(callSiteType != CallSiteType.UNSUPPORTED);
464
465 boolean isCallInLoop = NodeUtil.isWithinLoop(callNode);
466
467 // Store the name for the result. This will be used to
468 // replace "return expr" statements with "resultName = expr"
469 // to replace
470 String resultName = null;
471 boolean needsDefaultReturnResult = true;
472 switch (callSiteType) {
473 case SIMPLE_ASSIGNMENT:
474 resultName = parent.getFirstChild().getString();
475 break;
476
477 case VAR_DECL_SIMPLE_ASSIGNMENT:
478 resultName = parent.getString();
479 break;
480
481 case SIMPLE_CALL:
482 resultName = null; // "foo()" doesn't need a result.
483 needsDefaultReturnResult = false;
484 break;
485
486 case EXPRESSION:
487 throw new IllegalStateException(
488 "Movable expressions must be moved before inlining.");
489
490 case DECOMPOSABLE_EXPRESSION:
491 throw new IllegalStateException(
492 "Decomposable expressions must be decomposed before inlining.");
493
494 default:
495 throw new IllegalStateException("Unexpected call site type.");
496 }
497
498 FunctionToBlockMutator mutator = new FunctionToBlockMutator(
499 compiler, this.safeNameIdSupplier);
500
501 Node newBlock = mutator.mutate(
502 fnName, fnNode, callNode, resultName,
503 needsDefaultReturnResult, isCallInLoop);
504
505 // TODO(nicksantos): Create a common mutation function that
506 // can replace either a VAR name assignment, assignment expression or
507 // a EXPR_RESULT.
508 Node greatGrandParent = grandParent.getParent();
509 switch (callSiteType) {
510 case VAR_DECL_SIMPLE_ASSIGNMENT:
511 // Remove the call from the name node.
512 parent.removeChild(parent.getFirstChild());
513 Preconditions.checkState(parent.getFirstChild() == null);
514 // Add the call, after the VAR.
515 greatGrandParent.addChildAfter(newBlock, grandParent);
516 break;
517
518 case SIMPLE_ASSIGNMENT:
519 // The assignment is now part of the inline function so
520 // replace it completely.
521 Preconditions.checkState(grandParent.isExprResult());
522 greatGrandParent.replaceChild(grandParent, newBlock);
523 break;
524
525 case SIMPLE_CALL:
526 // If nothing is looking at the result just replace the call.
527 Preconditions.checkState(parent.isExprResult());
528 grandParent.replaceChild(parent, newBlock);
529 break;
530
531 default:
532 throw new IllegalStateException("Unexpected call site type.");
533 }
534
535 return newBlock;
536 }
537
538 /**
539 * Checks if the given function matches the criteria for an inlinable
540 * function, and if so, adds it to our set of inlinable functions.
541 */
542 boolean isDirectCallNodeReplacementPossible(Node fnNode) {
543 // Only inline single-statement functions
544 Node block = NodeUtil.getFunctionBody(fnNode);
545
546 // Check if this function is suitable for direct replacement of a CALL node:
547 // a function that consists of single return that returns an expression.
548 if (!block.hasChildren()) {
549 // special case empty functions.
550 return true;
551 } else if (block.hasOneChild()) {
552 // Only inline functions that return something.
553 if (block.getFirstChild().isReturn()
554 && block.getFirstChild().getFirstChild() != null) {
555 return true;
556 }
557 }
558
559 return false;
560 }
561
562 enum CanInlineResult {
563 YES,
564 AFTER_PREPARATION,
565 NO
566 }
567
568 /**
569 * Determines whether a function can be inlined at a particular call site.
570 * There are several criteria that the function and reference must hold in
571 * order for the functions to be inlined:
572 * - It must be a simple call, or assignment, or var initialization.
573 * <pre>
574 * f();
575 * a = foo();
576 * var a = foo();
577 * </pre>
578 */
579 private CanInlineResult canInlineReferenceAsStatementBlock(
580 NodeTraversal t, Node callNode, Node fnNode, Set<String> namesToAlias) {
581 CallSiteType callSiteType = classifyCallSite(callNode);
582 if (callSiteType == CallSiteType.UNSUPPORTED) {
583 return CanInlineResult.NO;
584 }
585
586 if (!allowDecomposition
587 && (callSiteType == CallSiteType.DECOMPOSABLE_EXPRESSION
588 || callSiteType == CallSiteType.EXPRESSION)) {
589 return CanInlineResult.NO;
590 }
591
592 if (!callMeetsBlockInliningRequirements(
593 t, callNode, fnNode, namesToAlias)) {
594 return CanInlineResult.NO;
595 }
596
597 if (callSiteType == CallSiteType.DECOMPOSABLE_EXPRESSION
598 || callSiteType == CallSiteType.EXPRESSION) {
599 return CanInlineResult.AFTER_PREPARATION;
600 } else {
601 return CanInlineResult.YES;
602 }
603 }
604
605 /**
606 * Determines whether a function can be inlined at a particular call site.
607 * - Don't inline if the calling function contains an inner function and
608 * inlining would introduce new globals.
609 */
610 private boolean callMeetsBlockInliningRequirements(
611 NodeTraversal t, Node callNode, final Node fnNode,
612 Set<String> namesToAlias) {
613 final boolean assumeMinimumCapture = this.assumeMinimumCapture;
614
615 // Note: functions that contain function definitions are filtered out
616 // in isCandidateFunction.
617
618 // TODO(johnlenz): Determining if the called function contains VARs
619 // or if the caller contains inner functions accounts for 20% of the
620 // run-time cost of this pass.
621
622 // Don't inline functions with var declarations into a scope with inner
623 // functions as the new vars would leak into the inner function and
624 // cause memory leaks.
625 boolean fnContainsVars = NodeUtil.has(
626 NodeUtil.getFunctionBody(fnNode),
627 new NodeUtil.MatchDeclaration(),
628 new NodeUtil.MatchShallowStatement());
629 boolean forbidTemps = false;
630 if (!t.inGlobalScope()) {
631 Node fnCaller = t.getScopeRoot();
632 Node fnCallerBody = fnCaller.getLastChild();
633
634 // Don't allow any new vars into a scope that contains eval or one
635 // that contains functions (excluding the function being inlined).
636 Predicate<Node> match = new Predicate<Node>(){
637 @Override
638 public boolean apply(Node n) {
639 if (n.isName()) {
640 return n.getString().equals("eval");
641 }
642 if (!assumeMinimumCapture && n.isFunction()) {
643 return n != fnNode;
644 }
645 return false;
646 }
647 };
648 forbidTemps = NodeUtil.has(fnCallerBody,
649 match, NodeUtil.MATCH_NOT_FUNCTION);
650 }
651
652 if (fnContainsVars && forbidTemps) {
653 return false;
654 }
655
656 // If the caller contains functions or evals, verify we aren't adding any
657 // additional VAR declarations because aliasing is needed.
658 if (forbidTemps) {
659 Map<String, Node> args =
660 FunctionArgumentInjector.getFunctionCallParameterMap(
661 fnNode, callNode, this.safeNameIdSupplier);
662 boolean hasArgs = !args.isEmpty();
663 if (hasArgs) {
664 // Limit the inlining
665 Set<String> allNamesToAlias = Sets.newHashSet(namesToAlias);
666 FunctionArgumentInjector.maybeAddTempsForCallArguments(
667 fnNode, args, allNamesToAlias, compiler.getCodingConvention());
668 if (!allNamesToAlias.isEmpty()) {
669 return false;
670 }
671 }
672 }
673
674 return true;
675 }
676
677 /**
678 * Determines whether a function can be inlined at a particular call site.
679 * There are several criteria that the function and reference must hold in
680 * order for the functions to be inlined:
681 * 1) If a call's arguments have side effects,
682 * the corresponding argument in the function must only be referenced once.
683 * For instance, this will not be inlined:
684 * <pre>
685 * function foo(a) { return a + a }
686 * x = foo(i++);
687 * </pre>
688 */
689 private CanInlineResult canInlineReferenceDirectly(
690 Node callNode, Node fnNode) {
691 if (!isDirectCallNodeReplacementPossible(fnNode)) {
692 return CanInlineResult.NO;
693 }
694
695 Node block = fnNode.getLastChild();
696
697 // CALL NODE: [ NAME, ARG1, ARG2, ... ]
698 Node cArg = callNode.getFirstChild().getNext();
699
700 // Functions called via 'call' and 'apply' have a this-object as
701 // the first parameter, but this is not part of the called function's
702 // parameter list.
703 if (!callNode.getFirstChild().isName()) {
704 if (NodeUtil.isFunctionObjectCall(callNode)) {
705 // TODO(johnlenz): Support replace this with a value.
706 if (cArg == null || !cArg.isThis()) {
707 return CanInlineResult.NO;
708 }
709 cArg = cArg.getNext();
710 } else {
711 // ".apply" call should be filtered before this.
712 Preconditions.checkState(!NodeUtil.isFunctionObjectApply(callNode));
713 }
714 }
715
716 // FUNCTION NODE -> LP NODE: [ ARG1, ARG2, ... ]
717 Node fnParam = NodeUtil.getFunctionParameters(fnNode).getFirstChild();
718 while (cArg != null || fnParam != null) {
719 // For each named parameter check if a mutable argument use more than one.
720 if (fnParam != null) {
721 if (cArg != null) {
722 // Check for arguments that are evaluated more than once.
723 // Note: Unlike block inlining, there it is not possible that a
724 // parameter reference will be in a loop.
725 if (NodeUtil.mayEffectMutableState(cArg, compiler)
726 && NodeUtil.getNameReferenceCount(
727 block, fnParam.getString()) > 1) {
728 return CanInlineResult.NO;
729 }
730 }
731
732 // Move to the next name.
733 fnParam = fnParam.getNext();
734 }
735
736 // For every call argument check for side-effects, even if there
737 // isn't a named parameter to match.
738 if (cArg != null) {
739 if (NodeUtil.mayHaveSideEffects(cArg, compiler)) {
740 return CanInlineResult.NO;
741 }
742 cArg = cArg.getNext();
743 }
744 }
745
746 return CanInlineResult.YES;
747 }
748
749 /**
750 * Determine if inlining the function is likely to reduce the code size.
751 * @param namesToAlias
752 */
753 boolean inliningLowersCost(
754 JSModule fnModule, Node fnNode, Collection<? extends Reference> refs,
755 Set<String> namesToAlias, boolean isRemovable, boolean referencesThis) {
756 int referenceCount = refs.size();
757 if (referenceCount == 0) {
758 return true;
759 }
760
761 int referencesUsingBlockInlining = 0;
762
763 boolean checkModules = isRemovable && fnModule != null;
764 JSModuleGraph moduleGraph = compiler.getModuleGraph();
765
766 for (Reference ref : refs) {
767 if (ref.mode == InliningMode.BLOCK) {
768 referencesUsingBlockInlining++;
769 }
770
771 // Check if any of the references cross the module boundaries.
772 if (checkModules && ref.module != null) {
773 if (ref.module != fnModule &&
774 !moduleGraph.dependsOn(ref.module, fnModule)) {
775 // Calculate the cost as if the function were non-removable,
776 // if it still lowers the cost inline it.
777 isRemovable = false;
778 checkModules = false; // no need to check additional modules.
779 }
780 }
781 }
782
783 int referencesUsingDirectInlining = referenceCount -
784 referencesUsingBlockInlining;
785
786 // Don't bother calculating the cost of function for simple functions where
787 // possible.
788 // However, when inlining a complex function, even a single reference may be
789 // larger than the original function if there are many returns (resulting
790 // in additional assignments) or many parameters that need to be aliased
791 // so use the cost estimating.
792 if (referenceCount == 1 && isRemovable &&
793 referencesUsingDirectInlining == 1) {
794 return true;
795 }
796
797 int callCost = estimateCallCost(fnNode, referencesThis);
798 int overallCallCost = callCost * referenceCount;
799
800 int costDeltaDirect = inlineCostDelta(
801 fnNode, namesToAlias, InliningMode.DIRECT);
802 int costDeltaBlock = inlineCostDelta(
803 fnNode, namesToAlias, InliningMode.BLOCK);
804
805 return doesLowerCost(fnNode, overallCallCost,
806 referencesUsingDirectInlining, costDeltaDirect,
807 referencesUsingBlockInlining, costDeltaBlock,
808 isRemovable);
809 }
810
811 /**
812 * @return Whether inlining will lower cost.
813 */
814 private boolean doesLowerCost(
815 Node fnNode, int callCost,
816 int directInlines, int costDeltaDirect,
817 int blockInlines, int costDeltaBlock,
818 boolean removable) {
819
820 // Determine the threshold value for this inequality:
821 // inline_cost < call_cost
822 // But solve it for the function declaration size so the size of it
823 // is only calculated once and terminated early if possible.
824
825 int fnInstanceCount = directInlines + blockInlines - (removable ? 1 : 0);
826 // Prevent division by zero.
827 if (fnInstanceCount == 0) {
828 // Special case single reference function that are being block inlined:
829 // If the cost of the inline is greater than the function definition size,
830 // don't inline.
831 if (blockInlines > 0 && costDeltaBlock > 0) {
832 return false;
833 }
834 return true;
835 }
836
837 int costDelta = (directInlines * costDeltaDirect) +
838 (blockInlines * costDeltaBlock);
839 int threshold = (callCost - costDelta) / fnInstanceCount;
840
841 return InlineCostEstimator.getCost(fnNode, threshold + 1) <= threshold;
842 }
843
844 /**
845 * Gets an estimate of the cost in characters of making the function call:
846 * the sum of the identifiers and the separators.
847 * @param referencesThis
848 */
849 private static int estimateCallCost(Node fnNode, boolean referencesThis) {
850 Node argsNode = NodeUtil.getFunctionParameters(fnNode);
851 int numArgs = argsNode.getChildCount();
852
853 int callCost = NAME_COST_ESTIMATE + PAREN_COST;
854 if (numArgs > 0) {
855 callCost += (numArgs * NAME_COST_ESTIMATE) + ((numArgs - 1) * COMMA_COST);
856 }
857
858 if (referencesThis) {
859 // TODO(johnlenz): Update this if we start supporting inlining
860 // other functions that reference this.
861 // The only functions that reference this that are currently inlined
862 // are those that are called via ".call" with an explicit "this".
863 callCost += 5 + 5; // ".call" + "this,"
864 }
865
866 return callCost;
867 }
868
869 /**
870 * @return The difference between the function definition cost and
871 * inline cost.
872 */
873 private static int inlineCostDelta(
874 Node fnNode, Set<String> namesToAlias, InliningMode mode) {
875 // The part of the function that is never inlined:
876 // "function xx(xx,xx){}" (15 + (param count * 3) -1;
877 int paramCount = NodeUtil.getFunctionParameters(fnNode).getChildCount();
878 int commaCount = (paramCount > 1) ? paramCount - 1 : 0;
879 int costDeltaFunctionOverhead = 15 + commaCount +
880 (paramCount * InlineCostEstimator.ESTIMATED_IDENTIFIER_COST);
881
882 Node block = fnNode.getLastChild();
883 if (!block.hasChildren()) {
884 // Assume the inline cost is zero for empty functions.
885 return -costDeltaFunctionOverhead;
886 }
887
888 if (mode == InliningMode.DIRECT) {
889 // The part of the function that is inlined using direct inlining:
890 // "return " (7)
891 return -(costDeltaFunctionOverhead + 7);
892 } else {
893 int aliasCount = namesToAlias.size();
894
895 // Originally, we estimated purely base on the function code size, relying
896 // on later optimizations. But that did not produce good results, so here
897 // we try to estimate the something closer to the actual inlined coded.
898
899 // NOTE 1: Result overhead is only if there is an assignment, but
900 // getting that information would require some refactoring.
901 // NOTE 2: The aliasing overhead is currently an under-estimate,
902 // as some parameters are aliased because of the parameters used.
903 // Perhaps we should just assume all parameters will be aliased?
904 final int INLINE_BLOCK_OVERHEAD = 4; // "X:{}"
905 final int PER_RETURN_OVERHEAD = 2; // "return" --> "break X"
906 final int PER_RETURN_RESULT_OVERHEAD = 3; // "XX="
907 final int PER_ALIAS_OVERHEAD = 3; // "XX="
908
909 // TODO(johnlenz): Counting the number of returns is relatively expensive
910 // this information should be determined during the traversal and
911 // cached.
912 int returnCount = NodeUtil.getNodeTypeReferenceCount(
913 block, Token.RETURN, new NodeUtil.MatchShallowStatement());
914 int resultCount = (returnCount > 0) ? returnCount - 1 : 0;
915 int baseOverhead = (returnCount > 0) ? INLINE_BLOCK_OVERHEAD : 0;
916
917 int overhead = baseOverhead
918 + returnCount * PER_RETURN_OVERHEAD
919 + resultCount * PER_RETURN_RESULT_OVERHEAD
920 + aliasCount * PER_ALIAS_OVERHEAD;
921
922 return (overhead - costDeltaFunctionOverhead);
923 }
924 }
925
926 /**
927 * Store the names of known constants to be used when classifying call-sites
928 * in expressions.
929 */
930 public void setKnownConstants(Set<String> knownConstants) {
931 // This is only expected to be set once. The same set should be used
932 // when evaluating call-sites and inlining calls.
933 Preconditions.checkState(this.knownConstants.isEmpty());
934 this.knownConstants = knownConstants;
935 }
936 }