b46563b475ecd083cc4676e35ed2bd280cb29d1f
[oota-llvm.git] / include / llvm / Analysis / MemoryDependenceAnalysis.h
1 //===- llvm/Analysis/MemoryDependenceAnalysis.h - Memory Deps  --*- 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 file defines the MemoryDependenceAnalysis analysis pass.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_ANALYSIS_MEMORY_DEPENDENCE_H
15 #define LLVM_ANALYSIS_MEMORY_DEPENDENCE_H
16
17 #include "llvm/BasicBlock.h"
18 #include "llvm/Pass.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/ADT/PointerIntPair.h"
23
24 namespace llvm {
25   class Function;
26   class FunctionPass;
27   class Instruction;
28   class CallSite;
29   class AliasAnalysis;
30   class TargetData;
31   class MemoryDependenceAnalysis;
32   class PredIteratorCache;
33   class DominatorTree;
34   class PHITransAddr;
35   
36   /// MemDepResult - A memory dependence query can return one of three different
37   /// answers, described below.
38   class MemDepResult {
39     enum DepType {
40       /// Invalid - Clients of MemDep never see this.
41       Invalid = 0,
42       
43       /// Clobber - This is a dependence on the specified instruction which
44       /// clobbers the desired value.  The pointer member of the MemDepResult
45       /// pair holds the instruction that clobbers the memory.  For example,
46       /// this occurs when we see a may-aliased store to the memory location we
47       /// care about.
48       Clobber,
49
50       /// Def - This is a dependence on the specified instruction which
51       /// defines/produces the desired memory location.  The pointer member of
52       /// the MemDepResult pair holds the instruction that defines the memory.
53       /// Cases of interest:
54       ///   1. This could be a load or store for dependence queries on
55       ///      load/store.  The value loaded or stored is the produced value.
56       ///      Note that the pointer operand may be different than that of the
57       ///      queried pointer due to must aliases and phi translation.  Note
58       ///      that the def may not be the same type as the query, the pointers
59       ///      may just be must aliases.
60       ///   2. For loads and stores, this could be an allocation instruction. In
61       ///      this case, the load is loading an undef value or a store is the
62       ///      first store to (that part of) the allocation.
63       ///   3. Dependence queries on calls return Def only when they are
64       ///      readonly calls or memory use intrinsics with identical callees
65       ///      and no intervening clobbers.  No validation is done that the
66       ///      operands to the calls are the same.
67       Def,
68       
69       /// NonLocal - This marker indicates that the query has no dependency in
70       /// the specified block.  To find out more, the client should query other
71       /// predecessor blocks.
72       NonLocal
73     };
74     typedef PointerIntPair<Instruction*, 2, DepType> PairTy;
75     PairTy Value;
76     explicit MemDepResult(PairTy V) : Value(V) {}
77   public:
78     MemDepResult() : Value(0, Invalid) {}
79     
80     /// get methods: These are static ctor methods for creating various
81     /// MemDepResult kinds.
82     static MemDepResult getDef(Instruction *Inst) {
83       return MemDepResult(PairTy(Inst, Def));
84     }
85     static MemDepResult getClobber(Instruction *Inst) {
86       return MemDepResult(PairTy(Inst, Clobber));
87     }
88     static MemDepResult getNonLocal() {
89       return MemDepResult(PairTy(0, NonLocal));
90     }
91
92     /// isClobber - Return true if this MemDepResult represents a query that is
93     /// a instruction clobber dependency.
94     bool isClobber() const { return Value.getInt() == Clobber; }
95
96     /// isDef - Return true if this MemDepResult represents a query that is
97     /// a instruction definition dependency.
98     bool isDef() const { return Value.getInt() == Def; }
99     
100     /// isNonLocal - Return true if this MemDepResult represents a query that
101     /// is transparent to the start of the block, but where a non-local hasn't
102     /// been done.
103     bool isNonLocal() const { return Value.getInt() == NonLocal; }
104     
105     /// getInst() - If this is a normal dependency, return the instruction that
106     /// is depended on.  Otherwise, return null.
107     Instruction *getInst() const { return Value.getPointer(); }
108     
109     bool operator==(const MemDepResult &M) const { return Value == M.Value; }
110     bool operator!=(const MemDepResult &M) const { return Value != M.Value; }
111     bool operator<(const MemDepResult &M) const { return Value < M.Value; }
112     bool operator>(const MemDepResult &M) const { return Value > M.Value; }
113   private:
114     friend class MemoryDependenceAnalysis;
115     /// Dirty - Entries with this marker occur in a LocalDeps map or
116     /// NonLocalDeps map when the instruction they previously referenced was
117     /// removed from MemDep.  In either case, the entry may include an
118     /// instruction pointer.  If so, the pointer is an instruction in the
119     /// block where scanning can start from, saving some work.
120     ///
121     /// In a default-constructed MemDepResult object, the type will be Dirty
122     /// and the instruction pointer will be null.
123     ///
124          
125     /// isDirty - Return true if this is a MemDepResult in its dirty/invalid.
126     /// state.
127     bool isDirty() const { return Value.getInt() == Invalid; }
128     
129     static MemDepResult getDirty(Instruction *Inst) {
130       return MemDepResult(PairTy(Inst, Invalid));
131     }
132   };
133
134   /// MemoryDependenceAnalysis - This is an analysis that determines, for a
135   /// given memory operation, what preceding memory operations it depends on.
136   /// It builds on alias analysis information, and tries to provide a lazy,
137   /// caching interface to a common kind of alias information query.
138   ///
139   /// The dependency information returned is somewhat unusual, but is pragmatic.
140   /// If queried about a store or call that might modify memory, the analysis
141   /// will return the instruction[s] that may either load from that memory or
142   /// store to it.  If queried with a load or call that can never modify memory,
143   /// the analysis will return calls and stores that might modify the pointer,
144   /// but generally does not return loads unless a) they are volatile, or
145   /// b) they load from *must-aliased* pointers.  Returning a dependence on
146   /// must-alias'd pointers instead of all pointers interacts well with the
147   /// internal caching mechanism.
148   ///
149   class MemoryDependenceAnalysis : public FunctionPass {
150     // A map from instructions to their dependency.
151     typedef DenseMap<Instruction*, MemDepResult> LocalDepMapType;
152     LocalDepMapType LocalDeps;
153
154   public:
155     typedef std::pair<BasicBlock*, MemDepResult> NonLocalDepEntry;
156     typedef std::vector<NonLocalDepEntry> NonLocalDepInfo;
157   private:
158     /// ValueIsLoadPair - This is a pair<Value*, bool> where the bool is true if
159     /// the dependence is a read only dependence, false if read/write.
160     typedef PointerIntPair<Value*, 1, bool> ValueIsLoadPair;
161
162     /// BBSkipFirstBlockPair - This pair is used when caching information for a
163     /// block.  If the pointer is null, the cache value is not a full query that
164     /// starts at the specified block.  If non-null, the bool indicates whether
165     /// or not the contents of the block was skipped.
166     typedef PointerIntPair<BasicBlock*, 1, bool> BBSkipFirstBlockPair;
167
168     /// CachedNonLocalPointerInfo - This map stores the cached results of doing
169     /// a pointer lookup at the bottom of a block.  The key of this map is the
170     /// pointer+isload bit, the value is a list of <bb->result> mappings.
171     typedef DenseMap<ValueIsLoadPair, std::pair<BBSkipFirstBlockPair, 
172                   NonLocalDepInfo> > CachedNonLocalPointerInfo;
173     CachedNonLocalPointerInfo NonLocalPointerDeps;
174
175     // A map from instructions to their non-local pointer dependencies.
176     typedef DenseMap<Instruction*, 
177                      SmallPtrSet<ValueIsLoadPair, 4> > ReverseNonLocalPtrDepTy;
178     ReverseNonLocalPtrDepTy ReverseNonLocalPtrDeps;
179
180     
181     /// PerInstNLInfo - This is the instruction we keep for each cached access
182     /// that we have for an instruction.  The pointer is an owning pointer and
183     /// the bool indicates whether we have any dirty bits in the set.
184     typedef std::pair<NonLocalDepInfo, bool> PerInstNLInfo;
185     
186     // A map from instructions to their non-local dependencies.
187     typedef DenseMap<Instruction*, PerInstNLInfo> NonLocalDepMapType;
188       
189     NonLocalDepMapType NonLocalDeps;
190     
191     // A reverse mapping from dependencies to the dependees.  This is
192     // used when removing instructions to keep the cache coherent.
193     typedef DenseMap<Instruction*,
194                      SmallPtrSet<Instruction*, 4> > ReverseDepMapType;
195     ReverseDepMapType ReverseLocalDeps;
196     
197     // A reverse mapping form dependencies to the non-local dependees.
198     ReverseDepMapType ReverseNonLocalDeps;
199     
200     /// Current AA implementation, just a cache.
201     AliasAnalysis *AA;
202     TargetData *TD;
203     OwningPtr<PredIteratorCache> PredCache;
204   public:
205     MemoryDependenceAnalysis();
206     ~MemoryDependenceAnalysis();
207     static char ID;
208
209     /// Pass Implementation stuff.  This doesn't do any analysis eagerly.
210     bool runOnFunction(Function &);
211     
212     /// Clean up memory in between runs
213     void releaseMemory();
214     
215     /// getAnalysisUsage - Does not modify anything.  It uses Value Numbering
216     /// and Alias Analysis.
217     ///
218     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
219     
220     /// getDependency - Return the instruction on which a memory operation
221     /// depends.  See the class comment for more details.  It is illegal to call
222     /// this on non-memory instructions.
223     MemDepResult getDependency(Instruction *QueryInst);
224
225     /// getNonLocalCallDependency - Perform a full dependency query for the
226     /// specified call, returning the set of blocks that the value is
227     /// potentially live across.  The returned set of results will include a
228     /// "NonLocal" result for all blocks where the value is live across.
229     ///
230     /// This method assumes the instruction returns a "NonLocal" dependency
231     /// within its own block.
232     ///
233     /// This returns a reference to an internal data structure that may be
234     /// invalidated on the next non-local query or when an instruction is
235     /// removed.  Clients must copy this data if they want it around longer than
236     /// that.
237     const NonLocalDepInfo &getNonLocalCallDependency(CallSite QueryCS);
238     
239     
240     /// getNonLocalPointerDependency - Perform a full dependency query for an
241     /// access to the specified (non-volatile) memory location, returning the
242     /// set of instructions that either define or clobber the value.
243     ///
244     /// This method assumes the pointer has a "NonLocal" dependency within BB.
245     void getNonLocalPointerDependency(Value *Pointer, bool isLoad,
246                                       BasicBlock *BB,
247                                      SmallVectorImpl<NonLocalDepEntry> &Result);
248     
249     /// removeInstruction - Remove an instruction from the dependence analysis,
250     /// updating the dependence of instructions that previously depended on it.
251     void removeInstruction(Instruction *InstToRemove);
252     
253     /// invalidateCachedPointerInfo - This method is used to invalidate cached
254     /// information about the specified pointer, because it may be too
255     /// conservative in memdep.  This is an optional call that can be used when
256     /// the client detects an equivalence between the pointer and some other
257     /// value and replaces the other value with ptr. This can make Ptr available
258     /// in more places that cached info does not necessarily keep.
259     void invalidateCachedPointerInfo(Value *Ptr);
260     
261   private:
262     MemDepResult getPointerDependencyFrom(Value *Pointer, uint64_t MemSize,
263                                           bool isLoad, 
264                                           BasicBlock::iterator ScanIt,
265                                           BasicBlock *BB);
266     MemDepResult getCallSiteDependencyFrom(CallSite C, bool isReadOnlyCall,
267                                            BasicBlock::iterator ScanIt,
268                                            BasicBlock *BB);
269     bool getNonLocalPointerDepFromBB(const PHITransAddr &Pointer, uint64_t Size,
270                                      bool isLoad, BasicBlock *BB,
271                                      SmallVectorImpl<NonLocalDepEntry> &Result,
272                                      DenseMap<BasicBlock*, Value*> &Visited,
273                                      bool SkipFirstBlock = false);
274     MemDepResult GetNonLocalInfoForBlock(Value *Pointer, uint64_t PointeeSize,
275                                          bool isLoad, BasicBlock *BB,
276                                          NonLocalDepInfo *Cache,
277                                          unsigned NumSortedEntries);
278
279     void RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P);
280     
281     /// verifyRemoved - Verify that the specified instruction does not occur
282     /// in our internal data structures.
283     void verifyRemoved(Instruction *Inst) const;
284     
285   };
286
287 } // End llvm namespace
288
289 #endif