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/AliasAnalysis.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 // -- Setting up/registering CFLAA pass -- //
57 char CFLAliasAnalysis::ID = 0;
59 INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
60 "CFL-Based AA implementation", false, true, false)
62 ImmutablePass *llvm::createCFLAliasAnalysisPass() {
63 return new CFLAliasAnalysis();
66 // \brief Information we have about a function and would like to keep around
67 struct CFLAliasAnalysis::FunctionInfo {
68 StratifiedSets<Value *> Sets;
69 // Lots of functions have < 4 returns. Adjust as necessary.
70 SmallVector<Value *, 4> ReturnedValues;
72 FunctionInfo(StratifiedSets<Value *> &&S, SmallVector<Value *, 4> &&RV)
73 : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
76 CFLAliasAnalysis::CFLAliasAnalysis() : ImmutablePass(ID) {
77 initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
80 CFLAliasAnalysis::~CFLAliasAnalysis() {}
82 void CFLAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
83 AliasAnalysis::getAnalysisUsage(AU);
86 void *CFLAliasAnalysis::getAdjustedAnalysisPointer(const void *ID) {
87 if (ID == &AliasAnalysis::ID)
88 return (AliasAnalysis *)this;
92 // Try to go from a Value* to a Function*. Never returns nullptr.
93 static Optional<Function *> parentFunctionOfValue(Value *);
95 // Returns possible functions called by the Inst* into the given
96 // SmallVectorImpl. Returns true if targets found, false otherwise.
97 // This is templated because InvokeInst/CallInst give us the same
98 // set of functions that we care about, and I don't like repeating
100 template <typename Inst>
101 static bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &);
103 // Some instructions need to have their users tracked. Instructions like
104 // `add` require you to get the users of the Instruction* itself, other
105 // instructions like `store` require you to get the users of the first
106 // operand. This function gets the "proper" value to track for each
107 // type of instruction we support.
108 static Optional<Value *> getTargetValue(Instruction *);
110 // There are certain instructions (i.e. FenceInst, etc.) that we ignore.
111 // This notes that we should ignore those.
112 static bool hasUsefulEdges(Instruction *);
114 const StratifiedIndex StratifiedLink::SetSentinel =
115 std::numeric_limits<StratifiedIndex>::max();
118 // StratifiedInfo Attribute things.
119 typedef unsigned StratifiedAttr;
120 LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
121 LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
122 LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
123 LLVM_CONSTEXPR unsigned AttrUnknownIndex = 2;
124 LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 3;
125 LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
126 LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
128 LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
129 LLVM_CONSTEXPR StratifiedAttr AttrUnknown = 1 << AttrUnknownIndex;
130 LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
132 // \brief StratifiedSets call for knowledge of "direction", so this is how we
133 // represent that locally.
134 enum class Level { Same, Above, Below };
136 // \brief Edges can be one of four "weights" -- each weight must have an inverse
137 // weight (Assign has Assign; Reference has Dereference).
138 enum class EdgeType {
139 // The weight assigned when assigning from or to a value. For example, in:
140 // %b = getelementptr %a, 0
141 // ...The relationships are %b assign %a, and %a assign %b. This used to be
142 // two edges, but having a distinction bought us nothing.
145 // The edge used when we have an edge going from some handle to a Value.
146 // Examples of this include:
147 // %b = load %a (%b Dereference %a)
148 // %b = extractelement %a, 0 (%a Dereference %b)
151 // The edge used when our edge goes from a value to a handle that may have
152 // contained it at some point. Examples:
153 // %b = load %a (%a Reference %b)
154 // %b = extractelement %a, 0 (%b Reference %a)
158 // \brief Encodes the notion of a "use"
160 // \brief Which value the edge is coming from
163 // \brief Which value the edge is pointing to
166 // \brief Edge weight
169 // \brief Whether we aliased any external values along the way that may be
170 // invisible to the analysis (i.e. landingpad for exceptions, calls for
171 // interprocedural analysis, etc.)
172 StratifiedAttrs AdditionalAttrs;
174 Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
175 : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
178 // \brief Gets the edges our graph should have, based on an Instruction*
179 class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
180 CFLAliasAnalysis &AA;
181 SmallVectorImpl<Edge> &Output;
184 GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
185 : AA(AA), Output(Output) {}
187 void visitInstruction(Instruction &) {
188 llvm_unreachable("Unsupported instruction encountered");
191 void visitPtrToIntInst(PtrToIntInst &Inst) {
192 auto *Ptr = Inst.getOperand(0);
193 Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
196 void visitIntToPtrInst(IntToPtrInst &Inst) {
198 Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
201 void visitCastInst(CastInst &Inst) {
203 Edge(&Inst, Inst.getOperand(0), EdgeType::Assign, AttrNone));
206 void visitBinaryOperator(BinaryOperator &Inst) {
207 auto *Op1 = Inst.getOperand(0);
208 auto *Op2 = Inst.getOperand(1);
209 Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
210 Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
213 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
214 auto *Ptr = Inst.getPointerOperand();
215 auto *Val = Inst.getNewValOperand();
216 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
219 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
220 auto *Ptr = Inst.getPointerOperand();
221 auto *Val = Inst.getValOperand();
222 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
225 void visitPHINode(PHINode &Inst) {
226 for (Value *Val : Inst.incoming_values()) {
227 Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
231 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
232 auto *Op = Inst.getPointerOperand();
233 Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
234 for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
235 Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
238 void visitSelectInst(SelectInst &Inst) {
239 // Condition is not processed here (The actual statement producing
240 // the condition result is processed elsewhere). For select, the
241 // condition is evaluated, but not loaded, stored, or assigned
242 // simply as a result of being the condition of a select.
244 auto *TrueVal = Inst.getTrueValue();
245 Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
246 auto *FalseVal = Inst.getFalseValue();
247 Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
250 void visitAllocaInst(AllocaInst &) {}
252 void visitLoadInst(LoadInst &Inst) {
253 auto *Ptr = Inst.getPointerOperand();
255 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
258 void visitStoreInst(StoreInst &Inst) {
259 auto *Ptr = Inst.getPointerOperand();
260 auto *Val = Inst.getValueOperand();
261 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
264 void visitVAArgInst(VAArgInst &Inst) {
265 // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
267 // 1. Loads a value from *((T*)*Ptr).
268 // 2. Increments (stores to) *Ptr by some target-specific amount.
269 // For now, we'll handle this like a landingpad instruction (by placing the
270 // result in its own group, and having that group alias externals).
272 Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll));
275 static bool isFunctionExternal(Function *Fn) {
276 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
279 // Gets whether the sets at Index1 above, below, or equal to the sets at
280 // Index2. Returns None if they are not in the same set chain.
281 static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
282 StratifiedIndex Index1,
283 StratifiedIndex Index2) {
284 if (Index1 == Index2)
287 const auto *Current = &Sets.getLink(Index1);
288 while (Current->hasBelow()) {
289 if (Current->Below == Index2)
291 Current = &Sets.getLink(Current->Below);
294 Current = &Sets.getLink(Index1);
295 while (Current->hasAbove()) {
296 if (Current->Above == Index2)
298 Current = &Sets.getLink(Current->Above);
305 tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
307 const iterator_range<User::op_iterator> &Args) {
308 const unsigned ExpectedMaxArgs = 8;
309 const unsigned MaxSupportedArgs = 50;
310 assert(Fns.size() > 0);
312 // I put this here to give us an upper bound on time taken by IPA. Is it
313 // really (realistically) needed? Keep in mind that we do have an n^2 algo.
314 if (std::distance(Args.begin(), Args.end()) > (int)MaxSupportedArgs)
317 // Exit early if we'll fail anyway
318 for (auto *Fn : Fns) {
319 if (isFunctionExternal(Fn) || Fn->isVarArg())
321 auto &MaybeInfo = AA.ensureCached(Fn);
322 if (!MaybeInfo.hasValue())
326 SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
327 SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
328 for (auto *Fn : Fns) {
329 auto &Info = *AA.ensureCached(Fn);
330 auto &Sets = Info.Sets;
331 auto &RetVals = Info.ReturnedValues;
334 for (auto &Param : Fn->args()) {
335 auto MaybeInfo = Sets.find(&Param);
336 // Did a new parameter somehow get added to the function/slip by?
337 if (!MaybeInfo.hasValue())
339 Parameters.push_back(*MaybeInfo);
342 // Adding an edge from argument -> return value for each parameter that
343 // may alias the return value
344 for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
345 auto &ParamInfo = Parameters[I];
346 auto &ArgVal = Arguments[I];
347 bool AddEdge = false;
348 StratifiedAttrs Externals;
349 for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
350 auto MaybeInfo = Sets.find(RetVals[X]);
351 if (!MaybeInfo.hasValue())
354 auto &RetInfo = *MaybeInfo;
355 auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
356 auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
358 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
359 if (MaybeRelation.hasValue()) {
361 Externals |= RetAttrs | ParamAttrs;
365 Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
366 StratifiedAttrs().flip()));
369 if (Parameters.size() != Arguments.size())
372 // Adding edges between arguments for arguments that may end up aliasing
373 // each other. This is necessary for functions such as
374 // void foo(int** a, int** b) { *a = *b; }
375 // (Technically, the proper sets for this would be those below
376 // Arguments[I] and Arguments[X], but our algorithm will produce
377 // extremely similar, and equally correct, results either way)
378 for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
379 auto &MainVal = Arguments[I];
380 auto &MainInfo = Parameters[I];
381 auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
382 for (unsigned X = I + 1; X != E; ++X) {
383 auto &SubInfo = Parameters[X];
384 auto &SubVal = Arguments[X];
385 auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
387 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
389 if (!MaybeRelation.hasValue())
392 auto NewAttrs = SubAttrs | MainAttrs;
393 Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
400 template <typename InstT> void visitCallLikeInst(InstT &Inst) {
401 SmallVector<Function *, 4> Targets;
402 if (getPossibleTargets(&Inst, Targets)) {
403 if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
405 // Cleanup from interprocedural analysis
409 for (Value *V : Inst.arg_operands())
410 Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
413 void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
415 void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
417 // Because vectors/aggregates are immutable and unaddressable,
418 // there's nothing we can do to coax a value out of them, other
419 // than calling Extract{Element,Value}. We can effectively treat
420 // them as pointers to arbitrary memory locations we can store in
422 void visitExtractElementInst(ExtractElementInst &Inst) {
423 auto *Ptr = Inst.getVectorOperand();
425 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
428 void visitInsertElementInst(InsertElementInst &Inst) {
429 auto *Vec = Inst.getOperand(0);
430 auto *Val = Inst.getOperand(1);
431 Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
432 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
435 void visitLandingPadInst(LandingPadInst &Inst) {
436 // Exceptions come from "nowhere", from our analysis' perspective.
437 // So we place the instruction its own group, noting that said group may
439 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
442 void visitInsertValueInst(InsertValueInst &Inst) {
443 auto *Agg = Inst.getOperand(0);
444 auto *Val = Inst.getOperand(1);
445 Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
446 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
449 void visitExtractValueInst(ExtractValueInst &Inst) {
450 auto *Ptr = Inst.getAggregateOperand();
451 Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
454 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
455 auto *From1 = Inst.getOperand(0);
456 auto *From2 = Inst.getOperand(1);
457 Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
458 Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
461 void visitConstantExpr(ConstantExpr *CE) {
462 switch (CE->getOpcode()) {
464 llvm_unreachable("Unknown instruction type encountered!");
465 // Build the switch statement using the Instruction.def file.
466 #define HANDLE_INST(NUM, OPCODE, CLASS) \
467 case Instruction::OPCODE: \
468 visit##OPCODE(*(CLASS *)CE); \
470 #include "llvm/IR/Instruction.def"
475 // For a given instruction, we need to know which Value* to get the
476 // users of in order to build our graph. In some cases (i.e. add),
477 // we simply need the Instruction*. In other cases (i.e. store),
478 // finding the users of the Instruction* is useless; we need to find
479 // the users of the first operand. This handles determining which
480 // value to follow for us.
482 // Note: we *need* to keep this in sync with GetEdgesVisitor. Add
483 // something to GetEdgesVisitor, add it here -- remove something from
484 // GetEdgesVisitor, remove it here.
485 class GetTargetValueVisitor
486 : public InstVisitor<GetTargetValueVisitor, Value *> {
488 Value *visitInstruction(Instruction &Inst) { return &Inst; }
490 Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
492 Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
493 return Inst.getPointerOperand();
496 Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
497 return Inst.getPointerOperand();
500 Value *visitInsertElementInst(InsertElementInst &Inst) {
501 return Inst.getOperand(0);
504 Value *visitInsertValueInst(InsertValueInst &Inst) {
505 return Inst.getAggregateOperand();
509 // Set building requires a weighted bidirectional graph.
510 template <typename EdgeTypeT> class WeightedBidirectionalGraph {
512 typedef std::size_t Node;
515 const static Node StartNode = Node(0);
521 Edge(const EdgeTypeT &W, const Node &N) : Weight(W), Other(N) {}
523 bool operator==(const Edge &E) const {
524 return Weight == E.Weight && Other == E.Other;
527 bool operator!=(const Edge &E) const { return !operator==(E); }
531 std::vector<Edge> Edges;
534 std::vector<NodeImpl> NodeImpls;
536 bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
538 const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
539 NodeImpl &getNode(Node N) { return NodeImpls[N]; }
542 // ----- Various Edge iterators for the graph ----- //
544 // \brief Iterator for edges. Because this graph is bidirected, we don't
545 // allow modification of the edges using this iterator. Additionally, the
546 // iterator becomes invalid if you add edges to or from the node you're
547 // getting the edges of.
548 struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
549 std::tuple<EdgeTypeT, Node *>> {
550 EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
553 EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
555 EdgeIterator &operator++() {
560 EdgeIterator operator++(int) {
561 EdgeIterator Copy(Current);
566 std::tuple<EdgeTypeT, Node> &operator*() {
567 Store = std::make_tuple(Current->Weight, Current->Other);
571 bool operator==(const EdgeIterator &Other) const {
572 return Current == Other.Current;
575 bool operator!=(const EdgeIterator &Other) const {
576 return !operator==(Other);
580 typename std::vector<Edge>::const_iterator Current;
581 std::tuple<EdgeTypeT, Node> Store;
584 // Wrapper for EdgeIterator with begin()/end() calls.
585 struct EdgeIterable {
586 EdgeIterable(const std::vector<Edge> &Edges)
587 : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
589 EdgeIterator begin() { return EdgeIterator(BeginIter); }
591 EdgeIterator end() { return EdgeIterator(EndIter); }
594 typename std::vector<Edge>::const_iterator BeginIter;
595 typename std::vector<Edge>::const_iterator EndIter;
598 // ----- Actual graph-related things ----- //
600 WeightedBidirectionalGraph() {}
602 WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
603 : NodeImpls(std::move(Other.NodeImpls)) {}
605 WeightedBidirectionalGraph<EdgeTypeT> &
606 operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
607 NodeImpls = std::move(Other.NodeImpls);
612 auto Index = NodeImpls.size();
613 auto NewNode = Node(Index);
614 NodeImpls.push_back(NodeImpl());
618 void addEdge(Node From, Node To, const EdgeTypeT &Weight,
619 const EdgeTypeT &ReverseWeight) {
620 assert(inbounds(From));
621 assert(inbounds(To));
622 auto &FromNode = getNode(From);
623 auto &ToNode = getNode(To);
624 FromNode.Edges.push_back(Edge(Weight, To));
625 ToNode.Edges.push_back(Edge(ReverseWeight, From));
628 EdgeIterable edgesFor(const Node &N) const {
629 const auto &Node = getNode(N);
630 return EdgeIterable(Node.Edges);
633 bool empty() const { return NodeImpls.empty(); }
634 std::size_t size() const { return NodeImpls.size(); }
636 // \brief Gets an arbitrary node in the graph as a starting point for
638 Node getEntryNode() {
639 assert(inbounds(StartNode));
644 typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
645 typedef DenseMap<Value *, GraphT::Node> NodeMapT;
648 //===----------------------------------------------------------------------===//
649 // Function declarations that require types defined in the namespace above
650 //===----------------------------------------------------------------------===//
652 // Given an argument number, returns the appropriate Attr index to set.
653 static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
655 // Given a Value, potentially return which AttrIndex it maps to.
656 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
658 // Gets the inverse of a given EdgeType.
659 static EdgeType flipWeight(EdgeType);
661 // Gets edges of the given Instruction*, writing them to the SmallVector*.
662 static void argsToEdges(CFLAliasAnalysis &, Instruction *,
663 SmallVectorImpl<Edge> &);
665 // Gets edges of the given ConstantExpr*, writing them to the SmallVector*.
666 static void argsToEdges(CFLAliasAnalysis &, ConstantExpr *,
667 SmallVectorImpl<Edge> &);
669 // Gets the "Level" that one should travel in StratifiedSets
670 // given an EdgeType.
671 static Level directionOfEdgeType(EdgeType);
673 // Builds the graph needed for constructing the StratifiedSets for the
675 static void buildGraphFrom(CFLAliasAnalysis &, Function *,
676 SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
678 // Gets the edges of a ConstantExpr as if it was an Instruction. This
679 // function also acts on any nested ConstantExprs, adding the edges
680 // of those to the given SmallVector as well.
681 static void constexprToEdges(CFLAliasAnalysis &, ConstantExpr &,
682 SmallVectorImpl<Edge> &);
684 // Given an Instruction, this will add it to the graph, along with any
685 // Instructions that are potentially only available from said Instruction
686 // For example, given the following line:
687 // %0 = load i16* getelementptr ([1 x i16]* @a, 0, 0), align 2
688 // addInstructionToGraph would add both the `load` and `getelementptr`
689 // instructions to the graph appropriately.
690 static void addInstructionToGraph(CFLAliasAnalysis &, Instruction &,
691 SmallVectorImpl<Value *> &, NodeMapT &,
694 // Notes whether it would be pointless to add the given Value to our sets.
695 static bool canSkipAddingToSets(Value *Val);
697 static Optional<Function *> parentFunctionOfValue(Value *Val) {
698 if (auto *Inst = dyn_cast<Instruction>(Val)) {
699 auto *Bb = Inst->getParent();
700 return Bb->getParent();
703 if (auto *Arg = dyn_cast<Argument>(Val))
704 return Arg->getParent();
708 template <typename Inst>
709 static bool getPossibleTargets(Inst *Call,
710 SmallVectorImpl<Function *> &Output) {
711 if (auto *Fn = Call->getCalledFunction()) {
712 Output.push_back(Fn);
716 // TODO: If the call is indirect, we might be able to enumerate all potential
717 // targets of the call and return them, rather than just failing.
721 static Optional<Value *> getTargetValue(Instruction *Inst) {
722 GetTargetValueVisitor V;
723 return V.visit(Inst);
726 static bool hasUsefulEdges(Instruction *Inst) {
727 bool IsNonInvokeTerminator =
728 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
729 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
732 static bool hasUsefulEdges(ConstantExpr *CE) {
733 // ConstantExpr doesn't have terminators, invokes, or fences, so only needs
734 // to check for compares.
735 return CE->getOpcode() != Instruction::ICmp &&
736 CE->getOpcode() != Instruction::FCmp;
739 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
740 if (isa<GlobalValue>(Val))
741 return AttrGlobalIndex;
743 if (auto *Arg = dyn_cast<Argument>(Val))
744 // Only pointer arguments should have the argument attribute,
745 // because things can't escape through scalars without us seeing a
746 // cast, and thus, interaction with them doesn't matter.
747 if (!Arg->hasNoAliasAttr() && Arg->getType()->isPointerTy())
748 return argNumberToAttrIndex(Arg->getArgNo());
752 static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
753 if (ArgNum >= AttrMaxNumArgs)
755 return ArgNum + AttrFirstArgIndex;
758 static EdgeType flipWeight(EdgeType Initial) {
760 case EdgeType::Assign:
761 return EdgeType::Assign;
762 case EdgeType::Dereference:
763 return EdgeType::Reference;
764 case EdgeType::Reference:
765 return EdgeType::Dereference;
767 llvm_unreachable("Incomplete coverage of EdgeType enum");
770 static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
771 SmallVectorImpl<Edge> &Output) {
772 assert(hasUsefulEdges(Inst) &&
773 "Expected instructions to have 'useful' edges");
774 GetEdgesVisitor v(Analysis, Output);
778 static void argsToEdges(CFLAliasAnalysis &Analysis, ConstantExpr *CE,
779 SmallVectorImpl<Edge> &Output) {
780 assert(hasUsefulEdges(CE) && "Expected constant expr to have 'useful' edges");
781 GetEdgesVisitor v(Analysis, Output);
782 v.visitConstantExpr(CE);
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 static void constexprToEdges(CFLAliasAnalysis &Analysis,
798 ConstantExpr &CExprToCollapse,
799 SmallVectorImpl<Edge> &Results) {
800 SmallVector<ConstantExpr *, 4> Worklist;
801 Worklist.push_back(&CExprToCollapse);
803 SmallVector<Edge, 8> ConstexprEdges;
804 SmallPtrSet<ConstantExpr *, 4> Visited;
805 while (!Worklist.empty()) {
806 auto *CExpr = Worklist.pop_back_val();
808 if (!hasUsefulEdges(CExpr))
811 ConstexprEdges.clear();
812 argsToEdges(Analysis, CExpr, ConstexprEdges);
813 for (auto &Edge : ConstexprEdges) {
814 if (auto *Nested = dyn_cast<ConstantExpr>(Edge.From))
815 if (Visited.insert(Nested).second)
816 Worklist.push_back(Nested);
818 if (auto *Nested = dyn_cast<ConstantExpr>(Edge.To))
819 if (Visited.insert(Nested).second)
820 Worklist.push_back(Nested);
823 Results.append(ConstexprEdges.begin(), ConstexprEdges.end());
827 static void addInstructionToGraph(CFLAliasAnalysis &Analysis, Instruction &Inst,
828 SmallVectorImpl<Value *> &ReturnedValues,
829 NodeMapT &Map, GraphT &Graph) {
830 const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
831 auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
832 auto &Iter = Pair.first;
834 auto NewNode = Graph.addNode();
835 Iter->second = NewNode;
840 // We don't want the edges of most "return" instructions, but we *do* want
841 // to know what can be returned.
842 if (isa<ReturnInst>(&Inst))
843 ReturnedValues.push_back(&Inst);
845 if (!hasUsefulEdges(&Inst))
848 SmallVector<Edge, 8> Edges;
849 argsToEdges(Analysis, &Inst, Edges);
851 // In the case of an unused alloca (or similar), edges may be empty. Note
852 // that it exists so we can potentially answer NoAlias.
854 auto MaybeVal = getTargetValue(&Inst);
855 assert(MaybeVal.hasValue());
856 auto *Target = *MaybeVal;
857 findOrInsertNode(Target);
861 const auto addEdgeToGraph = [&Graph, &findOrInsertNode](const Edge &E) {
862 auto To = findOrInsertNode(E.To);
863 auto From = findOrInsertNode(E.From);
864 auto FlippedWeight = flipWeight(E.Weight);
865 auto Attrs = E.AdditionalAttrs;
866 Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
867 std::make_pair(FlippedWeight, Attrs));
870 SmallVector<ConstantExpr *, 4> ConstantExprs;
871 for (const Edge &E : Edges) {
873 if (auto *Constexpr = dyn_cast<ConstantExpr>(E.To))
874 ConstantExprs.push_back(Constexpr);
875 if (auto *Constexpr = dyn_cast<ConstantExpr>(E.From))
876 ConstantExprs.push_back(Constexpr);
879 for (ConstantExpr *CE : ConstantExprs) {
881 constexprToEdges(Analysis, *CE, Edges);
882 std::for_each(Edges.begin(), Edges.end(), addEdgeToGraph);
886 // Aside: We may remove graph construction entirely, because it doesn't really
887 // buy us much that we don't already have. I'd like to add interprocedural
888 // analysis prior to this however, in case that somehow requires the graph
889 // produced by this for efficient execution
890 static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
891 SmallVectorImpl<Value *> &ReturnedValues,
892 NodeMapT &Map, GraphT &Graph) {
893 for (auto &Bb : Fn->getBasicBlockList())
894 for (auto &Inst : Bb.getInstList())
895 addInstructionToGraph(Analysis, Inst, ReturnedValues, Map, Graph);
898 static bool canSkipAddingToSets(Value *Val) {
899 // Constants can share instances, which may falsely unify multiple
901 // store i32* null, i32** %ptr1
902 // store i32* null, i32** %ptr2
903 // clearly ptr1 and ptr2 should not be unified into the same set, so
904 // we should filter out the (potentially shared) instance to
906 if (isa<Constant>(Val)) {
907 bool Container = isa<ConstantVector>(Val) || isa<ConstantArray>(Val) ||
908 isa<ConstantStruct>(Val);
909 // TODO: Because all of these things are constant, we can determine whether
910 // the data is *actually* mutable at graph building time. This will probably
911 // come for free/cheap with offset awareness.
912 bool CanStoreMutableData =
913 isa<GlobalValue>(Val) || isa<ConstantExpr>(Val) || Container;
914 return !CanStoreMutableData;
920 // Builds the graph + StratifiedSets for a function.
921 CFLAliasAnalysis::FunctionInfo CFLAliasAnalysis::buildSetsFrom(Function *Fn) {
924 SmallVector<Value *, 4> ReturnedValues;
926 buildGraphFrom(*this, Fn, ReturnedValues, Map, Graph);
928 DenseMap<GraphT::Node, Value *> NodeValueMap;
929 NodeValueMap.resize(Map.size());
930 for (const auto &Pair : Map)
931 NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
933 const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
934 auto ValIter = NodeValueMap.find(Node);
935 assert(ValIter != NodeValueMap.end());
936 return ValIter->second;
939 StratifiedSetsBuilder<Value *> Builder;
941 SmallVector<GraphT::Node, 16> Worklist;
942 for (auto &Pair : Map) {
945 auto *Value = Pair.first;
947 auto InitialNode = Pair.second;
948 Worklist.push_back(InitialNode);
949 while (!Worklist.empty()) {
950 auto Node = Worklist.pop_back_val();
951 auto *CurValue = findValueOrDie(Node);
952 if (canSkipAddingToSets(CurValue))
955 for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
956 auto Weight = std::get<0>(EdgeTuple);
957 auto Label = Weight.first;
958 auto &OtherNode = std::get<1>(EdgeTuple);
959 auto *OtherValue = findValueOrDie(OtherNode);
961 if (canSkipAddingToSets(OtherValue))
965 switch (directionOfEdgeType(Label)) {
967 Added = Builder.addAbove(CurValue, OtherValue);
970 Added = Builder.addBelow(CurValue, OtherValue);
973 Added = Builder.addWith(CurValue, OtherValue);
977 auto Aliasing = Weight.second;
978 if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
979 Aliasing.set(*MaybeCurIndex);
980 if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
981 Aliasing.set(*MaybeOtherIndex);
982 Builder.noteAttributes(CurValue, Aliasing);
983 Builder.noteAttributes(OtherValue, Aliasing);
986 Worklist.push_back(OtherNode);
991 // There are times when we end up with parameters not in our graph (i.e. if
992 // it's only used as the condition of a branch). Other bits of code depend on
993 // things that were present during construction being present in the graph.
994 // So, we add all present arguments here.
995 for (auto &Arg : Fn->args()) {
996 if (!Builder.add(&Arg))
999 auto Attrs = valueToAttrIndex(&Arg);
1000 if (Attrs.hasValue())
1001 Builder.noteAttributes(&Arg, *Attrs);
1004 return FunctionInfo(Builder.build(), std::move(ReturnedValues));
1007 void CFLAliasAnalysis::scan(Function *Fn) {
1008 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
1010 assert(InsertPair.second &&
1011 "Trying to scan a function that has already been cached");
1013 FunctionInfo Info(buildSetsFrom(Fn));
1014 Cache[Fn] = std::move(Info);
1015 Handles.push_front(FunctionHandle(Fn, this));
1018 void CFLAliasAnalysis::evict(Function *Fn) { Cache.erase(Fn); }
1020 /// \brief Ensures that the given function is available in the cache.
1021 /// Returns the appropriate entry from the cache.
1022 const Optional<CFLAliasAnalysis::FunctionInfo> &
1023 CFLAliasAnalysis::ensureCached(Function *Fn) {
1024 auto Iter = Cache.find(Fn);
1025 if (Iter == Cache.end()) {
1027 Iter = Cache.find(Fn);
1028 assert(Iter != Cache.end());
1029 assert(Iter->second.hasValue());
1031 return Iter->second;
1034 AliasResult CFLAliasAnalysis::query(const MemoryLocation &LocA,
1035 const MemoryLocation &LocB) {
1036 auto *ValA = const_cast<Value *>(LocA.Ptr);
1037 auto *ValB = const_cast<Value *>(LocB.Ptr);
1039 Function *Fn = nullptr;
1040 auto MaybeFnA = parentFunctionOfValue(ValA);
1041 auto MaybeFnB = parentFunctionOfValue(ValB);
1042 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
1043 // The only times this is known to happen are when globals + InlineAsm
1045 DEBUG(dbgs() << "CFLAA: could not extract parent function information.\n");
1049 if (MaybeFnA.hasValue()) {
1051 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
1052 "Interprocedural queries not supported");
1057 assert(Fn != nullptr);
1058 auto &MaybeInfo = ensureCached(Fn);
1059 assert(MaybeInfo.hasValue());
1061 auto &Sets = MaybeInfo->Sets;
1062 auto MaybeA = Sets.find(ValA);
1063 if (!MaybeA.hasValue())
1066 auto MaybeB = Sets.find(ValB);
1067 if (!MaybeB.hasValue())
1070 auto SetA = *MaybeA;
1071 auto SetB = *MaybeB;
1072 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
1073 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
1075 // Stratified set attributes are used as markets to signify whether a member
1076 // of a StratifiedSet (or a member of a set above the current set) has
1077 // interacted with either arguments or globals. "Interacted with" meaning
1078 // its value may be different depending on the value of an argument or
1079 // global. The thought behind this is that, because arguments and globals
1080 // may alias each other, if AttrsA and AttrsB have touched args/globals,
1081 // we must conservatively say that they alias. However, if at least one of
1082 // the sets has no values that could legally be altered by changing the value
1083 // of an argument or global, then we don't have to be as conservative.
1084 if (AttrsA.any() && AttrsB.any())
1087 // We currently unify things even if the accesses to them may not be in
1088 // bounds, so we can't return partial alias here because we don't
1089 // know whether the pointer is really within the object or not.
1090 // IE Given an out of bounds GEP and an alloca'd pointer, we may
1091 // unify the two. We can't return partial alias for this case.
1092 // Since we do not currently track enough information to
1095 if (SetA.Index == SetB.Index)
1101 bool CFLAliasAnalysis::doInitialization(Module &M) {
1102 InitializeAliasAnalysis(this, &M.getDataLayout());