blob: 5c4d55bfbb2b2db24708e8a5cd2e65f87ee729f7 [file] [log] [blame]
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001//===- InductiveRangeCheckElimination.cpp - -------------------------------===//
Sanjoy Dasa1837a32015-01-16 01:03:22 +00002//
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//===----------------------------------------------------------------------===//
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00009//
Sanjoy Dasa1837a32015-01-16 01:03:22 +000010// The InductiveRangeCheckElimination pass splits a loop's iteration space into
11// three disjoint ranges. It does that in a way such that the loop running in
12// the middle loop provably does not need range checks. As an example, it will
13// convert
14//
15// len = < known positive >
16// for (i = 0; i < n; i++) {
17// if (0 <= i && i < len) {
18// do_something();
19// } else {
20// throw_out_of_bounds();
21// }
22// }
23//
24// to
25//
26// len = < known positive >
27// limit = smin(n, len)
28// // no first segment
29// for (i = 0; i < limit; i++) {
30// if (0 <= i && i < len) { // this check is fully redundant
31// do_something();
32// } else {
33// throw_out_of_bounds();
34// }
35// }
36// for (i = limit; i < n; i++) {
37// if (0 <= i && i < len) {
38// do_something();
39// } else {
40// throw_out_of_bounds();
41// }
42// }
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000043//
Sanjoy Dasa1837a32015-01-16 01:03:22 +000044//===----------------------------------------------------------------------===//
45
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000046#include "llvm/ADT/APInt.h"
47#include "llvm/ADT/ArrayRef.h"
48#include "llvm/ADT/None.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000049#include "llvm/ADT/Optional.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000050#include "llvm/ADT/SmallPtrSet.h"
51#include "llvm/ADT/SmallVector.h"
52#include "llvm/ADT/StringRef.h"
53#include "llvm/ADT/Twine.h"
Sanjoy Dasdcf26512015-01-27 21:38:12 +000054#include "llvm/Analysis/BranchProbabilityInfo.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000055#include "llvm/Analysis/LoopInfo.h"
56#include "llvm/Analysis/LoopPass.h"
57#include "llvm/Analysis/ScalarEvolution.h"
58#include "llvm/Analysis/ScalarEvolutionExpander.h"
59#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000060#include "llvm/IR/BasicBlock.h"
61#include "llvm/IR/CFG.h"
62#include "llvm/IR/Constants.h"
63#include "llvm/IR/DerivedTypes.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000064#include "llvm/IR/Dominators.h"
65#include "llvm/IR/Function.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000066#include "llvm/IR/IRBuilder.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000067#include "llvm/IR/InstrTypes.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000068#include "llvm/IR/Instructions.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000069#include "llvm/IR/Metadata.h"
70#include "llvm/IR/Module.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000071#include "llvm/IR/PatternMatch.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000072#include "llvm/IR/Type.h"
73#include "llvm/IR/Use.h"
74#include "llvm/IR/User.h"
75#include "llvm/IR/Value.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000076#include "llvm/Pass.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000077#include "llvm/Support/BranchProbability.h"
78#include "llvm/Support/Casting.h"
79#include "llvm/Support/CommandLine.h"
80#include "llvm/Support/Compiler.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000081#include "llvm/Support/Debug.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000082#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000083#include "llvm/Support/raw_ostream.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000084#include "llvm/Transforms/Scalar.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000085#include "llvm/Transforms/Utils/Cloning.h"
Sanjoy Dascf181862016-08-06 00:01:56 +000086#include "llvm/Transforms/Utils/LoopSimplify.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000087#include "llvm/Transforms/Utils/LoopUtils.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000088#include "llvm/Transforms/Utils/ValueMapper.h"
89#include <algorithm>
90#include <cassert>
91#include <iterator>
92#include <limits>
93#include <utility>
94#include <vector>
Sanjoy Dasa1837a32015-01-16 01:03:22 +000095
96using namespace llvm;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000097using namespace llvm::PatternMatch;
Sanjoy Dasa1837a32015-01-16 01:03:22 +000098
Benjamin Kramer970eac42015-02-06 17:51:54 +000099static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
100 cl::init(64));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000101
Benjamin Kramer970eac42015-02-06 17:51:54 +0000102static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
103 cl::init(false));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000104
Sanjoy Das9c1bfae2015-03-17 01:40:22 +0000105static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
106 cl::init(false));
107
Sanjoy Dase91665d2015-02-26 08:56:04 +0000108static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
109 cl::Hidden, cl::init(10));
110
Sanjoy Dasbb969792016-07-22 00:40:56 +0000111static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks",
112 cl::Hidden, cl::init(false));
113
Max Kazantsev8aacef62017-10-04 06:53:22 +0000114static cl::opt<bool> AllowUnsignedLatchCondition("irce-allow-unsigned-latch",
Max Kazantsev9ac70212017-10-25 06:47:39 +0000115 cl::Hidden, cl::init(true));
Max Kazantsev8aacef62017-10-04 06:53:22 +0000116
Sanjoy Das7a18a232016-08-14 01:04:36 +0000117static const char *ClonedLoopTag = "irce.loop.clone";
118
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000119#define DEBUG_TYPE "irce"
120
121namespace {
122
123/// An inductive range check is conditional branch in a loop with
124///
125/// 1. a very cold successor (i.e. the branch jumps to that successor very
126/// rarely)
127///
128/// and
129///
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000130/// 2. a condition that is provably true for some contiguous range of values
131/// taken by the containing loop's induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000132///
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000133class InductiveRangeCheck {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000134 // Classifies a range check
Reid Kleckner0b168592015-03-17 16:50:20 +0000135 enum RangeCheckKind : unsigned {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000136 // Range check of the form "0 <= I".
137 RANGE_CHECK_LOWER = 1,
138
139 // Range check of the form "I < L" where L is known positive.
140 RANGE_CHECK_UPPER = 2,
141
142 // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER
143 // conditions.
144 RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
145
146 // Unrecognized range check condition.
147 RANGE_CHECK_UNKNOWN = (unsigned)-1
148 };
149
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000150 static StringRef rangeCheckKindToStr(RangeCheckKind);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000151
Max Kazantsev84286ce2017-10-31 06:19:05 +0000152 const SCEV *Begin = nullptr;
153 const SCEV *Step = nullptr;
154 const SCEV *End = nullptr;
Sanjoy Dasee77a482016-05-26 01:50:18 +0000155 Use *CheckUse = nullptr;
156 RangeCheckKind Kind = RANGE_CHECK_UNKNOWN;
Max Kazantsev9ac70212017-10-25 06:47:39 +0000157 bool IsSigned = true;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000158
Sanjoy Das337d46b2015-03-24 19:29:18 +0000159 static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
160 ScalarEvolution &SE, Value *&Index,
Max Kazantsev9ac70212017-10-25 06:47:39 +0000161 Value *&Length, bool &IsSigned);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000162
Sanjoy Dasa0992682016-05-26 00:09:02 +0000163 static void
164 extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,
165 SmallVectorImpl<InductiveRangeCheck> &Checks,
166 SmallPtrSetImpl<Value *> &Visited);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000167
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000168public:
Max Kazantsev84286ce2017-10-31 06:19:05 +0000169 const SCEV *getBegin() const { return Begin; }
170 const SCEV *getStep() const { return Step; }
171 const SCEV *getEnd() const { return End; }
Max Kazantsev9ac70212017-10-25 06:47:39 +0000172 bool isSigned() const { return IsSigned; }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000173
174 void print(raw_ostream &OS) const {
175 OS << "InductiveRangeCheck:\n";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000176 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n";
Max Kazantsev84286ce2017-10-31 06:19:05 +0000177 OS << " Begin: ";
178 Begin->print(OS);
179 OS << " Step: ";
180 Step->print(OS);
181 OS << " End: ";
182 if (End)
183 End->print(OS);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000184 else
185 OS << "(null)";
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000186 OS << "\n CheckUse: ";
187 getCheckUse()->getUser()->print(OS);
188 OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000189 }
190
Davide Italianod1279df2016-08-18 15:55:49 +0000191 LLVM_DUMP_METHOD
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000192 void dump() {
193 print(dbgs());
194 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000195
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000196 Use *getCheckUse() const { return CheckUse; }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000197
Sanjoy Das351db052015-01-22 09:32:02 +0000198 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
199 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
200
201 class Range {
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000202 const SCEV *Begin;
203 const SCEV *End;
Sanjoy Das351db052015-01-22 09:32:02 +0000204
205 public:
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000206 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
Sanjoy Das351db052015-01-22 09:32:02 +0000207 assert(Begin->getType() == End->getType() && "ill-typed range!");
208 }
209
210 Type *getType() const { return Begin->getType(); }
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000211 const SCEV *getBegin() const { return Begin; }
212 const SCEV *getEnd() const { return End; }
Max Kazantsev4332a942017-10-25 06:10:02 +0000213 bool isEmpty(ScalarEvolution &SE, bool IsSigned) const {
214 if (Begin == End)
215 return true;
216 if (IsSigned)
217 return SE.isKnownPredicate(ICmpInst::ICMP_SGE, Begin, End);
218 else
219 return SE.isKnownPredicate(ICmpInst::ICMP_UGE, Begin, End);
220 }
Sanjoy Das351db052015-01-22 09:32:02 +0000221 };
222
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000223 /// This is the value the condition of the branch needs to evaluate to for the
224 /// branch to take the hot successor (see (1) above).
225 bool getPassingDirection() { return true; }
226
Sanjoy Das95c476d2015-02-21 22:20:22 +0000227 /// Computes a range for the induction variable (IndVar) in which the range
228 /// check is redundant and can be constant-folded away. The induction
229 /// variable is not required to be the canonical {0,+,1} induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000230 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
Max Kazantsev26846782017-11-20 06:07:57 +0000231 const SCEVAddRecExpr *IndVar,
232 bool IsLatchSigned) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000233
Sanjoy Dasa0992682016-05-26 00:09:02 +0000234 /// Parse out a set of inductive range checks from \p BI and append them to \p
235 /// Checks.
236 ///
237 /// NB! There may be conditions feeding into \p BI that aren't inductive range
238 /// checks, and hence don't end up in \p Checks.
239 static void
240 extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE,
241 BranchProbabilityInfo &BPI,
242 SmallVectorImpl<InductiveRangeCheck> &Checks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000243};
244
245class InductiveRangeCheckElimination : public LoopPass {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000246public:
247 static char ID;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000248
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000249 InductiveRangeCheckElimination() : LoopPass(ID) {
250 initializeInductiveRangeCheckEliminationPass(
251 *PassRegistry::getPassRegistry());
252 }
253
254 void getAnalysisUsage(AnalysisUsage &AU) const override {
Cong Houab23bfb2015-07-15 22:48:29 +0000255 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000256 getLoopAnalysisUsage(AU);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000257 }
258
259 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
260};
261
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000262} // end anonymous namespace
263
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000264char InductiveRangeCheckElimination::ID = 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000265
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000266INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce",
267 "Inductive range check elimination", false, false)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000268INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000269INITIALIZE_PASS_DEPENDENCY(LoopPass)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000270INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce",
271 "Inductive range check elimination", false, false)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000272
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000273StringRef InductiveRangeCheck::rangeCheckKindToStr(
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000274 InductiveRangeCheck::RangeCheckKind RCK) {
275 switch (RCK) {
276 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
277 return "RANGE_CHECK_UNKNOWN";
278
279 case InductiveRangeCheck::RANGE_CHECK_UPPER:
280 return "RANGE_CHECK_UPPER";
281
282 case InductiveRangeCheck::RANGE_CHECK_LOWER:
283 return "RANGE_CHECK_LOWER";
284
285 case InductiveRangeCheck::RANGE_CHECK_BOTH:
286 return "RANGE_CHECK_BOTH";
287 }
288
289 llvm_unreachable("unknown range check type!");
290}
291
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000292/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000293/// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000294/// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000295/// range checked, and set `Length` to the upper limit `Index` is being range
296/// checked with if (and only if) the range check type is stronger or equal to
297/// RANGE_CHECK_UPPER.
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000298InductiveRangeCheck::RangeCheckKind
Sanjoy Das337d46b2015-03-24 19:29:18 +0000299InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
300 ScalarEvolution &SE, Value *&Index,
Max Kazantsev9ac70212017-10-25 06:47:39 +0000301 Value *&Length, bool &IsSigned) {
Sanjoy Das337d46b2015-03-24 19:29:18 +0000302 auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) {
303 const SCEV *S = SE.getSCEV(V);
304 if (isa<SCEVCouldNotCompute>(S))
305 return false;
306
307 return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant &&
308 SE.isKnownNonNegative(S);
309 };
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000310
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000311 ICmpInst::Predicate Pred = ICI->getPredicate();
312 Value *LHS = ICI->getOperand(0);
313 Value *RHS = ICI->getOperand(1);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000314
315 switch (Pred) {
316 default:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000317 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000318
319 case ICmpInst::ICMP_SLE:
320 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000321 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000322 case ICmpInst::ICMP_SGE:
Max Kazantsev9ac70212017-10-25 06:47:39 +0000323 IsSigned = true;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000324 if (match(RHS, m_ConstantInt<0>())) {
325 Index = LHS;
326 return RANGE_CHECK_LOWER;
327 }
328 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000329
330 case ICmpInst::ICMP_SLT:
331 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000332 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000333 case ICmpInst::ICMP_SGT:
Max Kazantsev9ac70212017-10-25 06:47:39 +0000334 IsSigned = true;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000335 if (match(RHS, m_ConstantInt<-1>())) {
336 Index = LHS;
337 return RANGE_CHECK_LOWER;
338 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000339
Sanjoy Das337d46b2015-03-24 19:29:18 +0000340 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000341 Index = RHS;
342 Length = LHS;
343 return RANGE_CHECK_UPPER;
344 }
345 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000346
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000347 case ICmpInst::ICMP_ULT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000348 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000349 LLVM_FALLTHROUGH;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000350 case ICmpInst::ICMP_UGT:
Max Kazantsev9ac70212017-10-25 06:47:39 +0000351 IsSigned = false;
Sanjoy Das337d46b2015-03-24 19:29:18 +0000352 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000353 Index = RHS;
354 Length = LHS;
355 return RANGE_CHECK_BOTH;
356 }
357 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000358 }
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000359
360 llvm_unreachable("default clause returns!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000361}
362
Sanjoy Dasa0992682016-05-26 00:09:02 +0000363void InductiveRangeCheck::extractRangeChecksFromCond(
364 Loop *L, ScalarEvolution &SE, Use &ConditionUse,
365 SmallVectorImpl<InductiveRangeCheck> &Checks,
366 SmallPtrSetImpl<Value *> &Visited) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000367 Value *Condition = ConditionUse.get();
Sanjoy Dasa0992682016-05-26 00:09:02 +0000368 if (!Visited.insert(Condition).second)
369 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000370
Max Kazantsev1ac6e8a2017-11-17 06:49:26 +0000371 // TODO: Do the same for OR, XOR, NOT etc?
Sanjoy Dasa0992682016-05-26 00:09:02 +0000372 if (match(Condition, m_And(m_Value(), m_Value()))) {
Sanjoy Dasa0992682016-05-26 00:09:02 +0000373 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
Max Kazantsev1ac6e8a2017-11-17 06:49:26 +0000374 Checks, Visited);
Sanjoy Dasa0992682016-05-26 00:09:02 +0000375 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
Max Kazantsev1ac6e8a2017-11-17 06:49:26 +0000376 Checks, Visited);
Sanjoy Dasa0992682016-05-26 00:09:02 +0000377 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000378 }
379
Sanjoy Dasa0992682016-05-26 00:09:02 +0000380 ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);
381 if (!ICI)
382 return;
383
384 Value *Length = nullptr, *Index;
Max Kazantsev9ac70212017-10-25 06:47:39 +0000385 bool IsSigned;
386 auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length, IsSigned);
Sanjoy Dasa0992682016-05-26 00:09:02 +0000387 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
388 return;
389
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000390 const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000391 bool IsAffineIndex =
392 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
393
394 if (!IsAffineIndex)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000395 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000396
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000397 InductiveRangeCheck IRC;
Max Kazantsev84286ce2017-10-31 06:19:05 +0000398 IRC.End = Length ? SE.getSCEV(Length) : nullptr;
399 IRC.Begin = IndexAddRec->getStart();
400 IRC.Step = IndexAddRec->getStepRecurrence(SE);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000401 IRC.CheckUse = &ConditionUse;
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000402 IRC.Kind = RCKind;
Max Kazantsev9ac70212017-10-25 06:47:39 +0000403 IRC.IsSigned = IsSigned;
Sanjoy Dasa0992682016-05-26 00:09:02 +0000404 Checks.push_back(IRC);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000405}
406
Sanjoy Dasa0992682016-05-26 00:09:02 +0000407void InductiveRangeCheck::extractRangeChecksFromBranch(
408 BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo &BPI,
409 SmallVectorImpl<InductiveRangeCheck> &Checks) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000410 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
Sanjoy Dasa0992682016-05-26 00:09:02 +0000411 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000412
413 BranchProbability LikelyTaken(15, 16);
414
Sanjoy Dasbb969792016-07-22 00:40:56 +0000415 if (!SkipProfitabilityChecks &&
416 BPI.getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000417 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000418
Sanjoy Dasa0992682016-05-26 00:09:02 +0000419 SmallPtrSet<Value *, 8> Visited;
420 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
421 Checks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000422}
423
Anna Thomas65ca8e92016-12-13 21:05:21 +0000424// Add metadata to the loop L to disable loop optimizations. Callers need to
425// confirm that optimizing loop L is not beneficial.
426static void DisableAllLoopOptsOnLoop(Loop &L) {
427 // We do not care about any existing loopID related metadata for L, since we
428 // are setting all loop metadata to false.
429 LLVMContext &Context = L.getHeader()->getContext();
430 // Reserve first location for self reference to the LoopID metadata node.
431 MDNode *Dummy = MDNode::get(Context, {});
432 MDNode *DisableUnroll = MDNode::get(
433 Context, {MDString::get(Context, "llvm.loop.unroll.disable")});
434 Metadata *FalseVal =
435 ConstantAsMetadata::get(ConstantInt::get(Type::getInt1Ty(Context), 0));
436 MDNode *DisableVectorize = MDNode::get(
437 Context,
438 {MDString::get(Context, "llvm.loop.vectorize.enable"), FalseVal});
439 MDNode *DisableLICMVersioning = MDNode::get(
440 Context, {MDString::get(Context, "llvm.loop.licm_versioning.disable")});
441 MDNode *DisableDistribution= MDNode::get(
442 Context,
443 {MDString::get(Context, "llvm.loop.distribute.enable"), FalseVal});
444 MDNode *NewLoopID =
445 MDNode::get(Context, {Dummy, DisableUnroll, DisableVectorize,
446 DisableLICMVersioning, DisableDistribution});
447 // Set operand 0 to refer to the loop id itself.
448 NewLoopID->replaceOperandWith(0, NewLoopID);
449 L.setLoopID(NewLoopID);
450}
451
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000452namespace {
453
Sanjoy Dase75ed922015-02-26 08:19:31 +0000454// Keeps track of the structure of a loop. This is similar to llvm::Loop,
455// except that it is more lightweight and can track the state of a loop through
456// changing and potentially invalid IR. This structure also formalizes the
457// kinds of loops we can deal with -- ones that have a single latch that is also
458// an exiting block *and* have a canonical induction variable.
459struct LoopStructure {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000460 const char *Tag = "";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000461
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000462 BasicBlock *Header = nullptr;
463 BasicBlock *Latch = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000464
465 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
466 // successor is `LatchExit', the exit block of the loop.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000467 BranchInst *LatchBr = nullptr;
468 BasicBlock *LatchExit = nullptr;
469 unsigned LatchBrExitIdx = std::numeric_limits<unsigned>::max();
Sanjoy Dase75ed922015-02-26 08:19:31 +0000470
Sanjoy Dasec892132017-02-07 23:59:07 +0000471 // The loop represented by this instance of LoopStructure is semantically
472 // equivalent to:
473 //
474 // intN_ty inc = IndVarIncreasing ? 1 : -1;
Serguei Katkov675e3042017-09-21 04:50:41 +0000475 // pred_ty predicate = IndVarIncreasing ? ICMP_SLT : ICMP_SGT;
Sanjoy Dasec892132017-02-07 23:59:07 +0000476 //
Serguei Katkov675e3042017-09-21 04:50:41 +0000477 // for (intN_ty iv = IndVarStart; predicate(iv, LoopExitAt); iv = IndVarBase)
Sanjoy Dasec892132017-02-07 23:59:07 +0000478 // ... body ...
479
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000480 Value *IndVarBase = nullptr;
481 Value *IndVarStart = nullptr;
482 Value *IndVarStep = nullptr;
483 Value *LoopExitAt = nullptr;
484 bool IndVarIncreasing = false;
485 bool IsSignedPredicate = true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000486
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000487 LoopStructure() = default;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000488
489 template <typename M> LoopStructure map(M Map) const {
490 LoopStructure Result;
491 Result.Tag = Tag;
492 Result.Header = cast<BasicBlock>(Map(Header));
493 Result.Latch = cast<BasicBlock>(Map(Latch));
494 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
495 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
496 Result.LatchBrExitIdx = LatchBrExitIdx;
Max Kazantseva22742b2017-08-31 05:58:15 +0000497 Result.IndVarBase = Map(IndVarBase);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000498 Result.IndVarStart = Map(IndVarStart);
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000499 Result.IndVarStep = Map(IndVarStep);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000500 Result.LoopExitAt = Map(LoopExitAt);
501 Result.IndVarIncreasing = IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000502 Result.IsSignedPredicate = IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000503 return Result;
504 }
505
Sanjoy Dase91665d2015-02-26 08:56:04 +0000506 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
507 BranchProbabilityInfo &BPI,
508 Loop &,
Sanjoy Dase75ed922015-02-26 08:19:31 +0000509 const char *&);
510};
511
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000512/// This class is used to constrain loops to run within a given iteration space.
513/// The algorithm this class implements is given a Loop and a range [Begin,
514/// End). The algorithm then tries to break out a "main loop" out of the loop
515/// it is given in a way that the "main loop" runs with the induction variable
516/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
517/// loops to run any remaining iterations. The pre loop runs any iterations in
518/// which the induction variable is < Begin, and the post loop runs any
519/// iterations in which the induction variable is >= End.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000520class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000521 // The representation of a clone of the original loop we started out with.
522 struct ClonedLoop {
523 // The cloned blocks
524 std::vector<BasicBlock *> Blocks;
525
526 // `Map` maps values in the clonee into values in the cloned version
527 ValueToValueMapTy Map;
528
529 // An instance of `LoopStructure` for the cloned loop
530 LoopStructure Structure;
531 };
532
533 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
534 // more details on what these fields mean.
535 struct RewrittenRangeInfo {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000536 BasicBlock *PseudoExit = nullptr;
537 BasicBlock *ExitSelector = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000538 std::vector<PHINode *> PHIValuesAtPseudoExit;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000539 PHINode *IndVarEnd = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000540
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000541 RewrittenRangeInfo() = default;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000542 };
543
544 // Calculated subranges we restrict the iteration space of the main loop to.
545 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000546 // these fields are computed. `LowLimit` is None if there is no restriction
547 // on low end of the restricted iteration space of the main loop. `HighLimit`
548 // is None if there is no restriction on high end of the restricted iteration
549 // space of the main loop.
550
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000551 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000552 Optional<const SCEV *> LowLimit;
553 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000554 };
555
556 // A utility function that does a `replaceUsesOfWith' on the incoming block
557 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
558 // incoming block list with `ReplaceBy'.
559 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
560 BasicBlock *ReplaceBy);
561
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000562 // Compute a safe set of limits for the main loop to run in -- effectively the
563 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000564 // Return None if unable to compute the set of subranges.
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000565 Optional<SubRanges> calculateSubRanges(bool IsSignedPredicate) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000566
567 // Clone `OriginalLoop' and return the result in CLResult. The IR after
568 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
569 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
570 // but there is no such edge.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000571 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
572
Sanjoy Das21434472016-08-14 01:04:46 +0000573 // Create the appropriate loop structure needed to describe a cloned copy of
574 // `Original`. The clone is described by `VM`.
575 Loop *createClonedLoopStructure(Loop *Original, Loop *Parent,
576 ValueToValueMapTy &VM);
577
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000578 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
579 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
580 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
581 // `OriginalHeaderCount'.
582 //
583 // If there are iterations left to execute, control is made to jump to
584 // `ContinuationBlock', otherwise they take the normal loop exit. The
585 // returned `RewrittenRangeInfo' object is populated as follows:
586 //
587 // .PseudoExit is a basic block that unconditionally branches to
588 // `ContinuationBlock'.
589 //
590 // .ExitSelector is a basic block that decides, on exit from the loop,
591 // whether to branch to the "true" exit or to `PseudoExit'.
592 //
593 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
594 // for each PHINode in the loop header on taking the pseudo exit.
595 //
596 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
597 // preheader because it is made to branch to the loop header only
598 // conditionally.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000599 RewrittenRangeInfo
600 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
601 Value *ExitLoopAt,
602 BasicBlock *ContinuationBlock) const;
603
604 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
605 // function creates a new preheader for `LS' and returns it.
Sanjoy Dase75ed922015-02-26 08:19:31 +0000606 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
607 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000608
609 // `ContinuationBlockAndPreheader' was the continuation block for some call to
610 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
611 // This function rewrites the PHI nodes in `LS.Header' to start with the
612 // correct value.
613 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000614 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000615 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
616
617 // Even though we do not preserve any passes at this time, we at least need to
618 // keep the parent loop structure consistent. The `LPPassManager' seems to
619 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000620 // blocks denoted by BBs to this loops parent loop if required.
621 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000622
623 // Some global state.
624 Function &F;
625 LLVMContext &Ctx;
626 ScalarEvolution &SE;
Sanjoy Dasf45e03e2016-08-02 19:31:54 +0000627 DominatorTree &DT;
Sanjoy Das21434472016-08-14 01:04:46 +0000628 LPPassManager &LPM;
Sanjoy Das35459f02016-08-14 01:04:50 +0000629 LoopInfo &LI;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000630
631 // Information about the original loop we started out with.
632 Loop &OriginalLoop;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000633
634 const SCEV *LatchTakenCount = nullptr;
635 BasicBlock *OriginalPreheader = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000636
637 // The preheader of the main loop. This may or may not be different from
638 // `OriginalPreheader'.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000639 BasicBlock *MainLoopPreheader = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000640
641 // The range we need to run the main loop in.
642 InductiveRangeCheck::Range Range;
643
644 // The structure of the main loop (see comment at the beginning of this class
645 // for a definition)
646 LoopStructure MainLoopStructure;
647
648public:
Sanjoy Das21434472016-08-14 01:04:46 +0000649 LoopConstrainer(Loop &L, LoopInfo &LI, LPPassManager &LPM,
650 const LoopStructure &LS, ScalarEvolution &SE,
651 DominatorTree &DT, InductiveRangeCheck::Range R)
Sanjoy Dase75ed922015-02-26 08:19:31 +0000652 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000653 SE(SE), DT(DT), LPM(LPM), LI(LI), OriginalLoop(L), Range(R),
654 MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000655
656 // Entry point for the algorithm. Returns true on success.
657 bool run();
658};
659
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000660} // end anonymous namespace
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000661
662void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
663 BasicBlock *ReplaceBy) {
664 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
665 if (PN->getIncomingBlock(i) == Block)
666 PN->setIncomingBlock(i, ReplaceBy);
667}
668
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000669static bool CanBeMax(ScalarEvolution &SE, const SCEV *S, bool Signed) {
670 APInt Max = Signed ?
671 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth()) :
672 APInt::getMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
673 return SE.getSignedRange(S).contains(Max) &&
674 SE.getUnsignedRange(S).contains(Max);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000675}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000676
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000677static bool SumCanReachMax(ScalarEvolution &SE, const SCEV *S1, const SCEV *S2,
678 bool Signed) {
679 // S1 < INT_MAX - S2 ===> S1 + S2 < INT_MAX.
680 assert(SE.isKnownNonNegative(S2) &&
681 "We expected the 2nd arg to be non-negative!");
682 const SCEV *Max = SE.getConstant(
683 Signed ? APInt::getSignedMaxValue(
684 cast<IntegerType>(S1->getType())->getBitWidth())
685 : APInt::getMaxValue(
686 cast<IntegerType>(S1->getType())->getBitWidth()));
687 const SCEV *CapForS1 = SE.getMinusSCEV(Max, S2);
688 return !SE.isKnownPredicate(Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
689 S1, CapForS1);
690}
691
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000692static bool CanBeMin(ScalarEvolution &SE, const SCEV *S, bool Signed) {
693 APInt Min = Signed ?
694 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth()) :
695 APInt::getMinValue(cast<IntegerType>(S->getType())->getBitWidth());
696 return SE.getSignedRange(S).contains(Min) &&
697 SE.getUnsignedRange(S).contains(Min);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000698}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000699
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000700static bool SumCanReachMin(ScalarEvolution &SE, const SCEV *S1, const SCEV *S2,
701 bool Signed) {
702 // S1 > INT_MIN - S2 ===> S1 + S2 > INT_MIN.
703 assert(SE.isKnownNonPositive(S2) &&
704 "We expected the 2nd arg to be non-positive!");
705 const SCEV *Max = SE.getConstant(
706 Signed ? APInt::getSignedMinValue(
707 cast<IntegerType>(S1->getType())->getBitWidth())
708 : APInt::getMinValue(
709 cast<IntegerType>(S1->getType())->getBitWidth()));
710 const SCEV *CapForS1 = SE.getMinusSCEV(Max, S2);
711 return !SE.isKnownPredicate(Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT,
712 S1, CapForS1);
713}
714
Sanjoy Dase75ed922015-02-26 08:19:31 +0000715Optional<LoopStructure>
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000716LoopStructure::parseLoopStructure(ScalarEvolution &SE,
717 BranchProbabilityInfo &BPI,
Sanjoy Dase91665d2015-02-26 08:56:04 +0000718 Loop &L, const char *&FailureReason) {
Sanjoy Das43fdc542016-08-14 01:04:31 +0000719 if (!L.isLoopSimplifyForm()) {
720 FailureReason = "loop not in LoopSimplify form";
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000721 return None;
Sanjoy Das43fdc542016-08-14 01:04:31 +0000722 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000723
724 BasicBlock *Latch = L.getLoopLatch();
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000725 assert(Latch && "Simplified loops only have one latch!");
726
Sanjoy Das7a18a232016-08-14 01:04:36 +0000727 if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) {
728 FailureReason = "loop has already been cloned";
729 return None;
730 }
731
Sanjoy Dase75ed922015-02-26 08:19:31 +0000732 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000733 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000734 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000735 }
736
Sanjoy Dase75ed922015-02-26 08:19:31 +0000737 BasicBlock *Header = L.getHeader();
738 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000739 if (!Preheader) {
740 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000741 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000742 }
743
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000744 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000745 if (!LatchBr || LatchBr->isUnconditional()) {
746 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000747 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000748 }
749
Sanjoy Dase75ed922015-02-26 08:19:31 +0000750 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000751
Sanjoy Dase91665d2015-02-26 08:56:04 +0000752 BranchProbability ExitProbability =
753 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
754
Sanjoy Dasbb969792016-07-22 00:40:56 +0000755 if (!SkipProfitabilityChecks &&
756 ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
Sanjoy Dase91665d2015-02-26 08:56:04 +0000757 FailureReason = "short running loop, not profitable";
758 return None;
759 }
760
Sanjoy Dase75ed922015-02-26 08:19:31 +0000761 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
762 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
763 FailureReason = "latch terminator branch not conditional on integral icmp";
764 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000765 }
766
Sanjoy Dase75ed922015-02-26 08:19:31 +0000767 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
768 if (isa<SCEVCouldNotCompute>(LatchCount)) {
769 FailureReason = "could not compute latch count";
770 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000771 }
772
Sanjoy Dase75ed922015-02-26 08:19:31 +0000773 ICmpInst::Predicate Pred = ICI->getPredicate();
774 Value *LeftValue = ICI->getOperand(0);
775 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
776 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
777
778 Value *RightValue = ICI->getOperand(1);
779 const SCEV *RightSCEV = SE.getSCEV(RightValue);
780
781 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
782 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
783 if (isa<SCEVAddRecExpr>(RightSCEV)) {
784 std::swap(LeftSCEV, RightSCEV);
785 std::swap(LeftValue, RightValue);
786 Pred = ICmpInst::getSwappedPredicate(Pred);
787 } else {
788 FailureReason = "no add recurrences in the icmp";
789 return None;
790 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000791 }
792
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000793 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
794 if (AR->getNoWrapFlags(SCEV::FlagNSW))
795 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000796
797 IntegerType *Ty = cast<IntegerType>(AR->getType());
798 IntegerType *WideTy =
799 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
800
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000801 const SCEVAddRecExpr *ExtendAfterOp =
802 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
803 if (ExtendAfterOp) {
804 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
805 const SCEV *ExtendedStep =
806 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
807
808 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
809 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
810
811 if (NoSignedWrap)
812 return true;
813 }
814
815 // We may have proved this when computing the sign extension above.
816 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
817 };
818
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000819 // Here we check whether the suggested AddRec is an induction variable that
820 // can be handled (i.e. with known constant step), and if yes, calculate its
821 // step and identify whether it is increasing or decreasing.
822 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing,
823 ConstantInt *&StepCI) {
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000824 if (!AR->isAffine())
825 return false;
826
Sanjoy Dase75ed922015-02-26 08:19:31 +0000827 // Currently we only work with induction variables that have been proved to
828 // not wrap. This restriction can potentially be lifted in the future.
829
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000830 if (!HasNoSignedWrap(AR))
Sanjoy Dase75ed922015-02-26 08:19:31 +0000831 return false;
832
833 if (const SCEVConstant *StepExpr =
834 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000835 StepCI = StepExpr->getValue();
Max Kazantsev85da7542017-08-01 06:27:51 +0000836 assert(!StepCI->isZero() && "Zero step?");
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000837 IsIncreasing = !StepCI->isNegative();
838 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000839 }
840
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000841 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000842 };
843
Serguei Katkov675e3042017-09-21 04:50:41 +0000844 // `ICI` is interpreted as taking the backedge if the *next* value of the
845 // induction variable satisfies some constraint.
Sanjoy Dase75ed922015-02-26 08:19:31 +0000846
Max Kazantseva22742b2017-08-31 05:58:15 +0000847 const SCEVAddRecExpr *IndVarBase = cast<SCEVAddRecExpr>(LeftSCEV);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000848 bool IsIncreasing = false;
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000849 bool IsSignedPredicate = true;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000850 ConstantInt *StepCI;
Max Kazantseva22742b2017-08-31 05:58:15 +0000851 if (!IsInductionVar(IndVarBase, IsIncreasing, StepCI)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000852 FailureReason = "LHS in icmp not induction variable";
853 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000854 }
855
Serguei Katkov675e3042017-09-21 04:50:41 +0000856 const SCEV *StartNext = IndVarBase->getStart();
857 const SCEV *Addend = SE.getNegativeSCEV(IndVarBase->getStepRecurrence(SE));
858 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000859 const SCEV *Step = SE.getSCEV(StepCI);
Sanjoy Dasec892132017-02-07 23:59:07 +0000860
Sanjoy Dase75ed922015-02-26 08:19:31 +0000861 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000862 if (IsIncreasing) {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000863 bool DecreasedRightValueByOne = false;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000864 if (StepCI->isOne()) {
865 // Try to turn eq/ne predicates to those we can work with.
866 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
867 // while (++i != len) { while (++i < len) {
868 // ... ---> ...
869 // } }
870 // If both parts are known non-negative, it is profitable to use
871 // unsigned comparison in increasing loop. This allows us to make the
872 // comparison check against "RightSCEV + 1" more optimistic.
873 if (SE.isKnownNonNegative(IndVarStart) &&
874 SE.isKnownNonNegative(RightSCEV))
875 Pred = ICmpInst::ICMP_ULT;
876 else
877 Pred = ICmpInst::ICMP_SLT;
878 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 &&
879 !CanBeMin(SE, RightSCEV, /* IsSignedPredicate */ true)) {
880 // while (true) { while (true) {
881 // if (++i == len) ---> if (++i > len - 1)
882 // break; break;
883 // ... ...
884 // } }
885 // TODO: Insert ICMP_UGT if both are non-negative?
886 Pred = ICmpInst::ICMP_SGT;
887 RightSCEV = SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType()));
888 DecreasedRightValueByOne = true;
889 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000890 }
891
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000892 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
893 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000894 bool FoundExpectedPred =
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000895 (LTPred && LatchBrExitIdx == 1) || (GTPred && LatchBrExitIdx == 0);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000896
897 if (!FoundExpectedPred) {
898 FailureReason = "expected icmp slt semantically, found something else";
899 return None;
900 }
901
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000902 IsSignedPredicate =
903 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
Max Kazantsev8aacef62017-10-04 06:53:22 +0000904
Max Kazantsev8aacef62017-10-04 06:53:22 +0000905 if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
906 FailureReason = "unsigned latch conditions are explicitly prohibited";
907 return None;
908 }
909
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000910 // The predicate that we need to check that the induction variable lies
911 // within bounds.
912 ICmpInst::Predicate BoundPred =
913 IsSignedPredicate ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
914
Sanjoy Dase75ed922015-02-26 08:19:31 +0000915 if (LatchBrExitIdx == 0) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000916 const SCEV *StepMinusOne = SE.getMinusSCEV(Step,
917 SE.getOne(Step->getType()));
918 if (SumCanReachMax(SE, RightSCEV, StepMinusOne, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000919 // TODO: this restriction is easily removable -- we just have to
920 // remember that the icmp was an slt and not an sle.
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000921 FailureReason = "limit may overflow when coercing le to lt";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000922 return None;
923 }
924
Sanjoy Dasec892132017-02-07 23:59:07 +0000925 if (!SE.isLoopEntryGuardedByCond(
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000926 &L, BoundPred, IndVarStart,
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000927 SE.getAddExpr(RightSCEV, Step))) {
Sanjoy Dasec892132017-02-07 23:59:07 +0000928 FailureReason = "Induction variable start not bounded by upper limit";
929 return None;
930 }
931
Max Kazantsev2c627a92017-07-18 04:53:48 +0000932 // We need to increase the right value unless we have already decreased
933 // it virtually when we replaced EQ with SGT.
934 if (!DecreasedRightValueByOne) {
935 IRBuilder<> B(Preheader->getTerminator());
936 RightValue = B.CreateAdd(RightValue, One);
937 }
Sanjoy Dasec892132017-02-07 23:59:07 +0000938 } else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000939 if (!SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) {
Sanjoy Dasec892132017-02-07 23:59:07 +0000940 FailureReason = "Induction variable start not bounded by upper limit";
941 return None;
942 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000943 assert(!DecreasedRightValueByOne &&
944 "Right value can be decreased only for LatchBrExitIdx == 0!");
Sanjoy Dase75ed922015-02-26 08:19:31 +0000945 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000946 } else {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000947 bool IncreasedRightValueByOne = false;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000948 if (StepCI->isMinusOne()) {
949 // Try to turn eq/ne predicates to those we can work with.
950 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
951 // while (--i != len) { while (--i > len) {
952 // ... ---> ...
953 // } }
954 // We intentionally don't turn the predicate into UGT even if we know
955 // that both operands are non-negative, because it will only pessimize
956 // our check against "RightSCEV - 1".
957 Pred = ICmpInst::ICMP_SGT;
958 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 &&
959 !CanBeMax(SE, RightSCEV, /* IsSignedPredicate */ true)) {
960 // while (true) { while (true) {
961 // if (--i == len) ---> if (--i < len + 1)
962 // break; break;
963 // ... ...
964 // } }
965 // TODO: Insert ICMP_ULT if both are non-negative?
966 Pred = ICmpInst::ICMP_SLT;
967 RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
968 IncreasedRightValueByOne = true;
969 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000970 }
971
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000972 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
973 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
974
Sanjoy Dase75ed922015-02-26 08:19:31 +0000975 bool FoundExpectedPred =
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000976 (GTPred && LatchBrExitIdx == 1) || (LTPred && LatchBrExitIdx == 0);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000977
978 if (!FoundExpectedPred) {
979 FailureReason = "expected icmp sgt semantically, found something else";
980 return None;
981 }
982
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000983 IsSignedPredicate =
984 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
Max Kazantsev8aacef62017-10-04 06:53:22 +0000985
Max Kazantsev8aacef62017-10-04 06:53:22 +0000986 if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
987 FailureReason = "unsigned latch conditions are explicitly prohibited";
988 return None;
989 }
990
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000991 // The predicate that we need to check that the induction variable lies
992 // within bounds.
993 ICmpInst::Predicate BoundPred =
994 IsSignedPredicate ? CmpInst::ICMP_SGT : CmpInst::ICMP_UGT;
995
Sanjoy Dase75ed922015-02-26 08:19:31 +0000996 if (LatchBrExitIdx == 0) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000997 const SCEV *StepPlusOne = SE.getAddExpr(Step, SE.getOne(Step->getType()));
998 if (SumCanReachMin(SE, RightSCEV, StepPlusOne, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000999 // TODO: this restriction is easily removable -- we just have to
1000 // remember that the icmp was an sgt and not an sge.
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001001 FailureReason = "limit may overflow when coercing ge to gt";
Sanjoy Dase75ed922015-02-26 08:19:31 +00001002 return None;
1003 }
1004
Sanjoy Dasec892132017-02-07 23:59:07 +00001005 if (!SE.isLoopEntryGuardedByCond(
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001006 &L, BoundPred, IndVarStart,
Sanjoy Dasec892132017-02-07 23:59:07 +00001007 SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType())))) {
1008 FailureReason = "Induction variable start not bounded by lower limit";
1009 return None;
1010 }
1011
Max Kazantsev2c627a92017-07-18 04:53:48 +00001012 // We need to decrease the right value unless we have already increased
1013 // it virtually when we replaced EQ with SLT.
1014 if (!IncreasedRightValueByOne) {
1015 IRBuilder<> B(Preheader->getTerminator());
1016 RightValue = B.CreateSub(RightValue, One);
1017 }
Sanjoy Dasec892132017-02-07 23:59:07 +00001018 } else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001019 if (!SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) {
Sanjoy Dasec892132017-02-07 23:59:07 +00001020 FailureReason = "Induction variable start not bounded by lower limit";
1021 return None;
1022 }
Max Kazantsev2c627a92017-07-18 04:53:48 +00001023 assert(!IncreasedRightValueByOne &&
1024 "Right value can be increased only for LatchBrExitIdx == 0!");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001025 }
1026 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001027 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
1028
Sanjoy Dase75ed922015-02-26 08:19:31 +00001029 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001030 ScalarEvolution::LoopInvariant &&
1031 "loop variant exit count doesn't make sense!");
1032
Sanjoy Dase75ed922015-02-26 08:19:31 +00001033 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001034 const DataLayout &DL = Preheader->getModule()->getDataLayout();
1035 Value *IndVarStartV =
1036 SCEVExpander(SE, DL, "irce")
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001037 .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001038 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001039
Sanjoy Dase75ed922015-02-26 08:19:31 +00001040 LoopStructure Result;
1041
1042 Result.Tag = "main";
1043 Result.Header = Header;
1044 Result.Latch = Latch;
1045 Result.LatchBr = LatchBr;
1046 Result.LatchExit = LatchExit;
1047 Result.LatchBrExitIdx = LatchBrExitIdx;
1048 Result.IndVarStart = IndVarStartV;
Max Kazantsev2f6ae282017-08-04 07:01:04 +00001049 Result.IndVarStep = StepCI;
Max Kazantseva22742b2017-08-31 05:58:15 +00001050 Result.IndVarBase = LeftValue;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001051 Result.IndVarIncreasing = IsIncreasing;
1052 Result.LoopExitAt = RightValue;
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001053 Result.IsSignedPredicate = IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001054
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001055 FailureReason = nullptr;
1056
Sanjoy Dase75ed922015-02-26 08:19:31 +00001057 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001058}
1059
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001060Optional<LoopConstrainer::SubRanges>
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001061LoopConstrainer::calculateSubRanges(bool IsSignedPredicate) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001062 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
1063
Sanjoy Das351db052015-01-22 09:32:02 +00001064 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001065 return None;
1066
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001067 LoopConstrainer::SubRanges Result;
1068
1069 // I think we can be more aggressive here and make this nuw / nsw if the
1070 // addition that feeds into the icmp for the latch's terminating branch is nuw
1071 // / nsw. In any case, a wrapping 2's complement addition is safe.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001072 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
1073 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001074
Sanjoy Dase75ed922015-02-26 08:19:31 +00001075 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001076
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001077 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest), or
1078 // [Smallest, GreatestSeen] is the range of values the induction variable
1079 // takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001080
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001081 const SCEV *Smallest = nullptr, *Greatest = nullptr, *GreatestSeen = nullptr;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001082
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001083 const SCEV *One = SE.getOne(Ty);
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001084 if (Increasing) {
1085 Smallest = Start;
1086 Greatest = End;
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001087 // No overflow, because the range [Smallest, GreatestSeen] is not empty.
1088 GreatestSeen = SE.getMinusSCEV(End, One);
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001089 } else {
1090 // These two computations may sign-overflow. Here is why that is okay:
1091 //
1092 // We know that the induction variable does not sign-overflow on any
1093 // iteration except the last one, and it starts at `Start` and ends at
1094 // `End`, decrementing by one every time.
1095 //
1096 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
1097 // induction variable is decreasing we know that that the smallest value
1098 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
1099 //
1100 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
1101 // that case, `Clamp` will always return `Smallest` and
1102 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
1103 // will be an empty range. Returning an empty range is always safe.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001104
Max Kazantsev6c466a32017-06-28 04:57:45 +00001105 Smallest = SE.getAddExpr(End, One);
1106 Greatest = SE.getAddExpr(Start, One);
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001107 GreatestSeen = Start;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001108 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001109
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001110 auto Clamp = [this, Smallest, Greatest, IsSignedPredicate](const SCEV *S) {
Max Kazantsev6f5229d72017-11-01 13:21:56 +00001111 return IsSignedPredicate
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001112 ? SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S))
1113 : SE.getUMaxExpr(Smallest, SE.getUMinExpr(Greatest, S));
Sanjoy Dase75ed922015-02-26 08:19:31 +00001114 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001115
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001116 // In some cases we can prove that we don't need a pre or post loop.
1117 ICmpInst::Predicate PredLE =
1118 IsSignedPredicate ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1119 ICmpInst::Predicate PredLT =
1120 IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001121
1122 bool ProvablyNoPreloop =
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001123 SE.isKnownPredicate(PredLE, Range.getBegin(), Smallest);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001124 if (!ProvablyNoPreloop)
1125 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001126
1127 bool ProvablyNoPostLoop =
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001128 SE.isKnownPredicate(PredLT, GreatestSeen, Range.getEnd());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001129 if (!ProvablyNoPostLoop)
1130 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001131
1132 return Result;
1133}
1134
1135void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
1136 const char *Tag) const {
1137 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
1138 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
1139 Result.Blocks.push_back(Clone);
1140 Result.Map[BB] = Clone;
1141 }
1142
1143 auto GetClonedValue = [&Result](Value *V) {
1144 assert(V && "null values not in domain!");
1145 auto It = Result.Map.find(V);
1146 if (It == Result.Map.end())
1147 return V;
1148 return static_cast<Value *>(It->second);
1149 };
1150
Sanjoy Das7a18a232016-08-14 01:04:36 +00001151 auto *ClonedLatch =
1152 cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch()));
1153 ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag,
1154 MDNode::get(Ctx, {}));
1155
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001156 Result.Structure = MainLoopStructure.map(GetClonedValue);
1157 Result.Structure.Tag = Tag;
1158
1159 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
1160 BasicBlock *ClonedBB = Result.Blocks[i];
1161 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
1162
1163 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
1164
1165 for (Instruction &I : *ClonedBB)
1166 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00001167 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001168
1169 // Exit blocks will now have one more predecessor and their PHI nodes need
1170 // to be edited to reflect that. No phi nodes need to be introduced because
1171 // the loop is in LCSSA.
1172
Sanjoy Dasd1d62a12016-08-13 22:00:09 +00001173 for (auto *SBB : successors(OriginalBB)) {
1174 if (OriginalLoop.contains(SBB))
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001175 continue; // not an exit block
1176
Sanjoy Dasd1d62a12016-08-13 22:00:09 +00001177 for (Instruction &I : *SBB) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001178 auto *PN = dyn_cast<PHINode>(&I);
1179 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001180 break;
1181
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001182 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
1183 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
1184 }
1185 }
1186 }
1187}
1188
1189LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001190 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001191 BasicBlock *ContinuationBlock) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001192 // We start with a loop with a single latch:
1193 //
1194 // +--------------------+
1195 // | |
1196 // | preheader |
1197 // | |
1198 // +--------+-----------+
1199 // | ----------------\
1200 // | / |
1201 // +--------v----v------+ |
1202 // | | |
1203 // | header | |
1204 // | | |
1205 // +--------------------+ |
1206 // |
1207 // ..... |
1208 // |
1209 // +--------------------+ |
1210 // | | |
1211 // | latch >----------/
1212 // | |
1213 // +-------v------------+
1214 // |
1215 // |
1216 // | +--------------------+
1217 // | | |
1218 // +---> original exit |
1219 // | |
1220 // +--------------------+
1221 //
1222 // We change the control flow to look like
1223 //
1224 //
1225 // +--------------------+
1226 // | |
1227 // | preheader >-------------------------+
1228 // | | |
1229 // +--------v-----------+ |
1230 // | /-------------+ |
1231 // | / | |
1232 // +--------v--v--------+ | |
1233 // | | | |
1234 // | header | | +--------+ |
1235 // | | | | | |
1236 // +--------------------+ | | +-----v-----v-----------+
1237 // | | | |
1238 // | | | .pseudo.exit |
1239 // | | | |
1240 // | | +-----------v-----------+
1241 // | | |
1242 // ..... | | |
1243 // | | +--------v-------------+
1244 // +--------------------+ | | | |
1245 // | | | | | ContinuationBlock |
1246 // | latch >------+ | | |
1247 // | | | +----------------------+
1248 // +---------v----------+ |
1249 // | |
1250 // | |
1251 // | +---------------^-----+
1252 // | | |
1253 // +-----> .exit.selector |
1254 // | |
1255 // +----------v----------+
1256 // |
1257 // +--------------------+ |
1258 // | | |
1259 // | original exit <----+
1260 // | |
1261 // +--------------------+
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001262
1263 RewrittenRangeInfo RRI;
1264
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001265 BasicBlock *BBInsertLocation = LS.Latch->getNextNode();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001266 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001267 &F, BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001268 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001269 BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001270
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001271 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001272 bool Increasing = LS.IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001273 bool IsSignedPredicate = LS.IsSignedPredicate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001274
1275 IRBuilder<> B(PreheaderJump);
1276
1277 // EnterLoopCond - is it okay to start executing this `LS'?
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001278 Value *EnterLoopCond = nullptr;
1279 if (Increasing)
1280 EnterLoopCond = IsSignedPredicate
1281 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1282 : B.CreateICmpULT(LS.IndVarStart, ExitSubloopAt);
1283 else
1284 EnterLoopCond = IsSignedPredicate
1285 ? B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt)
1286 : B.CreateICmpUGT(LS.IndVarStart, ExitSubloopAt);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001287
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001288 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1289 PreheaderJump->eraseFromParent();
1290
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001291 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001292 B.SetInsertPoint(LS.LatchBr);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001293 Value *TakeBackedgeLoopCond = nullptr;
1294 if (Increasing)
1295 TakeBackedgeLoopCond = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001296 ? B.CreateICmpSLT(LS.IndVarBase, ExitSubloopAt)
1297 : B.CreateICmpULT(LS.IndVarBase, ExitSubloopAt);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001298 else
1299 TakeBackedgeLoopCond = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001300 ? B.CreateICmpSGT(LS.IndVarBase, ExitSubloopAt)
1301 : B.CreateICmpUGT(LS.IndVarBase, ExitSubloopAt);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001302 Value *CondForBranch = LS.LatchBrExitIdx == 1
1303 ? TakeBackedgeLoopCond
1304 : B.CreateNot(TakeBackedgeLoopCond);
1305
1306 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001307
1308 B.SetInsertPoint(RRI.ExitSelector);
1309
1310 // IterationsLeft - are there any more iterations left, given the original
1311 // upper bound on the induction variable? If not, we branch to the "real"
1312 // exit.
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001313 Value *IterationsLeft = nullptr;
1314 if (Increasing)
1315 IterationsLeft = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001316 ? B.CreateICmpSLT(LS.IndVarBase, LS.LoopExitAt)
1317 : B.CreateICmpULT(LS.IndVarBase, LS.LoopExitAt);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001318 else
1319 IterationsLeft = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001320 ? B.CreateICmpSGT(LS.IndVarBase, LS.LoopExitAt)
1321 : B.CreateICmpUGT(LS.IndVarBase, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001322 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1323
1324 BranchInst *BranchToContinuation =
1325 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1326
1327 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1328 // each of the PHI nodes in the loop header. This feeds into the initial
1329 // value of the same PHI nodes if/when we continue execution.
1330 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001331 auto *PN = dyn_cast<PHINode>(&I);
1332 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001333 break;
1334
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001335 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1336 BranchToContinuation);
1337
1338 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
Serguei Katkov675e3042017-09-21 04:50:41 +00001339 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1340 RRI.ExitSelector);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001341 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1342 }
1343
Max Kazantseva22742b2017-08-31 05:58:15 +00001344 RRI.IndVarEnd = PHINode::Create(LS.IndVarBase->getType(), 2, "indvar.end",
Sanjoy Dase75ed922015-02-26 08:19:31 +00001345 BranchToContinuation);
1346 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
Max Kazantseva22742b2017-08-31 05:58:15 +00001347 RRI.IndVarEnd->addIncoming(LS.IndVarBase, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001348
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001349 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1350 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1351 for (Instruction &I : *LS.LatchExit) {
1352 if (PHINode *PN = dyn_cast<PHINode>(&I))
1353 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1354 else
1355 break;
1356 }
1357
1358 return RRI;
1359}
1360
1361void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001362 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001363 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001364 unsigned PHIIndex = 0;
1365 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001366 auto *PN = dyn_cast<PHINode>(&I);
1367 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001368 break;
1369
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001370 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1371 if (PN->getIncomingBlock(i) == ContinuationBlock)
1372 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1373 }
1374
Sanjoy Dase75ed922015-02-26 08:19:31 +00001375 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001376}
1377
Sanjoy Dase75ed922015-02-26 08:19:31 +00001378BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1379 BasicBlock *OldPreheader,
1380 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001381 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1382 BranchInst::Create(LS.Header, Preheader);
1383
1384 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001385 auto *PN = dyn_cast<PHINode>(&I);
1386 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001387 break;
1388
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001389 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1390 replacePHIBlock(PN, OldPreheader, Preheader);
1391 }
1392
1393 return Preheader;
1394}
1395
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001396void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001397 Loop *ParentLoop = OriginalLoop.getParentLoop();
1398 if (!ParentLoop)
1399 return;
1400
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001401 for (BasicBlock *BB : BBs)
Sanjoy Das83a72852016-08-02 19:32:01 +00001402 ParentLoop->addBasicBlockToLoop(BB, LI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001403}
1404
Sanjoy Das21434472016-08-14 01:04:46 +00001405Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent,
1406 ValueToValueMapTy &VM) {
Sanjoy Dasdef17292017-09-28 02:45:42 +00001407 Loop &New = *LI.AllocateLoop();
Chandler Carruth29c22d22017-05-25 03:01:31 +00001408 if (Parent)
1409 Parent->addChildLoop(&New);
1410 else
1411 LI.addTopLevelLoop(&New);
1412 LPM.addLoop(New);
Sanjoy Das21434472016-08-14 01:04:46 +00001413
1414 // Add all of the blocks in Original to the new loop.
1415 for (auto *BB : Original->blocks())
1416 if (LI.getLoopFor(BB) == Original)
1417 New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI);
1418
1419 // Add all of the subloops to the new loop.
1420 for (Loop *SubLoop : *Original)
1421 createClonedLoopStructure(SubLoop, &New, VM);
1422
1423 return &New;
1424}
1425
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001426bool LoopConstrainer::run() {
1427 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001428 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1429 Preheader = OriginalLoop.getLoopPreheader();
1430 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1431 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001432
1433 OriginalPreheader = Preheader;
1434 MainLoopPreheader = Preheader;
1435
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001436 bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate;
1437 Optional<SubRanges> MaybeSR = calculateSubRanges(IsSignedPredicate);
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001438 if (!MaybeSR.hasValue()) {
1439 DEBUG(dbgs() << "irce: could not compute subranges\n");
1440 return false;
1441 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001442
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001443 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001444 bool Increasing = MainLoopStructure.IndVarIncreasing;
1445 IntegerType *IVTy =
Max Kazantseva22742b2017-08-31 05:58:15 +00001446 cast<IntegerType>(MainLoopStructure.IndVarBase->getType());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001447
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001448 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001449 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001450
1451 // It would have been better to make `PreLoop' and `PostLoop'
1452 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1453 // constructor.
1454 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001455 bool NeedsPreLoop =
1456 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1457 bool NeedsPostLoop =
1458 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1459
1460 Value *ExitPreLoopAt = nullptr;
1461 Value *ExitMainLoopAt = nullptr;
1462 const SCEVConstant *MinusOneS =
1463 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1464
1465 if (NeedsPreLoop) {
1466 const SCEV *ExitPreLoopAtSCEV = nullptr;
1467
1468 if (Increasing)
1469 ExitPreLoopAtSCEV = *SR.LowLimit;
1470 else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001471 if (CanBeMin(SE, *SR.HighLimit, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +00001472 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1473 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1474 << "\n");
1475 return false;
1476 }
1477 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1478 }
Serguei Katkov675e3042017-09-21 04:50:41 +00001479
Max Kazantsevb1b8aff2017-11-16 06:06:27 +00001480 if (!isSafeToExpandAt(ExitPreLoopAtSCEV, InsertPt, SE)) {
1481 DEBUG(dbgs() << "irce: could not prove that it is safe to expand the"
1482 << " preloop exit limit " << *ExitPreLoopAtSCEV
1483 << " at block " << InsertPt->getParent()->getName() << "\n");
1484 return false;
1485 }
1486
Sanjoy Dase75ed922015-02-26 08:19:31 +00001487 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1488 ExitPreLoopAt->setName("exit.preloop.at");
1489 }
1490
1491 if (NeedsPostLoop) {
1492 const SCEV *ExitMainLoopAtSCEV = nullptr;
1493
1494 if (Increasing)
1495 ExitMainLoopAtSCEV = *SR.HighLimit;
1496 else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001497 if (CanBeMin(SE, *SR.LowLimit, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +00001498 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1499 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1500 << "\n");
1501 return false;
1502 }
1503 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1504 }
Serguei Katkov675e3042017-09-21 04:50:41 +00001505
Max Kazantsevb1b8aff2017-11-16 06:06:27 +00001506 if (!isSafeToExpandAt(ExitMainLoopAtSCEV, InsertPt, SE)) {
1507 DEBUG(dbgs() << "irce: could not prove that it is safe to expand the"
1508 << " main loop exit limit " << *ExitMainLoopAtSCEV
1509 << " at block " << InsertPt->getParent()->getName() << "\n");
1510 return false;
1511 }
1512
Sanjoy Dase75ed922015-02-26 08:19:31 +00001513 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1514 ExitMainLoopAt->setName("exit.mainloop.at");
1515 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001516
1517 // We clone these ahead of time so that we don't have to deal with changing
1518 // and temporarily invalid IR as we transform the loops.
1519 if (NeedsPreLoop)
1520 cloneLoop(PreLoop, "preloop");
1521 if (NeedsPostLoop)
1522 cloneLoop(PostLoop, "postloop");
1523
1524 RewrittenRangeInfo PreLoopRRI;
1525
1526 if (NeedsPreLoop) {
1527 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1528 PreLoop.Structure.Header);
1529
1530 MainLoopPreheader =
1531 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001532 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1533 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001534 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1535 PreLoopRRI);
1536 }
1537
1538 BasicBlock *PostLoopPreheader = nullptr;
1539 RewrittenRangeInfo PostLoopRRI;
1540
1541 if (NeedsPostLoop) {
1542 PostLoopPreheader =
1543 createPreheader(PostLoop.Structure, Preheader, "postloop");
1544 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001545 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001546 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1547 PostLoopRRI);
1548 }
1549
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001550 BasicBlock *NewMainLoopPreheader =
1551 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1552 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1553 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1554 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001555
1556 // Some of the above may be nullptr, filter them out before passing to
1557 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001558 auto NewBlocksEnd =
1559 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001560
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001561 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001562
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001563 DT.recalculate(F);
Sanjoy Das21434472016-08-14 01:04:46 +00001564
Anna Thomas72180322017-06-06 14:54:01 +00001565 // We need to first add all the pre and post loop blocks into the loop
1566 // structures (as part of createClonedLoopStructure), and then update the
1567 // LCSSA form and LoopSimplifyForm. This is necessary for correctly updating
1568 // LI when LoopSimplifyForm is generated.
1569 Loop *PreL = nullptr, *PostL = nullptr;
Sanjoy Das21434472016-08-14 01:04:46 +00001570 if (!PreLoop.Blocks.empty()) {
Anna Thomas72180322017-06-06 14:54:01 +00001571 PreL = createClonedLoopStructure(
Sanjoy Das21434472016-08-14 01:04:46 +00001572 &OriginalLoop, OriginalLoop.getParentLoop(), PreLoop.Map);
Sanjoy Das21434472016-08-14 01:04:46 +00001573 }
1574
1575 if (!PostLoop.Blocks.empty()) {
Anna Thomas72180322017-06-06 14:54:01 +00001576 PostL = createClonedLoopStructure(
Sanjoy Das21434472016-08-14 01:04:46 +00001577 &OriginalLoop, OriginalLoop.getParentLoop(), PostLoop.Map);
Sanjoy Das21434472016-08-14 01:04:46 +00001578 }
1579
Anna Thomas72180322017-06-06 14:54:01 +00001580 // This function canonicalizes the loop into Loop-Simplify and LCSSA forms.
1581 auto CanonicalizeLoop = [&] (Loop *L, bool IsOriginalLoop) {
1582 formLCSSARecursively(*L, DT, &LI, &SE);
1583 simplifyLoop(L, &DT, &LI, &SE, nullptr, true);
1584 // Pre/post loops are slow paths, we do not need to perform any loop
1585 // optimizations on them.
1586 if (!IsOriginalLoop)
1587 DisableAllLoopOptsOnLoop(*L);
1588 };
1589 if (PreL)
1590 CanonicalizeLoop(PreL, false);
1591 if (PostL)
1592 CanonicalizeLoop(PostL, false);
1593 CanonicalizeLoop(&OriginalLoop, true);
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001594
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001595 return true;
1596}
1597
Sanjoy Das95c476d2015-02-21 22:20:22 +00001598/// Computes and returns a range of values for the induction variable (IndVar)
1599/// in which the range check can be safely elided. If it cannot compute such a
1600/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001601Optional<InductiveRangeCheck::Range>
Sanjoy Das59776732016-05-21 02:31:51 +00001602InductiveRangeCheck::computeSafeIterationSpace(
Max Kazantsev26846782017-11-20 06:07:57 +00001603 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar,
1604 bool IsLatchSigned) const {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001605 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1606 // variable, that may or may not exist as a real llvm::Value in the loop) and
1607 // this inductive range check is a range check on the "C + D * I" ("C" is
Max Kazantsev84286ce2017-10-31 06:19:05 +00001608 // getBegin() and "D" is getStep()). We rewrite the value being range
Sanjoy Das95c476d2015-02-21 22:20:22 +00001609 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001610 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001611 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001612 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001613 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1614 //
Max Kazantsev26846782017-11-20 06:07:57 +00001615 // Here L stands for upper limit of the safe iteration space.
1616 // The inequality is satisfied by (0 - M) <= IndVar < (L - M). To avoid
1617 // overflows when calculating (0 - M) and (L - M) we, depending on type of
1618 // IV's iteration space, limit the calculations by borders of the iteration
1619 // space. For example, if IndVar is unsigned, (0 - M) overflows for any M > 0.
1620 // If we figured out that "anything greater than (-M) is safe", we strengthen
1621 // this to "everything greater than 0 is safe", assuming that values between
1622 // -M and 0 just do not exist in unsigned iteration space, and we don't want
1623 // to deal with overflown values.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001624
Sanjoy Das95c476d2015-02-21 22:20:22 +00001625 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001626 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001627
Sanjoy Das95c476d2015-02-21 22:20:22 +00001628 const SCEV *A = IndVar->getStart();
1629 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1630 if (!B)
1631 return None;
Max Kazantseve4c220e2017-08-01 06:49:29 +00001632 assert(!B->isZero() && "Recurrence with zero step?");
Sanjoy Das95c476d2015-02-21 22:20:22 +00001633
Max Kazantsev84286ce2017-10-31 06:19:05 +00001634 const SCEV *C = getBegin();
1635 const SCEVConstant *D = dyn_cast<SCEVConstant>(getStep());
Sanjoy Das95c476d2015-02-21 22:20:22 +00001636 if (D != B)
1637 return None;
1638
Max Kazantsev95054702017-08-04 07:41:24 +00001639 assert(!D->getValue()->isZero() && "Recurrence with zero step?");
Max Kazantsev26846782017-11-20 06:07:57 +00001640 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1641 const SCEV *SIntMax = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
Sanjoy Das95c476d2015-02-21 22:20:22 +00001642
Max Kazantsev26846782017-11-20 06:07:57 +00001643 // Substract Y from X so that it does not go through border of the IV
1644 // iteration space. Mathematically, it is equivalent to:
1645 //
1646 // ClampedSubstract(X, Y) = min(max(X - Y, INT_MIN), INT_MAX). [1]
1647 //
1648 // In [1], 'X - Y' is a mathematical substraction (result is not bounded to
1649 // any width of bit grid). But after we take min/max, the result is
1650 // guaranteed to be within [INT_MIN, INT_MAX].
1651 //
1652 // In [1], INT_MAX and INT_MIN are respectively signed and unsigned max/min
1653 // values, depending on type of latch condition that defines IV iteration
1654 // space.
1655 auto ClampedSubstract = [&](const SCEV *X, const SCEV *Y) {
1656 assert(SE.isKnownNonNegative(X) &&
1657 "We can only substract from values in [0; SINT_MAX]!");
1658 if (IsLatchSigned) {
1659 // X is a number from signed range, Y is interpreted as signed.
1660 // Even if Y is SINT_MAX, (X - Y) does not reach SINT_MIN. So the only
1661 // thing we should care about is that we didn't cross SINT_MAX.
1662 // So, if Y is positive, we substract Y safely.
1663 // Rule 1: Y > 0 ---> Y.
1664 // If 0 <= -Y <= (SINT_MAX - X), we substract Y safely.
1665 // Rule 2: Y >=s (X - SINT_MAX) ---> Y.
1666 // If 0 <= (SINT_MAX - X) < -Y, we can only substract (X - SINT_MAX).
1667 // Rule 3: Y <s (X - SINT_MAX) ---> (X - SINT_MAX).
1668 // It gives us smax(Y, X - SINT_MAX) to substract in all cases.
1669 const SCEV *XMinusSIntMax = SE.getMinusSCEV(X, SIntMax);
Max Kazantsev716e6472017-11-23 06:14:39 +00001670 return SE.getMinusSCEV(X, SE.getSMaxExpr(Y, XMinusSIntMax),
1671 SCEV::FlagNSW);
Max Kazantsev26846782017-11-20 06:07:57 +00001672 } else
1673 // X is a number from unsigned range, Y is interpreted as signed.
1674 // Even if Y is SINT_MIN, (X - Y) does not reach UINT_MAX. So the only
1675 // thing we should care about is that we didn't cross zero.
1676 // So, if Y is negative, we substract Y safely.
1677 // Rule 1: Y <s 0 ---> Y.
1678 // If 0 <= Y <= X, we substract Y safely.
1679 // Rule 2: Y <=s X ---> Y.
1680 // If 0 <= X < Y, we should stop at 0 and can only substract X.
1681 // Rule 3: Y >s X ---> X.
1682 // It gives us smin(X, Y) to substract in all cases.
Max Kazantsev716e6472017-11-23 06:14:39 +00001683 return SE.getMinusSCEV(X, SE.getSMinExpr(X, Y), SCEV::FlagNUW);
Max Kazantsev26846782017-11-20 06:07:57 +00001684 };
Sanjoy Das95c476d2015-02-21 22:20:22 +00001685 const SCEV *M = SE.getMinusSCEV(C, A);
Max Kazantsev26846782017-11-20 06:07:57 +00001686 const SCEV *Zero = SE.getZero(M->getType());
1687 const SCEV *Begin = ClampedSubstract(Zero, M);
1688 const SCEV *L = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001689
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001690 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1691 // We can potentially do much better here.
Max Kazantsev26846782017-11-20 06:07:57 +00001692 if (const SCEV *EndLimit = getEnd())
1693 L = EndLimit;
Max Kazantsev390fc572017-10-30 09:35:16 +00001694 else {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001695 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
Max Kazantsev26846782017-11-20 06:07:57 +00001696 L = SIntMax;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001697 }
Max Kazantsev26846782017-11-20 06:07:57 +00001698 const SCEV *End = ClampedSubstract(L, M);
Sanjoy Das351db052015-01-22 09:32:02 +00001699 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001700}
1701
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001702static Optional<InductiveRangeCheck::Range>
Max Kazantsev9ac70212017-10-25 06:47:39 +00001703IntersectSignedRange(ScalarEvolution &SE,
1704 const Optional<InductiveRangeCheck::Range> &R1,
1705 const InductiveRangeCheck::Range &R2) {
Max Kazantsev4332a942017-10-25 06:10:02 +00001706 if (R2.isEmpty(SE, /* IsSigned */ true))
Max Kazantsev25d86552017-10-11 06:53:07 +00001707 return None;
Max Kazantsev3612d4b2017-10-19 05:33:28 +00001708 if (!R1.hasValue())
1709 return R2;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001710 auto &R1Value = R1.getValue();
Max Kazantsev3612d4b2017-10-19 05:33:28 +00001711 // We never return empty ranges from this function, and R1 is supposed to be
1712 // a result of intersection. Thus, R1 is never empty.
Max Kazantsev4332a942017-10-25 06:10:02 +00001713 assert(!R1Value.isEmpty(SE, /* IsSigned */ true) &&
1714 "We should never have empty R1!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001715
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001716 // TODO: we could widen the smaller range and have this work; but for now we
1717 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001718 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001719 return None;
1720
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001721 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1722 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1723
Max Kazantsev25d86552017-10-11 06:53:07 +00001724 // If the resulting range is empty, just return None.
1725 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
Max Kazantsev4332a942017-10-25 06:10:02 +00001726 if (Ret.isEmpty(SE, /* IsSigned */ true))
Max Kazantsev25d86552017-10-11 06:53:07 +00001727 return None;
1728 return Ret;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001729}
1730
Max Kazantsev9ac70212017-10-25 06:47:39 +00001731static Optional<InductiveRangeCheck::Range>
1732IntersectUnsignedRange(ScalarEvolution &SE,
1733 const Optional<InductiveRangeCheck::Range> &R1,
1734 const InductiveRangeCheck::Range &R2) {
1735 if (R2.isEmpty(SE, /* IsSigned */ false))
1736 return None;
1737 if (!R1.hasValue())
1738 return R2;
1739 auto &R1Value = R1.getValue();
1740 // We never return empty ranges from this function, and R1 is supposed to be
1741 // a result of intersection. Thus, R1 is never empty.
1742 assert(!R1Value.isEmpty(SE, /* IsSigned */ false) &&
1743 "We should never have empty R1!");
1744
1745 // TODO: we could widen the smaller range and have this work; but for now we
1746 // bail out to keep things simple.
1747 if (R1Value.getType() != R2.getType())
1748 return None;
1749
1750 const SCEV *NewBegin = SE.getUMaxExpr(R1Value.getBegin(), R2.getBegin());
1751 const SCEV *NewEnd = SE.getUMinExpr(R1Value.getEnd(), R2.getEnd());
1752
1753 // If the resulting range is empty, just return None.
1754 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
1755 if (Ret.isEmpty(SE, /* IsSigned */ false))
1756 return None;
1757 return Ret;
1758}
1759
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001760bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001761 if (skipLoop(L))
1762 return false;
1763
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001764 if (L->getBlocks().size() >= LoopSizeCutoff) {
1765 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1766 return false;
1767 }
1768
1769 BasicBlock *Preheader = L->getLoopPreheader();
1770 if (!Preheader) {
1771 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1772 return false;
1773 }
1774
1775 LLVMContext &Context = Preheader->getContext();
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001776 SmallVector<InductiveRangeCheck, 16> RangeChecks;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001777 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Cong Houab23bfb2015-07-15 22:48:29 +00001778 BranchProbabilityInfo &BPI =
1779 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001780
1781 for (auto BBI : L->getBlocks())
1782 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
Sanjoy Dasa0992682016-05-26 00:09:02 +00001783 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1784 RangeChecks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001785
1786 if (RangeChecks.empty())
1787 return false;
1788
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001789 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1790 OS << "irce: looking at loop "; L->print(OS);
1791 OS << "irce: loop has " << RangeChecks.size()
1792 << " inductive range checks: \n";
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001793 for (InductiveRangeCheck &IRC : RangeChecks)
1794 IRC.print(OS);
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001795 };
1796
1797 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1798
1799 if (PrintRangeChecks)
1800 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001801
Sanjoy Dase75ed922015-02-26 08:19:31 +00001802 const char *FailureReason = nullptr;
1803 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001804 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001805 if (!MaybeLoopStructure.hasValue()) {
1806 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1807 << "\n";);
1808 return false;
1809 }
1810 LoopStructure LS = MaybeLoopStructure.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001811 const SCEVAddRecExpr *IndVar =
Serguei Katkov675e3042017-09-21 04:50:41 +00001812 cast<SCEVAddRecExpr>(SE.getMinusSCEV(SE.getSCEV(LS.IndVarBase), SE.getSCEV(LS.IndVarStep)));
Sanjoy Dase75ed922015-02-26 08:19:31 +00001813
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001814 Optional<InductiveRangeCheck::Range> SafeIterRange;
1815 Instruction *ExprInsertPt = Preheader->getTerminator();
1816
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001817 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
Max Kazantsev9ac70212017-10-25 06:47:39 +00001818 // Basing on the type of latch predicate, we interpret the IV iteration range
1819 // as signed or unsigned range. We use different min/max functions (signed or
1820 // unsigned) when intersecting this range with safe iteration ranges implied
1821 // by range checks.
1822 auto IntersectRange =
1823 LS.IsSignedPredicate ? IntersectSignedRange : IntersectUnsignedRange;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001824
1825 IRBuilder<> B(ExprInsertPt);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001826 for (InductiveRangeCheck &IRC : RangeChecks) {
Max Kazantsev26846782017-11-20 06:07:57 +00001827 auto Result = IRC.computeSafeIterationSpace(SE, IndVar,
1828 LS.IsSignedPredicate);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001829 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001830 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001831 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001832 if (MaybeSafeIterRange.hasValue()) {
Max Kazantsev4332a942017-10-25 06:10:02 +00001833 assert(
1834 !MaybeSafeIterRange.getValue().isEmpty(SE, LS.IsSignedPredicate) &&
1835 "We should never return empty ranges!");
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001836 RangeChecksToEliminate.push_back(IRC);
1837 SafeIterRange = MaybeSafeIterRange.getValue();
1838 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001839 }
1840 }
1841
1842 if (!SafeIterRange.hasValue())
1843 return false;
1844
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001845 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Sanjoy Das21434472016-08-14 01:04:46 +00001846 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LPM,
1847 LS, SE, DT, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001848 bool Changed = LC.run();
1849
1850 if (Changed) {
1851 auto PrintConstrainedLoopInfo = [L]() {
1852 dbgs() << "irce: in function ";
1853 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1854 dbgs() << "constrained ";
1855 L->print(dbgs());
1856 };
1857
1858 DEBUG(PrintConstrainedLoopInfo());
1859
1860 if (PrintChangedLoops)
1861 PrintConstrainedLoopInfo();
1862
1863 // Optimize away the now-redundant range checks.
1864
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001865 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1866 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001867 ? ConstantInt::getTrue(Context)
1868 : ConstantInt::getFalse(Context);
Sanjoy Dasaa83c472016-05-23 22:16:45 +00001869 IRC.getCheckUse()->set(FoldedRangeCheck);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001870 }
1871 }
1872
1873 return Changed;
1874}
1875
1876Pass *llvm::createInductiveRangeCheckEliminationPass() {
1877 return new InductiveRangeCheckElimination;
1878}