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