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