blob: 77d3727c303d5d9f9bd03c1027c8f720f1b92f0e [file] [log] [blame]
Hal Finkele5aaf3f2015-02-20 05:08:21 +00001//===-------- PPCLoopDataPrefetch.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 "ppc-loop-data-prefetch"
15#include "PPC.h"
16#include "llvm/Transforms/Scalar.h"
Hal Finkela9fceb82015-04-10 15:05:02 +000017#include "llvm/ADT/DepthFirstIterator.h"
Hal Finkele5aaf3f2015-02-20 05:08:21 +000018#include "llvm/ADT/Statistic.h"
19#include "llvm/Analysis/AssumptionCache.h"
20#include "llvm/Analysis/CodeMetrics.h"
21#include "llvm/Analysis/InstructionSimplify.h"
22#include "llvm/Analysis/LoopInfo.h"
23#include "llvm/Analysis/ScalarEvolution.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"
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>
43PrefetchWrites("ppc-loop-prefetch-writes", cl::Hidden, cl::init(false),
44 cl::desc("Prefetch write addresses"));
45
46// This seems like a reasonable default for the BG/Q (this pass is enabled, by
47// default, only on the BG/Q).
48static cl::opt<unsigned>
49PrefDist("ppc-loop-prefetch-distance", cl::Hidden, cl::init(300),
50 cl::desc("The loop prefetch distance"));
51
52static cl::opt<unsigned>
53CacheLineSize("ppc-loop-prefetch-cache-line", cl::Hidden, cl::init(64),
54 cl::desc("The loop prefetch cache line size"));
55
56namespace llvm {
57 void initializePPCLoopDataPrefetchPass(PassRegistry&);
58}
59
60namespace {
61
62 class PPCLoopDataPrefetch : public FunctionPass {
63 public:
64 static char ID; // Pass ID, replacement for typeid
65 PPCLoopDataPrefetch() : FunctionPass(ID) {
66 initializePPCLoopDataPrefetchPass(*PassRegistry::getPassRegistry());
67 }
68
69 void getAnalysisUsage(AnalysisUsage &AU) const override {
70 AU.addRequired<AssumptionCacheTracker>();
71 AU.addPreserved<DominatorTreeWrapperPass>();
72 AU.addRequired<LoopInfoWrapperPass>();
73 AU.addPreserved<LoopInfoWrapperPass>();
74 AU.addRequired<ScalarEvolution>();
75 // FIXME: For some reason, preserving SE here breaks LSR (even if
76 // this pass changes nothing).
77 // AU.addPreserved<ScalarEvolution>();
78 AU.addRequired<TargetTransformInfoWrapperPass>();
79 }
80
81 bool runOnFunction(Function &F) override;
82 bool runOnLoop(Loop *L);
83
84 private:
85 AssumptionCache *AC;
86 LoopInfo *LI;
87 ScalarEvolution *SE;
88 const TargetTransformInfo *TTI;
89 const DataLayout *DL;
90 };
91}
92
93char PPCLoopDataPrefetch::ID = 0;
94INITIALIZE_PASS_BEGIN(PPCLoopDataPrefetch, "ppc-loop-data-prefetch",
95 "PPC Loop Data Prefetch", false, false)
96INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
97INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
98INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
99INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
100INITIALIZE_PASS_END(PPCLoopDataPrefetch, "ppc-loop-data-prefetch",
101 "PPC Loop Data Prefetch", false, false)
102
103FunctionPass *llvm::createPPCLoopDataPrefetchPass() { return new PPCLoopDataPrefetch(); }
104
105bool PPCLoopDataPrefetch::runOnFunction(Function &F) {
106 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
107 SE = &getAnalysis<ScalarEvolution>();
Mehdi Amini46a43552015-03-04 18:43:29 +0000108 DL = &F.getParent()->getDataLayout();
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000109 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
110 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
111
112 bool MadeChange = false;
113
Hal Finkela9fceb82015-04-10 15:05:02 +0000114 if (LI->empty())
115 return MadeChange;
116
117 for (auto I = df_begin(*LI->begin()), E = df_end(*LI->begin()); I != E; ++I) {
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000118 Loop *L = *I;
119 MadeChange |= runOnLoop(L);
120 }
121
122 return MadeChange;
123}
124
125bool PPCLoopDataPrefetch::runOnLoop(Loop *L) {
126 bool MadeChange = false;
127
128 // Only prefetch in the inner-most loop
129 if (!L->empty())
130 return MadeChange;
131
132 SmallPtrSet<const Value *, 32> EphValues;
133 CodeMetrics::collectEphemeralValues(L, AC, EphValues);
134
135 // Calculate the number of iterations ahead to prefetch
136 CodeMetrics Metrics;
137 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
138 I != IE; ++I) {
139
140 // If the loop already has prefetches, then assume that the user knows
141 // what he or she is doing and don't add any more.
142 for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
143 J != JE; ++J)
144 if (CallInst *CI = dyn_cast<CallInst>(J))
145 if (Function *F = CI->getCalledFunction())
146 if (F->getIntrinsicID() == Intrinsic::prefetch)
147 return MadeChange;
148
149 Metrics.analyzeBasicBlock(*I, *TTI, EphValues);
150 }
151 unsigned LoopSize = Metrics.NumInsts;
152 if (!LoopSize)
153 LoopSize = 1;
154
155 unsigned ItersAhead = PrefDist/LoopSize;
156 if (!ItersAhead)
157 ItersAhead = 1;
158
159 SmallVector<std::pair<Instruction *, const SCEVAddRecExpr *>, 16> PrefLoads;
160 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
161 I != IE; ++I) {
162 for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
163 J != JE; ++J) {
164 Value *PtrValue;
165 Instruction *MemI;
166
167 if (LoadInst *LMemI = dyn_cast<LoadInst>(J)) {
168 MemI = LMemI;
169 PtrValue = LMemI->getPointerOperand();
170 } else if (StoreInst *SMemI = dyn_cast<StoreInst>(J)) {
171 if (!PrefetchWrites) continue;
172 MemI = SMemI;
173 PtrValue = SMemI->getPointerOperand();
174 } else continue;
175
176 unsigned PtrAddrSpace = PtrValue->getType()->getPointerAddressSpace();
177 if (PtrAddrSpace)
178 continue;
179
180 if (L->isLoopInvariant(PtrValue))
181 continue;
182
183 const SCEV *LSCEV = SE->getSCEV(PtrValue);
184 const SCEVAddRecExpr *LSCEVAddRec = dyn_cast<SCEVAddRecExpr>(LSCEV);
185 if (!LSCEVAddRec)
186 continue;
187
188 // We don't want to double prefetch individual cache lines. If this load
189 // is known to be within one cache line of some other load that has
190 // already been prefetched, then don't prefetch this one as well.
191 bool DupPref = false;
192 for (SmallVector<std::pair<Instruction *, const SCEVAddRecExpr *>,
193 16>::iterator K = PrefLoads.begin(), KE = PrefLoads.end();
194 K != KE; ++K) {
195 const SCEV *PtrDiff = SE->getMinusSCEV(LSCEVAddRec, K->second);
196 if (const SCEVConstant *ConstPtrDiff =
197 dyn_cast<SCEVConstant>(PtrDiff)) {
Benjamin Kramer7bd1f7c2015-03-09 20:20:16 +0000198 int64_t PD = std::abs(ConstPtrDiff->getValue()->getSExtValue());
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000199 if (PD < (int64_t) CacheLineSize) {
200 DupPref = true;
201 break;
202 }
203 }
204 }
205 if (DupPref)
206 continue;
207
208 const SCEV *NextLSCEV = SE->getAddExpr(LSCEVAddRec, SE->getMulExpr(
209 SE->getConstant(LSCEVAddRec->getType(), ItersAhead),
210 LSCEVAddRec->getStepRecurrence(*SE)));
211 if (!isSafeToExpand(NextLSCEV, *SE))
212 continue;
213
214 PrefLoads.push_back(std::make_pair(MemI, LSCEVAddRec));
215
216 Type *I8Ptr = Type::getInt8PtrTy((*I)->getContext(), PtrAddrSpace);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000217 SCEVExpander SCEVE(*SE, J->getModule()->getDataLayout(), "prefaddr");
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000218 Value *PrefPtrValue = SCEVE.expandCodeFor(NextLSCEV, I8Ptr, MemI);
219
220 IRBuilder<> Builder(MemI);
221 Module *M = (*I)->getParent()->getParent();
222 Type *I32 = Type::getInt32Ty((*I)->getContext());
223 Value *PrefetchFunc = Intrinsic::getDeclaration(M, Intrinsic::prefetch);
224 Builder.CreateCall4(PrefetchFunc, PrefPtrValue,
225 ConstantInt::get(I32, MemI->mayReadFromMemory() ? 0 : 1),
226 ConstantInt::get(I32, 3), ConstantInt::get(I32, 1));
227
228 MadeChange = true;
229 }
230 }
231
232 return MadeChange;
233}
234