17a7e6055SDimitry Andric //===-- LoopPredication.cpp - Guard based loop predication pass -----------===//
27a7e6055SDimitry Andric //
37a7e6055SDimitry Andric //                     The LLVM Compiler Infrastructure
47a7e6055SDimitry Andric //
57a7e6055SDimitry Andric // This file is distributed under the University of Illinois Open Source
67a7e6055SDimitry Andric // License. See LICENSE.TXT for details.
77a7e6055SDimitry Andric //
87a7e6055SDimitry Andric //===----------------------------------------------------------------------===//
97a7e6055SDimitry Andric //
107a7e6055SDimitry Andric // The LoopPredication pass tries to convert loop variant range checks to loop
117a7e6055SDimitry Andric // invariant by widening checks across loop iterations. For example, it will
127a7e6055SDimitry Andric // convert
137a7e6055SDimitry Andric //
147a7e6055SDimitry Andric //   for (i = 0; i < n; i++) {
157a7e6055SDimitry Andric //     guard(i < len);
167a7e6055SDimitry Andric //     ...
177a7e6055SDimitry Andric //   }
187a7e6055SDimitry Andric //
197a7e6055SDimitry Andric // to
207a7e6055SDimitry Andric //
217a7e6055SDimitry Andric //   for (i = 0; i < n; i++) {
227a7e6055SDimitry Andric //     guard(n - 1 < len);
237a7e6055SDimitry Andric //     ...
247a7e6055SDimitry Andric //   }
257a7e6055SDimitry Andric //
267a7e6055SDimitry Andric // After this transformation the condition of the guard is loop invariant, so
277a7e6055SDimitry Andric // loop-unswitch can later unswitch the loop by this condition which basically
287a7e6055SDimitry Andric // predicates the loop by the widened condition:
297a7e6055SDimitry Andric //
307a7e6055SDimitry Andric //   if (n - 1 < len)
317a7e6055SDimitry Andric //     for (i = 0; i < n; i++) {
327a7e6055SDimitry Andric //       ...
337a7e6055SDimitry Andric //     }
347a7e6055SDimitry Andric //   else
357a7e6055SDimitry Andric //     deoptimize
367a7e6055SDimitry Andric //
372cab237bSDimitry Andric // It's tempting to rely on SCEV here, but it has proven to be problematic.
382cab237bSDimitry Andric // Generally the facts SCEV provides about the increment step of add
392cab237bSDimitry Andric // recurrences are true if the backedge of the loop is taken, which implicitly
402cab237bSDimitry Andric // assumes that the guard doesn't fail. Using these facts to optimize the
412cab237bSDimitry Andric // guard results in a circular logic where the guard is optimized under the
422cab237bSDimitry Andric // assumption that it never fails.
432cab237bSDimitry Andric //
442cab237bSDimitry Andric // For example, in the loop below the induction variable will be marked as nuw
452cab237bSDimitry Andric // basing on the guard. Basing on nuw the guard predicate will be considered
462cab237bSDimitry Andric // monotonic. Given a monotonic condition it's tempting to replace the induction
472cab237bSDimitry Andric // variable in the condition with its value on the last iteration. But this
482cab237bSDimitry Andric // transformation is not correct, e.g. e = 4, b = 5 breaks the loop.
492cab237bSDimitry Andric //
502cab237bSDimitry Andric //   for (int i = b; i != e; i++)
512cab237bSDimitry Andric //     guard(i u< len)
522cab237bSDimitry Andric //
532cab237bSDimitry Andric // One of the ways to reason about this problem is to use an inductive proof
542cab237bSDimitry Andric // approach. Given the loop:
552cab237bSDimitry Andric //
562cab237bSDimitry Andric //   if (B(0)) {
572cab237bSDimitry Andric //     do {
582cab237bSDimitry Andric //       I = PHI(0, I.INC)
592cab237bSDimitry Andric //       I.INC = I + Step
602cab237bSDimitry Andric //       guard(G(I));
612cab237bSDimitry Andric //     } while (B(I));
622cab237bSDimitry Andric //   }
632cab237bSDimitry Andric //
642cab237bSDimitry Andric // where B(x) and G(x) are predicates that map integers to booleans, we want a
652cab237bSDimitry Andric // loop invariant expression M such the following program has the same semantics
662cab237bSDimitry Andric // as the above:
672cab237bSDimitry Andric //
682cab237bSDimitry Andric //   if (B(0)) {
692cab237bSDimitry Andric //     do {
702cab237bSDimitry Andric //       I = PHI(0, I.INC)
712cab237bSDimitry Andric //       I.INC = I + Step
722cab237bSDimitry Andric //       guard(G(0) && M);
732cab237bSDimitry Andric //     } while (B(I));
742cab237bSDimitry Andric //   }
752cab237bSDimitry Andric //
762cab237bSDimitry Andric // One solution for M is M = forall X . (G(X) && B(X)) => G(X + Step)
772cab237bSDimitry Andric //
782cab237bSDimitry Andric // Informal proof that the transformation above is correct:
792cab237bSDimitry Andric //
802cab237bSDimitry Andric //   By the definition of guards we can rewrite the guard condition to:
812cab237bSDimitry Andric //     G(I) && G(0) && M
822cab237bSDimitry Andric //
832cab237bSDimitry Andric //   Let's prove that for each iteration of the loop:
842cab237bSDimitry Andric //     G(0) && M => G(I)
852cab237bSDimitry Andric //   And the condition above can be simplified to G(Start) && M.
862cab237bSDimitry Andric //
872cab237bSDimitry Andric //   Induction base.
882cab237bSDimitry Andric //     G(0) && M => G(0)
892cab237bSDimitry Andric //
902cab237bSDimitry Andric //   Induction step. Assuming G(0) && M => G(I) on the subsequent
912cab237bSDimitry Andric //   iteration:
922cab237bSDimitry Andric //
932cab237bSDimitry Andric //     B(I) is true because it's the backedge condition.
942cab237bSDimitry Andric //     G(I) is true because the backedge is guarded by this condition.
952cab237bSDimitry Andric //
962cab237bSDimitry Andric //   So M = forall X . (G(X) && B(X)) => G(X + Step) implies G(I + Step).
972cab237bSDimitry Andric //
982cab237bSDimitry Andric // Note that we can use anything stronger than M, i.e. any condition which
992cab237bSDimitry Andric // implies M.
1002cab237bSDimitry Andric //
1012cab237bSDimitry Andric // When S = 1 (i.e. forward iterating loop), the transformation is supported
1022cab237bSDimitry Andric // when:
1032cab237bSDimitry Andric //   * The loop has a single latch with the condition of the form:
1042cab237bSDimitry Andric //     B(X) = latchStart + X <pred> latchLimit,
1052cab237bSDimitry Andric //     where <pred> is u<, u<=, s<, or s<=.
1062cab237bSDimitry Andric //   * The guard condition is of the form
1072cab237bSDimitry Andric //     G(X) = guardStart + X u< guardLimit
1082cab237bSDimitry Andric //
1092cab237bSDimitry Andric //   For the ult latch comparison case M is:
1102cab237bSDimitry Andric //     forall X . guardStart + X u< guardLimit && latchStart + X <u latchLimit =>
1112cab237bSDimitry Andric //        guardStart + X + 1 u< guardLimit
1122cab237bSDimitry Andric //
1132cab237bSDimitry Andric //   The only way the antecedent can be true and the consequent can be false is
1142cab237bSDimitry Andric //   if
1152cab237bSDimitry Andric //     X == guardLimit - 1 - guardStart
1162cab237bSDimitry Andric //   (and guardLimit is non-zero, but we won't use this latter fact).
1172cab237bSDimitry Andric //   If X == guardLimit - 1 - guardStart then the second half of the antecedent is
1182cab237bSDimitry Andric //     latchStart + guardLimit - 1 - guardStart u< latchLimit
1192cab237bSDimitry Andric //   and its negation is
1202cab237bSDimitry Andric //     latchStart + guardLimit - 1 - guardStart u>= latchLimit
1212cab237bSDimitry Andric //
1222cab237bSDimitry Andric //   In other words, if
1232cab237bSDimitry Andric //     latchLimit u<= latchStart + guardLimit - 1 - guardStart
1242cab237bSDimitry Andric //   then:
1252cab237bSDimitry Andric //   (the ranges below are written in ConstantRange notation, where [A, B) is the
1262cab237bSDimitry Andric //   set for (I = A; I != B; I++ /*maywrap*/) yield(I);)
1272cab237bSDimitry Andric //
1282cab237bSDimitry Andric //      forall X . guardStart + X u< guardLimit &&
1292cab237bSDimitry Andric //                 latchStart + X u< latchLimit =>
1302cab237bSDimitry Andric //        guardStart + X + 1 u< guardLimit
1312cab237bSDimitry Andric //   == forall X . guardStart + X u< guardLimit &&
1322cab237bSDimitry Andric //                 latchStart + X u< latchStart + guardLimit - 1 - guardStart =>
1332cab237bSDimitry Andric //        guardStart + X + 1 u< guardLimit
1342cab237bSDimitry Andric //   == forall X . (guardStart + X) in [0, guardLimit) &&
1352cab237bSDimitry Andric //                 (latchStart + X) in [0, latchStart + guardLimit - 1 - guardStart) =>
1362cab237bSDimitry Andric //        (guardStart + X + 1) in [0, guardLimit)
1372cab237bSDimitry Andric //   == forall X . X in [-guardStart, guardLimit - guardStart) &&
1382cab237bSDimitry Andric //                 X in [-latchStart, guardLimit - 1 - guardStart) =>
1392cab237bSDimitry Andric //         X in [-guardStart - 1, guardLimit - guardStart - 1)
1402cab237bSDimitry Andric //   == true
1412cab237bSDimitry Andric //
1422cab237bSDimitry Andric //   So the widened condition is:
1432cab237bSDimitry Andric //     guardStart u< guardLimit &&
1442cab237bSDimitry Andric //     latchStart + guardLimit - 1 - guardStart u>= latchLimit
1452cab237bSDimitry Andric //   Similarly for ule condition the widened condition is:
1462cab237bSDimitry Andric //     guardStart u< guardLimit &&
1472cab237bSDimitry Andric //     latchStart + guardLimit - 1 - guardStart u> latchLimit
1482cab237bSDimitry Andric //   For slt condition the widened condition is:
1492cab237bSDimitry Andric //     guardStart u< guardLimit &&
1502cab237bSDimitry Andric //     latchStart + guardLimit - 1 - guardStart s>= latchLimit
1512cab237bSDimitry Andric //   For sle condition the widened condition is:
1522cab237bSDimitry Andric //     guardStart u< guardLimit &&
1532cab237bSDimitry Andric //     latchStart + guardLimit - 1 - guardStart s> latchLimit
1542cab237bSDimitry Andric //
1552cab237bSDimitry Andric // When S = -1 (i.e. reverse iterating loop), the transformation is supported
1562cab237bSDimitry Andric // when:
1572cab237bSDimitry Andric //   * The loop has a single latch with the condition of the form:
1584ba319b5SDimitry Andric //     B(X) = X <pred> latchLimit, where <pred> is u>, u>=, s>, or s>=.
1592cab237bSDimitry Andric //   * The guard condition is of the form
1602cab237bSDimitry Andric //     G(X) = X - 1 u< guardLimit
1612cab237bSDimitry Andric //
1622cab237bSDimitry Andric //   For the ugt latch comparison case M is:
1632cab237bSDimitry Andric //     forall X. X-1 u< guardLimit and X u> latchLimit => X-2 u< guardLimit
1642cab237bSDimitry Andric //
1652cab237bSDimitry Andric //   The only way the antecedent can be true and the consequent can be false is if
1662cab237bSDimitry Andric //     X == 1.
1672cab237bSDimitry Andric //   If X == 1 then the second half of the antecedent is
1682cab237bSDimitry Andric //     1 u> latchLimit, and its negation is latchLimit u>= 1.
1692cab237bSDimitry Andric //
1702cab237bSDimitry Andric //   So the widened condition is:
1712cab237bSDimitry Andric //     guardStart u< guardLimit && latchLimit u>= 1.
1722cab237bSDimitry Andric //   Similarly for sgt condition the widened condition is:
1732cab237bSDimitry Andric //     guardStart u< guardLimit && latchLimit s>= 1.
1744ba319b5SDimitry Andric //   For uge condition the widened condition is:
1754ba319b5SDimitry Andric //     guardStart u< guardLimit && latchLimit u> 1.
1764ba319b5SDimitry Andric //   For sge condition the widened condition is:
1774ba319b5SDimitry Andric //     guardStart u< guardLimit && latchLimit s> 1.
1787a7e6055SDimitry Andric //===----------------------------------------------------------------------===//
1797a7e6055SDimitry Andric 
1807a7e6055SDimitry Andric #include "llvm/Transforms/Scalar/LoopPredication.h"
181*b5893f02SDimitry Andric #include "llvm/ADT/Statistic.h"
1824ba319b5SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
183*b5893f02SDimitry Andric #include "llvm/Analysis/GuardUtils.h"
1847a7e6055SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
1857a7e6055SDimitry Andric #include "llvm/Analysis/LoopPass.h"
1867a7e6055SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
1877a7e6055SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpander.h"
1887a7e6055SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
1897a7e6055SDimitry Andric #include "llvm/IR/Function.h"
1907a7e6055SDimitry Andric #include "llvm/IR/GlobalValue.h"
1917a7e6055SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
1927a7e6055SDimitry Andric #include "llvm/IR/Module.h"
1937a7e6055SDimitry Andric #include "llvm/IR/PatternMatch.h"
194db17bf38SDimitry Andric #include "llvm/Pass.h"
1957a7e6055SDimitry Andric #include "llvm/Support/Debug.h"
1967a7e6055SDimitry Andric #include "llvm/Transforms/Scalar.h"
1977a7e6055SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
1987a7e6055SDimitry Andric 
1997a7e6055SDimitry Andric #define DEBUG_TYPE "loop-predication"
2007a7e6055SDimitry Andric 
201*b5893f02SDimitry Andric STATISTIC(TotalConsidered, "Number of guards considered");
202*b5893f02SDimitry Andric STATISTIC(TotalWidened, "Number of checks widened");
203*b5893f02SDimitry Andric 
2047a7e6055SDimitry Andric using namespace llvm;
2057a7e6055SDimitry Andric 
2062cab237bSDimitry Andric static cl::opt<bool> EnableIVTruncation("loop-predication-enable-iv-truncation",
2072cab237bSDimitry Andric                                         cl::Hidden, cl::init(true));
2082cab237bSDimitry Andric 
2092cab237bSDimitry Andric static cl::opt<bool> EnableCountDownLoop("loop-predication-enable-count-down-loop",
2102cab237bSDimitry Andric                                         cl::Hidden, cl::init(true));
2114ba319b5SDimitry Andric 
2124ba319b5SDimitry Andric static cl::opt<bool>
2134ba319b5SDimitry Andric     SkipProfitabilityChecks("loop-predication-skip-profitability-checks",
2144ba319b5SDimitry Andric                             cl::Hidden, cl::init(false));
2154ba319b5SDimitry Andric 
2164ba319b5SDimitry Andric // This is the scale factor for the latch probability. We use this during
2174ba319b5SDimitry Andric // profitability analysis to find other exiting blocks that have a much higher
2184ba319b5SDimitry Andric // probability of exiting the loop instead of loop exiting via latch.
2194ba319b5SDimitry Andric // This value should be greater than 1 for a sane profitability check.
2204ba319b5SDimitry Andric static cl::opt<float> LatchExitProbabilityScale(
2214ba319b5SDimitry Andric     "loop-predication-latch-probability-scale", cl::Hidden, cl::init(2.0),
2224ba319b5SDimitry Andric     cl::desc("scale factor for the latch probability. Value should be greater "
2234ba319b5SDimitry Andric              "than 1. Lower values are ignored"));
2244ba319b5SDimitry Andric 
2257a7e6055SDimitry Andric namespace {
2267a7e6055SDimitry Andric class LoopPredication {
227d8866befSDimitry Andric   /// Represents an induction variable check:
228d8866befSDimitry Andric   ///   icmp Pred, <induction variable>, <loop invariant limit>
229d8866befSDimitry Andric   struct LoopICmp {
230d8866befSDimitry Andric     ICmpInst::Predicate Pred;
231d8866befSDimitry Andric     const SCEVAddRecExpr *IV;
232d8866befSDimitry Andric     const SCEV *Limit;
LoopICmp__anon96bde4440111::LoopPredication::LoopICmp233d8866befSDimitry Andric     LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV,
234d8866befSDimitry Andric              const SCEV *Limit)
235d8866befSDimitry Andric         : Pred(Pred), IV(IV), Limit(Limit) {}
LoopICmp__anon96bde4440111::LoopPredication::LoopICmp236d8866befSDimitry Andric     LoopICmp() {}
dump__anon96bde4440111::LoopPredication::LoopICmp2372cab237bSDimitry Andric     void dump() {
2382cab237bSDimitry Andric       dbgs() << "LoopICmp Pred = " << Pred << ", IV = " << *IV
2392cab237bSDimitry Andric              << ", Limit = " << *Limit << "\n";
2402cab237bSDimitry Andric     }
241d8866befSDimitry Andric   };
242d8866befSDimitry Andric 
2437a7e6055SDimitry Andric   ScalarEvolution *SE;
2444ba319b5SDimitry Andric   BranchProbabilityInfo *BPI;
2457a7e6055SDimitry Andric 
2467a7e6055SDimitry Andric   Loop *L;
2477a7e6055SDimitry Andric   const DataLayout *DL;
2487a7e6055SDimitry Andric   BasicBlock *Preheader;
2492cab237bSDimitry Andric   LoopICmp LatchCheck;
2507a7e6055SDimitry Andric 
2512cab237bSDimitry Andric   bool isSupportedStep(const SCEV* Step);
parseLoopICmp(ICmpInst * ICI)2522cab237bSDimitry Andric   Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI) {
2532cab237bSDimitry Andric     return parseLoopICmp(ICI->getPredicate(), ICI->getOperand(0),
2542cab237bSDimitry Andric                          ICI->getOperand(1));
2552cab237bSDimitry Andric   }
2562cab237bSDimitry Andric   Optional<LoopICmp> parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS,
2572cab237bSDimitry Andric                                    Value *RHS);
258d8866befSDimitry Andric 
2592cab237bSDimitry Andric   Optional<LoopICmp> parseLoopLatchICmp();
2602cab237bSDimitry Andric 
2612cab237bSDimitry Andric   bool CanExpand(const SCEV* S);
262d8866befSDimitry Andric   Value *expandCheck(SCEVExpander &Expander, IRBuilder<> &Builder,
263d8866befSDimitry Andric                      ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
264d8866befSDimitry Andric                      Instruction *InsertAt);
265d8866befSDimitry Andric 
2667a7e6055SDimitry Andric   Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander,
2677a7e6055SDimitry Andric                                         IRBuilder<> &Builder);
2682cab237bSDimitry Andric   Optional<Value *> widenICmpRangeCheckIncrementingLoop(LoopICmp LatchCheck,
2692cab237bSDimitry Andric                                                         LoopICmp RangeCheck,
2702cab237bSDimitry Andric                                                         SCEVExpander &Expander,
2712cab237bSDimitry Andric                                                         IRBuilder<> &Builder);
2722cab237bSDimitry Andric   Optional<Value *> widenICmpRangeCheckDecrementingLoop(LoopICmp LatchCheck,
2732cab237bSDimitry Andric                                                         LoopICmp RangeCheck,
2742cab237bSDimitry Andric                                                         SCEVExpander &Expander,
2752cab237bSDimitry Andric                                                         IRBuilder<> &Builder);
2767a7e6055SDimitry Andric   bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander);
2777a7e6055SDimitry Andric 
2784ba319b5SDimitry Andric   // If the loop always exits through another block in the loop, we should not
2794ba319b5SDimitry Andric   // predicate based on the latch check. For example, the latch check can be a
2804ba319b5SDimitry Andric   // very coarse grained check and there can be more fine grained exit checks
2814ba319b5SDimitry Andric   // within the loop. We identify such unprofitable loops through BPI.
2824ba319b5SDimitry Andric   bool isLoopProfitableToPredicate();
2834ba319b5SDimitry Andric 
2842cab237bSDimitry Andric   // When the IV type is wider than the range operand type, we can still do loop
2852cab237bSDimitry Andric   // predication, by generating SCEVs for the range and latch that are of the
2862cab237bSDimitry Andric   // same type. We achieve this by generating a SCEV truncate expression for the
2872cab237bSDimitry Andric   // latch IV. This is done iff truncation of the IV is a safe operation,
2882cab237bSDimitry Andric   // without loss of information.
2892cab237bSDimitry Andric   // Another way to achieve this is by generating a wider type SCEV for the
2902cab237bSDimitry Andric   // range check operand, however, this needs a more involved check that
2912cab237bSDimitry Andric   // operands do not overflow. This can lead to loss of information when the
2922cab237bSDimitry Andric   // range operand is of the form: add i32 %offset, %iv. We need to prove that
2932cab237bSDimitry Andric   // sext(x + y) is same as sext(x) + sext(y).
2942cab237bSDimitry Andric   // This function returns true if we can safely represent the IV type in
2952cab237bSDimitry Andric   // the RangeCheckType without loss of information.
2962cab237bSDimitry Andric   bool isSafeToTruncateWideIVType(Type *RangeCheckType);
2972cab237bSDimitry Andric   // Return the loopLatchCheck corresponding to the RangeCheckType if safe to do
2982cab237bSDimitry Andric   // so.
2992cab237bSDimitry Andric   Optional<LoopICmp> generateLoopLatchCheck(Type *RangeCheckType);
3004ba319b5SDimitry Andric 
3017a7e6055SDimitry Andric public:
LoopPredication(ScalarEvolution * SE,BranchProbabilityInfo * BPI)3024ba319b5SDimitry Andric   LoopPredication(ScalarEvolution *SE, BranchProbabilityInfo *BPI)
3034ba319b5SDimitry Andric       : SE(SE), BPI(BPI){};
3047a7e6055SDimitry Andric   bool runOnLoop(Loop *L);
3057a7e6055SDimitry Andric };
3067a7e6055SDimitry Andric 
3077a7e6055SDimitry Andric class LoopPredicationLegacyPass : public LoopPass {
3087a7e6055SDimitry Andric public:
3097a7e6055SDimitry Andric   static char ID;
LoopPredicationLegacyPass()3107a7e6055SDimitry Andric   LoopPredicationLegacyPass() : LoopPass(ID) {
3117a7e6055SDimitry Andric     initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry());
3127a7e6055SDimitry Andric   }
3137a7e6055SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const3147a7e6055SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
3154ba319b5SDimitry Andric     AU.addRequired<BranchProbabilityInfoWrapperPass>();
3167a7e6055SDimitry Andric     getLoopAnalysisUsage(AU);
3177a7e6055SDimitry Andric   }
3187a7e6055SDimitry Andric 
runOnLoop(Loop * L,LPPassManager & LPM)3197a7e6055SDimitry Andric   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
3207a7e6055SDimitry Andric     if (skipLoop(L))
3217a7e6055SDimitry Andric       return false;
3227a7e6055SDimitry Andric     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3234ba319b5SDimitry Andric     BranchProbabilityInfo &BPI =
3244ba319b5SDimitry Andric         getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
3254ba319b5SDimitry Andric     LoopPredication LP(SE, &BPI);
3267a7e6055SDimitry Andric     return LP.runOnLoop(L);
3277a7e6055SDimitry Andric   }
3287a7e6055SDimitry Andric };
3297a7e6055SDimitry Andric 
3307a7e6055SDimitry Andric char LoopPredicationLegacyPass::ID = 0;
3317a7e6055SDimitry Andric } // end namespace llvm
3327a7e6055SDimitry Andric 
3337a7e6055SDimitry Andric INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication",
3347a7e6055SDimitry Andric                       "Loop predication", false, false)
INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)3354ba319b5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
3367a7e6055SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopPass)
3377a7e6055SDimitry Andric INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication",
3387a7e6055SDimitry Andric                     "Loop predication", false, false)
3397a7e6055SDimitry Andric 
3407a7e6055SDimitry Andric Pass *llvm::createLoopPredicationPass() {
3417a7e6055SDimitry Andric   return new LoopPredicationLegacyPass();
3427a7e6055SDimitry Andric }
3437a7e6055SDimitry Andric 
run(Loop & L,LoopAnalysisManager & AM,LoopStandardAnalysisResults & AR,LPMUpdater & U)3447a7e6055SDimitry Andric PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM,
3457a7e6055SDimitry Andric                                            LoopStandardAnalysisResults &AR,
3467a7e6055SDimitry Andric                                            LPMUpdater &U) {
3474ba319b5SDimitry Andric   const auto &FAM =
3484ba319b5SDimitry Andric       AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
3494ba319b5SDimitry Andric   Function *F = L.getHeader()->getParent();
3504ba319b5SDimitry Andric   auto *BPI = FAM.getCachedResult<BranchProbabilityAnalysis>(*F);
3514ba319b5SDimitry Andric   LoopPredication LP(&AR.SE, BPI);
3527a7e6055SDimitry Andric   if (!LP.runOnLoop(&L))
3537a7e6055SDimitry Andric     return PreservedAnalyses::all();
3547a7e6055SDimitry Andric 
3557a7e6055SDimitry Andric   return getLoopPassPreservedAnalyses();
3567a7e6055SDimitry Andric }
3577a7e6055SDimitry Andric 
358d8866befSDimitry Andric Optional<LoopPredication::LoopICmp>
parseLoopICmp(ICmpInst::Predicate Pred,Value * LHS,Value * RHS)3592cab237bSDimitry Andric LoopPredication::parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS,
3602cab237bSDimitry Andric                                Value *RHS) {
3617a7e6055SDimitry Andric   const SCEV *LHSS = SE->getSCEV(LHS);
3627a7e6055SDimitry Andric   if (isa<SCEVCouldNotCompute>(LHSS))
3637a7e6055SDimitry Andric     return None;
3647a7e6055SDimitry Andric   const SCEV *RHSS = SE->getSCEV(RHS);
3657a7e6055SDimitry Andric   if (isa<SCEVCouldNotCompute>(RHSS))
3667a7e6055SDimitry Andric     return None;
3677a7e6055SDimitry Andric 
368d8866befSDimitry Andric   // Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV
3697a7e6055SDimitry Andric   if (SE->isLoopInvariant(LHSS, L)) {
3707a7e6055SDimitry Andric     std::swap(LHS, RHS);
3717a7e6055SDimitry Andric     std::swap(LHSS, RHSS);
3727a7e6055SDimitry Andric     Pred = ICmpInst::getSwappedPredicate(Pred);
3737a7e6055SDimitry Andric   }
374d8866befSDimitry Andric 
375d8866befSDimitry Andric   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS);
376d8866befSDimitry Andric   if (!AR || AR->getLoop() != L)
3777a7e6055SDimitry Andric     return None;
3787a7e6055SDimitry Andric 
379d8866befSDimitry Andric   return LoopICmp(Pred, AR, RHSS);
380d8866befSDimitry Andric }
381d8866befSDimitry Andric 
expandCheck(SCEVExpander & Expander,IRBuilder<> & Builder,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS,Instruction * InsertAt)382d8866befSDimitry Andric Value *LoopPredication::expandCheck(SCEVExpander &Expander,
383d8866befSDimitry Andric                                     IRBuilder<> &Builder,
384d8866befSDimitry Andric                                     ICmpInst::Predicate Pred, const SCEV *LHS,
385d8866befSDimitry Andric                                     const SCEV *RHS, Instruction *InsertAt) {
3862cab237bSDimitry Andric   // TODO: we can check isLoopEntryGuardedByCond before emitting the check
3872cab237bSDimitry Andric 
388d8866befSDimitry Andric   Type *Ty = LHS->getType();
389d8866befSDimitry Andric   assert(Ty == RHS->getType() && "expandCheck operands have different types?");
3902cab237bSDimitry Andric 
3912cab237bSDimitry Andric   if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS))
3922cab237bSDimitry Andric     return Builder.getTrue();
3932cab237bSDimitry Andric 
394d8866befSDimitry Andric   Value *LHSV = Expander.expandCodeFor(LHS, Ty, InsertAt);
395d8866befSDimitry Andric   Value *RHSV = Expander.expandCodeFor(RHS, Ty, InsertAt);
396d8866befSDimitry Andric   return Builder.CreateICmp(Pred, LHSV, RHSV);
397d8866befSDimitry Andric }
398d8866befSDimitry Andric 
3992cab237bSDimitry Andric Optional<LoopPredication::LoopICmp>
generateLoopLatchCheck(Type * RangeCheckType)4002cab237bSDimitry Andric LoopPredication::generateLoopLatchCheck(Type *RangeCheckType) {
4012cab237bSDimitry Andric 
4022cab237bSDimitry Andric   auto *LatchType = LatchCheck.IV->getType();
4032cab237bSDimitry Andric   if (RangeCheckType == LatchType)
4042cab237bSDimitry Andric     return LatchCheck;
4052cab237bSDimitry Andric   // For now, bail out if latch type is narrower than range type.
4062cab237bSDimitry Andric   if (DL->getTypeSizeInBits(LatchType) < DL->getTypeSizeInBits(RangeCheckType))
4072cab237bSDimitry Andric     return None;
4082cab237bSDimitry Andric   if (!isSafeToTruncateWideIVType(RangeCheckType))
4092cab237bSDimitry Andric     return None;
4102cab237bSDimitry Andric   // We can now safely identify the truncated version of the IV and limit for
4112cab237bSDimitry Andric   // RangeCheckType.
4122cab237bSDimitry Andric   LoopICmp NewLatchCheck;
4132cab237bSDimitry Andric   NewLatchCheck.Pred = LatchCheck.Pred;
4142cab237bSDimitry Andric   NewLatchCheck.IV = dyn_cast<SCEVAddRecExpr>(
4152cab237bSDimitry Andric       SE->getTruncateExpr(LatchCheck.IV, RangeCheckType));
4162cab237bSDimitry Andric   if (!NewLatchCheck.IV)
4172cab237bSDimitry Andric     return None;
4182cab237bSDimitry Andric   NewLatchCheck.Limit = SE->getTruncateExpr(LatchCheck.Limit, RangeCheckType);
4194ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "IV of type: " << *LatchType
4204ba319b5SDimitry Andric                     << "can be represented as range check type:"
4214ba319b5SDimitry Andric                     << *RangeCheckType << "\n");
4224ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "LatchCheck.IV: " << *NewLatchCheck.IV << "\n");
4234ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "LatchCheck.Limit: " << *NewLatchCheck.Limit << "\n");
4242cab237bSDimitry Andric   return NewLatchCheck;
4252cab237bSDimitry Andric }
4262cab237bSDimitry Andric 
isSupportedStep(const SCEV * Step)4272cab237bSDimitry Andric bool LoopPredication::isSupportedStep(const SCEV* Step) {
4282cab237bSDimitry Andric   return Step->isOne() || (Step->isAllOnesValue() && EnableCountDownLoop);
4292cab237bSDimitry Andric }
4302cab237bSDimitry Andric 
CanExpand(const SCEV * S)4312cab237bSDimitry Andric bool LoopPredication::CanExpand(const SCEV* S) {
4322cab237bSDimitry Andric   return SE->isLoopInvariant(S, L) && isSafeToExpand(S, *SE);
4332cab237bSDimitry Andric }
4342cab237bSDimitry Andric 
widenICmpRangeCheckIncrementingLoop(LoopPredication::LoopICmp LatchCheck,LoopPredication::LoopICmp RangeCheck,SCEVExpander & Expander,IRBuilder<> & Builder)4352cab237bSDimitry Andric Optional<Value *> LoopPredication::widenICmpRangeCheckIncrementingLoop(
4362cab237bSDimitry Andric     LoopPredication::LoopICmp LatchCheck, LoopPredication::LoopICmp RangeCheck,
4372cab237bSDimitry Andric     SCEVExpander &Expander, IRBuilder<> &Builder) {
4382cab237bSDimitry Andric   auto *Ty = RangeCheck.IV->getType();
4392cab237bSDimitry Andric   // Generate the widened condition for the forward loop:
4402cab237bSDimitry Andric   //   guardStart u< guardLimit &&
4412cab237bSDimitry Andric   //   latchLimit <pred> guardLimit - 1 - guardStart + latchStart
4422cab237bSDimitry Andric   // where <pred> depends on the latch condition predicate. See the file
4432cab237bSDimitry Andric   // header comment for the reasoning.
4442cab237bSDimitry Andric   // guardLimit - guardStart + latchStart - 1
4452cab237bSDimitry Andric   const SCEV *GuardStart = RangeCheck.IV->getStart();
4462cab237bSDimitry Andric   const SCEV *GuardLimit = RangeCheck.Limit;
4472cab237bSDimitry Andric   const SCEV *LatchStart = LatchCheck.IV->getStart();
4482cab237bSDimitry Andric   const SCEV *LatchLimit = LatchCheck.Limit;
4492cab237bSDimitry Andric 
4502cab237bSDimitry Andric   // guardLimit - guardStart + latchStart - 1
4512cab237bSDimitry Andric   const SCEV *RHS =
4522cab237bSDimitry Andric       SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart),
4532cab237bSDimitry Andric                      SE->getMinusSCEV(LatchStart, SE->getOne(Ty)));
4542cab237bSDimitry Andric   if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) ||
4552cab237bSDimitry Andric       !CanExpand(LatchLimit) || !CanExpand(RHS)) {
4564ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
4572cab237bSDimitry Andric     return None;
4582cab237bSDimitry Andric   }
4594ba319b5SDimitry Andric   auto LimitCheckPred =
4604ba319b5SDimitry Andric       ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred);
4612cab237bSDimitry Andric 
4624ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n");
4634ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "RHS: " << *RHS << "\n");
4644ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n");
4652cab237bSDimitry Andric 
4662cab237bSDimitry Andric   Instruction *InsertAt = Preheader->getTerminator();
4672cab237bSDimitry Andric   auto *LimitCheck =
4682cab237bSDimitry Andric       expandCheck(Expander, Builder, LimitCheckPred, LatchLimit, RHS, InsertAt);
4692cab237bSDimitry Andric   auto *FirstIterationCheck = expandCheck(Expander, Builder, RangeCheck.Pred,
4702cab237bSDimitry Andric                                           GuardStart, GuardLimit, InsertAt);
4712cab237bSDimitry Andric   return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
4722cab237bSDimitry Andric }
4732cab237bSDimitry Andric 
widenICmpRangeCheckDecrementingLoop(LoopPredication::LoopICmp LatchCheck,LoopPredication::LoopICmp RangeCheck,SCEVExpander & Expander,IRBuilder<> & Builder)4742cab237bSDimitry Andric Optional<Value *> LoopPredication::widenICmpRangeCheckDecrementingLoop(
4752cab237bSDimitry Andric     LoopPredication::LoopICmp LatchCheck, LoopPredication::LoopICmp RangeCheck,
4762cab237bSDimitry Andric     SCEVExpander &Expander, IRBuilder<> &Builder) {
4772cab237bSDimitry Andric   auto *Ty = RangeCheck.IV->getType();
4782cab237bSDimitry Andric   const SCEV *GuardStart = RangeCheck.IV->getStart();
4792cab237bSDimitry Andric   const SCEV *GuardLimit = RangeCheck.Limit;
4802cab237bSDimitry Andric   const SCEV *LatchLimit = LatchCheck.Limit;
4812cab237bSDimitry Andric   if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) ||
4822cab237bSDimitry Andric       !CanExpand(LatchLimit)) {
4834ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
4842cab237bSDimitry Andric     return None;
4852cab237bSDimitry Andric   }
4862cab237bSDimitry Andric   // The decrement of the latch check IV should be the same as the
4872cab237bSDimitry Andric   // rangeCheckIV.
4882cab237bSDimitry Andric   auto *PostDecLatchCheckIV = LatchCheck.IV->getPostIncExpr(*SE);
4892cab237bSDimitry Andric   if (RangeCheck.IV != PostDecLatchCheckIV) {
4904ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Not the same. PostDecLatchCheckIV: "
4912cab237bSDimitry Andric                       << *PostDecLatchCheckIV
4922cab237bSDimitry Andric                       << "  and RangeCheckIV: " << *RangeCheck.IV << "\n");
4932cab237bSDimitry Andric     return None;
4942cab237bSDimitry Andric   }
4952cab237bSDimitry Andric 
4962cab237bSDimitry Andric   // Generate the widened condition for CountDownLoop:
4972cab237bSDimitry Andric   // guardStart u< guardLimit &&
4982cab237bSDimitry Andric   // latchLimit <pred> 1.
4992cab237bSDimitry Andric   // See the header comment for reasoning of the checks.
5002cab237bSDimitry Andric   Instruction *InsertAt = Preheader->getTerminator();
5014ba319b5SDimitry Andric   auto LimitCheckPred =
5024ba319b5SDimitry Andric       ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred);
5032cab237bSDimitry Andric   auto *FirstIterationCheck = expandCheck(Expander, Builder, ICmpInst::ICMP_ULT,
5042cab237bSDimitry Andric                                           GuardStart, GuardLimit, InsertAt);
5052cab237bSDimitry Andric   auto *LimitCheck = expandCheck(Expander, Builder, LimitCheckPred, LatchLimit,
5062cab237bSDimitry Andric                                  SE->getOne(Ty), InsertAt);
5072cab237bSDimitry Andric   return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
5082cab237bSDimitry Andric }
5092cab237bSDimitry Andric 
510d8866befSDimitry Andric /// If ICI can be widened to a loop invariant condition emits the loop
511d8866befSDimitry Andric /// invariant condition in the loop preheader and return it, otherwise
512d8866befSDimitry Andric /// returns None.
widenICmpRangeCheck(ICmpInst * ICI,SCEVExpander & Expander,IRBuilder<> & Builder)513d8866befSDimitry Andric Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI,
514d8866befSDimitry Andric                                                        SCEVExpander &Expander,
515d8866befSDimitry Andric                                                        IRBuilder<> &Builder) {
5164ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Analyzing ICmpInst condition:\n");
5174ba319b5SDimitry Andric   LLVM_DEBUG(ICI->dump());
518d8866befSDimitry Andric 
5192cab237bSDimitry Andric   // parseLoopStructure guarantees that the latch condition is:
5202cab237bSDimitry Andric   //   ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=.
5212cab237bSDimitry Andric   // We are looking for the range checks of the form:
5222cab237bSDimitry Andric   //   i u< guardLimit
523d8866befSDimitry Andric   auto RangeCheck = parseLoopICmp(ICI);
524d8866befSDimitry Andric   if (!RangeCheck) {
5254ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
526d8866befSDimitry Andric     return None;
527d8866befSDimitry Andric   }
5284ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Guard check:\n");
5294ba319b5SDimitry Andric   LLVM_DEBUG(RangeCheck->dump());
5302cab237bSDimitry Andric   if (RangeCheck->Pred != ICmpInst::ICMP_ULT) {
5314ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Unsupported range check predicate("
5324ba319b5SDimitry Andric                       << RangeCheck->Pred << ")!\n");
5337a7e6055SDimitry Andric     return None;
5342cab237bSDimitry Andric   }
5352cab237bSDimitry Andric   auto *RangeCheckIV = RangeCheck->IV;
5362cab237bSDimitry Andric   if (!RangeCheckIV->isAffine()) {
5374ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Range check IV is not affine!\n");
5387a7e6055SDimitry Andric     return None;
5392cab237bSDimitry Andric   }
5402cab237bSDimitry Andric   auto *Step = RangeCheckIV->getStepRecurrence(*SE);
5412cab237bSDimitry Andric   // We cannot just compare with latch IV step because the latch and range IVs
5422cab237bSDimitry Andric   // may have different types.
5432cab237bSDimitry Andric   if (!isSupportedStep(Step)) {
5444ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Range check and latch have IVs different steps!\n");
5452cab237bSDimitry Andric     return None;
5462cab237bSDimitry Andric   }
5472cab237bSDimitry Andric   auto *Ty = RangeCheckIV->getType();
5482cab237bSDimitry Andric   auto CurrLatchCheckOpt = generateLoopLatchCheck(Ty);
5492cab237bSDimitry Andric   if (!CurrLatchCheckOpt) {
5504ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Failed to generate a loop latch check "
5512cab237bSDimitry Andric                          "corresponding to range type: "
5522cab237bSDimitry Andric                       << *Ty << "\n");
5537a7e6055SDimitry Andric     return None;
5547a7e6055SDimitry Andric   }
5557a7e6055SDimitry Andric 
5562cab237bSDimitry Andric   LoopICmp CurrLatchCheck = *CurrLatchCheckOpt;
5572cab237bSDimitry Andric   // At this point, the range and latch step should have the same type, but need
5582cab237bSDimitry Andric   // not have the same value (we support both 1 and -1 steps).
5592cab237bSDimitry Andric   assert(Step->getType() ==
5602cab237bSDimitry Andric              CurrLatchCheck.IV->getStepRecurrence(*SE)->getType() &&
5612cab237bSDimitry Andric          "Range and latch steps should be of same type!");
5622cab237bSDimitry Andric   if (Step != CurrLatchCheck.IV->getStepRecurrence(*SE)) {
5634ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Range and latch have different step values!\n");
5647a7e6055SDimitry Andric     return None;
5652cab237bSDimitry Andric   }
5667a7e6055SDimitry Andric 
5672cab237bSDimitry Andric   if (Step->isOne())
5682cab237bSDimitry Andric     return widenICmpRangeCheckIncrementingLoop(CurrLatchCheck, *RangeCheck,
5692cab237bSDimitry Andric                                                Expander, Builder);
5702cab237bSDimitry Andric   else {
5712cab237bSDimitry Andric     assert(Step->isAllOnesValue() && "Step should be -1!");
5722cab237bSDimitry Andric     return widenICmpRangeCheckDecrementingLoop(CurrLatchCheck, *RangeCheck,
5732cab237bSDimitry Andric                                                Expander, Builder);
5742cab237bSDimitry Andric   }
5757a7e6055SDimitry Andric }
5767a7e6055SDimitry Andric 
widenGuardConditions(IntrinsicInst * Guard,SCEVExpander & Expander)5777a7e6055SDimitry Andric bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard,
5787a7e6055SDimitry Andric                                            SCEVExpander &Expander) {
5794ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Processing guard:\n");
5804ba319b5SDimitry Andric   LLVM_DEBUG(Guard->dump());
5817a7e6055SDimitry Andric 
582*b5893f02SDimitry Andric   TotalConsidered++;
583*b5893f02SDimitry Andric 
5847a7e6055SDimitry Andric   IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator()));
5857a7e6055SDimitry Andric 
5867a7e6055SDimitry Andric   // The guard condition is expected to be in form of:
5877a7e6055SDimitry Andric   //   cond1 && cond2 && cond3 ...
5884ba319b5SDimitry Andric   // Iterate over subconditions looking for icmp conditions which can be
5897a7e6055SDimitry Andric   // widened across loop iterations. Widening these conditions remember the
5907a7e6055SDimitry Andric   // resulting list of subconditions in Checks vector.
5917a7e6055SDimitry Andric   SmallVector<Value *, 4> Worklist(1, Guard->getOperand(0));
5927a7e6055SDimitry Andric   SmallPtrSet<Value *, 4> Visited;
5937a7e6055SDimitry Andric 
5947a7e6055SDimitry Andric   SmallVector<Value *, 4> Checks;
5957a7e6055SDimitry Andric 
5967a7e6055SDimitry Andric   unsigned NumWidened = 0;
5977a7e6055SDimitry Andric   do {
5987a7e6055SDimitry Andric     Value *Condition = Worklist.pop_back_val();
5997a7e6055SDimitry Andric     if (!Visited.insert(Condition).second)
6007a7e6055SDimitry Andric       continue;
6017a7e6055SDimitry Andric 
6027a7e6055SDimitry Andric     Value *LHS, *RHS;
6037a7e6055SDimitry Andric     using namespace llvm::PatternMatch;
6047a7e6055SDimitry Andric     if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) {
6057a7e6055SDimitry Andric       Worklist.push_back(LHS);
6067a7e6055SDimitry Andric       Worklist.push_back(RHS);
6077a7e6055SDimitry Andric       continue;
6087a7e6055SDimitry Andric     }
6097a7e6055SDimitry Andric 
6107a7e6055SDimitry Andric     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
6117a7e6055SDimitry Andric       if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, Builder)) {
6127a7e6055SDimitry Andric         Checks.push_back(NewRangeCheck.getValue());
6137a7e6055SDimitry Andric         NumWidened++;
6147a7e6055SDimitry Andric         continue;
6157a7e6055SDimitry Andric       }
6167a7e6055SDimitry Andric     }
6177a7e6055SDimitry Andric 
6187a7e6055SDimitry Andric     // Save the condition as is if we can't widen it
6197a7e6055SDimitry Andric     Checks.push_back(Condition);
6207a7e6055SDimitry Andric   } while (Worklist.size() != 0);
6217a7e6055SDimitry Andric 
6227a7e6055SDimitry Andric   if (NumWidened == 0)
6237a7e6055SDimitry Andric     return false;
6247a7e6055SDimitry Andric 
625*b5893f02SDimitry Andric   TotalWidened += NumWidened;
626*b5893f02SDimitry Andric 
6277a7e6055SDimitry Andric   // Emit the new guard condition
6287a7e6055SDimitry Andric   Builder.SetInsertPoint(Guard);
6297a7e6055SDimitry Andric   Value *LastCheck = nullptr;
6307a7e6055SDimitry Andric   for (auto *Check : Checks)
6317a7e6055SDimitry Andric     if (!LastCheck)
6327a7e6055SDimitry Andric       LastCheck = Check;
6337a7e6055SDimitry Andric     else
6347a7e6055SDimitry Andric       LastCheck = Builder.CreateAnd(LastCheck, Check);
6357a7e6055SDimitry Andric   Guard->setOperand(0, LastCheck);
6367a7e6055SDimitry Andric 
6374ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
6387a7e6055SDimitry Andric   return true;
6397a7e6055SDimitry Andric }
6407a7e6055SDimitry Andric 
parseLoopLatchICmp()6412cab237bSDimitry Andric Optional<LoopPredication::LoopICmp> LoopPredication::parseLoopLatchICmp() {
6422cab237bSDimitry Andric   using namespace PatternMatch;
6432cab237bSDimitry Andric 
6442cab237bSDimitry Andric   BasicBlock *LoopLatch = L->getLoopLatch();
6452cab237bSDimitry Andric   if (!LoopLatch) {
6464ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "The loop doesn't have a single latch!\n");
6472cab237bSDimitry Andric     return None;
6482cab237bSDimitry Andric   }
6492cab237bSDimitry Andric 
6502cab237bSDimitry Andric   ICmpInst::Predicate Pred;
6512cab237bSDimitry Andric   Value *LHS, *RHS;
6522cab237bSDimitry Andric   BasicBlock *TrueDest, *FalseDest;
6532cab237bSDimitry Andric 
6542cab237bSDimitry Andric   if (!match(LoopLatch->getTerminator(),
6552cab237bSDimitry Andric              m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TrueDest,
6562cab237bSDimitry Andric                   FalseDest))) {
6574ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Failed to match the latch terminator!\n");
6582cab237bSDimitry Andric     return None;
6592cab237bSDimitry Andric   }
6602cab237bSDimitry Andric   assert((TrueDest == L->getHeader() || FalseDest == L->getHeader()) &&
6612cab237bSDimitry Andric          "One of the latch's destinations must be the header");
6622cab237bSDimitry Andric   if (TrueDest != L->getHeader())
6632cab237bSDimitry Andric     Pred = ICmpInst::getInversePredicate(Pred);
6642cab237bSDimitry Andric 
6652cab237bSDimitry Andric   auto Result = parseLoopICmp(Pred, LHS, RHS);
6662cab237bSDimitry Andric   if (!Result) {
6674ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
6682cab237bSDimitry Andric     return None;
6692cab237bSDimitry Andric   }
6702cab237bSDimitry Andric 
6712cab237bSDimitry Andric   // Check affine first, so if it's not we don't try to compute the step
6722cab237bSDimitry Andric   // recurrence.
6732cab237bSDimitry Andric   if (!Result->IV->isAffine()) {
6744ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "The induction variable is not affine!\n");
6752cab237bSDimitry Andric     return None;
6762cab237bSDimitry Andric   }
6772cab237bSDimitry Andric 
6782cab237bSDimitry Andric   auto *Step = Result->IV->getStepRecurrence(*SE);
6792cab237bSDimitry Andric   if (!isSupportedStep(Step)) {
6804ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n");
6812cab237bSDimitry Andric     return None;
6822cab237bSDimitry Andric   }
6832cab237bSDimitry Andric 
6842cab237bSDimitry Andric   auto IsUnsupportedPredicate = [](const SCEV *Step, ICmpInst::Predicate Pred) {
6852cab237bSDimitry Andric     if (Step->isOne()) {
6862cab237bSDimitry Andric       return Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_SLT &&
6872cab237bSDimitry Andric              Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_SLE;
6882cab237bSDimitry Andric     } else {
6892cab237bSDimitry Andric       assert(Step->isAllOnesValue() && "Step should be -1!");
6904ba319b5SDimitry Andric       return Pred != ICmpInst::ICMP_UGT && Pred != ICmpInst::ICMP_SGT &&
6914ba319b5SDimitry Andric              Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE;
6922cab237bSDimitry Andric     }
6932cab237bSDimitry Andric   };
6942cab237bSDimitry Andric 
6952cab237bSDimitry Andric   if (IsUnsupportedPredicate(Step, Result->Pred)) {
6964ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred
6972cab237bSDimitry Andric                       << ")!\n");
6982cab237bSDimitry Andric     return None;
6992cab237bSDimitry Andric   }
7002cab237bSDimitry Andric   return Result;
7012cab237bSDimitry Andric }
7022cab237bSDimitry Andric 
7032cab237bSDimitry Andric // Returns true if its safe to truncate the IV to RangeCheckType.
isSafeToTruncateWideIVType(Type * RangeCheckType)7042cab237bSDimitry Andric bool LoopPredication::isSafeToTruncateWideIVType(Type *RangeCheckType) {
7052cab237bSDimitry Andric   if (!EnableIVTruncation)
7062cab237bSDimitry Andric     return false;
7072cab237bSDimitry Andric   assert(DL->getTypeSizeInBits(LatchCheck.IV->getType()) >
7082cab237bSDimitry Andric              DL->getTypeSizeInBits(RangeCheckType) &&
7092cab237bSDimitry Andric          "Expected latch check IV type to be larger than range check operand "
7102cab237bSDimitry Andric          "type!");
7112cab237bSDimitry Andric   // The start and end values of the IV should be known. This is to guarantee
7122cab237bSDimitry Andric   // that truncating the wide type will not lose information.
7132cab237bSDimitry Andric   auto *Limit = dyn_cast<SCEVConstant>(LatchCheck.Limit);
7142cab237bSDimitry Andric   auto *Start = dyn_cast<SCEVConstant>(LatchCheck.IV->getStart());
7152cab237bSDimitry Andric   if (!Limit || !Start)
7162cab237bSDimitry Andric     return false;
7172cab237bSDimitry Andric   // This check makes sure that the IV does not change sign during loop
7182cab237bSDimitry Andric   // iterations. Consider latchType = i64, LatchStart = 5, Pred = ICMP_SGE,
7192cab237bSDimitry Andric   // LatchEnd = 2, rangeCheckType = i32. If it's not a monotonic predicate, the
7202cab237bSDimitry Andric   // IV wraps around, and the truncation of the IV would lose the range of
7212cab237bSDimitry Andric   // iterations between 2^32 and 2^64.
7222cab237bSDimitry Andric   bool Increasing;
7232cab237bSDimitry Andric   if (!SE->isMonotonicPredicate(LatchCheck.IV, LatchCheck.Pred, Increasing))
7242cab237bSDimitry Andric     return false;
7252cab237bSDimitry Andric   // The active bits should be less than the bits in the RangeCheckType. This
7262cab237bSDimitry Andric   // guarantees that truncating the latch check to RangeCheckType is a safe
7272cab237bSDimitry Andric   // operation.
7282cab237bSDimitry Andric   auto RangeCheckTypeBitSize = DL->getTypeSizeInBits(RangeCheckType);
7292cab237bSDimitry Andric   return Start->getAPInt().getActiveBits() < RangeCheckTypeBitSize &&
7302cab237bSDimitry Andric          Limit->getAPInt().getActiveBits() < RangeCheckTypeBitSize;
7312cab237bSDimitry Andric }
7322cab237bSDimitry Andric 
isLoopProfitableToPredicate()7334ba319b5SDimitry Andric bool LoopPredication::isLoopProfitableToPredicate() {
7344ba319b5SDimitry Andric   if (SkipProfitabilityChecks || !BPI)
7354ba319b5SDimitry Andric     return true;
7364ba319b5SDimitry Andric 
7374ba319b5SDimitry Andric   SmallVector<std::pair<const BasicBlock *, const BasicBlock *>, 8> ExitEdges;
7384ba319b5SDimitry Andric   L->getExitEdges(ExitEdges);
7394ba319b5SDimitry Andric   // If there is only one exiting edge in the loop, it is always profitable to
7404ba319b5SDimitry Andric   // predicate the loop.
7414ba319b5SDimitry Andric   if (ExitEdges.size() == 1)
7424ba319b5SDimitry Andric     return true;
7434ba319b5SDimitry Andric 
7444ba319b5SDimitry Andric   // Calculate the exiting probabilities of all exiting edges from the loop,
7454ba319b5SDimitry Andric   // starting with the LatchExitProbability.
7464ba319b5SDimitry Andric   // Heuristic for profitability: If any of the exiting blocks' probability of
7474ba319b5SDimitry Andric   // exiting the loop is larger than exiting through the latch block, it's not
7484ba319b5SDimitry Andric   // profitable to predicate the loop.
7494ba319b5SDimitry Andric   auto *LatchBlock = L->getLoopLatch();
7504ba319b5SDimitry Andric   assert(LatchBlock && "Should have a single latch at this point!");
7514ba319b5SDimitry Andric   auto *LatchTerm = LatchBlock->getTerminator();
7524ba319b5SDimitry Andric   assert(LatchTerm->getNumSuccessors() == 2 &&
7534ba319b5SDimitry Andric          "expected to be an exiting block with 2 succs!");
7544ba319b5SDimitry Andric   unsigned LatchBrExitIdx =
7554ba319b5SDimitry Andric       LatchTerm->getSuccessor(0) == L->getHeader() ? 1 : 0;
7564ba319b5SDimitry Andric   BranchProbability LatchExitProbability =
7574ba319b5SDimitry Andric       BPI->getEdgeProbability(LatchBlock, LatchBrExitIdx);
7584ba319b5SDimitry Andric 
7594ba319b5SDimitry Andric   // Protect against degenerate inputs provided by the user. Providing a value
7604ba319b5SDimitry Andric   // less than one, can invert the definition of profitable loop predication.
7614ba319b5SDimitry Andric   float ScaleFactor = LatchExitProbabilityScale;
7624ba319b5SDimitry Andric   if (ScaleFactor < 1) {
7634ba319b5SDimitry Andric     LLVM_DEBUG(
7644ba319b5SDimitry Andric         dbgs()
7654ba319b5SDimitry Andric         << "Ignored user setting for loop-predication-latch-probability-scale: "
7664ba319b5SDimitry Andric         << LatchExitProbabilityScale << "\n");
7674ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "The value is set to 1.0\n");
7684ba319b5SDimitry Andric     ScaleFactor = 1.0;
7694ba319b5SDimitry Andric   }
7704ba319b5SDimitry Andric   const auto LatchProbabilityThreshold =
7714ba319b5SDimitry Andric       LatchExitProbability * ScaleFactor;
7724ba319b5SDimitry Andric 
7734ba319b5SDimitry Andric   for (const auto &ExitEdge : ExitEdges) {
7744ba319b5SDimitry Andric     BranchProbability ExitingBlockProbability =
7754ba319b5SDimitry Andric         BPI->getEdgeProbability(ExitEdge.first, ExitEdge.second);
7764ba319b5SDimitry Andric     // Some exiting edge has higher probability than the latch exiting edge.
7774ba319b5SDimitry Andric     // No longer profitable to predicate.
7784ba319b5SDimitry Andric     if (ExitingBlockProbability > LatchProbabilityThreshold)
7794ba319b5SDimitry Andric       return false;
7804ba319b5SDimitry Andric   }
7814ba319b5SDimitry Andric   // Using BPI, we have concluded that the most probable way to exit from the
7824ba319b5SDimitry Andric   // loop is through the latch (or there's no profile information and all
7834ba319b5SDimitry Andric   // exits are equally likely).
7844ba319b5SDimitry Andric   return true;
7854ba319b5SDimitry Andric }
7864ba319b5SDimitry Andric 
runOnLoop(Loop * Loop)7877a7e6055SDimitry Andric bool LoopPredication::runOnLoop(Loop *Loop) {
7887a7e6055SDimitry Andric   L = Loop;
7897a7e6055SDimitry Andric 
7904ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Analyzing ");
7914ba319b5SDimitry Andric   LLVM_DEBUG(L->dump());
7927a7e6055SDimitry Andric 
7937a7e6055SDimitry Andric   Module *M = L->getHeader()->getModule();
7947a7e6055SDimitry Andric 
7957a7e6055SDimitry Andric   // There is nothing to do if the module doesn't use guards
7967a7e6055SDimitry Andric   auto *GuardDecl =
7977a7e6055SDimitry Andric       M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard));
7987a7e6055SDimitry Andric   if (!GuardDecl || GuardDecl->use_empty())
7997a7e6055SDimitry Andric     return false;
8007a7e6055SDimitry Andric 
8017a7e6055SDimitry Andric   DL = &M->getDataLayout();
8027a7e6055SDimitry Andric 
8037a7e6055SDimitry Andric   Preheader = L->getLoopPreheader();
8047a7e6055SDimitry Andric   if (!Preheader)
8057a7e6055SDimitry Andric     return false;
8067a7e6055SDimitry Andric 
8072cab237bSDimitry Andric   auto LatchCheckOpt = parseLoopLatchICmp();
8082cab237bSDimitry Andric   if (!LatchCheckOpt)
8092cab237bSDimitry Andric     return false;
8102cab237bSDimitry Andric   LatchCheck = *LatchCheckOpt;
8112cab237bSDimitry Andric 
8124ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Latch check:\n");
8134ba319b5SDimitry Andric   LLVM_DEBUG(LatchCheck.dump());
8142cab237bSDimitry Andric 
8154ba319b5SDimitry Andric   if (!isLoopProfitableToPredicate()) {
8164ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Loop not profitable to predicate!\n");
8174ba319b5SDimitry Andric     return false;
8184ba319b5SDimitry Andric   }
8197a7e6055SDimitry Andric   // Collect all the guards into a vector and process later, so as not
8207a7e6055SDimitry Andric   // to invalidate the instruction iterator.
8217a7e6055SDimitry Andric   SmallVector<IntrinsicInst *, 4> Guards;
8227a7e6055SDimitry Andric   for (const auto BB : L->blocks())
8237a7e6055SDimitry Andric     for (auto &I : *BB)
824*b5893f02SDimitry Andric       if (isGuard(&I))
825*b5893f02SDimitry Andric         Guards.push_back(cast<IntrinsicInst>(&I));
8267a7e6055SDimitry Andric 
827d8866befSDimitry Andric   if (Guards.empty())
828d8866befSDimitry Andric     return false;
829d8866befSDimitry Andric 
8307a7e6055SDimitry Andric   SCEVExpander Expander(*SE, *DL, "loop-predication");
8317a7e6055SDimitry Andric 
8327a7e6055SDimitry Andric   bool Changed = false;
8337a7e6055SDimitry Andric   for (auto *Guard : Guards)
8347a7e6055SDimitry Andric     Changed |= widenGuardConditions(Guard, Expander);
8357a7e6055SDimitry Andric 
8367a7e6055SDimitry Andric   return Changed;
8377a7e6055SDimitry Andric }
838