1 //===- LoopDependenceAnalysis.cpp - LDA Implementation ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is the (beginning) of an implementation of a loop dependence analysis
11 // framework, which is used to detect dependences in memory accesses in loops.
13 // Please note that this is work in progress and the interface is subject to
16 // TODO: adapt as implementation progresses.
18 // TODO: document lingo (pair, subscript, index)
20 //===----------------------------------------------------------------------===//
22 #define DEBUG_TYPE "lda"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/Analysis/LoopDependenceAnalysis.h"
26 #include "llvm/Analysis/LoopPass.h"
27 #include "llvm/Analysis/ScalarEvolution.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Operator.h"
30 #include "llvm/Support/Allocator.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetData.h"
37 STATISTIC(NumAnswered, "Number of dependence queries answered");
38 STATISTIC(NumAnalysed, "Number of distinct dependence pairs analysed");
39 STATISTIC(NumDependent, "Number of pairs with dependent accesses");
40 STATISTIC(NumIndependent, "Number of pairs with independent accesses");
41 STATISTIC(NumUnknown, "Number of pairs with unknown accesses");
43 LoopPass *llvm::createLoopDependenceAnalysisPass() {
44 return new LoopDependenceAnalysis();
47 static RegisterPass<LoopDependenceAnalysis>
48 R("lda", "Loop Dependence Analysis", false, true);
49 char LoopDependenceAnalysis::ID = 0;
51 //===----------------------------------------------------------------------===//
53 //===----------------------------------------------------------------------===//
55 static inline bool IsMemRefInstr(const Value *V) {
56 const Instruction *I = dyn_cast<const Instruction>(V);
57 return I && (I->mayReadFromMemory() || I->mayWriteToMemory());
60 static void GetMemRefInstrs(const Loop *L,
61 SmallVectorImpl<Instruction*> &Memrefs) {
62 for (Loop::block_iterator b = L->block_begin(), be = L->block_end();
64 for (BasicBlock::iterator i = (*b)->begin(), ie = (*b)->end();
70 static bool IsLoadOrStoreInst(Value *I) {
71 return isa<LoadInst>(I) || isa<StoreInst>(I);
74 static Value *GetPointerOperand(Value *I) {
75 if (LoadInst *i = dyn_cast<LoadInst>(I))
76 return i->getPointerOperand();
77 if (StoreInst *i = dyn_cast<StoreInst>(I))
78 return i->getPointerOperand();
79 llvm_unreachable("Value is no load or store instruction!");
84 static AliasAnalysis::AliasResult UnderlyingObjectsAlias(AliasAnalysis *AA,
87 const Value *aObj = A->getUnderlyingObject();
88 const Value *bObj = B->getUnderlyingObject();
89 return AA->alias(aObj, AA->getTypeStoreSize(aObj->getType()),
90 bObj, AA->getTypeStoreSize(bObj->getType()));
93 static inline const SCEV *GetZeroSCEV(ScalarEvolution *SE) {
94 return SE->getConstant(Type::Int32Ty, 0L);
97 //===----------------------------------------------------------------------===//
99 //===----------------------------------------------------------------------===//
101 bool LoopDependenceAnalysis::isDependencePair(const Value *A,
102 const Value *B) const {
103 return IsMemRefInstr(A) &&
105 (cast<const Instruction>(A)->mayWriteToMemory() ||
106 cast<const Instruction>(B)->mayWriteToMemory());
109 bool LoopDependenceAnalysis::findOrInsertDependencePair(Value *A,
111 DependencePair *&P) {
117 P = Pairs.FindNodeOrInsertPos(id, insertPos);
120 P = PairAllocator.Allocate<DependencePair>();
121 new (P) DependencePair(id, A, B);
122 Pairs.InsertNode(P, insertPos);
126 LoopDependenceAnalysis::DependenceResult
127 LoopDependenceAnalysis::analyseSubscript(const SCEV *A,
129 Subscript *S) const {
130 DEBUG(errs() << " Testing subscript: " << *A << ", " << *B << "\n");
133 DEBUG(errs() << " -> [D] same SCEV\n");
137 // TODO: Implement ZIV/SIV/MIV testers.
139 DEBUG(errs() << " -> [?] cannot analyse subscript\n");
143 LoopDependenceAnalysis::DependenceResult
144 LoopDependenceAnalysis::analysePair(DependencePair *P) const {
145 DEBUG(errs() << "Analysing:\n" << *P->A << "\n" << *P->B << "\n");
147 // We only analyse loads and stores but no possible memory accesses by e.g.
148 // free, call, or invoke instructions.
149 if (!IsLoadOrStoreInst(P->A) || !IsLoadOrStoreInst(P->B)) {
150 DEBUG(errs() << "--> [?] no load/store\n");
154 Value *aPtr = GetPointerOperand(P->A);
155 Value *bPtr = GetPointerOperand(P->B);
157 switch (UnderlyingObjectsAlias(AA, aPtr, bPtr)) {
158 case AliasAnalysis::MayAlias:
159 // We can not analyse objects if we do not know about their aliasing.
160 DEBUG(errs() << "---> [?] may alias\n");
163 case AliasAnalysis::NoAlias:
164 // If the objects noalias, they are distinct, accesses are independent.
165 DEBUG(errs() << "---> [I] no alias\n");
168 case AliasAnalysis::MustAlias:
169 break; // The underlying objects alias, test accesses for dependence.
172 const GEPOperator *aGEP = dyn_cast<GEPOperator>(aPtr);
173 const GEPOperator *bGEP = dyn_cast<GEPOperator>(bPtr);
178 // FIXME: Is filtering coupled subscripts necessary?
180 // Analyse indices pairwise (FIXME: use GetGEPOperands from BasicAA), adding
181 // trailing zeroes to the smaller GEP, if needed.
182 GEPOperator::const_op_iterator aIdx = aGEP->idx_begin(),
183 aEnd = aGEP->idx_end(),
184 bIdx = bGEP->idx_begin(),
185 bEnd = bGEP->idx_end();
186 while (aIdx != aEnd && bIdx != bEnd) {
187 const SCEV* aSCEV = (aIdx != aEnd) ? SE->getSCEV(*aIdx) : GetZeroSCEV(SE);
188 const SCEV* bSCEV = (bIdx != bEnd) ? SE->getSCEV(*bIdx) : GetZeroSCEV(SE);
190 DependenceResult result = analyseSubscript(aSCEV, bSCEV, &subscript);
191 if (result != Dependent) {
192 // We either proved independence or failed to analyse this subscript.
193 // Further subscripts will not improve the situation, so abort early.
196 P->Subscripts.push_back(subscript);
197 if (aIdx != aEnd) ++aIdx;
198 if (bIdx != bEnd) ++bIdx;
200 // Either there were no subscripts or all subscripts were analysed to be
201 // dependent; in both cases we know the accesses are dependent.
205 bool LoopDependenceAnalysis::depends(Value *A, Value *B) {
206 assert(isDependencePair(A, B) && "Values form no dependence pair!");
210 if (!findOrInsertDependencePair(A, B, p)) {
211 // The pair is not cached, so analyse it.
213 switch (p->Result = analysePair(p)) {
214 case Dependent: ++NumDependent; break;
215 case Independent: ++NumIndependent; break;
216 case Unknown: ++NumUnknown; break;
219 return p->Result != Independent;
222 //===----------------------------------------------------------------------===//
223 // LoopDependenceAnalysis Implementation
224 //===----------------------------------------------------------------------===//
226 bool LoopDependenceAnalysis::runOnLoop(Loop *L, LPPassManager &) {
228 AA = &getAnalysis<AliasAnalysis>();
229 SE = &getAnalysis<ScalarEvolution>();
233 void LoopDependenceAnalysis::releaseMemory() {
235 PairAllocator.Reset();
238 void LoopDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
239 AU.setPreservesAll();
240 AU.addRequiredTransitive<AliasAnalysis>();
241 AU.addRequiredTransitive<ScalarEvolution>();
244 static void PrintLoopInfo(raw_ostream &OS,
245 LoopDependenceAnalysis *LDA, const Loop *L) {
246 if (!L->empty()) return; // ignore non-innermost loops
248 SmallVector<Instruction*, 8> memrefs;
249 GetMemRefInstrs(L, memrefs);
251 OS << "Loop at depth " << L->getLoopDepth() << ", header block: ";
252 WriteAsOperand(OS, L->getHeader(), false);
255 OS << " Load/store instructions: " << memrefs.size() << "\n";
256 for (SmallVector<Instruction*, 8>::const_iterator x = memrefs.begin(),
257 end = memrefs.end(); x != end; ++x)
258 OS << "\t" << (x - memrefs.begin()) << ": " << **x << "\n";
260 OS << " Pairwise dependence results:\n";
261 for (SmallVector<Instruction*, 8>::const_iterator x = memrefs.begin(),
262 end = memrefs.end(); x != end; ++x)
263 for (SmallVector<Instruction*, 8>::const_iterator y = x + 1;
265 if (LDA->isDependencePair(*x, *y))
266 OS << "\t" << (x - memrefs.begin()) << "," << (y - memrefs.begin())
267 << ": " << (LDA->depends(*x, *y) ? "dependent" : "independent")
271 void LoopDependenceAnalysis::print(raw_ostream &OS, const Module*) const {
272 // TODO: doc why const_cast is safe
273 PrintLoopInfo(OS, const_cast<LoopDependenceAnalysis*>(this), this->L);
276 void LoopDependenceAnalysis::print(std::ostream &OS, const Module *M) const {
277 raw_os_ostream os(OS);