llvm::getLoopEstimatedTripCount

Return an estimated trip count for L, or std::nullopt if unavailable.

Synopsis

Declared in <llvm/Transforms/Utils/LoopUtils.h>

std::optional<unsigned int>
getLoopEstimatedTripCount(
    Loop* L,
    unsigned int* EstimatedLoopInvocationWeight = nullptr);

Description

Return either:

  • std::nullopt, if the implementation is unable to handle the loop form of L (e.g., L must have a latch block that controls the loop exit).

  • The value of llvm.loop.estimated_trip_count from the loop metadata of L, if that metadata is present.

  • Else, a new estimate of the trip count from the latch branch weights of L.

An estimate of zero is meaningful: it indicates that L is estimated not to be entered, that is, that its header is not reached. For example, after peeling 10 or more iterations from a loop with an estimated trip count of 10, llvm.loop.estimated_trip_count becomes 0 on the remaining loop. Callers that need a positive trip count must check for zero.

An estimated trip count is saturated at UINT_MAX.

In addition, if EstimatedLoopInvocationWeight, then either:

  • Set *EstimatedLoopInvocationWeight to the weight of the latch's branch to the loop exit.

  • Do not set it, and return std::nullopt, if the current implementation cannot compute that weight (e.g., if L does not have a latch block that controls the loop exit) or the weight is zero (because zero cannot be used to compute new branch weights that reflect the estimated trip count).

TODO: Eventually, once all passes have migrated away from setting branch weights to indicate estimated trip counts, this function will drop the EstimatedLoopInvocationWeight parameter.

Return Value

The estimated trip count, or std::nullopt if unavailable.

Parameters

NameDescription
LThe loop whose trip count is estimated.
EstimatedLoopInvocationWeightOptional out-parameter for latch exit weight.