xref: /llvm-project/llvm/lib/Transforms/Scalar/LoopDataPrefetch.cpp (revision 709e3046ee3c473b373fe5ec61e4d6e467991898)
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   if (ItersAhead > TTI->getMaxPrefetchIterationsAhead())
175     return MadeChange;
176 
177   DEBUG(dbgs() << "Prefetching " << ItersAhead
178                << " iterations ahead (loop size: " << LoopSize << ") in "
179                << L->getHeader()->getParent()->getName() << ": " << *L);
180 
181   SmallVector<std::pair<Instruction *, const SCEVAddRecExpr *>, 16> PrefLoads;
182   for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
183        I != IE; ++I) {
184     for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
185         J != JE; ++J) {
186       Value *PtrValue;
187       Instruction *MemI;
188 
189       if (LoadInst *LMemI = dyn_cast<LoadInst>(J)) {
190         MemI = LMemI;
191         PtrValue = LMemI->getPointerOperand();
192       } else if (StoreInst *SMemI = dyn_cast<StoreInst>(J)) {
193         if (!PrefetchWrites) continue;
194         MemI = SMemI;
195         PtrValue = SMemI->getPointerOperand();
196       } else continue;
197 
198       unsigned PtrAddrSpace = PtrValue->getType()->getPointerAddressSpace();
199       if (PtrAddrSpace)
200         continue;
201 
202       if (L->isLoopInvariant(PtrValue))
203         continue;
204 
205       const SCEV *LSCEV = SE->getSCEV(PtrValue);
206       const SCEVAddRecExpr *LSCEVAddRec = dyn_cast<SCEVAddRecExpr>(LSCEV);
207       if (!LSCEVAddRec)
208         continue;
209 
210       // Check if the the stride of the accesses is large enough to warrant a
211       // prefetch.
212       if (!isStrideLargeEnough(LSCEVAddRec))
213         continue;
214 
215       // We don't want to double prefetch individual cache lines. If this load
216       // is known to be within one cache line of some other load that has
217       // already been prefetched, then don't prefetch this one as well.
218       bool DupPref = false;
219       for (SmallVector<std::pair<Instruction *, const SCEVAddRecExpr *>,
220              16>::iterator K = PrefLoads.begin(), KE = PrefLoads.end();
221            K != KE; ++K) {
222         const SCEV *PtrDiff = SE->getMinusSCEV(LSCEVAddRec, K->second);
223         if (const SCEVConstant *ConstPtrDiff =
224             dyn_cast<SCEVConstant>(PtrDiff)) {
225           int64_t PD = std::abs(ConstPtrDiff->getValue()->getSExtValue());
226           if (PD < (int64_t) TTI->getCacheLineSize()) {
227             DupPref = true;
228             break;
229           }
230         }
231       }
232       if (DupPref)
233         continue;
234 
235       const SCEV *NextLSCEV = SE->getAddExpr(LSCEVAddRec, SE->getMulExpr(
236         SE->getConstant(LSCEVAddRec->getType(), ItersAhead),
237         LSCEVAddRec->getStepRecurrence(*SE)));
238       if (!isSafeToExpand(NextLSCEV, *SE))
239         continue;
240 
241       PrefLoads.push_back(std::make_pair(MemI, LSCEVAddRec));
242 
243       Type *I8Ptr = Type::getInt8PtrTy((*I)->getContext(), PtrAddrSpace);
244       SCEVExpander SCEVE(*SE, J->getModule()->getDataLayout(), "prefaddr");
245       Value *PrefPtrValue = SCEVE.expandCodeFor(NextLSCEV, I8Ptr, MemI);
246 
247       IRBuilder<> Builder(MemI);
248       Module *M = (*I)->getParent()->getParent();
249       Type *I32 = Type::getInt32Ty((*I)->getContext());
250       Value *PrefetchFunc = Intrinsic::getDeclaration(M, Intrinsic::prefetch);
251       Builder.CreateCall(
252           PrefetchFunc,
253           {PrefPtrValue,
254            ConstantInt::get(I32, MemI->mayReadFromMemory() ? 0 : 1),
255            ConstantInt::get(I32, 3), ConstantInt::get(I32, 1)});
256       ++NumPrefetches;
257       DEBUG(dbgs() << "  Access: " << *PtrValue << ", SCEV: " << *LSCEV
258                    << "\n");
259 
260       MadeChange = true;
261     }
262   }
263 
264   return MadeChange;
265 }
266 
267