xref: /llvm-project/llvm/lib/Transforms/Scalar/LoopPredication.cpp (revision e46d77d1d91eb498e261799df24bfd564e0c140b)
1 //===-- LoopPredication.cpp - Guard based loop predication pass -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // The LoopPredication pass tries to convert loop variant range checks to loop
10 // invariant by widening checks across loop iterations. For example, it will
11 // convert
12 //
13 //   for (i = 0; i < n; i++) {
14 //     guard(i < len);
15 //     ...
16 //   }
17 //
18 // to
19 //
20 //   for (i = 0; i < n; i++) {
21 //     guard(n - 1 < len);
22 //     ...
23 //   }
24 //
25 // After this transformation the condition of the guard is loop invariant, so
26 // loop-unswitch can later unswitch the loop by this condition which basically
27 // predicates the loop by the widened condition:
28 //
29 //   if (n - 1 < len)
30 //     for (i = 0; i < n; i++) {
31 //       ...
32 //     }
33 //   else
34 //     deoptimize
35 //
36 // It's tempting to rely on SCEV here, but it has proven to be problematic.
37 // Generally the facts SCEV provides about the increment step of add
38 // recurrences are true if the backedge of the loop is taken, which implicitly
39 // assumes that the guard doesn't fail. Using these facts to optimize the
40 // guard results in a circular logic where the guard is optimized under the
41 // assumption that it never fails.
42 //
43 // For example, in the loop below the induction variable will be marked as nuw
44 // basing on the guard. Basing on nuw the guard predicate will be considered
45 // monotonic. Given a monotonic condition it's tempting to replace the induction
46 // variable in the condition with its value on the last iteration. But this
47 // transformation is not correct, e.g. e = 4, b = 5 breaks the loop.
48 //
49 //   for (int i = b; i != e; i++)
50 //     guard(i u< len)
51 //
52 // One of the ways to reason about this problem is to use an inductive proof
53 // approach. Given the loop:
54 //
55 //   if (B(0)) {
56 //     do {
57 //       I = PHI(0, I.INC)
58 //       I.INC = I + Step
59 //       guard(G(I));
60 //     } while (B(I));
61 //   }
62 //
63 // where B(x) and G(x) are predicates that map integers to booleans, we want a
64 // loop invariant expression M such the following program has the same semantics
65 // as the above:
66 //
67 //   if (B(0)) {
68 //     do {
69 //       I = PHI(0, I.INC)
70 //       I.INC = I + Step
71 //       guard(G(0) && M);
72 //     } while (B(I));
73 //   }
74 //
75 // One solution for M is M = forall X . (G(X) && B(X)) => G(X + Step)
76 //
77 // Informal proof that the transformation above is correct:
78 //
79 //   By the definition of guards we can rewrite the guard condition to:
80 //     G(I) && G(0) && M
81 //
82 //   Let's prove that for each iteration of the loop:
83 //     G(0) && M => G(I)
84 //   And the condition above can be simplified to G(Start) && M.
85 //
86 //   Induction base.
87 //     G(0) && M => G(0)
88 //
89 //   Induction step. Assuming G(0) && M => G(I) on the subsequent
90 //   iteration:
91 //
92 //     B(I) is true because it's the backedge condition.
93 //     G(I) is true because the backedge is guarded by this condition.
94 //
95 //   So M = forall X . (G(X) && B(X)) => G(X + Step) implies G(I + Step).
96 //
97 // Note that we can use anything stronger than M, i.e. any condition which
98 // implies M.
99 //
100 // When S = 1 (i.e. forward iterating loop), the transformation is supported
101 // when:
102 //   * The loop has a single latch with the condition of the form:
103 //     B(X) = latchStart + X <pred> latchLimit,
104 //     where <pred> is u<, u<=, s<, or s<=.
105 //   * The guard condition is of the form
106 //     G(X) = guardStart + X u< guardLimit
107 //
108 //   For the ult latch comparison case M is:
109 //     forall X . guardStart + X u< guardLimit && latchStart + X <u latchLimit =>
110 //        guardStart + X + 1 u< guardLimit
111 //
112 //   The only way the antecedent can be true and the consequent can be false is
113 //   if
114 //     X == guardLimit - 1 - guardStart
115 //   (and guardLimit is non-zero, but we won't use this latter fact).
116 //   If X == guardLimit - 1 - guardStart then the second half of the antecedent is
117 //     latchStart + guardLimit - 1 - guardStart u< latchLimit
118 //   and its negation is
119 //     latchStart + guardLimit - 1 - guardStart u>= latchLimit
120 //
121 //   In other words, if
122 //     latchLimit u<= latchStart + guardLimit - 1 - guardStart
123 //   then:
124 //   (the ranges below are written in ConstantRange notation, where [A, B) is the
125 //   set for (I = A; I != B; I++ /*maywrap*/) yield(I);)
126 //
127 //      forall X . guardStart + X u< guardLimit &&
128 //                 latchStart + X u< latchLimit =>
129 //        guardStart + X + 1 u< guardLimit
130 //   == forall X . guardStart + X u< guardLimit &&
131 //                 latchStart + X u< latchStart + guardLimit - 1 - guardStart =>
132 //        guardStart + X + 1 u< guardLimit
133 //   == forall X . (guardStart + X) in [0, guardLimit) &&
134 //                 (latchStart + X) in [0, latchStart + guardLimit - 1 - guardStart) =>
135 //        (guardStart + X + 1) in [0, guardLimit)
136 //   == forall X . X in [-guardStart, guardLimit - guardStart) &&
137 //                 X in [-latchStart, guardLimit - 1 - guardStart) =>
138 //         X in [-guardStart - 1, guardLimit - guardStart - 1)
139 //   == true
140 //
141 //   So the widened condition is:
142 //     guardStart u< guardLimit &&
143 //     latchStart + guardLimit - 1 - guardStart u>= latchLimit
144 //   Similarly for ule condition the widened condition is:
145 //     guardStart u< guardLimit &&
146 //     latchStart + guardLimit - 1 - guardStart u> latchLimit
147 //   For slt condition the widened condition is:
148 //     guardStart u< guardLimit &&
149 //     latchStart + guardLimit - 1 - guardStart s>= latchLimit
150 //   For sle condition the widened condition is:
151 //     guardStart u< guardLimit &&
152 //     latchStart + guardLimit - 1 - guardStart s> latchLimit
153 //
154 // When S = -1 (i.e. reverse iterating loop), the transformation is supported
155 // when:
156 //   * The loop has a single latch with the condition of the form:
157 //     B(X) = X <pred> latchLimit, where <pred> is u>, u>=, s>, or s>=.
158 //   * The guard condition is of the form
159 //     G(X) = X - 1 u< guardLimit
160 //
161 //   For the ugt latch comparison case M is:
162 //     forall X. X-1 u< guardLimit and X u> latchLimit => X-2 u< guardLimit
163 //
164 //   The only way the antecedent can be true and the consequent can be false is if
165 //     X == 1.
166 //   If X == 1 then the second half of the antecedent is
167 //     1 u> latchLimit, and its negation is latchLimit u>= 1.
168 //
169 //   So the widened condition is:
170 //     guardStart u< guardLimit && latchLimit u>= 1.
171 //   Similarly for sgt condition the widened condition is:
172 //     guardStart u< guardLimit && latchLimit s>= 1.
173 //   For uge condition the widened condition is:
174 //     guardStart u< guardLimit && latchLimit u> 1.
175 //   For sge condition the widened condition is:
176 //     guardStart u< guardLimit && latchLimit s> 1.
177 //===----------------------------------------------------------------------===//
178 
179 #include "llvm/Transforms/Scalar/LoopPredication.h"
180 #include "llvm/ADT/Statistic.h"
181 #include "llvm/Analysis/BranchProbabilityInfo.h"
182 #include "llvm/Analysis/GuardUtils.h"
183 #include "llvm/Analysis/LoopInfo.h"
184 #include "llvm/Analysis/LoopPass.h"
185 #include "llvm/Analysis/ScalarEvolution.h"
186 #include "llvm/Analysis/ScalarEvolutionExpander.h"
187 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
188 #include "llvm/IR/Function.h"
189 #include "llvm/IR/GlobalValue.h"
190 #include "llvm/IR/IntrinsicInst.h"
191 #include "llvm/IR/Module.h"
192 #include "llvm/IR/PatternMatch.h"
193 #include "llvm/Pass.h"
194 #include "llvm/Support/Debug.h"
195 #include "llvm/Transforms/Scalar.h"
196 #include "llvm/Transforms/Utils/Local.h"
197 #include "llvm/Transforms/Utils/LoopUtils.h"
198 
199 #define DEBUG_TYPE "loop-predication"
200 
201 STATISTIC(TotalConsidered, "Number of guards considered");
202 STATISTIC(TotalWidened, "Number of checks widened");
203 
204 using namespace llvm;
205 
206 static cl::opt<bool> EnableIVTruncation("loop-predication-enable-iv-truncation",
207                                         cl::Hidden, cl::init(true));
208 
209 static cl::opt<bool> EnableCountDownLoop("loop-predication-enable-count-down-loop",
210                                         cl::Hidden, cl::init(true));
211 
212 static cl::opt<bool>
213     SkipProfitabilityChecks("loop-predication-skip-profitability-checks",
214                             cl::Hidden, cl::init(false));
215 
216 // This is the scale factor for the latch probability. We use this during
217 // profitability analysis to find other exiting blocks that have a much higher
218 // probability of exiting the loop instead of loop exiting via latch.
219 // This value should be greater than 1 for a sane profitability check.
220 static cl::opt<float> LatchExitProbabilityScale(
221     "loop-predication-latch-probability-scale", cl::Hidden, cl::init(2.0),
222     cl::desc("scale factor for the latch probability. Value should be greater "
223              "than 1. Lower values are ignored"));
224 
225 static cl::opt<bool> PredicateWidenableBranchGuards(
226     "loop-predication-predicate-widenable-branches-to-deopt", cl::Hidden,
227     cl::desc("Whether or not we should predicate guards "
228              "expressed as widenable branches to deoptimize blocks"),
229     cl::init(true));
230 
231 namespace {
232 class LoopPredication {
233   /// Represents an induction variable check:
234   ///   icmp Pred, <induction variable>, <loop invariant limit>
235   struct LoopICmp {
236     ICmpInst::Predicate Pred;
237     const SCEVAddRecExpr *IV;
238     const SCEV *Limit;
239     LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV,
240              const SCEV *Limit)
241         : Pred(Pred), IV(IV), Limit(Limit) {}
242     LoopICmp() {}
243     void dump() {
244       dbgs() << "LoopICmp Pred = " << Pred << ", IV = " << *IV
245              << ", Limit = " << *Limit << "\n";
246     }
247   };
248 
249   ScalarEvolution *SE;
250   BranchProbabilityInfo *BPI;
251 
252   Loop *L;
253   const DataLayout *DL;
254   BasicBlock *Preheader;
255   LoopICmp LatchCheck;
256 
257   bool isSupportedStep(const SCEV* Step);
258   Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI) {
259     return parseLoopICmp(ICI->getPredicate(), ICI->getOperand(0),
260                          ICI->getOperand(1));
261   }
262   Optional<LoopICmp> parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS,
263                                    Value *RHS);
264 
265   Optional<LoopICmp> parseLoopLatchICmp();
266 
267   /// Return an insertion point suitable for inserting a safe to speculate
268   /// instruction whose only user will be 'User' which has operands 'Ops'.  A
269   /// trivial result would be the at the User itself, but we try to return a
270   /// loop invariant location if possible.
271   Instruction *findInsertPt(Instruction *User, ArrayRef<Value*> Ops);
272   /// Same as above, *except* that this uses the SCEV definition of invariant
273   /// which is that an expression *can be made* invariant via SCEVExpander.
274   /// Thus, this version is only suitable for finding an insert point to be be
275   /// passed to SCEVExpander!
276   Instruction *findInsertPt(Instruction *User, ArrayRef<const SCEV*> Ops);
277 
278   bool CanExpand(const SCEV* S);
279   Value *expandCheck(SCEVExpander &Expander, Instruction *Guard,
280                      ICmpInst::Predicate Pred, const SCEV *LHS,
281                      const SCEV *RHS);
282 
283   Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander,
284                                         Instruction *Guard);
285   Optional<Value *> widenICmpRangeCheckIncrementingLoop(LoopICmp LatchCheck,
286                                                         LoopICmp RangeCheck,
287                                                         SCEVExpander &Expander,
288                                                         Instruction *Guard);
289   Optional<Value *> widenICmpRangeCheckDecrementingLoop(LoopICmp LatchCheck,
290                                                         LoopICmp RangeCheck,
291                                                         SCEVExpander &Expander,
292                                                         Instruction *Guard);
293   unsigned collectChecks(SmallVectorImpl<Value *> &Checks, Value *Condition,
294                          SCEVExpander &Expander, Instruction *Guard);
295   bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander);
296   bool widenWidenableBranchGuardConditions(BranchInst *Guard, SCEVExpander &Expander);
297   // If the loop always exits through another block in the loop, we should not
298   // predicate based on the latch check. For example, the latch check can be a
299   // very coarse grained check and there can be more fine grained exit checks
300   // within the loop. We identify such unprofitable loops through BPI.
301   bool isLoopProfitableToPredicate();
302 
303   // When the IV type is wider than the range operand type, we can still do loop
304   // predication, by generating SCEVs for the range and latch that are of the
305   // same type. We achieve this by generating a SCEV truncate expression for the
306   // latch IV. This is done iff truncation of the IV is a safe operation,
307   // without loss of information.
308   // Another way to achieve this is by generating a wider type SCEV for the
309   // range check operand, however, this needs a more involved check that
310   // operands do not overflow. This can lead to loss of information when the
311   // range operand is of the form: add i32 %offset, %iv. We need to prove that
312   // sext(x + y) is same as sext(x) + sext(y).
313   // This function returns true if we can safely represent the IV type in
314   // the RangeCheckType without loss of information.
315   bool isSafeToTruncateWideIVType(Type *RangeCheckType);
316   // Return the loopLatchCheck corresponding to the RangeCheckType if safe to do
317   // so.
318   Optional<LoopICmp> generateLoopLatchCheck(Type *RangeCheckType);
319 
320 public:
321   LoopPredication(ScalarEvolution *SE, BranchProbabilityInfo *BPI)
322       : SE(SE), BPI(BPI){};
323   bool runOnLoop(Loop *L);
324 };
325 
326 class LoopPredicationLegacyPass : public LoopPass {
327 public:
328   static char ID;
329   LoopPredicationLegacyPass() : LoopPass(ID) {
330     initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry());
331   }
332 
333   void getAnalysisUsage(AnalysisUsage &AU) const override {
334     AU.addRequired<BranchProbabilityInfoWrapperPass>();
335     getLoopAnalysisUsage(AU);
336   }
337 
338   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
339     if (skipLoop(L))
340       return false;
341     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
342     BranchProbabilityInfo &BPI =
343         getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
344     LoopPredication LP(SE, &BPI);
345     return LP.runOnLoop(L);
346   }
347 };
348 
349 char LoopPredicationLegacyPass::ID = 0;
350 } // end namespace llvm
351 
352 INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication",
353                       "Loop predication", false, false)
354 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
355 INITIALIZE_PASS_DEPENDENCY(LoopPass)
356 INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication",
357                     "Loop predication", false, false)
358 
359 Pass *llvm::createLoopPredicationPass() {
360   return new LoopPredicationLegacyPass();
361 }
362 
363 PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM,
364                                            LoopStandardAnalysisResults &AR,
365                                            LPMUpdater &U) {
366   const auto &FAM =
367       AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
368   Function *F = L.getHeader()->getParent();
369   auto *BPI = FAM.getCachedResult<BranchProbabilityAnalysis>(*F);
370   LoopPredication LP(&AR.SE, BPI);
371   if (!LP.runOnLoop(&L))
372     return PreservedAnalyses::all();
373 
374   return getLoopPassPreservedAnalyses();
375 }
376 
377 Optional<LoopPredication::LoopICmp>
378 LoopPredication::parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS,
379                                Value *RHS) {
380   const SCEV *LHSS = SE->getSCEV(LHS);
381   if (isa<SCEVCouldNotCompute>(LHSS))
382     return None;
383   const SCEV *RHSS = SE->getSCEV(RHS);
384   if (isa<SCEVCouldNotCompute>(RHSS))
385     return None;
386 
387   // Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV
388   if (SE->isLoopInvariant(LHSS, L)) {
389     std::swap(LHS, RHS);
390     std::swap(LHSS, RHSS);
391     Pred = ICmpInst::getSwappedPredicate(Pred);
392   }
393 
394   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS);
395   if (!AR || AR->getLoop() != L)
396     return None;
397 
398   return LoopICmp(Pred, AR, RHSS);
399 }
400 
401 Value *LoopPredication::expandCheck(SCEVExpander &Expander,
402                                     Instruction *Guard,
403                                     ICmpInst::Predicate Pred, const SCEV *LHS,
404                                     const SCEV *RHS) {
405   Type *Ty = LHS->getType();
406   assert(Ty == RHS->getType() && "expandCheck operands have different types?");
407 
408   if (SE->isLoopInvariant(LHS, L) && SE->isLoopInvariant(RHS, L)) {
409     IRBuilder<> Builder(Guard);
410     if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS))
411       return Builder.getTrue();
412     if (SE->isLoopEntryGuardedByCond(L, ICmpInst::getInversePredicate(Pred),
413                                      LHS, RHS))
414       return Builder.getFalse();
415   }
416 
417   Value *LHSV = Expander.expandCodeFor(LHS, Ty, findInsertPt(Guard, {LHS}));
418   Value *RHSV = Expander.expandCodeFor(RHS, Ty, findInsertPt(Guard, {RHS}));
419   IRBuilder<> Builder(findInsertPt(Guard, {LHSV, RHSV}));
420   return Builder.CreateICmp(Pred, LHSV, RHSV);
421 }
422 
423 Optional<LoopPredication::LoopICmp>
424 LoopPredication::generateLoopLatchCheck(Type *RangeCheckType) {
425 
426   auto *LatchType = LatchCheck.IV->getType();
427   if (RangeCheckType == LatchType)
428     return LatchCheck;
429   // For now, bail out if latch type is narrower than range type.
430   if (DL->getTypeSizeInBits(LatchType) < DL->getTypeSizeInBits(RangeCheckType))
431     return None;
432   if (!isSafeToTruncateWideIVType(RangeCheckType))
433     return None;
434   // We can now safely identify the truncated version of the IV and limit for
435   // RangeCheckType.
436   LoopICmp NewLatchCheck;
437   NewLatchCheck.Pred = LatchCheck.Pred;
438   NewLatchCheck.IV = dyn_cast<SCEVAddRecExpr>(
439       SE->getTruncateExpr(LatchCheck.IV, RangeCheckType));
440   if (!NewLatchCheck.IV)
441     return None;
442   NewLatchCheck.Limit = SE->getTruncateExpr(LatchCheck.Limit, RangeCheckType);
443   LLVM_DEBUG(dbgs() << "IV of type: " << *LatchType
444                     << "can be represented as range check type:"
445                     << *RangeCheckType << "\n");
446   LLVM_DEBUG(dbgs() << "LatchCheck.IV: " << *NewLatchCheck.IV << "\n");
447   LLVM_DEBUG(dbgs() << "LatchCheck.Limit: " << *NewLatchCheck.Limit << "\n");
448   return NewLatchCheck;
449 }
450 
451 bool LoopPredication::isSupportedStep(const SCEV* Step) {
452   return Step->isOne() || (Step->isAllOnesValue() && EnableCountDownLoop);
453 }
454 
455 Instruction *LoopPredication::findInsertPt(Instruction *Use,
456                                            ArrayRef<Value*> Ops) {
457   for (Value *Op : Ops)
458     if (!L->isLoopInvariant(Op))
459       return Use;
460   return Preheader->getTerminator();
461 }
462 
463 Instruction *LoopPredication::findInsertPt(Instruction *Use,
464                                            ArrayRef<const SCEV*> Ops) {
465   for (const SCEV *Op : Ops)
466     if (!SE->isLoopInvariant(Op, L))
467       return Use;
468   return Preheader->getTerminator();
469 }
470 
471 
472 bool LoopPredication::CanExpand(const SCEV* S) {
473   return SE->isLoopInvariant(S, L) && isSafeToExpand(S, *SE);
474 }
475 
476 Optional<Value *> LoopPredication::widenICmpRangeCheckIncrementingLoop(
477     LoopPredication::LoopICmp LatchCheck, LoopPredication::LoopICmp RangeCheck,
478     SCEVExpander &Expander, Instruction *Guard) {
479   auto *Ty = RangeCheck.IV->getType();
480   // Generate the widened condition for the forward loop:
481   //   guardStart u< guardLimit &&
482   //   latchLimit <pred> guardLimit - 1 - guardStart + latchStart
483   // where <pred> depends on the latch condition predicate. See the file
484   // header comment for the reasoning.
485   // guardLimit - guardStart + latchStart - 1
486   const SCEV *GuardStart = RangeCheck.IV->getStart();
487   const SCEV *GuardLimit = RangeCheck.Limit;
488   const SCEV *LatchStart = LatchCheck.IV->getStart();
489   const SCEV *LatchLimit = LatchCheck.Limit;
490 
491   // guardLimit - guardStart + latchStart - 1
492   const SCEV *RHS =
493       SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart),
494                      SE->getMinusSCEV(LatchStart, SE->getOne(Ty)));
495   if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) ||
496       !CanExpand(LatchLimit) || !CanExpand(RHS)) {
497     LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
498     return None;
499   }
500   auto LimitCheckPred =
501       ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred);
502 
503   LLVM_DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n");
504   LLVM_DEBUG(dbgs() << "RHS: " << *RHS << "\n");
505   LLVM_DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n");
506 
507   auto *LimitCheck =
508       expandCheck(Expander, Guard, LimitCheckPred, LatchLimit, RHS);
509   auto *FirstIterationCheck = expandCheck(Expander, Guard, RangeCheck.Pred,
510                                           GuardStart, GuardLimit);
511   IRBuilder<> Builder(findInsertPt(Guard, {FirstIterationCheck, LimitCheck}));
512   return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
513 }
514 
515 Optional<Value *> LoopPredication::widenICmpRangeCheckDecrementingLoop(
516     LoopPredication::LoopICmp LatchCheck, LoopPredication::LoopICmp RangeCheck,
517     SCEVExpander &Expander, Instruction *Guard) {
518   auto *Ty = RangeCheck.IV->getType();
519   const SCEV *GuardStart = RangeCheck.IV->getStart();
520   const SCEV *GuardLimit = RangeCheck.Limit;
521   const SCEV *LatchLimit = LatchCheck.Limit;
522   if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) ||
523       !CanExpand(LatchLimit)) {
524     LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
525     return None;
526   }
527   // The decrement of the latch check IV should be the same as the
528   // rangeCheckIV.
529   auto *PostDecLatchCheckIV = LatchCheck.IV->getPostIncExpr(*SE);
530   if (RangeCheck.IV != PostDecLatchCheckIV) {
531     LLVM_DEBUG(dbgs() << "Not the same. PostDecLatchCheckIV: "
532                       << *PostDecLatchCheckIV
533                       << "  and RangeCheckIV: " << *RangeCheck.IV << "\n");
534     return None;
535   }
536 
537   // Generate the widened condition for CountDownLoop:
538   // guardStart u< guardLimit &&
539   // latchLimit <pred> 1.
540   // See the header comment for reasoning of the checks.
541   auto LimitCheckPred =
542       ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred);
543   auto *FirstIterationCheck = expandCheck(Expander, Guard,
544                                           ICmpInst::ICMP_ULT,
545                                           GuardStart, GuardLimit);
546   auto *LimitCheck = expandCheck(Expander, Guard, LimitCheckPred, LatchLimit,
547                                  SE->getOne(Ty));
548   IRBuilder<> Builder(findInsertPt(Guard, {FirstIterationCheck, LimitCheck}));
549   return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
550 }
551 
552 /// If ICI can be widened to a loop invariant condition emits the loop
553 /// invariant condition in the loop preheader and return it, otherwise
554 /// returns None.
555 Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI,
556                                                        SCEVExpander &Expander,
557                                                        Instruction *Guard) {
558   LLVM_DEBUG(dbgs() << "Analyzing ICmpInst condition:\n");
559   LLVM_DEBUG(ICI->dump());
560 
561   // parseLoopStructure guarantees that the latch condition is:
562   //   ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=.
563   // We are looking for the range checks of the form:
564   //   i u< guardLimit
565   auto RangeCheck = parseLoopICmp(ICI);
566   if (!RangeCheck) {
567     LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
568     return None;
569   }
570   LLVM_DEBUG(dbgs() << "Guard check:\n");
571   LLVM_DEBUG(RangeCheck->dump());
572   if (RangeCheck->Pred != ICmpInst::ICMP_ULT) {
573     LLVM_DEBUG(dbgs() << "Unsupported range check predicate("
574                       << RangeCheck->Pred << ")!\n");
575     return None;
576   }
577   auto *RangeCheckIV = RangeCheck->IV;
578   if (!RangeCheckIV->isAffine()) {
579     LLVM_DEBUG(dbgs() << "Range check IV is not affine!\n");
580     return None;
581   }
582   auto *Step = RangeCheckIV->getStepRecurrence(*SE);
583   // We cannot just compare with latch IV step because the latch and range IVs
584   // may have different types.
585   if (!isSupportedStep(Step)) {
586     LLVM_DEBUG(dbgs() << "Range check and latch have IVs different steps!\n");
587     return None;
588   }
589   auto *Ty = RangeCheckIV->getType();
590   auto CurrLatchCheckOpt = generateLoopLatchCheck(Ty);
591   if (!CurrLatchCheckOpt) {
592     LLVM_DEBUG(dbgs() << "Failed to generate a loop latch check "
593                          "corresponding to range type: "
594                       << *Ty << "\n");
595     return None;
596   }
597 
598   LoopICmp CurrLatchCheck = *CurrLatchCheckOpt;
599   // At this point, the range and latch step should have the same type, but need
600   // not have the same value (we support both 1 and -1 steps).
601   assert(Step->getType() ==
602              CurrLatchCheck.IV->getStepRecurrence(*SE)->getType() &&
603          "Range and latch steps should be of same type!");
604   if (Step != CurrLatchCheck.IV->getStepRecurrence(*SE)) {
605     LLVM_DEBUG(dbgs() << "Range and latch have different step values!\n");
606     return None;
607   }
608 
609   if (Step->isOne())
610     return widenICmpRangeCheckIncrementingLoop(CurrLatchCheck, *RangeCheck,
611                                                Expander, Guard);
612   else {
613     assert(Step->isAllOnesValue() && "Step should be -1!");
614     return widenICmpRangeCheckDecrementingLoop(CurrLatchCheck, *RangeCheck,
615                                                Expander, Guard);
616   }
617 }
618 
619 unsigned LoopPredication::collectChecks(SmallVectorImpl<Value *> &Checks,
620                                         Value *Condition,
621                                         SCEVExpander &Expander,
622                                         Instruction *Guard) {
623   unsigned NumWidened = 0;
624   // The guard condition is expected to be in form of:
625   //   cond1 && cond2 && cond3 ...
626   // Iterate over subconditions looking for icmp conditions which can be
627   // widened across loop iterations. Widening these conditions remember the
628   // resulting list of subconditions in Checks vector.
629   SmallVector<Value *, 4> Worklist(1, Condition);
630   SmallPtrSet<Value *, 4> Visited;
631   Value *WideableCond = nullptr;
632   do {
633     Value *Condition = Worklist.pop_back_val();
634     if (!Visited.insert(Condition).second)
635       continue;
636 
637     Value *LHS, *RHS;
638     using namespace llvm::PatternMatch;
639     if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) {
640       Worklist.push_back(LHS);
641       Worklist.push_back(RHS);
642       continue;
643     }
644 
645     if (match(Condition,
646               m_Intrinsic<Intrinsic::experimental_widenable_condition>())) {
647       // Pick any, we don't care which
648       WideableCond = Condition;
649       continue;
650     }
651 
652     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
653       if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander,
654                                                    Guard)) {
655         Checks.push_back(NewRangeCheck.getValue());
656         NumWidened++;
657         continue;
658       }
659     }
660 
661     // Save the condition as is if we can't widen it
662     Checks.push_back(Condition);
663   } while (!Worklist.empty());
664   // At the moment, our matching logic for wideable conditions implicitly
665   // assumes we preserve the form: (br (and Cond, WC())).  FIXME
666   // Note that if there were multiple calls to wideable condition in the
667   // traversal, we only need to keep one, and which one is arbitrary.
668   if (WideableCond)
669     Checks.push_back(WideableCond);
670   return NumWidened;
671 }
672 
673 bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard,
674                                            SCEVExpander &Expander) {
675   LLVM_DEBUG(dbgs() << "Processing guard:\n");
676   LLVM_DEBUG(Guard->dump());
677 
678   TotalConsidered++;
679   SmallVector<Value *, 4> Checks;
680   unsigned NumWidened = collectChecks(Checks, Guard->getOperand(0), Expander,
681                                       Guard);
682   if (NumWidened == 0)
683     return false;
684 
685   TotalWidened += NumWidened;
686 
687   // Emit the new guard condition
688   IRBuilder<> Builder(findInsertPt(Guard, Checks));
689   Value *LastCheck = nullptr;
690   for (auto *Check : Checks)
691     if (!LastCheck)
692       LastCheck = Check;
693     else
694       LastCheck = Builder.CreateAnd(LastCheck, Check);
695   auto *OldCond = Guard->getOperand(0);
696   Guard->setOperand(0, LastCheck);
697   RecursivelyDeleteTriviallyDeadInstructions(OldCond);
698 
699   LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
700   return true;
701 }
702 
703 bool LoopPredication::widenWidenableBranchGuardConditions(
704     BranchInst *BI, SCEVExpander &Expander) {
705   assert(isGuardAsWidenableBranch(BI) && "Must be!");
706   LLVM_DEBUG(dbgs() << "Processing guard:\n");
707   LLVM_DEBUG(BI->dump());
708 
709   TotalConsidered++;
710   SmallVector<Value *, 4> Checks;
711   unsigned NumWidened = collectChecks(Checks, BI->getCondition(),
712                                       Expander, BI);
713   if (NumWidened == 0)
714     return false;
715 
716   TotalWidened += NumWidened;
717 
718   // Emit the new guard condition
719   IRBuilder<> Builder(findInsertPt(BI, Checks));
720   Value *LastCheck = nullptr;
721   for (auto *Check : Checks)
722     if (!LastCheck)
723       LastCheck = Check;
724     else
725       LastCheck = Builder.CreateAnd(LastCheck, Check);
726   auto *OldCond = BI->getCondition();
727   BI->setCondition(LastCheck);
728   assert(isGuardAsWidenableBranch(BI) &&
729          "Stopped being a guard after transform?");
730   RecursivelyDeleteTriviallyDeadInstructions(OldCond);
731 
732   LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
733   return true;
734 }
735 
736 Optional<LoopPredication::LoopICmp> LoopPredication::parseLoopLatchICmp() {
737   using namespace PatternMatch;
738 
739   BasicBlock *LoopLatch = L->getLoopLatch();
740   if (!LoopLatch) {
741     LLVM_DEBUG(dbgs() << "The loop doesn't have a single latch!\n");
742     return None;
743   }
744 
745   ICmpInst::Predicate Pred;
746   Value *LHS, *RHS;
747   BasicBlock *TrueDest, *FalseDest;
748 
749   if (!match(LoopLatch->getTerminator(),
750              m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TrueDest,
751                   FalseDest))) {
752     LLVM_DEBUG(dbgs() << "Failed to match the latch terminator!\n");
753     return None;
754   }
755   assert((TrueDest == L->getHeader() || FalseDest == L->getHeader()) &&
756          "One of the latch's destinations must be the header");
757   if (TrueDest != L->getHeader())
758     Pred = ICmpInst::getInversePredicate(Pred);
759 
760   auto Result = parseLoopICmp(Pred, LHS, RHS);
761   if (!Result) {
762     LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
763     return None;
764   }
765 
766   // Check affine first, so if it's not we don't try to compute the step
767   // recurrence.
768   if (!Result->IV->isAffine()) {
769     LLVM_DEBUG(dbgs() << "The induction variable is not affine!\n");
770     return None;
771   }
772 
773   auto *Step = Result->IV->getStepRecurrence(*SE);
774   if (!isSupportedStep(Step)) {
775     LLVM_DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n");
776     return None;
777   }
778 
779   auto IsUnsupportedPredicate = [](const SCEV *Step, ICmpInst::Predicate Pred) {
780     if (Step->isOne()) {
781       return Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_SLT &&
782              Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_SLE;
783     } else {
784       assert(Step->isAllOnesValue() && "Step should be -1!");
785       return Pred != ICmpInst::ICMP_UGT && Pred != ICmpInst::ICMP_SGT &&
786              Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE;
787     }
788   };
789 
790   if (IsUnsupportedPredicate(Step, Result->Pred)) {
791     LLVM_DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred
792                       << ")!\n");
793     return None;
794   }
795   return Result;
796 }
797 
798 // Returns true if its safe to truncate the IV to RangeCheckType.
799 bool LoopPredication::isSafeToTruncateWideIVType(Type *RangeCheckType) {
800   if (!EnableIVTruncation)
801     return false;
802   assert(DL->getTypeSizeInBits(LatchCheck.IV->getType()) >
803              DL->getTypeSizeInBits(RangeCheckType) &&
804          "Expected latch check IV type to be larger than range check operand "
805          "type!");
806   // The start and end values of the IV should be known. This is to guarantee
807   // that truncating the wide type will not lose information.
808   auto *Limit = dyn_cast<SCEVConstant>(LatchCheck.Limit);
809   auto *Start = dyn_cast<SCEVConstant>(LatchCheck.IV->getStart());
810   if (!Limit || !Start)
811     return false;
812   // This check makes sure that the IV does not change sign during loop
813   // iterations. Consider latchType = i64, LatchStart = 5, Pred = ICMP_SGE,
814   // LatchEnd = 2, rangeCheckType = i32. If it's not a monotonic predicate, the
815   // IV wraps around, and the truncation of the IV would lose the range of
816   // iterations between 2^32 and 2^64.
817   bool Increasing;
818   if (!SE->isMonotonicPredicate(LatchCheck.IV, LatchCheck.Pred, Increasing))
819     return false;
820   // The active bits should be less than the bits in the RangeCheckType. This
821   // guarantees that truncating the latch check to RangeCheckType is a safe
822   // operation.
823   auto RangeCheckTypeBitSize = DL->getTypeSizeInBits(RangeCheckType);
824   return Start->getAPInt().getActiveBits() < RangeCheckTypeBitSize &&
825          Limit->getAPInt().getActiveBits() < RangeCheckTypeBitSize;
826 }
827 
828 bool LoopPredication::isLoopProfitableToPredicate() {
829   if (SkipProfitabilityChecks || !BPI)
830     return true;
831 
832   SmallVector<std::pair<const BasicBlock *, const BasicBlock *>, 8> ExitEdges;
833   L->getExitEdges(ExitEdges);
834   // If there is only one exiting edge in the loop, it is always profitable to
835   // predicate the loop.
836   if (ExitEdges.size() == 1)
837     return true;
838 
839   // Calculate the exiting probabilities of all exiting edges from the loop,
840   // starting with the LatchExitProbability.
841   // Heuristic for profitability: If any of the exiting blocks' probability of
842   // exiting the loop is larger than exiting through the latch block, it's not
843   // profitable to predicate the loop.
844   auto *LatchBlock = L->getLoopLatch();
845   assert(LatchBlock && "Should have a single latch at this point!");
846   auto *LatchTerm = LatchBlock->getTerminator();
847   assert(LatchTerm->getNumSuccessors() == 2 &&
848          "expected to be an exiting block with 2 succs!");
849   unsigned LatchBrExitIdx =
850       LatchTerm->getSuccessor(0) == L->getHeader() ? 1 : 0;
851   BranchProbability LatchExitProbability =
852       BPI->getEdgeProbability(LatchBlock, LatchBrExitIdx);
853 
854   // Protect against degenerate inputs provided by the user. Providing a value
855   // less than one, can invert the definition of profitable loop predication.
856   float ScaleFactor = LatchExitProbabilityScale;
857   if (ScaleFactor < 1) {
858     LLVM_DEBUG(
859         dbgs()
860         << "Ignored user setting for loop-predication-latch-probability-scale: "
861         << LatchExitProbabilityScale << "\n");
862     LLVM_DEBUG(dbgs() << "The value is set to 1.0\n");
863     ScaleFactor = 1.0;
864   }
865   const auto LatchProbabilityThreshold =
866       LatchExitProbability * ScaleFactor;
867 
868   for (const auto &ExitEdge : ExitEdges) {
869     BranchProbability ExitingBlockProbability =
870         BPI->getEdgeProbability(ExitEdge.first, ExitEdge.second);
871     // Some exiting edge has higher probability than the latch exiting edge.
872     // No longer profitable to predicate.
873     if (ExitingBlockProbability > LatchProbabilityThreshold)
874       return false;
875   }
876   // Using BPI, we have concluded that the most probable way to exit from the
877   // loop is through the latch (or there's no profile information and all
878   // exits are equally likely).
879   return true;
880 }
881 
882 bool LoopPredication::runOnLoop(Loop *Loop) {
883   L = Loop;
884 
885   LLVM_DEBUG(dbgs() << "Analyzing ");
886   LLVM_DEBUG(L->dump());
887 
888   Module *M = L->getHeader()->getModule();
889 
890   // There is nothing to do if the module doesn't use guards
891   auto *GuardDecl =
892       M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard));
893   bool HasIntrinsicGuards = GuardDecl && !GuardDecl->use_empty();
894   auto *WCDecl = M->getFunction(
895       Intrinsic::getName(Intrinsic::experimental_widenable_condition));
896   bool HasWidenableConditions =
897       PredicateWidenableBranchGuards && WCDecl && !WCDecl->use_empty();
898   if (!HasIntrinsicGuards && !HasWidenableConditions)
899     return false;
900 
901   DL = &M->getDataLayout();
902 
903   Preheader = L->getLoopPreheader();
904   if (!Preheader)
905     return false;
906 
907   auto LatchCheckOpt = parseLoopLatchICmp();
908   if (!LatchCheckOpt)
909     return false;
910   LatchCheck = *LatchCheckOpt;
911 
912   LLVM_DEBUG(dbgs() << "Latch check:\n");
913   LLVM_DEBUG(LatchCheck.dump());
914 
915   if (!isLoopProfitableToPredicate()) {
916     LLVM_DEBUG(dbgs() << "Loop not profitable to predicate!\n");
917     return false;
918   }
919   // Collect all the guards into a vector and process later, so as not
920   // to invalidate the instruction iterator.
921   SmallVector<IntrinsicInst *, 4> Guards;
922   SmallVector<BranchInst *, 4> GuardsAsWidenableBranches;
923   for (const auto BB : L->blocks()) {
924     for (auto &I : *BB)
925       if (isGuard(&I))
926         Guards.push_back(cast<IntrinsicInst>(&I));
927     if (PredicateWidenableBranchGuards &&
928         isGuardAsWidenableBranch(BB->getTerminator()))
929       GuardsAsWidenableBranches.push_back(
930           cast<BranchInst>(BB->getTerminator()));
931   }
932 
933   if (Guards.empty() && GuardsAsWidenableBranches.empty())
934     return false;
935 
936   SCEVExpander Expander(*SE, *DL, "loop-predication");
937 
938   bool Changed = false;
939   for (auto *Guard : Guards)
940     Changed |= widenGuardConditions(Guard, Expander);
941   for (auto *Guard : GuardsAsWidenableBranches)
942     Changed |= widenWidenableBranchGuardConditions(Guard, Expander);
943 
944   return Changed;
945 }
946