1 //===- LoopCacheAnalysis.cpp - Loop Cache Analysis -------------------------==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
6 // See https://llvm.org/LICENSE.txt for license information.
7 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
8 //
9 //===----------------------------------------------------------------------===//
10 ///
11 /// \file
12 /// This file defines the implementation for the loop cache analysis.
13 /// The implementation is largely based on the following paper:
14 ///
15 ///       Compiler Optimizations for Improving Data Locality
16 ///       By: Steve Carr, Katherine S. McKinley, Chau-Wen Tseng
17 ///       http://www.cs.utexas.edu/users/mckinley/papers/asplos-1994.pdf
18 ///
19 /// The general approach taken to estimate the number of cache lines used by the
20 /// memory references in an inner loop is:
21 ///    1. Partition memory references that exhibit temporal or spacial reuse
22 ///       into reference groups.
23 ///    2. For each loop L in the a loop nest LN:
24 ///       a. Compute the cost of the reference group
25 ///       b. Compute the loop cost by summing up the reference groups costs
26 //===----------------------------------------------------------------------===//
27 
28 #include "llvm/Analysis/LoopCacheAnalysis.h"
29 #include "llvm/ADT/BreadthFirstIterator.h"
30 #include "llvm/ADT/Sequence.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 
35 using namespace llvm;
36 
37 #define DEBUG_TYPE "loop-cache-cost"
38 
39 static cl::opt<unsigned> DefaultTripCount(
40     "default-trip-count", cl::init(100), cl::Hidden,
41     cl::desc("Use this to specify the default trip count of a loop"));
42 
43 // In this analysis two array references are considered to exhibit temporal
44 // reuse if they access either the same memory location, or a memory location
45 // with distance smaller than a configurable threshold.
46 static cl::opt<unsigned> TemporalReuseThreshold(
47     "temporal-reuse-threshold", cl::init(2), cl::Hidden,
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 "
50              "temporal reuse"));
51 
52 /// Retrieve the innermost loop in the given loop nest \p Loops. It returns a
53 /// nullptr if any loops in the loop vector supplied has more than one sibling.
54 /// The loop vector is expected to contain loops collected in breadth-first
55 /// order.
56 static Loop *getInnerMostLoop(const LoopVectorTy &Loops) {
57   assert(!Loops.empty() && "Expecting a non-empy loop vector");
58 
59   Loop *LastLoop = Loops.back();
60   Loop *ParentLoop = LastLoop->getParentLoop();
61 
62   if (ParentLoop == nullptr) {
63     assert(Loops.size() == 1 && "Expecting a single loop");
64     return LastLoop;
65   }
66 
67   return (std::is_sorted(Loops.begin(), Loops.end(),
68                          [](const Loop *L1, const Loop *L2) {
69                            return L1->getLoopDepth() < L2->getLoopDepth();
70                          }))
71              ? LastLoop
72              : nullptr;
73 }
74 
75 static bool isOneDimensionalArray(const SCEV &AccessFn, const SCEV &ElemSize,
76                                   const Loop &L, ScalarEvolution &SE) {
77   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(&AccessFn);
78   if (!AR || !AR->isAffine())
79     return false;
80 
81   assert(AR->getLoop() && "AR should have a loop");
82 
83   // Check that start and increment are not add recurrences.
84   const SCEV *Start = AR->getStart();
85   const SCEV *Step = AR->getStepRecurrence(SE);
86   if (isa<SCEVAddRecExpr>(Start) || isa<SCEVAddRecExpr>(Step))
87     return false;
88 
89   // Check that start and increment are both invariant in the loop.
90   if (!SE.isLoopInvariant(Start, &L) || !SE.isLoopInvariant(Step, &L))
91     return false;
92 
93   return AR->getStepRecurrence(SE) == &ElemSize;
94 }
95 
96 /// Compute the trip count for the given loop \p L. Return the SCEV expression
97 /// for the trip count or nullptr if it cannot be computed.
98 static const SCEV *computeTripCount(const Loop &L, ScalarEvolution &SE) {
99   const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(&L);
100   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
101       !isa<SCEVConstant>(BackedgeTakenCount))
102     return nullptr;
103 
104   return SE.getAddExpr(BackedgeTakenCount,
105                        SE.getOne(BackedgeTakenCount->getType()));
106 }
107 
108 //===----------------------------------------------------------------------===//
109 // IndexedReference implementation
110 //
111 raw_ostream &llvm::operator<<(raw_ostream &OS, const IndexedReference &R) {
112   if (!R.IsValid) {
113     OS << R.StoreOrLoadInst;
114     OS << ", IsValid=false.";
115     return OS;
116   }
117 
118   OS << *R.BasePointer;
119   for (const SCEV *Subscript : R.Subscripts)
120     OS << "[" << *Subscript << "]";
121 
122   OS << ", Sizes: ";
123   for (const SCEV *Size : R.Sizes)
124     OS << "[" << *Size << "]";
125 
126   return OS;
127 }
128 
129 IndexedReference::IndexedReference(Instruction &StoreOrLoadInst,
130                                    const LoopInfo &LI, ScalarEvolution &SE)
131     : StoreOrLoadInst(StoreOrLoadInst), SE(SE) {
132   assert((isa<StoreInst>(StoreOrLoadInst) || isa<LoadInst>(StoreOrLoadInst)) &&
133          "Expecting a load or store instruction");
134 
135   IsValid = delinearize(LI);
136   if (IsValid)
137     LLVM_DEBUG(dbgs().indent(2) << "Succesfully delinearized: " << *this
138                                 << "\n");
139 }
140 
141 Optional<bool> IndexedReference::hasSpacialReuse(const IndexedReference &Other,
142                                                  unsigned CLS,
143                                                  AliasAnalysis &AA) const {
144   assert(IsValid && "Expecting a valid reference");
145 
146   if (BasePointer != Other.getBasePointer() && !isAliased(Other, AA)) {
147     LLVM_DEBUG(dbgs().indent(2)
148                << "No spacial reuse: different base pointers\n");
149     return false;
150   }
151 
152   unsigned NumSubscripts = getNumSubscripts();
153   if (NumSubscripts != Other.getNumSubscripts()) {
154     LLVM_DEBUG(dbgs().indent(2)
155                << "No spacial reuse: different number of subscripts\n");
156     return false;
157   }
158 
159   // all subscripts must be equal, except the leftmost one (the last one).
160   for (auto SubNum : seq<unsigned>(0, NumSubscripts - 1)) {
161     if (getSubscript(SubNum) != Other.getSubscript(SubNum)) {
162       LLVM_DEBUG(dbgs().indent(2) << "No spacial reuse, different subscripts: "
163                                   << "\n\t" << *getSubscript(SubNum) << "\n\t"
164                                   << *Other.getSubscript(SubNum) << "\n");
165       return false;
166     }
167   }
168 
169   // the difference between the last subscripts must be less than the cache line
170   // size.
171   const SCEV *LastSubscript = getLastSubscript();
172   const SCEV *OtherLastSubscript = Other.getLastSubscript();
173   const SCEVConstant *Diff = dyn_cast<SCEVConstant>(
174       SE.getMinusSCEV(LastSubscript, OtherLastSubscript));
175 
176   if (Diff == nullptr) {
177     LLVM_DEBUG(dbgs().indent(2)
178                << "No spacial reuse, difference between subscript:\n\t"
179                << *LastSubscript << "\n\t" << OtherLastSubscript
180                << "\nis not constant.\n");
181     return None;
182   }
183 
184   bool InSameCacheLine = (Diff->getValue()->getSExtValue() < CLS);
185 
186   LLVM_DEBUG({
187     if (InSameCacheLine)
188       dbgs().indent(2) << "Found spacial reuse.\n";
189     else
190       dbgs().indent(2) << "No spacial reuse.\n";
191   });
192 
193   return InSameCacheLine;
194 }
195 
196 Optional<bool> IndexedReference::hasTemporalReuse(const IndexedReference &Other,
197                                                   unsigned MaxDistance,
198                                                   const Loop &L,
199                                                   DependenceInfo &DI,
200                                                   AliasAnalysis &AA) const {
201   assert(IsValid && "Expecting a valid reference");
202 
203   if (BasePointer != Other.getBasePointer() && !isAliased(Other, AA)) {
204     LLVM_DEBUG(dbgs().indent(2)
205                << "No temporal reuse: different base pointer\n");
206     return false;
207   }
208 
209   std::unique_ptr<Dependence> D =
210       DI.depends(&StoreOrLoadInst, &Other.StoreOrLoadInst, true);
211 
212   if (D == nullptr) {
213     LLVM_DEBUG(dbgs().indent(2) << "No temporal reuse: no dependence\n");
214     return false;
215   }
216 
217   if (D->isLoopIndependent()) {
218     LLVM_DEBUG(dbgs().indent(2) << "Found temporal reuse\n");
219     return true;
220   }
221 
222   // Check the dependence distance at every loop level. There is temporal reuse
223   // if the distance at the given loop's depth is small (|d| <= MaxDistance) and
224   // it is zero at every other loop level.
225   int LoopDepth = L.getLoopDepth();
226   int Levels = D->getLevels();
227   for (int Level = 1; Level <= Levels; ++Level) {
228     const SCEV *Distance = D->getDistance(Level);
229     const SCEVConstant *SCEVConst = dyn_cast_or_null<SCEVConstant>(Distance);
230 
231     if (SCEVConst == nullptr) {
232       LLVM_DEBUG(dbgs().indent(2) << "No temporal reuse: distance unknown\n");
233       return None;
234     }
235 
236     const ConstantInt &CI = *SCEVConst->getValue();
237     if (Level != LoopDepth && !CI.isZero()) {
238       LLVM_DEBUG(dbgs().indent(2)
239                  << "No temporal reuse: distance is not zero at depth=" << Level
240                  << "\n");
241       return false;
242     } else if (Level == LoopDepth && CI.getSExtValue() > MaxDistance) {
243       LLVM_DEBUG(
244           dbgs().indent(2)
245           << "No temporal reuse: distance is greater than MaxDistance at depth="
246           << Level << "\n");
247       return false;
248     }
249   }
250 
251   LLVM_DEBUG(dbgs().indent(2) << "Found temporal reuse\n");
252   return true;
253 }
254 
255 CacheCostTy IndexedReference::computeRefCost(const Loop &L,
256                                              unsigned CLS) const {
257   assert(IsValid && "Expecting a valid reference");
258   LLVM_DEBUG({
259     dbgs().indent(2) << "Computing cache cost for:\n";
260     dbgs().indent(4) << *this << "\n";
261   });
262 
263   // If the indexed reference is loop invariant the cost is one.
264   if (isLoopInvariant(L)) {
265     LLVM_DEBUG(dbgs().indent(4) << "Reference is loop invariant: RefCost=1\n");
266     return 1;
267   }
268 
269   const SCEV *TripCount = computeTripCount(L, SE);
270   if (!TripCount) {
271     LLVM_DEBUG(dbgs() << "Trip count of loop " << L.getName()
272                       << " could not be computed, using DefaultTripCount\n");
273     const SCEV *ElemSize = Sizes.back();
274     TripCount = SE.getConstant(ElemSize->getType(), DefaultTripCount);
275   }
276   LLVM_DEBUG(dbgs() << "TripCount=" << *TripCount << "\n");
277 
278   // If the indexed reference is 'consecutive' the cost is
279   // (TripCount*Stride)/CLS, otherwise the cost is TripCount.
280   const SCEV *RefCost = TripCount;
281 
282   if (isConsecutive(L, CLS)) {
283     const SCEV *Coeff = getLastCoefficient();
284     const SCEV *ElemSize = Sizes.back();
285     const SCEV *Stride = SE.getMulExpr(Coeff, ElemSize);
286     const SCEV *CacheLineSize = SE.getConstant(Stride->getType(), CLS);
287     const SCEV *Numerator = SE.getMulExpr(Stride, TripCount);
288     RefCost = SE.getUDivExpr(Numerator, CacheLineSize);
289     LLVM_DEBUG(dbgs().indent(4)
290                << "Access is consecutive: RefCost=(TripCount*Stride)/CLS="
291                << *RefCost << "\n");
292   } else
293     LLVM_DEBUG(dbgs().indent(4)
294                << "Access is not consecutive: RefCost=TripCount=" << *RefCost
295                << "\n");
296 
297   // Attempt to fold RefCost into a constant.
298   if (auto ConstantCost = dyn_cast<SCEVConstant>(RefCost))
299     return ConstantCost->getValue()->getSExtValue();
300 
301   LLVM_DEBUG(dbgs().indent(4)
302              << "RefCost is not a constant! Setting to RefCost=InvalidCost "
303                 "(invalid value).\n");
304 
305   return CacheCost::InvalidCost;
306 }
307 
308 bool IndexedReference::delinearize(const LoopInfo &LI) {
309   assert(Subscripts.empty() && "Subscripts should be empty");
310   assert(Sizes.empty() && "Sizes should be empty");
311   assert(!IsValid && "Should be called once from the constructor");
312   LLVM_DEBUG(dbgs() << "Delinearizing: " << StoreOrLoadInst << "\n");
313 
314   const SCEV *ElemSize = SE.getElementSize(&StoreOrLoadInst);
315   const BasicBlock *BB = StoreOrLoadInst.getParent();
316 
317   if (Loop *L = LI.getLoopFor(BB)) {
318     const SCEV *AccessFn =
319         SE.getSCEVAtScope(getPointerOperand(&StoreOrLoadInst), L);
320 
321     BasePointer = dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFn));
322     if (BasePointer == nullptr) {
323       LLVM_DEBUG(
324           dbgs().indent(2)
325           << "ERROR: failed to delinearize, can't identify base pointer\n");
326       return false;
327     }
328 
329     AccessFn = SE.getMinusSCEV(AccessFn, BasePointer);
330 
331     LLVM_DEBUG(dbgs().indent(2) << "In Loop '" << L->getName()
332                                 << "', AccessFn: " << *AccessFn << "\n");
333 
334     SE.delinearize(AccessFn, Subscripts, Sizes,
335                    SE.getElementSize(&StoreOrLoadInst));
336 
337     if (Subscripts.empty() || Sizes.empty() ||
338         Subscripts.size() != Sizes.size()) {
339       // Attempt to determine whether we have a single dimensional array access.
340       // before giving up.
341       if (!isOneDimensionalArray(*AccessFn, *ElemSize, *L, SE)) {
342         LLVM_DEBUG(dbgs().indent(2)
343                    << "ERROR: failed to delinearize reference\n");
344         Subscripts.clear();
345         Sizes.clear();
346         return false;
347       }
348 
349       const SCEV *Div = SE.getUDivExactExpr(AccessFn, ElemSize);
350       Subscripts.push_back(Div);
351       Sizes.push_back(ElemSize);
352     }
353 
354     return all_of(Subscripts, [&](const SCEV *Subscript) {
355       return isSimpleAddRecurrence(*Subscript, *L);
356     });
357   }
358 
359   return false;
360 }
361 
362 bool IndexedReference::isLoopInvariant(const Loop &L) const {
363   Value *Addr = getPointerOperand(&StoreOrLoadInst);
364   assert(Addr != nullptr && "Expecting either a load or a store instruction");
365   assert(SE.isSCEVable(Addr->getType()) && "Addr should be SCEVable");
366 
367   if (SE.isLoopInvariant(SE.getSCEV(Addr), &L))
368     return true;
369 
370   // The indexed reference is loop invariant if none of the coefficients use
371   // the loop induction variable.
372   bool allCoeffForLoopAreZero = all_of(Subscripts, [&](const SCEV *Subscript) {
373     return isCoeffForLoopZeroOrInvariant(*Subscript, L);
374   });
375 
376   return allCoeffForLoopAreZero;
377 }
378 
379 bool IndexedReference::isConsecutive(const Loop &L, unsigned CLS) const {
380   // The indexed reference is 'consecutive' if the only coefficient that uses
381   // the loop induction variable is the last one...
382   const SCEV *LastSubscript = Subscripts.back();
383   for (const SCEV *Subscript : Subscripts) {
384     if (Subscript == LastSubscript)
385       continue;
386     if (!isCoeffForLoopZeroOrInvariant(*Subscript, L))
387       return false;
388   }
389 
390   // ...and the access stride is less than the cache line size.
391   const SCEV *Coeff = getLastCoefficient();
392   const SCEV *ElemSize = Sizes.back();
393   const SCEV *Stride = SE.getMulExpr(Coeff, ElemSize);
394   const SCEV *CacheLineSize = SE.getConstant(Stride->getType(), CLS);
395 
396   return SE.isKnownPredicate(ICmpInst::ICMP_ULT, Stride, CacheLineSize);
397 }
398 
399 const SCEV *IndexedReference::getLastCoefficient() const {
400   const SCEV *LastSubscript = getLastSubscript();
401   assert(isa<SCEVAddRecExpr>(LastSubscript) &&
402          "Expecting a SCEV add recurrence expression");
403   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LastSubscript);
404   return AR->getStepRecurrence(SE);
405 }
406 
407 bool IndexedReference::isCoeffForLoopZeroOrInvariant(const SCEV &Subscript,
408                                                      const Loop &L) const {
409   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(&Subscript);
410   return (AR != nullptr) ? AR->getLoop() != &L
411                          : SE.isLoopInvariant(&Subscript, &L);
412 }
413 
414 bool IndexedReference::isSimpleAddRecurrence(const SCEV &Subscript,
415                                              const Loop &L) const {
416   if (!isa<SCEVAddRecExpr>(Subscript))
417     return false;
418 
419   const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(&Subscript);
420   assert(AR->getLoop() && "AR should have a loop");
421 
422   if (!AR->isAffine())
423     return false;
424 
425   const SCEV *Start = AR->getStart();
426   const SCEV *Step = AR->getStepRecurrence(SE);
427 
428   if (!SE.isLoopInvariant(Start, &L) || !SE.isLoopInvariant(Step, &L))
429     return false;
430 
431   return true;
432 }
433 
434 bool IndexedReference::isAliased(const IndexedReference &Other,
435                                  AliasAnalysis &AA) const {
436   const auto &Loc1 = MemoryLocation::get(&StoreOrLoadInst);
437   const auto &Loc2 = MemoryLocation::get(&Other.StoreOrLoadInst);
438   return AA.isMustAlias(Loc1, Loc2);
439 }
440 
441 //===----------------------------------------------------------------------===//
442 // CacheCost implementation
443 //
444 raw_ostream &llvm::operator<<(raw_ostream &OS, const CacheCost &CC) {
445   for (const auto &LC : CC.LoopCosts) {
446     const Loop *L = LC.first;
447     OS << "Loop '" << L->getName() << "' has cost = " << LC.second << "\n";
448   }
449   return OS;
450 }
451 
452 CacheCost::CacheCost(const LoopVectorTy &Loops, const LoopInfo &LI,
453                      ScalarEvolution &SE, TargetTransformInfo &TTI,
454                      AliasAnalysis &AA, DependenceInfo &DI,
455                      Optional<unsigned> TRT)
456     : Loops(Loops), TripCounts(), LoopCosts(),
457       TRT((TRT == None) ? Optional<unsigned>(TemporalReuseThreshold) : TRT),
458       LI(LI), SE(SE), TTI(TTI), AA(AA), DI(DI) {
459   assert(!Loops.empty() && "Expecting a non-empty loop vector.");
460 
461   for (const Loop *L : Loops) {
462     unsigned TripCount = SE.getSmallConstantTripCount(L);
463     TripCount = (TripCount == 0) ? DefaultTripCount : TripCount;
464     TripCounts.push_back({L, TripCount});
465   }
466 
467   calculateCacheFootprint();
468 }
469 
470 std::unique_ptr<CacheCost>
471 CacheCost::getCacheCost(Loop &Root, LoopStandardAnalysisResults &AR,
472                         DependenceInfo &DI, Optional<unsigned> TRT) {
473   if (Root.getParentLoop()) {
474     LLVM_DEBUG(dbgs() << "Expecting the outermost loop in a loop nest\n");
475     return nullptr;
476   }
477 
478   LoopVectorTy Loops;
479   for (Loop *L : breadth_first(&Root))
480     Loops.push_back(L);
481 
482   if (!getInnerMostLoop(Loops)) {
483     LLVM_DEBUG(dbgs() << "Cannot compute cache cost of loop nest with more "
484                          "than one innermost loop\n");
485     return nullptr;
486   }
487 
488   return std::make_unique<CacheCost>(Loops, AR.LI, AR.SE, AR.TTI, AR.AA, DI, TRT);
489 }
490 
491 void CacheCost::calculateCacheFootprint() {
492   LLVM_DEBUG(dbgs() << "POPULATING REFERENCE GROUPS\n");
493   ReferenceGroupsTy RefGroups;
494   if (!populateReferenceGroups(RefGroups))
495     return;
496 
497   LLVM_DEBUG(dbgs() << "COMPUTING LOOP CACHE COSTS\n");
498   for (const Loop *L : Loops) {
499     assert((std::find_if(LoopCosts.begin(), LoopCosts.end(),
500                          [L](const LoopCacheCostTy &LCC) {
501                            return LCC.first == L;
502                          }) == LoopCosts.end()) &&
503            "Should not add duplicate element");
504     CacheCostTy LoopCost = computeLoopCacheCost(*L, RefGroups);
505     LoopCosts.push_back(std::make_pair(L, LoopCost));
506   }
507 
508   sortLoopCosts();
509   RefGroups.clear();
510 }
511 
512 bool CacheCost::populateReferenceGroups(ReferenceGroupsTy &RefGroups) const {
513   assert(RefGroups.empty() && "Reference groups should be empty");
514 
515   unsigned CLS = TTI.getCacheLineSize();
516   Loop *InnerMostLoop = getInnerMostLoop(Loops);
517   assert(InnerMostLoop != nullptr && "Expecting a valid innermost loop");
518 
519   for (BasicBlock *BB : InnerMostLoop->getBlocks()) {
520     for (Instruction &I : *BB) {
521       if (!isa<StoreInst>(I) && !isa<LoadInst>(I))
522         continue;
523 
524       std::unique_ptr<IndexedReference> R(new IndexedReference(I, LI, SE));
525       if (!R->isValid())
526         continue;
527 
528       bool Added = false;
529       for (ReferenceGroupTy &RefGroup : RefGroups) {
530         const IndexedReference &Representative = *RefGroup.front().get();
531         LLVM_DEBUG({
532           dbgs() << "References:\n";
533           dbgs().indent(2) << *R << "\n";
534           dbgs().indent(2) << Representative << "\n";
535         });
536 
537         Optional<bool> HasTemporalReuse =
538             R->hasTemporalReuse(Representative, *TRT, *InnerMostLoop, DI, AA);
539         Optional<bool> HasSpacialReuse =
540             R->hasSpacialReuse(Representative, CLS, AA);
541 
542         if ((HasTemporalReuse.hasValue() && *HasTemporalReuse) ||
543             (HasSpacialReuse.hasValue() && *HasSpacialReuse)) {
544           RefGroup.push_back(std::move(R));
545           Added = true;
546           break;
547         }
548       }
549 
550       if (!Added) {
551         ReferenceGroupTy RG;
552         RG.push_back(std::move(R));
553         RefGroups.push_back(std::move(RG));
554       }
555     }
556   }
557 
558   if (RefGroups.empty())
559     return false;
560 
561   LLVM_DEBUG({
562     dbgs() << "\nIDENTIFIED REFERENCE GROUPS:\n";
563     int n = 1;
564     for (const ReferenceGroupTy &RG : RefGroups) {
565       dbgs().indent(2) << "RefGroup " << n << ":\n";
566       for (const auto &IR : RG)
567         dbgs().indent(4) << *IR << "\n";
568       n++;
569     }
570     dbgs() << "\n";
571   });
572 
573   return true;
574 }
575 
576 CacheCostTy
577 CacheCost::computeLoopCacheCost(const Loop &L,
578                                 const ReferenceGroupsTy &RefGroups) const {
579   if (!L.isLoopSimplifyForm())
580     return InvalidCost;
581 
582   LLVM_DEBUG(dbgs() << "Considering loop '" << L.getName()
583                     << "' as innermost loop.\n");
584 
585   // Compute the product of the trip counts of each other loop in the nest.
586   CacheCostTy TripCountsProduct = 1;
587   for (const auto &TC : TripCounts) {
588     if (TC.first == &L)
589       continue;
590     TripCountsProduct *= TC.second;
591   }
592 
593   CacheCostTy LoopCost = 0;
594   for (const ReferenceGroupTy &RG : RefGroups) {
595     CacheCostTy RefGroupCost = computeRefGroupCacheCost(RG, L);
596     LoopCost += RefGroupCost * TripCountsProduct;
597   }
598 
599   LLVM_DEBUG(dbgs().indent(2) << "Loop '" << L.getName()
600                               << "' has cost=" << LoopCost << "\n");
601 
602   return LoopCost;
603 }
604 
605 CacheCostTy CacheCost::computeRefGroupCacheCost(const ReferenceGroupTy &RG,
606                                                 const Loop &L) const {
607   assert(!RG.empty() && "Reference group should have at least one member.");
608 
609   const IndexedReference *Representative = RG.front().get();
610   return Representative->computeRefCost(L, TTI.getCacheLineSize());
611 }
612 
613 //===----------------------------------------------------------------------===//
614 // LoopCachePrinterPass implementation
615 //
616 PreservedAnalyses LoopCachePrinterPass::run(Loop &L, LoopAnalysisManager &AM,
617                                             LoopStandardAnalysisResults &AR,
618                                             LPMUpdater &U) {
619   Function *F = L.getHeader()->getParent();
620   DependenceInfo DI(F, &AR.AA, &AR.SE, &AR.LI);
621 
622   if (auto CC = CacheCost::getCacheCost(L, AR, DI))
623     OS << *CC;
624 
625   return PreservedAnalyses::all();
626 }
627