Remove static global GCNames from Function.cpp and move it to the Context
[oota-llvm.git] / include / llvm / Analysis / BasicAliasAnalysis.h
index b394bc33f6ee25db1318e5b57824c0a9ed767ed3..181a9327024c2b699fbbfd39ba14eef2ab11225a 100644 (file)
 #include "llvm/IR/Instruction.h"
 #include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/Module.h"
-#include "llvm/Pass.h"
+#include "llvm/IR/PassManager.h"
 #include "llvm/Support/ErrorHandling.h"
 
 namespace llvm {
+class AssumptionCache;
+class DominatorTree;
+class LoopInfo;
+
+/// This is the AA result object for the basic, local, and stateless alias
+/// analysis. It implements the AA query interface in an entirely stateless
+/// manner. As one consequence, it is never invalidated. While it does retain
+/// some storage, that is used as an optimization and not to preserve
+/// information from query to query.
+class BasicAAResult : public AAResultBase<BasicAAResult> {
+  friend AAResultBase<BasicAAResult>;
+
+  const DataLayout &DL;
+  AssumptionCache &AC;
+  DominatorTree *DT;
+  LoopInfo *LI;
+
+public:
+  BasicAAResult(const DataLayout &DL, const TargetLibraryInfo &TLI,
+                AssumptionCache &AC, DominatorTree *DT = nullptr,
+                LoopInfo *LI = nullptr)
+      : AAResultBase(TLI), DL(DL), AC(AC), DT(DT), LI(LI) {}
+
+  BasicAAResult(const BasicAAResult &Arg)
+      : AAResultBase(Arg), DL(Arg.DL), AC(Arg.AC), DT(Arg.DT), LI(Arg.LI) {}
+  BasicAAResult(BasicAAResult &&Arg)
+      : AAResultBase(std::move(Arg)), DL(Arg.DL), AC(Arg.AC), DT(Arg.DT),
+        LI(Arg.LI) {}
+
+  /// Handle invalidation events from the new pass manager.
+  ///
+  /// By definition, this result is stateless and so remains valid.
+  bool invalidate(Function &, const PreservedAnalyses &) { return false; }
 
-/// BasicAliasAnalysis - This is the primary alias analysis implementation.
-struct BasicAliasAnalysis : public ImmutablePass, public AliasAnalysis {
-  static char ID; // Class identification, replacement for typeinfo
-
-#ifndef NDEBUG
-  static const Function *getParent(const Value *V) {
-    if (const Instruction *inst = dyn_cast<Instruction>(V))
-      return inst->getParent()->getParent();
-
-    if (const Argument *arg = dyn_cast<Argument>(V))
-      return arg->getParent();
+  AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB);
 
-    return nullptr;
-  }
+  ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc);
 
-  static bool notDifferentParent(const Value *O1, const Value *O2) {
+  ModRefInfo getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2);
 
-    const Function *F1 = getParent(O1);
-    const Function *F2 = getParent(O2);
+  /// Chases pointers until we find a (constant global) or not.
+  bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal);
 
-    return !F1 || !F2 || F1 == F2;
-  }
-#endif
+  /// Get the location associated with a pointer argument of a callsite.
+  ModRefInfo getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx);
 
-  BasicAliasAnalysis() : ImmutablePass(ID) {
-    initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
-  }
-
-  bool doInitialization(Module &M) override;
-
-  void getAnalysisUsage(AnalysisUsage &AU) const override {
-    AU.addRequired<AliasAnalysis>();
-    AU.addRequired<AssumptionCacheTracker>();
-    AU.addRequired<TargetLibraryInfoWrapperPass>();
-  }
-
-  AliasResult alias(const MemoryLocation &LocA,
-                    const MemoryLocation &LocB) override {
-    assert(AliasCache.empty() && "AliasCache must be cleared after use!");
-    assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&
-           "BasicAliasAnalysis doesn't support interprocedural queries.");
-    AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.AATags, LocB.Ptr,
-                                   LocB.Size, LocB.AATags);
-    // AliasCache rarely has more than 1 or 2 elements, always use
-    // shrink_and_clear so it quickly returns to the inline capacity of the
-    // SmallDenseMap if it ever grows larger.
-    // FIXME: This should really be shrink_to_inline_capacity_and_clear().
-    AliasCache.shrink_and_clear();
-    VisitedPhiBBs.clear();
-    return Alias;
-  }
-
-  ModRefInfo getModRefInfo(ImmutableCallSite CS,
-                           const MemoryLocation &Loc) override;
-
-  ModRefInfo getModRefInfo(ImmutableCallSite CS1,
-                           ImmutableCallSite CS2) override;
-
-  /// pointsToConstantMemory - Chase pointers until we find a (constant
-  /// global) or not.
-  bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal) override;
+  /// Returns the behavior when calling the given call site.
+  FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS);
 
