[llvm] [LoopUtils] prevent negative estimated trip count result (PR #195610)
Arda Serdar Pektezol via llvm-commits
llvm-commits at lists.llvm.org
Tue May 5 12:57:32 PDT 2026
pektezol wrote:
> > @jdenny-ornl so, should we keep it like this and merge it?
>
> No. I suggest treating estimated trip counts as unsigned:
>
> ```
> diff --git a/llvm/lib/Transforms/Utils/LoopPeel.cpp b/llvm/lib/Transforms/Utils/LoopPeel.cpp
> index 4c67d5a9ae68..3ae2a7819008 100644
> --- a/llvm/lib/Transforms/Utils/LoopPeel.cpp
> +++ b/llvm/lib/Transforms/Utils/LoopPeel.cpp
> @@ -32,6 +32,7 @@
> #include "llvm/IR/PatternMatch.h"
> #include "llvm/IR/ProfDataUtils.h"
> #include "llvm/Support/Casting.h"
> +#include "llvm/Support/CheckedArithmetic.h"
> #include "llvm/Support/CommandLine.h"
> #include "llvm/Support/Debug.h"
> #include "llvm/Support/raw_ostream.h"
> @@ -876,7 +877,9 @@ void llvm::computePeelCount(Loop *L, unsigned LoopSize,
> LLVM_DEBUG(dbgs() << "Profile-based estimated trip count is "
> << *EstimatedTripCount << "\n");
>
> - if (*EstimatedTripCount + AlreadyPeeled <= MaxPeelCount) {
> + std::optional<unsigned> TotalPeeled =
> + llvm::checkedAddUnsigned(*EstimatedTripCount, AlreadyPeeled);
> + if (TotalPeeled && *TotalPeeled <= MaxPeelCount) {
> unsigned PeelCount = *EstimatedTripCount;
> LLVM_DEBUG(dbgs() << "Peeling first " << PeelCount << " iterations.\n");
> PP.PeelCount = PeelCount;
> diff --git a/llvm/lib/Transforms/Utils/LoopUtils.cpp b/llvm/lib/Transforms/Utils/LoopUtils.cpp
> index 9c7d10629adf..b97be6e40da0 100644
> --- a/llvm/lib/Transforms/Utils/LoopUtils.cpp
> +++ b/llvm/lib/Transforms/Utils/LoopUtils.cpp
> @@ -926,7 +926,8 @@ llvm::getLoopEstimatedTripCount(Loop *L,
> // historically assume that llvm::getLoopEstimatedTripCount always returns a
> // positive count or std::nullopt. Thus, return std::nullopt when
> // llvm.loop.estimated_trip_count is 0.
> - if (auto TC = getOptionalIntLoopAttribute(L, LLVMLoopEstimatedTripCount)) {
> + if (std::optional<unsigned> TC =
> + getOptionalIntLoopAttribute(L, LLVMLoopEstimatedTripCount)) {
> LLVM_DEBUG(dbgs() << "getLoopEstimatedTripCount: "
> << LLVMLoopEstimatedTripCount << " metadata has trip "
> << "count of " << *TC
> ```
Ah yes. Updated, thank you for the review!
https://github.com/llvm/llvm-project/pull/195610
More information about the llvm-commits
mailing list