blob: 2b9f3f59c8e40079a438b3624fd5c5e7c39189f4 [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;
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000121 Use *CheckUse;
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
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000132 InductiveRangeCheck()
133 : Offset(nullptr), Scale(nullptr), Length(nullptr),
134 CheckUse(nullptr) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000135
136public:
137 const SCEV *getOffset() const { return Offset; }
138 const SCEV *getScale() const { return Scale; }
139 Value *getLength() const { return Length; }
140
141 void print(raw_ostream &OS) const {
142 OS << "InductiveRangeCheck:\n";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000143 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000144 OS << " Offset: ";
145 Offset->print(OS);
146 OS << " Scale: ";
147 Scale->print(OS);
148 OS << " Length: ";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000149 if (Length)
150 Length->print(OS);
151 else
152 OS << "(null)";
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000153 OS << "\n CheckUse: ";
154 getCheckUse()->getUser()->print(OS);
155 OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000156 }
157
158#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
159 void dump() {
160 print(dbgs());
161 }
162#endif
163
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000164 Use *getCheckUse() const { return CheckUse; }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000165
Sanjoy Das351db052015-01-22 09:32:02 +0000166 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
167 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
168
169 class Range {
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000170 const SCEV *Begin;
171 const SCEV *End;
Sanjoy Das351db052015-01-22 09:32:02 +0000172
173 public:
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000174 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
Sanjoy Das351db052015-01-22 09:32:02 +0000175 assert(Begin->getType() == End->getType() && "ill-typed range!");
176 }
177
178 Type *getType() const { return Begin->getType(); }
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000179 const SCEV *getBegin() const { return Begin; }
180 const SCEV *getEnd() const { return End; }
Sanjoy Das351db052015-01-22 09:32:02 +0000181 };
182
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000183 /// This is the value the condition of the branch needs to evaluate to for the
184 /// branch to take the hot successor (see (1) above).
185 bool getPassingDirection() { return true; }
186
Sanjoy Das95c476d2015-02-21 22:20:22 +0000187 /// Computes a range for the induction variable (IndVar) in which the range
188 /// check is redundant and can be constant-folded away. The induction
189 /// variable is not required to be the canonical {0,+,1} induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000190 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
Sanjoy Das59776732016-05-21 02:31:51 +0000191 const SCEVAddRecExpr *IndVar) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000192
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000193 /// Create an inductive range check out of BI if possible, else return None.
194 static Optional<InductiveRangeCheck> create(BranchInst *BI, Loop *L,
195 ScalarEvolution &SE,
196 BranchProbabilityInfo &BPI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000197};
198
199class InductiveRangeCheckElimination : public LoopPass {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000200public:
201 static char ID;
202 InductiveRangeCheckElimination() : LoopPass(ID) {
203 initializeInductiveRangeCheckEliminationPass(
204 *PassRegistry::getPassRegistry());
205 }
206
207 void getAnalysisUsage(AnalysisUsage &AU) const override {
Cong Houab23bfb2015-07-15 22:48:29 +0000208 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000209 getLoopAnalysisUsage(AU);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000210 }
211
212 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
213};
214
215char InductiveRangeCheckElimination::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000216}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000217
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000218INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce",
219 "Inductive range check elimination", false, false)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000220INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000221INITIALIZE_PASS_DEPENDENCY(LoopPass)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000222INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce",
223 "Inductive range check elimination", false, false)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000224
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000225StringRef InductiveRangeCheck::rangeCheckKindToStr(
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000226 InductiveRangeCheck::RangeCheckKind RCK) {
227 switch (RCK) {
228 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
229 return "RANGE_CHECK_UNKNOWN";
230
231 case InductiveRangeCheck::RANGE_CHECK_UPPER:
232 return "RANGE_CHECK_UPPER";
233
234 case InductiveRangeCheck::RANGE_CHECK_LOWER:
235 return "RANGE_CHECK_LOWER";
236
237 case InductiveRangeCheck::RANGE_CHECK_BOTH:
238 return "RANGE_CHECK_BOTH";
239 }
240
241 llvm_unreachable("unknown range check type!");
242}
243
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000244/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000245/// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000246/// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000247/// range checked, and set `Length` to the upper limit `Index` is being range
248/// checked with if (and only if) the range check type is stronger or equal to
249/// RANGE_CHECK_UPPER.
250///
251InductiveRangeCheck::RangeCheckKind
Sanjoy Das337d46b2015-03-24 19:29:18 +0000252InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
253 ScalarEvolution &SE, Value *&Index,
254 Value *&Length) {
255
256 auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) {
257 const SCEV *S = SE.getSCEV(V);
258 if (isa<SCEVCouldNotCompute>(S))
259 return false;
260
261 return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant &&
262 SE.isKnownNonNegative(S);
263 };
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000264
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000265 using namespace llvm::PatternMatch;
266
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000267 ICmpInst::Predicate Pred = ICI->getPredicate();
268 Value *LHS = ICI->getOperand(0);
269 Value *RHS = ICI->getOperand(1);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000270
271 switch (Pred) {
272 default:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000273 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000274
275 case ICmpInst::ICMP_SLE:
276 std::swap(LHS, RHS);
277 // fallthrough
278 case ICmpInst::ICMP_SGE:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000279 if (match(RHS, m_ConstantInt<0>())) {
280 Index = LHS;
281 return RANGE_CHECK_LOWER;
282 }
283 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000284
285 case ICmpInst::ICMP_SLT:
286 std::swap(LHS, RHS);
287 // fallthrough
288 case ICmpInst::ICMP_SGT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000289 if (match(RHS, m_ConstantInt<-1>())) {
290 Index = LHS;
291 return RANGE_CHECK_LOWER;
292 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000293
Sanjoy Das337d46b2015-03-24 19:29:18 +0000294 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000295 Index = RHS;
296 Length = LHS;
297 return RANGE_CHECK_UPPER;
298 }
299 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000300
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000301 case ICmpInst::ICMP_ULT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000302 std::swap(LHS, RHS);
303 // fallthrough
304 case ICmpInst::ICMP_UGT:
Sanjoy Das337d46b2015-03-24 19:29:18 +0000305 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000306 Index = RHS;
307 Length = LHS;
308 return RANGE_CHECK_BOTH;
309 }
310 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000311 }
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000312
313 llvm_unreachable("default clause returns!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000314}
315
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000316/// Parses an arbitrary condition into a range check. `Length` is set only if
317/// the range check is recognized to be `RANGE_CHECK_UPPER` or stronger.
318InductiveRangeCheck::RangeCheckKind
319InductiveRangeCheck::parseRangeCheck(Loop *L, ScalarEvolution &SE,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000320 Value *Condition, const SCEV *&Index,
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000321 Value *&Length) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000322 using namespace llvm::PatternMatch;
323
324 Value *A = nullptr;
325 Value *B = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000326
327 if (match(Condition, m_And(m_Value(A), m_Value(B)))) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000328 Value *IndexA = nullptr, *IndexB = nullptr;
329 Value *LengthA = nullptr, *LengthB = nullptr;
330 ICmpInst *ICmpA = dyn_cast<ICmpInst>(A), *ICmpB = dyn_cast<ICmpInst>(B);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000331
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000332 if (!ICmpA || !ICmpB)
333 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000334
Sanjoy Das337d46b2015-03-24 19:29:18 +0000335 auto RCKindA = parseRangeCheckICmp(L, ICmpA, SE, IndexA, LengthA);
336 auto RCKindB = parseRangeCheckICmp(L, ICmpB, SE, IndexB, LengthB);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000337
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000338 if (RCKindA == InductiveRangeCheck::RANGE_CHECK_UNKNOWN ||
339 RCKindB == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
340 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000341
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000342 if (IndexA != IndexB)
343 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
344
345 if (LengthA != nullptr && LengthB != nullptr && LengthA != LengthB)
346 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
347
348 Index = SE.getSCEV(IndexA);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000349 if (isa<SCEVCouldNotCompute>(Index))
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000350 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000351
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000352 Length = LengthA == nullptr ? LengthB : LengthA;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000353
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000354 return (InductiveRangeCheck::RangeCheckKind)(RCKindA | RCKindB);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000355 }
356
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000357 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
358 Value *IndexVal = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000359
Sanjoy Das337d46b2015-03-24 19:29:18 +0000360 auto RCKind = parseRangeCheckICmp(L, ICI, SE, IndexVal, Length);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000361
362 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
363 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
364
365 Index = SE.getSCEV(IndexVal);
366 if (isa<SCEVCouldNotCompute>(Index))
367 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
368
369 return RCKind;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000370 }
371
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000372 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000373}
374
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000375Optional<InductiveRangeCheck>
376InductiveRangeCheck::create(BranchInst *BI, Loop *L, ScalarEvolution &SE,
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000377 BranchProbabilityInfo &BPI) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000378
379 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000380 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000381
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000382 BranchProbability LikelyTaken(15, 16);
383
384 if (BPI.getEdgeProbability(BI->getParent(), (unsigned) 0) < LikelyTaken)
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000385 return None;
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000386
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 Dasc5b11692016-05-21 02:52:13 +0000394 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000395
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000396 assert(IndexSCEV && "contract with SplitRangeCheckCondition!");
David Blaikiec4dfa632015-03-17 17:48:24 +0000397 assert((!(RCKind & InductiveRangeCheck::RANGE_CHECK_UPPER) || Length) &&
398 "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)
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000405 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000406
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000407 InductiveRangeCheck IRC;
408 IRC.Length = Length;
409 IRC.Offset = IndexAddRec->getStart();
410 IRC.Scale = IndexAddRec->getStepRecurrence(SE);
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000411 IRC.CheckUse = &BI->getOperandUse(0);
Sanjoy Dasc5b11692016-05-21 02:52: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
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000612}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000613
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 Das45dc94a2015-03-24 19:29:22 +0000701 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
702 if (AR->getNoWrapFlags(SCEV::FlagNSW))
703 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000704
705 IntegerType *Ty = cast<IntegerType>(AR->getType());
706 IntegerType *WideTy =
707 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
708
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000709 const SCEVAddRecExpr *ExtendAfterOp =
710 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
711 if (ExtendAfterOp) {
712 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
713 const SCEV *ExtendedStep =
714 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
715
716 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
717 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
718
719 if (NoSignedWrap)
720 return true;
721 }
722
723 // We may have proved this when computing the sign extension above.
724 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
725 };
726
727 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing) {
728 if (!AR->isAffine())
729 return false;
730
Sanjoy Dase75ed922015-02-26 08:19:31 +0000731 // Currently we only work with induction variables that have been proved to
732 // not wrap. This restriction can potentially be lifted in the future.
733
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000734 if (!HasNoSignedWrap(AR))
Sanjoy Dase75ed922015-02-26 08:19:31 +0000735 return false;
736
737 if (const SCEVConstant *StepExpr =
738 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
739 ConstantInt *StepCI = StepExpr->getValue();
740 if (StepCI->isOne() || StepCI->isMinusOne()) {
741 IsIncreasing = StepCI->isOne();
742 return true;
743 }
744 }
745
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000746 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000747 };
748
749 // `ICI` is interpreted as taking the backedge if the *next* value of the
750 // induction variable satisfies some constraint.
751
752 const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
753 bool IsIncreasing = false;
754 if (!IsInductionVar(IndVarNext, IsIncreasing)) {
755 FailureReason = "LHS in icmp not induction variable";
756 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000757 }
758
Sanjoy Dase75ed922015-02-26 08:19:31 +0000759 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
760 // TODO: generalize the predicates here to also match their unsigned variants.
761 if (IsIncreasing) {
762 bool FoundExpectedPred =
763 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) ||
764 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0);
765
766 if (!FoundExpectedPred) {
767 FailureReason = "expected icmp slt semantically, found something else";
768 return None;
769 }
770
771 if (LatchBrExitIdx == 0) {
772 if (CanBeSMax(SE, RightSCEV)) {
773 // TODO: this restriction is easily removable -- we just have to
774 // remember that the icmp was an slt and not an sle.
775 FailureReason = "limit may overflow when coercing sle to slt";
776 return None;
777 }
778
779 IRBuilder<> B(&*Preheader->rbegin());
780 RightValue = B.CreateAdd(RightValue, One);
781 }
782
783 } else {
784 bool FoundExpectedPred =
785 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) ||
786 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0);
787
788 if (!FoundExpectedPred) {
789 FailureReason = "expected icmp sgt semantically, found something else";
790 return None;
791 }
792
793 if (LatchBrExitIdx == 0) {
794 if (CanBeSMin(SE, RightSCEV)) {
795 // TODO: this restriction is easily removable -- we just have to
796 // remember that the icmp was an sgt and not an sge.
797 FailureReason = "limit may overflow when coercing sge to sgt";
798 return None;
799 }
800
801 IRBuilder<> B(&*Preheader->rbegin());
802 RightValue = B.CreateSub(RightValue, One);
803 }
804 }
805
806 const SCEV *StartNext = IndVarNext->getStart();
807 const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
808 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
809
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000810 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
811
Sanjoy Dase75ed922015-02-26 08:19:31 +0000812 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000813 ScalarEvolution::LoopInvariant &&
814 "loop variant exit count doesn't make sense!");
815
Sanjoy Dase75ed922015-02-26 08:19:31 +0000816 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000817 const DataLayout &DL = Preheader->getModule()->getDataLayout();
818 Value *IndVarStartV =
819 SCEVExpander(SE, DL, "irce")
820 .expandCodeFor(IndVarStart, IndVarTy, &*Preheader->rbegin());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000821 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000822
Sanjoy Dase75ed922015-02-26 08:19:31 +0000823 LoopStructure Result;
824
825 Result.Tag = "main";
826 Result.Header = Header;
827 Result.Latch = Latch;
828 Result.LatchBr = LatchBr;
829 Result.LatchExit = LatchExit;
830 Result.LatchBrExitIdx = LatchBrExitIdx;
831 Result.IndVarStart = IndVarStartV;
832 Result.IndVarNext = LeftValue;
833 Result.IndVarIncreasing = IsIncreasing;
834 Result.LoopExitAt = RightValue;
835
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000836 FailureReason = nullptr;
837
Sanjoy Dase75ed922015-02-26 08:19:31 +0000838 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000839}
840
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000841Optional<LoopConstrainer::SubRanges>
Sanjoy Dase75ed922015-02-26 08:19:31 +0000842LoopConstrainer::calculateSubRanges() const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000843 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
844
Sanjoy Das351db052015-01-22 09:32:02 +0000845 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000846 return None;
847
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000848 LoopConstrainer::SubRanges Result;
849
850 // I think we can be more aggressive here and make this nuw / nsw if the
851 // addition that feeds into the icmp for the latch's terminating branch is nuw
852 // / nsw. In any case, a wrapping 2's complement addition is safe.
853 ConstantInt *One = ConstantInt::get(Ty, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000854 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
855 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000856
Sanjoy Dase75ed922015-02-26 08:19:31 +0000857 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000858
Sanjoy Dase75ed922015-02-26 08:19:31 +0000859 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the
860 // range of values the induction variable takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000861
862 const SCEV *Smallest = nullptr, *Greatest = nullptr;
863
864 if (Increasing) {
865 Smallest = Start;
866 Greatest = End;
867 } else {
868 // These two computations may sign-overflow. Here is why that is okay:
869 //
870 // We know that the induction variable does not sign-overflow on any
871 // iteration except the last one, and it starts at `Start` and ends at
872 // `End`, decrementing by one every time.
873 //
874 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
875 // induction variable is decreasing we know that that the smallest value
876 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
877 //
878 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
879 // that case, `Clamp` will always return `Smallest` and
880 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
881 // will be an empty range. Returning an empty range is always safe.
882 //
883
884 Smallest = SE.getAddExpr(End, SE.getSCEV(One));
885 Greatest = SE.getAddExpr(Start, SE.getSCEV(One));
886 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000887
888 auto Clamp = [this, Smallest, Greatest](const SCEV *S) {
889 return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S));
890 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000891
892 // In some cases we can prove that we don't need a pre or post loop
893
894 bool ProvablyNoPreloop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000895 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest);
896 if (!ProvablyNoPreloop)
897 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000898
899 bool ProvablyNoPostLoop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000900 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd());
901 if (!ProvablyNoPostLoop)
902 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000903
904 return Result;
905}
906
907void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
908 const char *Tag) const {
909 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
910 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
911 Result.Blocks.push_back(Clone);
912 Result.Map[BB] = Clone;
913 }
914
915 auto GetClonedValue = [&Result](Value *V) {
916 assert(V && "null values not in domain!");
917 auto It = Result.Map.find(V);
918 if (It == Result.Map.end())
919 return V;
920 return static_cast<Value *>(It->second);
921 };
922
923 Result.Structure = MainLoopStructure.map(GetClonedValue);
924 Result.Structure.Tag = Tag;
925
926 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
927 BasicBlock *ClonedBB = Result.Blocks[i];
928 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
929
930 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
931
932 for (Instruction &I : *ClonedBB)
933 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000934 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000935
936 // Exit blocks will now have one more predecessor and their PHI nodes need
937 // to be edited to reflect that. No phi nodes need to be introduced because
938 // the loop is in LCSSA.
939
940 for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB);
941 SBBI != SBBE; ++SBBI) {
942
943 if (OriginalLoop.contains(*SBBI))
944 continue; // not an exit block
945
946 for (Instruction &I : **SBBI) {
947 if (!isa<PHINode>(&I))
948 break;
949
950 PHINode *PN = cast<PHINode>(&I);
951 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
952 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
953 }
954 }
955 }
956}
957
958LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000959 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000960 BasicBlock *ContinuationBlock) const {
961
962 // We start with a loop with a single latch:
963 //
964 // +--------------------+
965 // | |
966 // | preheader |
967 // | |
968 // +--------+-----------+
969 // | ----------------\
970 // | / |
971 // +--------v----v------+ |
972 // | | |
973 // | header | |
974 // | | |
975 // +--------------------+ |
976 // |
977 // ..... |
978 // |
979 // +--------------------+ |
980 // | | |
981 // | latch >----------/
982 // | |
983 // +-------v------------+
984 // |
985 // |
986 // | +--------------------+
987 // | | |
988 // +---> original exit |
989 // | |
990 // +--------------------+
991 //
992 // We change the control flow to look like
993 //
994 //
995 // +--------------------+
996 // | |
997 // | preheader >-------------------------+
998 // | | |
999 // +--------v-----------+ |
1000 // | /-------------+ |
1001 // | / | |
1002 // +--------v--v--------+ | |
1003 // | | | |
1004 // | header | | +--------+ |
1005 // | | | | | |
1006 // +--------------------+ | | +-----v-----v-----------+
1007 // | | | |
1008 // | | | .pseudo.exit |
1009 // | | | |
1010 // | | +-----------v-----------+
1011 // | | |
1012 // ..... | | |
1013 // | | +--------v-------------+
1014 // +--------------------+ | | | |
1015 // | | | | | ContinuationBlock |
1016 // | latch >------+ | | |
1017 // | | | +----------------------+
1018 // +---------v----------+ |
1019 // | |
1020 // | |
1021 // | +---------------^-----+
1022 // | | |
1023 // +-----> .exit.selector |
1024 // | |
1025 // +----------v----------+
1026 // |
1027 // +--------------------+ |
1028 // | | |
1029 // | original exit <----+
1030 // | |
1031 // +--------------------+
1032 //
1033
1034 RewrittenRangeInfo RRI;
1035
1036 auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
1037 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001038 &F, &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001039 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001040 &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001041
1042 BranchInst *PreheaderJump = cast<BranchInst>(&*Preheader->rbegin());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001043 bool Increasing = LS.IndVarIncreasing;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001044
1045 IRBuilder<> B(PreheaderJump);
1046
1047 // EnterLoopCond - is it okay to start executing this `LS'?
Sanjoy Dase75ed922015-02-26 08:19:31 +00001048 Value *EnterLoopCond = Increasing
1049 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1050 : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt);
1051
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001052 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1053 PreheaderJump->eraseFromParent();
1054
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001055 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001056 B.SetInsertPoint(LS.LatchBr);
1057 Value *TakeBackedgeLoopCond =
1058 Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1059 : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt);
1060 Value *CondForBranch = LS.LatchBrExitIdx == 1
1061 ? TakeBackedgeLoopCond
1062 : B.CreateNot(TakeBackedgeLoopCond);
1063
1064 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001065
1066 B.SetInsertPoint(RRI.ExitSelector);
1067
1068 // IterationsLeft - are there any more iterations left, given the original
1069 // upper bound on the induction variable? If not, we branch to the "real"
1070 // exit.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001071 Value *IterationsLeft = Increasing
1072 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1073 : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001074 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1075
1076 BranchInst *BranchToContinuation =
1077 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1078
1079 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1080 // each of the PHI nodes in the loop header. This feeds into the initial
1081 // value of the same PHI nodes if/when we continue execution.
1082 for (Instruction &I : *LS.Header) {
1083 if (!isa<PHINode>(&I))
1084 break;
1085
1086 PHINode *PN = cast<PHINode>(&I);
1087
1088 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1089 BranchToContinuation);
1090
1091 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1092 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1093 RRI.ExitSelector);
1094 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1095 }
1096
Sanjoy Dase75ed922015-02-26 08:19:31 +00001097 RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1098 BranchToContinuation);
1099 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1100 RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1101
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001102 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1103 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1104 for (Instruction &I : *LS.LatchExit) {
1105 if (PHINode *PN = dyn_cast<PHINode>(&I))
1106 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1107 else
1108 break;
1109 }
1110
1111 return RRI;
1112}
1113
1114void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001115 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001116 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1117
1118 unsigned PHIIndex = 0;
1119 for (Instruction &I : *LS.Header) {
1120 if (!isa<PHINode>(&I))
1121 break;
1122
1123 PHINode *PN = cast<PHINode>(&I);
1124
1125 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1126 if (PN->getIncomingBlock(i) == ContinuationBlock)
1127 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1128 }
1129
Sanjoy Dase75ed922015-02-26 08:19:31 +00001130 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001131}
1132
Sanjoy Dase75ed922015-02-26 08:19:31 +00001133BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1134 BasicBlock *OldPreheader,
1135 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001136
1137 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1138 BranchInst::Create(LS.Header, Preheader);
1139
1140 for (Instruction &I : *LS.Header) {
1141 if (!isa<PHINode>(&I))
1142 break;
1143
1144 PHINode *PN = cast<PHINode>(&I);
1145 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1146 replacePHIBlock(PN, OldPreheader, Preheader);
1147 }
1148
1149 return Preheader;
1150}
1151
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001152void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001153 Loop *ParentLoop = OriginalLoop.getParentLoop();
1154 if (!ParentLoop)
1155 return;
1156
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001157 for (BasicBlock *BB : BBs)
1158 ParentLoop->addBasicBlockToLoop(BB, OriginalLoopInfo);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001159}
1160
1161bool LoopConstrainer::run() {
1162 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001163 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1164 Preheader = OriginalLoop.getLoopPreheader();
1165 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1166 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001167
1168 OriginalPreheader = Preheader;
1169 MainLoopPreheader = Preheader;
1170
Sanjoy Dase75ed922015-02-26 08:19:31 +00001171 Optional<SubRanges> MaybeSR = calculateSubRanges();
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001172 if (!MaybeSR.hasValue()) {
1173 DEBUG(dbgs() << "irce: could not compute subranges\n");
1174 return false;
1175 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001176
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001177 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001178 bool Increasing = MainLoopStructure.IndVarIncreasing;
1179 IntegerType *IVTy =
1180 cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1181
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001182 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001183 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001184
1185 // It would have been better to make `PreLoop' and `PostLoop'
1186 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1187 // constructor.
1188 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001189 bool NeedsPreLoop =
1190 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1191 bool NeedsPostLoop =
1192 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1193
1194 Value *ExitPreLoopAt = nullptr;
1195 Value *ExitMainLoopAt = nullptr;
1196 const SCEVConstant *MinusOneS =
1197 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1198
1199 if (NeedsPreLoop) {
1200 const SCEV *ExitPreLoopAtSCEV = nullptr;
1201
1202 if (Increasing)
1203 ExitPreLoopAtSCEV = *SR.LowLimit;
1204 else {
1205 if (CanBeSMin(SE, *SR.HighLimit)) {
1206 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1207 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1208 << "\n");
1209 return false;
1210 }
1211 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1212 }
1213
1214 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1215 ExitPreLoopAt->setName("exit.preloop.at");
1216 }
1217
1218 if (NeedsPostLoop) {
1219 const SCEV *ExitMainLoopAtSCEV = nullptr;
1220
1221 if (Increasing)
1222 ExitMainLoopAtSCEV = *SR.HighLimit;
1223 else {
1224 if (CanBeSMin(SE, *SR.LowLimit)) {
1225 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1226 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1227 << "\n");
1228 return false;
1229 }
1230 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1231 }
1232
1233 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1234 ExitMainLoopAt->setName("exit.mainloop.at");
1235 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001236
1237 // We clone these ahead of time so that we don't have to deal with changing
1238 // and temporarily invalid IR as we transform the loops.
1239 if (NeedsPreLoop)
1240 cloneLoop(PreLoop, "preloop");
1241 if (NeedsPostLoop)
1242 cloneLoop(PostLoop, "postloop");
1243
1244 RewrittenRangeInfo PreLoopRRI;
1245
1246 if (NeedsPreLoop) {
1247 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1248 PreLoop.Structure.Header);
1249
1250 MainLoopPreheader =
1251 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001252 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1253 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001254 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1255 PreLoopRRI);
1256 }
1257
1258 BasicBlock *PostLoopPreheader = nullptr;
1259 RewrittenRangeInfo PostLoopRRI;
1260
1261 if (NeedsPostLoop) {
1262 PostLoopPreheader =
1263 createPreheader(PostLoop.Structure, Preheader, "postloop");
1264 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001265 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001266 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1267 PostLoopRRI);
1268 }
1269
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001270 BasicBlock *NewMainLoopPreheader =
1271 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1272 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1273 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1274 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001275
1276 // Some of the above may be nullptr, filter them out before passing to
1277 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001278 auto NewBlocksEnd =
1279 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001280
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001281 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1282 addToParentLoopIfNeeded(PreLoop.Blocks);
1283 addToParentLoopIfNeeded(PostLoop.Blocks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001284
1285 return true;
1286}
1287
Sanjoy Das95c476d2015-02-21 22:20:22 +00001288/// Computes and returns a range of values for the induction variable (IndVar)
1289/// in which the range check can be safely elided. If it cannot compute such a
1290/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001291Optional<InductiveRangeCheck::Range>
Sanjoy Das59776732016-05-21 02:31:51 +00001292InductiveRangeCheck::computeSafeIterationSpace(
1293 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001294 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1295 // variable, that may or may not exist as a real llvm::Value in the loop) and
1296 // this inductive range check is a range check on the "C + D * I" ("C" is
1297 // getOffset() and "D" is getScale()). We rewrite the value being range
1298 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1299 // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code
1300 // can be generalized as needed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001301 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001302 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001303 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001304 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1305 //
1306 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1307 // and subtractions are twos-complement wrapping and comparisons are signed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001308 //
1309 // Proof:
1310 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001311 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1312 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1313 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1314 // overflown.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001315 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001316 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1317 // Hence 0 <= (IndVar + M) < L
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001318
Sanjoy Das95c476d2015-02-21 22:20:22 +00001319 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1320 // 127, IndVar = 126 and L = -2 in an i8 world.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001321
Sanjoy Das95c476d2015-02-21 22:20:22 +00001322 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001323 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001324
Sanjoy Das95c476d2015-02-21 22:20:22 +00001325 const SCEV *A = IndVar->getStart();
1326 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1327 if (!B)
1328 return None;
1329
1330 const SCEV *C = getOffset();
1331 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1332 if (D != B)
1333 return None;
1334
1335 ConstantInt *ConstD = D->getValue();
1336 if (!(ConstD->isMinusOne() || ConstD->isOne()))
1337 return None;
1338
1339 const SCEV *M = SE.getMinusSCEV(C, A);
1340
1341 const SCEV *Begin = SE.getNegativeSCEV(M);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001342 const SCEV *UpperLimit = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001343
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001344 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1345 // We can potentially do much better here.
1346 if (Value *V = getLength()) {
1347 UpperLimit = SE.getSCEV(V);
1348 } else {
1349 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1350 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1351 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1352 }
1353
1354 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
Sanjoy Das351db052015-01-22 09:32:02 +00001355 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001356}
1357
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001358static Optional<InductiveRangeCheck::Range>
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001359IntersectRange(ScalarEvolution &SE,
1360 const Optional<InductiveRangeCheck::Range> &R1,
Sanjoy Das59776732016-05-21 02:31:51 +00001361 const InductiveRangeCheck::Range &R2) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001362 if (!R1.hasValue())
1363 return R2;
1364 auto &R1Value = R1.getValue();
1365
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001366 // TODO: we could widen the smaller range and have this work; but for now we
1367 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001368 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001369 return None;
1370
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001371 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1372 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1373
1374 return InductiveRangeCheck::Range(NewBegin, NewEnd);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001375}
1376
1377bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001378 if (skipLoop(L))
1379 return false;
1380
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001381 if (L->getBlocks().size() >= LoopSizeCutoff) {
1382 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1383 return false;
1384 }
1385
1386 BasicBlock *Preheader = L->getLoopPreheader();
1387 if (!Preheader) {
1388 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1389 return false;
1390 }
1391
1392 LLVMContext &Context = Preheader->getContext();
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001393 SmallVector<InductiveRangeCheck, 16> RangeChecks;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001394 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Cong Houab23bfb2015-07-15 22:48:29 +00001395 BranchProbabilityInfo &BPI =
1396 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001397
1398 for (auto BBI : L->getBlocks())
1399 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001400 if (auto MaybeIRC = InductiveRangeCheck::create(TBI, L, SE, BPI))
1401 RangeChecks.push_back(*MaybeIRC);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001402
1403 if (RangeChecks.empty())
1404 return false;
1405
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001406 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1407 OS << "irce: looking at loop "; L->print(OS);
1408 OS << "irce: loop has " << RangeChecks.size()
1409 << " inductive range checks: \n";
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001410 for (InductiveRangeCheck &IRC : RangeChecks)
1411 IRC.print(OS);
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001412 };
1413
1414 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1415
1416 if (PrintRangeChecks)
1417 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001418
Sanjoy Dase75ed922015-02-26 08:19:31 +00001419 const char *FailureReason = nullptr;
1420 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001421 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001422 if (!MaybeLoopStructure.hasValue()) {
1423 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1424 << "\n";);
1425 return false;
1426 }
1427 LoopStructure LS = MaybeLoopStructure.getValue();
1428 bool Increasing = LS.IndVarIncreasing;
1429 const SCEV *MinusOne =
1430 SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true);
1431 const SCEVAddRecExpr *IndVar =
1432 cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne));
1433
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001434 Optional<InductiveRangeCheck::Range> SafeIterRange;
1435 Instruction *ExprInsertPt = Preheader->getTerminator();
1436
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001437 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001438
1439 IRBuilder<> B(ExprInsertPt);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001440 for (InductiveRangeCheck &IRC : RangeChecks) {
1441 auto Result = IRC.computeSafeIterationSpace(SE, IndVar);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001442 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001443 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001444 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001445 if (MaybeSafeIterRange.hasValue()) {
1446 RangeChecksToEliminate.push_back(IRC);
1447 SafeIterRange = MaybeSafeIterRange.getValue();
1448 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001449 }
1450 }
1451
1452 if (!SafeIterRange.hasValue())
1453 return false;
1454
Sanjoy Dase75ed922015-02-26 08:19:31 +00001455 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LS,
1456 SE, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001457 bool Changed = LC.run();
1458
1459 if (Changed) {
1460 auto PrintConstrainedLoopInfo = [L]() {
1461 dbgs() << "irce: in function ";
1462 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1463 dbgs() << "constrained ";
1464 L->print(dbgs());
1465 };
1466
1467 DEBUG(PrintConstrainedLoopInfo());
1468
1469 if (PrintChangedLoops)
1470 PrintConstrainedLoopInfo();
1471
1472 // Optimize away the now-redundant range checks.
1473
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001474 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1475 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001476 ? ConstantInt::getTrue(Context)
1477 : ConstantInt::getFalse(Context);
Sanjoy Dasaa83c472016-05-23 22:16:45 +00001478 IRC.getCheckUse()->set(FoldedRangeCheck);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001479 }
1480 }
1481
1482 return Changed;
1483}
1484
1485Pass *llvm::createInductiveRangeCheckEliminationPass() {
1486 return new InductiveRangeCheckElimination;
1487}