LoopCacheAnalysis.h 13 KB

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