blob: 01f7a969ba925d1af174c83fbe4d5e8c88a0d5f8 [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,
Sanjoy Das59776732016-05-21 02:31:51 +0000231 const SCEVAddRecExpr *IndVar) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000232
Sanjoy Dasa0992682016-05-26 00:09:02 +0000233 /// Parse out a set of inductive range checks from \p BI and append them to \p
234 /// Checks.
235 ///
236 /// NB! There may be conditions feeding into \p BI that aren't inductive range
237 /// checks, and hence don't end up in \p Checks.
238 static void
239 extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE,
240 BranchProbabilityInfo &BPI,
241 SmallVectorImpl<InductiveRangeCheck> &Checks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000242};
243
244class InductiveRangeCheckElimination : public LoopPass {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000245public:
246 static char ID;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000247
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000248 InductiveRangeCheckElimination() : LoopPass(ID) {
249 initializeInductiveRangeCheckEliminationPass(
250 *PassRegistry::getPassRegistry());
251 }
252
253 void getAnalysisUsage(AnalysisUsage &AU) const override {
Cong Houab23bfb2015-07-15 22:48:29 +0000254 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000255 getLoopAnalysisUsage(AU);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000256 }
257
258 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
259};
260
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000261} // end anonymous namespace
262
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000263char InductiveRangeCheckElimination::ID = 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000264
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000265INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce",
266 "Inductive range check elimination", false, false)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000267INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000268INITIALIZE_PASS_DEPENDENCY(LoopPass)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000269INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce",
270 "Inductive range check elimination", false, false)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000271
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000272StringRef InductiveRangeCheck::rangeCheckKindToStr(
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000273 InductiveRangeCheck::RangeCheckKind RCK) {
274 switch (RCK) {
275 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
276 return "RANGE_CHECK_UNKNOWN";
277
278 case InductiveRangeCheck::RANGE_CHECK_UPPER:
279 return "RANGE_CHECK_UPPER";
280
281 case InductiveRangeCheck::RANGE_CHECK_LOWER:
282 return "RANGE_CHECK_LOWER";
283
284 case InductiveRangeCheck::RANGE_CHECK_BOTH:
285 return "RANGE_CHECK_BOTH";
286 }
287
288 llvm_unreachable("unknown range check type!");
289}
290
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000291/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000292/// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000293/// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000294/// range checked, and set `Length` to the upper limit `Index` is being range
295/// checked with if (and only if) the range check type is stronger or equal to
296/// RANGE_CHECK_UPPER.
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000297InductiveRangeCheck::RangeCheckKind
Sanjoy Das337d46b2015-03-24 19:29:18 +0000298InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
299 ScalarEvolution &SE, Value *&Index,
Max Kazantsev9ac70212017-10-25 06:47:39 +0000300 Value *&Length, bool &IsSigned) {
Sanjoy Das337d46b2015-03-24 19:29:18 +0000301 auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) {
302 const SCEV *S = SE.getSCEV(V);
303 if (isa<SCEVCouldNotCompute>(S))
304 return false;
305
306 return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant &&
307 SE.isKnownNonNegative(S);
308 };
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000309
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000310 ICmpInst::Predicate Pred = ICI->getPredicate();
311 Value *LHS = ICI->getOperand(0);
312 Value *RHS = ICI->getOperand(1);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000313
314 switch (Pred) {
315 default:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000316 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000317
318 case ICmpInst::ICMP_SLE:
319 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000320 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000321 case ICmpInst::ICMP_SGE:
Max Kazantsev9ac70212017-10-25 06:47:39 +0000322 IsSigned = true;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000323 if (match(RHS, m_ConstantInt<0>())) {
324 Index = LHS;
325 return RANGE_CHECK_LOWER;
326 }
327 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000328
329 case ICmpInst::ICMP_SLT:
330 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000331 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000332 case ICmpInst::ICMP_SGT:
Max Kazantsev9ac70212017-10-25 06:47:39 +0000333 IsSigned = true;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000334 if (match(RHS, m_ConstantInt<-1>())) {
335 Index = LHS;
336 return RANGE_CHECK_LOWER;
337 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000338
Sanjoy Das337d46b2015-03-24 19:29:18 +0000339 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000340 Index = RHS;
341 Length = LHS;
342 return RANGE_CHECK_UPPER;
343 }
344 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000345
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000346 case ICmpInst::ICMP_ULT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000347 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000348 LLVM_FALLTHROUGH;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000349 case ICmpInst::ICMP_UGT:
Max Kazantsev9ac70212017-10-25 06:47:39 +0000350 IsSigned = false;
Sanjoy Das337d46b2015-03-24 19:29:18 +0000351 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000352 Index = RHS;
353 Length = LHS;
354 return RANGE_CHECK_BOTH;
355 }
356 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000357 }
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000358
359 llvm_unreachable("default clause returns!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000360}
361
Sanjoy Dasa0992682016-05-26 00:09:02 +0000362void InductiveRangeCheck::extractRangeChecksFromCond(
363 Loop *L, ScalarEvolution &SE, Use &ConditionUse,
364 SmallVectorImpl<InductiveRangeCheck> &Checks,
365 SmallPtrSetImpl<Value *> &Visited) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000366 Value *Condition = ConditionUse.get();
Sanjoy Dasa0992682016-05-26 00:09:02 +0000367 if (!Visited.insert(Condition).second)
368 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000369
Sanjoy Dasa0992682016-05-26 00:09:02 +0000370 if (match(Condition, m_And(m_Value(), m_Value()))) {
371 SmallVector<InductiveRangeCheck, 8> SubChecks;
372 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
373 SubChecks, Visited);
374 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
375 SubChecks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000376
Sanjoy Dasa0992682016-05-26 00:09:02 +0000377 if (SubChecks.size() == 2) {
378 // Handle a special case where we know how to merge two checks separately
379 // checking the upper and lower bounds into a full range check.
380 const auto &RChkA = SubChecks[0];
381 const auto &RChkB = SubChecks[1];
Max Kazantsev84286ce2017-10-31 06:19:05 +0000382 if ((RChkA.End == RChkB.End || !RChkA.End || !RChkB.End) &&
383 RChkA.Begin == RChkB.Begin && RChkA.Step == RChkB.Step &&
Max Kazantsev9ac70212017-10-25 06:47:39 +0000384 RChkA.IsSigned == RChkB.IsSigned) {
Sanjoy Dasa0992682016-05-26 00:09:02 +0000385 // If RChkA.Kind == RChkB.Kind then we just found two identical checks.
386 // But if one of them is a RANGE_CHECK_LOWER and the other is a
387 // RANGE_CHECK_UPPER (only possibility if they're different) then
388 // together they form a RANGE_CHECK_BOTH.
389 SubChecks[0].Kind =
390 (InductiveRangeCheck::RangeCheckKind)(RChkA.Kind | RChkB.Kind);
Max Kazantsev84286ce2017-10-31 06:19:05 +0000391 SubChecks[0].End = RChkA.End ? RChkA.End : RChkB.End;
Sanjoy Dasa0992682016-05-26 00:09:02 +0000392 SubChecks[0].CheckUse = &ConditionUse;
Max Kazantsev9ac70212017-10-25 06:47:39 +0000393 SubChecks[0].IsSigned = RChkA.IsSigned;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000394
Sanjoy Dasa0992682016-05-26 00:09:02 +0000395 // We updated one of the checks in place, now erase the other.
396 SubChecks.pop_back();
397 }
398 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000399
Sanjoy Dasa0992682016-05-26 00:09:02 +0000400 Checks.insert(Checks.end(), SubChecks.begin(), SubChecks.end());
401 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000402 }
403
Sanjoy Dasa0992682016-05-26 00:09:02 +0000404 ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);
405 if (!ICI)
406 return;
407
408 Value *Length = nullptr, *Index;
Max Kazantsev9ac70212017-10-25 06:47:39 +0000409 bool IsSigned;
410 auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length, IsSigned);
Sanjoy Dasa0992682016-05-26 00:09:02 +0000411 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
412 return;
413
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000414 const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000415 bool IsAffineIndex =
416 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
417
418 if (!IsAffineIndex)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000419 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000420
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000421 InductiveRangeCheck IRC;
Max Kazantsev84286ce2017-10-31 06:19:05 +0000422 IRC.End = Length ? SE.getSCEV(Length) : nullptr;
423 IRC.Begin = IndexAddRec->getStart();
424 IRC.Step = IndexAddRec->getStepRecurrence(SE);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000425 IRC.CheckUse = &ConditionUse;
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000426 IRC.Kind = RCKind;
Max Kazantsev9ac70212017-10-25 06:47:39 +0000427 IRC.IsSigned = IsSigned;
Sanjoy Dasa0992682016-05-26 00:09:02 +0000428 Checks.push_back(IRC);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000429}
430
Sanjoy Dasa0992682016-05-26 00:09:02 +0000431void InductiveRangeCheck::extractRangeChecksFromBranch(
432 BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo &BPI,
433 SmallVectorImpl<InductiveRangeCheck> &Checks) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000434 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
Sanjoy Dasa0992682016-05-26 00:09:02 +0000435 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000436
437 BranchProbability LikelyTaken(15, 16);
438
Sanjoy Dasbb969792016-07-22 00:40:56 +0000439 if (!SkipProfitabilityChecks &&
440 BPI.getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000441 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000442
Sanjoy Dasa0992682016-05-26 00:09:02 +0000443 SmallPtrSet<Value *, 8> Visited;
444 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
445 Checks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000446}
447
Anna Thomas65ca8e92016-12-13 21:05:21 +0000448// Add metadata to the loop L to disable loop optimizations. Callers need to
449// confirm that optimizing loop L is not beneficial.
450static void DisableAllLoopOptsOnLoop(Loop &L) {
451 // We do not care about any existing loopID related metadata for L, since we
452 // are setting all loop metadata to false.
453 LLVMContext &Context = L.getHeader()->getContext();
454 // Reserve first location for self reference to the LoopID metadata node.
455 MDNode *Dummy = MDNode::get(Context, {});
456 MDNode *DisableUnroll = MDNode::get(
457 Context, {MDString::get(Context, "llvm.loop.unroll.disable")});
458 Metadata *FalseVal =
459 ConstantAsMetadata::get(ConstantInt::get(Type::getInt1Ty(Context), 0));
460 MDNode *DisableVectorize = MDNode::get(
461 Context,
462 {MDString::get(Context, "llvm.loop.vectorize.enable"), FalseVal});
463 MDNode *DisableLICMVersioning = MDNode::get(
464 Context, {MDString::get(Context, "llvm.loop.licm_versioning.disable")});
465 MDNode *DisableDistribution= MDNode::get(
466 Context,
467 {MDString::get(Context, "llvm.loop.distribute.enable"), FalseVal});
468 MDNode *NewLoopID =
469 MDNode::get(Context, {Dummy, DisableUnroll, DisableVectorize,
470 DisableLICMVersioning, DisableDistribution});
471 // Set operand 0 to refer to the loop id itself.
472 NewLoopID->replaceOperandWith(0, NewLoopID);
473 L.setLoopID(NewLoopID);
474}
475
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000476namespace {
477
Sanjoy Dase75ed922015-02-26 08:19:31 +0000478// Keeps track of the structure of a loop. This is similar to llvm::Loop,
479// except that it is more lightweight and can track the state of a loop through
480// changing and potentially invalid IR. This structure also formalizes the
481// kinds of loops we can deal with -- ones that have a single latch that is also
482// an exiting block *and* have a canonical induction variable.
483struct LoopStructure {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000484 const char *Tag = "";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000485
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000486 BasicBlock *Header = nullptr;
487 BasicBlock *Latch = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000488
489 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
490 // successor is `LatchExit', the exit block of the loop.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000491 BranchInst *LatchBr = nullptr;
492 BasicBlock *LatchExit = nullptr;
493 unsigned LatchBrExitIdx = std::numeric_limits<unsigned>::max();
Sanjoy Dase75ed922015-02-26 08:19:31 +0000494
Sanjoy Dasec892132017-02-07 23:59:07 +0000495 // The loop represented by this instance of LoopStructure is semantically
496 // equivalent to:
497 //
498 // intN_ty inc = IndVarIncreasing ? 1 : -1;
Serguei Katkov675e3042017-09-21 04:50:41 +0000499 // pred_ty predicate = IndVarIncreasing ? ICMP_SLT : ICMP_SGT;
Sanjoy Dasec892132017-02-07 23:59:07 +0000500 //
Serguei Katkov675e3042017-09-21 04:50:41 +0000501 // for (intN_ty iv = IndVarStart; predicate(iv, LoopExitAt); iv = IndVarBase)
Sanjoy Dasec892132017-02-07 23:59:07 +0000502 // ... body ...
503
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000504 Value *IndVarBase = nullptr;
505 Value *IndVarStart = nullptr;
506 Value *IndVarStep = nullptr;
507 Value *LoopExitAt = nullptr;
508 bool IndVarIncreasing = false;
509 bool IsSignedPredicate = true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000510
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000511 LoopStructure() = default;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000512
513 template <typename M> LoopStructure map(M Map) const {
514 LoopStructure Result;
515 Result.Tag = Tag;
516 Result.Header = cast<BasicBlock>(Map(Header));
517 Result.Latch = cast<BasicBlock>(Map(Latch));
518 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
519 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
520 Result.LatchBrExitIdx = LatchBrExitIdx;
Max Kazantseva22742b2017-08-31 05:58:15 +0000521 Result.IndVarBase = Map(IndVarBase);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000522 Result.IndVarStart = Map(IndVarStart);
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000523 Result.IndVarStep = Map(IndVarStep);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000524 Result.LoopExitAt = Map(LoopExitAt);
525 Result.IndVarIncreasing = IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000526 Result.IsSignedPredicate = IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000527 return Result;
528 }
529
Sanjoy Dase91665d2015-02-26 08:56:04 +0000530 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
531 BranchProbabilityInfo &BPI,
532 Loop &,
Sanjoy Dase75ed922015-02-26 08:19:31 +0000533 const char *&);
534};
535
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000536/// This class is used to constrain loops to run within a given iteration space.
537/// The algorithm this class implements is given a Loop and a range [Begin,
538/// End). The algorithm then tries to break out a "main loop" out of the loop
539/// it is given in a way that the "main loop" runs with the induction variable
540/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
541/// loops to run any remaining iterations. The pre loop runs any iterations in
542/// which the induction variable is < Begin, and the post loop runs any
543/// iterations in which the induction variable is >= End.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000544class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000545 // The representation of a clone of the original loop we started out with.
546 struct ClonedLoop {
547 // The cloned blocks
548 std::vector<BasicBlock *> Blocks;
549
550 // `Map` maps values in the clonee into values in the cloned version
551 ValueToValueMapTy Map;
552
553 // An instance of `LoopStructure` for the cloned loop
554 LoopStructure Structure;
555 };
556
557 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
558 // more details on what these fields mean.
559 struct RewrittenRangeInfo {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000560 BasicBlock *PseudoExit = nullptr;
561 BasicBlock *ExitSelector = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000562 std::vector<PHINode *> PHIValuesAtPseudoExit;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000563 PHINode *IndVarEnd = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000564
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000565 RewrittenRangeInfo() = default;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000566 };
567
568 // Calculated subranges we restrict the iteration space of the main loop to.
569 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000570 // these fields are computed. `LowLimit` is None if there is no restriction
571 // on low end of the restricted iteration space of the main loop. `HighLimit`
572 // is None if there is no restriction on high end of the restricted iteration
573 // space of the main loop.
574
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000575 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000576 Optional<const SCEV *> LowLimit;
577 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000578 };
579
580 // A utility function that does a `replaceUsesOfWith' on the incoming block
581 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
582 // incoming block list with `ReplaceBy'.
583 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
584 BasicBlock *ReplaceBy);
585
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000586 // Compute a safe set of limits for the main loop to run in -- effectively the
587 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000588 // Return None if unable to compute the set of subranges.
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000589 Optional<SubRanges> calculateSubRanges(bool IsSignedPredicate) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000590
591 // Clone `OriginalLoop' and return the result in CLResult. The IR after
592 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
593 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
594 // but there is no such edge.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000595 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
596
Sanjoy Das21434472016-08-14 01:04:46 +0000597 // Create the appropriate loop structure needed to describe a cloned copy of
598 // `Original`. The clone is described by `VM`.
599 Loop *createClonedLoopStructure(Loop *Original, Loop *Parent,
600 ValueToValueMapTy &VM);
601
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000602 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
603 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
604 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
605 // `OriginalHeaderCount'.
606 //
607 // If there are iterations left to execute, control is made to jump to
608 // `ContinuationBlock', otherwise they take the normal loop exit. The
609 // returned `RewrittenRangeInfo' object is populated as follows:
610 //
611 // .PseudoExit is a basic block that unconditionally branches to
612 // `ContinuationBlock'.
613 //
614 // .ExitSelector is a basic block that decides, on exit from the loop,
615 // whether to branch to the "true" exit or to `PseudoExit'.
616 //
617 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
618 // for each PHINode in the loop header on taking the pseudo exit.
619 //
620 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
621 // preheader because it is made to branch to the loop header only
622 // conditionally.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000623 RewrittenRangeInfo
624 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
625 Value *ExitLoopAt,
626 BasicBlock *ContinuationBlock) const;
627
628 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
629 // function creates a new preheader for `LS' and returns it.
Sanjoy Dase75ed922015-02-26 08:19:31 +0000630 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
631 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000632
633 // `ContinuationBlockAndPreheader' was the continuation block for some call to
634 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
635 // This function rewrites the PHI nodes in `LS.Header' to start with the
636 // correct value.
637 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000638 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000639 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
640
641 // Even though we do not preserve any passes at this time, we at least need to
642 // keep the parent loop structure consistent. The `LPPassManager' seems to
643 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000644 // blocks denoted by BBs to this loops parent loop if required.
645 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000646
647 // Some global state.
648 Function &F;
649 LLVMContext &Ctx;
650 ScalarEvolution &SE;
Sanjoy Dasf45e03e2016-08-02 19:31:54 +0000651 DominatorTree &DT;
Sanjoy Das21434472016-08-14 01:04:46 +0000652 LPPassManager &LPM;
Sanjoy Das35459f02016-08-14 01:04:50 +0000653 LoopInfo &LI;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000654
655 // Information about the original loop we started out with.
656 Loop &OriginalLoop;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000657
658 const SCEV *LatchTakenCount = nullptr;
659 BasicBlock *OriginalPreheader = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000660
661 // The preheader of the main loop. This may or may not be different from
662 // `OriginalPreheader'.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000663 BasicBlock *MainLoopPreheader = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000664
665 // The range we need to run the main loop in.
666 InductiveRangeCheck::Range Range;
667
668 // The structure of the main loop (see comment at the beginning of this class
669 // for a definition)
670 LoopStructure MainLoopStructure;
671
672public:
Sanjoy Das21434472016-08-14 01:04:46 +0000673 LoopConstrainer(Loop &L, LoopInfo &LI, LPPassManager &LPM,
674 const LoopStructure &LS, ScalarEvolution &SE,
675 DominatorTree &DT, InductiveRangeCheck::Range R)
Sanjoy Dase75ed922015-02-26 08:19:31 +0000676 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000677 SE(SE), DT(DT), LPM(LPM), LI(LI), OriginalLoop(L), Range(R),
678 MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000679
680 // Entry point for the algorithm. Returns true on success.
681 bool run();
682};
683
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000684} // end anonymous namespace
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000685
686void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
687 BasicBlock *ReplaceBy) {
688 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
689 if (PN->getIncomingBlock(i) == Block)
690 PN->setIncomingBlock(i, ReplaceBy);
691}
692
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000693static bool CanBeMax(ScalarEvolution &SE, const SCEV *S, bool Signed) {
694 APInt Max = Signed ?
695 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth()) :
696 APInt::getMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
697 return SE.getSignedRange(S).contains(Max) &&
698 SE.getUnsignedRange(S).contains(Max);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000699}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000700
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000701static bool SumCanReachMax(ScalarEvolution &SE, const SCEV *S1, const SCEV *S2,
702 bool Signed) {
703 // S1 < INT_MAX - S2 ===> S1 + S2 < INT_MAX.
704 assert(SE.isKnownNonNegative(S2) &&
705 "We expected the 2nd arg to be non-negative!");
706 const SCEV *Max = SE.getConstant(
707 Signed ? APInt::getSignedMaxValue(
708 cast<IntegerType>(S1->getType())->getBitWidth())
709 : APInt::getMaxValue(
710 cast<IntegerType>(S1->getType())->getBitWidth()));
711 const SCEV *CapForS1 = SE.getMinusSCEV(Max, S2);
712 return !SE.isKnownPredicate(Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
713 S1, CapForS1);
714}
715
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000716static bool CanBeMin(ScalarEvolution &SE, const SCEV *S, bool Signed) {
717 APInt Min = Signed ?
718 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth()) :
719 APInt::getMinValue(cast<IntegerType>(S->getType())->getBitWidth());
720 return SE.getSignedRange(S).contains(Min) &&
721 SE.getUnsignedRange(S).contains(Min);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000722}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000723
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000724static bool SumCanReachMin(ScalarEvolution &SE, const SCEV *S1, const SCEV *S2,
725 bool Signed) {
726 // S1 > INT_MIN - S2 ===> S1 + S2 > INT_MIN.
727 assert(SE.isKnownNonPositive(S2) &&
728 "We expected the 2nd arg to be non-positive!");
729 const SCEV *Max = SE.getConstant(
730 Signed ? APInt::getSignedMinValue(
731 cast<IntegerType>(S1->getType())->getBitWidth())
732 : APInt::getMinValue(
733 cast<IntegerType>(S1->getType())->getBitWidth()));
734 const SCEV *CapForS1 = SE.getMinusSCEV(Max, S2);
735 return !SE.isKnownPredicate(Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT,
736 S1, CapForS1);
737}
738
Sanjoy Dase75ed922015-02-26 08:19:31 +0000739Optional<LoopStructure>
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000740LoopStructure::parseLoopStructure(ScalarEvolution &SE,
741 BranchProbabilityInfo &BPI,
Sanjoy Dase91665d2015-02-26 08:56:04 +0000742 Loop &L, const char *&FailureReason) {
Sanjoy Das43fdc542016-08-14 01:04:31 +0000743 if (!L.isLoopSimplifyForm()) {
744 FailureReason = "loop not in LoopSimplify form";
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000745 return None;
Sanjoy Das43fdc542016-08-14 01:04:31 +0000746 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000747
748 BasicBlock *Latch = L.getLoopLatch();
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000749 assert(Latch && "Simplified loops only have one latch!");
750
Sanjoy Das7a18a232016-08-14 01:04:36 +0000751 if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) {
752 FailureReason = "loop has already been cloned";
753 return None;
754 }
755
Sanjoy Dase75ed922015-02-26 08:19:31 +0000756 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000757 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000758 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000759 }
760
Sanjoy Dase75ed922015-02-26 08:19:31 +0000761 BasicBlock *Header = L.getHeader();
762 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000763 if (!Preheader) {
764 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000765 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000766 }
767
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000768 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000769 if (!LatchBr || LatchBr->isUnconditional()) {
770 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000771 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000772 }
773
Sanjoy Dase75ed922015-02-26 08:19:31 +0000774 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000775
Sanjoy Dase91665d2015-02-26 08:56:04 +0000776 BranchProbability ExitProbability =
777 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
778
Sanjoy Dasbb969792016-07-22 00:40:56 +0000779 if (!SkipProfitabilityChecks &&
780 ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
Sanjoy Dase91665d2015-02-26 08:56:04 +0000781 FailureReason = "short running loop, not profitable";
782 return None;
783 }
784
Sanjoy Dase75ed922015-02-26 08:19:31 +0000785 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
786 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
787 FailureReason = "latch terminator branch not conditional on integral icmp";
788 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000789 }
790
Sanjoy Dase75ed922015-02-26 08:19:31 +0000791 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
792 if (isa<SCEVCouldNotCompute>(LatchCount)) {
793 FailureReason = "could not compute latch count";
794 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000795 }
796
Sanjoy Dase75ed922015-02-26 08:19:31 +0000797 ICmpInst::Predicate Pred = ICI->getPredicate();
798 Value *LeftValue = ICI->getOperand(0);
799 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
800 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
801
802 Value *RightValue = ICI->getOperand(1);
803 const SCEV *RightSCEV = SE.getSCEV(RightValue);
804
805 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
806 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
807 if (isa<SCEVAddRecExpr>(RightSCEV)) {
808 std::swap(LeftSCEV, RightSCEV);
809 std::swap(LeftValue, RightValue);
810 Pred = ICmpInst::getSwappedPredicate(Pred);
811 } else {
812 FailureReason = "no add recurrences in the icmp";
813 return None;
814 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000815 }
816
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000817 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
818 if (AR->getNoWrapFlags(SCEV::FlagNSW))
819 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000820
821 IntegerType *Ty = cast<IntegerType>(AR->getType());
822 IntegerType *WideTy =
823 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
824
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000825 const SCEVAddRecExpr *ExtendAfterOp =
826 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
827 if (ExtendAfterOp) {
828 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
829 const SCEV *ExtendedStep =
830 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
831
832 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
833 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
834
835 if (NoSignedWrap)
836 return true;
837 }
838
839 // We may have proved this when computing the sign extension above.
840 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
841 };
842
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000843 // Here we check whether the suggested AddRec is an induction variable that
844 // can be handled (i.e. with known constant step), and if yes, calculate its
845 // step and identify whether it is increasing or decreasing.
846 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing,
847 ConstantInt *&StepCI) {
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000848 if (!AR->isAffine())
849 return false;
850
Sanjoy Dase75ed922015-02-26 08:19:31 +0000851 // Currently we only work with induction variables that have been proved to
852 // not wrap. This restriction can potentially be lifted in the future.
853
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000854 if (!HasNoSignedWrap(AR))
Sanjoy Dase75ed922015-02-26 08:19:31 +0000855 return false;
856
857 if (const SCEVConstant *StepExpr =
858 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000859 StepCI = StepExpr->getValue();
Max Kazantsev85da7542017-08-01 06:27:51 +0000860 assert(!StepCI->isZero() && "Zero step?");
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000861 IsIncreasing = !StepCI->isNegative();
862 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000863 }
864
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000865 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000866 };
867
Serguei Katkov675e3042017-09-21 04:50:41 +0000868 // `ICI` is interpreted as taking the backedge if the *next* value of the
869 // induction variable satisfies some constraint.
Sanjoy Dase75ed922015-02-26 08:19:31 +0000870
Max Kazantseva22742b2017-08-31 05:58:15 +0000871 const SCEVAddRecExpr *IndVarBase = cast<SCEVAddRecExpr>(LeftSCEV);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000872 bool IsIncreasing = false;
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000873 bool IsSignedPredicate = true;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000874 ConstantInt *StepCI;
Max Kazantseva22742b2017-08-31 05:58:15 +0000875 if (!IsInductionVar(IndVarBase, IsIncreasing, StepCI)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000876 FailureReason = "LHS in icmp not induction variable";
877 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000878 }
879
Serguei Katkov675e3042017-09-21 04:50:41 +0000880 const SCEV *StartNext = IndVarBase->getStart();
881 const SCEV *Addend = SE.getNegativeSCEV(IndVarBase->getStepRecurrence(SE));
882 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000883 const SCEV *Step = SE.getSCEV(StepCI);
Sanjoy Dasec892132017-02-07 23:59:07 +0000884
Sanjoy Dase75ed922015-02-26 08:19:31 +0000885 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000886 if (IsIncreasing) {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000887 bool DecreasedRightValueByOne = false;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000888 if (StepCI->isOne()) {
889 // Try to turn eq/ne predicates to those we can work with.
890 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
891 // while (++i != len) { while (++i < len) {
892 // ... ---> ...
893 // } }
894 // If both parts are known non-negative, it is profitable to use
895 // unsigned comparison in increasing loop. This allows us to make the
896 // comparison check against "RightSCEV + 1" more optimistic.
897 if (SE.isKnownNonNegative(IndVarStart) &&
898 SE.isKnownNonNegative(RightSCEV))
899 Pred = ICmpInst::ICMP_ULT;
900 else
901 Pred = ICmpInst::ICMP_SLT;
902 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 &&
903 !CanBeMin(SE, RightSCEV, /* IsSignedPredicate */ true)) {
904 // while (true) { while (true) {
905 // if (++i == len) ---> if (++i > len - 1)
906 // break; break;
907 // ... ...
908 // } }
909 // TODO: Insert ICMP_UGT if both are non-negative?
910 Pred = ICmpInst::ICMP_SGT;
911 RightSCEV = SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType()));
912 DecreasedRightValueByOne = true;
913 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000914 }
915
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000916 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
917 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000918 bool FoundExpectedPred =
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000919 (LTPred && LatchBrExitIdx == 1) || (GTPred && LatchBrExitIdx == 0);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000920
921 if (!FoundExpectedPred) {
922 FailureReason = "expected icmp slt semantically, found something else";
923 return None;
924 }
925
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000926 IsSignedPredicate =
927 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
Max Kazantsev8aacef62017-10-04 06:53:22 +0000928
Max Kazantsev8aacef62017-10-04 06:53:22 +0000929 if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
930 FailureReason = "unsigned latch conditions are explicitly prohibited";
931 return None;
932 }
933
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000934 // The predicate that we need to check that the induction variable lies
935 // within bounds.
936 ICmpInst::Predicate BoundPred =
937 IsSignedPredicate ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
938
Sanjoy Dase75ed922015-02-26 08:19:31 +0000939 if (LatchBrExitIdx == 0) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000940 const SCEV *StepMinusOne = SE.getMinusSCEV(Step,
941 SE.getOne(Step->getType()));
942 if (SumCanReachMax(SE, RightSCEV, StepMinusOne, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000943 // TODO: this restriction is easily removable -- we just have to
944 // remember that the icmp was an slt and not an sle.
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000945 FailureReason = "limit may overflow when coercing le to lt";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000946 return None;
947 }
948
Sanjoy Dasec892132017-02-07 23:59:07 +0000949 if (!SE.isLoopEntryGuardedByCond(
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000950 &L, BoundPred, IndVarStart,
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000951 SE.getAddExpr(RightSCEV, Step))) {
Sanjoy Dasec892132017-02-07 23:59:07 +0000952 FailureReason = "Induction variable start not bounded by upper limit";
953 return None;
954 }
955
Max Kazantsev2c627a92017-07-18 04:53:48 +0000956 // We need to increase the right value unless we have already decreased
957 // it virtually when we replaced EQ with SGT.
958 if (!DecreasedRightValueByOne) {
959 IRBuilder<> B(Preheader->getTerminator());
960 RightValue = B.CreateAdd(RightValue, One);
961 }
Sanjoy Dasec892132017-02-07 23:59:07 +0000962 } else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000963 if (!SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) {
Sanjoy Dasec892132017-02-07 23:59:07 +0000964 FailureReason = "Induction variable start not bounded by upper limit";
965 return None;
966 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000967 assert(!DecreasedRightValueByOne &&
968 "Right value can be decreased only for LatchBrExitIdx == 0!");
Sanjoy Dase75ed922015-02-26 08:19:31 +0000969 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000970 } else {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000971 bool IncreasedRightValueByOne = false;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000972 if (StepCI->isMinusOne()) {
973 // Try to turn eq/ne predicates to those we can work with.
974 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
975 // while (--i != len) { while (--i > len) {
976 // ... ---> ...
977 // } }
978 // We intentionally don't turn the predicate into UGT even if we know
979 // that both operands are non-negative, because it will only pessimize
980 // our check against "RightSCEV - 1".
981 Pred = ICmpInst::ICMP_SGT;
982 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 &&
983 !CanBeMax(SE, RightSCEV, /* IsSignedPredicate */ true)) {
984 // while (true) { while (true) {
985 // if (--i == len) ---> if (--i < len + 1)
986 // break; break;
987 // ... ...
988 // } }
989 // TODO: Insert ICMP_ULT if both are non-negative?
990 Pred = ICmpInst::ICMP_SLT;
991 RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
992 IncreasedRightValueByOne = true;
993 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000994 }
995
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000996 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
997 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
998
Sanjoy Dase75ed922015-02-26 08:19:31 +0000999 bool FoundExpectedPred =
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001000 (GTPred && LatchBrExitIdx == 1) || (LTPred && LatchBrExitIdx == 0);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001001
1002 if (!FoundExpectedPred) {
1003 FailureReason = "expected icmp sgt semantically, found something else";
1004 return None;
1005 }
1006
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001007 IsSignedPredicate =
1008 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
Max Kazantsev8aacef62017-10-04 06:53:22 +00001009
Max Kazantsev8aacef62017-10-04 06:53:22 +00001010 if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
1011 FailureReason = "unsigned latch conditions are explicitly prohibited";
1012 return None;
1013 }
1014
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001015 // The predicate that we need to check that the induction variable lies
1016 // within bounds.
1017 ICmpInst::Predicate BoundPred =
1018 IsSignedPredicate ? CmpInst::ICMP_SGT : CmpInst::ICMP_UGT;
1019
Sanjoy Dase75ed922015-02-26 08:19:31 +00001020 if (LatchBrExitIdx == 0) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +00001021 const SCEV *StepPlusOne = SE.getAddExpr(Step, SE.getOne(Step->getType()));
1022 if (SumCanReachMin(SE, RightSCEV, StepPlusOne, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +00001023 // TODO: this restriction is easily removable -- we just have to
1024 // remember that the icmp was an sgt and not an sge.
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001025 FailureReason = "limit may overflow when coercing ge to gt";
Sanjoy Dase75ed922015-02-26 08:19:31 +00001026 return None;
1027 }
1028
Sanjoy Dasec892132017-02-07 23:59:07 +00001029 if (!SE.isLoopEntryGuardedByCond(
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001030 &L, BoundPred, IndVarStart,
Sanjoy Dasec892132017-02-07 23:59:07 +00001031 SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType())))) {
1032 FailureReason = "Induction variable start not bounded by lower limit";
1033 return None;
1034 }
1035
Max Kazantsev2c627a92017-07-18 04:53:48 +00001036 // We need to decrease the right value unless we have already increased
1037 // it virtually when we replaced EQ with SLT.
1038 if (!IncreasedRightValueByOne) {
1039 IRBuilder<> B(Preheader->getTerminator());
1040 RightValue = B.CreateSub(RightValue, One);
1041 }
Sanjoy Dasec892132017-02-07 23:59:07 +00001042 } else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001043 if (!SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) {
Sanjoy Dasec892132017-02-07 23:59:07 +00001044 FailureReason = "Induction variable start not bounded by lower limit";
1045 return None;
1046 }
Max Kazantsev2c627a92017-07-18 04:53:48 +00001047 assert(!IncreasedRightValueByOne &&
1048 "Right value can be increased only for LatchBrExitIdx == 0!");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001049 }
1050 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001051 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
1052
Sanjoy Dase75ed922015-02-26 08:19:31 +00001053 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001054 ScalarEvolution::LoopInvariant &&
1055 "loop variant exit count doesn't make sense!");
1056
Sanjoy Dase75ed922015-02-26 08:19:31 +00001057 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001058 const DataLayout &DL = Preheader->getModule()->getDataLayout();
1059 Value *IndVarStartV =
1060 SCEVExpander(SE, DL, "irce")
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001061 .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001062 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001063
Sanjoy Dase75ed922015-02-26 08:19:31 +00001064 LoopStructure Result;
1065
1066 Result.Tag = "main";
1067 Result.Header = Header;
1068 Result.Latch = Latch;
1069 Result.LatchBr = LatchBr;
1070 Result.LatchExit = LatchExit;
1071 Result.LatchBrExitIdx = LatchBrExitIdx;
1072 Result.IndVarStart = IndVarStartV;
Max Kazantsev2f6ae282017-08-04 07:01:04 +00001073 Result.IndVarStep = StepCI;
Max Kazantseva22742b2017-08-31 05:58:15 +00001074 Result.IndVarBase = LeftValue;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001075 Result.IndVarIncreasing = IsIncreasing;
1076 Result.LoopExitAt = RightValue;
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001077 Result.IsSignedPredicate = IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001078
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001079 FailureReason = nullptr;
1080
Sanjoy Dase75ed922015-02-26 08:19:31 +00001081 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001082}
1083
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001084Optional<LoopConstrainer::SubRanges>
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001085LoopConstrainer::calculateSubRanges(bool IsSignedPredicate) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001086 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
1087
Sanjoy Das351db052015-01-22 09:32:02 +00001088 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001089 return None;
1090
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001091 LoopConstrainer::SubRanges Result;
1092
1093 // I think we can be more aggressive here and make this nuw / nsw if the
1094 // addition that feeds into the icmp for the latch's terminating branch is nuw
1095 // / nsw. In any case, a wrapping 2's complement addition is safe.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001096 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
1097 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001098
Sanjoy Dase75ed922015-02-26 08:19:31 +00001099 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001100
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001101 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest), or
1102 // [Smallest, GreatestSeen] is the range of values the induction variable
1103 // takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001104
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001105 const SCEV *Smallest = nullptr, *Greatest = nullptr, *GreatestSeen = nullptr;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001106
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001107 const SCEV *One = SE.getOne(Ty);
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001108 if (Increasing) {
1109 Smallest = Start;
1110 Greatest = End;
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001111 // No overflow, because the range [Smallest, GreatestSeen] is not empty.
1112 GreatestSeen = SE.getMinusSCEV(End, One);
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001113 } else {
1114 // These two computations may sign-overflow. Here is why that is okay:
1115 //
1116 // We know that the induction variable does not sign-overflow on any
1117 // iteration except the last one, and it starts at `Start` and ends at
1118 // `End`, decrementing by one every time.
1119 //
1120 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
1121 // induction variable is decreasing we know that that the smallest value
1122 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
1123 //
1124 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
1125 // that case, `Clamp` will always return `Smallest` and
1126 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
1127 // will be an empty range. Returning an empty range is always safe.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001128
Max Kazantsev6c466a32017-06-28 04:57:45 +00001129 Smallest = SE.getAddExpr(End, One);
1130 Greatest = SE.getAddExpr(Start, One);
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001131 GreatestSeen = Start;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001132 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001133
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001134 auto Clamp = [this, Smallest, Greatest, IsSignedPredicate](const SCEV *S) {
Max Kazantsev6f5229d72017-11-01 13:21:56 +00001135 return IsSignedPredicate
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001136 ? SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S))
1137 : SE.getUMaxExpr(Smallest, SE.getUMinExpr(Greatest, S));
Sanjoy Dase75ed922015-02-26 08:19:31 +00001138 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001139
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001140 // In some cases we can prove that we don't need a pre or post loop.
1141 ICmpInst::Predicate PredLE =
1142 IsSignedPredicate ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1143 ICmpInst::Predicate PredLT =
1144 IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001145
1146 bool ProvablyNoPreloop =
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001147 SE.isKnownPredicate(PredLE, Range.getBegin(), Smallest);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001148 if (!ProvablyNoPreloop)
1149 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001150
1151 bool ProvablyNoPostLoop =
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001152 SE.isKnownPredicate(PredLT, GreatestSeen, Range.getEnd());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001153 if (!ProvablyNoPostLoop)
1154 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001155
1156 return Result;
1157}
1158
1159void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
1160 const char *Tag) const {
1161 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
1162 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
1163 Result.Blocks.push_back(Clone);
1164 Result.Map[BB] = Clone;
1165 }
1166
1167 auto GetClonedValue = [&Result](Value *V) {
1168 assert(V && "null values not in domain!");
1169 auto It = Result.Map.find(V);
1170 if (It == Result.Map.end())
1171 return V;
1172 return static_cast<Value *>(It->second);
1173 };
1174
Sanjoy Das7a18a232016-08-14 01:04:36 +00001175 auto *ClonedLatch =
1176 cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch()));
1177 ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag,
1178 MDNode::get(Ctx, {}));
1179
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001180 Result.Structure = MainLoopStructure.map(GetClonedValue);
1181 Result.Structure.Tag = Tag;
1182
1183 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
1184 BasicBlock *ClonedBB = Result.Blocks[i];
1185 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
1186
1187 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
1188
1189 for (Instruction &I : *ClonedBB)
1190 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00001191 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001192
1193 // Exit blocks will now have one more predecessor and their PHI nodes need
1194 // to be edited to reflect that. No phi nodes need to be introduced because
1195 // the loop is in LCSSA.
1196
Sanjoy Dasd1d62a12016-08-13 22:00:09 +00001197 for (auto *SBB : successors(OriginalBB)) {
1198 if (OriginalLoop.contains(SBB))
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001199 continue; // not an exit block
1200
Sanjoy Dasd1d62a12016-08-13 22:00:09 +00001201 for (Instruction &I : *SBB) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001202 auto *PN = dyn_cast<PHINode>(&I);
1203 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001204 break;
1205
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001206 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
1207 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
1208 }
1209 }
1210 }
1211}
1212
1213LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001214 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001215 BasicBlock *ContinuationBlock) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001216 // We start with a loop with a single latch:
1217 //
1218 // +--------------------+
1219 // | |
1220 // | preheader |
1221 // | |
1222 // +--------+-----------+
1223 // | ----------------\
1224 // | / |
1225 // +--------v----v------+ |
1226 // | | |
1227 // | header | |
1228 // | | |
1229 // +--------------------+ |
1230 // |
1231 // ..... |
1232 // |
1233 // +--------------------+ |
1234 // | | |
1235 // | latch >----------/
1236 // | |
1237 // +-------v------------+
1238 // |
1239 // |
1240 // | +--------------------+
1241 // | | |
1242 // +---> original exit |
1243 // | |
1244 // +--------------------+
1245 //
1246 // We change the control flow to look like
1247 //
1248 //
1249 // +--------------------+
1250 // | |
1251 // | preheader >-------------------------+
1252 // | | |
1253 // +--------v-----------+ |
1254 // | /-------------+ |
1255 // | / | |
1256 // +--------v--v--------+ | |
1257 // | | | |
1258 // | header | | +--------+ |
1259 // | | | | | |
1260 // +--------------------+ | | +-----v-----v-----------+
1261 // | | | |
1262 // | | | .pseudo.exit |
1263 // | | | |
1264 // | | +-----------v-----------+
1265 // | | |
1266 // ..... | | |
1267 // | | +--------v-------------+
1268 // +--------------------+ | | | |
1269 // | | | | | ContinuationBlock |
1270 // | latch >------+ | | |
1271 // | | | +----------------------+
1272 // +---------v----------+ |
1273 // | |
1274 // | |
1275 // | +---------------^-----+
1276 // | | |
1277 // +-----> .exit.selector |
1278 // | |
1279 // +----------v----------+
1280 // |
1281 // +--------------------+ |
1282 // | | |
1283 // | original exit <----+
1284 // | |
1285 // +--------------------+
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001286
1287 RewrittenRangeInfo RRI;
1288
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001289 BasicBlock *BBInsertLocation = LS.Latch->getNextNode();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001290 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001291 &F, BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001292 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001293 BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001294
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001295 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001296 bool Increasing = LS.IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001297 bool IsSignedPredicate = LS.IsSignedPredicate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001298
1299 IRBuilder<> B(PreheaderJump);
1300
1301 // EnterLoopCond - is it okay to start executing this `LS'?
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001302 Value *EnterLoopCond = nullptr;
1303 if (Increasing)
1304 EnterLoopCond = IsSignedPredicate
1305 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1306 : B.CreateICmpULT(LS.IndVarStart, ExitSubloopAt);
1307 else
1308 EnterLoopCond = IsSignedPredicate
1309 ? B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt)
1310 : B.CreateICmpUGT(LS.IndVarStart, ExitSubloopAt);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001311
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001312 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1313 PreheaderJump->eraseFromParent();
1314
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001315 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001316 B.SetInsertPoint(LS.LatchBr);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001317 Value *TakeBackedgeLoopCond = nullptr;
1318 if (Increasing)
1319 TakeBackedgeLoopCond = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001320 ? B.CreateICmpSLT(LS.IndVarBase, ExitSubloopAt)
1321 : B.CreateICmpULT(LS.IndVarBase, ExitSubloopAt);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001322 else
1323 TakeBackedgeLoopCond = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001324 ? B.CreateICmpSGT(LS.IndVarBase, ExitSubloopAt)
1325 : B.CreateICmpUGT(LS.IndVarBase, ExitSubloopAt);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001326 Value *CondForBranch = LS.LatchBrExitIdx == 1
1327 ? TakeBackedgeLoopCond
1328 : B.CreateNot(TakeBackedgeLoopCond);
1329
1330 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001331
1332 B.SetInsertPoint(RRI.ExitSelector);
1333
1334 // IterationsLeft - are there any more iterations left, given the original
1335 // upper bound on the induction variable? If not, we branch to the "real"
1336 // exit.
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001337 Value *IterationsLeft = nullptr;
1338 if (Increasing)
1339 IterationsLeft = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001340 ? B.CreateICmpSLT(LS.IndVarBase, LS.LoopExitAt)
1341 : B.CreateICmpULT(LS.IndVarBase, LS.LoopExitAt);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001342 else
1343 IterationsLeft = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001344 ? B.CreateICmpSGT(LS.IndVarBase, LS.LoopExitAt)
1345 : B.CreateICmpUGT(LS.IndVarBase, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001346 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1347
1348 BranchInst *BranchToContinuation =
1349 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1350
1351 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1352 // each of the PHI nodes in the loop header. This feeds into the initial
1353 // value of the same PHI nodes if/when we continue execution.
1354 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001355 auto *PN = dyn_cast<PHINode>(&I);
1356 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001357 break;
1358
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001359 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1360 BranchToContinuation);
1361
1362 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
Serguei Katkov675e3042017-09-21 04:50:41 +00001363 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1364 RRI.ExitSelector);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001365 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1366 }
1367
Max Kazantseva22742b2017-08-31 05:58:15 +00001368 RRI.IndVarEnd = PHINode::Create(LS.IndVarBase->getType(), 2, "indvar.end",
Sanjoy Dase75ed922015-02-26 08:19:31 +00001369 BranchToContinuation);
1370 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
Max Kazantseva22742b2017-08-31 05:58:15 +00001371 RRI.IndVarEnd->addIncoming(LS.IndVarBase, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001372
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001373 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1374 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1375 for (Instruction &I : *LS.LatchExit) {
1376 if (PHINode *PN = dyn_cast<PHINode>(&I))
1377 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1378 else
1379 break;
1380 }
1381
1382 return RRI;
1383}
1384
1385void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001386 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001387 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001388 unsigned PHIIndex = 0;
1389 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001390 auto *PN = dyn_cast<PHINode>(&I);
1391 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001392 break;
1393
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001394 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1395 if (PN->getIncomingBlock(i) == ContinuationBlock)
1396 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1397 }
1398
Sanjoy Dase75ed922015-02-26 08:19:31 +00001399 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001400}
1401
Sanjoy Dase75ed922015-02-26 08:19:31 +00001402BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1403 BasicBlock *OldPreheader,
1404 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001405 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1406 BranchInst::Create(LS.Header, Preheader);
1407
1408 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001409 auto *PN = dyn_cast<PHINode>(&I);
1410 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001411 break;
1412
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001413 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1414 replacePHIBlock(PN, OldPreheader, Preheader);
1415 }
1416
1417 return Preheader;
1418}
1419
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001420void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001421 Loop *ParentLoop = OriginalLoop.getParentLoop();
1422 if (!ParentLoop)
1423 return;
1424
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001425 for (BasicBlock *BB : BBs)
Sanjoy Das83a72852016-08-02 19:32:01 +00001426 ParentLoop->addBasicBlockToLoop(BB, LI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001427}
1428
Sanjoy Das21434472016-08-14 01:04:46 +00001429Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent,
1430 ValueToValueMapTy &VM) {
Sanjoy Dasdef17292017-09-28 02:45:42 +00001431 Loop &New = *LI.AllocateLoop();
Chandler Carruth29c22d22017-05-25 03:01:31 +00001432 if (Parent)
1433 Parent->addChildLoop(&New);
1434 else
1435 LI.addTopLevelLoop(&New);
1436 LPM.addLoop(New);
Sanjoy Das21434472016-08-14 01:04:46 +00001437
1438 // Add all of the blocks in Original to the new loop.
1439 for (auto *BB : Original->blocks())
1440 if (LI.getLoopFor(BB) == Original)
1441 New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI);
1442
1443 // Add all of the subloops to the new loop.
1444 for (Loop *SubLoop : *Original)
1445 createClonedLoopStructure(SubLoop, &New, VM);
1446
1447 return &New;
1448}
1449
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001450bool LoopConstrainer::run() {
1451 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001452 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1453 Preheader = OriginalLoop.getLoopPreheader();
1454 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1455 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001456
1457 OriginalPreheader = Preheader;
1458 MainLoopPreheader = Preheader;
1459
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001460 bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate;
1461 Optional<SubRanges> MaybeSR = calculateSubRanges(IsSignedPredicate);
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001462 if (!MaybeSR.hasValue()) {
1463 DEBUG(dbgs() << "irce: could not compute subranges\n");
1464 return false;
1465 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001466
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001467 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001468 bool Increasing = MainLoopStructure.IndVarIncreasing;
1469 IntegerType *IVTy =
Max Kazantseva22742b2017-08-31 05:58:15 +00001470 cast<IntegerType>(MainLoopStructure.IndVarBase->getType());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001471
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001472 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001473 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001474
1475 // It would have been better to make `PreLoop' and `PostLoop'
1476 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1477 // constructor.
1478 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001479 bool NeedsPreLoop =
1480 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1481 bool NeedsPostLoop =
1482 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1483
1484 Value *ExitPreLoopAt = nullptr;
1485 Value *ExitMainLoopAt = nullptr;
1486 const SCEVConstant *MinusOneS =
1487 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1488
1489 if (NeedsPreLoop) {
1490 const SCEV *ExitPreLoopAtSCEV = nullptr;
1491
1492 if (Increasing)
1493 ExitPreLoopAtSCEV = *SR.LowLimit;
1494 else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001495 if (CanBeMin(SE, *SR.HighLimit, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +00001496 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1497 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1498 << "\n");
1499 return false;
1500 }
1501 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1502 }
Serguei Katkov675e3042017-09-21 04:50:41 +00001503
Sanjoy Dase75ed922015-02-26 08:19:31 +00001504 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1505 ExitPreLoopAt->setName("exit.preloop.at");
1506 }
1507
1508 if (NeedsPostLoop) {
1509 const SCEV *ExitMainLoopAtSCEV = nullptr;
1510
1511 if (Increasing)
1512 ExitMainLoopAtSCEV = *SR.HighLimit;
1513 else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001514 if (CanBeMin(SE, *SR.LowLimit, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +00001515 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1516 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1517 << "\n");
1518 return false;
1519 }
1520 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1521 }
Serguei Katkov675e3042017-09-21 04:50:41 +00001522
Sanjoy Dase75ed922015-02-26 08:19:31 +00001523 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1524 ExitMainLoopAt->setName("exit.mainloop.at");
1525 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001526
1527 // We clone these ahead of time so that we don't have to deal with changing
1528 // and temporarily invalid IR as we transform the loops.
1529 if (NeedsPreLoop)
1530 cloneLoop(PreLoop, "preloop");
1531 if (NeedsPostLoop)
1532 cloneLoop(PostLoop, "postloop");
1533
1534 RewrittenRangeInfo PreLoopRRI;
1535
1536 if (NeedsPreLoop) {
1537 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1538 PreLoop.Structure.Header);
1539
1540 MainLoopPreheader =
1541 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001542 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1543 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001544 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1545 PreLoopRRI);
1546 }
1547
1548 BasicBlock *PostLoopPreheader = nullptr;
1549 RewrittenRangeInfo PostLoopRRI;
1550
1551 if (NeedsPostLoop) {
1552 PostLoopPreheader =
1553 createPreheader(PostLoop.Structure, Preheader, "postloop");
1554 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001555 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001556 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1557 PostLoopRRI);
1558 }
1559
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001560 BasicBlock *NewMainLoopPreheader =
1561 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1562 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1563 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1564 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001565
1566 // Some of the above may be nullptr, filter them out before passing to
1567 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001568 auto NewBlocksEnd =
1569 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001570
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001571 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001572
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001573 DT.recalculate(F);
Sanjoy Das21434472016-08-14 01:04:46 +00001574
Anna Thomas72180322017-06-06 14:54:01 +00001575 // We need to first add all the pre and post loop blocks into the loop
1576 // structures (as part of createClonedLoopStructure), and then update the
1577 // LCSSA form and LoopSimplifyForm. This is necessary for correctly updating
1578 // LI when LoopSimplifyForm is generated.
1579 Loop *PreL = nullptr, *PostL = nullptr;
Sanjoy Das21434472016-08-14 01:04:46 +00001580 if (!PreLoop.Blocks.empty()) {
Anna Thomas72180322017-06-06 14:54:01 +00001581 PreL = createClonedLoopStructure(
Sanjoy Das21434472016-08-14 01:04:46 +00001582 &OriginalLoop, OriginalLoop.getParentLoop(), PreLoop.Map);
Sanjoy Das21434472016-08-14 01:04:46 +00001583 }
1584
1585 if (!PostLoop.Blocks.empty()) {
Anna Thomas72180322017-06-06 14:54:01 +00001586 PostL = createClonedLoopStructure(
Sanjoy Das21434472016-08-14 01:04:46 +00001587 &OriginalLoop, OriginalLoop.getParentLoop(), PostLoop.Map);
Sanjoy Das21434472016-08-14 01:04:46 +00001588 }
1589
Anna Thomas72180322017-06-06 14:54:01 +00001590 // This function canonicalizes the loop into Loop-Simplify and LCSSA forms.
1591 auto CanonicalizeLoop = [&] (Loop *L, bool IsOriginalLoop) {
1592 formLCSSARecursively(*L, DT, &LI, &SE);
1593 simplifyLoop(L, &DT, &LI, &SE, nullptr, true);
1594 // Pre/post loops are slow paths, we do not need to perform any loop
1595 // optimizations on them.
1596 if (!IsOriginalLoop)
1597 DisableAllLoopOptsOnLoop(*L);
1598 };
1599 if (PreL)
1600 CanonicalizeLoop(PreL, false);
1601 if (PostL)
1602 CanonicalizeLoop(PostL, false);
1603 CanonicalizeLoop(&OriginalLoop, true);
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001604
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001605 return true;
1606}
1607
Sanjoy Das95c476d2015-02-21 22:20:22 +00001608/// Computes and returns a range of values for the induction variable (IndVar)
1609/// in which the range check can be safely elided. If it cannot compute such a
1610/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001611Optional<InductiveRangeCheck::Range>
Sanjoy Das59776732016-05-21 02:31:51 +00001612InductiveRangeCheck::computeSafeIterationSpace(
1613 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001614 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1615 // variable, that may or may not exist as a real llvm::Value in the loop) and
1616 // this inductive range check is a range check on the "C + D * I" ("C" is
Max Kazantsev84286ce2017-10-31 06:19:05 +00001617 // getBegin() and "D" is getStep()). We rewrite the value being range
Sanjoy Das95c476d2015-02-21 22:20:22 +00001618 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001619 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001620 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001621 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001622 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1623 //
1624 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1625 // and subtractions are twos-complement wrapping and comparisons are signed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001626 //
1627 // Proof:
1628 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001629 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1630 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1631 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1632 // overflown.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001633 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001634 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1635 // Hence 0 <= (IndVar + M) < L
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001636
Sanjoy Das95c476d2015-02-21 22:20:22 +00001637 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1638 // 127, IndVar = 126 and L = -2 in an i8 world.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001639
Sanjoy Das95c476d2015-02-21 22:20:22 +00001640 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001641 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001642
Sanjoy Das95c476d2015-02-21 22:20:22 +00001643 const SCEV *A = IndVar->getStart();
1644 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1645 if (!B)
1646 return None;
Max Kazantseve4c220e2017-08-01 06:49:29 +00001647 assert(!B->isZero() && "Recurrence with zero step?");
Sanjoy Das95c476d2015-02-21 22:20:22 +00001648
Max Kazantsev84286ce2017-10-31 06:19:05 +00001649 const SCEV *C = getBegin();
1650 const SCEVConstant *D = dyn_cast<SCEVConstant>(getStep());
Sanjoy Das95c476d2015-02-21 22:20:22 +00001651 if (D != B)
1652 return None;
1653
Max Kazantsev95054702017-08-04 07:41:24 +00001654 assert(!D->getValue()->isZero() && "Recurrence with zero step?");
Sanjoy Das95c476d2015-02-21 22:20:22 +00001655
1656 const SCEV *M = SE.getMinusSCEV(C, A);
Sanjoy Das95c476d2015-02-21 22:20:22 +00001657 const SCEV *Begin = SE.getNegativeSCEV(M);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001658 const SCEV *UpperLimit = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001659
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001660 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1661 // We can potentially do much better here.
Max Kazantsev84286ce2017-10-31 06:19:05 +00001662 if (const SCEV *L = getEnd())
Max Kazantsev390fc572017-10-30 09:35:16 +00001663 UpperLimit = L;
1664 else {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001665 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1666 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1667 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1668 }
1669
1670 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
Sanjoy Das351db052015-01-22 09:32:02 +00001671 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001672}
1673
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001674static Optional<InductiveRangeCheck::Range>
Max Kazantsev9ac70212017-10-25 06:47:39 +00001675IntersectSignedRange(ScalarEvolution &SE,
1676 const Optional<InductiveRangeCheck::Range> &R1,
1677 const InductiveRangeCheck::Range &R2) {
Max Kazantsev4332a942017-10-25 06:10:02 +00001678 if (R2.isEmpty(SE, /* IsSigned */ true))
Max Kazantsev25d86552017-10-11 06:53:07 +00001679 return None;
Max Kazantsev3612d4b2017-10-19 05:33:28 +00001680 if (!R1.hasValue())
1681 return R2;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001682 auto &R1Value = R1.getValue();
Max Kazantsev3612d4b2017-10-19 05:33:28 +00001683 // We never return empty ranges from this function, and R1 is supposed to be
1684 // a result of intersection. Thus, R1 is never empty.
Max Kazantsev4332a942017-10-25 06:10:02 +00001685 assert(!R1Value.isEmpty(SE, /* IsSigned */ true) &&
1686 "We should never have empty R1!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001687
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001688 // TODO: we could widen the smaller range and have this work; but for now we
1689 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001690 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001691 return None;
1692
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001693 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1694 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1695
Max Kazantsev25d86552017-10-11 06:53:07 +00001696 // If the resulting range is empty, just return None.
1697 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
Max Kazantsev4332a942017-10-25 06:10:02 +00001698 if (Ret.isEmpty(SE, /* IsSigned */ true))
Max Kazantsev25d86552017-10-11 06:53:07 +00001699 return None;
1700 return Ret;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001701}
1702
Max Kazantsev9ac70212017-10-25 06:47:39 +00001703static Optional<InductiveRangeCheck::Range>
1704IntersectUnsignedRange(ScalarEvolution &SE,
1705 const Optional<InductiveRangeCheck::Range> &R1,
1706 const InductiveRangeCheck::Range &R2) {
1707 if (R2.isEmpty(SE, /* IsSigned */ false))
1708 return None;
1709 if (!R1.hasValue())
1710 return R2;
1711 auto &R1Value = R1.getValue();
1712 // We never return empty ranges from this function, and R1 is supposed to be
1713 // a result of intersection. Thus, R1 is never empty.
1714 assert(!R1Value.isEmpty(SE, /* IsSigned */ false) &&
1715 "We should never have empty R1!");
1716
1717 // TODO: we could widen the smaller range and have this work; but for now we
1718 // bail out to keep things simple.
1719 if (R1Value.getType() != R2.getType())
1720 return None;
1721
1722 const SCEV *NewBegin = SE.getUMaxExpr(R1Value.getBegin(), R2.getBegin());
1723 const SCEV *NewEnd = SE.getUMinExpr(R1Value.getEnd(), R2.getEnd());
1724
1725 // If the resulting range is empty, just return None.
1726 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
1727 if (Ret.isEmpty(SE, /* IsSigned */ false))
1728 return None;
1729 return Ret;
1730}
1731
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001732bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001733 if (skipLoop(L))
1734 return false;
1735
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001736 if (L->getBlocks().size() >= LoopSizeCutoff) {
1737 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1738 return false;
1739 }
1740
1741 BasicBlock *Preheader = L->getLoopPreheader();
1742 if (!Preheader) {
1743 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1744 return false;
1745 }
1746
1747 LLVMContext &Context = Preheader->getContext();
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001748 SmallVector<InductiveRangeCheck, 16> RangeChecks;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001749 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Cong Houab23bfb2015-07-15 22:48:29 +00001750 BranchProbabilityInfo &BPI =
1751 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001752
1753 for (auto BBI : L->getBlocks())
1754 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
Sanjoy Dasa0992682016-05-26 00:09:02 +00001755 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1756 RangeChecks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001757
1758 if (RangeChecks.empty())
1759 return false;
1760
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001761 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1762 OS << "irce: looking at loop "; L->print(OS);
1763 OS << "irce: loop has " << RangeChecks.size()
1764 << " inductive range checks: \n";
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001765 for (InductiveRangeCheck &IRC : RangeChecks)
1766 IRC.print(OS);
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001767 };
1768
1769 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1770
1771 if (PrintRangeChecks)
1772 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001773
Sanjoy Dase75ed922015-02-26 08:19:31 +00001774 const char *FailureReason = nullptr;
1775 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001776 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001777 if (!MaybeLoopStructure.hasValue()) {
1778 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1779 << "\n";);
1780 return false;
1781 }
1782 LoopStructure LS = MaybeLoopStructure.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001783 const SCEVAddRecExpr *IndVar =
Serguei Katkov675e3042017-09-21 04:50:41 +00001784 cast<SCEVAddRecExpr>(SE.getMinusSCEV(SE.getSCEV(LS.IndVarBase), SE.getSCEV(LS.IndVarStep)));
Sanjoy Dase75ed922015-02-26 08:19:31 +00001785
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001786 Optional<InductiveRangeCheck::Range> SafeIterRange;
1787 Instruction *ExprInsertPt = Preheader->getTerminator();
1788
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001789 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
Max Kazantsev9ac70212017-10-25 06:47:39 +00001790 auto RangeIsNonNegative = [&](InductiveRangeCheck::Range &R) {
1791 return SE.isKnownNonNegative(R.getBegin()) &&
1792 SE.isKnownNonNegative(R.getEnd());
1793 };
1794 // Basing on the type of latch predicate, we interpret the IV iteration range
1795 // as signed or unsigned range. We use different min/max functions (signed or
1796 // unsigned) when intersecting this range with safe iteration ranges implied
1797 // by range checks.
1798 auto IntersectRange =
1799 LS.IsSignedPredicate ? IntersectSignedRange : IntersectUnsignedRange;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001800
1801 IRBuilder<> B(ExprInsertPt);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001802 for (InductiveRangeCheck &IRC : RangeChecks) {
1803 auto Result = IRC.computeSafeIterationSpace(SE, IndVar);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001804 if (Result.hasValue()) {
Max Kazantsev9ac70212017-10-25 06:47:39 +00001805 // Intersecting a signed and an unsigned ranges may produce incorrect
1806 // results because we can use neither signed nor unsigned min/max for
1807 // reliably correct intersection if a range contains negative values
1808 // which are either actually negative or big positive. Intersection is
1809 // safe in two following cases:
1810 // 1. Both ranges are signed/unsigned, then we use signed/unsigned min/max
1811 // respectively for their intersection;
1812 // 2. IRC safe iteration space only contains values from [0, SINT_MAX].
1813 // The interpretation of these values is unambiguous.
1814 // We take the type of IV iteration range as a reference (we will
1815 // intersect it with the resulting range of all IRC's later in
1816 // calculateSubRanges). Only ranges of IRC of the same type are considered
1817 // for removal unless we prove that its range doesn't contain ambiguous
1818 // values.
1819 if (IRC.isSigned() != LS.IsSignedPredicate &&
1820 !RangeIsNonNegative(Result.getValue()))
1821 continue;
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001822 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001823 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001824 if (MaybeSafeIterRange.hasValue()) {
Max Kazantsev4332a942017-10-25 06:10:02 +00001825 assert(
1826 !MaybeSafeIterRange.getValue().isEmpty(SE, LS.IsSignedPredicate) &&
1827 "We should never return empty ranges!");
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001828 RangeChecksToEliminate.push_back(IRC);
1829 SafeIterRange = MaybeSafeIterRange.getValue();
1830 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001831 }
1832 }
1833
1834 if (!SafeIterRange.hasValue())
1835 return false;
1836
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001837 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Sanjoy Das21434472016-08-14 01:04:46 +00001838 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LPM,
1839 LS, SE, DT, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001840 bool Changed = LC.run();
1841
1842 if (Changed) {
1843 auto PrintConstrainedLoopInfo = [L]() {
1844 dbgs() << "irce: in function ";
1845 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1846 dbgs() << "constrained ";
1847 L->print(dbgs());
1848 };
1849
1850 DEBUG(PrintConstrainedLoopInfo());
1851
1852 if (PrintChangedLoops)
1853 PrintConstrainedLoopInfo();
1854
1855 // Optimize away the now-redundant range checks.
1856
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001857 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1858 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001859 ? ConstantInt::getTrue(Context)
1860 : ConstantInt::getFalse(Context);
Sanjoy Dasaa83c472016-05-23 22:16:45 +00001861 IRC.getCheckUse()->set(FoldedRangeCheck);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001862 }
1863 }
1864
1865 return Changed;
1866}
1867
1868Pass *llvm::createInductiveRangeCheckEliminationPass() {
1869 return new InductiveRangeCheckElimination;
1870}