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, or Assign.
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.
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
28 //===----------------------------------------------------------------------===//
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"
54 #define DEBUG_TYPE "cfl-aa"
56 CFLAAResult::CFLAAResult(const TargetLibraryInfo &TLI) : AAResultBase(TLI) {}
57 CFLAAResult::CFLAAResult(CFLAAResult &&Arg) : AAResultBase(std::move(Arg)) {}
59 // \brief Information we have about a function and would like to keep around
60 struct CFLAAResult::FunctionInfo {
61 StratifiedSets<Value *> Sets;
62 // Lots of functions have < 4 returns. Adjust as necessary.
63 SmallVector<Value *, 4> ReturnedValues;
65 FunctionInfo(StratifiedSets<Value *> &&S, SmallVector<Value *, 4> &&RV)
66 : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
69 // Try to go from a Value* to a Function*. Never returns nullptr.
70 static Optional<Function *> parentFunctionOfValue(Value *);
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
77 template <typename Inst>
78 static bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &);
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.
85 static Optional<Value *> getTargetValue(Instruction *);
87 // There are certain instructions (i.e. FenceInst, etc.) that we ignore.
88 // This notes that we should ignore those.
89 static bool hasUsefulEdges(Instruction *);
91 const StratifiedIndex StratifiedLink::SetSentinel =
92 std::numeric_limits<StratifiedIndex>::max();
95 // StratifiedInfo Attribute things.
96 typedef unsigned StratifiedAttr;
97 LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
98 LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
99 LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
100 LLVM_CONSTEXPR unsigned AttrUnknownIndex = 2;
101 LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 3;
102 LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
103 LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
105 LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
106 LLVM_CONSTEXPR StratifiedAttr AttrUnknown = 1 << AttrUnknownIndex;
107 LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
109 // \brief StratifiedSets call for knowledge of "direction", so this is how we
110 // represent that locally.
111 enum class Level { Same, Above, Below };
113 // \brief Edges can be one of four "weights" -- each weight must have an inverse
114 // weight (Assign has Assign; Reference has Dereference).
115 enum 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.
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)
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)
135 // \brief Encodes the notion of a "use"
137 // \brief Which value the edge is coming from
140 // \brief Which value the edge is pointing to
143 // \brief Edge weight
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;
151 Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
152 : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
155 // \brief Gets the edges our graph should have, based on an Instruction*
156 class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
158 SmallVectorImpl<Edge> &Output;
161 GetEdgesVisitor(CFLAAResult &AA, SmallVectorImpl<Edge> &Output)
162 : AA(AA), Output(Output) {}
164 void visitInstruction(Instruction &) {
165 llvm_unreachable("Unsupported instruction encountered");
168 void visitPtrToIntInst(PtrToIntInst &Inst) {
169 auto *Ptr = Inst.getOperand(0);
170 Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
173 void visitIntToPtrInst(IntToPtrInst &Inst) {
175 Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
178 void visitCastInst(CastInst &Inst) {
180 Edge(&Inst, Inst.getOperand(0), EdgeType::Assign, AttrNone));
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));
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));
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));
202 void visitPHINode(PHINode &Inst) {
203 for (Value *Val : Inst.incoming_values()) {
204 Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
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));
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.
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));
227 void visitAllocaInst(AllocaInst &) {}
229 void visitLoadInst(LoadInst &Inst) {
230 auto *Ptr = Inst.getPointerOperand();
232 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
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));
241 void visitVAArgInst(VAArgInst &Inst) {
242 // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
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).
249 Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll));
252 static bool isFunctionExternal(Function *Fn) {
253 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
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)
264 const auto *Current = &Sets.getLink(Index1);
265 while (Current->hasBelow()) {
266 if (Current->Below == Index2)
268 Current = &Sets.getLink(Current->Below);
271 Current = &Sets.getLink(Index1);
272 while (Current->hasAbove()) {
273 if (Current->Above == Index2)
275 Current = &Sets.getLink(Current->Above);
282 tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
284 const iterator_range<User::op_iterator> &Args) {
285 const unsigned ExpectedMaxArgs = 8;
286 const unsigned MaxSupportedArgs = 50;
287 assert(Fns.size() > 0);
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)
294 // Exit early if we'll fail anyway
295 for (auto *Fn : Fns) {
296 if (isFunctionExternal(Fn) || Fn->isVarArg())
298 auto &MaybeInfo = AA.ensureCached(Fn);
299 if (!MaybeInfo.hasValue())
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;
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())
316 Parameters.push_back(*MaybeInfo);
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())
331 auto &RetInfo = *MaybeInfo;
332 auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
333 auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
335 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
336 if (MaybeRelation.hasValue()) {
338 Externals |= RetAttrs | ParamAttrs;
342 Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
343 StratifiedAttrs().flip()));
346 if (Parameters.size() != Arguments.size())
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;
364 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
366 if (!MaybeRelation.hasValue())
369 auto NewAttrs = SubAttrs | MainAttrs;
370 Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
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()))
384 // Cleanup from interprocedural analysis
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));
400 void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
402 void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
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
409 void visitExtractElementInst(ExtractElementInst &Inst) {
410 auto *Ptr = Inst.getVectorOperand();
412 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
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));
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
426 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
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));
436 void visitExtractValueInst(ExtractValueInst &Inst) {
437 auto *Ptr = Inst.getAggregateOperand();
438 Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
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));
448 void visitConstantExpr(ConstantExpr *CE) {
449 switch (CE->getOpcode()) {
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); \
457 #include "llvm/IR/Instruction.def"
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.
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.
472 class GetTargetValueVisitor
473 : public InstVisitor<GetTargetValueVisitor, Value *> {
475 Value *visitInstruction(Instruction &Inst) { return &Inst; }
477 Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
479 Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
480 return Inst.getPointerOperand();
483 Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
484 return Inst.getPointerOperand();
487 Value *visitInsertElementInst(InsertElementInst &Inst) {
488 return Inst.getOperand(0);
491 Value *visitInsertValueInst(InsertValueInst &Inst) {
492 return Inst.getAggregateOperand();
496 // Set building requires a weighted bidirectional graph.
497 template <typename EdgeTypeT> class WeightedBidirectionalGraph {
499 typedef std::size_t Node;
502 const static Node StartNode = Node(0);
508 Edge(const EdgeTypeT &W, const Node &N) : Weight(W), Other(N) {}
510 bool operator==(const Edge &E) const {
511 return Weight == E.Weight && Other == E.Other;
514 bool operator!=(const Edge &E) const { return !operator==(E); }
518 std::vector<Edge> Edges;
521 std::vector<NodeImpl> NodeImpls;
523 bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
525 const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
526 NodeImpl &getNode(Node N) { return NodeImpls[N]; }
529 // ----- Various Edge iterators for the graph ----- //
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)
540 EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
542 EdgeIterator &operator++() {
547 EdgeIterator operator++(int) {
548 EdgeIterator Copy(Current);
553 std::tuple<EdgeTypeT, Node> &operator*() {
554 Store = std::make_tuple(Current->Weight, Current->Other);
558 bool operator==(const EdgeIterator &Other) const {
559 return Current == Other.Current;
562 bool operator!=(const EdgeIterator &Other) const {
563 return !operator==(Other);
567 typename std::vector<Edge>::const_iterator Current;
568 std::tuple<EdgeTypeT, Node> Store;
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()) {}
576 EdgeIterator begin() { return EdgeIterator(BeginIter); }
578 EdgeIterator end() { return EdgeIterator(EndIter); }
581 typename std::vector<Edge>::const_iterator BeginIter;
582 typename std::vector<Edge>::const_iterator EndIter;
585 // ----- Actual graph-related things ----- //
587 WeightedBidirectionalGraph() {}
589 WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
590 : NodeImpls(std::move(Other.NodeImpls)) {}
592 WeightedBidirectionalGraph<EdgeTypeT> &
593 operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
594 NodeImpls = std::move(Other.NodeImpls);
599 auto Index = NodeImpls.size();
600 auto NewNode = Node(Index);
601 NodeImpls.push_back(NodeImpl());
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));
615 EdgeIterable edgesFor(const Node &N) const {
616 const auto &Node = getNode(N);
617 return EdgeIterable(Node.Edges);
620 bool empty() const { return NodeImpls.empty(); }
621 std::size_t size() const { return NodeImpls.size(); }
623 // \brief Gets an arbitrary node in the graph as a starting point for
625 Node getEntryNode() {
626 assert(inbounds(StartNode));
631 typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
632 typedef DenseMap<Value *, GraphT::Node> NodeMapT;
635 //===----------------------------------------------------------------------===//
636 // Function declarations that require types defined in the namespace above
637 //===----------------------------------------------------------------------===//
639 // Given an argument number, returns the appropriate Attr index to set.
640 static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
642 // Given a Value, potentially return which AttrIndex it maps to.
643 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
645 // Gets the inverse of a given EdgeType.
646 static EdgeType flipWeight(EdgeType);
648 // Gets edges of the given Instruction*, writing them to the SmallVector*.
649 static void argsToEdges(CFLAAResult &, Instruction *, SmallVectorImpl<Edge> &);
651 // Gets edges of the given ConstantExpr*, writing them to the SmallVector*.
652 static void argsToEdges(CFLAAResult &, ConstantExpr *, SmallVectorImpl<Edge> &);
654 // Gets the "Level" that one should travel in StratifiedSets
655 // given an EdgeType.
656 static Level directionOfEdgeType(EdgeType);
658 // Builds the graph needed for constructing the StratifiedSets for the
660 static void buildGraphFrom(CFLAAResult &, Function *,
661 SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
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.
666 static void constexprToEdges(CFLAAResult &, ConstantExpr &,
667 SmallVectorImpl<Edge> &);
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.
675 static void addInstructionToGraph(CFLAAResult &, Instruction &,
676 SmallVectorImpl<Value *> &, NodeMapT &,
679 // Notes whether it would be pointless to add the given Value to our sets.
680 static bool canSkipAddingToSets(Value *Val);
682 static Optional<Function *> parentFunctionOfValue(Value *Val) {
683 if (auto *Inst = dyn_cast<Instruction>(Val)) {
684 auto *Bb = Inst->getParent();
685 return Bb->getParent();
688 if (auto *Arg = dyn_cast<Argument>(Val))
689 return Arg->getParent();
693 template <typename Inst>
694 static bool getPossibleTargets(Inst *Call,
695 SmallVectorImpl<Function *> &Output) {
696 if (auto *Fn = Call->getCalledFunction()) {
697 Output.push_back(Fn);
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.
706 static Optional<Value *> getTargetValue(Instruction *Inst) {
707 GetTargetValueVisitor V;
708 return V.visit(Inst);
711 static bool hasUsefulEdges(Instruction *Inst) {
712 bool IsNonInvokeTerminator =
713 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
714 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
717 static 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;
724 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
725 if (isa<GlobalValue>(Val))
726 return AttrGlobalIndex;
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());
737 static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
738 if (ArgNum >= AttrMaxNumArgs)
740 return ArgNum + AttrFirstArgIndex;
743 static EdgeType flipWeight(EdgeType 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;
752 llvm_unreachable("Incomplete coverage of EdgeType enum");
755 static 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);
763 static 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);
770 static Level directionOfEdgeType(EdgeType Weight) {
772 case EdgeType::Reference:
774 case EdgeType::Dereference:
776 case EdgeType::Assign:
779 llvm_unreachable("Incomplete switch coverage");
782 static void constexprToEdges(CFLAAResult &Analysis,
783 ConstantExpr &CExprToCollapse,
784 SmallVectorImpl<Edge> &Results) {
785 SmallVector<ConstantExpr *, 4> Worklist;
786 Worklist.push_back(&CExprToCollapse);
788 SmallVector<Edge, 8> ConstexprEdges;
789 SmallPtrSet<ConstantExpr *, 4> Visited;
790 while (!Worklist.empty()) {
791 auto *CExpr = Worklist.pop_back_val();
793 if (!hasUsefulEdges(CExpr))
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);
803 if (auto *Nested = dyn_cast<ConstantExpr>(Edge.To))
804 if (Visited.insert(Nested).second)
805 Worklist.push_back(Nested);
808 Results.append(ConstexprEdges.begin(), ConstexprEdges.end());
812 static 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;
819 auto NewNode = Graph.addNode();
820 Iter->second = NewNode;
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);
830 if (!hasUsefulEdges(&Inst))
833 SmallVector<Edge, 8> Edges;
834 argsToEdges(Analysis, &Inst, Edges);
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.
839 auto MaybeVal = getTargetValue(&Inst);
840 assert(MaybeVal.hasValue());
841 auto *Target = *MaybeVal;
842 findOrInsertNode(Target);
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));
855 SmallVector<ConstantExpr *, 4> ConstantExprs;
856 for (const Edge &E : Edges) {
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);
864 for (ConstantExpr *CE : ConstantExprs) {
866 constexprToEdges(Analysis, *CE, Edges);
867 std::for_each(Edges.begin(), Edges.end(), addEdgeToGraph);
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
875 static 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);
883 static bool canSkipAddingToSets(Value *Val) {
884 // Constants can share instances, which may falsely unify multiple
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
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;
905 // Builds the graph + StratifiedSets for a function.
906 CFLAAResult::FunctionInfo CFLAAResult::buildSetsFrom(Function *Fn) {
909 SmallVector<Value *, 4> ReturnedValues;
911 buildGraphFrom(*this, Fn, ReturnedValues, Map, Graph);
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));
918 const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
919 auto ValIter = NodeValueMap.find(Node);
920 assert(ValIter != NodeValueMap.end());
921 return ValIter->second;
924 StratifiedSetsBuilder<Value *> Builder;
926 SmallVector<GraphT::Node, 16> Worklist;
927 for (auto &Pair : Map) {
930 auto *Value = Pair.first;
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))
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);
946 if (canSkipAddingToSets(OtherValue))
950 switch (directionOfEdgeType(Label)) {
952 Added = Builder.addAbove(CurValue, OtherValue);
955 Added = Builder.addBelow(CurValue, OtherValue);
958 Added = Builder.addWith(CurValue, OtherValue);
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);
971 Worklist.push_back(OtherNode);
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))
984 auto Attrs = valueToAttrIndex(&Arg);
985 if (Attrs.hasValue())
986 Builder.noteAttributes(&Arg, *Attrs);
989 return FunctionInfo(Builder.build(), std::move(ReturnedValues));
992 void CFLAAResult::scan(Function *Fn) {
993 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
995 assert(InsertPair.second &&
996 "Trying to scan a function that has already been cached");
998 FunctionInfo Info(buildSetsFrom(Fn));
999 Cache[Fn] = std::move(Info);
1000 Handles.push_front(FunctionHandle(Fn, this));
1003 void CFLAAResult::evict(Function *Fn) { Cache.erase(Fn); }
1005 /// \brief Ensures that the given function is available in the cache.
1006 /// Returns the appropriate entry from the cache.
1007 const Optional<CFLAAResult::FunctionInfo> &
1008 CFLAAResult::ensureCached(Function *Fn) {
1009 auto Iter = Cache.find(Fn);
1010 if (Iter == Cache.end()) {
1012 Iter = Cache.find(Fn);
1013 assert(Iter != Cache.end());
1014 assert(Iter->second.hasValue());
1016 return Iter->second;
1019 AliasResult 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);
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
1030 DEBUG(dbgs() << "CFLAA: could not extract parent function information.\n");
1034 if (MaybeFnA.hasValue()) {
1036 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
1037 "Interprocedural queries not supported");
1042 assert(Fn != nullptr);
1043 auto &MaybeInfo = ensureCached(Fn);
1044 assert(MaybeInfo.hasValue());
1046 auto &Sets = MaybeInfo->Sets;
1047 auto MaybeA = Sets.find(ValA);
1048 if (!MaybeA.hasValue())
1051 auto MaybeB = Sets.find(ValB);
1052 if (!MaybeB.hasValue())
1055 auto SetA = *MaybeA;
1056 auto SetB = *MaybeB;
1057 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
1058 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
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())
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
1080 if (SetA.Index == SetB.Index)
1086 CFLAAResult CFLAA::run(Function &F, AnalysisManager<Function> *AM) {
1087 return CFLAAResult(AM->getResult<TargetLibraryAnalysis>(F));
1092 char CFLAAWrapperPass::ID = 0;
1093 INITIALIZE_PASS_BEGIN(CFLAAWrapperPass, "cfl-aa", "CFL-Based Alias Analysis",
1095 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1096 INITIALIZE_PASS_END(CFLAAWrapperPass, "cfl-aa", "CFL-Based Alias Analysis",
1099 ImmutablePass *llvm::createCFLAAWrapperPass() { return new CFLAAWrapperPass(); }
1101 CFLAAWrapperPass::CFLAAWrapperPass() : ImmutablePass(ID) {
1102 initializeCFLAAWrapperPassPass(*PassRegistry::getPassRegistry());
1105 bool CFLAAWrapperPass::doInitialization(Module &M) {
1107 new CFLAAResult(getAnalysis<TargetLibraryInfoWrapperPass>().getTLI()));
1111 bool CFLAAWrapperPass::doFinalization(Module &M) {
1116 void CFLAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1117 AU.setPreservesAll();
1118 AU.addRequired<TargetLibraryInfoWrapperPass>();