change NonLocalDepEntry from being a typedef for an std::pair to be its
[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   /// NonLocalDepEntry - This is an entry in the NonLocalDepInfo cache, and an
135   /// entry in the results set for a non-local query.  For each BasicBlock (the
136   /// BB entry) it keeps a MemDepResult.
137   class NonLocalDepEntry {
138     BasicBlock *BB;
139     MemDepResult Result;
140   public:
141     NonLocalDepEntry(BasicBlock *bb, MemDepResult result)
142       : BB(bb), Result(result) {}
143     
144     // BB is the sort key, it can't be changed.
145     BasicBlock *getBB() const { return BB; }
146     
147     const MemDepResult &getResult() const { return Result; }
148     void setResult(const MemDepResult &R) { Result = R; }
149     
150     bool operator<(const NonLocalDepEntry &RHS) const {
151       return BB < RHS.BB;
152     }
153   };
154   
155   /// MemoryDependenceAnalysis - This is an analysis that determines, for a
156   /// given memory operation, what preceding memory operations it depends on.
157   /// It builds on alias analysis information, and tries to provide a lazy,
158   /// caching interface to a common kind of alias information query.
159   ///
160   /// The dependency information returned is somewhat unusual, but is pragmatic.
161   /// If queried about a store or call that might modify memory, the analysis
162   /// will return the instruction[s] that may either load from that memory or
163   /// store to it.  If queried with a load or call that can never modify memory,
164   /// the analysis will return calls and stores that might modify the pointer,
165   /// but generally does not return loads unless a) they are volatile, or
166   /// b) they load from *must-aliased* pointers.  Returning a dependence on
167   /// must-alias'd pointers instead of all pointers interacts well with the
168   /// internal caching mechanism.
169   ///
170   class MemoryDependenceAnalysis : public FunctionPass {
171     // A map from instructions to their dependency.
172     typedef DenseMap<Instruction*, MemDepResult> LocalDepMapType;
173     LocalDepMapType LocalDeps;
174
175   public:
176     typedef std::vector<NonLocalDepEntry> NonLocalDepInfo;
177   private:
178     /// ValueIsLoadPair - This is a pair<Value*, bool> where the bool is true if
179     /// the dependence is a read only dependence, false if read/write.
180     typedef PointerIntPair<Value*, 1, bool> ValueIsLoadPair;
181
182     /// BBSkipFirstBlockPair - This pair is used when caching information for a
183     /// block.  If the pointer is null, the cache value is not a full query that
184     /// starts at the specified block.  If non-null, the bool indicates whether
185     /// or not the contents of the block was skipped.
186     typedef PointerIntPair<BasicBlock*, 1, bool> BBSkipFirstBlockPair;
187
188     /// CachedNonLocalPointerInfo - This map stores the cached results of doing
189     /// a pointer lookup at the bottom of a block.  The key of this map is the
190     /// pointer+isload bit, the value is a list of <bb->result> mappings.
191     typedef DenseMap<ValueIsLoadPair, std::pair<BBSkipFirstBlockPair, 
192                   NonLocalDepInfo> > CachedNonLocalPointerInfo;
193     CachedNonLocalPointerInfo NonLocalPointerDeps;
194
195     // A map from instructions to their non-local pointer dependencies.
196     typedef DenseMap<Instruction*, 
197                      SmallPtrSet<ValueIsLoadPair, 4> > ReverseNonLocalPtrDepTy;
198     ReverseNonLocalPtrDepTy ReverseNonLocalPtrDeps;
199
200     
201     /// PerInstNLInfo - This is the instruction we keep for each cached access
202     /// that we have for an instruction.  The pointer is an owning pointer and
203     /// the bool indicates whether we have any dirty bits in the set.
204     typedef std::pair<NonLocalDepInfo, bool> PerInstNLInfo;
205     
206     // A map from instructions to their non-local dependencies.
207     typedef DenseMap<Instruction*, PerInstNLInfo> NonLocalDepMapType;
208       
209     NonLocalDepMapType NonLocalDeps;
210     
211     // A reverse mapping from dependencies to the dependees.  This is
212     // used when removing instructions to keep the cache coherent.
213     typedef DenseMap<Instruction*,
214                      SmallPtrSet<Instruction*, 4> > ReverseDepMapType;
215     ReverseDepMapType ReverseLocalDeps;
216     
217     // A reverse mapping form dependencies to the non-local dependees.
218     ReverseDepMapType ReverseNonLocalDeps;
219     
220     /// Current AA implementation, just a cache.
221     AliasAnalysis *AA;
222     TargetData *TD;
223     OwningPtr<PredIteratorCache> PredCache;
224   public:
225     MemoryDependenceAnalysis();
226     ~MemoryDependenceAnalysis();
227     static char ID;
228
229     /// Pass Implementation stuff.  This doesn't do any analysis eagerly.
230     bool runOnFunction(Function &);
231     
232     /// Clean up memory in between runs
233     void releaseMemory();
234     
235     /// getAnalysisUsage - Does not modify anything.  It uses Value Numbering
236     /// and Alias Analysis.
237     ///
238     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
239     
240     /// getDependency - Return the instruction on which a memory operation
241     /// depends.  See the class comment for more details.  It is illegal to call
242     /// this on non-memory instructions.
243     MemDepResult getDependency(Instruction *QueryInst);
244
245     /// getNonLocalCallDependency - Perform a full dependency query for the
246     /// specified call, returning the set of blocks that the value is
247     /// potentially live across.  The returned set of results will include a
248     /// "NonLocal" result for all blocks where the value is live across.
249     ///
250     /// This method assumes the instruction returns a "NonLocal" dependency
251     /// within its own block.
252     ///
253     /// This returns a reference to an internal data structure that may be
254     /// invalidated on the next non-local query or when an instruction is
255     /// removed.  Clients must copy this data if they want it around longer than
256     /// that.
257     const NonLocalDepInfo &getNonLocalCallDependency(CallSite QueryCS);
258     
259     
260     /// getNonLocalPointerDependency - Perform a full dependency query for an
261     /// access to the specified (non-volatile) memory location, returning the
262     /// set of instructions that either define or clobber the value.
263     ///
264     /// This method assumes the pointer has a "NonLocal" dependency within BB.
265     void getNonLocalPointerDependency(Value *Pointer, bool isLoad,
266                                       BasicBlock *BB,
267                                      SmallVectorImpl<NonLocalDepEntry> &Result);
268     
269     /// removeInstruction - Remove an instruction from the dependence analysis,
270     /// updating the dependence of instructions that previously depended on it.
271     void removeInstruction(Instruction *InstToRemove);
272     
273     /// invalidateCachedPointerInfo - This method is used to invalidate cached
274     /// information about the specified pointer, because it may be too
275     /// conservative in memdep.  This is an optional call that can be used when
276     /// the client detects an equivalence between the pointer and some other
277     /// value and replaces the other value with ptr. This can make Ptr available
278     /// in more places that cached info does not necessarily keep.
279     void invalidateCachedPointerInfo(Value *Ptr);
280     
281   private:
282     MemDepResult getPointerDependencyFrom(Value *Pointer, uint64_t MemSize,
283                                           bool isLoad, 
284                                           BasicBlock::iterator ScanIt,
285                                           BasicBlock *BB);
286     MemDepResult getCallSiteDependencyFrom(CallSite C, bool isReadOnlyCall,
287                                            BasicBlock::iterator ScanIt,
288                                            BasicBlock *BB);
289     bool getNonLocalPointerDepFromBB(const PHITransAddr &Pointer, uint64_t Size,
290                                      bool isLoad, BasicBlock *BB,
291                                      SmallVectorImpl<NonLocalDepEntry> &Result,
292                                      DenseMap<BasicBlock*, Value*> &Visited,
293                                      bool SkipFirstBlock = false);
294     MemDepResult GetNonLocalInfoForBlock(Value *Pointer, uint64_t PointeeSize,
295                                          bool isLoad, BasicBlock *BB,
296                                          NonLocalDepInfo *Cache,
297                                          unsigned NumSortedEntries);
298
299     void RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P);
300     
301     /// verifyRemoved - Verify that the specified instruction does not occur
302     /// in our internal data structures.
303     void verifyRemoved(Instruction *Inst) const;
304     
305   };
306
307 } // End llvm namespace
308
309 #endif