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/IR/ValueHandle.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/Allocator.h"
44 #include "llvm/Support/Compiler.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/raw_ostream.h"
55 #define DEBUG_TYPE "cfl-aa"
57 // -- Setting up/registering CFLAA pass -- //
58 char CFLAliasAnalysis::ID = 0;
60 INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
61 "CFL-Based AA implementation", false, true, false)
63 ImmutablePass *llvm::createCFLAliasAnalysisPass() {
64 return new CFLAliasAnalysis();
67 // \brief Information we have about a function and would like to keep around
68 struct CFLAliasAnalysis::FunctionInfo {
69 StratifiedSets<Value *> Sets;
70 // Lots of functions have < 4 returns. Adjust as necessary.
71 SmallVector<Value *, 4> ReturnedValues;
73 FunctionInfo(StratifiedSets<Value *> &&S, SmallVector<Value *, 4> &&RV)
74 : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
77 struct CFLAliasAnalysis::FunctionHandle final : public CallbackVH {
78 FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
79 : CallbackVH(Fn), CFLAA(CFLAA) {
80 assert(Fn != nullptr);
81 assert(CFLAA != nullptr);
84 void deleted() override { removeSelfFromCache(); }
85 void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
88 CFLAliasAnalysis *CFLAA;
90 void removeSelfFromCache() {
91 assert(CFLAA != nullptr);
92 auto *Val = getValPtr();
93 CFLAA->evict(cast<Function>(Val));
98 CFLAliasAnalysis::CFLAliasAnalysis() : ImmutablePass(ID) {
99 initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
102 CFLAliasAnalysis::~CFLAliasAnalysis() {}
104 void CFLAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
105 AliasAnalysis::getAnalysisUsage(AU);
108 void *CFLAliasAnalysis::getAdjustedAnalysisPointer(const void *ID) {
109 if (ID == &AliasAnalysis::ID)
110 return (AliasAnalysis *)this;
114 // Try to go from a Value* to a Function*. Never returns nullptr.
115 static Optional<Function *> parentFunctionOfValue(Value *);
117 // Returns possible functions called by the Inst* into the given
118 // SmallVectorImpl. Returns true if targets found, false otherwise.
119 // This is templated because InvokeInst/CallInst give us the same
120 // set of functions that we care about, and I don't like repeating
122 template <typename Inst>
123 static bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &);
125 // Some instructions need to have their users tracked. Instructions like
126 // `add` require you to get the users of the Instruction* itself, other
127 // instructions like `store` require you to get the users of the first
128 // operand. This function gets the "proper" value to track for each
129 // type of instruction we support.
130 static Optional<Value *> getTargetValue(Instruction *);
132 // There are certain instructions (i.e. FenceInst, etc.) that we ignore.
133 // This notes that we should ignore those.
134 static bool hasUsefulEdges(Instruction *);
136 const StratifiedIndex StratifiedLink::SetSentinel =
137 std::numeric_limits<StratifiedIndex>::max();
140 // StratifiedInfo Attribute things.
141 typedef unsigned StratifiedAttr;
142 LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
143 LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
144 LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
145 LLVM_CONSTEXPR unsigned AttrUnknownIndex = 2;
146 LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 3;
147 LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
148 LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
150 LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
151 LLVM_CONSTEXPR StratifiedAttr AttrUnknown = 1 << AttrUnknownIndex;
152 LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
154 // \brief StratifiedSets call for knowledge of "direction", so this is how we
155 // represent that locally.
156 enum class Level { Same, Above, Below };
158 // \brief Edges can be one of four "weights" -- each weight must have an inverse
159 // weight (Assign has Assign; Reference has Dereference).
160 enum class EdgeType {
161 // The weight assigned when assigning from or to a value. For example, in:
162 // %b = getelementptr %a, 0
163 // ...The relationships are %b assign %a, and %a assign %b. This used to be
164 // two edges, but having a distinction bought us nothing.
167 // The edge used when we have an edge going from some handle to a Value.
168 // Examples of this include:
169 // %b = load %a (%b Dereference %a)
170 // %b = extractelement %a, 0 (%a Dereference %b)
173 // The edge used when our edge goes from a value to a handle that may have
174 // contained it at some point. Examples:
175 // %b = load %a (%a Reference %b)
176 // %b = extractelement %a, 0 (%b Reference %a)
180 // \brief Encodes the notion of a "use"
182 // \brief Which value the edge is coming from
185 // \brief Which value the edge is pointing to
188 // \brief Edge weight
191 // \brief Whether we aliased any external values along the way that may be
192 // invisible to the analysis (i.e. landingpad for exceptions, calls for
193 // interprocedural analysis, etc.)
194 StratifiedAttrs AdditionalAttrs;
196 Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
197 : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
200 // \brief Gets the edges our graph should have, based on an Instruction*
201 class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
202 CFLAliasAnalysis &AA;
203 SmallVectorImpl<Edge> &Output;
206 GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
207 : AA(AA), Output(Output) {}
209 void visitInstruction(Instruction &) {
210 llvm_unreachable("Unsupported instruction encountered");
213 void visitPtrToIntInst(PtrToIntInst &Inst) {
214 auto *Ptr = Inst.getOperand(0);
215 Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
218 void visitIntToPtrInst(IntToPtrInst &Inst) {
220 Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
223 void visitCastInst(CastInst &Inst) {
225 Edge(&Inst, Inst.getOperand(0), EdgeType::Assign, AttrNone));
228 void visitBinaryOperator(BinaryOperator &Inst) {
229 auto *Op1 = Inst.getOperand(0);
230 auto *Op2 = Inst.getOperand(1);
231 Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
232 Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
235 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
236 auto *Ptr = Inst.getPointerOperand();
237 auto *Val = Inst.getNewValOperand();
238 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
241 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
242 auto *Ptr = Inst.getPointerOperand();
243 auto *Val = Inst.getValOperand();
244 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
247 void visitPHINode(PHINode &Inst) {
248 for (Value *Val : Inst.incoming_values()) {
249 Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
253 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
254 auto *Op = Inst.getPointerOperand();
255 Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
256 for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
257 Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
260 void visitSelectInst(SelectInst &Inst) {
261 // Condition is not processed here (The actual statement producing
262 // the condition result is processed elsewhere). For select, the
263 // condition is evaluated, but not loaded, stored, or assigned
264 // simply as a result of being the condition of a select.
266 auto *TrueVal = Inst.getTrueValue();
267 Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
268 auto *FalseVal = Inst.getFalseValue();
269 Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
272 void visitAllocaInst(AllocaInst &) {}
274 void visitLoadInst(LoadInst &Inst) {
275 auto *Ptr = Inst.getPointerOperand();
277 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
280 void visitStoreInst(StoreInst &Inst) {
281 auto *Ptr = Inst.getPointerOperand();
282 auto *Val = Inst.getValueOperand();
283 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
286 void visitVAArgInst(VAArgInst &Inst) {
287 // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
289 // 1. Loads a value from *((T*)*Ptr).
290 // 2. Increments (stores to) *Ptr by some target-specific amount.
291 // For now, we'll handle this like a landingpad instruction (by placing the
292 // result in its own group, and having that group alias externals).
294 Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll));
297 static bool isFunctionExternal(Function *Fn) {
298 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
301 // Gets whether the sets at Index1 above, below, or equal to the sets at
302 // Index2. Returns None if they are not in the same set chain.
303 static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
304 StratifiedIndex Index1,
305 StratifiedIndex Index2) {
306 if (Index1 == Index2)
309 const auto *Current = &Sets.getLink(Index1);
310 while (Current->hasBelow()) {
311 if (Current->Below == Index2)
313 Current = &Sets.getLink(Current->Below);
316 Current = &Sets.getLink(Index1);
317 while (Current->hasAbove()) {
318 if (Current->Above == Index2)
320 Current = &Sets.getLink(Current->Above);
327 tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
329 const iterator_range<User::op_iterator> &Args) {
330 const unsigned ExpectedMaxArgs = 8;
331 const unsigned MaxSupportedArgs = 50;
332 assert(Fns.size() > 0);
334 // I put this here to give us an upper bound on time taken by IPA. Is it
335 // really (realistically) needed? Keep in mind that we do have an n^2 algo.
336 if (std::distance(Args.begin(), Args.end()) > (int)MaxSupportedArgs)
339 // Exit early if we'll fail anyway
340 for (auto *Fn : Fns) {
341 if (isFunctionExternal(Fn) || Fn->isVarArg())
343 auto &MaybeInfo = AA.ensureCached(Fn);
344 if (!MaybeInfo.hasValue())
348 SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
349 SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
350 for (auto *Fn : Fns) {
351 auto &Info = *AA.ensureCached(Fn);
352 auto &Sets = Info.Sets;
353 auto &RetVals = Info.ReturnedValues;
356 for (auto &Param : Fn->args()) {
357 auto MaybeInfo = Sets.find(&Param);
358 // Did a new parameter somehow get added to the function/slip by?
359 if (!MaybeInfo.hasValue())
361 Parameters.push_back(*MaybeInfo);
364 // Adding an edge from argument -> return value for each parameter that
365 // may alias the return value
366 for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
367 auto &ParamInfo = Parameters[I];
368 auto &ArgVal = Arguments[I];
369 bool AddEdge = false;
370 StratifiedAttrs Externals;
371 for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
372 auto MaybeInfo = Sets.find(RetVals[X]);
373 if (!MaybeInfo.hasValue())
376 auto &RetInfo = *MaybeInfo;
377 auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
378 auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
380 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
381 if (MaybeRelation.hasValue()) {
383 Externals |= RetAttrs | ParamAttrs;
387 Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
388 StratifiedAttrs().flip()));
391 if (Parameters.size() != Arguments.size())
394 // Adding edges between arguments for arguments that may end up aliasing
395 // each other. This is necessary for functions such as
396 // void foo(int** a, int** b) { *a = *b; }
397 // (Technically, the proper sets for this would be those below
398 // Arguments[I] and Arguments[X], but our algorithm will produce
399 // extremely similar, and equally correct, results either way)
400 for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
401 auto &MainVal = Arguments[I];
402 auto &MainInfo = Parameters[I];
403 auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
404 for (unsigned X = I + 1; X != E; ++X) {
405 auto &SubInfo = Parameters[X];
406 auto &SubVal = Arguments[X];
407 auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
409 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
411 if (!MaybeRelation.hasValue())
414 auto NewAttrs = SubAttrs | MainAttrs;
415 Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
422 template <typename InstT> void visitCallLikeInst(InstT &Inst) {
423 SmallVector<Function *, 4> Targets;
424 if (getPossibleTargets(&Inst, Targets)) {
425 if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
427 // Cleanup from interprocedural analysis
431 for (Value *V : Inst.arg_operands())
432 Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
435 void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
437 void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
439 // Because vectors/aggregates are immutable and unaddressable,
440 // there's nothing we can do to coax a value out of them, other
441 // than calling Extract{Element,Value}. We can effectively treat
442 // them as pointers to arbitrary memory locations we can store in
444 void visitExtractElementInst(ExtractElementInst &Inst) {
445 auto *Ptr = Inst.getVectorOperand();
447 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
450 void visitInsertElementInst(InsertElementInst &Inst) {
451 auto *Vec = Inst.getOperand(0);
452 auto *Val = Inst.getOperand(1);
453 Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
454 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
457 void visitLandingPadInst(LandingPadInst &Inst) {
458 // Exceptions come from "nowhere", from our analysis' perspective.
459 // So we place the instruction its own group, noting that said group may
461 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
464 void visitInsertValueInst(InsertValueInst &Inst) {
465 auto *Agg = Inst.getOperand(0);
466 auto *Val = Inst.getOperand(1);
467 Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
468 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
471 void visitExtractValueInst(ExtractValueInst &Inst) {
472 auto *Ptr = Inst.getAggregateOperand();
473 Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
476 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
477 auto *From1 = Inst.getOperand(0);
478 auto *From2 = Inst.getOperand(1);
479 Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
480 Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
483 void visitConstantExpr(ConstantExpr *CE) {
484 switch (CE->getOpcode()) {
486 llvm_unreachable("Unknown instruction type encountered!");
487 // Build the switch statement using the Instruction.def file.
488 #define HANDLE_INST(NUM, OPCODE, CLASS) \
489 case Instruction::OPCODE: \
490 visit##OPCODE(*(CLASS *)CE); \
492 #include "llvm/IR/Instruction.def"
497 // For a given instruction, we need to know which Value* to get the
498 // users of in order to build our graph. In some cases (i.e. add),
499 // we simply need the Instruction*. In other cases (i.e. store),
500 // finding the users of the Instruction* is useless; we need to find
501 // the users of the first operand. This handles determining which
502 // value to follow for us.
504 // Note: we *need* to keep this in sync with GetEdgesVisitor. Add
505 // something to GetEdgesVisitor, add it here -- remove something from
506 // GetEdgesVisitor, remove it here.
507 class GetTargetValueVisitor
508 : public InstVisitor<GetTargetValueVisitor, Value *> {
510 Value *visitInstruction(Instruction &Inst) { return &Inst; }
512 Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
514 Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
515 return Inst.getPointerOperand();
518 Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
519 return Inst.getPointerOperand();
522 Value *visitInsertElementInst(InsertElementInst &Inst) {
523 return Inst.getOperand(0);
526 Value *visitInsertValueInst(InsertValueInst &Inst) {
527 return Inst.getAggregateOperand();
531 // Set building requires a weighted bidirectional graph.
532 template <typename EdgeTypeT> class WeightedBidirectionalGraph {
534 typedef std::size_t Node;
537 const static Node StartNode = Node(0);
543 Edge(const EdgeTypeT &W, const Node &N) : Weight(W), Other(N) {}
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 modification 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() {}
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 //===----------------------------------------------------------------------===//
671 // Function declarations that require types defined in the namespace above
672 //===----------------------------------------------------------------------===//
674 // Given an argument number, returns the appropriate Attr index to set.
675 static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
677 // Given a Value, potentially return which AttrIndex it maps to.
678 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
680 // Gets the inverse of a given EdgeType.
681 static EdgeType flipWeight(EdgeType);
683 // Gets edges of the given Instruction*, writing them to the SmallVector*.
684 static void argsToEdges(CFLAliasAnalysis &, Instruction *,
685 SmallVectorImpl<Edge> &);
687 // Gets edges of the given ConstantExpr*, writing them to the SmallVector*.
688 static void argsToEdges(CFLAliasAnalysis &, ConstantExpr *,
689 SmallVectorImpl<Edge> &);
691 // Gets the "Level" that one should travel in StratifiedSets
692 // given an EdgeType.
693 static Level directionOfEdgeType(EdgeType);
695 // Builds the graph needed for constructing the StratifiedSets for the
697 static void buildGraphFrom(CFLAliasAnalysis &, Function *,
698 SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
700 // Gets the edges of a ConstantExpr as if it was an Instruction. This
701 // function also acts on any nested ConstantExprs, adding the edges
702 // of those to the given SmallVector as well.
703 static void constexprToEdges(CFLAliasAnalysis &, ConstantExpr &,
704 SmallVectorImpl<Edge> &);
706 // Given an Instruction, this will add it to the graph, along with any
707 // Instructions that are potentially only available from said Instruction
708 // For example, given the following line:
709 // %0 = load i16* getelementptr ([1 x i16]* @a, 0, 0), align 2
710 // addInstructionToGraph would add both the `load` and `getelementptr`
711 // instructions to the graph appropriately.
712 static void addInstructionToGraph(CFLAliasAnalysis &, Instruction &,
713 SmallVectorImpl<Value *> &, NodeMapT &,
716 // Notes whether it would be pointless to add the given Value to our sets.
717 static bool canSkipAddingToSets(Value *Val);
719 static Optional<Function *> parentFunctionOfValue(Value *Val) {
720 if (auto *Inst = dyn_cast<Instruction>(Val)) {
721 auto *Bb = Inst->getParent();
722 return Bb->getParent();
725 if (auto *Arg = dyn_cast<Argument>(Val))
726 return Arg->getParent();
730 template <typename Inst>
731 static bool getPossibleTargets(Inst *Call,
732 SmallVectorImpl<Function *> &Output) {
733 if (auto *Fn = Call->getCalledFunction()) {
734 Output.push_back(Fn);
738 // TODO: If the call is indirect, we might be able to enumerate all potential
739 // targets of the call and return them, rather than just failing.
743 static Optional<Value *> getTargetValue(Instruction *Inst) {
744 GetTargetValueVisitor V;
745 return V.visit(Inst);
748 static bool hasUsefulEdges(Instruction *Inst) {
749 bool IsNonInvokeTerminator =
750 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
751 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
754 static bool hasUsefulEdges(ConstantExpr *CE) {
755 // ConstantExpr doesn't have terminators, invokes, or fences, so only needs
756 // to check for compares.
757 return CE->getOpcode() != Instruction::ICmp &&
758 CE->getOpcode() != Instruction::FCmp;
761 static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
762 if (isa<GlobalValue>(Val))
763 return AttrGlobalIndex;
765 if (auto *Arg = dyn_cast<Argument>(Val))
766 // Only pointer arguments should have the argument attribute,
767 // because things can't escape through scalars without us seeing a
768 // cast, and thus, interaction with them doesn't matter.
769 if (!Arg->hasNoAliasAttr() && Arg->getType()->isPointerTy())
770 return argNumberToAttrIndex(Arg->getArgNo());
774 static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
775 if (ArgNum >= AttrMaxNumArgs)
777 return ArgNum + AttrFirstArgIndex;
780 static EdgeType flipWeight(EdgeType Initial) {
782 case EdgeType::Assign:
783 return EdgeType::Assign;
784 case EdgeType::Dereference:
785 return EdgeType::Reference;
786 case EdgeType::Reference:
787 return EdgeType::Dereference;
789 llvm_unreachable("Incomplete coverage of EdgeType enum");
792 static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
793 SmallVectorImpl<Edge> &Output) {
794 assert(hasUsefulEdges(Inst) &&
795 "Expected instructions to have 'useful' edges");
796 GetEdgesVisitor v(Analysis, Output);
800 static void argsToEdges(CFLAliasAnalysis &Analysis, ConstantExpr *CE,
801 SmallVectorImpl<Edge> &Output) {
802 assert(hasUsefulEdges(CE) && "Expected constant expr to have 'useful' edges");
803 GetEdgesVisitor v(Analysis, Output);
804 v.visitConstantExpr(CE);
807 static Level directionOfEdgeType(EdgeType Weight) {
809 case EdgeType::Reference:
811 case EdgeType::Dereference:
813 case EdgeType::Assign:
816 llvm_unreachable("Incomplete switch coverage");
819 static void constexprToEdges(CFLAliasAnalysis &Analysis,
820 ConstantExpr &CExprToCollapse,
821 SmallVectorImpl<Edge> &Results) {
822 SmallVector<ConstantExpr *, 4> Worklist;
823 Worklist.push_back(&CExprToCollapse);
825 SmallVector<Edge, 8> ConstexprEdges;
826 SmallPtrSet<ConstantExpr *, 4> Visited;
827 while (!Worklist.empty()) {
828 auto *CExpr = Worklist.pop_back_val();
830 if (!hasUsefulEdges(CExpr))
833 ConstexprEdges.clear();
834 argsToEdges(Analysis, CExpr, ConstexprEdges);
835 for (auto &Edge : ConstexprEdges) {
836 if (auto *Nested = dyn_cast<ConstantExpr>(Edge.From))
837 if (Visited.insert(Nested).second)
838 Worklist.push_back(Nested);
840 if (auto *Nested = dyn_cast<ConstantExpr>(Edge.To))
841 if (Visited.insert(Nested).second)
842 Worklist.push_back(Nested);
845 Results.append(ConstexprEdges.begin(), ConstexprEdges.end());
849 static void addInstructionToGraph(CFLAliasAnalysis &Analysis, Instruction &Inst,
850 SmallVectorImpl<Value *> &ReturnedValues,
851 NodeMapT &Map, GraphT &Graph) {
852 const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
853 auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
854 auto &Iter = Pair.first;
856 auto NewNode = Graph.addNode();
857 Iter->second = NewNode;
862 // We don't want the edges of most "return" instructions, but we *do* want
863 // to know what can be returned.
864 if (isa<ReturnInst>(&Inst))
865 ReturnedValues.push_back(&Inst);
867 if (!hasUsefulEdges(&Inst))
870 SmallVector<Edge, 8> Edges;
871 argsToEdges(Analysis, &Inst, Edges);
873 // In the case of an unused alloca (or similar), edges may be empty. Note
874 // that it exists so we can potentially answer NoAlias.
876 auto MaybeVal = getTargetValue(&Inst);
877 assert(MaybeVal.hasValue());
878 auto *Target = *MaybeVal;
879 findOrInsertNode(Target);
883 const auto addEdgeToGraph = [&Graph, &findOrInsertNode](const Edge &E) {
884 auto To = findOrInsertNode(E.To);
885 auto From = findOrInsertNode(E.From);
886 auto FlippedWeight = flipWeight(E.Weight);
887 auto Attrs = E.AdditionalAttrs;
888 Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
889 std::make_pair(FlippedWeight, Attrs));
892 SmallVector<ConstantExpr *, 4> ConstantExprs;
893 for (const Edge &E : Edges) {
895 if (auto *Constexpr = dyn_cast<ConstantExpr>(E.To))
896 ConstantExprs.push_back(Constexpr);
897 if (auto *Constexpr = dyn_cast<ConstantExpr>(E.From))
898 ConstantExprs.push_back(Constexpr);
901 for (ConstantExpr *CE : ConstantExprs) {
903 constexprToEdges(Analysis, *CE, Edges);
904 std::for_each(Edges.begin(), Edges.end(), addEdgeToGraph);
908 // Aside: We may remove graph construction entirely, because it doesn't really
909 // buy us much that we don't already have. I'd like to add interprocedural
910 // analysis prior to this however, in case that somehow requires the graph
911 // produced by this for efficient execution
912 static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
913 SmallVectorImpl<Value *> &ReturnedValues,
914 NodeMapT &Map, GraphT &Graph) {
915 for (auto &Bb : Fn->getBasicBlockList())
916 for (auto &Inst : Bb.getInstList())
917 addInstructionToGraph(Analysis, Inst, ReturnedValues, Map, Graph);
920 static bool canSkipAddingToSets(Value *Val) {
921 // Constants can share instances, which may falsely unify multiple
923 // store i32* null, i32** %ptr1
924 // store i32* null, i32** %ptr2
925 // clearly ptr1 and ptr2 should not be unified into the same set, so
926 // we should filter out the (potentially shared) instance to
928 if (isa<Constant>(Val)) {
929 bool Container = isa<ConstantVector>(Val) || isa<ConstantArray>(Val) ||
930 isa<ConstantStruct>(Val);
931 // TODO: Because all of these things are constant, we can determine whether
932 // the data is *actually* mutable at graph building time. This will probably
933 // come for free/cheap with offset awareness.
934 bool CanStoreMutableData =
935 isa<GlobalValue>(Val) || isa<ConstantExpr>(Val) || Container;
936 return !CanStoreMutableData;
942 // Builds the graph + StratifiedSets for a function.
943 CFLAliasAnalysis::FunctionInfo CFLAliasAnalysis::buildSetsFrom(Function *Fn) {
946 SmallVector<Value *, 4> ReturnedValues;
948 buildGraphFrom(*this, Fn, ReturnedValues, Map, Graph);
950 DenseMap<GraphT::Node, Value *> NodeValueMap;
951 NodeValueMap.resize(Map.size());
952 for (const auto &Pair : Map)
953 NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
955 const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
956 auto ValIter = NodeValueMap.find(Node);
957 assert(ValIter != NodeValueMap.end());
958 return ValIter->second;
961 StratifiedSetsBuilder<Value *> Builder;
963 SmallVector<GraphT::Node, 16> Worklist;
964 for (auto &Pair : Map) {
967 auto *Value = Pair.first;
969 auto InitialNode = Pair.second;
970 Worklist.push_back(InitialNode);
971 while (!Worklist.empty()) {
972 auto Node = Worklist.pop_back_val();
973 auto *CurValue = findValueOrDie(Node);
974 if (canSkipAddingToSets(CurValue))
977 for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
978 auto Weight = std::get<0>(EdgeTuple);
979 auto Label = Weight.first;
980 auto &OtherNode = std::get<1>(EdgeTuple);
981 auto *OtherValue = findValueOrDie(OtherNode);
983 if (canSkipAddingToSets(OtherValue))
987 switch (directionOfEdgeType(Label)) {
989 Added = Builder.addAbove(CurValue, OtherValue);
992 Added = Builder.addBelow(CurValue, OtherValue);
995 Added = Builder.addWith(CurValue, OtherValue);
999 auto Aliasing = Weight.second;
1000 if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
1001 Aliasing.set(*MaybeCurIndex);
1002 if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
1003 Aliasing.set(*MaybeOtherIndex);
1004 Builder.noteAttributes(CurValue, Aliasing);
1005 Builder.noteAttributes(OtherValue, Aliasing);
1008 Worklist.push_back(OtherNode);
1013 // There are times when we end up with parameters not in our graph (i.e. if
1014 // it's only used as the condition of a branch). Other bits of code depend on
1015 // things that were present during construction being present in the graph.
1016 // So, we add all present arguments here.
1017 for (auto &Arg : Fn->args()) {
1018 if (!Builder.add(&Arg))
1021 auto Attrs = valueToAttrIndex(&Arg);
1022 if (Attrs.hasValue())
1023 Builder.noteAttributes(&Arg, *Attrs);
1026 return FunctionInfo(Builder.build(), std::move(ReturnedValues));
1029 void CFLAliasAnalysis::scan(Function *Fn) {
1030 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
1032 assert(InsertPair.second &&
1033 "Trying to scan a function that has already been cached");
1035 FunctionInfo Info(buildSetsFrom(Fn));
1036 Cache[Fn] = std::move(Info);
1037 Handles.push_front(FunctionHandle(Fn, this));
1040 void CFLAliasAnalysis::evict(Function *Fn) { Cache.erase(Fn); }
1042 /// \brief Ensures that the given function is available in the cache.
1043 /// Returns the appropriate entry from the cache.
1044 const Optional<CFLAliasAnalysis::FunctionInfo> &
1045 CFLAliasAnalysis::ensureCached(Function *Fn) {
1046 auto Iter = Cache.find(Fn);
1047 if (Iter == Cache.end()) {
1049 Iter = Cache.find(Fn);
1050 assert(Iter != Cache.end());
1051 assert(Iter->second.hasValue());
1053 return Iter->second;
1056 AliasResult CFLAliasAnalysis::query(const MemoryLocation &LocA,
1057 const MemoryLocation &LocB) {
1058 auto *ValA = const_cast<Value *>(LocA.Ptr);
1059 auto *ValB = const_cast<Value *>(LocB.Ptr);
1061 Function *Fn = nullptr;
1062 auto MaybeFnA = parentFunctionOfValue(ValA);
1063 auto MaybeFnB = parentFunctionOfValue(ValB);
1064 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
1065 // The only times this is known to happen are when globals + InlineAsm
1067 DEBUG(dbgs() << "CFLAA: could not extract parent function information.\n");
1071 if (MaybeFnA.hasValue()) {
1073 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
1074 "Interprocedural queries not supported");
1079 assert(Fn != nullptr);
1080 auto &MaybeInfo = ensureCached(Fn);
1081 assert(MaybeInfo.hasValue());
1083 auto &Sets = MaybeInfo->Sets;
1084 auto MaybeA = Sets.find(ValA);
1085 if (!MaybeA.hasValue())
1088 auto MaybeB = Sets.find(ValB);
1089 if (!MaybeB.hasValue())
1092 auto SetA = *MaybeA;
1093 auto SetB = *MaybeB;
1094 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
1095 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
1097 // Stratified set attributes are used as markets to signify whether a member
1098 // of a StratifiedSet (or a member of a set above the current set) has
1099 // interacted with either arguments or globals. "Interacted with" meaning
1100 // its value may be different depending on the value of an argument or
1101 // global. The thought behind this is that, because arguments and globals
1102 // may alias each other, if AttrsA and AttrsB have touched args/globals,
1103 // we must conservatively say that they alias. However, if at least one of
1104 // the sets has no values that could legally be altered by changing the value
1105 // of an argument or global, then we don't have to be as conservative.
1106 if (AttrsA.any() && AttrsB.any())
1109 // We currently unify things even if the accesses to them may not be in
1110 // bounds, so we can't return partial alias here because we don't
1111 // know whether the pointer is really within the object or not.
1112 // IE Given an out of bounds GEP and an alloca'd pointer, we may
1113 // unify the two. We can't return partial alias for this case.
1114 // Since we do not currently track enough information to
1117 if (SetA.Index == SetB.Index)
1123 bool CFLAliasAnalysis::doInitialization(Module &M) {
1124 InitializeAliasAnalysis(this, &M.getDataLayout());