Home | History | Annotate | Download | only in Analysis
      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 due to IR changes.
     37 /// While it does retain some storage, that is used as an optimization and not
     38 /// to preserve information from query to query. However it does retain handles
     39 /// to various other analyses and must be recomputed when those analyses are.
     40 class BasicAAResult : public AAResultBase<BasicAAResult> {
     41   friend AAResultBase<BasicAAResult>;
     42 
     43   const DataLayout &DL;
     44   const TargetLibraryInfo &TLI;
     45   AssumptionCache &AC;
     46   DominatorTree *DT;
     47   LoopInfo *LI;
     48 
     49 public:
     50   BasicAAResult(const DataLayout &DL, const TargetLibraryInfo &TLI,
     51                 AssumptionCache &AC, DominatorTree *DT = nullptr,
     52                 LoopInfo *LI = nullptr)
     53       : AAResultBase(), DL(DL), TLI(TLI), AC(AC), DT(DT), LI(LI) {}
     54 
     55   BasicAAResult(const BasicAAResult &Arg)
     56       : AAResultBase(Arg), DL(Arg.DL), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
     57         LI(Arg.LI) {}
     58   BasicAAResult(BasicAAResult &&Arg)
     59       : AAResultBase(std::move(Arg)), DL(Arg.DL), TLI(Arg.TLI), AC(Arg.AC),
     60         DT(Arg.DT), LI(Arg.LI) {}
     61 
     62   /// Handle invalidation events in the new pass manager.
     63   bool invalidate(Function &F, const PreservedAnalyses &PA,
     64                   FunctionAnalysisManager::Invalidator &Inv);
     65 
     66   AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB);
     67 
     68   ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc);
     69 
     70   ModRefInfo getModRefInfo(ImmutableCallSite CS1, ImmutableCallSite CS2);
     71 
     72   /// Chases pointers until we find a (constant global) or not.
     73   bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal);
     74 
     75   /// Get the location associated with a pointer argument of a callsite.
     76   ModRefInfo getArgModRefInfo(ImmutableCallSite CS, unsigned ArgIdx);
     77 
     78   /// Returns the behavior when calling the given call site.
     79   FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS);
     80 
     81   /// Returns the behavior when calling the given function. For use when the
     82   /// call site is not known.
     83   FunctionModRefBehavior getModRefBehavior(const Function *F);
     84 
     85 private:
     86   // A linear transformation of a Value; this class represents ZExt(SExt(V,
     87   // SExtBits), ZExtBits) * Scale + Offset.
     88   struct VariableGEPIndex {
     89 
     90     // An opaque Value - we can't decompose this further.
     91     const Value *V;
     92 
     93     // We need to track what extensions we've done as we consider the same Value
     94     // with different extensions as different variables in a GEP's linear
     95     // expression;
     96     // e.g.: if V == -1, then sext(x) != zext(x).
     97     unsigned ZExtBits;
     98     unsigned SExtBits;
     99 
    100     int64_t Scale;
    101 
    102     bool operator==(const VariableGEPIndex &Other) const {
    103       return V == Other.V && ZExtBits == Other.ZExtBits &&
    104              SExtBits == Other.SExtBits && Scale == Other.Scale;
    105     }
    106 
    107     bool operator!=(const VariableGEPIndex &Other) const {
    108       return !operator==(Other);
    109     }
    110   };
    111 
    112   // Represents the internal structure of a GEP, decomposed into a base pointer,
    113   // constant offsets, and variable scaled indices.
    114   struct DecomposedGEP {
    115     // Base pointer of the GEP
    116     const Value *Base;
    117     // Total constant offset w.r.t the base from indexing into structs
    118     int64_t StructOffset;
    119     // Total constant offset w.r.t the base from indexing through
    120     // pointers/arrays/vectors
    121     int64_t OtherOffset;
    122     // Scaled variable (non-constant) indices.
    123     SmallVector<VariableGEPIndex, 4> VarIndices;
    124   };
    125 
    126   /// Track alias queries to guard against recursion.
    127   typedef std::pair<MemoryLocation, MemoryLocation> LocPair;
    128   typedef SmallDenseMap<LocPair, AliasResult, 8> AliasCacheTy;
    129   AliasCacheTy AliasCache;
    130 
    131   /// Tracks phi nodes we have visited.
    132   ///
    133   /// When interpret "Value" pointer equality as value equality we need to make
    134   /// sure that the "Value" is not part of a cycle. Otherwise, two uses could
    135   /// come from different "iterations" of a cycle and see different values for
    136   /// the same "Value" pointer.
    137   ///
    138   /// The following example shows the problem:
    139   ///   %p = phi(%alloca1, %addr2)
    140   ///   %l = load %ptr
    141   ///   %addr1 = gep, %alloca2, 0, %l
    142   ///   %addr2 = gep  %alloca2, 0, (%l + 1)
    143   ///      alias(%p, %addr1) -> MayAlias !
    144   ///   store %l, ...
    145   SmallPtrSet<const BasicBlock *, 8> VisitedPhiBBs;
    146 
    147   /// Tracks instructions visited by pointsToConstantMemory.
    148   SmallPtrSet<const Value *, 16> Visited;
    149 
    150   static const Value *
    151   GetLinearExpression(const Value *V, APInt &Scale, APInt &Offset,
    152                       unsigned &ZExtBits, unsigned &SExtBits,
    153                       const DataLayout &DL, unsigned Depth, AssumptionCache *AC,
    154                       DominatorTree *DT, bool &NSW, bool &NUW);
    155 
    156   static bool DecomposeGEPExpression(const Value *V, DecomposedGEP &Decomposed,
    157       const DataLayout &DL, AssumptionCache *AC, DominatorTree *DT);
    158 
    159   static bool isGEPBaseAtNegativeOffset(const GEPOperator *GEPOp,
    160       const DecomposedGEP &DecompGEP, const DecomposedGEP &DecompObject,
    161       uint64_t ObjectAccessSize);
    162 
    163   /// \brief A Heuristic for aliasGEP that searches for a constant offset
    164   /// between the variables.
    165   ///
    166   /// GetLinearExpression has some limitations, as generally zext(%x + 1)
    167   /// != zext(%x) + zext(1) if the arithmetic overflows. GetLinearExpression
    168   /// will therefore conservatively refuse to decompose these expressions.
    169   /// However, we know that, for all %x, zext(%x) != zext(%x + 1), even if
    170   /// the addition overflows.
    171   bool
    172   constantOffsetHeuristic(const SmallVectorImpl<VariableGEPIndex> &VarIndices,
    173                           uint64_t V1Size, uint64_t V2Size, int64_t BaseOffset,
    174                           AssumptionCache *AC, DominatorTree *DT);
    175 
    176   bool isValueEqualInPotentialCycles(const Value *V1, const Value *V2);
    177 
    178   void GetIndexDifference(SmallVectorImpl<VariableGEPIndex> &Dest,
    179                           const SmallVectorImpl<VariableGEPIndex> &Src);
    180 
    181   AliasResult aliasGEP(const GEPOperator *V1, uint64_t V1Size,
    182                        const AAMDNodes &V1AAInfo, const Value *V2,
    183                        uint64_t V2Size, const AAMDNodes &V2AAInfo,
    184                        const Value *UnderlyingV1, const Value *UnderlyingV2);
    185 
    186   AliasResult aliasPHI(const PHINode *PN, uint64_t PNSize,
    187                        const AAMDNodes &PNAAInfo, const Value *V2,
    188                        uint64_t V2Size, const AAMDNodes &V2AAInfo,
    189                        const Value *UnderV2);
    190 
    191   AliasResult aliasSelect(const SelectInst *SI, uint64_t SISize,
    192                           const AAMDNodes &SIAAInfo, const Value *V2,
    193                           uint64_t V2Size, const AAMDNodes &V2AAInfo,
    194                           const Value *UnderV2);
    195 
    196   AliasResult aliasCheck(const Value *V1, uint64_t V1Size, AAMDNodes V1AATag,
    197                          const Value *V2, uint64_t V2Size, AAMDNodes V2AATag,
    198                          const Value *O1 = nullptr, const Value *O2 = nullptr);
    199 };
    200 
    201 /// Analysis pass providing a never-invalidated alias analysis result.
    202 class BasicAA : public AnalysisInfoMixin<BasicAA> {
    203   friend AnalysisInfoMixin<BasicAA>;
    204   static AnalysisKey Key;
    205 
    206 public:
    207   typedef BasicAAResult Result;
    208 
    209   BasicAAResult run(Function &F, FunctionAnalysisManager &AM);
    210 };
    211 
    212 /// Legacy wrapper pass to provide the BasicAAResult object.
    213 class BasicAAWrapperPass : public FunctionPass {
    214   std::unique_ptr<BasicAAResult> Result;
    215 
    216   virtual void anchor();
    217 
    218 public:
    219   static char ID;
    220 
    221   BasicAAWrapperPass();
    222 
    223   BasicAAResult &getResult() { return *Result; }
    224   const BasicAAResult &getResult() const { return *Result; }
    225 
    226   bool runOnFunction(Function &F) override;
    227   void getAnalysisUsage(AnalysisUsage &AU) const override;
    228 };
    229 
    230 FunctionPass *createBasicAAWrapperPass();
    231 
    232 /// A helper for the legacy pass manager to create a \c BasicAAResult object
    233 /// populated to the best of our ability for a particular function when inside
    234 /// of a \c ModulePass or a \c CallGraphSCCPass.
    235 BasicAAResult createLegacyPMBasicAAResult(Pass &P, Function &F);
    236 
    237 /// This class is a functor to be used in legacy module or SCC passes for
    238 /// computing AA results for a function. We store the results in fields so that
    239 /// they live long enough to be queried, but we re-use them each time.
    240 class LegacyAARGetter {
    241   Pass &P;
    242   Optional<BasicAAResult> BAR;
    243   Optional<AAResults> AAR;
    244 
    245 public:
    246   LegacyAARGetter(Pass &P) : P(P) {}
    247   AAResults &operator()(Function &F) {
    248     BAR.emplace(createLegacyPMBasicAAResult(P, F));
    249     AAR.emplace(createLegacyPMAAResults(P, F, *BAR));
    250     return *AAR;
    251   }
    252 };
    253 
    254 }
    255 
    256 #endif
    257