blob: 6bd341769094238110301d063d6bf7e8913698fd [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
Fedor Sergeev194a4072018-03-15 11:01:19 +000046#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000047#include "llvm/ADT/APInt.h"
48#include "llvm/ADT/ArrayRef.h"
49#include "llvm/ADT/None.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000050#include "llvm/ADT/Optional.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000051#include "llvm/ADT/SmallPtrSet.h"
52#include "llvm/ADT/SmallVector.h"
53#include "llvm/ADT/StringRef.h"
54#include "llvm/ADT/Twine.h"
Sanjoy Dasdcf26512015-01-27 21:38:12 +000055#include "llvm/Analysis/BranchProbabilityInfo.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +000056#include "llvm/Analysis/LoopAnalysisManager.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000057#include "llvm/Analysis/LoopInfo.h"
58#include "llvm/Analysis/LoopPass.h"
59#include "llvm/Analysis/ScalarEvolution.h"
60#include "llvm/Analysis/ScalarEvolutionExpander.h"
61#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000062#include "llvm/IR/BasicBlock.h"
63#include "llvm/IR/CFG.h"
64#include "llvm/IR/Constants.h"
65#include "llvm/IR/DerivedTypes.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000066#include "llvm/IR/Dominators.h"
67#include "llvm/IR/Function.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000068#include "llvm/IR/IRBuilder.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000069#include "llvm/IR/InstrTypes.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000070#include "llvm/IR/Instructions.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000071#include "llvm/IR/Metadata.h"
72#include "llvm/IR/Module.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000073#include "llvm/IR/PatternMatch.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000074#include "llvm/IR/Type.h"
75#include "llvm/IR/Use.h"
76#include "llvm/IR/User.h"
77#include "llvm/IR/Value.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000078#include "llvm/Pass.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000079#include "llvm/Support/BranchProbability.h"
80#include "llvm/Support/Casting.h"
81#include "llvm/Support/CommandLine.h"
82#include "llvm/Support/Compiler.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000083#include "llvm/Support/Debug.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000084#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000085#include "llvm/Support/raw_ostream.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000086#include "llvm/Transforms/Scalar.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000087#include "llvm/Transforms/Utils/Cloning.h"
Sanjoy Dascf181862016-08-06 00:01:56 +000088#include "llvm/Transforms/Utils/LoopSimplify.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000089#include "llvm/Transforms/Utils/LoopUtils.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000090#include "llvm/Transforms/Utils/ValueMapper.h"
91#include <algorithm>
92#include <cassert>
93#include <iterator>
94#include <limits>
95#include <utility>
96#include <vector>
Sanjoy Dasa1837a32015-01-16 01:03:22 +000097
98using namespace llvm;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000099using namespace llvm::PatternMatch;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000100
Benjamin Kramer970eac42015-02-06 17:51:54 +0000101static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
102 cl::init(64));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000103
Benjamin Kramer970eac42015-02-06 17:51:54 +0000104static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
105 cl::init(false));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000106
Sanjoy Das9c1bfae2015-03-17 01:40:22 +0000107static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
108 cl::init(false));
109
Sanjoy Dase91665d2015-02-26 08:56:04 +0000110static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
111 cl::Hidden, cl::init(10));
112
Sanjoy Dasbb969792016-07-22 00:40:56 +0000113static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks",
114 cl::Hidden, cl::init(false));
115
Max Kazantsev8aacef62017-10-04 06:53:22 +0000116static cl::opt<bool> AllowUnsignedLatchCondition("irce-allow-unsigned-latch",
Max Kazantsev9ac70212017-10-25 06:47:39 +0000117 cl::Hidden, cl::init(true));
Max Kazantsev8aacef62017-10-04 06:53:22 +0000118
Sanjoy Das7a18a232016-08-14 01:04:36 +0000119static const char *ClonedLoopTag = "irce.loop.clone";
120
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000121#define DEBUG_TYPE "irce"
122
123namespace {
124
125/// An inductive range check is conditional branch in a loop with
126///
127/// 1. a very cold successor (i.e. the branch jumps to that successor very
128/// rarely)
129///
130/// and
131///
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000132/// 2. a condition that is provably true for some contiguous range of values
133/// taken by the containing loop's induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000134///
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000135class InductiveRangeCheck {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000136
Max Kazantsev84286ce2017-10-31 06:19:05 +0000137 const SCEV *Begin = nullptr;
138 const SCEV *Step = nullptr;
139 const SCEV *End = nullptr;
Sanjoy Dasee77a482016-05-26 01:50:18 +0000140 Use *CheckUse = nullptr;
Max Kazantsev9ac70212017-10-25 06:47:39 +0000141 bool IsSigned = true;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000142
Max Kazantsev80242ee2019-01-15 10:48:45 +0000143 static bool parseRangeCheckICmp(Loop *L, ICmpInst *ICI, ScalarEvolution &SE,
144 Value *&Index, Value *&Length,
145 bool &IsSigned);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000146
Sanjoy Dasa0992682016-05-26 00:09:02 +0000147 static void
148 extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,
149 SmallVectorImpl<InductiveRangeCheck> &Checks,
150 SmallPtrSetImpl<Value *> &Visited);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000151
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000152public:
Max Kazantsev84286ce2017-10-31 06:19:05 +0000153 const SCEV *getBegin() const { return Begin; }
154 const SCEV *getStep() const { return Step; }
155 const SCEV *getEnd() const { return End; }
Max Kazantsev9ac70212017-10-25 06:47:39 +0000156 bool isSigned() const { return IsSigned; }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000157
158 void print(raw_ostream &OS) const {
159 OS << "InductiveRangeCheck:\n";
Max Kazantsev84286ce2017-10-31 06:19:05 +0000160 OS << " Begin: ";
161 Begin->print(OS);
162 OS << " Step: ";
163 Step->print(OS);
164 OS << " End: ";
Max Kazantsevef057602018-01-12 10:00:26 +0000165 End->print(OS);
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000166 OS << "\n CheckUse: ";
167 getCheckUse()->getUser()->print(OS);
168 OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000169 }
170
Davide Italianod1279df2016-08-18 15:55:49 +0000171 LLVM_DUMP_METHOD
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000172 void dump() {
173 print(dbgs());
174 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000175
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000176 Use *getCheckUse() const { return CheckUse; }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000177
Sanjoy Das351db052015-01-22 09:32:02 +0000178 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
Max Kazantsevd0fe5022018-01-15 05:44:43 +0000179 /// R.getEnd() le R.getBegin(), then R denotes the empty range.
Sanjoy Das351db052015-01-22 09:32:02 +0000180
181 class Range {
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000182 const SCEV *Begin;
183 const SCEV *End;
Sanjoy Das351db052015-01-22 09:32:02 +0000184
185 public:
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000186 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
Sanjoy Das351db052015-01-22 09:32:02 +0000187 assert(Begin->getType() == End->getType() && "ill-typed range!");
188 }
189
190 Type *getType() const { return Begin->getType(); }
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000191 const SCEV *getBegin() const { return Begin; }
192 const SCEV *getEnd() const { return End; }
Max Kazantsev4332a942017-10-25 06:10:02 +0000193 bool isEmpty(ScalarEvolution &SE, bool IsSigned) const {
194 if (Begin == End)
195 return true;
196 if (IsSigned)
197 return SE.isKnownPredicate(ICmpInst::ICMP_SGE, Begin, End);
198 else
199 return SE.isKnownPredicate(ICmpInst::ICMP_UGE, Begin, End);
200 }
Sanjoy Das351db052015-01-22 09:32:02 +0000201 };
202
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000203 /// This is the value the condition of the branch needs to evaluate to for the
204 /// branch to take the hot successor (see (1) above).
205 bool getPassingDirection() { return true; }
206
Sanjoy Das95c476d2015-02-21 22:20:22 +0000207 /// Computes a range for the induction variable (IndVar) in which the range
208 /// check is redundant and can be constant-folded away. The induction
209 /// variable is not required to be the canonical {0,+,1} induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000210 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
Max Kazantsev26846782017-11-20 06:07:57 +0000211 const SCEVAddRecExpr *IndVar,
212 bool IsLatchSigned) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000213
Sanjoy Dasa0992682016-05-26 00:09:02 +0000214 /// Parse out a set of inductive range checks from \p BI and append them to \p
215 /// Checks.
216 ///
217 /// NB! There may be conditions feeding into \p BI that aren't inductive range
218 /// checks, and hence don't end up in \p Checks.
219 static void
220 extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE,
Fedor Sergeev194a4072018-03-15 11:01:19 +0000221 BranchProbabilityInfo *BPI,
Sanjoy Dasa0992682016-05-26 00:09:02 +0000222 SmallVectorImpl<InductiveRangeCheck> &Checks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000223};
224
Fedor Sergeev194a4072018-03-15 11:01:19 +0000225class InductiveRangeCheckElimination {
226 ScalarEvolution &SE;
227 BranchProbabilityInfo *BPI;
228 DominatorTree &DT;
229 LoopInfo &LI;
230
231public:
232 InductiveRangeCheckElimination(ScalarEvolution &SE,
233 BranchProbabilityInfo *BPI, DominatorTree &DT,
234 LoopInfo &LI)
235 : SE(SE), BPI(BPI), DT(DT), LI(LI) {}
236
237 bool run(Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop);
238};
239
240class IRCELegacyPass : public LoopPass {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000241public:
242 static char ID;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000243
Fedor Sergeev194a4072018-03-15 11:01:19 +0000244 IRCELegacyPass() : LoopPass(ID) {
245 initializeIRCELegacyPassPass(*PassRegistry::getPassRegistry());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000246 }
247
248 void getAnalysisUsage(AnalysisUsage &AU) const override {
Cong Houab23bfb2015-07-15 22:48:29 +0000249 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000250 getLoopAnalysisUsage(AU);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000251 }
252
253 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
254};
255
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000256} // end anonymous namespace
257
Fedor Sergeev194a4072018-03-15 11:01:19 +0000258char IRCELegacyPass::ID = 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000259
Fedor Sergeev194a4072018-03-15 11:01:19 +0000260INITIALIZE_PASS_BEGIN(IRCELegacyPass, "irce",
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000261 "Inductive range check elimination", false, false)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000262INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000263INITIALIZE_PASS_DEPENDENCY(LoopPass)
Fedor Sergeev194a4072018-03-15 11:01:19 +0000264INITIALIZE_PASS_END(IRCELegacyPass, "irce", "Inductive range check elimination",
265 false, false)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000266
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000267/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
Max Kazantsev80242ee2019-01-15 10:48:45 +0000268/// be interpreted as a range check, return false and set `Index` and `Length`
269/// to `nullptr`. Otherwise set `Index` to the value being range checked, and
270/// set `Length` to the upper limit `Index` is being range checked.
271bool
Sanjoy Das337d46b2015-03-24 19:29:18 +0000272InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
273 ScalarEvolution &SE, Value *&Index,
Max Kazantsev9ac70212017-10-25 06:47:39 +0000274 Value *&Length, bool &IsSigned) {
Max Kazantsev8624a472018-04-09 06:01:22 +0000275 auto IsLoopInvariant = [&SE, L](Value *V) {
276 return SE.isLoopInvariant(SE.getSCEV(V), L);
Sanjoy Das337d46b2015-03-24 19:29:18 +0000277 };
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000278
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000279 ICmpInst::Predicate Pred = ICI->getPredicate();
280 Value *LHS = ICI->getOperand(0);
281 Value *RHS = ICI->getOperand(1);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000282
283 switch (Pred) {
284 default:
Max Kazantsev80242ee2019-01-15 10:48:45 +0000285 return false;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000286
287 case ICmpInst::ICMP_SLE:
288 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000289 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000290 case ICmpInst::ICMP_SGE:
Max Kazantsev9ac70212017-10-25 06:47:39 +0000291 IsSigned = true;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000292 if (match(RHS, m_ConstantInt<0>())) {
293 Index = LHS;
Max Kazantsev80242ee2019-01-15 10:48:45 +0000294 return true; // Lower.
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000295 }
Max Kazantsev80242ee2019-01-15 10:48:45 +0000296 return false;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000297
298 case ICmpInst::ICMP_SLT:
299 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000300 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000301 case ICmpInst::ICMP_SGT:
Max Kazantsev9ac70212017-10-25 06:47:39 +0000302 IsSigned = true;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000303 if (match(RHS, m_ConstantInt<-1>())) {
304 Index = LHS;
Max Kazantsev80242ee2019-01-15 10:48:45 +0000305 return true; // Lower.
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000306 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000307
Max Kazantsev8624a472018-04-09 06:01:22 +0000308 if (IsLoopInvariant(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000309 Index = RHS;
310 Length = LHS;
Max Kazantsev80242ee2019-01-15 10:48:45 +0000311 return true; // Upper.
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000312 }
Max Kazantsev80242ee2019-01-15 10:48:45 +0000313 return false;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000314
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000315 case ICmpInst::ICMP_ULT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000316 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000317 LLVM_FALLTHROUGH;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000318 case ICmpInst::ICMP_UGT:
Max Kazantsev9ac70212017-10-25 06:47:39 +0000319 IsSigned = false;
Max Kazantsev8624a472018-04-09 06:01:22 +0000320 if (IsLoopInvariant(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000321 Index = RHS;
322 Length = LHS;
Max Kazantsev80242ee2019-01-15 10:48:45 +0000323 return true; // Both lower and upper.
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000324 }
Max Kazantsev80242ee2019-01-15 10:48:45 +0000325 return false;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000326 }
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000327
328 llvm_unreachable("default clause returns!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000329}
330
Sanjoy Dasa0992682016-05-26 00:09:02 +0000331void InductiveRangeCheck::extractRangeChecksFromCond(
332 Loop *L, ScalarEvolution &SE, Use &ConditionUse,
333 SmallVectorImpl<InductiveRangeCheck> &Checks,
334 SmallPtrSetImpl<Value *> &Visited) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000335 Value *Condition = ConditionUse.get();
Sanjoy Dasa0992682016-05-26 00:09:02 +0000336 if (!Visited.insert(Condition).second)
337 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000338
Max Kazantsev1ac6e8a2017-11-17 06:49:26 +0000339 // TODO: Do the same for OR, XOR, NOT etc?
Sanjoy Dasa0992682016-05-26 00:09:02 +0000340 if (match(Condition, m_And(m_Value(), m_Value()))) {
Sanjoy Dasa0992682016-05-26 00:09:02 +0000341 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
Max Kazantsev1ac6e8a2017-11-17 06:49:26 +0000342 Checks, Visited);
Sanjoy Dasa0992682016-05-26 00:09:02 +0000343 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
Max Kazantsev1ac6e8a2017-11-17 06:49:26 +0000344 Checks, Visited);
Sanjoy Dasa0992682016-05-26 00:09:02 +0000345 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000346 }
347
Sanjoy Dasa0992682016-05-26 00:09:02 +0000348 ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);
349 if (!ICI)
350 return;
351
352 Value *Length = nullptr, *Index;
Max Kazantsev9ac70212017-10-25 06:47:39 +0000353 bool IsSigned;
Max Kazantsev80242ee2019-01-15 10:48:45 +0000354 if (!parseRangeCheckICmp(L, ICI, SE, Index, Length, IsSigned))
Sanjoy Dasa0992682016-05-26 00:09:02 +0000355 return;
356
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000357 const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000358 bool IsAffineIndex =
359 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
360
361 if (!IsAffineIndex)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000362 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000363
Max Kazantsevef057602018-01-12 10:00:26 +0000364 const SCEV *End = nullptr;
365 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
366 // We can potentially do much better here.
367 if (Length)
368 End = SE.getSCEV(Length);
369 else {
Max Kazantsevef057602018-01-12 10:00:26 +0000370 // So far we can only reach this point for Signed range check. This may
371 // change in future. In this case we will need to pick Unsigned max for the
372 // unsigned range check.
373 unsigned BitWidth = cast<IntegerType>(IndexAddRec->getType())->getBitWidth();
374 const SCEV *SIntMax = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
375 End = SIntMax;
376 }
377
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000378 InductiveRangeCheck IRC;
Max Kazantsevef057602018-01-12 10:00:26 +0000379 IRC.End = End;
Max Kazantsev84286ce2017-10-31 06:19:05 +0000380 IRC.Begin = IndexAddRec->getStart();
381 IRC.Step = IndexAddRec->getStepRecurrence(SE);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000382 IRC.CheckUse = &ConditionUse;
Max Kazantsev9ac70212017-10-25 06:47:39 +0000383 IRC.IsSigned = IsSigned;
Sanjoy Dasa0992682016-05-26 00:09:02 +0000384 Checks.push_back(IRC);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000385}
386
Sanjoy Dasa0992682016-05-26 00:09:02 +0000387void InductiveRangeCheck::extractRangeChecksFromBranch(
Fedor Sergeev194a4072018-03-15 11:01:19 +0000388 BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo *BPI,
Sanjoy Dasa0992682016-05-26 00:09:02 +0000389 SmallVectorImpl<InductiveRangeCheck> &Checks) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000390 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
Sanjoy Dasa0992682016-05-26 00:09:02 +0000391 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000392
393 BranchProbability LikelyTaken(15, 16);
394
Fedor Sergeev194a4072018-03-15 11:01:19 +0000395 if (!SkipProfitabilityChecks && BPI &&
396 BPI->getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000397 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000398
Sanjoy Dasa0992682016-05-26 00:09:02 +0000399 SmallPtrSet<Value *, 8> Visited;
400 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
401 Checks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000402}
403
Anna Thomas65ca8e92016-12-13 21:05:21 +0000404// Add metadata to the loop L to disable loop optimizations. Callers need to
405// confirm that optimizing loop L is not beneficial.
406static void DisableAllLoopOptsOnLoop(Loop &L) {
407 // We do not care about any existing loopID related metadata for L, since we
408 // are setting all loop metadata to false.
409 LLVMContext &Context = L.getHeader()->getContext();
410 // Reserve first location for self reference to the LoopID metadata node.
411 MDNode *Dummy = MDNode::get(Context, {});
412 MDNode *DisableUnroll = MDNode::get(
413 Context, {MDString::get(Context, "llvm.loop.unroll.disable")});
414 Metadata *FalseVal =
415 ConstantAsMetadata::get(ConstantInt::get(Type::getInt1Ty(Context), 0));
416 MDNode *DisableVectorize = MDNode::get(
417 Context,
418 {MDString::get(Context, "llvm.loop.vectorize.enable"), FalseVal});
419 MDNode *DisableLICMVersioning = MDNode::get(
420 Context, {MDString::get(Context, "llvm.loop.licm_versioning.disable")});
421 MDNode *DisableDistribution= MDNode::get(
422 Context,
423 {MDString::get(Context, "llvm.loop.distribute.enable"), FalseVal});
424 MDNode *NewLoopID =
425 MDNode::get(Context, {Dummy, DisableUnroll, DisableVectorize,
426 DisableLICMVersioning, DisableDistribution});
427 // Set operand 0 to refer to the loop id itself.
428 NewLoopID->replaceOperandWith(0, NewLoopID);
429 L.setLoopID(NewLoopID);
430}
431
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000432namespace {
433
Sanjoy Dase75ed922015-02-26 08:19:31 +0000434// Keeps track of the structure of a loop. This is similar to llvm::Loop,
435// except that it is more lightweight and can track the state of a loop through
436// changing and potentially invalid IR. This structure also formalizes the
437// kinds of loops we can deal with -- ones that have a single latch that is also
438// an exiting block *and* have a canonical induction variable.
439struct LoopStructure {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000440 const char *Tag = "";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000441
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000442 BasicBlock *Header = nullptr;
443 BasicBlock *Latch = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000444
445 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
446 // successor is `LatchExit', the exit block of the loop.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000447 BranchInst *LatchBr = nullptr;
448 BasicBlock *LatchExit = nullptr;
449 unsigned LatchBrExitIdx = std::numeric_limits<unsigned>::max();
Sanjoy Dase75ed922015-02-26 08:19:31 +0000450
Sanjoy Dasec892132017-02-07 23:59:07 +0000451 // The loop represented by this instance of LoopStructure is semantically
452 // equivalent to:
453 //
454 // intN_ty inc = IndVarIncreasing ? 1 : -1;
Serguei Katkov675e3042017-09-21 04:50:41 +0000455 // pred_ty predicate = IndVarIncreasing ? ICMP_SLT : ICMP_SGT;
Sanjoy Dasec892132017-02-07 23:59:07 +0000456 //
Serguei Katkov675e3042017-09-21 04:50:41 +0000457 // for (intN_ty iv = IndVarStart; predicate(iv, LoopExitAt); iv = IndVarBase)
Sanjoy Dasec892132017-02-07 23:59:07 +0000458 // ... body ...
459
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000460 Value *IndVarBase = nullptr;
461 Value *IndVarStart = nullptr;
462 Value *IndVarStep = nullptr;
463 Value *LoopExitAt = nullptr;
464 bool IndVarIncreasing = false;
465 bool IsSignedPredicate = true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000466
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000467 LoopStructure() = default;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000468
469 template <typename M> LoopStructure map(M Map) const {
470 LoopStructure Result;
471 Result.Tag = Tag;
472 Result.Header = cast<BasicBlock>(Map(Header));
473 Result.Latch = cast<BasicBlock>(Map(Latch));
474 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
475 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
476 Result.LatchBrExitIdx = LatchBrExitIdx;
Max Kazantseva22742b2017-08-31 05:58:15 +0000477 Result.IndVarBase = Map(IndVarBase);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000478 Result.IndVarStart = Map(IndVarStart);
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000479 Result.IndVarStep = Map(IndVarStep);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000480 Result.LoopExitAt = Map(LoopExitAt);
481 Result.IndVarIncreasing = IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000482 Result.IsSignedPredicate = IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000483 return Result;
484 }
485
Sanjoy Dase91665d2015-02-26 08:56:04 +0000486 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
Fedor Sergeev194a4072018-03-15 11:01:19 +0000487 BranchProbabilityInfo *BPI,
488 Loop &, const char *&);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000489};
490
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000491/// This class is used to constrain loops to run within a given iteration space.
492/// The algorithm this class implements is given a Loop and a range [Begin,
493/// End). The algorithm then tries to break out a "main loop" out of the loop
494/// it is given in a way that the "main loop" runs with the induction variable
495/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
496/// loops to run any remaining iterations. The pre loop runs any iterations in
497/// which the induction variable is < Begin, and the post loop runs any
498/// iterations in which the induction variable is >= End.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000499class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000500 // The representation of a clone of the original loop we started out with.
501 struct ClonedLoop {
502 // The cloned blocks
503 std::vector<BasicBlock *> Blocks;
504
505 // `Map` maps values in the clonee into values in the cloned version
506 ValueToValueMapTy Map;
507
508 // An instance of `LoopStructure` for the cloned loop
509 LoopStructure Structure;
510 };
511
512 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
513 // more details on what these fields mean.
514 struct RewrittenRangeInfo {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000515 BasicBlock *PseudoExit = nullptr;
516 BasicBlock *ExitSelector = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000517 std::vector<PHINode *> PHIValuesAtPseudoExit;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000518 PHINode *IndVarEnd = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000519
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000520 RewrittenRangeInfo() = default;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000521 };
522
523 // Calculated subranges we restrict the iteration space of the main loop to.
524 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000525 // these fields are computed. `LowLimit` is None if there is no restriction
526 // on low end of the restricted iteration space of the main loop. `HighLimit`
527 // is None if there is no restriction on high end of the restricted iteration
528 // space of the main loop.
529
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000530 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000531 Optional<const SCEV *> LowLimit;
532 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000533 };
534
535 // A utility function that does a `replaceUsesOfWith' on the incoming block
536 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
537 // incoming block list with `ReplaceBy'.
538 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
539 BasicBlock *ReplaceBy);
540
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000541 // Compute a safe set of limits for the main loop to run in -- effectively the
542 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000543 // Return None if unable to compute the set of subranges.
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000544 Optional<SubRanges> calculateSubRanges(bool IsSignedPredicate) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000545
546 // Clone `OriginalLoop' and return the result in CLResult. The IR after
547 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
548 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
549 // but there is no such edge.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000550 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
551
Sanjoy Das21434472016-08-14 01:04:46 +0000552 // Create the appropriate loop structure needed to describe a cloned copy of
553 // `Original`. The clone is described by `VM`.
554 Loop *createClonedLoopStructure(Loop *Original, Loop *Parent,
Fedor Sergeev194a4072018-03-15 11:01:19 +0000555 ValueToValueMapTy &VM, bool IsSubloop);
Sanjoy Das21434472016-08-14 01:04:46 +0000556
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000557 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
558 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
559 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
560 // `OriginalHeaderCount'.
561 //
562 // If there are iterations left to execute, control is made to jump to
563 // `ContinuationBlock', otherwise they take the normal loop exit. The
564 // returned `RewrittenRangeInfo' object is populated as follows:
565 //
566 // .PseudoExit is a basic block that unconditionally branches to
567 // `ContinuationBlock'.
568 //
569 // .ExitSelector is a basic block that decides, on exit from the loop,
570 // whether to branch to the "true" exit or to `PseudoExit'.
571 //
572 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
573 // for each PHINode in the loop header on taking the pseudo exit.
574 //
575 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
576 // preheader because it is made to branch to the loop header only
577 // conditionally.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000578 RewrittenRangeInfo
579 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
580 Value *ExitLoopAt,
581 BasicBlock *ContinuationBlock) const;
582
583 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
584 // function creates a new preheader for `LS' and returns it.
Sanjoy Dase75ed922015-02-26 08:19:31 +0000585 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
586 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000587
588 // `ContinuationBlockAndPreheader' was the continuation block for some call to
589 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
590 // This function rewrites the PHI nodes in `LS.Header' to start with the
591 // correct value.
592 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000593 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000594 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
595
596 // Even though we do not preserve any passes at this time, we at least need to
597 // keep the parent loop structure consistent. The `LPPassManager' seems to
598 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000599 // blocks denoted by BBs to this loops parent loop if required.
600 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000601
602 // Some global state.
603 Function &F;
604 LLVMContext &Ctx;
605 ScalarEvolution &SE;
Sanjoy Dasf45e03e2016-08-02 19:31:54 +0000606 DominatorTree &DT;
Sanjoy Das35459f02016-08-14 01:04:50 +0000607 LoopInfo &LI;
Fedor Sergeev194a4072018-03-15 11:01:19 +0000608 function_ref<void(Loop *, bool)> LPMAddNewLoop;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000609
610 // Information about the original loop we started out with.
611 Loop &OriginalLoop;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000612
613 const SCEV *LatchTakenCount = nullptr;
614 BasicBlock *OriginalPreheader = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000615
616 // The preheader of the main loop. This may or may not be different from
617 // `OriginalPreheader'.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000618 BasicBlock *MainLoopPreheader = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000619
620 // The range we need to run the main loop in.
621 InductiveRangeCheck::Range Range;
622
623 // The structure of the main loop (see comment at the beginning of this class
624 // for a definition)
625 LoopStructure MainLoopStructure;
626
627public:
Fedor Sergeev194a4072018-03-15 11:01:19 +0000628 LoopConstrainer(Loop &L, LoopInfo &LI,
629 function_ref<void(Loop *, bool)> LPMAddNewLoop,
Sanjoy Das21434472016-08-14 01:04:46 +0000630 const LoopStructure &LS, ScalarEvolution &SE,
631 DominatorTree &DT, InductiveRangeCheck::Range R)
Sanjoy Dase75ed922015-02-26 08:19:31 +0000632 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
Fedor Sergeev194a4072018-03-15 11:01:19 +0000633 SE(SE), DT(DT), LI(LI), LPMAddNewLoop(LPMAddNewLoop), OriginalLoop(L),
634 Range(R), MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000635
636 // Entry point for the algorithm. Returns true on success.
637 bool run();
638};
639
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000640} // end anonymous namespace
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000641
642void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
643 BasicBlock *ReplaceBy) {
644 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
645 if (PN->getIncomingBlock(i) == Block)
646 PN->setIncomingBlock(i, ReplaceBy);
647}
648
Sam Parker90b7f4f2018-03-27 08:24:53 +0000649/// Given a loop with an deccreasing induction variable, is it possible to
650/// safely calculate the bounds of a new loop using the given Predicate.
651static bool isSafeDecreasingBound(const SCEV *Start,
652 const SCEV *BoundSCEV, const SCEV *Step,
653 ICmpInst::Predicate Pred,
654 unsigned LatchBrExitIdx,
655 Loop *L, ScalarEvolution &SE) {
656 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_SGT &&
657 Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_UGT)
658 return false;
659
660 if (!SE.isAvailableAtLoopEntry(BoundSCEV, L))
661 return false;
662
663 assert(SE.isKnownNegative(Step) && "expecting negative step");
664
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000665 LLVM_DEBUG(dbgs() << "irce: isSafeDecreasingBound with:\n");
666 LLVM_DEBUG(dbgs() << "irce: Start: " << *Start << "\n");
667 LLVM_DEBUG(dbgs() << "irce: Step: " << *Step << "\n");
668 LLVM_DEBUG(dbgs() << "irce: BoundSCEV: " << *BoundSCEV << "\n");
669 LLVM_DEBUG(dbgs() << "irce: Pred: " << ICmpInst::getPredicateName(Pred)
670 << "\n");
671 LLVM_DEBUG(dbgs() << "irce: LatchExitBrIdx: " << LatchBrExitIdx << "\n");
Sam Parker90b7f4f2018-03-27 08:24:53 +0000672
673 bool IsSigned = ICmpInst::isSigned(Pred);
674 // The predicate that we need to check that the induction variable lies
675 // within bounds.
676 ICmpInst::Predicate BoundPred =
677 IsSigned ? CmpInst::ICMP_SGT : CmpInst::ICMP_UGT;
678
679 if (LatchBrExitIdx == 1)
680 return SE.isLoopEntryGuardedByCond(L, BoundPred, Start, BoundSCEV);
681
682 assert(LatchBrExitIdx == 0 &&
683 "LatchBrExitIdx should be either 0 or 1");
Fangrui Songf78650a2018-07-30 19:41:25 +0000684
Sam Parker90b7f4f2018-03-27 08:24:53 +0000685 const SCEV *StepPlusOne = SE.getAddExpr(Step, SE.getOne(Step->getType()));
686 unsigned BitWidth = cast<IntegerType>(BoundSCEV->getType())->getBitWidth();
687 APInt Min = IsSigned ? APInt::getSignedMinValue(BitWidth) :
688 APInt::getMinValue(BitWidth);
689 const SCEV *Limit = SE.getMinusSCEV(SE.getConstant(Min), StepPlusOne);
690
691 const SCEV *MinusOne =
692 SE.getMinusSCEV(BoundSCEV, SE.getOne(BoundSCEV->getType()));
693
694 return SE.isLoopEntryGuardedByCond(L, BoundPred, Start, MinusOne) &&
695 SE.isLoopEntryGuardedByCond(L, BoundPred, BoundSCEV, Limit);
696
Sanjoy Dase75ed922015-02-26 08:19:31 +0000697}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000698
Sam Parker53a423a2018-03-26 09:29:42 +0000699/// Given a loop with an increasing induction variable, is it possible to
700/// safely calculate the bounds of a new loop using the given Predicate.
701static bool isSafeIncreasingBound(const SCEV *Start,
702 const SCEV *BoundSCEV, const SCEV *Step,
703 ICmpInst::Predicate Pred,
704 unsigned LatchBrExitIdx,
705 Loop *L, ScalarEvolution &SE) {
706 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_SGT &&
707 Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_UGT)
708 return false;
709
710 if (!SE.isAvailableAtLoopEntry(BoundSCEV, L))
711 return false;
712
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000713 LLVM_DEBUG(dbgs() << "irce: isSafeIncreasingBound with:\n");
714 LLVM_DEBUG(dbgs() << "irce: Start: " << *Start << "\n");
715 LLVM_DEBUG(dbgs() << "irce: Step: " << *Step << "\n");
716 LLVM_DEBUG(dbgs() << "irce: BoundSCEV: " << *BoundSCEV << "\n");
717 LLVM_DEBUG(dbgs() << "irce: Pred: " << ICmpInst::getPredicateName(Pred)
718 << "\n");
719 LLVM_DEBUG(dbgs() << "irce: LatchExitBrIdx: " << LatchBrExitIdx << "\n");
Sam Parker53a423a2018-03-26 09:29:42 +0000720
721 bool IsSigned = ICmpInst::isSigned(Pred);
722 // The predicate that we need to check that the induction variable lies
723 // within bounds.
724 ICmpInst::Predicate BoundPred =
725 IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
726
727 if (LatchBrExitIdx == 1)
728 return SE.isLoopEntryGuardedByCond(L, BoundPred, Start, BoundSCEV);
729
730 assert(LatchBrExitIdx == 0 && "LatchBrExitIdx should be 0 or 1");
731
732 const SCEV *StepMinusOne =
733 SE.getMinusSCEV(Step, SE.getOne(Step->getType()));
734 unsigned BitWidth = cast<IntegerType>(BoundSCEV->getType())->getBitWidth();
Fangrui Songf78650a2018-07-30 19:41:25 +0000735 APInt Max = IsSigned ? APInt::getSignedMaxValue(BitWidth) :
Sam Parker53a423a2018-03-26 09:29:42 +0000736 APInt::getMaxValue(BitWidth);
737 const SCEV *Limit = SE.getMinusSCEV(SE.getConstant(Max), StepMinusOne);
738
739 return (SE.isLoopEntryGuardedByCond(L, BoundPred, Start,
740 SE.getAddExpr(BoundSCEV, Step)) &&
741 SE.isLoopEntryGuardedByCond(L, BoundPred, BoundSCEV, Limit));
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000742}
743
Sanjoy Dase75ed922015-02-26 08:19:31 +0000744Optional<LoopStructure>
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000745LoopStructure::parseLoopStructure(ScalarEvolution &SE,
Fedor Sergeev194a4072018-03-15 11:01:19 +0000746 BranchProbabilityInfo *BPI, Loop &L,
747 const char *&FailureReason) {
Sanjoy Das43fdc542016-08-14 01:04:31 +0000748 if (!L.isLoopSimplifyForm()) {
749 FailureReason = "loop not in LoopSimplify form";
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000750 return None;
Sanjoy Das43fdc542016-08-14 01:04:31 +0000751 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000752
753 BasicBlock *Latch = L.getLoopLatch();
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000754 assert(Latch && "Simplified loops only have one latch!");
755
Sanjoy Das7a18a232016-08-14 01:04:36 +0000756 if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) {
757 FailureReason = "loop has already been cloned";
758 return None;
759 }
760
Sanjoy Dase75ed922015-02-26 08:19:31 +0000761 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000762 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000763 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000764 }
765
Sanjoy Dase75ed922015-02-26 08:19:31 +0000766 BasicBlock *Header = L.getHeader();
767 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000768 if (!Preheader) {
769 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000770 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000771 }
772
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000773 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000774 if (!LatchBr || LatchBr->isUnconditional()) {
775 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000776 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000777 }
778
Sanjoy Dase75ed922015-02-26 08:19:31 +0000779 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000780
Sanjoy Dase91665d2015-02-26 08:56:04 +0000781 BranchProbability ExitProbability =
Fedor Sergeev194a4072018-03-15 11:01:19 +0000782 BPI ? BPI->getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx)
783 : BranchProbability::getZero();
Sanjoy Dase91665d2015-02-26 08:56:04 +0000784
Sanjoy Dasbb969792016-07-22 00:40:56 +0000785 if (!SkipProfitabilityChecks &&
786 ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
Sanjoy Dase91665d2015-02-26 08:56:04 +0000787 FailureReason = "short running loop, not profitable";
788 return None;
789 }
790
Sanjoy Dase75ed922015-02-26 08:19:31 +0000791 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
792 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
793 FailureReason = "latch terminator branch not conditional on integral icmp";
794 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000795 }
796
Sanjoy Dase75ed922015-02-26 08:19:31 +0000797 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
798 if (isa<SCEVCouldNotCompute>(LatchCount)) {
799 FailureReason = "could not compute latch count";
800 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000801 }
802
Sanjoy Dase75ed922015-02-26 08:19:31 +0000803 ICmpInst::Predicate Pred = ICI->getPredicate();
804 Value *LeftValue = ICI->getOperand(0);
805 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
806 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
807
808 Value *RightValue = ICI->getOperand(1);
809 const SCEV *RightSCEV = SE.getSCEV(RightValue);
810
811 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
812 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
813 if (isa<SCEVAddRecExpr>(RightSCEV)) {
814 std::swap(LeftSCEV, RightSCEV);
815 std::swap(LeftValue, RightValue);
816 Pred = ICmpInst::getSwappedPredicate(Pred);
817 } else {
818 FailureReason = "no add recurrences in the icmp";
819 return None;
820 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000821 }
822
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000823 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
824 if (AR->getNoWrapFlags(SCEV::FlagNSW))
825 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000826
827 IntegerType *Ty = cast<IntegerType>(AR->getType());
828 IntegerType *WideTy =
829 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
830
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000831 const SCEVAddRecExpr *ExtendAfterOp =
832 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
833 if (ExtendAfterOp) {
834 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
835 const SCEV *ExtendedStep =
836 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
837
838 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
839 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
840
841 if (NoSignedWrap)
842 return true;
843 }
844
845 // We may have proved this when computing the sign extension above.
846 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
847 };
848
Serguei Katkov675e3042017-09-21 04:50:41 +0000849 // `ICI` is interpreted as taking the backedge if the *next* value of the
850 // induction variable satisfies some constraint.
Sanjoy Dase75ed922015-02-26 08:19:31 +0000851
Max Kazantseva22742b2017-08-31 05:58:15 +0000852 const SCEVAddRecExpr *IndVarBase = cast<SCEVAddRecExpr>(LeftSCEV);
Sam Parker3c190512018-04-18 13:50:28 +0000853 if (!IndVarBase->isAffine()) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000854 FailureReason = "LHS in icmp not induction variable";
855 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000856 }
Sam Parker3c190512018-04-18 13:50:28 +0000857 const SCEV* StepRec = IndVarBase->getStepRecurrence(SE);
Max Kazantsev786032c2018-05-04 07:34:35 +0000858 if (!isa<SCEVConstant>(StepRec)) {
Sam Parker3c190512018-04-18 13:50:28 +0000859 FailureReason = "LHS in icmp not induction variable";
860 return None;
861 }
Max Kazantsev786032c2018-05-04 07:34:35 +0000862 ConstantInt *StepCI = cast<SCEVConstant>(StepRec)->getValue();
863
Sam Parker3c190512018-04-18 13:50:28 +0000864 if (ICI->isEquality() && !HasNoSignedWrap(IndVarBase)) {
865 FailureReason = "LHS in icmp needs nsw for equality predicates";
866 return None;
867 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000868
Sam Parker3c190512018-04-18 13:50:28 +0000869 assert(!StepCI->isZero() && "Zero step?");
870 bool IsIncreasing = !StepCI->isNegative();
871 bool IsSignedPredicate = ICmpInst::isSigned(Pred);
Serguei Katkov675e3042017-09-21 04:50:41 +0000872 const SCEV *StartNext = IndVarBase->getStart();
873 const SCEV *Addend = SE.getNegativeSCEV(IndVarBase->getStepRecurrence(SE));
874 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000875 const SCEV *Step = SE.getSCEV(StepCI);
Sanjoy Dasec892132017-02-07 23:59:07 +0000876
Sanjoy Dase75ed922015-02-26 08:19:31 +0000877 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000878 if (IsIncreasing) {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000879 bool DecreasedRightValueByOne = false;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000880 if (StepCI->isOne()) {
881 // Try to turn eq/ne predicates to those we can work with.
882 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
883 // while (++i != len) { while (++i < len) {
884 // ... ---> ...
885 // } }
886 // If both parts are known non-negative, it is profitable to use
887 // unsigned comparison in increasing loop. This allows us to make the
888 // comparison check against "RightSCEV + 1" more optimistic.
Sam Parker97375352018-04-12 12:49:40 +0000889 if (isKnownNonNegativeInLoop(IndVarStart, &L, SE) &&
890 isKnownNonNegativeInLoop(RightSCEV, &L, SE))
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000891 Pred = ICmpInst::ICMP_ULT;
892 else
893 Pred = ICmpInst::ICMP_SLT;
Sam Parker53a423a2018-03-26 09:29:42 +0000894 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000895 // while (true) { while (true) {
896 // if (++i == len) ---> if (++i > len - 1)
897 // break; break;
898 // ... ...
899 // } }
Sam Parker53a423a2018-03-26 09:29:42 +0000900 if (IndVarBase->getNoWrapFlags(SCEV::FlagNUW) &&
Max Kazantseva78dc4d2019-01-15 09:51:34 +0000901 cannotBeMinInLoop(RightSCEV, &L, SE, /*Signed*/false)) {
Sam Parker53a423a2018-03-26 09:29:42 +0000902 Pred = ICmpInst::ICMP_UGT;
903 RightSCEV = SE.getMinusSCEV(RightSCEV,
904 SE.getOne(RightSCEV->getType()));
905 DecreasedRightValueByOne = true;
Max Kazantseva78dc4d2019-01-15 09:51:34 +0000906 } else if (cannotBeMinInLoop(RightSCEV, &L, SE, /*Signed*/true)) {
Sam Parker53a423a2018-03-26 09:29:42 +0000907 Pred = ICmpInst::ICMP_SGT;
908 RightSCEV = SE.getMinusSCEV(RightSCEV,
909 SE.getOne(RightSCEV->getType()));
910 DecreasedRightValueByOne = true;
911 }
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000912 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000913 }
914
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000915 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
916 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000917 bool FoundExpectedPred =
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000918 (LTPred && LatchBrExitIdx == 1) || (GTPred && LatchBrExitIdx == 0);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000919
920 if (!FoundExpectedPred) {
921 FailureReason = "expected icmp slt semantically, found something else";
922 return None;
923 }
924
Sam Parker53a423a2018-03-26 09:29:42 +0000925 IsSignedPredicate = ICmpInst::isSigned(Pred);
Max Kazantsev8aacef62017-10-04 06:53:22 +0000926 if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
927 FailureReason = "unsigned latch conditions are explicitly prohibited";
928 return None;
929 }
930
Sam Parker53a423a2018-03-26 09:29:42 +0000931 if (!isSafeIncreasingBound(IndVarStart, RightSCEV, Step, Pred,
932 LatchBrExitIdx, &L, SE)) {
933 FailureReason = "Unsafe loop bounds";
934 return None;
935 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000936 if (LatchBrExitIdx == 0) {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000937 // We need to increase the right value unless we have already decreased
938 // it virtually when we replaced EQ with SGT.
939 if (!DecreasedRightValueByOne) {
940 IRBuilder<> B(Preheader->getTerminator());
941 RightValue = B.CreateAdd(RightValue, One);
942 }
Sanjoy Dasec892132017-02-07 23:59:07 +0000943 } else {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000944 assert(!DecreasedRightValueByOne &&
945 "Right value can be decreased only for LatchBrExitIdx == 0!");
Sanjoy Dase75ed922015-02-26 08:19:31 +0000946 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000947 } else {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000948 bool IncreasedRightValueByOne = false;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000949 if (StepCI->isMinusOne()) {
950 // Try to turn eq/ne predicates to those we can work with.
951 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
952 // while (--i != len) { while (--i > len) {
953 // ... ---> ...
954 // } }
955 // We intentionally don't turn the predicate into UGT even if we know
956 // that both operands are non-negative, because it will only pessimize
957 // our check against "RightSCEV - 1".
958 Pred = ICmpInst::ICMP_SGT;
Sam Parker90b7f4f2018-03-27 08:24:53 +0000959 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000960 // while (true) { while (true) {
961 // if (--i == len) ---> if (--i < len + 1)
962 // break; break;
963 // ... ...
964 // } }
Sam Parker90b7f4f2018-03-27 08:24:53 +0000965 if (IndVarBase->getNoWrapFlags(SCEV::FlagNUW) &&
Max Kazantseva78dc4d2019-01-15 09:51:34 +0000966 cannotBeMaxInLoop(RightSCEV, &L, SE, /* Signed */ false)) {
Sam Parker90b7f4f2018-03-27 08:24:53 +0000967 Pred = ICmpInst::ICMP_ULT;
968 RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
969 IncreasedRightValueByOne = true;
Max Kazantseva78dc4d2019-01-15 09:51:34 +0000970 } else if (cannotBeMaxInLoop(RightSCEV, &L, SE, /* Signed */ true)) {
Sam Parker90b7f4f2018-03-27 08:24:53 +0000971 Pred = ICmpInst::ICMP_SLT;
972 RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
973 IncreasedRightValueByOne = true;
974 }
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000975 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000976 }
977
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000978 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
979 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
980
Sanjoy Dase75ed922015-02-26 08:19:31 +0000981 bool FoundExpectedPred =
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000982 (GTPred && LatchBrExitIdx == 1) || (LTPred && LatchBrExitIdx == 0);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000983
984 if (!FoundExpectedPred) {
985 FailureReason = "expected icmp sgt semantically, found something else";
986 return None;
987 }
988
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000989 IsSignedPredicate =
990 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
Max Kazantsev8aacef62017-10-04 06:53:22 +0000991
Max Kazantsev8aacef62017-10-04 06:53:22 +0000992 if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
993 FailureReason = "unsigned latch conditions are explicitly prohibited";
994 return None;
995 }
996
Sam Parker90b7f4f2018-03-27 08:24:53 +0000997 if (!isSafeDecreasingBound(IndVarStart, RightSCEV, Step, Pred,
998 LatchBrExitIdx, &L, SE)) {
999 FailureReason = "Unsafe bounds";
1000 return None;
1001 }
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001002
Sanjoy Dase75ed922015-02-26 08:19:31 +00001003 if (LatchBrExitIdx == 0) {
Max Kazantsev2c627a92017-07-18 04:53:48 +00001004 // We need to decrease the right value unless we have already increased
1005 // it virtually when we replaced EQ with SLT.
1006 if (!IncreasedRightValueByOne) {
1007 IRBuilder<> B(Preheader->getTerminator());
1008 RightValue = B.CreateSub(RightValue, One);
1009 }
Sanjoy Dasec892132017-02-07 23:59:07 +00001010 } else {
Max Kazantsev2c627a92017-07-18 04:53:48 +00001011 assert(!IncreasedRightValueByOne &&
1012 "Right value can be increased only for LatchBrExitIdx == 0!");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001013 }
1014 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001015 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
1016
Sanjoy Dase75ed922015-02-26 08:19:31 +00001017 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001018 ScalarEvolution::LoopInvariant &&
1019 "loop variant exit count doesn't make sense!");
1020
Sanjoy Dase75ed922015-02-26 08:19:31 +00001021 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001022 const DataLayout &DL = Preheader->getModule()->getDataLayout();
1023 Value *IndVarStartV =
1024 SCEVExpander(SE, DL, "irce")
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001025 .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001026 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001027
Sanjoy Dase75ed922015-02-26 08:19:31 +00001028 LoopStructure Result;
1029
1030 Result.Tag = "main";
1031 Result.Header = Header;
1032 Result.Latch = Latch;
1033 Result.LatchBr = LatchBr;
1034 Result.LatchExit = LatchExit;
1035 Result.LatchBrExitIdx = LatchBrExitIdx;
1036 Result.IndVarStart = IndVarStartV;
Max Kazantsev2f6ae282017-08-04 07:01:04 +00001037 Result.IndVarStep = StepCI;
Max Kazantseva22742b2017-08-31 05:58:15 +00001038 Result.IndVarBase = LeftValue;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001039 Result.IndVarIncreasing = IsIncreasing;
1040 Result.LoopExitAt = RightValue;
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001041 Result.IsSignedPredicate = IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001042
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001043 FailureReason = nullptr;
1044
Sanjoy Dase75ed922015-02-26 08:19:31 +00001045 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001046}
1047
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001048Optional<LoopConstrainer::SubRanges>
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001049LoopConstrainer::calculateSubRanges(bool IsSignedPredicate) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001050 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
1051
Sanjoy Das351db052015-01-22 09:32:02 +00001052 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001053 return None;
1054
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001055 LoopConstrainer::SubRanges Result;
1056
1057 // I think we can be more aggressive here and make this nuw / nsw if the
1058 // addition that feeds into the icmp for the latch's terminating branch is nuw
1059 // / nsw. In any case, a wrapping 2's complement addition is safe.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001060 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
1061 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001062
Sanjoy Dase75ed922015-02-26 08:19:31 +00001063 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001064
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001065 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest), or
1066 // [Smallest, GreatestSeen] is the range of values the induction variable
1067 // takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001068
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001069 const SCEV *Smallest = nullptr, *Greatest = nullptr, *GreatestSeen = nullptr;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001070
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001071 const SCEV *One = SE.getOne(Ty);
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001072 if (Increasing) {
1073 Smallest = Start;
1074 Greatest = End;
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001075 // No overflow, because the range [Smallest, GreatestSeen] is not empty.
1076 GreatestSeen = SE.getMinusSCEV(End, One);
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001077 } else {
1078 // These two computations may sign-overflow. Here is why that is okay:
1079 //
1080 // We know that the induction variable does not sign-overflow on any
1081 // iteration except the last one, and it starts at `Start` and ends at
1082 // `End`, decrementing by one every time.
1083 //
1084 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
1085 // induction variable is decreasing we know that that the smallest value
1086 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
1087 //
1088 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
1089 // that case, `Clamp` will always return `Smallest` and
1090 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
1091 // will be an empty range. Returning an empty range is always safe.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001092
Max Kazantsev6c466a32017-06-28 04:57:45 +00001093 Smallest = SE.getAddExpr(End, One);
1094 Greatest = SE.getAddExpr(Start, One);
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001095 GreatestSeen = Start;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001096 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001097
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001098 auto Clamp = [this, Smallest, Greatest, IsSignedPredicate](const SCEV *S) {
Max Kazantsev6f5229d72017-11-01 13:21:56 +00001099 return IsSignedPredicate
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001100 ? SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S))
1101 : SE.getUMaxExpr(Smallest, SE.getUMinExpr(Greatest, S));
Sanjoy Dase75ed922015-02-26 08:19:31 +00001102 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001103
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001104 // In some cases we can prove that we don't need a pre or post loop.
1105 ICmpInst::Predicate PredLE =
1106 IsSignedPredicate ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1107 ICmpInst::Predicate PredLT =
1108 IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001109
1110 bool ProvablyNoPreloop =
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001111 SE.isKnownPredicate(PredLE, Range.getBegin(), Smallest);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001112 if (!ProvablyNoPreloop)
1113 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001114
1115 bool ProvablyNoPostLoop =
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001116 SE.isKnownPredicate(PredLT, GreatestSeen, Range.getEnd());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001117 if (!ProvablyNoPostLoop)
1118 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001119
1120 return Result;
1121}
1122
1123void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
1124 const char *Tag) const {
1125 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
1126 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
1127 Result.Blocks.push_back(Clone);
1128 Result.Map[BB] = Clone;
1129 }
1130
1131 auto GetClonedValue = [&Result](Value *V) {
1132 assert(V && "null values not in domain!");
1133 auto It = Result.Map.find(V);
1134 if (It == Result.Map.end())
1135 return V;
1136 return static_cast<Value *>(It->second);
1137 };
1138
Sanjoy Das7a18a232016-08-14 01:04:36 +00001139 auto *ClonedLatch =
1140 cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch()));
1141 ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag,
1142 MDNode::get(Ctx, {}));
1143
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001144 Result.Structure = MainLoopStructure.map(GetClonedValue);
1145 Result.Structure.Tag = Tag;
1146
1147 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
1148 BasicBlock *ClonedBB = Result.Blocks[i];
1149 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
1150
1151 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
1152
1153 for (Instruction &I : *ClonedBB)
1154 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00001155 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001156
1157 // Exit blocks will now have one more predecessor and their PHI nodes need
1158 // to be edited to reflect that. No phi nodes need to be introduced because
1159 // the loop is in LCSSA.
1160
Sanjoy Dasd1d62a12016-08-13 22:00:09 +00001161 for (auto *SBB : successors(OriginalBB)) {
1162 if (OriginalLoop.contains(SBB))
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001163 continue; // not an exit block
1164
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001165 for (PHINode &PN : SBB->phis()) {
1166 Value *OldIncoming = PN.getIncomingValueForBlock(OriginalBB);
1167 PN.addIncoming(GetClonedValue(OldIncoming), ClonedBB);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001168 }
1169 }
1170 }
1171}
1172
1173LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001174 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001175 BasicBlock *ContinuationBlock) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001176 // We start with a loop with a single latch:
1177 //
1178 // +--------------------+
1179 // | |
1180 // | preheader |
1181 // | |
1182 // +--------+-----------+
1183 // | ----------------\
1184 // | / |
1185 // +--------v----v------+ |
1186 // | | |
1187 // | header | |
1188 // | | |
1189 // +--------------------+ |
1190 // |
1191 // ..... |
1192 // |
1193 // +--------------------+ |
1194 // | | |
1195 // | latch >----------/
1196 // | |
1197 // +-------v------------+
1198 // |
1199 // |
1200 // | +--------------------+
1201 // | | |
1202 // +---> original exit |
1203 // | |
1204 // +--------------------+
1205 //
1206 // We change the control flow to look like
1207 //
1208 //
1209 // +--------------------+
1210 // | |
1211 // | preheader >-------------------------+
1212 // | | |
1213 // +--------v-----------+ |
1214 // | /-------------+ |
1215 // | / | |
1216 // +--------v--v--------+ | |
1217 // | | | |
1218 // | header | | +--------+ |
1219 // | | | | | |
1220 // +--------------------+ | | +-----v-----v-----------+
1221 // | | | |
1222 // | | | .pseudo.exit |
1223 // | | | |
1224 // | | +-----------v-----------+
1225 // | | |
1226 // ..... | | |
1227 // | | +--------v-------------+
1228 // +--------------------+ | | | |
1229 // | | | | | ContinuationBlock |
1230 // | latch >------+ | | |
1231 // | | | +----------------------+
1232 // +---------v----------+ |
1233 // | |
1234 // | |
1235 // | +---------------^-----+
1236 // | | |
1237 // +-----> .exit.selector |
1238 // | |
1239 // +----------v----------+
1240 // |
1241 // +--------------------+ |
1242 // | | |
1243 // | original exit <----+
1244 // | |
1245 // +--------------------+
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001246
1247 RewrittenRangeInfo RRI;
1248
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001249 BasicBlock *BBInsertLocation = LS.Latch->getNextNode();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001250 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001251 &F, BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001252 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001253 BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001254
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001255 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001256 bool Increasing = LS.IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001257 bool IsSignedPredicate = LS.IsSignedPredicate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001258
1259 IRBuilder<> B(PreheaderJump);
1260
1261 // EnterLoopCond - is it okay to start executing this `LS'?
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001262 Value *EnterLoopCond = nullptr;
1263 if (Increasing)
1264 EnterLoopCond = IsSignedPredicate
1265 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1266 : B.CreateICmpULT(LS.IndVarStart, ExitSubloopAt);
1267 else
1268 EnterLoopCond = IsSignedPredicate
1269 ? B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt)
1270 : B.CreateICmpUGT(LS.IndVarStart, ExitSubloopAt);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001271
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001272 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1273 PreheaderJump->eraseFromParent();
1274
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001275 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001276 B.SetInsertPoint(LS.LatchBr);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001277 Value *TakeBackedgeLoopCond = nullptr;
1278 if (Increasing)
1279 TakeBackedgeLoopCond = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001280 ? B.CreateICmpSLT(LS.IndVarBase, ExitSubloopAt)
1281 : B.CreateICmpULT(LS.IndVarBase, ExitSubloopAt);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001282 else
1283 TakeBackedgeLoopCond = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001284 ? B.CreateICmpSGT(LS.IndVarBase, ExitSubloopAt)
1285 : B.CreateICmpUGT(LS.IndVarBase, ExitSubloopAt);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001286 Value *CondForBranch = LS.LatchBrExitIdx == 1
1287 ? TakeBackedgeLoopCond
1288 : B.CreateNot(TakeBackedgeLoopCond);
1289
1290 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001291
1292 B.SetInsertPoint(RRI.ExitSelector);
1293
1294 // IterationsLeft - are there any more iterations left, given the original
1295 // upper bound on the induction variable? If not, we branch to the "real"
1296 // exit.
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001297 Value *IterationsLeft = nullptr;
1298 if (Increasing)
1299 IterationsLeft = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001300 ? B.CreateICmpSLT(LS.IndVarBase, LS.LoopExitAt)
1301 : B.CreateICmpULT(LS.IndVarBase, LS.LoopExitAt);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001302 else
1303 IterationsLeft = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001304 ? B.CreateICmpSGT(LS.IndVarBase, LS.LoopExitAt)
1305 : B.CreateICmpUGT(LS.IndVarBase, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001306 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1307
1308 BranchInst *BranchToContinuation =
1309 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1310
1311 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1312 // each of the PHI nodes in the loop header. This feeds into the initial
1313 // value of the same PHI nodes if/when we continue execution.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001314 for (PHINode &PN : LS.Header->phis()) {
1315 PHINode *NewPHI = PHINode::Create(PN.getType(), 2, PN.getName() + ".copy",
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001316 BranchToContinuation);
1317
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001318 NewPHI->addIncoming(PN.getIncomingValueForBlock(Preheader), Preheader);
1319 NewPHI->addIncoming(PN.getIncomingValueForBlock(LS.Latch),
Serguei Katkov675e3042017-09-21 04:50:41 +00001320 RRI.ExitSelector);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001321 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1322 }
1323
Max Kazantseva22742b2017-08-31 05:58:15 +00001324 RRI.IndVarEnd = PHINode::Create(LS.IndVarBase->getType(), 2, "indvar.end",
Sanjoy Dase75ed922015-02-26 08:19:31 +00001325 BranchToContinuation);
1326 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
Max Kazantseva22742b2017-08-31 05:58:15 +00001327 RRI.IndVarEnd->addIncoming(LS.IndVarBase, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001328
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001329 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1330 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001331 for (PHINode &PN : LS.LatchExit->phis())
1332 replacePHIBlock(&PN, LS.Latch, RRI.ExitSelector);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001333
1334 return RRI;
1335}
1336
1337void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001338 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001339 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001340 unsigned PHIIndex = 0;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001341 for (PHINode &PN : LS.Header->phis())
1342 for (unsigned i = 0, e = PN.getNumIncomingValues(); i < e; ++i)
1343 if (PN.getIncomingBlock(i) == ContinuationBlock)
1344 PN.setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001345
Sanjoy Dase75ed922015-02-26 08:19:31 +00001346 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001347}
1348
Sanjoy Dase75ed922015-02-26 08:19:31 +00001349BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1350 BasicBlock *OldPreheader,
1351 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001352 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1353 BranchInst::Create(LS.Header, Preheader);
1354
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001355 for (PHINode &PN : LS.Header->phis())
1356 for (unsigned i = 0, e = PN.getNumIncomingValues(); i < e; ++i)
1357 replacePHIBlock(&PN, OldPreheader, Preheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001358
1359 return Preheader;
1360}
1361
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001362void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001363 Loop *ParentLoop = OriginalLoop.getParentLoop();
1364 if (!ParentLoop)
1365 return;
1366
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001367 for (BasicBlock *BB : BBs)
Sanjoy Das83a72852016-08-02 19:32:01 +00001368 ParentLoop->addBasicBlockToLoop(BB, LI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001369}
1370
Sanjoy Das21434472016-08-14 01:04:46 +00001371Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent,
Fedor Sergeev194a4072018-03-15 11:01:19 +00001372 ValueToValueMapTy &VM,
1373 bool IsSubloop) {
Sanjoy Dasdef17292017-09-28 02:45:42 +00001374 Loop &New = *LI.AllocateLoop();
Chandler Carruth29c22d22017-05-25 03:01:31 +00001375 if (Parent)
1376 Parent->addChildLoop(&New);
1377 else
1378 LI.addTopLevelLoop(&New);
Fedor Sergeev194a4072018-03-15 11:01:19 +00001379 LPMAddNewLoop(&New, IsSubloop);
Sanjoy Das21434472016-08-14 01:04:46 +00001380
1381 // Add all of the blocks in Original to the new loop.
1382 for (auto *BB : Original->blocks())
1383 if (LI.getLoopFor(BB) == Original)
1384 New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI);
1385
1386 // Add all of the subloops to the new loop.
1387 for (Loop *SubLoop : *Original)
Fedor Sergeev194a4072018-03-15 11:01:19 +00001388 createClonedLoopStructure(SubLoop, &New, VM, /* IsSubloop */ true);
Sanjoy Das21434472016-08-14 01:04:46 +00001389
1390 return &New;
1391}
1392
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001393bool LoopConstrainer::run() {
1394 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001395 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1396 Preheader = OriginalLoop.getLoopPreheader();
1397 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1398 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001399
1400 OriginalPreheader = Preheader;
1401 MainLoopPreheader = Preheader;
1402
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001403 bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate;
1404 Optional<SubRanges> MaybeSR = calculateSubRanges(IsSignedPredicate);
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001405 if (!MaybeSR.hasValue()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001406 LLVM_DEBUG(dbgs() << "irce: could not compute subranges\n");
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001407 return false;
1408 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001409
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001410 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001411 bool Increasing = MainLoopStructure.IndVarIncreasing;
1412 IntegerType *IVTy =
Max Kazantseva22742b2017-08-31 05:58:15 +00001413 cast<IntegerType>(MainLoopStructure.IndVarBase->getType());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001414
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001415 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001416 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001417
1418 // It would have been better to make `PreLoop' and `PostLoop'
1419 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1420 // constructor.
1421 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001422 bool NeedsPreLoop =
1423 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1424 bool NeedsPostLoop =
1425 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1426
1427 Value *ExitPreLoopAt = nullptr;
1428 Value *ExitMainLoopAt = nullptr;
1429 const SCEVConstant *MinusOneS =
1430 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1431
1432 if (NeedsPreLoop) {
1433 const SCEV *ExitPreLoopAtSCEV = nullptr;
1434
1435 if (Increasing)
1436 ExitPreLoopAtSCEV = *SR.LowLimit;
Max Kazantsev78a54352019-01-15 10:01:46 +00001437 else if (cannotBeMinInLoop(*SR.HighLimit, &OriginalLoop, SE,
1438 IsSignedPredicate))
1439 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001440 else {
Max Kazantsev78a54352019-01-15 10:01:46 +00001441 LLVM_DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1442 << "preloop exit limit. HighLimit = "
1443 << *(*SR.HighLimit) << "\n");
1444 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001445 }
Serguei Katkov675e3042017-09-21 04:50:41 +00001446
Max Kazantsevb1b8aff2017-11-16 06:06:27 +00001447 if (!isSafeToExpandAt(ExitPreLoopAtSCEV, InsertPt, SE)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001448 LLVM_DEBUG(dbgs() << "irce: could not prove that it is safe to expand the"
1449 << " preloop exit limit " << *ExitPreLoopAtSCEV
1450 << " at block " << InsertPt->getParent()->getName()
1451 << "\n");
Max Kazantsevb1b8aff2017-11-16 06:06:27 +00001452 return false;
1453 }
1454
Sanjoy Dase75ed922015-02-26 08:19:31 +00001455 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1456 ExitPreLoopAt->setName("exit.preloop.at");
1457 }
1458
1459 if (NeedsPostLoop) {
1460 const SCEV *ExitMainLoopAtSCEV = nullptr;
1461
1462 if (Increasing)
1463 ExitMainLoopAtSCEV = *SR.HighLimit;
Max Kazantsev78a54352019-01-15 10:01:46 +00001464 else if (cannotBeMinInLoop(*SR.LowLimit, &OriginalLoop, SE,
1465 IsSignedPredicate))
1466 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001467 else {
Max Kazantsev78a54352019-01-15 10:01:46 +00001468 LLVM_DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1469 << "mainloop exit limit. LowLimit = "
1470 << *(*SR.LowLimit) << "\n");
1471 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001472 }
Serguei Katkov675e3042017-09-21 04:50:41 +00001473
Max Kazantsevb1b8aff2017-11-16 06:06:27 +00001474 if (!isSafeToExpandAt(ExitMainLoopAtSCEV, InsertPt, SE)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001475 LLVM_DEBUG(dbgs() << "irce: could not prove that it is safe to expand the"
1476 << " main loop exit limit " << *ExitMainLoopAtSCEV
1477 << " at block " << InsertPt->getParent()->getName()
1478 << "\n");
Max Kazantsevb1b8aff2017-11-16 06:06:27 +00001479 return false;
1480 }
1481
Sanjoy Dase75ed922015-02-26 08:19:31 +00001482 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1483 ExitMainLoopAt->setName("exit.mainloop.at");
1484 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001485
1486 // We clone these ahead of time so that we don't have to deal with changing
1487 // and temporarily invalid IR as we transform the loops.
1488 if (NeedsPreLoop)
1489 cloneLoop(PreLoop, "preloop");
1490 if (NeedsPostLoop)
1491 cloneLoop(PostLoop, "postloop");
1492
1493 RewrittenRangeInfo PreLoopRRI;
1494
1495 if (NeedsPreLoop) {
1496 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1497 PreLoop.Structure.Header);
1498
1499 MainLoopPreheader =
1500 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001501 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1502 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001503 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1504 PreLoopRRI);
1505 }
1506
1507 BasicBlock *PostLoopPreheader = nullptr;
1508 RewrittenRangeInfo PostLoopRRI;
1509
1510 if (NeedsPostLoop) {
1511 PostLoopPreheader =
1512 createPreheader(PostLoop.Structure, Preheader, "postloop");
1513 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001514 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001515 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1516 PostLoopRRI);
1517 }
1518
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001519 BasicBlock *NewMainLoopPreheader =
1520 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1521 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1522 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1523 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001524
1525 // Some of the above may be nullptr, filter them out before passing to
1526 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001527 auto NewBlocksEnd =
1528 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001529
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001530 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001531
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001532 DT.recalculate(F);
Sanjoy Das21434472016-08-14 01:04:46 +00001533
Anna Thomas72180322017-06-06 14:54:01 +00001534 // We need to first add all the pre and post loop blocks into the loop
1535 // structures (as part of createClonedLoopStructure), and then update the
1536 // LCSSA form and LoopSimplifyForm. This is necessary for correctly updating
1537 // LI when LoopSimplifyForm is generated.
1538 Loop *PreL = nullptr, *PostL = nullptr;
Sanjoy Das21434472016-08-14 01:04:46 +00001539 if (!PreLoop.Blocks.empty()) {
Fedor Sergeev194a4072018-03-15 11:01:19 +00001540 PreL = createClonedLoopStructure(&OriginalLoop,
1541 OriginalLoop.getParentLoop(), PreLoop.Map,
1542 /* IsSubLoop */ false);
Sanjoy Das21434472016-08-14 01:04:46 +00001543 }
1544
1545 if (!PostLoop.Blocks.empty()) {
Fedor Sergeev194a4072018-03-15 11:01:19 +00001546 PostL =
1547 createClonedLoopStructure(&OriginalLoop, OriginalLoop.getParentLoop(),
1548 PostLoop.Map, /* IsSubLoop */ false);
Sanjoy Das21434472016-08-14 01:04:46 +00001549 }
1550
Anna Thomas72180322017-06-06 14:54:01 +00001551 // This function canonicalizes the loop into Loop-Simplify and LCSSA forms.
1552 auto CanonicalizeLoop = [&] (Loop *L, bool IsOriginalLoop) {
1553 formLCSSARecursively(*L, DT, &LI, &SE);
1554 simplifyLoop(L, &DT, &LI, &SE, nullptr, true);
1555 // Pre/post loops are slow paths, we do not need to perform any loop
1556 // optimizations on them.
1557 if (!IsOriginalLoop)
1558 DisableAllLoopOptsOnLoop(*L);
1559 };
1560 if (PreL)
1561 CanonicalizeLoop(PreL, false);
1562 if (PostL)
1563 CanonicalizeLoop(PostL, false);
1564 CanonicalizeLoop(&OriginalLoop, true);
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001565
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001566 return true;
1567}
1568
Sanjoy Das95c476d2015-02-21 22:20:22 +00001569/// Computes and returns a range of values for the induction variable (IndVar)
1570/// in which the range check can be safely elided. If it cannot compute such a
1571/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001572Optional<InductiveRangeCheck::Range>
Sanjoy Das59776732016-05-21 02:31:51 +00001573InductiveRangeCheck::computeSafeIterationSpace(
Max Kazantsev26846782017-11-20 06:07:57 +00001574 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar,
1575 bool IsLatchSigned) const {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001576 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1577 // variable, that may or may not exist as a real llvm::Value in the loop) and
1578 // this inductive range check is a range check on the "C + D * I" ("C" is
Max Kazantsev84286ce2017-10-31 06:19:05 +00001579 // getBegin() and "D" is getStep()). We rewrite the value being range
Sanjoy Das95c476d2015-02-21 22:20:22 +00001580 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001581 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001582 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001583 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001584 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1585 //
Max Kazantsev26846782017-11-20 06:07:57 +00001586 // Here L stands for upper limit of the safe iteration space.
1587 // The inequality is satisfied by (0 - M) <= IndVar < (L - M). To avoid
1588 // overflows when calculating (0 - M) and (L - M) we, depending on type of
1589 // IV's iteration space, limit the calculations by borders of the iteration
1590 // space. For example, if IndVar is unsigned, (0 - M) overflows for any M > 0.
1591 // If we figured out that "anything greater than (-M) is safe", we strengthen
1592 // this to "everything greater than 0 is safe", assuming that values between
1593 // -M and 0 just do not exist in unsigned iteration space, and we don't want
1594 // to deal with overflown values.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001595
Sanjoy Das95c476d2015-02-21 22:20:22 +00001596 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001597 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001598
Sanjoy Das95c476d2015-02-21 22:20:22 +00001599 const SCEV *A = IndVar->getStart();
1600 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1601 if (!B)
1602 return None;
Max Kazantseve4c220e2017-08-01 06:49:29 +00001603 assert(!B->isZero() && "Recurrence with zero step?");
Sanjoy Das95c476d2015-02-21 22:20:22 +00001604
Max Kazantsev84286ce2017-10-31 06:19:05 +00001605 const SCEV *C = getBegin();
1606 const SCEVConstant *D = dyn_cast<SCEVConstant>(getStep());
Sanjoy Das95c476d2015-02-21 22:20:22 +00001607 if (D != B)
1608 return None;
1609
Max Kazantsev95054702017-08-04 07:41:24 +00001610 assert(!D->getValue()->isZero() && "Recurrence with zero step?");
Max Kazantsev26846782017-11-20 06:07:57 +00001611 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1612 const SCEV *SIntMax = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
Sanjoy Das95c476d2015-02-21 22:20:22 +00001613
Max Kazantsevb57ca092018-02-12 05:16:28 +00001614 // Subtract Y from X so that it does not go through border of the IV
Max Kazantsev26846782017-11-20 06:07:57 +00001615 // iteration space. Mathematically, it is equivalent to:
1616 //
Max Kazantsevb57ca092018-02-12 05:16:28 +00001617 // ClampedSubtract(X, Y) = min(max(X - Y, INT_MIN), INT_MAX). [1]
Max Kazantsev26846782017-11-20 06:07:57 +00001618 //
Max Kazantsevb57ca092018-02-12 05:16:28 +00001619 // In [1], 'X - Y' is a mathematical subtraction (result is not bounded to
Max Kazantsev26846782017-11-20 06:07:57 +00001620 // any width of bit grid). But after we take min/max, the result is
1621 // guaranteed to be within [INT_MIN, INT_MAX].
1622 //
1623 // In [1], INT_MAX and INT_MIN are respectively signed and unsigned max/min
1624 // values, depending on type of latch condition that defines IV iteration
1625 // space.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001626 auto ClampedSubtract = [&](const SCEV *X, const SCEV *Y) {
Max Kazantsevc0b268f2018-05-19 13:06:37 +00001627 // FIXME: The current implementation assumes that X is in [0, SINT_MAX].
1628 // This is required to ensure that SINT_MAX - X does not overflow signed and
1629 // that X - Y does not overflow unsigned if Y is negative. Can we lift this
1630 // restriction and make it work for negative X either?
Max Kazantsev26846782017-11-20 06:07:57 +00001631 if (IsLatchSigned) {
1632 // X is a number from signed range, Y is interpreted as signed.
1633 // Even if Y is SINT_MAX, (X - Y) does not reach SINT_MIN. So the only
1634 // thing we should care about is that we didn't cross SINT_MAX.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001635 // So, if Y is positive, we subtract Y safely.
Max Kazantsev26846782017-11-20 06:07:57 +00001636 // Rule 1: Y > 0 ---> Y.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001637 // If 0 <= -Y <= (SINT_MAX - X), we subtract Y safely.
Max Kazantsev26846782017-11-20 06:07:57 +00001638 // Rule 2: Y >=s (X - SINT_MAX) ---> Y.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001639 // If 0 <= (SINT_MAX - X) < -Y, we can only subtract (X - SINT_MAX).
Max Kazantsev26846782017-11-20 06:07:57 +00001640 // Rule 3: Y <s (X - SINT_MAX) ---> (X - SINT_MAX).
Max Kazantsevb57ca092018-02-12 05:16:28 +00001641 // It gives us smax(Y, X - SINT_MAX) to subtract in all cases.
Max Kazantsev26846782017-11-20 06:07:57 +00001642 const SCEV *XMinusSIntMax = SE.getMinusSCEV(X, SIntMax);
Max Kazantsev716e6472017-11-23 06:14:39 +00001643 return SE.getMinusSCEV(X, SE.getSMaxExpr(Y, XMinusSIntMax),
1644 SCEV::FlagNSW);
Max Kazantsev26846782017-11-20 06:07:57 +00001645 } else
1646 // X is a number from unsigned range, Y is interpreted as signed.
1647 // Even if Y is SINT_MIN, (X - Y) does not reach UINT_MAX. So the only
1648 // thing we should care about is that we didn't cross zero.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001649 // So, if Y is negative, we subtract Y safely.
Max Kazantsev26846782017-11-20 06:07:57 +00001650 // Rule 1: Y <s 0 ---> Y.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001651 // If 0 <= Y <= X, we subtract Y safely.
Max Kazantsev26846782017-11-20 06:07:57 +00001652 // Rule 2: Y <=s X ---> Y.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001653 // If 0 <= X < Y, we should stop at 0 and can only subtract X.
Max Kazantsev26846782017-11-20 06:07:57 +00001654 // Rule 3: Y >s X ---> X.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001655 // It gives us smin(X, Y) to subtract in all cases.
Max Kazantsev716e6472017-11-23 06:14:39 +00001656 return SE.getMinusSCEV(X, SE.getSMinExpr(X, Y), SCEV::FlagNUW);
Max Kazantsev26846782017-11-20 06:07:57 +00001657 };
Sanjoy Das95c476d2015-02-21 22:20:22 +00001658 const SCEV *M = SE.getMinusSCEV(C, A);
Max Kazantsev26846782017-11-20 06:07:57 +00001659 const SCEV *Zero = SE.getZero(M->getType());
Max Kazantsevc0b268f2018-05-19 13:06:37 +00001660
1661 // This function returns SCEV equal to 1 if X is non-negative 0 otherwise.
1662 auto SCEVCheckNonNegative = [&](const SCEV *X) {
1663 const Loop *L = IndVar->getLoop();
1664 const SCEV *One = SE.getOne(X->getType());
1665 // Can we trivially prove that X is a non-negative or negative value?
1666 if (isKnownNonNegativeInLoop(X, L, SE))
1667 return One;
1668 else if (isKnownNegativeInLoop(X, L, SE))
1669 return Zero;
1670 // If not, we will have to figure it out during the execution.
1671 // Function smax(smin(X, 0), -1) + 1 equals to 1 if X >= 0 and 0 if X < 0.
1672 const SCEV *NegOne = SE.getNegativeSCEV(One);
1673 return SE.getAddExpr(SE.getSMaxExpr(SE.getSMinExpr(X, Zero), NegOne), One);
1674 };
1675 // FIXME: Current implementation of ClampedSubtract implicitly assumes that
1676 // X is non-negative (in sense of a signed value). We need to re-implement
1677 // this function in a way that it will correctly handle negative X as well.
1678 // We use it twice: for X = 0 everything is fine, but for X = getEnd() we can
1679 // end up with a negative X and produce wrong results. So currently we ensure
1680 // that if getEnd() is negative then both ends of the safe range are zero.
1681 // Note that this may pessimize elimination of unsigned range checks against
1682 // negative values.
1683 const SCEV *REnd = getEnd();
1684 const SCEV *EndIsNonNegative = SCEVCheckNonNegative(REnd);
1685
1686 const SCEV *Begin = SE.getMulExpr(ClampedSubtract(Zero, M), EndIsNonNegative);
1687 const SCEV *End = SE.getMulExpr(ClampedSubtract(REnd, M), EndIsNonNegative);
Sanjoy Das351db052015-01-22 09:32:02 +00001688 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001689}
1690
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001691static Optional<InductiveRangeCheck::Range>
Max Kazantsev9ac70212017-10-25 06:47:39 +00001692IntersectSignedRange(ScalarEvolution &SE,
1693 const Optional<InductiveRangeCheck::Range> &R1,
1694 const InductiveRangeCheck::Range &R2) {
Max Kazantsev4332a942017-10-25 06:10:02 +00001695 if (R2.isEmpty(SE, /* IsSigned */ true))
Max Kazantsev25d86552017-10-11 06:53:07 +00001696 return None;
Max Kazantsev3612d4b2017-10-19 05:33:28 +00001697 if (!R1.hasValue())
1698 return R2;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001699 auto &R1Value = R1.getValue();
Max Kazantsev3612d4b2017-10-19 05:33:28 +00001700 // We never return empty ranges from this function, and R1 is supposed to be
1701 // a result of intersection. Thus, R1 is never empty.
Max Kazantsev4332a942017-10-25 06:10:02 +00001702 assert(!R1Value.isEmpty(SE, /* IsSigned */ true) &&
1703 "We should never have empty R1!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001704
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001705 // TODO: we could widen the smaller range and have this work; but for now we
1706 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001707 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001708 return None;
1709
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001710 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1711 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1712
Max Kazantsev25d86552017-10-11 06:53:07 +00001713 // If the resulting range is empty, just return None.
1714 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
Max Kazantsev4332a942017-10-25 06:10:02 +00001715 if (Ret.isEmpty(SE, /* IsSigned */ true))
Max Kazantsev25d86552017-10-11 06:53:07 +00001716 return None;
1717 return Ret;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001718}
1719
Max Kazantsev9ac70212017-10-25 06:47:39 +00001720static Optional<InductiveRangeCheck::Range>
1721IntersectUnsignedRange(ScalarEvolution &SE,
1722 const Optional<InductiveRangeCheck::Range> &R1,
1723 const InductiveRangeCheck::Range &R2) {
1724 if (R2.isEmpty(SE, /* IsSigned */ false))
1725 return None;
1726 if (!R1.hasValue())
1727 return R2;
1728 auto &R1Value = R1.getValue();
1729 // We never return empty ranges from this function, and R1 is supposed to be
1730 // a result of intersection. Thus, R1 is never empty.
1731 assert(!R1Value.isEmpty(SE, /* IsSigned */ false) &&
1732 "We should never have empty R1!");
1733
1734 // TODO: we could widen the smaller range and have this work; but for now we
1735 // bail out to keep things simple.
1736 if (R1Value.getType() != R2.getType())
1737 return None;
1738
1739 const SCEV *NewBegin = SE.getUMaxExpr(R1Value.getBegin(), R2.getBegin());
1740 const SCEV *NewEnd = SE.getUMinExpr(R1Value.getEnd(), R2.getEnd());
1741
1742 // If the resulting range is empty, just return None.
1743 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
1744 if (Ret.isEmpty(SE, /* IsSigned */ false))
1745 return None;
1746 return Ret;
1747}
1748
Fedor Sergeev194a4072018-03-15 11:01:19 +00001749PreservedAnalyses IRCEPass::run(Loop &L, LoopAnalysisManager &AM,
1750 LoopStandardAnalysisResults &AR,
1751 LPMUpdater &U) {
1752 Function *F = L.getHeader()->getParent();
1753 const auto &FAM =
1754 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
1755 auto *BPI = FAM.getCachedResult<BranchProbabilityAnalysis>(*F);
1756 InductiveRangeCheckElimination IRCE(AR.SE, BPI, AR.DT, AR.LI);
1757 auto LPMAddNewLoop = [&U](Loop *NL, bool IsSubloop) {
1758 if (!IsSubloop)
1759 U.addSiblingLoops(NL);
1760 };
1761 bool Changed = IRCE.run(&L, LPMAddNewLoop);
1762 if (!Changed)
1763 return PreservedAnalyses::all();
1764
1765 return getLoopPassPreservedAnalyses();
1766}
1767
1768bool IRCELegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001769 if (skipLoop(L))
1770 return false;
1771
Fedor Sergeev194a4072018-03-15 11:01:19 +00001772 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1773 BranchProbabilityInfo &BPI =
1774 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
1775 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1776 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1777 InductiveRangeCheckElimination IRCE(SE, &BPI, DT, LI);
1778 auto LPMAddNewLoop = [&LPM](Loop *NL, bool /* IsSubLoop */) {
1779 LPM.addLoop(*NL);
1780 };
1781 return IRCE.run(L, LPMAddNewLoop);
1782}
1783
1784bool InductiveRangeCheckElimination::run(
1785 Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001786 if (L->getBlocks().size() >= LoopSizeCutoff) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001787 LLVM_DEBUG(dbgs() << "irce: giving up constraining loop, too large\n");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001788 return false;
1789 }
1790
1791 BasicBlock *Preheader = L->getLoopPreheader();
1792 if (!Preheader) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001793 LLVM_DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001794 return false;
1795 }
1796
1797 LLVMContext &Context = Preheader->getContext();
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001798 SmallVector<InductiveRangeCheck, 16> RangeChecks;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001799
1800 for (auto BBI : L->getBlocks())
1801 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
Sanjoy Dasa0992682016-05-26 00:09:02 +00001802 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1803 RangeChecks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001804
1805 if (RangeChecks.empty())
1806 return false;
1807
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001808 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1809 OS << "irce: looking at loop "; L->print(OS);
1810 OS << "irce: loop has " << RangeChecks.size()
1811 << " inductive range checks: \n";
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001812 for (InductiveRangeCheck &IRC : RangeChecks)
1813 IRC.print(OS);
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001814 };
1815
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001816 LLVM_DEBUG(PrintRecognizedRangeChecks(dbgs()));
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001817
1818 if (PrintRangeChecks)
1819 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001820
Sanjoy Dase75ed922015-02-26 08:19:31 +00001821 const char *FailureReason = nullptr;
1822 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001823 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001824 if (!MaybeLoopStructure.hasValue()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001825 LLVM_DEBUG(dbgs() << "irce: could not parse loop structure: "
1826 << FailureReason << "\n";);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001827 return false;
1828 }
1829 LoopStructure LS = MaybeLoopStructure.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001830 const SCEVAddRecExpr *IndVar =
Serguei Katkov675e3042017-09-21 04:50:41 +00001831 cast<SCEVAddRecExpr>(SE.getMinusSCEV(SE.getSCEV(LS.IndVarBase), SE.getSCEV(LS.IndVarStep)));
Sanjoy Dase75ed922015-02-26 08:19:31 +00001832
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001833 Optional<InductiveRangeCheck::Range> SafeIterRange;
1834 Instruction *ExprInsertPt = Preheader->getTerminator();
1835
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001836 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
Max Kazantsev9ac70212017-10-25 06:47:39 +00001837 // Basing on the type of latch predicate, we interpret the IV iteration range
1838 // as signed or unsigned range. We use different min/max functions (signed or
1839 // unsigned) when intersecting this range with safe iteration ranges implied
1840 // by range checks.
1841 auto IntersectRange =
1842 LS.IsSignedPredicate ? IntersectSignedRange : IntersectUnsignedRange;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001843
1844 IRBuilder<> B(ExprInsertPt);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001845 for (InductiveRangeCheck &IRC : RangeChecks) {
Max Kazantsev26846782017-11-20 06:07:57 +00001846 auto Result = IRC.computeSafeIterationSpace(SE, IndVar,
1847 LS.IsSignedPredicate);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001848 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001849 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001850 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001851 if (MaybeSafeIterRange.hasValue()) {
Max Kazantsev4332a942017-10-25 06:10:02 +00001852 assert(
1853 !MaybeSafeIterRange.getValue().isEmpty(SE, LS.IsSignedPredicate) &&
1854 "We should never return empty ranges!");
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001855 RangeChecksToEliminate.push_back(IRC);
1856 SafeIterRange = MaybeSafeIterRange.getValue();
1857 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001858 }
1859 }
1860
1861 if (!SafeIterRange.hasValue())
1862 return false;
1863
Fedor Sergeev194a4072018-03-15 11:01:19 +00001864 LoopConstrainer LC(*L, LI, LPMAddNewLoop, LS, SE, DT,
1865 SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001866 bool Changed = LC.run();
1867
1868 if (Changed) {
1869 auto PrintConstrainedLoopInfo = [L]() {
1870 dbgs() << "irce: in function ";
1871 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1872 dbgs() << "constrained ";
1873 L->print(dbgs());
1874 };
1875
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001876 LLVM_DEBUG(PrintConstrainedLoopInfo());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001877
1878 if (PrintChangedLoops)
1879 PrintConstrainedLoopInfo();
1880
1881 // Optimize away the now-redundant range checks.
1882
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001883 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1884 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001885 ? ConstantInt::getTrue(Context)
1886 : ConstantInt::getFalse(Context);
Sanjoy Dasaa83c472016-05-23 22:16:45 +00001887 IRC.getCheckUse()->set(FoldedRangeCheck);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001888 }
1889 }
1890
1891 return Changed;
1892}
1893
1894Pass *llvm::createInductiveRangeCheckEliminationPass() {
Fedor Sergeev194a4072018-03-15 11:01:19 +00001895 return new IRCELegacyPass();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001896}