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