diff options
author | Ramkumar Ramachandra <ramkumar.ramachandra@codasip.com> | 2025-03-04 08:43:08 +0000 |
---|---|---|
committer | GitHub <noreply@github.com> | 2025-03-04 08:43:08 +0000 |
commit | 80bdfcd411cd8197b0a8b6139b89a87d3a4528fa (patch) | |
tree | a24c9065fa4d698a257bf1228c58733e6e625eaa /llvm/lib/Transforms/Utils/LoopUtils.cpp | |
parent | 23a30e68888e764b2f4d32e51d415b50fa5f5cac (diff) | |
download | llvm-80bdfcd411cd8197b0a8b6139b89a87d3a4528fa.zip llvm-80bdfcd411cd8197b0a8b6139b89a87d3a4528fa.tar.gz llvm-80bdfcd411cd8197b0a8b6139b89a87d3a4528fa.tar.bz2 |
[LoopUtils] Don't wrap in getLoopEstimatedTripCount (#129080)
getLoopEstimatedTripCount returns the trip count based on profiling
data, and its documentation says that it could return 0 when the trip
count is zero, but this is not the case: a valid trip count can never be
zero, and it returns 0 when the unsigned ExitCount is incremented by 1
and wraps. Some callers are careful about checking for this zero value
in an std::optional, but it makes for an API with footguns, as a
std::optional return value indicates that a non-nullopt value would be a
valid trip count. Fix this by explicitly returning std::nullopt when the
return value would wrap, and strip additional checks in callers. This
also fixes a minor bug in LoopVectorize.
Diffstat (limited to 'llvm/lib/Transforms/Utils/LoopUtils.cpp')
-rw-r--r-- | llvm/lib/Transforms/Utils/LoopUtils.cpp | 7 |
1 files changed, 6 insertions, 1 deletions
diff --git a/llvm/lib/Transforms/Utils/LoopUtils.cpp b/llvm/lib/Transforms/Utils/LoopUtils.cpp index 0506ea9..ec1692a 100644 --- a/llvm/lib/Transforms/Utils/LoopUtils.cpp +++ b/llvm/lib/Transforms/Utils/LoopUtils.cpp @@ -820,7 +820,7 @@ static BranchInst *getExpectedExitLoopLatchBranch(Loop *L) { /// Return the estimated trip count for any exiting branch which dominates /// the loop latch. -static std::optional<uint64_t> getEstimatedTripCount(BranchInst *ExitingBranch, +static std::optional<unsigned> getEstimatedTripCount(BranchInst *ExitingBranch, Loop *L, uint64_t &OrigExitWeight) { // To estimate the number of times the loop body was executed, we want to @@ -842,6 +842,11 @@ static std::optional<uint64_t> getEstimatedTripCount(BranchInst *ExitingBranch, // Estimated exit count is a ratio of the loop weight by the weight of the // edge exiting the loop, rounded to nearest. uint64_t ExitCount = llvm::divideNearest(LoopWeight, ExitWeight); + + // When ExitCount + 1 would wrap in unsigned, return std::nullopt instead. + if (ExitCount >= std::numeric_limits<unsigned>::max()) + return std::nullopt; + // Estimated trip count is one plus estimated exit count. return ExitCount + 1; } |