Reformat partially.
[oota-llvm.git] / include / llvm / Analysis / BasicAliasAnalysis.h
1 //===- BasicAliasAnalysis.h - Stateless, local Alias Analysis ---*- 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 /// \file
10 /// This is the interface for LLVM's primary stateless and local alias analysis.
11 ///
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_ANALYSIS_BASICALIASANALYSIS_H
15 #define LLVM_ANALYSIS_BASICALIASANALYSIS_H
16
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Analysis/AssumptionCache.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/GetElementPtrTypeIterator.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/PassManager.h"
27 #include "llvm/Support/ErrorHandling.h"
28
29 namespace llvm {
30 class AssumptionCache;
31 class DominatorTree;
32 class LoopInfo;
33
34 /// This is the AA result object for the basic, local, and stateless alias
35 /// analysis. It implements the AA query interface in an entirely stateless
36 /// manner. As one consequence, it is never invalidated. While it does retain
37 /// some storage, that is used as an optimization and not to preserve
38 /// information from query to query.
39 class BasicAAResult : public AAResultBase<BasicAAResult> {
40   friend AAResultBase<BasicAAResult>;
41
42   const DataLayout &DL;
43   AssumptionCache &AC;
44   DominatorTree *DT;
45   LoopInfo *LI;
46
47 #ifndef NDEBUG
48   static const Function *getParent(const Value *V) {
49     if (const Instruction *inst = dyn_cast<Instruction>(V))
50       return inst->getParent()->getParent();
51
52     if (const Argument *arg = dyn_cast<Argument>(V))
53       return arg->getParent();
54
55     return nullptr;
56   }
57
58   static bool notDifferentParent(const Value *O1, const Value *O2) {
59
60     const Function *F1 = getParent(O1);
61     const Function *F2 = getParent(O2);
62
63     return !F1 || !F2 || F1 == F2;
64   }
65 #endif
66
67 public:
68   BasicAAResult(const DataLayout &DL, const TargetLibraryInfo &TLI,
69                 AssumptionCache &AC, DominatorTree *DT = nullptr,
70                 LoopInfo *LI = nullptr)
71       : AAResultBase(TLI), DL(DL), AC(AC), DT(DT), LI(LI) {}
72
73   BasicAAResult(const BasicAAResult &Arg)
74       : AAResultBase(Arg), DL(Arg.DL), AC(Arg.AC), DT(Arg.DT), LI(Arg.LI) {}
75   BasicAAResult(BasicAAResult &&Arg)
76       : AAResultBase(std::move(Arg)), DL(Arg.DL), AC(Arg.AC), DT(Arg.DT),
77         LI(Arg.LI) {}
78
79   /// Handle invalidation events from the new pass manager.
80   ///
81   /// By definition, this result is stateless and so remains valid.
82   bool invalidate(Function &, const PreservedAnalyses &) { return false; }
83
84   AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
85     assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
86            "BasicAliasAnalysis doesn't support interprocedural queries.");
87
88     // If we have a directly cached entry for these locations, we have recursed
89     // through this once, so just return the cached results. Notably, when this
90     // happens, we don't clear the cache.
91     auto CacheIt = AliasCache.find(LocPair(LocA, LocB));
92     if (CacheIt != AliasCache.end())
93       return CacheIt->second;
94
95     AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.AATags, LocB.Ptr,
96                                    LocB.Size, LocB.AATags);
97     // AliasCache rarely has more than 1 or 2 elements, always use
98     // shrink_and_clear so it quickly returns to the inline capacity of the
99     // SmallDenseMap if it ever grows larger.
100     // FIXME: This should really be shrink_to_inline_capacity_and_clear().
101     AliasCache.shrink_and_clear();
102     VisitedPhiBBs.clear();
103     return Alias;
104   }
105
106   ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc);
107
108   ModRefInfo getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2);
109
110   /// Chases pointers until we find a (constant global) or not.
111   bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal);
112
113   /// Get the location associated with a pointer argument of a callsite.
114   ModRefInfo getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx);
115
116   /// Returns the behavior when calling the given call site.
117   FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS);
118
119   /// Returns the behavior when calling the given function. For use when the
120   /// call site is not known.
121   FunctionModRefBehavior getModRefBehavior(const Function *F);
122
123 private:
124   // A linear transformation of a Value; this class represents ZExt(SExt(V,
125   // SExtBits), ZExtBits) * Scale + Offset.
126   struct VariableGEPIndex {
127
128     // An opaque Value - we can't decompose this further.
129     const Value *V;
130
131     // We need to track what extensions we've done as we consider the same Value
132     // with different extensions as different variables in a GEP's linear
133     // expression;
134     // e.g.: if V == -1, then sext(x) != zext(x).
135     unsigned ZExtBits;
136     unsigned SExtBits;
137
138     int64_t Scale;
139
140     bool operator==(const VariableGEPIndex &Other) const {
141       return V == Other.V && ZExtBits == Other.ZExtBits &&
142              SExtBits == Other.SExtBits && Scale == Other.Scale;
143     }
144
145     bool operator!=(const VariableGEPIndex &Other) const {
146       return !operator==(Other);
147     }
148   };
149
150   /// Track alias queries to guard against recursion.
151   typedef std::pair<MemoryLocation, MemoryLocation> LocPair;
152   typedef SmallDenseMap<LocPair, AliasResult, 8> AliasCacheTy;
153   AliasCacheTy AliasCache;
154
155   /// Tracks phi nodes we have visited.
156   ///
157   /// When interpret "Value" pointer equality as value equality we need to make
158   /// sure that the "Value" is not part of a cycle. Otherwise, two uses could
159   /// come from different "iterations" of a cycle and see different values for
160   /// the same "Value" pointer.
161   ///
162   /// The following example shows the problem:
163   ///   %p = phi(%alloca1, %addr2)
164   ///   %l = load %ptr
165   ///   %addr1 = gep, %alloca2, 0, %l
166   ///   %addr2 = gep  %alloca2, 0, (%l + 1)
167   ///      alias(%p, %addr1) -> MayAlias !
168   ///   store %l, ...
169   SmallPtrSet<const BasicBlock *, 8> VisitedPhiBBs;
170
171   /// Tracks instructions visited by pointsToConstantMemory.
172   SmallPtrSet<const Value *, 16> Visited;
173
174   static const Value *
175   GetLinearExpression(const Value *V, APInt &Scale, APInt &Offset,
176                       unsigned &ZExtBits, unsigned &SExtBits,
177                       const DataLayout &DL, unsigned Depth, AssumptionCache *AC,
178                       DominatorTree *DT, bool &NSW, bool &NUW);
179
180   static const Value *
181   DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
182                          SmallVectorImpl<VariableGEPIndex> &VarIndices,
183                          bool &MaxLookupReached, const DataLayout &DL,
184                          AssumptionCache *AC, DominatorTree *DT);
185   /// \brief A Heuristic for aliasGEP that searches for a constant offset
186   /// between the variables.
187   ///
188   /// GetLinearExpression has some limitations, as generally zext(%x + 1)
189   /// != zext(%x) + zext(1) if the arithmetic overflows. GetLinearExpression
190   /// will therefore conservatively refuse to decompose these expressions.
191   /// However, we know that, for all %x, zext(%x) != zext(%x + 1), even if
192   /// the addition overflows.
193   bool
194   constantOffsetHeuristic(const SmallVectorImpl<VariableGEPIndex> &VarIndices,
195                           uint64_t V1Size, uint64_t V2Size, int64_t BaseOffset,
196                           AssumptionCache *AC, DominatorTree *DT);
197
198   bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
199
200   void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
201                           const SmallVectorImpl<VariableGEPIndex> &Src);
202
203   AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
204                        const AAMDNodes &V1AAInfo, const Value *V2,
205                        uint64_t V2Size, const AAMDNodes &V2AAInfo,
206                        const Value *UnderlyingV1, const Value *UnderlyingV2);
207
208   AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
209                        const AAMDNodes &PNAAInfo, const Value *V2,
210                        uint64_t V2Size, const AAMDNodes &V2AAInfo);
211
212   AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
213                           const AAMDNodes &SIAAInfo, const Value *V2,
214                           uint64_t V2Size, const AAMDNodes &V2AAInfo);
215
216   AliasResult aliasCheck(const Value *V1, uint64_t V1Size, AAMDNodes V1AATag,
217                          const Value *V2, uint64_t V2Size, AAMDNodes V2AATag);
218 };
219
220 /// Analysis pass providing a never-invalidated alias analysis result.
221 class BasicAA {
222 public:
223   typedef BasicAAResult Result;
224
225   /// \brief Opaque, unique identifier for this analysis pass.
226   static void *ID() { return (void *)&PassID; }
227
228   BasicAAResult run(Function &F, AnalysisManager<Function> *AM);
229
230   /// \brief Provide access to a name for this pass for debugging purposes.
231   static StringRef name() { return "BasicAliasAnalysis"; }
232
233 private:
234   static char PassID;
235 };
236
237 /// Legacy wrapper pass to provide the BasicAAResult object.
238 class BasicAAWrapperPass : public FunctionPass {
239   std::unique_ptr<BasicAAResult> Result;
240
241   virtual void anchor();
242
243 public:
244   static char ID;
245
246   BasicAAWrapperPass() : FunctionPass(ID) {}
247
248   BasicAAResult &getResult() { return *Result; }
249   const BasicAAResult &getResult() const { return *Result; }
250
251   bool runOnFunction(Function &F) override;
252   void getAnalysisUsage(AnalysisUsage &AU) const override;
253 };
254
255 FunctionPass *createBasicAAWrapperPass();
256
257 /// A helper for the legacy pass manager to create a \c BasicAAResult object
258 /// populated to the best of our ability for a particular function when inside
259 /// of a \c ModulePass or a \c CallGraphSCCPass.
260 BasicAAResult createLegacyPMBasicAAResult(Pass &P, Function &F);
261 }
262
263 #endif