blob: ac918dcf0c8eecd74e1e3a2c6bb248dd803f9fe2 [file] [log] [blame]
Hal Finkel7529c552014-09-02 21:43:13 +00001//===- CFLAliasAnalysis.cpp - CFL-Based Alias Analysis Implementation ------==//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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
Chad Rosier38c6ad22015-06-19 17:32:57 +000017// location. The "actions" can be one of Dereference, Reference, or Assign.
Hal Finkel7529c552014-09-02 21:43:13 +000018//
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.
22//
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
George Burgess IV77351ba32016-01-28 00:54:01 +000026// ~nlogn time (n = number of variables), which makes queries take constant
Hal Finkel7529c552014-09-02 21:43:13 +000027// time.
28//===----------------------------------------------------------------------===//
29
George Burgess IV77351ba32016-01-28 00:54:01 +000030// N.B. AliasAnalysis as a whole is phrased as a FunctionPass at the moment, and
31// CFLAA is interprocedural. This is *technically* A Bad Thing, because
32// FunctionPasses are only allowed to inspect the Function that they're being
33// run on. Realistically, this likely isn't a problem until we allow
34// FunctionPasses to run concurrently.
35
Chandler Carruth8b046a42015-08-14 02:42:20 +000036#include "llvm/Analysis/CFLAliasAnalysis.h"
Hal Finkel7529c552014-09-02 21:43:13 +000037#include "StratifiedSets.h"
Hal Finkel7529c552014-09-02 21:43:13 +000038#include "llvm/ADT/DenseMap.h"
Hal Finkel7529c552014-09-02 21:43:13 +000039#include "llvm/ADT/None.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000040#include "llvm/ADT/Optional.h"
George Burgess IV18b83fe2016-06-01 18:39:54 +000041#include "llvm/Analysis/MemoryBuiltins.h"
42#include "llvm/Analysis/TargetLibraryInfo.h"
Hal Finkel7529c552014-09-02 21:43:13 +000043#include "llvm/IR/Constants.h"
44#include "llvm/IR/Function.h"
Hal Finkel7529c552014-09-02 21:43:13 +000045#include "llvm/IR/InstVisitor.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000046#include "llvm/IR/Instructions.h"
Hal Finkel7529c552014-09-02 21:43:13 +000047#include "llvm/Pass.h"
Hal Finkel7d7087c2014-09-02 22:13:00 +000048#include "llvm/Support/Compiler.h"
George Burgess IV33305e72015-02-12 03:07:07 +000049#include "llvm/Support/Debug.h"
Hal Finkel7529c552014-09-02 21:43:13 +000050#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000051#include "llvm/Support/raw_ostream.h"
Hal Finkel7529c552014-09-02 21:43:13 +000052#include <algorithm>
53#include <cassert>
Benjamin Kramer799003b2015-03-23 19:32:43 +000054#include <memory>
Hal Finkel7529c552014-09-02 21:43:13 +000055#include <tuple>
56
57using namespace llvm;
58
George Burgess IV33305e72015-02-12 03:07:07 +000059#define DEBUG_TYPE "cfl-aa"
60
George Burgess IV18b83fe2016-06-01 18:39:54 +000061CFLAAResult::CFLAAResult(const TargetLibraryInfo &TLI)
62 : AAResultBase(), TLI(TLI) {}
63CFLAAResult::CFLAAResult(CFLAAResult &&Arg)
64 : AAResultBase(std::move(Arg)), TLI(Arg.TLI) {}
Chandler Carruth342c6712016-02-20 03:52:02 +000065CFLAAResult::~CFLAAResult() {}
Chandler Carruth8b046a42015-08-14 02:42:20 +000066
George Burgess IVcae581d2016-04-13 23:27:37 +000067/// Information we have about a function and would like to keep around.
Chandler Carruth7b560d42015-09-09 17:55:00 +000068struct CFLAAResult::FunctionInfo {
Chandler Carruth8b046a42015-08-14 02:42:20 +000069 StratifiedSets<Value *> Sets;
70 // Lots of functions have < 4 returns. Adjust as necessary.
71 SmallVector<Value *, 4> ReturnedValues;
72
73 FunctionInfo(StratifiedSets<Value *> &&S, SmallVector<Value *, 4> &&RV)
74 : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
75};
76
George Burgess IVcae581d2016-04-13 23:27:37 +000077/// Try to go from a Value* to a Function*. Never returns nullptr.
Hal Finkel7529c552014-09-02 21:43:13 +000078static Optional<Function *> parentFunctionOfValue(Value *);
79
George Burgess IVcae581d2016-04-13 23:27:37 +000080/// Returns possible functions called by the Inst* into the given
81/// SmallVectorImpl. Returns true if targets found, false otherwise. This is
82/// templated so we can use it with CallInsts and InvokeInsts.
George Burgess IV24eb0da2016-06-14 18:12:28 +000083static bool getPossibleTargets(CallSite, SmallVectorImpl<Function *> &);
Hal Finkel7529c552014-09-02 21:43:13 +000084
Hal Finkel1ae325f2014-09-02 23:50:01 +000085const StratifiedIndex StratifiedLink::SetSentinel =
George Burgess IV11d509d2015-03-15 00:52:21 +000086 std::numeric_limits<StratifiedIndex>::max();
Hal Finkel1ae325f2014-09-02 23:50:01 +000087
Hal Finkel7529c552014-09-02 21:43:13 +000088namespace {
George Burgess IVcae581d2016-04-13 23:27:37 +000089/// StratifiedInfo Attribute things.
Hal Finkel7529c552014-09-02 21:43:13 +000090typedef unsigned StratifiedAttr;
Hal Finkel7d7087c2014-09-02 22:13:00 +000091LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
George Burgess IVa1f9a2d2016-06-07 18:35:37 +000092LLVM_CONSTEXPR unsigned AttrEscapedIndex = 0;
93LLVM_CONSTEXPR unsigned AttrUnknownIndex = 1;
94LLVM_CONSTEXPR unsigned AttrGlobalIndex = 2;
George Burgess IVb54a8d622015-03-10 02:40:06 +000095LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 3;
Hal Finkel7d7087c2014-09-02 22:13:00 +000096LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
97LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
Hal Finkel7529c552014-09-02 21:43:13 +000098
Hal Finkel7d7087c2014-09-02 22:13:00 +000099LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000100LLVM_CONSTEXPR StratifiedAttr AttrEscaped = 1 << AttrEscapedIndex;
George Burgess IVb54a8d622015-03-10 02:40:06 +0000101LLVM_CONSTEXPR StratifiedAttr AttrUnknown = 1 << AttrUnknownIndex;
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000102LLVM_CONSTEXPR StratifiedAttr AttrGlobal = 1 << AttrGlobalIndex;
Hal Finkel7529c552014-09-02 21:43:13 +0000103
George Burgess IVcae581d2016-04-13 23:27:37 +0000104/// StratifiedSets call for knowledge of "direction", so this is how we
105/// represent that locally.
Hal Finkel7529c552014-09-02 21:43:13 +0000106enum class Level { Same, Above, Below };
107
George Burgess IVcae581d2016-04-13 23:27:37 +0000108/// Edges can be one of four "weights" -- each weight must have an inverse
109/// weight (Assign has Assign; Reference has Dereference).
Hal Finkel7529c552014-09-02 21:43:13 +0000110enum class EdgeType {
George Burgess IVcae581d2016-04-13 23:27:37 +0000111 /// The weight assigned when assigning from or to a value. For example, in:
112 /// %b = getelementptr %a, 0
113 /// ...The relationships are %b assign %a, and %a assign %b. This used to be
114 /// two edges, but having a distinction bought us nothing.
Hal Finkel7529c552014-09-02 21:43:13 +0000115 Assign,
116
George Burgess IVcae581d2016-04-13 23:27:37 +0000117 /// The edge used when we have an edge going from some handle to a Value.
118 /// Examples of this include:
119 /// %b = load %a (%b Dereference %a)
120 /// %b = extractelement %a, 0 (%a Dereference %b)
Hal Finkel7529c552014-09-02 21:43:13 +0000121 Dereference,
122
George Burgess IVcae581d2016-04-13 23:27:37 +0000123 /// The edge used when our edge goes from a value to a handle that may have
124 /// contained it at some point. Examples:
125 /// %b = load %a (%a Reference %b)
126 /// %b = extractelement %a, 0 (%b Reference %a)
Hal Finkel7529c552014-09-02 21:43:13 +0000127 Reference
128};
129
George Burgess IV24eb0da2016-06-14 18:12:28 +0000130/// The Program Expression Graph (PEG) of CFL analysis
131class CFLGraph {
132 typedef Value *Node;
Hal Finkel7529c552014-09-02 21:43:13 +0000133
George Burgess IV24eb0da2016-06-14 18:12:28 +0000134 struct Edge {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000135 EdgeType Type;
136 Node Other;
137 };
Hal Finkel7529c552014-09-02 21:43:13 +0000138
George Burgess IV24eb0da2016-06-14 18:12:28 +0000139 typedef std::vector<Edge> EdgeList;
George Burgess IV259d9012016-06-15 20:43:41 +0000140
141 struct NodeInfo {
142 EdgeList Edges;
143 StratifiedAttrs Attr;
144 };
145
146 typedef DenseMap<Node, NodeInfo> NodeMap;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000147 NodeMap NodeImpls;
Hal Finkel7529c552014-09-02 21:43:13 +0000148
George Burgess IV24eb0da2016-06-14 18:12:28 +0000149 // Gets the inverse of a given EdgeType.
150 static EdgeType flipWeight(EdgeType Initial) {
151 switch (Initial) {
152 case EdgeType::Assign:
153 return EdgeType::Assign;
154 case EdgeType::Dereference:
155 return EdgeType::Reference;
156 case EdgeType::Reference:
157 return EdgeType::Dereference;
158 }
159 llvm_unreachable("Incomplete coverage of EdgeType enum");
160 }
Hal Finkel7529c552014-09-02 21:43:13 +0000161
George Burgess IV259d9012016-06-15 20:43:41 +0000162 const NodeInfo *getNode(Node N) const {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000163 auto Itr = NodeImpls.find(N);
164 if (Itr == NodeImpls.end())
165 return nullptr;
166 return &Itr->second;
167 }
George Burgess IV259d9012016-06-15 20:43:41 +0000168 NodeInfo *getNode(Node N) {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000169 auto Itr = NodeImpls.find(N);
170 if (Itr == NodeImpls.end())
171 return nullptr;
172 return &Itr->second;
173 }
174
175 static Node nodeDeref(const NodeMap::value_type &P) { return P.first; }
176 typedef std::pointer_to_unary_function<const NodeMap::value_type &, Node>
177 NodeDerefFun;
178
179public:
180 typedef EdgeList::const_iterator const_edge_iterator;
181 typedef mapped_iterator<NodeMap::const_iterator, NodeDerefFun>
182 const_node_iterator;
183
184 bool addNode(Node N) {
George Burgess IV259d9012016-06-15 20:43:41 +0000185 return NodeImpls.insert(std::make_pair(N, NodeInfo{EdgeList(), AttrNone}))
186 .second;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000187 }
188
George Burgess IV259d9012016-06-15 20:43:41 +0000189 void addAttr(Node N, StratifiedAttrs Attr) {
190 auto *Info = getNode(N);
191 assert(Info != nullptr);
192 Info->Attr |= Attr;
193 }
George Burgess IV24eb0da2016-06-14 18:12:28 +0000194
George Burgess IV259d9012016-06-15 20:43:41 +0000195 void addEdge(Node From, Node To, EdgeType Type) {
196 auto *FromInfo = getNode(From);
197 assert(FromInfo != nullptr);
198 auto *ToInfo = getNode(To);
199 assert(ToInfo != nullptr);
200
201 FromInfo->Edges.push_back(Edge{Type, To});
202 ToInfo->Edges.push_back(Edge{flipWeight(Type), From});
203 }
204
205 StratifiedAttrs attrFor(Node N) const {
206 auto *Info = getNode(N);
207 assert(Info != nullptr);
208 return Info->Attr;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000209 }
210
211 iterator_range<const_edge_iterator> edgesFor(Node N) const {
George Burgess IV259d9012016-06-15 20:43:41 +0000212 auto *Info = getNode(N);
213 assert(Info != nullptr);
214 auto &Edges = Info->Edges;
215 return make_range(Edges.begin(), Edges.end());
George Burgess IV24eb0da2016-06-14 18:12:28 +0000216 }
217
218 iterator_range<const_node_iterator> nodes() const {
219 return make_range<const_node_iterator>(
220 map_iterator(NodeImpls.begin(), NodeDerefFun(nodeDeref)),
221 map_iterator(NodeImpls.end(), NodeDerefFun(nodeDeref)));
222 }
223
224 bool empty() const { return NodeImpls.empty(); }
225 std::size_t size() const { return NodeImpls.size(); }
Hal Finkel7529c552014-09-02 21:43:13 +0000226};
227
George Burgess IVcae581d2016-04-13 23:27:37 +0000228/// Gets the edges our graph should have, based on an Instruction*
Hal Finkel7529c552014-09-02 21:43:13 +0000229class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
Chandler Carruth7b560d42015-09-09 17:55:00 +0000230 CFLAAResult &AA;
George Burgess IV18b83fe2016-06-01 18:39:54 +0000231 const TargetLibraryInfo &TLI;
Hal Finkel7529c552014-09-02 21:43:13 +0000232
George Burgess IV24eb0da2016-06-14 18:12:28 +0000233 CFLGraph &Graph;
234 SmallPtrSetImpl<Value *> &Externals;
235 SmallPtrSetImpl<Value *> &Escapes;
236
237 static bool hasUsefulEdges(ConstantExpr *CE) {
238 // ConstantExpr doesn't have terminators, invokes, or fences, so only needs
239 // to check for compares.
240 return CE->getOpcode() != Instruction::ICmp &&
241 CE->getOpcode() != Instruction::FCmp;
242 }
243
244 void addNode(Value *Val) {
245 if (!Graph.addNode(Val))
246 return;
247
248 if (isa<GlobalValue>(Val))
249 Externals.insert(Val);
250 else if (auto CExpr = dyn_cast<ConstantExpr>(Val))
251 if (hasUsefulEdges(CExpr))
252 visitConstantExpr(CExpr);
253 }
254
George Burgess IV259d9012016-06-15 20:43:41 +0000255 void addNodeWithAttr(Value *Val, StratifiedAttrs Attr) {
256 addNode(Val);
257 Graph.addAttr(Val, Attr);
258 }
259
260 void addEdge(Value *From, Value *To, EdgeType Type) {
261 if (!From->getType()->isPointerTy() || !To->getType()->isPointerTy())
262 return;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000263 addNode(From);
264 if (To != From)
265 addNode(To);
George Burgess IV259d9012016-06-15 20:43:41 +0000266 Graph.addEdge(From, To, Type);
George Burgess IV24eb0da2016-06-14 18:12:28 +0000267 }
268
Hal Finkel7529c552014-09-02 21:43:13 +0000269public:
George Burgess IV24eb0da2016-06-14 18:12:28 +0000270 GetEdgesVisitor(CFLAAResult &AA, const TargetLibraryInfo &TLI,
271 CFLGraph &Graph, SmallPtrSetImpl<Value *> &Externals,
272 SmallPtrSetImpl<Value *> &Escapes)
273 : AA(AA), TLI(TLI), Graph(Graph), Externals(Externals), Escapes(Escapes) {
274 }
Hal Finkel7529c552014-09-02 21:43:13 +0000275
276 void visitInstruction(Instruction &) {
277 llvm_unreachable("Unsupported instruction encountered");
278 }
279
George Burgess IVb54a8d622015-03-10 02:40:06 +0000280 void visitPtrToIntInst(PtrToIntInst &Inst) {
281 auto *Ptr = Inst.getOperand(0);
George Burgess IV259d9012016-06-15 20:43:41 +0000282 addNodeWithAttr(Ptr, AttrEscaped);
George Burgess IVb54a8d622015-03-10 02:40:06 +0000283 }
284
285 void visitIntToPtrInst(IntToPtrInst &Inst) {
286 auto *Ptr = &Inst;
George Burgess IV259d9012016-06-15 20:43:41 +0000287 addNodeWithAttr(Ptr, AttrUnknown);
George Burgess IVb54a8d622015-03-10 02:40:06 +0000288 }
289
Hal Finkel7529c552014-09-02 21:43:13 +0000290 void visitCastInst(CastInst &Inst) {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000291 auto *Src = Inst.getOperand(0);
George Burgess IV259d9012016-06-15 20:43:41 +0000292 addEdge(Src, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000293 }
294
295 void visitBinaryOperator(BinaryOperator &Inst) {
296 auto *Op1 = Inst.getOperand(0);
297 auto *Op2 = Inst.getOperand(1);
George Burgess IV259d9012016-06-15 20:43:41 +0000298 addEdge(Op1, &Inst, EdgeType::Assign);
299 addEdge(Op2, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000300 }
301
302 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
303 auto *Ptr = Inst.getPointerOperand();
304 auto *Val = Inst.getNewValOperand();
George Burgess IV259d9012016-06-15 20:43:41 +0000305 addEdge(Ptr, Val, EdgeType::Dereference);
Hal Finkel7529c552014-09-02 21:43:13 +0000306 }
307
308 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
309 auto *Ptr = Inst.getPointerOperand();
310 auto *Val = Inst.getValOperand();
George Burgess IV259d9012016-06-15 20:43:41 +0000311 addEdge(Ptr, Val, EdgeType::Dereference);
Hal Finkel7529c552014-09-02 21:43:13 +0000312 }
313
314 void visitPHINode(PHINode &Inst) {
George Burgess IV77351ba32016-01-28 00:54:01 +0000315 for (Value *Val : Inst.incoming_values())
George Burgess IV259d9012016-06-15 20:43:41 +0000316 addEdge(Val, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000317 }
318
319 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
320 auto *Op = Inst.getPointerOperand();
George Burgess IV259d9012016-06-15 20:43:41 +0000321 addEdge(Op, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000322 }
323
324 void visitSelectInst(SelectInst &Inst) {
Daniel Berlin16f7a522015-01-26 17:31:17 +0000325 // Condition is not processed here (The actual statement producing
326 // the condition result is processed elsewhere). For select, the
327 // condition is evaluated, but not loaded, stored, or assigned
328 // simply as a result of being the condition of a select.
329
Hal Finkel7529c552014-09-02 21:43:13 +0000330 auto *TrueVal = Inst.getTrueValue();
Hal Finkel7529c552014-09-02 21:43:13 +0000331 auto *FalseVal = Inst.getFalseValue();
George Burgess IV259d9012016-06-15 20:43:41 +0000332 addEdge(TrueVal, &Inst, EdgeType::Assign);
333 addEdge(FalseVal, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000334 }
335
George Burgess IV24eb0da2016-06-14 18:12:28 +0000336 void visitAllocaInst(AllocaInst &Inst) { Graph.addNode(&Inst); }
Hal Finkel7529c552014-09-02 21:43:13 +0000337
338 void visitLoadInst(LoadInst &Inst) {
339 auto *Ptr = Inst.getPointerOperand();
340 auto *Val = &Inst;
George Burgess IV259d9012016-06-15 20:43:41 +0000341 addEdge(Val, Ptr, EdgeType::Reference);
Hal Finkel7529c552014-09-02 21:43:13 +0000342 }
343
344 void visitStoreInst(StoreInst &Inst) {
345 auto *Ptr = Inst.getPointerOperand();
346 auto *Val = Inst.getValueOperand();
George Burgess IV259d9012016-06-15 20:43:41 +0000347 addEdge(Ptr, Val, EdgeType::Dereference);
Hal Finkel7529c552014-09-02 21:43:13 +0000348 }
349
Hal Finkeldb5f86a2014-10-14 20:51:26 +0000350 void visitVAArgInst(VAArgInst &Inst) {
351 // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
352 // two things:
353 // 1. Loads a value from *((T*)*Ptr).
354 // 2. Increments (stores to) *Ptr by some target-specific amount.
355 // For now, we'll handle this like a landingpad instruction (by placing the
356 // result in its own group, and having that group alias externals).
George Burgess IV259d9012016-06-15 20:43:41 +0000357 addNodeWithAttr(&Inst, AttrUnknown);
Hal Finkeldb5f86a2014-10-14 20:51:26 +0000358 }
359
Hal Finkel7529c552014-09-02 21:43:13 +0000360 static bool isFunctionExternal(Function *Fn) {
361 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
362 }
363
George Burgess IVcae581d2016-04-13 23:27:37 +0000364 /// Gets whether the sets at Index1 above, below, or equal to the sets at
365 /// Index2. Returns None if they are not in the same set chain.
Hal Finkel7529c552014-09-02 21:43:13 +0000366 static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
367 StratifiedIndex Index1,
368 StratifiedIndex Index2) {
369 if (Index1 == Index2)
370 return Level::Same;
371
372 const auto *Current = &Sets.getLink(Index1);
373 while (Current->hasBelow()) {
374 if (Current->Below == Index2)
375 return Level::Below;
376 Current = &Sets.getLink(Current->Below);
377 }
378
379 Current = &Sets.getLink(Index1);
380 while (Current->hasAbove()) {
381 if (Current->Above == Index2)
382 return Level::Above;
383 Current = &Sets.getLink(Current->Above);
384 }
385
George Burgess IV77351ba32016-01-28 00:54:01 +0000386 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000387 }
388
George Burgess IV24eb0da2016-06-14 18:12:28 +0000389 // Encodes the notion of a "use"
390 struct Edge {
391 // Which value the edge is coming from
392 Value *From;
393
394 // Which value the edge is pointing to
395 Value *To;
396
397 // Edge weight
398 EdgeType Weight;
399
400 // Whether we aliased any external values along the way that may be
George Burgess IV259d9012016-06-15 20:43:41 +0000401 // invisible to the analysis
402 StratifiedAttrs FromAttrs, ToAttrs;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000403 };
404
Hal Finkel7529c552014-09-02 21:43:13 +0000405 bool
406 tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
407 Value *FuncValue,
408 const iterator_range<User::op_iterator> &Args) {
Hal Finkelca616ac2014-09-02 23:29:48 +0000409 const unsigned ExpectedMaxArgs = 8;
410 const unsigned MaxSupportedArgs = 50;
Hal Finkel7529c552014-09-02 21:43:13 +0000411 assert(Fns.size() > 0);
412
George Burgess IVcae581d2016-04-13 23:27:37 +0000413 // This algorithm is n^2, so an arbitrary upper-bound of 50 args was
414 // selected, so it doesn't take too long in insane cases.
George Burgess IVab03af22015-03-10 02:58:15 +0000415 if (std::distance(Args.begin(), Args.end()) > (int)MaxSupportedArgs)
Hal Finkel7529c552014-09-02 21:43:13 +0000416 return false;
417
418 // Exit early if we'll fail anyway
419 for (auto *Fn : Fns) {
420 if (isFunctionExternal(Fn) || Fn->isVarArg())
421 return false;
422 auto &MaybeInfo = AA.ensureCached(Fn);
423 if (!MaybeInfo.hasValue())
424 return false;
425 }
426
George Burgess IV24eb0da2016-06-14 18:12:28 +0000427 SmallVector<Edge, 8> Output;
Hal Finkel7529c552014-09-02 21:43:13 +0000428 SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
429 SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
430 for (auto *Fn : Fns) {
431 auto &Info = *AA.ensureCached(Fn);
432 auto &Sets = Info.Sets;
433 auto &RetVals = Info.ReturnedValues;
434
435 Parameters.clear();
436 for (auto &Param : Fn->args()) {
437 auto MaybeInfo = Sets.find(&Param);
438 // Did a new parameter somehow get added to the function/slip by?
439 if (!MaybeInfo.hasValue())
440 return false;
441 Parameters.push_back(*MaybeInfo);
442 }
443
444 // Adding an edge from argument -> return value for each parameter that
445 // may alias the return value
446 for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
447 auto &ParamInfo = Parameters[I];
448 auto &ArgVal = Arguments[I];
449 bool AddEdge = false;
George Burgess IV259d9012016-06-15 20:43:41 +0000450 StratifiedAttrs RetAttrs, ParamAttrs;
Hal Finkel7529c552014-09-02 21:43:13 +0000451 for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
452 auto MaybeInfo = Sets.find(RetVals[X]);
453 if (!MaybeInfo.hasValue())
454 return false;
455
456 auto &RetInfo = *MaybeInfo;
George Burgess IV259d9012016-06-15 20:43:41 +0000457 RetAttrs |= Sets.getLink(RetInfo.Index).Attrs;
458 ParamAttrs |= Sets.getLink(ParamInfo.Index).Attrs;
Hal Finkel7529c552014-09-02 21:43:13 +0000459 auto MaybeRelation =
460 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
George Burgess IV259d9012016-06-15 20:43:41 +0000461 if (MaybeRelation.hasValue())
Hal Finkel7529c552014-09-02 21:43:13 +0000462 AddEdge = true;
Hal Finkel7529c552014-09-02 21:43:13 +0000463 }
464 if (AddEdge)
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000465 Output.push_back(
George Burgess IV259d9012016-06-15 20:43:41 +0000466 Edge{FuncValue, ArgVal, EdgeType::Assign, RetAttrs, ParamAttrs});
Hal Finkel7529c552014-09-02 21:43:13 +0000467 }
468
469 if (Parameters.size() != Arguments.size())
470 return false;
471
George Burgess IVcae581d2016-04-13 23:27:37 +0000472 /// Adding edges between arguments for arguments that may end up aliasing
473 /// each other. This is necessary for functions such as
474 /// void foo(int** a, int** b) { *a = *b; }
475 /// (Technically, the proper sets for this would be those below
476 /// Arguments[I] and Arguments[X], but our algorithm will produce
477 /// extremely similar, and equally correct, results either way)
Hal Finkel7529c552014-09-02 21:43:13 +0000478 for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
479 auto &MainVal = Arguments[I];
480 auto &MainInfo = Parameters[I];
481 auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
482 for (unsigned X = I + 1; X != E; ++X) {
483 auto &SubInfo = Parameters[X];
484 auto &SubVal = Arguments[X];
485 auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
486 auto MaybeRelation =
487 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
488
489 if (!MaybeRelation.hasValue())
490 continue;
491
George Burgess IV259d9012016-06-15 20:43:41 +0000492 Output.push_back(
493 Edge{MainVal, SubVal, EdgeType::Assign, MainAttrs, SubAttrs});
Hal Finkel7529c552014-09-02 21:43:13 +0000494 }
495 }
496 }
George Burgess IV24eb0da2016-06-14 18:12:28 +0000497
498 // Commit all edges in Output to CFLGraph
George Burgess IV259d9012016-06-15 20:43:41 +0000499 for (const auto &Edge : Output) {
500 addEdge(Edge.From, Edge.To, Edge.Weight);
501 Graph.addAttr(Edge.From, Edge.FromAttrs);
502 Graph.addAttr(Edge.To, Edge.ToAttrs);
503 }
George Burgess IV24eb0da2016-06-14 18:12:28 +0000504
Hal Finkel7529c552014-09-02 21:43:13 +0000505 return true;
506 }
507
George Burgess IV24eb0da2016-06-14 18:12:28 +0000508 void visitCallSite(CallSite CS) {
509 auto Inst = CS.getInstruction();
510
511 // Make sure all arguments and return value are added to the graph first
512 for (Value *V : CS.args())
513 addNode(V);
514 if (!Inst->getType()->isVoidTy())
515 addNode(Inst);
516
George Burgess IV18b83fe2016-06-01 18:39:54 +0000517 // Check if Inst is a call to a library function that allocates/deallocates
518 // on the heap. Those kinds of functions do not introduce any aliases.
519 // TODO: address other common library functions such as realloc(), strdup(),
520 // etc.
George Burgess IV24eb0da2016-06-14 18:12:28 +0000521 if (isMallocLikeFn(Inst, &TLI) || isCallocLikeFn(Inst, &TLI) ||
522 isFreeCall(Inst, &TLI))
George Burgess IV18b83fe2016-06-01 18:39:54 +0000523 return;
George Burgess IV18b83fe2016-06-01 18:39:54 +0000524
George Burgess IV68b36e02015-08-28 00:16:18 +0000525 // TODO: Add support for noalias args/all the other fun function attributes
526 // that we can tack on.
Hal Finkel7529c552014-09-02 21:43:13 +0000527 SmallVector<Function *, 4> Targets;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000528 if (getPossibleTargets(CS, Targets))
529 if (tryInterproceduralAnalysis(Targets, Inst, CS.args()))
Hal Finkel7529c552014-09-02 21:43:13 +0000530 return;
Hal Finkel7529c552014-09-02 21:43:13 +0000531
George Burgess IV68b36e02015-08-28 00:16:18 +0000532 // Because the function is opaque, we need to note that anything
George Burgess IV24eb0da2016-06-14 18:12:28 +0000533 // could have happened to the arguments (unless the function is marked
534 // readonly or readnone), and that the result could alias just about
535 // anything, too (unless the result is marked noalias).
536 if (!CS.onlyReadsMemory())
537 for (Value *V : CS.args()) {
George Burgess IV259d9012016-06-15 20:43:41 +0000538 if (V->getType()->isPointerTy())
539 Escapes.insert(V);
George Burgess IV24eb0da2016-06-14 18:12:28 +0000540 }
541
542 if (!Inst->getType()->isVoidTy()) {
543 auto *Fn = CS.getCalledFunction();
544 if (Fn == nullptr || !Fn->doesNotAlias(0))
George Burgess IV259d9012016-06-15 20:43:41 +0000545 Graph.addAttr(Inst, AttrUnknown);
George Burgess IV24eb0da2016-06-14 18:12:28 +0000546 }
Hal Finkel7529c552014-09-02 21:43:13 +0000547 }
548
George Burgess IVcae581d2016-04-13 23:27:37 +0000549 /// Because vectors/aggregates are immutable and unaddressable, there's
550 /// nothing we can do to coax a value out of them, other than calling
551 /// Extract{Element,Value}. We can effectively treat them as pointers to
552 /// arbitrary memory locations we can store in and load from.
Hal Finkel7529c552014-09-02 21:43:13 +0000553 void visitExtractElementInst(ExtractElementInst &Inst) {
554 auto *Ptr = Inst.getVectorOperand();
555 auto *Val = &Inst;
George Burgess IV259d9012016-06-15 20:43:41 +0000556 addEdge(Val, Ptr, EdgeType::Reference);
Hal Finkel7529c552014-09-02 21:43:13 +0000557 }
558
559 void visitInsertElementInst(InsertElementInst &Inst) {
560 auto *Vec = Inst.getOperand(0);
561 auto *Val = Inst.getOperand(1);
George Burgess IV259d9012016-06-15 20:43:41 +0000562 addEdge(Vec, &Inst, EdgeType::Assign);
563 addEdge(&Inst, Val, EdgeType::Dereference);
Hal Finkel7529c552014-09-02 21:43:13 +0000564 }
565
566 void visitLandingPadInst(LandingPadInst &Inst) {
567 // Exceptions come from "nowhere", from our analysis' perspective.
568 // So we place the instruction its own group, noting that said group may
569 // alias externals
George Burgess IV259d9012016-06-15 20:43:41 +0000570 addNodeWithAttr(&Inst, AttrUnknown);
Hal Finkel7529c552014-09-02 21:43:13 +0000571 }
572
573 void visitInsertValueInst(InsertValueInst &Inst) {
574 auto *Agg = Inst.getOperand(0);
575 auto *Val = Inst.getOperand(1);
George Burgess IV259d9012016-06-15 20:43:41 +0000576 addEdge(Agg, &Inst, EdgeType::Assign);
577 addEdge(&Inst, Val, EdgeType::Dereference);
Hal Finkel7529c552014-09-02 21:43:13 +0000578 }
579
580 void visitExtractValueInst(ExtractValueInst &Inst) {
581 auto *Ptr = Inst.getAggregateOperand();
George Burgess IV259d9012016-06-15 20:43:41 +0000582 addEdge(&Inst, Ptr, EdgeType::Reference);
Hal Finkel7529c552014-09-02 21:43:13 +0000583 }
584
585 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
586 auto *From1 = Inst.getOperand(0);
587 auto *From2 = Inst.getOperand(1);
George Burgess IV259d9012016-06-15 20:43:41 +0000588 addEdge(From1, &Inst, EdgeType::Assign);
589 addEdge(From2, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000590 }
Pete Cooper36642532015-06-12 16:13:54 +0000591
592 void visitConstantExpr(ConstantExpr *CE) {
593 switch (CE->getOpcode()) {
594 default:
595 llvm_unreachable("Unknown instruction type encountered!");
596// Build the switch statement using the Instruction.def file.
597#define HANDLE_INST(NUM, OPCODE, CLASS) \
598 case Instruction::OPCODE: \
599 visit##OPCODE(*(CLASS *)CE); \
600 break;
601#include "llvm/IR/Instruction.def"
602 }
603 }
Hal Finkel7529c552014-09-02 21:43:13 +0000604};
605
George Burgess IVe17756e2016-06-14 18:02:27 +0000606class CFLGraphBuilder {
607 // Input of the builder
608 CFLAAResult &Analysis;
609 const TargetLibraryInfo &TLI;
610
611 // Output of the builder
612 CFLGraph Graph;
613 SmallVector<Value *, 4> ReturnedValues;
614
615 // Auxiliary structures used by the builder
George Burgess IV24eb0da2016-06-14 18:12:28 +0000616 SmallPtrSet<Value *, 8> ExternalValues;
617 SmallPtrSet<Value *, 8> EscapedValues;
George Burgess IVe17756e2016-06-14 18:02:27 +0000618
619 // Helper functions
620
621 // Determines whether or not we an instruction is useless to us (e.g.
622 // FenceInst)
623 static bool hasUsefulEdges(Instruction *Inst) {
624 bool IsNonInvokeTerminator =
625 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
626 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) &&
627 !IsNonInvokeTerminator;
628 }
629
George Burgess IV24eb0da2016-06-14 18:12:28 +0000630 void addArgumentToGraph(Argument &Arg) {
George Burgess IV259d9012016-06-15 20:43:41 +0000631 if (Arg.getType()->isPointerTy()) {
632 Graph.addNode(&Arg);
633 ExternalValues.insert(&Arg);
634 }
George Burgess IVe17756e2016-06-14 18:02:27 +0000635 }
636
637 // Given an Instruction, this will add it to the graph, along with any
638 // Instructions that are potentially only available from said Instruction
639 // For example, given the following line:
640 // %0 = load i16* getelementptr ([1 x i16]* @a, 0, 0), align 2
641 // addInstructionToGraph would add both the `load` and `getelementptr`
642 // instructions to the graph appropriately.
643 void addInstructionToGraph(Instruction &Inst) {
644 // We don't want the edges of most "return" instructions, but we *do* want
645 // to know what can be returned.
646 if (isa<ReturnInst>(&Inst))
647 ReturnedValues.push_back(&Inst);
648
649 if (!hasUsefulEdges(&Inst))
650 return;
651
George Burgess IV24eb0da2016-06-14 18:12:28 +0000652 GetEdgesVisitor(Analysis, TLI, Graph, ExternalValues, EscapedValues)
653 .visit(Inst);
654 }
George Burgess IVe17756e2016-06-14 18:02:27 +0000655
George Burgess IV24eb0da2016-06-14 18:12:28 +0000656 // Builds the graph needed for constructing the StratifiedSets for the given
657 // function
658 void buildGraphFrom(Function &Fn) {
659 for (auto &Bb : Fn.getBasicBlockList())
660 for (auto &Inst : Bb.getInstList())
661 addInstructionToGraph(Inst);
George Burgess IVe17756e2016-06-14 18:02:27 +0000662
George Burgess IV24eb0da2016-06-14 18:12:28 +0000663 for (auto &Arg : Fn.args())
664 addArgumentToGraph(Arg);
George Burgess IVe17756e2016-06-14 18:02:27 +0000665 }
666
667public:
668 CFLGraphBuilder(CFLAAResult &Analysis, const TargetLibraryInfo &TLI,
669 Function &Fn)
670 : Analysis(Analysis), TLI(TLI) {
671 buildGraphFrom(Fn);
672 }
673
674 const CFLGraph &getCFLGraph() { return Graph; }
675 SmallVector<Value *, 4> takeReturnValues() {
676 return std::move(ReturnedValues);
677 }
George Burgess IV24eb0da2016-06-14 18:12:28 +0000678 const SmallPtrSet<Value *, 8> &getExternalValues() { return ExternalValues; }
679 const SmallPtrSet<Value *, 8> &getEscapedValues() { return EscapedValues; }
George Burgess IVe17756e2016-06-14 18:02:27 +0000680};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000681}
Hal Finkel7529c552014-09-02 21:43:13 +0000682
Hal Finkel7529c552014-09-02 21:43:13 +0000683//===----------------------------------------------------------------------===//
684// Function declarations that require types defined in the namespace above
685//===----------------------------------------------------------------------===//
686
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000687/// Given a StratifiedAttrs, returns true if it marks the corresponding values
688/// as globals or arguments
689static bool isGlobalOrArgAttr(StratifiedAttrs Attr);
Hal Finkel7529c552014-09-02 21:43:13 +0000690
George Burgess IV652ec4f2016-06-09 23:15:04 +0000691/// Given a StratifiedAttrs, returns true if the corresponding values come from
692/// an unknown source (such as opaque memory or an integer cast)
693static bool isUnknownAttr(StratifiedAttrs Attr);
694
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000695/// Given an argument number, returns the appropriate StratifiedAttr to set.
696static StratifiedAttr argNumberToAttr(unsigned ArgNum);
697
698/// Given a Value, potentially return which StratifiedAttr it maps to.
699static Optional<StratifiedAttr> valueToAttr(Value *Val);
Hal Finkel7529c552014-09-02 21:43:13 +0000700
George Burgess IVcae581d2016-04-13 23:27:37 +0000701/// Gets the "Level" that one should travel in StratifiedSets
702/// given an EdgeType.
Hal Finkel7529c552014-09-02 21:43:13 +0000703static Level directionOfEdgeType(EdgeType);
704
George Burgess IVcae581d2016-04-13 23:27:37 +0000705/// Determines whether it would be pointless to add the given Value to our sets.
George Burgess IVab03af22015-03-10 02:58:15 +0000706static bool canSkipAddingToSets(Value *Val);
707
Hal Finkel7529c552014-09-02 21:43:13 +0000708static Optional<Function *> parentFunctionOfValue(Value *Val) {
709 if (auto *Inst = dyn_cast<Instruction>(Val)) {
710 auto *Bb = Inst->getParent();
711 return Bb->getParent();
712 }
713
714 if (auto *Arg = dyn_cast<Argument>(Val))
715 return Arg->getParent();
George Burgess IV77351ba32016-01-28 00:54:01 +0000716 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000717}
718
George Burgess IV24eb0da2016-06-14 18:12:28 +0000719static bool getPossibleTargets(CallSite CS,
Hal Finkel7529c552014-09-02 21:43:13 +0000720 SmallVectorImpl<Function *> &Output) {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000721 if (auto *Fn = CS.getCalledFunction()) {
Hal Finkel7529c552014-09-02 21:43:13 +0000722 Output.push_back(Fn);
723 return true;
724 }
725
726 // TODO: If the call is indirect, we might be able to enumerate all potential
727 // targets of the call and return them, rather than just failing.
728 return false;
729}
730
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000731static bool isGlobalOrArgAttr(StratifiedAttrs Attr) {
732 return Attr.reset(AttrEscapedIndex).reset(AttrUnknownIndex).any();
733}
734
George Burgess IV652ec4f2016-06-09 23:15:04 +0000735static bool isUnknownAttr(StratifiedAttrs Attr) {
736 return Attr.test(AttrUnknownIndex);
737}
738
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000739static Optional<StratifiedAttr> valueToAttr(Value *Val) {
Hal Finkel7529c552014-09-02 21:43:13 +0000740 if (isa<GlobalValue>(Val))
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000741 return AttrGlobal;
Hal Finkel7529c552014-09-02 21:43:13 +0000742
743 if (auto *Arg = dyn_cast<Argument>(Val))
Daniel Berlin16f7a522015-01-26 17:31:17 +0000744 // 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())
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000748 return argNumberToAttr(Arg->getArgNo());
George Burgess IV77351ba32016-01-28 00:54:01 +0000749 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000750}
751
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000752static StratifiedAttr argNumberToAttr(unsigned ArgNum) {
George Burgess IV3c898c22015-01-21 16:37:21 +0000753 if (ArgNum >= AttrMaxNumArgs)
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000754 return AttrUnknown;
755 return 1 << (ArgNum + AttrFirstArgIndex);
Hal Finkel7529c552014-09-02 21:43:13 +0000756}
757
Hal Finkel7529c552014-09-02 21:43:13 +0000758static Level directionOfEdgeType(EdgeType Weight) {
759 switch (Weight) {
760 case EdgeType::Reference:
761 return Level::Above;
762 case EdgeType::Dereference:
763 return Level::Below;
764 case EdgeType::Assign:
765 return Level::Same;
766 }
767 llvm_unreachable("Incomplete switch coverage");
768}
769
George Burgess IVab03af22015-03-10 02:58:15 +0000770static bool canSkipAddingToSets(Value *Val) {
771 // Constants can share instances, which may falsely unify multiple
772 // sets, e.g. in
773 // store i32* null, i32** %ptr1
774 // store i32* null, i32** %ptr2
775 // clearly ptr1 and ptr2 should not be unified into the same set, so
776 // we should filter out the (potentially shared) instance to
777 // i32* null.
778 if (isa<Constant>(Val)) {
George Burgess IVab03af22015-03-10 02:58:15 +0000779 // TODO: Because all of these things are constant, we can determine whether
780 // the data is *actually* mutable at graph building time. This will probably
781 // come for free/cheap with offset awareness.
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000782 bool CanStoreMutableData = isa<GlobalValue>(Val) ||
783 isa<ConstantExpr>(Val) ||
784 isa<ConstantAggregate>(Val);
George Burgess IVab03af22015-03-10 02:58:15 +0000785 return !CanStoreMutableData;
786 }
787
788 return false;
Hal Finkel7529c552014-09-02 21:43:13 +0000789}
790
Chandler Carruth8b046a42015-08-14 02:42:20 +0000791// Builds the graph + StratifiedSets for a function.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000792CFLAAResult::FunctionInfo CFLAAResult::buildSetsFrom(Function *Fn) {
George Burgess IVe17756e2016-06-14 18:02:27 +0000793 CFLGraphBuilder GraphBuilder(*this, TLI, *Fn);
794 StratifiedSetsBuilder<Value *> SetBuilder;
Hal Finkel7529c552014-09-02 21:43:13 +0000795
George Burgess IVe17756e2016-06-14 18:02:27 +0000796 auto &Graph = GraphBuilder.getCFLGraph();
George Burgess IVdc96feb2016-06-13 19:21:18 +0000797 SmallVector<Value *, 16> Worklist;
George Burgess IVdc96feb2016-06-13 19:21:18 +0000798 for (auto Node : Graph.nodes())
799 Worklist.push_back(Node);
800
801 while (!Worklist.empty()) {
802 auto *CurValue = Worklist.pop_back_val();
George Burgess IVe17756e2016-06-14 18:02:27 +0000803 SetBuilder.add(CurValue);
George Burgess IVdc96feb2016-06-13 19:21:18 +0000804 if (canSkipAddingToSets(CurValue))
805 continue;
806
George Burgess IV259d9012016-06-15 20:43:41 +0000807 auto Attr = Graph.attrFor(CurValue);
808 SetBuilder.noteAttributes(CurValue, Attr);
809
George Burgess IVdc96feb2016-06-13 19:21:18 +0000810 for (const auto &Edge : Graph.edgesFor(CurValue)) {
811 auto Label = Edge.Type;
812 auto *OtherValue = Edge.Other;
813
814 if (canSkipAddingToSets(OtherValue))
Hal Finkel7529c552014-09-02 21:43:13 +0000815 continue;
816
George Burgess IVdc96feb2016-06-13 19:21:18 +0000817 bool Added;
818 switch (directionOfEdgeType(Label)) {
819 case Level::Above:
George Burgess IVe17756e2016-06-14 18:02:27 +0000820 Added = SetBuilder.addAbove(CurValue, OtherValue);
George Burgess IVdc96feb2016-06-13 19:21:18 +0000821 break;
822 case Level::Below:
George Burgess IVe17756e2016-06-14 18:02:27 +0000823 Added = SetBuilder.addBelow(CurValue, OtherValue);
George Burgess IVdc96feb2016-06-13 19:21:18 +0000824 break;
825 case Level::Same:
George Burgess IVe17756e2016-06-14 18:02:27 +0000826 Added = SetBuilder.addWith(CurValue, OtherValue);
George Burgess IVdc96feb2016-06-13 19:21:18 +0000827 break;
Hal Finkel7529c552014-09-02 21:43:13 +0000828 }
George Burgess IVdc96feb2016-06-13 19:21:18 +0000829
George Burgess IVdc96feb2016-06-13 19:21:18 +0000830 if (Added)
831 Worklist.push_back(OtherValue);
Hal Finkel7529c552014-09-02 21:43:13 +0000832 }
833 }
834
George Burgess IV652ec4f2016-06-09 23:15:04 +0000835 // Special handling for globals and arguments
George Burgess IV24eb0da2016-06-14 18:12:28 +0000836 for (auto *External : GraphBuilder.getExternalValues()) {
837 SetBuilder.add(External);
838 auto Attr = valueToAttr(External);
George Burgess IV652ec4f2016-06-09 23:15:04 +0000839 if (Attr.hasValue()) {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000840 SetBuilder.noteAttributes(External, *Attr);
841 SetBuilder.addAttributesBelow(External, AttrUnknown);
George Burgess IV652ec4f2016-06-09 23:15:04 +0000842 }
George Burgess IV24eb0da2016-06-14 18:12:28 +0000843 }
George Burgess IVab03af22015-03-10 02:58:15 +0000844
George Burgess IV24eb0da2016-06-14 18:12:28 +0000845 for (auto *Escape : GraphBuilder.getEscapedValues()) {
846 SetBuilder.add(Escape);
847 SetBuilder.noteAttributes(Escape, AttrEscaped);
848 SetBuilder.addAttributesBelow(Escape, AttrUnknown);
849 }
Hal Finkel7529c552014-09-02 21:43:13 +0000850
George Burgess IVe17756e2016-06-14 18:02:27 +0000851 return FunctionInfo(SetBuilder.build(), GraphBuilder.takeReturnValues());
Hal Finkel7529c552014-09-02 21:43:13 +0000852}
853
Chandler Carruth7b560d42015-09-09 17:55:00 +0000854void CFLAAResult::scan(Function *Fn) {
Hal Finkel8d1590d2014-09-02 22:52:30 +0000855 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
Hal Finkel7529c552014-09-02 21:43:13 +0000856 (void)InsertPair;
857 assert(InsertPair.second &&
858 "Trying to scan a function that has already been cached");
859
George Burgess IV6edb8912016-05-02 18:09:19 +0000860 // Note that we can't do Cache[Fn] = buildSetsFrom(Fn) here: the function call
861 // may get evaluated after operator[], potentially triggering a DenseMap
862 // resize and invalidating the reference returned by operator[]
863 auto FunInfo = buildSetsFrom(Fn);
864 Cache[Fn] = std::move(FunInfo);
865
Hal Finkel7529c552014-09-02 21:43:13 +0000866 Handles.push_front(FunctionHandle(Fn, this));
867}
868
Chandler Carruth7b560d42015-09-09 17:55:00 +0000869void CFLAAResult::evict(Function *Fn) { Cache.erase(Fn); }
Chandler Carruth8b046a42015-08-14 02:42:20 +0000870
George Burgess IVcae581d2016-04-13 23:27:37 +0000871/// Ensures that the given function is available in the cache, and returns the
872/// entry.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000873const Optional<CFLAAResult::FunctionInfo> &
874CFLAAResult::ensureCached(Function *Fn) {
Chandler Carruth8b046a42015-08-14 02:42:20 +0000875 auto Iter = Cache.find(Fn);
876 if (Iter == Cache.end()) {
877 scan(Fn);
878 Iter = Cache.find(Fn);
879 assert(Iter != Cache.end());
880 assert(Iter->second.hasValue());
881 }
882 return Iter->second;
883}
884
Chandler Carruth7b560d42015-09-09 17:55:00 +0000885AliasResult CFLAAResult::query(const MemoryLocation &LocA,
886 const MemoryLocation &LocB) {
Hal Finkel7529c552014-09-02 21:43:13 +0000887 auto *ValA = const_cast<Value *>(LocA.Ptr);
888 auto *ValB = const_cast<Value *>(LocB.Ptr);
889
George Burgess IV259d9012016-06-15 20:43:41 +0000890 if (!ValA->getType()->isPointerTy() || !ValB->getType()->isPointerTy())
891 return NoAlias;
892
Hal Finkel7529c552014-09-02 21:43:13 +0000893 Function *Fn = nullptr;
894 auto MaybeFnA = parentFunctionOfValue(ValA);
895 auto MaybeFnB = parentFunctionOfValue(ValB);
896 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
George Burgess IVcae581d2016-04-13 23:27:37 +0000897 // The only times this is known to happen are when globals + InlineAsm are
898 // involved
George Burgess IV33305e72015-02-12 03:07:07 +0000899 DEBUG(dbgs() << "CFLAA: could not extract parent function information.\n");
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000900 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +0000901 }
902
903 if (MaybeFnA.hasValue()) {
904 Fn = *MaybeFnA;
905 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
906 "Interprocedural queries not supported");
907 } else {
908 Fn = *MaybeFnB;
909 }
910
911 assert(Fn != nullptr);
912 auto &MaybeInfo = ensureCached(Fn);
913 assert(MaybeInfo.hasValue());
914
915 auto &Sets = MaybeInfo->Sets;
916 auto MaybeA = Sets.find(ValA);
917 if (!MaybeA.hasValue())
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000918 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +0000919
920 auto MaybeB = Sets.find(ValB);
921 if (!MaybeB.hasValue())
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000922 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +0000923
924 auto SetA = *MaybeA;
925 auto SetB = *MaybeB;
Hal Finkel7529c552014-09-02 21:43:13 +0000926 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
927 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
George Burgess IV33305e72015-02-12 03:07:07 +0000928
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000929 // If both values are local (meaning the corresponding set has attribute
930 // AttrNone or AttrEscaped), then we know that CFLAA fully models them: they
931 // may-alias each other if and only if they are in the same set
932 // If at least one value is non-local (meaning it either is global/argument or
933 // it comes from unknown sources like integer cast), the situation becomes a
934 // bit more interesting. We follow three general rules described below:
935 // - Non-local values may alias each other
936 // - AttrNone values do not alias any non-local values
George Burgess IV652ec4f2016-06-09 23:15:04 +0000937 // - AttrEscaped do not alias globals/arguments, but they may alias
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000938 // AttrUnknown values
939 if (SetA.Index == SetB.Index)
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000940 return MayAlias;
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000941 if (AttrsA.none() || AttrsB.none())
942 return NoAlias;
George Burgess IV652ec4f2016-06-09 23:15:04 +0000943 if (isUnknownAttr(AttrsA) || isUnknownAttr(AttrsB))
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000944 return MayAlias;
945 if (isGlobalOrArgAttr(AttrsA) && isGlobalOrArgAttr(AttrsB))
946 return MayAlias;
947 return NoAlias;
Hal Finkel7529c552014-09-02 21:43:13 +0000948}
Mehdi Amini46a43552015-03-04 18:43:29 +0000949
Chandler Carruthb4faf132016-03-11 10:22:49 +0000950char CFLAA::PassID;
951
Chandler Carruthb47f8012016-03-11 11:05:24 +0000952CFLAAResult CFLAA::run(Function &F, AnalysisManager<Function> &AM) {
George Burgess IV18b83fe2016-06-01 18:39:54 +0000953 return CFLAAResult(AM.getResult<TargetLibraryAnalysis>(F));
Chandler Carruth7b560d42015-09-09 17:55:00 +0000954}
955
Chandler Carruth7b560d42015-09-09 17:55:00 +0000956char CFLAAWrapperPass::ID = 0;
Chandler Carruth12884f72016-03-02 15:56:53 +0000957INITIALIZE_PASS(CFLAAWrapperPass, "cfl-aa", "CFL-Based Alias Analysis", false,
958 true)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000959
960ImmutablePass *llvm::createCFLAAWrapperPass() { return new CFLAAWrapperPass(); }
961
962CFLAAWrapperPass::CFLAAWrapperPass() : ImmutablePass(ID) {
963 initializeCFLAAWrapperPassPass(*PassRegistry::getPassRegistry());
964}
965
George Burgess IV18b83fe2016-06-01 18:39:54 +0000966void CFLAAWrapperPass::initializePass() {
967 auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>();
968 Result.reset(new CFLAAResult(TLIWP.getTLI()));
Chandler Carruth7b560d42015-09-09 17:55:00 +0000969}
970
971void CFLAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
972 AU.setPreservesAll();
George Burgess IV18b83fe2016-06-01 18:39:54 +0000973 AU.addRequired<TargetLibraryInfoWrapperPass>();
Mehdi Amini46a43552015-03-04 18:43:29 +0000974}