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