Simplify LDA-internal interface.
[oota-llvm.git] / lib / Analysis / LoopDependenceAnalysis.cpp
1 //===- LoopDependenceAnalysis.cpp - LDA Implementation ----------*- C++ -*-===//
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 is the (beginning) of an implementation of a loop dependence analysis
11 // framework, which is used to detect dependences in memory accesses in loops.
12 //
13 // Please note that this is work in progress and the interface is subject to
14 // change.
15 //
16 // TODO: adapt as implementation progresses.
17 //
18 //===----------------------------------------------------------------------===//
19
20 #define DEBUG_TYPE "lda"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/LoopDependenceAnalysis.h"
24 #include "llvm/Analysis/LoopPass.h"
25 #include "llvm/Analysis/ScalarEvolution.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Support/Allocator.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Target/TargetData.h"
32 using namespace llvm;
33
34 STATISTIC(NumAnswered,    "Number of dependence queries answered");
35 STATISTIC(NumAnalysed,    "Number of distinct dependence pairs analysed");
36 STATISTIC(NumDependent,   "Number of pairs with dependent accesses");
37 STATISTIC(NumIndependent, "Number of pairs with independent accesses");
38 STATISTIC(NumUnknown,     "Number of pairs with unknown accesses");
39
40 LoopPass *llvm::createLoopDependenceAnalysisPass() {
41   return new LoopDependenceAnalysis();
42 }
43
44 static RegisterPass<LoopDependenceAnalysis>
45 R("lda", "Loop Dependence Analysis", false, true);
46 char LoopDependenceAnalysis::ID = 0;
47
48 //===----------------------------------------------------------------------===//
49 //                             Utility Functions
50 //===----------------------------------------------------------------------===//
51
52 static inline bool IsMemRefInstr(const Value *V) {
53   const Instruction *I = dyn_cast<const Instruction>(V);
54   return I && (I->mayReadFromMemory() || I->mayWriteToMemory());
55 }
56
57 static void GetMemRefInstrs(const Loop *L,
58                             SmallVectorImpl<Instruction*> &Memrefs) {
59   for (Loop::block_iterator b = L->block_begin(), be = L->block_end();
60        b != be; ++b)
61     for (BasicBlock::iterator i = (*b)->begin(), ie = (*b)->end();
62          i != ie; ++i)
63       if (IsMemRefInstr(i))
64         Memrefs.push_back(i);
65 }
66
67 static bool IsLoadOrStoreInst(Value *I) {
68   return isa<LoadInst>(I) || isa<StoreInst>(I);
69 }
70
71 static Value *GetPointerOperand(Value *I) {
72   if (LoadInst *i = dyn_cast<LoadInst>(I))
73     return i->getPointerOperand();
74   if (StoreInst *i = dyn_cast<StoreInst>(I))
75     return i->getPointerOperand();
76   llvm_unreachable("Value is no load or store instruction!");
77   // Never reached.
78   return 0;
79 }
80
81 static AliasAnalysis::AliasResult UnderlyingObjectsAlias(AliasAnalysis *AA,
82                                                          const Value *A,
83                                                          const Value *B) {
84   const Value *aObj = A->getUnderlyingObject();
85   const Value *bObj = B->getUnderlyingObject();
86   return AA->alias(aObj, AA->getTypeStoreSize(aObj->getType()),
87                    bObj, AA->getTypeStoreSize(bObj->getType()));
88 }
89
90 //===----------------------------------------------------------------------===//
91 //                             Dependence Testing
92 //===----------------------------------------------------------------------===//
93
94 bool LoopDependenceAnalysis::isDependencePair(const Value *A,
95                                               const Value *B) const {
96   return IsMemRefInstr(A) &&
97          IsMemRefInstr(B) &&
98          (cast<const Instruction>(A)->mayWriteToMemory() ||
99           cast<const Instruction>(B)->mayWriteToMemory());
100 }
101
102 bool LoopDependenceAnalysis::findOrInsertDependencePair(Value *A,
103                                                         Value *B,
104                                                         DependencePair *&P) {
105   void *insertPos = 0;
106   FoldingSetNodeID id;
107   id.AddPointer(A);
108   id.AddPointer(B);
109
110   P = Pairs.FindNodeOrInsertPos(id, insertPos);
111   if (P) return true;
112
113   P = PairAllocator.Allocate<DependencePair>();
114   new (P) DependencePair(id, A, B);
115   Pairs.InsertNode(P, insertPos);
116   return false;
117 }
118
119 LoopDependenceAnalysis::DependenceResult
120 LoopDependenceAnalysis::analysePair(DependencePair *P) const {
121   DEBUG(errs() << "Analysing:\n" << *P->A << "\n" << *P->B << "\n");
122
123   // We only analyse loads and stores but no possible memory accesses by e.g.
124   // free, call, or invoke instructions.
125   if (!IsLoadOrStoreInst(P->A) || !IsLoadOrStoreInst(P->B)) {
126     DEBUG(errs() << "--> [?] no load/store\n");
127     return Unknown;
128   }
129
130   Value *aPtr = GetPointerOperand(P->A);
131   Value *bPtr = GetPointerOperand(P->B);
132
133   switch (UnderlyingObjectsAlias(AA, aPtr, bPtr)) {
134   case AliasAnalysis::MayAlias:
135     // We can not analyse objects if we do not know about their aliasing.
136     DEBUG(errs() << "---> [?] may alias\n");
137     return Unknown;
138
139   case AliasAnalysis::NoAlias:
140     // If the objects noalias, they are distinct, accesses are independent.
141     DEBUG(errs() << "---> [I] no alias\n");
142     return Independent;
143
144   case AliasAnalysis::MustAlias:
145     break; // The underlying objects alias, test accesses for dependence.
146   }
147
148   // We failed to analyse this pair to get a more specific answer.
149   DEBUG(errs() << "---> [?] cannot analyse\n");
150   return Unknown;
151 }
152
153 bool LoopDependenceAnalysis::depends(Value *A, Value *B) {
154   assert(isDependencePair(A, B) && "Values form no dependence pair!");
155   ++NumAnswered;
156
157   DependencePair *p;
158   if (!findOrInsertDependencePair(A, B, p)) {
159     // The pair is not cached, so analyse it.
160     ++NumAnalysed;
161     switch (p->Result = analysePair(p)) {
162     case Dependent:   ++NumDependent;   break;
163     case Independent: ++NumIndependent; break;
164     case Unknown:     ++NumUnknown;     break;
165     }
166   }
167   return p->Result != Independent;
168 }
169
170 //===----------------------------------------------------------------------===//
171 //                   LoopDependenceAnalysis Implementation
172 //===----------------------------------------------------------------------===//
173
174 bool LoopDependenceAnalysis::runOnLoop(Loop *L, LPPassManager &) {
175   this->L = L;
176   AA = &getAnalysis<AliasAnalysis>();
177   SE = &getAnalysis<ScalarEvolution>();
178   return false;
179 }
180
181 void LoopDependenceAnalysis::releaseMemory() {
182   Pairs.clear();
183   PairAllocator.Reset();
184 }
185
186 void LoopDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
187   AU.setPreservesAll();
188   AU.addRequiredTransitive<AliasAnalysis>();
189   AU.addRequiredTransitive<ScalarEvolution>();
190 }
191
192 static void PrintLoopInfo(raw_ostream &OS,
193                           LoopDependenceAnalysis *LDA, const Loop *L) {
194   if (!L->empty()) return; // ignore non-innermost loops
195
196   SmallVector<Instruction*, 8> memrefs;
197   GetMemRefInstrs(L, memrefs);
198
199   OS << "Loop at depth " << L->getLoopDepth() << ", header block: ";
200   WriteAsOperand(OS, L->getHeader(), false);
201   OS << "\n";
202
203   OS << "  Load/store instructions: " << memrefs.size() << "\n";
204   for (SmallVector<Instruction*, 8>::const_iterator x = memrefs.begin(),
205        end = memrefs.end(); x != end; ++x)
206     OS << "\t" << (x - memrefs.begin()) << ": " << **x << "\n";
207
208   OS << "  Pairwise dependence results:\n";
209   for (SmallVector<Instruction*, 8>::const_iterator x = memrefs.begin(),
210        end = memrefs.end(); x != end; ++x)
211     for (SmallVector<Instruction*, 8>::const_iterator y = x + 1;
212          y != end; ++y)
213       if (LDA->isDependencePair(*x, *y))
214         OS << "\t" << (x - memrefs.begin()) << "," << (y - memrefs.begin())
215            << ": " << (LDA->depends(*x, *y) ? "dependent" : "independent")
216            << "\n";
217 }
218
219 void LoopDependenceAnalysis::print(raw_ostream &OS, const Module*) const {
220   // TODO: doc why const_cast is safe
221   PrintLoopInfo(OS, const_cast<LoopDependenceAnalysis*>(this), this->L);
222 }
223
224 void LoopDependenceAnalysis::print(std::ostream &OS, const Module *M) const {
225   raw_os_ostream os(OS);
226   print(os, M);
227 }