Debian Codegraph @

external/llvm/releases/14.0.0/patches_external/IterativelyComputeRangesForDeeplyNested.patch

raw
1 From 5dad4c67882a5eac2485f722e8e4109642155058 Mon Sep 17 00:00:00 2001
2 From: Florian Hahn <[email protected]>
3 Date: Mon, 21 Nov 2022 21:56:14 +0000
4 Subject: [PATCH] [SCEV] Iteratively compute ranges for deeply nested
5 expressions.
6
7 At the moment, getRangeRef may overflow the stack for very deeply nested
8 expressions.
9
10 This patch introduces a new getRangeRefIter function, which first builds
11 a worklist of N-ary expressions and phi nodes, followed by their
12 operands iteratively.
13
14 getRangeRef has been extended to also take a Depth argument and it
15 switches to use getRangeRefIter once the depth reaches a certain
16 threshold.
17
18 This ensures compile-time is not impacted in general. Note that
19 the iterative algorithm may lead to a slightly different evaluation
20 order, which could result in slightly worse ranges for cyclic phis.
21
22 https://llvm-compile-time-tracker.com/compare.php?from=23c3eb7cdf3478c9db86f6cb5115821a8f0f5f40&to=e0e09fa338e77e53242bfc846e1484350ad79773&stat=instructions
23
24 Fixes #49579.
25
26 Reviewed By: mkazantsev
27
28 Differential Revision: https://reviews.llvm.org/D130728
29 ---
30 llvm/include/llvm/Analysis/ScalarEvolution.h | 10 +-
31 llvm/lib/Analysis/ScalarEvolution.cpp | 110 +++++++++++++++---
32 llvm/test/Analysis/ScalarEvolution/ranges.ll | 1 +
33 .../IndVarSimplify/range-iter-threshold.ll | 73 ++++++++++++
34 4 files changed, 174 insertions(+), 20 deletions(-)
35 create mode 100644 llvm/test/Transforms/IndVarSimplify/range-iter-threshold.ll
36
37 diff --git a/llvm/include/llvm/Analysis/ScalarEvolution.h b/llvm/include/llvm/Analysis/ScalarEvolution.h
38 index 580fef9f7a5d656..49f8ae84f46f5ee 100644
39 --- a/llvm/include/llvm/Analysis/ScalarEvolution.h
40 +++ b/llvm/include/llvm/Analysis/ScalarEvolution.h
41 @@ -1283,6 +1283,9 @@ class ScalarEvolution {
42 /// Mark SCEVUnknown Phis currently being processed by getRangeRef.
43 SmallPtrSet<const PHINode *, 6> PendingPhiRanges;
44
45 + /// Mark SCEVUnknown Phis currently being processed by getRangeRefIter.
46 + SmallPtrSet<const PHINode *, 6> PendingPhiRangesIter;
47 +
48 // Mark SCEVUnknown Phis currently being processed by isImpliedViaMerge.
49 SmallPtrSet<const PHINode *, 6> PendingMerges;
50
51 @@ -1560,7 +1563,12 @@ class ScalarEvolution {
52 /// Determine the range for a particular SCEV.
53 /// NOTE: This returns a reference to an entry in a cache. It must be
54 /// copied if its needed for longer.
55 - const ConstantRange &getRangeRef(const SCEV *S, RangeSignHint Hint);
56 + const ConstantRange &getRangeRef(const SCEV *S, RangeSignHint Hint,
57 + unsigned Depth = 0);
58 +
59 + /// Determine the range for a particular SCEV, but evaluates ranges for
60 + /// operands iteratively first.
61 + const ConstantRange &getRangeRefIter(const SCEV *S, RangeSignHint Hint);
62
63 /// Determines the range for the affine SCEVAddRecExpr {\p Start,+,\p Step}.
64 /// Helper for \c getRange.
65 diff --git a/llvm/lib/Analysis/ScalarEvolution.cpp b/llvm/lib/Analysis/ScalarEvolution.cpp
66 index e2dd015bc57159e..b7766992590f81e 100644
67 --- a/llvm/lib/Analysis/ScalarEvolution.cpp
68 +++ b/llvm/lib/Analysis/ScalarEvolution.cpp
69 @@ -220,6 +220,11 @@ static cl::opt<unsigned>
70 cl::desc("Size of the expression which is considered huge"),
71 cl::init(4096));
72
73 +static cl::opt<unsigned> RangeIterThreshold(
74 + "scev-range-iter-threshold", cl::Hidden,
75 + cl::desc("Threshold for switching to iteratively computing SCEV ranges"),
76 + cl::init(32));
77 +
78 static cl::opt<bool>
79 ClassifyExpressions("scalar-evolution-classify-expressions",
80 cl::Hidden, cl::init(true),
81 @@ -6425,18 +6430,78 @@ getRangeForUnknownRecurrence(const SCEVUnknown *U) {
82 return FullSet;
83 }
84
85 +const ConstantRange &
86 +ScalarEvolution::getRangeRefIter(const SCEV *S,
87 + ScalarEvolution::RangeSignHint SignHint) {
88 + DenseMap<const SCEV *, ConstantRange> &Cache =
89 + SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
90 + : SignedRanges;
91 + SmallVector<const SCEV *> WorkList;
92 + SmallPtrSet<const SCEV *, 8> Seen;
93 +
94 + // Add Expr to the worklist, if Expr is either an N-ary expression or a
95 + // SCEVUnknown PHI node.
96 + auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
97 + if (!Seen.insert(Expr).second)
98 + return;
99 + if (Cache.find(Expr) != Cache.end())
100 + return;
101 + if (isa<SCEVNAryExpr>(Expr) || isa<SCEVUDivExpr>(Expr))
102 + WorkList.push_back(Expr);
103 + else if (auto *UnknownS = dyn_cast<SCEVUnknown>(Expr))
104 + if (isa<PHINode>(UnknownS->getValue()))
105 + WorkList.push_back(Expr);
106 + };
107 + AddToWorklist(S);
108 +
109 + // Build worklist by queuing operands of N-ary expressions and phi nodes.
110 + for (unsigned I = 0; I != WorkList.size(); ++I) {
111 + const SCEV *P = WorkList[I];
112 + if (auto *NaryS = dyn_cast<SCEVNAryExpr>(P)) {
113 + for (const SCEV *Op : NaryS->operands())
114 + AddToWorklist(Op);
115 + } else if (auto *UDiv = dyn_cast<SCEVUDivExpr>(P)) {
116 + AddToWorklist(UDiv->getLHS());
117 + AddToWorklist(UDiv->getRHS());
118 + } else {
119 + auto *UnknownS = cast<SCEVUnknown>(P);
120 + if (const PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
121 + if (!PendingPhiRangesIter.insert(P).second)
122 + continue;
123 + for (auto &Op : reverse(P->operands()))
124 + AddToWorklist(getSCEV(Op));
125 + }
126 + }
127 + }
128 +
129 + if (!WorkList.empty()) {
130 + // Use getRangeRef to compute ranges for items in the worklist in reverse
131 + // order. This will force ranges for earlier operands to be computed before
132 + // their users in most cases.
133 + for (const SCEV *P :
134 + reverse(make_range(WorkList.begin() + 1, WorkList.end()))) {
135 + getRangeRef(P, SignHint);
136 +
137 + if (auto *UnknownS = dyn_cast<SCEVUnknown>(P))
138 + if (const PHINode *P = dyn_cast<PHINode>(UnknownS->getValue()))
139 + PendingPhiRangesIter.erase(P);
140 + }
141 + }
142 +
143 + return getRangeRef(S, SignHint, 0);
144 +}
145 +
146 /// Determine the range for a particular SCEV. If SignHint is
147 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
148 /// with a "cleaner" unsigned (resp. signed) representation.
149 -const ConstantRange &
150 -ScalarEvolution::getRangeRef(const SCEV *S,
151 - ScalarEvolution::RangeSignHint SignHint) {
152 +const ConstantRange &ScalarEvolution::getRangeRef(
153 + const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
154 DenseMap<const SCEV *, ConstantRange> &Cache =
155 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
156 : SignedRanges;
157 ConstantRange::PreferredRangeType RangeType =
158 - SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
159 - ? ConstantRange::Unsigned : ConstantRange::Signed;
160 + SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
161 + : ConstantRange::Signed;
162
163 // See if we've computed this range already.
164 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
165 @@ -6446,6 +6511,11 @@ ScalarEvolution::getRangeRef(const SCEV *S,
166 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
167 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
168
169 + // Switch to iteratively computing the range for S, if it is part of a deeply
170 + // nested expression.
171 + if (Depth > RangeIterThreshold)
172 + return getRangeRefIter(S, SignHint);
173 +
174 unsigned BitWidth = getTypeSizeInBits(S->getType());
175 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
176 using OBO = OverflowingBinaryOperator;
177 @@ -6465,23 +6535,23 @@ ScalarEvolution::getRangeRef(const SCEV *S,
178 }
179
180 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
181 - ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
182 + ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
183 unsigned WrapType = OBO::AnyWrap;
184 if (Add->hasNoSignedWrap())
185 WrapType |= OBO::NoSignedWrap;
186 if (Add->hasNoUnsignedWrap())
187 WrapType |= OBO::NoUnsignedWrap;
188 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
189 - X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint),
190 + X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint, Depth + 1),
191 WrapType, RangeType);
192 return setRange(Add, SignHint,
193 ConservativeResult.intersectWith(X, RangeType));
194 }
195
196 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
197 - ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
198 + ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
199 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
200 - X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
201 + X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint, Depth + 1));
202 return setRange(Mul, SignHint,
203 ConservativeResult.intersectWith(X, RangeType));
204 }
205 @@ -6507,41 +6577,42 @@ ScalarEvolution::getRangeRef(const SCEV *S,
206 }
207
208 const auto *NAry = cast<SCEVNAryExpr>(S);
209 - ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint);
210 + ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
211 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
212 - X = X.intrinsic(ID, {X, getRangeRef(NAry->getOperand(i), SignHint)});
213 + X = X.intrinsic(
214 + ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
215 return setRange(S, SignHint,
216 ConservativeResult.intersectWith(X, RangeType));
217 }
218
219 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
220 - ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
221 - ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
222 + ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
223 + ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
224 return setRange(UDiv, SignHint,
225 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
226 }
227
228 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
229 - ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
230 + ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
231 return setRange(ZExt, SignHint,
232 ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
233 RangeType));
234 }
235
236 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
237 - ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
238 + ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
239 return setRange(SExt, SignHint,
240 ConservativeResult.intersectWith(X.signExtend(BitWidth),
241 RangeType));
242 }
243
244 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) {
245 - ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint);
246 + ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint, Depth + 1);
247 return setRange(PtrToInt, SignHint, X);
248 }
249
250 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
251 - ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
252 + ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
253 return setRange(Trunc, SignHint,
254 ConservativeResult.intersectWith(X.truncate(BitWidth),
255 RangeType));
256 @@ -6671,12 +6742,13 @@ ScalarEvolution::getRangeRef(const SCEV *S,
257 RangeType);
258
259 // A range of Phi is a subset of union of all ranges of its input.
260 - if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
261 + if (PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
262 // Make sure that we do not run over cycled Phis.
263 if (PendingPhiRanges.insert(Phi).second) {
264 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
265 +
266 for (auto &Op : Phi->operands()) {
267 - auto OpRange = getRangeRef(getSCEV(Op), SignHint);
268 + auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
269 RangeFromOps = RangeFromOps.unionWith(OpRange);
270 // No point to continue if we already have a full set.
271 if (RangeFromOps.isFullSet())
272 diff --git a/llvm/test/Analysis/ScalarEvolution/ranges.ll b/llvm/test/Analysis/ScalarEvolution/ranges.ll
273 index f5583d091f148d2..1a72f10cdd3df7a 100644
274 --- a/llvm/test/Analysis/ScalarEvolution/ranges.ll
275 +++ b/llvm/test/Analysis/ScalarEvolution/ranges.ll
276 @@ -1,5 +1,6 @@
277 ; NOTE: Assertions have been autogenerated by utils/update_analyze_test_checks.py
278 ; RUN: opt < %s -disable-output "-passes=print<scalar-evolution>" 2>&1 | FileCheck %s
279 + ; RUN: opt < %s -disable-output "-passes=print<scalar-evolution>" -scev-range-iter-threshold=1 2>&1 | FileCheck %s
280
281 target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64"
282
283 diff --git a/llvm/test/Transforms/IndVarSimplify/range-iter-threshold.ll b/llvm/test/Transforms/IndVarSimplify/range-iter-threshold.ll
284 new file mode 100644
285 index 000000000000000..9b27d01f8eee0f9
286 --- /dev/null
287 +++ b/llvm/test/Transforms/IndVarSimplify/range-iter-threshold.ll
288 @@ -0,0 +1,73 @@
289 +; RUN: opt -passes=indvars -S %s | FileCheck --check-prefix=COMMON --check-prefix=DEFAULT %s
290 +; RUN: opt -passes=indvars -scev-range-iter-threshold=1 -S %s | FileCheck --check-prefix=COMMON --check-prefix=LIMIT %s
291 +
292 +target datalayout = "e-m:o-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
293 +
294 +define i32 @test(i1 %c.0, i32 %m) {
295 +; COMMON-LABEL: @test(
296 +; COMMON-NEXT: entry:
297 +; COMMON-NEXT: br label [[OUTER_HEADER:%.*]]
298 +; COMMON: outer.header:
299 +; DEFAULT-NEXT: [[INDVARS_IV:%.*]] = phi i32 [ [[INDVARS_IV_NEXT:%.*]], [[OUTER_LATCH:%.*]] ], [ 2, [[ENTRY:%.*]] ]
300 +; COMMON-NEXT: [[IV_1:%.*]] = phi i32 [ 0, [[ENTRY:%.*]] ], [ [[IV_1_NEXT:%.*]], [[OUTER_LATCH:%.*]] ]
301 +; COMMON-NEXT: [[MAX_0:%.*]] = phi i32 [ 0, [[ENTRY]] ], [ [[MAX_1:%.*]], [[OUTER_LATCH]] ]
302 +; COMMON-NEXT: [[TMP0:%.*]] = sext i32 [[IV_1]] to i64
303 +; COMMON-NEXT: br label [[INNER_1:%.*]]
304 +; COMMON: inner.1:
305 +; COMMON-NEXT: [[C_1:%.*]] = icmp slt i64 0, [[TMP0]]
306 +; COMMON-NEXT: br i1 [[C_1]], label [[INNER_1]], label [[INNER_2_HEADER_PREHEADER:%.*]]
307 +; COMMON: inner.2.header.preheader:
308 +; COMMON-NEXT: br label [[INNER_2_HEADER:%.*]]
309 +; COMMON: inner.2.header:
310 +; COMMON-NEXT: [[IV_3:%.*]] = phi i32 [ [[IV_3_NEXT:%.*]], [[INNER_2_LATCH:%.*]] ], [ 0, [[INNER_2_HEADER_PREHEADER]] ]
311 +; COMMON-NEXT: br i1 [[C_0:%.*]], label [[OUTER_LATCH]], label [[INNER_2_LATCH]]
312 +; COMMON: inner.2.latch:
313 +; COMMON-NEXT: [[IV_3_NEXT]] = add i32 [[IV_3]], 1
314 +; DEFAULT-NEXT: [[EXITCOND:%.*]] = icmp eq i32 [[IV_3_NEXT]], [[INDVARS_IV]]
315 +; LIMIT-NEXT: [[EXITCOND:%.*]] = icmp ugt i32 [[IV_3]], [[IV_1]]
316 +; COMMON-NEXT: br i1 [[EXITCOND]], label [[OUTER_LATCH]], label [[INNER_2_HEADER]]
317 +; COMMON: outer.latch:
318 +; COMMON-NEXT: [[MAX_1]] = phi i32 [ [[M:%.*]], [[INNER_2_LATCH]] ], [ 0, [[INNER_2_HEADER]] ]
319 +; COMMON-NEXT: [[IV_1_NEXT]] = add nuw i32 [[IV_1]], 1
320 +; COMMON-NEXT: [[C_3:%.*]] = icmp ugt i32 [[IV_1]], [[MAX_0]]
321 +; DEFAULT-NEXT: [[INDVARS_IV_NEXT]] = add i32 [[INDVARS_IV]], 1
322 +; COMMON-NEXT: br i1 [[C_3]], label [[EXIT:%.*]], label [[OUTER_HEADER]], !llvm.loop [[LOOP0:![0-9]+]]
323 +; COMMON: exit:
324 +; COMMON-NEXT: ret i32 0
325 +;
326 +entry:
327 + br label %outer.header
328 +
329 +outer.header:
330 + %iv.1 = phi i32 [ 0, %entry ], [ %iv.1.next, %outer.latch ]
331 + %iv.2 = phi i32 [ 0, %entry ], [ %iv.2.next , %outer.latch ]
332 + %max.0 = phi i32 [ 0, %entry ], [ %max.1, %outer.latch ]
333 + %0 = sext i32 %iv.1 to i64
334 + br label %inner.1
335 +
336 +inner.1:
337 + %c.1 = icmp slt i64 0, %0
338 + br i1 %c.1, label %inner.1, label %inner.2.header
339 +
340 +inner.2.header:
341 + %iv.3 = phi i32 [ 0, %inner.1 ], [ %iv.3.next, %inner.2.latch ]
342 + br i1 %c.0, label %outer.latch, label %inner.2.latch
343 +
344 +inner.2.latch:
345 + %iv.3.next = add i32 %iv.3, 1
346 + %c.2 = icmp ugt i32 %iv.3, %iv.2
347 + br i1 %c.2, label %outer.latch, label %inner.2.header
348 +
349 +outer.latch:
350 + %max.1 = phi i32 [ %m, %inner.2.latch ], [ %iv.3, %inner.2.header ]
351 + %iv.1.next = add i32 %iv.1, 1
352 + %iv.2.next = add i32 %iv.2, 1
353 + %c.3 = icmp ugt i32 %iv.2, %max.0
354 + br i1 %c.3, label %exit, label %outer.header, !llvm.loop !0
355 +
356 +exit:
357 + ret i32 0
358 +}
359 +
360 +!0 = distinct !{!0, !1}
361 +!1 = !{!"llvm.loop.mustprogress"}