blob: 8e81541c233786afc19457108e6d3dc650a139bf [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
Anna Thomas65ca8e92016-12-13 21:05:21 +0000402// Add metadata to the loop L to disable loop optimizations. Callers need to
403// confirm that optimizing loop L is not beneficial.
404static void DisableAllLoopOptsOnLoop(Loop &L) {
405 // We do not care about any existing loopID related metadata for L, since we
406 // are setting all loop metadata to false.
407 LLVMContext &Context = L.getHeader()->getContext();
408 // Reserve first location for self reference to the LoopID metadata node.
409 MDNode *Dummy = MDNode::get(Context, {});
410 MDNode *DisableUnroll = MDNode::get(
411 Context, {MDString::get(Context, "llvm.loop.unroll.disable")});
412 Metadata *FalseVal =
413 ConstantAsMetadata::get(ConstantInt::get(Type::getInt1Ty(Context), 0));
414 MDNode *DisableVectorize = MDNode::get(
415 Context,
416 {MDString::get(Context, "llvm.loop.vectorize.enable"), FalseVal});
417 MDNode *DisableLICMVersioning = MDNode::get(
418 Context, {MDString::get(Context, "llvm.loop.licm_versioning.disable")});
419 MDNode *DisableDistribution= MDNode::get(
420 Context,
421 {MDString::get(Context, "llvm.loop.distribute.enable"), FalseVal});
422 MDNode *NewLoopID =
423 MDNode::get(Context, {Dummy, DisableUnroll, DisableVectorize,
424 DisableLICMVersioning, DisableDistribution});
425 // Set operand 0 to refer to the loop id itself.
426 NewLoopID->replaceOperandWith(0, NewLoopID);
427 L.setLoopID(NewLoopID);
428}
429
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000430namespace {
431
Sanjoy Dase75ed922015-02-26 08:19:31 +0000432// Keeps track of the structure of a loop. This is similar to llvm::Loop,
433// except that it is more lightweight and can track the state of a loop through
434// changing and potentially invalid IR. This structure also formalizes the
435// kinds of loops we can deal with -- ones that have a single latch that is also
436// an exiting block *and* have a canonical induction variable.
437struct LoopStructure {
438 const char *Tag;
439
440 BasicBlock *Header;
441 BasicBlock *Latch;
442
443 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
444 // successor is `LatchExit', the exit block of the loop.
445 BranchInst *LatchBr;
446 BasicBlock *LatchExit;
447 unsigned LatchBrExitIdx;
448
449 Value *IndVarNext;
450 Value *IndVarStart;
451 Value *LoopExitAt;
452 bool IndVarIncreasing;
453
454 LoopStructure()
455 : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr),
456 LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr),
457 IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false) {}
458
459 template <typename M> LoopStructure map(M Map) const {
460 LoopStructure Result;
461 Result.Tag = Tag;
462 Result.Header = cast<BasicBlock>(Map(Header));
463 Result.Latch = cast<BasicBlock>(Map(Latch));
464 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
465 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
466 Result.LatchBrExitIdx = LatchBrExitIdx;
467 Result.IndVarNext = Map(IndVarNext);
468 Result.IndVarStart = Map(IndVarStart);
469 Result.LoopExitAt = Map(LoopExitAt);
470 Result.IndVarIncreasing = IndVarIncreasing;
471 return Result;
472 }
473
Sanjoy Dase91665d2015-02-26 08:56:04 +0000474 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
475 BranchProbabilityInfo &BPI,
476 Loop &,
Sanjoy Dase75ed922015-02-26 08:19:31 +0000477 const char *&);
478};
479
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000480/// This class is used to constrain loops to run within a given iteration space.
481/// The algorithm this class implements is given a Loop and a range [Begin,
482/// End). The algorithm then tries to break out a "main loop" out of the loop
483/// it is given in a way that the "main loop" runs with the induction variable
484/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
485/// loops to run any remaining iterations. The pre loop runs any iterations in
486/// which the induction variable is < Begin, and the post loop runs any
487/// iterations in which the induction variable is >= End.
488///
489class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000490 // The representation of a clone of the original loop we started out with.
491 struct ClonedLoop {
492 // The cloned blocks
493 std::vector<BasicBlock *> Blocks;
494
495 // `Map` maps values in the clonee into values in the cloned version
496 ValueToValueMapTy Map;
497
498 // An instance of `LoopStructure` for the cloned loop
499 LoopStructure Structure;
500 };
501
502 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
503 // more details on what these fields mean.
504 struct RewrittenRangeInfo {
505 BasicBlock *PseudoExit;
506 BasicBlock *ExitSelector;
507 std::vector<PHINode *> PHIValuesAtPseudoExit;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000508 PHINode *IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000509
Sanjoy Dase75ed922015-02-26 08:19:31 +0000510 RewrittenRangeInfo()
511 : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000512 };
513
514 // Calculated subranges we restrict the iteration space of the main loop to.
515 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000516 // these fields are computed. `LowLimit` is None if there is no restriction
517 // on low end of the restricted iteration space of the main loop. `HighLimit`
518 // is None if there is no restriction on high end of the restricted iteration
519 // space of the main loop.
520
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000521 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000522 Optional<const SCEV *> LowLimit;
523 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000524 };
525
526 // A utility function that does a `replaceUsesOfWith' on the incoming block
527 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
528 // incoming block list with `ReplaceBy'.
529 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
530 BasicBlock *ReplaceBy);
531
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000532 // Compute a safe set of limits for the main loop to run in -- effectively the
533 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000534 // Return None if unable to compute the set of subranges.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000535 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000536 Optional<SubRanges> calculateSubRanges() const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000537
538 // Clone `OriginalLoop' and return the result in CLResult. The IR after
539 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
540 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
541 // but there is no such edge.
542 //
543 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
544
Sanjoy Das21434472016-08-14 01:04:46 +0000545 // Create the appropriate loop structure needed to describe a cloned copy of
546 // `Original`. The clone is described by `VM`.
547 Loop *createClonedLoopStructure(Loop *Original, Loop *Parent,
548 ValueToValueMapTy &VM);
549
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000550 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
551 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
552 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
553 // `OriginalHeaderCount'.
554 //
555 // If there are iterations left to execute, control is made to jump to
556 // `ContinuationBlock', otherwise they take the normal loop exit. The
557 // returned `RewrittenRangeInfo' object is populated as follows:
558 //
559 // .PseudoExit is a basic block that unconditionally branches to
560 // `ContinuationBlock'.
561 //
562 // .ExitSelector is a basic block that decides, on exit from the loop,
563 // whether to branch to the "true" exit or to `PseudoExit'.
564 //
565 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
566 // for each PHINode in the loop header on taking the pseudo exit.
567 //
568 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
569 // preheader because it is made to branch to the loop header only
570 // conditionally.
571 //
572 RewrittenRangeInfo
573 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
574 Value *ExitLoopAt,
575 BasicBlock *ContinuationBlock) const;
576
577 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
578 // function creates a new preheader for `LS' and returns it.
579 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000580 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
581 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000582
583 // `ContinuationBlockAndPreheader' was the continuation block for some call to
584 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
585 // This function rewrites the PHI nodes in `LS.Header' to start with the
586 // correct value.
587 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000588 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000589 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
590
591 // Even though we do not preserve any passes at this time, we at least need to
592 // keep the parent loop structure consistent. The `LPPassManager' seems to
593 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000594 // blocks denoted by BBs to this loops parent loop if required.
595 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000596
597 // Some global state.
598 Function &F;
599 LLVMContext &Ctx;
600 ScalarEvolution &SE;
Sanjoy Dasf45e03e2016-08-02 19:31:54 +0000601 DominatorTree &DT;
Sanjoy Das21434472016-08-14 01:04:46 +0000602 LPPassManager &LPM;
Sanjoy Das35459f02016-08-14 01:04:50 +0000603 LoopInfo &LI;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000604
605 // Information about the original loop we started out with.
606 Loop &OriginalLoop;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000607 const SCEV *LatchTakenCount;
608 BasicBlock *OriginalPreheader;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000609
610 // The preheader of the main loop. This may or may not be different from
611 // `OriginalPreheader'.
612 BasicBlock *MainLoopPreheader;
613
614 // The range we need to run the main loop in.
615 InductiveRangeCheck::Range Range;
616
617 // The structure of the main loop (see comment at the beginning of this class
618 // for a definition)
619 LoopStructure MainLoopStructure;
620
621public:
Sanjoy Das21434472016-08-14 01:04:46 +0000622 LoopConstrainer(Loop &L, LoopInfo &LI, LPPassManager &LPM,
623 const LoopStructure &LS, ScalarEvolution &SE,
624 DominatorTree &DT, InductiveRangeCheck::Range R)
Sanjoy Dase75ed922015-02-26 08:19:31 +0000625 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
Sanjoy Das35459f02016-08-14 01:04:50 +0000626 SE(SE), DT(DT), LPM(LPM), LI(LI), OriginalLoop(L),
Sanjoy Das21434472016-08-14 01:04:46 +0000627 LatchTakenCount(nullptr), OriginalPreheader(nullptr),
628 MainLoopPreheader(nullptr), Range(R), MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000629
630 // Entry point for the algorithm. Returns true on success.
631 bool run();
632};
633
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000634}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000635
636void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
637 BasicBlock *ReplaceBy) {
638 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
639 if (PN->getIncomingBlock(i) == Block)
640 PN->setIncomingBlock(i, ReplaceBy);
641}
642
Sanjoy Dase75ed922015-02-26 08:19:31 +0000643static bool CanBeSMax(ScalarEvolution &SE, const SCEV *S) {
644 APInt SMax =
645 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
646 return SE.getSignedRange(S).contains(SMax) &&
647 SE.getUnsignedRange(S).contains(SMax);
648}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000649
Sanjoy Dase75ed922015-02-26 08:19:31 +0000650static bool CanBeSMin(ScalarEvolution &SE, const SCEV *S) {
651 APInt SMin =
652 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth());
653 return SE.getSignedRange(S).contains(SMin) &&
654 SE.getUnsignedRange(S).contains(SMin);
655}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000656
Sanjoy Dase75ed922015-02-26 08:19:31 +0000657Optional<LoopStructure>
Sanjoy Dase91665d2015-02-26 08:56:04 +0000658LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI,
659 Loop &L, const char *&FailureReason) {
Sanjoy Das43fdc542016-08-14 01:04:31 +0000660 if (!L.isLoopSimplifyForm()) {
661 FailureReason = "loop not in LoopSimplify form";
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000662 return None;
Sanjoy Das43fdc542016-08-14 01:04:31 +0000663 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000664
665 BasicBlock *Latch = L.getLoopLatch();
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000666 assert(Latch && "Simplified loops only have one latch!");
667
Sanjoy Das7a18a232016-08-14 01:04:36 +0000668 if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) {
669 FailureReason = "loop has already been cloned";
670 return None;
671 }
672
Sanjoy Dase75ed922015-02-26 08:19:31 +0000673 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000674 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000675 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000676 }
677
Sanjoy Dase75ed922015-02-26 08:19:31 +0000678 BasicBlock *Header = L.getHeader();
679 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000680 if (!Preheader) {
681 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000682 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000683 }
684
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000685 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000686 if (!LatchBr || LatchBr->isUnconditional()) {
687 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000688 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000689 }
690
Sanjoy Dase75ed922015-02-26 08:19:31 +0000691 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000692
Sanjoy Dase91665d2015-02-26 08:56:04 +0000693 BranchProbability ExitProbability =
694 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
695
Sanjoy Dasbb969792016-07-22 00:40:56 +0000696 if (!SkipProfitabilityChecks &&
697 ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
Sanjoy Dase91665d2015-02-26 08:56:04 +0000698 FailureReason = "short running loop, not profitable";
699 return None;
700 }
701
Sanjoy Dase75ed922015-02-26 08:19:31 +0000702 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
703 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
704 FailureReason = "latch terminator branch not conditional on integral icmp";
705 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000706 }
707
Sanjoy Dase75ed922015-02-26 08:19:31 +0000708 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
709 if (isa<SCEVCouldNotCompute>(LatchCount)) {
710 FailureReason = "could not compute latch count";
711 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000712 }
713
Sanjoy Dase75ed922015-02-26 08:19:31 +0000714 ICmpInst::Predicate Pred = ICI->getPredicate();
715 Value *LeftValue = ICI->getOperand(0);
716 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
717 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
718
719 Value *RightValue = ICI->getOperand(1);
720 const SCEV *RightSCEV = SE.getSCEV(RightValue);
721
722 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
723 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
724 if (isa<SCEVAddRecExpr>(RightSCEV)) {
725 std::swap(LeftSCEV, RightSCEV);
726 std::swap(LeftValue, RightValue);
727 Pred = ICmpInst::getSwappedPredicate(Pred);
728 } else {
729 FailureReason = "no add recurrences in the icmp";
730 return None;
731 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000732 }
733
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000734 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
735 if (AR->getNoWrapFlags(SCEV::FlagNSW))
736 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000737
738 IntegerType *Ty = cast<IntegerType>(AR->getType());
739 IntegerType *WideTy =
740 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
741
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000742 const SCEVAddRecExpr *ExtendAfterOp =
743 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
744 if (ExtendAfterOp) {
745 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
746 const SCEV *ExtendedStep =
747 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
748
749 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
750 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
751
752 if (NoSignedWrap)
753 return true;
754 }
755
756 // We may have proved this when computing the sign extension above.
757 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
758 };
759
760 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing) {
761 if (!AR->isAffine())
762 return false;
763
Sanjoy Dase75ed922015-02-26 08:19:31 +0000764 // Currently we only work with induction variables that have been proved to
765 // not wrap. This restriction can potentially be lifted in the future.
766
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000767 if (!HasNoSignedWrap(AR))
Sanjoy Dase75ed922015-02-26 08:19:31 +0000768 return false;
769
770 if (const SCEVConstant *StepExpr =
771 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
772 ConstantInt *StepCI = StepExpr->getValue();
773 if (StepCI->isOne() || StepCI->isMinusOne()) {
774 IsIncreasing = StepCI->isOne();
775 return true;
776 }
777 }
778
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000779 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000780 };
781
782 // `ICI` is interpreted as taking the backedge if the *next* value of the
783 // induction variable satisfies some constraint.
784
785 const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
786 bool IsIncreasing = false;
787 if (!IsInductionVar(IndVarNext, IsIncreasing)) {
788 FailureReason = "LHS in icmp not induction variable";
789 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000790 }
791
Sanjoy Dase75ed922015-02-26 08:19:31 +0000792 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
793 // TODO: generalize the predicates here to also match their unsigned variants.
794 if (IsIncreasing) {
795 bool FoundExpectedPred =
796 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) ||
797 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0);
798
799 if (!FoundExpectedPred) {
800 FailureReason = "expected icmp slt semantically, found something else";
801 return None;
802 }
803
804 if (LatchBrExitIdx == 0) {
805 if (CanBeSMax(SE, RightSCEV)) {
806 // TODO: this restriction is easily removable -- we just have to
807 // remember that the icmp was an slt and not an sle.
808 FailureReason = "limit may overflow when coercing sle to slt";
809 return None;
810 }
811
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000812 IRBuilder<> B(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000813 RightValue = B.CreateAdd(RightValue, One);
814 }
815
816 } else {
817 bool FoundExpectedPred =
818 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) ||
819 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0);
820
821 if (!FoundExpectedPred) {
822 FailureReason = "expected icmp sgt semantically, found something else";
823 return None;
824 }
825
826 if (LatchBrExitIdx == 0) {
827 if (CanBeSMin(SE, RightSCEV)) {
828 // TODO: this restriction is easily removable -- we just have to
829 // remember that the icmp was an sgt and not an sge.
830 FailureReason = "limit may overflow when coercing sge to sgt";
831 return None;
832 }
833
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000834 IRBuilder<> B(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000835 RightValue = B.CreateSub(RightValue, One);
836 }
837 }
838
839 const SCEV *StartNext = IndVarNext->getStart();
840 const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
841 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
842
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000843 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
844
Sanjoy Dase75ed922015-02-26 08:19:31 +0000845 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000846 ScalarEvolution::LoopInvariant &&
847 "loop variant exit count doesn't make sense!");
848
Sanjoy Dase75ed922015-02-26 08:19:31 +0000849 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000850 const DataLayout &DL = Preheader->getModule()->getDataLayout();
851 Value *IndVarStartV =
852 SCEVExpander(SE, DL, "irce")
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000853 .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000854 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000855
Sanjoy Dase75ed922015-02-26 08:19:31 +0000856 LoopStructure Result;
857
858 Result.Tag = "main";
859 Result.Header = Header;
860 Result.Latch = Latch;
861 Result.LatchBr = LatchBr;
862 Result.LatchExit = LatchExit;
863 Result.LatchBrExitIdx = LatchBrExitIdx;
864 Result.IndVarStart = IndVarStartV;
865 Result.IndVarNext = LeftValue;
866 Result.IndVarIncreasing = IsIncreasing;
867 Result.LoopExitAt = RightValue;
868
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000869 FailureReason = nullptr;
870
Sanjoy Dase75ed922015-02-26 08:19:31 +0000871 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000872}
873
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000874Optional<LoopConstrainer::SubRanges>
Sanjoy Dase75ed922015-02-26 08:19:31 +0000875LoopConstrainer::calculateSubRanges() const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000876 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
877
Sanjoy Das351db052015-01-22 09:32:02 +0000878 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000879 return None;
880
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000881 LoopConstrainer::SubRanges Result;
882
883 // I think we can be more aggressive here and make this nuw / nsw if the
884 // addition that feeds into the icmp for the latch's terminating branch is nuw
885 // / nsw. In any case, a wrapping 2's complement addition is safe.
886 ConstantInt *One = ConstantInt::get(Ty, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000887 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
888 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000889
Sanjoy Dase75ed922015-02-26 08:19:31 +0000890 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000891
Sanjoy Dase75ed922015-02-26 08:19:31 +0000892 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the
893 // range of values the induction variable takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000894
895 const SCEV *Smallest = nullptr, *Greatest = nullptr;
896
897 if (Increasing) {
898 Smallest = Start;
899 Greatest = End;
900 } else {
901 // These two computations may sign-overflow. Here is why that is okay:
902 //
903 // We know that the induction variable does not sign-overflow on any
904 // iteration except the last one, and it starts at `Start` and ends at
905 // `End`, decrementing by one every time.
906 //
907 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
908 // induction variable is decreasing we know that that the smallest value
909 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
910 //
911 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
912 // that case, `Clamp` will always return `Smallest` and
913 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
914 // will be an empty range. Returning an empty range is always safe.
915 //
916
917 Smallest = SE.getAddExpr(End, SE.getSCEV(One));
918 Greatest = SE.getAddExpr(Start, SE.getSCEV(One));
919 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000920
921 auto Clamp = [this, Smallest, Greatest](const SCEV *S) {
922 return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S));
923 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000924
925 // In some cases we can prove that we don't need a pre or post loop
926
927 bool ProvablyNoPreloop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000928 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest);
929 if (!ProvablyNoPreloop)
930 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000931
932 bool ProvablyNoPostLoop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000933 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd());
934 if (!ProvablyNoPostLoop)
935 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000936
937 return Result;
938}
939
940void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
941 const char *Tag) const {
942 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
943 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
944 Result.Blocks.push_back(Clone);
945 Result.Map[BB] = Clone;
946 }
947
948 auto GetClonedValue = [&Result](Value *V) {
949 assert(V && "null values not in domain!");
950 auto It = Result.Map.find(V);
951 if (It == Result.Map.end())
952 return V;
953 return static_cast<Value *>(It->second);
954 };
955
Sanjoy Das7a18a232016-08-14 01:04:36 +0000956 auto *ClonedLatch =
957 cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch()));
958 ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag,
959 MDNode::get(Ctx, {}));
960
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000961 Result.Structure = MainLoopStructure.map(GetClonedValue);
962 Result.Structure.Tag = Tag;
963
964 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
965 BasicBlock *ClonedBB = Result.Blocks[i];
966 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
967
968 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
969
970 for (Instruction &I : *ClonedBB)
971 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000972 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000973
974 // Exit blocks will now have one more predecessor and their PHI nodes need
975 // to be edited to reflect that. No phi nodes need to be introduced because
976 // the loop is in LCSSA.
977
Sanjoy Dasd1d62a12016-08-13 22:00:09 +0000978 for (auto *SBB : successors(OriginalBB)) {
979 if (OriginalLoop.contains(SBB))
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000980 continue; // not an exit block
981
Sanjoy Dasd1d62a12016-08-13 22:00:09 +0000982 for (Instruction &I : *SBB) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +0000983 auto *PN = dyn_cast<PHINode>(&I);
984 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000985 break;
986
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000987 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
988 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
989 }
990 }
991 }
992}
993
994LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000995 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000996 BasicBlock *ContinuationBlock) const {
997
998 // We start with a loop with a single latch:
999 //
1000 // +--------------------+
1001 // | |
1002 // | preheader |
1003 // | |
1004 // +--------+-----------+
1005 // | ----------------\
1006 // | / |
1007 // +--------v----v------+ |
1008 // | | |
1009 // | header | |
1010 // | | |
1011 // +--------------------+ |
1012 // |
1013 // ..... |
1014 // |
1015 // +--------------------+ |
1016 // | | |
1017 // | latch >----------/
1018 // | |
1019 // +-------v------------+
1020 // |
1021 // |
1022 // | +--------------------+
1023 // | | |
1024 // +---> original exit |
1025 // | |
1026 // +--------------------+
1027 //
1028 // We change the control flow to look like
1029 //
1030 //
1031 // +--------------------+
1032 // | |
1033 // | preheader >-------------------------+
1034 // | | |
1035 // +--------v-----------+ |
1036 // | /-------------+ |
1037 // | / | |
1038 // +--------v--v--------+ | |
1039 // | | | |
1040 // | header | | +--------+ |
1041 // | | | | | |
1042 // +--------------------+ | | +-----v-----v-----------+
1043 // | | | |
1044 // | | | .pseudo.exit |
1045 // | | | |
1046 // | | +-----------v-----------+
1047 // | | |
1048 // ..... | | |
1049 // | | +--------v-------------+
1050 // +--------------------+ | | | |
1051 // | | | | | ContinuationBlock |
1052 // | latch >------+ | | |
1053 // | | | +----------------------+
1054 // +---------v----------+ |
1055 // | |
1056 // | |
1057 // | +---------------^-----+
1058 // | | |
1059 // +-----> .exit.selector |
1060 // | |
1061 // +----------v----------+
1062 // |
1063 // +--------------------+ |
1064 // | | |
1065 // | original exit <----+
1066 // | |
1067 // +--------------------+
1068 //
1069
1070 RewrittenRangeInfo RRI;
1071
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001072 BasicBlock *BBInsertLocation = LS.Latch->getNextNode();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001073 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001074 &F, BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001075 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001076 BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001077
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001078 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001079 bool Increasing = LS.IndVarIncreasing;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001080
1081 IRBuilder<> B(PreheaderJump);
1082
1083 // EnterLoopCond - is it okay to start executing this `LS'?
Sanjoy Dase75ed922015-02-26 08:19:31 +00001084 Value *EnterLoopCond = Increasing
1085 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1086 : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt);
1087
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001088 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1089 PreheaderJump->eraseFromParent();
1090
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001091 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001092 B.SetInsertPoint(LS.LatchBr);
1093 Value *TakeBackedgeLoopCond =
1094 Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1095 : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt);
1096 Value *CondForBranch = LS.LatchBrExitIdx == 1
1097 ? TakeBackedgeLoopCond
1098 : B.CreateNot(TakeBackedgeLoopCond);
1099
1100 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001101
1102 B.SetInsertPoint(RRI.ExitSelector);
1103
1104 // IterationsLeft - are there any more iterations left, given the original
1105 // upper bound on the induction variable? If not, we branch to the "real"
1106 // exit.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001107 Value *IterationsLeft = Increasing
1108 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1109 : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001110 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1111
1112 BranchInst *BranchToContinuation =
1113 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1114
1115 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1116 // each of the PHI nodes in the loop header. This feeds into the initial
1117 // value of the same PHI nodes if/when we continue execution.
1118 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001119 auto *PN = dyn_cast<PHINode>(&I);
1120 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001121 break;
1122
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001123 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1124 BranchToContinuation);
1125
1126 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1127 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1128 RRI.ExitSelector);
1129 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1130 }
1131
Sanjoy Dase75ed922015-02-26 08:19:31 +00001132 RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1133 BranchToContinuation);
1134 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1135 RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1136
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001137 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1138 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1139 for (Instruction &I : *LS.LatchExit) {
1140 if (PHINode *PN = dyn_cast<PHINode>(&I))
1141 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1142 else
1143 break;
1144 }
1145
1146 return RRI;
1147}
1148
1149void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001150 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001151 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1152
1153 unsigned PHIIndex = 0;
1154 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001155 auto *PN = dyn_cast<PHINode>(&I);
1156 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001157 break;
1158
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001159 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1160 if (PN->getIncomingBlock(i) == ContinuationBlock)
1161 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1162 }
1163
Sanjoy Dase75ed922015-02-26 08:19:31 +00001164 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001165}
1166
Sanjoy Dase75ed922015-02-26 08:19:31 +00001167BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1168 BasicBlock *OldPreheader,
1169 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001170
1171 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1172 BranchInst::Create(LS.Header, Preheader);
1173
1174 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001175 auto *PN = dyn_cast<PHINode>(&I);
1176 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001177 break;
1178
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001179 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1180 replacePHIBlock(PN, OldPreheader, Preheader);
1181 }
1182
1183 return Preheader;
1184}
1185
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001186void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001187 Loop *ParentLoop = OriginalLoop.getParentLoop();
1188 if (!ParentLoop)
1189 return;
1190
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001191 for (BasicBlock *BB : BBs)
Sanjoy Das83a72852016-08-02 19:32:01 +00001192 ParentLoop->addBasicBlockToLoop(BB, LI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001193}
1194
Sanjoy Das21434472016-08-14 01:04:46 +00001195Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent,
1196 ValueToValueMapTy &VM) {
1197 Loop &New = LPM.addLoop(Parent);
1198
1199 // Add all of the blocks in Original to the new loop.
1200 for (auto *BB : Original->blocks())
1201 if (LI.getLoopFor(BB) == Original)
1202 New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI);
1203
1204 // Add all of the subloops to the new loop.
1205 for (Loop *SubLoop : *Original)
1206 createClonedLoopStructure(SubLoop, &New, VM);
1207
1208 return &New;
1209}
1210
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001211bool LoopConstrainer::run() {
1212 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001213 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1214 Preheader = OriginalLoop.getLoopPreheader();
1215 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1216 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001217
1218 OriginalPreheader = Preheader;
1219 MainLoopPreheader = Preheader;
1220
Sanjoy Dase75ed922015-02-26 08:19:31 +00001221 Optional<SubRanges> MaybeSR = calculateSubRanges();
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001222 if (!MaybeSR.hasValue()) {
1223 DEBUG(dbgs() << "irce: could not compute subranges\n");
1224 return false;
1225 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001226
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001227 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001228 bool Increasing = MainLoopStructure.IndVarIncreasing;
1229 IntegerType *IVTy =
1230 cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1231
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001232 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001233 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001234
1235 // It would have been better to make `PreLoop' and `PostLoop'
1236 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1237 // constructor.
1238 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001239 bool NeedsPreLoop =
1240 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1241 bool NeedsPostLoop =
1242 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1243
1244 Value *ExitPreLoopAt = nullptr;
1245 Value *ExitMainLoopAt = nullptr;
1246 const SCEVConstant *MinusOneS =
1247 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1248
1249 if (NeedsPreLoop) {
1250 const SCEV *ExitPreLoopAtSCEV = nullptr;
1251
1252 if (Increasing)
1253 ExitPreLoopAtSCEV = *SR.LowLimit;
1254 else {
1255 if (CanBeSMin(SE, *SR.HighLimit)) {
1256 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1257 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1258 << "\n");
1259 return false;
1260 }
1261 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1262 }
1263
1264 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1265 ExitPreLoopAt->setName("exit.preloop.at");
1266 }
1267
1268 if (NeedsPostLoop) {
1269 const SCEV *ExitMainLoopAtSCEV = nullptr;
1270
1271 if (Increasing)
1272 ExitMainLoopAtSCEV = *SR.HighLimit;
1273 else {
1274 if (CanBeSMin(SE, *SR.LowLimit)) {
1275 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1276 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1277 << "\n");
1278 return false;
1279 }
1280 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1281 }
1282
1283 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1284 ExitMainLoopAt->setName("exit.mainloop.at");
1285 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001286
1287 // We clone these ahead of time so that we don't have to deal with changing
1288 // and temporarily invalid IR as we transform the loops.
1289 if (NeedsPreLoop)
1290 cloneLoop(PreLoop, "preloop");
1291 if (NeedsPostLoop)
1292 cloneLoop(PostLoop, "postloop");
1293
1294 RewrittenRangeInfo PreLoopRRI;
1295
1296 if (NeedsPreLoop) {
1297 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1298 PreLoop.Structure.Header);
1299
1300 MainLoopPreheader =
1301 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001302 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1303 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001304 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1305 PreLoopRRI);
1306 }
1307
1308 BasicBlock *PostLoopPreheader = nullptr;
1309 RewrittenRangeInfo PostLoopRRI;
1310
1311 if (NeedsPostLoop) {
1312 PostLoopPreheader =
1313 createPreheader(PostLoop.Structure, Preheader, "postloop");
1314 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001315 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001316 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1317 PostLoopRRI);
1318 }
1319
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001320 BasicBlock *NewMainLoopPreheader =
1321 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1322 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1323 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1324 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001325
1326 // Some of the above may be nullptr, filter them out before passing to
1327 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001328 auto NewBlocksEnd =
1329 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001330
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001331 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001332
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001333 DT.recalculate(F);
Sanjoy Das21434472016-08-14 01:04:46 +00001334
1335 if (!PreLoop.Blocks.empty()) {
1336 auto *L = createClonedLoopStructure(
1337 &OriginalLoop, OriginalLoop.getParentLoop(), PreLoop.Map);
1338 formLCSSARecursively(*L, DT, &LI, &SE);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001339 simplifyLoop(L, &DT, &LI, &SE, nullptr, true);
Anna Thomas65ca8e92016-12-13 21:05:21 +00001340 // Pre loops are slow paths, we do not need to perform any loop
1341 // optimizations on them.
1342 DisableAllLoopOptsOnLoop(*L);
Sanjoy Das21434472016-08-14 01:04:46 +00001343 }
1344
1345 if (!PostLoop.Blocks.empty()) {
1346 auto *L = createClonedLoopStructure(
1347 &OriginalLoop, OriginalLoop.getParentLoop(), PostLoop.Map);
1348 formLCSSARecursively(*L, DT, &LI, &SE);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001349 simplifyLoop(L, &DT, &LI, &SE, nullptr, true);
Anna Thomas65ca8e92016-12-13 21:05:21 +00001350 // Post loops are slow paths, we do not need to perform any loop
1351 // optimizations on them.
1352 DisableAllLoopOptsOnLoop(*L);
Sanjoy Das21434472016-08-14 01:04:46 +00001353 }
1354
Sanjoy Das83a72852016-08-02 19:32:01 +00001355 formLCSSARecursively(OriginalLoop, DT, &LI, &SE);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001356 simplifyLoop(&OriginalLoop, &DT, &LI, &SE, nullptr, true);
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001357
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001358 return true;
1359}
1360
Sanjoy Das95c476d2015-02-21 22:20:22 +00001361/// Computes and returns a range of values for the induction variable (IndVar)
1362/// in which the range check can be safely elided. If it cannot compute such a
1363/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001364Optional<InductiveRangeCheck::Range>
Sanjoy Das59776732016-05-21 02:31:51 +00001365InductiveRangeCheck::computeSafeIterationSpace(
1366 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001367 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1368 // variable, that may or may not exist as a real llvm::Value in the loop) and
1369 // this inductive range check is a range check on the "C + D * I" ("C" is
1370 // getOffset() and "D" is getScale()). We rewrite the value being range
1371 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1372 // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code
1373 // can be generalized as needed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001374 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001375 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001376 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001377 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1378 //
1379 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1380 // and subtractions are twos-complement wrapping and comparisons are signed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001381 //
1382 // Proof:
1383 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001384 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1385 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1386 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1387 // overflown.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001388 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001389 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1390 // Hence 0 <= (IndVar + M) < L
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001391
Sanjoy Das95c476d2015-02-21 22:20:22 +00001392 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1393 // 127, IndVar = 126 and L = -2 in an i8 world.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001394
Sanjoy Das95c476d2015-02-21 22:20:22 +00001395 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001396 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001397
Sanjoy Das95c476d2015-02-21 22:20:22 +00001398 const SCEV *A = IndVar->getStart();
1399 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1400 if (!B)
1401 return None;
1402
1403 const SCEV *C = getOffset();
1404 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1405 if (D != B)
1406 return None;
1407
1408 ConstantInt *ConstD = D->getValue();
1409 if (!(ConstD->isMinusOne() || ConstD->isOne()))
1410 return None;
1411
1412 const SCEV *M = SE.getMinusSCEV(C, A);
1413
1414 const SCEV *Begin = SE.getNegativeSCEV(M);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001415 const SCEV *UpperLimit = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001416
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001417 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1418 // We can potentially do much better here.
1419 if (Value *V = getLength()) {
1420 UpperLimit = SE.getSCEV(V);
1421 } else {
1422 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1423 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1424 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1425 }
1426
1427 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
Sanjoy Das351db052015-01-22 09:32:02 +00001428 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001429}
1430
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001431static Optional<InductiveRangeCheck::Range>
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001432IntersectRange(ScalarEvolution &SE,
1433 const Optional<InductiveRangeCheck::Range> &R1,
Sanjoy Das59776732016-05-21 02:31:51 +00001434 const InductiveRangeCheck::Range &R2) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001435 if (!R1.hasValue())
1436 return R2;
1437 auto &R1Value = R1.getValue();
1438
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001439 // TODO: we could widen the smaller range and have this work; but for now we
1440 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001441 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001442 return None;
1443
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001444 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1445 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1446
1447 return InductiveRangeCheck::Range(NewBegin, NewEnd);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001448}
1449
1450bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001451 if (skipLoop(L))
1452 return false;
1453
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001454 if (L->getBlocks().size() >= LoopSizeCutoff) {
1455 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1456 return false;
1457 }
1458
1459 BasicBlock *Preheader = L->getLoopPreheader();
1460 if (!Preheader) {
1461 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1462 return false;
1463 }
1464
1465 LLVMContext &Context = Preheader->getContext();
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001466 SmallVector<InductiveRangeCheck, 16> RangeChecks;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001467 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Cong Houab23bfb2015-07-15 22:48:29 +00001468 BranchProbabilityInfo &BPI =
1469 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001470
1471 for (auto BBI : L->getBlocks())
1472 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
Sanjoy Dasa0992682016-05-26 00:09:02 +00001473 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1474 RangeChecks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001475
1476 if (RangeChecks.empty())
1477 return false;
1478
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001479 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1480 OS << "irce: looking at loop "; L->print(OS);
1481 OS << "irce: loop has " << RangeChecks.size()
1482 << " inductive range checks: \n";
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001483 for (InductiveRangeCheck &IRC : RangeChecks)
1484 IRC.print(OS);
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001485 };
1486
1487 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1488
1489 if (PrintRangeChecks)
1490 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001491
Sanjoy Dase75ed922015-02-26 08:19:31 +00001492 const char *FailureReason = nullptr;
1493 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001494 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001495 if (!MaybeLoopStructure.hasValue()) {
1496 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1497 << "\n";);
1498 return false;
1499 }
1500 LoopStructure LS = MaybeLoopStructure.getValue();
1501 bool Increasing = LS.IndVarIncreasing;
1502 const SCEV *MinusOne =
1503 SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true);
1504 const SCEVAddRecExpr *IndVar =
1505 cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne));
1506
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001507 Optional<InductiveRangeCheck::Range> SafeIterRange;
1508 Instruction *ExprInsertPt = Preheader->getTerminator();
1509
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001510 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001511
1512 IRBuilder<> B(ExprInsertPt);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001513 for (InductiveRangeCheck &IRC : RangeChecks) {
1514 auto Result = IRC.computeSafeIterationSpace(SE, IndVar);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001515 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001516 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001517 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001518 if (MaybeSafeIterRange.hasValue()) {
1519 RangeChecksToEliminate.push_back(IRC);
1520 SafeIterRange = MaybeSafeIterRange.getValue();
1521 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001522 }
1523 }
1524
1525 if (!SafeIterRange.hasValue())
1526 return false;
1527
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001528 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Sanjoy Das21434472016-08-14 01:04:46 +00001529 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LPM,
1530 LS, SE, DT, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001531 bool Changed = LC.run();
1532
1533 if (Changed) {
1534 auto PrintConstrainedLoopInfo = [L]() {
1535 dbgs() << "irce: in function ";
1536 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1537 dbgs() << "constrained ";
1538 L->print(dbgs());
1539 };
1540
1541 DEBUG(PrintConstrainedLoopInfo());
1542
1543 if (PrintChangedLoops)
1544 PrintConstrainedLoopInfo();
1545
1546 // Optimize away the now-redundant range checks.
1547
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001548 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1549 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001550 ? ConstantInt::getTrue(Context)
1551 : ConstantInt::getFalse(Context);
Sanjoy Dasaa83c472016-05-23 22:16:45 +00001552 IRC.getCheckUse()->set(FoldedRangeCheck);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001553 }
1554 }
1555
1556 return Changed;
1557}
1558
1559Pass *llvm::createInductiveRangeCheckEliminationPass() {
1560 return new InductiveRangeCheckElimination;
1561}