blob: 8e0322150b3171453f90986e992b3c83045351cb [file] [log] [blame]
Adam Nemet9d9cb272016-02-18 21:38:19 +00001//===-------- LoopDataPrefetch.cpp - Loop Data Prefetching Pass -----------===//
Hal Finkele5aaf3f2015-02-20 05:08:21 +00002//
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
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000014#define DEBUG_TYPE "loop-data-prefetch"
Hal Finkele5aaf3f2015-02-20 05:08:21 +000015#include "llvm/Transforms/Scalar.h"
Hal Finkela9fceb82015-04-10 15:05:02 +000016#include "llvm/ADT/DepthFirstIterator.h"
Hal Finkele5aaf3f2015-02-20 05:08:21 +000017#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"
Chandler Carruth7b560d42015-09-09 17:55:00 +000023#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Hal Finkele5aaf3f2015-02-20 05:08:21 +000024#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"
38using 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).
42static cl::opt<bool>
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000043PrefetchWrites("loop-prefetch-writes", cl::Hidden, cl::init(false),
Hal Finkele5aaf3f2015-02-20 05:08:21 +000044 cl::desc("Prefetch write addresses"));
45
Adam Nemet34785ec2016-03-09 05:33:21 +000046STATISTIC(NumPrefetches, "Number of prefetches inserted");
47
Hal Finkele5aaf3f2015-02-20 05:08:21 +000048namespace llvm {
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000049 void initializeLoopDataPrefetchPass(PassRegistry&);
Hal Finkele5aaf3f2015-02-20 05:08:21 +000050}
51
52namespace {
53
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000054 class LoopDataPrefetch : public FunctionPass {
Hal Finkele5aaf3f2015-02-20 05:08:21 +000055 public:
56 static char ID; // Pass ID, replacement for typeid
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000057 LoopDataPrefetch() : FunctionPass(ID) {
58 initializeLoopDataPrefetchPass(*PassRegistry::getPassRegistry());
Hal Finkele5aaf3f2015-02-20 05:08:21 +000059 }
60
61 void getAnalysisUsage(AnalysisUsage &AU) const override {
62 AU.addRequired<AssumptionCacheTracker>();
63 AU.addPreserved<DominatorTreeWrapperPass>();
64 AU.addRequired<LoopInfoWrapperPass>();
65 AU.addPreserved<LoopInfoWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +000066 AU.addRequired<ScalarEvolutionWrapperPass>();
Hal Finkele5aaf3f2015-02-20 05:08:21 +000067 // FIXME: For some reason, preserving SE here breaks LSR (even if
68 // this pass changes nothing).
Chandler Carruth2f1fd162015-08-17 02:08:17 +000069 // AU.addPreserved<ScalarEvolutionWrapperPass>();
Hal Finkele5aaf3f2015-02-20 05:08:21 +000070 AU.addRequired<TargetTransformInfoWrapperPass>();
71 }
72
73 bool runOnFunction(Function &F) override;
74 bool runOnLoop(Loop *L);
75
Adam Nemet6d8beec2016-03-18 00:27:38 +000076 /// \brief Check if the the stride of the accesses is large enough to
77 /// warrant a prefetch.
78 bool isStrideLargeEnough(const SCEVAddRecExpr *AR);
79
Hal Finkele5aaf3f2015-02-20 05:08:21 +000080 private:
81 AssumptionCache *AC;
82 LoopInfo *LI;
83 ScalarEvolution *SE;
84 const TargetTransformInfo *TTI;
85 const DataLayout *DL;
86 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000087}
Hal Finkele5aaf3f2015-02-20 05:08:21 +000088
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000089char LoopDataPrefetch::ID = 0;
90INITIALIZE_PASS_BEGIN(LoopDataPrefetch, "loop-data-prefetch",
91 "Loop Data Prefetch", false, false)
Hal Finkele5aaf3f2015-02-20 05:08:21 +000092INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
93INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
94INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +000095INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Adam Nemet7cf9b1b2016-02-18 21:37:12 +000096INITIALIZE_PASS_END(LoopDataPrefetch, "loop-data-prefetch",
97 "Loop Data Prefetch", false, false)
Hal Finkele5aaf3f2015-02-20 05:08:21 +000098
Adam Nemet9d9cb272016-02-18 21:38:19 +000099FunctionPass *llvm::createLoopDataPrefetchPass() { return new LoopDataPrefetch(); }
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000100
Adam Nemet6d8beec2016-03-18 00:27:38 +0000101bool 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
Adam Nemet7cf9b1b2016-02-18 21:37:12 +0000117bool LoopDataPrefetch::runOnFunction(Function &F) {
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000118 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000119 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Mehdi Amini46a43552015-03-04 18:43:29 +0000120 DL = &F.getParent()->getDataLayout();
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000121 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
122 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
123
Adam Nemetbb3680b2016-03-07 18:35:42 +0000124 // 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;
Adam Nemetaf761102016-01-21 18:28:36 +0000129 assert(TTI->getCacheLineSize() && "Cache line size is not set for target");
130
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000131 bool MadeChange = false;
132
Hal Finkel5551f252015-04-12 17:18:56 +0000133 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);
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000136
137 return MadeChange;
138}
139
Adam Nemet7cf9b1b2016-02-18 21:37:12 +0000140bool LoopDataPrefetch::runOnLoop(Loop *L) {
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000141 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
Adam Nemetdadfbb52016-01-27 22:21:25 +0000170 unsigned ItersAhead = TTI->getPrefetchDistance() / LoopSize;
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000171 if (!ItersAhead)
172 ItersAhead = 1;
173
Adam Nemet34785ec2016-03-09 05:33:21 +0000174 DEBUG(dbgs() << "Prefetching " << ItersAhead
175 << " iterations ahead (loop size: " << LoopSize << ") in "
176 << L->getHeader()->getParent()->getName() << ": " << *L);
177
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000178 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
Adam Nemet6d8beec2016-03-18 00:27:38 +0000207 // Check if the the stride of the accesses is large enough to warrant a
208 // prefetch.
209 if (!isStrideLargeEnough(LSCEVAddRec))
210 continue;
211
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000212 // 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)) {
Benjamin Kramer7bd1f7c2015-03-09 20:20:16 +0000222 int64_t PD = std::abs(ConstPtrDiff->getValue()->getSExtValue());
Adam Nemetaf761102016-01-21 18:28:36 +0000223 if (PD < (int64_t) TTI->getCacheLineSize()) {
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000224 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);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000241 SCEVExpander SCEVE(*SE, J->getModule()->getDataLayout(), "prefaddr");
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000242 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);
David Blaikieff6409d2015-05-18 22:13:54 +0000248 Builder.CreateCall(
249 PrefetchFunc,
250 {PrefPtrValue,
251 ConstantInt::get(I32, MemI->mayReadFromMemory() ? 0 : 1),
252 ConstantInt::get(I32, 3), ConstantInt::get(I32, 1)});
Adam Nemet34785ec2016-03-09 05:33:21 +0000253 ++NumPrefetches;
254 DEBUG(dbgs() << " Access: " << *PtrValue << ", SCEV: " << *LSCEV
255 << "\n");
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000256
257 MadeChange = true;
258 }
259 }
260
261 return MadeChange;
262}
263