Fix incorrect partial aliasing
[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     // Condition is not processed here (The actual statement producing
302     // the condition result is processed elsewhere). For select, the
303     // condition is evaluated, but not loaded, stored, or assigned
304     // simply as a result of being the condition of a select.
305
306     auto *TrueVal = Inst.getTrueValue();
307     Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
308     auto *FalseVal = Inst.getFalseValue();
309     Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
310   }
311
312   void visitAllocaInst(AllocaInst &) {}
313
314   void visitLoadInst(LoadInst &Inst) {
315     auto *Ptr = Inst.getPointerOperand();
316     auto *Val = &Inst;
317     Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
318   }
319
320   void visitStoreInst(StoreInst &Inst) {
321     auto *Ptr = Inst.getPointerOperand();
322     auto *Val = Inst.getValueOperand();
323     Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
324   }
325
326   void visitVAArgInst(VAArgInst &Inst) {
327     // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
328     // two things:
329     //  1. Loads a value from *((T*)*Ptr).
330     //  2. Increments (stores to) *Ptr by some target-specific amount.
331     // For now, we'll handle this like a landingpad instruction (by placing the
332     // result in its own group, and having that group alias externals).
333     auto *Val = &Inst;
334     Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll));
335   }
336
337   static bool isFunctionExternal(Function *Fn) {
338     return Fn->isDeclaration() || !Fn->hasLocalLinkage();
339   }
340
341   // Gets whether the sets at Index1 above, below, or equal to the sets at
342   // Index2. Returns None if they are not in the same set chain.
343   static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
344                                           StratifiedIndex Index1,
345                                           StratifiedIndex Index2) {
346     if (Index1 == Index2)
347       return Level::Same;
348
349     const auto *Current = &Sets.getLink(Index1);
350     while (Current->hasBelow()) {
351       if (Current->Below == Index2)
352         return Level::Below;
353       Current = &Sets.getLink(Current->Below);
354     }
355
356     Current = &Sets.getLink(Index1);
357     while (Current->hasAbove()) {
358       if (Current->Above == Index2)
359         return Level::Above;
360       Current = &Sets.getLink(Current->Above);
361     }
362
363     return NoneType();
364   }
365
366   bool
367   tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
368                              Value *FuncValue,
369                              const iterator_range<User::op_iterator> &Args) {
370     const unsigned ExpectedMaxArgs = 8;
371     const unsigned MaxSupportedArgs = 50;
372     assert(Fns.size() > 0);
373
374     // I put this here to give us an upper bound on time taken by IPA. Is it
375     // really (realistically) needed? Keep in mind that we do have an n^2 algo.
376     if (std::distance(Args.begin(), Args.end()) > (int) MaxSupportedArgs)
377       return false;
378
379     // Exit early if we'll fail anyway
380     for (auto *Fn : Fns) {
381       if (isFunctionExternal(Fn) || Fn->isVarArg())
382         return false;
383       auto &MaybeInfo = AA.ensureCached(Fn);
384       if (!MaybeInfo.hasValue())
385         return false;
386     }
387
388     SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
389     SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
390     for (auto *Fn : Fns) {
391       auto &Info = *AA.ensureCached(Fn);
392       auto &Sets = Info.Sets;
393       auto &RetVals = Info.ReturnedValues;
394
395       Parameters.clear();
396       for (auto &Param : Fn->args()) {
397         auto MaybeInfo = Sets.find(&Param);
398         // Did a new parameter somehow get added to the function/slip by?
399         if (!MaybeInfo.hasValue())
400           return false;
401         Parameters.push_back(*MaybeInfo);
402       }
403
404       // Adding an edge from argument -> return value for each parameter that
405       // may alias the return value
406       for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
407         auto &ParamInfo = Parameters[I];
408         auto &ArgVal = Arguments[I];
409         bool AddEdge = false;
410         StratifiedAttrs Externals;
411         for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
412           auto MaybeInfo = Sets.find(RetVals[X]);
413           if (!MaybeInfo.hasValue())
414             return false;
415
416           auto &RetInfo = *MaybeInfo;
417           auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
418           auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
419           auto MaybeRelation =
420               getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
421           if (MaybeRelation.hasValue()) {
422             AddEdge = true;
423             Externals |= RetAttrs | ParamAttrs;
424           }
425         }
426         if (AddEdge)
427           Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
428                             StratifiedAttrs().flip()));
429       }
430
431       if (Parameters.size() != Arguments.size())
432         return false;
433
434       // Adding edges between arguments for arguments that may end up aliasing
435       // each other. This is necessary for functions such as
436       // void foo(int** a, int** b) { *a = *b; }
437       // (Technically, the proper sets for this would be those below
438       // Arguments[I] and Arguments[X], but our algorithm will produce
439       // extremely similar, and equally correct, results either way)
440       for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
441         auto &MainVal = Arguments[I];
442         auto &MainInfo = Parameters[I];
443         auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
444         for (unsigned X = I + 1; X != E; ++X) {
445           auto &SubInfo = Parameters[X];
446           auto &SubVal = Arguments[X];
447           auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
448           auto MaybeRelation =
449               getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
450
451           if (!MaybeRelation.hasValue())
452             continue;
453
454           auto NewAttrs = SubAttrs | MainAttrs;
455           Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
456         }
457       }
458     }
459     return true;
460   }
461
462   template <typename InstT> void visitCallLikeInst(InstT &Inst) {
463     SmallVector<Function *, 4> Targets;
464     if (getPossibleTargets(&Inst, Targets)) {
465       if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
466         return;
467       // Cleanup from interprocedural analysis
468       Output.clear();
469     }
470
471     for (Value *V : Inst.arg_operands())
472       Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
473   }
474
475   void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
476
477   void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
478
479   // Because vectors/aggregates are immutable and unaddressable,
480   // there's nothing we can do to coax a value out of them, other
481   // than calling Extract{Element,Value}. We can effectively treat
482   // them as pointers to arbitrary memory locations we can store in
483   // and load from.
484   void visitExtractElementInst(ExtractElementInst &Inst) {
485     auto *Ptr = Inst.getVectorOperand();
486     auto *Val = &Inst;
487     Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
488   }
489
490   void visitInsertElementInst(InsertElementInst &Inst) {
491     auto *Vec = Inst.getOperand(0);
492     auto *Val = Inst.getOperand(1);
493     Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
494     Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
495   }
496
497   void visitLandingPadInst(LandingPadInst &Inst) {
498     // Exceptions come from "nowhere", from our analysis' perspective.
499     // So we place the instruction its own group, noting that said group may
500     // alias externals
501     Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
502   }
503
504   void visitInsertValueInst(InsertValueInst &Inst) {
505     auto *Agg = Inst.getOperand(0);
506     auto *Val = Inst.getOperand(1);
507     Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
508     Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
509   }
510
511   void visitExtractValueInst(ExtractValueInst &Inst) {
512     auto *Ptr = Inst.getAggregateOperand();
513     Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
514   }
515
516   void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
517     auto *From1 = Inst.getOperand(0);
518     auto *From2 = Inst.getOperand(1);
519     Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
520     Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
521   }
522 };
523
524 // For a given instruction, we need to know which Value* to get the
525 // users of in order to build our graph. In some cases (i.e. add),
526 // we simply need the Instruction*. In other cases (i.e. store),
527 // finding the users of the Instruction* is useless; we need to find
528 // the users of the first operand. This handles determining which
529 // value to follow for us.
530 //
531 // Note: we *need* to keep this in sync with GetEdgesVisitor. Add
532 // something to GetEdgesVisitor, add it here -- remove something from
533 // GetEdgesVisitor, remove it here.
534 class GetTargetValueVisitor
535     : public InstVisitor<GetTargetValueVisitor, Value *> {
536 public:
537   Value *visitInstruction(Instruction &Inst) { return &Inst; }
538
539   Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
540
541   Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
542     return Inst.getPointerOperand();
543   }
544
545   Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
546     return Inst.getPointerOperand();
547   }
548
549   Value *visitInsertElementInst(InsertElementInst &Inst) {
550     return Inst.getOperand(0);
551   }
552
553   Value *visitInsertValueInst(InsertValueInst &Inst) {
554     return Inst.getAggregateOperand();
555   }
556 };
557
558 // Set building requires a weighted bidirectional graph.
559 template <typename EdgeTypeT> class WeightedBidirectionalGraph {
560 public:
561   typedef std::size_t Node;
562
563 private:
564   const static Node StartNode = Node(0);
565
566   struct Edge {
567     EdgeTypeT Weight;
568     Node Other;
569
570     Edge(const EdgeTypeT &W, const Node &N)
571       : Weight(W), Other(N) {}
572
573     bool operator==(const Edge &E) const {
574       return Weight == E.Weight && Other == E.Other;
575     }
576
577     bool operator!=(const Edge &E) const { return !operator==(E); }
578   };
579
580   struct NodeImpl {
581     std::vector<Edge> Edges;
582   };
583
584   std::vector<NodeImpl> NodeImpls;
585
586   bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
587
588   const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
589   NodeImpl &getNode(Node N) { return NodeImpls[N]; }
590
591 public:
592   // ----- Various Edge iterators for the graph ----- //
593
594   // \brief Iterator for edges. Because this graph is bidirected, we don't
595   // allow modificaiton of the edges using this iterator. Additionally, the
596   // iterator becomes invalid if you add edges to or from the node you're
597   // getting the edges of.
598   struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
599                                              std::tuple<EdgeTypeT, Node *>> {
600     EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
601         : Current(Iter) {}
602
603     EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
604
605     EdgeIterator &operator++() {
606       ++Current;
607       return *this;
608     }
609
610     EdgeIterator operator++(int) {
611       EdgeIterator Copy(Current);
612       operator++();
613       return Copy;
614     }
615
616     std::tuple<EdgeTypeT, Node> &operator*() {
617       Store = std::make_tuple(Current->Weight, Current->Other);
618       return Store;
619     }
620
621     bool operator==(const EdgeIterator &Other) const {
622       return Current == Other.Current;
623     }
624
625     bool operator!=(const EdgeIterator &Other) const {
626       return !operator==(Other);
627     }
628
629   private:
630     typename std::vector<Edge>::const_iterator Current;
631     std::tuple<EdgeTypeT, Node> Store;
632   };
633
634   // Wrapper for EdgeIterator with begin()/end() calls.
635   struct EdgeIterable {
636     EdgeIterable(const std::vector<Edge> &Edges)
637         : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
638
639     EdgeIterator begin() { return EdgeIterator(BeginIter); }
640
641     EdgeIterator end() { return EdgeIterator(EndIter); }
642
643   private:
644     typename std::vector<Edge>::const_iterator BeginIter;
645     typename std::vector<Edge>::const_iterator EndIter;
646   };
647
648   // ----- Actual graph-related things ----- //
649
650   WeightedBidirectionalGraph() {}
651
652   WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
653       : NodeImpls(std::move(Other.NodeImpls)) {}
654
655   WeightedBidirectionalGraph<EdgeTypeT> &
656   operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
657     NodeImpls = std::move(Other.NodeImpls);
658     return *this;
659   }
660
661   Node addNode() {
662     auto Index = NodeImpls.size();
663     auto NewNode = Node(Index);
664     NodeImpls.push_back(NodeImpl());
665     return NewNode;
666   }
667
668   void addEdge(Node From, Node To, const EdgeTypeT &Weight,
669                const EdgeTypeT &ReverseWeight) {
670     assert(inbounds(From));
671     assert(inbounds(To));
672     auto &FromNode = getNode(From);
673     auto &ToNode = getNode(To);
674     FromNode.Edges.push_back(Edge(Weight, To));
675     ToNode.Edges.push_back(Edge(ReverseWeight, From));
676   }
677
678   EdgeIterable edgesFor(const Node &N) const {
679     const auto &Node = getNode(N);
680     return EdgeIterable(Node.Edges);
681   }
682
683   bool empty() const { return NodeImpls.empty(); }
684   std::size_t size() const { return NodeImpls.size(); }
685
686   // \brief Gets an arbitrary node in the graph as a starting point for
687   // traversal.
688   Node getEntryNode() {
689     assert(inbounds(StartNode));
690     return StartNode;
691   }
692 };
693
694 typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
695 typedef DenseMap<Value *, GraphT::Node> NodeMapT;
696 }
697
698 // -- Setting up/registering CFLAA pass -- //
699 char CFLAliasAnalysis::ID = 0;
700
701 INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
702                    "CFL-Based AA implementation", false, true, false)
703
704 ImmutablePass *llvm::createCFLAliasAnalysisPass() {
705   return new CFLAliasAnalysis();
706 }
707
708 //===----------------------------------------------------------------------===//
709 // Function declarations that require types defined in the namespace above
710 //===----------------------------------------------------------------------===//
711
712 // Given an argument number, returns the appropriate Attr index to set.
713 static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
714
715 // Given a Value, potentially return which AttrIndex it maps to.
716 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
717
718 // Gets the inverse of a given EdgeType.
719 static EdgeType flipWeight(EdgeType);
720
721 // Gets edges of the given Instruction*, writing them to the SmallVector*.
722 static void argsToEdges(CFLAliasAnalysis &, Instruction *,
723                         SmallVectorImpl<Edge> &);
724
725 // Gets the "Level" that one should travel in StratifiedSets
726 // given an EdgeType.
727 static Level directionOfEdgeType(EdgeType);
728
729 // Builds the graph needed for constructing the StratifiedSets for the
730 // given function
731 static void buildGraphFrom(CFLAliasAnalysis &, Function *,
732                            SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
733
734 // Builds the graph + StratifiedSets for a function.
735 static FunctionInfo buildSetsFrom(CFLAliasAnalysis &, Function *);
736
737 static Optional<Function *> parentFunctionOfValue(Value *Val) {
738   if (auto *Inst = dyn_cast<Instruction>(Val)) {
739     auto *Bb = Inst->getParent();
740     return Bb->getParent();
741   }
742
743   if (auto *Arg = dyn_cast<Argument>(Val))
744     return Arg->getParent();
745   return NoneType();
746 }
747
748 template <typename Inst>
749 static bool getPossibleTargets(Inst *Call,
750                                SmallVectorImpl<Function *> &Output) {
751   if (auto *Fn = Call->getCalledFunction()) {
752     Output.push_back(Fn);
753     return true;
754   }
755
756   // TODO: If the call is indirect, we might be able to enumerate all potential
757   // targets of the call and return them, rather than just failing.
758   return false;
759 }
760
761 static Optional<Value *> getTargetValue(Instruction *Inst) {
762   GetTargetValueVisitor V;
763   return V.visit(Inst);
764 }
765
766 static bool hasUsefulEdges(Instruction *Inst) {
767   bool IsNonInvokeTerminator =
768       isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
769   return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
770 }
771
772 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
773   if (isa<GlobalValue>(Val))
774     return AttrGlobalIndex;
775
776   if (auto *Arg = dyn_cast<Argument>(Val))
777     // Only pointer arguments should have the argument attribute,
778     // because things can't escape through scalars without us seeing a
779     // cast, and thus, interaction with them doesn't matter.
780     if (!Arg->hasNoAliasAttr() && Arg->getType()->isPointerTy())
781       return argNumberToAttrIndex(Arg->getArgNo());
782   return NoneType();
783 }
784
785 static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
786   if (ArgNum >= AttrMaxNumArgs)
787     return AttrAllIndex;
788   return ArgNum + AttrFirstArgIndex;
789 }
790
791 static EdgeType flipWeight(EdgeType Initial) {
792   switch (Initial) {
793   case EdgeType::Assign:
794     return EdgeType::Assign;
795   case EdgeType::Dereference:
796     return EdgeType::Reference;
797   case EdgeType::Reference:
798     return EdgeType::Dereference;
799   }
800   llvm_unreachable("Incomplete coverage of EdgeType enum");
801 }
802
803 static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
804                         SmallVectorImpl<Edge> &Output) {
805   GetEdgesVisitor v(Analysis, Output);
806   v.visit(Inst);
807 }
808
809 static Level directionOfEdgeType(EdgeType Weight) {
810   switch (Weight) {
811   case EdgeType::Reference:
812     return Level::Above;
813   case EdgeType::Dereference:
814     return Level::Below;
815   case EdgeType::Assign:
816     return Level::Same;
817   }
818   llvm_unreachable("Incomplete switch coverage");
819 }
820
821 // Aside: We may remove graph construction entirely, because it doesn't really
822 // buy us much that we don't already have. I'd like to add interprocedural
823 // analysis prior to this however, in case that somehow requires the graph
824 // produced by this for efficient execution
825 static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
826                            SmallVectorImpl<Value *> &ReturnedValues,
827                            NodeMapT &Map, GraphT &Graph) {
828   const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
829     auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
830     auto &Iter = Pair.first;
831     if (Pair.second) {
832       auto NewNode = Graph.addNode();
833       Iter->second = NewNode;
834     }
835     return Iter->second;
836   };
837
838   SmallVector<Edge, 8> Edges;
839   for (auto &Bb : Fn->getBasicBlockList()) {
840     for (auto &Inst : Bb.getInstList()) {
841       // We don't want the edges of most "return" instructions, but we *do* want
842       // to know what can be returned.
843       if (auto *Ret = dyn_cast<ReturnInst>(&Inst))
844         ReturnedValues.push_back(Ret);
845
846       if (!hasUsefulEdges(&Inst))
847         continue;
848
849       Edges.clear();
850       argsToEdges(Analysis, &Inst, Edges);
851
852       // In the case of an unused alloca (or similar), edges may be empty. Note
853       // that it exists so we can potentially answer NoAlias.
854       if (Edges.empty()) {
855         auto MaybeVal = getTargetValue(&Inst);
856         assert(MaybeVal.hasValue());
857         auto *Target = *MaybeVal;
858         findOrInsertNode(Target);
859         continue;
860       }
861
862       for (const Edge &E : Edges) {
863         auto To = findOrInsertNode(E.To);
864         auto From = findOrInsertNode(E.From);
865         auto FlippedWeight = flipWeight(E.Weight);
866         auto Attrs = E.AdditionalAttrs;
867         Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
868                                 std::make_pair(FlippedWeight, Attrs));
869       }
870     }
871   }
872 }
873
874 static FunctionInfo buildSetsFrom(CFLAliasAnalysis &Analysis, Function *Fn) {
875   NodeMapT Map;
876   GraphT Graph;
877   SmallVector<Value *, 4> ReturnedValues;
878
879   buildGraphFrom(Analysis, Fn, ReturnedValues, Map, Graph);
880
881   DenseMap<GraphT::Node, Value *> NodeValueMap;
882   NodeValueMap.resize(Map.size());
883   for (const auto &Pair : Map)
884     NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
885
886   const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
887     auto ValIter = NodeValueMap.find(Node);
888     assert(ValIter != NodeValueMap.end());
889     return ValIter->second;
890   };
891
892   StratifiedSetsBuilder<Value *> Builder;
893
894   SmallVector<GraphT::Node, 16> Worklist;
895   for (auto &Pair : Map) {
896     Worklist.clear();
897
898     auto *Value = Pair.first;
899     Builder.add(Value);
900     auto InitialNode = Pair.second;
901     Worklist.push_back(InitialNode);
902     while (!Worklist.empty()) {
903       auto Node = Worklist.pop_back_val();
904       auto *CurValue = findValueOrDie(Node);
905       if (isa<Constant>(CurValue) && !isa<GlobalValue>(CurValue))
906         continue;
907
908       for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
909         auto Weight = std::get<0>(EdgeTuple);
910         auto Label = Weight.first;
911         auto &OtherNode = std::get<1>(EdgeTuple);
912         auto *OtherValue = findValueOrDie(OtherNode);
913
914         if (isa<Constant>(OtherValue) && !isa<GlobalValue>(OtherValue))
915           continue;
916
917         bool Added;
918         switch (directionOfEdgeType(Label)) {
919         case Level::Above:
920           Added = Builder.addAbove(CurValue, OtherValue);
921           break;
922         case Level::Below:
923           Added = Builder.addBelow(CurValue, OtherValue);
924           break;
925         case Level::Same:
926           Added = Builder.addWith(CurValue, OtherValue);
927           break;
928         }
929
930         if (Added) {
931           auto Aliasing = Weight.second;
932           if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
933             Aliasing.set(*MaybeCurIndex);
934           if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
935             Aliasing.set(*MaybeOtherIndex);
936           Builder.noteAttributes(CurValue, Aliasing);
937           Builder.noteAttributes(OtherValue, Aliasing);
938           Worklist.push_back(OtherNode);
939         }
940       }
941     }
942   }
943
944   // There are times when we end up with parameters not in our graph (i.e. if
945   // it's only used as the condition of a branch). Other bits of code depend on
946   // things that were present during construction being present in the graph.
947   // So, we add all present arguments here.
948   for (auto &Arg : Fn->args()) {
949     Builder.add(&Arg);
950   }
951
952   return FunctionInfo(Builder.build(), std::move(ReturnedValues));
953 }
954
955 void CFLAliasAnalysis::scan(Function *Fn) {
956   auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
957   (void)InsertPair;
958   assert(InsertPair.second &&
959          "Trying to scan a function that has already been cached");
960
961   FunctionInfo Info(buildSetsFrom(*this, Fn));
962   Cache[Fn] = std::move(Info);
963   Handles.push_front(FunctionHandle(Fn, this));
964 }
965
966 AliasAnalysis::AliasResult
967 CFLAliasAnalysis::query(const AliasAnalysis::Location &LocA,
968                         const AliasAnalysis::Location &LocB) {
969   auto *ValA = const_cast<Value *>(LocA.Ptr);
970   auto *ValB = const_cast<Value *>(LocB.Ptr);
971
972   Function *Fn = nullptr;
973   auto MaybeFnA = parentFunctionOfValue(ValA);
974   auto MaybeFnB = parentFunctionOfValue(ValB);
975   if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
976     llvm_unreachable("Don't know how to extract the parent function "
977                      "from values A or B");
978   }
979
980   if (MaybeFnA.hasValue()) {
981     Fn = *MaybeFnA;
982     assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
983            "Interprocedural queries not supported");
984   } else {
985     Fn = *MaybeFnB;
986   }
987
988   assert(Fn != nullptr);
989   auto &MaybeInfo = ensureCached(Fn);
990   assert(MaybeInfo.hasValue());
991
992   auto &Sets = MaybeInfo->Sets;
993   auto MaybeA = Sets.find(ValA);
994   if (!MaybeA.hasValue())
995     return AliasAnalysis::MayAlias;
996
997   auto MaybeB = Sets.find(ValB);
998   if (!MaybeB.hasValue())
999     return AliasAnalysis::MayAlias;
1000
1001   auto SetA = *MaybeA;
1002   auto SetB = *MaybeB;
1003   auto AttrsA = Sets.getLink(SetA.Index).Attrs;
1004   auto AttrsB = Sets.getLink(SetB.Index).Attrs;
1005   // Stratified set attributes are used as markets to signify whether a member
1006   // of a StratifiedSet (or a member of a set above the current set) has 
1007   // interacted with either arguments or globals. "Interacted with" meaning
1008   // its value may be different depending on the value of an argument or 
1009   // global. The thought behind this is that, because arguments and globals
1010   // may alias each other, if AttrsA and AttrsB have touched args/globals,
1011   // we must conservatively say that they alias. However, if at least one of 
1012   // the sets has no values that could legally be altered by changing the value 
1013   // of an argument or global, then we don't have to be as conservative.
1014   if (AttrsA.any() && AttrsB.any())
1015     return AliasAnalysis::MayAlias;
1016
1017   // We currently unify things even if the accesses to them may not be in
1018   // bounds, so we can't return partial alias here because we don't
1019   // know whether the pointer is really within the object or not.
1020   // IE Given an out of bounds GEP and an alloca'd pointer, we may
1021   // unify the two. We can't return partial alias for this case.
1022   // Since we do not currently track enough information to
1023   // differentiate
1024
1025   if (SetA.Index == SetB.Index)
1026     return AliasAnalysis::MayAlias;
1027
1028   return AliasAnalysis::NoAlias;
1029 }