Debian Codegraph @

net/sf/saxon/expr/parser/LoopLifter.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.expr.parser;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.*;
12 import net.sf.saxon.expr.instruct.ConditionalInstruction;
13 import net.sf.saxon.lib.Feature;
14 import net.sf.saxon.lib.Logger;
15 import net.sf.saxon.lib.NamespaceConstant;
16 import net.sf.saxon.om.StructuredQName;
17 import net.sf.saxon.trans.XPathException;
18 import net.sf.saxon.type.UType;
19 import net.sf.saxon.value.Cardinality;
20 import net.sf.saxon.value.SequenceType;
21
22 import java.util.IdentityHashMap;
23 import java.util.Map;
24
25 /**
26 * Class to handle loop-lifting optimization, that is, extraction of subexpressions appearing within
27 * a loop when there is no dependency on the controlling variable of the loop. This handles both
28 * focus-dependent loops (such as xsl:for-each) and variable-dependent loops (such as XPath for-expressions),
29 * and also takes into account specialist loops such as xsl:for-each-group, xsl:merge, and xsl:analyze-string.
30 *
31 * The class is instantiated to perform optimization of a component such as a function or template, and
32 * it contains temporary instance-level data pertaining to that function or template.
33 */
34
35 public class LoopLifter {
36
37 /**
38 * Apply loop-lifting to an expression (typically the body of a template or function)
39 * @param exp the expression to which loop lifting is applied
40 * @return the optimized expression
41 */
42
43 public static Expression process(Expression exp, ExpressionVisitor visitor, ContextItemStaticInfo contextInfo)
44 throws XPathException {
45 //exp.verifyParentPointers();
46 if (exp instanceof Literal || exp instanceof VariableReference) {
47 return exp;
48 } else {
49 LoopLifter lifter = new LoopLifter(exp, visitor.getConfiguration(), visitor.isOptimizeForStreaming());
50 RetainedStaticContext rsc = exp.getRetainedStaticContext();
51 lifter.gatherInfo(exp);
52 lifter.loopLift(exp);
53 lifter.root.setRetainedStaticContext(rsc);
54 lifter.root.setParentExpression(null);
55 if (lifter.changed) {
56 ExpressionTool.resetPropertiesWithinSubtree(lifter.root);
57 Expression e2 = lifter.root.optimize(visitor, contextInfo);
58 e2.setParentExpression(null);
59 return e2;
60 } else {
61 return lifter.root;
62 }
63 }
64 }
65
66 private Expression root;
67 private Configuration config;
68 private int sequence = 0;
69 private boolean changed = false;
70 private boolean tracing = false;
71 private boolean streaming = false;
72
73 private static class ExpInfo {
74 Expression expression;
75 int loopLevel;
76 boolean multiThreaded;
77 Map<Expression, Boolean> dependees = new IdentityHashMap<>();
78
79 }
80
81 private Map<Expression, ExpInfo> expInfoMap = new IdentityHashMap<>();
82
83 public LoopLifter(Expression root, Configuration config, boolean streaming) {
84 this.root = root;
85 this.config = config;
86 this.tracing = config.getBooleanProperty(Feature.TRACE_OPTIMIZER_DECISIONS);
87 this.streaming = streaming;
88 }
89
90 public Expression getRoot() {
91 return root;
92 }
93
94 /**
95 * Gather information about an expression. The information (in the form of an ExpInfo object)
96 * is added to the expInfoMap, which is indexed by expression.
97 * @param exp the expression for which information is required
98 */
99
100 public void gatherInfo(Expression exp) {
101 gatherInfo(exp, 0, 0, false);
102 }
103
104 private void gatherInfo(Expression exp, int level, int loopLevel, boolean multiThreaded) {
105 ExpInfo info = new ExpInfo();
106 info.expression = exp;
107 info.loopLevel = loopLevel;
108 info.multiThreaded = multiThreaded;
109 expInfoMap.put(exp, info);
110 Expression scope = exp.getScopingExpression();
111 if (scope != null) {
112 markDependencies(exp, scope);
113 }
114 boolean threaded = multiThreaded || exp.isMultiThreaded(config);
115 // Don't loop-lift out of a conditional, because it can lead to type errors,
116 // or outside a try/catch, because it could lead to errors not being caught
117 Expression choose = getContainingConditional(exp);
118 if (choose != null) {
119 markDependencies(exp, choose);
120 }
121 for (Operand o : exp.operands()) {
122 gatherInfo(o.getChildExpression(), level+1, o.isEvaluatedRepeatedly() ? loopLevel+1 : loopLevel, threaded);
123 }
124 }
125
126 private Expression getContainingConditional(Expression exp) {
127 Expression parent = exp.getParentExpression();
128 while (parent != null) {
129 if (parent instanceof ConditionalInstruction) {
130 Operand o = ExpressionTool.findOperand(parent, exp);
131 if (o == null) {
132 throw new AssertionError();
133 }
134 if (o.getOperandRole().isInChoiceGroup()) {
135 return parent;
136 }
137 } else if (parent instanceof TryCatch) {
138 return parent;
139 }
140 exp = parent;
141 parent = parent.getParentExpression();
142 }
143 return null;
144 }
145
146
147 private boolean mayReturnStreamedNodes(Expression exp) {
148 // bug 3465: expressions returning streamed nodes cannot be loop-lifted,
149 // because such nodes must not be bound to a variable
150 // TODO: attempt a more rigorous analysis - see bug 3465
151 return streaming && !exp.getItemType().getUType().intersection(UType.ANY_NODE).equals(UType.VOID);
152 }
153
154 /**
155 * Register the dependencies of an expressions, and its applicable ancestor expressions, on some ancestor
156 * expression that binds a variable or the focus
157 * @param exp the dependent expression
158 * @param variableSetter the expression that sets the focus or the variable in question. May be null, in which
159 * case no dependencies are marked.
160 */
161
162 private void markDependencies(Expression exp, Expression variableSetter) {
163 Expression parent;
164 if (variableSetter != null) {
165 parent = exp;
166 while (parent != null && parent != variableSetter) {
167 try {
168 expInfoMap.get(parent).dependees.put(variableSetter, true);
169 } catch (NullPointerException e) {
170 e.printStackTrace();
171 throw e;
172 }
173 parent = parent.getParentExpression();
174 }
175 }
176 }
177
178
179 private void loopLift(Expression exp) {
180 ExpInfo info = expInfoMap.get(exp);
181 if (!info.multiThreaded) {
182 if (info.loopLevel > 0 && exp.getNetCost() > 0) {
183 if (info.dependees.isEmpty() && exp.isLiftable(streaming) && !mayReturnStreamedNodes(exp)) {
184 root = lift(exp, root);
185 } else {
186 Expression child = exp;
187 ExpInfo expInfo = expInfoMap.get(exp);
188 Expression parent = exp.getParentExpression();
189 while (parent != null) {
190 if (expInfo.dependees.get(parent) != null) {
191 ExpInfo childInfo = expInfoMap.get(child);
192 if (expInfo.loopLevel != childInfo.loopLevel) {
193 Operand o = ExpressionTool.findOperand(parent, child);
194 assert o != null;
195 if (exp.isLiftable(streaming) && !(child instanceof PseudoExpression) && !o.getOperandRole().isConstrainedClass()) {
196 Expression lifted = lift(exp, child);
197 o.setChildExpression(lifted);
198 }
199 }
200 break;
201 }
202 child = parent;
203 parent = parent.getParentExpression();
204 }
205 }
206 }
207 for (Operand o : exp.operands()) {
208 if (!o.getOperandRole().isConstrainedClass()) {
209 loopLift(o.getChildExpression());
210 }
211 }
212 }
213 }
214
215 private Expression lift(Expression child, Expression newAction) {
216
217 changed = true;
218 ExpInfo childInfo = expInfoMap.get(child);
219 ExpInfo actionInfo = expInfoMap.get(newAction);
220
221 final int hoist = childInfo.loopLevel - actionInfo.loopLevel;
222
223 Expression oldParent = child.getParentExpression();
224 Operand oldOperand = ExpressionTool.findOperand(oldParent, child);
225 assert oldOperand != null;
226
227 LetExpression let = new LetExpression();
228 let.setVariableQName(new StructuredQName("vv", NamespaceConstant.SAXON_GENERATED_VARIABLE, "v" + sequence++));
229 SequenceType type = SequenceType.makeSequenceType(child.getItemType(), child.getCardinality());
230 let.setRequiredType(type);
231 ExpressionTool.copyLocationInfo(child, let);
232 let.setSequence(child);
233 let.setNeedsLazyEvaluation(true);
234 let.setEvaluationMode(Cardinality.allowsMany(child.getCardinality()) ? ExpressionTool.MAKE_MEMO_CLOSURE : ExpressionTool.MAKE_SINGLETON_CLOSURE);
235 let.setAction(newAction);
236 let.adoptChildExpression(newAction);
237 // if (indexed) {
238 // let.setIndexedVariable();
239 // }
240
241
242 ExpInfo letInfo = new ExpInfo();
243 letInfo.expression = let;
244 letInfo.dependees = childInfo.dependees;
245 letInfo.dependees.putAll(actionInfo.dependees);
246 letInfo.loopLevel = actionInfo.loopLevel;
247 expInfoMap.put(let, letInfo);
248
249 try {
250 ExpressionTool.processExpressionTree(child, null, (expression, result) -> {
251 ExpInfo info = expInfoMap.get(expression);
252 info.loopLevel -= hoist;
253 return false;
254 });
255 } catch (XPathException e) {
256 e.printStackTrace();
257 }
258
259 LocalVariableReference var = new LocalVariableReference(let);
260 int properties = child.getSpecialProperties() & StaticProperty.NOT_UNTYPED_ATOMIC;
261 var.setStaticType(type, null, properties);
262 var.setInLoop(true);
263 let.addReference(var, true);
264 ExpressionTool.copyLocationInfo(child, var);
265 oldOperand.setChildExpression(var);
266
267 if (tracing) {
268 Logger err = config.getLogger();
269 err.info("OPT : At line " + child.getLocation().getLineNumber() + " of " + child.getLocation().getSystemId());
270 err.info("OPT : Lifted (" + child.toShortString() + ") above (" + newAction.toShortString() + ") on line " + newAction.getLocation().getLineNumber());
271 err.info("OPT : Expression after rewrite: " + let);
272 }
273 return let;
274 }
275
276
277 }
278