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