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