blob: 915e3d60c86f14c622cd833866bc77ba55d81129 [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/LoopInfo.h"
47#include "llvm/Analysis/LoopPass.h"
48#include "llvm/Analysis/ScalarEvolution.h"
49#include "llvm/Analysis/ScalarEvolutionExpander.h"
50#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000051#include "llvm/IR/Dominators.h"
52#include "llvm/IR/Function.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000053#include "llvm/IR/IRBuilder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000054#include "llvm/IR/Instructions.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000055#include "llvm/IR/PatternMatch.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000056#include "llvm/Pass.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000057#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000058#include "llvm/Support/raw_ostream.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000059#include "llvm/Transforms/Scalar.h"
60#include "llvm/Transforms/Utils/BasicBlockUtils.h"
61#include "llvm/Transforms/Utils/Cloning.h"
62#include "llvm/Transforms/Utils/LoopUtils.h"
Sanjoy Dascf181862016-08-06 00:01:56 +000063#include "llvm/Transforms/Utils/LoopSimplify.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000064
65using namespace llvm;
66
Benjamin Kramer970eac42015-02-06 17:51:54 +000067static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
68 cl::init(64));
Sanjoy Dasa1837a32015-01-16 01:03:22 +000069
Benjamin Kramer970eac42015-02-06 17:51:54 +000070static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
71 cl::init(false));
Sanjoy Dasa1837a32015-01-16 01:03:22 +000072
Sanjoy Das9c1bfae2015-03-17 01:40:22 +000073static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
74 cl::init(false));
75
Sanjoy Dase91665d2015-02-26 08:56:04 +000076static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
77 cl::Hidden, cl::init(10));
78
Sanjoy Dasbb969792016-07-22 00:40:56 +000079static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks",
80 cl::Hidden, cl::init(false));
81
Sanjoy Das7a18a232016-08-14 01:04:36 +000082static const char *ClonedLoopTag = "irce.loop.clone";
83
Sanjoy Dasa1837a32015-01-16 01:03:22 +000084#define DEBUG_TYPE "irce"
85
86namespace {
87
88/// An inductive range check is conditional branch in a loop with
89///
90/// 1. a very cold successor (i.e. the branch jumps to that successor very
91/// rarely)
92///
93/// and
94///
Sanjoy Dase2cde6f2015-03-17 00:42:13 +000095/// 2. a condition that is provably true for some contiguous range of values
96/// taken by the containing loop's induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +000097///
Sanjoy Dasa1837a32015-01-16 01:03:22 +000098class InductiveRangeCheck {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +000099 // Classifies a range check
Reid Kleckner0b168592015-03-17 16:50:20 +0000100 enum RangeCheckKind : unsigned {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000101 // Range check of the form "0 <= I".
102 RANGE_CHECK_LOWER = 1,
103
104 // Range check of the form "I < L" where L is known positive.
105 RANGE_CHECK_UPPER = 2,
106
107 // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER
108 // conditions.
109 RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
110
111 // Unrecognized range check condition.
112 RANGE_CHECK_UNKNOWN = (unsigned)-1
113 };
114
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000115 static StringRef rangeCheckKindToStr(RangeCheckKind);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000116
Sanjoy Dasee77a482016-05-26 01:50:18 +0000117 const SCEV *Offset = nullptr;
118 const SCEV *Scale = nullptr;
119 Value *Length = nullptr;
120 Use *CheckUse = nullptr;
121 RangeCheckKind Kind = RANGE_CHECK_UNKNOWN;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000122
Sanjoy Das337d46b2015-03-24 19:29:18 +0000123 static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
124 ScalarEvolution &SE, Value *&Index,
125 Value *&Length);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000126
Sanjoy Dasa0992682016-05-26 00:09:02 +0000127 static void
128 extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,
129 SmallVectorImpl<InductiveRangeCheck> &Checks,
130 SmallPtrSetImpl<Value *> &Visited);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000131
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000132public:
133 const SCEV *getOffset() const { return Offset; }
134 const SCEV *getScale() const { return Scale; }
135 Value *getLength() const { return Length; }
136
137 void print(raw_ostream &OS) const {
138 OS << "InductiveRangeCheck:\n";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000139 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000140 OS << " Offset: ";
141 Offset->print(OS);
142 OS << " Scale: ";
143 Scale->print(OS);
144 OS << " Length: ";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000145 if (Length)
146 Length->print(OS);
147 else
148 OS << "(null)";
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000149 OS << "\n CheckUse: ";
150 getCheckUse()->getUser()->print(OS);
151 OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000152 }
153
Davide Italianod1279df2016-08-18 15:55:49 +0000154 LLVM_DUMP_METHOD
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000155 void dump() {
156 print(dbgs());
157 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000158
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000159 Use *getCheckUse() const { return CheckUse; }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000160
Sanjoy Das351db052015-01-22 09:32:02 +0000161 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
162 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
163
164 class Range {
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000165 const SCEV *Begin;
166 const SCEV *End;
Sanjoy Das351db052015-01-22 09:32:02 +0000167
168 public:
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000169 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
Sanjoy Das351db052015-01-22 09:32:02 +0000170 assert(Begin->getType() == End->getType() && "ill-typed range!");
171 }
172
173 Type *getType() const { return Begin->getType(); }
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000174 const SCEV *getBegin() const { return Begin; }
175 const SCEV *getEnd() const { return End; }
Sanjoy Das351db052015-01-22 09:32:02 +0000176 };
177
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000178 /// This is the value the condition of the branch needs to evaluate to for the
179 /// branch to take the hot successor (see (1) above).
180 bool getPassingDirection() { return true; }
181
Sanjoy Das95c476d2015-02-21 22:20:22 +0000182 /// Computes a range for the induction variable (IndVar) in which the range
183 /// check is redundant and can be constant-folded away. The induction
184 /// variable is not required to be the canonical {0,+,1} induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000185 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
Sanjoy Das59776732016-05-21 02:31:51 +0000186 const SCEVAddRecExpr *IndVar) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000187
Sanjoy Dasa0992682016-05-26 00:09:02 +0000188 /// Parse out a set of inductive range checks from \p BI and append them to \p
189 /// Checks.
190 ///
191 /// NB! There may be conditions feeding into \p BI that aren't inductive range
192 /// checks, and hence don't end up in \p Checks.
193 static void
194 extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE,
195 BranchProbabilityInfo &BPI,
196 SmallVectorImpl<InductiveRangeCheck> &Checks);
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);
Justin Bognerb03fd122016-08-17 05:10:15 +0000277 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000278 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);
Justin Bognerb03fd122016-08-17 05:10:15 +0000287 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000288 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);
Justin Bognerb03fd122016-08-17 05:10:15 +0000303 LLVM_FALLTHROUGH;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000304 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 Dasa0992682016-05-26 00:09:02 +0000316void InductiveRangeCheck::extractRangeChecksFromCond(
317 Loop *L, ScalarEvolution &SE, Use &ConditionUse,
318 SmallVectorImpl<InductiveRangeCheck> &Checks,
319 SmallPtrSetImpl<Value *> &Visited) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000320 using namespace llvm::PatternMatch;
321
Sanjoy Das8fe88922016-05-26 00:08:24 +0000322 Value *Condition = ConditionUse.get();
Sanjoy Dasa0992682016-05-26 00:09:02 +0000323 if (!Visited.insert(Condition).second)
324 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000325
Sanjoy Dasa0992682016-05-26 00:09:02 +0000326 if (match(Condition, m_And(m_Value(), m_Value()))) {
327 SmallVector<InductiveRangeCheck, 8> SubChecks;
328 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
329 SubChecks, Visited);
330 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
331 SubChecks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000332
Sanjoy Dasa0992682016-05-26 00:09:02 +0000333 if (SubChecks.size() == 2) {
334 // Handle a special case where we know how to merge two checks separately
335 // checking the upper and lower bounds into a full range check.
336 const auto &RChkA = SubChecks[0];
337 const auto &RChkB = SubChecks[1];
338 if ((RChkA.Length == RChkB.Length || !RChkA.Length || !RChkB.Length) &&
339 RChkA.Offset == RChkB.Offset && RChkA.Scale == RChkB.Scale) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000340
Sanjoy Dasa0992682016-05-26 00:09:02 +0000341 // If RChkA.Kind == RChkB.Kind then we just found two identical checks.
342 // But if one of them is a RANGE_CHECK_LOWER and the other is a
343 // RANGE_CHECK_UPPER (only possibility if they're different) then
344 // together they form a RANGE_CHECK_BOTH.
345 SubChecks[0].Kind =
346 (InductiveRangeCheck::RangeCheckKind)(RChkA.Kind | RChkB.Kind);
347 SubChecks[0].Length = RChkA.Length ? RChkA.Length : RChkB.Length;
348 SubChecks[0].CheckUse = &ConditionUse;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000349
Sanjoy Dasa0992682016-05-26 00:09:02 +0000350 // We updated one of the checks in place, now erase the other.
351 SubChecks.pop_back();
352 }
353 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000354
Sanjoy Dasa0992682016-05-26 00:09:02 +0000355 Checks.insert(Checks.end(), SubChecks.begin(), SubChecks.end());
356 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000357 }
358
Sanjoy Dasa0992682016-05-26 00:09:02 +0000359 ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);
360 if (!ICI)
361 return;
362
363 Value *Length = nullptr, *Index;
364 auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length);
365 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
366 return;
367
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000368 const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000369 bool IsAffineIndex =
370 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
371
372 if (!IsAffineIndex)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000373 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000374
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000375 InductiveRangeCheck IRC;
376 IRC.Length = Length;
377 IRC.Offset = IndexAddRec->getStart();
378 IRC.Scale = IndexAddRec->getStepRecurrence(SE);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000379 IRC.CheckUse = &ConditionUse;
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000380 IRC.Kind = RCKind;
Sanjoy Dasa0992682016-05-26 00:09:02 +0000381 Checks.push_back(IRC);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000382}
383
Sanjoy Dasa0992682016-05-26 00:09:02 +0000384void InductiveRangeCheck::extractRangeChecksFromBranch(
385 BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo &BPI,
386 SmallVectorImpl<InductiveRangeCheck> &Checks) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000387
388 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
Sanjoy Dasa0992682016-05-26 00:09:02 +0000389 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000390
391 BranchProbability LikelyTaken(15, 16);
392
Sanjoy Dasbb969792016-07-22 00:40:56 +0000393 if (!SkipProfitabilityChecks &&
394 BPI.getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000395 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000396
Sanjoy Dasa0992682016-05-26 00:09:02 +0000397 SmallPtrSet<Value *, 8> Visited;
398 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
399 Checks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000400}
401
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000402namespace {
403
Sanjoy Dase75ed922015-02-26 08:19:31 +0000404// Keeps track of the structure of a loop. This is similar to llvm::Loop,
405// except that it is more lightweight and can track the state of a loop through
406// changing and potentially invalid IR. This structure also formalizes the
407// kinds of loops we can deal with -- ones that have a single latch that is also
408// an exiting block *and* have a canonical induction variable.
409struct LoopStructure {
410 const char *Tag;
411
412 BasicBlock *Header;
413 BasicBlock *Latch;
414
415 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
416 // successor is `LatchExit', the exit block of the loop.
417 BranchInst *LatchBr;
418 BasicBlock *LatchExit;
419 unsigned LatchBrExitIdx;
420
421 Value *IndVarNext;
422 Value *IndVarStart;
423 Value *LoopExitAt;
424 bool IndVarIncreasing;
425
426 LoopStructure()
427 : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr),
428 LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr),
429 IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false) {}
430
431 template <typename M> LoopStructure map(M Map) const {
432 LoopStructure Result;
433 Result.Tag = Tag;
434 Result.Header = cast<BasicBlock>(Map(Header));
435 Result.Latch = cast<BasicBlock>(Map(Latch));
436 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
437 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
438 Result.LatchBrExitIdx = LatchBrExitIdx;
439 Result.IndVarNext = Map(IndVarNext);
440 Result.IndVarStart = Map(IndVarStart);
441 Result.LoopExitAt = Map(LoopExitAt);
442 Result.IndVarIncreasing = IndVarIncreasing;
443 return Result;
444 }
445
Sanjoy Dase91665d2015-02-26 08:56:04 +0000446 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
447 BranchProbabilityInfo &BPI,
448 Loop &,
Sanjoy Dase75ed922015-02-26 08:19:31 +0000449 const char *&);
450};
451
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000452/// This class is used to constrain loops to run within a given iteration space.
453/// The algorithm this class implements is given a Loop and a range [Begin,
454/// End). The algorithm then tries to break out a "main loop" out of the loop
455/// it is given in a way that the "main loop" runs with the induction variable
456/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
457/// loops to run any remaining iterations. The pre loop runs any iterations in
458/// which the induction variable is < Begin, and the post loop runs any
459/// iterations in which the induction variable is >= End.
460///
461class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000462 // The representation of a clone of the original loop we started out with.
463 struct ClonedLoop {
464 // The cloned blocks
465 std::vector<BasicBlock *> Blocks;
466
467 // `Map` maps values in the clonee into values in the cloned version
468 ValueToValueMapTy Map;
469
470 // An instance of `LoopStructure` for the cloned loop
471 LoopStructure Structure;
472 };
473
474 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
475 // more details on what these fields mean.
476 struct RewrittenRangeInfo {
477 BasicBlock *PseudoExit;
478 BasicBlock *ExitSelector;
479 std::vector<PHINode *> PHIValuesAtPseudoExit;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000480 PHINode *IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000481
Sanjoy Dase75ed922015-02-26 08:19:31 +0000482 RewrittenRangeInfo()
483 : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000484 };
485
486 // Calculated subranges we restrict the iteration space of the main loop to.
487 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000488 // these fields are computed. `LowLimit` is None if there is no restriction
489 // on low end of the restricted iteration space of the main loop. `HighLimit`
490 // is None if there is no restriction on high end of the restricted iteration
491 // space of the main loop.
492
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000493 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000494 Optional<const SCEV *> LowLimit;
495 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000496 };
497
498 // A utility function that does a `replaceUsesOfWith' on the incoming block
499 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
500 // incoming block list with `ReplaceBy'.
501 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
502 BasicBlock *ReplaceBy);
503
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000504 // Compute a safe set of limits for the main loop to run in -- effectively the
505 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000506 // Return None if unable to compute the set of subranges.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000507 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000508 Optional<SubRanges> calculateSubRanges() const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000509
510 // Clone `OriginalLoop' and return the result in CLResult. The IR after
511 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
512 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
513 // but there is no such edge.
514 //
515 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
516
Sanjoy Das21434472016-08-14 01:04:46 +0000517 // Create the appropriate loop structure needed to describe a cloned copy of
518 // `Original`. The clone is described by `VM`.
519 Loop *createClonedLoopStructure(Loop *Original, Loop *Parent,
520 ValueToValueMapTy &VM);
521
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000522 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
523 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
524 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
525 // `OriginalHeaderCount'.
526 //
527 // If there are iterations left to execute, control is made to jump to
528 // `ContinuationBlock', otherwise they take the normal loop exit. The
529 // returned `RewrittenRangeInfo' object is populated as follows:
530 //
531 // .PseudoExit is a basic block that unconditionally branches to
532 // `ContinuationBlock'.
533 //
534 // .ExitSelector is a basic block that decides, on exit from the loop,
535 // whether to branch to the "true" exit or to `PseudoExit'.
536 //
537 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
538 // for each PHINode in the loop header on taking the pseudo exit.
539 //
540 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
541 // preheader because it is made to branch to the loop header only
542 // conditionally.
543 //
544 RewrittenRangeInfo
545 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
546 Value *ExitLoopAt,
547 BasicBlock *ContinuationBlock) const;
548
549 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
550 // function creates a new preheader for `LS' and returns it.
551 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000552 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
553 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000554
555 // `ContinuationBlockAndPreheader' was the continuation block for some call to
556 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
557 // This function rewrites the PHI nodes in `LS.Header' to start with the
558 // correct value.
559 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000560 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000561 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
562
563 // Even though we do not preserve any passes at this time, we at least need to
564 // keep the parent loop structure consistent. The `LPPassManager' seems to
565 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000566 // blocks denoted by BBs to this loops parent loop if required.
567 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000568
569 // Some global state.
570 Function &F;
571 LLVMContext &Ctx;
572 ScalarEvolution &SE;
Sanjoy Dasf45e03e2016-08-02 19:31:54 +0000573 DominatorTree &DT;
Sanjoy Das21434472016-08-14 01:04:46 +0000574 LPPassManager &LPM;
Sanjoy Das35459f02016-08-14 01:04:50 +0000575 LoopInfo &LI;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000576
577 // Information about the original loop we started out with.
578 Loop &OriginalLoop;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000579 const SCEV *LatchTakenCount;
580 BasicBlock *OriginalPreheader;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000581
582 // The preheader of the main loop. This may or may not be different from
583 // `OriginalPreheader'.
584 BasicBlock *MainLoopPreheader;
585
586 // The range we need to run the main loop in.
587 InductiveRangeCheck::Range Range;
588
589 // The structure of the main loop (see comment at the beginning of this class
590 // for a definition)
591 LoopStructure MainLoopStructure;
592
593public:
Sanjoy Das21434472016-08-14 01:04:46 +0000594 LoopConstrainer(Loop &L, LoopInfo &LI, LPPassManager &LPM,
595 const LoopStructure &LS, ScalarEvolution &SE,
596 DominatorTree &DT, InductiveRangeCheck::Range R)
Sanjoy Dase75ed922015-02-26 08:19:31 +0000597 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
Sanjoy Das35459f02016-08-14 01:04:50 +0000598 SE(SE), DT(DT), LPM(LPM), LI(LI), OriginalLoop(L),
Sanjoy Das21434472016-08-14 01:04:46 +0000599 LatchTakenCount(nullptr), OriginalPreheader(nullptr),
600 MainLoopPreheader(nullptr), Range(R), MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000601
602 // Entry point for the algorithm. Returns true on success.
603 bool run();
604};
605
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000606}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000607
608void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
609 BasicBlock *ReplaceBy) {
610 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
611 if (PN->getIncomingBlock(i) == Block)
612 PN->setIncomingBlock(i, ReplaceBy);
613}
614
Sanjoy Dase75ed922015-02-26 08:19:31 +0000615static bool CanBeSMax(ScalarEvolution &SE, const SCEV *S) {
616 APInt SMax =
617 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
618 return SE.getSignedRange(S).contains(SMax) &&
619 SE.getUnsignedRange(S).contains(SMax);
620}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000621
Sanjoy Dase75ed922015-02-26 08:19:31 +0000622static bool CanBeSMin(ScalarEvolution &SE, const SCEV *S) {
623 APInt SMin =
624 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth());
625 return SE.getSignedRange(S).contains(SMin) &&
626 SE.getUnsignedRange(S).contains(SMin);
627}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000628
Sanjoy Dase75ed922015-02-26 08:19:31 +0000629Optional<LoopStructure>
Sanjoy Dase91665d2015-02-26 08:56:04 +0000630LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI,
631 Loop &L, const char *&FailureReason) {
Sanjoy Das43fdc542016-08-14 01:04:31 +0000632 if (!L.isLoopSimplifyForm()) {
633 FailureReason = "loop not in LoopSimplify form";
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000634 return None;
Sanjoy Das43fdc542016-08-14 01:04:31 +0000635 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000636
637 BasicBlock *Latch = L.getLoopLatch();
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000638 assert(Latch && "Simplified loops only have one latch!");
639
Sanjoy Das7a18a232016-08-14 01:04:36 +0000640 if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) {
641 FailureReason = "loop has already been cloned";
642 return None;
643 }
644
Sanjoy Dase75ed922015-02-26 08:19:31 +0000645 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000646 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000647 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000648 }
649
Sanjoy Dase75ed922015-02-26 08:19:31 +0000650 BasicBlock *Header = L.getHeader();
651 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000652 if (!Preheader) {
653 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000654 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000655 }
656
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000657 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000658 if (!LatchBr || LatchBr->isUnconditional()) {
659 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000660 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000661 }
662
Sanjoy Dase75ed922015-02-26 08:19:31 +0000663 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000664
Sanjoy Dase91665d2015-02-26 08:56:04 +0000665 BranchProbability ExitProbability =
666 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
667
Sanjoy Dasbb969792016-07-22 00:40:56 +0000668 if (!SkipProfitabilityChecks &&
669 ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
Sanjoy Dase91665d2015-02-26 08:56:04 +0000670 FailureReason = "short running loop, not profitable";
671 return None;
672 }
673
Sanjoy Dase75ed922015-02-26 08:19:31 +0000674 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
675 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
676 FailureReason = "latch terminator branch not conditional on integral icmp";
677 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000678 }
679
Sanjoy Dase75ed922015-02-26 08:19:31 +0000680 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
681 if (isa<SCEVCouldNotCompute>(LatchCount)) {
682 FailureReason = "could not compute latch count";
683 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000684 }
685
Sanjoy Dase75ed922015-02-26 08:19:31 +0000686 ICmpInst::Predicate Pred = ICI->getPredicate();
687 Value *LeftValue = ICI->getOperand(0);
688 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
689 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
690
691 Value *RightValue = ICI->getOperand(1);
692 const SCEV *RightSCEV = SE.getSCEV(RightValue);
693
694 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
695 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
696 if (isa<SCEVAddRecExpr>(RightSCEV)) {
697 std::swap(LeftSCEV, RightSCEV);
698 std::swap(LeftValue, RightValue);
699 Pred = ICmpInst::getSwappedPredicate(Pred);
700 } else {
701 FailureReason = "no add recurrences in the icmp";
702 return None;
703 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000704 }
705
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000706 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
707 if (AR->getNoWrapFlags(SCEV::FlagNSW))
708 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000709
710 IntegerType *Ty = cast<IntegerType>(AR->getType());
711 IntegerType *WideTy =
712 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
713
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000714 const SCEVAddRecExpr *ExtendAfterOp =
715 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
716 if (ExtendAfterOp) {
717 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
718 const SCEV *ExtendedStep =
719 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
720
721 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
722 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
723
724 if (NoSignedWrap)
725 return true;
726 }
727
728 // We may have proved this when computing the sign extension above.
729 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
730 };
731
732 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing) {
733 if (!AR->isAffine())
734 return false;
735
Sanjoy Dase75ed922015-02-26 08:19:31 +0000736 // Currently we only work with induction variables that have been proved to
737 // not wrap. This restriction can potentially be lifted in the future.
738
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000739 if (!HasNoSignedWrap(AR))
Sanjoy Dase75ed922015-02-26 08:19:31 +0000740 return false;
741
742 if (const SCEVConstant *StepExpr =
743 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
744 ConstantInt *StepCI = StepExpr->getValue();
745 if (StepCI->isOne() || StepCI->isMinusOne()) {
746 IsIncreasing = StepCI->isOne();
747 return true;
748 }
749 }
750
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000751 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000752 };
753
754 // `ICI` is interpreted as taking the backedge if the *next* value of the
755 // induction variable satisfies some constraint.
756
757 const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
758 bool IsIncreasing = false;
759 if (!IsInductionVar(IndVarNext, IsIncreasing)) {
760 FailureReason = "LHS in icmp not induction variable";
761 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000762 }
763
Sanjoy Dase75ed922015-02-26 08:19:31 +0000764 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
765 // TODO: generalize the predicates here to also match their unsigned variants.
766 if (IsIncreasing) {
767 bool FoundExpectedPred =
768 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) ||
769 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0);
770
771 if (!FoundExpectedPred) {
772 FailureReason = "expected icmp slt semantically, found something else";
773 return None;
774 }
775
776 if (LatchBrExitIdx == 0) {
777 if (CanBeSMax(SE, RightSCEV)) {
778 // TODO: this restriction is easily removable -- we just have to
779 // remember that the icmp was an slt and not an sle.
780 FailureReason = "limit may overflow when coercing sle to slt";
781 return None;
782 }
783
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000784 IRBuilder<> B(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000785 RightValue = B.CreateAdd(RightValue, One);
786 }
787
788 } else {
789 bool FoundExpectedPred =
790 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) ||
791 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0);
792
793 if (!FoundExpectedPred) {
794 FailureReason = "expected icmp sgt semantically, found something else";
795 return None;
796 }
797
798 if (LatchBrExitIdx == 0) {
799 if (CanBeSMin(SE, RightSCEV)) {
800 // TODO: this restriction is easily removable -- we just have to
801 // remember that the icmp was an sgt and not an sge.
802 FailureReason = "limit may overflow when coercing sge to sgt";
803 return None;
804 }
805
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000806 IRBuilder<> B(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000807 RightValue = B.CreateSub(RightValue, One);
808 }
809 }
810
811 const SCEV *StartNext = IndVarNext->getStart();
812 const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
813 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
814
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000815 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
816
Sanjoy Dase75ed922015-02-26 08:19:31 +0000817 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000818 ScalarEvolution::LoopInvariant &&
819 "loop variant exit count doesn't make sense!");
820
Sanjoy Dase75ed922015-02-26 08:19:31 +0000821 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000822 const DataLayout &DL = Preheader->getModule()->getDataLayout();
823 Value *IndVarStartV =
824 SCEVExpander(SE, DL, "irce")
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000825 .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000826 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000827
Sanjoy Dase75ed922015-02-26 08:19:31 +0000828 LoopStructure Result;
829
830 Result.Tag = "main";
831 Result.Header = Header;
832 Result.Latch = Latch;
833 Result.LatchBr = LatchBr;
834 Result.LatchExit = LatchExit;
835 Result.LatchBrExitIdx = LatchBrExitIdx;
836 Result.IndVarStart = IndVarStartV;
837 Result.IndVarNext = LeftValue;
838 Result.IndVarIncreasing = IsIncreasing;
839 Result.LoopExitAt = RightValue;
840
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000841 FailureReason = nullptr;
842
Sanjoy Dase75ed922015-02-26 08:19:31 +0000843 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000844}
845
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000846Optional<LoopConstrainer::SubRanges>
Sanjoy Dase75ed922015-02-26 08:19:31 +0000847LoopConstrainer::calculateSubRanges() const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000848 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
849
Sanjoy Das351db052015-01-22 09:32:02 +0000850 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000851 return None;
852
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000853 LoopConstrainer::SubRanges Result;
854
855 // I think we can be more aggressive here and make this nuw / nsw if the
856 // addition that feeds into the icmp for the latch's terminating branch is nuw
857 // / nsw. In any case, a wrapping 2's complement addition is safe.
858 ConstantInt *One = ConstantInt::get(Ty, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000859 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
860 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000861
Sanjoy Dase75ed922015-02-26 08:19:31 +0000862 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000863
Sanjoy Dase75ed922015-02-26 08:19:31 +0000864 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the
865 // range of values the induction variable takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000866
867 const SCEV *Smallest = nullptr, *Greatest = nullptr;
868
869 if (Increasing) {
870 Smallest = Start;
871 Greatest = End;
872 } else {
873 // These two computations may sign-overflow. Here is why that is okay:
874 //
875 // We know that the induction variable does not sign-overflow on any
876 // iteration except the last one, and it starts at `Start` and ends at
877 // `End`, decrementing by one every time.
878 //
879 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
880 // induction variable is decreasing we know that that the smallest value
881 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
882 //
883 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
884 // that case, `Clamp` will always return `Smallest` and
885 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
886 // will be an empty range. Returning an empty range is always safe.
887 //
888
889 Smallest = SE.getAddExpr(End, SE.getSCEV(One));
890 Greatest = SE.getAddExpr(Start, SE.getSCEV(One));
891 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000892
893 auto Clamp = [this, Smallest, Greatest](const SCEV *S) {
894 return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S));
895 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000896
897 // In some cases we can prove that we don't need a pre or post loop
898
899 bool ProvablyNoPreloop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000900 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest);
901 if (!ProvablyNoPreloop)
902 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000903
904 bool ProvablyNoPostLoop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000905 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd());
906 if (!ProvablyNoPostLoop)
907 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000908
909 return Result;
910}
911
912void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
913 const char *Tag) const {
914 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
915 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
916 Result.Blocks.push_back(Clone);
917 Result.Map[BB] = Clone;
918 }
919
920 auto GetClonedValue = [&Result](Value *V) {
921 assert(V && "null values not in domain!");
922 auto It = Result.Map.find(V);
923 if (It == Result.Map.end())
924 return V;
925 return static_cast<Value *>(It->second);
926 };
927
Sanjoy Das7a18a232016-08-14 01:04:36 +0000928 auto *ClonedLatch =
929 cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch()));
930 ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag,
931 MDNode::get(Ctx, {}));
932
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000933 Result.Structure = MainLoopStructure.map(GetClonedValue);
934 Result.Structure.Tag = Tag;
935
936 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
937 BasicBlock *ClonedBB = Result.Blocks[i];
938 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
939
940 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
941
942 for (Instruction &I : *ClonedBB)
943 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000944 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000945
946 // Exit blocks will now have one more predecessor and their PHI nodes need
947 // to be edited to reflect that. No phi nodes need to be introduced because
948 // the loop is in LCSSA.
949
Sanjoy Dasd1d62a12016-08-13 22:00:09 +0000950 for (auto *SBB : successors(OriginalBB)) {
951 if (OriginalLoop.contains(SBB))
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000952 continue; // not an exit block
953
Sanjoy Dasd1d62a12016-08-13 22:00:09 +0000954 for (Instruction &I : *SBB) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +0000955 auto *PN = dyn_cast<PHINode>(&I);
956 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000957 break;
958
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000959 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
960 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
961 }
962 }
963 }
964}
965
966LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000967 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000968 BasicBlock *ContinuationBlock) const {
969
970 // We start with a loop with a single latch:
971 //
972 // +--------------------+
973 // | |
974 // | preheader |
975 // | |
976 // +--------+-----------+
977 // | ----------------\
978 // | / |
979 // +--------v----v------+ |
980 // | | |
981 // | header | |
982 // | | |
983 // +--------------------+ |
984 // |
985 // ..... |
986 // |
987 // +--------------------+ |
988 // | | |
989 // | latch >----------/
990 // | |
991 // +-------v------------+
992 // |
993 // |
994 // | +--------------------+
995 // | | |
996 // +---> original exit |
997 // | |
998 // +--------------------+
999 //
1000 // We change the control flow to look like
1001 //
1002 //
1003 // +--------------------+
1004 // | |
1005 // | preheader >-------------------------+
1006 // | | |
1007 // +--------v-----------+ |
1008 // | /-------------+ |
1009 // | / | |
1010 // +--------v--v--------+ | |
1011 // | | | |
1012 // | header | | +--------+ |
1013 // | | | | | |
1014 // +--------------------+ | | +-----v-----v-----------+
1015 // | | | |
1016 // | | | .pseudo.exit |
1017 // | | | |
1018 // | | +-----------v-----------+
1019 // | | |
1020 // ..... | | |
1021 // | | +--------v-------------+
1022 // +--------------------+ | | | |
1023 // | | | | | ContinuationBlock |
1024 // | latch >------+ | | |
1025 // | | | +----------------------+
1026 // +---------v----------+ |
1027 // | |
1028 // | |
1029 // | +---------------^-----+
1030 // | | |
1031 // +-----> .exit.selector |
1032 // | |
1033 // +----------v----------+
1034 // |
1035 // +--------------------+ |
1036 // | | |
1037 // | original exit <----+
1038 // | |
1039 // +--------------------+
1040 //
1041
1042 RewrittenRangeInfo RRI;
1043
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001044 BasicBlock *BBInsertLocation = LS.Latch->getNextNode();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001045 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001046 &F, BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001047 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001048 BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001049
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001050 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001051 bool Increasing = LS.IndVarIncreasing;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001052
1053 IRBuilder<> B(PreheaderJump);
1054
1055 // EnterLoopCond - is it okay to start executing this `LS'?
Sanjoy Dase75ed922015-02-26 08:19:31 +00001056 Value *EnterLoopCond = Increasing
1057 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1058 : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt);
1059
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001060 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1061 PreheaderJump->eraseFromParent();
1062
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001063 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001064 B.SetInsertPoint(LS.LatchBr);
1065 Value *TakeBackedgeLoopCond =
1066 Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1067 : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt);
1068 Value *CondForBranch = LS.LatchBrExitIdx == 1
1069 ? TakeBackedgeLoopCond
1070 : B.CreateNot(TakeBackedgeLoopCond);
1071
1072 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001073
1074 B.SetInsertPoint(RRI.ExitSelector);
1075
1076 // IterationsLeft - are there any more iterations left, given the original
1077 // upper bound on the induction variable? If not, we branch to the "real"
1078 // exit.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001079 Value *IterationsLeft = Increasing
1080 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1081 : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001082 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1083
1084 BranchInst *BranchToContinuation =
1085 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1086
1087 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1088 // each of the PHI nodes in the loop header. This feeds into the initial
1089 // value of the same PHI nodes if/when we continue execution.
1090 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001091 auto *PN = dyn_cast<PHINode>(&I);
1092 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001093 break;
1094
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001095 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1096 BranchToContinuation);
1097
1098 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1099 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1100 RRI.ExitSelector);
1101 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1102 }
1103
Sanjoy Dase75ed922015-02-26 08:19:31 +00001104 RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1105 BranchToContinuation);
1106 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1107 RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1108
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001109 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1110 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1111 for (Instruction &I : *LS.LatchExit) {
1112 if (PHINode *PN = dyn_cast<PHINode>(&I))
1113 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1114 else
1115 break;
1116 }
1117
1118 return RRI;
1119}
1120
1121void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001122 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001123 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1124
1125 unsigned PHIIndex = 0;
1126 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001127 auto *PN = dyn_cast<PHINode>(&I);
1128 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001129 break;
1130
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001131 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1132 if (PN->getIncomingBlock(i) == ContinuationBlock)
1133 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1134 }
1135
Sanjoy Dase75ed922015-02-26 08:19:31 +00001136 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001137}
1138
Sanjoy Dase75ed922015-02-26 08:19:31 +00001139BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1140 BasicBlock *OldPreheader,
1141 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001142
1143 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1144 BranchInst::Create(LS.Header, Preheader);
1145
1146 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001147 auto *PN = dyn_cast<PHINode>(&I);
1148 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001149 break;
1150
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001151 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1152 replacePHIBlock(PN, OldPreheader, Preheader);
1153 }
1154
1155 return Preheader;
1156}
1157
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001158void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001159 Loop *ParentLoop = OriginalLoop.getParentLoop();
1160 if (!ParentLoop)
1161 return;
1162
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001163 for (BasicBlock *BB : BBs)
Sanjoy Das83a72852016-08-02 19:32:01 +00001164 ParentLoop->addBasicBlockToLoop(BB, LI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001165}
1166
Sanjoy Das21434472016-08-14 01:04:46 +00001167Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent,
1168 ValueToValueMapTy &VM) {
1169 Loop &New = LPM.addLoop(Parent);
1170
1171 // Add all of the blocks in Original to the new loop.
1172 for (auto *BB : Original->blocks())
1173 if (LI.getLoopFor(BB) == Original)
1174 New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI);
1175
1176 // Add all of the subloops to the new loop.
1177 for (Loop *SubLoop : *Original)
1178 createClonedLoopStructure(SubLoop, &New, VM);
1179
1180 return &New;
1181}
1182
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001183bool LoopConstrainer::run() {
1184 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001185 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1186 Preheader = OriginalLoop.getLoopPreheader();
1187 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1188 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001189
1190 OriginalPreheader = Preheader;
1191 MainLoopPreheader = Preheader;
1192
Sanjoy Dase75ed922015-02-26 08:19:31 +00001193 Optional<SubRanges> MaybeSR = calculateSubRanges();
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001194 if (!MaybeSR.hasValue()) {
1195 DEBUG(dbgs() << "irce: could not compute subranges\n");
1196 return false;
1197 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001198
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001199 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001200 bool Increasing = MainLoopStructure.IndVarIncreasing;
1201 IntegerType *IVTy =
1202 cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1203
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001204 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001205 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001206
1207 // It would have been better to make `PreLoop' and `PostLoop'
1208 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1209 // constructor.
1210 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001211 bool NeedsPreLoop =
1212 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1213 bool NeedsPostLoop =
1214 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1215
1216 Value *ExitPreLoopAt = nullptr;
1217 Value *ExitMainLoopAt = nullptr;
1218 const SCEVConstant *MinusOneS =
1219 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1220
1221 if (NeedsPreLoop) {
1222 const SCEV *ExitPreLoopAtSCEV = nullptr;
1223
1224 if (Increasing)
1225 ExitPreLoopAtSCEV = *SR.LowLimit;
1226 else {
1227 if (CanBeSMin(SE, *SR.HighLimit)) {
1228 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1229 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1230 << "\n");
1231 return false;
1232 }
1233 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1234 }
1235
1236 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1237 ExitPreLoopAt->setName("exit.preloop.at");
1238 }
1239
1240 if (NeedsPostLoop) {
1241 const SCEV *ExitMainLoopAtSCEV = nullptr;
1242
1243 if (Increasing)
1244 ExitMainLoopAtSCEV = *SR.HighLimit;
1245 else {
1246 if (CanBeSMin(SE, *SR.LowLimit)) {
1247 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1248 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1249 << "\n");
1250 return false;
1251 }
1252 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1253 }
1254
1255 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1256 ExitMainLoopAt->setName("exit.mainloop.at");
1257 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001258
1259 // We clone these ahead of time so that we don't have to deal with changing
1260 // and temporarily invalid IR as we transform the loops.
1261 if (NeedsPreLoop)
1262 cloneLoop(PreLoop, "preloop");
1263 if (NeedsPostLoop)
1264 cloneLoop(PostLoop, "postloop");
1265
1266 RewrittenRangeInfo PreLoopRRI;
1267
1268 if (NeedsPreLoop) {
1269 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1270 PreLoop.Structure.Header);
1271
1272 MainLoopPreheader =
1273 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001274 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1275 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001276 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1277 PreLoopRRI);
1278 }
1279
1280 BasicBlock *PostLoopPreheader = nullptr;
1281 RewrittenRangeInfo PostLoopRRI;
1282
1283 if (NeedsPostLoop) {
1284 PostLoopPreheader =
1285 createPreheader(PostLoop.Structure, Preheader, "postloop");
1286 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001287 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001288 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1289 PostLoopRRI);
1290 }
1291
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001292 BasicBlock *NewMainLoopPreheader =
1293 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1294 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1295 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1296 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001297
1298 // Some of the above may be nullptr, filter them out before passing to
1299 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001300 auto NewBlocksEnd =
1301 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001302
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001303 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001304
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001305 DT.recalculate(F);
Sanjoy Das21434472016-08-14 01:04:46 +00001306
1307 if (!PreLoop.Blocks.empty()) {
1308 auto *L = createClonedLoopStructure(
1309 &OriginalLoop, OriginalLoop.getParentLoop(), PreLoop.Map);
1310 formLCSSARecursively(*L, DT, &LI, &SE);
1311 simplifyLoop(L, &DT, &LI, &SE, nullptr, true);
1312 }
1313
1314 if (!PostLoop.Blocks.empty()) {
1315 auto *L = createClonedLoopStructure(
1316 &OriginalLoop, OriginalLoop.getParentLoop(), PostLoop.Map);
1317 formLCSSARecursively(*L, DT, &LI, &SE);
1318 simplifyLoop(L, &DT, &LI, &SE, nullptr, true);
1319 }
1320
Sanjoy Das83a72852016-08-02 19:32:01 +00001321 formLCSSARecursively(OriginalLoop, DT, &LI, &SE);
Sanjoy Dascf181862016-08-06 00:01:56 +00001322 simplifyLoop(&OriginalLoop, &DT, &LI, &SE, nullptr, true);
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001323
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001324 return true;
1325}
1326
Sanjoy Das95c476d2015-02-21 22:20:22 +00001327/// Computes and returns a range of values for the induction variable (IndVar)
1328/// in which the range check can be safely elided. If it cannot compute such a
1329/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001330Optional<InductiveRangeCheck::Range>
Sanjoy Das59776732016-05-21 02:31:51 +00001331InductiveRangeCheck::computeSafeIterationSpace(
1332 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001333 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1334 // variable, that may or may not exist as a real llvm::Value in the loop) and
1335 // this inductive range check is a range check on the "C + D * I" ("C" is
1336 // getOffset() and "D" is getScale()). We rewrite the value being range
1337 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1338 // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code
1339 // can be generalized as needed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001340 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001341 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001342 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001343 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1344 //
1345 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1346 // and subtractions are twos-complement wrapping and comparisons are signed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001347 //
1348 // Proof:
1349 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001350 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1351 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1352 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1353 // overflown.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001354 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001355 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1356 // Hence 0 <= (IndVar + M) < L
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001357
Sanjoy Das95c476d2015-02-21 22:20:22 +00001358 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1359 // 127, IndVar = 126 and L = -2 in an i8 world.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001360
Sanjoy Das95c476d2015-02-21 22:20:22 +00001361 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001362 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001363
Sanjoy Das95c476d2015-02-21 22:20:22 +00001364 const SCEV *A = IndVar->getStart();
1365 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1366 if (!B)
1367 return None;
1368
1369 const SCEV *C = getOffset();
1370 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1371 if (D != B)
1372 return None;
1373
1374 ConstantInt *ConstD = D->getValue();
1375 if (!(ConstD->isMinusOne() || ConstD->isOne()))
1376 return None;
1377
1378 const SCEV *M = SE.getMinusSCEV(C, A);
1379
1380 const SCEV *Begin = SE.getNegativeSCEV(M);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001381 const SCEV *UpperLimit = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001382
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001383 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1384 // We can potentially do much better here.
1385 if (Value *V = getLength()) {
1386 UpperLimit = SE.getSCEV(V);
1387 } else {
1388 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1389 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1390 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1391 }
1392
1393 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
Sanjoy Das351db052015-01-22 09:32:02 +00001394 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001395}
1396
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001397static Optional<InductiveRangeCheck::Range>
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001398IntersectRange(ScalarEvolution &SE,
1399 const Optional<InductiveRangeCheck::Range> &R1,
Sanjoy Das59776732016-05-21 02:31:51 +00001400 const InductiveRangeCheck::Range &R2) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001401 if (!R1.hasValue())
1402 return R2;
1403 auto &R1Value = R1.getValue();
1404
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001405 // TODO: we could widen the smaller range and have this work; but for now we
1406 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001407 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001408 return None;
1409
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001410 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1411 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1412
1413 return InductiveRangeCheck::Range(NewBegin, NewEnd);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001414}
1415
1416bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001417 if (skipLoop(L))
1418 return false;
1419
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001420 if (L->getBlocks().size() >= LoopSizeCutoff) {
1421 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1422 return false;
1423 }
1424
1425 BasicBlock *Preheader = L->getLoopPreheader();
1426 if (!Preheader) {
1427 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1428 return false;
1429 }
1430
1431 LLVMContext &Context = Preheader->getContext();
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001432 SmallVector<InductiveRangeCheck, 16> RangeChecks;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001433 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Cong Houab23bfb2015-07-15 22:48:29 +00001434 BranchProbabilityInfo &BPI =
1435 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001436
1437 for (auto BBI : L->getBlocks())
1438 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
Sanjoy Dasa0992682016-05-26 00:09:02 +00001439 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1440 RangeChecks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001441
1442 if (RangeChecks.empty())
1443 return false;
1444
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001445 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1446 OS << "irce: looking at loop "; L->print(OS);
1447 OS << "irce: loop has " << RangeChecks.size()
1448 << " inductive range checks: \n";
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001449 for (InductiveRangeCheck &IRC : RangeChecks)
1450 IRC.print(OS);
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001451 };
1452
1453 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1454
1455 if (PrintRangeChecks)
1456 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001457
Sanjoy Dase75ed922015-02-26 08:19:31 +00001458 const char *FailureReason = nullptr;
1459 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001460 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001461 if (!MaybeLoopStructure.hasValue()) {
1462 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1463 << "\n";);
1464 return false;
1465 }
1466 LoopStructure LS = MaybeLoopStructure.getValue();
1467 bool Increasing = LS.IndVarIncreasing;
1468 const SCEV *MinusOne =
1469 SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true);
1470 const SCEVAddRecExpr *IndVar =
1471 cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne));
1472
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001473 Optional<InductiveRangeCheck::Range> SafeIterRange;
1474 Instruction *ExprInsertPt = Preheader->getTerminator();
1475
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001476 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001477
1478 IRBuilder<> B(ExprInsertPt);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001479 for (InductiveRangeCheck &IRC : RangeChecks) {
1480 auto Result = IRC.computeSafeIterationSpace(SE, IndVar);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001481 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001482 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001483 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001484 if (MaybeSafeIterRange.hasValue()) {
1485 RangeChecksToEliminate.push_back(IRC);
1486 SafeIterRange = MaybeSafeIterRange.getValue();
1487 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001488 }
1489 }
1490
1491 if (!SafeIterRange.hasValue())
1492 return false;
1493
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001494 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Sanjoy Das21434472016-08-14 01:04:46 +00001495 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LPM,
1496 LS, SE, DT, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001497 bool Changed = LC.run();
1498
1499 if (Changed) {
1500 auto PrintConstrainedLoopInfo = [L]() {
1501 dbgs() << "irce: in function ";
1502 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1503 dbgs() << "constrained ";
1504 L->print(dbgs());
1505 };
1506
1507 DEBUG(PrintConstrainedLoopInfo());
1508
1509 if (PrintChangedLoops)
1510 PrintConstrainedLoopInfo();
1511
1512 // Optimize away the now-redundant range checks.
1513
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001514 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1515 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001516 ? ConstantInt::getTrue(Context)
1517 : ConstantInt::getFalse(Context);
Sanjoy Dasaa83c472016-05-23 22:16:45 +00001518 IRC.getCheckUse()->set(FoldedRangeCheck);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001519 }
1520 }
1521
1522 return Changed;
1523}
1524
1525Pass *llvm::createInductiveRangeCheckEliminationPass() {
1526 return new InductiveRangeCheckElimination;
1527}