blob: cfefcb8cd5d56eb31530364a6a195136473cdebe [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
Sanjoy Das8fe88922016-05-26 00:08:24 +0000128 static Optional<InductiveRangeCheck>
129 parseRangeCheckFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000130
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000131 InductiveRangeCheck()
132 : Offset(nullptr), Scale(nullptr), Length(nullptr),
133 CheckUse(nullptr) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000134
135public:
136 const SCEV *getOffset() const { return Offset; }
137 const SCEV *getScale() const { return Scale; }
138 Value *getLength() const { return Length; }
139
140 void print(raw_ostream &OS) const {
141 OS << "InductiveRangeCheck:\n";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000142 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000143 OS << " Offset: ";
144 Offset->print(OS);
145 OS << " Scale: ";
146 Scale->print(OS);
147 OS << " Length: ";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000148 if (Length)
149 Length->print(OS);
150 else
151 OS << "(null)";
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000152 OS << "\n CheckUse: ";
153 getCheckUse()->getUser()->print(OS);
154 OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000155 }
156
157#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
158 void dump() {
159 print(dbgs());
160 }
161#endif
162
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000163 Use *getCheckUse() const { return CheckUse; }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000164
Sanjoy Das351db052015-01-22 09:32:02 +0000165 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
166 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
167
168 class Range {
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000169 const SCEV *Begin;
170 const SCEV *End;
Sanjoy Das351db052015-01-22 09:32:02 +0000171
172 public:
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000173 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
Sanjoy Das351db052015-01-22 09:32:02 +0000174 assert(Begin->getType() == End->getType() && "ill-typed range!");
175 }
176
177 Type *getType() const { return Begin->getType(); }
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000178 const SCEV *getBegin() const { return Begin; }
179 const SCEV *getEnd() const { return End; }
Sanjoy Das351db052015-01-22 09:32:02 +0000180 };
181
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000182 /// This is the value the condition of the branch needs to evaluate to for the
183 /// branch to take the hot successor (see (1) above).
184 bool getPassingDirection() { return true; }
185
Sanjoy Das95c476d2015-02-21 22:20:22 +0000186 /// Computes a range for the induction variable (IndVar) in which the range
187 /// check is redundant and can be constant-folded away. The induction
188 /// variable is not required to be the canonical {0,+,1} induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000189 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
Sanjoy Das59776732016-05-21 02:31:51 +0000190 const SCEVAddRecExpr *IndVar) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000191
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000192 /// Create an inductive range check out of BI if possible, else return None.
193 static Optional<InductiveRangeCheck> create(BranchInst *BI, Loop *L,
194 ScalarEvolution &SE,
195 BranchProbabilityInfo &BPI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000196};
197
198class InductiveRangeCheckElimination : public LoopPass {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000199public:
200 static char ID;
201 InductiveRangeCheckElimination() : LoopPass(ID) {
202 initializeInductiveRangeCheckEliminationPass(
203 *PassRegistry::getPassRegistry());
204 }
205
206 void getAnalysisUsage(AnalysisUsage &AU) const override {
Cong Houab23bfb2015-07-15 22:48:29 +0000207 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000208 getLoopAnalysisUsage(AU);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000209 }
210
211 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
212};
213
214char InductiveRangeCheckElimination::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000215}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000216
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000217INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce",
218 "Inductive range check elimination", false, false)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000219INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000220INITIALIZE_PASS_DEPENDENCY(LoopPass)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000221INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce",
222 "Inductive range check elimination", false, false)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000223
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000224StringRef InductiveRangeCheck::rangeCheckKindToStr(
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000225 InductiveRangeCheck::RangeCheckKind RCK) {
226 switch (RCK) {
227 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
228 return "RANGE_CHECK_UNKNOWN";
229
230 case InductiveRangeCheck::RANGE_CHECK_UPPER:
231 return "RANGE_CHECK_UPPER";
232
233 case InductiveRangeCheck::RANGE_CHECK_LOWER:
234 return "RANGE_CHECK_LOWER";
235
236 case InductiveRangeCheck::RANGE_CHECK_BOTH:
237 return "RANGE_CHECK_BOTH";
238 }
239
240 llvm_unreachable("unknown range check type!");
241}
242
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000243/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000244/// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000245/// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000246/// range checked, and set `Length` to the upper limit `Index` is being range
247/// checked with if (and only if) the range check type is stronger or equal to
248/// RANGE_CHECK_UPPER.
249///
250InductiveRangeCheck::RangeCheckKind
Sanjoy Das337d46b2015-03-24 19:29:18 +0000251InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
252 ScalarEvolution &SE, Value *&Index,
253 Value *&Length) {
254
255 auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) {
256 const SCEV *S = SE.getSCEV(V);
257 if (isa<SCEVCouldNotCompute>(S))
258 return false;
259
260 return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant &&
261 SE.isKnownNonNegative(S);
262 };
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000263
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000264 using namespace llvm::PatternMatch;
265
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000266 ICmpInst::Predicate Pred = ICI->getPredicate();
267 Value *LHS = ICI->getOperand(0);
268 Value *RHS = ICI->getOperand(1);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000269
270 switch (Pred) {
271 default:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000272 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000273
274 case ICmpInst::ICMP_SLE:
275 std::swap(LHS, RHS);
276 // fallthrough
277 case ICmpInst::ICMP_SGE:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000278 if (match(RHS, m_ConstantInt<0>())) {
279 Index = LHS;
280 return RANGE_CHECK_LOWER;
281 }
282 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000283
284 case ICmpInst::ICMP_SLT:
285 std::swap(LHS, RHS);
286 // fallthrough
287 case ICmpInst::ICMP_SGT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000288 if (match(RHS, m_ConstantInt<-1>())) {
289 Index = LHS;
290 return RANGE_CHECK_LOWER;
291 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000292
Sanjoy Das337d46b2015-03-24 19:29:18 +0000293 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000294 Index = RHS;
295 Length = LHS;
296 return RANGE_CHECK_UPPER;
297 }
298 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000299
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000300 case ICmpInst::ICMP_ULT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000301 std::swap(LHS, RHS);
302 // fallthrough
303 case ICmpInst::ICMP_UGT:
Sanjoy Das337d46b2015-03-24 19:29:18 +0000304 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000305 Index = RHS;
306 Length = LHS;
307 return RANGE_CHECK_BOTH;
308 }
309 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000310 }
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000311
312 llvm_unreachable("default clause returns!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000313}
314
Sanjoy Das8fe88922016-05-26 00:08:24 +0000315/// Parses an arbitrary condition into an inductive range check.
316Optional<InductiveRangeCheck>
317InductiveRangeCheck::parseRangeCheckFromCond(Loop *L, ScalarEvolution &SE,
318 Use &ConditionUse) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000319 using namespace llvm::PatternMatch;
320
Sanjoy Das8fe88922016-05-26 00:08:24 +0000321 Value *Condition = ConditionUse.get();
322
323 Value *Length, *Index;
324 InductiveRangeCheck::RangeCheckKind RCKind;
325
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000326 Value *A = nullptr;
327 Value *B = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000328
329 if (match(Condition, m_And(m_Value(A), m_Value(B)))) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000330 Value *IndexA = nullptr, *IndexB = nullptr;
331 Value *LengthA = nullptr, *LengthB = nullptr;
332 ICmpInst *ICmpA = dyn_cast<ICmpInst>(A), *ICmpB = dyn_cast<ICmpInst>(B);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000333
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000334 if (!ICmpA || !ICmpB)
Sanjoy Das8fe88922016-05-26 00:08:24 +0000335 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000336
Sanjoy Das337d46b2015-03-24 19:29:18 +0000337 auto RCKindA = parseRangeCheckICmp(L, ICmpA, SE, IndexA, LengthA);
338 auto RCKindB = parseRangeCheckICmp(L, ICmpB, SE, IndexB, LengthB);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000339
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000340 if (RCKindA == InductiveRangeCheck::RANGE_CHECK_UNKNOWN ||
Sanjoy Das8fe88922016-05-26 00:08:24 +0000341 RCKindB == InductiveRangeCheck::RANGE_CHECK_UNKNOWN ||
342 IndexA != IndexB ||
343 (LengthA != nullptr && LengthB != nullptr && LengthA != LengthB))
344 return None;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000345
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000346 Index = IndexA;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000347 Length = LengthA == nullptr ? LengthB : LengthA;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000348 RCKind = (InductiveRangeCheck::RangeCheckKind)(RCKindA | RCKindB);
349 } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
350 RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length);
351 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
352 return None;
353 } else {
354 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000355 }
356
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000357 const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000358 bool IsAffineIndex =
359 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
360
361 if (!IsAffineIndex)
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000362 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000363
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000364 InductiveRangeCheck IRC;
365 IRC.Length = Length;
366 IRC.Offset = IndexAddRec->getStart();
367 IRC.Scale = IndexAddRec->getStepRecurrence(SE);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000368 IRC.CheckUse = &ConditionUse;
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000369 IRC.Kind = RCKind;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000370 return IRC;
371}
372
Sanjoy Das8fe88922016-05-26 00:08:24 +0000373Optional<InductiveRangeCheck>
374InductiveRangeCheck::create(BranchInst *BI, Loop *L, ScalarEvolution &SE,
375 BranchProbabilityInfo &BPI) {
376
377 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
378 return None;
379
380 BranchProbability LikelyTaken(15, 16);
381
382 if (BPI.getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken)
383 return None;
384
385 return InductiveRangeCheck::parseRangeCheckFromCond(L, SE,
386 BI->getOperandUse(0));
387}
388
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000389namespace {
390
Sanjoy Dase75ed922015-02-26 08:19:31 +0000391// Keeps track of the structure of a loop. This is similar to llvm::Loop,
392// except that it is more lightweight and can track the state of a loop through
393// changing and potentially invalid IR. This structure also formalizes the
394// kinds of loops we can deal with -- ones that have a single latch that is also
395// an exiting block *and* have a canonical induction variable.
396struct LoopStructure {
397 const char *Tag;
398
399 BasicBlock *Header;
400 BasicBlock *Latch;
401
402 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
403 // successor is `LatchExit', the exit block of the loop.
404 BranchInst *LatchBr;
405 BasicBlock *LatchExit;
406 unsigned LatchBrExitIdx;
407
408 Value *IndVarNext;
409 Value *IndVarStart;
410 Value *LoopExitAt;
411 bool IndVarIncreasing;
412
413 LoopStructure()
414 : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr),
415 LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr),
416 IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false) {}
417
418 template <typename M> LoopStructure map(M Map) const {
419 LoopStructure Result;
420 Result.Tag = Tag;
421 Result.Header = cast<BasicBlock>(Map(Header));
422 Result.Latch = cast<BasicBlock>(Map(Latch));
423 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
424 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
425 Result.LatchBrExitIdx = LatchBrExitIdx;
426 Result.IndVarNext = Map(IndVarNext);
427 Result.IndVarStart = Map(IndVarStart);
428 Result.LoopExitAt = Map(LoopExitAt);
429 Result.IndVarIncreasing = IndVarIncreasing;
430 return Result;
431 }
432
Sanjoy Dase91665d2015-02-26 08:56:04 +0000433 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
434 BranchProbabilityInfo &BPI,
435 Loop &,
Sanjoy Dase75ed922015-02-26 08:19:31 +0000436 const char *&);
437};
438
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000439/// This class is used to constrain loops to run within a given iteration space.
440/// The algorithm this class implements is given a Loop and a range [Begin,
441/// End). The algorithm then tries to break out a "main loop" out of the loop
442/// it is given in a way that the "main loop" runs with the induction variable
443/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
444/// loops to run any remaining iterations. The pre loop runs any iterations in
445/// which the induction variable is < Begin, and the post loop runs any
446/// iterations in which the induction variable is >= End.
447///
448class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000449 // The representation of a clone of the original loop we started out with.
450 struct ClonedLoop {
451 // The cloned blocks
452 std::vector<BasicBlock *> Blocks;
453
454 // `Map` maps values in the clonee into values in the cloned version
455 ValueToValueMapTy Map;
456
457 // An instance of `LoopStructure` for the cloned loop
458 LoopStructure Structure;
459 };
460
461 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
462 // more details on what these fields mean.
463 struct RewrittenRangeInfo {
464 BasicBlock *PseudoExit;
465 BasicBlock *ExitSelector;
466 std::vector<PHINode *> PHIValuesAtPseudoExit;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000467 PHINode *IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000468
Sanjoy Dase75ed922015-02-26 08:19:31 +0000469 RewrittenRangeInfo()
470 : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000471 };
472
473 // Calculated subranges we restrict the iteration space of the main loop to.
474 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000475 // these fields are computed. `LowLimit` is None if there is no restriction
476 // on low end of the restricted iteration space of the main loop. `HighLimit`
477 // is None if there is no restriction on high end of the restricted iteration
478 // space of the main loop.
479
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000480 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000481 Optional<const SCEV *> LowLimit;
482 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000483 };
484
485 // A utility function that does a `replaceUsesOfWith' on the incoming block
486 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
487 // incoming block list with `ReplaceBy'.
488 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
489 BasicBlock *ReplaceBy);
490
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000491 // Compute a safe set of limits for the main loop to run in -- effectively the
492 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000493 // Return None if unable to compute the set of subranges.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000494 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000495 Optional<SubRanges> calculateSubRanges() const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000496
497 // Clone `OriginalLoop' and return the result in CLResult. The IR after
498 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
499 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
500 // but there is no such edge.
501 //
502 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
503
504 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
505 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
506 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
507 // `OriginalHeaderCount'.
508 //
509 // If there are iterations left to execute, control is made to jump to
510 // `ContinuationBlock', otherwise they take the normal loop exit. The
511 // returned `RewrittenRangeInfo' object is populated as follows:
512 //
513 // .PseudoExit is a basic block that unconditionally branches to
514 // `ContinuationBlock'.
515 //
516 // .ExitSelector is a basic block that decides, on exit from the loop,
517 // whether to branch to the "true" exit or to `PseudoExit'.
518 //
519 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
520 // for each PHINode in the loop header on taking the pseudo exit.
521 //
522 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
523 // preheader because it is made to branch to the loop header only
524 // conditionally.
525 //
526 RewrittenRangeInfo
527 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
528 Value *ExitLoopAt,
529 BasicBlock *ContinuationBlock) const;
530
531 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
532 // function creates a new preheader for `LS' and returns it.
533 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000534 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
535 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000536
537 // `ContinuationBlockAndPreheader' was the continuation block for some call to
538 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
539 // This function rewrites the PHI nodes in `LS.Header' to start with the
540 // correct value.
541 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000542 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000543 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
544
545 // Even though we do not preserve any passes at this time, we at least need to
546 // keep the parent loop structure consistent. The `LPPassManager' seems to
547 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000548 // blocks denoted by BBs to this loops parent loop if required.
549 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000550
551 // Some global state.
552 Function &F;
553 LLVMContext &Ctx;
554 ScalarEvolution &SE;
555
556 // Information about the original loop we started out with.
557 Loop &OriginalLoop;
558 LoopInfo &OriginalLoopInfo;
559 const SCEV *LatchTakenCount;
560 BasicBlock *OriginalPreheader;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000561
562 // The preheader of the main loop. This may or may not be different from
563 // `OriginalPreheader'.
564 BasicBlock *MainLoopPreheader;
565
566 // The range we need to run the main loop in.
567 InductiveRangeCheck::Range Range;
568
569 // The structure of the main loop (see comment at the beginning of this class
570 // for a definition)
571 LoopStructure MainLoopStructure;
572
573public:
Sanjoy Dase75ed922015-02-26 08:19:31 +0000574 LoopConstrainer(Loop &L, LoopInfo &LI, const LoopStructure &LS,
575 ScalarEvolution &SE, InductiveRangeCheck::Range R)
576 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
577 SE(SE), OriginalLoop(L), OriginalLoopInfo(LI), LatchTakenCount(nullptr),
578 OriginalPreheader(nullptr), MainLoopPreheader(nullptr), Range(R),
579 MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000580
581 // Entry point for the algorithm. Returns true on success.
582 bool run();
583};
584
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000585}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000586
587void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
588 BasicBlock *ReplaceBy) {
589 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
590 if (PN->getIncomingBlock(i) == Block)
591 PN->setIncomingBlock(i, ReplaceBy);
592}
593
Sanjoy Dase75ed922015-02-26 08:19:31 +0000594static bool CanBeSMax(ScalarEvolution &SE, const SCEV *S) {
595 APInt SMax =
596 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
597 return SE.getSignedRange(S).contains(SMax) &&
598 SE.getUnsignedRange(S).contains(SMax);
599}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000600
Sanjoy Dase75ed922015-02-26 08:19:31 +0000601static bool CanBeSMin(ScalarEvolution &SE, const SCEV *S) {
602 APInt SMin =
603 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth());
604 return SE.getSignedRange(S).contains(SMin) &&
605 SE.getUnsignedRange(S).contains(SMin);
606}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000607
Sanjoy Dase75ed922015-02-26 08:19:31 +0000608Optional<LoopStructure>
Sanjoy Dase91665d2015-02-26 08:56:04 +0000609LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI,
610 Loop &L, const char *&FailureReason) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000611 assert(L.isLoopSimplifyForm() && "should follow from addRequired<>");
612
613 BasicBlock *Latch = L.getLoopLatch();
614 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000615 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000616 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000617 }
618
Sanjoy Dase75ed922015-02-26 08:19:31 +0000619 BasicBlock *Header = L.getHeader();
620 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000621 if (!Preheader) {
622 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000623 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000624 }
625
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000626 BranchInst *LatchBr = dyn_cast<BranchInst>(&*Latch->rbegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000627 if (!LatchBr || LatchBr->isUnconditional()) {
628 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000629 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000630 }
631
Sanjoy Dase75ed922015-02-26 08:19:31 +0000632 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000633
Sanjoy Dase91665d2015-02-26 08:56:04 +0000634 BranchProbability ExitProbability =
635 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
636
637 if (ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
638 FailureReason = "short running loop, not profitable";
639 return None;
640 }
641
Sanjoy Dase75ed922015-02-26 08:19:31 +0000642 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
643 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
644 FailureReason = "latch terminator branch not conditional on integral icmp";
645 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000646 }
647
Sanjoy Dase75ed922015-02-26 08:19:31 +0000648 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
649 if (isa<SCEVCouldNotCompute>(LatchCount)) {
650 FailureReason = "could not compute latch count";
651 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000652 }
653
Sanjoy Dase75ed922015-02-26 08:19:31 +0000654 ICmpInst::Predicate Pred = ICI->getPredicate();
655 Value *LeftValue = ICI->getOperand(0);
656 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
657 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
658
659 Value *RightValue = ICI->getOperand(1);
660 const SCEV *RightSCEV = SE.getSCEV(RightValue);
661
662 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
663 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
664 if (isa<SCEVAddRecExpr>(RightSCEV)) {
665 std::swap(LeftSCEV, RightSCEV);
666 std::swap(LeftValue, RightValue);
667 Pred = ICmpInst::getSwappedPredicate(Pred);
668 } else {
669 FailureReason = "no add recurrences in the icmp";
670 return None;
671 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000672 }
673
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000674 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
675 if (AR->getNoWrapFlags(SCEV::FlagNSW))
676 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000677
678 IntegerType *Ty = cast<IntegerType>(AR->getType());
679 IntegerType *WideTy =
680 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
681
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000682 const SCEVAddRecExpr *ExtendAfterOp =
683 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
684 if (ExtendAfterOp) {
685 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
686 const SCEV *ExtendedStep =
687 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
688
689 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
690 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
691
692 if (NoSignedWrap)
693 return true;
694 }
695
696 // We may have proved this when computing the sign extension above.
697 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
698 };
699
700 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing) {
701 if (!AR->isAffine())
702 return false;
703
Sanjoy Dase75ed922015-02-26 08:19:31 +0000704 // Currently we only work with induction variables that have been proved to
705 // not wrap. This restriction can potentially be lifted in the future.
706
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000707 if (!HasNoSignedWrap(AR))
Sanjoy Dase75ed922015-02-26 08:19:31 +0000708 return false;
709
710 if (const SCEVConstant *StepExpr =
711 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
712 ConstantInt *StepCI = StepExpr->getValue();
713 if (StepCI->isOne() || StepCI->isMinusOne()) {
714 IsIncreasing = StepCI->isOne();
715 return true;
716 }
717 }
718
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000719 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000720 };
721
722 // `ICI` is interpreted as taking the backedge if the *next* value of the
723 // induction variable satisfies some constraint.
724
725 const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
726 bool IsIncreasing = false;
727 if (!IsInductionVar(IndVarNext, IsIncreasing)) {
728 FailureReason = "LHS in icmp not induction variable";
729 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000730 }
731
Sanjoy Dase75ed922015-02-26 08:19:31 +0000732 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
733 // TODO: generalize the predicates here to also match their unsigned variants.
734 if (IsIncreasing) {
735 bool FoundExpectedPred =
736 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) ||
737 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0);
738
739 if (!FoundExpectedPred) {
740 FailureReason = "expected icmp slt semantically, found something else";
741 return None;
742 }
743
744 if (LatchBrExitIdx == 0) {
745 if (CanBeSMax(SE, RightSCEV)) {
746 // TODO: this restriction is easily removable -- we just have to
747 // remember that the icmp was an slt and not an sle.
748 FailureReason = "limit may overflow when coercing sle to slt";
749 return None;
750 }
751
752 IRBuilder<> B(&*Preheader->rbegin());
753 RightValue = B.CreateAdd(RightValue, One);
754 }
755
756 } else {
757 bool FoundExpectedPred =
758 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) ||
759 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0);
760
761 if (!FoundExpectedPred) {
762 FailureReason = "expected icmp sgt semantically, found something else";
763 return None;
764 }
765
766 if (LatchBrExitIdx == 0) {
767 if (CanBeSMin(SE, RightSCEV)) {
768 // TODO: this restriction is easily removable -- we just have to
769 // remember that the icmp was an sgt and not an sge.
770 FailureReason = "limit may overflow when coercing sge to sgt";
771 return None;
772 }
773
774 IRBuilder<> B(&*Preheader->rbegin());
775 RightValue = B.CreateSub(RightValue, One);
776 }
777 }
778
779 const SCEV *StartNext = IndVarNext->getStart();
780 const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
781 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
782
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000783 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
784
Sanjoy Dase75ed922015-02-26 08:19:31 +0000785 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000786 ScalarEvolution::LoopInvariant &&
787 "loop variant exit count doesn't make sense!");
788
Sanjoy Dase75ed922015-02-26 08:19:31 +0000789 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000790 const DataLayout &DL = Preheader->getModule()->getDataLayout();
791 Value *IndVarStartV =
792 SCEVExpander(SE, DL, "irce")
793 .expandCodeFor(IndVarStart, IndVarTy, &*Preheader->rbegin());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000794 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000795
Sanjoy Dase75ed922015-02-26 08:19:31 +0000796 LoopStructure Result;
797
798 Result.Tag = "main";
799 Result.Header = Header;
800 Result.Latch = Latch;
801 Result.LatchBr = LatchBr;
802 Result.LatchExit = LatchExit;
803 Result.LatchBrExitIdx = LatchBrExitIdx;
804 Result.IndVarStart = IndVarStartV;
805 Result.IndVarNext = LeftValue;
806 Result.IndVarIncreasing = IsIncreasing;
807 Result.LoopExitAt = RightValue;
808
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000809 FailureReason = nullptr;
810
Sanjoy Dase75ed922015-02-26 08:19:31 +0000811 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000812}
813
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000814Optional<LoopConstrainer::SubRanges>
Sanjoy Dase75ed922015-02-26 08:19:31 +0000815LoopConstrainer::calculateSubRanges() const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000816 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
817
Sanjoy Das351db052015-01-22 09:32:02 +0000818 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000819 return None;
820
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000821 LoopConstrainer::SubRanges Result;
822
823 // I think we can be more aggressive here and make this nuw / nsw if the
824 // addition that feeds into the icmp for the latch's terminating branch is nuw
825 // / nsw. In any case, a wrapping 2's complement addition is safe.
826 ConstantInt *One = ConstantInt::get(Ty, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000827 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
828 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000829
Sanjoy Dase75ed922015-02-26 08:19:31 +0000830 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000831
Sanjoy Dase75ed922015-02-26 08:19:31 +0000832 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the
833 // range of values the induction variable takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000834
835 const SCEV *Smallest = nullptr, *Greatest = nullptr;
836
837 if (Increasing) {
838 Smallest = Start;
839 Greatest = End;
840 } else {
841 // These two computations may sign-overflow. Here is why that is okay:
842 //
843 // We know that the induction variable does not sign-overflow on any
844 // iteration except the last one, and it starts at `Start` and ends at
845 // `End`, decrementing by one every time.
846 //
847 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
848 // induction variable is decreasing we know that that the smallest value
849 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
850 //
851 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
852 // that case, `Clamp` will always return `Smallest` and
853 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
854 // will be an empty range. Returning an empty range is always safe.
855 //
856
857 Smallest = SE.getAddExpr(End, SE.getSCEV(One));
858 Greatest = SE.getAddExpr(Start, SE.getSCEV(One));
859 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000860
861 auto Clamp = [this, Smallest, Greatest](const SCEV *S) {
862 return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S));
863 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000864
865 // In some cases we can prove that we don't need a pre or post loop
866
867 bool ProvablyNoPreloop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000868 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest);
869 if (!ProvablyNoPreloop)
870 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000871
872 bool ProvablyNoPostLoop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000873 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd());
874 if (!ProvablyNoPostLoop)
875 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000876
877 return Result;
878}
879
880void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
881 const char *Tag) const {
882 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
883 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
884 Result.Blocks.push_back(Clone);
885 Result.Map[BB] = Clone;
886 }
887
888 auto GetClonedValue = [&Result](Value *V) {
889 assert(V && "null values not in domain!");
890 auto It = Result.Map.find(V);
891 if (It == Result.Map.end())
892 return V;
893 return static_cast<Value *>(It->second);
894 };
895
896 Result.Structure = MainLoopStructure.map(GetClonedValue);
897 Result.Structure.Tag = Tag;
898
899 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
900 BasicBlock *ClonedBB = Result.Blocks[i];
901 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
902
903 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
904
905 for (Instruction &I : *ClonedBB)
906 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000907 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000908
909 // Exit blocks will now have one more predecessor and their PHI nodes need
910 // to be edited to reflect that. No phi nodes need to be introduced because
911 // the loop is in LCSSA.
912
913 for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB);
914 SBBI != SBBE; ++SBBI) {
915
916 if (OriginalLoop.contains(*SBBI))
917 continue; // not an exit block
918
919 for (Instruction &I : **SBBI) {
920 if (!isa<PHINode>(&I))
921 break;
922
923 PHINode *PN = cast<PHINode>(&I);
924 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
925 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
926 }
927 }
928 }
929}
930
931LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000932 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000933 BasicBlock *ContinuationBlock) const {
934
935 // We start with a loop with a single latch:
936 //
937 // +--------------------+
938 // | |
939 // | preheader |
940 // | |
941 // +--------+-----------+
942 // | ----------------\
943 // | / |
944 // +--------v----v------+ |
945 // | | |
946 // | header | |
947 // | | |
948 // +--------------------+ |
949 // |
950 // ..... |
951 // |
952 // +--------------------+ |
953 // | | |
954 // | latch >----------/
955 // | |
956 // +-------v------------+
957 // |
958 // |
959 // | +--------------------+
960 // | | |
961 // +---> original exit |
962 // | |
963 // +--------------------+
964 //
965 // We change the control flow to look like
966 //
967 //
968 // +--------------------+
969 // | |
970 // | preheader >-------------------------+
971 // | | |
972 // +--------v-----------+ |
973 // | /-------------+ |
974 // | / | |
975 // +--------v--v--------+ | |
976 // | | | |
977 // | header | | +--------+ |
978 // | | | | | |
979 // +--------------------+ | | +-----v-----v-----------+
980 // | | | |
981 // | | | .pseudo.exit |
982 // | | | |
983 // | | +-----------v-----------+
984 // | | |
985 // ..... | | |
986 // | | +--------v-------------+
987 // +--------------------+ | | | |
988 // | | | | | ContinuationBlock |
989 // | latch >------+ | | |
990 // | | | +----------------------+
991 // +---------v----------+ |
992 // | |
993 // | |
994 // | +---------------^-----+
995 // | | |
996 // +-----> .exit.selector |
997 // | |
998 // +----------v----------+
999 // |
1000 // +--------------------+ |
1001 // | | |
1002 // | original exit <----+
1003 // | |
1004 // +--------------------+
1005 //
1006
1007 RewrittenRangeInfo RRI;
1008
1009 auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
1010 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001011 &F, &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001012 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001013 &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001014
1015 BranchInst *PreheaderJump = cast<BranchInst>(&*Preheader->rbegin());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001016 bool Increasing = LS.IndVarIncreasing;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001017
1018 IRBuilder<> B(PreheaderJump);
1019
1020 // EnterLoopCond - is it okay to start executing this `LS'?
Sanjoy Dase75ed922015-02-26 08:19:31 +00001021 Value *EnterLoopCond = Increasing
1022 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1023 : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt);
1024
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001025 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1026 PreheaderJump->eraseFromParent();
1027
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001028 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001029 B.SetInsertPoint(LS.LatchBr);
1030 Value *TakeBackedgeLoopCond =
1031 Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1032 : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt);
1033 Value *CondForBranch = LS.LatchBrExitIdx == 1
1034 ? TakeBackedgeLoopCond
1035 : B.CreateNot(TakeBackedgeLoopCond);
1036
1037 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001038
1039 B.SetInsertPoint(RRI.ExitSelector);
1040
1041 // IterationsLeft - are there any more iterations left, given the original
1042 // upper bound on the induction variable? If not, we branch to the "real"
1043 // exit.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001044 Value *IterationsLeft = Increasing
1045 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1046 : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001047 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1048
1049 BranchInst *BranchToContinuation =
1050 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1051
1052 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1053 // each of the PHI nodes in the loop header. This feeds into the initial
1054 // value of the same PHI nodes if/when we continue execution.
1055 for (Instruction &I : *LS.Header) {
1056 if (!isa<PHINode>(&I))
1057 break;
1058
1059 PHINode *PN = cast<PHINode>(&I);
1060
1061 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1062 BranchToContinuation);
1063
1064 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1065 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1066 RRI.ExitSelector);
1067 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1068 }
1069
Sanjoy Dase75ed922015-02-26 08:19:31 +00001070 RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1071 BranchToContinuation);
1072 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1073 RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1074
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001075 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1076 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1077 for (Instruction &I : *LS.LatchExit) {
1078 if (PHINode *PN = dyn_cast<PHINode>(&I))
1079 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1080 else
1081 break;
1082 }
1083
1084 return RRI;
1085}
1086
1087void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001088 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001089 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1090
1091 unsigned PHIIndex = 0;
1092 for (Instruction &I : *LS.Header) {
1093 if (!isa<PHINode>(&I))
1094 break;
1095
1096 PHINode *PN = cast<PHINode>(&I);
1097
1098 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1099 if (PN->getIncomingBlock(i) == ContinuationBlock)
1100 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1101 }
1102
Sanjoy Dase75ed922015-02-26 08:19:31 +00001103 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001104}
1105
Sanjoy Dase75ed922015-02-26 08:19:31 +00001106BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1107 BasicBlock *OldPreheader,
1108 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001109
1110 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1111 BranchInst::Create(LS.Header, Preheader);
1112
1113 for (Instruction &I : *LS.Header) {
1114 if (!isa<PHINode>(&I))
1115 break;
1116
1117 PHINode *PN = cast<PHINode>(&I);
1118 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1119 replacePHIBlock(PN, OldPreheader, Preheader);
1120 }
1121
1122 return Preheader;
1123}
1124
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001125void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001126 Loop *ParentLoop = OriginalLoop.getParentLoop();
1127 if (!ParentLoop)
1128 return;
1129
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001130 for (BasicBlock *BB : BBs)
1131 ParentLoop->addBasicBlockToLoop(BB, OriginalLoopInfo);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001132}
1133
1134bool LoopConstrainer::run() {
1135 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001136 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1137 Preheader = OriginalLoop.getLoopPreheader();
1138 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1139 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001140
1141 OriginalPreheader = Preheader;
1142 MainLoopPreheader = Preheader;
1143
Sanjoy Dase75ed922015-02-26 08:19:31 +00001144 Optional<SubRanges> MaybeSR = calculateSubRanges();
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001145 if (!MaybeSR.hasValue()) {
1146 DEBUG(dbgs() << "irce: could not compute subranges\n");
1147 return false;
1148 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001149
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001150 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001151 bool Increasing = MainLoopStructure.IndVarIncreasing;
1152 IntegerType *IVTy =
1153 cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1154
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001155 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001156 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001157
1158 // It would have been better to make `PreLoop' and `PostLoop'
1159 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1160 // constructor.
1161 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001162 bool NeedsPreLoop =
1163 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1164 bool NeedsPostLoop =
1165 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1166
1167 Value *ExitPreLoopAt = nullptr;
1168 Value *ExitMainLoopAt = nullptr;
1169 const SCEVConstant *MinusOneS =
1170 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1171
1172 if (NeedsPreLoop) {
1173 const SCEV *ExitPreLoopAtSCEV = nullptr;
1174
1175 if (Increasing)
1176 ExitPreLoopAtSCEV = *SR.LowLimit;
1177 else {
1178 if (CanBeSMin(SE, *SR.HighLimit)) {
1179 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1180 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1181 << "\n");
1182 return false;
1183 }
1184 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1185 }
1186
1187 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1188 ExitPreLoopAt->setName("exit.preloop.at");
1189 }
1190
1191 if (NeedsPostLoop) {
1192 const SCEV *ExitMainLoopAtSCEV = nullptr;
1193
1194 if (Increasing)
1195 ExitMainLoopAtSCEV = *SR.HighLimit;
1196 else {
1197 if (CanBeSMin(SE, *SR.LowLimit)) {
1198 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1199 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1200 << "\n");
1201 return false;
1202 }
1203 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1204 }
1205
1206 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1207 ExitMainLoopAt->setName("exit.mainloop.at");
1208 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001209
1210 // We clone these ahead of time so that we don't have to deal with changing
1211 // and temporarily invalid IR as we transform the loops.
1212 if (NeedsPreLoop)
1213 cloneLoop(PreLoop, "preloop");
1214 if (NeedsPostLoop)
1215 cloneLoop(PostLoop, "postloop");
1216
1217 RewrittenRangeInfo PreLoopRRI;
1218
1219 if (NeedsPreLoop) {
1220 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1221 PreLoop.Structure.Header);
1222
1223 MainLoopPreheader =
1224 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001225 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1226 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001227 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1228 PreLoopRRI);
1229 }
1230
1231 BasicBlock *PostLoopPreheader = nullptr;
1232 RewrittenRangeInfo PostLoopRRI;
1233
1234 if (NeedsPostLoop) {
1235 PostLoopPreheader =
1236 createPreheader(PostLoop.Structure, Preheader, "postloop");
1237 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001238 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001239 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1240 PostLoopRRI);
1241 }
1242
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001243 BasicBlock *NewMainLoopPreheader =
1244 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1245 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1246 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1247 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001248
1249 // Some of the above may be nullptr, filter them out before passing to
1250 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001251 auto NewBlocksEnd =
1252 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001253
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001254 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1255 addToParentLoopIfNeeded(PreLoop.Blocks);
1256 addToParentLoopIfNeeded(PostLoop.Blocks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001257
1258 return true;
1259}
1260
Sanjoy Das95c476d2015-02-21 22:20:22 +00001261/// Computes and returns a range of values for the induction variable (IndVar)
1262/// in which the range check can be safely elided. If it cannot compute such a
1263/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001264Optional<InductiveRangeCheck::Range>
Sanjoy Das59776732016-05-21 02:31:51 +00001265InductiveRangeCheck::computeSafeIterationSpace(
1266 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001267 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1268 // variable, that may or may not exist as a real llvm::Value in the loop) and
1269 // this inductive range check is a range check on the "C + D * I" ("C" is
1270 // getOffset() and "D" is getScale()). We rewrite the value being range
1271 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1272 // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code
1273 // can be generalized as needed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001274 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001275 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001276 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001277 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1278 //
1279 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1280 // and subtractions are twos-complement wrapping and comparisons are signed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001281 //
1282 // Proof:
1283 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001284 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1285 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1286 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1287 // overflown.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001288 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001289 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1290 // Hence 0 <= (IndVar + M) < L
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001291
Sanjoy Das95c476d2015-02-21 22:20:22 +00001292 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1293 // 127, IndVar = 126 and L = -2 in an i8 world.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001294
Sanjoy Das95c476d2015-02-21 22:20:22 +00001295 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001296 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001297
Sanjoy Das95c476d2015-02-21 22:20:22 +00001298 const SCEV *A = IndVar->getStart();
1299 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1300 if (!B)
1301 return None;
1302
1303 const SCEV *C = getOffset();
1304 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1305 if (D != B)
1306 return None;
1307
1308 ConstantInt *ConstD = D->getValue();
1309 if (!(ConstD->isMinusOne() || ConstD->isOne()))
1310 return None;
1311
1312 const SCEV *M = SE.getMinusSCEV(C, A);
1313
1314 const SCEV *Begin = SE.getNegativeSCEV(M);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001315 const SCEV *UpperLimit = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001316
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001317 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1318 // We can potentially do much better here.
1319 if (Value *V = getLength()) {
1320 UpperLimit = SE.getSCEV(V);
1321 } else {
1322 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1323 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1324 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1325 }
1326
1327 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
Sanjoy Das351db052015-01-22 09:32:02 +00001328 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001329}
1330
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001331static Optional<InductiveRangeCheck::Range>
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001332IntersectRange(ScalarEvolution &SE,
1333 const Optional<InductiveRangeCheck::Range> &R1,
Sanjoy Das59776732016-05-21 02:31:51 +00001334 const InductiveRangeCheck::Range &R2) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001335 if (!R1.hasValue())
1336 return R2;
1337 auto &R1Value = R1.getValue();
1338
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001339 // TODO: we could widen the smaller range and have this work; but for now we
1340 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001341 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001342 return None;
1343
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001344 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1345 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1346
1347 return InductiveRangeCheck::Range(NewBegin, NewEnd);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001348}
1349
1350bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001351 if (skipLoop(L))
1352 return false;
1353
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001354 if (L->getBlocks().size() >= LoopSizeCutoff) {
1355 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1356 return false;
1357 }
1358
1359 BasicBlock *Preheader = L->getLoopPreheader();
1360 if (!Preheader) {
1361 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1362 return false;
1363 }
1364
1365 LLVMContext &Context = Preheader->getContext();
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001366 SmallVector<InductiveRangeCheck, 16> RangeChecks;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001367 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Cong Houab23bfb2015-07-15 22:48:29 +00001368 BranchProbabilityInfo &BPI =
1369 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001370
1371 for (auto BBI : L->getBlocks())
1372 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001373 if (auto MaybeIRC = InductiveRangeCheck::create(TBI, L, SE, BPI))
1374 RangeChecks.push_back(*MaybeIRC);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001375
1376 if (RangeChecks.empty())
1377 return false;
1378
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001379 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1380 OS << "irce: looking at loop "; L->print(OS);
1381 OS << "irce: loop has " << RangeChecks.size()
1382 << " inductive range checks: \n";
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001383 for (InductiveRangeCheck &IRC : RangeChecks)
1384 IRC.print(OS);
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001385 };
1386
1387 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1388
1389 if (PrintRangeChecks)
1390 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001391
Sanjoy Dase75ed922015-02-26 08:19:31 +00001392 const char *FailureReason = nullptr;
1393 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001394 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001395 if (!MaybeLoopStructure.hasValue()) {
1396 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1397 << "\n";);
1398 return false;
1399 }
1400 LoopStructure LS = MaybeLoopStructure.getValue();
1401 bool Increasing = LS.IndVarIncreasing;
1402 const SCEV *MinusOne =
1403 SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true);
1404 const SCEVAddRecExpr *IndVar =
1405 cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne));
1406
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001407 Optional<InductiveRangeCheck::Range> SafeIterRange;
1408 Instruction *ExprInsertPt = Preheader->getTerminator();
1409
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001410 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001411
1412 IRBuilder<> B(ExprInsertPt);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001413 for (InductiveRangeCheck &IRC : RangeChecks) {
1414 auto Result = IRC.computeSafeIterationSpace(SE, IndVar);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001415 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001416 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001417 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001418 if (MaybeSafeIterRange.hasValue()) {
1419 RangeChecksToEliminate.push_back(IRC);
1420 SafeIterRange = MaybeSafeIterRange.getValue();
1421 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001422 }
1423 }
1424
1425 if (!SafeIterRange.hasValue())
1426 return false;
1427
Sanjoy Dase75ed922015-02-26 08:19:31 +00001428 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LS,
1429 SE, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001430 bool Changed = LC.run();
1431
1432 if (Changed) {
1433 auto PrintConstrainedLoopInfo = [L]() {
1434 dbgs() << "irce: in function ";
1435 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1436 dbgs() << "constrained ";
1437 L->print(dbgs());
1438 };
1439
1440 DEBUG(PrintConstrainedLoopInfo());
1441
1442 if (PrintChangedLoops)
1443 PrintConstrainedLoopInfo();
1444
1445 // Optimize away the now-redundant range checks.
1446
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001447 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1448 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001449 ? ConstantInt::getTrue(Context)
1450 : ConstantInt::getFalse(Context);
Sanjoy Dasaa83c472016-05-23 22:16:45 +00001451 IRC.getCheckUse()->set(FoldedRangeCheck);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001452 }
1453 }
1454
1455 return Changed;
1456}
1457
1458Pass *llvm::createInductiveRangeCheckEliminationPass() {
1459 return new InductiveRangeCheckElimination;
1460}