xref: /llvm-project/llvm/lib/Transforms/Scalar/LoopDataPrefetch.cpp (revision 6d8beeca5302984e845d9c6d7bf0a9e4a5ca98f9)
1 //===-------- LoopDataPrefetch.cpp - Loop Data Prefetching Pass -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a Loop Data Prefetching Pass.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #define DEBUG_TYPE "loop-data-prefetch"
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/ADT/DepthFirstIterator.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/CodeMetrics.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/Analysis/ScalarEvolution.h"
23 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
24 #include "llvm/Analysis/ScalarEvolutionExpander.h"
25 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
26 #include "llvm/Analysis/TargetTransformInfo.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/IR/CFG.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
36 #include "llvm/Transforms/Utils/Local.h"
37 #include "llvm/Transforms/Utils/ValueMapper.h"
38 using namespace llvm;
39 
40 // By default, we limit this to creating 16 PHIs (which is a little over half
41 // of the allocatable register set).
42 static cl::opt<bool>
43 PrefetchWrites("loop-prefetch-writes", cl::Hidden, cl::init(false),
44                cl::desc("Prefetch write addresses"));
45 
46 STATISTIC(NumPrefetches, "Number of prefetches inserted");
47 
48 namespace llvm {
49   void initializeLoopDataPrefetchPass(PassRegistry&);
50 }
51 
52 namespace {
53 
54   class LoopDataPrefetch : public FunctionPass {
55   public:
56     static char ID; // Pass ID, replacement for typeid
57     LoopDataPrefetch() : FunctionPass(ID) {
58       initializeLoopDataPrefetchPass(*PassRegistry::getPassRegistry());
59     }
60 
61     void getAnalysisUsage(AnalysisUsage &AU) const override {
62       AU.addRequired<AssumptionCacheTracker>();
63       AU.addPreserved<DominatorTreeWrapperPass>();
64       AU.addRequired<LoopInfoWrapperPass>();
65       AU.addPreserved<LoopInfoWrapperPass>();
66       AU.addRequired<ScalarEvolutionWrapperPass>();
67       // FIXME: For some reason, preserving SE here breaks LSR (even if
68       // this pass changes nothing).
69       // AU.addPreserved<ScalarEvolutionWrapperPass>();
70       AU.addRequired<TargetTransformInfoWrapperPass>();
71     }
72 
73     bool runOnFunction(Function &F) override;
74     bool runOnLoop(Loop *L);
75 
76     /// \brief Check if the the stride of the accesses is large enough to
77     /// warrant a prefetch.
78     bool isStrideLargeEnough(const SCEVAddRecExpr *AR);
79 
80   private:
81     AssumptionCache *AC;
82     LoopInfo *LI;
83     ScalarEvolution *SE;
84     const TargetTransformInfo *TTI;
85     const DataLayout *DL;
86   };
87 }
88 
89 char LoopDataPrefetch::ID = 0;
90 INITIALIZE_PASS_BEGIN(LoopDataPrefetch, "loop-data-prefetch",
91                       "Loop Data Prefetch", false, false)
92 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
93 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
94 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
95 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
96 INITIALIZE_PASS_END(LoopDataPrefetch, "loop-data-prefetch",
97                     "Loop Data Prefetch", false, false)
98 
99 FunctionPass *llvm::createLoopDataPrefetchPass() { return new LoopDataPrefetch(); }
100 
101 bool LoopDataPrefetch::isStrideLargeEnough(const SCEVAddRecExpr *AR) {
102   unsigned TargetMinStride = TTI->getMinPrefetchStride();
103   // No need to check if any stride goes.
104   if (TargetMinStride <= 1)
105     return true;
106 
107   const auto *ConstStride = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
108   // If MinStride is set, don't prefetch unless we can ensure that stride is
109   // larger.
110   if (!ConstStride)
111     return false;
112 
113   unsigned AbsStride = std::abs(ConstStride->getAPInt().getSExtValue());
114   return TargetMinStride <= AbsStride;
115 }
116 
117 bool LoopDataPrefetch::runOnFunction(Function &F) {
118   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
119   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
120   DL = &F.getParent()->getDataLayout();
121   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
122   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
123 
124   // If PrefetchDistance is not set, don't run the pass.  This gives an
125   // opportunity for targets to run this pass for selected subtargets only
126   // (whose TTI sets PrefetchDistance).
127   if (TTI->getPrefetchDistance() == 0)
128     return false;
129   assert(TTI->getCacheLineSize() && "Cache line size is not set for target");
130 
131   bool MadeChange = false;
132 
133   for (auto I = LI->begin(), IE = LI->end(); I != IE; ++I)
134     for (auto L = df_begin(*I), LE = df_end(*I); L != LE; ++L)
135       MadeChange |= runOnLoop(*L);
136 
137   return MadeChange;
138 }
139 
140 bool LoopDataPrefetch::runOnLoop(Loop *L) {
141   bool MadeChange = false;
142 
143   // Only prefetch in the inner-most loop
144   if (!L->empty())
145     return MadeChange;
146 
147   SmallPtrSet<const Value *, 32> EphValues;
148   CodeMetrics::collectEphemeralValues(L, AC, EphValues);
149 
150   // Calculate the number of iterations ahead to prefetch
151   CodeMetrics Metrics;
152   for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
153        I != IE; ++I) {
154 
155     // If the loop already has prefetches, then assume that the user knows
156     // what he or she is doing and don't add any more.
157     for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
158          J != JE; ++J)
159       if (CallInst *CI = dyn_cast<CallInst>(J))
160         if (Function *F = CI->getCalledFunction())
161           if (F->getIntrinsicID() == Intrinsic::prefetch)
162             return MadeChange;
163 
164     Metrics.analyzeBasicBlock(*I, *TTI, EphValues);
165   }
166   unsigned LoopSize = Metrics.NumInsts;
167   if (!LoopSize)
168     LoopSize = 1;
169 
170   unsigned ItersAhead = TTI->getPrefetchDistance() / LoopSize;
171   if (!ItersAhead)
172     ItersAhead = 1;
173 
174   DEBUG(dbgs() << "Prefetching " << ItersAhead
175                << " iterations ahead (loop size: " << LoopSize << ") in "
176                << L->getHeader()->getParent()->getName() << ": " << *L);
177 
178   SmallVector<std::pair<Instruction *, const SCEVAddRecExpr *>, 16> PrefLoads;
179   for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
180        I != IE; ++I) {
181     for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
182         J != JE; ++J) {
183       Value *PtrValue;
184       Instruction *MemI;
185 
186       if (LoadInst *LMemI = dyn_cast<LoadInst>(J)) {
187         MemI = LMemI;
188         PtrValue = LMemI->getPointerOperand();
189       } else if (StoreInst *SMemI = dyn_cast<StoreInst>(J)) {
190         if (!PrefetchWrites) continue;
191         MemI = SMemI;
192         PtrValue = SMemI->getPointerOperand();
193       } else continue;
194 
195       unsigned PtrAddrSpace = PtrValue->getType()->getPointerAddressSpace();
196       if (PtrAddrSpace)
197         continue;
198 
199       if (L->isLoopInvariant(PtrValue))
200         continue;
201 
202       const SCEV *LSCEV = SE->getSCEV(PtrValue);
203       const SCEVAddRecExpr *LSCEVAddRec = dyn_cast<SCEVAddRecExpr>(LSCEV);
204       if (!LSCEVAddRec)
205         continue;
206 
207       // Check if the the stride of the accesses is large enough to warrant a
208       // prefetch.
209       if (!isStrideLargeEnough(LSCEVAddRec))
210         continue;
211 
212       // We don't want to double prefetch individual cache lines. If this load
213       // is known to be within one cache line of some other load that has
214       // already been prefetched, then don't prefetch this one as well.
215       bool DupPref = false;
216       for (SmallVector<std::pair<Instruction *, const SCEVAddRecExpr *>,
217              16>::iterator K = PrefLoads.begin(), KE = PrefLoads.end();
218            K != KE; ++K) {
219         const SCEV *PtrDiff = SE->getMinusSCEV(LSCEVAddRec, K->second);
220         if (const SCEVConstant *ConstPtrDiff =
221             dyn_cast<SCEVConstant>(PtrDiff)) {
222           int64_t PD = std::abs(ConstPtrDiff->getValue()->getSExtValue());
223           if (PD < (int64_t) TTI->getCacheLineSize()) {
224             DupPref = true;
225             break;
226           }
227         }
228       }
229       if (DupPref)
230         continue;
231 
232       const SCEV *NextLSCEV = SE->getAddExpr(LSCEVAddRec, SE->getMulExpr(
233         SE->getConstant(LSCEVAddRec->getType(), ItersAhead),
234         LSCEVAddRec->getStepRecurrence(*SE)));
235       if (!isSafeToExpand(NextLSCEV, *SE))
236         continue;
237 
238       PrefLoads.push_back(std::make_pair(MemI, LSCEVAddRec));
239 
240       Type *I8Ptr = Type::getInt8PtrTy((*I)->getContext(), PtrAddrSpace);
241       SCEVExpander SCEVE(*SE, J->getModule()->getDataLayout(), "prefaddr");
242       Value *PrefPtrValue = SCEVE.expandCodeFor(NextLSCEV, I8Ptr, MemI);
243 
244       IRBuilder<> Builder(MemI);
245       Module *M = (*I)->getParent()->getParent();
246       Type *I32 = Type::getInt32Ty((*I)->getContext());
247       Value *PrefetchFunc = Intrinsic::getDeclaration(M, Intrinsic::prefetch);
248       Builder.CreateCall(
249           PrefetchFunc,
250           {PrefPtrValue,
251            ConstantInt::get(I32, MemI->mayReadFromMemory() ? 0 : 1),
252            ConstantInt::get(I32, 3), ConstantInt::get(I32, 1)});
253       ++NumPrefetches;
254       DEBUG(dbgs() << "  Access: " << *PtrValue << ", SCEV: " << *LSCEV
255                    << "\n");
256 
257       MadeChange = true;
258     }
259   }
260 
261   return MadeChange;
262 }
263 
264