Fix delegation
[oota-llvm.git] / lib / Analysis / CFLAliasAnalysis.cpp
1 //===- CFLAliasAnalysis.cpp - CFL-Based Alias Analysis Implementation ------==//
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 implements a CFL-based context-insensitive alias analysis
11 // algorithm. It does not depend on types. The algorithm is a mixture of the one
12 // described in "Demand-driven alias analysis for C" by Xin Zheng and Radu
13 // Rugina, and "Fast algorithms for Dyck-CFL-reachability with applications to
14 // Alias Analysis" by Zhang Q, Lyu M R, Yuan H, and Su Z. -- to summarize the
15 // papers, we build a graph of the uses of a variable, where each node is a
16 // memory location, and each edge is an action that happened on that memory
17 // location.  The "actions" can be one of Dereference, Reference, Assign, or
18 // Assign.
19 //
20 // Two variables are considered as aliasing iff you can reach one value's node
21 // from the other value's node and the language formed by concatenating all of
22 // the edge labels (actions) conforms to a context-free grammar.
23 //
24 // Because this algorithm requires a graph search on each query, we execute the
25 // algorithm outlined in "Fast algorithms..." (mentioned above)
26 // in order to transform the graph into sets of variables that may alias in
27 // ~nlogn time (n = number of variables.), which makes queries take constant
28 // time.
29 //===----------------------------------------------------------------------===//
30
31 #include "StratifiedSets.h"
32 #include "llvm/ADT/BitVector.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/None.h"
35 #include "llvm/ADT/Optional.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/Analysis/Passes.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/InstVisitor.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/ValueHandle.h"
43 #include "llvm/Pass.h"
44 #include "llvm/Support/Allocator.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include <algorithm>
48 #include <cassert>
49 #include <forward_list>
50 #include <tuple>
51
52 using namespace llvm;
53
54 // Try to go from a Value* to a Function*. Never returns nullptr.
55 static Optional<Function *> parentFunctionOfValue(Value *);
56
57 // Returns possible functions called by the Inst* into the given
58 // SmallVectorImpl. Returns true if targets found, false otherwise.
59 // This is templated because InvokeInst/CallInst give us the same
60 // set of functions that we care about, and I don't like repeating
61 // myself.
62 template <typename Inst>
63 static bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &);
64
65 // Some instructions need to have their users tracked. Instructions like
66 // `add` require you to get the users of the Instruction* itself, other
67 // instructions like `store` require you to get the users of the first
68 // operand. This function gets the "proper" value to track for each
69 // type of instruction we support.
70 static Optional<Value *> getTargetValue(Instruction *);
71
72 // There are certain instructions (i.e. FenceInst, etc.) that we ignore.
73 // This notes that we should ignore those.
74 static bool hasUsefulEdges(Instruction *);
75
76 const StratifiedIndex StratifiedLink::SetSentinel =
77   std::numeric_limits<StratifiedIndex>::max();
78
79 namespace {
80 // StratifiedInfo Attribute things.
81 typedef unsigned StratifiedAttr;
82 LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
83 LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
84 LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
85 LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 2;
86 LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
87 LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
88
89 LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
90 LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
91
92 // \brief StratifiedSets call for knowledge of "direction", so this is how we
93 // represent that locally.
94 enum class Level { Same, Above, Below };
95
96 // \brief Edges can be one of four "weights" -- each weight must have an inverse
97 // weight (Assign has Assign; Reference has Dereference).
98 enum class EdgeType {
99   // The weight assigned when assigning from or to a value. For example, in:
100   // %b = getelementptr %a, 0
101   // ...The relationships are %b assign %a, and %a assign %b. This used to be
102   // two edges, but having a distinction bought us nothing.
103   Assign,
104
105   // The edge used when we have an edge going from some handle to a Value.
106   // Examples of this include:
107   // %b = load %a              (%b Dereference %a)
108   // %b = extractelement %a, 0 (%a Dereference %b)
109   Dereference,
110
111   // The edge used when our edge goes from a value to a handle that may have
112   // contained it at some point. Examples:
113   // %b = load %a              (%a Reference %b)
114   // %b = extractelement %a, 0 (%b Reference %a)
115   Reference
116 };
117
118 // \brief Encodes the notion of a "use"
119 struct Edge {
120   // \brief Which value the edge is coming from
121   Value *From;
122
123   // \brief Which value the edge is pointing to
124   Value *To;
125
126   // \brief Edge weight
127   EdgeType Weight;
128
129   // \brief Whether we aliased any external values along the way that may be
130   // invisible to the analysis (i.e. landingpad for exceptions, calls for
131   // interprocedural analysis, etc.)
132   StratifiedAttrs AdditionalAttrs;
133
134   Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
135       : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
136 };
137
138 // \brief Information we have about a function and would like to keep around
139 struct FunctionInfo {
140   StratifiedSets<Value *> Sets;
141   // Lots of functions have < 4 returns. Adjust as necessary.
142   SmallVector<Value *, 4> ReturnedValues;
143
144   FunctionInfo(StratifiedSets<Value *> &&S,
145                SmallVector<Value *, 4> &&RV)
146     : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
147 };
148
149 struct CFLAliasAnalysis;
150
151 struct FunctionHandle : public CallbackVH {
152   FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
153       : CallbackVH(Fn), CFLAA(CFLAA) {
154     assert(Fn != nullptr);
155     assert(CFLAA != nullptr);
156   }
157
158   virtual ~FunctionHandle() {}
159
160   void deleted() override { removeSelfFromCache(); }
161   void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
162
163 private:
164   CFLAliasAnalysis *CFLAA;
165
166   void removeSelfFromCache();
167 };
168
169 struct CFLAliasAnalysis : public ImmutablePass, public AliasAnalysis {
170 private:
171   /// \brief Cached mapping of Functions to their StratifiedSets.
172   /// If a function's sets are currently being built, it is marked
173   /// in the cache as an Optional without a value. This way, if we
174   /// have any kind of recursion, it is discernable from a function
175   /// that simply has empty sets.
176   DenseMap<Function *, Optional<FunctionInfo>> Cache;
177   std::forward_list<FunctionHandle> Handles;
178
179 public:
180   static char ID;
181
182   CFLAliasAnalysis() : ImmutablePass(ID) {
183     initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
184   }
185
186   virtual ~CFLAliasAnalysis() {}
187
188   void getAnalysisUsage(AnalysisUsage &AU) const override {
189     AliasAnalysis::getAnalysisUsage(AU);
190   }
191
192   void *getAdjustedAnalysisPointer(const void *ID) override {
193     if (ID == &AliasAnalysis::ID)
194       return (AliasAnalysis *)this;
195     return this;
196   }
197
198   /// \brief Inserts the given Function into the cache.
199   void scan(Function *Fn);
200
201   void evict(Function *Fn) { Cache.erase(Fn); }
202
203   /// \brief Ensures that the given function is available in the cache.
204   /// Returns the appropriate entry from the cache.
205   const Optional<FunctionInfo> &ensureCached(Function *Fn) {
206     auto Iter = Cache.find(Fn);
207     if (Iter == Cache.end()) {
208       scan(Fn);
209       Iter = Cache.find(Fn);
210       assert(Iter != Cache.end());
211       assert(Iter->second.hasValue());
212     }
213     return Iter->second;
214   }
215
216   AliasResult query(const Location &LocA, const Location &LocB);
217
218   AliasResult alias(const Location &LocA, const Location &LocB) override {
219     if (LocA.Ptr == LocB.Ptr) {
220       if (LocA.Size == LocB.Size) {
221         return MustAlias;
222       } else {
223         return PartialAlias;
224       }
225     }
226
227     // Comparisons between global variables and other constants should be
228     // handled by BasicAA.
229     if (isa<Constant>(LocA.Ptr) && isa<Constant>(LocB.Ptr)) {
230       return AliasAnalysis::alias(LocA, LocB);
231     }
232     AliasResult QueryResult = query(LocA, LocB);
233     if (QueryResult == MayAlias)
234       return AliasAnalysis::alias(LocA, LocB);
235
236     return QueryResult;
237   }
238
239   void initializePass() override { InitializeAliasAnalysis(this); }
240 };
241
242 void FunctionHandle::removeSelfFromCache() {
243   assert(CFLAA != nullptr);
244   auto *Val = getValPtr();
245   CFLAA->evict(cast<Function>(Val));
246   setValPtr(nullptr);
247 }
248
249 // \brief Gets the edges our graph should have, based on an Instruction*
250 class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
251   CFLAliasAnalysis &AA;
252   SmallVectorImpl<Edge> &Output;
253
254 public:
255   GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
256       : AA(AA), Output(Output) {}
257
258   void visitInstruction(Instruction &) {
259     llvm_unreachable("Unsupported instruction encountered");
260   }
261
262   void visitCastInst(CastInst &Inst) {
263     Output.push_back(Edge(&Inst, Inst.getOperand(0), EdgeType::Assign,
264                           AttrNone));
265   }
266
267   void visitBinaryOperator(BinaryOperator &Inst) {
268     auto *Op1 = Inst.getOperand(0);
269     auto *Op2 = Inst.getOperand(1);
270     Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
271     Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
272   }
273
274   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
275     auto *Ptr = Inst.getPointerOperand();
276     auto *Val = Inst.getNewValOperand();
277     Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
278   }
279
280   void visitAtomicRMWInst(AtomicRMWInst &Inst) {
281     auto *Ptr = Inst.getPointerOperand();
282     auto *Val = Inst.getValOperand();
283     Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
284   }
285
286   void visitPHINode(PHINode &Inst) {
287     for (unsigned I = 0, E = Inst.getNumIncomingValues(); I != E; ++I) {
288       Value *Val = Inst.getIncomingValue(I);
289       Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
290     }
291   }
292
293   void visitGetElementPtrInst(GetElementPtrInst &Inst) {
294     auto *Op = Inst.getPointerOperand();
295     Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
296     for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
297       Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
298   }
299
300   void visitSelectInst(SelectInst &Inst) {
301     auto *Condition = Inst.getCondition();
302     Output.push_back(Edge(&Inst, Condition, EdgeType::Assign, AttrNone));
303     auto *TrueVal = Inst.getTrueValue();
304     Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
305     auto *FalseVal = Inst.getFalseValue();
306     Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
307   }
308
309   void visitAllocaInst(AllocaInst &) {}
310
311   void visitLoadInst(LoadInst &Inst) {
312     auto *Ptr = Inst.getPointerOperand();
313     auto *Val = &Inst;
314     Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
315   }
316
317   void visitStoreInst(StoreInst &Inst) {
318     auto *Ptr = Inst.getPointerOperand();
319     auto *Val = Inst.getValueOperand();
320     Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
321   }
322
323   void visitVAArgInst(VAArgInst &Inst) {
324     // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
325     // two things:
326     //  1. Loads a value from *((T*)*Ptr).
327     //  2. Increments (stores to) *Ptr by some target-specific amount.
328     // For now, we'll handle this like a landingpad instruction (by placing the
329     // result in its own group, and having that group alias externals).
330     auto *Val = &Inst;
331     Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll));
332   }
333
334   static bool isFunctionExternal(Function *Fn) {
335     return Fn->isDeclaration() || !Fn->hasLocalLinkage();
336   }
337
338   // Gets whether the sets at Index1 above, below, or equal to the sets at
339   // Index2. Returns None if they are not in the same set chain.
340   static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
341                                           StratifiedIndex Index1,
342                                           StratifiedIndex Index2) {
343     if (Index1 == Index2)
344       return Level::Same;
345
346     const auto *Current = &Sets.getLink(Index1);
347     while (Current->hasBelow()) {
348       if (Current->Below == Index2)
349         return Level::Below;
350       Current = &Sets.getLink(Current->Below);
351     }
352
353     Current = &Sets.getLink(Index1);
354     while (Current->hasAbove()) {
355       if (Current->Above == Index2)
356         return Level::Above;
357       Current = &Sets.getLink(Current->Above);
358     }
359
360     return NoneType();
361   }
362
363   bool
364   tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
365                              Value *FuncValue,
366                              const iterator_range<User::op_iterator> &Args) {
367     const unsigned ExpectedMaxArgs = 8;
368     const unsigned MaxSupportedArgs = 50;
369     assert(Fns.size() > 0);
370
371     // I put this here to give us an upper bound on time taken by IPA. Is it
372     // really (realistically) needed? Keep in mind that we do have an n^2 algo.
373     if (std::distance(Args.begin(), Args.end()) > (int) MaxSupportedArgs)
374       return false;
375
376     // Exit early if we'll fail anyway
377     for (auto *Fn : Fns) {
378       if (isFunctionExternal(Fn) || Fn->isVarArg())
379         return false;
380       auto &MaybeInfo = AA.ensureCached(Fn);
381       if (!MaybeInfo.hasValue())
382         return false;
383     }
384
385     SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
386     SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
387     for (auto *Fn : Fns) {
388       auto &Info = *AA.ensureCached(Fn);
389       auto &Sets = Info.Sets;
390       auto &RetVals = Info.ReturnedValues;
391
392       Parameters.clear();
393       for (auto &Param : Fn->args()) {
394         auto MaybeInfo = Sets.find(&Param);
395         // Did a new parameter somehow get added to the function/slip by?
396         if (!MaybeInfo.hasValue())
397           return false;
398         Parameters.push_back(*MaybeInfo);
399       }
400
401       // Adding an edge from argument -> return value for each parameter that
402       // may alias the return value
403       for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
404         auto &ParamInfo = Parameters[I];
405         auto &ArgVal = Arguments[I];
406         bool AddEdge = false;
407         StratifiedAttrs Externals;
408         for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
409           auto MaybeInfo = Sets.find(RetVals[X]);
410           if (!MaybeInfo.hasValue())
411             return false;
412
413           auto &RetInfo = *MaybeInfo;
414           auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
415           auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
416           auto MaybeRelation =
417               getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
418           if (MaybeRelation.hasValue()) {
419             AddEdge = true;
420             Externals |= RetAttrs | ParamAttrs;
421           }
422         }
423         if (AddEdge)
424           Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
425                             StratifiedAttrs().flip()));
426       }
427
428       if (Parameters.size() != Arguments.size())
429         return false;
430
431       // Adding edges between arguments for arguments that may end up aliasing
432       // each other. This is necessary for functions such as
433       // void foo(int** a, int** b) { *a = *b; }
434       // (Technically, the proper sets for this would be those below
435       // Arguments[I] and Arguments[X], but our algorithm will produce
436       // extremely similar, and equally correct, results either way)
437       for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
438         auto &MainVal = Arguments[I];
439         auto &MainInfo = Parameters[I];
440         auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
441         for (unsigned X = I + 1; X != E; ++X) {
442           auto &SubInfo = Parameters[X];
443           auto &SubVal = Arguments[X];
444           auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
445           auto MaybeRelation =
446               getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
447
448           if (!MaybeRelation.hasValue())
449             continue;
450
451           auto NewAttrs = SubAttrs | MainAttrs;
452           Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
453         }
454       }
455     }
456     return true;
457   }
458
459   template <typename InstT> void visitCallLikeInst(InstT &Inst) {
460     SmallVector<Function *, 4> Targets;
461     if (getPossibleTargets(&Inst, Targets)) {
462       if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
463         return;
464       // Cleanup from interprocedural analysis
465       Output.clear();
466     }
467
468     for (Value *V : Inst.arg_operands())
469       Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
470   }
471
472   void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
473
474   void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
475
476   // Because vectors/aggregates are immutable and unaddressable,
477   // there's nothing we can do to coax a value out of them, other
478   // than calling Extract{Element,Value}. We can effectively treat
479   // them as pointers to arbitrary memory locations we can store in
480   // and load from.
481   void visitExtractElementInst(ExtractElementInst &Inst) {
482     auto *Ptr = Inst.getVectorOperand();
483     auto *Val = &Inst;
484     Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
485   }
486
487   void visitInsertElementInst(InsertElementInst &Inst) {
488     auto *Vec = Inst.getOperand(0);
489     auto *Val = Inst.getOperand(1);
490     Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
491     Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
492   }
493
494   void visitLandingPadInst(LandingPadInst &Inst) {
495     // Exceptions come from "nowhere", from our analysis' perspective.
496     // So we place the instruction its own group, noting that said group may
497     // alias externals
498     Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
499   }
500
501   void visitInsertValueInst(InsertValueInst &Inst) {
502     auto *Agg = Inst.getOperand(0);
503     auto *Val = Inst.getOperand(1);
504     Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
505     Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
506   }
507
508   void visitExtractValueInst(ExtractValueInst &Inst) {
509     auto *Ptr = Inst.getAggregateOperand();
510     Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
511   }
512
513   void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
514     auto *From1 = Inst.getOperand(0);
515     auto *From2 = Inst.getOperand(1);
516     Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
517     Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
518   }
519 };
520
521 // For a given instruction, we need to know which Value* to get the
522 // users of in order to build our graph. In some cases (i.e. add),
523 // we simply need the Instruction*. In other cases (i.e. store),
524 // finding the users of the Instruction* is useless; we need to find
525 // the users of the first operand. This handles determining which
526 // value to follow for us.
527 //
528 // Note: we *need* to keep this in sync with GetEdgesVisitor. Add
529 // something to GetEdgesVisitor, add it here -- remove something from
530 // GetEdgesVisitor, remove it here.
531 class GetTargetValueVisitor
532     : public InstVisitor<GetTargetValueVisitor, Value *> {
533 public:
534   Value *visitInstruction(Instruction &Inst) { return &Inst; }
535
536   Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
537
538   Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
539     return Inst.getPointerOperand();
540   }
541
542   Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
543     return Inst.getPointerOperand();
544   }
545
546   Value *visitInsertElementInst(InsertElementInst &Inst) {
547     return Inst.getOperand(0);
548   }
549
550   Value *visitInsertValueInst(InsertValueInst &Inst) {
551     return Inst.getAggregateOperand();
552   }
553 };
554
555 // Set building requires a weighted bidirectional graph.
556 template <typename EdgeTypeT> class WeightedBidirectionalGraph {
557 public:
558   typedef std::size_t Node;
559
560 private:
561   const static Node StartNode = Node(0);
562
563   struct Edge {
564     EdgeTypeT Weight;
565     Node Other;
566
567     Edge(const EdgeTypeT &W, const Node &N)
568       : Weight(W), Other(N) {}
569
570     bool operator==(const Edge &E) const {
571       return Weight == E.Weight && Other == E.Other;
572     }
573
574     bool operator!=(const Edge &E) const { return !operator==(E); }
575   };
576
577   struct NodeImpl {
578     std::vector<Edge> Edges;
579   };
580
581   std::vector<NodeImpl> NodeImpls;
582
583   bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
584
585   const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
586   NodeImpl &getNode(Node N) { return NodeImpls[N]; }
587
588 public:
589   // ----- Various Edge iterators for the graph ----- //
590
591   // \brief Iterator for edges. Because this graph is bidirected, we don't
592   // allow modificaiton of the edges using this iterator. Additionally, the
593   // iterator becomes invalid if you add edges to or from the node you're
594   // getting the edges of.
595   struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
596                                              std::tuple<EdgeTypeT, Node *>> {
597     EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
598         : Current(Iter) {}
599
600     EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
601
602     EdgeIterator &operator++() {
603       ++Current;
604       return *this;
605     }
606
607     EdgeIterator operator++(int) {
608       EdgeIterator Copy(Current);
609       operator++();
610       return Copy;
611     }
612
613     std::tuple<EdgeTypeT, Node> &operator*() {
614       Store = std::make_tuple(Current->Weight, Current->Other);
615       return Store;
616     }
617
618     bool operator==(const EdgeIterator &Other) const {
619       return Current == Other.Current;
620     }
621
622     bool operator!=(const EdgeIterator &Other) const {
623       return !operator==(Other);
624     }
625
626   private:
627     typename std::vector<Edge>::const_iterator Current;
628     std::tuple<EdgeTypeT, Node> Store;
629   };
630
631   // Wrapper for EdgeIterator with begin()/end() calls.
632   struct EdgeIterable {
633     EdgeIterable(const std::vector<Edge> &Edges)
634         : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
635
636     EdgeIterator begin() { return EdgeIterator(BeginIter); }
637
638     EdgeIterator end() { return EdgeIterator(EndIter); }
639
640   private:
641     typename std::vector<Edge>::const_iterator BeginIter;
642     typename std::vector<Edge>::const_iterator EndIter;
643   };
644
645   // ----- Actual graph-related things ----- //
646
647   WeightedBidirectionalGraph() {}
648
649   WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
650       : NodeImpls(std::move(Other.NodeImpls)) {}
651
652   WeightedBidirectionalGraph<EdgeTypeT> &
653   operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
654     NodeImpls = std::move(Other.NodeImpls);
655     return *this;
656   }
657
658   Node addNode() {
659     auto Index = NodeImpls.size();
660     auto NewNode = Node(Index);
661     NodeImpls.push_back(NodeImpl());
662     return NewNode;
663   }
664
665   void addEdge(Node From, Node To, const EdgeTypeT &Weight,
666                const EdgeTypeT &ReverseWeight) {
667     assert(inbounds(From));
668     assert(inbounds(To));
669     auto &FromNode = getNode(From);
670     auto &ToNode = getNode(To);
671     FromNode.Edges.push_back(Edge(Weight, To));
672     ToNode.Edges.push_back(Edge(ReverseWeight, From));
673   }
674
675   EdgeIterable edgesFor(const Node &N) const {
676     const auto &Node = getNode(N);
677     return EdgeIterable(Node.Edges);
678   }
679
680   bool empty() const { return NodeImpls.empty(); }
681   std::size_t size() const { return NodeImpls.size(); }
682
683   // \brief Gets an arbitrary node in the graph as a starting point for
684   // traversal.
685   Node getEntryNode() {
686     assert(inbounds(StartNode));
687     return StartNode;
688   }
689 };
690
691 typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
692 typedef DenseMap<Value *, GraphT::Node> NodeMapT;
693 }
694
695 // -- Setting up/registering CFLAA pass -- //
696 char CFLAliasAnalysis::ID = 0;
697
698 INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
699                    "CFL-Based AA implementation", false, true, false)
700
701 ImmutablePass *llvm::createCFLAliasAnalysisPass() {
702   return new CFLAliasAnalysis();
703 }
704
705 //===----------------------------------------------------------------------===//
706 // Function declarations that require types defined in the namespace above
707 //===----------------------------------------------------------------------===//
708
709 // Given an argument number, returns the appropriate Attr index to set.
710 static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
711
712 // Given a Value, potentially return which AttrIndex it maps to.
713 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
714
715 // Gets the inverse of a given EdgeType.
716 static EdgeType flipWeight(EdgeType);
717
718 // Gets edges of the given Instruction*, writing them to the SmallVector*.
719 static void argsToEdges(CFLAliasAnalysis &, Instruction *,
720                         SmallVectorImpl<Edge> &);
721
722 // Gets the "Level" that one should travel in StratifiedSets
723 // given an EdgeType.
724 static Level directionOfEdgeType(EdgeType);
725
726 // Builds the graph needed for constructing the StratifiedSets for the
727 // given function
728 static void buildGraphFrom(CFLAliasAnalysis &, Function *,
729                            SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
730
731 // Builds the graph + StratifiedSets for a function.
732 static FunctionInfo buildSetsFrom(CFLAliasAnalysis &, Function *);
733
734 static Optional<Function *> parentFunctionOfValue(Value *Val) {
735   if (auto *Inst = dyn_cast<Instruction>(Val)) {
736     auto *Bb = Inst->getParent();
737     return Bb->getParent();
738   }
739
740   if (auto *Arg = dyn_cast<Argument>(Val))
741     return Arg->getParent();
742   return NoneType();
743 }
744
745 template <typename Inst>
746 static bool getPossibleTargets(Inst *Call,
747                                SmallVectorImpl<Function *> &Output) {
748   if (auto *Fn = Call->getCalledFunction()) {
749     Output.push_back(Fn);
750     return true;
751   }
752
753   // TODO: If the call is indirect, we might be able to enumerate all potential
754   // targets of the call and return them, rather than just failing.
755   return false;
756 }
757
758 static Optional<Value *> getTargetValue(Instruction *Inst) {
759   GetTargetValueVisitor V;
760   return V.visit(Inst);
761 }
762
763 static bool hasUsefulEdges(Instruction *Inst) {
764   bool IsNonInvokeTerminator =
765       isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
766   return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
767 }
768
769 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
770   if (isa<GlobalValue>(Val))
771     return AttrGlobalIndex;
772
773   if (auto *Arg = dyn_cast<Argument>(Val))
774     if (!Arg->hasNoAliasAttr())
775       return argNumberToAttrIndex(Arg->getArgNo());
776   return NoneType();
777 }
778
779 static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
780   if (ArgNum >= AttrMaxNumArgs)
781     return AttrAllIndex;
782   return ArgNum + AttrFirstArgIndex;
783 }
784
785 static EdgeType flipWeight(EdgeType Initial) {
786   switch (Initial) {
787   case EdgeType::Assign:
788     return EdgeType::Assign;
789   case EdgeType::Dereference:
790     return EdgeType::Reference;
791   case EdgeType::Reference:
792     return EdgeType::Dereference;
793   }
794   llvm_unreachable("Incomplete coverage of EdgeType enum");
795 }
796
797 static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
798                         SmallVectorImpl<Edge> &Output) {
799   GetEdgesVisitor v(Analysis, Output);
800   v.visit(Inst);
801 }
802
803 static Level directionOfEdgeType(EdgeType Weight) {
804   switch (Weight) {
805   case EdgeType::Reference:
806     return Level::Above;
807   case EdgeType::Dereference:
808     return Level::Below;
809   case EdgeType::Assign:
810     return Level::Same;
811   }
812   llvm_unreachable("Incomplete switch coverage");
813 }
814
815 // Aside: We may remove graph construction entirely, because it doesn't really
816 // buy us much that we don't already have. I'd like to add interprocedural
817 // analysis prior to this however, in case that somehow requires the graph
818 // produced by this for efficient execution
819 static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
820                            SmallVectorImpl<Value *> &ReturnedValues,
821                            NodeMapT &Map, GraphT &Graph) {
822   const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
823     auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
824     auto &Iter = Pair.first;
825     if (Pair.second) {
826       auto NewNode = Graph.addNode();
827       Iter->second = NewNode;
828     }
829     return Iter->second;
830   };
831
832   SmallVector<Edge, 8> Edges;
833   for (auto &Bb : Fn->getBasicBlockList()) {
834     for (auto &Inst : Bb.getInstList()) {
835       // We don't want the edges of most "return" instructions, but we *do* want
836       // to know what can be returned.
837       if (auto *Ret = dyn_cast<ReturnInst>(&Inst))
838         ReturnedValues.push_back(Ret);
839
840       if (!hasUsefulEdges(&Inst))
841         continue;
842
843       Edges.clear();
844       argsToEdges(Analysis, &Inst, Edges);
845
846       // In the case of an unused alloca (or similar), edges may be empty. Note
847       // that it exists so we can potentially answer NoAlias.
848       if (Edges.empty()) {
849         auto MaybeVal = getTargetValue(&Inst);
850         assert(MaybeVal.hasValue());
851         auto *Target = *MaybeVal;
852         findOrInsertNode(Target);
853         continue;
854       }
855
856       for (const Edge &E : Edges) {
857         auto To = findOrInsertNode(E.To);
858         auto From = findOrInsertNode(E.From);
859         auto FlippedWeight = flipWeight(E.Weight);
860         auto Attrs = E.AdditionalAttrs;
861         Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
862                                 std::make_pair(FlippedWeight, Attrs));
863       }
864     }
865   }
866 }
867
868 static FunctionInfo buildSetsFrom(CFLAliasAnalysis &Analysis, Function *Fn) {
869   NodeMapT Map;
870   GraphT Graph;
871   SmallVector<Value *, 4> ReturnedValues;
872
873   buildGraphFrom(Analysis, Fn, ReturnedValues, Map, Graph);
874
875   DenseMap<GraphT::Node, Value *> NodeValueMap;
876   NodeValueMap.resize(Map.size());
877   for (const auto &Pair : Map)
878     NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
879
880   const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
881     auto ValIter = NodeValueMap.find(Node);
882     assert(ValIter != NodeValueMap.end());
883     return ValIter->second;
884   };
885
886   StratifiedSetsBuilder<Value *> Builder;
887
888   SmallVector<GraphT::Node, 16> Worklist;
889   for (auto &Pair : Map) {
890     Worklist.clear();
891
892     auto *Value = Pair.first;
893     Builder.add(Value);
894     auto InitialNode = Pair.second;
895     Worklist.push_back(InitialNode);
896     while (!Worklist.empty()) {
897       auto Node = Worklist.pop_back_val();
898       auto *CurValue = findValueOrDie(Node);
899       if (isa<Constant>(CurValue) && !isa<GlobalValue>(CurValue))
900         continue;
901
902       for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
903         auto Weight = std::get<0>(EdgeTuple);
904         auto Label = Weight.first;
905         auto &OtherNode = std::get<1>(EdgeTuple);
906         auto *OtherValue = findValueOrDie(OtherNode);
907
908         if (isa<Constant>(OtherValue) && !isa<GlobalValue>(OtherValue))
909           continue;
910
911         bool Added;
912         switch (directionOfEdgeType(Label)) {
913         case Level::Above:
914           Added = Builder.addAbove(CurValue, OtherValue);
915           break;
916         case Level::Below:
917           Added = Builder.addBelow(CurValue, OtherValue);
918           break;
919         case Level::Same:
920           Added = Builder.addWith(CurValue, OtherValue);
921           break;
922         }
923
924         if (Added) {
925           auto Aliasing = Weight.second;
926           if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
927             Aliasing.set(*MaybeCurIndex);
928           if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
929             Aliasing.set(*MaybeOtherIndex);
930           Builder.noteAttributes(CurValue, Aliasing);
931           Builder.noteAttributes(OtherValue, Aliasing);
932           Worklist.push_back(OtherNode);
933         }
934       }
935     }
936   }
937
938   // There are times when we end up with parameters not in our graph (i.e. if
939   // it's only used as the condition of a branch). Other bits of code depend on
940   // things that were present during construction being present in the graph.
941   // So, we add all present arguments here.
942   for (auto &Arg : Fn->args()) {
943     Builder.add(&Arg);
944   }
945
946   return FunctionInfo(Builder.build(), std::move(ReturnedValues));
947 }
948
949 void CFLAliasAnalysis::scan(Function *Fn) {
950   auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
951   (void)InsertPair;
952   assert(InsertPair.second &&
953          "Trying to scan a function that has already been cached");
954
955   FunctionInfo Info(buildSetsFrom(*this, Fn));
956   Cache[Fn] = std::move(Info);
957   Handles.push_front(FunctionHandle(Fn, this));
958 }
959
960 AliasAnalysis::AliasResult
961 CFLAliasAnalysis::query(const AliasAnalysis::Location &LocA,
962                         const AliasAnalysis::Location &LocB) {
963   auto *ValA = const_cast<Value *>(LocA.Ptr);
964   auto *ValB = const_cast<Value *>(LocB.Ptr);
965
966   Function *Fn = nullptr;
967   auto MaybeFnA = parentFunctionOfValue(ValA);
968   auto MaybeFnB = parentFunctionOfValue(ValB);
969   if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
970     llvm_unreachable("Don't know how to extract the parent function "
971                      "from values A or B");
972   }
973
974   if (MaybeFnA.hasValue()) {
975     Fn = *MaybeFnA;
976     assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
977            "Interprocedural queries not supported");
978   } else {
979     Fn = *MaybeFnB;
980   }
981
982   assert(Fn != nullptr);
983   auto &MaybeInfo = ensureCached(Fn);
984   assert(MaybeInfo.hasValue());
985
986   auto &Sets = MaybeInfo->Sets;
987   auto MaybeA = Sets.find(ValA);
988   if (!MaybeA.hasValue())
989     return AliasAnalysis::MayAlias;
990
991   auto MaybeB = Sets.find(ValB);
992   if (!MaybeB.hasValue())
993     return AliasAnalysis::MayAlias;
994
995   auto SetA = *MaybeA;
996   auto SetB = *MaybeB;
997
998   if (SetA.Index == SetB.Index)
999     return AliasAnalysis::PartialAlias;
1000
1001   auto AttrsA = Sets.getLink(SetA.Index).Attrs;
1002   auto AttrsB = Sets.getLink(SetB.Index).Attrs;
1003   // Stratified set attributes are used as markets to signify whether a member
1004   // of a StratifiedSet (or a member of a set above the current set) has 
1005   // interacted with either arguments or globals. "Interacted with" meaning
1006   // its value may be different depending on the value of an argument or 
1007   // global. The thought behind this is that, because arguments and globals
1008   // may alias each other, if AttrsA and AttrsB have touched args/globals,
1009   // we must conservatively say that they alias. However, if at least one of 
1010   // the sets has no values that could legally be altered by changing the value 
1011   // of an argument or global, then we don't have to be as conservative.
1012   if (AttrsA.any() && AttrsB.any())
1013     return AliasAnalysis::MayAlias;
1014
1015   return AliasAnalysis::NoAlias;
1016 }