blob: 4cbf2112e1e3f77b40c957e1ac8c70b9d848ab00 [file] [log] [blame]
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001//===-- InductiveRangeCheckElimination.cpp - ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9// The InductiveRangeCheckElimination pass splits a loop's iteration space into
10// three disjoint ranges. It does that in a way such that the loop running in
11// the middle loop provably does not need range checks. As an example, it will
12// convert
13//
14// len = < known positive >
15// for (i = 0; i < n; i++) {
16// if (0 <= i && i < len) {
17// do_something();
18// } else {
19// throw_out_of_bounds();
20// }
21// }
22//
23// to
24//
25// len = < known positive >
26// limit = smin(n, len)
27// // no first segment
28// for (i = 0; i < limit; i++) {
29// if (0 <= i && i < len) { // this check is fully redundant
30// do_something();
31// } else {
32// throw_out_of_bounds();
33// }
34// }
35// for (i = limit; i < n; i++) {
36// if (0 <= i && i < len) {
37// do_something();
38// } else {
39// throw_out_of_bounds();
40// }
41// }
42//===----------------------------------------------------------------------===//
43
44#include "llvm/ADT/Optional.h"
Sanjoy Dasdcf26512015-01-27 21:38:12 +000045#include "llvm/Analysis/BranchProbabilityInfo.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000046#include "llvm/Analysis/InstructionSimplify.h"
47#include "llvm/Analysis/LoopInfo.h"
48#include "llvm/Analysis/LoopPass.h"
49#include "llvm/Analysis/ScalarEvolution.h"
50#include "llvm/Analysis/ScalarEvolutionExpander.h"
51#include "llvm/Analysis/ScalarEvolutionExpressions.h"
52#include "llvm/Analysis/ValueTracking.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000053#include "llvm/IR/Dominators.h"
54#include "llvm/IR/Function.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000055#include "llvm/IR/IRBuilder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000056#include "llvm/IR/Instructions.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000057#include "llvm/IR/Module.h"
58#include "llvm/IR/PatternMatch.h"
59#include "llvm/IR/ValueHandle.h"
60#include "llvm/IR/Verifier.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000061#include "llvm/Pass.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000062#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000063#include "llvm/Support/raw_ostream.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000064#include "llvm/Transforms/Scalar.h"
65#include "llvm/Transforms/Utils/BasicBlockUtils.h"
66#include "llvm/Transforms/Utils/Cloning.h"
67#include "llvm/Transforms/Utils/LoopUtils.h"
68#include "llvm/Transforms/Utils/SimplifyIndVar.h"
Sanjoy Dascf181862016-08-06 00:01:56 +000069#include "llvm/Transforms/Utils/LoopSimplify.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000070#include "llvm/Transforms/Utils/UnrollLoop.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000071
72using namespace llvm;
73
Benjamin Kramer970eac42015-02-06 17:51:54 +000074static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
75 cl::init(64));
Sanjoy Dasa1837a32015-01-16 01:03:22 +000076
Benjamin Kramer970eac42015-02-06 17:51:54 +000077static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
78 cl::init(false));
Sanjoy Dasa1837a32015-01-16 01:03:22 +000079
Sanjoy Das9c1bfae2015-03-17 01:40:22 +000080static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
81 cl::init(false));
82
Sanjoy Dase91665d2015-02-26 08:56:04 +000083static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
84 cl::Hidden, cl::init(10));
85
Sanjoy Dasbb969792016-07-22 00:40:56 +000086static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks",
87 cl::Hidden, cl::init(false));
88
Sanjoy Dasa1837a32015-01-16 01:03:22 +000089#define DEBUG_TYPE "irce"
90
91namespace {
92
93/// An inductive range check is conditional branch in a loop with
94///
95/// 1. a very cold successor (i.e. the branch jumps to that successor very
96/// rarely)
97///
98/// and
99///
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000100/// 2. a condition that is provably true for some contiguous range of values
101/// taken by the containing loop's induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000102///
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000103class InductiveRangeCheck {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000104 // Classifies a range check
Reid Kleckner0b168592015-03-17 16:50:20 +0000105 enum RangeCheckKind : unsigned {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000106 // Range check of the form "0 <= I".
107 RANGE_CHECK_LOWER = 1,
108
109 // Range check of the form "I < L" where L is known positive.
110 RANGE_CHECK_UPPER = 2,
111
112 // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER
113 // conditions.
114 RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
115
116 // Unrecognized range check condition.
117 RANGE_CHECK_UNKNOWN = (unsigned)-1
118 };
119
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000120 static StringRef rangeCheckKindToStr(RangeCheckKind);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000121
Sanjoy Dasee77a482016-05-26 01:50:18 +0000122 const SCEV *Offset = nullptr;
123 const SCEV *Scale = nullptr;
124 Value *Length = nullptr;
125 Use *CheckUse = nullptr;
126 RangeCheckKind Kind = RANGE_CHECK_UNKNOWN;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000127
Sanjoy Das337d46b2015-03-24 19:29:18 +0000128 static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
129 ScalarEvolution &SE, Value *&Index,
130 Value *&Length);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000131
Sanjoy Dasa0992682016-05-26 00:09:02 +0000132 static void
133 extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,
134 SmallVectorImpl<InductiveRangeCheck> &Checks,
135 SmallPtrSetImpl<Value *> &Visited);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000136
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000137public:
138 const SCEV *getOffset() const { return Offset; }
139 const SCEV *getScale() const { return Scale; }
140 Value *getLength() const { return Length; }
141
142 void print(raw_ostream &OS) const {
143 OS << "InductiveRangeCheck:\n";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000144 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000145 OS << " Offset: ";
146 Offset->print(OS);
147 OS << " Scale: ";
148 Scale->print(OS);
149 OS << " Length: ";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000150 if (Length)
151 Length->print(OS);
152 else
153 OS << "(null)";
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000154 OS << "\n CheckUse: ";
155 getCheckUse()->getUser()->print(OS);
156 OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000157 }
158
159#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
160 void dump() {
161 print(dbgs());
162 }
163#endif
164
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000165 Use *getCheckUse() const { return CheckUse; }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000166
Sanjoy Das351db052015-01-22 09:32:02 +0000167 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
168 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
169
170 class Range {
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000171 const SCEV *Begin;
172 const SCEV *End;
Sanjoy Das351db052015-01-22 09:32:02 +0000173
174 public:
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000175 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
Sanjoy Das351db052015-01-22 09:32:02 +0000176 assert(Begin->getType() == End->getType() && "ill-typed range!");
177 }
178
179 Type *getType() const { return Begin->getType(); }
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000180 const SCEV *getBegin() const { return Begin; }
181 const SCEV *getEnd() const { return End; }
Sanjoy Das351db052015-01-22 09:32:02 +0000182 };
183
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000184 /// This is the value the condition of the branch needs to evaluate to for the
185 /// branch to take the hot successor (see (1) above).
186 bool getPassingDirection() { return true; }
187
Sanjoy Das95c476d2015-02-21 22:20:22 +0000188 /// Computes a range for the induction variable (IndVar) in which the range
189 /// check is redundant and can be constant-folded away. The induction
190 /// variable is not required to be the canonical {0,+,1} induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000191 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
Sanjoy Das59776732016-05-21 02:31:51 +0000192 const SCEVAddRecExpr *IndVar) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000193
Sanjoy Dasa0992682016-05-26 00:09:02 +0000194 /// Parse out a set of inductive range checks from \p BI and append them to \p
195 /// Checks.
196 ///
197 /// NB! There may be conditions feeding into \p BI that aren't inductive range
198 /// checks, and hence don't end up in \p Checks.
199 static void
200 extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE,
201 BranchProbabilityInfo &BPI,
202 SmallVectorImpl<InductiveRangeCheck> &Checks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000203};
204
205class InductiveRangeCheckElimination : public LoopPass {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000206public:
207 static char ID;
208 InductiveRangeCheckElimination() : LoopPass(ID) {
209 initializeInductiveRangeCheckEliminationPass(
210 *PassRegistry::getPassRegistry());
211 }
212
213 void getAnalysisUsage(AnalysisUsage &AU) const override {
Cong Houab23bfb2015-07-15 22:48:29 +0000214 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000215 getLoopAnalysisUsage(AU);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000216 }
217
218 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
219};
220
221char InductiveRangeCheckElimination::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000222}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000223
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000224INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce",
225 "Inductive range check elimination", false, false)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000226INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000227INITIALIZE_PASS_DEPENDENCY(LoopPass)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000228INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce",
229 "Inductive range check elimination", false, false)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000230
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000231StringRef InductiveRangeCheck::rangeCheckKindToStr(
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000232 InductiveRangeCheck::RangeCheckKind RCK) {
233 switch (RCK) {
234 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
235 return "RANGE_CHECK_UNKNOWN";
236
237 case InductiveRangeCheck::RANGE_CHECK_UPPER:
238 return "RANGE_CHECK_UPPER";
239
240 case InductiveRangeCheck::RANGE_CHECK_LOWER:
241 return "RANGE_CHECK_LOWER";
242
243 case InductiveRangeCheck::RANGE_CHECK_BOTH:
244 return "RANGE_CHECK_BOTH";
245 }
246
247 llvm_unreachable("unknown range check type!");
248}
249
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000250/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000251/// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000252/// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000253/// range checked, and set `Length` to the upper limit `Index` is being range
254/// checked with if (and only if) the range check type is stronger or equal to
255/// RANGE_CHECK_UPPER.
256///
257InductiveRangeCheck::RangeCheckKind
Sanjoy Das337d46b2015-03-24 19:29:18 +0000258InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
259 ScalarEvolution &SE, Value *&Index,
260 Value *&Length) {
261
262 auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) {
263 const SCEV *S = SE.getSCEV(V);
264 if (isa<SCEVCouldNotCompute>(S))
265 return false;
266
267 return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant &&
268 SE.isKnownNonNegative(S);
269 };
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000270
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000271 using namespace llvm::PatternMatch;
272
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000273 ICmpInst::Predicate Pred = ICI->getPredicate();
274 Value *LHS = ICI->getOperand(0);
275 Value *RHS = ICI->getOperand(1);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000276
277 switch (Pred) {
278 default:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000279 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000280
281 case ICmpInst::ICMP_SLE:
282 std::swap(LHS, RHS);
283 // fallthrough
284 case ICmpInst::ICMP_SGE:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000285 if (match(RHS, m_ConstantInt<0>())) {
286 Index = LHS;
287 return RANGE_CHECK_LOWER;
288 }
289 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000290
291 case ICmpInst::ICMP_SLT:
292 std::swap(LHS, RHS);
293 // fallthrough
294 case ICmpInst::ICMP_SGT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000295 if (match(RHS, m_ConstantInt<-1>())) {
296 Index = LHS;
297 return RANGE_CHECK_LOWER;
298 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000299
Sanjoy Das337d46b2015-03-24 19:29:18 +0000300 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000301 Index = RHS;
302 Length = LHS;
303 return RANGE_CHECK_UPPER;
304 }
305 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000306
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000307 case ICmpInst::ICMP_ULT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000308 std::swap(LHS, RHS);
309 // fallthrough
310 case ICmpInst::ICMP_UGT:
Sanjoy Das337d46b2015-03-24 19:29:18 +0000311 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000312 Index = RHS;
313 Length = LHS;
314 return RANGE_CHECK_BOTH;
315 }
316 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000317 }
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000318
319 llvm_unreachable("default clause returns!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000320}
321
Sanjoy Dasa0992682016-05-26 00:09:02 +0000322void InductiveRangeCheck::extractRangeChecksFromCond(
323 Loop *L, ScalarEvolution &SE, Use &ConditionUse,
324 SmallVectorImpl<InductiveRangeCheck> &Checks,
325 SmallPtrSetImpl<Value *> &Visited) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000326 using namespace llvm::PatternMatch;
327
Sanjoy Das8fe88922016-05-26 00:08:24 +0000328 Value *Condition = ConditionUse.get();
Sanjoy Dasa0992682016-05-26 00:09:02 +0000329 if (!Visited.insert(Condition).second)
330 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000331
Sanjoy Dasa0992682016-05-26 00:09:02 +0000332 if (match(Condition, m_And(m_Value(), m_Value()))) {
333 SmallVector<InductiveRangeCheck, 8> SubChecks;
334 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
335 SubChecks, Visited);
336 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
337 SubChecks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000338
Sanjoy Dasa0992682016-05-26 00:09:02 +0000339 if (SubChecks.size() == 2) {
340 // Handle a special case where we know how to merge two checks separately
341 // checking the upper and lower bounds into a full range check.
342 const auto &RChkA = SubChecks[0];
343 const auto &RChkB = SubChecks[1];
344 if ((RChkA.Length == RChkB.Length || !RChkA.Length || !RChkB.Length) &&
345 RChkA.Offset == RChkB.Offset && RChkA.Scale == RChkB.Scale) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000346
Sanjoy Dasa0992682016-05-26 00:09:02 +0000347 // If RChkA.Kind == RChkB.Kind then we just found two identical checks.
348 // But if one of them is a RANGE_CHECK_LOWER and the other is a
349 // RANGE_CHECK_UPPER (only possibility if they're different) then
350 // together they form a RANGE_CHECK_BOTH.
351 SubChecks[0].Kind =
352 (InductiveRangeCheck::RangeCheckKind)(RChkA.Kind | RChkB.Kind);
353 SubChecks[0].Length = RChkA.Length ? RChkA.Length : RChkB.Length;
354 SubChecks[0].CheckUse = &ConditionUse;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000355
Sanjoy Dasa0992682016-05-26 00:09:02 +0000356 // We updated one of the checks in place, now erase the other.
357 SubChecks.pop_back();
358 }
359 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000360
Sanjoy Dasa0992682016-05-26 00:09:02 +0000361 Checks.insert(Checks.end(), SubChecks.begin(), SubChecks.end());
362 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000363 }
364
Sanjoy Dasa0992682016-05-26 00:09:02 +0000365 ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);
366 if (!ICI)
367 return;
368
369 Value *Length = nullptr, *Index;
370 auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length);
371 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
372 return;
373
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000374 const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000375 bool IsAffineIndex =
376 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
377
378 if (!IsAffineIndex)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000379 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000380
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000381 InductiveRangeCheck IRC;
382 IRC.Length = Length;
383 IRC.Offset = IndexAddRec->getStart();
384 IRC.Scale = IndexAddRec->getStepRecurrence(SE);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000385 IRC.CheckUse = &ConditionUse;
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000386 IRC.Kind = RCKind;
Sanjoy Dasa0992682016-05-26 00:09:02 +0000387 Checks.push_back(IRC);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000388}
389
Sanjoy Dasa0992682016-05-26 00:09:02 +0000390void InductiveRangeCheck::extractRangeChecksFromBranch(
391 BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo &BPI,
392 SmallVectorImpl<InductiveRangeCheck> &Checks) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000393
394 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
Sanjoy Dasa0992682016-05-26 00:09:02 +0000395 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000396
397 BranchProbability LikelyTaken(15, 16);
398
Sanjoy Dasbb969792016-07-22 00:40:56 +0000399 if (!SkipProfitabilityChecks &&
400 BPI.getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000401 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000402
Sanjoy Dasa0992682016-05-26 00:09:02 +0000403 SmallPtrSet<Value *, 8> Visited;
404 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
405 Checks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000406}
407
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000408namespace {
409
Sanjoy Dase75ed922015-02-26 08:19:31 +0000410// Keeps track of the structure of a loop. This is similar to llvm::Loop,
411// except that it is more lightweight and can track the state of a loop through
412// changing and potentially invalid IR. This structure also formalizes the
413// kinds of loops we can deal with -- ones that have a single latch that is also
414// an exiting block *and* have a canonical induction variable.
415struct LoopStructure {
416 const char *Tag;
417
418 BasicBlock *Header;
419 BasicBlock *Latch;
420
421 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
422 // successor is `LatchExit', the exit block of the loop.
423 BranchInst *LatchBr;
424 BasicBlock *LatchExit;
425 unsigned LatchBrExitIdx;
426
427 Value *IndVarNext;
428 Value *IndVarStart;
429 Value *LoopExitAt;
430 bool IndVarIncreasing;
431
432 LoopStructure()
433 : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr),
434 LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr),
435 IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false) {}
436
437 template <typename M> LoopStructure map(M Map) const {
438 LoopStructure Result;
439 Result.Tag = Tag;
440 Result.Header = cast<BasicBlock>(Map(Header));
441 Result.Latch = cast<BasicBlock>(Map(Latch));
442 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
443 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
444 Result.LatchBrExitIdx = LatchBrExitIdx;
445 Result.IndVarNext = Map(IndVarNext);
446 Result.IndVarStart = Map(IndVarStart);
447 Result.LoopExitAt = Map(LoopExitAt);
448 Result.IndVarIncreasing = IndVarIncreasing;
449 return Result;
450 }
451
Sanjoy Dase91665d2015-02-26 08:56:04 +0000452 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
453 BranchProbabilityInfo &BPI,
454 Loop &,
Sanjoy Dase75ed922015-02-26 08:19:31 +0000455 const char *&);
456};
457
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000458/// This class is used to constrain loops to run within a given iteration space.
459/// The algorithm this class implements is given a Loop and a range [Begin,
460/// End). The algorithm then tries to break out a "main loop" out of the loop
461/// it is given in a way that the "main loop" runs with the induction variable
462/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
463/// loops to run any remaining iterations. The pre loop runs any iterations in
464/// which the induction variable is < Begin, and the post loop runs any
465/// iterations in which the induction variable is >= End.
466///
467class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000468 // The representation of a clone of the original loop we started out with.
469 struct ClonedLoop {
470 // The cloned blocks
471 std::vector<BasicBlock *> Blocks;
472
473 // `Map` maps values in the clonee into values in the cloned version
474 ValueToValueMapTy Map;
475
476 // An instance of `LoopStructure` for the cloned loop
477 LoopStructure Structure;
478 };
479
480 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
481 // more details on what these fields mean.
482 struct RewrittenRangeInfo {
483 BasicBlock *PseudoExit;
484 BasicBlock *ExitSelector;
485 std::vector<PHINode *> PHIValuesAtPseudoExit;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000486 PHINode *IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000487
Sanjoy Dase75ed922015-02-26 08:19:31 +0000488 RewrittenRangeInfo()
489 : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000490 };
491
492 // Calculated subranges we restrict the iteration space of the main loop to.
493 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000494 // these fields are computed. `LowLimit` is None if there is no restriction
495 // on low end of the restricted iteration space of the main loop. `HighLimit`
496 // is None if there is no restriction on high end of the restricted iteration
497 // space of the main loop.
498
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000499 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000500 Optional<const SCEV *> LowLimit;
501 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000502 };
503
504 // A utility function that does a `replaceUsesOfWith' on the incoming block
505 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
506 // incoming block list with `ReplaceBy'.
507 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
508 BasicBlock *ReplaceBy);
509
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000510 // Compute a safe set of limits for the main loop to run in -- effectively the
511 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000512 // Return None if unable to compute the set of subranges.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000513 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000514 Optional<SubRanges> calculateSubRanges() const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000515
516 // Clone `OriginalLoop' and return the result in CLResult. The IR after
517 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
518 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
519 // but there is no such edge.
520 //
521 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
522
523 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
524 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
525 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
526 // `OriginalHeaderCount'.
527 //
528 // If there are iterations left to execute, control is made to jump to
529 // `ContinuationBlock', otherwise they take the normal loop exit. The
530 // returned `RewrittenRangeInfo' object is populated as follows:
531 //
532 // .PseudoExit is a basic block that unconditionally branches to
533 // `ContinuationBlock'.
534 //
535 // .ExitSelector is a basic block that decides, on exit from the loop,
536 // whether to branch to the "true" exit or to `PseudoExit'.
537 //
538 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
539 // for each PHINode in the loop header on taking the pseudo exit.
540 //
541 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
542 // preheader because it is made to branch to the loop header only
543 // conditionally.
544 //
545 RewrittenRangeInfo
546 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
547 Value *ExitLoopAt,
548 BasicBlock *ContinuationBlock) const;
549
550 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
551 // function creates a new preheader for `LS' and returns it.
552 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000553 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
554 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000555
556 // `ContinuationBlockAndPreheader' was the continuation block for some call to
557 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
558 // This function rewrites the PHI nodes in `LS.Header' to start with the
559 // correct value.
560 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000561 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000562 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
563
564 // Even though we do not preserve any passes at this time, we at least need to
565 // keep the parent loop structure consistent. The `LPPassManager' seems to
566 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000567 // blocks denoted by BBs to this loops parent loop if required.
568 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000569
570 // Some global state.
571 Function &F;
572 LLVMContext &Ctx;
573 ScalarEvolution &SE;
Sanjoy Dasf45e03e2016-08-02 19:31:54 +0000574 DominatorTree &DT;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000575
576 // Information about the original loop we started out with.
577 Loop &OriginalLoop;
Sanjoy Das83a72852016-08-02 19:32:01 +0000578 LoopInfo &LI;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000579 const SCEV *LatchTakenCount;
580 BasicBlock *OriginalPreheader;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000581
582 // The preheader of the main loop. This may or may not be different from
583 // `OriginalPreheader'.
584 BasicBlock *MainLoopPreheader;
585
586 // The range we need to run the main loop in.
587 InductiveRangeCheck::Range Range;
588
589 // The structure of the main loop (see comment at the beginning of this class
590 // for a definition)
591 LoopStructure MainLoopStructure;
592
593public:
Sanjoy Dase75ed922015-02-26 08:19:31 +0000594 LoopConstrainer(Loop &L, LoopInfo &LI, const LoopStructure &LS,
Sanjoy Dasf45e03e2016-08-02 19:31:54 +0000595 ScalarEvolution &SE, DominatorTree &DT,
596 InductiveRangeCheck::Range R)
Sanjoy Dase75ed922015-02-26 08:19:31 +0000597 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
Sanjoy Das83a72852016-08-02 19:32:01 +0000598 SE(SE), DT(DT), OriginalLoop(L), LI(LI), LatchTakenCount(nullptr),
599 OriginalPreheader(nullptr), MainLoopPreheader(nullptr), Range(R),
600 MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000601
602 // Entry point for the algorithm. Returns true on success.
603 bool run();
604};
605
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000606}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000607
608void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
609 BasicBlock *ReplaceBy) {
610 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
611 if (PN->getIncomingBlock(i) == Block)
612 PN->setIncomingBlock(i, ReplaceBy);
613}
614
Sanjoy Dase75ed922015-02-26 08:19:31 +0000615static bool CanBeSMax(ScalarEvolution &SE, const SCEV *S) {
616 APInt SMax =
617 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
618 return SE.getSignedRange(S).contains(SMax) &&
619 SE.getUnsignedRange(S).contains(SMax);
620}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000621
Sanjoy Dase75ed922015-02-26 08:19:31 +0000622static bool CanBeSMin(ScalarEvolution &SE, const SCEV *S) {
623 APInt SMin =
624 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth());
625 return SE.getSignedRange(S).contains(SMin) &&
626 SE.getUnsignedRange(S).contains(SMin);
627}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000628
Sanjoy Dase75ed922015-02-26 08:19:31 +0000629Optional<LoopStructure>
Sanjoy Dase91665d2015-02-26 08:56:04 +0000630LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI,
631 Loop &L, const char *&FailureReason) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000632 assert(L.isLoopSimplifyForm() && "should follow from addRequired<>");
633
634 BasicBlock *Latch = L.getLoopLatch();
635 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000636 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000637 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000638 }
639
Sanjoy Dase75ed922015-02-26 08:19:31 +0000640 BasicBlock *Header = L.getHeader();
641 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000642 if (!Preheader) {
643 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000644 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000645 }
646
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000647 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000648 if (!LatchBr || LatchBr->isUnconditional()) {
649 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000650 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000651 }
652
Sanjoy Dase75ed922015-02-26 08:19:31 +0000653 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000654
Sanjoy Dase91665d2015-02-26 08:56:04 +0000655 BranchProbability ExitProbability =
656 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
657
Sanjoy Dasbb969792016-07-22 00:40:56 +0000658 if (!SkipProfitabilityChecks &&
659 ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
Sanjoy Dase91665d2015-02-26 08:56:04 +0000660 FailureReason = "short running loop, not profitable";
661 return None;
662 }
663
Sanjoy Dase75ed922015-02-26 08:19:31 +0000664 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
665 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
666 FailureReason = "latch terminator branch not conditional on integral icmp";
667 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000668 }
669
Sanjoy Dase75ed922015-02-26 08:19:31 +0000670 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
671 if (isa<SCEVCouldNotCompute>(LatchCount)) {
672 FailureReason = "could not compute latch count";
673 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000674 }
675
Sanjoy Dase75ed922015-02-26 08:19:31 +0000676 ICmpInst::Predicate Pred = ICI->getPredicate();
677 Value *LeftValue = ICI->getOperand(0);
678 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
679 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
680
681 Value *RightValue = ICI->getOperand(1);
682 const SCEV *RightSCEV = SE.getSCEV(RightValue);
683
684 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
685 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
686 if (isa<SCEVAddRecExpr>(RightSCEV)) {
687 std::swap(LeftSCEV, RightSCEV);
688 std::swap(LeftValue, RightValue);
689 Pred = ICmpInst::getSwappedPredicate(Pred);
690 } else {
691 FailureReason = "no add recurrences in the icmp";
692 return None;
693 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000694 }
695
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000696 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
697 if (AR->getNoWrapFlags(SCEV::FlagNSW))
698 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000699
700 IntegerType *Ty = cast<IntegerType>(AR->getType());
701 IntegerType *WideTy =
702 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
703
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000704 const SCEVAddRecExpr *ExtendAfterOp =
705 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
706 if (ExtendAfterOp) {
707 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
708 const SCEV *ExtendedStep =
709 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
710
711 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
712 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
713
714 if (NoSignedWrap)
715 return true;
716 }
717
718 // We may have proved this when computing the sign extension above.
719 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
720 };
721
722 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing) {
723 if (!AR->isAffine())
724 return false;
725
Sanjoy Dase75ed922015-02-26 08:19:31 +0000726 // Currently we only work with induction variables that have been proved to
727 // not wrap. This restriction can potentially be lifted in the future.
728
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000729 if (!HasNoSignedWrap(AR))
Sanjoy Dase75ed922015-02-26 08:19:31 +0000730 return false;
731
732 if (const SCEVConstant *StepExpr =
733 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
734 ConstantInt *StepCI = StepExpr->getValue();
735 if (StepCI->isOne() || StepCI->isMinusOne()) {
736 IsIncreasing = StepCI->isOne();
737 return true;
738 }
739 }
740
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000741 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000742 };
743
744 // `ICI` is interpreted as taking the backedge if the *next* value of the
745 // induction variable satisfies some constraint.
746
747 const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
748 bool IsIncreasing = false;
749 if (!IsInductionVar(IndVarNext, IsIncreasing)) {
750 FailureReason = "LHS in icmp not induction variable";
751 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000752 }
753
Sanjoy Dase75ed922015-02-26 08:19:31 +0000754 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
755 // TODO: generalize the predicates here to also match their unsigned variants.
756 if (IsIncreasing) {
757 bool FoundExpectedPred =
758 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) ||
759 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0);
760
761 if (!FoundExpectedPred) {
762 FailureReason = "expected icmp slt semantically, found something else";
763 return None;
764 }
765
766 if (LatchBrExitIdx == 0) {
767 if (CanBeSMax(SE, RightSCEV)) {
768 // TODO: this restriction is easily removable -- we just have to
769 // remember that the icmp was an slt and not an sle.
770 FailureReason = "limit may overflow when coercing sle to slt";
771 return None;
772 }
773
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000774 IRBuilder<> B(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000775 RightValue = B.CreateAdd(RightValue, One);
776 }
777
778 } else {
779 bool FoundExpectedPred =
780 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) ||
781 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0);
782
783 if (!FoundExpectedPred) {
784 FailureReason = "expected icmp sgt semantically, found something else";
785 return None;
786 }
787
788 if (LatchBrExitIdx == 0) {
789 if (CanBeSMin(SE, RightSCEV)) {
790 // TODO: this restriction is easily removable -- we just have to
791 // remember that the icmp was an sgt and not an sge.
792 FailureReason = "limit may overflow when coercing sge to sgt";
793 return None;
794 }
795
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000796 IRBuilder<> B(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000797 RightValue = B.CreateSub(RightValue, One);
798 }
799 }
800
801 const SCEV *StartNext = IndVarNext->getStart();
802 const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
803 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
804
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000805 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
806
Sanjoy Dase75ed922015-02-26 08:19:31 +0000807 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000808 ScalarEvolution::LoopInvariant &&
809 "loop variant exit count doesn't make sense!");
810
Sanjoy Dase75ed922015-02-26 08:19:31 +0000811 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000812 const DataLayout &DL = Preheader->getModule()->getDataLayout();
813 Value *IndVarStartV =
814 SCEVExpander(SE, DL, "irce")
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000815 .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000816 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000817
Sanjoy Dase75ed922015-02-26 08:19:31 +0000818 LoopStructure Result;
819
820 Result.Tag = "main";
821 Result.Header = Header;
822 Result.Latch = Latch;
823 Result.LatchBr = LatchBr;
824 Result.LatchExit = LatchExit;
825 Result.LatchBrExitIdx = LatchBrExitIdx;
826 Result.IndVarStart = IndVarStartV;
827 Result.IndVarNext = LeftValue;
828 Result.IndVarIncreasing = IsIncreasing;
829 Result.LoopExitAt = RightValue;
830
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000831 FailureReason = nullptr;
832
Sanjoy Dase75ed922015-02-26 08:19:31 +0000833 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000834}
835
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000836Optional<LoopConstrainer::SubRanges>
Sanjoy Dase75ed922015-02-26 08:19:31 +0000837LoopConstrainer::calculateSubRanges() const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000838 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
839
Sanjoy Das351db052015-01-22 09:32:02 +0000840 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000841 return None;
842
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000843 LoopConstrainer::SubRanges Result;
844
845 // I think we can be more aggressive here and make this nuw / nsw if the
846 // addition that feeds into the icmp for the latch's terminating branch is nuw
847 // / nsw. In any case, a wrapping 2's complement addition is safe.
848 ConstantInt *One = ConstantInt::get(Ty, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000849 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
850 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000851
Sanjoy Dase75ed922015-02-26 08:19:31 +0000852 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000853
Sanjoy Dase75ed922015-02-26 08:19:31 +0000854 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the
855 // range of values the induction variable takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000856
857 const SCEV *Smallest = nullptr, *Greatest = nullptr;
858
859 if (Increasing) {
860 Smallest = Start;
861 Greatest = End;
862 } else {
863 // These two computations may sign-overflow. Here is why that is okay:
864 //
865 // We know that the induction variable does not sign-overflow on any
866 // iteration except the last one, and it starts at `Start` and ends at
867 // `End`, decrementing by one every time.
868 //
869 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
870 // induction variable is decreasing we know that that the smallest value
871 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
872 //
873 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
874 // that case, `Clamp` will always return `Smallest` and
875 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
876 // will be an empty range. Returning an empty range is always safe.
877 //
878
879 Smallest = SE.getAddExpr(End, SE.getSCEV(One));
880 Greatest = SE.getAddExpr(Start, SE.getSCEV(One));
881 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000882
883 auto Clamp = [this, Smallest, Greatest](const SCEV *S) {
884 return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S));
885 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000886
887 // In some cases we can prove that we don't need a pre or post loop
888
889 bool ProvablyNoPreloop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000890 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest);
891 if (!ProvablyNoPreloop)
892 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000893
894 bool ProvablyNoPostLoop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000895 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd());
896 if (!ProvablyNoPostLoop)
897 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000898
899 return Result;
900}
901
902void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
903 const char *Tag) const {
904 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
905 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
906 Result.Blocks.push_back(Clone);
907 Result.Map[BB] = Clone;
908 }
909
910 auto GetClonedValue = [&Result](Value *V) {
911 assert(V && "null values not in domain!");
912 auto It = Result.Map.find(V);
913 if (It == Result.Map.end())
914 return V;
915 return static_cast<Value *>(It->second);
916 };
917
918 Result.Structure = MainLoopStructure.map(GetClonedValue);
919 Result.Structure.Tag = Tag;
920
921 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
922 BasicBlock *ClonedBB = Result.Blocks[i];
923 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
924
925 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
926
927 for (Instruction &I : *ClonedBB)
928 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000929 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000930
931 // Exit blocks will now have one more predecessor and their PHI nodes need
932 // to be edited to reflect that. No phi nodes need to be introduced because
933 // the loop is in LCSSA.
934
935 for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB);
936 SBBI != SBBE; ++SBBI) {
937
938 if (OriginalLoop.contains(*SBBI))
939 continue; // not an exit block
940
941 for (Instruction &I : **SBBI) {
942 if (!isa<PHINode>(&I))
943 break;
944
945 PHINode *PN = cast<PHINode>(&I);
946 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
947 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
948 }
949 }
950 }
951}
952
953LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000954 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000955 BasicBlock *ContinuationBlock) const {
956
957 // We start with a loop with a single latch:
958 //
959 // +--------------------+
960 // | |
961 // | preheader |
962 // | |
963 // +--------+-----------+
964 // | ----------------\
965 // | / |
966 // +--------v----v------+ |
967 // | | |
968 // | header | |
969 // | | |
970 // +--------------------+ |
971 // |
972 // ..... |
973 // |
974 // +--------------------+ |
975 // | | |
976 // | latch >----------/
977 // | |
978 // +-------v------------+
979 // |
980 // |
981 // | +--------------------+
982 // | | |
983 // +---> original exit |
984 // | |
985 // +--------------------+
986 //
987 // We change the control flow to look like
988 //
989 //
990 // +--------------------+
991 // | |
992 // | preheader >-------------------------+
993 // | | |
994 // +--------v-----------+ |
995 // | /-------------+ |
996 // | / | |
997 // +--------v--v--------+ | |
998 // | | | |
999 // | header | | +--------+ |
1000 // | | | | | |
1001 // +--------------------+ | | +-----v-----v-----------+
1002 // | | | |
1003 // | | | .pseudo.exit |
1004 // | | | |
1005 // | | +-----------v-----------+
1006 // | | |
1007 // ..... | | |
1008 // | | +--------v-------------+
1009 // +--------------------+ | | | |
1010 // | | | | | ContinuationBlock |
1011 // | latch >------+ | | |
1012 // | | | +----------------------+
1013 // +---------v----------+ |
1014 // | |
1015 // | |
1016 // | +---------------^-----+
1017 // | | |
1018 // +-----> .exit.selector |
1019 // | |
1020 // +----------v----------+
1021 // |
1022 // +--------------------+ |
1023 // | | |
1024 // | original exit <----+
1025 // | |
1026 // +--------------------+
1027 //
1028
1029 RewrittenRangeInfo RRI;
1030
1031 auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
1032 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001033 &F, &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001034 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001035 &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001036
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001037 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001038 bool Increasing = LS.IndVarIncreasing;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001039
1040 IRBuilder<> B(PreheaderJump);
1041
1042 // EnterLoopCond - is it okay to start executing this `LS'?
Sanjoy Dase75ed922015-02-26 08:19:31 +00001043 Value *EnterLoopCond = Increasing
1044 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1045 : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt);
1046
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001047 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1048 PreheaderJump->eraseFromParent();
1049
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001050 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001051 B.SetInsertPoint(LS.LatchBr);
1052 Value *TakeBackedgeLoopCond =
1053 Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1054 : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt);
1055 Value *CondForBranch = LS.LatchBrExitIdx == 1
1056 ? TakeBackedgeLoopCond
1057 : B.CreateNot(TakeBackedgeLoopCond);
1058
1059 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001060
1061 B.SetInsertPoint(RRI.ExitSelector);
1062
1063 // IterationsLeft - are there any more iterations left, given the original
1064 // upper bound on the induction variable? If not, we branch to the "real"
1065 // exit.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001066 Value *IterationsLeft = Increasing
1067 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1068 : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001069 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1070
1071 BranchInst *BranchToContinuation =
1072 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1073
1074 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1075 // each of the PHI nodes in the loop header. This feeds into the initial
1076 // value of the same PHI nodes if/when we continue execution.
1077 for (Instruction &I : *LS.Header) {
1078 if (!isa<PHINode>(&I))
1079 break;
1080
1081 PHINode *PN = cast<PHINode>(&I);
1082
1083 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1084 BranchToContinuation);
1085
1086 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1087 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1088 RRI.ExitSelector);
1089 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1090 }
1091
Sanjoy Dase75ed922015-02-26 08:19:31 +00001092 RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1093 BranchToContinuation);
1094 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1095 RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1096
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001097 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1098 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1099 for (Instruction &I : *LS.LatchExit) {
1100 if (PHINode *PN = dyn_cast<PHINode>(&I))
1101 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1102 else
1103 break;
1104 }
1105
1106 return RRI;
1107}
1108
1109void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001110 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001111 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1112
1113 unsigned PHIIndex = 0;
1114 for (Instruction &I : *LS.Header) {
1115 if (!isa<PHINode>(&I))
1116 break;
1117
1118 PHINode *PN = cast<PHINode>(&I);
1119
1120 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1121 if (PN->getIncomingBlock(i) == ContinuationBlock)
1122 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1123 }
1124
Sanjoy Dase75ed922015-02-26 08:19:31 +00001125 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001126}
1127
Sanjoy Dase75ed922015-02-26 08:19:31 +00001128BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1129 BasicBlock *OldPreheader,
1130 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001131
1132 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1133 BranchInst::Create(LS.Header, Preheader);
1134
1135 for (Instruction &I : *LS.Header) {
1136 if (!isa<PHINode>(&I))
1137 break;
1138
1139 PHINode *PN = cast<PHINode>(&I);
1140 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1141 replacePHIBlock(PN, OldPreheader, Preheader);
1142 }
1143
1144 return Preheader;
1145}
1146
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001147void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001148 Loop *ParentLoop = OriginalLoop.getParentLoop();
1149 if (!ParentLoop)
1150 return;
1151
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001152 for (BasicBlock *BB : BBs)
Sanjoy Das83a72852016-08-02 19:32:01 +00001153 ParentLoop->addBasicBlockToLoop(BB, LI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001154}
1155
1156bool LoopConstrainer::run() {
1157 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001158 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1159 Preheader = OriginalLoop.getLoopPreheader();
1160 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1161 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001162
1163 OriginalPreheader = Preheader;
1164 MainLoopPreheader = Preheader;
1165
Sanjoy Dase75ed922015-02-26 08:19:31 +00001166 Optional<SubRanges> MaybeSR = calculateSubRanges();
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001167 if (!MaybeSR.hasValue()) {
1168 DEBUG(dbgs() << "irce: could not compute subranges\n");
1169 return false;
1170 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001171
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001172 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001173 bool Increasing = MainLoopStructure.IndVarIncreasing;
1174 IntegerType *IVTy =
1175 cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1176
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001177 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001178 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001179
1180 // It would have been better to make `PreLoop' and `PostLoop'
1181 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1182 // constructor.
1183 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001184 bool NeedsPreLoop =
1185 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1186 bool NeedsPostLoop =
1187 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1188
1189 Value *ExitPreLoopAt = nullptr;
1190 Value *ExitMainLoopAt = nullptr;
1191 const SCEVConstant *MinusOneS =
1192 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1193
1194 if (NeedsPreLoop) {
1195 const SCEV *ExitPreLoopAtSCEV = nullptr;
1196
1197 if (Increasing)
1198 ExitPreLoopAtSCEV = *SR.LowLimit;
1199 else {
1200 if (CanBeSMin(SE, *SR.HighLimit)) {
1201 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1202 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1203 << "\n");
1204 return false;
1205 }
1206 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1207 }
1208
1209 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1210 ExitPreLoopAt->setName("exit.preloop.at");
1211 }
1212
1213 if (NeedsPostLoop) {
1214 const SCEV *ExitMainLoopAtSCEV = nullptr;
1215
1216 if (Increasing)
1217 ExitMainLoopAtSCEV = *SR.HighLimit;
1218 else {
1219 if (CanBeSMin(SE, *SR.LowLimit)) {
1220 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1221 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1222 << "\n");
1223 return false;
1224 }
1225 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1226 }
1227
1228 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1229 ExitMainLoopAt->setName("exit.mainloop.at");
1230 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001231
1232 // We clone these ahead of time so that we don't have to deal with changing
1233 // and temporarily invalid IR as we transform the loops.
1234 if (NeedsPreLoop)
1235 cloneLoop(PreLoop, "preloop");
1236 if (NeedsPostLoop)
1237 cloneLoop(PostLoop, "postloop");
1238
1239 RewrittenRangeInfo PreLoopRRI;
1240
1241 if (NeedsPreLoop) {
1242 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1243 PreLoop.Structure.Header);
1244
1245 MainLoopPreheader =
1246 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001247 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1248 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001249 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1250 PreLoopRRI);
1251 }
1252
1253 BasicBlock *PostLoopPreheader = nullptr;
1254 RewrittenRangeInfo PostLoopRRI;
1255
1256 if (NeedsPostLoop) {
1257 PostLoopPreheader =
1258 createPreheader(PostLoop.Structure, Preheader, "postloop");
1259 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001260 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001261 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1262 PostLoopRRI);
1263 }
1264
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001265 BasicBlock *NewMainLoopPreheader =
1266 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1267 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1268 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1269 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001270
1271 // Some of the above may be nullptr, filter them out before passing to
1272 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001273 auto NewBlocksEnd =
1274 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001275
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001276 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1277 addToParentLoopIfNeeded(PreLoop.Blocks);
1278 addToParentLoopIfNeeded(PostLoop.Blocks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001279
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001280 DT.recalculate(F);
Sanjoy Das83a72852016-08-02 19:32:01 +00001281 formLCSSARecursively(OriginalLoop, DT, &LI, &SE);
Sanjoy Dascf181862016-08-06 00:01:56 +00001282 simplifyLoop(&OriginalLoop, &DT, &LI, &SE, nullptr, true);
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001283
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001284 return true;
1285}
1286
Sanjoy Das95c476d2015-02-21 22:20:22 +00001287/// Computes and returns a range of values for the induction variable (IndVar)
1288/// in which the range check can be safely elided. If it cannot compute such a
1289/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001290Optional<InductiveRangeCheck::Range>
Sanjoy Das59776732016-05-21 02:31:51 +00001291InductiveRangeCheck::computeSafeIterationSpace(
1292 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001293 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1294 // variable, that may or may not exist as a real llvm::Value in the loop) and
1295 // this inductive range check is a range check on the "C + D * I" ("C" is
1296 // getOffset() and "D" is getScale()). We rewrite the value being range
1297 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1298 // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code
1299 // can be generalized as needed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001300 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001301 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001302 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001303 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1304 //
1305 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1306 // and subtractions are twos-complement wrapping and comparisons are signed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001307 //
1308 // Proof:
1309 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001310 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1311 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1312 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1313 // overflown.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001314 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001315 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1316 // Hence 0 <= (IndVar + M) < L
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001317
Sanjoy Das95c476d2015-02-21 22:20:22 +00001318 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1319 // 127, IndVar = 126 and L = -2 in an i8 world.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001320
Sanjoy Das95c476d2015-02-21 22:20:22 +00001321 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001322 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001323
Sanjoy Das95c476d2015-02-21 22:20:22 +00001324 const SCEV *A = IndVar->getStart();
1325 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1326 if (!B)
1327 return None;
1328
1329 const SCEV *C = getOffset();
1330 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1331 if (D != B)
1332 return None;
1333
1334 ConstantInt *ConstD = D->getValue();
1335 if (!(ConstD->isMinusOne() || ConstD->isOne()))
1336 return None;
1337
1338 const SCEV *M = SE.getMinusSCEV(C, A);
1339
1340 const SCEV *Begin = SE.getNegativeSCEV(M);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001341 const SCEV *UpperLimit = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001342
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001343 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1344 // We can potentially do much better here.
1345 if (Value *V = getLength()) {
1346 UpperLimit = SE.getSCEV(V);
1347 } else {
1348 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1349 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1350 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1351 }
1352
1353 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
Sanjoy Das351db052015-01-22 09:32:02 +00001354 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001355}
1356
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001357static Optional<InductiveRangeCheck::Range>
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001358IntersectRange(ScalarEvolution &SE,
1359 const Optional<InductiveRangeCheck::Range> &R1,
Sanjoy Das59776732016-05-21 02:31:51 +00001360 const InductiveRangeCheck::Range &R2) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001361 if (!R1.hasValue())
1362 return R2;
1363 auto &R1Value = R1.getValue();
1364
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001365 // TODO: we could widen the smaller range and have this work; but for now we
1366 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001367 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001368 return None;
1369
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001370 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1371 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1372
1373 return InductiveRangeCheck::Range(NewBegin, NewEnd);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001374}
1375
1376bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001377 if (skipLoop(L))
1378 return false;
1379
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001380 if (L->getBlocks().size() >= LoopSizeCutoff) {
1381 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1382 return false;
1383 }
1384
1385 BasicBlock *Preheader = L->getLoopPreheader();
1386 if (!Preheader) {
1387 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1388 return false;
1389 }
1390
1391 LLVMContext &Context = Preheader->getContext();
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001392 SmallVector<InductiveRangeCheck, 16> RangeChecks;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001393 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Cong Houab23bfb2015-07-15 22:48:29 +00001394 BranchProbabilityInfo &BPI =
1395 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001396
1397 for (auto BBI : L->getBlocks())
1398 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
Sanjoy Dasa0992682016-05-26 00:09:02 +00001399 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1400 RangeChecks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001401
1402 if (RangeChecks.empty())
1403 return false;
1404
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001405 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1406 OS << "irce: looking at loop "; L->print(OS);
1407 OS << "irce: loop has " << RangeChecks.size()
1408 << " inductive range checks: \n";
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001409 for (InductiveRangeCheck &IRC : RangeChecks)
1410 IRC.print(OS);
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001411 };
1412
1413 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1414
1415 if (PrintRangeChecks)
1416 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001417
Sanjoy Dase75ed922015-02-26 08:19:31 +00001418 const char *FailureReason = nullptr;
1419 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001420 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001421 if (!MaybeLoopStructure.hasValue()) {
1422 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1423 << "\n";);
1424 return false;
1425 }
1426 LoopStructure LS = MaybeLoopStructure.getValue();
1427 bool Increasing = LS.IndVarIncreasing;
1428 const SCEV *MinusOne =
1429 SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true);
1430 const SCEVAddRecExpr *IndVar =
1431 cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne));
1432
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001433 Optional<InductiveRangeCheck::Range> SafeIterRange;
1434 Instruction *ExprInsertPt = Preheader->getTerminator();
1435
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001436 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001437
1438 IRBuilder<> B(ExprInsertPt);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001439 for (InductiveRangeCheck &IRC : RangeChecks) {
1440 auto Result = IRC.computeSafeIterationSpace(SE, IndVar);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001441 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001442 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001443 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001444 if (MaybeSafeIterRange.hasValue()) {
1445 RangeChecksToEliminate.push_back(IRC);
1446 SafeIterRange = MaybeSafeIterRange.getValue();
1447 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001448 }
1449 }
1450
1451 if (!SafeIterRange.hasValue())
1452 return false;
1453
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001454 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001455 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LS,
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001456 SE, DT, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001457 bool Changed = LC.run();
1458
1459 if (Changed) {
1460 auto PrintConstrainedLoopInfo = [L]() {
1461 dbgs() << "irce: in function ";
1462 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1463 dbgs() << "constrained ";
1464 L->print(dbgs());
1465 };
1466
1467 DEBUG(PrintConstrainedLoopInfo());
1468
1469 if (PrintChangedLoops)
1470 PrintConstrainedLoopInfo();
1471
1472 // Optimize away the now-redundant range checks.
1473
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001474 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1475 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001476 ? ConstantInt::getTrue(Context)
1477 : ConstantInt::getFalse(Context);
Sanjoy Dasaa83c472016-05-23 22:16:45 +00001478 IRC.getCheckUse()->set(FoldedRangeCheck);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001479 }
1480 }
1481
1482 return Changed;
1483}
1484
1485Pass *llvm::createInductiveRangeCheckEliminationPass() {
1486 return new InductiveRangeCheckElimination;
1487}