blob: 1b5cf89b4d9bf78e8cec55f54500bb25d78f32ea [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,
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000130 Value *&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 Das5fd7ac42016-05-24 17:19:56 +0000320 Value *Condition, Value *&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
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000348 Index = IndexA;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000349 Length = LengthA == nullptr ? LengthB : LengthA;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000350
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000351 return (InductiveRangeCheck::RangeCheckKind)(RCKindA | RCKindB);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000352 }
353
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000354 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition))
355 return parseRangeCheckICmp(L, ICI, SE, Index, Length);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000356
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000357 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000358}
359
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000360Optional<InductiveRangeCheck>
361InductiveRangeCheck::create(BranchInst *BI, Loop *L, ScalarEvolution &SE,
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000362 BranchProbabilityInfo &BPI) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000363
364 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000365 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000366
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000367 BranchProbability LikelyTaken(15, 16);
368
369 if (BPI.getEdgeProbability(BI->getParent(), (unsigned) 0) < LikelyTaken)
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000370 return None;
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000371
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000372 Value *Length = nullptr, *Index = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000373
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000374 auto RCKind = InductiveRangeCheck::parseRangeCheck(L, SE, BI->getCondition(),
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000375 Index, Length);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000376
377 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000378 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000379
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000380 assert(Index && "contract with parseRangeCheck!");
David Blaikiec4dfa632015-03-17 17:48:24 +0000381 assert((!(RCKind & InductiveRangeCheck::RANGE_CHECK_UPPER) || Length) &&
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000382 "contract with parseRangeCheck!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000383
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000384 const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000385 bool IsAffineIndex =
386 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
387
388 if (!IsAffineIndex)
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000389 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000390
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000391 InductiveRangeCheck IRC;
392 IRC.Length = Length;
393 IRC.Offset = IndexAddRec->getStart();
394 IRC.Scale = IndexAddRec->getStepRecurrence(SE);
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000395 IRC.CheckUse = &BI->getOperandUse(0);
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000396 IRC.Kind = RCKind;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000397 return IRC;
398}
399
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000400namespace {
401
Sanjoy Dase75ed922015-02-26 08:19:31 +0000402// Keeps track of the structure of a loop. This is similar to llvm::Loop,
403// except that it is more lightweight and can track the state of a loop through
404// changing and potentially invalid IR. This structure also formalizes the
405// kinds of loops we can deal with -- ones that have a single latch that is also
406// an exiting block *and* have a canonical induction variable.
407struct LoopStructure {
408 const char *Tag;
409
410 BasicBlock *Header;
411 BasicBlock *Latch;
412
413 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
414 // successor is `LatchExit', the exit block of the loop.
415 BranchInst *LatchBr;
416 BasicBlock *LatchExit;
417 unsigned LatchBrExitIdx;
418
419 Value *IndVarNext;
420 Value *IndVarStart;
421 Value *LoopExitAt;
422 bool IndVarIncreasing;
423
424 LoopStructure()
425 : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr),
426 LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr),
427 IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false) {}
428
429 template <typename M> LoopStructure map(M Map) const {
430 LoopStructure Result;
431 Result.Tag = Tag;
432 Result.Header = cast<BasicBlock>(Map(Header));
433 Result.Latch = cast<BasicBlock>(Map(Latch));
434 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
435 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
436 Result.LatchBrExitIdx = LatchBrExitIdx;
437 Result.IndVarNext = Map(IndVarNext);
438 Result.IndVarStart = Map(IndVarStart);
439 Result.LoopExitAt = Map(LoopExitAt);
440 Result.IndVarIncreasing = IndVarIncreasing;
441 return Result;
442 }
443
Sanjoy Dase91665d2015-02-26 08:56:04 +0000444 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
445 BranchProbabilityInfo &BPI,
446 Loop &,
Sanjoy Dase75ed922015-02-26 08:19:31 +0000447 const char *&);
448};
449
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000450/// This class is used to constrain loops to run within a given iteration space.
451/// The algorithm this class implements is given a Loop and a range [Begin,
452/// End). The algorithm then tries to break out a "main loop" out of the loop
453/// it is given in a way that the "main loop" runs with the induction variable
454/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
455/// loops to run any remaining iterations. The pre loop runs any iterations in
456/// which the induction variable is < Begin, and the post loop runs any
457/// iterations in which the induction variable is >= End.
458///
459class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000460 // The representation of a clone of the original loop we started out with.
461 struct ClonedLoop {
462 // The cloned blocks
463 std::vector<BasicBlock *> Blocks;
464
465 // `Map` maps values in the clonee into values in the cloned version
466 ValueToValueMapTy Map;
467
468 // An instance of `LoopStructure` for the cloned loop
469 LoopStructure Structure;
470 };
471
472 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
473 // more details on what these fields mean.
474 struct RewrittenRangeInfo {
475 BasicBlock *PseudoExit;
476 BasicBlock *ExitSelector;
477 std::vector<PHINode *> PHIValuesAtPseudoExit;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000478 PHINode *IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000479
Sanjoy Dase75ed922015-02-26 08:19:31 +0000480 RewrittenRangeInfo()
481 : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000482 };
483
484 // Calculated subranges we restrict the iteration space of the main loop to.
485 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000486 // these fields are computed. `LowLimit` is None if there is no restriction
487 // on low end of the restricted iteration space of the main loop. `HighLimit`
488 // is None if there is no restriction on high end of the restricted iteration
489 // space of the main loop.
490
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000491 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000492 Optional<const SCEV *> LowLimit;
493 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000494 };
495
496 // A utility function that does a `replaceUsesOfWith' on the incoming block
497 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
498 // incoming block list with `ReplaceBy'.
499 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
500 BasicBlock *ReplaceBy);
501
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000502 // Compute a safe set of limits for the main loop to run in -- effectively the
503 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000504 // Return None if unable to compute the set of subranges.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000505 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000506 Optional<SubRanges> calculateSubRanges() const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000507
508 // Clone `OriginalLoop' and return the result in CLResult. The IR after
509 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
510 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
511 // but there is no such edge.
512 //
513 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
514
515 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
516 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
517 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
518 // `OriginalHeaderCount'.
519 //
520 // If there are iterations left to execute, control is made to jump to
521 // `ContinuationBlock', otherwise they take the normal loop exit. The
522 // returned `RewrittenRangeInfo' object is populated as follows:
523 //
524 // .PseudoExit is a basic block that unconditionally branches to
525 // `ContinuationBlock'.
526 //
527 // .ExitSelector is a basic block that decides, on exit from the loop,
528 // whether to branch to the "true" exit or to `PseudoExit'.
529 //
530 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
531 // for each PHINode in the loop header on taking the pseudo exit.
532 //
533 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
534 // preheader because it is made to branch to the loop header only
535 // conditionally.
536 //
537 RewrittenRangeInfo
538 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
539 Value *ExitLoopAt,
540 BasicBlock *ContinuationBlock) const;
541
542 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
543 // function creates a new preheader for `LS' and returns it.
544 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000545 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
546 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000547
548 // `ContinuationBlockAndPreheader' was the continuation block for some call to
549 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
550 // This function rewrites the PHI nodes in `LS.Header' to start with the
551 // correct value.
552 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000553 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000554 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
555
556 // Even though we do not preserve any passes at this time, we at least need to
557 // keep the parent loop structure consistent. The `LPPassManager' seems to
558 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000559 // blocks denoted by BBs to this loops parent loop if required.
560 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000561
562 // Some global state.
563 Function &F;
564 LLVMContext &Ctx;
565 ScalarEvolution &SE;
566
567 // Information about the original loop we started out with.
568 Loop &OriginalLoop;
569 LoopInfo &OriginalLoopInfo;
570 const SCEV *LatchTakenCount;
571 BasicBlock *OriginalPreheader;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000572
573 // The preheader of the main loop. This may or may not be different from
574 // `OriginalPreheader'.
575 BasicBlock *MainLoopPreheader;
576
577 // The range we need to run the main loop in.
578 InductiveRangeCheck::Range Range;
579
580 // The structure of the main loop (see comment at the beginning of this class
581 // for a definition)
582 LoopStructure MainLoopStructure;
583
584public:
Sanjoy Dase75ed922015-02-26 08:19:31 +0000585 LoopConstrainer(Loop &L, LoopInfo &LI, const LoopStructure &LS,
586 ScalarEvolution &SE, InductiveRangeCheck::Range R)
587 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
588 SE(SE), OriginalLoop(L), OriginalLoopInfo(LI), LatchTakenCount(nullptr),
589 OriginalPreheader(nullptr), MainLoopPreheader(nullptr), Range(R),
590 MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000591
592 // Entry point for the algorithm. Returns true on success.
593 bool run();
594};
595
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000596}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000597
598void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
599 BasicBlock *ReplaceBy) {
600 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
601 if (PN->getIncomingBlock(i) == Block)
602 PN->setIncomingBlock(i, ReplaceBy);
603}
604
Sanjoy Dase75ed922015-02-26 08:19:31 +0000605static bool CanBeSMax(ScalarEvolution &SE, const SCEV *S) {
606 APInt SMax =
607 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
608 return SE.getSignedRange(S).contains(SMax) &&
609 SE.getUnsignedRange(S).contains(SMax);
610}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000611
Sanjoy Dase75ed922015-02-26 08:19:31 +0000612static bool CanBeSMin(ScalarEvolution &SE, const SCEV *S) {
613 APInt SMin =
614 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth());
615 return SE.getSignedRange(S).contains(SMin) &&
616 SE.getUnsignedRange(S).contains(SMin);
617}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000618
Sanjoy Dase75ed922015-02-26 08:19:31 +0000619Optional<LoopStructure>
Sanjoy Dase91665d2015-02-26 08:56:04 +0000620LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI,
621 Loop &L, const char *&FailureReason) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000622 assert(L.isLoopSimplifyForm() && "should follow from addRequired<>");
623
624 BasicBlock *Latch = L.getLoopLatch();
625 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000626 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000627 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000628 }
629
Sanjoy Dase75ed922015-02-26 08:19:31 +0000630 BasicBlock *Header = L.getHeader();
631 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000632 if (!Preheader) {
633 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000634 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000635 }
636
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000637 BranchInst *LatchBr = dyn_cast<BranchInst>(&*Latch->rbegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000638 if (!LatchBr || LatchBr->isUnconditional()) {
639 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000640 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000641 }
642
Sanjoy Dase75ed922015-02-26 08:19:31 +0000643 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000644
Sanjoy Dase91665d2015-02-26 08:56:04 +0000645 BranchProbability ExitProbability =
646 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
647
648 if (ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
649 FailureReason = "short running loop, not profitable";
650 return None;
651 }
652
Sanjoy Dase75ed922015-02-26 08:19:31 +0000653 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
654 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
655 FailureReason = "latch terminator branch not conditional on integral icmp";
656 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000657 }
658
Sanjoy Dase75ed922015-02-26 08:19:31 +0000659 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
660 if (isa<SCEVCouldNotCompute>(LatchCount)) {
661 FailureReason = "could not compute latch count";
662 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000663 }
664
Sanjoy Dase75ed922015-02-26 08:19:31 +0000665 ICmpInst::Predicate Pred = ICI->getPredicate();
666 Value *LeftValue = ICI->getOperand(0);
667 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
668 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
669
670 Value *RightValue = ICI->getOperand(1);
671 const SCEV *RightSCEV = SE.getSCEV(RightValue);
672
673 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
674 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
675 if (isa<SCEVAddRecExpr>(RightSCEV)) {
676 std::swap(LeftSCEV, RightSCEV);
677 std::swap(LeftValue, RightValue);
678 Pred = ICmpInst::getSwappedPredicate(Pred);
679 } else {
680 FailureReason = "no add recurrences in the icmp";
681 return None;
682 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000683 }
684
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000685 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
686 if (AR->getNoWrapFlags(SCEV::FlagNSW))
687 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000688
689 IntegerType *Ty = cast<IntegerType>(AR->getType());
690 IntegerType *WideTy =
691 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
692
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000693 const SCEVAddRecExpr *ExtendAfterOp =
694 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
695 if (ExtendAfterOp) {
696 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
697 const SCEV *ExtendedStep =
698 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
699
700 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
701 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
702
703 if (NoSignedWrap)
704 return true;
705 }
706
707 // We may have proved this when computing the sign extension above.
708 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
709 };
710
711 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing) {
712 if (!AR->isAffine())
713 return false;
714
Sanjoy Dase75ed922015-02-26 08:19:31 +0000715 // Currently we only work with induction variables that have been proved to
716 // not wrap. This restriction can potentially be lifted in the future.
717
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000718 if (!HasNoSignedWrap(AR))
Sanjoy Dase75ed922015-02-26 08:19:31 +0000719 return false;
720
721 if (const SCEVConstant *StepExpr =
722 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
723 ConstantInt *StepCI = StepExpr->getValue();
724 if (StepCI->isOne() || StepCI->isMinusOne()) {
725 IsIncreasing = StepCI->isOne();
726 return true;
727 }
728 }
729
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000730 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000731 };
732
733 // `ICI` is interpreted as taking the backedge if the *next* value of the
734 // induction variable satisfies some constraint.
735
736 const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
737 bool IsIncreasing = false;
738 if (!IsInductionVar(IndVarNext, IsIncreasing)) {
739 FailureReason = "LHS in icmp not induction variable";
740 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000741 }
742
Sanjoy Dase75ed922015-02-26 08:19:31 +0000743 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
744 // TODO: generalize the predicates here to also match their unsigned variants.
745 if (IsIncreasing) {
746 bool FoundExpectedPred =
747 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) ||
748 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0);
749
750 if (!FoundExpectedPred) {
751 FailureReason = "expected icmp slt semantically, found something else";
752 return None;
753 }
754
755 if (LatchBrExitIdx == 0) {
756 if (CanBeSMax(SE, RightSCEV)) {
757 // TODO: this restriction is easily removable -- we just have to
758 // remember that the icmp was an slt and not an sle.
759 FailureReason = "limit may overflow when coercing sle to slt";
760 return None;
761 }
762
763 IRBuilder<> B(&*Preheader->rbegin());
764 RightValue = B.CreateAdd(RightValue, One);
765 }
766
767 } else {
768 bool FoundExpectedPred =
769 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) ||
770 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0);
771
772 if (!FoundExpectedPred) {
773 FailureReason = "expected icmp sgt semantically, found something else";
774 return None;
775 }
776
777 if (LatchBrExitIdx == 0) {
778 if (CanBeSMin(SE, RightSCEV)) {
779 // TODO: this restriction is easily removable -- we just have to
780 // remember that the icmp was an sgt and not an sge.
781 FailureReason = "limit may overflow when coercing sge to sgt";
782 return None;
783 }
784
785 IRBuilder<> B(&*Preheader->rbegin());
786 RightValue = B.CreateSub(RightValue, One);
787 }
788 }
789
790 const SCEV *StartNext = IndVarNext->getStart();
791 const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
792 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
793
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000794 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
795
Sanjoy Dase75ed922015-02-26 08:19:31 +0000796 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000797 ScalarEvolution::LoopInvariant &&
798 "loop variant exit count doesn't make sense!");
799
Sanjoy Dase75ed922015-02-26 08:19:31 +0000800 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000801 const DataLayout &DL = Preheader->getModule()->getDataLayout();
802 Value *IndVarStartV =
803 SCEVExpander(SE, DL, "irce")
804 .expandCodeFor(IndVarStart, IndVarTy, &*Preheader->rbegin());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000805 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000806
Sanjoy Dase75ed922015-02-26 08:19:31 +0000807 LoopStructure Result;
808
809 Result.Tag = "main";
810 Result.Header = Header;
811 Result.Latch = Latch;
812 Result.LatchBr = LatchBr;
813 Result.LatchExit = LatchExit;
814 Result.LatchBrExitIdx = LatchBrExitIdx;
815 Result.IndVarStart = IndVarStartV;
816 Result.IndVarNext = LeftValue;
817 Result.IndVarIncreasing = IsIncreasing;
818 Result.LoopExitAt = RightValue;
819
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000820 FailureReason = nullptr;
821
Sanjoy Dase75ed922015-02-26 08:19:31 +0000822 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000823}
824
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000825Optional<LoopConstrainer::SubRanges>
Sanjoy Dase75ed922015-02-26 08:19:31 +0000826LoopConstrainer::calculateSubRanges() const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000827 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
828
Sanjoy Das351db052015-01-22 09:32:02 +0000829 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000830 return None;
831
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000832 LoopConstrainer::SubRanges Result;
833
834 // I think we can be more aggressive here and make this nuw / nsw if the
835 // addition that feeds into the icmp for the latch's terminating branch is nuw
836 // / nsw. In any case, a wrapping 2's complement addition is safe.
837 ConstantInt *One = ConstantInt::get(Ty, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000838 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
839 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000840
Sanjoy Dase75ed922015-02-26 08:19:31 +0000841 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000842
Sanjoy Dase75ed922015-02-26 08:19:31 +0000843 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the
844 // range of values the induction variable takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000845
846 const SCEV *Smallest = nullptr, *Greatest = nullptr;
847
848 if (Increasing) {
849 Smallest = Start;
850 Greatest = End;
851 } else {
852 // These two computations may sign-overflow. Here is why that is okay:
853 //
854 // We know that the induction variable does not sign-overflow on any
855 // iteration except the last one, and it starts at `Start` and ends at
856 // `End`, decrementing by one every time.
857 //
858 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
859 // induction variable is decreasing we know that that the smallest value
860 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
861 //
862 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
863 // that case, `Clamp` will always return `Smallest` and
864 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
865 // will be an empty range. Returning an empty range is always safe.
866 //
867
868 Smallest = SE.getAddExpr(End, SE.getSCEV(One));
869 Greatest = SE.getAddExpr(Start, SE.getSCEV(One));
870 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000871
872 auto Clamp = [this, Smallest, Greatest](const SCEV *S) {
873 return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S));
874 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000875
876 // In some cases we can prove that we don't need a pre or post loop
877
878 bool ProvablyNoPreloop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000879 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest);
880 if (!ProvablyNoPreloop)
881 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000882
883 bool ProvablyNoPostLoop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000884 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd());
885 if (!ProvablyNoPostLoop)
886 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000887
888 return Result;
889}
890
891void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
892 const char *Tag) const {
893 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
894 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
895 Result.Blocks.push_back(Clone);
896 Result.Map[BB] = Clone;
897 }
898
899 auto GetClonedValue = [&Result](Value *V) {
900 assert(V && "null values not in domain!");
901 auto It = Result.Map.find(V);
902 if (It == Result.Map.end())
903 return V;
904 return static_cast<Value *>(It->second);
905 };
906
907 Result.Structure = MainLoopStructure.map(GetClonedValue);
908 Result.Structure.Tag = Tag;
909
910 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
911 BasicBlock *ClonedBB = Result.Blocks[i];
912 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
913
914 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
915
916 for (Instruction &I : *ClonedBB)
917 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000918 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000919
920 // Exit blocks will now have one more predecessor and their PHI nodes need
921 // to be edited to reflect that. No phi nodes need to be introduced because
922 // the loop is in LCSSA.
923
924 for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB);
925 SBBI != SBBE; ++SBBI) {
926
927 if (OriginalLoop.contains(*SBBI))
928 continue; // not an exit block
929
930 for (Instruction &I : **SBBI) {
931 if (!isa<PHINode>(&I))
932 break;
933
934 PHINode *PN = cast<PHINode>(&I);
935 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
936 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
937 }
938 }
939 }
940}
941
942LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000943 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000944 BasicBlock *ContinuationBlock) const {
945
946 // We start with a loop with a single latch:
947 //
948 // +--------------------+
949 // | |
950 // | preheader |
951 // | |
952 // +--------+-----------+
953 // | ----------------\
954 // | / |
955 // +--------v----v------+ |
956 // | | |
957 // | header | |
958 // | | |
959 // +--------------------+ |
960 // |
961 // ..... |
962 // |
963 // +--------------------+ |
964 // | | |
965 // | latch >----------/
966 // | |
967 // +-------v------------+
968 // |
969 // |
970 // | +--------------------+
971 // | | |
972 // +---> original exit |
973 // | |
974 // +--------------------+
975 //
976 // We change the control flow to look like
977 //
978 //
979 // +--------------------+
980 // | |
981 // | preheader >-------------------------+
982 // | | |
983 // +--------v-----------+ |
984 // | /-------------+ |
985 // | / | |
986 // +--------v--v--------+ | |
987 // | | | |
988 // | header | | +--------+ |
989 // | | | | | |
990 // +--------------------+ | | +-----v-----v-----------+
991 // | | | |
992 // | | | .pseudo.exit |
993 // | | | |
994 // | | +-----------v-----------+
995 // | | |
996 // ..... | | |
997 // | | +--------v-------------+
998 // +--------------------+ | | | |
999 // | | | | | ContinuationBlock |
1000 // | latch >------+ | | |
1001 // | | | +----------------------+
1002 // +---------v----------+ |
1003 // | |
1004 // | |
1005 // | +---------------^-----+
1006 // | | |
1007 // +-----> .exit.selector |
1008 // | |
1009 // +----------v----------+
1010 // |
1011 // +--------------------+ |
1012 // | | |
1013 // | original exit <----+
1014 // | |
1015 // +--------------------+
1016 //
1017
1018 RewrittenRangeInfo RRI;
1019
1020 auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
1021 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001022 &F, &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001023 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001024 &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001025
1026 BranchInst *PreheaderJump = cast<BranchInst>(&*Preheader->rbegin());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001027 bool Increasing = LS.IndVarIncreasing;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001028
1029 IRBuilder<> B(PreheaderJump);
1030
1031 // EnterLoopCond - is it okay to start executing this `LS'?
Sanjoy Dase75ed922015-02-26 08:19:31 +00001032 Value *EnterLoopCond = Increasing
1033 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1034 : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt);
1035
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001036 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1037 PreheaderJump->eraseFromParent();
1038
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001039 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001040 B.SetInsertPoint(LS.LatchBr);
1041 Value *TakeBackedgeLoopCond =
1042 Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1043 : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt);
1044 Value *CondForBranch = LS.LatchBrExitIdx == 1
1045 ? TakeBackedgeLoopCond
1046 : B.CreateNot(TakeBackedgeLoopCond);
1047
1048 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001049
1050 B.SetInsertPoint(RRI.ExitSelector);
1051
1052 // IterationsLeft - are there any more iterations left, given the original
1053 // upper bound on the induction variable? If not, we branch to the "real"
1054 // exit.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001055 Value *IterationsLeft = Increasing
1056 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1057 : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001058 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1059
1060 BranchInst *BranchToContinuation =
1061 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1062
1063 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1064 // each of the PHI nodes in the loop header. This feeds into the initial
1065 // value of the same PHI nodes if/when we continue execution.
1066 for (Instruction &I : *LS.Header) {
1067 if (!isa<PHINode>(&I))
1068 break;
1069
1070 PHINode *PN = cast<PHINode>(&I);
1071
1072 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1073 BranchToContinuation);
1074
1075 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1076 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1077 RRI.ExitSelector);
1078 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1079 }
1080
Sanjoy Dase75ed922015-02-26 08:19:31 +00001081 RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1082 BranchToContinuation);
1083 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1084 RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1085
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001086 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1087 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1088 for (Instruction &I : *LS.LatchExit) {
1089 if (PHINode *PN = dyn_cast<PHINode>(&I))
1090 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1091 else
1092 break;
1093 }
1094
1095 return RRI;
1096}
1097
1098void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001099 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001100 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1101
1102 unsigned PHIIndex = 0;
1103 for (Instruction &I : *LS.Header) {
1104 if (!isa<PHINode>(&I))
1105 break;
1106
1107 PHINode *PN = cast<PHINode>(&I);
1108
1109 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1110 if (PN->getIncomingBlock(i) == ContinuationBlock)
1111 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1112 }
1113
Sanjoy Dase75ed922015-02-26 08:19:31 +00001114 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001115}
1116
Sanjoy Dase75ed922015-02-26 08:19:31 +00001117BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1118 BasicBlock *OldPreheader,
1119 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001120
1121 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1122 BranchInst::Create(LS.Header, Preheader);
1123
1124 for (Instruction &I : *LS.Header) {
1125 if (!isa<PHINode>(&I))
1126 break;
1127
1128 PHINode *PN = cast<PHINode>(&I);
1129 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1130 replacePHIBlock(PN, OldPreheader, Preheader);
1131 }
1132
1133 return Preheader;
1134}
1135
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001136void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001137 Loop *ParentLoop = OriginalLoop.getParentLoop();
1138 if (!ParentLoop)
1139 return;
1140
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001141 for (BasicBlock *BB : BBs)
1142 ParentLoop->addBasicBlockToLoop(BB, OriginalLoopInfo);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001143}
1144
1145bool LoopConstrainer::run() {
1146 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001147 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1148 Preheader = OriginalLoop.getLoopPreheader();
1149 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1150 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001151
1152 OriginalPreheader = Preheader;
1153 MainLoopPreheader = Preheader;
1154
Sanjoy Dase75ed922015-02-26 08:19:31 +00001155 Optional<SubRanges> MaybeSR = calculateSubRanges();
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001156 if (!MaybeSR.hasValue()) {
1157 DEBUG(dbgs() << "irce: could not compute subranges\n");
1158 return false;
1159 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001160
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001161 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001162 bool Increasing = MainLoopStructure.IndVarIncreasing;
1163 IntegerType *IVTy =
1164 cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1165
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001166 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001167 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001168
1169 // It would have been better to make `PreLoop' and `PostLoop'
1170 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1171 // constructor.
1172 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001173 bool NeedsPreLoop =
1174 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1175 bool NeedsPostLoop =
1176 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1177
1178 Value *ExitPreLoopAt = nullptr;
1179 Value *ExitMainLoopAt = nullptr;
1180 const SCEVConstant *MinusOneS =
1181 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1182
1183 if (NeedsPreLoop) {
1184 const SCEV *ExitPreLoopAtSCEV = nullptr;
1185
1186 if (Increasing)
1187 ExitPreLoopAtSCEV = *SR.LowLimit;
1188 else {
1189 if (CanBeSMin(SE, *SR.HighLimit)) {
1190 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1191 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1192 << "\n");
1193 return false;
1194 }
1195 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1196 }
1197
1198 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1199 ExitPreLoopAt->setName("exit.preloop.at");
1200 }
1201
1202 if (NeedsPostLoop) {
1203 const SCEV *ExitMainLoopAtSCEV = nullptr;
1204
1205 if (Increasing)
1206 ExitMainLoopAtSCEV = *SR.HighLimit;
1207 else {
1208 if (CanBeSMin(SE, *SR.LowLimit)) {
1209 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1210 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1211 << "\n");
1212 return false;
1213 }
1214 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1215 }
1216
1217 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1218 ExitMainLoopAt->setName("exit.mainloop.at");
1219 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001220
1221 // We clone these ahead of time so that we don't have to deal with changing
1222 // and temporarily invalid IR as we transform the loops.
1223 if (NeedsPreLoop)
1224 cloneLoop(PreLoop, "preloop");
1225 if (NeedsPostLoop)
1226 cloneLoop(PostLoop, "postloop");
1227
1228 RewrittenRangeInfo PreLoopRRI;
1229
1230 if (NeedsPreLoop) {
1231 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1232 PreLoop.Structure.Header);
1233
1234 MainLoopPreheader =
1235 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001236 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1237 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001238 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1239 PreLoopRRI);
1240 }
1241
1242 BasicBlock *PostLoopPreheader = nullptr;
1243 RewrittenRangeInfo PostLoopRRI;
1244
1245 if (NeedsPostLoop) {
1246 PostLoopPreheader =
1247 createPreheader(PostLoop.Structure, Preheader, "postloop");
1248 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001249 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001250 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1251 PostLoopRRI);
1252 }
1253
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001254 BasicBlock *NewMainLoopPreheader =
1255 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1256 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1257 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1258 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001259
1260 // Some of the above may be nullptr, filter them out before passing to
1261 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001262 auto NewBlocksEnd =
1263 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001264
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001265 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1266 addToParentLoopIfNeeded(PreLoop.Blocks);
1267 addToParentLoopIfNeeded(PostLoop.Blocks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001268
1269 return true;
1270}
1271
Sanjoy Das95c476d2015-02-21 22:20:22 +00001272/// Computes and returns a range of values for the induction variable (IndVar)
1273/// in which the range check can be safely elided. If it cannot compute such a
1274/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001275Optional<InductiveRangeCheck::Range>
Sanjoy Das59776732016-05-21 02:31:51 +00001276InductiveRangeCheck::computeSafeIterationSpace(
1277 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001278 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1279 // variable, that may or may not exist as a real llvm::Value in the loop) and
1280 // this inductive range check is a range check on the "C + D * I" ("C" is
1281 // getOffset() and "D" is getScale()). We rewrite the value being range
1282 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1283 // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code
1284 // can be generalized as needed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001285 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001286 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001287 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001288 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1289 //
1290 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1291 // and subtractions are twos-complement wrapping and comparisons are signed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001292 //
1293 // Proof:
1294 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001295 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1296 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1297 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1298 // overflown.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001299 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001300 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1301 // Hence 0 <= (IndVar + M) < L
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001302
Sanjoy Das95c476d2015-02-21 22:20:22 +00001303 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1304 // 127, IndVar = 126 and L = -2 in an i8 world.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001305
Sanjoy Das95c476d2015-02-21 22:20:22 +00001306 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001307 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001308
Sanjoy Das95c476d2015-02-21 22:20:22 +00001309 const SCEV *A = IndVar->getStart();
1310 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1311 if (!B)
1312 return None;
1313
1314 const SCEV *C = getOffset();
1315 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1316 if (D != B)
1317 return None;
1318
1319 ConstantInt *ConstD = D->getValue();
1320 if (!(ConstD->isMinusOne() || ConstD->isOne()))
1321 return None;
1322
1323 const SCEV *M = SE.getMinusSCEV(C, A);
1324
1325 const SCEV *Begin = SE.getNegativeSCEV(M);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001326 const SCEV *UpperLimit = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001327
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001328 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1329 // We can potentially do much better here.
1330 if (Value *V = getLength()) {
1331 UpperLimit = SE.getSCEV(V);
1332 } else {
1333 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1334 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1335 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1336 }
1337
1338 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
Sanjoy Das351db052015-01-22 09:32:02 +00001339 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001340}
1341
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001342static Optional<InductiveRangeCheck::Range>
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001343IntersectRange(ScalarEvolution &SE,
1344 const Optional<InductiveRangeCheck::Range> &R1,
Sanjoy Das59776732016-05-21 02:31:51 +00001345 const InductiveRangeCheck::Range &R2) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001346 if (!R1.hasValue())
1347 return R2;
1348 auto &R1Value = R1.getValue();
1349
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001350 // TODO: we could widen the smaller range and have this work; but for now we
1351 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001352 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001353 return None;
1354
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001355 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1356 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1357
1358 return InductiveRangeCheck::Range(NewBegin, NewEnd);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001359}
1360
1361bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001362 if (skipLoop(L))
1363 return false;
1364
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001365 if (L->getBlocks().size() >= LoopSizeCutoff) {
1366 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1367 return false;
1368 }
1369
1370 BasicBlock *Preheader = L->getLoopPreheader();
1371 if (!Preheader) {
1372 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1373 return false;
1374 }
1375
1376 LLVMContext &Context = Preheader->getContext();
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001377 SmallVector<InductiveRangeCheck, 16> RangeChecks;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001378 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Cong Houab23bfb2015-07-15 22:48:29 +00001379 BranchProbabilityInfo &BPI =
1380 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001381
1382 for (auto BBI : L->getBlocks())
1383 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001384 if (auto MaybeIRC = InductiveRangeCheck::create(TBI, L, SE, BPI))
1385 RangeChecks.push_back(*MaybeIRC);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001386
1387 if (RangeChecks.empty())
1388 return false;
1389
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001390 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1391 OS << "irce: looking at loop "; L->print(OS);
1392 OS << "irce: loop has " << RangeChecks.size()
1393 << " inductive range checks: \n";
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001394 for (InductiveRangeCheck &IRC : RangeChecks)
1395 IRC.print(OS);
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001396 };
1397
1398 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1399
1400 if (PrintRangeChecks)
1401 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001402
Sanjoy Dase75ed922015-02-26 08:19:31 +00001403 const char *FailureReason = nullptr;
1404 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001405 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001406 if (!MaybeLoopStructure.hasValue()) {
1407 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1408 << "\n";);
1409 return false;
1410 }
1411 LoopStructure LS = MaybeLoopStructure.getValue();
1412 bool Increasing = LS.IndVarIncreasing;
1413 const SCEV *MinusOne =
1414 SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true);
1415 const SCEVAddRecExpr *IndVar =
1416 cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne));
1417
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001418 Optional<InductiveRangeCheck::Range> SafeIterRange;
1419 Instruction *ExprInsertPt = Preheader->getTerminator();
1420
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001421 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001422
1423 IRBuilder<> B(ExprInsertPt);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001424 for (InductiveRangeCheck &IRC : RangeChecks) {
1425 auto Result = IRC.computeSafeIterationSpace(SE, IndVar);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001426 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001427 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001428 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001429 if (MaybeSafeIterRange.hasValue()) {
1430 RangeChecksToEliminate.push_back(IRC);
1431 SafeIterRange = MaybeSafeIterRange.getValue();
1432 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001433 }
1434 }
1435
1436 if (!SafeIterRange.hasValue())
1437 return false;
1438
Sanjoy Dase75ed922015-02-26 08:19:31 +00001439 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LS,
1440 SE, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001441 bool Changed = LC.run();
1442
1443 if (Changed) {
1444 auto PrintConstrainedLoopInfo = [L]() {
1445 dbgs() << "irce: in function ";
1446 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1447 dbgs() << "constrained ";
1448 L->print(dbgs());
1449 };
1450
1451 DEBUG(PrintConstrainedLoopInfo());
1452
1453 if (PrintChangedLoops)
1454 PrintConstrainedLoopInfo();
1455
1456 // Optimize away the now-redundant range checks.
1457
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001458 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1459 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001460 ? ConstantInt::getTrue(Context)
1461 : ConstantInt::getFalse(Context);
Sanjoy Dasaa83c472016-05-23 22:16:45 +00001462 IRC.getCheckUse()->set(FoldedRangeCheck);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001463 }
1464 }
1465
1466 return Changed;
1467}
1468
1469Pass *llvm::createInductiveRangeCheckEliminationPass() {
1470 return new InductiveRangeCheckElimination;
1471}