[llvm] [LoopPeel] Implement initial peeling off the last loop iteration. (PR #139551)

Philip Reames via llvm-commits llvm-commits at lists.llvm.org
Wed May 14 07:36:11 PDT 2025


================
@@ -325,19 +326,71 @@ static unsigned peelToTurnInvariantLoadsDerefencebale(Loop &L,
   return 0;
 }
 
-// Return the number of iterations to peel off that make conditions in the
-// body true/false. For example, if we peel 2 iterations off the loop below,
-// the condition i < 2 can be evaluated at compile time.
+bool llvm::canPeelLastIteration(const Loop &L, ScalarEvolution &SE) {
+  const SCEV *BTC = SE.getBackedgeTakenCount(&L);
+  Value *Inc;
+  CmpPredicate Pred;
+  BasicBlock *Succ1;
+  BasicBlock *Succ2;
+  // The loop must execute at least 2 iterations to guarantee that peeled
+  // iteration executes.
+  // TODO: Add checks during codegen.
+  if (isa<SCEVCouldNotCompute>(BTC) ||
----------------
preames wrote:

I released this condition is actually stronger than you need.  This is the backedge taken count, not the trip count.  As a result, you just need a non-zero BTC to ensure there are at least two iterations of the loop run, and that peeling is safe.  

https://github.com/llvm/llvm-project/pull/139551


More information about the llvm-commits mailing list