[llvm] [LoopFlatten] Add option to version loops instead of widening IVs (PR #166156)

John Brawn via llvm-commits llvm-commits at lists.llvm.org
Mon Nov 3 07:50:13 PST 2025


================
@@ -961,30 +998,7 @@ static bool FlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
       return false;
     }
     LLVM_DEBUG(dbgs() << "Multiply might overflow, versioning loop\n");
-
-    // Version the loop. The overflow check isn't a runtime pointer check, so we
-    // pass an empty list of runtime pointer checks, causing LoopVersioning to
-    // emit 'false' as the branch condition, and add our own check afterwards.
-    BasicBlock *CheckBlock = FI.OuterLoop->getLoopPreheader();
-    ArrayRef<RuntimePointerCheck> Checks(nullptr, nullptr);
-    LoopVersioning LVer(LAI, Checks, FI.OuterLoop, LI, DT, SE);
-    LVer.versionLoop();
-
-    // Check for overflow by calculating the new tripcount using
-    // umul_with_overflow and then checking if it overflowed.
-    BranchInst *Br = cast<BranchInst>(CheckBlock->getTerminator());
-    assert(Br->isConditional() &&
-           "Expected LoopVersioning to generate a conditional branch");
-    assert(match(Br->getCondition(), m_Zero()) &&
-           "Expected branch condition to be false");
-    IRBuilder<> Builder(Br);
-    Value *Call = Builder.CreateIntrinsic(
-        Intrinsic::umul_with_overflow, FI.OuterTripCount->getType(),
-        {FI.OuterTripCount, FI.InnerTripCount},
-        /*FMFSource=*/nullptr, "flatten.mul");
-    FI.NewTripCount = Builder.CreateExtractValue(Call, 0, "flatten.tripcount");
-    Value *Overflow = Builder.CreateExtractValue(Call, 1, "flatten.overflow");
-    Br->setCondition(Overflow);
+    assert(VersionLoop(FI, DT, LI, SE, LAI) && "Failed to version loop");
----------------
john-brawn-arm wrote:

Calling VersionLoop inside the assert won't work in a no-asserts build, as it means VersionLoop won't get called at all. You need to assign the result to a bool variable, then use that inside the assert.

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


More information about the llvm-commits mailing list