xref: /llvm-project/llvm/lib/Transforms/Scalar/LoopPredication.cpp (revision 8aadc643cf8d049c7d895023ed1bc210dd7dca75)
1 //===-- LoopPredication.cpp - Guard based loop predication pass -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // The LoopPredication pass tries to convert loop variant range checks to loop
11 // invariant by widening checks across loop iterations. For example, it will
12 // convert
13 //
14 //   for (i = 0; i < n; i++) {
15 //     guard(i < len);
16 //     ...
17 //   }
18 //
19 // to
20 //
21 //   for (i = 0; i < n; i++) {
22 //     guard(n - 1 < len);
23 //     ...
24 //   }
25 //
26 // After this transformation the condition of the guard is loop invariant, so
27 // loop-unswitch can later unswitch the loop by this condition which basically
28 // predicates the loop by the widened condition:
29 //
30 //   if (n - 1 < len)
31 //     for (i = 0; i < n; i++) {
32 //       ...
33 //     }
34 //   else
35 //     deoptimize
36 //
37 // It's tempting to rely on SCEV here, but it has proven to be problematic.
38 // Generally the facts SCEV provides about the increment step of add
39 // recurrences are true if the backedge of the loop is taken, which implicitly
40 // assumes that the guard doesn't fail. Using these facts to optimize the
41 // guard results in a circular logic where the guard is optimized under the
42 // assumption that it never fails.
43 //
44 // For example, in the loop below the induction variable will be marked as nuw
45 // basing on the guard. Basing on nuw the guard predicate will be considered
46 // monotonic. Given a monotonic condition it's tempting to replace the induction
47 // variable in the condition with its value on the last iteration. But this
48 // transformation is not correct, e.g. e = 4, b = 5 breaks the loop.
49 //
50 //   for (int i = b; i != e; i++)
51 //     guard(i u< len)
52 //
53 // One of the ways to reason about this problem is to use an inductive proof
54 // approach. Given the loop:
55 //
56 //   if (B(0)) {
57 //     do {
58 //       I = PHI(0, I.INC)
59 //       I.INC = I + Step
60 //       guard(G(I));
61 //     } while (B(I));
62 //   }
63 //
64 // where B(x) and G(x) are predicates that map integers to booleans, we want a
65 // loop invariant expression M such the following program has the same semantics
66 // as the above:
67 //
68 //   if (B(0)) {
69 //     do {
70 //       I = PHI(0, I.INC)
71 //       I.INC = I + Step
72 //       guard(G(0) && M);
73 //     } while (B(I));
74 //   }
75 //
76 // One solution for M is M = forall X . (G(X) && B(X)) => G(X + Step)
77 //
78 // Informal proof that the transformation above is correct:
79 //
80 //   By the definition of guards we can rewrite the guard condition to:
81 //     G(I) && G(0) && M
82 //
83 //   Let's prove that for each iteration of the loop:
84 //     G(0) && M => G(I)
85 //   And the condition above can be simplified to G(Start) && M.
86 //
87 //   Induction base.
88 //     G(0) && M => G(0)
89 //
90 //   Induction step. Assuming G(0) && M => G(I) on the subsequent
91 //   iteration:
92 //
93 //     B(I) is true because it's the backedge condition.
94 //     G(I) is true because the backedge is guarded by this condition.
95 //
96 //   So M = forall X . (G(X) && B(X)) => G(X + Step) implies G(I + Step).
97 //
98 // Note that we can use anything stronger than M, i.e. any condition which
99 // implies M.
100 //
101 // For now the transformation is limited to the following case:
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 step of the IV used in the latch condition is 1.
106 //   * The guard condition is of the form
107 //     G(X) = guardStart + X u< guardLimit
108 //
109 // For the ult latch comparison case M is:
110 //   forall X . guardStart + X u< guardLimit && latchStart + X <u latchLimit =>
111 //      guardStart + X + 1 u< guardLimit
112 //
113 // The only way the antecedent can be true and the consequent can be false is
114 // if
115 //   X == guardLimit - 1 - guardStart
116 // (and guardLimit is non-zero, but we won't use this latter fact).
117 // If X == guardLimit - 1 - guardStart then the second half of the antecedent is
118 //   latchStart + guardLimit - 1 - guardStart u< latchLimit
119 // and its negation is
120 //   latchStart + guardLimit - 1 - guardStart u>= latchLimit
121 //
122 // In other words, if
123 //   latchLimit u<= latchStart + guardLimit - 1 - guardStart
124 // then:
125 // (the ranges below are written in ConstantRange notation, where [A, B) is the
126 // set for (I = A; I != B; I++ /*maywrap*/) yield(I);)
127 //
128 //    forall X . guardStart + X u< guardLimit &&
129 //               latchStart + X u< latchLimit =>
130 //      guardStart + X + 1 u< guardLimit
131 // == forall X . guardStart + X u< guardLimit &&
132 //               latchStart + X u< latchStart + guardLimit - 1 - guardStart =>
133 //      guardStart + X + 1 u< guardLimit
134 // == forall X . (guardStart + X) in [0, guardLimit) &&
135 //               (latchStart + X) in [0, latchStart + guardLimit - 1 - guardStart) =>
136 //      (guardStart + X + 1) in [0, guardLimit)
137 // == forall X . X in [-guardStart, guardLimit - guardStart) &&
138 //               X in [-latchStart, guardLimit - 1 - guardStart) =>
139 //       X in [-guardStart - 1, guardLimit - guardStart - 1)
140 // == true
141 //
142 // So the widened condition is:
143 //   guardStart u< guardLimit &&
144 //   latchStart + guardLimit - 1 - guardStart u>= latchLimit
145 // Similarly for ule condition the widened condition is:
146 //   guardStart u< guardLimit &&
147 //   latchStart + guardLimit - 1 - guardStart u> latchLimit
148 // For slt condition the widened condition is:
149 //   guardStart u< guardLimit &&
150 //   latchStart + guardLimit - 1 - guardStart s>= latchLimit
151 // For sle condition the widened condition is:
152 //   guardStart u< guardLimit &&
153 //   latchStart + guardLimit - 1 - guardStart s> latchLimit
154 //
155 //===----------------------------------------------------------------------===//
156 
157 #include "llvm/Transforms/Scalar/LoopPredication.h"
158 #include "llvm/Analysis/LoopInfo.h"
159 #include "llvm/Analysis/LoopPass.h"
160 #include "llvm/Analysis/ScalarEvolution.h"
161 #include "llvm/Analysis/ScalarEvolutionExpander.h"
162 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
163 #include "llvm/IR/Function.h"
164 #include "llvm/IR/GlobalValue.h"
165 #include "llvm/IR/IntrinsicInst.h"
166 #include "llvm/IR/Module.h"
167 #include "llvm/IR/PatternMatch.h"
168 #include "llvm/Pass.h"
169 #include "llvm/Support/Debug.h"
170 #include "llvm/Transforms/Scalar.h"
171 #include "llvm/Transforms/Utils/LoopUtils.h"
172 
173 #define DEBUG_TYPE "loop-predication"
174 
175 using namespace llvm;
176 
177 namespace {
178 class LoopPredication {
179   /// Represents an induction variable check:
180   ///   icmp Pred, <induction variable>, <loop invariant limit>
181   struct LoopICmp {
182     ICmpInst::Predicate Pred;
183     const SCEVAddRecExpr *IV;
184     const SCEV *Limit;
185     LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV,
186              const SCEV *Limit)
187         : Pred(Pred), IV(IV), Limit(Limit) {}
188     LoopICmp() {}
189   };
190 
191   ScalarEvolution *SE;
192 
193   Loop *L;
194   const DataLayout *DL;
195   BasicBlock *Preheader;
196   LoopICmp LatchCheck;
197 
198   Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI) {
199     return parseLoopICmp(ICI->getPredicate(), ICI->getOperand(0),
200                          ICI->getOperand(1));
201   }
202   Optional<LoopICmp> parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS,
203                                    Value *RHS);
204 
205   Optional<LoopICmp> parseLoopLatchICmp();
206 
207   Value *expandCheck(SCEVExpander &Expander, IRBuilder<> &Builder,
208                      ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
209                      Instruction *InsertAt);
210 
211   Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander,
212                                         IRBuilder<> &Builder);
213   bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander);
214 
215 public:
216   LoopPredication(ScalarEvolution *SE) : SE(SE){};
217   bool runOnLoop(Loop *L);
218 };
219 
220 class LoopPredicationLegacyPass : public LoopPass {
221 public:
222   static char ID;
223   LoopPredicationLegacyPass() : LoopPass(ID) {
224     initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry());
225   }
226 
227   void getAnalysisUsage(AnalysisUsage &AU) const override {
228     getLoopAnalysisUsage(AU);
229   }
230 
231   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
232     if (skipLoop(L))
233       return false;
234     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
235     LoopPredication LP(SE);
236     return LP.runOnLoop(L);
237   }
238 };
239 
240 char LoopPredicationLegacyPass::ID = 0;
241 } // end namespace llvm
242 
243 INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication",
244                       "Loop predication", false, false)
245 INITIALIZE_PASS_DEPENDENCY(LoopPass)
246 INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication",
247                     "Loop predication", false, false)
248 
249 Pass *llvm::createLoopPredicationPass() {
250   return new LoopPredicationLegacyPass();
251 }
252 
253 PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM,
254                                            LoopStandardAnalysisResults &AR,
255                                            LPMUpdater &U) {
256   LoopPredication LP(&AR.SE);
257   if (!LP.runOnLoop(&L))
258     return PreservedAnalyses::all();
259 
260   return getLoopPassPreservedAnalyses();
261 }
262 
263 Optional<LoopPredication::LoopICmp>
264 LoopPredication::parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS,
265                                Value *RHS) {
266   const SCEV *LHSS = SE->getSCEV(LHS);
267   if (isa<SCEVCouldNotCompute>(LHSS))
268     return None;
269   const SCEV *RHSS = SE->getSCEV(RHS);
270   if (isa<SCEVCouldNotCompute>(RHSS))
271     return None;
272 
273   // Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV
274   if (SE->isLoopInvariant(LHSS, L)) {
275     std::swap(LHS, RHS);
276     std::swap(LHSS, RHSS);
277     Pred = ICmpInst::getSwappedPredicate(Pred);
278   }
279 
280   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS);
281   if (!AR || AR->getLoop() != L)
282     return None;
283 
284   return LoopICmp(Pred, AR, RHSS);
285 }
286 
287 Value *LoopPredication::expandCheck(SCEVExpander &Expander,
288                                     IRBuilder<> &Builder,
289                                     ICmpInst::Predicate Pred, const SCEV *LHS,
290                                     const SCEV *RHS, Instruction *InsertAt) {
291   // TODO: we can check isLoopEntryGuardedByCond before emitting the check
292 
293   Type *Ty = LHS->getType();
294   assert(Ty == RHS->getType() && "expandCheck operands have different types?");
295 
296   if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS))
297     return Builder.getTrue();
298 
299   Value *LHSV = Expander.expandCodeFor(LHS, Ty, InsertAt);
300   Value *RHSV = Expander.expandCodeFor(RHS, Ty, InsertAt);
301   return Builder.CreateICmp(Pred, LHSV, RHSV);
302 }
303 
304 /// If ICI can be widened to a loop invariant condition emits the loop
305 /// invariant condition in the loop preheader and return it, otherwise
306 /// returns None.
307 Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI,
308                                                        SCEVExpander &Expander,
309                                                        IRBuilder<> &Builder) {
310   DEBUG(dbgs() << "Analyzing ICmpInst condition:\n");
311   DEBUG(ICI->dump());
312 
313   // parseLoopStructure guarantees that the latch condition is:
314   //   ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=.
315   // We are looking for the range checks of the form:
316   //   i u< guardLimit
317   auto RangeCheck = parseLoopICmp(ICI);
318   if (!RangeCheck) {
319     DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
320     return None;
321   }
322   if (RangeCheck->Pred != ICmpInst::ICMP_ULT) {
323     DEBUG(dbgs() << "Unsupported range check predicate(" << RangeCheck->Pred
324                  << ")!\n");
325     return None;
326   }
327   auto *RangeCheckIV = RangeCheck->IV;
328   auto *Ty = RangeCheckIV->getType();
329   if (Ty != LatchCheck.IV->getType()) {
330     DEBUG(dbgs() << "Type mismatch between range check and latch IVs!\n");
331     return None;
332   }
333   if (!RangeCheckIV->isAffine()) {
334     DEBUG(dbgs() << "Range check IV is not affine!\n");
335     return None;
336   }
337   auto *Step = RangeCheckIV->getStepRecurrence(*SE);
338   if (Step != LatchCheck.IV->getStepRecurrence(*SE)) {
339     DEBUG(dbgs() << "Range check and latch have IVs different steps!\n");
340     return None;
341   }
342   assert(Step->isOne() && "must be one");
343 
344   // Generate the widened condition:
345   //   guardStart u< guardLimit &&
346   //   latchLimit <pred> guardLimit - 1 - guardStart + latchStart
347   // where <pred> depends on the latch condition predicate. See the file
348   // header comment for the reasoning.
349   const SCEV *GuardStart = RangeCheckIV->getStart();
350   const SCEV *GuardLimit = RangeCheck->Limit;
351   const SCEV *LatchStart = LatchCheck.IV->getStart();
352   const SCEV *LatchLimit = LatchCheck.Limit;
353 
354   // guardLimit - guardStart + latchStart - 1
355   const SCEV *RHS =
356       SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart),
357                      SE->getMinusSCEV(LatchStart, SE->getOne(Ty)));
358 
359   ICmpInst::Predicate LimitCheckPred;
360   switch (LatchCheck.Pred) {
361   case ICmpInst::ICMP_ULT:
362     LimitCheckPred = ICmpInst::ICMP_ULE;
363     break;
364   case ICmpInst::ICMP_ULE:
365     LimitCheckPred = ICmpInst::ICMP_ULT;
366     break;
367   case ICmpInst::ICMP_SLT:
368     LimitCheckPred = ICmpInst::ICMP_SLE;
369     break;
370   case ICmpInst::ICMP_SLE:
371     LimitCheckPred = ICmpInst::ICMP_SLT;
372     break;
373   default:
374     llvm_unreachable("Unsupported loop latch!");
375   }
376 
377   DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n");
378   DEBUG(dbgs() << "RHS: " << *RHS << "\n");
379   DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n");
380 
381   auto CanExpand = [this](const SCEV *S) {
382     return SE->isLoopInvariant(S, L) && isSafeToExpand(S, *SE);
383   };
384   if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) ||
385       !CanExpand(LatchLimit) || !CanExpand(RHS)) {
386     DEBUG(dbgs() << "Can't expand limit check!\n");
387     return None;
388   }
389 
390   Instruction *InsertAt = Preheader->getTerminator();
391   auto *LimitCheck =
392       expandCheck(Expander, Builder, LimitCheckPred, LatchLimit, RHS, InsertAt);
393   auto *FirstIterationCheck = expandCheck(Expander, Builder, RangeCheck->Pred,
394                                           GuardStart, GuardLimit, InsertAt);
395   return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
396 }
397 
398 bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard,
399                                            SCEVExpander &Expander) {
400   DEBUG(dbgs() << "Processing guard:\n");
401   DEBUG(Guard->dump());
402 
403   IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator()));
404 
405   // The guard condition is expected to be in form of:
406   //   cond1 && cond2 && cond3 ...
407   // Iterate over subconditions looking for for icmp conditions which can be
408   // widened across loop iterations. Widening these conditions remember the
409   // resulting list of subconditions in Checks vector.
410   SmallVector<Value *, 4> Worklist(1, Guard->getOperand(0));
411   SmallPtrSet<Value *, 4> Visited;
412 
413   SmallVector<Value *, 4> Checks;
414 
415   unsigned NumWidened = 0;
416   do {
417     Value *Condition = Worklist.pop_back_val();
418     if (!Visited.insert(Condition).second)
419       continue;
420 
421     Value *LHS, *RHS;
422     using namespace llvm::PatternMatch;
423     if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) {
424       Worklist.push_back(LHS);
425       Worklist.push_back(RHS);
426       continue;
427     }
428 
429     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
430       if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, Builder)) {
431         Checks.push_back(NewRangeCheck.getValue());
432         NumWidened++;
433         continue;
434       }
435     }
436 
437     // Save the condition as is if we can't widen it
438     Checks.push_back(Condition);
439   } while (Worklist.size() != 0);
440 
441   if (NumWidened == 0)
442     return false;
443 
444   // Emit the new guard condition
445   Builder.SetInsertPoint(Guard);
446   Value *LastCheck = nullptr;
447   for (auto *Check : Checks)
448     if (!LastCheck)
449       LastCheck = Check;
450     else
451       LastCheck = Builder.CreateAnd(LastCheck, Check);
452   Guard->setOperand(0, LastCheck);
453 
454   DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
455   return true;
456 }
457 
458 Optional<LoopPredication::LoopICmp> LoopPredication::parseLoopLatchICmp() {
459   using namespace PatternMatch;
460 
461   BasicBlock *LoopLatch = L->getLoopLatch();
462   if (!LoopLatch) {
463     DEBUG(dbgs() << "The loop doesn't have a single latch!\n");
464     return None;
465   }
466 
467   ICmpInst::Predicate Pred;
468   Value *LHS, *RHS;
469   BasicBlock *TrueDest, *FalseDest;
470 
471   if (!match(LoopLatch->getTerminator(),
472              m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TrueDest,
473                   FalseDest))) {
474     DEBUG(dbgs() << "Failed to match the latch terminator!\n");
475     return None;
476   }
477   assert((TrueDest == L->getHeader() || FalseDest == L->getHeader()) &&
478          "One of the latch's destinations must be the header");
479   if (TrueDest != L->getHeader())
480     Pred = ICmpInst::getInversePredicate(Pred);
481 
482   auto Result = parseLoopICmp(Pred, LHS, RHS);
483   if (!Result) {
484     DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
485     return None;
486   }
487 
488   if (Result->Pred != ICmpInst::ICMP_ULT &&
489       Result->Pred != ICmpInst::ICMP_SLT &&
490       Result->Pred != ICmpInst::ICMP_ULE &&
491       Result->Pred != ICmpInst::ICMP_SLE) {
492     DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred
493                  << ")!\n");
494     return None;
495   }
496 
497   // Check affine first, so if it's not we don't try to compute the step
498   // recurrence.
499   if (!Result->IV->isAffine()) {
500     DEBUG(dbgs() << "The induction variable is not affine!\n");
501     return None;
502   }
503 
504   auto *Step = Result->IV->getStepRecurrence(*SE);
505   if (!Step->isOne()) {
506     DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n");
507     return None;
508   }
509 
510   return Result;
511 }
512 
513 bool LoopPredication::runOnLoop(Loop *Loop) {
514   L = Loop;
515 
516   DEBUG(dbgs() << "Analyzing ");
517   DEBUG(L->dump());
518 
519   Module *M = L->getHeader()->getModule();
520 
521   // There is nothing to do if the module doesn't use guards
522   auto *GuardDecl =
523       M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard));
524   if (!GuardDecl || GuardDecl->use_empty())
525     return false;
526 
527   DL = &M->getDataLayout();
528 
529   Preheader = L->getLoopPreheader();
530   if (!Preheader)
531     return false;
532 
533   auto LatchCheckOpt = parseLoopLatchICmp();
534   if (!LatchCheckOpt)
535     return false;
536   LatchCheck = *LatchCheckOpt;
537 
538   // Collect all the guards into a vector and process later, so as not
539   // to invalidate the instruction iterator.
540   SmallVector<IntrinsicInst *, 4> Guards;
541   for (const auto BB : L->blocks())
542     for (auto &I : *BB)
543       if (auto *II = dyn_cast<IntrinsicInst>(&I))
544         if (II->getIntrinsicID() == Intrinsic::experimental_guard)
545           Guards.push_back(II);
546 
547   if (Guards.empty())
548     return false;
549 
550   SCEVExpander Expander(*SE, *DL, "loop-predication");
551 
552   bool Changed = false;
553   for (auto *Guard : Guards)
554     Changed |= widenGuardConditions(Guard, Expander);
555 
556   return Changed;
557 }
558