1 //===- CFLAliasAnalysis.cpp - CFL-Based Alias Analysis Implementation ------==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a CFL-based context-insensitive alias analysis
11 // algorithm. It does not depend on types. The algorithm is a mixture of the one
12 // described in "Demand-driven alias analysis for C" by Xin Zheng and Radu
13 // Rugina, and "Fast algorithms for Dyck-CFL-reachability with applications to
14 // Alias Analysis" by Zhang Q, Lyu M R, Yuan H, and Su Z. -- to summarize the
15 // papers, we build a graph of the uses of a variable, where each node is a
16 // memory location, and each edge is an action that happened on that memory
17 // location. The "actions" can be one of Dereference, Reference, Assign, or
20 // Two variables are considered as aliasing iff you can reach one value's node
21 // from the other value's node and the language formed by concatenating all of
22 // the edge labels (actions) conforms to a context-free grammar.
24 // Because this algorithm requires a graph search on each query, we execute the
25 // algorithm outlined in "Fast algorithms..." (mentioned above)
26 // in order to transform the graph into sets of variables that may alias in
27 // ~nlogn time (n = number of variables.), which makes queries take constant
29 //===----------------------------------------------------------------------===//
31 #include "StratifiedSets.h"
32 #include "llvm/ADT/BitVector.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/None.h"
35 #include "llvm/ADT/Optional.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/Analysis/Passes.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/InstVisitor.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/ValueHandle.h"
43 #include "llvm/Pass.h"
44 #include "llvm/Support/Allocator.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/ErrorHandling.h"
49 #include <forward_list>
54 // Try to go from a Value* to a Function*. Never returns nullptr.
55 static Optional<Function *> parentFunctionOfValue(Value *);
57 // Returns possible functions called by the Inst* into the given
58 // SmallVectorImpl. Returns true if targets found, false otherwise.
59 // This is templated because InvokeInst/CallInst give us the same
60 // set of functions that we care about, and I don't like repeating
62 template <typename Inst>
63 static bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &);
65 // Some instructions need to have their users tracked. Instructions like
66 // `add` require you to get the users of the Instruction* itself, other
67 // instructions like `store` require you to get the users of the first
68 // operand. This function gets the "proper" value to track for each
69 // type of instruction we support.
70 static Optional<Value *> getTargetValue(Instruction *);
72 // There are certain instructions (i.e. FenceInst, etc.) that we ignore.
73 // This notes that we should ignore those.
74 static bool hasUsefulEdges(Instruction *);
76 const StratifiedIndex StratifiedLink::SetSentinel =
77 std::numeric_limits<StratifiedIndex>::max();
80 // StratifiedInfo Attribute things.
81 typedef unsigned StratifiedAttr;
82 LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
83 LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
84 LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
85 LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 2;
86 LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
87 LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
89 LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
90 LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
92 // \brief StratifiedSets call for knowledge of "direction", so this is how we
93 // represent that locally.
94 enum class Level { Same, Above, Below };
96 // \brief Edges can be one of four "weights" -- each weight must have an inverse
97 // weight (Assign has Assign; Reference has Dereference).
99 // The weight assigned when assigning from or to a value. For example, in:
100 // %b = getelementptr %a, 0
101 // ...The relationships are %b assign %a, and %a assign %b. This used to be
102 // two edges, but having a distinction bought us nothing.
105 // The edge used when we have an edge going from some handle to a Value.
106 // Examples of this include:
107 // %b = load %a (%b Dereference %a)
108 // %b = extractelement %a, 0 (%a Dereference %b)
111 // The edge used when our edge goes from a value to a handle that may have
112 // contained it at some point. Examples:
113 // %b = load %a (%a Reference %b)
114 // %b = extractelement %a, 0 (%b Reference %a)
118 // \brief Encodes the notion of a "use"
120 // \brief Which value the edge is coming from
123 // \brief Which value the edge is pointing to
126 // \brief Edge weight
129 // \brief Whether we aliased any external values along the way that may be
130 // invisible to the analysis (i.e. landingpad for exceptions, calls for
131 // interprocedural analysis, etc.)
132 StratifiedAttrs AdditionalAttrs;
134 Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
135 : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
138 // \brief Information we have about a function and would like to keep around
139 struct FunctionInfo {
140 StratifiedSets<Value *> Sets;
141 // Lots of functions have < 4 returns. Adjust as necessary.
142 SmallVector<Value *, 4> ReturnedValues;
144 FunctionInfo(StratifiedSets<Value *> &&S,
145 SmallVector<Value *, 4> &&RV)
146 : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
149 struct CFLAliasAnalysis;
151 struct FunctionHandle : public CallbackVH {
152 FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
153 : CallbackVH(Fn), CFLAA(CFLAA) {
154 assert(Fn != nullptr);
155 assert(CFLAA != nullptr);
158 virtual ~FunctionHandle() {}
160 void deleted() override { removeSelfFromCache(); }
161 void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
164 CFLAliasAnalysis *CFLAA;
166 void removeSelfFromCache();
169 struct CFLAliasAnalysis : public ImmutablePass, public AliasAnalysis {
171 /// \brief Cached mapping of Functions to their StratifiedSets.
172 /// If a function's sets are currently being built, it is marked
173 /// in the cache as an Optional without a value. This way, if we
174 /// have any kind of recursion, it is discernable from a function
175 /// that simply has empty sets.
176 DenseMap<Function *, Optional<FunctionInfo>> Cache;
177 std::forward_list<FunctionHandle> Handles;
182 CFLAliasAnalysis() : ImmutablePass(ID) {
183 initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
186 virtual ~CFLAliasAnalysis() {}
188 void getAnalysisUsage(AnalysisUsage &AU) const override {
189 AliasAnalysis::getAnalysisUsage(AU);
192 void *getAdjustedAnalysisPointer(const void *ID) override {
193 if (ID == &AliasAnalysis::ID)
194 return (AliasAnalysis *)this;
198 /// \brief Inserts the given Function into the cache.
199 void scan(Function *Fn);
201 void evict(Function *Fn) { Cache.erase(Fn); }
203 /// \brief Ensures that the given function is available in the cache.
204 /// Returns the appropriate entry from the cache.
205 const Optional<FunctionInfo> &ensureCached(Function *Fn) {
206 auto Iter = Cache.find(Fn);
207 if (Iter == Cache.end()) {
209 Iter = Cache.find(Fn);
210 assert(Iter != Cache.end());
211 assert(Iter->second.hasValue());
216 AliasResult query(const Location &LocA, const Location &LocB);
218 AliasResult alias(const Location &LocA, const Location &LocB) override {
219 if (LocA.Ptr == LocB.Ptr) {
220 if (LocA.Size == LocB.Size) {
227 // Comparisons between global variables and other constants should be
228 // handled by BasicAA.
229 if (isa<Constant>(LocA.Ptr) && isa<Constant>(LocB.Ptr)) {
230 return AliasAnalysis::alias(LocA, LocB);
232 AliasResult QueryResult = query(LocA, LocB);
233 if (QueryResult == MayAlias)
234 return AliasAnalysis::alias(LocA, LocB);
239 void initializePass() override { InitializeAliasAnalysis(this); }
242 void FunctionHandle::removeSelfFromCache() {
243 assert(CFLAA != nullptr);
244 auto *Val = getValPtr();
245 CFLAA->evict(cast<Function>(Val));
249 // \brief Gets the edges our graph should have, based on an Instruction*
250 class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
251 CFLAliasAnalysis &AA;
252 SmallVectorImpl<Edge> &Output;
255 GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
256 : AA(AA), Output(Output) {}
258 void visitInstruction(Instruction &) {
259 llvm_unreachable("Unsupported instruction encountered");
262 void visitCastInst(CastInst &Inst) {
263 Output.push_back(Edge(&Inst, Inst.getOperand(0), EdgeType::Assign,
267 void visitBinaryOperator(BinaryOperator &Inst) {
268 auto *Op1 = Inst.getOperand(0);
269 auto *Op2 = Inst.getOperand(1);
270 Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
271 Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
274 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
275 auto *Ptr = Inst.getPointerOperand();
276 auto *Val = Inst.getNewValOperand();
277 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
280 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
281 auto *Ptr = Inst.getPointerOperand();
282 auto *Val = Inst.getValOperand();
283 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
286 void visitPHINode(PHINode &Inst) {
287 for (unsigned I = 0, E = Inst.getNumIncomingValues(); I != E; ++I) {
288 Value *Val = Inst.getIncomingValue(I);
289 Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
293 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
294 auto *Op = Inst.getPointerOperand();
295 Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
296 for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
297 Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
300 void visitSelectInst(SelectInst &Inst) {
301 auto *Condition = Inst.getCondition();
302 Output.push_back(Edge(&Inst, Condition, EdgeType::Assign, AttrNone));
303 auto *TrueVal = Inst.getTrueValue();
304 Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
305 auto *FalseVal = Inst.getFalseValue();
306 Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
309 void visitAllocaInst(AllocaInst &) {}
311 void visitLoadInst(LoadInst &Inst) {
312 auto *Ptr = Inst.getPointerOperand();
314 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
317 void visitStoreInst(StoreInst &Inst) {
318 auto *Ptr = Inst.getPointerOperand();
319 auto *Val = Inst.getValueOperand();
320 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
323 void visitVAArgInst(VAArgInst &Inst) {
324 // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
326 // 1. Loads a value from *((T*)*Ptr).
327 // 2. Increments (stores to) *Ptr by some target-specific amount.
328 // For now, we'll handle this like a landingpad instruction (by placing the
329 // result in its own group, and having that group alias externals).
331 Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll));
334 static bool isFunctionExternal(Function *Fn) {
335 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
338 // Gets whether the sets at Index1 above, below, or equal to the sets at
339 // Index2. Returns None if they are not in the same set chain.
340 static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
341 StratifiedIndex Index1,
342 StratifiedIndex Index2) {
343 if (Index1 == Index2)
346 const auto *Current = &Sets.getLink(Index1);
347 while (Current->hasBelow()) {
348 if (Current->Below == Index2)
350 Current = &Sets.getLink(Current->Below);
353 Current = &Sets.getLink(Index1);
354 while (Current->hasAbove()) {
355 if (Current->Above == Index2)
357 Current = &Sets.getLink(Current->Above);
364 tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
366 const iterator_range<User::op_iterator> &Args) {
367 const unsigned ExpectedMaxArgs = 8;
368 const unsigned MaxSupportedArgs = 50;
369 assert(Fns.size() > 0);
371 // I put this here to give us an upper bound on time taken by IPA. Is it
372 // really (realistically) needed? Keep in mind that we do have an n^2 algo.
373 if (std::distance(Args.begin(), Args.end()) > (int) MaxSupportedArgs)
376 // Exit early if we'll fail anyway
377 for (auto *Fn : Fns) {
378 if (isFunctionExternal(Fn) || Fn->isVarArg())
380 auto &MaybeInfo = AA.ensureCached(Fn);
381 if (!MaybeInfo.hasValue())
385 SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
386 SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
387 for (auto *Fn : Fns) {
388 auto &Info = *AA.ensureCached(Fn);
389 auto &Sets = Info.Sets;
390 auto &RetVals = Info.ReturnedValues;
393 for (auto &Param : Fn->args()) {
394 auto MaybeInfo = Sets.find(&Param);
395 // Did a new parameter somehow get added to the function/slip by?
396 if (!MaybeInfo.hasValue())
398 Parameters.push_back(*MaybeInfo);
401 // Adding an edge from argument -> return value for each parameter that
402 // may alias the return value
403 for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
404 auto &ParamInfo = Parameters[I];
405 auto &ArgVal = Arguments[I];
406 bool AddEdge = false;
407 StratifiedAttrs Externals;
408 for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
409 auto MaybeInfo = Sets.find(RetVals[X]);
410 if (!MaybeInfo.hasValue())
413 auto &RetInfo = *MaybeInfo;
414 auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
415 auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
417 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
418 if (MaybeRelation.hasValue()) {
420 Externals |= RetAttrs | ParamAttrs;
424 Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
425 StratifiedAttrs().flip()));
428 if (Parameters.size() != Arguments.size())
431 // Adding edges between arguments for arguments that may end up aliasing
432 // each other. This is necessary for functions such as
433 // void foo(int** a, int** b) { *a = *b; }
434 // (Technically, the proper sets for this would be those below
435 // Arguments[I] and Arguments[X], but our algorithm will produce
436 // extremely similar, and equally correct, results either way)
437 for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
438 auto &MainVal = Arguments[I];
439 auto &MainInfo = Parameters[I];
440 auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
441 for (unsigned X = I + 1; X != E; ++X) {
442 auto &SubInfo = Parameters[X];
443 auto &SubVal = Arguments[X];
444 auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
446 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
448 if (!MaybeRelation.hasValue())
451 auto NewAttrs = SubAttrs | MainAttrs;
452 Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
459 template <typename InstT> void visitCallLikeInst(InstT &Inst) {
460 SmallVector<Function *, 4> Targets;
461 if (getPossibleTargets(&Inst, Targets)) {
462 if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
464 // Cleanup from interprocedural analysis
468 for (Value *V : Inst.arg_operands())
469 Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
472 void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
474 void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
476 // Because vectors/aggregates are immutable and unaddressable,
477 // there's nothing we can do to coax a value out of them, other
478 // than calling Extract{Element,Value}. We can effectively treat
479 // them as pointers to arbitrary memory locations we can store in
481 void visitExtractElementInst(ExtractElementInst &Inst) {
482 auto *Ptr = Inst.getVectorOperand();
484 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
487 void visitInsertElementInst(InsertElementInst &Inst) {
488 auto *Vec = Inst.getOperand(0);
489 auto *Val = Inst.getOperand(1);
490 Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
491 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
494 void visitLandingPadInst(LandingPadInst &Inst) {
495 // Exceptions come from "nowhere", from our analysis' perspective.
496 // So we place the instruction its own group, noting that said group may
498 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
501 void visitInsertValueInst(InsertValueInst &Inst) {
502 auto *Agg = Inst.getOperand(0);
503 auto *Val = Inst.getOperand(1);
504 Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
505 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
508 void visitExtractValueInst(ExtractValueInst &Inst) {
509 auto *Ptr = Inst.getAggregateOperand();
510 Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
513 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
514 auto *From1 = Inst.getOperand(0);
515 auto *From2 = Inst.getOperand(1);
516 Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
517 Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
521 // For a given instruction, we need to know which Value* to get the
522 // users of in order to build our graph. In some cases (i.e. add),
523 // we simply need the Instruction*. In other cases (i.e. store),
524 // finding the users of the Instruction* is useless; we need to find
525 // the users of the first operand. This handles determining which
526 // value to follow for us.
528 // Note: we *need* to keep this in sync with GetEdgesVisitor. Add
529 // something to GetEdgesVisitor, add it here -- remove something from
530 // GetEdgesVisitor, remove it here.
531 class GetTargetValueVisitor
532 : public InstVisitor<GetTargetValueVisitor, Value *> {
534 Value *visitInstruction(Instruction &Inst) { return &Inst; }
536 Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
538 Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
539 return Inst.getPointerOperand();
542 Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
543 return Inst.getPointerOperand();
546 Value *visitInsertElementInst(InsertElementInst &Inst) {
547 return Inst.getOperand(0);
550 Value *visitInsertValueInst(InsertValueInst &Inst) {
551 return Inst.getAggregateOperand();
555 // Set building requires a weighted bidirectional graph.
556 template <typename EdgeTypeT> class WeightedBidirectionalGraph {
558 typedef std::size_t Node;
561 const static Node StartNode = Node(0);
567 Edge(const EdgeTypeT &W, const Node &N)
568 : Weight(W), Other(N) {}
570 bool operator==(const Edge &E) const {
571 return Weight == E.Weight && Other == E.Other;
574 bool operator!=(const Edge &E) const { return !operator==(E); }
578 std::vector<Edge> Edges;
581 std::vector<NodeImpl> NodeImpls;
583 bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
585 const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
586 NodeImpl &getNode(Node N) { return NodeImpls[N]; }
589 // ----- Various Edge iterators for the graph ----- //
591 // \brief Iterator for edges. Because this graph is bidirected, we don't
592 // allow modificaiton of the edges using this iterator. Additionally, the
593 // iterator becomes invalid if you add edges to or from the node you're
594 // getting the edges of.
595 struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
596 std::tuple<EdgeTypeT, Node *>> {
597 EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
600 EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
602 EdgeIterator &operator++() {
607 EdgeIterator operator++(int) {
608 EdgeIterator Copy(Current);
613 std::tuple<EdgeTypeT, Node> &operator*() {
614 Store = std::make_tuple(Current->Weight, Current->Other);
618 bool operator==(const EdgeIterator &Other) const {
619 return Current == Other.Current;
622 bool operator!=(const EdgeIterator &Other) const {
623 return !operator==(Other);
627 typename std::vector<Edge>::const_iterator Current;
628 std::tuple<EdgeTypeT, Node> Store;
631 // Wrapper for EdgeIterator with begin()/end() calls.
632 struct EdgeIterable {
633 EdgeIterable(const std::vector<Edge> &Edges)
634 : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
636 EdgeIterator begin() { return EdgeIterator(BeginIter); }
638 EdgeIterator end() { return EdgeIterator(EndIter); }
641 typename std::vector<Edge>::const_iterator BeginIter;
642 typename std::vector<Edge>::const_iterator EndIter;
645 // ----- Actual graph-related things ----- //
647 WeightedBidirectionalGraph() {}
649 WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
650 : NodeImpls(std::move(Other.NodeImpls)) {}
652 WeightedBidirectionalGraph<EdgeTypeT> &
653 operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
654 NodeImpls = std::move(Other.NodeImpls);
659 auto Index = NodeImpls.size();
660 auto NewNode = Node(Index);
661 NodeImpls.push_back(NodeImpl());
665 void addEdge(Node From, Node To, const EdgeTypeT &Weight,
666 const EdgeTypeT &ReverseWeight) {
667 assert(inbounds(From));
668 assert(inbounds(To));
669 auto &FromNode = getNode(From);
670 auto &ToNode = getNode(To);
671 FromNode.Edges.push_back(Edge(Weight, To));
672 ToNode.Edges.push_back(Edge(ReverseWeight, From));
675 EdgeIterable edgesFor(const Node &N) const {
676 const auto &Node = getNode(N);
677 return EdgeIterable(Node.Edges);
680 bool empty() const { return NodeImpls.empty(); }
681 std::size_t size() const { return NodeImpls.size(); }
683 // \brief Gets an arbitrary node in the graph as a starting point for
685 Node getEntryNode() {
686 assert(inbounds(StartNode));
691 typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
692 typedef DenseMap<Value *, GraphT::Node> NodeMapT;
695 // -- Setting up/registering CFLAA pass -- //
696 char CFLAliasAnalysis::ID = 0;
698 INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
699 "CFL-Based AA implementation", false, true, false)
701 ImmutablePass *llvm::createCFLAliasAnalysisPass() {
702 return new CFLAliasAnalysis();
705 //===----------------------------------------------------------------------===//
706 // Function declarations that require types defined in the namespace above
707 //===----------------------------------------------------------------------===//
709 // Given an argument number, returns the appropriate Attr index to set.
710 static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
712 // Given a Value, potentially return which AttrIndex it maps to.
713 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
715 // Gets the inverse of a given EdgeType.
716 static EdgeType flipWeight(EdgeType);
718 // Gets edges of the given Instruction*, writing them to the SmallVector*.
719 static void argsToEdges(CFLAliasAnalysis &, Instruction *,
720 SmallVectorImpl<Edge> &);
722 // Gets the "Level" that one should travel in StratifiedSets
723 // given an EdgeType.
724 static Level directionOfEdgeType(EdgeType);
726 // Builds the graph needed for constructing the StratifiedSets for the
728 static void buildGraphFrom(CFLAliasAnalysis &, Function *,
729 SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
731 // Builds the graph + StratifiedSets for a function.
732 static FunctionInfo buildSetsFrom(CFLAliasAnalysis &, Function *);
734 static Optional<Function *> parentFunctionOfValue(Value *Val) {
735 if (auto *Inst = dyn_cast<Instruction>(Val)) {
736 auto *Bb = Inst->getParent();
737 return Bb->getParent();
740 if (auto *Arg = dyn_cast<Argument>(Val))
741 return Arg->getParent();
745 template <typename Inst>
746 static bool getPossibleTargets(Inst *Call,
747 SmallVectorImpl<Function *> &Output) {
748 if (auto *Fn = Call->getCalledFunction()) {
749 Output.push_back(Fn);
753 // TODO: If the call is indirect, we might be able to enumerate all potential
754 // targets of the call and return them, rather than just failing.
758 static Optional<Value *> getTargetValue(Instruction *Inst) {
759 GetTargetValueVisitor V;
760 return V.visit(Inst);
763 static bool hasUsefulEdges(Instruction *Inst) {
764 bool IsNonInvokeTerminator =
765 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
766 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
769 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
770 if (isa<GlobalValue>(Val))
771 return AttrGlobalIndex;
773 if (auto *Arg = dyn_cast<Argument>(Val))
774 if (!Arg->hasNoAliasAttr())
775 return argNumberToAttrIndex(Arg->getArgNo());
779 static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
780 if (ArgNum >= AttrMaxNumArgs)
782 return ArgNum + AttrFirstArgIndex;
785 static EdgeType flipWeight(EdgeType Initial) {
787 case EdgeType::Assign:
788 return EdgeType::Assign;
789 case EdgeType::Dereference:
790 return EdgeType::Reference;
791 case EdgeType::Reference:
792 return EdgeType::Dereference;
794 llvm_unreachable("Incomplete coverage of EdgeType enum");
797 static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
798 SmallVectorImpl<Edge> &Output) {
799 GetEdgesVisitor v(Analysis, Output);
803 static Level directionOfEdgeType(EdgeType Weight) {
805 case EdgeType::Reference:
807 case EdgeType::Dereference:
809 case EdgeType::Assign:
812 llvm_unreachable("Incomplete switch coverage");
815 // Aside: We may remove graph construction entirely, because it doesn't really
816 // buy us much that we don't already have. I'd like to add interprocedural
817 // analysis prior to this however, in case that somehow requires the graph
818 // produced by this for efficient execution
819 static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
820 SmallVectorImpl<Value *> &ReturnedValues,
821 NodeMapT &Map, GraphT &Graph) {
822 const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
823 auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
824 auto &Iter = Pair.first;
826 auto NewNode = Graph.addNode();
827 Iter->second = NewNode;
832 SmallVector<Edge, 8> Edges;
833 for (auto &Bb : Fn->getBasicBlockList()) {
834 for (auto &Inst : Bb.getInstList()) {
835 // We don't want the edges of most "return" instructions, but we *do* want
836 // to know what can be returned.
837 if (auto *Ret = dyn_cast<ReturnInst>(&Inst))
838 ReturnedValues.push_back(Ret);
840 if (!hasUsefulEdges(&Inst))
844 argsToEdges(Analysis, &Inst, Edges);
846 // In the case of an unused alloca (or similar), edges may be empty. Note
847 // that it exists so we can potentially answer NoAlias.
849 auto MaybeVal = getTargetValue(&Inst);
850 assert(MaybeVal.hasValue());
851 auto *Target = *MaybeVal;
852 findOrInsertNode(Target);
856 for (const Edge &E : Edges) {
857 auto To = findOrInsertNode(E.To);
858 auto From = findOrInsertNode(E.From);
859 auto FlippedWeight = flipWeight(E.Weight);
860 auto Attrs = E.AdditionalAttrs;
861 Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
862 std::make_pair(FlippedWeight, Attrs));
868 static FunctionInfo buildSetsFrom(CFLAliasAnalysis &Analysis, Function *Fn) {
871 SmallVector<Value *, 4> ReturnedValues;
873 buildGraphFrom(Analysis, Fn, ReturnedValues, Map, Graph);
875 DenseMap<GraphT::Node, Value *> NodeValueMap;
876 NodeValueMap.resize(Map.size());
877 for (const auto &Pair : Map)
878 NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
880 const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
881 auto ValIter = NodeValueMap.find(Node);
882 assert(ValIter != NodeValueMap.end());
883 return ValIter->second;
886 StratifiedSetsBuilder<Value *> Builder;
888 SmallVector<GraphT::Node, 16> Worklist;
889 for (auto &Pair : Map) {
892 auto *Value = Pair.first;
894 auto InitialNode = Pair.second;
895 Worklist.push_back(InitialNode);
896 while (!Worklist.empty()) {
897 auto Node = Worklist.pop_back_val();
898 auto *CurValue = findValueOrDie(Node);
899 if (isa<Constant>(CurValue) && !isa<GlobalValue>(CurValue))
902 for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
903 auto Weight = std::get<0>(EdgeTuple);
904 auto Label = Weight.first;
905 auto &OtherNode = std::get<1>(EdgeTuple);
906 auto *OtherValue = findValueOrDie(OtherNode);
908 if (isa<Constant>(OtherValue) && !isa<GlobalValue>(OtherValue))
912 switch (directionOfEdgeType(Label)) {
914 Added = Builder.addAbove(CurValue, OtherValue);
917 Added = Builder.addBelow(CurValue, OtherValue);
920 Added = Builder.addWith(CurValue, OtherValue);
925 auto Aliasing = Weight.second;
926 if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
927 Aliasing.set(*MaybeCurIndex);
928 if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
929 Aliasing.set(*MaybeOtherIndex);
930 Builder.noteAttributes(CurValue, Aliasing);
931 Builder.noteAttributes(OtherValue, Aliasing);
932 Worklist.push_back(OtherNode);
938 // There are times when we end up with parameters not in our graph (i.e. if
939 // it's only used as the condition of a branch). Other bits of code depend on
940 // things that were present during construction being present in the graph.
941 // So, we add all present arguments here.
942 for (auto &Arg : Fn->args()) {
946 return FunctionInfo(Builder.build(), std::move(ReturnedValues));
949 void CFLAliasAnalysis::scan(Function *Fn) {
950 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
952 assert(InsertPair.second &&
953 "Trying to scan a function that has already been cached");
955 FunctionInfo Info(buildSetsFrom(*this, Fn));
956 Cache[Fn] = std::move(Info);
957 Handles.push_front(FunctionHandle(Fn, this));
960 AliasAnalysis::AliasResult
961 CFLAliasAnalysis::query(const AliasAnalysis::Location &LocA,
962 const AliasAnalysis::Location &LocB) {
963 auto *ValA = const_cast<Value *>(LocA.Ptr);
964 auto *ValB = const_cast<Value *>(LocB.Ptr);
966 Function *Fn = nullptr;
967 auto MaybeFnA = parentFunctionOfValue(ValA);
968 auto MaybeFnB = parentFunctionOfValue(ValB);
969 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
970 llvm_unreachable("Don't know how to extract the parent function "
971 "from values A or B");
974 if (MaybeFnA.hasValue()) {
976 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
977 "Interprocedural queries not supported");
982 assert(Fn != nullptr);
983 auto &MaybeInfo = ensureCached(Fn);
984 assert(MaybeInfo.hasValue());
986 auto &Sets = MaybeInfo->Sets;
987 auto MaybeA = Sets.find(ValA);
988 if (!MaybeA.hasValue())
989 return AliasAnalysis::MayAlias;
991 auto MaybeB = Sets.find(ValB);
992 if (!MaybeB.hasValue())
993 return AliasAnalysis::MayAlias;
998 if (SetA.Index == SetB.Index)
999 return AliasAnalysis::PartialAlias;
1001 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
1002 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
1003 // Stratified set attributes are used as markets to signify whether a member
1004 // of a StratifiedSet (or a member of a set above the current set) has
1005 // interacted with either arguments or globals. "Interacted with" meaning
1006 // its value may be different depending on the value of an argument or
1007 // global. The thought behind this is that, because arguments and globals
1008 // may alias each other, if AttrsA and AttrsB have touched args/globals,
1009 // we must conservatively say that they alias. However, if at least one of
1010 // the sets has no values that could legally be altered by changing the value
1011 // of an argument or global, then we don't have to be as conservative.
1012 if (AttrsA.any() && AttrsB.any())
1013 return AliasAnalysis::MayAlias;
1015 return AliasAnalysis::NoAlias;