LLVM API Documentation

CFLAliasAnalysis.cpp
Go to the documentation of this file.
00001 //===- CFLAliasAnalysis.cpp - CFL-Based Alias Analysis Implementation ------==//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements a CFL-based context-insensitive alias analysis
00011 // algorithm. It does not depend on types. The algorithm is a mixture of the one
00012 // described in "Demand-driven alias analysis for C" by Xin Zheng and Radu
00013 // Rugina, and "Fast algorithms for Dyck-CFL-reachability with applications to
00014 // Alias Analysis" by Zhang Q, Lyu M R, Yuan H, and Su Z. -- to summarize the
00015 // papers, we build a graph of the uses of a variable, where each node is a
00016 // memory location, and each edge is an action that happened on that memory
00017 // location.  The "actions" can be one of Dereference, Reference, Assign, or
00018 // Assign.
00019 //
00020 // Two variables are considered as aliasing iff you can reach one value's node
00021 // from the other value's node and the language formed by concatenating all of
00022 // the edge labels (actions) conforms to a context-free grammar.
00023 //
00024 // Because this algorithm requires a graph search on each query, we execute the
00025 // algorithm outlined in "Fast algorithms..." (mentioned above)
00026 // in order to transform the graph into sets of variables that may alias in
00027 // ~nlogn time (n = number of variables.), which makes queries take constant
00028 // time.
00029 //===----------------------------------------------------------------------===//
00030 
00031 #include "StratifiedSets.h"
00032 #include "llvm/Analysis/Passes.h"
00033 #include "llvm/ADT/BitVector.h"
00034 #include "llvm/ADT/DenseMap.h"
00035 #include "llvm/ADT/Optional.h"
00036 #include "llvm/ADT/None.h"
00037 #include "llvm/Analysis/AliasAnalysis.h"
00038 #include "llvm/IR/Constants.h"
00039 #include "llvm/IR/Function.h"
00040 #include "llvm/IR/Instructions.h"
00041 #include "llvm/IR/InstVisitor.h"
00042 #include "llvm/IR/ValueHandle.h"
00043 #include "llvm/Pass.h"
00044 #include "llvm/Support/Allocator.h"
00045 #include "llvm/Support/Compiler.h"
00046 #include "llvm/Support/ErrorHandling.h"
00047 #include <algorithm>
00048 #include <cassert>
00049 #include <forward_list>
00050 #include <tuple>
00051 
00052 using namespace llvm;
00053 
00054 // Try to go from a Value* to a Function*. Never returns nullptr.
00055 static Optional<Function *> parentFunctionOfValue(Value *);
00056 
00057 // Returns possible functions called by the Inst* into the given
00058 // SmallVectorImpl. Returns true if targets found, false otherwise.
00059 // This is templated because InvokeInst/CallInst give us the same
00060 // set of functions that we care about, and I don't like repeating
00061 // myself.
00062 template <typename Inst>
00063 static bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &);
00064 
00065 // Some instructions need to have their users tracked. Instructions like
00066 // `add` require you to get the users of the Instruction* itself, other
00067 // instructions like `store` require you to get the users of the first
00068 // operand. This function gets the "proper" value to track for each
00069 // type of instruction we support.
00070 static Optional<Value *> getTargetValue(Instruction *);
00071 
00072 // There are certain instructions (i.e. FenceInst, etc.) that we ignore.
00073 // This notes that we should ignore those.
00074 static bool hasUsefulEdges(Instruction *);
00075 
00076 const StratifiedIndex StratifiedLink::SetSentinel =
00077   std::numeric_limits<StratifiedIndex>::max();
00078 
00079 namespace {
00080 // StratifiedInfo Attribute things.
00081 typedef unsigned StratifiedAttr;
00082 LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
00083 LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
00084 LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
00085 LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 2;
00086 LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
00087 LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
00088 
00089 LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
00090 LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
00091 
00092 // \brief StratifiedSets call for knowledge of "direction", so this is how we
00093 // represent that locally.
00094 enum class Level { Same, Above, Below };
00095 
00096 // \brief Edges can be one of four "weights" -- each weight must have an inverse
00097 // weight (Assign has Assign; Reference has Dereference).
00098 enum class EdgeType {
00099   // The weight assigned when assigning from or to a value. For example, in:
00100   // %b = getelementptr %a, 0
00101   // ...The relationships are %b assign %a, and %a assign %b. This used to be
00102   // two edges, but having a distinction bought us nothing.
00103   Assign,
00104 
00105   // The edge used when we have an edge going from some handle to a Value.
00106   // Examples of this include:
00107   // %b = load %a              (%b Dereference %a)
00108   // %b = extractelement %a, 0 (%a Dereference %b)
00109   Dereference,
00110 
00111   // The edge used when our edge goes from a value to a handle that may have
00112   // contained it at some point. Examples:
00113   // %b = load %a              (%a Reference %b)
00114   // %b = extractelement %a, 0 (%b Reference %a)
00115   Reference
00116 };
00117 
00118 // \brief Encodes the notion of a "use"
00119 struct Edge {
00120   // \brief Which value the edge is coming from
00121   Value *From;
00122 
00123   // \brief Which value the edge is pointing to
00124   Value *To;
00125 
00126   // \brief Edge weight
00127   EdgeType Weight;
00128 
00129   // \brief Whether we aliased any external values along the way that may be
00130   // invisible to the analysis (i.e. landingpad for exceptions, calls for
00131   // interprocedural analysis, etc.)
00132   StratifiedAttrs AdditionalAttrs;
00133 
00134   Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
00135       : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
00136 };
00137 
00138 // \brief Information we have about a function and would like to keep around
00139 struct FunctionInfo {
00140   StratifiedSets<Value *> Sets;
00141   // Lots of functions have < 4 returns. Adjust as necessary.
00142   SmallVector<Value *, 4> ReturnedValues;
00143 
00144   FunctionInfo(StratifiedSets<Value *> &&S,
00145                SmallVector<Value *, 4> &&RV)
00146     : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
00147 };
00148 
00149 struct CFLAliasAnalysis;
00150 
00151 struct FunctionHandle : public CallbackVH {
00152   FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
00153       : CallbackVH(Fn), CFLAA(CFLAA) {
00154     assert(Fn != nullptr);
00155     assert(CFLAA != nullptr);
00156   }
00157 
00158   virtual ~FunctionHandle() {}
00159 
00160   virtual void deleted() override { removeSelfFromCache(); }
00161   virtual void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
00162 
00163 private:
00164   CFLAliasAnalysis *CFLAA;
00165 
00166   void removeSelfFromCache();
00167 };
00168 
00169 struct CFLAliasAnalysis : public ImmutablePass, public AliasAnalysis {
00170 private:
00171   /// \brief Cached mapping of Functions to their StratifiedSets.
00172   /// If a function's sets are currently being built, it is marked
00173   /// in the cache as an Optional without a value. This way, if we
00174   /// have any kind of recursion, it is discernable from a function
00175   /// that simply has empty sets.
00176   DenseMap<Function *, Optional<FunctionInfo>> Cache;
00177   std::forward_list<FunctionHandle> Handles;
00178 
00179 public:
00180   static char ID;
00181 
00182   CFLAliasAnalysis() : ImmutablePass(ID) {
00183     initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
00184   }
00185 
00186   virtual ~CFLAliasAnalysis() {}
00187 
00188   void getAnalysisUsage(AnalysisUsage &AU) const {
00189     AliasAnalysis::getAnalysisUsage(AU);
00190   }
00191 
00192   void *getAdjustedAnalysisPointer(const void *ID) override {
00193     if (ID == &AliasAnalysis::ID)
00194       return (AliasAnalysis *)this;
00195     return this;
00196   }
00197 
00198   /// \brief Inserts the given Function into the cache.
00199   void scan(Function *Fn);
00200 
00201   void evict(Function *Fn) { Cache.erase(Fn); }
00202 
00203   /// \brief Ensures that the given function is available in the cache.
00204   /// Returns the appropriate entry from the cache.
00205   const Optional<FunctionInfo> &ensureCached(Function *Fn) {
00206     auto Iter = Cache.find(Fn);
00207     if (Iter == Cache.end()) {
00208       scan(Fn);
00209       Iter = Cache.find(Fn);
00210       assert(Iter != Cache.end());
00211       assert(Iter->second.hasValue());
00212     }
00213     return Iter->second;
00214   }
00215 
00216   AliasResult query(const Location &LocA, const Location &LocB);
00217 
00218   AliasResult alias(const Location &LocA, const Location &LocB) override {
00219     if (LocA.Ptr == LocB.Ptr) {
00220       if (LocA.Size == LocB.Size) {
00221         return MustAlias;
00222       } else {
00223         return PartialAlias;
00224       }
00225     }
00226 
00227     // Comparisons between global variables and other constants should be
00228     // handled by BasicAA.
00229     if (isa<Constant>(LocA.Ptr) && isa<Constant>(LocB.Ptr)) {
00230       return MayAlias;
00231     }
00232 
00233     return query(LocA, LocB);
00234   }
00235 
00236   void initializePass() override { InitializeAliasAnalysis(this); }
00237 };
00238 
00239 void FunctionHandle::removeSelfFromCache() {
00240   assert(CFLAA != nullptr);
00241   auto *Val = getValPtr();
00242   CFLAA->evict(cast<Function>(Val));
00243   setValPtr(nullptr);
00244 }
00245 
00246 // \brief Gets the edges our graph should have, based on an Instruction*
00247 class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
00248   CFLAliasAnalysis &AA;
00249   SmallVectorImpl<Edge> &Output;
00250 
00251 public:
00252   GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
00253       : AA(AA), Output(Output) {}
00254 
00255   void visitInstruction(Instruction &) {
00256     llvm_unreachable("Unsupported instruction encountered");
00257   }
00258 
00259   void visitCastInst(CastInst &Inst) {
00260     Output.push_back(Edge(&Inst, Inst.getOperand(0), EdgeType::Assign,
00261                           AttrNone));
00262   }
00263 
00264   void visitBinaryOperator(BinaryOperator &Inst) {
00265     auto *Op1 = Inst.getOperand(0);
00266     auto *Op2 = Inst.getOperand(1);
00267     Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
00268     Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
00269   }
00270 
00271   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
00272     auto *Ptr = Inst.getPointerOperand();
00273     auto *Val = Inst.getNewValOperand();
00274     Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
00275   }
00276 
00277   void visitAtomicRMWInst(AtomicRMWInst &Inst) {
00278     auto *Ptr = Inst.getPointerOperand();
00279     auto *Val = Inst.getValOperand();
00280     Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
00281   }
00282 
00283   void visitPHINode(PHINode &Inst) {
00284     for (unsigned I = 0, E = Inst.getNumIncomingValues(); I != E; ++I) {
00285       Value *Val = Inst.getIncomingValue(I);
00286       Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
00287     }
00288   }
00289 
00290   void visitGetElementPtrInst(GetElementPtrInst &Inst) {
00291     auto *Op = Inst.getPointerOperand();
00292     Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
00293     for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
00294       Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
00295   }
00296 
00297   void visitSelectInst(SelectInst &Inst) {
00298     auto *Condition = Inst.getCondition();
00299     Output.push_back(Edge(&Inst, Condition, EdgeType::Assign, AttrNone));
00300     auto *TrueVal = Inst.getTrueValue();
00301     Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
00302     auto *FalseVal = Inst.getFalseValue();
00303     Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
00304   }
00305 
00306   void visitAllocaInst(AllocaInst &) {}
00307 
00308   void visitLoadInst(LoadInst &Inst) {
00309     auto *Ptr = Inst.getPointerOperand();
00310     auto *Val = &Inst;
00311     Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
00312   }
00313 
00314   void visitStoreInst(StoreInst &Inst) {
00315     auto *Ptr = Inst.getPointerOperand();
00316     auto *Val = Inst.getValueOperand();
00317     Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
00318   }
00319 
00320   static bool isFunctionExternal(Function *Fn) {
00321     return Fn->isDeclaration() || !Fn->hasLocalLinkage();
00322   }
00323 
00324   // Gets whether the sets at Index1 above, below, or equal to the sets at
00325   // Index2. Returns None if they are not in the same set chain.
00326   static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
00327                                           StratifiedIndex Index1,
00328                                           StratifiedIndex Index2) {
00329     if (Index1 == Index2)
00330       return Level::Same;
00331 
00332     const auto *Current = &Sets.getLink(Index1);
00333     while (Current->hasBelow()) {
00334       if (Current->Below == Index2)
00335         return Level::Below;
00336       Current = &Sets.getLink(Current->Below);
00337     }
00338 
00339     Current = &Sets.getLink(Index1);
00340     while (Current->hasAbove()) {
00341       if (Current->Above == Index2)
00342         return Level::Above;
00343       Current = &Sets.getLink(Current->Above);
00344     }
00345 
00346     return NoneType();
00347   }
00348 
00349   bool
00350   tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
00351                              Value *FuncValue,
00352                              const iterator_range<User::op_iterator> &Args) {
00353     const unsigned ExpectedMaxArgs = 8;
00354     const unsigned MaxSupportedArgs = 50;
00355     assert(Fns.size() > 0);
00356 
00357     // I put this here to give us an upper bound on time taken by IPA. Is it
00358     // really (realistically) needed? Keep in mind that we do have an n^2 algo.
00359     if (std::distance(Args.begin(), Args.end()) > (int) MaxSupportedArgs)
00360       return false;
00361 
00362     // Exit early if we'll fail anyway
00363     for (auto *Fn : Fns) {
00364       if (isFunctionExternal(Fn) || Fn->isVarArg())
00365         return false;
00366       auto &MaybeInfo = AA.ensureCached(Fn);
00367       if (!MaybeInfo.hasValue())
00368         return false;
00369     }
00370 
00371     SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
00372     SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
00373     for (auto *Fn : Fns) {
00374       auto &Info = *AA.ensureCached(Fn);
00375       auto &Sets = Info.Sets;
00376       auto &RetVals = Info.ReturnedValues;
00377 
00378       Parameters.clear();
00379       for (auto &Param : Fn->args()) {
00380         auto MaybeInfo = Sets.find(&Param);
00381         // Did a new parameter somehow get added to the function/slip by?
00382         if (!MaybeInfo.hasValue())
00383           return false;
00384         Parameters.push_back(*MaybeInfo);
00385       }
00386 
00387       // Adding an edge from argument -> return value for each parameter that
00388       // may alias the return value
00389       for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
00390         auto &ParamInfo = Parameters[I];
00391         auto &ArgVal = Arguments[I];
00392         bool AddEdge = false;
00393         StratifiedAttrs Externals;
00394         for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
00395           auto MaybeInfo = Sets.find(RetVals[X]);
00396           if (!MaybeInfo.hasValue())
00397             return false;
00398 
00399           auto &RetInfo = *MaybeInfo;
00400           auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
00401           auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
00402           auto MaybeRelation =
00403               getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
00404           if (MaybeRelation.hasValue()) {
00405             AddEdge = true;
00406             Externals |= RetAttrs | ParamAttrs;
00407           }
00408         }
00409         if (AddEdge)
00410           Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
00411                             StratifiedAttrs().flip()));
00412       }
00413 
00414       if (Parameters.size() != Arguments.size())
00415         return false;
00416 
00417       // Adding edges between arguments for arguments that may end up aliasing
00418       // each other. This is necessary for functions such as
00419       // void foo(int** a, int** b) { *a = *b; }
00420       // (Technically, the proper sets for this would be those below
00421       // Arguments[I] and Arguments[X], but our algorithm will produce
00422       // extremely similar, and equally correct, results either way)
00423       for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
00424         auto &MainVal = Arguments[I];
00425         auto &MainInfo = Parameters[I];
00426         auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
00427         for (unsigned X = I + 1; X != E; ++X) {
00428           auto &SubInfo = Parameters[X];
00429           auto &SubVal = Arguments[X];
00430           auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
00431           auto MaybeRelation =
00432               getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
00433 
00434           if (!MaybeRelation.hasValue())
00435             continue;
00436 
00437           auto NewAttrs = SubAttrs | MainAttrs;
00438           Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
00439         }
00440       }
00441     }
00442     return true;
00443   }
00444 
00445   template <typename InstT> void visitCallLikeInst(InstT &Inst) {
00446     SmallVector<Function *, 4> Targets;
00447     if (getPossibleTargets(&Inst, Targets)) {
00448       if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
00449         return;
00450       // Cleanup from interprocedural analysis
00451       Output.clear();
00452     }
00453 
00454     for (Value *V : Inst.arg_operands())
00455       Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
00456   }
00457 
00458   void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
00459 
00460   void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
00461 
00462   // Because vectors/aggregates are immutable and unaddressable,
00463   // there's nothing we can do to coax a value out of them, other
00464   // than calling Extract{Element,Value}. We can effectively treat
00465   // them as pointers to arbitrary memory locations we can store in
00466   // and load from.
00467   void visitExtractElementInst(ExtractElementInst &Inst) {
00468     auto *Ptr = Inst.getVectorOperand();
00469     auto *Val = &Inst;
00470     Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
00471   }
00472 
00473   void visitInsertElementInst(InsertElementInst &Inst) {
00474     auto *Vec = Inst.getOperand(0);
00475     auto *Val = Inst.getOperand(1);
00476     Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
00477     Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
00478   }
00479 
00480   void visitLandingPadInst(LandingPadInst &Inst) {
00481     // Exceptions come from "nowhere", from our analysis' perspective.
00482     // So we place the instruction its own group, noting that said group may
00483     // alias externals
00484     Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
00485   }
00486 
00487   void visitInsertValueInst(InsertValueInst &Inst) {
00488     auto *Agg = Inst.getOperand(0);
00489     auto *Val = Inst.getOperand(1);
00490     Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
00491     Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
00492   }
00493 
00494   void visitExtractValueInst(ExtractValueInst &Inst) {
00495     auto *Ptr = Inst.getAggregateOperand();
00496     Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
00497   }
00498 
00499   void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
00500     auto *From1 = Inst.getOperand(0);
00501     auto *From2 = Inst.getOperand(1);
00502     Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
00503     Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
00504   }
00505 };
00506 
00507 // For a given instruction, we need to know which Value* to get the
00508 // users of in order to build our graph. In some cases (i.e. add),
00509 // we simply need the Instruction*. In other cases (i.e. store),
00510 // finding the users of the Instruction* is useless; we need to find
00511 // the users of the first operand. This handles determining which
00512 // value to follow for us.
00513 //
00514 // Note: we *need* to keep this in sync with GetEdgesVisitor. Add
00515 // something to GetEdgesVisitor, add it here -- remove something from
00516 // GetEdgesVisitor, remove it here.
00517 class GetTargetValueVisitor
00518     : public InstVisitor<GetTargetValueVisitor, Value *> {
00519 public:
00520   Value *visitInstruction(Instruction &Inst) { return &Inst; }
00521 
00522   Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
00523 
00524   Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
00525     return Inst.getPointerOperand();
00526   }
00527 
00528   Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
00529     return Inst.getPointerOperand();
00530   }
00531 
00532   Value *visitInsertElementInst(InsertElementInst &Inst) {
00533     return Inst.getOperand(0);
00534   }
00535 
00536   Value *visitInsertValueInst(InsertValueInst &Inst) {
00537     return Inst.getAggregateOperand();
00538   }
00539 };
00540 
00541 // Set building requires a weighted bidirectional graph.
00542 template <typename EdgeTypeT> class WeightedBidirectionalGraph {
00543 public:
00544   typedef std::size_t Node;
00545 
00546 private:
00547   const static Node StartNode = Node(0);
00548 
00549   struct Edge {
00550     EdgeTypeT Weight;
00551     Node Other;
00552 
00553     Edge(const EdgeTypeT &W, const Node &N)
00554       : Weight(W), Other(N) {}
00555 
00556     bool operator==(const Edge &E) const {
00557       return Weight == E.Weight && Other == E.Other;
00558     }
00559 
00560     bool operator!=(const Edge &E) const { return !operator==(E); }
00561   };
00562 
00563   struct NodeImpl {
00564     std::vector<Edge> Edges;
00565   };
00566 
00567   std::vector<NodeImpl> NodeImpls;
00568 
00569   bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
00570 
00571   const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
00572   NodeImpl &getNode(Node N) { return NodeImpls[N]; }
00573 
00574 public:
00575   // ----- Various Edge iterators for the graph ----- //
00576 
00577   // \brief Iterator for edges. Because this graph is bidirected, we don't
00578   // allow modificaiton of the edges using this iterator. Additionally, the
00579   // iterator becomes invalid if you add edges to or from the node you're
00580   // getting the edges of.
00581   struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
00582                                              std::tuple<EdgeTypeT, Node *>> {
00583     EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
00584         : Current(Iter) {}
00585 
00586     EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
00587 
00588     EdgeIterator &operator++() {
00589       ++Current;
00590       return *this;
00591     }
00592 
00593     EdgeIterator operator++(int) {
00594       EdgeIterator Copy(Current);
00595       operator++();
00596       return Copy;
00597     }
00598 
00599     std::tuple<EdgeTypeT, Node> &operator*() {
00600       Store = std::make_tuple(Current->Weight, Current->Other);
00601       return Store;
00602     }
00603 
00604     bool operator==(const EdgeIterator &Other) const {
00605       return Current == Other.Current;
00606     }
00607 
00608     bool operator!=(const EdgeIterator &Other) const {
00609       return !operator==(Other);
00610     }
00611 
00612   private:
00613     typename std::vector<Edge>::const_iterator Current;
00614     std::tuple<EdgeTypeT, Node> Store;
00615   };
00616 
00617   // Wrapper for EdgeIterator with begin()/end() calls.
00618   struct EdgeIterable {
00619     EdgeIterable(const std::vector<Edge> &Edges)
00620         : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
00621 
00622     EdgeIterator begin() { return EdgeIterator(BeginIter); }
00623 
00624     EdgeIterator end() { return EdgeIterator(EndIter); }
00625 
00626   private:
00627     typename std::vector<Edge>::const_iterator BeginIter;
00628     typename std::vector<Edge>::const_iterator EndIter;
00629   };
00630 
00631   // ----- Actual graph-related things ----- //
00632 
00633   WeightedBidirectionalGraph() {}
00634 
00635   WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
00636       : NodeImpls(std::move(Other.NodeImpls)) {}
00637 
00638   WeightedBidirectionalGraph<EdgeTypeT> &
00639   operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
00640     NodeImpls = std::move(Other.NodeImpls);
00641     return *this;
00642   }
00643 
00644   Node addNode() {
00645     auto Index = NodeImpls.size();
00646     auto NewNode = Node(Index);
00647     NodeImpls.push_back(NodeImpl());
00648     return NewNode;
00649   }
00650 
00651   void addEdge(Node From, Node To, const EdgeTypeT &Weight,
00652                const EdgeTypeT &ReverseWeight) {
00653     assert(inbounds(From));
00654     assert(inbounds(To));
00655     auto &FromNode = getNode(From);
00656     auto &ToNode = getNode(To);
00657     FromNode.Edges.push_back(Edge(Weight, To));
00658     ToNode.Edges.push_back(Edge(ReverseWeight, From));
00659   }
00660 
00661   EdgeIterable edgesFor(const Node &N) const {
00662     const auto &Node = getNode(N);
00663     return EdgeIterable(Node.Edges);
00664   }
00665 
00666   bool empty() const { return NodeImpls.empty(); }
00667   std::size_t size() const { return NodeImpls.size(); }
00668 
00669   // \brief Gets an arbitrary node in the graph as a starting point for
00670   // traversal.
00671   Node getEntryNode() {
00672     assert(inbounds(StartNode));
00673     return StartNode;
00674   }
00675 };
00676 
00677 typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
00678 typedef DenseMap<Value *, GraphT::Node> NodeMapT;
00679 }
00680 
00681 // -- Setting up/registering CFLAA pass -- //
00682 char CFLAliasAnalysis::ID = 0;
00683 
00684 INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
00685                    "CFL-Based AA implementation", false, true, false)
00686 
00687 ImmutablePass *llvm::createCFLAliasAnalysisPass() {
00688   return new CFLAliasAnalysis();
00689 }
00690 
00691 //===----------------------------------------------------------------------===//
00692 // Function declarations that require types defined in the namespace above
00693 //===----------------------------------------------------------------------===//
00694 
00695 // Given an argument number, returns the appropriate Attr index to set.
00696 static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
00697 
00698 // Given a Value, potentially return which AttrIndex it maps to.
00699 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
00700 
00701 // Gets the inverse of a given EdgeType.
00702 static EdgeType flipWeight(EdgeType);
00703 
00704 // Gets edges of the given Instruction*, writing them to the SmallVector*.
00705 static void argsToEdges(CFLAliasAnalysis &, Instruction *,
00706                         SmallVectorImpl<Edge> &);
00707 
00708 // Gets the "Level" that one should travel in StratifiedSets
00709 // given an EdgeType.
00710 static Level directionOfEdgeType(EdgeType);
00711 
00712 // Builds the graph needed for constructing the StratifiedSets for the
00713 // given function
00714 static void buildGraphFrom(CFLAliasAnalysis &, Function *,
00715                            SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
00716 
00717 // Builds the graph + StratifiedSets for a function.
00718 static FunctionInfo buildSetsFrom(CFLAliasAnalysis &, Function *);
00719 
00720 static Optional<Function *> parentFunctionOfValue(Value *Val) {
00721   if (auto *Inst = dyn_cast<Instruction>(Val)) {
00722     auto *Bb = Inst->getParent();
00723     return Bb->getParent();
00724   }
00725 
00726   if (auto *Arg = dyn_cast<Argument>(Val))
00727     return Arg->getParent();
00728   return NoneType();
00729 }
00730 
00731 template <typename Inst>
00732 static bool getPossibleTargets(Inst *Call,
00733                                SmallVectorImpl<Function *> &Output) {
00734   if (auto *Fn = Call->getCalledFunction()) {
00735     Output.push_back(Fn);
00736     return true;
00737   }
00738 
00739   // TODO: If the call is indirect, we might be able to enumerate all potential
00740   // targets of the call and return them, rather than just failing.
00741   return false;
00742 }
00743 
00744 static Optional<Value *> getTargetValue(Instruction *Inst) {
00745   GetTargetValueVisitor V;
00746   return V.visit(Inst);
00747 }
00748 
00749 static bool hasUsefulEdges(Instruction *Inst) {
00750   bool IsNonInvokeTerminator =
00751       isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
00752   return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
00753 }
00754 
00755 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
00756   if (isa<GlobalValue>(Val))
00757     return AttrGlobalIndex;
00758 
00759   if (auto *Arg = dyn_cast<Argument>(Val))
00760     if (!Arg->hasNoAliasAttr())
00761       return argNumberToAttrIndex(Arg->getArgNo());
00762   return NoneType();
00763 }
00764 
00765 static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
00766   if (ArgNum > AttrMaxNumArgs)
00767     return AttrAllIndex;
00768   return ArgNum + AttrFirstArgIndex;
00769 }
00770 
00771 static EdgeType flipWeight(EdgeType Initial) {
00772   switch (Initial) {
00773   case EdgeType::Assign:
00774     return EdgeType::Assign;
00775   case EdgeType::Dereference:
00776     return EdgeType::Reference;
00777   case EdgeType::Reference:
00778     return EdgeType::Dereference;
00779   }
00780   llvm_unreachable("Incomplete coverage of EdgeType enum");
00781 }
00782 
00783 static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
00784                         SmallVectorImpl<Edge> &Output) {
00785   GetEdgesVisitor v(Analysis, Output);
00786   v.visit(Inst);
00787 }
00788 
00789 static Level directionOfEdgeType(EdgeType Weight) {
00790   switch (Weight) {
00791   case EdgeType::Reference:
00792     return Level::Above;
00793   case EdgeType::Dereference:
00794     return Level::Below;
00795   case EdgeType::Assign:
00796     return Level::Same;
00797   }
00798   llvm_unreachable("Incomplete switch coverage");
00799 }
00800 
00801 // Aside: We may remove graph construction entirely, because it doesn't really
00802 // buy us much that we don't already have. I'd like to add interprocedural
00803 // analysis prior to this however, in case that somehow requires the graph
00804 // produced by this for efficient execution
00805 static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
00806                            SmallVectorImpl<Value *> &ReturnedValues,
00807                            NodeMapT &Map, GraphT &Graph) {
00808   const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
00809     auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
00810     auto &Iter = Pair.first;
00811     if (Pair.second) {
00812       auto NewNode = Graph.addNode();
00813       Iter->second = NewNode;
00814     }
00815     return Iter->second;
00816   };
00817 
00818   SmallVector<Edge, 8> Edges;
00819   for (auto &Bb : Fn->getBasicBlockList()) {
00820     for (auto &Inst : Bb.getInstList()) {
00821       // We don't want the edges of most "return" instructions, but we *do* want
00822       // to know what can be returned.
00823       if (auto *Ret = dyn_cast<ReturnInst>(&Inst))
00824         ReturnedValues.push_back(Ret);
00825 
00826       if (!hasUsefulEdges(&Inst))
00827         continue;
00828 
00829       Edges.clear();
00830       argsToEdges(Analysis, &Inst, Edges);
00831 
00832       // In the case of an unused alloca (or similar), edges may be empty. Note
00833       // that it exists so we can potentially answer NoAlias.
00834       if (Edges.empty()) {
00835         auto MaybeVal = getTargetValue(&Inst);
00836         assert(MaybeVal.hasValue());
00837         auto *Target = *MaybeVal;
00838         findOrInsertNode(Target);
00839         continue;
00840       }
00841 
00842       for (const Edge &E : Edges) {
00843         auto To = findOrInsertNode(E.To);
00844         auto From = findOrInsertNode(E.From);
00845         auto FlippedWeight = flipWeight(E.Weight);
00846         auto Attrs = E.AdditionalAttrs;
00847         Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
00848                                 std::make_pair(FlippedWeight, Attrs));
00849       }
00850     }
00851   }
00852 }
00853 
00854 static FunctionInfo buildSetsFrom(CFLAliasAnalysis &Analysis, Function *Fn) {
00855   NodeMapT Map;
00856   GraphT Graph;
00857   SmallVector<Value *, 4> ReturnedValues;
00858 
00859   buildGraphFrom(Analysis, Fn, ReturnedValues, Map, Graph);
00860 
00861   DenseMap<GraphT::Node, Value *> NodeValueMap;
00862   NodeValueMap.resize(Map.size());
00863   for (const auto &Pair : Map)
00864     NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
00865 
00866   const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
00867     auto ValIter = NodeValueMap.find(Node);
00868     assert(ValIter != NodeValueMap.end());
00869     return ValIter->second;
00870   };
00871 
00872   StratifiedSetsBuilder<Value *> Builder;
00873 
00874   SmallVector<GraphT::Node, 16> Worklist;
00875   for (auto &Pair : Map) {
00876     Worklist.clear();
00877 
00878     auto *Value = Pair.first;
00879     Builder.add(Value);
00880     auto InitialNode = Pair.second;
00881     Worklist.push_back(InitialNode);
00882     while (!Worklist.empty()) {
00883       auto Node = Worklist.pop_back_val();
00884       auto *CurValue = findValueOrDie(Node);
00885       if (isa<Constant>(CurValue) && !isa<GlobalValue>(CurValue))
00886         continue;
00887 
00888       for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
00889         auto Weight = std::get<0>(EdgeTuple);
00890         auto Label = Weight.first;
00891         auto &OtherNode = std::get<1>(EdgeTuple);
00892         auto *OtherValue = findValueOrDie(OtherNode);
00893 
00894         if (isa<Constant>(OtherValue) && !isa<GlobalValue>(OtherValue))
00895           continue;
00896 
00897         bool Added;
00898         switch (directionOfEdgeType(Label)) {
00899         case Level::Above:
00900           Added = Builder.addAbove(CurValue, OtherValue);
00901           break;
00902         case Level::Below:
00903           Added = Builder.addBelow(CurValue, OtherValue);
00904           break;
00905         case Level::Same:
00906           Added = Builder.addWith(CurValue, OtherValue);
00907           break;
00908         }
00909 
00910         if (Added) {
00911           auto Aliasing = Weight.second;
00912           if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
00913             Aliasing.set(*MaybeCurIndex);
00914           if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
00915             Aliasing.set(*MaybeOtherIndex);
00916           Builder.noteAttributes(CurValue, Aliasing);
00917           Builder.noteAttributes(OtherValue, Aliasing);
00918           Worklist.push_back(OtherNode);
00919         }
00920       }
00921     }
00922   }
00923 
00924   // There are times when we end up with parameters not in our graph (i.e. if
00925   // it's only used as the condition of a branch). Other bits of code depend on
00926   // things that were present during construction being present in the graph.
00927   // So, we add all present arguments here.
00928   for (auto &Arg : Fn->args()) {
00929     Builder.add(&Arg);
00930   }
00931 
00932   return FunctionInfo(Builder.build(), std::move(ReturnedValues));
00933 }
00934 
00935 void CFLAliasAnalysis::scan(Function *Fn) {
00936   auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
00937   (void)InsertPair;
00938   assert(InsertPair.second &&
00939          "Trying to scan a function that has already been cached");
00940 
00941   FunctionInfo Info(buildSetsFrom(*this, Fn));
00942   Cache[Fn] = std::move(Info);
00943   Handles.push_front(FunctionHandle(Fn, this));
00944 }
00945 
00946 AliasAnalysis::AliasResult
00947 CFLAliasAnalysis::query(const AliasAnalysis::Location &LocA,
00948                         const AliasAnalysis::Location &LocB) {
00949   auto *ValA = const_cast<Value *>(LocA.Ptr);
00950   auto *ValB = const_cast<Value *>(LocB.Ptr);
00951 
00952   Function *Fn = nullptr;
00953   auto MaybeFnA = parentFunctionOfValue(ValA);
00954   auto MaybeFnB = parentFunctionOfValue(ValB);
00955   if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
00956     llvm_unreachable("Don't know how to extract the parent function "
00957                      "from values A or B");
00958   }
00959 
00960   if (MaybeFnA.hasValue()) {
00961     Fn = *MaybeFnA;
00962     assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
00963            "Interprocedural queries not supported");
00964   } else {
00965     Fn = *MaybeFnB;
00966   }
00967 
00968   assert(Fn != nullptr);
00969   auto &MaybeInfo = ensureCached(Fn);
00970   assert(MaybeInfo.hasValue());
00971 
00972   auto &Sets = MaybeInfo->Sets;
00973   auto MaybeA = Sets.find(ValA);
00974   if (!MaybeA.hasValue())
00975     return AliasAnalysis::MayAlias;
00976 
00977   auto MaybeB = Sets.find(ValB);
00978   if (!MaybeB.hasValue())
00979     return AliasAnalysis::MayAlias;
00980 
00981   auto SetA = *MaybeA;
00982   auto SetB = *MaybeB;
00983 
00984   if (SetA.Index == SetB.Index)
00985     return AliasAnalysis::PartialAlias;
00986 
00987   auto AttrsA = Sets.getLink(SetA.Index).Attrs;
00988   auto AttrsB = Sets.getLink(SetB.Index).Attrs;
00989   auto CombinedAttrs = AttrsA | AttrsB;
00990   if (CombinedAttrs.any())
00991     return AliasAnalysis::PartialAlias;
00992 
00993   return AliasAnalysis::NoAlias;
00994 }