blob: 0429aeeb49e83986edb00a5215c13b71ac39779f [file] [log] [blame]
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001//===-- InductiveRangeCheckElimination.cpp - ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9// The InductiveRangeCheckElimination pass splits a loop's iteration space into
10// three disjoint ranges. It does that in a way such that the loop running in
11// the middle loop provably does not need range checks. As an example, it will
12// convert
13//
14// len = < known positive >
15// for (i = 0; i < n; i++) {
16// if (0 <= i && i < len) {
17// do_something();
18// } else {
19// throw_out_of_bounds();
20// }
21// }
22//
23// to
24//
25// len = < known positive >
26// limit = smin(n, len)
27// // no first segment
28// for (i = 0; i < limit; i++) {
29// if (0 <= i && i < len) { // this check is fully redundant
30// do_something();
31// } else {
32// throw_out_of_bounds();
33// }
34// }
35// for (i = limit; i < n; i++) {
36// if (0 <= i && i < len) {
37// do_something();
38// } else {
39// throw_out_of_bounds();
40// }
41// }
42//===----------------------------------------------------------------------===//
43
44#include "llvm/ADT/Optional.h"
45
Sanjoy Dasdcf26512015-01-27 21:38:12 +000046#include "llvm/Analysis/BranchProbabilityInfo.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000047#include "llvm/Analysis/InstructionSimplify.h"
48#include "llvm/Analysis/LoopInfo.h"
49#include "llvm/Analysis/LoopPass.h"
50#include "llvm/Analysis/ScalarEvolution.h"
51#include "llvm/Analysis/ScalarEvolutionExpander.h"
52#include "llvm/Analysis/ScalarEvolutionExpressions.h"
53#include "llvm/Analysis/ValueTracking.h"
54
55#include "llvm/IR/Dominators.h"
56#include "llvm/IR/Function.h"
57#include "llvm/IR/Instructions.h"
58#include "llvm/IR/IRBuilder.h"
59#include "llvm/IR/Module.h"
60#include "llvm/IR/PatternMatch.h"
61#include "llvm/IR/ValueHandle.h"
62#include "llvm/IR/Verifier.h"
63
64#include "llvm/Support/Debug.h"
65
66#include "llvm/Transforms/Scalar.h"
67#include "llvm/Transforms/Utils/BasicBlockUtils.h"
68#include "llvm/Transforms/Utils/Cloning.h"
69#include "llvm/Transforms/Utils/LoopUtils.h"
70#include "llvm/Transforms/Utils/SimplifyIndVar.h"
71#include "llvm/Transforms/Utils/UnrollLoop.h"
72
73#include "llvm/Pass.h"
74
75#include <array>
76
77using namespace llvm;
78
Benjamin Kramer970eac42015-02-06 17:51:54 +000079static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
80 cl::init(64));
Sanjoy Dasa1837a32015-01-16 01:03:22 +000081
Benjamin Kramer970eac42015-02-06 17:51:54 +000082static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
83 cl::init(false));
Sanjoy Dasa1837a32015-01-16 01:03:22 +000084
Sanjoy Dase91665d2015-02-26 08:56:04 +000085static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
86 cl::Hidden, cl::init(10));
87
Sanjoy Dasa1837a32015-01-16 01:03:22 +000088#define DEBUG_TYPE "irce"
89
90namespace {
91
92/// An inductive range check is conditional branch in a loop with
93///
94/// 1. a very cold successor (i.e. the branch jumps to that successor very
95/// rarely)
96///
97/// and
98///
Sanjoy Dase2cde6f2015-03-17 00:42:13 +000099/// 2. a condition that is provably true for some contiguous range of values
100/// taken by the containing loop's induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000101///
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000102class InductiveRangeCheck {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000103 // Classifies a range check
104 enum RangeCheckKind {
105 // Range check of the form "0 <= I".
106 RANGE_CHECK_LOWER = 1,
107
108 // Range check of the form "I < L" where L is known positive.
109 RANGE_CHECK_UPPER = 2,
110
111 // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER
112 // conditions.
113 RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
114
115 // Unrecognized range check condition.
116 RANGE_CHECK_UNKNOWN = (unsigned)-1
117 };
118
119 static const char *rangeCheckKindToStr(RangeCheckKind);
120
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000121 const SCEV *Offset;
122 const SCEV *Scale;
123 Value *Length;
124 BranchInst *Branch;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000125 RangeCheckKind Kind;
126
127 static RangeCheckKind parseRangeCheckICmp(ICmpInst *ICI, ScalarEvolution &SE,
128 Value *&Index, Value *&Length);
129
130 static InductiveRangeCheck::RangeCheckKind
131 parseRangeCheck(Loop *L, ScalarEvolution &SE, Value *Condition,
132 const SCEV *&Index, Value *&UpperLimit);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000133
134 InductiveRangeCheck() :
135 Offset(nullptr), Scale(nullptr), Length(nullptr), Branch(nullptr) { }
136
137public:
138 const SCEV *getOffset() const { return Offset; }
139 const SCEV *getScale() const { return Scale; }
140 Value *getLength() const { return Length; }
141
142 void print(raw_ostream &OS) const {
143 OS << "InductiveRangeCheck:\n";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000144 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000145 OS << " Offset: ";
146 Offset->print(OS);
147 OS << " Scale: ";
148 Scale->print(OS);
149 OS << " Length: ";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000150 if (Length)
151 Length->print(OS);
152 else
153 OS << "(null)";
154 OS << "\n Branch: ";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000155 getBranch()->print(OS);
Sanjoy Das48c75812015-02-26 04:03:31 +0000156 OS << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000157 }
158
159#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
160 void dump() {
161 print(dbgs());
162 }
163#endif
164
165 BranchInst *getBranch() const { return Branch; }
166
Sanjoy Das351db052015-01-22 09:32:02 +0000167 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
168 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
169
170 class Range {
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000171 const SCEV *Begin;
172 const SCEV *End;
Sanjoy Das351db052015-01-22 09:32:02 +0000173
174 public:
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000175 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
Sanjoy Das351db052015-01-22 09:32:02 +0000176 assert(Begin->getType() == End->getType() && "ill-typed range!");
177 }
178
179 Type *getType() const { return Begin->getType(); }
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000180 const SCEV *getBegin() const { return Begin; }
181 const SCEV *getEnd() const { return End; }
Sanjoy Das351db052015-01-22 09:32:02 +0000182 };
183
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000184 typedef SpecificBumpPtrAllocator<InductiveRangeCheck> AllocatorTy;
185
186 /// This is the value the condition of the branch needs to evaluate to for the
187 /// branch to take the hot successor (see (1) above).
188 bool getPassingDirection() { return true; }
189
Sanjoy Das95c476d2015-02-21 22:20:22 +0000190 /// Computes a range for the induction variable (IndVar) in which the range
191 /// check is redundant and can be constant-folded away. The induction
192 /// variable is not required to be the canonical {0,+,1} induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000193 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
Sanjoy Das95c476d2015-02-21 22:20:22 +0000194 const SCEVAddRecExpr *IndVar,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000195 IRBuilder<> &B) const;
196
197 /// Create an inductive range check out of BI if possible, else return
198 /// nullptr.
199 static InductiveRangeCheck *create(AllocatorTy &Alloc, BranchInst *BI,
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000200 Loop *L, ScalarEvolution &SE,
201 BranchProbabilityInfo &BPI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000202};
203
204class InductiveRangeCheckElimination : public LoopPass {
205 InductiveRangeCheck::AllocatorTy Allocator;
206
207public:
208 static char ID;
209 InductiveRangeCheckElimination() : LoopPass(ID) {
210 initializeInductiveRangeCheckEliminationPass(
211 *PassRegistry::getPassRegistry());
212 }
213
214 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000215 AU.addRequired<LoopInfoWrapperPass>();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000216 AU.addRequiredID(LoopSimplifyID);
217 AU.addRequiredID(LCSSAID);
218 AU.addRequired<ScalarEvolution>();
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000219 AU.addRequired<BranchProbabilityInfo>();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000220 }
221
222 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
223};
224
225char InductiveRangeCheckElimination::ID = 0;
226}
227
228INITIALIZE_PASS(InductiveRangeCheckElimination, "irce",
229 "Inductive range check elimination", false, false)
230
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000231const char *InductiveRangeCheck::rangeCheckKindToStr(
232 InductiveRangeCheck::RangeCheckKind RCK) {
233 switch (RCK) {
234 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
235 return "RANGE_CHECK_UNKNOWN";
236
237 case InductiveRangeCheck::RANGE_CHECK_UPPER:
238 return "RANGE_CHECK_UPPER";
239
240 case InductiveRangeCheck::RANGE_CHECK_LOWER:
241 return "RANGE_CHECK_LOWER";
242
243 case InductiveRangeCheck::RANGE_CHECK_BOTH:
244 return "RANGE_CHECK_BOTH";
245 }
246
247 llvm_unreachable("unknown range check type!");
248}
249
250/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI`
251/// cannot
252/// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
253/// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value
254/// being
255/// range checked, and set `Length` to the upper limit `Index` is being range
256/// checked with if (and only if) the range check type is stronger or equal to
257/// RANGE_CHECK_UPPER.
258///
259InductiveRangeCheck::RangeCheckKind
260InductiveRangeCheck::parseRangeCheckICmp(ICmpInst *ICI, ScalarEvolution &SE,
261 Value *&Index, Value *&Length) {
262
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000263 using namespace llvm::PatternMatch;
264
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000265 ICmpInst::Predicate Pred = ICI->getPredicate();
266 Value *LHS = ICI->getOperand(0);
267 Value *RHS = ICI->getOperand(1);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000268
269 switch (Pred) {
270 default:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000271 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000272
273 case ICmpInst::ICMP_SLE:
274 std::swap(LHS, RHS);
275 // fallthrough
276 case ICmpInst::ICMP_SGE:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000277 if (match(RHS, m_ConstantInt<0>())) {
278 Index = LHS;
279 return RANGE_CHECK_LOWER;
280 }
281 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000282
283 case ICmpInst::ICMP_SLT:
284 std::swap(LHS, RHS);
285 // fallthrough
286 case ICmpInst::ICMP_SGT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000287 if (match(RHS, m_ConstantInt<-1>())) {
288 Index = LHS;
289 return RANGE_CHECK_LOWER;
290 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000291
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000292 if (SE.isKnownNonNegative(SE.getSCEV(LHS))) {
293 Index = RHS;
294 Length = LHS;
295 return RANGE_CHECK_UPPER;
296 }
297 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000298
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000299 case ICmpInst::ICMP_ULT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000300 std::swap(LHS, RHS);
301 // fallthrough
302 case ICmpInst::ICMP_UGT:
303 if (SE.isKnownNonNegative(SE.getSCEV(LHS))) {
304 Index = RHS;
305 Length = LHS;
306 return RANGE_CHECK_BOTH;
307 }
308 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000309 }
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000310
311 llvm_unreachable("default clause returns!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000312}
313
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000314/// Parses an arbitrary condition into a range check. `Length` is set only if
315/// the range check is recognized to be `RANGE_CHECK_UPPER` or stronger.
316InductiveRangeCheck::RangeCheckKind
317InductiveRangeCheck::parseRangeCheck(Loop *L, ScalarEvolution &SE,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000318 Value *Condition, const SCEV *&Index,
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000319 Value *&Length) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000320 using namespace llvm::PatternMatch;
321
322 Value *A = nullptr;
323 Value *B = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000324
325 if (match(Condition, m_And(m_Value(A), m_Value(B)))) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000326 Value *IndexA = nullptr, *IndexB = nullptr;
327 Value *LengthA = nullptr, *LengthB = nullptr;
328 ICmpInst *ICmpA = dyn_cast<ICmpInst>(A), *ICmpB = dyn_cast<ICmpInst>(B);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000329
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000330 if (!ICmpA || !ICmpB)
331 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000332
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000333 auto RCKindA = parseRangeCheckICmp(ICmpA, SE, IndexA, LengthA);
334 auto RCKindB = parseRangeCheckICmp(ICmpB, SE, IndexB, LengthB);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000335
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000336 if (RCKindA == InductiveRangeCheck::RANGE_CHECK_UNKNOWN ||
337 RCKindB == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
338 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000339
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000340 if (IndexA != IndexB)
341 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
342
343 if (LengthA != nullptr && LengthB != nullptr && LengthA != LengthB)
344 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
345
346 Index = SE.getSCEV(IndexA);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000347 if (isa<SCEVCouldNotCompute>(Index))
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000348 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000349
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000350 Length = LengthA == nullptr ? LengthB : LengthA;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000351
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000352 return (InductiveRangeCheck::RangeCheckKind)(RCKindA | RCKindB);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000353 }
354
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000355 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
356 Value *IndexVal = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000357
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000358 auto RCKind = parseRangeCheckICmp(ICI, SE, IndexVal, Length);
359
360 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
361 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
362
363 Index = SE.getSCEV(IndexVal);
364 if (isa<SCEVCouldNotCompute>(Index))
365 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
366
367 return RCKind;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000368 }
369
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000370 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000371}
372
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000373
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000374InductiveRangeCheck *
375InductiveRangeCheck::create(InductiveRangeCheck::AllocatorTy &A, BranchInst *BI,
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000376 Loop *L, ScalarEvolution &SE,
377 BranchProbabilityInfo &BPI) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000378
379 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
380 return nullptr;
381
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000382 BranchProbability LikelyTaken(15, 16);
383
384 if (BPI.getEdgeProbability(BI->getParent(), (unsigned) 0) < LikelyTaken)
385 return nullptr;
386
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000387 Value *Length = nullptr;
388 const SCEV *IndexSCEV = nullptr;
389
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000390 auto RCKind = InductiveRangeCheck::parseRangeCheck(L, SE, BI->getCondition(),
391 IndexSCEV, Length);
392
393 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000394 return nullptr;
395
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000396 assert(IndexSCEV && "contract with SplitRangeCheckCondition!");
397 assert(!(RCKind & InductiveRangeCheck::RANGE_CHECK_UPPER) ||
398 Length && "contract with SplitRangeCheckCondition!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000399
400 const SCEVAddRecExpr *IndexAddRec = dyn_cast<SCEVAddRecExpr>(IndexSCEV);
401 bool IsAffineIndex =
402 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
403
404 if (!IsAffineIndex)
405 return nullptr;
406
407 InductiveRangeCheck *IRC = new (A.Allocate()) InductiveRangeCheck;
408 IRC->Length = Length;
409 IRC->Offset = IndexAddRec->getStart();
410 IRC->Scale = IndexAddRec->getStepRecurrence(SE);
411 IRC->Branch = BI;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000412 IRC->Kind = RCKind;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000413 return IRC;
414}
415
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000416namespace {
417
Sanjoy Dase75ed922015-02-26 08:19:31 +0000418// Keeps track of the structure of a loop. This is similar to llvm::Loop,
419// except that it is more lightweight and can track the state of a loop through
420// changing and potentially invalid IR. This structure also formalizes the
421// kinds of loops we can deal with -- ones that have a single latch that is also
422// an exiting block *and* have a canonical induction variable.
423struct LoopStructure {
424 const char *Tag;
425
426 BasicBlock *Header;
427 BasicBlock *Latch;
428
429 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
430 // successor is `LatchExit', the exit block of the loop.
431 BranchInst *LatchBr;
432 BasicBlock *LatchExit;
433 unsigned LatchBrExitIdx;
434
435 Value *IndVarNext;
436 Value *IndVarStart;
437 Value *LoopExitAt;
438 bool IndVarIncreasing;
439
440 LoopStructure()
441 : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr),
442 LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr),
443 IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false) {}
444
445 template <typename M> LoopStructure map(M Map) const {
446 LoopStructure Result;
447 Result.Tag = Tag;
448 Result.Header = cast<BasicBlock>(Map(Header));
449 Result.Latch = cast<BasicBlock>(Map(Latch));
450 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
451 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
452 Result.LatchBrExitIdx = LatchBrExitIdx;
453 Result.IndVarNext = Map(IndVarNext);
454 Result.IndVarStart = Map(IndVarStart);
455 Result.LoopExitAt = Map(LoopExitAt);
456 Result.IndVarIncreasing = IndVarIncreasing;
457 return Result;
458 }
459
Sanjoy Dase91665d2015-02-26 08:56:04 +0000460 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
461 BranchProbabilityInfo &BPI,
462 Loop &,
Sanjoy Dase75ed922015-02-26 08:19:31 +0000463 const char *&);
464};
465
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000466/// This class is used to constrain loops to run within a given iteration space.
467/// The algorithm this class implements is given a Loop and a range [Begin,
468/// End). The algorithm then tries to break out a "main loop" out of the loop
469/// it is given in a way that the "main loop" runs with the induction variable
470/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
471/// loops to run any remaining iterations. The pre loop runs any iterations in
472/// which the induction variable is < Begin, and the post loop runs any
473/// iterations in which the induction variable is >= End.
474///
475class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000476 // The representation of a clone of the original loop we started out with.
477 struct ClonedLoop {
478 // The cloned blocks
479 std::vector<BasicBlock *> Blocks;
480
481 // `Map` maps values in the clonee into values in the cloned version
482 ValueToValueMapTy Map;
483
484 // An instance of `LoopStructure` for the cloned loop
485 LoopStructure Structure;
486 };
487
488 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
489 // more details on what these fields mean.
490 struct RewrittenRangeInfo {
491 BasicBlock *PseudoExit;
492 BasicBlock *ExitSelector;
493 std::vector<PHINode *> PHIValuesAtPseudoExit;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000494 PHINode *IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000495
Sanjoy Dase75ed922015-02-26 08:19:31 +0000496 RewrittenRangeInfo()
497 : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000498 };
499
500 // Calculated subranges we restrict the iteration space of the main loop to.
501 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000502 // these fields are computed. `LowLimit` is None if there is no restriction
503 // on low end of the restricted iteration space of the main loop. `HighLimit`
504 // is None if there is no restriction on high end of the restricted iteration
505 // space of the main loop.
506
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000507 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000508 Optional<const SCEV *> LowLimit;
509 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000510 };
511
512 // A utility function that does a `replaceUsesOfWith' on the incoming block
513 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
514 // incoming block list with `ReplaceBy'.
515 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
516 BasicBlock *ReplaceBy);
517
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000518 // Compute a safe set of limits for the main loop to run in -- effectively the
519 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000520 // Return None if unable to compute the set of subranges.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000521 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000522 Optional<SubRanges> calculateSubRanges() const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000523
524 // Clone `OriginalLoop' and return the result in CLResult. The IR after
525 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
526 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
527 // but there is no such edge.
528 //
529 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
530
531 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
532 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
533 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
534 // `OriginalHeaderCount'.
535 //
536 // If there are iterations left to execute, control is made to jump to
537 // `ContinuationBlock', otherwise they take the normal loop exit. The
538 // returned `RewrittenRangeInfo' object is populated as follows:
539 //
540 // .PseudoExit is a basic block that unconditionally branches to
541 // `ContinuationBlock'.
542 //
543 // .ExitSelector is a basic block that decides, on exit from the loop,
544 // whether to branch to the "true" exit or to `PseudoExit'.
545 //
546 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
547 // for each PHINode in the loop header on taking the pseudo exit.
548 //
549 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
550 // preheader because it is made to branch to the loop header only
551 // conditionally.
552 //
553 RewrittenRangeInfo
554 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
555 Value *ExitLoopAt,
556 BasicBlock *ContinuationBlock) const;
557
558 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
559 // function creates a new preheader for `LS' and returns it.
560 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000561 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
562 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000563
564 // `ContinuationBlockAndPreheader' was the continuation block for some call to
565 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
566 // This function rewrites the PHI nodes in `LS.Header' to start with the
567 // correct value.
568 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000569 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000570 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
571
572 // Even though we do not preserve any passes at this time, we at least need to
573 // keep the parent loop structure consistent. The `LPPassManager' seems to
574 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000575 // blocks denoted by BBs to this loops parent loop if required.
576 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000577
578 // Some global state.
579 Function &F;
580 LLVMContext &Ctx;
581 ScalarEvolution &SE;
582
583 // Information about the original loop we started out with.
584 Loop &OriginalLoop;
585 LoopInfo &OriginalLoopInfo;
586 const SCEV *LatchTakenCount;
587 BasicBlock *OriginalPreheader;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000588
589 // The preheader of the main loop. This may or may not be different from
590 // `OriginalPreheader'.
591 BasicBlock *MainLoopPreheader;
592
593 // The range we need to run the main loop in.
594 InductiveRangeCheck::Range Range;
595
596 // The structure of the main loop (see comment at the beginning of this class
597 // for a definition)
598 LoopStructure MainLoopStructure;
599
600public:
Sanjoy Dase75ed922015-02-26 08:19:31 +0000601 LoopConstrainer(Loop &L, LoopInfo &LI, const LoopStructure &LS,
602 ScalarEvolution &SE, InductiveRangeCheck::Range R)
603 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
604 SE(SE), OriginalLoop(L), OriginalLoopInfo(LI), LatchTakenCount(nullptr),
605 OriginalPreheader(nullptr), MainLoopPreheader(nullptr), Range(R),
606 MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000607
608 // Entry point for the algorithm. Returns true on success.
609 bool run();
610};
611
612}
613
614void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
615 BasicBlock *ReplaceBy) {
616 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
617 if (PN->getIncomingBlock(i) == Block)
618 PN->setIncomingBlock(i, ReplaceBy);
619}
620
Sanjoy Dase75ed922015-02-26 08:19:31 +0000621static bool CanBeSMax(ScalarEvolution &SE, const SCEV *S) {
622 APInt SMax =
623 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
624 return SE.getSignedRange(S).contains(SMax) &&
625 SE.getUnsignedRange(S).contains(SMax);
626}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000627
Sanjoy Dase75ed922015-02-26 08:19:31 +0000628static bool CanBeSMin(ScalarEvolution &SE, const SCEV *S) {
629 APInt SMin =
630 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth());
631 return SE.getSignedRange(S).contains(SMin) &&
632 SE.getUnsignedRange(S).contains(SMin);
633}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000634
Sanjoy Dase75ed922015-02-26 08:19:31 +0000635Optional<LoopStructure>
Sanjoy Dase91665d2015-02-26 08:56:04 +0000636LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI,
637 Loop &L, const char *&FailureReason) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000638 assert(L.isLoopSimplifyForm() && "should follow from addRequired<>");
639
640 BasicBlock *Latch = L.getLoopLatch();
641 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000642 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000643 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000644 }
645
Sanjoy Dase75ed922015-02-26 08:19:31 +0000646 BasicBlock *Header = L.getHeader();
647 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000648 if (!Preheader) {
649 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000650 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000651 }
652
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000653 BranchInst *LatchBr = dyn_cast<BranchInst>(&*Latch->rbegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000654 if (!LatchBr || LatchBr->isUnconditional()) {
655 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000656 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000657 }
658
Sanjoy Dase75ed922015-02-26 08:19:31 +0000659 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000660
Sanjoy Dase91665d2015-02-26 08:56:04 +0000661 BranchProbability ExitProbability =
662 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
663
664 if (ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
665 FailureReason = "short running loop, not profitable";
666 return None;
667 }
668
Sanjoy Dase75ed922015-02-26 08:19:31 +0000669 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
670 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
671 FailureReason = "latch terminator branch not conditional on integral icmp";
672 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000673 }
674
Sanjoy Dase75ed922015-02-26 08:19:31 +0000675 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
676 if (isa<SCEVCouldNotCompute>(LatchCount)) {
677 FailureReason = "could not compute latch count";
678 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000679 }
680
Sanjoy Dase75ed922015-02-26 08:19:31 +0000681 ICmpInst::Predicate Pred = ICI->getPredicate();
682 Value *LeftValue = ICI->getOperand(0);
683 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
684 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
685
686 Value *RightValue = ICI->getOperand(1);
687 const SCEV *RightSCEV = SE.getSCEV(RightValue);
688
689 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
690 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
691 if (isa<SCEVAddRecExpr>(RightSCEV)) {
692 std::swap(LeftSCEV, RightSCEV);
693 std::swap(LeftValue, RightValue);
694 Pred = ICmpInst::getSwappedPredicate(Pred);
695 } else {
696 FailureReason = "no add recurrences in the icmp";
697 return None;
698 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000699 }
700
Sanjoy Dase75ed922015-02-26 08:19:31 +0000701 auto IsInductionVar = [&SE](const SCEVAddRecExpr *AR, bool &IsIncreasing) {
702 if (!AR->isAffine())
703 return false;
704
705 IntegerType *Ty = cast<IntegerType>(AR->getType());
706 IntegerType *WideTy =
707 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
708
709 // Currently we only work with induction variables that have been proved to
710 // not wrap. This restriction can potentially be lifted in the future.
711
712 const SCEVAddRecExpr *ExtendAfterOp =
713 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
714 if (!ExtendAfterOp)
715 return false;
716
717 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
718 const SCEV *ExtendedStep =
719 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
720
721 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
722 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
723
724 if (!NoSignedWrap)
725 return false;
726
727 if (const SCEVConstant *StepExpr =
728 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
729 ConstantInt *StepCI = StepExpr->getValue();
730 if (StepCI->isOne() || StepCI->isMinusOne()) {
731 IsIncreasing = StepCI->isOne();
732 return true;
733 }
734 }
735
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000736 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000737 };
738
739 // `ICI` is interpreted as taking the backedge if the *next* value of the
740 // induction variable satisfies some constraint.
741
742 const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
743 bool IsIncreasing = false;
744 if (!IsInductionVar(IndVarNext, IsIncreasing)) {
745 FailureReason = "LHS in icmp not induction variable";
746 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000747 }
748
Sanjoy Dase75ed922015-02-26 08:19:31 +0000749 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
750 // TODO: generalize the predicates here to also match their unsigned variants.
751 if (IsIncreasing) {
752 bool FoundExpectedPred =
753 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) ||
754 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0);
755
756 if (!FoundExpectedPred) {
757 FailureReason = "expected icmp slt semantically, found something else";
758 return None;
759 }
760
761 if (LatchBrExitIdx == 0) {
762 if (CanBeSMax(SE, RightSCEV)) {
763 // TODO: this restriction is easily removable -- we just have to
764 // remember that the icmp was an slt and not an sle.
765 FailureReason = "limit may overflow when coercing sle to slt";
766 return None;
767 }
768
769 IRBuilder<> B(&*Preheader->rbegin());
770 RightValue = B.CreateAdd(RightValue, One);
771 }
772
773 } else {
774 bool FoundExpectedPred =
775 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) ||
776 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0);
777
778 if (!FoundExpectedPred) {
779 FailureReason = "expected icmp sgt semantically, found something else";
780 return None;
781 }
782
783 if (LatchBrExitIdx == 0) {
784 if (CanBeSMin(SE, RightSCEV)) {
785 // TODO: this restriction is easily removable -- we just have to
786 // remember that the icmp was an sgt and not an sge.
787 FailureReason = "limit may overflow when coercing sge to sgt";
788 return None;
789 }
790
791 IRBuilder<> B(&*Preheader->rbegin());
792 RightValue = B.CreateSub(RightValue, One);
793 }
794 }
795
796 const SCEV *StartNext = IndVarNext->getStart();
797 const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
798 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
799
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000800 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
801
Sanjoy Dase75ed922015-02-26 08:19:31 +0000802 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000803 ScalarEvolution::LoopInvariant &&
804 "loop variant exit count doesn't make sense!");
805
Sanjoy Dase75ed922015-02-26 08:19:31 +0000806 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000807 const DataLayout &DL = Preheader->getModule()->getDataLayout();
808 Value *IndVarStartV =
809 SCEVExpander(SE, DL, "irce")
810 .expandCodeFor(IndVarStart, IndVarTy, &*Preheader->rbegin());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000811 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000812
Sanjoy Dase75ed922015-02-26 08:19:31 +0000813 LoopStructure Result;
814
815 Result.Tag = "main";
816 Result.Header = Header;
817 Result.Latch = Latch;
818 Result.LatchBr = LatchBr;
819 Result.LatchExit = LatchExit;
820 Result.LatchBrExitIdx = LatchBrExitIdx;
821 Result.IndVarStart = IndVarStartV;
822 Result.IndVarNext = LeftValue;
823 Result.IndVarIncreasing = IsIncreasing;
824 Result.LoopExitAt = RightValue;
825
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000826 FailureReason = nullptr;
827
Sanjoy Dase75ed922015-02-26 08:19:31 +0000828 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000829}
830
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000831Optional<LoopConstrainer::SubRanges>
Sanjoy Dase75ed922015-02-26 08:19:31 +0000832LoopConstrainer::calculateSubRanges() const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000833 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
834
Sanjoy Das351db052015-01-22 09:32:02 +0000835 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000836 return None;
837
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000838 LoopConstrainer::SubRanges Result;
839
840 // I think we can be more aggressive here and make this nuw / nsw if the
841 // addition that feeds into the icmp for the latch's terminating branch is nuw
842 // / nsw. In any case, a wrapping 2's complement addition is safe.
843 ConstantInt *One = ConstantInt::get(Ty, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000844 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
845 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000846
Sanjoy Dase75ed922015-02-26 08:19:31 +0000847 bool Increasing = MainLoopStructure.IndVarIncreasing;
848 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the
849 // range of values the induction variable takes.
850 const SCEV *Smallest =
851 Increasing ? Start : SE.getAddExpr(End, SE.getSCEV(One));
852 const SCEV *Greatest =
853 Increasing ? End : SE.getAddExpr(Start, SE.getSCEV(One));
854
855 auto Clamp = [this, Smallest, Greatest](const SCEV *S) {
856 return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S));
857 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000858
859 // In some cases we can prove that we don't need a pre or post loop
860
861 bool ProvablyNoPreloop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000862 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest);
863 if (!ProvablyNoPreloop)
864 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000865
866 bool ProvablyNoPostLoop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000867 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd());
868 if (!ProvablyNoPostLoop)
869 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000870
871 return Result;
872}
873
874void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
875 const char *Tag) const {
876 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
877 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
878 Result.Blocks.push_back(Clone);
879 Result.Map[BB] = Clone;
880 }
881
882 auto GetClonedValue = [&Result](Value *V) {
883 assert(V && "null values not in domain!");
884 auto It = Result.Map.find(V);
885 if (It == Result.Map.end())
886 return V;
887 return static_cast<Value *>(It->second);
888 };
889
890 Result.Structure = MainLoopStructure.map(GetClonedValue);
891 Result.Structure.Tag = Tag;
892
893 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
894 BasicBlock *ClonedBB = Result.Blocks[i];
895 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
896
897 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
898
899 for (Instruction &I : *ClonedBB)
900 RemapInstruction(&I, Result.Map,
901 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
902
903 // Exit blocks will now have one more predecessor and their PHI nodes need
904 // to be edited to reflect that. No phi nodes need to be introduced because
905 // the loop is in LCSSA.
906
907 for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB);
908 SBBI != SBBE; ++SBBI) {
909
910 if (OriginalLoop.contains(*SBBI))
911 continue; // not an exit block
912
913 for (Instruction &I : **SBBI) {
914 if (!isa<PHINode>(&I))
915 break;
916
917 PHINode *PN = cast<PHINode>(&I);
918 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
919 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
920 }
921 }
922 }
923}
924
925LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000926 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000927 BasicBlock *ContinuationBlock) const {
928
929 // We start with a loop with a single latch:
930 //
931 // +--------------------+
932 // | |
933 // | preheader |
934 // | |
935 // +--------+-----------+
936 // | ----------------\
937 // | / |
938 // +--------v----v------+ |
939 // | | |
940 // | header | |
941 // | | |
942 // +--------------------+ |
943 // |
944 // ..... |
945 // |
946 // +--------------------+ |
947 // | | |
948 // | latch >----------/
949 // | |
950 // +-------v------------+
951 // |
952 // |
953 // | +--------------------+
954 // | | |
955 // +---> original exit |
956 // | |
957 // +--------------------+
958 //
959 // We change the control flow to look like
960 //
961 //
962 // +--------------------+
963 // | |
964 // | preheader >-------------------------+
965 // | | |
966 // +--------v-----------+ |
967 // | /-------------+ |
968 // | / | |
969 // +--------v--v--------+ | |
970 // | | | |
971 // | header | | +--------+ |
972 // | | | | | |
973 // +--------------------+ | | +-----v-----v-----------+
974 // | | | |
975 // | | | .pseudo.exit |
976 // | | | |
977 // | | +-----------v-----------+
978 // | | |
979 // ..... | | |
980 // | | +--------v-------------+
981 // +--------------------+ | | | |
982 // | | | | | ContinuationBlock |
983 // | latch >------+ | | |
984 // | | | +----------------------+
985 // +---------v----------+ |
986 // | |
987 // | |
988 // | +---------------^-----+
989 // | | |
990 // +-----> .exit.selector |
991 // | |
992 // +----------v----------+
993 // |
994 // +--------------------+ |
995 // | | |
996 // | original exit <----+
997 // | |
998 // +--------------------+
999 //
1000
1001 RewrittenRangeInfo RRI;
1002
1003 auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
1004 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
1005 &F, BBInsertLocation);
1006 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
1007 BBInsertLocation);
1008
1009 BranchInst *PreheaderJump = cast<BranchInst>(&*Preheader->rbegin());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001010 bool Increasing = LS.IndVarIncreasing;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001011
1012 IRBuilder<> B(PreheaderJump);
1013
1014 // EnterLoopCond - is it okay to start executing this `LS'?
Sanjoy Dase75ed922015-02-26 08:19:31 +00001015 Value *EnterLoopCond = Increasing
1016 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1017 : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt);
1018
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001019 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1020 PreheaderJump->eraseFromParent();
1021
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001022 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001023 B.SetInsertPoint(LS.LatchBr);
1024 Value *TakeBackedgeLoopCond =
1025 Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1026 : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt);
1027 Value *CondForBranch = LS.LatchBrExitIdx == 1
1028 ? TakeBackedgeLoopCond
1029 : B.CreateNot(TakeBackedgeLoopCond);
1030
1031 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001032
1033 B.SetInsertPoint(RRI.ExitSelector);
1034
1035 // IterationsLeft - are there any more iterations left, given the original
1036 // upper bound on the induction variable? If not, we branch to the "real"
1037 // exit.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001038 Value *IterationsLeft = Increasing
1039 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1040 : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001041 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1042
1043 BranchInst *BranchToContinuation =
1044 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1045
1046 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1047 // each of the PHI nodes in the loop header. This feeds into the initial
1048 // value of the same PHI nodes if/when we continue execution.
1049 for (Instruction &I : *LS.Header) {
1050 if (!isa<PHINode>(&I))
1051 break;
1052
1053 PHINode *PN = cast<PHINode>(&I);
1054
1055 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1056 BranchToContinuation);
1057
1058 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1059 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1060 RRI.ExitSelector);
1061 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1062 }
1063
Sanjoy Dase75ed922015-02-26 08:19:31 +00001064 RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1065 BranchToContinuation);
1066 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1067 RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1068
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001069 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1070 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1071 for (Instruction &I : *LS.LatchExit) {
1072 if (PHINode *PN = dyn_cast<PHINode>(&I))
1073 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1074 else
1075 break;
1076 }
1077
1078 return RRI;
1079}
1080
1081void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001082 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001083 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1084
1085 unsigned PHIIndex = 0;
1086 for (Instruction &I : *LS.Header) {
1087 if (!isa<PHINode>(&I))
1088 break;
1089
1090 PHINode *PN = cast<PHINode>(&I);
1091
1092 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1093 if (PN->getIncomingBlock(i) == ContinuationBlock)
1094 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1095 }
1096
Sanjoy Dase75ed922015-02-26 08:19:31 +00001097 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001098}
1099
Sanjoy Dase75ed922015-02-26 08:19:31 +00001100BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1101 BasicBlock *OldPreheader,
1102 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001103
1104 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1105 BranchInst::Create(LS.Header, Preheader);
1106
1107 for (Instruction &I : *LS.Header) {
1108 if (!isa<PHINode>(&I))
1109 break;
1110
1111 PHINode *PN = cast<PHINode>(&I);
1112 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1113 replacePHIBlock(PN, OldPreheader, Preheader);
1114 }
1115
1116 return Preheader;
1117}
1118
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001119void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001120 Loop *ParentLoop = OriginalLoop.getParentLoop();
1121 if (!ParentLoop)
1122 return;
1123
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001124 for (BasicBlock *BB : BBs)
1125 ParentLoop->addBasicBlockToLoop(BB, OriginalLoopInfo);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001126}
1127
1128bool LoopConstrainer::run() {
1129 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001130 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1131 Preheader = OriginalLoop.getLoopPreheader();
1132 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1133 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001134
1135 OriginalPreheader = Preheader;
1136 MainLoopPreheader = Preheader;
1137
Sanjoy Dase75ed922015-02-26 08:19:31 +00001138 Optional<SubRanges> MaybeSR = calculateSubRanges();
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001139 if (!MaybeSR.hasValue()) {
1140 DEBUG(dbgs() << "irce: could not compute subranges\n");
1141 return false;
1142 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001143
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001144 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001145 bool Increasing = MainLoopStructure.IndVarIncreasing;
1146 IntegerType *IVTy =
1147 cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1148
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001149 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001150 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001151
1152 // It would have been better to make `PreLoop' and `PostLoop'
1153 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1154 // constructor.
1155 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001156 bool NeedsPreLoop =
1157 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1158 bool NeedsPostLoop =
1159 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1160
1161 Value *ExitPreLoopAt = nullptr;
1162 Value *ExitMainLoopAt = nullptr;
1163 const SCEVConstant *MinusOneS =
1164 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1165
1166 if (NeedsPreLoop) {
1167 const SCEV *ExitPreLoopAtSCEV = nullptr;
1168
1169 if (Increasing)
1170 ExitPreLoopAtSCEV = *SR.LowLimit;
1171 else {
1172 if (CanBeSMin(SE, *SR.HighLimit)) {
1173 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1174 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1175 << "\n");
1176 return false;
1177 }
1178 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1179 }
1180
1181 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1182 ExitPreLoopAt->setName("exit.preloop.at");
1183 }
1184
1185 if (NeedsPostLoop) {
1186 const SCEV *ExitMainLoopAtSCEV = nullptr;
1187
1188 if (Increasing)
1189 ExitMainLoopAtSCEV = *SR.HighLimit;
1190 else {
1191 if (CanBeSMin(SE, *SR.LowLimit)) {
1192 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1193 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1194 << "\n");
1195 return false;
1196 }
1197 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1198 }
1199
1200 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1201 ExitMainLoopAt->setName("exit.mainloop.at");
1202 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001203
1204 // We clone these ahead of time so that we don't have to deal with changing
1205 // and temporarily invalid IR as we transform the loops.
1206 if (NeedsPreLoop)
1207 cloneLoop(PreLoop, "preloop");
1208 if (NeedsPostLoop)
1209 cloneLoop(PostLoop, "postloop");
1210
1211 RewrittenRangeInfo PreLoopRRI;
1212
1213 if (NeedsPreLoop) {
1214 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1215 PreLoop.Structure.Header);
1216
1217 MainLoopPreheader =
1218 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001219 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1220 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001221 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1222 PreLoopRRI);
1223 }
1224
1225 BasicBlock *PostLoopPreheader = nullptr;
1226 RewrittenRangeInfo PostLoopRRI;
1227
1228 if (NeedsPostLoop) {
1229 PostLoopPreheader =
1230 createPreheader(PostLoop.Structure, Preheader, "postloop");
1231 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001232 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001233 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1234 PostLoopRRI);
1235 }
1236
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001237 BasicBlock *NewMainLoopPreheader =
1238 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1239 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1240 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1241 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001242
1243 // Some of the above may be nullptr, filter them out before passing to
1244 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001245 auto NewBlocksEnd =
1246 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001247
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001248 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1249 addToParentLoopIfNeeded(PreLoop.Blocks);
1250 addToParentLoopIfNeeded(PostLoop.Blocks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001251
1252 return true;
1253}
1254
Sanjoy Das95c476d2015-02-21 22:20:22 +00001255/// Computes and returns a range of values for the induction variable (IndVar)
1256/// in which the range check can be safely elided. If it cannot compute such a
1257/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001258Optional<InductiveRangeCheck::Range>
1259InductiveRangeCheck::computeSafeIterationSpace(ScalarEvolution &SE,
Sanjoy Das95c476d2015-02-21 22:20:22 +00001260 const SCEVAddRecExpr *IndVar,
1261 IRBuilder<> &) const {
1262 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1263 // variable, that may or may not exist as a real llvm::Value in the loop) and
1264 // this inductive range check is a range check on the "C + D * I" ("C" is
1265 // getOffset() and "D" is getScale()). We rewrite the value being range
1266 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1267 // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code
1268 // can be generalized as needed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001269 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001270 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001271 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001272 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1273 //
1274 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1275 // and subtractions are twos-complement wrapping and comparisons are signed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001276 //
1277 // Proof:
1278 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001279 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1280 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1281 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1282 // overflown.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001283 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001284 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1285 // Hence 0 <= (IndVar + M) < L
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001286
Sanjoy Das95c476d2015-02-21 22:20:22 +00001287 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1288 // 127, IndVar = 126 and L = -2 in an i8 world.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001289
Sanjoy Das95c476d2015-02-21 22:20:22 +00001290 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001291 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001292
Sanjoy Das95c476d2015-02-21 22:20:22 +00001293 const SCEV *A = IndVar->getStart();
1294 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1295 if (!B)
1296 return None;
1297
1298 const SCEV *C = getOffset();
1299 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1300 if (D != B)
1301 return None;
1302
1303 ConstantInt *ConstD = D->getValue();
1304 if (!(ConstD->isMinusOne() || ConstD->isOne()))
1305 return None;
1306
1307 const SCEV *M = SE.getMinusSCEV(C, A);
1308
1309 const SCEV *Begin = SE.getNegativeSCEV(M);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001310 const SCEV *UpperLimit = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001311
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001312 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1313 // We can potentially do much better here.
1314 if (Value *V = getLength()) {
1315 UpperLimit = SE.getSCEV(V);
1316 } else {
1317 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1318 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1319 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1320 }
1321
1322 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
Sanjoy Das351db052015-01-22 09:32:02 +00001323 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001324}
1325
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001326static Optional<InductiveRangeCheck::Range>
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001327IntersectRange(ScalarEvolution &SE,
1328 const Optional<InductiveRangeCheck::Range> &R1,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001329 const InductiveRangeCheck::Range &R2, IRBuilder<> &B) {
1330 if (!R1.hasValue())
1331 return R2;
1332 auto &R1Value = R1.getValue();
1333
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001334 // TODO: we could widen the smaller range and have this work; but for now we
1335 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001336 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001337 return None;
1338
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001339 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1340 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1341
1342 return InductiveRangeCheck::Range(NewBegin, NewEnd);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001343}
1344
1345bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
1346 if (L->getBlocks().size() >= LoopSizeCutoff) {
1347 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1348 return false;
1349 }
1350
1351 BasicBlock *Preheader = L->getLoopPreheader();
1352 if (!Preheader) {
1353 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1354 return false;
1355 }
1356
1357 LLVMContext &Context = Preheader->getContext();
1358 InductiveRangeCheck::AllocatorTy IRCAlloc;
1359 SmallVector<InductiveRangeCheck *, 16> RangeChecks;
1360 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
Sanjoy Dasdcf26512015-01-27 21:38:12 +00001361 BranchProbabilityInfo &BPI = getAnalysis<BranchProbabilityInfo>();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001362
1363 for (auto BBI : L->getBlocks())
1364 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
1365 if (InductiveRangeCheck *IRC =
Sanjoy Dasdcf26512015-01-27 21:38:12 +00001366 InductiveRangeCheck::create(IRCAlloc, TBI, L, SE, BPI))
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001367 RangeChecks.push_back(IRC);
1368
1369 if (RangeChecks.empty())
1370 return false;
1371
1372 DEBUG(dbgs() << "irce: looking at loop "; L->print(dbgs());
1373 dbgs() << "irce: loop has " << RangeChecks.size()
1374 << " inductive range checks: \n";
1375 for (InductiveRangeCheck *IRC : RangeChecks)
1376 IRC->print(dbgs());
1377 );
1378
Sanjoy Dase75ed922015-02-26 08:19:31 +00001379 const char *FailureReason = nullptr;
1380 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001381 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001382 if (!MaybeLoopStructure.hasValue()) {
1383 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1384 << "\n";);
1385 return false;
1386 }
1387 LoopStructure LS = MaybeLoopStructure.getValue();
1388 bool Increasing = LS.IndVarIncreasing;
1389 const SCEV *MinusOne =
1390 SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true);
1391 const SCEVAddRecExpr *IndVar =
1392 cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne));
1393
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001394 Optional<InductiveRangeCheck::Range> SafeIterRange;
1395 Instruction *ExprInsertPt = Preheader->getTerminator();
1396
1397 SmallVector<InductiveRangeCheck *, 4> RangeChecksToEliminate;
1398
1399 IRBuilder<> B(ExprInsertPt);
1400 for (InductiveRangeCheck *IRC : RangeChecks) {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001401 auto Result = IRC->computeSafeIterationSpace(SE, IndVar, B);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001402 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001403 auto MaybeSafeIterRange =
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001404 IntersectRange(SE, SafeIterRange, Result.getValue(), B);
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001405 if (MaybeSafeIterRange.hasValue()) {
1406 RangeChecksToEliminate.push_back(IRC);
1407 SafeIterRange = MaybeSafeIterRange.getValue();
1408 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001409 }
1410 }
1411
1412 if (!SafeIterRange.hasValue())
1413 return false;
1414
Sanjoy Dase75ed922015-02-26 08:19:31 +00001415 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LS,
1416 SE, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001417 bool Changed = LC.run();
1418
1419 if (Changed) {
1420 auto PrintConstrainedLoopInfo = [L]() {
1421 dbgs() << "irce: in function ";
1422 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1423 dbgs() << "constrained ";
1424 L->print(dbgs());
1425 };
1426
1427 DEBUG(PrintConstrainedLoopInfo());
1428
1429 if (PrintChangedLoops)
1430 PrintConstrainedLoopInfo();
1431
1432 // Optimize away the now-redundant range checks.
1433
1434 for (InductiveRangeCheck *IRC : RangeChecksToEliminate) {
1435 ConstantInt *FoldedRangeCheck = IRC->getPassingDirection()
1436 ? ConstantInt::getTrue(Context)
1437 : ConstantInt::getFalse(Context);
1438 IRC->getBranch()->setCondition(FoldedRangeCheck);
1439 }
1440 }
1441
1442 return Changed;
1443}
1444
1445Pass *llvm::createInductiveRangeCheckEliminationPass() {
1446 return new InductiveRangeCheckElimination;
1447}