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