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