blob: c113ae5f52cef46b4b0621e3daf43e9498284cfe [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"
Chandler Carruth7b560d42015-09-09 17:55:00 +000024#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Hal Finkele5aaf3f2015-02-20 05:08:21 +000025#include "llvm/Analysis/ScalarEvolutionExpander.h"
26#include "llvm/Analysis/ScalarEvolutionExpressions.h"
27#include "llvm/Analysis/TargetTransformInfo.h"
28#include "llvm/Analysis/ValueTracking.h"
29#include "llvm/IR/CFG.h"
30#include "llvm/IR/Dominators.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/IntrinsicInst.h"
33#include "llvm/IR/Module.h"
34#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Transforms/Utils/BasicBlockUtils.h"
37#include "llvm/Transforms/Utils/Local.h"
38#include "llvm/Transforms/Utils/ValueMapper.h"
39using 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).
43static cl::opt<bool>
44PrefetchWrites("ppc-loop-prefetch-writes", cl::Hidden, cl::init(false),
45 cl::desc("Prefetch write addresses"));
46
47// This seems like a reasonable default for the BG/Q (this pass is enabled, by
48// default, only on the BG/Q).
49static cl::opt<unsigned>
50PrefDist("ppc-loop-prefetch-distance", cl::Hidden, cl::init(300),
51 cl::desc("The loop prefetch distance"));
52
Hal Finkele5aaf3f2015-02-20 05:08:21 +000053namespace llvm {
54 void initializePPCLoopDataPrefetchPass(PassRegistry&);
55}
56
57namespace {
58
59 class PPCLoopDataPrefetch : public FunctionPass {
60 public:
61 static char ID; // Pass ID, replacement for typeid
62 PPCLoopDataPrefetch() : FunctionPass(ID) {
63 initializePPCLoopDataPrefetchPass(*PassRegistry::getPassRegistry());
64 }
65
66 void getAnalysisUsage(AnalysisUsage &AU) const override {
67 AU.addRequired<AssumptionCacheTracker>();
68 AU.addPreserved<DominatorTreeWrapperPass>();
69 AU.addRequired<LoopInfoWrapperPass>();
70 AU.addPreserved<LoopInfoWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +000071 AU.addRequired<ScalarEvolutionWrapperPass>();
Hal Finkele5aaf3f2015-02-20 05:08:21 +000072 // FIXME: For some reason, preserving SE here breaks LSR (even if
73 // this pass changes nothing).
Chandler Carruth2f1fd162015-08-17 02:08:17 +000074 // AU.addPreserved<ScalarEvolutionWrapperPass>();
Hal Finkele5aaf3f2015-02-20 05:08:21 +000075 AU.addRequired<TargetTransformInfoWrapperPass>();
76 }
77
78 bool runOnFunction(Function &F) override;
79 bool runOnLoop(Loop *L);
80
81 private:
82 AssumptionCache *AC;
83 LoopInfo *LI;
84 ScalarEvolution *SE;
85 const TargetTransformInfo *TTI;
86 const DataLayout *DL;
87 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000088}
Hal Finkele5aaf3f2015-02-20 05:08:21 +000089
90char PPCLoopDataPrefetch::ID = 0;
91INITIALIZE_PASS_BEGIN(PPCLoopDataPrefetch, "ppc-loop-data-prefetch",
92 "PPC Loop Data Prefetch", false, false)
93INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
94INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
95INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +000096INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Hal Finkele5aaf3f2015-02-20 05:08:21 +000097INITIALIZE_PASS_END(PPCLoopDataPrefetch, "ppc-loop-data-prefetch",
98 "PPC Loop Data Prefetch", false, false)
99
100FunctionPass *llvm::createPPCLoopDataPrefetchPass() { return new PPCLoopDataPrefetch(); }
101
102bool PPCLoopDataPrefetch::runOnFunction(Function &F) {
103 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000104 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Mehdi Amini46a43552015-03-04 18:43:29 +0000105 DL = &F.getParent()->getDataLayout();
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000106 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
107 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
108
Adam Nemetaf761102016-01-21 18:28:36 +0000109 assert(TTI->getCacheLineSize() && "Cache line size is not set for target");
110
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000111 bool MadeChange = false;
112
Hal Finkel5551f252015-04-12 17:18:56 +0000113 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);
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000116
117 return MadeChange;
118}
119
120bool PPCLoopDataPrefetch::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 = PrefDist/LoopSize;
151 if (!ItersAhead)
152 ItersAhead = 1;
153
154 SmallVector<std::pair<Instruction *, const SCEVAddRecExpr *>, 16> PrefLoads;
155 for (Loop::block_iterator I = L->block_begin(), IE = L->block_end();
156 I != IE; ++I) {
157 for (BasicBlock::iterator J = (*I)->begin(), JE = (*I)->end();
158 J != JE; ++J) {
159 Value *PtrValue;
160 Instruction *MemI;
161
162 if (LoadInst *LMemI = dyn_cast<LoadInst>(J)) {
163 MemI = LMemI;
164 PtrValue = LMemI->getPointerOperand();
165 } else if (StoreInst *SMemI = dyn_cast<StoreInst>(J)) {
166 if (!PrefetchWrites) continue;
167 MemI = SMemI;
168 PtrValue = SMemI->getPointerOperand();
169 } else continue;
170
171 unsigned PtrAddrSpace = PtrValue->getType()->getPointerAddressSpace();
172 if (PtrAddrSpace)
173 continue;
174
175 if (L->isLoopInvariant(PtrValue))
176 continue;
177
178 const SCEV *LSCEV = SE->getSCEV(PtrValue);
179 const SCEVAddRecExpr *LSCEVAddRec = dyn_cast<SCEVAddRecExpr>(LSCEV);
180 if (!LSCEVAddRec)
181 continue;
182
183 // We don't want to double prefetch individual cache lines. If this load
184 // is known to be within one cache line of some other load that has
185 // already been prefetched, then don't prefetch this one as well.
186 bool DupPref = false;
187 for (SmallVector<std::pair<Instruction *, const SCEVAddRecExpr *>,
188 16>::iterator K = PrefLoads.begin(), KE = PrefLoads.end();
189 K != KE; ++K) {
190 const SCEV *PtrDiff = SE->getMinusSCEV(LSCEVAddRec, K->second);
191 if (const SCEVConstant *ConstPtrDiff =
192 dyn_cast<SCEVConstant>(PtrDiff)) {
Benjamin Kramer7bd1f7c2015-03-09 20:20:16 +0000193 int64_t PD = std::abs(ConstPtrDiff->getValue()->getSExtValue());
Adam Nemetaf761102016-01-21 18:28:36 +0000194 if (PD < (int64_t) TTI->getCacheLineSize()) {
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000195 DupPref = true;
196 break;
197 }
198 }
199 }
200 if (DupPref)
201 continue;
202
203 const SCEV *NextLSCEV = SE->getAddExpr(LSCEVAddRec, SE->getMulExpr(
204 SE->getConstant(LSCEVAddRec->getType(), ItersAhead),
205 LSCEVAddRec->getStepRecurrence(*SE)));
206 if (!isSafeToExpand(NextLSCEV, *SE))
207 continue;
208
209 PrefLoads.push_back(std::make_pair(MemI, LSCEVAddRec));
210
211 Type *I8Ptr = Type::getInt8PtrTy((*I)->getContext(), PtrAddrSpace);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000212 SCEVExpander SCEVE(*SE, J->getModule()->getDataLayout(), "prefaddr");
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000213 Value *PrefPtrValue = SCEVE.expandCodeFor(NextLSCEV, I8Ptr, MemI);
214
215 IRBuilder<> Builder(MemI);
216 Module *M = (*I)->getParent()->getParent();
217 Type *I32 = Type::getInt32Ty((*I)->getContext());
218 Value *PrefetchFunc = Intrinsic::getDeclaration(M, Intrinsic::prefetch);
David Blaikieff6409d2015-05-18 22:13:54 +0000219 Builder.CreateCall(
220 PrefetchFunc,
221 {PrefPtrValue,
222 ConstantInt::get(I32, MemI->mayReadFromMemory() ? 0 : 1),
223 ConstantInt::get(I32, 3), ConstantInt::get(I32, 1)});
Hal Finkele5aaf3f2015-02-20 05:08:21 +0000224
225 MadeChange = true;
226 }
227 }
228
229 return MadeChange;
230}
231