blob: 4843ed6587a80362278596c5a1cff13809411e6f [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
26// ~nlogn time (n = number of variables.), which makes queries take constant
27// time.
28//===----------------------------------------------------------------------===//
29
Chandler Carruth8b046a42015-08-14 02:42:20 +000030#include "llvm/Analysis/CFLAliasAnalysis.h"
Hal Finkel7529c552014-09-02 21:43:13 +000031#include "StratifiedSets.h"
Hal Finkel7529c552014-09-02 21:43:13 +000032#include "llvm/ADT/BitVector.h"
33#include "llvm/ADT/DenseMap.h"
Hal Finkel7529c552014-09-02 21:43:13 +000034#include "llvm/ADT/None.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000035#include "llvm/ADT/Optional.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000036#include "llvm/Analysis/TargetLibraryInfo.h"
Hal Finkel7529c552014-09-02 21:43:13 +000037#include "llvm/IR/Constants.h"
38#include "llvm/IR/Function.h"
Hal Finkel7529c552014-09-02 21:43:13 +000039#include "llvm/IR/InstVisitor.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000040#include "llvm/IR/Instructions.h"
Hal Finkel7529c552014-09-02 21:43:13 +000041#include "llvm/Pass.h"
42#include "llvm/Support/Allocator.h"
Hal Finkel7d7087c2014-09-02 22:13:00 +000043#include "llvm/Support/Compiler.h"
George Burgess IV33305e72015-02-12 03:07:07 +000044#include "llvm/Support/Debug.h"
Hal Finkel7529c552014-09-02 21:43:13 +000045#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000046#include "llvm/Support/raw_ostream.h"
Hal Finkel7529c552014-09-02 21:43:13 +000047#include <algorithm>
48#include <cassert>
Benjamin Kramer799003b2015-03-23 19:32:43 +000049#include <memory>
Hal Finkel7529c552014-09-02 21:43:13 +000050#include <tuple>
51
52using namespace llvm;
53
George Burgess IV33305e72015-02-12 03:07:07 +000054#define DEBUG_TYPE "cfl-aa"
55
Chandler Carruth7b560d42015-09-09 17:55:00 +000056CFLAAResult::CFLAAResult(const TargetLibraryInfo &TLI) : AAResultBase(TLI) {}
57CFLAAResult::CFLAAResult(CFLAAResult &&Arg) : AAResultBase(std::move(Arg)) {}
Chandler Carruth8b046a42015-08-14 02:42:20 +000058
59// \brief Information we have about a function and would like to keep around
Chandler Carruth7b560d42015-09-09 17:55:00 +000060struct CFLAAResult::FunctionInfo {
Chandler Carruth8b046a42015-08-14 02:42:20 +000061 StratifiedSets<Value *> Sets;
62 // Lots of functions have < 4 returns. Adjust as necessary.
63 SmallVector<Value *, 4> ReturnedValues;
64
65 FunctionInfo(StratifiedSets<Value *> &&S, SmallVector<Value *, 4> &&RV)
66 : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
67};
68
Hal Finkel7529c552014-09-02 21:43:13 +000069// Try to go from a Value* to a Function*. Never returns nullptr.
70static Optional<Function *> parentFunctionOfValue(Value *);
71
72// Returns possible functions called by the Inst* into the given
73// SmallVectorImpl. Returns true if targets found, false otherwise.
74// This is templated because InvokeInst/CallInst give us the same
75// set of functions that we care about, and I don't like repeating
76// myself.
77template <typename Inst>
78static bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &);
79
80// Some instructions need to have their users tracked. Instructions like
81// `add` require you to get the users of the Instruction* itself, other
82// instructions like `store` require you to get the users of the first
83// operand. This function gets the "proper" value to track for each
84// type of instruction we support.
85static Optional<Value *> getTargetValue(Instruction *);
86
87// There are certain instructions (i.e. FenceInst, etc.) that we ignore.
88// This notes that we should ignore those.
89static bool hasUsefulEdges(Instruction *);
90
Hal Finkel1ae325f2014-09-02 23:50:01 +000091const StratifiedIndex StratifiedLink::SetSentinel =
George Burgess IV11d509d2015-03-15 00:52:21 +000092 std::numeric_limits<StratifiedIndex>::max();
Hal Finkel1ae325f2014-09-02 23:50:01 +000093
Hal Finkel7529c552014-09-02 21:43:13 +000094namespace {
95// StratifiedInfo Attribute things.
96typedef unsigned StratifiedAttr;
Hal Finkel7d7087c2014-09-02 22:13:00 +000097LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
98LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
99LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
George Burgess IVb54a8d622015-03-10 02:40:06 +0000100LLVM_CONSTEXPR unsigned AttrUnknownIndex = 2;
101LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 3;
Hal Finkel7d7087c2014-09-02 22:13:00 +0000102LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
103LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
Hal Finkel7529c552014-09-02 21:43:13 +0000104
Hal Finkel7d7087c2014-09-02 22:13:00 +0000105LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
George Burgess IVb54a8d622015-03-10 02:40:06 +0000106LLVM_CONSTEXPR StratifiedAttr AttrUnknown = 1 << AttrUnknownIndex;
Hal Finkel7d7087c2014-09-02 22:13:00 +0000107LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
Hal Finkel7529c552014-09-02 21:43:13 +0000108
109// \brief StratifiedSets call for knowledge of "direction", so this is how we
110// represent that locally.
111enum class Level { Same, Above, Below };
112
113// \brief Edges can be one of four "weights" -- each weight must have an inverse
114// weight (Assign has Assign; Reference has Dereference).
115enum class EdgeType {
116 // The weight assigned when assigning from or to a value. For example, in:
117 // %b = getelementptr %a, 0
118 // ...The relationships are %b assign %a, and %a assign %b. This used to be
119 // two edges, but having a distinction bought us nothing.
120 Assign,
121
122 // The edge used when we have an edge going from some handle to a Value.
123 // Examples of this include:
124 // %b = load %a (%b Dereference %a)
125 // %b = extractelement %a, 0 (%a Dereference %b)
126 Dereference,
127
128 // The edge used when our edge goes from a value to a handle that may have
129 // contained it at some point. Examples:
130 // %b = load %a (%a Reference %b)
131 // %b = extractelement %a, 0 (%b Reference %a)
132 Reference
133};
134
135// \brief Encodes the notion of a "use"
136struct Edge {
137 // \brief Which value the edge is coming from
138 Value *From;
139
140 // \brief Which value the edge is pointing to
141 Value *To;
142
143 // \brief Edge weight
144 EdgeType Weight;
145
146 // \brief Whether we aliased any external values along the way that may be
147 // invisible to the analysis (i.e. landingpad for exceptions, calls for
148 // interprocedural analysis, etc.)
149 StratifiedAttrs AdditionalAttrs;
150
151 Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
152 : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
153};
154
Hal Finkel7529c552014-09-02 21:43:13 +0000155// \brief Gets the edges our graph should have, based on an Instruction*
156class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
Chandler Carruth7b560d42015-09-09 17:55:00 +0000157 CFLAAResult &AA;
Hal Finkel7529c552014-09-02 21:43:13 +0000158 SmallVectorImpl<Edge> &Output;
159
160public:
Chandler Carruth7b560d42015-09-09 17:55:00 +0000161 GetEdgesVisitor(CFLAAResult &AA, SmallVectorImpl<Edge> &Output)
Hal Finkel7529c552014-09-02 21:43:13 +0000162 : AA(AA), Output(Output) {}
163
164 void visitInstruction(Instruction &) {
165 llvm_unreachable("Unsupported instruction encountered");
166 }
167
George Burgess IVb54a8d622015-03-10 02:40:06 +0000168 void visitPtrToIntInst(PtrToIntInst &Inst) {
169 auto *Ptr = Inst.getOperand(0);
170 Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
171 }
172
173 void visitIntToPtrInst(IntToPtrInst &Inst) {
174 auto *Ptr = &Inst;
175 Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
176 }
177
Hal Finkel7529c552014-09-02 21:43:13 +0000178 void visitCastInst(CastInst &Inst) {
George Burgess IV11d509d2015-03-15 00:52:21 +0000179 Output.push_back(
180 Edge(&Inst, Inst.getOperand(0), EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000181 }
182
183 void visitBinaryOperator(BinaryOperator &Inst) {
184 auto *Op1 = Inst.getOperand(0);
185 auto *Op2 = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000186 Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
187 Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000188 }
189
190 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
191 auto *Ptr = Inst.getPointerOperand();
192 auto *Val = Inst.getNewValOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000193 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000194 }
195
196 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
197 auto *Ptr = Inst.getPointerOperand();
198 auto *Val = Inst.getValOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000199 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000200 }
201
202 void visitPHINode(PHINode &Inst) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000203 for (Value *Val : Inst.incoming_values()) {
Hal Finkel8d1590d2014-09-02 22:52:30 +0000204 Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000205 }
206 }
207
208 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
209 auto *Op = Inst.getPointerOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000210 Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000211 for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
Hal Finkel8d1590d2014-09-02 22:52:30 +0000212 Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000213 }
214
215 void visitSelectInst(SelectInst &Inst) {
Daniel Berlin16f7a522015-01-26 17:31:17 +0000216 // Condition is not processed here (The actual statement producing
217 // the condition result is processed elsewhere). For select, the
218 // condition is evaluated, but not loaded, stored, or assigned
219 // simply as a result of being the condition of a select.
220
Hal Finkel7529c552014-09-02 21:43:13 +0000221 auto *TrueVal = Inst.getTrueValue();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000222 Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000223 auto *FalseVal = Inst.getFalseValue();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000224 Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000225 }
226
227 void visitAllocaInst(AllocaInst &) {}
228
229 void visitLoadInst(LoadInst &Inst) {
230 auto *Ptr = Inst.getPointerOperand();
231 auto *Val = &Inst;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000232 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000233 }
234
235 void visitStoreInst(StoreInst &Inst) {
236 auto *Ptr = Inst.getPointerOperand();
237 auto *Val = Inst.getValueOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000238 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000239 }
240
Hal Finkeldb5f86a2014-10-14 20:51:26 +0000241 void visitVAArgInst(VAArgInst &Inst) {
242 // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
243 // two things:
244 // 1. Loads a value from *((T*)*Ptr).
245 // 2. Increments (stores to) *Ptr by some target-specific amount.
246 // For now, we'll handle this like a landingpad instruction (by placing the
247 // result in its own group, and having that group alias externals).
248 auto *Val = &Inst;
249 Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll));
250 }
251
Hal Finkel7529c552014-09-02 21:43:13 +0000252 static bool isFunctionExternal(Function *Fn) {
253 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
254 }
255
256 // Gets whether the sets at Index1 above, below, or equal to the sets at
257 // Index2. Returns None if they are not in the same set chain.
258 static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
259 StratifiedIndex Index1,
260 StratifiedIndex Index2) {
261 if (Index1 == Index2)
262 return Level::Same;
263
264 const auto *Current = &Sets.getLink(Index1);
265 while (Current->hasBelow()) {
266 if (Current->Below == Index2)
267 return Level::Below;
268 Current = &Sets.getLink(Current->Below);
269 }
270
271 Current = &Sets.getLink(Index1);
272 while (Current->hasAbove()) {
273 if (Current->Above == Index2)
274 return Level::Above;
275 Current = &Sets.getLink(Current->Above);
276 }
277
278 return NoneType();
279 }
280
281 bool
282 tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
283 Value *FuncValue,
284 const iterator_range<User::op_iterator> &Args) {
Hal Finkelca616ac2014-09-02 23:29:48 +0000285 const unsigned ExpectedMaxArgs = 8;
286 const unsigned MaxSupportedArgs = 50;
Hal Finkel7529c552014-09-02 21:43:13 +0000287 assert(Fns.size() > 0);
288
289 // I put this here to give us an upper bound on time taken by IPA. Is it
290 // really (realistically) needed? Keep in mind that we do have an n^2 algo.
George Burgess IVab03af22015-03-10 02:58:15 +0000291 if (std::distance(Args.begin(), Args.end()) > (int)MaxSupportedArgs)
Hal Finkel7529c552014-09-02 21:43:13 +0000292 return false;
293
294 // Exit early if we'll fail anyway
295 for (auto *Fn : Fns) {
296 if (isFunctionExternal(Fn) || Fn->isVarArg())
297 return false;
298 auto &MaybeInfo = AA.ensureCached(Fn);
299 if (!MaybeInfo.hasValue())
300 return false;
301 }
302
303 SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
304 SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
305 for (auto *Fn : Fns) {
306 auto &Info = *AA.ensureCached(Fn);
307 auto &Sets = Info.Sets;
308 auto &RetVals = Info.ReturnedValues;
309
310 Parameters.clear();
311 for (auto &Param : Fn->args()) {
312 auto MaybeInfo = Sets.find(&Param);
313 // Did a new parameter somehow get added to the function/slip by?
314 if (!MaybeInfo.hasValue())
315 return false;
316 Parameters.push_back(*MaybeInfo);
317 }
318
319 // Adding an edge from argument -> return value for each parameter that
320 // may alias the return value
321 for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
322 auto &ParamInfo = Parameters[I];
323 auto &ArgVal = Arguments[I];
324 bool AddEdge = false;
325 StratifiedAttrs Externals;
326 for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
327 auto MaybeInfo = Sets.find(RetVals[X]);
328 if (!MaybeInfo.hasValue())
329 return false;
330
331 auto &RetInfo = *MaybeInfo;
332 auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
333 auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
334 auto MaybeRelation =
335 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
336 if (MaybeRelation.hasValue()) {
337 AddEdge = true;
338 Externals |= RetAttrs | ParamAttrs;
339 }
340 }
341 if (AddEdge)
Hal Finkelca616ac2014-09-02 23:29:48 +0000342 Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
George Burgess IV11d509d2015-03-15 00:52:21 +0000343 StratifiedAttrs().flip()));
Hal Finkel7529c552014-09-02 21:43:13 +0000344 }
345
346 if (Parameters.size() != Arguments.size())
347 return false;
348
349 // Adding edges between arguments for arguments that may end up aliasing
350 // each other. This is necessary for functions such as
351 // void foo(int** a, int** b) { *a = *b; }
352 // (Technically, the proper sets for this would be those below
353 // Arguments[I] and Arguments[X], but our algorithm will produce
354 // extremely similar, and equally correct, results either way)
355 for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
356 auto &MainVal = Arguments[I];
357 auto &MainInfo = Parameters[I];
358 auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
359 for (unsigned X = I + 1; X != E; ++X) {
360 auto &SubInfo = Parameters[X];
361 auto &SubVal = Arguments[X];
362 auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
363 auto MaybeRelation =
364 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
365
366 if (!MaybeRelation.hasValue())
367 continue;
368
369 auto NewAttrs = SubAttrs | MainAttrs;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000370 Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
Hal Finkel7529c552014-09-02 21:43:13 +0000371 }
372 }
373 }
374 return true;
375 }
376
377 template <typename InstT> void visitCallLikeInst(InstT &Inst) {
George Burgess IV68b36e02015-08-28 00:16:18 +0000378 // TODO: Add support for noalias args/all the other fun function attributes
379 // that we can tack on.
Hal Finkel7529c552014-09-02 21:43:13 +0000380 SmallVector<Function *, 4> Targets;
381 if (getPossibleTargets(&Inst, Targets)) {
382 if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
383 return;
384 // Cleanup from interprocedural analysis
385 Output.clear();
386 }
387
George Burgess IV68b36e02015-08-28 00:16:18 +0000388 // Because the function is opaque, we need to note that anything
389 // could have happened to the arguments, and that the result could alias
390 // just about anything, too.
391 // The goal of the loop is in part to unify many Values into one set, so we
392 // don't care if the function is void there.
Hal Finkel7529c552014-09-02 21:43:13 +0000393 for (Value *V : Inst.arg_operands())
Hal Finkel8d1590d2014-09-02 22:52:30 +0000394 Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
George Burgess IV68b36e02015-08-28 00:16:18 +0000395 if (Inst.getNumArgOperands() == 0 &&
396 Inst.getType() != Type::getVoidTy(Inst.getContext()))
397 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
Hal Finkel7529c552014-09-02 21:43:13 +0000398 }
399
400 void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
401
402 void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
403
404 // Because vectors/aggregates are immutable and unaddressable,
405 // there's nothing we can do to coax a value out of them, other
406 // than calling Extract{Element,Value}. We can effectively treat
407 // them as pointers to arbitrary memory locations we can store in
408 // and load from.
409 void visitExtractElementInst(ExtractElementInst &Inst) {
410 auto *Ptr = Inst.getVectorOperand();
411 auto *Val = &Inst;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000412 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000413 }
414
415 void visitInsertElementInst(InsertElementInst &Inst) {
416 auto *Vec = Inst.getOperand(0);
417 auto *Val = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000418 Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
419 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000420 }
421
422 void visitLandingPadInst(LandingPadInst &Inst) {
423 // Exceptions come from "nowhere", from our analysis' perspective.
424 // So we place the instruction its own group, noting that said group may
425 // alias externals
Hal Finkel8d1590d2014-09-02 22:52:30 +0000426 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
Hal Finkel7529c552014-09-02 21:43:13 +0000427 }
428
429 void visitInsertValueInst(InsertValueInst &Inst) {
430 auto *Agg = Inst.getOperand(0);
431 auto *Val = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000432 Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
433 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000434 }
435
436 void visitExtractValueInst(ExtractValueInst &Inst) {
437 auto *Ptr = Inst.getAggregateOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000438 Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000439 }
440
441 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
442 auto *From1 = Inst.getOperand(0);
443 auto *From2 = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000444 Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
445 Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000446 }
Pete Cooper36642532015-06-12 16:13:54 +0000447
448 void visitConstantExpr(ConstantExpr *CE) {
449 switch (CE->getOpcode()) {
450 default:
451 llvm_unreachable("Unknown instruction type encountered!");
452// Build the switch statement using the Instruction.def file.
453#define HANDLE_INST(NUM, OPCODE, CLASS) \
454 case Instruction::OPCODE: \
455 visit##OPCODE(*(CLASS *)CE); \
456 break;
457#include "llvm/IR/Instruction.def"
458 }
459 }
Hal Finkel7529c552014-09-02 21:43:13 +0000460};
461
462// For a given instruction, we need to know which Value* to get the
463// users of in order to build our graph. In some cases (i.e. add),
464// we simply need the Instruction*. In other cases (i.e. store),
465// finding the users of the Instruction* is useless; we need to find
466// the users of the first operand. This handles determining which
467// value to follow for us.
468//
469// Note: we *need* to keep this in sync with GetEdgesVisitor. Add
470// something to GetEdgesVisitor, add it here -- remove something from
471// GetEdgesVisitor, remove it here.
472class GetTargetValueVisitor
473 : public InstVisitor<GetTargetValueVisitor, Value *> {
474public:
475 Value *visitInstruction(Instruction &Inst) { return &Inst; }
476
477 Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
478
479 Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
480 return Inst.getPointerOperand();
481 }
482
483 Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
484 return Inst.getPointerOperand();
485 }
486
487 Value *visitInsertElementInst(InsertElementInst &Inst) {
488 return Inst.getOperand(0);
489 }
490
491 Value *visitInsertValueInst(InsertValueInst &Inst) {
492 return Inst.getAggregateOperand();
493 }
494};
495
496// Set building requires a weighted bidirectional graph.
497template <typename EdgeTypeT> class WeightedBidirectionalGraph {
498public:
499 typedef std::size_t Node;
500
501private:
Hal Finkelca616ac2014-09-02 23:29:48 +0000502 const static Node StartNode = Node(0);
Hal Finkel7529c552014-09-02 21:43:13 +0000503
504 struct Edge {
505 EdgeTypeT Weight;
506 Node Other;
507
George Burgess IV11d509d2015-03-15 00:52:21 +0000508 Edge(const EdgeTypeT &W, const Node &N) : Weight(W), Other(N) {}
Hal Finkelca616ac2014-09-02 23:29:48 +0000509
Hal Finkel7529c552014-09-02 21:43:13 +0000510 bool operator==(const Edge &E) const {
511 return Weight == E.Weight && Other == E.Other;
512 }
513
514 bool operator!=(const Edge &E) const { return !operator==(E); }
515 };
516
517 struct NodeImpl {
518 std::vector<Edge> Edges;
519 };
520
521 std::vector<NodeImpl> NodeImpls;
522
523 bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
524
525 const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
526 NodeImpl &getNode(Node N) { return NodeImpls[N]; }
527
528public:
529 // ----- Various Edge iterators for the graph ----- //
530
531 // \brief Iterator for edges. Because this graph is bidirected, we don't
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000532 // allow modification of the edges using this iterator. Additionally, the
Hal Finkel7529c552014-09-02 21:43:13 +0000533 // iterator becomes invalid if you add edges to or from the node you're
534 // getting the edges of.
535 struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
536 std::tuple<EdgeTypeT, Node *>> {
537 EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
538 : Current(Iter) {}
539
540 EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
541
542 EdgeIterator &operator++() {
543 ++Current;
544 return *this;
545 }
546
547 EdgeIterator operator++(int) {
548 EdgeIterator Copy(Current);
549 operator++();
550 return Copy;
551 }
552
553 std::tuple<EdgeTypeT, Node> &operator*() {
554 Store = std::make_tuple(Current->Weight, Current->Other);
555 return Store;
556 }
557
558 bool operator==(const EdgeIterator &Other) const {
559 return Current == Other.Current;
560 }
561
562 bool operator!=(const EdgeIterator &Other) const {
563 return !operator==(Other);
564 }
565
566 private:
567 typename std::vector<Edge>::const_iterator Current;
568 std::tuple<EdgeTypeT, Node> Store;
569 };
570
571 // Wrapper for EdgeIterator with begin()/end() calls.
572 struct EdgeIterable {
573 EdgeIterable(const std::vector<Edge> &Edges)
574 : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
575
576 EdgeIterator begin() { return EdgeIterator(BeginIter); }
577
578 EdgeIterator end() { return EdgeIterator(EndIter); }
579
580 private:
581 typename std::vector<Edge>::const_iterator BeginIter;
582 typename std::vector<Edge>::const_iterator EndIter;
583 };
584
585 // ----- Actual graph-related things ----- //
586
Hal Finkelca616ac2014-09-02 23:29:48 +0000587 WeightedBidirectionalGraph() {}
Hal Finkel7529c552014-09-02 21:43:13 +0000588
589 WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
590 : NodeImpls(std::move(Other.NodeImpls)) {}
591
592 WeightedBidirectionalGraph<EdgeTypeT> &
593 operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
594 NodeImpls = std::move(Other.NodeImpls);
595 return *this;
596 }
597
598 Node addNode() {
599 auto Index = NodeImpls.size();
600 auto NewNode = Node(Index);
601 NodeImpls.push_back(NodeImpl());
602 return NewNode;
603 }
604
605 void addEdge(Node From, Node To, const EdgeTypeT &Weight,
606 const EdgeTypeT &ReverseWeight) {
607 assert(inbounds(From));
608 assert(inbounds(To));
609 auto &FromNode = getNode(From);
610 auto &ToNode = getNode(To);
Hal Finkelca616ac2014-09-02 23:29:48 +0000611 FromNode.Edges.push_back(Edge(Weight, To));
612 ToNode.Edges.push_back(Edge(ReverseWeight, From));
Hal Finkel7529c552014-09-02 21:43:13 +0000613 }
614
615 EdgeIterable edgesFor(const Node &N) const {
616 const auto &Node = getNode(N);
617 return EdgeIterable(Node.Edges);
618 }
619
620 bool empty() const { return NodeImpls.empty(); }
621 std::size_t size() const { return NodeImpls.size(); }
622
623 // \brief Gets an arbitrary node in the graph as a starting point for
624 // traversal.
625 Node getEntryNode() {
626 assert(inbounds(StartNode));
627 return StartNode;
628 }
629};
630
631typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
632typedef DenseMap<Value *, GraphT::Node> NodeMapT;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000633}
Hal Finkel7529c552014-09-02 21:43:13 +0000634
Hal Finkel7529c552014-09-02 21:43:13 +0000635//===----------------------------------------------------------------------===//
636// Function declarations that require types defined in the namespace above
637//===----------------------------------------------------------------------===//
638
639// Given an argument number, returns the appropriate Attr index to set.
640static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
641
642// Given a Value, potentially return which AttrIndex it maps to.
643static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
644
645// Gets the inverse of a given EdgeType.
646static EdgeType flipWeight(EdgeType);
647
648// Gets edges of the given Instruction*, writing them to the SmallVector*.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000649static void argsToEdges(CFLAAResult &, Instruction *, SmallVectorImpl<Edge> &);
Hal Finkel7529c552014-09-02 21:43:13 +0000650
Pete Cooper36642532015-06-12 16:13:54 +0000651// Gets edges of the given ConstantExpr*, writing them to the SmallVector*.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000652static void argsToEdges(CFLAAResult &, ConstantExpr *, SmallVectorImpl<Edge> &);
Pete Cooper36642532015-06-12 16:13:54 +0000653
Hal Finkel7529c552014-09-02 21:43:13 +0000654// Gets the "Level" that one should travel in StratifiedSets
655// given an EdgeType.
656static Level directionOfEdgeType(EdgeType);
657
658// Builds the graph needed for constructing the StratifiedSets for the
659// given function
Chandler Carruth7b560d42015-09-09 17:55:00 +0000660static void buildGraphFrom(CFLAAResult &, Function *,
Hal Finkel7529c552014-09-02 21:43:13 +0000661 SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
662
George Burgess IVab03af22015-03-10 02:58:15 +0000663// Gets the edges of a ConstantExpr as if it was an Instruction. This
664// function also acts on any nested ConstantExprs, adding the edges
665// of those to the given SmallVector as well.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000666static void constexprToEdges(CFLAAResult &, ConstantExpr &,
George Burgess IVab03af22015-03-10 02:58:15 +0000667 SmallVectorImpl<Edge> &);
668
669// Given an Instruction, this will add it to the graph, along with any
670// Instructions that are potentially only available from said Instruction
671// For example, given the following line:
672// %0 = load i16* getelementptr ([1 x i16]* @a, 0, 0), align 2
673// addInstructionToGraph would add both the `load` and `getelementptr`
674// instructions to the graph appropriately.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000675static void addInstructionToGraph(CFLAAResult &, Instruction &,
George Burgess IVab03af22015-03-10 02:58:15 +0000676 SmallVectorImpl<Value *> &, NodeMapT &,
677 GraphT &);
678
679// Notes whether it would be pointless to add the given Value to our sets.
680static bool canSkipAddingToSets(Value *Val);
681
Hal Finkel7529c552014-09-02 21:43:13 +0000682static Optional<Function *> parentFunctionOfValue(Value *Val) {
683 if (auto *Inst = dyn_cast<Instruction>(Val)) {
684 auto *Bb = Inst->getParent();
685 return Bb->getParent();
686 }
687
688 if (auto *Arg = dyn_cast<Argument>(Val))
689 return Arg->getParent();
690 return NoneType();
691}
692
693template <typename Inst>
694static bool getPossibleTargets(Inst *Call,
695 SmallVectorImpl<Function *> &Output) {
696 if (auto *Fn = Call->getCalledFunction()) {
697 Output.push_back(Fn);
698 return true;
699 }
700
701 // TODO: If the call is indirect, we might be able to enumerate all potential
702 // targets of the call and return them, rather than just failing.
703 return false;
704}
705
706static Optional<Value *> getTargetValue(Instruction *Inst) {
707 GetTargetValueVisitor V;
708 return V.visit(Inst);
709}
710
711static bool hasUsefulEdges(Instruction *Inst) {
712 bool IsNonInvokeTerminator =
713 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
714 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
715}
716
Pete Cooper36642532015-06-12 16:13:54 +0000717static bool hasUsefulEdges(ConstantExpr *CE) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000718 // ConstantExpr doesn't have terminators, invokes, or fences, so only needs
Pete Cooper36642532015-06-12 16:13:54 +0000719 // to check for compares.
720 return CE->getOpcode() != Instruction::ICmp &&
721 CE->getOpcode() != Instruction::FCmp;
722}
723
Hal Finkel7529c552014-09-02 21:43:13 +0000724static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
725 if (isa<GlobalValue>(Val))
726 return AttrGlobalIndex;
727
728 if (auto *Arg = dyn_cast<Argument>(Val))
Daniel Berlin16f7a522015-01-26 17:31:17 +0000729 // Only pointer arguments should have the argument attribute,
730 // because things can't escape through scalars without us seeing a
731 // cast, and thus, interaction with them doesn't matter.
732 if (!Arg->hasNoAliasAttr() && Arg->getType()->isPointerTy())
Hal Finkel7529c552014-09-02 21:43:13 +0000733 return argNumberToAttrIndex(Arg->getArgNo());
734 return NoneType();
735}
736
737static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
George Burgess IV3c898c22015-01-21 16:37:21 +0000738 if (ArgNum >= AttrMaxNumArgs)
Hal Finkel7529c552014-09-02 21:43:13 +0000739 return AttrAllIndex;
740 return ArgNum + AttrFirstArgIndex;
741}
742
743static EdgeType flipWeight(EdgeType Initial) {
744 switch (Initial) {
745 case EdgeType::Assign:
746 return EdgeType::Assign;
747 case EdgeType::Dereference:
748 return EdgeType::Reference;
749 case EdgeType::Reference:
750 return EdgeType::Dereference;
751 }
752 llvm_unreachable("Incomplete coverage of EdgeType enum");
753}
754
Chandler Carruth7b560d42015-09-09 17:55:00 +0000755static void argsToEdges(CFLAAResult &Analysis, Instruction *Inst,
Hal Finkel7529c552014-09-02 21:43:13 +0000756 SmallVectorImpl<Edge> &Output) {
George Burgess IVab03af22015-03-10 02:58:15 +0000757 assert(hasUsefulEdges(Inst) &&
758 "Expected instructions to have 'useful' edges");
Hal Finkel7529c552014-09-02 21:43:13 +0000759 GetEdgesVisitor v(Analysis, Output);
760 v.visit(Inst);
761}
762
Chandler Carruth7b560d42015-09-09 17:55:00 +0000763static void argsToEdges(CFLAAResult &Analysis, ConstantExpr *CE,
Pete Cooper36642532015-06-12 16:13:54 +0000764 SmallVectorImpl<Edge> &Output) {
765 assert(hasUsefulEdges(CE) && "Expected constant expr to have 'useful' edges");
766 GetEdgesVisitor v(Analysis, Output);
767 v.visitConstantExpr(CE);
768}
769
Hal Finkel7529c552014-09-02 21:43:13 +0000770static Level directionOfEdgeType(EdgeType Weight) {
771 switch (Weight) {
772 case EdgeType::Reference:
773 return Level::Above;
774 case EdgeType::Dereference:
775 return Level::Below;
776 case EdgeType::Assign:
777 return Level::Same;
778 }
779 llvm_unreachable("Incomplete switch coverage");
780}
781
Chandler Carruth7b560d42015-09-09 17:55:00 +0000782static void constexprToEdges(CFLAAResult &Analysis,
George Burgess IVab03af22015-03-10 02:58:15 +0000783 ConstantExpr &CExprToCollapse,
784 SmallVectorImpl<Edge> &Results) {
785 SmallVector<ConstantExpr *, 4> Worklist;
786 Worklist.push_back(&CExprToCollapse);
787
788 SmallVector<Edge, 8> ConstexprEdges;
Pete Cooper36642532015-06-12 16:13:54 +0000789 SmallPtrSet<ConstantExpr *, 4> Visited;
George Burgess IVab03af22015-03-10 02:58:15 +0000790 while (!Worklist.empty()) {
791 auto *CExpr = Worklist.pop_back_val();
George Burgess IVab03af22015-03-10 02:58:15 +0000792
Pete Cooper36642532015-06-12 16:13:54 +0000793 if (!hasUsefulEdges(CExpr))
George Burgess IVab03af22015-03-10 02:58:15 +0000794 continue;
795
796 ConstexprEdges.clear();
Pete Cooper36642532015-06-12 16:13:54 +0000797 argsToEdges(Analysis, CExpr, ConstexprEdges);
George Burgess IVab03af22015-03-10 02:58:15 +0000798 for (auto &Edge : ConstexprEdges) {
Pete Cooper36642532015-06-12 16:13:54 +0000799 if (auto *Nested = dyn_cast<ConstantExpr>(Edge.From))
800 if (Visited.insert(Nested).second)
801 Worklist.push_back(Nested);
George Burgess IVab03af22015-03-10 02:58:15 +0000802
Pete Cooper36642532015-06-12 16:13:54 +0000803 if (auto *Nested = dyn_cast<ConstantExpr>(Edge.To))
804 if (Visited.insert(Nested).second)
805 Worklist.push_back(Nested);
George Burgess IVab03af22015-03-10 02:58:15 +0000806 }
807
808 Results.append(ConstexprEdges.begin(), ConstexprEdges.end());
809 }
810}
811
Chandler Carruth7b560d42015-09-09 17:55:00 +0000812static void addInstructionToGraph(CFLAAResult &Analysis, Instruction &Inst,
George Burgess IVab03af22015-03-10 02:58:15 +0000813 SmallVectorImpl<Value *> &ReturnedValues,
814 NodeMapT &Map, GraphT &Graph) {
Hal Finkel7529c552014-09-02 21:43:13 +0000815 const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
816 auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
817 auto &Iter = Pair.first;
818 if (Pair.second) {
819 auto NewNode = Graph.addNode();
820 Iter->second = NewNode;
821 }
822 return Iter->second;
823 };
824
George Burgess IVab03af22015-03-10 02:58:15 +0000825 // We don't want the edges of most "return" instructions, but we *do* want
826 // to know what can be returned.
827 if (isa<ReturnInst>(&Inst))
828 ReturnedValues.push_back(&Inst);
829
830 if (!hasUsefulEdges(&Inst))
831 return;
832
Hal Finkel7529c552014-09-02 21:43:13 +0000833 SmallVector<Edge, 8> Edges;
George Burgess IVab03af22015-03-10 02:58:15 +0000834 argsToEdges(Analysis, &Inst, Edges);
Hal Finkel7529c552014-09-02 21:43:13 +0000835
George Burgess IVab03af22015-03-10 02:58:15 +0000836 // In the case of an unused alloca (or similar), edges may be empty. Note
837 // that it exists so we can potentially answer NoAlias.
838 if (Edges.empty()) {
839 auto MaybeVal = getTargetValue(&Inst);
840 assert(MaybeVal.hasValue());
841 auto *Target = *MaybeVal;
842 findOrInsertNode(Target);
843 return;
Hal Finkel7529c552014-09-02 21:43:13 +0000844 }
George Burgess IVab03af22015-03-10 02:58:15 +0000845
846 const auto addEdgeToGraph = [&Graph, &findOrInsertNode](const Edge &E) {
847 auto To = findOrInsertNode(E.To);
848 auto From = findOrInsertNode(E.From);
849 auto FlippedWeight = flipWeight(E.Weight);
850 auto Attrs = E.AdditionalAttrs;
851 Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
852 std::make_pair(FlippedWeight, Attrs));
853 };
854
855 SmallVector<ConstantExpr *, 4> ConstantExprs;
856 for (const Edge &E : Edges) {
857 addEdgeToGraph(E);
858 if (auto *Constexpr = dyn_cast<ConstantExpr>(E.To))
859 ConstantExprs.push_back(Constexpr);
860 if (auto *Constexpr = dyn_cast<ConstantExpr>(E.From))
861 ConstantExprs.push_back(Constexpr);
862 }
863
864 for (ConstantExpr *CE : ConstantExprs) {
865 Edges.clear();
866 constexprToEdges(Analysis, *CE, Edges);
867 std::for_each(Edges.begin(), Edges.end(), addEdgeToGraph);
868 }
869}
870
871// Aside: We may remove graph construction entirely, because it doesn't really
872// buy us much that we don't already have. I'd like to add interprocedural
873// analysis prior to this however, in case that somehow requires the graph
874// produced by this for efficient execution
Chandler Carruth7b560d42015-09-09 17:55:00 +0000875static void buildGraphFrom(CFLAAResult &Analysis, Function *Fn,
George Burgess IVab03af22015-03-10 02:58:15 +0000876 SmallVectorImpl<Value *> &ReturnedValues,
877 NodeMapT &Map, GraphT &Graph) {
878 for (auto &Bb : Fn->getBasicBlockList())
879 for (auto &Inst : Bb.getInstList())
880 addInstructionToGraph(Analysis, Inst, ReturnedValues, Map, Graph);
881}
882
883static bool canSkipAddingToSets(Value *Val) {
884 // Constants can share instances, which may falsely unify multiple
885 // sets, e.g. in
886 // store i32* null, i32** %ptr1
887 // store i32* null, i32** %ptr2
888 // clearly ptr1 and ptr2 should not be unified into the same set, so
889 // we should filter out the (potentially shared) instance to
890 // i32* null.
891 if (isa<Constant>(Val)) {
892 bool Container = isa<ConstantVector>(Val) || isa<ConstantArray>(Val) ||
893 isa<ConstantStruct>(Val);
894 // TODO: Because all of these things are constant, we can determine whether
895 // the data is *actually* mutable at graph building time. This will probably
896 // come for free/cheap with offset awareness.
897 bool CanStoreMutableData =
898 isa<GlobalValue>(Val) || isa<ConstantExpr>(Val) || Container;
899 return !CanStoreMutableData;
900 }
901
902 return false;
Hal Finkel7529c552014-09-02 21:43:13 +0000903}
904
Chandler Carruth8b046a42015-08-14 02:42:20 +0000905// Builds the graph + StratifiedSets for a function.
Chandler Carruth7b560d42015-09-09 17:55:00 +0000906CFLAAResult::FunctionInfo CFLAAResult::buildSetsFrom(Function *Fn) {
Hal Finkel7529c552014-09-02 21:43:13 +0000907 NodeMapT Map;
908 GraphT Graph;
909 SmallVector<Value *, 4> ReturnedValues;
910
Chandler Carruth8b046a42015-08-14 02:42:20 +0000911 buildGraphFrom(*this, Fn, ReturnedValues, Map, Graph);
Hal Finkel7529c552014-09-02 21:43:13 +0000912
913 DenseMap<GraphT::Node, Value *> NodeValueMap;
914 NodeValueMap.resize(Map.size());
915 for (const auto &Pair : Map)
Hal Finkel8d1590d2014-09-02 22:52:30 +0000916 NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
Hal Finkel7529c552014-09-02 21:43:13 +0000917
918 const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
919 auto ValIter = NodeValueMap.find(Node);
920 assert(ValIter != NodeValueMap.end());
921 return ValIter->second;
922 };
923
924 StratifiedSetsBuilder<Value *> Builder;
925
926 SmallVector<GraphT::Node, 16> Worklist;
927 for (auto &Pair : Map) {
928 Worklist.clear();
929
930 auto *Value = Pair.first;
931 Builder.add(Value);
932 auto InitialNode = Pair.second;
933 Worklist.push_back(InitialNode);
934 while (!Worklist.empty()) {
935 auto Node = Worklist.pop_back_val();
936 auto *CurValue = findValueOrDie(Node);
George Burgess IVab03af22015-03-10 02:58:15 +0000937 if (canSkipAddingToSets(CurValue))
Hal Finkel7529c552014-09-02 21:43:13 +0000938 continue;
939
940 for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
941 auto Weight = std::get<0>(EdgeTuple);
942 auto Label = Weight.first;
943 auto &OtherNode = std::get<1>(EdgeTuple);
944 auto *OtherValue = findValueOrDie(OtherNode);
945
George Burgess IVab03af22015-03-10 02:58:15 +0000946 if (canSkipAddingToSets(OtherValue))
Hal Finkel7529c552014-09-02 21:43:13 +0000947 continue;
948
949 bool Added;
950 switch (directionOfEdgeType(Label)) {
951 case Level::Above:
952 Added = Builder.addAbove(CurValue, OtherValue);
953 break;
954 case Level::Below:
955 Added = Builder.addBelow(CurValue, OtherValue);
956 break;
957 case Level::Same:
958 Added = Builder.addWith(CurValue, OtherValue);
959 break;
960 }
961
George Burgess IVb54a8d622015-03-10 02:40:06 +0000962 auto Aliasing = Weight.second;
963 if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
964 Aliasing.set(*MaybeCurIndex);
965 if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
966 Aliasing.set(*MaybeOtherIndex);
967 Builder.noteAttributes(CurValue, Aliasing);
968 Builder.noteAttributes(OtherValue, Aliasing);
969
970 if (Added)
Hal Finkel7529c552014-09-02 21:43:13 +0000971 Worklist.push_back(OtherNode);
Hal Finkel7529c552014-09-02 21:43:13 +0000972 }
973 }
974 }
975
976 // There are times when we end up with parameters not in our graph (i.e. if
977 // it's only used as the condition of a branch). Other bits of code depend on
978 // things that were present during construction being present in the graph.
979 // So, we add all present arguments here.
980 for (auto &Arg : Fn->args()) {
George Burgess IVab03af22015-03-10 02:58:15 +0000981 if (!Builder.add(&Arg))
982 continue;
983
984 auto Attrs = valueToAttrIndex(&Arg);
985 if (Attrs.hasValue())
986 Builder.noteAttributes(&Arg, *Attrs);
Hal Finkel7529c552014-09-02 21:43:13 +0000987 }
988
Hal Finkel85f26922014-09-03 00:06:47 +0000989 return FunctionInfo(Builder.build(), std::move(ReturnedValues));
Hal Finkel7529c552014-09-02 21:43:13 +0000990}
991
Chandler Carruth7b560d42015-09-09 17:55:00 +0000992void CFLAAResult::scan(Function *Fn) {
Hal Finkel8d1590d2014-09-02 22:52:30 +0000993 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
Hal Finkel7529c552014-09-02 21:43:13 +0000994 (void)InsertPair;
995 assert(InsertPair.second &&
996 "Trying to scan a function that has already been cached");
997
Chandler Carruth8b046a42015-08-14 02:42:20 +0000998 FunctionInfo Info(buildSetsFrom(Fn));
Hal Finkel7529c552014-09-02 21:43:13 +0000999 Cache[Fn] = std::move(Info);
1000 Handles.push_front(FunctionHandle(Fn, this));
1001}
1002
Chandler Carruth7b560d42015-09-09 17:55:00 +00001003void CFLAAResult::evict(Function *Fn) { Cache.erase(Fn); }
Chandler Carruth8b046a42015-08-14 02:42:20 +00001004
1005/// \brief Ensures that the given function is available in the cache.
1006/// Returns the appropriate entry from the cache.
Chandler Carruth7b560d42015-09-09 17:55:00 +00001007const Optional<CFLAAResult::FunctionInfo> &
1008CFLAAResult::ensureCached(Function *Fn) {
Chandler Carruth8b046a42015-08-14 02:42:20 +00001009 auto Iter = Cache.find(Fn);
1010 if (Iter == Cache.end()) {
1011 scan(Fn);
1012 Iter = Cache.find(Fn);
1013 assert(Iter != Cache.end());
1014 assert(Iter->second.hasValue());
1015 }
1016 return Iter->second;
1017}
1018
Chandler Carruth7b560d42015-09-09 17:55:00 +00001019AliasResult CFLAAResult::query(const MemoryLocation &LocA,
1020 const MemoryLocation &LocB) {
Hal Finkel7529c552014-09-02 21:43:13 +00001021 auto *ValA = const_cast<Value *>(LocA.Ptr);
1022 auto *ValB = const_cast<Value *>(LocB.Ptr);
1023
1024 Function *Fn = nullptr;
1025 auto MaybeFnA = parentFunctionOfValue(ValA);
1026 auto MaybeFnB = parentFunctionOfValue(ValB);
1027 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
George Burgess IV33305e72015-02-12 03:07:07 +00001028 // The only times this is known to happen are when globals + InlineAsm
1029 // are involved
1030 DEBUG(dbgs() << "CFLAA: could not extract parent function information.\n");
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001031 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001032 }
1033
1034 if (MaybeFnA.hasValue()) {
1035 Fn = *MaybeFnA;
1036 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
1037 "Interprocedural queries not supported");
1038 } else {
1039 Fn = *MaybeFnB;
1040 }
1041
1042 assert(Fn != nullptr);
1043 auto &MaybeInfo = ensureCached(Fn);
1044 assert(MaybeInfo.hasValue());
1045
1046 auto &Sets = MaybeInfo->Sets;
1047 auto MaybeA = Sets.find(ValA);
1048 if (!MaybeA.hasValue())
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001049 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001050
1051 auto MaybeB = Sets.find(ValB);
1052 if (!MaybeB.hasValue())
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001053 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001054
1055 auto SetA = *MaybeA;
1056 auto SetB = *MaybeB;
Hal Finkel7529c552014-09-02 21:43:13 +00001057 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
1058 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
George Burgess IV33305e72015-02-12 03:07:07 +00001059
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001060 // Stratified set attributes are used as markets to signify whether a member
George Burgess IV33305e72015-02-12 03:07:07 +00001061 // of a StratifiedSet (or a member of a set above the current set) has
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001062 // interacted with either arguments or globals. "Interacted with" meaning
George Burgess IV33305e72015-02-12 03:07:07 +00001063 // its value may be different depending on the value of an argument or
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001064 // global. The thought behind this is that, because arguments and globals
1065 // may alias each other, if AttrsA and AttrsB have touched args/globals,
George Burgess IV33305e72015-02-12 03:07:07 +00001066 // we must conservatively say that they alias. However, if at least one of
1067 // the sets has no values that could legally be altered by changing the value
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001068 // of an argument or global, then we don't have to be as conservative.
1069 if (AttrsA.any() && AttrsB.any())
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001070 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001071
Daniel Berlin16f7a522015-01-26 17:31:17 +00001072 // We currently unify things even if the accesses to them may not be in
1073 // bounds, so we can't return partial alias here because we don't
1074 // know whether the pointer is really within the object or not.
1075 // IE Given an out of bounds GEP and an alloca'd pointer, we may
1076 // unify the two. We can't return partial alias for this case.
1077 // Since we do not currently track enough information to
1078 // differentiate
1079
1080 if (SetA.Index == SetB.Index)
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001081 return MayAlias;
Daniel Berlin16f7a522015-01-26 17:31:17 +00001082
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001083 return NoAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001084}
Mehdi Amini46a43552015-03-04 18:43:29 +00001085
Chandler Carruth7b560d42015-09-09 17:55:00 +00001086CFLAAResult CFLAA::run(Function &F, AnalysisManager<Function> *AM) {
1087 return CFLAAResult(AM->getResult<TargetLibraryAnalysis>(F));
1088}
1089
1090char CFLAA::PassID;
1091
1092char CFLAAWrapperPass::ID = 0;
1093INITIALIZE_PASS_BEGIN(CFLAAWrapperPass, "cfl-aa", "CFL-Based Alias Analysis",
1094 false, true)
1095INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1096INITIALIZE_PASS_END(CFLAAWrapperPass, "cfl-aa", "CFL-Based Alias Analysis",
1097 false, true)
1098
1099ImmutablePass *llvm::createCFLAAWrapperPass() { return new CFLAAWrapperPass(); }
1100
1101CFLAAWrapperPass::CFLAAWrapperPass() : ImmutablePass(ID) {
1102 initializeCFLAAWrapperPassPass(*PassRegistry::getPassRegistry());
1103}
1104
1105bool CFLAAWrapperPass::doInitialization(Module &M) {
1106 Result.reset(
1107 new CFLAAResult(getAnalysis<TargetLibraryInfoWrapperPass>().getTLI()));
1108 return false;
1109}
1110
1111bool CFLAAWrapperPass::doFinalization(Module &M) {
1112 Result.reset();
1113 return false;
1114}
1115
1116void CFLAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1117 AU.setPreservesAll();
1118 AU.addRequired<TargetLibraryInfoWrapperPass>();
Mehdi Amini46a43552015-03-04 18:43:29 +00001119}