xref: /llvm-project/llvm/lib/Transforms/Scalar/LoopDataPrefetch.cpp (revision 34785ecff11854110344a4c8ab2d6165b883fb2b)
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   private:
77     AssumptionCache *AC;
78     LoopInfo *LI;
79     ScalarEvolution *SE;
80     const TargetTransformInfo *TTI;
81     const DataLayout *DL;
82   };
83 }
84 
85 char LoopDataPrefetch::ID = 0;
86 INITIALIZE_PASS_BEGIN(LoopDataPrefetch, "loop-data-prefetch",
87                       "Loop Data Prefetch", false, false)
88 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
89 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
90 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
91 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
92 INITIALIZE_PASS_END(LoopDataPrefetch, "loop-data-prefetch",
93                     "Loop Data Prefetch", false, false)
94 
95 FunctionPass *llvm::createLoopDataPrefetchPass() { return new LoopDataPrefetch(); }
96 
97 bool LoopDataPrefetch::runOnFunction(Function &F) {
98   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
99   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
100   DL = &F.getParent()->getDataLayout();
101   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
102   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
103 
104   // If PrefetchDistance is not set, don't run the pass.  This gives an
105   // opportunity for targets to run this pass for selected subtargets only
106   // (whose TTI sets PrefetchDistance).
107   if (TTI->getPrefetchDistance() == 0)
108     return false;
109   assert(TTI->getCacheLineSize() && "Cache line size is not set for target");
110 
111   bool MadeChange = false;
112 
113   for (auto I = LI->begin(), IE = LI->end(); I != IE; ++I)
114     for (auto L = df_begin(*I), LE = df_end(*I); L != LE; ++L)
115       MadeChange |= runOnLoop(*L);
116 
117   return MadeChange;
118 }
119 
120 bool LoopDataPrefetch::runOnLoop(Loop *L) {
121   bool MadeChange = false;
122 
123   // Only prefetch in the inner-most loop
124   if (!L->empty())
125     return MadeChange;
126 
127   SmallPtrSet<const Value *, 32> EphValues;
128   CodeMetrics::collectEphemeralValues(L, AC, EphValues);
129 
130   // Calculate the number of iterations ahead to prefetch
131   CodeMetrics Metrics;
132   for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
133        I != IE; ++I) {
134 
135     // If the loop already has prefetches, then assume that the user knows
136     // what he or she is doing and don't add any more.
137     for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
138          J != JE; ++J)
139       if (CallInst *CI = dyn_cast<CallInst>(J))
140         if (Function *F = CI->getCalledFunction())
141           if (F->getIntrinsicID() == Intrinsic::prefetch)
142             return MadeChange;
143 
144     Metrics.analyzeBasicBlock(*I, *TTI, EphValues);
145   }
146   unsigned LoopSize = Metrics.NumInsts;
147   if (!LoopSize)
148     LoopSize = 1;
149 
150   unsigned ItersAhead = TTI->getPrefetchDistance() / LoopSize;
151   if (!ItersAhead)
152     ItersAhead = 1;
153 
154   DEBUG(dbgs() << "Prefetching " << ItersAhead
155                << " iterations ahead (loop size: " << LoopSize << ") in "
156                << L->getHeader()->getParent()->getName() << ": " << *L);
157 
158   SmallVector<std::pair<Instruction *, const SCEVAddRecExpr *>, 16> PrefLoads;
159   for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
160        I != IE; ++I) {
161     for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
162         J != JE; ++J) {
163       Value *PtrValue;
164       Instruction *MemI;
165 
166       if (LoadInst *LMemI = dyn_cast<LoadInst>(J)) {
167         MemI = LMemI;
168         PtrValue = LMemI->getPointerOperand();
169       } else if (StoreInst *SMemI = dyn_cast<StoreInst>(J)) {
170         if (!PrefetchWrites) continue;
171         MemI = SMemI;
172         PtrValue = SMemI->getPointerOperand();
173       } else continue;
174 
175       unsigned PtrAddrSpace = PtrValue->getType()->getPointerAddressSpace();
176       if (PtrAddrSpace)
177         continue;
178 
179       if (L->isLoopInvariant(PtrValue))
180         continue;
181 
182       const SCEV *LSCEV = SE->getSCEV(PtrValue);
183       const SCEVAddRecExpr *LSCEVAddRec = dyn_cast<SCEVAddRecExpr>(LSCEV);
184       if (!LSCEVAddRec)
185         continue;
186 
187       // We don't want to double prefetch individual cache lines. If this load
188       // is known to be within one cache line of some other load that has
189       // already been prefetched, then don't prefetch this one as well.
190       bool DupPref = false;
191       for (SmallVector<std::pair<Instruction *, const SCEVAddRecExpr *>,
192              16>::iterator K = PrefLoads.begin(), KE = PrefLoads.end();
193            K != KE; ++K) {
194         const SCEV *PtrDiff = SE->getMinusSCEV(LSCEVAddRec, K->second);
195         if (const SCEVConstant *ConstPtrDiff =
196             dyn_cast<SCEVConstant>(PtrDiff)) {
197           int64_t PD = std::abs(ConstPtrDiff->getValue()->getSExtValue());
198           if (PD < (int64_t) TTI->getCacheLineSize()) {
199             DupPref = true;
200             break;
201           }
202         }
203       }
204       if (DupPref)
205         continue;
206 
207       const SCEV *NextLSCEV = SE->getAddExpr(LSCEVAddRec, SE->getMulExpr(
208         SE->getConstant(LSCEVAddRec->getType(), ItersAhead),
209         LSCEVAddRec->getStepRecurrence(*SE)));
210       if (!isSafeToExpand(NextLSCEV, *SE))
211         continue;
212 
213       PrefLoads.push_back(std::make_pair(MemI, LSCEVAddRec));
214 
215       Type *I8Ptr = Type::getInt8PtrTy((*I)->getContext(), PtrAddrSpace);
216       SCEVExpander SCEVE(*SE, J->getModule()->getDataLayout(), "prefaddr");
217       Value *PrefPtrValue = SCEVE.expandCodeFor(NextLSCEV, I8Ptr, MemI);
218 
219       IRBuilder<> Builder(MemI);
220       Module *M = (*I)->getParent()->getParent();
221       Type *I32 = Type::getInt32Ty((*I)->getContext());
222       Value *PrefetchFunc = Intrinsic::getDeclaration(M, Intrinsic::prefetch);
223       Builder.CreateCall(
224           PrefetchFunc,
225           {PrefPtrValue,
226            ConstantInt::get(I32, MemI->mayReadFromMemory() ? 0 : 1),
227            ConstantInt::get(I32, 3), ConstantInt::get(I32, 1)});
228       ++NumPrefetches;
229       DEBUG(dbgs() << "  Access: " << *PtrValue << ", SCEV: " << *LSCEV
230                    << "\n");
231 
232       MadeChange = true;
233     }
234   }
235 
236   return MadeChange;
237 }
238 
239