blob: cf67c00ae9c2e90d3ec6c035171cf37461aeec20 [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
154#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
155 void dump() {
156 print(dbgs());
157 }
158#endif
159
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000160 Use *getCheckUse() const { return CheckUse; }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000161
Sanjoy Das351db052015-01-22 09:32:02 +0000162 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
163 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
164
165 class Range {
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000166 const SCEV *Begin;
167 const SCEV *End;
Sanjoy Das351db052015-01-22 09:32:02 +0000168
169 public:
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000170 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
Sanjoy Das351db052015-01-22 09:32:02 +0000171 assert(Begin->getType() == End->getType() && "ill-typed range!");
172 }
173
174 Type *getType() const { return Begin->getType(); }
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000175 const SCEV *getBegin() const { return Begin; }
176 const SCEV *getEnd() const { return End; }
Sanjoy Das351db052015-01-22 09:32:02 +0000177 };
178
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000179 /// This is the value the condition of the branch needs to evaluate to for the
180 /// branch to take the hot successor (see (1) above).
181 bool getPassingDirection() { return true; }
182
Sanjoy Das95c476d2015-02-21 22:20:22 +0000183 /// Computes a range for the induction variable (IndVar) in which the range
184 /// check is redundant and can be constant-folded away. The induction
185 /// variable is not required to be the canonical {0,+,1} induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000186 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
Sanjoy Das59776732016-05-21 02:31:51 +0000187 const SCEVAddRecExpr *IndVar) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000188
Sanjoy Dasa0992682016-05-26 00:09:02 +0000189 /// Parse out a set of inductive range checks from \p BI and append them to \p
190 /// Checks.
191 ///
192 /// NB! There may be conditions feeding into \p BI that aren't inductive range
193 /// checks, and hence don't end up in \p Checks.
194 static void
195 extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE,
196 BranchProbabilityInfo &BPI,
197 SmallVectorImpl<InductiveRangeCheck> &Checks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000198};
199
200class InductiveRangeCheckElimination : public LoopPass {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000201public:
202 static char ID;
203 InductiveRangeCheckElimination() : LoopPass(ID) {
204 initializeInductiveRangeCheckEliminationPass(
205 *PassRegistry::getPassRegistry());
206 }
207
208 void getAnalysisUsage(AnalysisUsage &AU) const override {
Cong Houab23bfb2015-07-15 22:48:29 +0000209 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000210 getLoopAnalysisUsage(AU);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000211 }
212
213 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
214};
215
216char InductiveRangeCheckElimination::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000217}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000218
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000219INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce",
220 "Inductive range check elimination", false, false)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000221INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000222INITIALIZE_PASS_DEPENDENCY(LoopPass)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000223INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce",
224 "Inductive range check elimination", false, false)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000225
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000226StringRef InductiveRangeCheck::rangeCheckKindToStr(
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000227 InductiveRangeCheck::RangeCheckKind RCK) {
228 switch (RCK) {
229 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
230 return "RANGE_CHECK_UNKNOWN";
231
232 case InductiveRangeCheck::RANGE_CHECK_UPPER:
233 return "RANGE_CHECK_UPPER";
234
235 case InductiveRangeCheck::RANGE_CHECK_LOWER:
236 return "RANGE_CHECK_LOWER";
237
238 case InductiveRangeCheck::RANGE_CHECK_BOTH:
239 return "RANGE_CHECK_BOTH";
240 }
241
242 llvm_unreachable("unknown range check type!");
243}
244
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000245/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000246/// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000247/// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000248/// range checked, and set `Length` to the upper limit `Index` is being range
249/// checked with if (and only if) the range check type is stronger or equal to
250/// RANGE_CHECK_UPPER.
251///
252InductiveRangeCheck::RangeCheckKind
Sanjoy Das337d46b2015-03-24 19:29:18 +0000253InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
254 ScalarEvolution &SE, Value *&Index,
255 Value *&Length) {
256
257 auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) {
258 const SCEV *S = SE.getSCEV(V);
259 if (isa<SCEVCouldNotCompute>(S))
260 return false;
261
262 return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant &&
263 SE.isKnownNonNegative(S);
264 };
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000265
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000266 using namespace llvm::PatternMatch;
267
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000268 ICmpInst::Predicate Pred = ICI->getPredicate();
269 Value *LHS = ICI->getOperand(0);
270 Value *RHS = ICI->getOperand(1);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000271
272 switch (Pred) {
273 default:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000274 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000275
276 case ICmpInst::ICMP_SLE:
277 std::swap(LHS, RHS);
278 // fallthrough
279 case ICmpInst::ICMP_SGE:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000280 if (match(RHS, m_ConstantInt<0>())) {
281 Index = LHS;
282 return RANGE_CHECK_LOWER;
283 }
284 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000285
286 case ICmpInst::ICMP_SLT:
287 std::swap(LHS, RHS);
288 // fallthrough
289 case ICmpInst::ICMP_SGT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000290 if (match(RHS, m_ConstantInt<-1>())) {
291 Index = LHS;
292 return RANGE_CHECK_LOWER;
293 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000294
Sanjoy Das337d46b2015-03-24 19:29:18 +0000295 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000296 Index = RHS;
297 Length = LHS;
298 return RANGE_CHECK_UPPER;
299 }
300 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000301
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000302 case ICmpInst::ICMP_ULT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000303 std::swap(LHS, RHS);
304 // fallthrough
305 case ICmpInst::ICMP_UGT:
Sanjoy Das337d46b2015-03-24 19:29:18 +0000306 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000307 Index = RHS;
308 Length = LHS;
309 return RANGE_CHECK_BOTH;
310 }
311 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000312 }
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000313
314 llvm_unreachable("default clause returns!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000315}
316
Sanjoy Dasa0992682016-05-26 00:09:02 +0000317void InductiveRangeCheck::extractRangeChecksFromCond(
318 Loop *L, ScalarEvolution &SE, Use &ConditionUse,
319 SmallVectorImpl<InductiveRangeCheck> &Checks,
320 SmallPtrSetImpl<Value *> &Visited) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000321 using namespace llvm::PatternMatch;
322
Sanjoy Das8fe88922016-05-26 00:08:24 +0000323 Value *Condition = ConditionUse.get();
Sanjoy Dasa0992682016-05-26 00:09:02 +0000324 if (!Visited.insert(Condition).second)
325 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000326
Sanjoy Dasa0992682016-05-26 00:09:02 +0000327 if (match(Condition, m_And(m_Value(), m_Value()))) {
328 SmallVector<InductiveRangeCheck, 8> SubChecks;
329 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
330 SubChecks, Visited);
331 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
332 SubChecks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000333
Sanjoy Dasa0992682016-05-26 00:09:02 +0000334 if (SubChecks.size() == 2) {
335 // Handle a special case where we know how to merge two checks separately
336 // checking the upper and lower bounds into a full range check.
337 const auto &RChkA = SubChecks[0];
338 const auto &RChkB = SubChecks[1];
339 if ((RChkA.Length == RChkB.Length || !RChkA.Length || !RChkB.Length) &&
340 RChkA.Offset == RChkB.Offset && RChkA.Scale == RChkB.Scale) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000341
Sanjoy Dasa0992682016-05-26 00:09:02 +0000342 // If RChkA.Kind == RChkB.Kind then we just found two identical checks.
343 // But if one of them is a RANGE_CHECK_LOWER and the other is a
344 // RANGE_CHECK_UPPER (only possibility if they're different) then
345 // together they form a RANGE_CHECK_BOTH.
346 SubChecks[0].Kind =
347 (InductiveRangeCheck::RangeCheckKind)(RChkA.Kind | RChkB.Kind);
348 SubChecks[0].Length = RChkA.Length ? RChkA.Length : RChkB.Length;
349 SubChecks[0].CheckUse = &ConditionUse;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000350
Sanjoy Dasa0992682016-05-26 00:09:02 +0000351 // We updated one of the checks in place, now erase the other.
352 SubChecks.pop_back();
353 }
354 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000355
Sanjoy Dasa0992682016-05-26 00:09:02 +0000356 Checks.insert(Checks.end(), SubChecks.begin(), SubChecks.end());
357 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000358 }
359
Sanjoy Dasa0992682016-05-26 00:09:02 +0000360 ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);
361 if (!ICI)
362 return;
363
364 Value *Length = nullptr, *Index;
365 auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length);
366 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
367 return;
368
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000369 const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000370 bool IsAffineIndex =
371 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
372
373 if (!IsAffineIndex)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000374 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000375
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000376 InductiveRangeCheck IRC;
377 IRC.Length = Length;
378 IRC.Offset = IndexAddRec->getStart();
379 IRC.Scale = IndexAddRec->getStepRecurrence(SE);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000380 IRC.CheckUse = &ConditionUse;
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000381 IRC.Kind = RCKind;
Sanjoy Dasa0992682016-05-26 00:09:02 +0000382 Checks.push_back(IRC);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000383}
384
Sanjoy Dasa0992682016-05-26 00:09:02 +0000385void InductiveRangeCheck::extractRangeChecksFromBranch(
386 BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo &BPI,
387 SmallVectorImpl<InductiveRangeCheck> &Checks) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000388
389 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
Sanjoy Dasa0992682016-05-26 00:09:02 +0000390 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000391
392 BranchProbability LikelyTaken(15, 16);
393
Sanjoy Dasbb969792016-07-22 00:40:56 +0000394 if (!SkipProfitabilityChecks &&
395 BPI.getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000396 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000397
Sanjoy Dasa0992682016-05-26 00:09:02 +0000398 SmallPtrSet<Value *, 8> Visited;
399 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
400 Checks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000401}
402
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000403namespace {
404
Sanjoy Dase75ed922015-02-26 08:19:31 +0000405// Keeps track of the structure of a loop. This is similar to llvm::Loop,
406// except that it is more lightweight and can track the state of a loop through
407// changing and potentially invalid IR. This structure also formalizes the
408// kinds of loops we can deal with -- ones that have a single latch that is also
409// an exiting block *and* have a canonical induction variable.
410struct LoopStructure {
411 const char *Tag;
412
413 BasicBlock *Header;
414 BasicBlock *Latch;
415
416 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
417 // successor is `LatchExit', the exit block of the loop.
418 BranchInst *LatchBr;
419 BasicBlock *LatchExit;
420 unsigned LatchBrExitIdx;
421
422 Value *IndVarNext;
423 Value *IndVarStart;
424 Value *LoopExitAt;
425 bool IndVarIncreasing;
426
427 LoopStructure()
428 : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr),
429 LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr),
430 IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false) {}
431
432 template <typename M> LoopStructure map(M Map) const {
433 LoopStructure Result;
434 Result.Tag = Tag;
435 Result.Header = cast<BasicBlock>(Map(Header));
436 Result.Latch = cast<BasicBlock>(Map(Latch));
437 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
438 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
439 Result.LatchBrExitIdx = LatchBrExitIdx;
440 Result.IndVarNext = Map(IndVarNext);
441 Result.IndVarStart = Map(IndVarStart);
442 Result.LoopExitAt = Map(LoopExitAt);
443 Result.IndVarIncreasing = IndVarIncreasing;
444 return Result;
445 }
446
Sanjoy Dase91665d2015-02-26 08:56:04 +0000447 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
448 BranchProbabilityInfo &BPI,
449 Loop &,
Sanjoy Dase75ed922015-02-26 08:19:31 +0000450 const char *&);
451};
452
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000453/// This class is used to constrain loops to run within a given iteration space.
454/// The algorithm this class implements is given a Loop and a range [Begin,
455/// End). The algorithm then tries to break out a "main loop" out of the loop
456/// it is given in a way that the "main loop" runs with the induction variable
457/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
458/// loops to run any remaining iterations. The pre loop runs any iterations in
459/// which the induction variable is < Begin, and the post loop runs any
460/// iterations in which the induction variable is >= End.
461///
462class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000463 // The representation of a clone of the original loop we started out with.
464 struct ClonedLoop {
465 // The cloned blocks
466 std::vector<BasicBlock *> Blocks;
467
468 // `Map` maps values in the clonee into values in the cloned version
469 ValueToValueMapTy Map;
470
471 // An instance of `LoopStructure` for the cloned loop
472 LoopStructure Structure;
473 };
474
475 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
476 // more details on what these fields mean.
477 struct RewrittenRangeInfo {
478 BasicBlock *PseudoExit;
479 BasicBlock *ExitSelector;
480 std::vector<PHINode *> PHIValuesAtPseudoExit;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000481 PHINode *IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000482
Sanjoy Dase75ed922015-02-26 08:19:31 +0000483 RewrittenRangeInfo()
484 : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000485 };
486
487 // Calculated subranges we restrict the iteration space of the main loop to.
488 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000489 // these fields are computed. `LowLimit` is None if there is no restriction
490 // on low end of the restricted iteration space of the main loop. `HighLimit`
491 // is None if there is no restriction on high end of the restricted iteration
492 // space of the main loop.
493
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000494 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000495 Optional<const SCEV *> LowLimit;
496 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000497 };
498
499 // A utility function that does a `replaceUsesOfWith' on the incoming block
500 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
501 // incoming block list with `ReplaceBy'.
502 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
503 BasicBlock *ReplaceBy);
504
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000505 // Compute a safe set of limits for the main loop to run in -- effectively the
506 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000507 // Return None if unable to compute the set of subranges.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000508 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000509 Optional<SubRanges> calculateSubRanges() const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000510
511 // Clone `OriginalLoop' and return the result in CLResult. The IR after
512 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
513 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
514 // but there is no such edge.
515 //
516 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
517
518 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
519 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
520 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
521 // `OriginalHeaderCount'.
522 //
523 // If there are iterations left to execute, control is made to jump to
524 // `ContinuationBlock', otherwise they take the normal loop exit. The
525 // returned `RewrittenRangeInfo' object is populated as follows:
526 //
527 // .PseudoExit is a basic block that unconditionally branches to
528 // `ContinuationBlock'.
529 //
530 // .ExitSelector is a basic block that decides, on exit from the loop,
531 // whether to branch to the "true" exit or to `PseudoExit'.
532 //
533 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
534 // for each PHINode in the loop header on taking the pseudo exit.
535 //
536 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
537 // preheader because it is made to branch to the loop header only
538 // conditionally.
539 //
540 RewrittenRangeInfo
541 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
542 Value *ExitLoopAt,
543 BasicBlock *ContinuationBlock) const;
544
545 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
546 // function creates a new preheader for `LS' and returns it.
547 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000548 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
549 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000550
551 // `ContinuationBlockAndPreheader' was the continuation block for some call to
552 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
553 // This function rewrites the PHI nodes in `LS.Header' to start with the
554 // correct value.
555 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000556 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000557 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
558
559 // Even though we do not preserve any passes at this time, we at least need to
560 // keep the parent loop structure consistent. The `LPPassManager' seems to
561 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000562 // blocks denoted by BBs to this loops parent loop if required.
563 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000564
565 // Some global state.
566 Function &F;
567 LLVMContext &Ctx;
568 ScalarEvolution &SE;
Sanjoy Dasf45e03e2016-08-02 19:31:54 +0000569 DominatorTree &DT;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000570
571 // Information about the original loop we started out with.
572 Loop &OriginalLoop;
Sanjoy Das83a72852016-08-02 19:32:01 +0000573 LoopInfo &LI;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000574 const SCEV *LatchTakenCount;
575 BasicBlock *OriginalPreheader;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000576
577 // The preheader of the main loop. This may or may not be different from
578 // `OriginalPreheader'.
579 BasicBlock *MainLoopPreheader;
580
581 // The range we need to run the main loop in.
582 InductiveRangeCheck::Range Range;
583
584 // The structure of the main loop (see comment at the beginning of this class
585 // for a definition)
586 LoopStructure MainLoopStructure;
587
588public:
Sanjoy Dase75ed922015-02-26 08:19:31 +0000589 LoopConstrainer(Loop &L, LoopInfo &LI, const LoopStructure &LS,
Sanjoy Dasf45e03e2016-08-02 19:31:54 +0000590 ScalarEvolution &SE, DominatorTree &DT,
591 InductiveRangeCheck::Range R)
Sanjoy Dase75ed922015-02-26 08:19:31 +0000592 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
Sanjoy Das83a72852016-08-02 19:32:01 +0000593 SE(SE), DT(DT), OriginalLoop(L), LI(LI), LatchTakenCount(nullptr),
594 OriginalPreheader(nullptr), MainLoopPreheader(nullptr), Range(R),
595 MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000596
597 // Entry point for the algorithm. Returns true on success.
598 bool run();
599};
600
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000601}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000602
603void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
604 BasicBlock *ReplaceBy) {
605 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
606 if (PN->getIncomingBlock(i) == Block)
607 PN->setIncomingBlock(i, ReplaceBy);
608}
609
Sanjoy Dase75ed922015-02-26 08:19:31 +0000610static bool CanBeSMax(ScalarEvolution &SE, const SCEV *S) {
611 APInt SMax =
612 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
613 return SE.getSignedRange(S).contains(SMax) &&
614 SE.getUnsignedRange(S).contains(SMax);
615}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000616
Sanjoy Dase75ed922015-02-26 08:19:31 +0000617static bool CanBeSMin(ScalarEvolution &SE, const SCEV *S) {
618 APInt SMin =
619 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth());
620 return SE.getSignedRange(S).contains(SMin) &&
621 SE.getUnsignedRange(S).contains(SMin);
622}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000623
Sanjoy Dase75ed922015-02-26 08:19:31 +0000624Optional<LoopStructure>
Sanjoy Dase91665d2015-02-26 08:56:04 +0000625LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI,
626 Loop &L, const char *&FailureReason) {
Sanjoy Das43fdc542016-08-14 01:04:31 +0000627 if (!L.isLoopSimplifyForm()) {
628 FailureReason = "loop not in LoopSimplify form";
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000629 return None;
Sanjoy Das43fdc542016-08-14 01:04:31 +0000630 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000631
632 BasicBlock *Latch = L.getLoopLatch();
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000633 assert(Latch && "Simplified loops only have one latch!");
634
Sanjoy Das7a18a232016-08-14 01:04:36 +0000635 if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) {
636 FailureReason = "loop has already been cloned";
637 return None;
638 }
639
Sanjoy Dase75ed922015-02-26 08:19:31 +0000640 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000641 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000642 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000643 }
644
Sanjoy Dase75ed922015-02-26 08:19:31 +0000645 BasicBlock *Header = L.getHeader();
646 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000647 if (!Preheader) {
648 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000649 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000650 }
651
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000652 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000653 if (!LatchBr || LatchBr->isUnconditional()) {
654 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000655 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000656 }
657
Sanjoy Dase75ed922015-02-26 08:19:31 +0000658 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000659
Sanjoy Dase91665d2015-02-26 08:56:04 +0000660 BranchProbability ExitProbability =
661 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
662
Sanjoy Dasbb969792016-07-22 00:40:56 +0000663 if (!SkipProfitabilityChecks &&
664 ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
Sanjoy Dase91665d2015-02-26 08:56:04 +0000665 FailureReason = "short running loop, not profitable";
666 return None;
667 }
668
Sanjoy Dase75ed922015-02-26 08:19:31 +0000669 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
670 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
671 FailureReason = "latch terminator branch not conditional on integral icmp";
672 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000673 }
674
Sanjoy Dase75ed922015-02-26 08:19:31 +0000675 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
676 if (isa<SCEVCouldNotCompute>(LatchCount)) {
677 FailureReason = "could not compute latch count";
678 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000679 }
680
Sanjoy Dase75ed922015-02-26 08:19:31 +0000681 ICmpInst::Predicate Pred = ICI->getPredicate();
682 Value *LeftValue = ICI->getOperand(0);
683 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
684 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
685
686 Value *RightValue = ICI->getOperand(1);
687 const SCEV *RightSCEV = SE.getSCEV(RightValue);
688
689 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
690 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
691 if (isa<SCEVAddRecExpr>(RightSCEV)) {
692 std::swap(LeftSCEV, RightSCEV);
693 std::swap(LeftValue, RightValue);
694 Pred = ICmpInst::getSwappedPredicate(Pred);
695 } else {
696 FailureReason = "no add recurrences in the icmp";
697 return None;
698 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000699 }
700
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000701 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
702 if (AR->getNoWrapFlags(SCEV::FlagNSW))
703 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000704
705 IntegerType *Ty = cast<IntegerType>(AR->getType());
706 IntegerType *WideTy =
707 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
708
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000709 const SCEVAddRecExpr *ExtendAfterOp =
710 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
711 if (ExtendAfterOp) {
712 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
713 const SCEV *ExtendedStep =
714 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
715
716 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
717 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
718
719 if (NoSignedWrap)
720 return true;
721 }
722
723 // We may have proved this when computing the sign extension above.
724 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
725 };
726
727 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing) {
728 if (!AR->isAffine())
729 return false;
730
Sanjoy Dase75ed922015-02-26 08:19:31 +0000731 // Currently we only work with induction variables that have been proved to
732 // not wrap. This restriction can potentially be lifted in the future.
733
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000734 if (!HasNoSignedWrap(AR))
Sanjoy Dase75ed922015-02-26 08:19:31 +0000735 return false;
736
737 if (const SCEVConstant *StepExpr =
738 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
739 ConstantInt *StepCI = StepExpr->getValue();
740 if (StepCI->isOne() || StepCI->isMinusOne()) {
741 IsIncreasing = StepCI->isOne();
742 return true;
743 }
744 }
745
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000746 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000747 };
748
749 // `ICI` is interpreted as taking the backedge if the *next* value of the
750 // induction variable satisfies some constraint.
751
752 const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
753 bool IsIncreasing = false;
754 if (!IsInductionVar(IndVarNext, IsIncreasing)) {
755 FailureReason = "LHS in icmp not induction variable";
756 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000757 }
758
Sanjoy Dase75ed922015-02-26 08:19:31 +0000759 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
760 // TODO: generalize the predicates here to also match their unsigned variants.
761 if (IsIncreasing) {
762 bool FoundExpectedPred =
763 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) ||
764 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0);
765
766 if (!FoundExpectedPred) {
767 FailureReason = "expected icmp slt semantically, found something else";
768 return None;
769 }
770
771 if (LatchBrExitIdx == 0) {
772 if (CanBeSMax(SE, RightSCEV)) {
773 // TODO: this restriction is easily removable -- we just have to
774 // remember that the icmp was an slt and not an sle.
775 FailureReason = "limit may overflow when coercing sle to slt";
776 return None;
777 }
778
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000779 IRBuilder<> B(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000780 RightValue = B.CreateAdd(RightValue, One);
781 }
782
783 } else {
784 bool FoundExpectedPred =
785 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) ||
786 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0);
787
788 if (!FoundExpectedPred) {
789 FailureReason = "expected icmp sgt semantically, found something else";
790 return None;
791 }
792
793 if (LatchBrExitIdx == 0) {
794 if (CanBeSMin(SE, RightSCEV)) {
795 // TODO: this restriction is easily removable -- we just have to
796 // remember that the icmp was an sgt and not an sge.
797 FailureReason = "limit may overflow when coercing sge to sgt";
798 return None;
799 }
800
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000801 IRBuilder<> B(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000802 RightValue = B.CreateSub(RightValue, One);
803 }
804 }
805
806 const SCEV *StartNext = IndVarNext->getStart();
807 const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
808 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
809
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000810 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
811
Sanjoy Dase75ed922015-02-26 08:19:31 +0000812 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000813 ScalarEvolution::LoopInvariant &&
814 "loop variant exit count doesn't make sense!");
815
Sanjoy Dase75ed922015-02-26 08:19:31 +0000816 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000817 const DataLayout &DL = Preheader->getModule()->getDataLayout();
818 Value *IndVarStartV =
819 SCEVExpander(SE, DL, "irce")
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000820 .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000821 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000822
Sanjoy Dase75ed922015-02-26 08:19:31 +0000823 LoopStructure Result;
824
825 Result.Tag = "main";
826 Result.Header = Header;
827 Result.Latch = Latch;
828 Result.LatchBr = LatchBr;
829 Result.LatchExit = LatchExit;
830 Result.LatchBrExitIdx = LatchBrExitIdx;
831 Result.IndVarStart = IndVarStartV;
832 Result.IndVarNext = LeftValue;
833 Result.IndVarIncreasing = IsIncreasing;
834 Result.LoopExitAt = RightValue;
835
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000836 FailureReason = nullptr;
837
Sanjoy Dase75ed922015-02-26 08:19:31 +0000838 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000839}
840
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000841Optional<LoopConstrainer::SubRanges>
Sanjoy Dase75ed922015-02-26 08:19:31 +0000842LoopConstrainer::calculateSubRanges() const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000843 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
844
Sanjoy Das351db052015-01-22 09:32:02 +0000845 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000846 return None;
847
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000848 LoopConstrainer::SubRanges Result;
849
850 // I think we can be more aggressive here and make this nuw / nsw if the
851 // addition that feeds into the icmp for the latch's terminating branch is nuw
852 // / nsw. In any case, a wrapping 2's complement addition is safe.
853 ConstantInt *One = ConstantInt::get(Ty, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000854 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
855 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000856
Sanjoy Dase75ed922015-02-26 08:19:31 +0000857 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000858
Sanjoy Dase75ed922015-02-26 08:19:31 +0000859 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the
860 // range of values the induction variable takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000861
862 const SCEV *Smallest = nullptr, *Greatest = nullptr;
863
864 if (Increasing) {
865 Smallest = Start;
866 Greatest = End;
867 } else {
868 // These two computations may sign-overflow. Here is why that is okay:
869 //
870 // We know that the induction variable does not sign-overflow on any
871 // iteration except the last one, and it starts at `Start` and ends at
872 // `End`, decrementing by one every time.
873 //
874 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
875 // induction variable is decreasing we know that that the smallest value
876 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
877 //
878 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
879 // that case, `Clamp` will always return `Smallest` and
880 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
881 // will be an empty range. Returning an empty range is always safe.
882 //
883
884 Smallest = SE.getAddExpr(End, SE.getSCEV(One));
885 Greatest = SE.getAddExpr(Start, SE.getSCEV(One));
886 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000887
888 auto Clamp = [this, Smallest, Greatest](const SCEV *S) {
889 return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S));
890 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000891
892 // In some cases we can prove that we don't need a pre or post loop
893
894 bool ProvablyNoPreloop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000895 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest);
896 if (!ProvablyNoPreloop)
897 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000898
899 bool ProvablyNoPostLoop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000900 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd());
901 if (!ProvablyNoPostLoop)
902 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000903
904 return Result;
905}
906
907void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
908 const char *Tag) const {
909 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
910 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
911 Result.Blocks.push_back(Clone);
912 Result.Map[BB] = Clone;
913 }
914
915 auto GetClonedValue = [&Result](Value *V) {
916 assert(V && "null values not in domain!");
917 auto It = Result.Map.find(V);
918 if (It == Result.Map.end())
919 return V;
920 return static_cast<Value *>(It->second);
921 };
922
Sanjoy Das7a18a232016-08-14 01:04:36 +0000923 auto *ClonedLatch =
924 cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch()));
925 ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag,
926 MDNode::get(Ctx, {}));
927
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000928 Result.Structure = MainLoopStructure.map(GetClonedValue);
929 Result.Structure.Tag = Tag;
930
931 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
932 BasicBlock *ClonedBB = Result.Blocks[i];
933 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
934
935 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
936
937 for (Instruction &I : *ClonedBB)
938 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000939 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000940
941 // Exit blocks will now have one more predecessor and their PHI nodes need
942 // to be edited to reflect that. No phi nodes need to be introduced because
943 // the loop is in LCSSA.
944
Sanjoy Dasd1d62a12016-08-13 22:00:09 +0000945 for (auto *SBB : successors(OriginalBB)) {
946 if (OriginalLoop.contains(SBB))
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000947 continue; // not an exit block
948
Sanjoy Dasd1d62a12016-08-13 22:00:09 +0000949 for (Instruction &I : *SBB) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +0000950 auto *PN = dyn_cast<PHINode>(&I);
951 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000952 break;
953
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000954 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
955 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
956 }
957 }
958 }
959}
960
961LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000962 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000963 BasicBlock *ContinuationBlock) const {
964
965 // We start with a loop with a single latch:
966 //
967 // +--------------------+
968 // | |
969 // | preheader |
970 // | |
971 // +--------+-----------+
972 // | ----------------\
973 // | / |
974 // +--------v----v------+ |
975 // | | |
976 // | header | |
977 // | | |
978 // +--------------------+ |
979 // |
980 // ..... |
981 // |
982 // +--------------------+ |
983 // | | |
984 // | latch >----------/
985 // | |
986 // +-------v------------+
987 // |
988 // |
989 // | +--------------------+
990 // | | |
991 // +---> original exit |
992 // | |
993 // +--------------------+
994 //
995 // We change the control flow to look like
996 //
997 //
998 // +--------------------+
999 // | |
1000 // | preheader >-------------------------+
1001 // | | |
1002 // +--------v-----------+ |
1003 // | /-------------+ |
1004 // | / | |
1005 // +--------v--v--------+ | |
1006 // | | | |
1007 // | header | | +--------+ |
1008 // | | | | | |
1009 // +--------------------+ | | +-----v-----v-----------+
1010 // | | | |
1011 // | | | .pseudo.exit |
1012 // | | | |
1013 // | | +-----------v-----------+
1014 // | | |
1015 // ..... | | |
1016 // | | +--------v-------------+
1017 // +--------------------+ | | | |
1018 // | | | | | ContinuationBlock |
1019 // | latch >------+ | | |
1020 // | | | +----------------------+
1021 // +---------v----------+ |
1022 // | |
1023 // | |
1024 // | +---------------^-----+
1025 // | | |
1026 // +-----> .exit.selector |
1027 // | |
1028 // +----------v----------+
1029 // |
1030 // +--------------------+ |
1031 // | | |
1032 // | original exit <----+
1033 // | |
1034 // +--------------------+
1035 //
1036
1037 RewrittenRangeInfo RRI;
1038
1039 auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
1040 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001041 &F, &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001042 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001043 &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001044
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001045 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001046 bool Increasing = LS.IndVarIncreasing;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001047
1048 IRBuilder<> B(PreheaderJump);
1049
1050 // EnterLoopCond - is it okay to start executing this `LS'?
Sanjoy Dase75ed922015-02-26 08:19:31 +00001051 Value *EnterLoopCond = Increasing
1052 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1053 : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt);
1054
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001055 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1056 PreheaderJump->eraseFromParent();
1057
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001058 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001059 B.SetInsertPoint(LS.LatchBr);
1060 Value *TakeBackedgeLoopCond =
1061 Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1062 : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt);
1063 Value *CondForBranch = LS.LatchBrExitIdx == 1
1064 ? TakeBackedgeLoopCond
1065 : B.CreateNot(TakeBackedgeLoopCond);
1066
1067 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001068
1069 B.SetInsertPoint(RRI.ExitSelector);
1070
1071 // IterationsLeft - are there any more iterations left, given the original
1072 // upper bound on the induction variable? If not, we branch to the "real"
1073 // exit.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001074 Value *IterationsLeft = Increasing
1075 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1076 : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001077 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1078
1079 BranchInst *BranchToContinuation =
1080 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1081
1082 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1083 // each of the PHI nodes in the loop header. This feeds into the initial
1084 // value of the same PHI nodes if/when we continue execution.
1085 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001086 auto *PN = dyn_cast<PHINode>(&I);
1087 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001088 break;
1089
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001090 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1091 BranchToContinuation);
1092
1093 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1094 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1095 RRI.ExitSelector);
1096 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1097 }
1098
Sanjoy Dase75ed922015-02-26 08:19:31 +00001099 RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1100 BranchToContinuation);
1101 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1102 RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1103
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001104 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1105 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1106 for (Instruction &I : *LS.LatchExit) {
1107 if (PHINode *PN = dyn_cast<PHINode>(&I))
1108 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1109 else
1110 break;
1111 }
1112
1113 return RRI;
1114}
1115
1116void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001117 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001118 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1119
1120 unsigned PHIIndex = 0;
1121 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001122 auto *PN = dyn_cast<PHINode>(&I);
1123 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001124 break;
1125
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001126 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1127 if (PN->getIncomingBlock(i) == ContinuationBlock)
1128 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1129 }
1130
Sanjoy Dase75ed922015-02-26 08:19:31 +00001131 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001132}
1133
Sanjoy Dase75ed922015-02-26 08:19:31 +00001134BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1135 BasicBlock *OldPreheader,
1136 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001137
1138 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1139 BranchInst::Create(LS.Header, Preheader);
1140
1141 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001142 auto *PN = dyn_cast<PHINode>(&I);
1143 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001144 break;
1145
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001146 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1147 replacePHIBlock(PN, OldPreheader, Preheader);
1148 }
1149
1150 return Preheader;
1151}
1152
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001153void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001154 Loop *ParentLoop = OriginalLoop.getParentLoop();
1155 if (!ParentLoop)
1156 return;
1157
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001158 for (BasicBlock *BB : BBs)
Sanjoy Das83a72852016-08-02 19:32:01 +00001159 ParentLoop->addBasicBlockToLoop(BB, LI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001160}
1161
1162bool LoopConstrainer::run() {
1163 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001164 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1165 Preheader = OriginalLoop.getLoopPreheader();
1166 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1167 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001168
1169 OriginalPreheader = Preheader;
1170 MainLoopPreheader = Preheader;
1171
Sanjoy Dase75ed922015-02-26 08:19:31 +00001172 Optional<SubRanges> MaybeSR = calculateSubRanges();
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001173 if (!MaybeSR.hasValue()) {
1174 DEBUG(dbgs() << "irce: could not compute subranges\n");
1175 return false;
1176 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001177
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001178 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001179 bool Increasing = MainLoopStructure.IndVarIncreasing;
1180 IntegerType *IVTy =
1181 cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1182
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001183 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001184 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001185
1186 // It would have been better to make `PreLoop' and `PostLoop'
1187 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1188 // constructor.
1189 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001190 bool NeedsPreLoop =
1191 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1192 bool NeedsPostLoop =
1193 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1194
1195 Value *ExitPreLoopAt = nullptr;
1196 Value *ExitMainLoopAt = nullptr;
1197 const SCEVConstant *MinusOneS =
1198 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1199
1200 if (NeedsPreLoop) {
1201 const SCEV *ExitPreLoopAtSCEV = nullptr;
1202
1203 if (Increasing)
1204 ExitPreLoopAtSCEV = *SR.LowLimit;
1205 else {
1206 if (CanBeSMin(SE, *SR.HighLimit)) {
1207 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1208 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1209 << "\n");
1210 return false;
1211 }
1212 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1213 }
1214
1215 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1216 ExitPreLoopAt->setName("exit.preloop.at");
1217 }
1218
1219 if (NeedsPostLoop) {
1220 const SCEV *ExitMainLoopAtSCEV = nullptr;
1221
1222 if (Increasing)
1223 ExitMainLoopAtSCEV = *SR.HighLimit;
1224 else {
1225 if (CanBeSMin(SE, *SR.LowLimit)) {
1226 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1227 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1228 << "\n");
1229 return false;
1230 }
1231 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1232 }
1233
1234 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1235 ExitMainLoopAt->setName("exit.mainloop.at");
1236 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001237
1238 // We clone these ahead of time so that we don't have to deal with changing
1239 // and temporarily invalid IR as we transform the loops.
1240 if (NeedsPreLoop)
1241 cloneLoop(PreLoop, "preloop");
1242 if (NeedsPostLoop)
1243 cloneLoop(PostLoop, "postloop");
1244
1245 RewrittenRangeInfo PreLoopRRI;
1246
1247 if (NeedsPreLoop) {
1248 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1249 PreLoop.Structure.Header);
1250
1251 MainLoopPreheader =
1252 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001253 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1254 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001255 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1256 PreLoopRRI);
1257 }
1258
1259 BasicBlock *PostLoopPreheader = nullptr;
1260 RewrittenRangeInfo PostLoopRRI;
1261
1262 if (NeedsPostLoop) {
1263 PostLoopPreheader =
1264 createPreheader(PostLoop.Structure, Preheader, "postloop");
1265 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001266 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001267 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1268 PostLoopRRI);
1269 }
1270
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001271 BasicBlock *NewMainLoopPreheader =
1272 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1273 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1274 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1275 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001276
1277 // Some of the above may be nullptr, filter them out before passing to
1278 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001279 auto NewBlocksEnd =
1280 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001281
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001282 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1283 addToParentLoopIfNeeded(PreLoop.Blocks);
1284 addToParentLoopIfNeeded(PostLoop.Blocks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001285
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001286 DT.recalculate(F);
Sanjoy Das83a72852016-08-02 19:32:01 +00001287 formLCSSARecursively(OriginalLoop, DT, &LI, &SE);
Sanjoy Dascf181862016-08-06 00:01:56 +00001288 simplifyLoop(&OriginalLoop, &DT, &LI, &SE, nullptr, true);
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001289
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001290 return true;
1291}
1292
Sanjoy Das95c476d2015-02-21 22:20:22 +00001293/// Computes and returns a range of values for the induction variable (IndVar)
1294/// in which the range check can be safely elided. If it cannot compute such a
1295/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001296Optional<InductiveRangeCheck::Range>
Sanjoy Das59776732016-05-21 02:31:51 +00001297InductiveRangeCheck::computeSafeIterationSpace(
1298 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001299 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1300 // variable, that may or may not exist as a real llvm::Value in the loop) and
1301 // this inductive range check is a range check on the "C + D * I" ("C" is
1302 // getOffset() and "D" is getScale()). We rewrite the value being range
1303 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1304 // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code
1305 // can be generalized as needed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001306 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001307 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001308 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001309 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1310 //
1311 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1312 // and subtractions are twos-complement wrapping and comparisons are signed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001313 //
1314 // Proof:
1315 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001316 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1317 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1318 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1319 // overflown.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001320 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001321 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1322 // Hence 0 <= (IndVar + M) < L
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001323
Sanjoy Das95c476d2015-02-21 22:20:22 +00001324 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1325 // 127, IndVar = 126 and L = -2 in an i8 world.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001326
Sanjoy Das95c476d2015-02-21 22:20:22 +00001327 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001328 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001329
Sanjoy Das95c476d2015-02-21 22:20:22 +00001330 const SCEV *A = IndVar->getStart();
1331 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1332 if (!B)
1333 return None;
1334
1335 const SCEV *C = getOffset();
1336 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1337 if (D != B)
1338 return None;
1339
1340 ConstantInt *ConstD = D->getValue();
1341 if (!(ConstD->isMinusOne() || ConstD->isOne()))
1342 return None;
1343
1344 const SCEV *M = SE.getMinusSCEV(C, A);
1345
1346 const SCEV *Begin = SE.getNegativeSCEV(M);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001347 const SCEV *UpperLimit = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001348
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001349 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1350 // We can potentially do much better here.
1351 if (Value *V = getLength()) {
1352 UpperLimit = SE.getSCEV(V);
1353 } else {
1354 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1355 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1356 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1357 }
1358
1359 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
Sanjoy Das351db052015-01-22 09:32:02 +00001360 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001361}
1362
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001363static Optional<InductiveRangeCheck::Range>
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001364IntersectRange(ScalarEvolution &SE,
1365 const Optional<InductiveRangeCheck::Range> &R1,
Sanjoy Das59776732016-05-21 02:31:51 +00001366 const InductiveRangeCheck::Range &R2) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001367 if (!R1.hasValue())
1368 return R2;
1369 auto &R1Value = R1.getValue();
1370
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001371 // TODO: we could widen the smaller range and have this work; but for now we
1372 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001373 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001374 return None;
1375
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001376 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1377 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1378
1379 return InductiveRangeCheck::Range(NewBegin, NewEnd);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001380}
1381
1382bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001383 if (skipLoop(L))
1384 return false;
1385
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001386 if (L->getBlocks().size() >= LoopSizeCutoff) {
1387 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1388 return false;
1389 }
1390
1391 BasicBlock *Preheader = L->getLoopPreheader();
1392 if (!Preheader) {
1393 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1394 return false;
1395 }
1396
1397 LLVMContext &Context = Preheader->getContext();
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001398 SmallVector<InductiveRangeCheck, 16> RangeChecks;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001399 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Cong Houab23bfb2015-07-15 22:48:29 +00001400 BranchProbabilityInfo &BPI =
1401 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001402
1403 for (auto BBI : L->getBlocks())
1404 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
Sanjoy Dasa0992682016-05-26 00:09:02 +00001405 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1406 RangeChecks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001407
1408 if (RangeChecks.empty())
1409 return false;
1410
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001411 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1412 OS << "irce: looking at loop "; L->print(OS);
1413 OS << "irce: loop has " << RangeChecks.size()
1414 << " inductive range checks: \n";
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001415 for (InductiveRangeCheck &IRC : RangeChecks)
1416 IRC.print(OS);
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001417 };
1418
1419 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1420
1421 if (PrintRangeChecks)
1422 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001423
Sanjoy Dase75ed922015-02-26 08:19:31 +00001424 const char *FailureReason = nullptr;
1425 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001426 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001427 if (!MaybeLoopStructure.hasValue()) {
1428 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1429 << "\n";);
1430 return false;
1431 }
1432 LoopStructure LS = MaybeLoopStructure.getValue();
1433 bool Increasing = LS.IndVarIncreasing;
1434 const SCEV *MinusOne =
1435 SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true);
1436 const SCEVAddRecExpr *IndVar =
1437 cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne));
1438
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001439 Optional<InductiveRangeCheck::Range> SafeIterRange;
1440 Instruction *ExprInsertPt = Preheader->getTerminator();
1441
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001442 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001443
1444 IRBuilder<> B(ExprInsertPt);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001445 for (InductiveRangeCheck &IRC : RangeChecks) {
1446 auto Result = IRC.computeSafeIterationSpace(SE, IndVar);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001447 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001448 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001449 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001450 if (MaybeSafeIterRange.hasValue()) {
1451 RangeChecksToEliminate.push_back(IRC);
1452 SafeIterRange = MaybeSafeIterRange.getValue();
1453 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001454 }
1455 }
1456
1457 if (!SafeIterRange.hasValue())
1458 return false;
1459
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001460 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001461 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LS,
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001462 SE, DT, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001463 bool Changed = LC.run();
1464
1465 if (Changed) {
1466 auto PrintConstrainedLoopInfo = [L]() {
1467 dbgs() << "irce: in function ";
1468 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1469 dbgs() << "constrained ";
1470 L->print(dbgs());
1471 };
1472
1473 DEBUG(PrintConstrainedLoopInfo());
1474
1475 if (PrintChangedLoops)
1476 PrintConstrainedLoopInfo();
1477
1478 // Optimize away the now-redundant range checks.
1479
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001480 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1481 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001482 ? ConstantInt::getTrue(Context)
1483 : ConstantInt::getFalse(Context);
Sanjoy Dasaa83c472016-05-23 22:16:45 +00001484 IRC.getCheckUse()->set(FoldedRangeCheck);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001485 }
1486 }
1487
1488 return Changed;
1489}
1490
1491Pass *llvm::createInductiveRangeCheckEliminationPass() {
1492 return new InductiveRangeCheckElimination;
1493}