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/Analysis/Passes.h"
33 #include "llvm/ADT/BitVector.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/Optional.h"
36 #include "llvm/ADT/None.h"
37 #include "llvm/Analysis/AliasAnalysis.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/InstVisitor.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;
145 struct CFLAliasAnalysis;
147 struct FunctionHandle : public CallbackVH {
148 FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
149 : CallbackVH(Fn), CFLAA(CFLAA) {
150 assert(Fn != nullptr);
151 assert(CFLAA != nullptr);
154 virtual ~FunctionHandle() {}
156 virtual void deleted() override { removeSelfFromCache(); }
157 virtual void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
160 CFLAliasAnalysis *CFLAA;
162 void removeSelfFromCache();
165 struct CFLAliasAnalysis : public ImmutablePass, public AliasAnalysis {
167 /// \brief Cached mapping of Functions to their StratifiedSets.
168 /// If a function's sets are currently being built, it is marked
169 /// in the cache as an Optional without a value. This way, if we
170 /// have any kind of recursion, it is discernable from a function
171 /// that simply has empty sets.
172 DenseMap<Function *, Optional<FunctionInfo>> Cache;
173 std::forward_list<FunctionHandle> Handles;
178 CFLAliasAnalysis() : ImmutablePass(ID) {
179 initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
182 virtual ~CFLAliasAnalysis() {}
184 void getAnalysisUsage(AnalysisUsage &AU) const {
185 AliasAnalysis::getAnalysisUsage(AU);
188 void *getAdjustedAnalysisPointer(const void *ID) override {
189 if (ID == &AliasAnalysis::ID)
190 return (AliasAnalysis *)this;
194 /// \brief Inserts the given Function into the cache.
195 void scan(Function *Fn);
197 void evict(Function *Fn) { Cache.erase(Fn); }
199 /// \brief Ensures that the given function is available in the cache.
200 /// Returns the appropriate entry from the cache.
201 const Optional<FunctionInfo> &ensureCached(Function *Fn) {
202 auto Iter = Cache.find(Fn);
203 if (Iter == Cache.end()) {
205 Iter = Cache.find(Fn);
206 assert(Iter != Cache.end());
207 assert(Iter->second.hasValue());
212 AliasResult query(const Location &LocA, const Location &LocB);
214 AliasResult alias(const Location &LocA, const Location &LocB) override {
215 if (LocA.Ptr == LocB.Ptr) {
216 if (LocA.Size == LocB.Size) {
223 // Comparisons between global variables and other constants should be
224 // handled by BasicAA.
225 if (isa<Constant>(LocA.Ptr) && isa<Constant>(LocB.Ptr)) {
229 return query(LocA, LocB);
232 void initializePass() override { InitializeAliasAnalysis(this); }
235 void FunctionHandle::removeSelfFromCache() {
236 assert(CFLAA != nullptr);
237 auto *Val = getValPtr();
238 CFLAA->evict(cast<Function>(Val));
242 // \brief Gets the edges our graph should have, based on an Instruction*
243 class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
244 CFLAliasAnalysis &AA;
245 SmallVectorImpl<Edge> &Output;
248 GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
249 : AA(AA), Output(Output) {}
251 void visitInstruction(Instruction &) {
252 llvm_unreachable("Unsupported instruction encountered");
255 void visitCastInst(CastInst &Inst) {
256 Output.push_back(Edge(&Inst, Inst.getOperand(0), EdgeType::Assign,
260 void visitBinaryOperator(BinaryOperator &Inst) {
261 auto *Op1 = Inst.getOperand(0);
262 auto *Op2 = Inst.getOperand(1);
263 Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
264 Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
267 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
268 auto *Ptr = Inst.getPointerOperand();
269 auto *Val = Inst.getNewValOperand();
270 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
273 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
274 auto *Ptr = Inst.getPointerOperand();
275 auto *Val = Inst.getValOperand();
276 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
279 void visitPHINode(PHINode &Inst) {
280 for (unsigned I = 0, E = Inst.getNumIncomingValues(); I != E; ++I) {
281 Value *Val = Inst.getIncomingValue(I);
282 Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
286 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
287 auto *Op = Inst.getPointerOperand();
288 Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
289 for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
290 Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
293 void visitSelectInst(SelectInst &Inst) {
294 auto *Condition = Inst.getCondition();
295 Output.push_back(Edge(&Inst, Condition, EdgeType::Assign, AttrNone));
296 auto *TrueVal = Inst.getTrueValue();
297 Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
298 auto *FalseVal = Inst.getFalseValue();
299 Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
302 void visitAllocaInst(AllocaInst &) {}
304 void visitLoadInst(LoadInst &Inst) {
305 auto *Ptr = Inst.getPointerOperand();
307 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
310 void visitStoreInst(StoreInst &Inst) {
311 auto *Ptr = Inst.getPointerOperand();
312 auto *Val = Inst.getValueOperand();
313 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
316 static bool isFunctionExternal(Function *Fn) {
317 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
320 // Gets whether the sets at Index1 above, below, or equal to the sets at
321 // Index2. Returns None if they are not in the same set chain.
322 static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
323 StratifiedIndex Index1,
324 StratifiedIndex Index2) {
325 if (Index1 == Index2)
328 const auto *Current = &Sets.getLink(Index1);
329 while (Current->hasBelow()) {
330 if (Current->Below == Index2)
332 Current = &Sets.getLink(Current->Below);
335 Current = &Sets.getLink(Index1);
336 while (Current->hasAbove()) {
337 if (Current->Above == Index2)
339 Current = &Sets.getLink(Current->Above);
346 tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
348 const iterator_range<User::op_iterator> &Args) {
349 const unsigned ExpectedMaxArgs = 8;
350 const unsigned MaxSupportedArgs = 50;
351 assert(Fns.size() > 0);
353 // I put this here to give us an upper bound on time taken by IPA. Is it
354 // really (realistically) needed? Keep in mind that we do have an n^2 algo.
355 if (std::distance(Args.begin(), Args.end()) > (int) MaxSupportedArgs)
358 // Exit early if we'll fail anyway
359 for (auto *Fn : Fns) {
360 if (isFunctionExternal(Fn) || Fn->isVarArg())
362 auto &MaybeInfo = AA.ensureCached(Fn);
363 if (!MaybeInfo.hasValue())
367 SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
368 SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
369 for (auto *Fn : Fns) {
370 auto &Info = *AA.ensureCached(Fn);
371 auto &Sets = Info.Sets;
372 auto &RetVals = Info.ReturnedValues;
375 for (auto &Param : Fn->args()) {
376 auto MaybeInfo = Sets.find(&Param);
377 // Did a new parameter somehow get added to the function/slip by?
378 if (!MaybeInfo.hasValue())
380 Parameters.push_back(*MaybeInfo);
383 // Adding an edge from argument -> return value for each parameter that
384 // may alias the return value
385 for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
386 auto &ParamInfo = Parameters[I];
387 auto &ArgVal = Arguments[I];
388 bool AddEdge = false;
389 StratifiedAttrs Externals;
390 for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
391 auto MaybeInfo = Sets.find(RetVals[X]);
392 if (!MaybeInfo.hasValue())
395 auto &RetInfo = *MaybeInfo;
396 auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
397 auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
399 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
400 if (MaybeRelation.hasValue()) {
402 Externals |= RetAttrs | ParamAttrs;
406 Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
407 StratifiedAttrs().flip()));
410 if (Parameters.size() != Arguments.size())
413 // Adding edges between arguments for arguments that may end up aliasing
414 // each other. This is necessary for functions such as
415 // void foo(int** a, int** b) { *a = *b; }
416 // (Technically, the proper sets for this would be those below
417 // Arguments[I] and Arguments[X], but our algorithm will produce
418 // extremely similar, and equally correct, results either way)
419 for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
420 auto &MainVal = Arguments[I];
421 auto &MainInfo = Parameters[I];
422 auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
423 for (unsigned X = I + 1; X != E; ++X) {
424 auto &SubInfo = Parameters[X];
425 auto &SubVal = Arguments[X];
426 auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
428 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
430 if (!MaybeRelation.hasValue())
433 auto NewAttrs = SubAttrs | MainAttrs;
434 Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
441 template <typename InstT> void visitCallLikeInst(InstT &Inst) {
442 SmallVector<Function *, 4> Targets;
443 if (getPossibleTargets(&Inst, Targets)) {
444 if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
446 // Cleanup from interprocedural analysis
450 for (Value *V : Inst.arg_operands())
451 Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
454 void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
456 void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
458 // Because vectors/aggregates are immutable and unaddressable,
459 // there's nothing we can do to coax a value out of them, other
460 // than calling Extract{Element,Value}. We can effectively treat
461 // them as pointers to arbitrary memory locations we can store in
463 void visitExtractElementInst(ExtractElementInst &Inst) {
464 auto *Ptr = Inst.getVectorOperand();
466 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
469 void visitInsertElementInst(InsertElementInst &Inst) {
470 auto *Vec = Inst.getOperand(0);
471 auto *Val = Inst.getOperand(1);
472 Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
473 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
476 void visitLandingPadInst(LandingPadInst &Inst) {
477 // Exceptions come from "nowhere", from our analysis' perspective.
478 // So we place the instruction its own group, noting that said group may
480 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
483 void visitInsertValueInst(InsertValueInst &Inst) {
484 auto *Agg = Inst.getOperand(0);
485 auto *Val = Inst.getOperand(1);
486 Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
487 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
490 void visitExtractValueInst(ExtractValueInst &Inst) {
491 auto *Ptr = Inst.getAggregateOperand();
492 Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
495 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
496 auto *From1 = Inst.getOperand(0);
497 auto *From2 = Inst.getOperand(1);
498 Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
499 Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
503 // For a given instruction, we need to know which Value* to get the
504 // users of in order to build our graph. In some cases (i.e. add),
505 // we simply need the Instruction*. In other cases (i.e. store),
506 // finding the users of the Instruction* is useless; we need to find
507 // the users of the first operand. This handles determining which
508 // value to follow for us.
510 // Note: we *need* to keep this in sync with GetEdgesVisitor. Add
511 // something to GetEdgesVisitor, add it here -- remove something from
512 // GetEdgesVisitor, remove it here.
513 class GetTargetValueVisitor
514 : public InstVisitor<GetTargetValueVisitor, Value *> {
516 Value *visitInstruction(Instruction &Inst) { return &Inst; }
518 Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
520 Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
521 return Inst.getPointerOperand();
524 Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
525 return Inst.getPointerOperand();
528 Value *visitInsertElementInst(InsertElementInst &Inst) {
529 return Inst.getOperand(0);
532 Value *visitInsertValueInst(InsertValueInst &Inst) {
533 return Inst.getAggregateOperand();
537 // Set building requires a weighted bidirectional graph.
538 template <typename EdgeTypeT> class WeightedBidirectionalGraph {
540 typedef std::size_t Node;
543 const static Node StartNode = Node(0);
549 Edge(const EdgeTypeT &W, const Node &N)
550 : Weight(W), Other(N) {}
552 bool operator==(const Edge &E) const {
553 return Weight == E.Weight && Other == E.Other;
556 bool operator!=(const Edge &E) const { return !operator==(E); }
560 std::vector<Edge> Edges;
563 std::vector<NodeImpl> NodeImpls;
565 bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
567 const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
568 NodeImpl &getNode(Node N) { return NodeImpls[N]; }
571 // ----- Various Edge iterators for the graph ----- //
573 // \brief Iterator for edges. Because this graph is bidirected, we don't
574 // allow modificaiton of the edges using this iterator. Additionally, the
575 // iterator becomes invalid if you add edges to or from the node you're
576 // getting the edges of.
577 struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
578 std::tuple<EdgeTypeT, Node *>> {
579 EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
582 EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
584 EdgeIterator &operator++() {
589 EdgeIterator operator++(int) {
590 EdgeIterator Copy(Current);
595 std::tuple<EdgeTypeT, Node> &operator*() {
596 Store = std::make_tuple(Current->Weight, Current->Other);
600 bool operator==(const EdgeIterator &Other) const {
601 return Current == Other.Current;
604 bool operator!=(const EdgeIterator &Other) const {
605 return !operator==(Other);
609 typename std::vector<Edge>::const_iterator Current;
610 std::tuple<EdgeTypeT, Node> Store;
613 // Wrapper for EdgeIterator with begin()/end() calls.
614 struct EdgeIterable {
615 EdgeIterable(const std::vector<Edge> &Edges)
616 : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
618 EdgeIterator begin() { return EdgeIterator(BeginIter); }
620 EdgeIterator end() { return EdgeIterator(EndIter); }
623 typename std::vector<Edge>::const_iterator BeginIter;
624 typename std::vector<Edge>::const_iterator EndIter;
627 // ----- Actual graph-related things ----- //
629 WeightedBidirectionalGraph() {}
631 WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
632 : NodeImpls(std::move(Other.NodeImpls)) {}
634 WeightedBidirectionalGraph<EdgeTypeT> &
635 operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
636 NodeImpls = std::move(Other.NodeImpls);
641 auto Index = NodeImpls.size();
642 auto NewNode = Node(Index);
643 NodeImpls.push_back(NodeImpl());
647 void addEdge(Node From, Node To, const EdgeTypeT &Weight,
648 const EdgeTypeT &ReverseWeight) {
649 assert(inbounds(From));
650 assert(inbounds(To));
651 auto &FromNode = getNode(From);
652 auto &ToNode = getNode(To);
653 FromNode.Edges.push_back(Edge(Weight, To));
654 ToNode.Edges.push_back(Edge(ReverseWeight, From));
657 EdgeIterable edgesFor(const Node &N) const {
658 const auto &Node = getNode(N);
659 return EdgeIterable(Node.Edges);
662 bool empty() const { return NodeImpls.empty(); }
663 std::size_t size() const { return NodeImpls.size(); }
665 // \brief Gets an arbitrary node in the graph as a starting point for
667 Node getEntryNode() {
668 assert(inbounds(StartNode));
673 typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
674 typedef DenseMap<Value *, GraphT::Node> NodeMapT;
677 // -- Setting up/registering CFLAA pass -- //
678 char CFLAliasAnalysis::ID = 0;
680 INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
681 "CFL-Based AA implementation", false, true, false)
683 ImmutablePass *llvm::createCFLAliasAnalysisPass() {
684 return new CFLAliasAnalysis();
687 //===----------------------------------------------------------------------===//
688 // Function declarations that require types defined in the namespace above
689 //===----------------------------------------------------------------------===//
691 // Given an argument number, returns the appropriate Attr index to set.
692 static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
694 // Given a Value, potentially return which AttrIndex it maps to.
695 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
697 // Gets the inverse of a given EdgeType.
698 static EdgeType flipWeight(EdgeType);
700 // Gets edges of the given Instruction*, writing them to the SmallVector*.
701 static void argsToEdges(CFLAliasAnalysis &, Instruction *,
702 SmallVectorImpl<Edge> &);
704 // Gets the "Level" that one should travel in StratifiedSets
705 // given an EdgeType.
706 static Level directionOfEdgeType(EdgeType);
708 // Builds the graph needed for constructing the StratifiedSets for the
710 static void buildGraphFrom(CFLAliasAnalysis &, Function *,
711 SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
713 // Builds the graph + StratifiedSets for a function.
714 static FunctionInfo buildSetsFrom(CFLAliasAnalysis &, Function *);
716 static Optional<Function *> parentFunctionOfValue(Value *Val) {
717 if (auto *Inst = dyn_cast<Instruction>(Val)) {
718 auto *Bb = Inst->getParent();
719 return Bb->getParent();
722 if (auto *Arg = dyn_cast<Argument>(Val))
723 return Arg->getParent();
727 template <typename Inst>
728 static bool getPossibleTargets(Inst *Call,
729 SmallVectorImpl<Function *> &Output) {
730 if (auto *Fn = Call->getCalledFunction()) {
731 Output.push_back(Fn);
735 // TODO: If the call is indirect, we might be able to enumerate all potential
736 // targets of the call and return them, rather than just failing.
740 static Optional<Value *> getTargetValue(Instruction *Inst) {
741 GetTargetValueVisitor V;
742 return V.visit(Inst);
745 static bool hasUsefulEdges(Instruction *Inst) {
746 bool IsNonInvokeTerminator =
747 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
748 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
751 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
752 if (isa<GlobalValue>(Val))
753 return AttrGlobalIndex;
755 if (auto *Arg = dyn_cast<Argument>(Val))
756 if (!Arg->hasNoAliasAttr())
757 return argNumberToAttrIndex(Arg->getArgNo());
761 static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
762 if (ArgNum > AttrMaxNumArgs)
764 return ArgNum + AttrFirstArgIndex;
767 static EdgeType flipWeight(EdgeType Initial) {
769 case EdgeType::Assign:
770 return EdgeType::Assign;
771 case EdgeType::Dereference:
772 return EdgeType::Reference;
773 case EdgeType::Reference:
774 return EdgeType::Dereference;
776 llvm_unreachable("Incomplete coverage of EdgeType enum");
779 static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
780 SmallVectorImpl<Edge> &Output) {
781 GetEdgesVisitor v(Analysis, Output);
785 static Level directionOfEdgeType(EdgeType Weight) {
787 case EdgeType::Reference:
789 case EdgeType::Dereference:
791 case EdgeType::Assign:
794 llvm_unreachable("Incomplete switch coverage");
797 // Aside: We may remove graph construction entirely, because it doesn't really
798 // buy us much that we don't already have. I'd like to add interprocedural
799 // analysis prior to this however, in case that somehow requires the graph
800 // produced by this for efficient execution
801 static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
802 SmallVectorImpl<Value *> &ReturnedValues,
803 NodeMapT &Map, GraphT &Graph) {
804 const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
805 auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
806 auto &Iter = Pair.first;
808 auto NewNode = Graph.addNode();
809 Iter->second = NewNode;
814 SmallVector<Edge, 8> Edges;
815 for (auto &Bb : Fn->getBasicBlockList()) {
816 for (auto &Inst : Bb.getInstList()) {
817 // We don't want the edges of most "return" instructions, but we *do* want
818 // to know what can be returned.
819 if (auto *Ret = dyn_cast<ReturnInst>(&Inst))
820 ReturnedValues.push_back(Ret);
822 if (!hasUsefulEdges(&Inst))
826 argsToEdges(Analysis, &Inst, Edges);
828 // In the case of an unused alloca (or similar), edges may be empty. Note
829 // that it exists so we can potentially answer NoAlias.
831 auto MaybeVal = getTargetValue(&Inst);
832 assert(MaybeVal.hasValue());
833 auto *Target = *MaybeVal;
834 findOrInsertNode(Target);
838 for (const Edge &E : Edges) {
839 auto To = findOrInsertNode(E.To);
840 auto From = findOrInsertNode(E.From);
841 auto FlippedWeight = flipWeight(E.Weight);
842 auto Attrs = E.AdditionalAttrs;
843 Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
844 std::make_pair(FlippedWeight, Attrs));
850 static FunctionInfo buildSetsFrom(CFLAliasAnalysis &Analysis, Function *Fn) {
853 SmallVector<Value *, 4> ReturnedValues;
855 buildGraphFrom(Analysis, Fn, ReturnedValues, Map, Graph);
857 DenseMap<GraphT::Node, Value *> NodeValueMap;
858 NodeValueMap.resize(Map.size());
859 for (const auto &Pair : Map)
860 NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
862 const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
863 auto ValIter = NodeValueMap.find(Node);
864 assert(ValIter != NodeValueMap.end());
865 return ValIter->second;
868 StratifiedSetsBuilder<Value *> Builder;
870 SmallVector<GraphT::Node, 16> Worklist;
871 for (auto &Pair : Map) {
874 auto *Value = Pair.first;
876 auto InitialNode = Pair.second;
877 Worklist.push_back(InitialNode);
878 while (!Worklist.empty()) {
879 auto Node = Worklist.pop_back_val();
880 auto *CurValue = findValueOrDie(Node);
881 if (isa<Constant>(CurValue) && !isa<GlobalValue>(CurValue))
884 for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
885 auto Weight = std::get<0>(EdgeTuple);
886 auto Label = Weight.first;
887 auto &OtherNode = std::get<1>(EdgeTuple);
888 auto *OtherValue = findValueOrDie(OtherNode);
890 if (isa<Constant>(OtherValue) && !isa<GlobalValue>(OtherValue))
894 switch (directionOfEdgeType(Label)) {
896 Added = Builder.addAbove(CurValue, OtherValue);
899 Added = Builder.addBelow(CurValue, OtherValue);
902 Added = Builder.addWith(CurValue, OtherValue);
907 auto Aliasing = Weight.second;
908 if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
909 Aliasing.set(*MaybeCurIndex);
910 if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
911 Aliasing.set(*MaybeOtherIndex);
912 Builder.noteAttributes(CurValue, Aliasing);
913 Builder.noteAttributes(OtherValue, Aliasing);
914 Worklist.push_back(OtherNode);
920 // There are times when we end up with parameters not in our graph (i.e. if
921 // it's only used as the condition of a branch). Other bits of code depend on
922 // things that were present during construction being present in the graph.
923 // So, we add all present arguments here.
924 for (auto &Arg : Fn->args()) {
928 return {Builder.build(), std::move(ReturnedValues)};
931 void CFLAliasAnalysis::scan(Function *Fn) {
932 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
934 assert(InsertPair.second &&
935 "Trying to scan a function that has already been cached");
937 FunctionInfo Info(buildSetsFrom(*this, Fn));
938 Cache[Fn] = std::move(Info);
939 Handles.push_front(FunctionHandle(Fn, this));
942 AliasAnalysis::AliasResult
943 CFLAliasAnalysis::query(const AliasAnalysis::Location &LocA,
944 const AliasAnalysis::Location &LocB) {
945 auto *ValA = const_cast<Value *>(LocA.Ptr);
946 auto *ValB = const_cast<Value *>(LocB.Ptr);
948 Function *Fn = nullptr;
949 auto MaybeFnA = parentFunctionOfValue(ValA);
950 auto MaybeFnB = parentFunctionOfValue(ValB);
951 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
952 llvm_unreachable("Don't know how to extract the parent function "
953 "from values A or B");
956 if (MaybeFnA.hasValue()) {
958 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
959 "Interprocedural queries not supported");
964 assert(Fn != nullptr);
965 auto &MaybeInfo = ensureCached(Fn);
966 assert(MaybeInfo.hasValue());
968 auto &Sets = MaybeInfo->Sets;
969 auto MaybeA = Sets.find(ValA);
970 if (!MaybeA.hasValue())
971 return AliasAnalysis::MayAlias;
973 auto MaybeB = Sets.find(ValB);
974 if (!MaybeB.hasValue())
975 return AliasAnalysis::MayAlias;
980 if (SetA.Index == SetB.Index)
981 return AliasAnalysis::PartialAlias;
983 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
984 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
985 auto CombinedAttrs = AttrsA | AttrsB;
986 if (CombinedAttrs.any())
987 return AliasAnalysis::PartialAlias;
989 return AliasAnalysis::NoAlias;