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 *);
77 // StratifiedInfo Attribute things.
78 typedef unsigned StratifiedAttr;
79 LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
80 LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
81 LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
82 LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 2;
83 LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
84 LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
86 LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
87 LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
89 // \brief StratifiedSets call for knowledge of "direction", so this is how we
90 // represent that locally.
91 enum class Level { Same, Above, Below };
93 // \brief Edges can be one of four "weights" -- each weight must have an inverse
94 // weight (Assign has Assign; Reference has Dereference).
96 // The weight assigned when assigning from or to a value. For example, in:
97 // %b = getelementptr %a, 0
98 // ...The relationships are %b assign %a, and %a assign %b. This used to be
99 // two edges, but having a distinction bought us nothing.
102 // The edge used when we have an edge going from some handle to a Value.
103 // Examples of this include:
104 // %b = load %a (%b Dereference %a)
105 // %b = extractelement %a, 0 (%a Dereference %b)
108 // The edge used when our edge goes from a value to a handle that may have
109 // contained it at some point. Examples:
110 // %b = load %a (%a Reference %b)
111 // %b = extractelement %a, 0 (%b Reference %a)
115 // \brief Encodes the notion of a "use"
117 // \brief Which value the edge is coming from
120 // \brief Which value the edge is pointing to
123 // \brief Edge weight
126 // \brief Whether we aliased any external values along the way that may be
127 // invisible to the analysis (i.e. landingpad for exceptions, calls for
128 // interprocedural analysis, etc.)
129 StratifiedAttrs AdditionalAttrs;
131 Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
132 : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
135 // \brief Information we have about a function and would like to keep around
136 struct FunctionInfo {
137 StratifiedSets<Value *> Sets;
138 // Lots of functions have < 4 returns. Adjust as necessary.
139 SmallVector<Value *, 4> ReturnedValues;
142 struct CFLAliasAnalysis;
144 struct FunctionHandle : public CallbackVH {
145 FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
146 : CallbackVH(Fn), CFLAA(CFLAA) {
147 assert(Fn != nullptr);
148 assert(CFLAA != nullptr);
151 virtual ~FunctionHandle() {}
153 virtual void deleted() override { removeSelfFromCache(); }
154 virtual void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
157 CFLAliasAnalysis *CFLAA;
159 void removeSelfFromCache();
162 struct CFLAliasAnalysis : public ImmutablePass, public AliasAnalysis {
164 /// \brief Cached mapping of Functions to their StratifiedSets.
165 /// If a function's sets are currently being built, it is marked
166 /// in the cache as an Optional without a value. This way, if we
167 /// have any kind of recursion, it is discernable from a function
168 /// that simply has empty sets.
169 DenseMap<Function *, Optional<FunctionInfo>> Cache;
170 std::forward_list<FunctionHandle> Handles;
175 CFLAliasAnalysis() : ImmutablePass(ID) {
176 initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
179 virtual ~CFLAliasAnalysis() {}
181 void getAnalysisUsage(AnalysisUsage &AU) const {
182 AliasAnalysis::getAnalysisUsage(AU);
185 void *getAdjustedAnalysisPointer(const void *ID) override {
186 if (ID == &AliasAnalysis::ID)
187 return (AliasAnalysis *)this;
191 /// \brief Inserts the given Function into the cache.
192 void scan(Function *Fn);
194 void evict(Function *Fn) { Cache.erase(Fn); }
196 /// \brief Ensures that the given function is available in the cache.
197 /// Returns the appropriate entry from the cache.
198 const Optional<FunctionInfo> &ensureCached(Function *Fn) {
199 auto Iter = Cache.find(Fn);
200 if (Iter == Cache.end()) {
202 Iter = Cache.find(Fn);
203 assert(Iter != Cache.end());
204 assert(Iter->second.hasValue());
209 AliasResult query(const Location &LocA, const Location &LocB);
211 AliasResult alias(const Location &LocA, const Location &LocB) override {
212 if (LocA.Ptr == LocB.Ptr) {
213 if (LocA.Size == LocB.Size) {
220 // Comparisons between global variables and other constants should be
221 // handled by BasicAA.
222 if (isa<Constant>(LocA.Ptr) && isa<Constant>(LocB.Ptr)) {
226 return query(LocA, LocB);
229 void initializePass() override { InitializeAliasAnalysis(this); }
232 void FunctionHandle::removeSelfFromCache() {
233 assert(CFLAA != nullptr);
234 auto *Val = getValPtr();
235 CFLAA->evict(cast<Function>(Val));
239 // \brief Gets the edges our graph should have, based on an Instruction*
240 class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
241 CFLAliasAnalysis &AA;
242 SmallVectorImpl<Edge> &Output;
245 GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
246 : AA(AA), Output(Output) {}
248 void visitInstruction(Instruction &) {
249 llvm_unreachable("Unsupported instruction encountered");
252 void visitCastInst(CastInst &Inst) {
253 Output.push_back({&Inst, Inst.getOperand(0), EdgeType::Assign, AttrNone});
256 void visitBinaryOperator(BinaryOperator &Inst) {
257 auto *Op1 = Inst.getOperand(0);
258 auto *Op2 = Inst.getOperand(1);
259 Output.push_back({&Inst, Op1, EdgeType::Assign, AttrNone});
260 Output.push_back({&Inst, Op2, EdgeType::Assign, AttrNone});
263 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
264 auto *Ptr = Inst.getPointerOperand();
265 auto *Val = Inst.getNewValOperand();
266 Output.push_back({Ptr, Val, EdgeType::Dereference, AttrNone});
269 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
270 auto *Ptr = Inst.getPointerOperand();
271 auto *Val = Inst.getValOperand();
272 Output.push_back({Ptr, Val, EdgeType::Dereference, AttrNone});
275 void visitPHINode(PHINode &Inst) {
276 for (unsigned I = 0, E = Inst.getNumIncomingValues(); I != E; ++I) {
277 Value *Val = Inst.getIncomingValue(I);
278 Output.push_back({&Inst, Val, EdgeType::Assign, AttrNone});
282 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
283 auto *Op = Inst.getPointerOperand();
284 Output.push_back({&Inst, Op, EdgeType::Assign, AttrNone});
285 for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
286 Output.push_back({&Inst, *I, EdgeType::Assign, AttrNone});
289 void visitSelectInst(SelectInst &Inst) {
290 auto *Condition = Inst.getCondition();
291 Output.push_back({&Inst, Condition, EdgeType::Assign, AttrNone});
292 auto *TrueVal = Inst.getTrueValue();
293 Output.push_back({&Inst, TrueVal, EdgeType::Assign, AttrNone});
294 auto *FalseVal = Inst.getFalseValue();
295 Output.push_back({&Inst, FalseVal, EdgeType::Assign, AttrNone});
298 void visitAllocaInst(AllocaInst &) {}
300 void visitLoadInst(LoadInst &Inst) {
301 auto *Ptr = Inst.getPointerOperand();
303 Output.push_back({Val, Ptr, EdgeType::Reference, AttrNone});
306 void visitStoreInst(StoreInst &Inst) {
307 auto *Ptr = Inst.getPointerOperand();
308 auto *Val = Inst.getValueOperand();
309 Output.push_back({Ptr, Val, EdgeType::Dereference, AttrNone});
312 static bool isFunctionExternal(Function *Fn) {
313 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
316 // Gets whether the sets at Index1 above, below, or equal to the sets at
317 // Index2. Returns None if they are not in the same set chain.
318 static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
319 StratifiedIndex Index1,
320 StratifiedIndex Index2) {
321 if (Index1 == Index2)
324 const auto *Current = &Sets.getLink(Index1);
325 while (Current->hasBelow()) {
326 if (Current->Below == Index2)
328 Current = &Sets.getLink(Current->Below);
331 Current = &Sets.getLink(Index1);
332 while (Current->hasAbove()) {
333 if (Current->Above == Index2)
335 Current = &Sets.getLink(Current->Above);
342 tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
344 const iterator_range<User::op_iterator> &Args) {
345 LLVM_CONSTEXPR unsigned ExpectedMaxArgs = 8;
346 LLVM_CONSTEXPR unsigned MaxSupportedArgs = 50;
347 assert(Fns.size() > 0);
349 // I put this here to give us an upper bound on time taken by IPA. Is it
350 // really (realistically) needed? Keep in mind that we do have an n^2 algo.
351 if (std::distance(Args.begin(), Args.end()) > MaxSupportedArgs)
354 // Exit early if we'll fail anyway
355 for (auto *Fn : Fns) {
356 if (isFunctionExternal(Fn) || Fn->isVarArg())
358 auto &MaybeInfo = AA.ensureCached(Fn);
359 if (!MaybeInfo.hasValue())
363 SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
364 SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
365 for (auto *Fn : Fns) {
366 auto &Info = *AA.ensureCached(Fn);
367 auto &Sets = Info.Sets;
368 auto &RetVals = Info.ReturnedValues;
371 for (auto &Param : Fn->args()) {
372 auto MaybeInfo = Sets.find(&Param);
373 // Did a new parameter somehow get added to the function/slip by?
374 if (!MaybeInfo.hasValue())
376 Parameters.push_back(*MaybeInfo);
379 // Adding an edge from argument -> return value for each parameter that
380 // may alias the return value
381 for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
382 auto &ParamInfo = Parameters[I];
383 auto &ArgVal = Arguments[I];
384 bool AddEdge = false;
385 StratifiedAttrs Externals;
386 for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
387 auto MaybeInfo = Sets.find(RetVals[X]);
388 if (!MaybeInfo.hasValue())
391 auto &RetInfo = *MaybeInfo;
392 auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
393 auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
395 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
396 if (MaybeRelation.hasValue()) {
398 Externals |= RetAttrs | ParamAttrs;
402 Output.push_back({FuncValue, ArgVal, EdgeType::Assign,
403 StratifiedAttrs().flip()});
406 if (Parameters.size() != Arguments.size())
409 // Adding edges between arguments for arguments that may end up aliasing
410 // each other. This is necessary for functions such as
411 // void foo(int** a, int** b) { *a = *b; }
412 // (Technically, the proper sets for this would be those below
413 // Arguments[I] and Arguments[X], but our algorithm will produce
414 // extremely similar, and equally correct, results either way)
415 for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
416 auto &MainVal = Arguments[I];
417 auto &MainInfo = Parameters[I];
418 auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
419 for (unsigned X = I + 1; X != E; ++X) {
420 auto &SubInfo = Parameters[X];
421 auto &SubVal = Arguments[X];
422 auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
424 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
426 if (!MaybeRelation.hasValue())
429 auto NewAttrs = SubAttrs | MainAttrs;
430 Output.push_back({MainVal, SubVal, EdgeType::Assign, NewAttrs});
437 template <typename InstT> void visitCallLikeInst(InstT &Inst) {
438 SmallVector<Function *, 4> Targets;
439 if (getPossibleTargets(&Inst, Targets)) {
440 if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
442 // Cleanup from interprocedural analysis
446 for (Value *V : Inst.arg_operands())
447 Output.push_back({&Inst, V, EdgeType::Assign, AttrAll});
450 void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
452 void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
454 // Because vectors/aggregates are immutable and unaddressable,
455 // there's nothing we can do to coax a value out of them, other
456 // than calling Extract{Element,Value}. We can effectively treat
457 // them as pointers to arbitrary memory locations we can store in
459 void visitExtractElementInst(ExtractElementInst &Inst) {
460 auto *Ptr = Inst.getVectorOperand();
462 Output.push_back({Val, Ptr, EdgeType::Reference, AttrNone});
465 void visitInsertElementInst(InsertElementInst &Inst) {
466 auto *Vec = Inst.getOperand(0);
467 auto *Val = Inst.getOperand(1);
468 Output.push_back({&Inst, Vec, EdgeType::Assign, AttrNone});
469 Output.push_back({&Inst, Val, EdgeType::Dereference, AttrNone});
472 void visitLandingPadInst(LandingPadInst &Inst) {
473 // Exceptions come from "nowhere", from our analysis' perspective.
474 // So we place the instruction its own group, noting that said group may
476 Output.push_back({&Inst, &Inst, EdgeType::Assign, AttrAll});
479 void visitInsertValueInst(InsertValueInst &Inst) {
480 auto *Agg = Inst.getOperand(0);
481 auto *Val = Inst.getOperand(1);
482 Output.push_back({&Inst, Agg, EdgeType::Assign, AttrNone});
483 Output.push_back({&Inst, Val, EdgeType::Dereference, AttrNone});
486 void visitExtractValueInst(ExtractValueInst &Inst) {
487 auto *Ptr = Inst.getAggregateOperand();
488 Output.push_back({&Inst, Ptr, EdgeType::Reference, AttrNone});
491 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
492 auto *From1 = Inst.getOperand(0);
493 auto *From2 = Inst.getOperand(1);
494 Output.push_back({&Inst, From1, EdgeType::Assign, AttrNone});
495 Output.push_back({&Inst, From2, EdgeType::Assign, AttrNone});
499 // For a given instruction, we need to know which Value* to get the
500 // users of in order to build our graph. In some cases (i.e. add),
501 // we simply need the Instruction*. In other cases (i.e. store),
502 // finding the users of the Instruction* is useless; we need to find
503 // the users of the first operand. This handles determining which
504 // value to follow for us.
506 // Note: we *need* to keep this in sync with GetEdgesVisitor. Add
507 // something to GetEdgesVisitor, add it here -- remove something from
508 // GetEdgesVisitor, remove it here.
509 class GetTargetValueVisitor
510 : public InstVisitor<GetTargetValueVisitor, Value *> {
512 Value *visitInstruction(Instruction &Inst) { return &Inst; }
514 Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
516 Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
517 return Inst.getPointerOperand();
520 Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
521 return Inst.getPointerOperand();
524 Value *visitInsertElementInst(InsertElementInst &Inst) {
525 return Inst.getOperand(0);
528 Value *visitInsertValueInst(InsertValueInst &Inst) {
529 return Inst.getAggregateOperand();
533 // Set building requires a weighted bidirectional graph.
534 template <typename EdgeTypeT> class WeightedBidirectionalGraph {
536 typedef std::size_t Node;
539 LLVM_CONSTEXPR static Node StartNode = Node(0);
545 bool operator==(const Edge &E) const {
546 return Weight == E.Weight && Other == E.Other;
549 bool operator!=(const Edge &E) const { return !operator==(E); }
553 std::vector<Edge> Edges;
556 std::vector<NodeImpl> NodeImpls;
558 bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
560 const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
561 NodeImpl &getNode(Node N) { return NodeImpls[N]; }
564 // ----- Various Edge iterators for the graph ----- //
566 // \brief Iterator for edges. Because this graph is bidirected, we don't
567 // allow modificaiton of the edges using this iterator. Additionally, the
568 // iterator becomes invalid if you add edges to or from the node you're
569 // getting the edges of.
570 struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
571 std::tuple<EdgeTypeT, Node *>> {
572 EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
575 EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
577 EdgeIterator &operator++() {
582 EdgeIterator operator++(int) {
583 EdgeIterator Copy(Current);
588 std::tuple<EdgeTypeT, Node> &operator*() {
589 Store = std::make_tuple(Current->Weight, Current->Other);
593 bool operator==(const EdgeIterator &Other) const {
594 return Current == Other.Current;
597 bool operator!=(const EdgeIterator &Other) const {
598 return !operator==(Other);
602 typename std::vector<Edge>::const_iterator Current;
603 std::tuple<EdgeTypeT, Node> Store;
606 // Wrapper for EdgeIterator with begin()/end() calls.
607 struct EdgeIterable {
608 EdgeIterable(const std::vector<Edge> &Edges)
609 : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
611 EdgeIterator begin() { return EdgeIterator(BeginIter); }
613 EdgeIterator end() { return EdgeIterator(EndIter); }
616 typename std::vector<Edge>::const_iterator BeginIter;
617 typename std::vector<Edge>::const_iterator EndIter;
620 // ----- Actual graph-related things ----- //
622 WeightedBidirectionalGraph() = default;
624 WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
625 : NodeImpls(std::move(Other.NodeImpls)) {}
627 WeightedBidirectionalGraph<EdgeTypeT> &
628 operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
629 NodeImpls = std::move(Other.NodeImpls);
634 auto Index = NodeImpls.size();
635 auto NewNode = Node(Index);
636 NodeImpls.push_back(NodeImpl());
640 void addEdge(Node From, Node To, const EdgeTypeT &Weight,
641 const EdgeTypeT &ReverseWeight) {
642 assert(inbounds(From));
643 assert(inbounds(To));
644 auto &FromNode = getNode(From);
645 auto &ToNode = getNode(To);
646 FromNode.Edges.push_back(Edge{Weight, To});
647 ToNode.Edges.push_back(Edge{ReverseWeight, From});
650 EdgeIterable edgesFor(const Node &N) const {
651 const auto &Node = getNode(N);
652 return EdgeIterable(Node.Edges);
655 bool empty() const { return NodeImpls.empty(); }
656 std::size_t size() const { return NodeImpls.size(); }
658 // \brief Gets an arbitrary node in the graph as a starting point for
660 Node getEntryNode() {
661 assert(inbounds(StartNode));
666 typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
667 typedef DenseMap<Value *, GraphT::Node> NodeMapT;
670 // -- Setting up/registering CFLAA pass -- //
671 char CFLAliasAnalysis::ID = 0;
673 INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
674 "CFL-Based AA implementation", false, true, false)
676 ImmutablePass *llvm::createCFLAliasAnalysisPass() {
677 return new CFLAliasAnalysis();
680 //===----------------------------------------------------------------------===//
681 // Function declarations that require types defined in the namespace above
682 //===----------------------------------------------------------------------===//
684 // Given an argument number, returns the appropriate Attr index to set.
685 static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
687 // Given a Value, potentially return which AttrIndex it maps to.
688 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
690 // Gets the inverse of a given EdgeType.
691 static EdgeType flipWeight(EdgeType);
693 // Gets edges of the given Instruction*, writing them to the SmallVector*.
694 static void argsToEdges(CFLAliasAnalysis &, Instruction *,
695 SmallVectorImpl<Edge> &);
697 // Gets the "Level" that one should travel in StratifiedSets
698 // given an EdgeType.
699 static Level directionOfEdgeType(EdgeType);
701 // Builds the graph needed for constructing the StratifiedSets for the
703 static void buildGraphFrom(CFLAliasAnalysis &, Function *,
704 SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
706 // Builds the graph + StratifiedSets for a function.
707 static FunctionInfo buildSetsFrom(CFLAliasAnalysis &, Function *);
709 static Optional<Function *> parentFunctionOfValue(Value *Val) {
710 if (auto *Inst = dyn_cast<Instruction>(Val)) {
711 auto *Bb = Inst->getParent();
712 return Bb->getParent();
715 if (auto *Arg = dyn_cast<Argument>(Val))
716 return Arg->getParent();
720 template <typename Inst>
721 static bool getPossibleTargets(Inst *Call,
722 SmallVectorImpl<Function *> &Output) {
723 if (auto *Fn = Call->getCalledFunction()) {
724 Output.push_back(Fn);
728 // TODO: If the call is indirect, we might be able to enumerate all potential
729 // targets of the call and return them, rather than just failing.
733 static Optional<Value *> getTargetValue(Instruction *Inst) {
734 GetTargetValueVisitor V;
735 return V.visit(Inst);
738 static bool hasUsefulEdges(Instruction *Inst) {
739 bool IsNonInvokeTerminator =
740 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
741 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
744 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
745 if (isa<GlobalValue>(Val))
746 return AttrGlobalIndex;
748 if (auto *Arg = dyn_cast<Argument>(Val))
749 if (!Arg->hasNoAliasAttr())
750 return argNumberToAttrIndex(Arg->getArgNo());
754 static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
755 if (ArgNum > AttrMaxNumArgs)
757 return ArgNum + AttrFirstArgIndex;
760 static EdgeType flipWeight(EdgeType Initial) {
762 case EdgeType::Assign:
763 return EdgeType::Assign;
764 case EdgeType::Dereference:
765 return EdgeType::Reference;
766 case EdgeType::Reference:
767 return EdgeType::Dereference;
769 llvm_unreachable("Incomplete coverage of EdgeType enum");
772 static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
773 SmallVectorImpl<Edge> &Output) {
774 GetEdgesVisitor v(Analysis, Output);
778 static Level directionOfEdgeType(EdgeType Weight) {
780 case EdgeType::Reference:
782 case EdgeType::Dereference:
784 case EdgeType::Assign:
787 llvm_unreachable("Incomplete switch coverage");
790 // Aside: We may remove graph construction entirely, because it doesn't really
791 // buy us much that we don't already have. I'd like to add interprocedural
792 // analysis prior to this however, in case that somehow requires the graph
793 // produced by this for efficient execution
794 static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
795 SmallVectorImpl<Value *> &ReturnedValues,
796 NodeMapT &Map, GraphT &Graph) {
797 const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
798 auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
799 auto &Iter = Pair.first;
801 auto NewNode = Graph.addNode();
802 Iter->second = NewNode;
807 SmallVector<Edge, 8> Edges;
808 for (auto &Bb : Fn->getBasicBlockList()) {
809 for (auto &Inst : Bb.getInstList()) {
810 // We don't want the edges of most "return" instructions, but we *do* want
811 // to know what can be returned.
812 if (auto *Ret = dyn_cast<ReturnInst>(&Inst))
813 ReturnedValues.push_back(Ret);
815 if (!hasUsefulEdges(&Inst))
819 argsToEdges(Analysis, &Inst, Edges);
821 // In the case of an unused alloca (or similar), edges may be empty. Note
822 // that it exists so we can potentially answer NoAlias.
824 auto MaybeVal = getTargetValue(&Inst);
825 assert(MaybeVal.hasValue());
826 auto *Target = *MaybeVal;
827 findOrInsertNode(Target);
831 for (const Edge &E : Edges) {
832 auto To = findOrInsertNode(E.To);
833 auto From = findOrInsertNode(E.From);
834 auto FlippedWeight = flipWeight(E.Weight);
835 auto Attrs = E.AdditionalAttrs;
836 Graph.addEdge(From, To, {E.Weight, Attrs}, {FlippedWeight, Attrs});
842 static FunctionInfo buildSetsFrom(CFLAliasAnalysis &Analysis, Function *Fn) {
845 SmallVector<Value *, 4> ReturnedValues;
847 buildGraphFrom(Analysis, Fn, ReturnedValues, Map, Graph);
849 DenseMap<GraphT::Node, Value *> NodeValueMap;
850 NodeValueMap.resize(Map.size());
851 for (const auto &Pair : Map)
852 NodeValueMap.insert({Pair.second, Pair.first});
854 const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
855 auto ValIter = NodeValueMap.find(Node);
856 assert(ValIter != NodeValueMap.end());
857 return ValIter->second;
860 StratifiedSetsBuilder<Value *> Builder;
862 SmallVector<GraphT::Node, 16> Worklist;
863 for (auto &Pair : Map) {
866 auto *Value = Pair.first;
868 auto InitialNode = Pair.second;
869 Worklist.push_back(InitialNode);
870 while (!Worklist.empty()) {
871 auto Node = Worklist.pop_back_val();
872 auto *CurValue = findValueOrDie(Node);
873 if (isa<Constant>(CurValue) && !isa<GlobalValue>(CurValue))
876 for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
877 auto Weight = std::get<0>(EdgeTuple);
878 auto Label = Weight.first;
879 auto &OtherNode = std::get<1>(EdgeTuple);
880 auto *OtherValue = findValueOrDie(OtherNode);
882 if (isa<Constant>(OtherValue) && !isa<GlobalValue>(OtherValue))
886 switch (directionOfEdgeType(Label)) {
888 Added = Builder.addAbove(CurValue, OtherValue);
891 Added = Builder.addBelow(CurValue, OtherValue);
894 Added = Builder.addWith(CurValue, OtherValue);
899 auto Aliasing = Weight.second;
900 if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
901 Aliasing.set(*MaybeCurIndex);
902 if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
903 Aliasing.set(*MaybeOtherIndex);
904 Builder.noteAttributes(CurValue, Aliasing);
905 Builder.noteAttributes(OtherValue, Aliasing);
906 Worklist.push_back(OtherNode);
912 // There are times when we end up with parameters not in our graph (i.e. if
913 // it's only used as the condition of a branch). Other bits of code depend on
914 // things that were present during construction being present in the graph.
915 // So, we add all present arguments here.
916 for (auto &Arg : Fn->args()) {
920 return {Builder.build(), std::move(ReturnedValues)};
923 void CFLAliasAnalysis::scan(Function *Fn) {
924 auto InsertPair = Cache.insert({Fn, Optional<FunctionInfo>()});
926 assert(InsertPair.second &&
927 "Trying to scan a function that has already been cached");
929 FunctionInfo Info(buildSetsFrom(*this, Fn));
930 Cache[Fn] = std::move(Info);
931 Handles.push_front(FunctionHandle(Fn, this));
934 AliasAnalysis::AliasResult
935 CFLAliasAnalysis::query(const AliasAnalysis::Location &LocA,
936 const AliasAnalysis::Location &LocB) {
937 auto *ValA = const_cast<Value *>(LocA.Ptr);
938 auto *ValB = const_cast<Value *>(LocB.Ptr);
940 Function *Fn = nullptr;
941 auto MaybeFnA = parentFunctionOfValue(ValA);
942 auto MaybeFnB = parentFunctionOfValue(ValB);
943 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
944 llvm_unreachable("Don't know how to extract the parent function "
945 "from values A or B");
948 if (MaybeFnA.hasValue()) {
950 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
951 "Interprocedural queries not supported");
956 assert(Fn != nullptr);
957 auto &MaybeInfo = ensureCached(Fn);
958 assert(MaybeInfo.hasValue());
960 auto &Sets = MaybeInfo->Sets;
961 auto MaybeA = Sets.find(ValA);
962 if (!MaybeA.hasValue())
963 return AliasAnalysis::MayAlias;
965 auto MaybeB = Sets.find(ValB);
966 if (!MaybeB.hasValue())
967 return AliasAnalysis::MayAlias;
972 if (SetA.Index == SetB.Index)
973 return AliasAnalysis::PartialAlias;
975 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
976 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
977 auto CombinedAttrs = AttrsA | AttrsB;
978 if (CombinedAttrs.any())
979 return AliasAnalysis::PartialAlias;
981 return AliasAnalysis::NoAlias;