blob: 86a00b1590e5144de8424f96a3380324eb5370eb [file] [log] [blame]
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001//===-- InductiveRangeCheckElimination.cpp - ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9// The InductiveRangeCheckElimination pass splits a loop's iteration space into
10// three disjoint ranges. It does that in a way such that the loop running in
11// the middle loop provably does not need range checks. As an example, it will
12// convert
13//
14// len = < known positive >
15// for (i = 0; i < n; i++) {
16// if (0 <= i && i < len) {
17// do_something();
18// } else {
19// throw_out_of_bounds();
20// }
21// }
22//
23// to
24//
25// len = < known positive >
26// limit = smin(n, len)
27// // no first segment
28// for (i = 0; i < limit; i++) {
29// if (0 <= i && i < len) { // this check is fully redundant
30// do_something();
31// } else {
32// throw_out_of_bounds();
33// }
34// }
35// for (i = limit; i < n; i++) {
36// if (0 <= i && i < len) {
37// do_something();
38// } else {
39// throw_out_of_bounds();
40// }
41// }
42//===----------------------------------------------------------------------===//
43
44#include "llvm/ADT/Optional.h"
45
Sanjoy Dasdcf26512015-01-27 21:38:12 +000046#include "llvm/Analysis/BranchProbabilityInfo.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000047#include "llvm/Analysis/InstructionSimplify.h"
48#include "llvm/Analysis/LoopInfo.h"
49#include "llvm/Analysis/LoopPass.h"
50#include "llvm/Analysis/ScalarEvolution.h"
51#include "llvm/Analysis/ScalarEvolutionExpander.h"
52#include "llvm/Analysis/ScalarEvolutionExpressions.h"
53#include "llvm/Analysis/ValueTracking.h"
54
55#include "llvm/IR/Dominators.h"
56#include "llvm/IR/Function.h"
57#include "llvm/IR/Instructions.h"
58#include "llvm/IR/IRBuilder.h"
59#include "llvm/IR/Module.h"
60#include "llvm/IR/PatternMatch.h"
61#include "llvm/IR/ValueHandle.h"
62#include "llvm/IR/Verifier.h"
63
64#include "llvm/Support/Debug.h"
65
66#include "llvm/Transforms/Scalar.h"
67#include "llvm/Transforms/Utils/BasicBlockUtils.h"
68#include "llvm/Transforms/Utils/Cloning.h"
69#include "llvm/Transforms/Utils/LoopUtils.h"
70#include "llvm/Transforms/Utils/SimplifyIndVar.h"
71#include "llvm/Transforms/Utils/UnrollLoop.h"
72
73#include "llvm/Pass.h"
74
75#include <array>
76
77using namespace llvm;
78
Benjamin Kramer970eac42015-02-06 17:51:54 +000079static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
80 cl::init(64));
Sanjoy Dasa1837a32015-01-16 01:03:22 +000081
Benjamin Kramer970eac42015-02-06 17:51:54 +000082static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
83 cl::init(false));
Sanjoy Dasa1837a32015-01-16 01:03:22 +000084
85#define DEBUG_TYPE "irce"
86
87namespace {
88
89/// An inductive range check is conditional branch in a loop with
90///
91/// 1. a very cold successor (i.e. the branch jumps to that successor very
92/// rarely)
93///
94/// and
95///
96/// 2. a condition that is provably true for some range of values taken by the
97/// containing loop's induction variable.
98///
99/// Currently all inductive range checks are branches conditional on an
100/// expression of the form
101///
102/// 0 <= (Offset + Scale * I) < Length
103///
104/// where `I' is the canonical induction variable of a loop to which Offset and
105/// Scale are loop invariant, and Length is >= 0. Currently the 'false' branch
106/// is considered cold, looking at profiling data to verify that is a TODO.
107
108class InductiveRangeCheck {
109 const SCEV *Offset;
110 const SCEV *Scale;
111 Value *Length;
112 BranchInst *Branch;
113
114 InductiveRangeCheck() :
115 Offset(nullptr), Scale(nullptr), Length(nullptr), Branch(nullptr) { }
116
117public:
118 const SCEV *getOffset() const { return Offset; }
119 const SCEV *getScale() const { return Scale; }
120 Value *getLength() const { return Length; }
121
122 void print(raw_ostream &OS) const {
123 OS << "InductiveRangeCheck:\n";
124 OS << " Offset: ";
125 Offset->print(OS);
126 OS << " Scale: ";
127 Scale->print(OS);
128 OS << " Length: ";
129 Length->print(OS);
130 OS << " Branch: ";
131 getBranch()->print(OS);
132 }
133
134#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
135 void dump() {
136 print(dbgs());
137 }
138#endif
139
140 BranchInst *getBranch() const { return Branch; }
141
Sanjoy Das351db052015-01-22 09:32:02 +0000142 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
143 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
144
145 class Range {
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000146 const SCEV *Begin;
147 const SCEV *End;
Sanjoy Das351db052015-01-22 09:32:02 +0000148
149 public:
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000150 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
Sanjoy Das351db052015-01-22 09:32:02 +0000151 assert(Begin->getType() == End->getType() && "ill-typed range!");
152 }
153
154 Type *getType() const { return Begin->getType(); }
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000155 const SCEV *getBegin() const { return Begin; }
156 const SCEV *getEnd() const { return End; }
Sanjoy Das351db052015-01-22 09:32:02 +0000157 };
158
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000159 typedef SpecificBumpPtrAllocator<InductiveRangeCheck> AllocatorTy;
160
161 /// This is the value the condition of the branch needs to evaluate to for the
162 /// branch to take the hot successor (see (1) above).
163 bool getPassingDirection() { return true; }
164
165 /// Computes a range for the induction variable in which the range check is
166 /// redundant and can be constant-folded away.
167 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
168 IRBuilder<> &B) const;
169
170 /// Create an inductive range check out of BI if possible, else return
171 /// nullptr.
172 static InductiveRangeCheck *create(AllocatorTy &Alloc, BranchInst *BI,
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000173 Loop *L, ScalarEvolution &SE,
174 BranchProbabilityInfo &BPI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000175};
176
177class InductiveRangeCheckElimination : public LoopPass {
178 InductiveRangeCheck::AllocatorTy Allocator;
179
180public:
181 static char ID;
182 InductiveRangeCheckElimination() : LoopPass(ID) {
183 initializeInductiveRangeCheckEliminationPass(
184 *PassRegistry::getPassRegistry());
185 }
186
187 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000188 AU.addRequired<LoopInfoWrapperPass>();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000189 AU.addRequiredID(LoopSimplifyID);
190 AU.addRequiredID(LCSSAID);
191 AU.addRequired<ScalarEvolution>();
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000192 AU.addRequired<BranchProbabilityInfo>();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000193 }
194
195 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
196};
197
198char InductiveRangeCheckElimination::ID = 0;
199}
200
201INITIALIZE_PASS(InductiveRangeCheckElimination, "irce",
202 "Inductive range check elimination", false, false)
203
204static bool IsLowerBoundCheck(Value *Check, Value *&IndexV) {
205 using namespace llvm::PatternMatch;
206
207 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
208 Value *LHS = nullptr, *RHS = nullptr;
209
210 if (!match(Check, m_ICmp(Pred, m_Value(LHS), m_Value(RHS))))
211 return false;
212
213 switch (Pred) {
214 default:
215 return false;
216
217 case ICmpInst::ICMP_SLE:
218 std::swap(LHS, RHS);
219 // fallthrough
220 case ICmpInst::ICMP_SGE:
221 if (!match(RHS, m_ConstantInt<0>()))
222 return false;
223 IndexV = LHS;
224 return true;
225
226 case ICmpInst::ICMP_SLT:
227 std::swap(LHS, RHS);
228 // fallthrough
229 case ICmpInst::ICMP_SGT:
230 if (!match(RHS, m_ConstantInt<-1>()))
231 return false;
232 IndexV = LHS;
233 return true;
234 }
235}
236
237static bool IsUpperBoundCheck(Value *Check, Value *Index, Value *&UpperLimit) {
238 using namespace llvm::PatternMatch;
239
240 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
241 Value *LHS = nullptr, *RHS = nullptr;
242
243 if (!match(Check, m_ICmp(Pred, m_Value(LHS), m_Value(RHS))))
244 return false;
245
246 switch (Pred) {
247 default:
248 return false;
249
250 case ICmpInst::ICMP_SGT:
251 std::swap(LHS, RHS);
252 // fallthrough
253 case ICmpInst::ICMP_SLT:
254 if (LHS != Index)
255 return false;
256 UpperLimit = RHS;
257 return true;
258
259 case ICmpInst::ICMP_UGT:
260 std::swap(LHS, RHS);
261 // fallthrough
262 case ICmpInst::ICMP_ULT:
263 if (LHS != Index)
264 return false;
265 UpperLimit = RHS;
266 return true;
267 }
268}
269
270/// Split a condition into something semantically equivalent to (0 <= I <
271/// Limit), both comparisons signed and Len loop invariant on L and positive.
272/// On success, return true and set Index to I and UpperLimit to Limit. Return
273/// false on failure (we may still write to UpperLimit and Index on failure).
274/// It does not try to interpret I as a loop index.
275///
276static bool SplitRangeCheckCondition(Loop *L, ScalarEvolution &SE,
277 Value *Condition, const SCEV *&Index,
278 Value *&UpperLimit) {
279
280 // TODO: currently this catches some silly cases like comparing "%idx slt 1".
281 // Our transformations are still correct, but less likely to be profitable in
282 // those cases. We have to come up with some heuristics that pick out the
283 // range checks that are more profitable to clone a loop for. This function
284 // in general can be made more robust.
285
286 using namespace llvm::PatternMatch;
287
288 Value *A = nullptr;
289 Value *B = nullptr;
290 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
291
292 // In these early checks we assume that the matched UpperLimit is positive.
293 // We'll verify that fact later, before returning true.
294
295 if (match(Condition, m_And(m_Value(A), m_Value(B)))) {
296 Value *IndexV = nullptr;
297 Value *ExpectedUpperBoundCheck = nullptr;
298
299 if (IsLowerBoundCheck(A, IndexV))
300 ExpectedUpperBoundCheck = B;
301 else if (IsLowerBoundCheck(B, IndexV))
302 ExpectedUpperBoundCheck = A;
303 else
304 return false;
305
306 if (!IsUpperBoundCheck(ExpectedUpperBoundCheck, IndexV, UpperLimit))
307 return false;
308
309 Index = SE.getSCEV(IndexV);
310
311 if (isa<SCEVCouldNotCompute>(Index))
312 return false;
313
314 } else if (match(Condition, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
315 switch (Pred) {
316 default:
317 return false;
318
319 case ICmpInst::ICMP_SGT:
320 std::swap(A, B);
321 // fall through
322 case ICmpInst::ICMP_SLT:
323 UpperLimit = B;
324 Index = SE.getSCEV(A);
325 if (isa<SCEVCouldNotCompute>(Index) || !SE.isKnownNonNegative(Index))
326 return false;
327 break;
328
329 case ICmpInst::ICMP_UGT:
330 std::swap(A, B);
331 // fall through
332 case ICmpInst::ICMP_ULT:
333 UpperLimit = B;
334 Index = SE.getSCEV(A);
335 if (isa<SCEVCouldNotCompute>(Index))
336 return false;
337 break;
338 }
339 } else {
340 return false;
341 }
342
343 const SCEV *UpperLimitSCEV = SE.getSCEV(UpperLimit);
344 if (isa<SCEVCouldNotCompute>(UpperLimitSCEV) ||
345 !SE.isKnownNonNegative(UpperLimitSCEV))
346 return false;
347
348 if (SE.getLoopDisposition(UpperLimitSCEV, L) !=
349 ScalarEvolution::LoopInvariant) {
350 DEBUG(dbgs() << " in function: " << L->getHeader()->getParent()->getName()
351 << " ";
352 dbgs() << " UpperLimit is not loop invariant: "
353 << UpperLimit->getName() << "\n";);
354 return false;
355 }
356
357 return true;
358}
359
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000360
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000361InductiveRangeCheck *
362InductiveRangeCheck::create(InductiveRangeCheck::AllocatorTy &A, BranchInst *BI,
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000363 Loop *L, ScalarEvolution &SE,
364 BranchProbabilityInfo &BPI) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000365
366 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
367 return nullptr;
368
Sanjoy Dasdcf26512015-01-27 21:38:12 +0000369 BranchProbability LikelyTaken(15, 16);
370
371 if (BPI.getEdgeProbability(BI->getParent(), (unsigned) 0) < LikelyTaken)
372 return nullptr;
373
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000374 Value *Length = nullptr;
375 const SCEV *IndexSCEV = nullptr;
376
377 if (!SplitRangeCheckCondition(L, SE, BI->getCondition(), IndexSCEV, Length))
378 return nullptr;
379
380 assert(IndexSCEV && Length && "contract with SplitRangeCheckCondition!");
381
382 const SCEVAddRecExpr *IndexAddRec = dyn_cast<SCEVAddRecExpr>(IndexSCEV);
383 bool IsAffineIndex =
384 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
385
386 if (!IsAffineIndex)
387 return nullptr;
388
389 InductiveRangeCheck *IRC = new (A.Allocate()) InductiveRangeCheck;
390 IRC->Length = Length;
391 IRC->Offset = IndexAddRec->getStart();
392 IRC->Scale = IndexAddRec->getStepRecurrence(SE);
393 IRC->Branch = BI;
394 return IRC;
395}
396
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000397namespace {
398
399/// This class is used to constrain loops to run within a given iteration space.
400/// The algorithm this class implements is given a Loop and a range [Begin,
401/// End). The algorithm then tries to break out a "main loop" out of the loop
402/// it is given in a way that the "main loop" runs with the induction variable
403/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
404/// loops to run any remaining iterations. The pre loop runs any iterations in
405/// which the induction variable is < Begin, and the post loop runs any
406/// iterations in which the induction variable is >= End.
407///
408class LoopConstrainer {
409
410 // Keeps track of the structure of a loop. This is similar to llvm::Loop,
411 // except that it is more lightweight and can track the state of a loop
412 // through changing and potentially invalid IR. This structure also
413 // formalizes the kinds of loops we can deal with -- ones that have a single
414 // latch that is also an exiting block *and* have a canonical induction
415 // variable.
416 struct LoopStructure {
417 const char *Tag;
418
419 BasicBlock *Header;
420 BasicBlock *Latch;
421
422 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
423 // successor is `LatchExit', the exit block of the loop.
424 BranchInst *LatchBr;
425 BasicBlock *LatchExit;
426 unsigned LatchBrExitIdx;
427
428 // The canonical induction variable. It's value is `CIVStart` on the 0th
429 // itertion and `CIVNext` for all iterations after that.
430 PHINode *CIV;
431 Value *CIVStart;
432 Value *CIVNext;
433
434 LoopStructure() : Tag(""), Header(nullptr), Latch(nullptr),
435 LatchBr(nullptr), LatchExit(nullptr),
436 LatchBrExitIdx(-1), CIV(nullptr),
437 CIVStart(nullptr), CIVNext(nullptr) { }
438
439 template <typename M> LoopStructure map(M Map) const {
440 LoopStructure Result;
441 Result.Tag = Tag;
442 Result.Header = cast<BasicBlock>(Map(Header));
443 Result.Latch = cast<BasicBlock>(Map(Latch));
444 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
445 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
446 Result.LatchBrExitIdx = LatchBrExitIdx;
447 Result.CIV = cast<PHINode>(Map(CIV));
448 Result.CIVNext = Map(CIVNext);
449 Result.CIVStart = Map(CIVStart);
450 return Result;
451 }
452 };
453
454 // The representation of a clone of the original loop we started out with.
455 struct ClonedLoop {
456 // The cloned blocks
457 std::vector<BasicBlock *> Blocks;
458
459 // `Map` maps values in the clonee into values in the cloned version
460 ValueToValueMapTy Map;
461
462 // An instance of `LoopStructure` for the cloned loop
463 LoopStructure Structure;
464 };
465
466 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
467 // more details on what these fields mean.
468 struct RewrittenRangeInfo {
469 BasicBlock *PseudoExit;
470 BasicBlock *ExitSelector;
471 std::vector<PHINode *> PHIValuesAtPseudoExit;
472
473 RewrittenRangeInfo() : PseudoExit(nullptr), ExitSelector(nullptr) { }
474 };
475
476 // Calculated subranges we restrict the iteration space of the main loop to.
477 // See the implementation of `calculateSubRanges' for more details on how
478 // these fields are computed. `ExitPreLoopAt' is `None' if we don't need a
479 // pre loop. `ExitMainLoopAt' is `None' if we don't need a post loop.
480 struct SubRanges {
481 Optional<Value *> ExitPreLoopAt;
482 Optional<Value *> ExitMainLoopAt;
483 };
484
485 // A utility function that does a `replaceUsesOfWith' on the incoming block
486 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
487 // incoming block list with `ReplaceBy'.
488 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
489 BasicBlock *ReplaceBy);
490
491 // Try to "parse" `OriginalLoop' and populate the various out parameters.
492 // Returns true on success, false on failure.
493 //
494 bool recognizeLoop(LoopStructure &LoopStructureOut,
495 const SCEV *&LatchCountOut, BasicBlock *&PreHeaderOut,
496 const char *&FailureReasonOut) const;
497
498 // Compute a safe set of limits for the main loop to run in -- effectively the
499 // intersection of `Range' and the iteration space of the original loop.
500 // Return the header count (1 + the latch taken count) in `HeaderCount'.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000501 // Return None if unable to compute the set of subranges.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000502 //
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000503 Optional<SubRanges> calculateSubRanges(Value *&HeaderCount) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000504
505 // Clone `OriginalLoop' and return the result in CLResult. The IR after
506 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
507 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
508 // but there is no such edge.
509 //
510 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
511
512 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
513 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
514 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
515 // `OriginalHeaderCount'.
516 //
517 // If there are iterations left to execute, control is made to jump to
518 // `ContinuationBlock', otherwise they take the normal loop exit. The
519 // returned `RewrittenRangeInfo' object is populated as follows:
520 //
521 // .PseudoExit is a basic block that unconditionally branches to
522 // `ContinuationBlock'.
523 //
524 // .ExitSelector is a basic block that decides, on exit from the loop,
525 // whether to branch to the "true" exit or to `PseudoExit'.
526 //
527 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
528 // for each PHINode in the loop header on taking the pseudo exit.
529 //
530 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
531 // preheader because it is made to branch to the loop header only
532 // conditionally.
533 //
534 RewrittenRangeInfo
535 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
536 Value *ExitLoopAt,
537 BasicBlock *ContinuationBlock) const;
538
539 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
540 // function creates a new preheader for `LS' and returns it.
541 //
542 BasicBlock *createPreheader(const LoopConstrainer::LoopStructure &LS,
543 BasicBlock *OldPreheader, const char *Tag) const;
544
545 // `ContinuationBlockAndPreheader' was the continuation block for some call to
546 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
547 // This function rewrites the PHI nodes in `LS.Header' to start with the
548 // correct value.
549 void rewriteIncomingValuesForPHIs(
550 LoopConstrainer::LoopStructure &LS,
551 BasicBlock *ContinuationBlockAndPreheader,
552 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
553
554 // Even though we do not preserve any passes at this time, we at least need to
555 // keep the parent loop structure consistent. The `LPPassManager' seems to
556 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000557 // blocks denoted by BBs to this loops parent loop if required.
558 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000559
560 // Some global state.
561 Function &F;
562 LLVMContext &Ctx;
563 ScalarEvolution &SE;
564
565 // Information about the original loop we started out with.
566 Loop &OriginalLoop;
567 LoopInfo &OriginalLoopInfo;
568 const SCEV *LatchTakenCount;
569 BasicBlock *OriginalPreheader;
570 Value *OriginalHeaderCount;
571
572 // The preheader of the main loop. This may or may not be different from
573 // `OriginalPreheader'.
574 BasicBlock *MainLoopPreheader;
575
576 // The range we need to run the main loop in.
577 InductiveRangeCheck::Range Range;
578
579 // The structure of the main loop (see comment at the beginning of this class
580 // for a definition)
581 LoopStructure MainLoopStructure;
582
583public:
584 LoopConstrainer(Loop &L, LoopInfo &LI, ScalarEvolution &SE,
585 InductiveRangeCheck::Range R)
586 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()), SE(SE),
587 OriginalLoop(L), OriginalLoopInfo(LI), LatchTakenCount(nullptr),
588 OriginalPreheader(nullptr), OriginalHeaderCount(nullptr),
589 MainLoopPreheader(nullptr), Range(R) { }
590
591 // Entry point for the algorithm. Returns true on success.
592 bool run();
593};
594
595}
596
597void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
598 BasicBlock *ReplaceBy) {
599 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
600 if (PN->getIncomingBlock(i) == Block)
601 PN->setIncomingBlock(i, ReplaceBy);
602}
603
604bool LoopConstrainer::recognizeLoop(LoopStructure &LoopStructureOut,
605 const SCEV *&LatchCountOut,
606 BasicBlock *&PreheaderOut,
607 const char *&FailureReason) const {
608 using namespace llvm::PatternMatch;
609
610 assert(OriginalLoop.isLoopSimplifyForm() &&
611 "should follow from addRequired<>");
612
613 BasicBlock *Latch = OriginalLoop.getLoopLatch();
614 if (!OriginalLoop.isLoopExiting(Latch)) {
615 FailureReason = "no loop latch";
616 return false;
617 }
618
619 PHINode *CIV = OriginalLoop.getCanonicalInductionVariable();
620 if (!CIV) {
621 FailureReason = "no CIV";
622 return false;
623 }
624
625 BasicBlock *Header = OriginalLoop.getHeader();
626 BasicBlock *Preheader = OriginalLoop.getLoopPreheader();
627 if (!Preheader) {
628 FailureReason = "no preheader";
629 return false;
630 }
631
632 Value *CIVNext = CIV->getIncomingValueForBlock(Latch);
633 Value *CIVStart = CIV->getIncomingValueForBlock(Preheader);
634
635 const SCEV *LatchCount = SE.getExitCount(&OriginalLoop, Latch);
636 if (isa<SCEVCouldNotCompute>(LatchCount)) {
637 FailureReason = "could not compute latch count";
638 return false;
639 }
640
641 // While SCEV does most of the analysis for us, we still have to
642 // modify the latch; and currently we can only deal with certain
643 // kinds of latches. This can be made more sophisticated as needed.
644
645 BranchInst *LatchBr = dyn_cast<BranchInst>(&*Latch->rbegin());
646
647 if (!LatchBr || LatchBr->isUnconditional()) {
648 FailureReason = "latch terminator not conditional branch";
649 return false;
650 }
651
652 // Currently we only support a latch condition of the form:
653 //
654 // %condition = icmp slt %civNext, %limit
655 // br i1 %condition, label %header, label %exit
656
657 if (LatchBr->getSuccessor(0) != Header) {
658 FailureReason = "unknown latch form (header not first successor)";
659 return false;
660 }
661
662 Value *CIVComparedTo = nullptr;
663 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
664 if (!(match(LatchBr->getCondition(),
665 m_ICmp(Pred, m_Specific(CIVNext), m_Value(CIVComparedTo))) &&
666 Pred == ICmpInst::ICMP_SLT)) {
667 FailureReason = "unknown latch form (not slt)";
668 return false;
669 }
670
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000671 // IndVarSimplify will sometimes leave behind (in SCEV's cache) backedge-taken
672 // counts that are narrower than the canonical induction variable. These
673 // values are still accurate, and we could probably use them after sign/zero
674 // extension; but for now we just bail out of the transformation to keep
675 // things simple.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000676 const SCEV *CIVComparedToSCEV = SE.getSCEV(CIVComparedTo);
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000677 if (isa<SCEVCouldNotCompute>(CIVComparedToSCEV) ||
678 CIVComparedToSCEV->getType() != LatchCount->getType()) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000679 FailureReason = "could not relate CIV to latch expression";
680 return false;
681 }
682
683 const SCEV *ShouldBeOne = SE.getMinusSCEV(CIVComparedToSCEV, LatchCount);
684 const SCEVConstant *SCEVOne = dyn_cast<SCEVConstant>(ShouldBeOne);
685 if (!SCEVOne || SCEVOne->getValue()->getValue() != 1) {
686 FailureReason = "unexpected header count in latch";
687 return false;
688 }
689
690 unsigned LatchBrExitIdx = 1;
691 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
692
693 assert(SE.getLoopDisposition(LatchCount, &OriginalLoop) ==
694 ScalarEvolution::LoopInvariant &&
695 "loop variant exit count doesn't make sense!");
696
697 assert(!OriginalLoop.contains(LatchExit) && "expected an exit block!");
698
699 LoopStructureOut.Tag = "main";
700 LoopStructureOut.Header = Header;
701 LoopStructureOut.Latch = Latch;
702 LoopStructureOut.LatchBr = LatchBr;
703 LoopStructureOut.LatchExit = LatchExit;
704 LoopStructureOut.LatchBrExitIdx = LatchBrExitIdx;
705 LoopStructureOut.CIV = CIV;
706 LoopStructureOut.CIVNext = CIVNext;
707 LoopStructureOut.CIVStart = CIVStart;
708
709 LatchCountOut = LatchCount;
710 PreheaderOut = Preheader;
711 FailureReason = nullptr;
712
713 return true;
714}
715
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000716Optional<LoopConstrainer::SubRanges>
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000717LoopConstrainer::calculateSubRanges(Value *&HeaderCountOut) const {
718 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
719
Sanjoy Das351db052015-01-22 09:32:02 +0000720 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000721 return None;
722
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000723 SCEVExpander Expander(SE, "irce");
724 Instruction *InsertPt = OriginalPreheader->getTerminator();
725
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000726 LoopConstrainer::SubRanges Result;
727
728 // I think we can be more aggressive here and make this nuw / nsw if the
729 // addition that feeds into the icmp for the latch's terminating branch is nuw
730 // / nsw. In any case, a wrapping 2's complement addition is safe.
731 ConstantInt *One = ConstantInt::get(Ty, 1);
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000732 const SCEV *HeaderCountSCEV = SE.getAddExpr(LatchTakenCount, SE.getSCEV(One));
733 HeaderCountOut = Expander.expandCodeFor(HeaderCountSCEV, Ty, InsertPt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000734
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000735 const SCEV *Zero = SE.getConstant(Ty, 0);
736
737 // In some cases we can prove that we don't need a pre or post loop
738
739 bool ProvablyNoPreloop =
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000740 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Zero);
741 if (!ProvablyNoPreloop) {
742 const SCEV *ExitPreLoopAtSCEV =
743 SE.getSMinExpr(HeaderCountSCEV, Range.getBegin());
744 Result.ExitPreLoopAt =
745 Expander.expandCodeFor(ExitPreLoopAtSCEV, Ty, InsertPt);
746 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000747
748 bool ProvablyNoPostLoop =
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000749 SE.isKnownPredicate(ICmpInst::ICMP_SLE, HeaderCountSCEV, Range.getEnd());
750 if (!ProvablyNoPostLoop) {
751 const SCEV *ExitMainLoopAtSCEV =
752 SE.getSMinExpr(HeaderCountSCEV, Range.getEnd());
753 Result.ExitMainLoopAt =
754 Expander.expandCodeFor(ExitMainLoopAtSCEV, Ty, InsertPt);
755 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000756
757 return Result;
758}
759
760void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
761 const char *Tag) const {
762 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
763 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
764 Result.Blocks.push_back(Clone);
765 Result.Map[BB] = Clone;
766 }
767
768 auto GetClonedValue = [&Result](Value *V) {
769 assert(V && "null values not in domain!");
770 auto It = Result.Map.find(V);
771 if (It == Result.Map.end())
772 return V;
773 return static_cast<Value *>(It->second);
774 };
775
776 Result.Structure = MainLoopStructure.map(GetClonedValue);
777 Result.Structure.Tag = Tag;
778
779 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
780 BasicBlock *ClonedBB = Result.Blocks[i];
781 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
782
783 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
784
785 for (Instruction &I : *ClonedBB)
786 RemapInstruction(&I, Result.Map,
787 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
788
789 // Exit blocks will now have one more predecessor and their PHI nodes need
790 // to be edited to reflect that. No phi nodes need to be introduced because
791 // the loop is in LCSSA.
792
793 for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB);
794 SBBI != SBBE; ++SBBI) {
795
796 if (OriginalLoop.contains(*SBBI))
797 continue; // not an exit block
798
799 for (Instruction &I : **SBBI) {
800 if (!isa<PHINode>(&I))
801 break;
802
803 PHINode *PN = cast<PHINode>(&I);
804 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
805 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
806 }
807 }
808 }
809}
810
811LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
812 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitLoopAt,
813 BasicBlock *ContinuationBlock) const {
814
815 // We start with a loop with a single latch:
816 //
817 // +--------------------+
818 // | |
819 // | preheader |
820 // | |
821 // +--------+-----------+
822 // | ----------------\
823 // | / |
824 // +--------v----v------+ |
825 // | | |
826 // | header | |
827 // | | |
828 // +--------------------+ |
829 // |
830 // ..... |
831 // |
832 // +--------------------+ |
833 // | | |
834 // | latch >----------/
835 // | |
836 // +-------v------------+
837 // |
838 // |
839 // | +--------------------+
840 // | | |
841 // +---> original exit |
842 // | |
843 // +--------------------+
844 //
845 // We change the control flow to look like
846 //
847 //
848 // +--------------------+
849 // | |
850 // | preheader >-------------------------+
851 // | | |
852 // +--------v-----------+ |
853 // | /-------------+ |
854 // | / | |
855 // +--------v--v--------+ | |
856 // | | | |
857 // | header | | +--------+ |
858 // | | | | | |
859 // +--------------------+ | | +-----v-----v-----------+
860 // | | | |
861 // | | | .pseudo.exit |
862 // | | | |
863 // | | +-----------v-----------+
864 // | | |
865 // ..... | | |
866 // | | +--------v-------------+
867 // +--------------------+ | | | |
868 // | | | | | ContinuationBlock |
869 // | latch >------+ | | |
870 // | | | +----------------------+
871 // +---------v----------+ |
872 // | |
873 // | |
874 // | +---------------^-----+
875 // | | |
876 // +-----> .exit.selector |
877 // | |
878 // +----------v----------+
879 // |
880 // +--------------------+ |
881 // | | |
882 // | original exit <----+
883 // | |
884 // +--------------------+
885 //
886
887 RewrittenRangeInfo RRI;
888
889 auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
890 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
891 &F, BBInsertLocation);
892 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
893 BBInsertLocation);
894
895 BranchInst *PreheaderJump = cast<BranchInst>(&*Preheader->rbegin());
896
897 IRBuilder<> B(PreheaderJump);
898
899 // EnterLoopCond - is it okay to start executing this `LS'?
900 Value *EnterLoopCond = B.CreateICmpSLT(LS.CIVStart, ExitLoopAt);
901 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
902 PreheaderJump->eraseFromParent();
903
904 assert(LS.LatchBrExitIdx == 1 && "generalize this as needed!");
905
906 B.SetInsertPoint(LS.LatchBr);
907
908 // ContinueCond - is it okay to execute the next iteration in `LS'?
909 Value *ContinueCond = B.CreateICmpSLT(LS.CIVNext, ExitLoopAt);
910
911 LS.LatchBr->setCondition(ContinueCond);
912 assert(LS.LatchBr->getSuccessor(LS.LatchBrExitIdx) == LS.LatchExit &&
913 "invariant!");
914 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
915
916 B.SetInsertPoint(RRI.ExitSelector);
917
918 // IterationsLeft - are there any more iterations left, given the original
919 // upper bound on the induction variable? If not, we branch to the "real"
920 // exit.
921 Value *IterationsLeft = B.CreateICmpSLT(LS.CIVNext, OriginalHeaderCount);
922 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
923
924 BranchInst *BranchToContinuation =
925 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
926
927 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
928 // each of the PHI nodes in the loop header. This feeds into the initial
929 // value of the same PHI nodes if/when we continue execution.
930 for (Instruction &I : *LS.Header) {
931 if (!isa<PHINode>(&I))
932 break;
933
934 PHINode *PN = cast<PHINode>(&I);
935
936 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
937 BranchToContinuation);
938
939 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
940 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
941 RRI.ExitSelector);
942 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
943 }
944
945 // The latch exit now has a branch from `RRI.ExitSelector' instead of
946 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
947 for (Instruction &I : *LS.LatchExit) {
948 if (PHINode *PN = dyn_cast<PHINode>(&I))
949 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
950 else
951 break;
952 }
953
954 return RRI;
955}
956
957void LoopConstrainer::rewriteIncomingValuesForPHIs(
958 LoopConstrainer::LoopStructure &LS, BasicBlock *ContinuationBlock,
959 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
960
961 unsigned PHIIndex = 0;
962 for (Instruction &I : *LS.Header) {
963 if (!isa<PHINode>(&I))
964 break;
965
966 PHINode *PN = cast<PHINode>(&I);
967
968 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
969 if (PN->getIncomingBlock(i) == ContinuationBlock)
970 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
971 }
972
973 LS.CIVStart = LS.CIV->getIncomingValueForBlock(ContinuationBlock);
974}
975
976BasicBlock *
977LoopConstrainer::createPreheader(const LoopConstrainer::LoopStructure &LS,
978 BasicBlock *OldPreheader,
979 const char *Tag) const {
980
981 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
982 BranchInst::Create(LS.Header, Preheader);
983
984 for (Instruction &I : *LS.Header) {
985 if (!isa<PHINode>(&I))
986 break;
987
988 PHINode *PN = cast<PHINode>(&I);
989 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
990 replacePHIBlock(PN, OldPreheader, Preheader);
991 }
992
993 return Preheader;
994}
995
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000996void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000997 Loop *ParentLoop = OriginalLoop.getParentLoop();
998 if (!ParentLoop)
999 return;
1000
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001001 for (BasicBlock *BB : BBs)
1002 ParentLoop->addBasicBlockToLoop(BB, OriginalLoopInfo);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001003}
1004
1005bool LoopConstrainer::run() {
1006 BasicBlock *Preheader = nullptr;
1007 const char *CouldNotProceedBecause = nullptr;
1008 if (!recognizeLoop(MainLoopStructure, LatchTakenCount, Preheader,
1009 CouldNotProceedBecause)) {
1010 DEBUG(dbgs() << "irce: could not recognize loop, " << CouldNotProceedBecause
1011 << "\n";);
1012 return false;
1013 }
1014
1015 OriginalPreheader = Preheader;
1016 MainLoopPreheader = Preheader;
1017
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001018 Optional<SubRanges> MaybeSR = calculateSubRanges(OriginalHeaderCount);
1019 if (!MaybeSR.hasValue()) {
1020 DEBUG(dbgs() << "irce: could not compute subranges\n");
1021 return false;
1022 }
1023 SubRanges SR = MaybeSR.getValue();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001024
1025 // It would have been better to make `PreLoop' and `PostLoop'
1026 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1027 // constructor.
1028 ClonedLoop PreLoop, PostLoop;
1029 bool NeedsPreLoop = SR.ExitPreLoopAt.hasValue();
1030 bool NeedsPostLoop = SR.ExitMainLoopAt.hasValue();
1031
1032 // We clone these ahead of time so that we don't have to deal with changing
1033 // and temporarily invalid IR as we transform the loops.
1034 if (NeedsPreLoop)
1035 cloneLoop(PreLoop, "preloop");
1036 if (NeedsPostLoop)
1037 cloneLoop(PostLoop, "postloop");
1038
1039 RewrittenRangeInfo PreLoopRRI;
1040
1041 if (NeedsPreLoop) {
1042 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1043 PreLoop.Structure.Header);
1044
1045 MainLoopPreheader =
1046 createPreheader(MainLoopStructure, Preheader, "mainloop");
1047 PreLoopRRI =
1048 changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1049 SR.ExitPreLoopAt.getValue(), MainLoopPreheader);
1050 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1051 PreLoopRRI);
1052 }
1053
1054 BasicBlock *PostLoopPreheader = nullptr;
1055 RewrittenRangeInfo PostLoopRRI;
1056
1057 if (NeedsPostLoop) {
1058 PostLoopPreheader =
1059 createPreheader(PostLoop.Structure, Preheader, "postloop");
1060 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
1061 SR.ExitMainLoopAt.getValue(),
1062 PostLoopPreheader);
1063 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1064 PostLoopRRI);
1065 }
1066
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001067 BasicBlock *NewMainLoopPreheader =
1068 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1069 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1070 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1071 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001072
1073 // Some of the above may be nullptr, filter them out before passing to
1074 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001075 auto NewBlocksEnd =
1076 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001077
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001078 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1079 addToParentLoopIfNeeded(PreLoop.Blocks);
1080 addToParentLoopIfNeeded(PostLoop.Blocks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001081
1082 return true;
1083}
1084
1085/// Computes and returns a range of values for the induction variable in which
1086/// the range check can be safely elided. If it cannot compute such a range,
1087/// returns None.
1088Optional<InductiveRangeCheck::Range>
1089InductiveRangeCheck::computeSafeIterationSpace(ScalarEvolution &SE,
1090 IRBuilder<> &B) const {
1091
1092 // Currently we support inequalities of the form:
1093 //
1094 // 0 <= Offset + 1 * CIV < L given L >= 0
1095 //
1096 // The inequality is satisfied by -Offset <= CIV < (L - Offset) [^1]. All
1097 // additions and subtractions are twos-complement wrapping and comparisons are
1098 // signed.
1099 //
1100 // Proof:
1101 //
1102 // If there exists CIV such that -Offset <= CIV < (L - Offset) then it
1103 // follows that -Offset <= (-Offset + L) [== Eq. 1]. Since L >= 0, if
1104 // (-Offset + L) sign-overflows then (-Offset + L) < (-Offset). Hence by
1105 // [Eq. 1], (-Offset + L) could not have overflown.
1106 //
1107 // This means CIV = t + (-Offset) for t in [0, L). Hence (CIV + Offset) =
1108 // t. Hence 0 <= (CIV + Offset) < L
1109
1110 // [^1]: Note that the solution does _not_ apply if L < 0; consider values
1111 // Offset = 127, CIV = 126 and L = -2 in an i8 world.
1112
1113 const SCEVConstant *ScaleC = dyn_cast<SCEVConstant>(getScale());
1114 if (!(ScaleC && ScaleC->getValue()->getValue() == 1)) {
1115 DEBUG(dbgs() << "irce: could not compute safe iteration space for:\n";
1116 print(dbgs()));
1117 return None;
1118 }
1119
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001120 const SCEV *Begin = SE.getNegativeSCEV(getOffset());
1121 const SCEV *End = SE.getMinusSCEV(SE.getSCEV(getLength()), getOffset());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001122
Sanjoy Das351db052015-01-22 09:32:02 +00001123 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001124}
1125
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001126static Optional<InductiveRangeCheck::Range>
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001127IntersectRange(ScalarEvolution &SE,
1128 const Optional<InductiveRangeCheck::Range> &R1,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001129 const InductiveRangeCheck::Range &R2, IRBuilder<> &B) {
1130 if (!R1.hasValue())
1131 return R2;
1132 auto &R1Value = R1.getValue();
1133
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001134 // TODO: we could widen the smaller range and have this work; but for now we
1135 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001136 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001137 return None;
1138
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001139 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1140 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1141
1142 return InductiveRangeCheck::Range(NewBegin, NewEnd);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001143}
1144
1145bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
1146 if (L->getBlocks().size() >= LoopSizeCutoff) {
1147 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1148 return false;
1149 }
1150
1151 BasicBlock *Preheader = L->getLoopPreheader();
1152 if (!Preheader) {
1153 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1154 return false;
1155 }
1156
1157 LLVMContext &Context = Preheader->getContext();
1158 InductiveRangeCheck::AllocatorTy IRCAlloc;
1159 SmallVector<InductiveRangeCheck *, 16> RangeChecks;
1160 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
Sanjoy Dasdcf26512015-01-27 21:38:12 +00001161 BranchProbabilityInfo &BPI = getAnalysis<BranchProbabilityInfo>();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001162
1163 for (auto BBI : L->getBlocks())
1164 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
1165 if (InductiveRangeCheck *IRC =
Sanjoy Dasdcf26512015-01-27 21:38:12 +00001166 InductiveRangeCheck::create(IRCAlloc, TBI, L, SE, BPI))
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001167 RangeChecks.push_back(IRC);
1168
1169 if (RangeChecks.empty())
1170 return false;
1171
1172 DEBUG(dbgs() << "irce: looking at loop "; L->print(dbgs());
1173 dbgs() << "irce: loop has " << RangeChecks.size()
1174 << " inductive range checks: \n";
1175 for (InductiveRangeCheck *IRC : RangeChecks)
1176 IRC->print(dbgs());
1177 );
1178
1179 Optional<InductiveRangeCheck::Range> SafeIterRange;
1180 Instruction *ExprInsertPt = Preheader->getTerminator();
1181
1182 SmallVector<InductiveRangeCheck *, 4> RangeChecksToEliminate;
1183
1184 IRBuilder<> B(ExprInsertPt);
1185 for (InductiveRangeCheck *IRC : RangeChecks) {
1186 auto Result = IRC->computeSafeIterationSpace(SE, B);
1187 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001188 auto MaybeSafeIterRange =
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001189 IntersectRange(SE, SafeIterRange, Result.getValue(), B);
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001190 if (MaybeSafeIterRange.hasValue()) {
1191 RangeChecksToEliminate.push_back(IRC);
1192 SafeIterRange = MaybeSafeIterRange.getValue();
1193 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001194 }
1195 }
1196
1197 if (!SafeIterRange.hasValue())
1198 return false;
1199
Chandler Carruth4f8f3072015-01-17 14:16:18 +00001200 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), SE,
1201 SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001202 bool Changed = LC.run();
1203
1204 if (Changed) {
1205 auto PrintConstrainedLoopInfo = [L]() {
1206 dbgs() << "irce: in function ";
1207 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1208 dbgs() << "constrained ";
1209 L->print(dbgs());
1210 };
1211
1212 DEBUG(PrintConstrainedLoopInfo());
1213
1214 if (PrintChangedLoops)
1215 PrintConstrainedLoopInfo();
1216
1217 // Optimize away the now-redundant range checks.
1218
1219 for (InductiveRangeCheck *IRC : RangeChecksToEliminate) {
1220 ConstantInt *FoldedRangeCheck = IRC->getPassingDirection()
1221 ? ConstantInt::getTrue(Context)
1222 : ConstantInt::getFalse(Context);
1223 IRC->getBranch()->setCondition(FoldedRangeCheck);
1224 }
1225 }
1226
1227 return Changed;
1228}
1229
1230Pass *llvm::createInductiveRangeCheckEliminationPass() {
1231 return new InductiveRangeCheckElimination;
1232}