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