blob: 984b4c404945eb1bb848f921a57e860bb5a88ef9 [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"
Sanjoy Dasdcf26512015-01-27 21:38:12 +000045#include "llvm/Analysis/BranchProbabilityInfo.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000046#include "llvm/Analysis/InstructionSimplify.h"
47#include "llvm/Analysis/LoopInfo.h"
48#include "llvm/Analysis/LoopPass.h"
49#include "llvm/Analysis/ScalarEvolution.h"
50#include "llvm/Analysis/ScalarEvolutionExpander.h"
51#include "llvm/Analysis/ScalarEvolutionExpressions.h"
52#include "llvm/Analysis/ValueTracking.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000053#include "llvm/IR/Dominators.h"
54#include "llvm/IR/Function.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000055#include "llvm/IR/IRBuilder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000056#include "llvm/IR/Instructions.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000057#include "llvm/IR/Module.h"
58#include "llvm/IR/PatternMatch.h"
59#include "llvm/IR/ValueHandle.h"
60#include "llvm/IR/Verifier.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000061#include "llvm/Pass.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000062#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000063#include "llvm/Support/raw_ostream.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000064#include "llvm/Transforms/Scalar.h"
65#include "llvm/Transforms/Utils/BasicBlockUtils.h"
66#include "llvm/Transforms/Utils/Cloning.h"
67#include "llvm/Transforms/Utils/LoopUtils.h"
68#include "llvm/Transforms/Utils/SimplifyIndVar.h"
69#include "llvm/Transforms/Utils/UnrollLoop.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000070
71using namespace llvm;
72
Benjamin Kramer970eac42015-02-06 17:51:54 +000073static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
74 cl::init(64));
Sanjoy Dasa1837a32015-01-16 01:03:22 +000075
Benjamin Kramer970eac42015-02-06 17:51:54 +000076static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
77 cl::init(false));
Sanjoy Dasa1837a32015-01-16 01:03:22 +000078
Sanjoy Das9c1bfae2015-03-17 01:40:22 +000079static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
80 cl::init(false));
81
Sanjoy Dase91665d2015-02-26 08:56:04 +000082static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
83 cl::Hidden, cl::init(10));
84
Sanjoy Dasa1837a32015-01-16 01:03:22 +000085#define DEBUG_TYPE "irce"
86
87namespace {
88
89/// An inductive range check is conditional branch in a loop with
90///
91/// 1. a very cold successor (i.e. the branch jumps to that successor very
92/// rarely)
93///
94/// and
95///
Sanjoy Dase2cde6f2015-03-17 00:42:13 +000096/// 2. a condition that is provably true for some contiguous range of values
97/// taken by the containing loop's induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +000098///
Sanjoy Dasa1837a32015-01-16 01:03:22 +000099class InductiveRangeCheck {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000100 // Classifies a range check
Reid Kleckner0b168592015-03-17 16:50:20 +0000101 enum RangeCheckKind : unsigned {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000102 // Range check of the form "0 <= I".
103 RANGE_CHECK_LOWER = 1,
104
105 // Range check of the form "I < L" where L is known positive.
106 RANGE_CHECK_UPPER = 2,
107
108 // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER
109 // conditions.
110 RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
111
112 // Unrecognized range check condition.
113 RANGE_CHECK_UNKNOWN = (unsigned)-1
114 };
115
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000116 static StringRef rangeCheckKindToStr(RangeCheckKind);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000117
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000118 const SCEV *Offset;
119 const SCEV *Scale;
120 Value *Length;
121 BranchInst *Branch;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000122 RangeCheckKind Kind;
123
Sanjoy Das337d46b2015-03-24 19:29:18 +0000124 static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
125 ScalarEvolution &SE, Value *&Index,
126 Value *&Length);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000127
128 static InductiveRangeCheck::RangeCheckKind
129 parseRangeCheck(Loop *L, ScalarEvolution &SE, Value *Condition,
130 const SCEV *&Index, Value *&UpperLimit);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000131
132 InductiveRangeCheck() :
133 Offset(nullptr), Scale(nullptr), Length(nullptr), Branch(nullptr) { }
134
135public:
136 const SCEV *getOffset() const { return Offset; }
137 const SCEV *getScale() const { return Scale; }
138 Value *getLength() const { return Length; }
139
140 void print(raw_ostream &OS) const {
141 OS << "InductiveRangeCheck:\n";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000142 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000143 OS << " Offset: ";
144 Offset->print(OS);
145 OS << " Scale: ";
146 Scale->print(OS);
147 OS << " Length: ";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000148 if (Length)
149 Length->print(OS);
150 else
151 OS << "(null)";
152 OS << "\n Branch: ";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000153 getBranch()->print(OS);
Sanjoy Das48c75812015-02-26 04:03:31 +0000154 OS << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000155 }
156
157#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
158 void dump() {
159 print(dbgs());
160 }
161#endif
162
163 BranchInst *getBranch() const { return Branch; }
164
Sanjoy Das351db052015-01-22 09:32:02 +0000165 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
166 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
167
168 class Range {
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000169 const SCEV *Begin;
170 const SCEV *End;
Sanjoy Das351db052015-01-22 09:32:02 +0000171
172 public:
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000173 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
Sanjoy Das351db052015-01-22 09:32:02 +0000174 assert(Begin->getType() == End->getType() && "ill-typed range!");
175 }
176
177 Type *getType() const { return Begin->getType(); }
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000178 const SCEV *getBegin() const { return Begin; }
179 const SCEV *getEnd() const { return End; }
Sanjoy Das351db052015-01-22 09:32:02 +0000180 };
181
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000182 typedef SpecificBumpPtrAllocator<InductiveRangeCheck> AllocatorTy;
183
184 /// This is the value the condition of the branch needs to evaluate to for the
185 /// branch to take the hot successor (see (1) above).
186 bool getPassingDirection() { return true; }
187
Sanjoy Das95c476d2015-02-21 22:20:22 +0000188 /// Computes a range for the induction variable (IndVar) in which the range
189 /// check is redundant and can be constant-folded away. The induction
190 /// variable is not required to be the canonical {0,+,1} induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000191 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
Sanjoy Das59776732016-05-21 02:31:51 +0000192 const SCEVAddRecExpr *IndVar) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000193
194 /// Create an inductive range check out of BI if possible, else return
195 /// nullptr.
196 static InductiveRangeCheck *create(AllocatorTy &Alloc, BranchInst *BI,
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000197 Loop *L, ScalarEvolution &SE,
198 BranchProbabilityInfo &BPI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000199};
200
201class InductiveRangeCheckElimination : public LoopPass {
202 InductiveRangeCheck::AllocatorTy Allocator;
203
204public:
205 static char ID;
206 InductiveRangeCheckElimination() : LoopPass(ID) {
207 initializeInductiveRangeCheckEliminationPass(
208 *PassRegistry::getPassRegistry());
209 }
210
211 void getAnalysisUsage(AnalysisUsage &AU) const override {
Cong Houab23bfb2015-07-15 22:48:29 +0000212 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000213 getLoopAnalysisUsage(AU);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000214 }
215
216 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
217};
218
219char InductiveRangeCheckElimination::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000220}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000221
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000222INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce",
223 "Inductive range check elimination", false, false)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000224INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000225INITIALIZE_PASS_DEPENDENCY(LoopPass)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000226INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce",
227 "Inductive range check elimination", false, false)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000228
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000229StringRef InductiveRangeCheck::rangeCheckKindToStr(
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000230 InductiveRangeCheck::RangeCheckKind RCK) {
231 switch (RCK) {
232 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
233 return "RANGE_CHECK_UNKNOWN";
234
235 case InductiveRangeCheck::RANGE_CHECK_UPPER:
236 return "RANGE_CHECK_UPPER";
237
238 case InductiveRangeCheck::RANGE_CHECK_LOWER:
239 return "RANGE_CHECK_LOWER";
240
241 case InductiveRangeCheck::RANGE_CHECK_BOTH:
242 return "RANGE_CHECK_BOTH";
243 }
244
245 llvm_unreachable("unknown range check type!");
246}
247
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000248/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000249/// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000250/// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000251/// range checked, and set `Length` to the upper limit `Index` is being range
252/// checked with if (and only if) the range check type is stronger or equal to
253/// RANGE_CHECK_UPPER.
254///
255InductiveRangeCheck::RangeCheckKind
Sanjoy Das337d46b2015-03-24 19:29:18 +0000256InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
257 ScalarEvolution &SE, Value *&Index,
258 Value *&Length) {
259
260 auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) {
261 const SCEV *S = SE.getSCEV(V);
262 if (isa<SCEVCouldNotCompute>(S))
263 return false;
264
265 return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant &&
266 SE.isKnownNonNegative(S);
267 };
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000268
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000269 using namespace llvm::PatternMatch;
270
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000271 ICmpInst::Predicate Pred = ICI->getPredicate();
272 Value *LHS = ICI->getOperand(0);
273 Value *RHS = ICI->getOperand(1);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000274
275 switch (Pred) {
276 default:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000277 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000278
279 case ICmpInst::ICMP_SLE:
280 std::swap(LHS, RHS);
281 // fallthrough
282 case ICmpInst::ICMP_SGE:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000283 if (match(RHS, m_ConstantInt<0>())) {
284 Index = LHS;
285 return RANGE_CHECK_LOWER;
286 }
287 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000288
289 case ICmpInst::ICMP_SLT:
290 std::swap(LHS, RHS);
291 // fallthrough
292 case ICmpInst::ICMP_SGT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000293 if (match(RHS, m_ConstantInt<-1>())) {
294 Index = LHS;
295 return RANGE_CHECK_LOWER;
296 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000297
Sanjoy Das337d46b2015-03-24 19:29:18 +0000298 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000299 Index = RHS;
300 Length = LHS;
301 return RANGE_CHECK_UPPER;
302 }
303 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000304
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000305 case ICmpInst::ICMP_ULT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000306 std::swap(LHS, RHS);
307 // fallthrough
308 case ICmpInst::ICMP_UGT:
Sanjoy Das337d46b2015-03-24 19:29:18 +0000309 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000310 Index = RHS;
311 Length = LHS;
312 return RANGE_CHECK_BOTH;
313 }
314 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000315 }
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000316
317 llvm_unreachable("default clause returns!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000318}
319
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000320/// Parses an arbitrary condition into a range check. `Length` is set only if
321/// the range check is recognized to be `RANGE_CHECK_UPPER` or stronger.
322InductiveRangeCheck::RangeCheckKind
323InductiveRangeCheck::parseRangeCheck(Loop *L, ScalarEvolution &SE,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000324 Value *Condition, const SCEV *&Index,
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000325 Value *&Length) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000326 using namespace llvm::PatternMatch;
327
328 Value *A = nullptr;
329 Value *B = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000330
331 if (match(Condition, m_And(m_Value(A), m_Value(B)))) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000332 Value *IndexA = nullptr, *IndexB = nullptr;
333 Value *LengthA = nullptr, *LengthB = nullptr;
334 ICmpInst *ICmpA = dyn_cast<ICmpInst>(A), *ICmpB = dyn_cast<ICmpInst>(B);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000335
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000336 if (!ICmpA || !ICmpB)
337 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000338
Sanjoy Das337d46b2015-03-24 19:29:18 +0000339 auto RCKindA = parseRangeCheckICmp(L, ICmpA, SE, IndexA, LengthA);
340 auto RCKindB = parseRangeCheckICmp(L, ICmpB, SE, IndexB, LengthB);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000341
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000342 if (RCKindA == InductiveRangeCheck::RANGE_CHECK_UNKNOWN ||
343 RCKindB == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
344 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000345
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000346 if (IndexA != IndexB)
347 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
348
349 if (LengthA != nullptr && LengthB != nullptr && LengthA != LengthB)
350 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
351
352 Index = SE.getSCEV(IndexA);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000353 if (isa<SCEVCouldNotCompute>(Index))
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000354 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000355
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000356 Length = LengthA == nullptr ? LengthB : LengthA;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000357
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000358 return (InductiveRangeCheck::RangeCheckKind)(RCKindA | RCKindB);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000359 }
360
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000361 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
362 Value *IndexVal = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000363
Sanjoy Das337d46b2015-03-24 19:29:18 +0000364 auto RCKind = parseRangeCheckICmp(L, ICI, SE, IndexVal, Length);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000365
366 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
367 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
368
369 Index = SE.getSCEV(IndexVal);
370 if (isa<SCEVCouldNotCompute>(Index))
371 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
372
373 return RCKind;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000374 }
375
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000376 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000377}
378
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000379
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000380InductiveRangeCheck *
381InductiveRangeCheck::create(InductiveRangeCheck::AllocatorTy &A, BranchInst *BI,
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000382 Loop *L, ScalarEvolution &SE,
383 BranchProbabilityInfo &BPI) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000384
385 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
386 return nullptr;
387
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000388 BranchProbability LikelyTaken(15, 16);
389
390 if (BPI.getEdgeProbability(BI->getParent(), (unsigned) 0) < LikelyTaken)
391 return nullptr;
392
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000393 Value *Length = nullptr;
394 const SCEV *IndexSCEV = nullptr;
395
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000396 auto RCKind = InductiveRangeCheck::parseRangeCheck(L, SE, BI->getCondition(),
397 IndexSCEV, Length);
398
399 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000400 return nullptr;
401
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000402 assert(IndexSCEV && "contract with SplitRangeCheckCondition!");
David Blaikiec4dfa632015-03-17 17:48:24 +0000403 assert((!(RCKind & InductiveRangeCheck::RANGE_CHECK_UPPER) || Length) &&
404 "contract with SplitRangeCheckCondition!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000405
406 const SCEVAddRecExpr *IndexAddRec = dyn_cast<SCEVAddRecExpr>(IndexSCEV);
407 bool IsAffineIndex =
408 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
409
410 if (!IsAffineIndex)
411 return nullptr;
412
413 InductiveRangeCheck *IRC = new (A.Allocate()) InductiveRangeCheck;
414 IRC->Length = Length;
415 IRC->Offset = IndexAddRec->getStart();
416 IRC->Scale = IndexAddRec->getStepRecurrence(SE);
417 IRC->Branch = BI;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000418 IRC->Kind = RCKind;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000419 return IRC;
420}
421
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000422namespace {
423
Sanjoy Dase75ed922015-02-26 08:19:31 +0000424// Keeps track of the structure of a loop. This is similar to llvm::Loop,
425// except that it is more lightweight and can track the state of a loop through
426// changing and potentially invalid IR. This structure also formalizes the
427// kinds of loops we can deal with -- ones that have a single latch that is also
428// an exiting block *and* have a canonical induction variable.
429struct LoopStructure {
430 const char *Tag;
431
432 BasicBlock *Header;
433 BasicBlock *Latch;
434
435 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
436 // successor is `LatchExit', the exit block of the loop.
437 BranchInst *LatchBr;
438 BasicBlock *LatchExit;
439 unsigned LatchBrExitIdx;
440
441 Value *IndVarNext;
442 Value *IndVarStart;
443 Value *LoopExitAt;
444 bool IndVarIncreasing;
445
446 LoopStructure()
447 : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr),
448 LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr),
449 IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false) {}
450
451 template <typename M> LoopStructure map(M Map) const {
452 LoopStructure Result;
453 Result.Tag = Tag;
454 Result.Header = cast<BasicBlock>(Map(Header));
455 Result.Latch = cast<BasicBlock>(Map(Latch));
456 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
457 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
458 Result.LatchBrExitIdx = LatchBrExitIdx;
459 Result.IndVarNext = Map(IndVarNext);
460 Result.IndVarStart = Map(IndVarStart);
461 Result.LoopExitAt = Map(LoopExitAt);
462 Result.IndVarIncreasing = IndVarIncreasing;
463 return Result;
464 }
465
Sanjoy Dase91665d2015-02-26 08:56:04 +0000466 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
467 BranchProbabilityInfo &BPI,
468 Loop &,
Sanjoy Dase75ed922015-02-26 08:19:31 +0000469 const char *&);
470};
471
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000472/// This class is used to constrain loops to run within a given iteration space.
473/// The algorithm this class implements is given a Loop and a range [Begin,
474/// End). The algorithm then tries to break out a "main loop" out of the loop
475/// it is given in a way that the "main loop" runs with the induction variable
476/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
477/// loops to run any remaining iterations. The pre loop runs any iterations in
478/// which the induction variable is < Begin, and the post loop runs any
479/// iterations in which the induction variable is >= End.
480///
481class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000482 // The representation of a clone of the original loop we started out with.
483 struct ClonedLoop {
484 // The cloned blocks
485 std::vector<BasicBlock *> Blocks;
486
487 // `Map` maps values in the clonee into values in the cloned version
488 ValueToValueMapTy Map;
489
490 // An instance of `LoopStructure` for the cloned loop
491 LoopStructure Structure;
492 };
493
494 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
495 // more details on what these fields mean.
496 struct RewrittenRangeInfo {
497 BasicBlock *PseudoExit;
498 BasicBlock *ExitSelector;
499 std::vector<PHINode *> PHIValuesAtPseudoExit;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000500 PHINode *IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000501
Sanjoy Dase75ed922015-02-26 08:19:31 +0000502 RewrittenRangeInfo()
503 : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000504 };
505
506 // Calculated subranges we restrict the iteration space of the main loop to.
507 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000508 // these fields are computed. `LowLimit` is None if there is no restriction
509 // on low end of the restricted iteration space of the main loop. `HighLimit`
510 // is None if there is no restriction on high end of the restricted iteration
511 // space of the main loop.
512
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000513 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000514 Optional<const SCEV *> LowLimit;
515 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000516 };
517
518 // A utility function that does a `replaceUsesOfWith' on the incoming block
519 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
520 // incoming block list with `ReplaceBy'.
521 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
522 BasicBlock *ReplaceBy);
523
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000524 // Compute a safe set of limits for the main loop to run in -- effectively the
525 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000526 // Return None if unable to compute the set of subranges.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000527 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000528 Optional<SubRanges> calculateSubRanges() const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000529
530 // Clone `OriginalLoop' and return the result in CLResult. The IR after
531 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
532 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
533 // but there is no such edge.
534 //
535 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
536
537 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
538 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
539 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
540 // `OriginalHeaderCount'.
541 //
542 // If there are iterations left to execute, control is made to jump to
543 // `ContinuationBlock', otherwise they take the normal loop exit. The
544 // returned `RewrittenRangeInfo' object is populated as follows:
545 //
546 // .PseudoExit is a basic block that unconditionally branches to
547 // `ContinuationBlock'.
548 //
549 // .ExitSelector is a basic block that decides, on exit from the loop,
550 // whether to branch to the "true" exit or to `PseudoExit'.
551 //
552 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
553 // for each PHINode in the loop header on taking the pseudo exit.
554 //
555 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
556 // preheader because it is made to branch to the loop header only
557 // conditionally.
558 //
559 RewrittenRangeInfo
560 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
561 Value *ExitLoopAt,
562 BasicBlock *ContinuationBlock) const;
563
564 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
565 // function creates a new preheader for `LS' and returns it.
566 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000567 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
568 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000569
570 // `ContinuationBlockAndPreheader' was the continuation block for some call to
571 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
572 // This function rewrites the PHI nodes in `LS.Header' to start with the
573 // correct value.
574 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000575 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000576 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
577
578 // Even though we do not preserve any passes at this time, we at least need to
579 // keep the parent loop structure consistent. The `LPPassManager' seems to
580 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000581 // blocks denoted by BBs to this loops parent loop if required.
582 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000583
584 // Some global state.
585 Function &F;
586 LLVMContext &Ctx;
587 ScalarEvolution &SE;
588
589 // Information about the original loop we started out with.
590 Loop &OriginalLoop;
591 LoopInfo &OriginalLoopInfo;
592 const SCEV *LatchTakenCount;
593 BasicBlock *OriginalPreheader;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000594
595 // The preheader of the main loop. This may or may not be different from
596 // `OriginalPreheader'.
597 BasicBlock *MainLoopPreheader;
598
599 // The range we need to run the main loop in.
600 InductiveRangeCheck::Range Range;
601
602 // The structure of the main loop (see comment at the beginning of this class
603 // for a definition)
604 LoopStructure MainLoopStructure;
605
606public:
Sanjoy Dase75ed922015-02-26 08:19:31 +0000607 LoopConstrainer(Loop &L, LoopInfo &LI, const LoopStructure &LS,
608 ScalarEvolution &SE, InductiveRangeCheck::Range R)
609 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
610 SE(SE), OriginalLoop(L), OriginalLoopInfo(LI), LatchTakenCount(nullptr),
611 OriginalPreheader(nullptr), MainLoopPreheader(nullptr), Range(R),
612 MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000613
614 // Entry point for the algorithm. Returns true on success.
615 bool run();
616};
617
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000618}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000619
620void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
621 BasicBlock *ReplaceBy) {
622 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
623 if (PN->getIncomingBlock(i) == Block)
624 PN->setIncomingBlock(i, ReplaceBy);
625}
626
Sanjoy Dase75ed922015-02-26 08:19:31 +0000627static bool CanBeSMax(ScalarEvolution &SE, const SCEV *S) {
628 APInt SMax =
629 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
630 return SE.getSignedRange(S).contains(SMax) &&
631 SE.getUnsignedRange(S).contains(SMax);
632}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000633
Sanjoy Dase75ed922015-02-26 08:19:31 +0000634static bool CanBeSMin(ScalarEvolution &SE, const SCEV *S) {
635 APInt SMin =
636 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth());
637 return SE.getSignedRange(S).contains(SMin) &&
638 SE.getUnsignedRange(S).contains(SMin);
639}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000640
Sanjoy Dase75ed922015-02-26 08:19:31 +0000641Optional<LoopStructure>
Sanjoy Dase91665d2015-02-26 08:56:04 +0000642LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI,
643 Loop &L, const char *&FailureReason) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000644 assert(L.isLoopSimplifyForm() && "should follow from addRequired<>");
645
646 BasicBlock *Latch = L.getLoopLatch();
647 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000648 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000649 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000650 }
651
Sanjoy Dase75ed922015-02-26 08:19:31 +0000652 BasicBlock *Header = L.getHeader();
653 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000654 if (!Preheader) {
655 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000656 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000657 }
658
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000659 BranchInst *LatchBr = dyn_cast<BranchInst>(&*Latch->rbegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000660 if (!LatchBr || LatchBr->isUnconditional()) {
661 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000662 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000663 }
664
Sanjoy Dase75ed922015-02-26 08:19:31 +0000665 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000666
Sanjoy Dase91665d2015-02-26 08:56:04 +0000667 BranchProbability ExitProbability =
668 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
669
670 if (ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
671 FailureReason = "short running loop, not profitable";
672 return None;
673 }
674
Sanjoy Dase75ed922015-02-26 08:19:31 +0000675 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
676 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
677 FailureReason = "latch terminator branch not conditional on integral icmp";
678 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000679 }
680
Sanjoy Dase75ed922015-02-26 08:19:31 +0000681 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
682 if (isa<SCEVCouldNotCompute>(LatchCount)) {
683 FailureReason = "could not compute latch count";
684 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000685 }
686
Sanjoy Dase75ed922015-02-26 08:19:31 +0000687 ICmpInst::Predicate Pred = ICI->getPredicate();
688 Value *LeftValue = ICI->getOperand(0);
689 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
690 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
691
692 Value *RightValue = ICI->getOperand(1);
693 const SCEV *RightSCEV = SE.getSCEV(RightValue);
694
695 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
696 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
697 if (isa<SCEVAddRecExpr>(RightSCEV)) {
698 std::swap(LeftSCEV, RightSCEV);
699 std::swap(LeftValue, RightValue);
700 Pred = ICmpInst::getSwappedPredicate(Pred);
701 } else {
702 FailureReason = "no add recurrences in the icmp";
703 return None;
704 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000705 }
706
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000707 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
708 if (AR->getNoWrapFlags(SCEV::FlagNSW))
709 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000710
711 IntegerType *Ty = cast<IntegerType>(AR->getType());
712 IntegerType *WideTy =
713 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
714
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000715 const SCEVAddRecExpr *ExtendAfterOp =
716 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
717 if (ExtendAfterOp) {
718 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
719 const SCEV *ExtendedStep =
720 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
721
722 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
723 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
724
725 if (NoSignedWrap)
726 return true;
727 }
728
729 // We may have proved this when computing the sign extension above.
730 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
731 };
732
733 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing) {
734 if (!AR->isAffine())
735 return false;
736
Sanjoy Dase75ed922015-02-26 08:19:31 +0000737 // Currently we only work with induction variables that have been proved to
738 // not wrap. This restriction can potentially be lifted in the future.
739
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000740 if (!HasNoSignedWrap(AR))
Sanjoy Dase75ed922015-02-26 08:19:31 +0000741 return false;
742
743 if (const SCEVConstant *StepExpr =
744 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
745 ConstantInt *StepCI = StepExpr->getValue();
746 if (StepCI->isOne() || StepCI->isMinusOne()) {
747 IsIncreasing = StepCI->isOne();
748 return true;
749 }
750 }
751
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000752 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000753 };
754
755 // `ICI` is interpreted as taking the backedge if the *next* value of the
756 // induction variable satisfies some constraint.
757
758 const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
759 bool IsIncreasing = false;
760 if (!IsInductionVar(IndVarNext, IsIncreasing)) {
761 FailureReason = "LHS in icmp not induction variable";
762 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000763 }
764
Sanjoy Dase75ed922015-02-26 08:19:31 +0000765 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
766 // TODO: generalize the predicates here to also match their unsigned variants.
767 if (IsIncreasing) {
768 bool FoundExpectedPred =
769 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) ||
770 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0);
771
772 if (!FoundExpectedPred) {
773 FailureReason = "expected icmp slt semantically, found something else";
774 return None;
775 }
776
777 if (LatchBrExitIdx == 0) {
778 if (CanBeSMax(SE, RightSCEV)) {
779 // TODO: this restriction is easily removable -- we just have to
780 // remember that the icmp was an slt and not an sle.
781 FailureReason = "limit may overflow when coercing sle to slt";
782 return None;
783 }
784
785 IRBuilder<> B(&*Preheader->rbegin());
786 RightValue = B.CreateAdd(RightValue, One);
787 }
788
789 } else {
790 bool FoundExpectedPred =
791 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) ||
792 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0);
793
794 if (!FoundExpectedPred) {
795 FailureReason = "expected icmp sgt semantically, found something else";
796 return None;
797 }
798
799 if (LatchBrExitIdx == 0) {
800 if (CanBeSMin(SE, RightSCEV)) {
801 // TODO: this restriction is easily removable -- we just have to
802 // remember that the icmp was an sgt and not an sge.
803 FailureReason = "limit may overflow when coercing sge to sgt";
804 return None;
805 }
806
807 IRBuilder<> B(&*Preheader->rbegin());
808 RightValue = B.CreateSub(RightValue, One);
809 }
810 }
811
812 const SCEV *StartNext = IndVarNext->getStart();
813 const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
814 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
815
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000816 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
817
Sanjoy Dase75ed922015-02-26 08:19:31 +0000818 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000819 ScalarEvolution::LoopInvariant &&
820 "loop variant exit count doesn't make sense!");
821
Sanjoy Dase75ed922015-02-26 08:19:31 +0000822 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000823 const DataLayout &DL = Preheader->getModule()->getDataLayout();
824 Value *IndVarStartV =
825 SCEVExpander(SE, DL, "irce")
826 .expandCodeFor(IndVarStart, IndVarTy, &*Preheader->rbegin());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000827 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000828
Sanjoy Dase75ed922015-02-26 08:19:31 +0000829 LoopStructure Result;
830
831 Result.Tag = "main";
832 Result.Header = Header;
833 Result.Latch = Latch;
834 Result.LatchBr = LatchBr;
835 Result.LatchExit = LatchExit;
836 Result.LatchBrExitIdx = LatchBrExitIdx;
837 Result.IndVarStart = IndVarStartV;
838 Result.IndVarNext = LeftValue;
839 Result.IndVarIncreasing = IsIncreasing;
840 Result.LoopExitAt = RightValue;
841
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000842 FailureReason = nullptr;
843
Sanjoy Dase75ed922015-02-26 08:19:31 +0000844 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000845}
846
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000847Optional<LoopConstrainer::SubRanges>
Sanjoy Dase75ed922015-02-26 08:19:31 +0000848LoopConstrainer::calculateSubRanges() const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000849 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
850
Sanjoy Das351db052015-01-22 09:32:02 +0000851 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000852 return None;
853
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000854 LoopConstrainer::SubRanges Result;
855
856 // I think we can be more aggressive here and make this nuw / nsw if the
857 // addition that feeds into the icmp for the latch's terminating branch is nuw
858 // / nsw. In any case, a wrapping 2's complement addition is safe.
859 ConstantInt *One = ConstantInt::get(Ty, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000860 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
861 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000862
Sanjoy Dase75ed922015-02-26 08:19:31 +0000863 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000864
Sanjoy Dase75ed922015-02-26 08:19:31 +0000865 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the
866 // range of values the induction variable takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000867
868 const SCEV *Smallest = nullptr, *Greatest = nullptr;
869
870 if (Increasing) {
871 Smallest = Start;
872 Greatest = End;
873 } else {
874 // These two computations may sign-overflow. Here is why that is okay:
875 //
876 // We know that the induction variable does not sign-overflow on any
877 // iteration except the last one, and it starts at `Start` and ends at
878 // `End`, decrementing by one every time.
879 //
880 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
881 // induction variable is decreasing we know that that the smallest value
882 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
883 //
884 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
885 // that case, `Clamp` will always return `Smallest` and
886 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
887 // will be an empty range. Returning an empty range is always safe.
888 //
889
890 Smallest = SE.getAddExpr(End, SE.getSCEV(One));
891 Greatest = SE.getAddExpr(Start, SE.getSCEV(One));
892 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000893
894 auto Clamp = [this, Smallest, Greatest](const SCEV *S) {
895 return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S));
896 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000897
898 // In some cases we can prove that we don't need a pre or post loop
899
900 bool ProvablyNoPreloop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000901 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest);
902 if (!ProvablyNoPreloop)
903 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000904
905 bool ProvablyNoPostLoop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000906 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd());
907 if (!ProvablyNoPostLoop)
908 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000909
910 return Result;
911}
912
913void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
914 const char *Tag) const {
915 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
916 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
917 Result.Blocks.push_back(Clone);
918 Result.Map[BB] = Clone;
919 }
920
921 auto GetClonedValue = [&Result](Value *V) {
922 assert(V && "null values not in domain!");
923 auto It = Result.Map.find(V);
924 if (It == Result.Map.end())
925 return V;
926 return static_cast<Value *>(It->second);
927 };
928
929 Result.Structure = MainLoopStructure.map(GetClonedValue);
930 Result.Structure.Tag = Tag;
931
932 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
933 BasicBlock *ClonedBB = Result.Blocks[i];
934 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
935
936 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
937
938 for (Instruction &I : *ClonedBB)
939 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000940 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000941
942 // Exit blocks will now have one more predecessor and their PHI nodes need
943 // to be edited to reflect that. No phi nodes need to be introduced because
944 // the loop is in LCSSA.
945
946 for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB);
947 SBBI != SBBE; ++SBBI) {
948
949 if (OriginalLoop.contains(*SBBI))
950 continue; // not an exit block
951
952 for (Instruction &I : **SBBI) {
953 if (!isa<PHINode>(&I))
954 break;
955
956 PHINode *PN = cast<PHINode>(&I);
957 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
958 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
959 }
960 }
961 }
962}
963
964LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000965 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000966 BasicBlock *ContinuationBlock) const {
967
968 // We start with a loop with a single latch:
969 //
970 // +--------------------+
971 // | |
972 // | preheader |
973 // | |
974 // +--------+-----------+
975 // | ----------------\
976 // | / |
977 // +--------v----v------+ |
978 // | | |
979 // | header | |
980 // | | |
981 // +--------------------+ |
982 // |
983 // ..... |
984 // |
985 // +--------------------+ |
986 // | | |
987 // | latch >----------/
988 // | |
989 // +-------v------------+
990 // |
991 // |
992 // | +--------------------+
993 // | | |
994 // +---> original exit |
995 // | |
996 // +--------------------+
997 //
998 // We change the control flow to look like
999 //
1000 //
1001 // +--------------------+
1002 // | |
1003 // | preheader >-------------------------+
1004 // | | |
1005 // +--------v-----------+ |
1006 // | /-------------+ |
1007 // | / | |
1008 // +--------v--v--------+ | |
1009 // | | | |
1010 // | header | | +--------+ |
1011 // | | | | | |
1012 // +--------------------+ | | +-----v-----v-----------+
1013 // | | | |
1014 // | | | .pseudo.exit |
1015 // | | | |
1016 // | | +-----------v-----------+
1017 // | | |
1018 // ..... | | |
1019 // | | +--------v-------------+
1020 // +--------------------+ | | | |
1021 // | | | | | ContinuationBlock |
1022 // | latch >------+ | | |
1023 // | | | +----------------------+
1024 // +---------v----------+ |
1025 // | |
1026 // | |
1027 // | +---------------^-----+
1028 // | | |
1029 // +-----> .exit.selector |
1030 // | |
1031 // +----------v----------+
1032 // |
1033 // +--------------------+ |
1034 // | | |
1035 // | original exit <----+
1036 // | |
1037 // +--------------------+
1038 //
1039
1040 RewrittenRangeInfo RRI;
1041
1042 auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
1043 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001044 &F, &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001045 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001046 &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001047
1048 BranchInst *PreheaderJump = cast<BranchInst>(&*Preheader->rbegin());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001049 bool Increasing = LS.IndVarIncreasing;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001050
1051 IRBuilder<> B(PreheaderJump);
1052
1053 // EnterLoopCond - is it okay to start executing this `LS'?
Sanjoy Dase75ed922015-02-26 08:19:31 +00001054 Value *EnterLoopCond = Increasing
1055 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1056 : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt);
1057
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001058 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1059 PreheaderJump->eraseFromParent();
1060
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001061 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001062 B.SetInsertPoint(LS.LatchBr);
1063 Value *TakeBackedgeLoopCond =
1064 Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1065 : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt);
1066 Value *CondForBranch = LS.LatchBrExitIdx == 1
1067 ? TakeBackedgeLoopCond
1068 : B.CreateNot(TakeBackedgeLoopCond);
1069
1070 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001071
1072 B.SetInsertPoint(RRI.ExitSelector);
1073
1074 // IterationsLeft - are there any more iterations left, given the original
1075 // upper bound on the induction variable? If not, we branch to the "real"
1076 // exit.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001077 Value *IterationsLeft = Increasing
1078 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1079 : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001080 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1081
1082 BranchInst *BranchToContinuation =
1083 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1084
1085 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1086 // each of the PHI nodes in the loop header. This feeds into the initial
1087 // value of the same PHI nodes if/when we continue execution.
1088 for (Instruction &I : *LS.Header) {
1089 if (!isa<PHINode>(&I))
1090 break;
1091
1092 PHINode *PN = cast<PHINode>(&I);
1093
1094 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1095 BranchToContinuation);
1096
1097 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1098 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1099 RRI.ExitSelector);
1100 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1101 }
1102
Sanjoy Dase75ed922015-02-26 08:19:31 +00001103 RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1104 BranchToContinuation);
1105 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1106 RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1107
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001108 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1109 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1110 for (Instruction &I : *LS.LatchExit) {
1111 if (PHINode *PN = dyn_cast<PHINode>(&I))
1112 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1113 else
1114 break;
1115 }
1116
1117 return RRI;
1118}
1119
1120void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001121 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001122 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1123
1124 unsigned PHIIndex = 0;
1125 for (Instruction &I : *LS.Header) {
1126 if (!isa<PHINode>(&I))
1127 break;
1128
1129 PHINode *PN = cast<PHINode>(&I);
1130
1131 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1132 if (PN->getIncomingBlock(i) == ContinuationBlock)
1133 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1134 }
1135
Sanjoy Dase75ed922015-02-26 08:19:31 +00001136 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001137}
1138
Sanjoy Dase75ed922015-02-26 08:19:31 +00001139BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1140 BasicBlock *OldPreheader,
1141 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001142
1143 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1144 BranchInst::Create(LS.Header, Preheader);
1145
1146 for (Instruction &I : *LS.Header) {
1147 if (!isa<PHINode>(&I))
1148 break;
1149
1150 PHINode *PN = cast<PHINode>(&I);
1151 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1152 replacePHIBlock(PN, OldPreheader, Preheader);
1153 }
1154
1155 return Preheader;
1156}
1157
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001158void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001159 Loop *ParentLoop = OriginalLoop.getParentLoop();
1160 if (!ParentLoop)
1161 return;
1162
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001163 for (BasicBlock *BB : BBs)
1164 ParentLoop->addBasicBlockToLoop(BB, OriginalLoopInfo);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001165}
1166
1167bool LoopConstrainer::run() {
1168 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001169 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1170 Preheader = OriginalLoop.getLoopPreheader();
1171 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1172 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001173
1174 OriginalPreheader = Preheader;
1175 MainLoopPreheader = Preheader;
1176
Sanjoy Dase75ed922015-02-26 08:19:31 +00001177 Optional<SubRanges> MaybeSR = calculateSubRanges();
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001178 if (!MaybeSR.hasValue()) {
1179 DEBUG(dbgs() << "irce: could not compute subranges\n");
1180 return false;
1181 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001182
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001183 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001184 bool Increasing = MainLoopStructure.IndVarIncreasing;
1185 IntegerType *IVTy =
1186 cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1187
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001188 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001189 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001190
1191 // It would have been better to make `PreLoop' and `PostLoop'
1192 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1193 // constructor.
1194 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001195 bool NeedsPreLoop =
1196 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1197 bool NeedsPostLoop =
1198 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1199
1200 Value *ExitPreLoopAt = nullptr;
1201 Value *ExitMainLoopAt = nullptr;
1202 const SCEVConstant *MinusOneS =
1203 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1204
1205 if (NeedsPreLoop) {
1206 const SCEV *ExitPreLoopAtSCEV = nullptr;
1207
1208 if (Increasing)
1209 ExitPreLoopAtSCEV = *SR.LowLimit;
1210 else {
1211 if (CanBeSMin(SE, *SR.HighLimit)) {
1212 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1213 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1214 << "\n");
1215 return false;
1216 }
1217 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1218 }
1219
1220 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1221 ExitPreLoopAt->setName("exit.preloop.at");
1222 }
1223
1224 if (NeedsPostLoop) {
1225 const SCEV *ExitMainLoopAtSCEV = nullptr;
1226
1227 if (Increasing)
1228 ExitMainLoopAtSCEV = *SR.HighLimit;
1229 else {
1230 if (CanBeSMin(SE, *SR.LowLimit)) {
1231 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1232 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1233 << "\n");
1234 return false;
1235 }
1236 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1237 }
1238
1239 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1240 ExitMainLoopAt->setName("exit.mainloop.at");
1241 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001242
1243 // We clone these ahead of time so that we don't have to deal with changing
1244 // and temporarily invalid IR as we transform the loops.
1245 if (NeedsPreLoop)
1246 cloneLoop(PreLoop, "preloop");
1247 if (NeedsPostLoop)
1248 cloneLoop(PostLoop, "postloop");
1249
1250 RewrittenRangeInfo PreLoopRRI;
1251
1252 if (NeedsPreLoop) {
1253 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1254 PreLoop.Structure.Header);
1255
1256 MainLoopPreheader =
1257 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001258 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1259 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001260 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1261 PreLoopRRI);
1262 }
1263
1264 BasicBlock *PostLoopPreheader = nullptr;
1265 RewrittenRangeInfo PostLoopRRI;
1266
1267 if (NeedsPostLoop) {
1268 PostLoopPreheader =
1269 createPreheader(PostLoop.Structure, Preheader, "postloop");
1270 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001271 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001272 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1273 PostLoopRRI);
1274 }
1275
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001276 BasicBlock *NewMainLoopPreheader =
1277 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1278 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1279 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1280 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001281
1282 // Some of the above may be nullptr, filter them out before passing to
1283 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001284 auto NewBlocksEnd =
1285 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001286
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001287 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1288 addToParentLoopIfNeeded(PreLoop.Blocks);
1289 addToParentLoopIfNeeded(PostLoop.Blocks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001290
1291 return true;
1292}
1293
Sanjoy Das95c476d2015-02-21 22:20:22 +00001294/// Computes and returns a range of values for the induction variable (IndVar)
1295/// in which the range check can be safely elided. If it cannot compute such a
1296/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001297Optional<InductiveRangeCheck::Range>
Sanjoy Das59776732016-05-21 02:31:51 +00001298InductiveRangeCheck::computeSafeIterationSpace(
1299 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001300 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1301 // variable, that may or may not exist as a real llvm::Value in the loop) and
1302 // this inductive range check is a range check on the "C + D * I" ("C" is
1303 // getOffset() and "D" is getScale()). We rewrite the value being range
1304 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1305 // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code
1306 // can be generalized as needed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001307 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001308 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001309 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001310 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1311 //
1312 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1313 // and subtractions are twos-complement wrapping and comparisons are signed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001314 //
1315 // Proof:
1316 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001317 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1318 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1319 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1320 // overflown.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001321 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001322 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1323 // Hence 0 <= (IndVar + M) < L
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001324
Sanjoy Das95c476d2015-02-21 22:20:22 +00001325 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1326 // 127, IndVar = 126 and L = -2 in an i8 world.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001327
Sanjoy Das95c476d2015-02-21 22:20:22 +00001328 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001329 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001330
Sanjoy Das95c476d2015-02-21 22:20:22 +00001331 const SCEV *A = IndVar->getStart();
1332 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1333 if (!B)
1334 return None;
1335
1336 const SCEV *C = getOffset();
1337 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1338 if (D != B)
1339 return None;
1340
1341 ConstantInt *ConstD = D->getValue();
1342 if (!(ConstD->isMinusOne() || ConstD->isOne()))
1343 return None;
1344
1345 const SCEV *M = SE.getMinusSCEV(C, A);
1346
1347 const SCEV *Begin = SE.getNegativeSCEV(M);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001348 const SCEV *UpperLimit = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001349
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001350 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1351 // We can potentially do much better here.
1352 if (Value *V = getLength()) {
1353 UpperLimit = SE.getSCEV(V);
1354 } else {
1355 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1356 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1357 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1358 }
1359
1360 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
Sanjoy Das351db052015-01-22 09:32:02 +00001361 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001362}
1363
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001364static Optional<InductiveRangeCheck::Range>
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001365IntersectRange(ScalarEvolution &SE,
1366 const Optional<InductiveRangeCheck::Range> &R1,
Sanjoy Das59776732016-05-21 02:31:51 +00001367 const InductiveRangeCheck::Range &R2) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001368 if (!R1.hasValue())
1369 return R2;
1370 auto &R1Value = R1.getValue();
1371
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001372 // TODO: we could widen the smaller range and have this work; but for now we
1373 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001374 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001375 return None;
1376
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001377 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1378 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1379
1380 return InductiveRangeCheck::Range(NewBegin, NewEnd);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001381}
1382
1383bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001384 if (skipLoop(L))
1385 return false;
1386
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001387 if (L->getBlocks().size() >= LoopSizeCutoff) {
1388 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1389 return false;
1390 }
1391
1392 BasicBlock *Preheader = L->getLoopPreheader();
1393 if (!Preheader) {
1394 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1395 return false;
1396 }
1397
1398 LLVMContext &Context = Preheader->getContext();
1399 InductiveRangeCheck::AllocatorTy IRCAlloc;
1400 SmallVector<InductiveRangeCheck *, 16> RangeChecks;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001401 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Cong Houab23bfb2015-07-15 22:48:29 +00001402 BranchProbabilityInfo &BPI =
1403 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001404
1405 for (auto BBI : L->getBlocks())
1406 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
1407 if (InductiveRangeCheck *IRC =
Sanjoy Dasdcf26512015-01-27 21:38:12 +00001408 InductiveRangeCheck::create(IRCAlloc, TBI, L, SE, BPI))
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001409 RangeChecks.push_back(IRC);
1410
1411 if (RangeChecks.empty())
1412 return false;
1413
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001414 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1415 OS << "irce: looking at loop "; L->print(OS);
1416 OS << "irce: loop has " << RangeChecks.size()
1417 << " inductive range checks: \n";
1418 for (InductiveRangeCheck *IRC : RangeChecks)
1419 IRC->print(OS);
1420 };
1421
1422 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1423
1424 if (PrintRangeChecks)
1425 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001426
Sanjoy Dase75ed922015-02-26 08:19:31 +00001427 const char *FailureReason = nullptr;
1428 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001429 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001430 if (!MaybeLoopStructure.hasValue()) {
1431 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1432 << "\n";);
1433 return false;
1434 }
1435 LoopStructure LS = MaybeLoopStructure.getValue();
1436 bool Increasing = LS.IndVarIncreasing;
1437 const SCEV *MinusOne =
1438 SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true);
1439 const SCEVAddRecExpr *IndVar =
1440 cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne));
1441
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001442 Optional<InductiveRangeCheck::Range> SafeIterRange;
1443 Instruction *ExprInsertPt = Preheader->getTerminator();
1444
1445 SmallVector<InductiveRangeCheck *, 4> RangeChecksToEliminate;
1446
1447 IRBuilder<> B(ExprInsertPt);
1448 for (InductiveRangeCheck *IRC : RangeChecks) {
Sanjoy Das59776732016-05-21 02:31:51 +00001449 auto Result = IRC->computeSafeIterationSpace(SE, IndVar);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001450 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001451 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001452 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001453 if (MaybeSafeIterRange.hasValue()) {
1454 RangeChecksToEliminate.push_back(IRC);
1455 SafeIterRange = MaybeSafeIterRange.getValue();
1456 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001457 }
1458 }
1459
1460 if (!SafeIterRange.hasValue())
1461 return false;
1462
Sanjoy Dase75ed922015-02-26 08:19:31 +00001463 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LS,
1464 SE, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001465 bool Changed = LC.run();
1466
1467 if (Changed) {
1468 auto PrintConstrainedLoopInfo = [L]() {
1469 dbgs() << "irce: in function ";
1470 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1471 dbgs() << "constrained ";
1472 L->print(dbgs());
1473 };
1474
1475 DEBUG(PrintConstrainedLoopInfo());
1476
1477 if (PrintChangedLoops)
1478 PrintConstrainedLoopInfo();
1479
1480 // Optimize away the now-redundant range checks.
1481
1482 for (InductiveRangeCheck *IRC : RangeChecksToEliminate) {
1483 ConstantInt *FoldedRangeCheck = IRC->getPassingDirection()
1484 ? ConstantInt::getTrue(Context)
1485 : ConstantInt::getFalse(Context);
1486 IRC->getBranch()->setCondition(FoldedRangeCheck);
1487 }
1488 }
1489
1490 return Changed;
1491}
1492
1493Pass *llvm::createInductiveRangeCheckEliminationPass() {
1494 return new InductiveRangeCheckElimination;
1495}