blob: 82fbfe06aee931867945c081870b52747e98e884 [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
17// location. The "actions" can be one of Dereference, Reference, Assign, or
18// Assign.
19//
20// Two variables are considered as aliasing iff you can reach one value's node
21// from the other value's node and the language formed by concatenating all of
22// the edge labels (actions) conforms to a context-free grammar.
23//
24// Because this algorithm requires a graph search on each query, we execute the
25// algorithm outlined in "Fast algorithms..." (mentioned above)
26// in order to transform the graph into sets of variables that may alias in
27// ~nlogn time (n = number of variables.), which makes queries take constant
28// time.
29//===----------------------------------------------------------------------===//
30
31#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"
Hal Finkel7529c552014-09-02 21:43:13 +000036#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000037#include "llvm/Analysis/Passes.h"
Hal Finkel7529c552014-09-02 21:43:13 +000038#include "llvm/IR/Constants.h"
39#include "llvm/IR/Function.h"
Hal Finkel7529c552014-09-02 21:43:13 +000040#include "llvm/IR/InstVisitor.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000041#include "llvm/IR/Instructions.h"
Hal Finkel7529c552014-09-02 21:43:13 +000042#include "llvm/IR/ValueHandle.h"
43#include "llvm/Pass.h"
44#include "llvm/Support/Allocator.h"
Hal Finkel7d7087c2014-09-02 22:13:00 +000045#include "llvm/Support/Compiler.h"
George Burgess IV33305e72015-02-12 03:07:07 +000046#include "llvm/Support/Debug.h"
Hal Finkel7529c552014-09-02 21:43:13 +000047#include "llvm/Support/ErrorHandling.h"
48#include <algorithm>
49#include <cassert>
50#include <forward_list>
51#include <tuple>
52
53using namespace llvm;
54
George Burgess IV33305e72015-02-12 03:07:07 +000055#define DEBUG_TYPE "cfl-aa"
56
Hal Finkel7529c552014-09-02 21:43:13 +000057// Try to go from a Value* to a Function*. Never returns nullptr.
58static Optional<Function *> parentFunctionOfValue(Value *);
59
60// Returns possible functions called by the Inst* into the given
61// SmallVectorImpl. Returns true if targets found, false otherwise.
62// This is templated because InvokeInst/CallInst give us the same
63// set of functions that we care about, and I don't like repeating
64// myself.
65template <typename Inst>
66static bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &);
67
68// Some instructions need to have their users tracked. Instructions like
69// `add` require you to get the users of the Instruction* itself, other
70// instructions like `store` require you to get the users of the first
71// operand. This function gets the "proper" value to track for each
72// type of instruction we support.
73static Optional<Value *> getTargetValue(Instruction *);
74
75// There are certain instructions (i.e. FenceInst, etc.) that we ignore.
76// This notes that we should ignore those.
77static bool hasUsefulEdges(Instruction *);
78
Hal Finkel1ae325f2014-09-02 23:50:01 +000079const StratifiedIndex StratifiedLink::SetSentinel =
80 std::numeric_limits<StratifiedIndex>::max();
81
Hal Finkel7529c552014-09-02 21:43:13 +000082namespace {
83// StratifiedInfo Attribute things.
84typedef unsigned StratifiedAttr;
Hal Finkel7d7087c2014-09-02 22:13:00 +000085LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
86LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
87LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
88LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 2;
89LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
90LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
Hal Finkel7529c552014-09-02 21:43:13 +000091
Hal Finkel7d7087c2014-09-02 22:13:00 +000092LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
93LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
Hal Finkel7529c552014-09-02 21:43:13 +000094
95// \brief StratifiedSets call for knowledge of "direction", so this is how we
96// represent that locally.
97enum class Level { Same, Above, Below };
98
99// \brief Edges can be one of four "weights" -- each weight must have an inverse
100// weight (Assign has Assign; Reference has Dereference).
101enum class EdgeType {
102 // The weight assigned when assigning from or to a value. For example, in:
103 // %b = getelementptr %a, 0
104 // ...The relationships are %b assign %a, and %a assign %b. This used to be
105 // two edges, but having a distinction bought us nothing.
106 Assign,
107
108 // The edge used when we have an edge going from some handle to a Value.
109 // Examples of this include:
110 // %b = load %a (%b Dereference %a)
111 // %b = extractelement %a, 0 (%a Dereference %b)
112 Dereference,
113
114 // The edge used when our edge goes from a value to a handle that may have
115 // contained it at some point. Examples:
116 // %b = load %a (%a Reference %b)
117 // %b = extractelement %a, 0 (%b Reference %a)
118 Reference
119};
120
121// \brief Encodes the notion of a "use"
122struct Edge {
123 // \brief Which value the edge is coming from
124 Value *From;
125
126 // \brief Which value the edge is pointing to
127 Value *To;
128
129 // \brief Edge weight
130 EdgeType Weight;
131
132 // \brief Whether we aliased any external values along the way that may be
133 // invisible to the analysis (i.e. landingpad for exceptions, calls for
134 // interprocedural analysis, etc.)
135 StratifiedAttrs AdditionalAttrs;
136
137 Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
138 : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
139};
140
141// \brief Information we have about a function and would like to keep around
142struct FunctionInfo {
143 StratifiedSets<Value *> Sets;
144 // Lots of functions have < 4 returns. Adjust as necessary.
145 SmallVector<Value *, 4> ReturnedValues;
Hal Finkel85f26922014-09-03 00:06:47 +0000146
147 FunctionInfo(StratifiedSets<Value *> &&S,
148 SmallVector<Value *, 4> &&RV)
149 : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
Hal Finkel7529c552014-09-02 21:43:13 +0000150};
151
152struct CFLAliasAnalysis;
153
154struct FunctionHandle : public CallbackVH {
155 FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
156 : CallbackVH(Fn), CFLAA(CFLAA) {
157 assert(Fn != nullptr);
158 assert(CFLAA != nullptr);
159 }
160
161 virtual ~FunctionHandle() {}
162
David Blaikie711cd9c2014-11-14 19:06:36 +0000163 void deleted() override { removeSelfFromCache(); }
164 void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
Hal Finkel7529c552014-09-02 21:43:13 +0000165
166private:
167 CFLAliasAnalysis *CFLAA;
168
169 void removeSelfFromCache();
170};
171
172struct CFLAliasAnalysis : public ImmutablePass, public AliasAnalysis {
173private:
174 /// \brief Cached mapping of Functions to their StratifiedSets.
175 /// If a function's sets are currently being built, it is marked
176 /// in the cache as an Optional without a value. This way, if we
177 /// have any kind of recursion, it is discernable from a function
178 /// that simply has empty sets.
179 DenseMap<Function *, Optional<FunctionInfo>> Cache;
180 std::forward_list<FunctionHandle> Handles;
181
182public:
183 static char ID;
184
185 CFLAliasAnalysis() : ImmutablePass(ID) {
186 initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
187 }
188
189 virtual ~CFLAliasAnalysis() {}
190
Argyrios Kyrtzidis0b9f5502014-10-01 21:00:44 +0000191 void getAnalysisUsage(AnalysisUsage &AU) const override {
Hal Finkel7529c552014-09-02 21:43:13 +0000192 AliasAnalysis::getAnalysisUsage(AU);
193 }
194
195 void *getAdjustedAnalysisPointer(const void *ID) override {
196 if (ID == &AliasAnalysis::ID)
197 return (AliasAnalysis *)this;
198 return this;
199 }
200
201 /// \brief Inserts the given Function into the cache.
202 void scan(Function *Fn);
203
204 void evict(Function *Fn) { Cache.erase(Fn); }
205
206 /// \brief Ensures that the given function is available in the cache.
207 /// Returns the appropriate entry from the cache.
208 const Optional<FunctionInfo> &ensureCached(Function *Fn) {
209 auto Iter = Cache.find(Fn);
210 if (Iter == Cache.end()) {
211 scan(Fn);
212 Iter = Cache.find(Fn);
213 assert(Iter != Cache.end());
214 assert(Iter->second.hasValue());
215 }
216 return Iter->second;
217 }
218
219 AliasResult query(const Location &LocA, const Location &LocB);
220
221 AliasResult alias(const Location &LocA, const Location &LocB) override {
222 if (LocA.Ptr == LocB.Ptr) {
223 if (LocA.Size == LocB.Size) {
224 return MustAlias;
225 } else {
226 return PartialAlias;
227 }
228 }
229
230 // Comparisons between global variables and other constants should be
231 // handled by BasicAA.
232 if (isa<Constant>(LocA.Ptr) && isa<Constant>(LocB.Ptr)) {
Daniel Berlin8f10e382015-01-26 17:30:39 +0000233 return AliasAnalysis::alias(LocA, LocB);
Hal Finkel7529c552014-09-02 21:43:13 +0000234 }
George Burgess IV33305e72015-02-12 03:07:07 +0000235
Daniel Berlin8f10e382015-01-26 17:30:39 +0000236 AliasResult QueryResult = query(LocA, LocB);
237 if (QueryResult == MayAlias)
238 return AliasAnalysis::alias(LocA, LocB);
Hal Finkel7529c552014-09-02 21:43:13 +0000239
Daniel Berlin8f10e382015-01-26 17:30:39 +0000240 return QueryResult;
Hal Finkel7529c552014-09-02 21:43:13 +0000241 }
242
243 void initializePass() override { InitializeAliasAnalysis(this); }
244};
245
246void FunctionHandle::removeSelfFromCache() {
247 assert(CFLAA != nullptr);
248 auto *Val = getValPtr();
249 CFLAA->evict(cast<Function>(Val));
250 setValPtr(nullptr);
251}
252
253// \brief Gets the edges our graph should have, based on an Instruction*
254class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
255 CFLAliasAnalysis &AA;
256 SmallVectorImpl<Edge> &Output;
257
258public:
259 GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
260 : AA(AA), Output(Output) {}
261
262 void visitInstruction(Instruction &) {
263 llvm_unreachable("Unsupported instruction encountered");
264 }
265
266 void visitCastInst(CastInst &Inst) {
Hal Finkel8d1590d2014-09-02 22:52:30 +0000267 Output.push_back(Edge(&Inst, Inst.getOperand(0), EdgeType::Assign,
268 AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000269 }
270
271 void visitBinaryOperator(BinaryOperator &Inst) {
272 auto *Op1 = Inst.getOperand(0);
273 auto *Op2 = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000274 Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
275 Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000276 }
277
278 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
279 auto *Ptr = Inst.getPointerOperand();
280 auto *Val = Inst.getNewValOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000281 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000282 }
283
284 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
285 auto *Ptr = Inst.getPointerOperand();
286 auto *Val = Inst.getValOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000287 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000288 }
289
290 void visitPHINode(PHINode &Inst) {
291 for (unsigned I = 0, E = Inst.getNumIncomingValues(); I != E; ++I) {
292 Value *Val = Inst.getIncomingValue(I);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000293 Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000294 }
295 }
296
297 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
298 auto *Op = Inst.getPointerOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000299 Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000300 for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
Hal Finkel8d1590d2014-09-02 22:52:30 +0000301 Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000302 }
303
304 void visitSelectInst(SelectInst &Inst) {
Daniel Berlin16f7a522015-01-26 17:31:17 +0000305 // Condition is not processed here (The actual statement producing
306 // the condition result is processed elsewhere). For select, the
307 // condition is evaluated, but not loaded, stored, or assigned
308 // simply as a result of being the condition of a select.
309
Hal Finkel7529c552014-09-02 21:43:13 +0000310 auto *TrueVal = Inst.getTrueValue();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000311 Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000312 auto *FalseVal = Inst.getFalseValue();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000313 Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000314 }
315
316 void visitAllocaInst(AllocaInst &) {}
317
318 void visitLoadInst(LoadInst &Inst) {
319 auto *Ptr = Inst.getPointerOperand();
320 auto *Val = &Inst;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000321 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000322 }
323
324 void visitStoreInst(StoreInst &Inst) {
325 auto *Ptr = Inst.getPointerOperand();
326 auto *Val = Inst.getValueOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000327 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000328 }
329
Hal Finkeldb5f86a2014-10-14 20:51:26 +0000330 void visitVAArgInst(VAArgInst &Inst) {
331 // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
332 // two things:
333 // 1. Loads a value from *((T*)*Ptr).
334 // 2. Increments (stores to) *Ptr by some target-specific amount.
335 // For now, we'll handle this like a landingpad instruction (by placing the
336 // result in its own group, and having that group alias externals).
337 auto *Val = &Inst;
338 Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll));
339 }
340
Hal Finkel7529c552014-09-02 21:43:13 +0000341 static bool isFunctionExternal(Function *Fn) {
342 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
343 }
344
345 // Gets whether the sets at Index1 above, below, or equal to the sets at
346 // Index2. Returns None if they are not in the same set chain.
347 static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
348 StratifiedIndex Index1,
349 StratifiedIndex Index2) {
350 if (Index1 == Index2)
351 return Level::Same;
352
353 const auto *Current = &Sets.getLink(Index1);
354 while (Current->hasBelow()) {
355 if (Current->Below == Index2)
356 return Level::Below;
357 Current = &Sets.getLink(Current->Below);
358 }
359
360 Current = &Sets.getLink(Index1);
361 while (Current->hasAbove()) {
362 if (Current->Above == Index2)
363 return Level::Above;
364 Current = &Sets.getLink(Current->Above);
365 }
366
367 return NoneType();
368 }
369
370 bool
371 tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
372 Value *FuncValue,
373 const iterator_range<User::op_iterator> &Args) {
Hal Finkelca616ac2014-09-02 23:29:48 +0000374 const unsigned ExpectedMaxArgs = 8;
375 const unsigned MaxSupportedArgs = 50;
Hal Finkel7529c552014-09-02 21:43:13 +0000376 assert(Fns.size() > 0);
377
378 // I put this here to give us an upper bound on time taken by IPA. Is it
379 // really (realistically) needed? Keep in mind that we do have an n^2 algo.
Hal Finkelca616ac2014-09-02 23:29:48 +0000380 if (std::distance(Args.begin(), Args.end()) > (int) MaxSupportedArgs)
Hal Finkel7529c552014-09-02 21:43:13 +0000381 return false;
382
383 // Exit early if we'll fail anyway
384 for (auto *Fn : Fns) {
385 if (isFunctionExternal(Fn) || Fn->isVarArg())
386 return false;
387 auto &MaybeInfo = AA.ensureCached(Fn);
388 if (!MaybeInfo.hasValue())
389 return false;
390 }
391
392 SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
393 SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
394 for (auto *Fn : Fns) {
395 auto &Info = *AA.ensureCached(Fn);
396 auto &Sets = Info.Sets;
397 auto &RetVals = Info.ReturnedValues;
398
399 Parameters.clear();
400 for (auto &Param : Fn->args()) {
401 auto MaybeInfo = Sets.find(&Param);
402 // Did a new parameter somehow get added to the function/slip by?
403 if (!MaybeInfo.hasValue())
404 return false;
405 Parameters.push_back(*MaybeInfo);
406 }
407
408 // Adding an edge from argument -> return value for each parameter that
409 // may alias the return value
410 for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
411 auto &ParamInfo = Parameters[I];
412 auto &ArgVal = Arguments[I];
413 bool AddEdge = false;
414 StratifiedAttrs Externals;
415 for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
416 auto MaybeInfo = Sets.find(RetVals[X]);
417 if (!MaybeInfo.hasValue())
418 return false;
419
420 auto &RetInfo = *MaybeInfo;
421 auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
422 auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
423 auto MaybeRelation =
424 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
425 if (MaybeRelation.hasValue()) {
426 AddEdge = true;
427 Externals |= RetAttrs | ParamAttrs;
428 }
429 }
430 if (AddEdge)
Hal Finkelca616ac2014-09-02 23:29:48 +0000431 Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
432 StratifiedAttrs().flip()));
Hal Finkel7529c552014-09-02 21:43:13 +0000433 }
434
435 if (Parameters.size() != Arguments.size())
436 return false;
437
438 // Adding edges between arguments for arguments that may end up aliasing
439 // each other. This is necessary for functions such as
440 // void foo(int** a, int** b) { *a = *b; }
441 // (Technically, the proper sets for this would be those below
442 // Arguments[I] and Arguments[X], but our algorithm will produce
443 // extremely similar, and equally correct, results either way)
444 for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
445 auto &MainVal = Arguments[I];
446 auto &MainInfo = Parameters[I];
447 auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
448 for (unsigned X = I + 1; X != E; ++X) {
449 auto &SubInfo = Parameters[X];
450 auto &SubVal = Arguments[X];
451 auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
452 auto MaybeRelation =
453 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
454
455 if (!MaybeRelation.hasValue())
456 continue;
457
458 auto NewAttrs = SubAttrs | MainAttrs;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000459 Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
Hal Finkel7529c552014-09-02 21:43:13 +0000460 }
461 }
462 }
463 return true;
464 }
465
466 template <typename InstT> void visitCallLikeInst(InstT &Inst) {
467 SmallVector<Function *, 4> Targets;
468 if (getPossibleTargets(&Inst, Targets)) {
469 if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
470 return;
471 // Cleanup from interprocedural analysis
472 Output.clear();
473 }
474
475 for (Value *V : Inst.arg_operands())
Hal Finkel8d1590d2014-09-02 22:52:30 +0000476 Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
Hal Finkel7529c552014-09-02 21:43:13 +0000477 }
478
479 void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
480
481 void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
482
483 // Because vectors/aggregates are immutable and unaddressable,
484 // there's nothing we can do to coax a value out of them, other
485 // than calling Extract{Element,Value}. We can effectively treat
486 // them as pointers to arbitrary memory locations we can store in
487 // and load from.
488 void visitExtractElementInst(ExtractElementInst &Inst) {
489 auto *Ptr = Inst.getVectorOperand();
490 auto *Val = &Inst;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000491 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000492 }
493
494 void visitInsertElementInst(InsertElementInst &Inst) {
495 auto *Vec = Inst.getOperand(0);
496 auto *Val = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000497 Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
498 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000499 }
500
501 void visitLandingPadInst(LandingPadInst &Inst) {
502 // Exceptions come from "nowhere", from our analysis' perspective.
503 // So we place the instruction its own group, noting that said group may
504 // alias externals
Hal Finkel8d1590d2014-09-02 22:52:30 +0000505 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
Hal Finkel7529c552014-09-02 21:43:13 +0000506 }
507
508 void visitInsertValueInst(InsertValueInst &Inst) {
509 auto *Agg = Inst.getOperand(0);
510 auto *Val = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000511 Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
512 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000513 }
514
515 void visitExtractValueInst(ExtractValueInst &Inst) {
516 auto *Ptr = Inst.getAggregateOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000517 Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000518 }
519
520 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
521 auto *From1 = Inst.getOperand(0);
522 auto *From2 = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000523 Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
524 Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000525 }
526};
527
528// For a given instruction, we need to know which Value* to get the
529// users of in order to build our graph. In some cases (i.e. add),
530// we simply need the Instruction*. In other cases (i.e. store),
531// finding the users of the Instruction* is useless; we need to find
532// the users of the first operand. This handles determining which
533// value to follow for us.
534//
535// Note: we *need* to keep this in sync with GetEdgesVisitor. Add
536// something to GetEdgesVisitor, add it here -- remove something from
537// GetEdgesVisitor, remove it here.
538class GetTargetValueVisitor
539 : public InstVisitor<GetTargetValueVisitor, Value *> {
540public:
541 Value *visitInstruction(Instruction &Inst) { return &Inst; }
542
543 Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
544
545 Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
546 return Inst.getPointerOperand();
547 }
548
549 Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
550 return Inst.getPointerOperand();
551 }
552
553 Value *visitInsertElementInst(InsertElementInst &Inst) {
554 return Inst.getOperand(0);
555 }
556
557 Value *visitInsertValueInst(InsertValueInst &Inst) {
558 return Inst.getAggregateOperand();
559 }
560};
561
562// Set building requires a weighted bidirectional graph.
563template <typename EdgeTypeT> class WeightedBidirectionalGraph {
564public:
565 typedef std::size_t Node;
566
567private:
Hal Finkelca616ac2014-09-02 23:29:48 +0000568 const static Node StartNode = Node(0);
Hal Finkel7529c552014-09-02 21:43:13 +0000569
570 struct Edge {
571 EdgeTypeT Weight;
572 Node Other;
573
Hal Finkelca616ac2014-09-02 23:29:48 +0000574 Edge(const EdgeTypeT &W, const Node &N)
575 : Weight(W), Other(N) {}
576
Hal Finkel7529c552014-09-02 21:43:13 +0000577 bool operator==(const Edge &E) const {
578 return Weight == E.Weight && Other == E.Other;
579 }
580
581 bool operator!=(const Edge &E) const { return !operator==(E); }
582 };
583
584 struct NodeImpl {
585 std::vector<Edge> Edges;
586 };
587
588 std::vector<NodeImpl> NodeImpls;
589
590 bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
591
592 const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
593 NodeImpl &getNode(Node N) { return NodeImpls[N]; }
594
595public:
596 // ----- Various Edge iterators for the graph ----- //
597
598 // \brief Iterator for edges. Because this graph is bidirected, we don't
599 // allow modificaiton of the edges using this iterator. Additionally, the
600 // iterator becomes invalid if you add edges to or from the node you're
601 // getting the edges of.
602 struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
603 std::tuple<EdgeTypeT, Node *>> {
604 EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
605 : Current(Iter) {}
606
607 EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
608
609 EdgeIterator &operator++() {
610 ++Current;
611 return *this;
612 }
613
614 EdgeIterator operator++(int) {
615 EdgeIterator Copy(Current);
616 operator++();
617 return Copy;
618 }
619
620 std::tuple<EdgeTypeT, Node> &operator*() {
621 Store = std::make_tuple(Current->Weight, Current->Other);
622 return Store;
623 }
624
625 bool operator==(const EdgeIterator &Other) const {
626 return Current == Other.Current;
627 }
628
629 bool operator!=(const EdgeIterator &Other) const {
630 return !operator==(Other);
631 }
632
633 private:
634 typename std::vector<Edge>::const_iterator Current;
635 std::tuple<EdgeTypeT, Node> Store;
636 };
637
638 // Wrapper for EdgeIterator with begin()/end() calls.
639 struct EdgeIterable {
640 EdgeIterable(const std::vector<Edge> &Edges)
641 : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
642
643 EdgeIterator begin() { return EdgeIterator(BeginIter); }
644
645 EdgeIterator end() { return EdgeIterator(EndIter); }
646
647 private:
648 typename std::vector<Edge>::const_iterator BeginIter;
649 typename std::vector<Edge>::const_iterator EndIter;
650 };
651
652 // ----- Actual graph-related things ----- //
653
Hal Finkelca616ac2014-09-02 23:29:48 +0000654 WeightedBidirectionalGraph() {}
Hal Finkel7529c552014-09-02 21:43:13 +0000655
656 WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
657 : NodeImpls(std::move(Other.NodeImpls)) {}
658
659 WeightedBidirectionalGraph<EdgeTypeT> &
660 operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
661 NodeImpls = std::move(Other.NodeImpls);
662 return *this;
663 }
664
665 Node addNode() {
666 auto Index = NodeImpls.size();
667 auto NewNode = Node(Index);
668 NodeImpls.push_back(NodeImpl());
669 return NewNode;
670 }
671
672 void addEdge(Node From, Node To, const EdgeTypeT &Weight,
673 const EdgeTypeT &ReverseWeight) {
674 assert(inbounds(From));
675 assert(inbounds(To));
676 auto &FromNode = getNode(From);
677 auto &ToNode = getNode(To);
Hal Finkelca616ac2014-09-02 23:29:48 +0000678 FromNode.Edges.push_back(Edge(Weight, To));
679 ToNode.Edges.push_back(Edge(ReverseWeight, From));
Hal Finkel7529c552014-09-02 21:43:13 +0000680 }
681
682 EdgeIterable edgesFor(const Node &N) const {
683 const auto &Node = getNode(N);
684 return EdgeIterable(Node.Edges);
685 }
686
687 bool empty() const { return NodeImpls.empty(); }
688 std::size_t size() const { return NodeImpls.size(); }
689
690 // \brief Gets an arbitrary node in the graph as a starting point for
691 // traversal.
692 Node getEntryNode() {
693 assert(inbounds(StartNode));
694 return StartNode;
695 }
696};
697
698typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
699typedef DenseMap<Value *, GraphT::Node> NodeMapT;
700}
701
702// -- Setting up/registering CFLAA pass -- //
703char CFLAliasAnalysis::ID = 0;
704
705INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
706 "CFL-Based AA implementation", false, true, false)
707
708ImmutablePass *llvm::createCFLAliasAnalysisPass() {
709 return new CFLAliasAnalysis();
710}
711
712//===----------------------------------------------------------------------===//
713// Function declarations that require types defined in the namespace above
714//===----------------------------------------------------------------------===//
715
716// Given an argument number, returns the appropriate Attr index to set.
717static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
718
719// Given a Value, potentially return which AttrIndex it maps to.
720static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
721
722// Gets the inverse of a given EdgeType.
723static EdgeType flipWeight(EdgeType);
724
725// Gets edges of the given Instruction*, writing them to the SmallVector*.
726static void argsToEdges(CFLAliasAnalysis &, Instruction *,
727 SmallVectorImpl<Edge> &);
728
729// Gets the "Level" that one should travel in StratifiedSets
730// given an EdgeType.
731static Level directionOfEdgeType(EdgeType);
732
733// Builds the graph needed for constructing the StratifiedSets for the
734// given function
735static void buildGraphFrom(CFLAliasAnalysis &, Function *,
736 SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
737
738// Builds the graph + StratifiedSets for a function.
739static FunctionInfo buildSetsFrom(CFLAliasAnalysis &, Function *);
740
741static Optional<Function *> parentFunctionOfValue(Value *Val) {
742 if (auto *Inst = dyn_cast<Instruction>(Val)) {
743 auto *Bb = Inst->getParent();
744 return Bb->getParent();
745 }
746
747 if (auto *Arg = dyn_cast<Argument>(Val))
748 return Arg->getParent();
749 return NoneType();
750}
751
752template <typename Inst>
753static bool getPossibleTargets(Inst *Call,
754 SmallVectorImpl<Function *> &Output) {
755 if (auto *Fn = Call->getCalledFunction()) {
756 Output.push_back(Fn);
757 return true;
758 }
759
760 // TODO: If the call is indirect, we might be able to enumerate all potential
761 // targets of the call and return them, rather than just failing.
762 return false;
763}
764
765static Optional<Value *> getTargetValue(Instruction *Inst) {
766 GetTargetValueVisitor V;
767 return V.visit(Inst);
768}
769
770static bool hasUsefulEdges(Instruction *Inst) {
771 bool IsNonInvokeTerminator =
772 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
773 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
774}
775
776static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
777 if (isa<GlobalValue>(Val))
778 return AttrGlobalIndex;
779
780 if (auto *Arg = dyn_cast<Argument>(Val))
Daniel Berlin16f7a522015-01-26 17:31:17 +0000781 // Only pointer arguments should have the argument attribute,
782 // because things can't escape through scalars without us seeing a
783 // cast, and thus, interaction with them doesn't matter.
784 if (!Arg->hasNoAliasAttr() && Arg->getType()->isPointerTy())
Hal Finkel7529c552014-09-02 21:43:13 +0000785 return argNumberToAttrIndex(Arg->getArgNo());
786 return NoneType();
787}
788
789static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
George Burgess IV3c898c22015-01-21 16:37:21 +0000790 if (ArgNum >= AttrMaxNumArgs)
Hal Finkel7529c552014-09-02 21:43:13 +0000791 return AttrAllIndex;
792 return ArgNum + AttrFirstArgIndex;
793}
794
795static EdgeType flipWeight(EdgeType Initial) {
796 switch (Initial) {
797 case EdgeType::Assign:
798 return EdgeType::Assign;
799 case EdgeType::Dereference:
800 return EdgeType::Reference;
801 case EdgeType::Reference:
802 return EdgeType::Dereference;
803 }
804 llvm_unreachable("Incomplete coverage of EdgeType enum");
805}
806
807static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
808 SmallVectorImpl<Edge> &Output) {
809 GetEdgesVisitor v(Analysis, Output);
810 v.visit(Inst);
811}
812
813static Level directionOfEdgeType(EdgeType Weight) {
814 switch (Weight) {
815 case EdgeType::Reference:
816 return Level::Above;
817 case EdgeType::Dereference:
818 return Level::Below;
819 case EdgeType::Assign:
820 return Level::Same;
821 }
822 llvm_unreachable("Incomplete switch coverage");
823}
824
825// Aside: We may remove graph construction entirely, because it doesn't really
826// buy us much that we don't already have. I'd like to add interprocedural
827// analysis prior to this however, in case that somehow requires the graph
828// produced by this for efficient execution
829static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
830 SmallVectorImpl<Value *> &ReturnedValues,
831 NodeMapT &Map, GraphT &Graph) {
832 const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
833 auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
834 auto &Iter = Pair.first;
835 if (Pair.second) {
836 auto NewNode = Graph.addNode();
837 Iter->second = NewNode;
838 }
839 return Iter->second;
840 };
841
842 SmallVector<Edge, 8> Edges;
843 for (auto &Bb : Fn->getBasicBlockList()) {
844 for (auto &Inst : Bb.getInstList()) {
845 // We don't want the edges of most "return" instructions, but we *do* want
846 // to know what can be returned.
847 if (auto *Ret = dyn_cast<ReturnInst>(&Inst))
848 ReturnedValues.push_back(Ret);
849
850 if (!hasUsefulEdges(&Inst))
851 continue;
852
853 Edges.clear();
854 argsToEdges(Analysis, &Inst, Edges);
855
856 // In the case of an unused alloca (or similar), edges may be empty. Note
857 // that it exists so we can potentially answer NoAlias.
858 if (Edges.empty()) {
859 auto MaybeVal = getTargetValue(&Inst);
860 assert(MaybeVal.hasValue());
861 auto *Target = *MaybeVal;
862 findOrInsertNode(Target);
863 continue;
864 }
865
866 for (const Edge &E : Edges) {
867 auto To = findOrInsertNode(E.To);
868 auto From = findOrInsertNode(E.From);
869 auto FlippedWeight = flipWeight(E.Weight);
870 auto Attrs = E.AdditionalAttrs;
Hal Finkel1ae325f2014-09-02 23:50:01 +0000871 Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
872 std::make_pair(FlippedWeight, Attrs));
Hal Finkel7529c552014-09-02 21:43:13 +0000873 }
874 }
875 }
876}
877
878static FunctionInfo buildSetsFrom(CFLAliasAnalysis &Analysis, Function *Fn) {
879 NodeMapT Map;
880 GraphT Graph;
881 SmallVector<Value *, 4> ReturnedValues;
882
883 buildGraphFrom(Analysis, Fn, ReturnedValues, Map, Graph);
884
885 DenseMap<GraphT::Node, Value *> NodeValueMap;
886 NodeValueMap.resize(Map.size());
887 for (const auto &Pair : Map)
Hal Finkel8d1590d2014-09-02 22:52:30 +0000888 NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
Hal Finkel7529c552014-09-02 21:43:13 +0000889
890 const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
891 auto ValIter = NodeValueMap.find(Node);
892 assert(ValIter != NodeValueMap.end());
893 return ValIter->second;
894 };
895
896 StratifiedSetsBuilder<Value *> Builder;
897
898 SmallVector<GraphT::Node, 16> Worklist;
899 for (auto &Pair : Map) {
900 Worklist.clear();
901
902 auto *Value = Pair.first;
903 Builder.add(Value);
904 auto InitialNode = Pair.second;
905 Worklist.push_back(InitialNode);
906 while (!Worklist.empty()) {
907 auto Node = Worklist.pop_back_val();
908 auto *CurValue = findValueOrDie(Node);
909 if (isa<Constant>(CurValue) && !isa<GlobalValue>(CurValue))
910 continue;
911
912 for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
913 auto Weight = std::get<0>(EdgeTuple);
914 auto Label = Weight.first;
915 auto &OtherNode = std::get<1>(EdgeTuple);
916 auto *OtherValue = findValueOrDie(OtherNode);
917
918 if (isa<Constant>(OtherValue) && !isa<GlobalValue>(OtherValue))
919 continue;
920
921 bool Added;
922 switch (directionOfEdgeType(Label)) {
923 case Level::Above:
924 Added = Builder.addAbove(CurValue, OtherValue);
925 break;
926 case Level::Below:
927 Added = Builder.addBelow(CurValue, OtherValue);
928 break;
929 case Level::Same:
930 Added = Builder.addWith(CurValue, OtherValue);
931 break;
932 }
933
934 if (Added) {
935 auto Aliasing = Weight.second;
936 if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
937 Aliasing.set(*MaybeCurIndex);
938 if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
939 Aliasing.set(*MaybeOtherIndex);
940 Builder.noteAttributes(CurValue, Aliasing);
941 Builder.noteAttributes(OtherValue, Aliasing);
942 Worklist.push_back(OtherNode);
943 }
944 }
945 }
946 }
947
948 // There are times when we end up with parameters not in our graph (i.e. if
949 // it's only used as the condition of a branch). Other bits of code depend on
950 // things that were present during construction being present in the graph.
951 // So, we add all present arguments here.
952 for (auto &Arg : Fn->args()) {
953 Builder.add(&Arg);
954 }
955
Hal Finkel85f26922014-09-03 00:06:47 +0000956 return FunctionInfo(Builder.build(), std::move(ReturnedValues));
Hal Finkel7529c552014-09-02 21:43:13 +0000957}
958
959void CFLAliasAnalysis::scan(Function *Fn) {
Hal Finkel8d1590d2014-09-02 22:52:30 +0000960 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
Hal Finkel7529c552014-09-02 21:43:13 +0000961 (void)InsertPair;
962 assert(InsertPair.second &&
963 "Trying to scan a function that has already been cached");
964
965 FunctionInfo Info(buildSetsFrom(*this, Fn));
966 Cache[Fn] = std::move(Info);
967 Handles.push_front(FunctionHandle(Fn, this));
968}
969
970AliasAnalysis::AliasResult
971CFLAliasAnalysis::query(const AliasAnalysis::Location &LocA,
972 const AliasAnalysis::Location &LocB) {
973 auto *ValA = const_cast<Value *>(LocA.Ptr);
974 auto *ValB = const_cast<Value *>(LocB.Ptr);
975
976 Function *Fn = nullptr;
977 auto MaybeFnA = parentFunctionOfValue(ValA);
978 auto MaybeFnB = parentFunctionOfValue(ValB);
979 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
George Burgess IV33305e72015-02-12 03:07:07 +0000980 // The only times this is known to happen are when globals + InlineAsm
981 // are involved
982 DEBUG(dbgs() << "CFLAA: could not extract parent function information.\n");
983 return AliasAnalysis::MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +0000984 }
985
986 if (MaybeFnA.hasValue()) {
987 Fn = *MaybeFnA;
988 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
989 "Interprocedural queries not supported");
990 } else {
991 Fn = *MaybeFnB;
992 }
993
994 assert(Fn != nullptr);
995 auto &MaybeInfo = ensureCached(Fn);
996 assert(MaybeInfo.hasValue());
997
998 auto &Sets = MaybeInfo->Sets;
999 auto MaybeA = Sets.find(ValA);
1000 if (!MaybeA.hasValue())
1001 return AliasAnalysis::MayAlias;
1002
1003 auto MaybeB = Sets.find(ValB);
1004 if (!MaybeB.hasValue())
1005 return AliasAnalysis::MayAlias;
1006
1007 auto SetA = *MaybeA;
1008 auto SetB = *MaybeB;
Hal Finkel7529c552014-09-02 21:43:13 +00001009 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
1010 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
George Burgess IV33305e72015-02-12 03:07:07 +00001011
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001012 // Stratified set attributes are used as markets to signify whether a member
George Burgess IV33305e72015-02-12 03:07:07 +00001013 // of a StratifiedSet (or a member of a set above the current set) has
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001014 // interacted with either arguments or globals. "Interacted with" meaning
George Burgess IV33305e72015-02-12 03:07:07 +00001015 // its value may be different depending on the value of an argument or
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001016 // global. The thought behind this is that, because arguments and globals
1017 // may alias each other, if AttrsA and AttrsB have touched args/globals,
George Burgess IV33305e72015-02-12 03:07:07 +00001018 // we must conservatively say that they alias. However, if at least one of
1019 // the sets has no values that could legally be altered by changing the value
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001020 // of an argument or global, then we don't have to be as conservative.
1021 if (AttrsA.any() && AttrsB.any())
1022 return AliasAnalysis::MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001023
Daniel Berlin16f7a522015-01-26 17:31:17 +00001024 // We currently unify things even if the accesses to them may not be in
1025 // bounds, so we can't return partial alias here because we don't
1026 // know whether the pointer is really within the object or not.
1027 // IE Given an out of bounds GEP and an alloca'd pointer, we may
1028 // unify the two. We can't return partial alias for this case.
1029 // Since we do not currently track enough information to
1030 // differentiate
1031
1032 if (SetA.Index == SetB.Index)
1033 return AliasAnalysis::MayAlias;
1034
Hal Finkel7529c552014-09-02 21:43:13 +00001035 return AliasAnalysis::NoAlias;
1036}