-  /// Get the location associated with a pointer argument of a callsite.
-  ModRefInfo getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx) override;
-
-  /// getModRefBehavior - Return the behavior when calling the given
-  /// call site.
-  FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS) override;
-
-  /// getModRefBehavior - Return the behavior when calling the given function.
-  /// For use when the call site is not known.
-  FunctionModRefBehavior getModRefBehavior(const Function *F) override;
-
-  /// getAdjustedAnalysisPointer - This method is used when a pass implements
-  /// an analysis interface through multiple inheritance.  If needed, it
-  /// should override this to adjust the this pointer as needed for the
-  /// specified pass info.
-  void *getAdjustedAnalysisPointer(const void *ID) override {
-    if (ID == &AliasAnalysis::ID)
-      return (AliasAnalysis *)this;
-    return this;
-  }
+  /// Returns the behavior when calling the given function. For use when the
+  /// call site is not known.
+  FunctionModRefBehavior getModRefBehavior(const Function *F);
 
 private:
-  enum ExtensionKind { EK_NotExtended, EK_SignExt, EK_ZeroExt };
-
+  // A linear transformation of a Value; this class represents ZExt(SExt(V,
+  // SExtBits), ZExtBits) * Scale + Offset.
   struct VariableGEPIndex {
+
+    // An opaque Value - we can't decompose this further.
     const Value *V;
-    ExtensionKind Extension;
+
+    // We need to track what extensions we've done as we consider the same Value
+    // with different extensions as different variables in a GEP's linear
+    // expression;
+    // e.g.: if V == -1, then sext(x) != zext(x).
+    unsigned ZExtBits;
+    unsigned SExtBits;
+
     int64_t Scale;
 
     bool operator==(const VariableGEPIndex &Other) const {
-      return V == Other.V && Extension == Other.Extension &&
-             Scale == Other.Scale;
+      return V == Other.V && ZExtBits == Other.ZExtBits &&
+             SExtBits == Other.SExtBits && Scale == Other.Scale;
     }
 
     bool operator!=(const VariableGEPIndex &Other) const {
@@ -129,16 +107,18 @@ private:
     }
   };
 
-  // AliasCache - Track alias queries to guard against recursion.
+  /// Track alias queries to guard against recursion.
   typedef std::pair<MemoryLocation, MemoryLocation> LocPair;
   typedef SmallDenseMap<LocPair, AliasResult, 8> AliasCacheTy;
   AliasCacheTy AliasCache;
 
-  /// \brief Track phi nodes we have visited. When interpret "Value" pointer
-  /// equality as value equality we need to make sure that the "Value" is not
-  /// part of a cycle. Otherwise, two uses could come from different
-  /// "iterations" of a cycle and see different values for the same "Value"
-  /// pointer.
+  /// Tracks phi nodes we have visited.
+  ///
+  /// When interpret "Value" pointer equality as value equality we need to make
+  /// sure that the "Value" is not part of a cycle. Otherwise, two uses could
+  /// come from different "iterations" of a cycle and see different values for
+  /// the same "Value" pointer.
+  ///
   /// The following example shows the problem:
   ///   %p = phi(%alloca1, %addr2)
   ///   %l = load %ptr
@@ -148,50 +128,47 @@ private:
   ///   store %l, ...
   SmallPtrSet<const BasicBlock *, 8> VisitedPhiBBs;
 
-  // Visited - Track instructions visited by pointsToConstantMemory.
+  /// Tracks instructions visited by pointsToConstantMemory.
   SmallPtrSet<const Value *, 16> Visited;
 
-  static Value *GetLinearExpression(Value *V, APInt &Scale, APInt &Offset,
-                                    ExtensionKind &Extension,
-                                    const DataLayout &DL, unsigned Depth,
-                                    AssumptionCache *AC, DominatorTree *DT);
+  static const Value *
+  GetLinearExpression(const Value *V, APInt &Scale, APInt &Offset,
+                      unsigned &ZExtBits, unsigned &SExtBits,
+                      const DataLayout &DL, unsigned Depth, AssumptionCache *AC,
+                      DominatorTree *DT, bool &NSW, bool &NUW);
 
   static const Value *
   DecomposeGEPExpression(const Value *V, int64_t &BaseOffs,
                          SmallVectorImpl<VariableGEPIndex> &VarIndices,
                          bool &MaxLookupReached, const DataLayout &DL,
                          AssumptionCache *AC, DominatorTree *DT);
