Debian Codegraph @

src/com/google/javascript/jscomp/ExpressionDecomposer.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 package com.google.javascript.jscomp;
17
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.base.Preconditions;
20 import com.google.common.base.Supplier;
21 import com.google.javascript.jscomp.MakeDeclaredNamesUnique.ContextualRenamer;
22 import com.google.javascript.rhino.IR;
23 import com.google.javascript.rhino.Node;
24 import com.google.javascript.rhino.Token;
25
26 import java.util.Set;
27
28 /**
29 * Methods necessary for partially or full decomposing an expression. Initially
30 * this is intended to expanded the locations were inlining can occur, but has
31 * other uses as well.
32 *
33 * For example:
34 * var x = y() + z();
35 *
36 * Becomes:
37 * var a = y();
38 * var b = z();
39 * x = a + b;
40 *
41 * @author [email protected] (John Lenz)
42 */
43 class ExpressionDecomposer {
44
45 /**
46 * @see #canExposeExpression
47 */
48 enum DecompositionType {
49 UNDECOMPOSABLE,
50 MOVABLE,
51 DECOMPOSABLE
52 }
53
54 private final AbstractCompiler compiler;
55 private final Supplier<String> safeNameIdSupplier;
56 private final Set<String> knownConstants;
57
58 public ExpressionDecomposer(
59 AbstractCompiler compiler,
60 Supplier<String> safeNameIdSupplier,
61 Set<String> constNames) {
62 Preconditions.checkNotNull(compiler);
63 Preconditions.checkNotNull(safeNameIdSupplier);
64 Preconditions.checkNotNull(constNames);
65 this.compiler = compiler;
66 this.safeNameIdSupplier = safeNameIdSupplier;
67 this.knownConstants = constNames;
68 }
69
70 // An arbitrary limit to prevent catch infinite recursion.
71 private static final int MAX_INTERATIONS = 100;
72
73 /**
74 * If required, rewrite the statement containing the expression.
75 * @param expression The expression to be exposed.
76 * @see #canExposeExpression
77 */
78 void maybeExposeExpression(Node expression) {
79 // If the expression needs to exposed.
80 int i = 0;
81 while (DecompositionType.DECOMPOSABLE == canExposeExpression(expression)) {
82 exposeExpression(expression);
83 i++;
84 if (i > MAX_INTERATIONS) {
85 throw new IllegalStateException(
86 "DecomposeExpression depth exceeded on :\n" +
87 expression.toStringTree());
88 }
89 }
90 }
91
92 /**
93 * Perform any rewriting necessary so that the specified expression
94 * is movable. This is a partial expression decomposition.
95 * @see #canExposeExpression
96 */
97 void exposeExpression(Node expression) {
98 Node expressionRoot = findExpressionRoot(expression);
99 Preconditions.checkState(expressionRoot != null);
100 exposeExpression(expressionRoot, expression);
101 compiler.reportCodeChange();
102 }
103
104 // TODO(johnlenz): This is not currently used by the function inliner,
105 // as moving the call out of the expression before the actual function
106 // results in additional variables being introduced. As the variable
107 // inliner is improved, this might be a viable option.
108 /**
109 * Extract the specified expression from its parent expression.
110 * @see #canExposeExpression
111 */
112 void moveExpression(Node expression) {
113 String resultName = getResultValueName();
114 Node injectionPoint = findInjectionPoint(expression);
115 Preconditions.checkNotNull(injectionPoint);
116 Node injectionPointParent = injectionPoint.getParent();
117 Preconditions.checkNotNull(injectionPointParent);
118 Preconditions.checkState(NodeUtil.isStatementBlock(injectionPointParent));
119
120 // Replace the expression with a reference to the new name.
121 Node expressionParent = expression.getParent();
122 expressionParent.replaceChild(
123 expression, IR.name(resultName));
124
125 // Re-add the expression at the appropriate place.
126 Node newExpressionRoot = NodeUtil.newVarNode(resultName, expression);
127 injectionPointParent.addChildBefore(newExpressionRoot, injectionPoint);
128 compiler.reportCodeChange();
129 }
130
131 /**
132 * Rewrite the expression such that the sub-expression is in a movable
133 * expression statement while maintaining evaluation order.
134 *
135 * Two types of subexpressions are extracted from the source expression:
136 * 1) subexpressions with side-effects.
137 * 2) conditional expressions, that contain the call, which are transformed
138 * into IF statements.
139 *
140 * The following terms are used:
141 * expressionRoot: The top-level node before which the any extracted
142 * expressions should be placed before.
143 * nonconditionalExpr: The node that will be extracted either expres.
144 *
145 */
146 private void exposeExpression(Node expressionRoot, Node subExpression) {
147 Node nonconditionalExpr = findNonconditionalParent(
148 subExpression, expressionRoot);
149 // Before extraction, record whether there are side-effect
150 boolean hasFollowingSideEffects = NodeUtil.mayHaveSideEffects(
151 nonconditionalExpr, compiler);
152
153 Node exprInjectionPoint = findInjectionPoint(nonconditionalExpr);
154 DecompositionState state = new DecompositionState();
155 state.sideEffects = hasFollowingSideEffects;
156 state.extractBeforeStatement = exprInjectionPoint;
157
158 // Extract expressions in the reverse order of their evaluation.
159 for (Node grandchild = null,
160 child = nonconditionalExpr,
161 parent = child.getParent();
162 parent != expressionRoot;
163 grandchild = child,
164 child = parent,
165 parent = child.getParent()) {
166 int parentType = parent.getType();
167 Preconditions.checkState(
168 !isConditionalOp(parent) || child == parent.getFirstChild());
169 if (parentType == Token.ASSIGN) {
170 if (isSafeAssign(parent, state.sideEffects)) {
171 // It is always safe to inline "foo()" for expressions such as
172 // "a = b = c = foo();"
173 // As the assignment is unaffected by side effect of "foo()"
174 // and the names assigned-to can not influence the state before
175 // the call to foo.
176 //
177 // This is not true of more complex LHS values, such as
178 // a.x = foo();
179 // next().x = foo();
180 // in these cases the checks below are necessary.
181 } else {
182 // Alias "next()" in "next().foo"
183 Node left = parent.getFirstChild();
184 int type = left.getType();
185 if (left != child) {
186 Preconditions.checkState(NodeUtil.isGet(left));
187 if (type == Token.GETELEM) {
188 decomposeSubExpressions(left.getLastChild(), null, state);
189 }
190 decomposeSubExpressions(left.getFirstChild(), null, state);
191 }
192 }
193 } else if (parentType == Token.CALL
194 && NodeUtil.isGet(parent.getFirstChild())) {
195 Node functionExpression = parent.getFirstChild();
196 decomposeSubExpressions(functionExpression.getNext(), child, state);
197 // Now handle the call expression
198 if (isExpressionTreeUnsafe(functionExpression, state.sideEffects)
199 && functionExpression.getFirstChild() != grandchild) {
200 // TODO(johnlenz): In Internet Explorer, non-JavaScript objects such
201 // as DOM objects can not be decomposed.
202 Preconditions.checkState(allowObjectCallDecomposing(),
203 "Object method calls can not be decomposed.");
204 // Either there were preexisting side-effects, or this node has
205 // side-effects.
206 state.sideEffects = true;
207
208 // Rewrite the call so "this" is preserved.
209 Node replacement = rewriteCallExpression(parent, state);
210 // Continue from here.
211 parent = replacement;
212 }
213 } else if (parentType == Token.OBJECTLIT) {
214 decomposeObjectLiteralKeys(parent.getFirstChild(), child, state);
215 } else {
216 decomposeSubExpressions(parent.getFirstChild(), child, state);
217 }
218 }
219
220 // Now extract the expression that the decomposition is being performed to
221 // to allow to be moved. All expressions that need to be evaluated before
222 // this have been extracted, so add the expression statement after the
223 // other extracted expressions and the original statement (or replace
224 // the original statement.
225 if (nonconditionalExpr == subExpression) {
226 // Don't extract the call, as that introduces an extra constant VAR
227 // that will simply need to be inlined back. It will be handled as
228 // an EXPRESSION call site type.
229 // Node extractedCall = extractExpression(decomposition, expressionRoot);
230 } else {
231 Node parent = nonconditionalExpr.getParent();
232 boolean needResult = !parent.isExprResult();
233 extractConditional(nonconditionalExpr, exprInjectionPoint, needResult);
234 }
235 }
236
237 private static boolean allowObjectCallDecomposing() {
238 return false;
239 }
240
241 /**
242 * @return Whether the node may represent an external method.
243 */
244 private boolean maybeExternMethod(Node node) {
245 // TODO(johnlenz): Provide some mechanism for determining this.
246 return true;
247 }
248
249 /**
250 * @return "expression" or the node closest to "expression", that does not
251 * have a conditional ancestor.
252 */
253 private static Node findNonconditionalParent(
254 Node subExpression, Node expressionRoot) {
255 Node result = subExpression;
256
257 for (Node child = subExpression, parent = child.getParent();
258 parent != expressionRoot;
259 child = parent, parent = child.getParent()) {
260 if (isConditionalOp(parent)) {
261 // Only the first child is always executed, if the function may never
262 // be called, don't inline it.
263 if (child != parent.getFirstChild()) {
264 result = parent;
265 }
266 }
267 }
268
269 return result;
270 }
271
272 /**
273 * A simple class to track two things:
274 * - whether side effects have been seen.
275 * - the last statement inserted
276 */
277 private static class DecompositionState {
278 boolean sideEffects;
279 Node extractBeforeStatement;
280 }
281
282 /**
283 * Decompose an object literal.
284 * @param key The object literal key.
285 * @param stopNode A node after which to stop iterating.
286 */
287 private void decomposeObjectLiteralKeys(
288 Node key, Node stopNode, DecompositionState state) {
289 if (key == null || key == stopNode) {
290 return;
291 }
292 decomposeObjectLiteralKeys(key.getNext(), stopNode, state);
293 decomposeSubExpressions(key.getFirstChild(), stopNode, state);
294 }
295
296 /**
297 * @param n The node with which to start iterating.
298 * @param stopNode A node after which to stop iterating.
299 */
300 private void decomposeSubExpressions(
301 Node n, Node stopNode, DecompositionState state) {
302 if (n == null || n == stopNode) {
303 return;
304 }
305
306 // Never try to decompose an object literal key.
307 Preconditions.checkState(!NodeUtil.isObjectLitKey(n));
308
309 // Decompose the children in reverse evaluation order. This simplifies
310 // determining if the any of the children following have side-effects.
311 // If they do we need to be more aggressive about removing values
312 // from the expression.
313 decomposeSubExpressions(
314 n.getNext(), stopNode, state);
315
316 // Now this node.
317 // TODO(johnlenz): Move "safety" code to a shared class.
318 if (isExpressionTreeUnsafe(n, state.sideEffects)) {
319 // Either there were preexisting side-effects, or this node has
320 // side-effects.
321 state.sideEffects = true;
322 state.extractBeforeStatement = extractExpression(
323 n, state.extractBeforeStatement);
324 }
325 }
326
327 /**
328 *
329 * @param expr The conditional expression to extract.
330 * @param injectionPoint The before which extracted expression, would be
331 * injected.
332 * @param needResult Whether the result of the expression is required.
333 * @return The node that contains the logic of the expression after
334 * extraction.
335 */
336 private Node extractConditional(
337 Node expr, Node injectionPoint, boolean needResult) {
338 Node parent = expr.getParent();
339 String tempName = getTempValueName();
340
341 // Break down the conditional.
342 Node first = expr.getFirstChild();
343 Node second = first.getNext();
344 Node last = expr.getLastChild();
345
346 // Isolate the children nodes.
347 expr.detachChildren();
348
349 // Transform the conditional to an IF statement.
350 Node cond = null;
351 Node trueExpr = IR.block().srcref(expr);
352 Node falseExpr = IR.block().srcref(expr);
353 switch (expr.getType()) {
354 case Token.HOOK:
355 // a = x?y:z --> if (x) {a=y} else {a=z}
356 cond = first;
357 trueExpr.addChildToFront(NodeUtil.newExpr(
358 buildResultExpression(second, needResult, tempName)));
359 falseExpr.addChildToFront(NodeUtil.newExpr(
360 buildResultExpression(last, needResult, tempName)));
361 break;
362 case Token.AND:
363 // a = x&&y --> if (a=x) {a=y} else {}
364 cond = buildResultExpression(first, needResult, tempName);
365 trueExpr.addChildToFront(NodeUtil.newExpr(
366 buildResultExpression(last, needResult, tempName)));
367 break;
368 case Token.OR:
369 // a = x||y --> if (a=x) {} else {a=y}
370 cond = buildResultExpression(first, needResult, tempName);
371 falseExpr.addChildToFront(NodeUtil.newExpr(
372 buildResultExpression(last, needResult, tempName)));
373 break;
374 default:
375 // With a valid tree we should never get here.
376 throw new IllegalStateException("Unexpected.");
377 }
378
379 Node ifNode;
380 if (falseExpr.hasChildren()) {
381 ifNode = IR.ifNode(cond, trueExpr, falseExpr);
382 } else {
383 ifNode = IR.ifNode(cond, trueExpr);
384 }
385 ifNode.copyInformationFrom(expr);
386
387 if (needResult) {
388 Node tempVarNode = NodeUtil.newVarNode(tempName, null)
389 .copyInformationFromForTree(expr);
390 Node injectionPointParent = injectionPoint.getParent();
391 injectionPointParent.addChildBefore(tempVarNode, injectionPoint);
392 injectionPointParent.addChildAfter(ifNode, tempVarNode);
393
394 // Replace the expression with the temporary name.
395 Node replacementValueNode = IR.name(tempName);
396 parent.replaceChild(expr, replacementValueNode);
397 } else {
398 // Only conditionals that are the direct child of an expression statement
399 // don't need results, for those simply replace the expression statement.
400 Preconditions.checkArgument(parent.isExprResult());
401 Node gramps = parent.getParent();
402 gramps.replaceChild(parent, ifNode);
403 }
404
405 return ifNode;
406 }
407
408 /**
409 * Create an expression tree for an expression.
410 * If the result of the expression is needed, then:
411 * ASSIGN
412 * tempName
413 * expr
414 * otherwise, simply:
415 * expr
416 */
417 private static Node buildResultExpression(
418 Node expr, boolean needResult, String tempName) {
419 if (needResult) {
420 return IR.assign(
421 IR.name(tempName),
422 expr).srcrefTree(expr);
423 } else {
424 return expr;
425 }
426 }
427
428 private boolean isConstantName(Node n, Set<String> knownConstants) {
429 // Non-constant names values may have been changed.
430 return n.isName() && (NodeUtil.isConstantName(n)
431 || knownConstants.contains(n.getString()));
432 }
433
434 /**
435 * @param expr The expression to extract.
436 * @param injectionPoint The node before which to added the extracted
437 * expression.
438 * @return The extract statement node.
439 */
440 private Node extractExpression(Node expr, Node injectionPoint) {
441 Node parent = expr.getParent();
442
443 boolean isLhsOfAssignOp = NodeUtil.isAssignmentOp(parent)
444 && !parent.isAssign()
445 && parent.getFirstChild() == expr;
446
447 Node firstExtractedNode = null;
448
449 // Expressions on the LHS of an assignment-op must have any possible
450 // side-effects extracted as the value must be duplicated:
451 // next().foo += 2;
452 // becomes:
453 // var t1 = next();
454 // t1.foo = t1.foo + 2;
455 if (isLhsOfAssignOp && NodeUtil.isGet(expr)) {
456 for (Node n : expr.children()) {
457 if (!n.isString() && !isConstantName(n, knownConstants)) {
458 Node extractedNode = extractExpression(n, injectionPoint);
459 if (firstExtractedNode == null) {
460 firstExtractedNode = extractedNode;
461 }
462 }
463 }
464 }
465
466 // The temp is known to be constant.
467 String tempName = getTempConstantValueName();
468 Node replacementValueNode = IR.name(tempName).srcref(expr);
469
470 Node tempNameValue;
471
472 // If it is ASSIGN_XXX, keep the assignment in place and extract the
473 // original value of the LHS operand.
474 if (isLhsOfAssignOp) {
475 Preconditions.checkState(expr.isName() || NodeUtil.isGet(expr));
476 // Transform "x += 2" into "x = temp + 2"
477 Node opNode = new Node(NodeUtil.getOpFromAssignmentOp(parent))
478 .copyInformationFrom(parent);
479
480 Node rightOperand = parent.getLastChild();
481
482 parent.setType(Token.ASSIGN);
483 parent.replaceChild(rightOperand, opNode);
484 opNode.addChildToFront(replacementValueNode);
485 opNode.addChildToBack(rightOperand);
486
487 // The original expression is still being used, so make a clone.
488 tempNameValue = expr.cloneTree();
489 } else {
490 // Replace the expression with the temporary name.
491 parent.replaceChild(expr, replacementValueNode);
492
493 // Keep the original node so that CALL expressions can still be found
494 // and inlined properly.
495 tempNameValue = expr;
496 }
497
498 // Re-add the expression in the declaration of the temporary name.
499 Node tempVarNode = NodeUtil.newVarNode(tempName, tempNameValue);
500
501 Node injectionPointParent = injectionPoint.getParent();
502 injectionPointParent.addChildBefore(tempVarNode, injectionPoint);
503
504 if (firstExtractedNode == null) {
505 firstExtractedNode = tempVarNode;
506 }
507 return firstExtractedNode;
508 }
509
510 /**
511 * Rewrite the call so "this" is preserved.
512 * a.b(c);
513 * becomes:
514 * var temp1 = a;
515 * var temp0 = temp1.b;
516 * temp0.call(temp1,c);
517 *
518 * @return The replacement node.
519 */
520 private Node rewriteCallExpression(Node call, DecompositionState state) {
521 Preconditions.checkArgument(call.isCall());
522 Node first = call.getFirstChild();
523 Preconditions.checkArgument(NodeUtil.isGet(first));
524
525 // Extracts the expression representing the function to call. For example:
526 // "a['b'].c" from "a['b'].c()"
527 Node getVarNode = extractExpression(
528 first, state.extractBeforeStatement);
529 state.extractBeforeStatement = getVarNode;
530
531 // Extracts the object reference to be used as "this". For example:
532 // "a['b']" from "a['b'].c"
533 Node getExprNode = getVarNode.getFirstChild().getFirstChild();
534 Preconditions.checkArgument(NodeUtil.isGet(getExprNode));
535 Node thisVarNode = extractExpression(
536 getExprNode.getFirstChild(), state.extractBeforeStatement);
537 state.extractBeforeStatement = thisVarNode;
538
539 // Rewrite the CALL expression.
540 Node thisNameNode = thisVarNode.getFirstChild();
541 Node functionNameNode = getVarNode.getFirstChild();
542
543 // CALL
544 // GETPROP
545 // functionName
546 // "call"
547 // thisName
548 // original-parameter1
549 // original-parameter2
550 // ...
551 Node newCall = IR.call(
552 IR.getprop(
553 functionNameNode.cloneNode(),
554 IR.string("call")),
555 thisNameNode.cloneNode()).srcref(call);
556
557 // Throw away the call name
558 call.removeFirstChild();
559 if (call.hasChildren()) {
560 // Add the call parameters to the new call.
561 newCall.addChildrenToBack(call.removeChildren());
562 }
563
564 // Replace the call.
565 Node callParent = call.getParent();
566 callParent.replaceChild(call, newCall);
567
568 return newCall;
569 }
570
571 private String tempNamePrefix = "JSCompiler_temp";
572 private String resultNamePrefix = "JSCompiler_inline_result";
573
574 /**
575 * Allow the temp name to be overridden to make tests more readable.
576 */
577 @VisibleForTesting
578 public void setTempNamePrefix(String prefix) {
579 this.tempNamePrefix = prefix;
580 }
581
582 /**
583 * Create a unique temp name.
584 */
585 private String getTempValueName(){
586 return tempNamePrefix + ContextualRenamer.UNIQUE_ID_SEPARATOR
587 + safeNameIdSupplier.get();
588 }
589
590 /**
591 * Allow the temp name to be overridden to make tests more readable.
592 */
593 @VisibleForTesting
594 public void setResultNamePrefix(String prefix) {
595 this.resultNamePrefix = prefix;
596 }
597
598 /**
599 * Create a unique name for call results.
600 */
601 private String getResultValueName() {
602 return resultNamePrefix
603 + ContextualRenamer.UNIQUE_ID_SEPARATOR + safeNameIdSupplier.get();
604 }
605
606 /**
607 * Create a constant unique temp name.
608 */
609 private String getTempConstantValueName(){
610 String name = tempNamePrefix + "_const"
611 + ContextualRenamer.UNIQUE_ID_SEPARATOR
612 + safeNameIdSupplier.get();
613 this.knownConstants.add(name);
614 return name;
615 }
616
617 /**
618 * @return For the subExpression, find the nearest statement Node before which
619 * it can be inlined. Null if no such location can be found.
620 */
621 static Node findInjectionPoint(Node subExpression) {
622 Node expressionRoot = findExpressionRoot(subExpression);
623 Preconditions.checkNotNull(expressionRoot);
624
625 Node injectionPoint = expressionRoot;
626
627 Node parent = injectionPoint.getParent();
628 while (parent.isLabel()) {
629 injectionPoint = parent;
630 parent = injectionPoint.getParent();
631 }
632
633 Preconditions.checkState(
634 NodeUtil.isStatementBlock(injectionPoint.getParent()));
635 return injectionPoint;
636 }
637
638 /**
639 * @return Whether the node is a conditional op.
640 */
641 private static boolean isConditionalOp(Node n) {
642 switch(n.getType()) {
643 case Token.HOOK:
644 case Token.AND:
645 case Token.OR:
646 return true;
647 default:
648 return false;
649 }
650 }
651
652 /**
653 * @return The statement containing the expression. null if subExpression
654 * is not contain by in by a Node where inlining is known to be possible.
655 * For example, a WHILE node condition expression.
656 */
657 static Node findExpressionRoot(Node subExpression) {
658 Node child = subExpression;
659 for (Node parent : child.getAncestors()) {
660 int parentType = parent.getType();
661 switch (parentType) {
662 // Supported expression roots:
663 // SWITCH and IF can have multiple children, but the CASE, DEFAULT,
664 // or BLOCK will be encountered first for any of the children other
665 // than the condition.
666 case Token.EXPR_RESULT:
667 case Token.IF:
668 case Token.SWITCH:
669 case Token.RETURN:
670 case Token.VAR:
671 Preconditions.checkState(child == parent.getFirstChild());
672 return parent;
673 // Any of these indicate an unsupported expression:
674 case Token.SCRIPT:
675 case Token.BLOCK:
676 case Token.LABEL:
677 case Token.CASE:
678 case Token.DEFAULT_CASE:
679 return null;
680 }
681 child = parent;
682 }
683
684 throw new IllegalStateException("Unexpected AST structure.");
685 }
686
687 /**
688 * Determine whether a expression is movable, or can be be made movable be
689 * decomposing the containing expression.
690 *
691 * An subExpression is MOVABLE if it can be replaced with a temporary holding
692 * its results and moved to immediately before the root of the expression.
693 * There are three conditions that must be met for this to occur:
694 * 1) There must be a location to inject a statement for the expression. For
695 * example, this condition can not be met if the expression is a loop
696 * condition or CASE condition.
697 * 2) If the expression can be affect by side-effects, there can not be a
698 * side-effect between original location and the expression root.
699 * 3) If the expression has side-effects, there can not be any other
700 * expression that can be effected between the original location and the
701 * expression root.
702 *
703 * An expression is DECOMPOSABLE if it can be rewritten so that an
704 * subExpression is MOVABLE.
705 *
706 * An expression is decomposed by moving any other sub-expressions that
707 * preventing an subExpression from being MOVABLE.
708 *
709 * @return Whether This is a call that can be moved to an new point in the
710 * AST to allow it to be inlined.
711 */
712 DecompositionType canExposeExpression(Node subExpression) {
713 Node expressionRoot = findExpressionRoot(subExpression);
714 if (expressionRoot != null) {
715 return isSubexpressionMovable(expressionRoot, subExpression);
716 }
717 return DecompositionType.UNDECOMPOSABLE;
718 }
719
720 /**
721 * Walk the AST from the call site to the expression root and verify that
722 * the portions of the expression that are evaluated before the call are:
723 * 1) Unaffected by the the side-effects, if any, of the call.
724 * 2) That there are no side-effects, that may influence the call.
725 *
726 * For example, if x has side-effects:
727 * a = 1 + x();
728 * the call to x can be moved because "a" final value of a can not be
729 * influenced by x(), but in:
730 * a = b + x();
731 * the call to x can not be moved because the value of b may be modified
732 * by the call to x.
733 *
734 * If x is without side-effects in:
735 * a = b + x();
736 * the call to x can be moved, but in:
737 * a = (b.foo = c) + x();
738 * the call to x can not be moved because the value of b.foo may be referenced
739 * by x(). Note: this is true even if b is a local variable; the object that
740 * b refers to may have a global alias.
741 *
742 * @return UNDECOMPOSABLE if the expression can not be moved, DECOMPOSABLE if
743 * decomposition is required before the expression can be moved, otherwise
744 * MOVABLE.
745 */
746 private DecompositionType isSubexpressionMovable(
747 Node expressionRoot, Node subExpression) {
748 boolean requiresDecomposition = false;
749 boolean seenSideEffects = NodeUtil.mayHaveSideEffects(
750 subExpression, compiler);
751
752 Node child = subExpression;
753 for (Node parent : child.getAncestors()) {
754 if (parent == expressionRoot) {
755 // Done. The walk back to the root of the expression is complete, and
756 // nothing was encountered that blocks the call from being moved.
757 return requiresDecomposition
758 ? DecompositionType.DECOMPOSABLE
759 : DecompositionType.MOVABLE;
760 }
761
762 if (isConditionalOp(parent)) {
763 // Only the first child is always executed, otherwise it must be
764 // decomposed.
765 if (child != parent.getFirstChild()) {
766 requiresDecomposition = true;
767 }
768 } else {
769 // Only inline the call if none of the preceding siblings in the
770 // expression have side-effects, and are unaffected by the side-effects,
771 // if any, of the call in question.
772 // NOTE: This depends on the siblings being in the same order as they
773 // are evaluated.
774
775 // SPECIAL CASE: Assignment to a simple name
776 if (isSafeAssign(parent, seenSideEffects)) {
777 // It is always safe to inline "foo()" for expressions such as
778 // "a = b = c = foo();"
779 // As the assignment is unaffected by side effect of "foo()"
780 // and the names assigned-to can not influence the state before
781 // the call to foo.
782 //
783 // This is not true of more complex LHS values, such as
784 // a.x = foo();
785 // next().x = foo();
786 // in these cases the checks below are necessary.
787 } else {
788 // Everything else.
789 for (Node n : parent.children()) {
790 if (n == child) {
791 // None of the preceding siblings have side-effects.
792 // This is OK.
793 break;
794 }
795
796 if (isExpressionTreeUnsafe(
797 n, seenSideEffects)) {
798 seenSideEffects = true;
799 requiresDecomposition = true;
800 }
801 }
802
803 // In Internet Explorer, DOM objects and other external objects
804 // methods can not be called indirectly, as is required when the
805 // object or its property can be side-effected. For example,
806 // when exposing expression f() (with side-effects) in: x.m(f())
807 // either the value of x or its property m might have changed, so
808 // both the 'this' value ('x') and the function to be called ('x.m')
809 // need to be preserved. Like so:
810 // var t1 = x, t2 = x.m, t3 = f();
811 // t2.call(t1, t3);
812 // As IE doesn't support the call to these non-JavaScript objects
813 // methods in this way. We can't do this.
814 // We don't currently distinguish between these types of objects
815 // in the extern definitions and if we did we would need accurate
816 // type information.
817 //
818 Node first = parent.getFirstChild();
819 if (requiresDecomposition
820 && parent.isCall()
821 && NodeUtil.isGet(first)) {
822 if (maybeExternMethod(first)) {
823 return DecompositionType.UNDECOMPOSABLE;
824 } else {
825 return DecompositionType.DECOMPOSABLE;
826 }
827 }
828 }
829 }
830 // Continue looking up the expression tree.
831 child = parent;
832 }
833
834 // With a valid tree we should never get here.
835 throw new IllegalStateException("Unexpected.");
836 }
837
838 /**
839 * It is always safe to inline "foo()" for expressions such as
840 * "a = b = c = foo();"
841 * As the assignment is unaffected by side effect of "foo()"
842 * and the names assigned-to can not influence the state before
843 * the call to foo.
844 *
845 * It is also safe in cases like where the object is constant:
846 * CONST_NAME.a = foo()
847 * CONST_NAME[CONST_VALUE] = foo();
848 *
849 * This is not true of more complex LHS values, such as
850 * a.x = foo();
851 * next().x = foo();
852 * in these cases the checks below are necessary.
853 *
854 * @param seenSideEffects If true, check to see if node-tree maybe affected by
855 * side-effects, otherwise if the tree has side-effects. @see
856 * isExpressionTreeUnsafe
857 * @return Whether the assignment is safe from side-effects.
858 */
859 private boolean isSafeAssign(Node n, boolean seenSideEffects) {
860 if (n.isAssign()) {
861 Node lhs = n.getFirstChild();
862 switch (lhs.getType()) {
863 case Token.NAME:
864 return true;
865 case Token.GETPROP:
866 return !isExpressionTreeUnsafe(lhs.getFirstChild(), seenSideEffects);
867 case Token.GETELEM:
868 return !isExpressionTreeUnsafe(lhs.getFirstChild(), seenSideEffects)
869 && !isExpressionTreeUnsafe(lhs.getLastChild(), seenSideEffects);
870 }
871 }
872 return false;
873 }
874
875 /**
876 * @return Whether anything in the expression tree prevents a call from
877 * being moved.
878 */
879 private boolean isExpressionTreeUnsafe(
880 Node n, boolean followingSideEffectsExist) {
881 if (followingSideEffectsExist) {
882 // If the call to be inlined has side-effects, check to see if this
883 // expression tree can be affected by any side-effects.
884
885 // This is a superset of "NodeUtil.mayHaveSideEffects".
886 return NodeUtil.canBeSideEffected(n, this.knownConstants);
887 } else {
888 // The function called doesn't have side-effects but check to see if there
889 // are side-effects that that may affect it.
890 return NodeUtil.mayHaveSideEffects(n, compiler);
891 }
892 }
893 }