LoopCacheAnalysis.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/Analysis/LoopCacheAnalysis.h ------------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. ///
  14. /// \file
  15. /// This file defines the interface for the loop cache analysis.
  16. ///
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_ANALYSIS_LOOPCACHEANALYSIS_H
  19. #define LLVM_ANALYSIS_LOOPCACHEANALYSIS_H
  20. #include "llvm/Analysis/LoopAnalysisManager.h"
  21. #include "llvm/IR/Instructions.h"
  22. #include "llvm/IR/PassManager.h"
  23. #include "llvm/Support/raw_ostream.h"
  24. namespace llvm {
  25. class AAResults;
  26. class DependenceInfo;
  27. class LPMUpdater;
  28. class ScalarEvolution;
  29. class SCEV;
  30. class TargetTransformInfo;
  31. using CacheCostTy = int64_t;
  32. using LoopVectorTy = SmallVector<Loop *, 8>;
  33. /// Represents a memory reference as a base pointer and a set of indexing
  34. /// operations. For example given the array reference A[i][2j+1][3k+2] in a
  35. /// 3-dim loop nest:
  36. /// for(i=0;i<n;++i)
  37. /// for(j=0;j<m;++j)
  38. /// for(k=0;k<o;++k)
  39. /// ... A[i][2j+1][3k+2] ...
  40. /// We expect:
  41. /// BasePointer -> A
  42. /// Subscripts -> [{0,+,1}<%for.i>][{1,+,2}<%for.j>][{2,+,3}<%for.k>]
  43. /// Sizes -> [m][o][4]
  44. class IndexedReference {
  45. friend raw_ostream &operator<<(raw_ostream &OS, const IndexedReference &R);
  46. public:
  47. /// Construct an indexed reference given a \p StoreOrLoadInst instruction.
  48. IndexedReference(Instruction &StoreOrLoadInst, const LoopInfo &LI,
  49. ScalarEvolution &SE);
  50. bool isValid() const { return IsValid; }
  51. const SCEV *getBasePointer() const { return BasePointer; }
  52. size_t getNumSubscripts() const { return Subscripts.size(); }
  53. const SCEV *getSubscript(unsigned SubNum) const {
  54. assert(SubNum < getNumSubscripts() && "Invalid subscript number");
  55. return Subscripts[SubNum];
  56. }
  57. const SCEV *getFirstSubscript() const {
  58. assert(!Subscripts.empty() && "Expecting non-empty container");
  59. return Subscripts.front();
  60. }
  61. const SCEV *getLastSubscript() const {
  62. assert(!Subscripts.empty() && "Expecting non-empty container");
  63. return Subscripts.back();
  64. }
  65. /// Return true/false if the current object and the indexed reference \p Other
  66. /// are/aren't in the same cache line of size \p CLS. Two references are in
  67. /// the same chace line iff the distance between them in the innermost
  68. /// dimension is less than the cache line size. Return None if unsure.
  69. Optional<bool> hasSpacialReuse(const IndexedReference &Other, unsigned CLS,
  70. AAResults &AA) const;
  71. /// Return true if the current object and the indexed reference \p Other
  72. /// have distance smaller than \p MaxDistance in the dimension associated with
  73. /// the given loop \p L. Return false if the distance is not smaller than \p
  74. /// MaxDistance and None if unsure.
  75. Optional<bool> hasTemporalReuse(const IndexedReference &Other,
  76. unsigned MaxDistance, const Loop &L,
  77. DependenceInfo &DI, AAResults &AA) const;
  78. /// Compute the cost of the reference w.r.t. the given loop \p L when it is
  79. /// considered in the innermost position in the loop nest.
  80. /// The cost is defined as:
  81. /// - equal to one if the reference is loop invariant, or
  82. /// - equal to '(TripCount * stride) / cache_line_size' if:
  83. /// + the reference stride is less than the cache line size, and
  84. /// + the coefficient of this loop's index variable used in all other
  85. /// subscripts is zero
  86. /// - or otherwise equal to 'TripCount'.
  87. CacheCostTy computeRefCost(const Loop &L, unsigned CLS) const;
  88. private:
  89. /// Attempt to delinearize the indexed reference.
  90. bool delinearize(const LoopInfo &LI);
  91. /// Return true if the index reference is invariant with respect to loop \p L.
  92. bool isLoopInvariant(const Loop &L) const;
  93. /// Return true if the indexed reference is 'consecutive' in loop \p L.
  94. /// An indexed reference is 'consecutive' if the only coefficient that uses
  95. /// the loop induction variable is the rightmost one, and the access stride is
  96. /// smaller than the cache line size \p CLS.
  97. bool isConsecutive(const Loop &L, unsigned CLS) const;
  98. /// Return the coefficient used in the rightmost dimension.
  99. const SCEV *getLastCoefficient() const;
  100. /// Return true if the coefficient corresponding to induction variable of
  101. /// loop \p L in the given \p Subscript is zero or is loop invariant in \p L.
  102. bool isCoeffForLoopZeroOrInvariant(const SCEV &Subscript,
  103. const Loop &L) const;
  104. /// Verify that the given \p Subscript is 'well formed' (must be a simple add
  105. /// recurrence).
  106. bool isSimpleAddRecurrence(const SCEV &Subscript, const Loop &L) const;
  107. /// Return true if the given reference \p Other is definetely aliased with
  108. /// the indexed reference represented by this class.
  109. bool isAliased(const IndexedReference &Other, AAResults &AA) const;
  110. private:
  111. /// True if the reference can be delinearized, false otherwise.
  112. bool IsValid = false;
  113. /// Represent the memory reference instruction.
  114. Instruction &StoreOrLoadInst;
  115. /// The base pointer of the memory reference.
  116. const SCEV *BasePointer = nullptr;
  117. /// The subscript (indexes) of the memory reference.
  118. SmallVector<const SCEV *, 3> Subscripts;
  119. /// The dimensions of the memory reference.
  120. SmallVector<const SCEV *, 3> Sizes;
  121. ScalarEvolution &SE;
  122. };
  123. /// A reference group represents a set of memory references that exhibit
  124. /// temporal or spacial reuse. Two references belong to the same
  125. /// reference group with respect to a inner loop L iff:
  126. /// 1. they have a loop independent dependency, or
  127. /// 2. they have a loop carried dependence with a small dependence distance
  128. /// (e.g. less than 2) carried by the inner loop, or
  129. /// 3. they refer to the same array, and the subscript in their innermost
  130. /// dimension is less than or equal to 'd' (where 'd' is less than the cache
  131. /// line size)
  132. ///
  133. /// Intuitively a reference group represents memory references that access
  134. /// the same cache line. Conditions 1,2 above account for temporal reuse, while
  135. /// contition 3 accounts for spacial reuse.
  136. using ReferenceGroupTy = SmallVector<std::unique_ptr<IndexedReference>, 8>;
  137. using ReferenceGroupsTy = SmallVector<ReferenceGroupTy, 8>;
  138. /// \c CacheCost represents the estimated cost of a inner loop as the number of
  139. /// cache lines used by the memory references it contains.
  140. /// The 'cache cost' of a loop 'L' in a loop nest 'LN' is computed as the sum of
  141. /// the cache costs of all of its reference groups when the loop is considered
  142. /// to be in the innermost position in the nest.
  143. /// A reference group represents memory references that fall into the same cache
  144. /// line. Each reference group is analysed with respect to the innermost loop in
  145. /// a loop nest. The cost of a reference is defined as follow:
  146. /// - one if it is loop invariant w.r.t the innermost loop,
  147. /// - equal to the loop trip count divided by the cache line times the
  148. /// reference stride if the reference stride is less than the cache line
  149. /// size (CLS), and the coefficient of this loop's index variable used in all
  150. /// other subscripts is zero (e.g. RefCost = TripCount/(CLS/RefStride))
  151. /// - equal to the innermost loop trip count if the reference stride is greater
  152. /// or equal to the cache line size CLS.
  153. class CacheCost {
  154. friend raw_ostream &operator<<(raw_ostream &OS, const CacheCost &CC);
  155. using LoopTripCountTy = std::pair<const Loop *, unsigned>;
  156. using LoopCacheCostTy = std::pair<const Loop *, CacheCostTy>;
  157. public:
  158. static CacheCostTy constexpr InvalidCost = -1;
  159. /// Construct a CacheCost object for the loop nest described by \p Loops.
  160. /// The optional parameter \p TRT can be used to specify the max. distance
  161. /// between array elements accessed in a loop so that the elements are
  162. /// classified to have temporal reuse.
  163. CacheCost(const LoopVectorTy &Loops, const LoopInfo &LI, ScalarEvolution &SE,
  164. TargetTransformInfo &TTI, AAResults &AA, DependenceInfo &DI,
  165. Optional<unsigned> TRT = None);
  166. /// Create a CacheCost for the loop nest rooted by \p Root.
  167. /// The optional parameter \p TRT can be used to specify the max. distance
  168. /// between array elements accessed in a loop so that the elements are
  169. /// classified to have temporal reuse.
  170. static std::unique_ptr<CacheCost>
  171. getCacheCost(Loop &Root, LoopStandardAnalysisResults &AR, DependenceInfo &DI,
  172. Optional<unsigned> TRT = None);
  173. /// Return the estimated cost of loop \p L if the given loop is part of the
  174. /// loop nest associated with this object. Return -1 otherwise.
  175. CacheCostTy getLoopCost(const Loop &L) const {
  176. auto IT = llvm::find_if(LoopCosts, [&L](const LoopCacheCostTy &LCC) {
  177. return LCC.first == &L;
  178. });
  179. return (IT != LoopCosts.end()) ? (*IT).second : -1;
  180. }
  181. /// Return the estimated ordered loop costs.
  182. ArrayRef<LoopCacheCostTy> getLoopCosts() const { return LoopCosts; }
  183. private:
  184. /// Calculate the cache footprint of each loop in the nest (when it is
  185. /// considered to be in the innermost position).
  186. void calculateCacheFootprint();
  187. /// Partition store/load instructions in the loop nest into reference groups.
  188. /// Two or more memory accesses belong in the same reference group if they
  189. /// share the same cache line.
  190. bool populateReferenceGroups(ReferenceGroupsTy &RefGroups) const;
  191. /// Calculate the cost of the given loop \p L assuming it is the innermost
  192. /// loop in nest.
  193. CacheCostTy computeLoopCacheCost(const Loop &L,
  194. const ReferenceGroupsTy &RefGroups) const;
  195. /// Compute the cost of a representative reference in reference group \p RG
  196. /// when the given loop \p L is considered as the innermost loop in the nest.
  197. /// The computed cost is an estimate for the number of cache lines used by the
  198. /// reference group. The representative reference cost is defined as:
  199. /// - equal to one if the reference is loop invariant, or
  200. /// - equal to '(TripCount * stride) / cache_line_size' if (a) loop \p L's
  201. /// induction variable is used only in the reference subscript associated
  202. /// with loop \p L, and (b) the reference stride is less than the cache
  203. /// line size, or
  204. /// - TripCount otherwise
  205. CacheCostTy computeRefGroupCacheCost(const ReferenceGroupTy &RG,
  206. const Loop &L) const;
  207. /// Sort the LoopCosts vector by decreasing cache cost.
  208. void sortLoopCosts() {
  209. sort(LoopCosts, [](const LoopCacheCostTy &A, const LoopCacheCostTy &B) {
  210. return A.second > B.second;
  211. });
  212. }
  213. private:
  214. /// Loops in the loop nest associated with this object.
  215. LoopVectorTy Loops;
  216. /// Trip counts for the loops in the loop nest associated with this object.
  217. SmallVector<LoopTripCountTy, 3> TripCounts;
  218. /// Cache costs for the loops in the loop nest associated with this object.
  219. SmallVector<LoopCacheCostTy, 3> LoopCosts;
  220. /// The max. distance between array elements accessed in a loop so that the
  221. /// elements are classified to have temporal reuse.
  222. Optional<unsigned> TRT;
  223. const LoopInfo &LI;
  224. ScalarEvolution &SE;
  225. TargetTransformInfo &TTI;
  226. AAResults &AA;
  227. DependenceInfo &DI;
  228. };
  229. raw_ostream &operator<<(raw_ostream &OS, const IndexedReference &R);
  230. raw_ostream &operator<<(raw_ostream &OS, const CacheCost &CC);
  231. /// Printer pass for the \c CacheCost results.
  232. class LoopCachePrinterPass : public PassInfoMixin<LoopCachePrinterPass> {
  233. raw_ostream &OS;
  234. public:
  235. explicit LoopCachePrinterPass(raw_ostream &OS) : OS(OS) {}
  236. PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM,
  237. LoopStandardAnalysisResults &AR, LPMUpdater &U);
  238. };
  239. } // namespace llvm
  240. #endif // LLVM_ANALYSIS_LOOPCACHEANALYSIS_H
  241. #ifdef __GNUC__
  242. #pragma GCC diagnostic pop
  243. #endif