-
-  /// \brief Check whether two Values can be considered equivalent.
+  /// \brief A Heuristic for aliasGEP that searches for a constant offset
+  /// between the variables.
   ///
-  /// In addition to pointer equivalence of \p V1 and \p V2 this checks
-  /// whether they can not be part of a cycle in the value graph by looking at
-  /// all visited phi nodes an making sure that the phis cannot reach the
-  /// value. We have to do this because we are looking through phi nodes (That
-  /// is we say noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
+  /// GetLinearExpression has some limitations, as generally zext(%x + 1)
+  /// != zext(%x) + zext(1) if the arithmetic overflows. GetLinearExpression
+  /// will therefore conservatively refuse to decompose these expressions.
+  /// However, we know that, for all %x, zext(%x) != zext(%x + 1), even if
+  /// the addition overflows.
+  bool
+  constantOffsetHeuristic(const SmallVectorImpl<VariableGEPIndex> &VarIndices,
+                          uint64_t V1Size, uint64_t V2Size, int64_t BaseOffset,
+                          AssumptionCache *AC, DominatorTree *DT);
+
   bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
 
-  /// \brief Dest and Src are the variable indices from two decomposed
-  /// GetElementPtr instructions GEP1 and GEP2 which have common base
-  /// pointers.  Subtract the GEP2 indices from GEP1 to find the symbolic
-  /// difference between the two pointers.
   void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
                           const SmallVectorImpl<VariableGEPIndex> &Src);
 
-  // aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP
-  // instruction against another.
   AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
                        const AAMDNodes &V1AAInfo, const Value *V2,
                        uint64_t V2Size, const AAMDNodes &V2AAInfo,
                        const Value *UnderlyingV1, const Value *UnderlyingV2);
 
-  // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI
-  // instruction against another.
   AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
                        const AAMDNodes &PNAAInfo, const Value *V2,
                        uint64_t V2Size, const AAMDNodes &V2AAInfo);
 
-  /// aliasSelect - Disambiguate a Select instruction against another value.
   AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
                           const AAMDNodes &SIAAInfo, const Value *V2,
                           uint64_t V2Size, const AAMDNodes &V2AAInfo);
@@ -200,13 +177,47 @@ private:
                          const Value *V2, uint64_t V2Size, AAMDNodes V2AATag);
 };
 
-//===--------------------------------------------------------------------===//
-//
-// createBasicAliasAnalysisPass - This pass implements the stateless alias
-// analysis.
-//
-ImmutablePass *createBasicAliasAnalysisPass();
+/// Analysis pass providing a never-invalidated alias analysis result.
+class BasicAA {
+public:
+  typedef BasicAAResult Result;
+
+  /// \brief Opaque, unique identifier for this analysis pass.
+  static void *ID() { return (void *)&PassID; }
+
+  BasicAAResult run(Function &F, AnalysisManager<Function> *AM);
+
+  /// \brief Provide access to a name for this pass for debugging purposes.
+  static StringRef name() { return "BasicAliasAnalysis"; }
+
+private:
+  static char PassID;
+};
+
+/// Legacy wrapper pass to provide the BasicAAResult object.
+class BasicAAWrapperPass : public FunctionPass {
+  std::unique_ptr<BasicAAResult> Result;
+
+  virtual void anchor();
+
+public:
+  static char ID;
+
+  BasicAAWrapperPass();
+
+  BasicAAResult &getResult() { return *Result; }
+  const BasicAAResult &getResult() const { return *Result; }
+
+  bool runOnFunction(Function &F) override;
+  void getAnalysisUsage(AnalysisUsage &AU) const override;
+};
+
+FunctionPass *createBasicAAWrapperPass();
 
+/// A helper for the legacy pass manager to create a \c BasicAAResult object
+/// populated to the best of our ability for a particular function when inside
+/// of a \c ModulePass or a \c CallGraphSCCPass.
+BasicAAResult createLegacyPMBasicAAResult(Pass &P, Function &F);
 }
 
 #endif