blob: ea3894e5fe5842f83135d5f09a75ea3dc53f4376 [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 IV87b2e412016-06-20 23:10:56 +000067/// We use ExternalRelation to describe an externally visible interaction
68/// between parameters/return value of a function.
69/// Both From and To are integer indices that represent a single parameter or
70/// return value. When the index is 0, they represent the return value. Non-zero
71/// index i represents the i-th parameter.
72struct ExternalRelation {
73 unsigned From, To;
74};
Chandler Carruth8b046a42015-08-14 02:42:20 +000075
George Burgess IV87b2e412016-06-20 23:10:56 +000076/// Information we have about a function and would like to keep around.
77class CFLAAResult::FunctionInfo {
78 StratifiedSets<Value *> Sets;
79
80 // RetParamRelations is a collection of ExternalRelations.
81 SmallVector<ExternalRelation, 8> RetParamRelations;
82
83public:
84 FunctionInfo(Function &Fn, const SmallVectorImpl<Value *> &RetVals,
85 StratifiedSets<Value *> S);
86
87 const StratifiedSets<Value *> &getStratifiedSets() const { return Sets; }
88 const SmallVectorImpl<ExternalRelation> &getRetParamRelations() const {
89 return RetParamRelations;
90 }
Chandler Carruth8b046a42015-08-14 02:42:20 +000091};
92
George Burgess IVcae581d2016-04-13 23:27:37 +000093/// Try to go from a Value* to a Function*. Never returns nullptr.
Hal Finkel7529c552014-09-02 21:43:13 +000094static Optional<Function *> parentFunctionOfValue(Value *);
95
George Burgess IVcae581d2016-04-13 23:27:37 +000096/// Returns possible functions called by the Inst* into the given
97/// SmallVectorImpl. Returns true if targets found, false otherwise. This is
98/// templated so we can use it with CallInsts and InvokeInsts.
George Burgess IV24eb0da2016-06-14 18:12:28 +000099static bool getPossibleTargets(CallSite, SmallVectorImpl<Function *> &);
Hal Finkel7529c552014-09-02 21:43:13 +0000100
Hal Finkel1ae325f2014-09-02 23:50:01 +0000101const StratifiedIndex StratifiedLink::SetSentinel =
George Burgess IV11d509d2015-03-15 00:52:21 +0000102 std::numeric_limits<StratifiedIndex>::max();
Hal Finkel1ae325f2014-09-02 23:50:01 +0000103
Hal Finkel7529c552014-09-02 21:43:13 +0000104namespace {
George Burgess IVcae581d2016-04-13 23:27:37 +0000105/// StratifiedInfo Attribute things.
Hal Finkel7529c552014-09-02 21:43:13 +0000106typedef unsigned StratifiedAttr;
Hal Finkel7d7087c2014-09-02 22:13:00 +0000107LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000108LLVM_CONSTEXPR unsigned AttrEscapedIndex = 0;
109LLVM_CONSTEXPR unsigned AttrUnknownIndex = 1;
110LLVM_CONSTEXPR unsigned AttrGlobalIndex = 2;
George Burgess IVb54a8d622015-03-10 02:40:06 +0000111LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 3;
Hal Finkel7d7087c2014-09-02 22:13:00 +0000112LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
113LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
Hal Finkel7529c552014-09-02 21:43:13 +0000114
Hal Finkel7d7087c2014-09-02 22:13:00 +0000115LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000116LLVM_CONSTEXPR StratifiedAttr AttrEscaped = 1 << AttrEscapedIndex;
George Burgess IVb54a8d622015-03-10 02:40:06 +0000117LLVM_CONSTEXPR StratifiedAttr AttrUnknown = 1 << AttrUnknownIndex;
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000118LLVM_CONSTEXPR StratifiedAttr AttrGlobal = 1 << AttrGlobalIndex;
Hal Finkel7529c552014-09-02 21:43:13 +0000119
George Burgess IV87b2e412016-06-20 23:10:56 +0000120/// The maximum number of arguments we can put into a summary.
121LLVM_CONSTEXPR unsigned MaxSupportedArgsInSummary = 50;
122
George Burgess IVcae581d2016-04-13 23:27:37 +0000123/// StratifiedSets call for knowledge of "direction", so this is how we
124/// represent that locally.
Hal Finkel7529c552014-09-02 21:43:13 +0000125enum class Level { Same, Above, Below };
126
George Burgess IVcae581d2016-04-13 23:27:37 +0000127/// Edges can be one of four "weights" -- each weight must have an inverse
128/// weight (Assign has Assign; Reference has Dereference).
Hal Finkel7529c552014-09-02 21:43:13 +0000129enum class EdgeType {
George Burgess IVcae581d2016-04-13 23:27:37 +0000130 /// The weight assigned when assigning from or to a value. For example, in:
131 /// %b = getelementptr %a, 0
132 /// ...The relationships are %b assign %a, and %a assign %b. This used to be
133 /// two edges, but having a distinction bought us nothing.
Hal Finkel7529c552014-09-02 21:43:13 +0000134 Assign,
135
George Burgess IVcae581d2016-04-13 23:27:37 +0000136 /// The edge used when we have an edge going from some handle to a Value.
137 /// Examples of this include:
138 /// %b = load %a (%b Dereference %a)
139 /// %b = extractelement %a, 0 (%a Dereference %b)
Hal Finkel7529c552014-09-02 21:43:13 +0000140 Dereference,
141
George Burgess IVcae581d2016-04-13 23:27:37 +0000142 /// The edge used when our edge goes from a value to a handle that may have
143 /// contained it at some point. Examples:
144 /// %b = load %a (%a Reference %b)
145 /// %b = extractelement %a, 0 (%b Reference %a)
Hal Finkel7529c552014-09-02 21:43:13 +0000146 Reference
147};
148
George Burgess IV24eb0da2016-06-14 18:12:28 +0000149/// The Program Expression Graph (PEG) of CFL analysis
150class CFLGraph {
151 typedef Value *Node;
Hal Finkel7529c552014-09-02 21:43:13 +0000152
George Burgess IV24eb0da2016-06-14 18:12:28 +0000153 struct Edge {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000154 EdgeType Type;
155 Node Other;
156 };
Hal Finkel7529c552014-09-02 21:43:13 +0000157
George Burgess IV24eb0da2016-06-14 18:12:28 +0000158 typedef std::vector<Edge> EdgeList;
George Burgess IV259d9012016-06-15 20:43:41 +0000159
160 struct NodeInfo {
161 EdgeList Edges;
162 StratifiedAttrs Attr;
163 };
164
165 typedef DenseMap<Node, NodeInfo> NodeMap;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000166 NodeMap NodeImpls;
Hal Finkel7529c552014-09-02 21:43:13 +0000167
George Burgess IV24eb0da2016-06-14 18:12:28 +0000168 // Gets the inverse of a given EdgeType.
169 static EdgeType flipWeight(EdgeType Initial) {
170 switch (Initial) {
171 case EdgeType::Assign:
172 return EdgeType::Assign;
173 case EdgeType::Dereference:
174 return EdgeType::Reference;
175 case EdgeType::Reference:
176 return EdgeType::Dereference;
177 }
178 llvm_unreachable("Incomplete coverage of EdgeType enum");
179 }
Hal Finkel7529c552014-09-02 21:43:13 +0000180
George Burgess IV259d9012016-06-15 20:43:41 +0000181 const NodeInfo *getNode(Node N) const {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000182 auto Itr = NodeImpls.find(N);
183 if (Itr == NodeImpls.end())
184 return nullptr;
185 return &Itr->second;
186 }
George Burgess IV259d9012016-06-15 20:43:41 +0000187 NodeInfo *getNode(Node N) {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000188 auto Itr = NodeImpls.find(N);
189 if (Itr == NodeImpls.end())
190 return nullptr;
191 return &Itr->second;
192 }
193
194 static Node nodeDeref(const NodeMap::value_type &P) { return P.first; }
195 typedef std::pointer_to_unary_function<const NodeMap::value_type &, Node>
196 NodeDerefFun;
197
198public:
199 typedef EdgeList::const_iterator const_edge_iterator;
200 typedef mapped_iterator<NodeMap::const_iterator, NodeDerefFun>
201 const_node_iterator;
202
203 bool addNode(Node N) {
George Burgess IV259d9012016-06-15 20:43:41 +0000204 return NodeImpls.insert(std::make_pair(N, NodeInfo{EdgeList(), AttrNone}))
205 .second;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000206 }
207
George Burgess IV259d9012016-06-15 20:43:41 +0000208 void addAttr(Node N, StratifiedAttrs Attr) {
209 auto *Info = getNode(N);
210 assert(Info != nullptr);
211 Info->Attr |= Attr;
212 }
George Burgess IV24eb0da2016-06-14 18:12:28 +0000213
George Burgess IV259d9012016-06-15 20:43:41 +0000214 void addEdge(Node From, Node To, EdgeType Type) {
215 auto *FromInfo = getNode(From);
216 assert(FromInfo != nullptr);
217 auto *ToInfo = getNode(To);
218 assert(ToInfo != nullptr);
219
220 FromInfo->Edges.push_back(Edge{Type, To});
221 ToInfo->Edges.push_back(Edge{flipWeight(Type), From});
222 }
223
224 StratifiedAttrs attrFor(Node N) const {
225 auto *Info = getNode(N);
226 assert(Info != nullptr);
227 return Info->Attr;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000228 }
229
230 iterator_range<const_edge_iterator> edgesFor(Node N) const {
George Burgess IV259d9012016-06-15 20:43:41 +0000231 auto *Info = getNode(N);
232 assert(Info != nullptr);
233 auto &Edges = Info->Edges;
234 return make_range(Edges.begin(), Edges.end());
George Burgess IV24eb0da2016-06-14 18:12:28 +0000235 }
236
237 iterator_range<const_node_iterator> nodes() const {
238 return make_range<const_node_iterator>(
239 map_iterator(NodeImpls.begin(), NodeDerefFun(nodeDeref)),
240 map_iterator(NodeImpls.end(), NodeDerefFun(nodeDeref)));
241 }
242
243 bool empty() const { return NodeImpls.empty(); }
244 std::size_t size() const { return NodeImpls.size(); }
Hal Finkel7529c552014-09-02 21:43:13 +0000245};
246
George Burgess IVcae581d2016-04-13 23:27:37 +0000247/// Gets the edges our graph should have, based on an Instruction*
Hal Finkel7529c552014-09-02 21:43:13 +0000248class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
Chandler Carruth7b560d42015-09-09 17:55:00 +0000249 CFLAAResult &AA;
George Burgess IV18b83fe2016-06-01 18:39:54 +0000250 const TargetLibraryInfo &TLI;
Hal Finkel7529c552014-09-02 21:43:13 +0000251
George Burgess IV24eb0da2016-06-14 18:12:28 +0000252 CFLGraph &Graph;
253 SmallPtrSetImpl<Value *> &Externals;
254 SmallPtrSetImpl<Value *> &Escapes;
255
256 static bool hasUsefulEdges(ConstantExpr *CE) {
257 // ConstantExpr doesn't have terminators, invokes, or fences, so only needs
258 // to check for compares.
259 return CE->getOpcode() != Instruction::ICmp &&
260 CE->getOpcode() != Instruction::FCmp;
261 }
262
263 void addNode(Value *Val) {
264 if (!Graph.addNode(Val))
265 return;
266
267 if (isa<GlobalValue>(Val))
268 Externals.insert(Val);
269 else if (auto CExpr = dyn_cast<ConstantExpr>(Val))
270 if (hasUsefulEdges(CExpr))
271 visitConstantExpr(CExpr);
272 }
273
George Burgess IV259d9012016-06-15 20:43:41 +0000274 void addNodeWithAttr(Value *Val, StratifiedAttrs Attr) {
275 addNode(Val);
276 Graph.addAttr(Val, Attr);
277 }
278
279 void addEdge(Value *From, Value *To, EdgeType Type) {
280 if (!From->getType()->isPointerTy() || !To->getType()->isPointerTy())
281 return;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000282 addNode(From);
283 if (To != From)
284 addNode(To);
George Burgess IV259d9012016-06-15 20:43:41 +0000285 Graph.addEdge(From, To, Type);
George Burgess IV24eb0da2016-06-14 18:12:28 +0000286 }
287
Hal Finkel7529c552014-09-02 21:43:13 +0000288public:
George Burgess IV24eb0da2016-06-14 18:12:28 +0000289 GetEdgesVisitor(CFLAAResult &AA, const TargetLibraryInfo &TLI,
290 CFLGraph &Graph, SmallPtrSetImpl<Value *> &Externals,
291 SmallPtrSetImpl<Value *> &Escapes)
292 : AA(AA), TLI(TLI), Graph(Graph), Externals(Externals), Escapes(Escapes) {
293 }
Hal Finkel7529c552014-09-02 21:43:13 +0000294
295 void visitInstruction(Instruction &) {
296 llvm_unreachable("Unsupported instruction encountered");
297 }
298
George Burgess IVb54a8d622015-03-10 02:40:06 +0000299 void visitPtrToIntInst(PtrToIntInst &Inst) {
300 auto *Ptr = Inst.getOperand(0);
George Burgess IV259d9012016-06-15 20:43:41 +0000301 addNodeWithAttr(Ptr, AttrEscaped);
George Burgess IVb54a8d622015-03-10 02:40:06 +0000302 }
303
304 void visitIntToPtrInst(IntToPtrInst &Inst) {
305 auto *Ptr = &Inst;
George Burgess IV259d9012016-06-15 20:43:41 +0000306 addNodeWithAttr(Ptr, AttrUnknown);
George Burgess IVb54a8d622015-03-10 02:40:06 +0000307 }
308
Hal Finkel7529c552014-09-02 21:43:13 +0000309 void visitCastInst(CastInst &Inst) {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000310 auto *Src = Inst.getOperand(0);
George Burgess IV259d9012016-06-15 20:43:41 +0000311 addEdge(Src, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000312 }
313
314 void visitBinaryOperator(BinaryOperator &Inst) {
315 auto *Op1 = Inst.getOperand(0);
316 auto *Op2 = Inst.getOperand(1);
George Burgess IV259d9012016-06-15 20:43:41 +0000317 addEdge(Op1, &Inst, EdgeType::Assign);
318 addEdge(Op2, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000319 }
320
321 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
322 auto *Ptr = Inst.getPointerOperand();
323 auto *Val = Inst.getNewValOperand();
George Burgess IV259d9012016-06-15 20:43:41 +0000324 addEdge(Ptr, Val, EdgeType::Dereference);
Hal Finkel7529c552014-09-02 21:43:13 +0000325 }
326
327 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
328 auto *Ptr = Inst.getPointerOperand();
329 auto *Val = Inst.getValOperand();
George Burgess IV259d9012016-06-15 20:43:41 +0000330 addEdge(Ptr, Val, EdgeType::Dereference);
Hal Finkel7529c552014-09-02 21:43:13 +0000331 }
332
333 void visitPHINode(PHINode &Inst) {
George Burgess IV77351ba32016-01-28 00:54:01 +0000334 for (Value *Val : Inst.incoming_values())
George Burgess IV259d9012016-06-15 20:43:41 +0000335 addEdge(Val, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000336 }
337
338 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
339 auto *Op = Inst.getPointerOperand();
George Burgess IV259d9012016-06-15 20:43:41 +0000340 addEdge(Op, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000341 }
342
343 void visitSelectInst(SelectInst &Inst) {
Daniel Berlin16f7a522015-01-26 17:31:17 +0000344 // Condition is not processed here (The actual statement producing
345 // the condition result is processed elsewhere). For select, the
346 // condition is evaluated, but not loaded, stored, or assigned
347 // simply as a result of being the condition of a select.
348
Hal Finkel7529c552014-09-02 21:43:13 +0000349 auto *TrueVal = Inst.getTrueValue();
Hal Finkel7529c552014-09-02 21:43:13 +0000350 auto *FalseVal = Inst.getFalseValue();
George Burgess IV259d9012016-06-15 20:43:41 +0000351 addEdge(TrueVal, &Inst, EdgeType::Assign);
352 addEdge(FalseVal, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000353 }
354
George Burgess IV24eb0da2016-06-14 18:12:28 +0000355 void visitAllocaInst(AllocaInst &Inst) { Graph.addNode(&Inst); }
Hal Finkel7529c552014-09-02 21:43:13 +0000356
357 void visitLoadInst(LoadInst &Inst) {
358 auto *Ptr = Inst.getPointerOperand();
359 auto *Val = &Inst;
George Burgess IV259d9012016-06-15 20:43:41 +0000360 addEdge(Val, Ptr, EdgeType::Reference);
Hal Finkel7529c552014-09-02 21:43:13 +0000361 }
362
363 void visitStoreInst(StoreInst &Inst) {
364 auto *Ptr = Inst.getPointerOperand();
365 auto *Val = Inst.getValueOperand();
George Burgess IV259d9012016-06-15 20:43:41 +0000366 addEdge(Ptr, Val, EdgeType::Dereference);
Hal Finkel7529c552014-09-02 21:43:13 +0000367 }
368
Hal Finkeldb5f86a2014-10-14 20:51:26 +0000369 void visitVAArgInst(VAArgInst &Inst) {
370 // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
371 // two things:
372 // 1. Loads a value from *((T*)*Ptr).
373 // 2. Increments (stores to) *Ptr by some target-specific amount.
374 // For now, we'll handle this like a landingpad instruction (by placing the
375 // result in its own group, and having that group alias externals).
George Burgess IV259d9012016-06-15 20:43:41 +0000376 addNodeWithAttr(&Inst, AttrUnknown);
Hal Finkeldb5f86a2014-10-14 20:51:26 +0000377 }
378
Hal Finkel7529c552014-09-02 21:43:13 +0000379 static bool isFunctionExternal(Function *Fn) {
380 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
381 }
382
George Burgess IV87b2e412016-06-20 23:10:56 +0000383 bool tryInterproceduralAnalysis(CallSite CS,
384 const SmallVectorImpl<Function *> &Fns) {
Hal Finkel7529c552014-09-02 21:43:13 +0000385 assert(Fns.size() > 0);
386
George Burgess IV87b2e412016-06-20 23:10:56 +0000387 if (CS.arg_size() > MaxSupportedArgsInSummary)
Hal Finkel7529c552014-09-02 21:43:13 +0000388 return false;
389
390 // Exit early if we'll fail anyway
391 for (auto *Fn : Fns) {
392 if (isFunctionExternal(Fn) || Fn->isVarArg())
393 return false;
George Burgess IV87b2e412016-06-20 23:10:56 +0000394 // Fail if the caller does not provide enough arguments
395 assert(Fn->arg_size() <= CS.arg_size());
Hal Finkel7529c552014-09-02 21:43:13 +0000396 auto &MaybeInfo = AA.ensureCached(Fn);
397 if (!MaybeInfo.hasValue())
398 return false;
399 }
400
Hal Finkel7529c552014-09-02 21:43:13 +0000401 for (auto *Fn : Fns) {
George Burgess IV87b2e412016-06-20 23:10:56 +0000402 auto &FnInfo = AA.ensureCached(Fn);
403 assert(FnInfo.hasValue());
Hal Finkel7529c552014-09-02 21:43:13 +0000404
George Burgess IV87b2e412016-06-20 23:10:56 +0000405 auto &RetParamRelations = FnInfo->getRetParamRelations();
406 for (auto &Relation : RetParamRelations) {
407 auto FromIndex = Relation.From;
408 auto ToIndex = Relation.To;
409 auto FromVal = (FromIndex == 0) ? CS.getInstruction()
410 : CS.getArgument(FromIndex - 1);
411 auto ToVal =
412 (ToIndex == 0) ? CS.getInstruction() : CS.getArgument(ToIndex - 1);
413 if (FromVal->getType()->isPointerTy() &&
414 ToVal->getType()->isPointerTy())
415 // Actual arguments must be defined before they are used at callsite.
416 // Therefore by the time we reach here, FromVal and ToVal should
417 // already exist in the graph. We can go ahead and add them directly.
418 Graph.addEdge(FromVal, ToVal, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000419 }
George Burgess IV259d9012016-06-15 20:43:41 +0000420 }
George Burgess IV24eb0da2016-06-14 18:12:28 +0000421
Hal Finkel7529c552014-09-02 21:43:13 +0000422 return true;
423 }
424
George Burgess IV24eb0da2016-06-14 18:12:28 +0000425 void visitCallSite(CallSite CS) {
426 auto Inst = CS.getInstruction();
427
428 // Make sure all arguments and return value are added to the graph first
429 for (Value *V : CS.args())
430 addNode(V);
George Burgess IV87b2e412016-06-20 23:10:56 +0000431 if (Inst->getType()->isPointerTy())
George Burgess IV24eb0da2016-06-14 18:12:28 +0000432 addNode(Inst);
433
George Burgess IV18b83fe2016-06-01 18:39:54 +0000434 // Check if Inst is a call to a library function that allocates/deallocates
435 // on the heap. Those kinds of functions do not introduce any aliases.
436 // TODO: address other common library functions such as realloc(), strdup(),
437 // etc.
George Burgess IV24eb0da2016-06-14 18:12:28 +0000438 if (isMallocLikeFn(Inst, &TLI) || isCallocLikeFn(Inst, &TLI) ||
439 isFreeCall(Inst, &TLI))
George Burgess IV18b83fe2016-06-01 18:39:54 +0000440 return;
George Burgess IV18b83fe2016-06-01 18:39:54 +0000441
George Burgess IV68b36e02015-08-28 00:16:18 +0000442 // TODO: Add support for noalias args/all the other fun function attributes
443 // that we can tack on.
Hal Finkel7529c552014-09-02 21:43:13 +0000444 SmallVector<Function *, 4> Targets;
George Burgess IV24eb0da2016-06-14 18:12:28 +0000445 if (getPossibleTargets(CS, Targets))
George Burgess IV87b2e412016-06-20 23:10:56 +0000446 if (tryInterproceduralAnalysis(CS, Targets))
Hal Finkel7529c552014-09-02 21:43:13 +0000447 return;
Hal Finkel7529c552014-09-02 21:43:13 +0000448
George Burgess IV68b36e02015-08-28 00:16:18 +0000449 // Because the function is opaque, we need to note that anything
George Burgess IV24eb0da2016-06-14 18:12:28 +0000450 // could have happened to the arguments (unless the function is marked
451 // readonly or readnone), and that the result could alias just about
452 // anything, too (unless the result is marked noalias).
453 if (!CS.onlyReadsMemory())
454 for (Value *V : CS.args()) {
George Burgess IV259d9012016-06-15 20:43:41 +0000455 if (V->getType()->isPointerTy())
456 Escapes.insert(V);
George Burgess IV24eb0da2016-06-14 18:12:28 +0000457 }
458
George Burgess IV87b2e412016-06-20 23:10:56 +0000459 if (Inst->getType()->isPointerTy()) {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000460 auto *Fn = CS.getCalledFunction();
461 if (Fn == nullptr || !Fn->doesNotAlias(0))
George Burgess IV259d9012016-06-15 20:43:41 +0000462 Graph.addAttr(Inst, AttrUnknown);
George Burgess IV24eb0da2016-06-14 18:12:28 +0000463 }
Hal Finkel7529c552014-09-02 21:43:13 +0000464 }
465
George Burgess IVcae581d2016-04-13 23:27:37 +0000466 /// Because vectors/aggregates are immutable and unaddressable, there's
467 /// nothing we can do to coax a value out of them, other than calling
468 /// Extract{Element,Value}. We can effectively treat them as pointers to
469 /// arbitrary memory locations we can store in and load from.
Hal Finkel7529c552014-09-02 21:43:13 +0000470 void visitExtractElementInst(ExtractElementInst &Inst) {
471 auto *Ptr = Inst.getVectorOperand();
472 auto *Val = &Inst;
George Burgess IV259d9012016-06-15 20:43:41 +0000473 addEdge(Val, Ptr, EdgeType::Reference);
Hal Finkel7529c552014-09-02 21:43:13 +0000474 }
475
476 void visitInsertElementInst(InsertElementInst &Inst) {
477 auto *Vec = Inst.getOperand(0);
478 auto *Val = Inst.getOperand(1);
George Burgess IV259d9012016-06-15 20:43:41 +0000479 addEdge(Vec, &Inst, EdgeType::Assign);
480 addEdge(&Inst, Val, EdgeType::Dereference);
Hal Finkel7529c552014-09-02 21:43:13 +0000481 }
482
483 void visitLandingPadInst(LandingPadInst &Inst) {
484 // Exceptions come from "nowhere", from our analysis' perspective.
485 // So we place the instruction its own group, noting that said group may
486 // alias externals
George Burgess IV259d9012016-06-15 20:43:41 +0000487 addNodeWithAttr(&Inst, AttrUnknown);
Hal Finkel7529c552014-09-02 21:43:13 +0000488 }
489
490 void visitInsertValueInst(InsertValueInst &Inst) {
491 auto *Agg = Inst.getOperand(0);
492 auto *Val = Inst.getOperand(1);
George Burgess IV259d9012016-06-15 20:43:41 +0000493 addEdge(Agg, &Inst, EdgeType::Assign);
494 addEdge(&Inst, Val, EdgeType::Dereference);
Hal Finkel7529c552014-09-02 21:43:13 +0000495 }
496
497 void visitExtractValueInst(ExtractValueInst &Inst) {
498 auto *Ptr = Inst.getAggregateOperand();
George Burgess IV259d9012016-06-15 20:43:41 +0000499 addEdge(&Inst, Ptr, EdgeType::Reference);
Hal Finkel7529c552014-09-02 21:43:13 +0000500 }
501
502 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
503 auto *From1 = Inst.getOperand(0);
504 auto *From2 = Inst.getOperand(1);
George Burgess IV259d9012016-06-15 20:43:41 +0000505 addEdge(From1, &Inst, EdgeType::Assign);
506 addEdge(From2, &Inst, EdgeType::Assign);
Hal Finkel7529c552014-09-02 21:43:13 +0000507 }
Pete Cooper36642532015-06-12 16:13:54 +0000508
509 void visitConstantExpr(ConstantExpr *CE) {
510 switch (CE->getOpcode()) {
511 default:
512 llvm_unreachable("Unknown instruction type encountered!");
513// Build the switch statement using the Instruction.def file.
514#define HANDLE_INST(NUM, OPCODE, CLASS) \
515 case Instruction::OPCODE: \
516 visit##OPCODE(*(CLASS *)CE); \
517 break;
518#include "llvm/IR/Instruction.def"
519 }
520 }
Hal Finkel7529c552014-09-02 21:43:13 +0000521};
522
George Burgess IVe17756e2016-06-14 18:02:27 +0000523class CFLGraphBuilder {
524 // Input of the builder
525 CFLAAResult &Analysis;
526 const TargetLibraryInfo &TLI;
527
528 // Output of the builder
529 CFLGraph Graph;
530 SmallVector<Value *, 4> ReturnedValues;
531
532 // Auxiliary structures used by the builder
George Burgess IV24eb0da2016-06-14 18:12:28 +0000533 SmallPtrSet<Value *, 8> ExternalValues;
534 SmallPtrSet<Value *, 8> EscapedValues;
George Burgess IVe17756e2016-06-14 18:02:27 +0000535
536 // Helper functions
537
538 // Determines whether or not we an instruction is useless to us (e.g.
539 // FenceInst)
540 static bool hasUsefulEdges(Instruction *Inst) {
541 bool IsNonInvokeTerminator =
542 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
543 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) &&
544 !IsNonInvokeTerminator;
545 }
546
George Burgess IV24eb0da2016-06-14 18:12:28 +0000547 void addArgumentToGraph(Argument &Arg) {
George Burgess IV259d9012016-06-15 20:43:41 +0000548 if (Arg.getType()->isPointerTy()) {
549 Graph.addNode(&Arg);
550 ExternalValues.insert(&Arg);
551 }
George Burgess IVe17756e2016-06-14 18:02:27 +0000552 }
553
554 // Given an Instruction, this will add it to the graph, along with any
555 // Instructions that are potentially only available from said Instruction
556 // For example, given the following line:
557 // %0 = load i16* getelementptr ([1 x i16]* @a, 0, 0), align 2
558 // addInstructionToGraph would add both the `load` and `getelementptr`
559 // instructions to the graph appropriately.
560 void addInstructionToGraph(Instruction &Inst) {
561 // We don't want the edges of most "return" instructions, but we *do* want
562 // to know what can be returned.
George Burgess IV87b2e412016-06-20 23:10:56 +0000563 if (auto RetInst = dyn_cast<ReturnInst>(&Inst))
564 if (auto RetVal = RetInst->getReturnValue())
565 if (RetVal->getType()->isPointerTy())
566 ReturnedValues.push_back(RetVal);
George Burgess IVe17756e2016-06-14 18:02:27 +0000567
568 if (!hasUsefulEdges(&Inst))
569 return;
570
George Burgess IV24eb0da2016-06-14 18:12:28 +0000571 GetEdgesVisitor(Analysis, TLI, Graph, ExternalValues, EscapedValues)
572 .visit(Inst);
573 }
George Burgess IVe17756e2016-06-14 18:02:27 +0000574
George Burgess IV24eb0da2016-06-14 18:12:28 +0000575 // Builds the graph needed for constructing the StratifiedSets for the given
576 // function
577 void buildGraphFrom(Function &Fn) {
578 for (auto &Bb : Fn.getBasicBlockList())
579 for (auto &Inst : Bb.getInstList())
580 addInstructionToGraph(Inst);
George Burgess IVe17756e2016-06-14 18:02:27 +0000581
George Burgess IV24eb0da2016-06-14 18:12:28 +0000582 for (auto &Arg : Fn.args())
583 addArgumentToGraph(Arg);
George Burgess IVe17756e2016-06-14 18:02:27 +0000584 }
585
586public:
587 CFLGraphBuilder(CFLAAResult &Analysis, const TargetLibraryInfo &TLI,
588 Function &Fn)
589 : Analysis(Analysis), TLI(TLI) {
590 buildGraphFrom(Fn);
591 }
592
George Burgess IV87b2e412016-06-20 23:10:56 +0000593 const CFLGraph &getCFLGraph() const { return Graph; }
594 const SmallVector<Value *, 4> &getReturnValues() const {
595 return ReturnedValues;
George Burgess IVe17756e2016-06-14 18:02:27 +0000596 }
George Burgess IV87b2e412016-06-20 23:10:56 +0000597 const SmallPtrSet<Value *, 8> &getExternalValues() const {
598 return ExternalValues;
599 }
600 const SmallPtrSet<Value *, 8> &getEscapedValues() const {
601 return EscapedValues;
602 }
George Burgess IVe17756e2016-06-14 18:02:27 +0000603};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000604}
Hal Finkel7529c552014-09-02 21:43:13 +0000605
Hal Finkel7529c552014-09-02 21:43:13 +0000606//===----------------------------------------------------------------------===//
607// Function declarations that require types defined in the namespace above
608//===----------------------------------------------------------------------===//
609
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000610/// Given a StratifiedAttrs, returns true if it marks the corresponding values
611/// as globals or arguments
612static bool isGlobalOrArgAttr(StratifiedAttrs Attr);
Hal Finkel7529c552014-09-02 21:43:13 +0000613
George Burgess IV652ec4f2016-06-09 23:15:04 +0000614/// Given a StratifiedAttrs, returns true if the corresponding values come from
615/// an unknown source (such as opaque memory or an integer cast)
616static bool isUnknownAttr(StratifiedAttrs Attr);
617
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000618/// Given an argument number, returns the appropriate StratifiedAttr to set.
619static StratifiedAttr argNumberToAttr(unsigned ArgNum);
620
621/// Given a Value, potentially return which StratifiedAttr it maps to.
622static Optional<StratifiedAttr> valueToAttr(Value *Val);
Hal Finkel7529c552014-09-02 21:43:13 +0000623
George Burgess IVcae581d2016-04-13 23:27:37 +0000624/// Gets the "Level" that one should travel in StratifiedSets
625/// given an EdgeType.
Hal Finkel7529c552014-09-02 21:43:13 +0000626static Level directionOfEdgeType(EdgeType);
627
George Burgess IVcae581d2016-04-13 23:27:37 +0000628/// Determines whether it would be pointless to add the given Value to our sets.
George Burgess IVab03af22015-03-10 02:58:15 +0000629static bool canSkipAddingToSets(Value *Val);
630
Hal Finkel7529c552014-09-02 21:43:13 +0000631static Optional<Function *> parentFunctionOfValue(Value *Val) {
632 if (auto *Inst = dyn_cast<Instruction>(Val)) {
633 auto *Bb = Inst->getParent();
634 return Bb->getParent();
635 }
636
637 if (auto *Arg = dyn_cast<Argument>(Val))
638 return Arg->getParent();
George Burgess IV77351ba32016-01-28 00:54:01 +0000639 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000640}
641
George Burgess IV24eb0da2016-06-14 18:12:28 +0000642static bool getPossibleTargets(CallSite CS,
Hal Finkel7529c552014-09-02 21:43:13 +0000643 SmallVectorImpl<Function *> &Output) {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000644 if (auto *Fn = CS.getCalledFunction()) {
Hal Finkel7529c552014-09-02 21:43:13 +0000645 Output.push_back(Fn);
646 return true;
647 }
648
649 // TODO: If the call is indirect, we might be able to enumerate all potential
650 // targets of the call and return them, rather than just failing.
651 return false;
652}
653
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000654static bool isGlobalOrArgAttr(StratifiedAttrs Attr) {
655 return Attr.reset(AttrEscapedIndex).reset(AttrUnknownIndex).any();
656}
657
George Burgess IV652ec4f2016-06-09 23:15:04 +0000658static bool isUnknownAttr(StratifiedAttrs Attr) {
659 return Attr.test(AttrUnknownIndex);
660}
661
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000662static Optional<StratifiedAttr> valueToAttr(Value *Val) {
Hal Finkel7529c552014-09-02 21:43:13 +0000663 if (isa<GlobalValue>(Val))
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000664 return AttrGlobal;
Hal Finkel7529c552014-09-02 21:43:13 +0000665
666 if (auto *Arg = dyn_cast<Argument>(Val))
Daniel Berlin16f7a522015-01-26 17:31:17 +0000667 // Only pointer arguments should have the argument attribute,
668 // because things can't escape through scalars without us seeing a
669 // cast, and thus, interaction with them doesn't matter.
670 if (!Arg->hasNoAliasAttr() && Arg->getType()->isPointerTy())
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000671 return argNumberToAttr(Arg->getArgNo());
George Burgess IV77351ba32016-01-28 00:54:01 +0000672 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000673}
674
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000675static StratifiedAttr argNumberToAttr(unsigned ArgNum) {
George Burgess IV3c898c22015-01-21 16:37:21 +0000676 if (ArgNum >= AttrMaxNumArgs)
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000677 return AttrUnknown;
678 return 1 << (ArgNum + AttrFirstArgIndex);
Hal Finkel7529c552014-09-02 21:43:13 +0000679}
680
Hal Finkel7529c552014-09-02 21:43:13 +0000681static Level directionOfEdgeType(EdgeType Weight) {
682 switch (Weight) {
683 case EdgeType::Reference:
684 return Level::Above;
685 case EdgeType::Dereference:
686 return Level::Below;
687 case EdgeType::Assign:
688 return Level::Same;
689 }
690 llvm_unreachable("Incomplete switch coverage");
691}
692
George Burgess IVab03af22015-03-10 02:58:15 +0000693static bool canSkipAddingToSets(Value *Val) {
694 // Constants can share instances, which may falsely unify multiple
695 // sets, e.g. in
696 // store i32* null, i32** %ptr1
697 // store i32* null, i32** %ptr2
698 // clearly ptr1 and ptr2 should not be unified into the same set, so
699 // we should filter out the (potentially shared) instance to
700 // i32* null.
701 if (isa<Constant>(Val)) {
George Burgess IVab03af22015-03-10 02:58:15 +0000702 // TODO: Because all of these things are constant, we can determine whether
703 // the data is *actually* mutable at graph building time. This will probably
704 // come for free/cheap with offset awareness.
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +0000705 bool CanStoreMutableData = isa<GlobalValue>(Val) ||
706 isa<ConstantExpr>(Val) ||
707 isa<ConstantAggregate>(Val);
George Burgess IVab03af22015-03-10 02:58:15 +0000708 return !CanStoreMutableData;
709 }
710
711 return false;
Hal Finkel7529c552014-09-02 21:43:13 +0000712}
713
George Burgess IV87b2e412016-06-20 23:10:56 +0000714/// Gets whether the sets at Index1 above, below, or equal to the sets at
715/// Index2. Returns None if they are not in the same set chain.
716static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
717 StratifiedIndex Index1,
718 StratifiedIndex Index2) {
719 if (Index1 == Index2)
720 return Level::Same;
721
722 const auto *Current = &Sets.getLink(Index1);
723 while (Current->hasBelow()) {
724 if (Current->Below == Index2)
725 return Level::Below;
726 Current = &Sets.getLink(Current->Below);
727 }
728
729 Current = &Sets.getLink(Index1);
730 while (Current->hasAbove()) {
731 if (Current->Above == Index2)
732 return Level::Above;
733 Current = &Sets.getLink(Current->Above);
734 }
735
736 return None;
737}
738
739CFLAAResult::FunctionInfo::FunctionInfo(Function &Fn,
740 const SmallVectorImpl<Value *> &RetVals,
741 StratifiedSets<Value *> S)
742 : Sets(std::move(S)) {
743 LLVM_CONSTEXPR unsigned ExpectedMaxArgs = 8;
744
745 // Collect StratifiedInfo for each parameter
746 SmallVector<Optional<StratifiedInfo>, ExpectedMaxArgs> ParamInfos;
747 for (auto &Param : Fn.args()) {
748 if (Param.getType()->isPointerTy())
749 ParamInfos.push_back(Sets.find(&Param));
750 else
751 ParamInfos.push_back(None);
752 }
753 // Collect StratifiedInfo for each return value
754 SmallVector<Optional<StratifiedInfo>, 4> RetInfos;
755 RetInfos.reserve(RetVals.size());
756 for (unsigned I = 0, E = RetVals.size(); I != E; ++I)
757 RetInfos.push_back(Sets.find(RetVals[I]));
758
759 // This summary generation algorithm is n^2. An arbitrary upper-bound of 50
760 // args was selected, so it doesn't take too long in insane cases.
761 if (Fn.arg_size() <= MaxSupportedArgsInSummary) {
762 for (unsigned I = 0, E = ParamInfos.size(); I != E; ++I) {
763 auto &MainInfo = ParamInfos[I];
764 if (!MainInfo)
765 continue;
766
767 // Adding edges between arguments for arguments that may end up aliasing
768 // each other. This is necessary for functions such as
769 // void foo(int** a, int** b) { *a = *b; }
770 // (Technically, the proper sets for this would be those below
771 // Arguments[I] and Arguments[X], but our algorithm will produce
772 // extremely similar, and equally correct, results either way)
773 for (unsigned X = I + 1; X != E; ++X) {
774 auto &SubInfo = ParamInfos[X];
775 if (!SubInfo)
776 continue;
777
778 auto MaybeRelation =
779 getIndexRelation(Sets, MainInfo->Index, SubInfo->Index);
780 if (!MaybeRelation.hasValue())
781 continue;
782
783 RetParamRelations.push_back(ExternalRelation{1 + I, 1 + X});
784 }
785
786 // Adding an edge from argument -> return value for each parameter that
787 // may alias the return value
788 for (unsigned X = 0, XE = RetInfos.size(); X != XE; ++X) {
789 auto &RetInfo = RetInfos[X];
790 if (!RetInfo)
791 continue;
792
793 auto MaybeRelation =
794 getIndexRelation(Sets, MainInfo->Index, RetInfo->Index);
795 if (!MaybeRelation.hasValue())
796 continue;
797
798 RetParamRelations.push_back(ExternalRelation{1 + I, 0});
799 }
800 }
801 }
802}
803
Chandler Carruth8b046a42015-08-14 02:42:20 +0000804// Builds the graph + StratifiedSets for a function.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000805CFLAAResult::FunctionInfo CFLAAResult::buildSetsFrom(Function *Fn) {
George Burgess IVe17756e2016-06-14 18:02:27 +0000806 CFLGraphBuilder GraphBuilder(*this, TLI, *Fn);
807 StratifiedSetsBuilder<Value *> SetBuilder;
Hal Finkel7529c552014-09-02 21:43:13 +0000808
George Burgess IVe17756e2016-06-14 18:02:27 +0000809 auto &Graph = GraphBuilder.getCFLGraph();
George Burgess IVdc96feb2016-06-13 19:21:18 +0000810 SmallVector<Value *, 16> Worklist;
George Burgess IVdc96feb2016-06-13 19:21:18 +0000811 for (auto Node : Graph.nodes())
812 Worklist.push_back(Node);
813
814 while (!Worklist.empty()) {
815 auto *CurValue = Worklist.pop_back_val();
George Burgess IVe17756e2016-06-14 18:02:27 +0000816 SetBuilder.add(CurValue);
George Burgess IVdc96feb2016-06-13 19:21:18 +0000817 if (canSkipAddingToSets(CurValue))
818 continue;
819
George Burgess IV259d9012016-06-15 20:43:41 +0000820 auto Attr = Graph.attrFor(CurValue);
821 SetBuilder.noteAttributes(CurValue, Attr);
822
George Burgess IVdc96feb2016-06-13 19:21:18 +0000823 for (const auto &Edge : Graph.edgesFor(CurValue)) {
824 auto Label = Edge.Type;
825 auto *OtherValue = Edge.Other;
826
827 if (canSkipAddingToSets(OtherValue))
Hal Finkel7529c552014-09-02 21:43:13 +0000828 continue;
829
George Burgess IVdc96feb2016-06-13 19:21:18 +0000830 bool Added;
831 switch (directionOfEdgeType(Label)) {
832 case Level::Above:
George Burgess IVe17756e2016-06-14 18:02:27 +0000833 Added = SetBuilder.addAbove(CurValue, OtherValue);
George Burgess IVdc96feb2016-06-13 19:21:18 +0000834 break;
835 case Level::Below:
George Burgess IVe17756e2016-06-14 18:02:27 +0000836 Added = SetBuilder.addBelow(CurValue, OtherValue);
George Burgess IVdc96feb2016-06-13 19:21:18 +0000837 break;
838 case Level::Same:
George Burgess IVe17756e2016-06-14 18:02:27 +0000839 Added = SetBuilder.addWith(CurValue, OtherValue);
George Burgess IVdc96feb2016-06-13 19:21:18 +0000840 break;
Hal Finkel7529c552014-09-02 21:43:13 +0000841 }
George Burgess IVdc96feb2016-06-13 19:21:18 +0000842
George Burgess IVdc96feb2016-06-13 19:21:18 +0000843 if (Added)
844 Worklist.push_back(OtherValue);
Hal Finkel7529c552014-09-02 21:43:13 +0000845 }
846 }
847
George Burgess IV652ec4f2016-06-09 23:15:04 +0000848 // Special handling for globals and arguments
George Burgess IV24eb0da2016-06-14 18:12:28 +0000849 for (auto *External : GraphBuilder.getExternalValues()) {
850 SetBuilder.add(External);
851 auto Attr = valueToAttr(External);
George Burgess IV652ec4f2016-06-09 23:15:04 +0000852 if (Attr.hasValue()) {
George Burgess IV24eb0da2016-06-14 18:12:28 +0000853 SetBuilder.noteAttributes(External, *Attr);
854 SetBuilder.addAttributesBelow(External, AttrUnknown);
George Burgess IV652ec4f2016-06-09 23:15:04 +0000855 }
George Burgess IV24eb0da2016-06-14 18:12:28 +0000856 }
George Burgess IVab03af22015-03-10 02:58:15 +0000857
George Burgess IV24eb0da2016-06-14 18:12:28 +0000858 for (auto *Escape : GraphBuilder.getEscapedValues()) {
859 SetBuilder.add(Escape);
860 SetBuilder.noteAttributes(Escape, AttrEscaped);
861 SetBuilder.addAttributesBelow(Escape, AttrUnknown);
862 }
Hal Finkel7529c552014-09-02 21:43:13 +0000863
George Burgess IV87b2e412016-06-20 23:10:56 +0000864 return FunctionInfo(*Fn, GraphBuilder.getReturnValues(), SetBuilder.build());
Hal Finkel7529c552014-09-02 21:43:13 +0000865}
866
Chandler Carruth7b560d42015-09-09 17:55:00 +0000867void CFLAAResult::scan(Function *Fn) {
Hal Finkel8d1590d2014-09-02 22:52:30 +0000868 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
Hal Finkel7529c552014-09-02 21:43:13 +0000869 (void)InsertPair;
870 assert(InsertPair.second &&
871 "Trying to scan a function that has already been cached");
872
George Burgess IV6edb8912016-05-02 18:09:19 +0000873 // Note that we can't do Cache[Fn] = buildSetsFrom(Fn) here: the function call
874 // may get evaluated after operator[], potentially triggering a DenseMap
875 // resize and invalidating the reference returned by operator[]
876 auto FunInfo = buildSetsFrom(Fn);
877 Cache[Fn] = std::move(FunInfo);
878
Hal Finkel7529c552014-09-02 21:43:13 +0000879 Handles.push_front(FunctionHandle(Fn, this));
880}
881
Chandler Carruth7b560d42015-09-09 17:55:00 +0000882void CFLAAResult::evict(Function *Fn) { Cache.erase(Fn); }
Chandler Carruth8b046a42015-08-14 02:42:20 +0000883
George Burgess IVcae581d2016-04-13 23:27:37 +0000884/// Ensures that the given function is available in the cache, and returns the
885/// entry.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000886const Optional<CFLAAResult::FunctionInfo> &
887CFLAAResult::ensureCached(Function *Fn) {
Chandler Carruth8b046a42015-08-14 02:42:20 +0000888 auto Iter = Cache.find(Fn);
889 if (Iter == Cache.end()) {
890 scan(Fn);
891 Iter = Cache.find(Fn);
892 assert(Iter != Cache.end());
893 assert(Iter->second.hasValue());
894 }
895 return Iter->second;
896}
897
Chandler Carruth7b560d42015-09-09 17:55:00 +0000898AliasResult CFLAAResult::query(const MemoryLocation &LocA,
899 const MemoryLocation &LocB) {
Hal Finkel7529c552014-09-02 21:43:13 +0000900 auto *ValA = const_cast<Value *>(LocA.Ptr);
901 auto *ValB = const_cast<Value *>(LocB.Ptr);
902
George Burgess IV259d9012016-06-15 20:43:41 +0000903 if (!ValA->getType()->isPointerTy() || !ValB->getType()->isPointerTy())
904 return NoAlias;
905
Hal Finkel7529c552014-09-02 21:43:13 +0000906 Function *Fn = nullptr;
907 auto MaybeFnA = parentFunctionOfValue(ValA);
908 auto MaybeFnB = parentFunctionOfValue(ValB);
909 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
George Burgess IVcae581d2016-04-13 23:27:37 +0000910 // The only times this is known to happen are when globals + InlineAsm are
911 // involved
George Burgess IV33305e72015-02-12 03:07:07 +0000912 DEBUG(dbgs() << "CFLAA: could not extract parent function information.\n");
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000913 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +0000914 }
915
916 if (MaybeFnA.hasValue()) {
917 Fn = *MaybeFnA;
918 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
919 "Interprocedural queries not supported");
920 } else {
921 Fn = *MaybeFnB;
922 }
923
924 assert(Fn != nullptr);
925 auto &MaybeInfo = ensureCached(Fn);
926 assert(MaybeInfo.hasValue());
927
George Burgess IV87b2e412016-06-20 23:10:56 +0000928 auto &Sets = MaybeInfo->getStratifiedSets();
Hal Finkel7529c552014-09-02 21:43:13 +0000929 auto MaybeA = Sets.find(ValA);
930 if (!MaybeA.hasValue())
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000931 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +0000932
933 auto MaybeB = Sets.find(ValB);
934 if (!MaybeB.hasValue())
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000935 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +0000936
937 auto SetA = *MaybeA;
938 auto SetB = *MaybeB;
Hal Finkel7529c552014-09-02 21:43:13 +0000939 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
940 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
George Burgess IV33305e72015-02-12 03:07:07 +0000941
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000942 // If both values are local (meaning the corresponding set has attribute
943 // AttrNone or AttrEscaped), then we know that CFLAA fully models them: they
944 // may-alias each other if and only if they are in the same set
945 // If at least one value is non-local (meaning it either is global/argument or
946 // it comes from unknown sources like integer cast), the situation becomes a
947 // bit more interesting. We follow three general rules described below:
948 // - Non-local values may alias each other
949 // - AttrNone values do not alias any non-local values
George Burgess IV652ec4f2016-06-09 23:15:04 +0000950 // - AttrEscaped do not alias globals/arguments, but they may alias
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000951 // AttrUnknown values
952 if (SetA.Index == SetB.Index)
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000953 return MayAlias;
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000954 if (AttrsA.none() || AttrsB.none())
955 return NoAlias;
George Burgess IV652ec4f2016-06-09 23:15:04 +0000956 if (isUnknownAttr(AttrsA) || isUnknownAttr(AttrsB))
George Burgess IVa1f9a2d2016-06-07 18:35:37 +0000957 return MayAlias;
958 if (isGlobalOrArgAttr(AttrsA) && isGlobalOrArgAttr(AttrsB))
959 return MayAlias;
960 return NoAlias;
Hal Finkel7529c552014-09-02 21:43:13 +0000961}
Mehdi Amini46a43552015-03-04 18:43:29 +0000962
Chandler Carruthb4faf132016-03-11 10:22:49 +0000963char CFLAA::PassID;
964
Chandler Carruthb47f8012016-03-11 11:05:24 +0000965CFLAAResult CFLAA::run(Function &F, AnalysisManager<Function> &AM) {
George Burgess IV18b83fe2016-06-01 18:39:54 +0000966 return CFLAAResult(AM.getResult<TargetLibraryAnalysis>(F));
Chandler Carruth7b560d42015-09-09 17:55:00 +0000967}
968
Chandler Carruth7b560d42015-09-09 17:55:00 +0000969char CFLAAWrapperPass::ID = 0;
Chandler Carruth12884f72016-03-02 15:56:53 +0000970INITIALIZE_PASS(CFLAAWrapperPass, "cfl-aa", "CFL-Based Alias Analysis", false,
971 true)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000972
973ImmutablePass *llvm::createCFLAAWrapperPass() { return new CFLAAWrapperPass(); }
974
975CFLAAWrapperPass::CFLAAWrapperPass() : ImmutablePass(ID) {
976 initializeCFLAAWrapperPassPass(*PassRegistry::getPassRegistry());
977}
978
George Burgess IV18b83fe2016-06-01 18:39:54 +0000979void CFLAAWrapperPass::initializePass() {
980 auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>();
981 Result.reset(new CFLAAResult(TLIWP.getTLI()));
Chandler Carruth7b560d42015-09-09 17:55:00 +0000982}
983
984void CFLAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
985 AU.setPreservesAll();
George Burgess IV18b83fe2016-06-01 18:39:54 +0000986 AU.addRequired<TargetLibraryInfoWrapperPass>();
Mehdi Amini46a43552015-03-04 18:43:29 +0000987}