xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/Scalar/LoopDataPrefetch.cpp (revision d5b0e70f7e04d971691517ce1304d86a1e367e2e)
1 //===-------- LoopDataPrefetch.cpp - Loop Data Prefetching Pass -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements a Loop Data Prefetching Pass.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
14 #include "llvm/InitializePasses.h"
15 
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/LoopInfo.h"
21 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
22 #include "llvm/Analysis/ScalarEvolution.h"
23 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
24 #include "llvm/Analysis/TargetTransformInfo.h"
25 #include "llvm/IR/CFG.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Transforms/Scalar.h"
32 #include "llvm/Transforms/Utils.h"
33 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
34 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
35 #include "llvm/Transforms/Utils/ValueMapper.h"
36 
37 #define DEBUG_TYPE "loop-data-prefetch"
38 
39 using namespace llvm;
40 
41 // By default, we limit this to creating 16 PHIs (which is a little over half
42 // of the allocatable register set).
43 static cl::opt<bool>
44 PrefetchWrites("loop-prefetch-writes", cl::Hidden, cl::init(false),
45                cl::desc("Prefetch write addresses"));
46 
47 static cl::opt<unsigned>
48     PrefetchDistance("prefetch-distance",
49                      cl::desc("Number of instructions to prefetch ahead"),
50                      cl::Hidden);
51 
52 static cl::opt<unsigned>
53     MinPrefetchStride("min-prefetch-stride",
54                       cl::desc("Min stride to add prefetches"), cl::Hidden);
55 
56 static cl::opt<unsigned> MaxPrefetchIterationsAhead(
57     "max-prefetch-iters-ahead",
58     cl::desc("Max number of iterations to prefetch ahead"), cl::Hidden);
59 
60 STATISTIC(NumPrefetches, "Number of prefetches inserted");
61 
62 namespace {
63 
64 /// Loop prefetch implementation class.
65 class LoopDataPrefetch {
66 public:
67   LoopDataPrefetch(AssumptionCache *AC, DominatorTree *DT, LoopInfo *LI,
68                    ScalarEvolution *SE, const TargetTransformInfo *TTI,
69                    OptimizationRemarkEmitter *ORE)
70       : AC(AC), DT(DT), LI(LI), SE(SE), TTI(TTI), ORE(ORE) {}
71 
72   bool run();
73 
74 private:
75   bool runOnLoop(Loop *L);
76 
77   /// Check if the stride of the accesses is large enough to
78   /// warrant a prefetch.
79   bool isStrideLargeEnough(const SCEVAddRecExpr *AR, unsigned TargetMinStride);
80 
81   unsigned getMinPrefetchStride(unsigned NumMemAccesses,
82                                 unsigned NumStridedMemAccesses,
83                                 unsigned NumPrefetches,
84                                 bool HasCall) {
85     if (MinPrefetchStride.getNumOccurrences() > 0)
86       return MinPrefetchStride;
87     return TTI->getMinPrefetchStride(NumMemAccesses, NumStridedMemAccesses,
88                                      NumPrefetches, HasCall);
89   }
90 
91   unsigned getPrefetchDistance() {
92     if (PrefetchDistance.getNumOccurrences() > 0)
93       return PrefetchDistance;
94     return TTI->getPrefetchDistance();
95   }
96 
97   unsigned getMaxPrefetchIterationsAhead() {
98     if (MaxPrefetchIterationsAhead.getNumOccurrences() > 0)
99       return MaxPrefetchIterationsAhead;
100     return TTI->getMaxPrefetchIterationsAhead();
101   }
102 
103   bool doPrefetchWrites() {
104     if (PrefetchWrites.getNumOccurrences() > 0)
105       return PrefetchWrites;
106     return TTI->enableWritePrefetching();
107   }
108 
109   AssumptionCache *AC;
110   DominatorTree *DT;
111   LoopInfo *LI;
112   ScalarEvolution *SE;
113   const TargetTransformInfo *TTI;
114   OptimizationRemarkEmitter *ORE;
115 };
116 
117 /// Legacy class for inserting loop data prefetches.
118 class LoopDataPrefetchLegacyPass : public FunctionPass {
119 public:
120   static char ID; // Pass ID, replacement for typeid
121   LoopDataPrefetchLegacyPass() : FunctionPass(ID) {
122     initializeLoopDataPrefetchLegacyPassPass(*PassRegistry::getPassRegistry());
123   }
124 
125   void getAnalysisUsage(AnalysisUsage &AU) const override {
126     AU.addRequired<AssumptionCacheTracker>();
127     AU.addRequired<DominatorTreeWrapperPass>();
128     AU.addPreserved<DominatorTreeWrapperPass>();
129     AU.addRequired<LoopInfoWrapperPass>();
130     AU.addPreserved<LoopInfoWrapperPass>();
131     AU.addRequiredID(LoopSimplifyID);
132     AU.addPreservedID(LoopSimplifyID);
133     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
134     AU.addRequired<ScalarEvolutionWrapperPass>();
135     AU.addPreserved<ScalarEvolutionWrapperPass>();
136     AU.addRequired<TargetTransformInfoWrapperPass>();
137   }
138 
139   bool runOnFunction(Function &F) override;
140   };
141 }
142 
143 char LoopDataPrefetchLegacyPass::ID = 0;
144 INITIALIZE_PASS_BEGIN(LoopDataPrefetchLegacyPass, "loop-data-prefetch",
145                       "Loop Data Prefetch", false, false)
146 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
147 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
148 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
149 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
150 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
151 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
152 INITIALIZE_PASS_END(LoopDataPrefetchLegacyPass, "loop-data-prefetch",
153                     "Loop Data Prefetch", false, false)
154 
155 FunctionPass *llvm::createLoopDataPrefetchPass() {
156   return new LoopDataPrefetchLegacyPass();
157 }
158 
159 bool LoopDataPrefetch::isStrideLargeEnough(const SCEVAddRecExpr *AR,
160                                            unsigned TargetMinStride) {
161   // No need to check if any stride goes.
162   if (TargetMinStride <= 1)
163     return true;
164 
165   const auto *ConstStride = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
166   // If MinStride is set, don't prefetch unless we can ensure that stride is
167   // larger.
168   if (!ConstStride)
169     return false;
170 
171   unsigned AbsStride = std::abs(ConstStride->getAPInt().getSExtValue());
172   return TargetMinStride <= AbsStride;
173 }
174 
175 PreservedAnalyses LoopDataPrefetchPass::run(Function &F,
176                                             FunctionAnalysisManager &AM) {
177   DominatorTree *DT = &AM.getResult<DominatorTreeAnalysis>(F);
178   LoopInfo *LI = &AM.getResult<LoopAnalysis>(F);
179   ScalarEvolution *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
180   AssumptionCache *AC = &AM.getResult<AssumptionAnalysis>(F);
181   OptimizationRemarkEmitter *ORE =
182       &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
183   const TargetTransformInfo *TTI = &AM.getResult<TargetIRAnalysis>(F);
184 
185   LoopDataPrefetch LDP(AC, DT, LI, SE, TTI, ORE);
186   bool Changed = LDP.run();
187 
188   if (Changed) {
189     PreservedAnalyses PA;
190     PA.preserve<DominatorTreeAnalysis>();
191     PA.preserve<LoopAnalysis>();
192     return PA;
193   }
194 
195   return PreservedAnalyses::all();
196 }
197 
198 bool LoopDataPrefetchLegacyPass::runOnFunction(Function &F) {
199   if (skipFunction(F))
200     return false;
201 
202   DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
203   LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
204   ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
205   AssumptionCache *AC =
206       &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
207   OptimizationRemarkEmitter *ORE =
208       &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
209   const TargetTransformInfo *TTI =
210       &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
211 
212   LoopDataPrefetch LDP(AC, DT, LI, SE, TTI, ORE);
213   return LDP.run();
214 }
215 
216 bool LoopDataPrefetch::run() {
217   // If PrefetchDistance is not set, don't run the pass.  This gives an
218   // opportunity for targets to run this pass for selected subtargets only
219   // (whose TTI sets PrefetchDistance).
220   if (getPrefetchDistance() == 0)
221     return false;
222   assert(TTI->getCacheLineSize() && "Cache line size is not set for target");
223 
224   bool MadeChange = false;
225 
226   for (Loop *I : *LI)
227     for (Loop *L : depth_first(I))
228       MadeChange |= runOnLoop(L);
229 
230   return MadeChange;
231 }
232 
233 /// A record for a potential prefetch made during the initial scan of the
234 /// loop. This is used to let a single prefetch target multiple memory accesses.
235 struct Prefetch {
236   /// The address formula for this prefetch as returned by ScalarEvolution.
237   const SCEVAddRecExpr *LSCEVAddRec;
238   /// The point of insertion for the prefetch instruction.
239   Instruction *InsertPt;
240   /// True if targeting a write memory access.
241   bool Writes;
242   /// The (first seen) prefetched instruction.
243   Instruction *MemI;
244 
245   /// Constructor to create a new Prefetch for \p I.
246   Prefetch(const SCEVAddRecExpr *L, Instruction *I)
247       : LSCEVAddRec(L), InsertPt(nullptr), Writes(false), MemI(nullptr) {
248     addInstruction(I);
249   };
250 
251   /// Add the instruction \param I to this prefetch. If it's not the first
252   /// one, 'InsertPt' and 'Writes' will be updated as required.
253   /// \param PtrDiff the known constant address difference to the first added
254   /// instruction.
255   void addInstruction(Instruction *I, DominatorTree *DT = nullptr,
256                       int64_t PtrDiff = 0) {
257     if (!InsertPt) {
258       MemI = I;
259       InsertPt = I;
260       Writes = isa<StoreInst>(I);
261     } else {
262       BasicBlock *PrefBB = InsertPt->getParent();
263       BasicBlock *InsBB = I->getParent();
264       if (PrefBB != InsBB) {
265         BasicBlock *DomBB = DT->findNearestCommonDominator(PrefBB, InsBB);
266         if (DomBB != PrefBB)
267           InsertPt = DomBB->getTerminator();
268       }
269 
270       if (isa<StoreInst>(I) && PtrDiff == 0)
271         Writes = true;
272     }
273   }
274 };
275 
276 bool LoopDataPrefetch::runOnLoop(Loop *L) {
277   bool MadeChange = false;
278 
279   // Only prefetch in the inner-most loop
280   if (!L->isInnermost())
281     return MadeChange;
282 
283   SmallPtrSet<const Value *, 32> EphValues;
284   CodeMetrics::collectEphemeralValues(L, AC, EphValues);
285 
286   // Calculate the number of iterations ahead to prefetch
287   CodeMetrics Metrics;
288   bool HasCall = false;
289   for (const auto BB : L->blocks()) {
290     // If the loop already has prefetches, then assume that the user knows
291     // what they are doing and don't add any more.
292     for (auto &I : *BB) {
293       if (isa<CallInst>(&I) || isa<InvokeInst>(&I)) {
294         if (const Function *F = cast<CallBase>(I).getCalledFunction()) {
295           if (F->getIntrinsicID() == Intrinsic::prefetch)
296             return MadeChange;
297           if (TTI->isLoweredToCall(F))
298             HasCall = true;
299         } else { // indirect call.
300           HasCall = true;
301         }
302       }
303     }
304     Metrics.analyzeBasicBlock(BB, *TTI, EphValues);
305   }
306   unsigned LoopSize = Metrics.NumInsts;
307   if (!LoopSize)
308     LoopSize = 1;
309 
310   unsigned ItersAhead = getPrefetchDistance() / LoopSize;
311   if (!ItersAhead)
312     ItersAhead = 1;
313 
314   if (ItersAhead > getMaxPrefetchIterationsAhead())
315     return MadeChange;
316 
317   unsigned ConstantMaxTripCount = SE->getSmallConstantMaxTripCount(L);
318   if (ConstantMaxTripCount && ConstantMaxTripCount < ItersAhead + 1)
319     return MadeChange;
320 
321   unsigned NumMemAccesses = 0;
322   unsigned NumStridedMemAccesses = 0;
323   SmallVector<Prefetch, 16> Prefetches;
324   for (const auto BB : L->blocks())
325     for (auto &I : *BB) {
326       Value *PtrValue;
327       Instruction *MemI;
328 
329       if (LoadInst *LMemI = dyn_cast<LoadInst>(&I)) {
330         MemI = LMemI;
331         PtrValue = LMemI->getPointerOperand();
332       } else if (StoreInst *SMemI = dyn_cast<StoreInst>(&I)) {
333         if (!doPrefetchWrites()) continue;
334         MemI = SMemI;
335         PtrValue = SMemI->getPointerOperand();
336       } else continue;
337 
338       unsigned PtrAddrSpace = PtrValue->getType()->getPointerAddressSpace();
339       if (PtrAddrSpace)
340         continue;
341       NumMemAccesses++;
342       if (L->isLoopInvariant(PtrValue))
343         continue;
344 
345       const SCEV *LSCEV = SE->getSCEV(PtrValue);
346       const SCEVAddRecExpr *LSCEVAddRec = dyn_cast<SCEVAddRecExpr>(LSCEV);
347       if (!LSCEVAddRec)
348         continue;
349       NumStridedMemAccesses++;
350 
351       // We don't want to double prefetch individual cache lines. If this
352       // access is known to be within one cache line of some other one that
353       // has already been prefetched, then don't prefetch this one as well.
354       bool DupPref = false;
355       for (auto &Pref : Prefetches) {
356         const SCEV *PtrDiff = SE->getMinusSCEV(LSCEVAddRec, Pref.LSCEVAddRec);
357         if (const SCEVConstant *ConstPtrDiff =
358             dyn_cast<SCEVConstant>(PtrDiff)) {
359           int64_t PD = std::abs(ConstPtrDiff->getValue()->getSExtValue());
360           if (PD < (int64_t) TTI->getCacheLineSize()) {
361             Pref.addInstruction(MemI, DT, PD);
362             DupPref = true;
363             break;
364           }
365         }
366       }
367       if (!DupPref)
368         Prefetches.push_back(Prefetch(LSCEVAddRec, MemI));
369     }
370 
371   unsigned TargetMinStride =
372     getMinPrefetchStride(NumMemAccesses, NumStridedMemAccesses,
373                          Prefetches.size(), HasCall);
374 
375   LLVM_DEBUG(dbgs() << "Prefetching " << ItersAhead
376              << " iterations ahead (loop size: " << LoopSize << ") in "
377              << L->getHeader()->getParent()->getName() << ": " << *L);
378   LLVM_DEBUG(dbgs() << "Loop has: "
379              << NumMemAccesses << " memory accesses, "
380              << NumStridedMemAccesses << " strided memory accesses, "
381              << Prefetches.size() << " potential prefetch(es), "
382              << "a minimum stride of " << TargetMinStride << ", "
383              << (HasCall ? "calls" : "no calls") << ".\n");
384 
385   for (auto &P : Prefetches) {
386     // Check if the stride of the accesses is large enough to warrant a
387     // prefetch.
388     if (!isStrideLargeEnough(P.LSCEVAddRec, TargetMinStride))
389       continue;
390 
391     const SCEV *NextLSCEV = SE->getAddExpr(P.LSCEVAddRec, SE->getMulExpr(
392       SE->getConstant(P.LSCEVAddRec->getType(), ItersAhead),
393       P.LSCEVAddRec->getStepRecurrence(*SE)));
394     if (!isSafeToExpand(NextLSCEV, *SE))
395       continue;
396 
397     BasicBlock *BB = P.InsertPt->getParent();
398     Type *I8Ptr = Type::getInt8PtrTy(BB->getContext(), 0/*PtrAddrSpace*/);
399     SCEVExpander SCEVE(*SE, BB->getModule()->getDataLayout(), "prefaddr");
400     Value *PrefPtrValue = SCEVE.expandCodeFor(NextLSCEV, I8Ptr, P.InsertPt);
401 
402     IRBuilder<> Builder(P.InsertPt);
403     Module *M = BB->getParent()->getParent();
404     Type *I32 = Type::getInt32Ty(BB->getContext());
405     Function *PrefetchFunc = Intrinsic::getDeclaration(
406         M, Intrinsic::prefetch, PrefPtrValue->getType());
407     Builder.CreateCall(
408         PrefetchFunc,
409         {PrefPtrValue,
410          ConstantInt::get(I32, P.Writes),
411          ConstantInt::get(I32, 3), ConstantInt::get(I32, 1)});
412     ++NumPrefetches;
413     LLVM_DEBUG(dbgs() << "  Access: "
414                << *P.MemI->getOperand(isa<LoadInst>(P.MemI) ? 0 : 1)
415                << ", SCEV: " << *P.LSCEVAddRec << "\n");
416     ORE->emit([&]() {
417         return OptimizationRemark(DEBUG_TYPE, "Prefetched", P.MemI)
418           << "prefetched memory access";
419       });
420 
421     MadeChange = true;
422   }
423 
424   return MadeChange;
425 }
426