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/DenseSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/Analysis/LoopDependenceAnalysis.h"
27 #include "llvm/Analysis/LoopPass.h"
28 #include "llvm/Analysis/ScalarEvolution.h"
29 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/Assembly/Writer.h"
32 #include "llvm/Instructions.h"
33 #include "llvm/Operator.h"
34 #include "llvm/Support/Allocator.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetData.h"
41 STATISTIC(NumAnswered
, "Number of dependence queries answered");
42 STATISTIC(NumAnalysed
, "Number of distinct dependence pairs analysed");
43 STATISTIC(NumDependent
, "Number of pairs with dependent accesses");
44 STATISTIC(NumIndependent
, "Number of pairs with independent accesses");
45 STATISTIC(NumUnknown
, "Number of pairs with unknown accesses");
47 LoopPass
*llvm::createLoopDependenceAnalysisPass() {
48 return new LoopDependenceAnalysis();
51 INITIALIZE_PASS_BEGIN(LoopDependenceAnalysis
, "lda",
52 "Loop Dependence Analysis", false, true)
53 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution
)
54 INITIALIZE_AG_DEPENDENCY(AliasAnalysis
)
55 INITIALIZE_PASS_END(LoopDependenceAnalysis
, "lda",
56 "Loop Dependence Analysis", false, true)
57 char LoopDependenceAnalysis::ID
= 0;
59 //===----------------------------------------------------------------------===//
61 //===----------------------------------------------------------------------===//
63 static inline bool IsMemRefInstr(const Value
*V
) {
64 const Instruction
*I
= dyn_cast
<const Instruction
>(V
);
65 return I
&& (I
->mayReadFromMemory() || I
->mayWriteToMemory());
68 static void GetMemRefInstrs(const Loop
*L
,
69 SmallVectorImpl
<Instruction
*> &Memrefs
) {
70 for (Loop::block_iterator b
= L
->block_begin(), be
= L
->block_end();
72 for (BasicBlock::iterator i
= (*b
)->begin(), ie
= (*b
)->end();
78 static bool IsLoadOrStoreInst(Value
*I
) {
79 return isa
<LoadInst
>(I
) || isa
<StoreInst
>(I
);
82 static Value
*GetPointerOperand(Value
*I
) {
83 if (LoadInst
*i
= dyn_cast
<LoadInst
>(I
))
84 return i
->getPointerOperand();
85 if (StoreInst
*i
= dyn_cast
<StoreInst
>(I
))
86 return i
->getPointerOperand();
87 llvm_unreachable("Value is no load or store instruction!");
92 static AliasAnalysis::AliasResult
UnderlyingObjectsAlias(AliasAnalysis
*AA
,
95 const Value
*aObj
= GetUnderlyingObject(A
);
96 const Value
*bObj
= GetUnderlyingObject(B
);
97 return AA
->alias(aObj
, AA
->getTypeStoreSize(aObj
->getType()),
98 bObj
, AA
->getTypeStoreSize(bObj
->getType()));
101 static inline const SCEV
*GetZeroSCEV(ScalarEvolution
*SE
) {
102 return SE
->getConstant(Type::getInt32Ty(SE
->getContext()), 0L);
105 //===----------------------------------------------------------------------===//
106 // Dependence Testing
107 //===----------------------------------------------------------------------===//
109 bool LoopDependenceAnalysis::isDependencePair(const Value
*A
,
110 const Value
*B
) const {
111 return IsMemRefInstr(A
) &&
113 (cast
<const Instruction
>(A
)->mayWriteToMemory() ||
114 cast
<const Instruction
>(B
)->mayWriteToMemory());
117 bool LoopDependenceAnalysis::findOrInsertDependencePair(Value
*A
,
119 DependencePair
*&P
) {
125 P
= Pairs
.FindNodeOrInsertPos(id
, insertPos
);
128 P
= new (PairAllocator
) DependencePair(id
, A
, B
);
129 Pairs
.InsertNode(P
, insertPos
);
133 void LoopDependenceAnalysis::getLoops(const SCEV
*S
,
134 DenseSet
<const Loop
*>* Loops
) const {
135 // Refactor this into an SCEVVisitor, if efficiency becomes a concern.
136 for (const Loop
*L
= this->L
; L
!= 0; L
= L
->getParentLoop())
137 if (!SE
->isLoopInvariant(S
, L
))
141 bool LoopDependenceAnalysis::isLoopInvariant(const SCEV
*S
) const {
142 DenseSet
<const Loop
*> loops
;
144 return loops
.empty();
147 bool LoopDependenceAnalysis::isAffine(const SCEV
*S
) const {
148 const SCEVAddRecExpr
*rec
= dyn_cast
<SCEVAddRecExpr
>(S
);
149 return isLoopInvariant(S
) || (rec
&& rec
->isAffine());
152 bool LoopDependenceAnalysis::isZIVPair(const SCEV
*A
, const SCEV
*B
) const {
153 return isLoopInvariant(A
) && isLoopInvariant(B
);
156 bool LoopDependenceAnalysis::isSIVPair(const SCEV
*A
, const SCEV
*B
) const {
157 DenseSet
<const Loop
*> loops
;
160 return loops
.size() == 1;
163 LoopDependenceAnalysis::DependenceResult
164 LoopDependenceAnalysis::analyseZIV(const SCEV
*A
,
166 Subscript
*S
) const {
167 assert(isZIVPair(A
, B
) && "Attempted to ZIV-test non-ZIV SCEVs!");
168 return A
== B
? Dependent
: Independent
;
171 LoopDependenceAnalysis::DependenceResult
172 LoopDependenceAnalysis::analyseSIV(const SCEV
*A
,
174 Subscript
*S
) const {
175 return Unknown
; // TODO: Implement.
178 LoopDependenceAnalysis::DependenceResult
179 LoopDependenceAnalysis::analyseMIV(const SCEV
*A
,
181 Subscript
*S
) const {
182 return Unknown
; // TODO: Implement.
185 LoopDependenceAnalysis::DependenceResult
186 LoopDependenceAnalysis::analyseSubscript(const SCEV
*A
,
188 Subscript
*S
) const {
189 DEBUG(dbgs() << " Testing subscript: " << *A
<< ", " << *B
<< "\n");
192 DEBUG(dbgs() << " -> [D] same SCEV\n");
196 if (!isAffine(A
) || !isAffine(B
)) {
197 DEBUG(dbgs() << " -> [?] not affine\n");
202 return analyseZIV(A
, B
, S
);
205 return analyseSIV(A
, B
, S
);
207 return analyseMIV(A
, B
, S
);
210 LoopDependenceAnalysis::DependenceResult
211 LoopDependenceAnalysis::analysePair(DependencePair
*P
) const {
212 DEBUG(dbgs() << "Analysing:\n" << *P
->A
<< "\n" << *P
->B
<< "\n");
214 // We only analyse loads and stores but no possible memory accesses by e.g.
215 // free, call, or invoke instructions.
216 if (!IsLoadOrStoreInst(P
->A
) || !IsLoadOrStoreInst(P
->B
)) {
217 DEBUG(dbgs() << "--> [?] no load/store\n");
221 Value
*aPtr
= GetPointerOperand(P
->A
);
222 Value
*bPtr
= GetPointerOperand(P
->B
);
224 switch (UnderlyingObjectsAlias(AA
, aPtr
, bPtr
)) {
225 case AliasAnalysis::MayAlias
:
226 case AliasAnalysis::PartialAlias
:
227 // We can not analyse objects if we do not know about their aliasing.
228 DEBUG(dbgs() << "---> [?] may alias\n");
231 case AliasAnalysis::NoAlias
:
232 // If the objects noalias, they are distinct, accesses are independent.
233 DEBUG(dbgs() << "---> [I] no alias\n");
236 case AliasAnalysis::MustAlias
:
237 break; // The underlying objects alias, test accesses for dependence.
240 const GEPOperator
*aGEP
= dyn_cast
<GEPOperator
>(aPtr
);
241 const GEPOperator
*bGEP
= dyn_cast
<GEPOperator
>(bPtr
);
246 // FIXME: Is filtering coupled subscripts necessary?
248 // Collect GEP operand pairs (FIXME: use GetGEPOperands from BasicAA), adding
249 // trailing zeroes to the smaller GEP, if needed.
250 typedef SmallVector
<std::pair
<const SCEV
*, const SCEV
*>, 4> GEPOpdPairsTy
;
252 for(GEPOperator::const_op_iterator aIdx
= aGEP
->idx_begin(),
253 aEnd
= aGEP
->idx_end(),
254 bIdx
= bGEP
->idx_begin(),
255 bEnd
= bGEP
->idx_end();
256 aIdx
!= aEnd
&& bIdx
!= bEnd
;
257 aIdx
+= (aIdx
!= aEnd
), bIdx
+= (bIdx
!= bEnd
)) {
258 const SCEV
* aSCEV
= (aIdx
!= aEnd
) ? SE
->getSCEV(*aIdx
) : GetZeroSCEV(SE
);
259 const SCEV
* bSCEV
= (bIdx
!= bEnd
) ? SE
->getSCEV(*bIdx
) : GetZeroSCEV(SE
);
260 opds
.push_back(std::make_pair(aSCEV
, bSCEV
));
263 if (!opds
.empty() && opds
[0].first
!= opds
[0].second
) {
264 // We cannot (yet) handle arbitrary GEP pointer offsets. By limiting
266 // TODO: this could be relaxed by adding the size of the underlying object
267 // to the first subscript. If we have e.g. (GEP x,0,i; GEP x,2,-i) and we
268 // know that x is a [100 x i8]*, we could modify the first subscript to be
269 // (i, 200-i) instead of (i, -i).
273 // Now analyse the collected operand pairs (skipping the GEP ptr offsets).
274 for (GEPOpdPairsTy::const_iterator i
= opds
.begin() + 1, end
= opds
.end();
277 DependenceResult result
= analyseSubscript(i
->first
, i
->second
, &subscript
);
278 if (result
!= Dependent
) {
279 // We either proved independence or failed to analyse this subscript.
280 // Further subscripts will not improve the situation, so abort early.
283 P
->Subscripts
.push_back(subscript
);
285 // We successfully analysed all subscripts but failed to prove independence.
289 bool LoopDependenceAnalysis::depends(Value
*A
, Value
*B
) {
290 assert(isDependencePair(A
, B
) && "Values form no dependence pair!");
294 if (!findOrInsertDependencePair(A
, B
, p
)) {
295 // The pair is not cached, so analyse it.
297 switch (p
->Result
= analysePair(p
)) {
298 case Dependent
: ++NumDependent
; break;
299 case Independent
: ++NumIndependent
; break;
300 case Unknown
: ++NumUnknown
; break;
303 return p
->Result
!= Independent
;
306 //===----------------------------------------------------------------------===//
307 // LoopDependenceAnalysis Implementation
308 //===----------------------------------------------------------------------===//
310 bool LoopDependenceAnalysis::runOnLoop(Loop
*L
, LPPassManager
&) {
312 AA
= &getAnalysis
<AliasAnalysis
>();
313 SE
= &getAnalysis
<ScalarEvolution
>();
317 void LoopDependenceAnalysis::releaseMemory() {
319 PairAllocator
.Reset();
322 void LoopDependenceAnalysis::getAnalysisUsage(AnalysisUsage
&AU
) const {
323 AU
.setPreservesAll();
324 AU
.addRequiredTransitive
<AliasAnalysis
>();
325 AU
.addRequiredTransitive
<ScalarEvolution
>();
328 static void PrintLoopInfo(raw_ostream
&OS
,
329 LoopDependenceAnalysis
*LDA
, const Loop
*L
) {
330 if (!L
->empty()) return; // ignore non-innermost loops
332 SmallVector
<Instruction
*, 8> memrefs
;
333 GetMemRefInstrs(L
, memrefs
);
335 OS
<< "Loop at depth " << L
->getLoopDepth() << ", header block: ";
336 WriteAsOperand(OS
, L
->getHeader(), false);
339 OS
<< " Load/store instructions: " << memrefs
.size() << "\n";
340 for (SmallVector
<Instruction
*, 8>::const_iterator x
= memrefs
.begin(),
341 end
= memrefs
.end(); x
!= end
; ++x
)
342 OS
<< "\t" << (x
- memrefs
.begin()) << ": " << **x
<< "\n";
344 OS
<< " Pairwise dependence results:\n";
345 for (SmallVector
<Instruction
*, 8>::const_iterator x
= memrefs
.begin(),
346 end
= memrefs
.end(); x
!= end
; ++x
)
347 for (SmallVector
<Instruction
*, 8>::const_iterator y
= x
+ 1;
349 if (LDA
->isDependencePair(*x
, *y
))
350 OS
<< "\t" << (x
- memrefs
.begin()) << "," << (y
- memrefs
.begin())
351 << ": " << (LDA
->depends(*x
, *y
) ? "dependent" : "independent")
355 void LoopDependenceAnalysis::print(raw_ostream
&OS
, const Module
*) const {
356 // TODO: doc why const_cast is safe
357 PrintLoopInfo(OS
, const_cast<LoopDependenceAnalysis
*>(this), this->L
);