37 #define DEBUG_TYPE "loop-cache-cost" 41 cl::desc(
"Use this to specify the default trip count of a loop"));
48 cl::desc(
"Use this to specify the max. distance between array elements " 49 "accessed in a loop so that the elements are classified to have " 57 assert(!Loops.
empty() &&
"Expecting a non-empy loop vector");
62 if (ParentLoop ==
nullptr) {
63 assert(Loops.
size() == 1 &&
"Expecting a single loop");
67 return (std::is_sorted(Loops.
begin(), Loops.
end(),
86 if (isa<SCEVAddRecExpr>(Start) || isa<SCEVAddRecExpr>(Step))
100 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
101 !isa<SCEVConstant>(BackedgeTakenCount))
113 OS << R.StoreOrLoadInst;
114 OS <<
", IsValid=false.";
118 OS << *R.BasePointer;
119 for (
const SCEV *Subscript : R.Subscripts)
120 OS <<
"[" << *Subscript <<
"]";
124 OS <<
"[" << *Size <<
"]";
131 : StoreOrLoadInst(StoreOrLoadInst), SE(SE) {
132 assert((isa<StoreInst>(StoreOrLoadInst) || isa<LoadInst>(StoreOrLoadInst)) &&
133 "Expecting a load or store instruction");
135 IsValid = delinearize(LI);
137 LLVM_DEBUG(
dbgs().indent(2) <<
"Succesfully delinearized: " << *
this 144 assert(IsValid &&
"Expecting a valid reference");
146 if (BasePointer != Other.
getBasePointer() && !isAliased(Other, AA)) {
148 <<
"No spacial reuse: different base pointers\n");
155 <<
"No spacial reuse: different number of subscripts\n");
160 for (
auto SubNum : seq<unsigned>(0, NumSubscripts - 1)) {
162 LLVM_DEBUG(
dbgs().indent(2) <<
"No spacial reuse, different subscripts: " 176 if (Diff ==
nullptr) {
178 <<
"No spacial reuse, difference between subscript:\n\t" 179 << *LastSubscript <<
"\n\t" << OtherLastSubscript
180 <<
"\nis not constant.\n");
188 dbgs().indent(2) <<
"Found spacial reuse.\n";
193 return InSameCacheLine;
197 unsigned MaxDistance,
201 assert(IsValid &&
"Expecting a valid reference");
203 if (BasePointer != Other.
getBasePointer() && !isAliased(Other, AA)) {
205 <<
"No temporal reuse: different base pointer\n");
209 std::unique_ptr<Dependence>
D =
210 DI.
depends(&StoreOrLoadInst, &Other.StoreOrLoadInst,
true);
213 LLVM_DEBUG(
dbgs().indent(2) <<
"No temporal reuse: no dependence\n");
217 if (D->isLoopIndependent()) {
226 int Levels = D->getLevels();
228 const SCEV *Distance = D->getDistance(
Level);
229 const SCEVConstant *SCEVConst = dyn_cast_or_null<SCEVConstant>(Distance);
231 if (SCEVConst ==
nullptr) {
232 LLVM_DEBUG(
dbgs().indent(2) <<
"No temporal reuse: distance unknown\n");
239 <<
"No temporal reuse: distance is not zero at depth=" <<
Level 245 <<
"No temporal reuse: distance is greater than MaxDistance at depth=" 256 unsigned CLS)
const {
257 assert(IsValid &&
"Expecting a valid reference");
259 dbgs().
indent(2) <<
"Computing cache cost for:\n";
264 if (isLoopInvariant(L)) {
265 LLVM_DEBUG(
dbgs().indent(4) <<
"Reference is loop invariant: RefCost=1\n");
272 <<
" could not be computed, using DefaultTripCount\n");
273 const SCEV *ElemSize = Sizes.back();
280 const SCEV *RefCost = TripCount;
282 if (isConsecutive(L, CLS)) {
283 const SCEV *Coeff = getLastCoefficient();
284 const SCEV *ElemSize = Sizes.back();
291 RefCost = SE.
getUDivExpr(Numerator, CacheLineSize);
293 <<
"Access is consecutive: RefCost=(TripCount*Stride)/CLS=" 294 << *RefCost <<
"\n");
297 <<
"Access is not consecutive: RefCost=TripCount=" << *RefCost
301 if (
auto ConstantCost = dyn_cast<SCEVConstant>(RefCost))
302 return ConstantCost->getValue()->getSExtValue();
305 <<
"RefCost is not a constant! Setting to RefCost=InvalidCost " 306 "(invalid value).\n");
311 bool IndexedReference::delinearize(
const LoopInfo &LI) {
312 assert(Subscripts.empty() &&
"Subscripts should be empty");
313 assert(Sizes.empty() &&
"Sizes should be empty");
314 assert(!IsValid &&
"Should be called once from the constructor");
315 LLVM_DEBUG(
dbgs() <<
"Delinearizing: " << StoreOrLoadInst <<
"\n");
321 const SCEV *AccessFn =
325 if (BasePointer ==
nullptr) {
328 <<
"ERROR: failed to delinearize, can't identify base pointer\n");
335 <<
"', AccessFn: " << *AccessFn <<
"\n");
340 if (Subscripts.empty() || Sizes.empty() ||
341 Subscripts.size() != Sizes.size()) {
346 <<
"ERROR: failed to delinearize reference\n");
353 Subscripts.push_back(Div);
354 Sizes.push_back(ElemSize);
357 return all_of(Subscripts, [&](
const SCEV *Subscript) {
358 return isSimpleAddRecurrence(*Subscript, *L);
365 bool IndexedReference::isLoopInvariant(
const Loop &L)
const {
367 assert(Addr !=
nullptr &&
"Expecting either a load or a store instruction");
375 bool allCoeffForLoopAreZero =
all_of(Subscripts, [&](
const SCEV *Subscript) {
376 return isCoeffForLoopZeroOrInvariant(*Subscript, L);
379 return allCoeffForLoopAreZero;
382 bool IndexedReference::isConsecutive(
const Loop &L,
unsigned CLS)
const {
385 const SCEV *LastSubscript = Subscripts.back();
386 for (
const SCEV *Subscript : Subscripts) {
387 if (Subscript == LastSubscript)
389 if (!isCoeffForLoopZeroOrInvariant(*Subscript, L))
394 const SCEV *Coeff = getLastCoefficient();
395 const SCEV *ElemSize = Sizes.back();
402 const SCEV *IndexedReference::getLastCoefficient()
const {
404 assert(isa<SCEVAddRecExpr>(LastSubscript) &&
405 "Expecting a SCEV add recurrence expression");
410 bool IndexedReference::isCoeffForLoopZeroOrInvariant(
const SCEV &Subscript,
411 const Loop &L)
const {
413 return (AR !=
nullptr) ? AR->
getLoop() != &L
417 bool IndexedReference::isSimpleAddRecurrence(
const SCEV &Subscript,
418 const Loop &L)
const {
419 if (!isa<SCEVAddRecExpr>(Subscript))
448 for (
const auto &LC : CC.LoopCosts) {
449 const Loop *L = LC.first;
450 OS <<
"Loop '" << L->
getName() <<
"' has cost = " << LC.second <<
"\n";
459 : Loops(Loops), TripCounts(), LoopCosts(),
461 LI(LI), SE(SE), TTI(TTI), AA(AA), DI(DI) {
462 assert(!Loops.
empty() &&
"Expecting a non-empty loop vector.");
464 for (
const Loop *L : Loops) {
470 calculateCacheFootprint();
473 std::unique_ptr<CacheCost>
477 LLVM_DEBUG(
dbgs() <<
"Expecting the outermost loop in a loop nest\n");
486 LLVM_DEBUG(
dbgs() <<
"Cannot compute cache cost of loop nest with more " 487 "than one innermost loop\n");
491 return std::make_unique<CacheCost>(Loops, AR.
LI, AR.
SE, AR.
TTI, AR.
AA, DI, TRT);
494 void CacheCost::calculateCacheFootprint() {
497 if (!populateReferenceGroups(RefGroups))
501 for (
const Loop *L : Loops) {
503 [L](
const LoopCacheCostTy &LCC) {
504 return LCC.first == L;
505 }) == LoopCosts.
end()) &&
506 "Should not add duplicate element");
507 CacheCostTy LoopCost = computeLoopCacheCost(*L, RefGroups);
508 LoopCosts.
push_back(std::make_pair(L, LoopCost));
516 assert(RefGroups.
empty() &&
"Reference groups should be empty");
520 assert(InnerMostLoop !=
nullptr &&
"Expecting a valid innermost loop");
524 if (!isa<StoreInst>(
I) && !isa<LoadInst>(
I))
535 dbgs() <<
"References:\n";
541 R->hasTemporalReuse(Representative, *TRT, *InnerMostLoop, DI, AA);
543 R->hasSpacialReuse(Representative, CLS, AA);
545 if ((HasTemporalReuse.hasValue() && *HasTemporalReuse) ||
546 (HasSpacialReuse.
hasValue() && *HasSpacialReuse)) {
547 RefGroup.push_back(std::move(R));
556 RefGroups.push_back(std::move(RG));
561 if (RefGroups.
empty())
565 dbgs() <<
"\nIDENTIFIED REFERENCE GROUPS:\n";
568 dbgs().
indent(2) <<
"RefGroup " << n <<
":\n";
569 for (
const auto &
IR : RG)
580 CacheCost::computeLoopCacheCost(
const Loop &L,
586 <<
"' as innermost loop.\n");
590 for (
const auto &TC : TripCounts) {
593 TripCountsProduct *= TC.second;
598 CacheCostTy RefGroupCost = computeRefGroupCacheCost(RG, L);
599 LoopCost += RefGroupCost * TripCountsProduct;
603 <<
"' has cost=" << LoopCost <<
"\n");
609 const Loop &L)
const {
610 assert(!RG.
empty() &&
"Reference group should have at least one member.");
unsigned getSmallConstantTripCount(const Loop *L)
Returns the maximum trip count of the loop if it is a single-exit loop and we can compute a small max...
This routine provides some synthesis utilities to produce sequences of values.
static std::unique_ptr< CacheCost > getCacheCost(Loop &Root, LoopStandardAnalysisResults &AR, DependenceInfo &DI, Optional< unsigned > TRT=None)
Create a CacheCost for the loop nest rooted by Root.
const SCEV * getConstant(ConstantInt *V)
This class represents lattice values for constants.
void delinearize(const SCEV *Expr, SmallVectorImpl< const SCEV *> &Subscripts, SmallVectorImpl< const SCEV *> &Sizes, const SCEV *ElementSize)
Split this SCEVAddRecExpr into two vectors of SCEVs representing the subscripts and sizes of an array...
static cl::opt< unsigned > TemporalReuseThreshold("temporal-reuse-threshold", cl::init(2), cl::Hidden, cl::desc("Use this to specify the max. distance between array elements " "accessed in a loop so that the elements are classified to have " "temporal reuse"))
static bool isOneDimensionalArray(const SCEV &AccessFn, const SCEV &ElemSize, const Loop &L, ScalarEvolution &SE)
unsigned getLoopDepth() const
Return the nesting level of this loop.
void push_back(const T &Elt)
const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
The main scalar evolution driver.
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
iterator_range< bf_iterator< T > > breadth_first(const T &G)
bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
DependenceInfo - This class is the main dependence-analysis driver.
static Loop * getInnerMostLoop(const LoopVectorTy &Loops)
Retrieve the innermost loop in the given loop nest Loops.
const Loop * getLoop() const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
BlockT * getHeader() const
ConstantInt * getValue() const
bool isKnownPredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS...
Type * getType() const
All values are typed, get the type of this value.
This node represents a polynomial recurrence on the trip count of the specified loop.
static cl::opt< unsigned > DefaultTripCount("default-trip-count", cl::init(100), cl::Hidden, cl::desc("Use this to specify the default trip count of a loop"))
CacheCost represents the estimated cost of a inner loop as the number of cache lines used by the memo...
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
initializer< Ty > init(const Ty &Val)
std::unique_ptr< Dependence > depends(Instruction *Src, Instruction *Dst, bool PossiblyLoopIndependent)
depends - Tests for a dependence between the Src and Dst instructions.
A set of analyses that are preserved following a run of a transformation pass.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
const SCEV * getAddExpr(SmallVectorImpl< const SCEV *> &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
const SCEV * getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
static const SCEV * computeTripCount(const Loop &L, ScalarEvolution &SE)
Compute the trip count for the given loop L.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values...
Optional< bool > hasSpacialReuse(const IndexedReference &Other, unsigned CLS, AliasAnalysis &AA) const
Return true/false if the current object and the indexed reference Other are/aren't in the same cache ...
const SCEV * getStart() const
auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
const SCEV * getMulExpr(SmallVectorImpl< const SCEV *> &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
const SCEV * getUDivExactExpr(const SCEV *LHS, const SCEV *RHS)
Get a canonical unsigned division expression, or something simpler if possible.
TargetTransformInfo & TTI
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
size_t getNumSubscripts() const
const SCEV * getSubscript(unsigned SubNum) const
This is the shared class of boolean and integer constants.
Type * getType() const
Return the LLVM type of this SCEV expression.
Optional< bool > hasTemporalReuse(const IndexedReference &Other, unsigned MaxDistance, const Loop &L, DependenceInfo &DI, AliasAnalysis &AA) const
Return true if the current object and the indexed reference Other have distance smaller than MaxDista...
Represents a memory reference as a base pointer and a set of indexing operations. ...
const SCEV * getNoopOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
const SCEV * getLastSubscript() const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
IndexedReference(Instruction &StoreOrLoadInst, const LoopInfo &LI, ScalarEvolution &SE)
Construct an indexed reference given a StoreOrLoadInst instruction.
static CacheCostTy constexpr InvalidCost
CacheCost(const LoopVectorTy &Loops, const LoopInfo &LI, ScalarEvolution &SE, TargetTransformInfo &TTI, AliasAnalysis &AA, DependenceInfo &DI, Optional< unsigned > TRT=None)
Construct a CacheCost object for the loop nest described by Loops.
Type * getWiderType(Type *Ty1, Type *Ty2) const
bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB)
A trivial helper function to check to see if the specified pointers are must-alias.
const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LoopT * getParentLoop() const
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to...
This class represents an analyzed expression in the program.
LLVM_NODISCARD bool empty() const
StringRef getName() const
Represents a single loop in the control flow graph.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
const Function * getParent() const
Return the enclosing method, or null if none.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
This file defines the interface for the loop cache analysis.
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
CacheCostTy computeRefCost(const Loop &L, unsigned CLS) const
Compute the cost of the reference w.r.t.
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
const SCEV * getBasePointer() const
This class implements an extremely fast bulk output stream that can only output to a stream...
const SCEV * getUDivExpr(const SCEV *LHS, const SCEV *RHS)
Get a canonical unsigned division expression, or something simpler if possible.
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
A container for analyses that lazily runs them and caches their results.
const SCEV * getElementSize(Instruction *Inst)
Return the size of an element read or written by Inst.
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
const SCEV * getNoopOrAnyExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
Statically lint checks LLVM IR
const BasicBlock * getParent() const
This class represents a constant integer value.