blob: db94f2868c4907ce656ea26cc77c02997f1e1907 [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"
32#include "llvm/Analysis/Passes.h"
33#include "llvm/ADT/BitVector.h"
34#include "llvm/ADT/DenseMap.h"
35#include "llvm/ADT/Optional.h"
36#include "llvm/ADT/None.h"
37#include "llvm/Analysis/AliasAnalysis.h"
38#include "llvm/IR/Constants.h"
39#include "llvm/IR/Function.h"
40#include "llvm/IR/Instructions.h"
41#include "llvm/IR/InstVisitor.h"
42#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"
Hal Finkel7529c552014-09-02 21:43:13 +000046#include "llvm/Support/ErrorHandling.h"
47#include <algorithm>
48#include <cassert>
49#include <forward_list>
50#include <tuple>
51
52using namespace llvm;
53
54// Try to go from a Value* to a Function*. Never returns nullptr.
55static Optional<Function *> parentFunctionOfValue(Value *);
56
57// Returns possible functions called by the Inst* into the given
58// SmallVectorImpl. Returns true if targets found, false otherwise.
59// This is templated because InvokeInst/CallInst give us the same
60// set of functions that we care about, and I don't like repeating
61// myself.
62template <typename Inst>
63static bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &);
64
65// Some instructions need to have their users tracked. Instructions like
66// `add` require you to get the users of the Instruction* itself, other
67// instructions like `store` require you to get the users of the first
68// operand. This function gets the "proper" value to track for each
69// type of instruction we support.
70static Optional<Value *> getTargetValue(Instruction *);
71
72// There are certain instructions (i.e. FenceInst, etc.) that we ignore.
73// This notes that we should ignore those.
74static bool hasUsefulEdges(Instruction *);
75
Hal Finkel1ae325f2014-09-02 23:50:01 +000076const StratifiedIndex StratifiedLink::SetSentinel =
77 std::numeric_limits<StratifiedIndex>::max();
78
Hal Finkel7529c552014-09-02 21:43:13 +000079namespace {
80// StratifiedInfo Attribute things.
81typedef unsigned StratifiedAttr;
Hal Finkel7d7087c2014-09-02 22:13:00 +000082LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
83LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
84LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
85LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 2;
86LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
87LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
Hal Finkel7529c552014-09-02 21:43:13 +000088
Hal Finkel7d7087c2014-09-02 22:13:00 +000089LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
90LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
Hal Finkel7529c552014-09-02 21:43:13 +000091
92// \brief StratifiedSets call for knowledge of "direction", so this is how we
93// represent that locally.
94enum class Level { Same, Above, Below };
95
96// \brief Edges can be one of four "weights" -- each weight must have an inverse
97// weight (Assign has Assign; Reference has Dereference).
98enum class EdgeType {
99 // The weight assigned when assigning from or to a value. For example, in:
100 // %b = getelementptr %a, 0
101 // ...The relationships are %b assign %a, and %a assign %b. This used to be
102 // two edges, but having a distinction bought us nothing.
103 Assign,
104
105 // The edge used when we have an edge going from some handle to a Value.
106 // Examples of this include:
107 // %b = load %a (%b Dereference %a)
108 // %b = extractelement %a, 0 (%a Dereference %b)
109 Dereference,
110
111 // The edge used when our edge goes from a value to a handle that may have
112 // contained it at some point. Examples:
113 // %b = load %a (%a Reference %b)
114 // %b = extractelement %a, 0 (%b Reference %a)
115 Reference
116};
117
118// \brief Encodes the notion of a "use"
119struct Edge {
120 // \brief Which value the edge is coming from
121 Value *From;
122
123 // \brief Which value the edge is pointing to
124 Value *To;
125
126 // \brief Edge weight
127 EdgeType Weight;
128
129 // \brief Whether we aliased any external values along the way that may be
130 // invisible to the analysis (i.e. landingpad for exceptions, calls for
131 // interprocedural analysis, etc.)
132 StratifiedAttrs AdditionalAttrs;
133
134 Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
135 : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
136};
137
138// \brief Information we have about a function and would like to keep around
139struct FunctionInfo {
140 StratifiedSets<Value *> Sets;
141 // Lots of functions have < 4 returns. Adjust as necessary.
142 SmallVector<Value *, 4> ReturnedValues;
Hal Finkel85f26922014-09-03 00:06:47 +0000143
144 FunctionInfo(StratifiedSets<Value *> &&S,
145 SmallVector<Value *, 4> &&RV)
146 : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
Hal Finkel7529c552014-09-02 21:43:13 +0000147};
148
149struct CFLAliasAnalysis;
150
151struct FunctionHandle : public CallbackVH {
152 FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
153 : CallbackVH(Fn), CFLAA(CFLAA) {
154 assert(Fn != nullptr);
155 assert(CFLAA != nullptr);
156 }
157
158 virtual ~FunctionHandle() {}
159
160 virtual void deleted() override { removeSelfFromCache(); }
161 virtual void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
162
163private:
164 CFLAliasAnalysis *CFLAA;
165
166 void removeSelfFromCache();
167};
168
169struct CFLAliasAnalysis : public ImmutablePass, public AliasAnalysis {
170private:
171 /// \brief Cached mapping of Functions to their StratifiedSets.
172 /// If a function's sets are currently being built, it is marked
173 /// in the cache as an Optional without a value. This way, if we
174 /// have any kind of recursion, it is discernable from a function
175 /// that simply has empty sets.
176 DenseMap<Function *, Optional<FunctionInfo>> Cache;
177 std::forward_list<FunctionHandle> Handles;
178
179public:
180 static char ID;
181
182 CFLAliasAnalysis() : ImmutablePass(ID) {
183 initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
184 }
185
186 virtual ~CFLAliasAnalysis() {}
187
Argyrios Kyrtzidis0b9f5502014-10-01 21:00:44 +0000188 void getAnalysisUsage(AnalysisUsage &AU) const override {
Hal Finkel7529c552014-09-02 21:43:13 +0000189 AliasAnalysis::getAnalysisUsage(AU);
190 }
191
192 void *getAdjustedAnalysisPointer(const void *ID) override {
193 if (ID == &AliasAnalysis::ID)
194 return (AliasAnalysis *)this;
195 return this;
196 }
197
198 /// \brief Inserts the given Function into the cache.
199 void scan(Function *Fn);
200
201 void evict(Function *Fn) { Cache.erase(Fn); }
202
203 /// \brief Ensures that the given function is available in the cache.
204 /// Returns the appropriate entry from the cache.
205 const Optional<FunctionInfo> &ensureCached(Function *Fn) {
206 auto Iter = Cache.find(Fn);
207 if (Iter == Cache.end()) {
208 scan(Fn);
209 Iter = Cache.find(Fn);
210 assert(Iter != Cache.end());
211 assert(Iter->second.hasValue());
212 }
213 return Iter->second;
214 }
215
216 AliasResult query(const Location &LocA, const Location &LocB);
217
218 AliasResult alias(const Location &LocA, const Location &LocB) override {
219 if (LocA.Ptr == LocB.Ptr) {
220 if (LocA.Size == LocB.Size) {
221 return MustAlias;
222 } else {
223 return PartialAlias;
224 }
225 }
226
227 // Comparisons between global variables and other constants should be
228 // handled by BasicAA.
229 if (isa<Constant>(LocA.Ptr) && isa<Constant>(LocB.Ptr)) {
230 return MayAlias;
231 }
232
233 return query(LocA, LocB);
234 }
235
236 void initializePass() override { InitializeAliasAnalysis(this); }
237};
238
239void FunctionHandle::removeSelfFromCache() {
240 assert(CFLAA != nullptr);
241 auto *Val = getValPtr();
242 CFLAA->evict(cast<Function>(Val));
243 setValPtr(nullptr);
244}
245
246// \brief Gets the edges our graph should have, based on an Instruction*
247class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
248 CFLAliasAnalysis &AA;
249 SmallVectorImpl<Edge> &Output;
250
251public:
252 GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
253 : AA(AA), Output(Output) {}
254
255 void visitInstruction(Instruction &) {
256 llvm_unreachable("Unsupported instruction encountered");
257 }
258
259 void visitCastInst(CastInst &Inst) {
Hal Finkel8d1590d2014-09-02 22:52:30 +0000260 Output.push_back(Edge(&Inst, Inst.getOperand(0), EdgeType::Assign,
261 AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000262 }
263
264 void visitBinaryOperator(BinaryOperator &Inst) {
265 auto *Op1 = Inst.getOperand(0);
266 auto *Op2 = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000267 Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
268 Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000269 }
270
271 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
272 auto *Ptr = Inst.getPointerOperand();
273 auto *Val = Inst.getNewValOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000274 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000275 }
276
277 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
278 auto *Ptr = Inst.getPointerOperand();
279 auto *Val = Inst.getValOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000280 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000281 }
282
283 void visitPHINode(PHINode &Inst) {
284 for (unsigned I = 0, E = Inst.getNumIncomingValues(); I != E; ++I) {
285 Value *Val = Inst.getIncomingValue(I);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000286 Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000287 }
288 }
289
290 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
291 auto *Op = Inst.getPointerOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000292 Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000293 for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
Hal Finkel8d1590d2014-09-02 22:52:30 +0000294 Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000295 }
296
297 void visitSelectInst(SelectInst &Inst) {
298 auto *Condition = Inst.getCondition();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000299 Output.push_back(Edge(&Inst, Condition, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000300 auto *TrueVal = Inst.getTrueValue();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000301 Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000302 auto *FalseVal = Inst.getFalseValue();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000303 Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000304 }
305
306 void visitAllocaInst(AllocaInst &) {}
307
308 void visitLoadInst(LoadInst &Inst) {
309 auto *Ptr = Inst.getPointerOperand();
310 auto *Val = &Inst;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000311 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000312 }
313
314 void visitStoreInst(StoreInst &Inst) {
315 auto *Ptr = Inst.getPointerOperand();
316 auto *Val = Inst.getValueOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000317 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000318 }
319
320 static bool isFunctionExternal(Function *Fn) {
321 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
322 }
323
324 // Gets whether the sets at Index1 above, below, or equal to the sets at
325 // Index2. Returns None if they are not in the same set chain.
326 static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
327 StratifiedIndex Index1,
328 StratifiedIndex Index2) {
329 if (Index1 == Index2)
330 return Level::Same;
331
332 const auto *Current = &Sets.getLink(Index1);
333 while (Current->hasBelow()) {
334 if (Current->Below == Index2)
335 return Level::Below;
336 Current = &Sets.getLink(Current->Below);
337 }
338
339 Current = &Sets.getLink(Index1);
340 while (Current->hasAbove()) {
341 if (Current->Above == Index2)
342 return Level::Above;
343 Current = &Sets.getLink(Current->Above);
344 }
345
346 return NoneType();
347 }
348
349 bool
350 tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
351 Value *FuncValue,
352 const iterator_range<User::op_iterator> &Args) {
Hal Finkelca616ac2014-09-02 23:29:48 +0000353 const unsigned ExpectedMaxArgs = 8;
354 const unsigned MaxSupportedArgs = 50;
Hal Finkel7529c552014-09-02 21:43:13 +0000355 assert(Fns.size() > 0);
356
357 // I put this here to give us an upper bound on time taken by IPA. Is it
358 // really (realistically) needed? Keep in mind that we do have an n^2 algo.
Hal Finkelca616ac2014-09-02 23:29:48 +0000359 if (std::distance(Args.begin(), Args.end()) > (int) MaxSupportedArgs)
Hal Finkel7529c552014-09-02 21:43:13 +0000360 return false;
361
362 // Exit early if we'll fail anyway
363 for (auto *Fn : Fns) {
364 if (isFunctionExternal(Fn) || Fn->isVarArg())
365 return false;
366 auto &MaybeInfo = AA.ensureCached(Fn);
367 if (!MaybeInfo.hasValue())
368 return false;
369 }
370
371 SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
372 SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
373 for (auto *Fn : Fns) {
374 auto &Info = *AA.ensureCached(Fn);
375 auto &Sets = Info.Sets;
376 auto &RetVals = Info.ReturnedValues;
377
378 Parameters.clear();
379 for (auto &Param : Fn->args()) {
380 auto MaybeInfo = Sets.find(&Param);
381 // Did a new parameter somehow get added to the function/slip by?
382 if (!MaybeInfo.hasValue())
383 return false;
384 Parameters.push_back(*MaybeInfo);
385 }
386
387 // Adding an edge from argument -> return value for each parameter that
388 // may alias the return value
389 for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
390 auto &ParamInfo = Parameters[I];
391 auto &ArgVal = Arguments[I];
392 bool AddEdge = false;
393 StratifiedAttrs Externals;
394 for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
395 auto MaybeInfo = Sets.find(RetVals[X]);
396 if (!MaybeInfo.hasValue())
397 return false;
398
399 auto &RetInfo = *MaybeInfo;
400 auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
401 auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
402 auto MaybeRelation =
403 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
404 if (MaybeRelation.hasValue()) {
405 AddEdge = true;
406 Externals |= RetAttrs | ParamAttrs;
407 }
408 }
409 if (AddEdge)
Hal Finkelca616ac2014-09-02 23:29:48 +0000410 Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
411 StratifiedAttrs().flip()));
Hal Finkel7529c552014-09-02 21:43:13 +0000412 }
413
414 if (Parameters.size() != Arguments.size())
415 return false;
416
417 // Adding edges between arguments for arguments that may end up aliasing
418 // each other. This is necessary for functions such as
419 // void foo(int** a, int** b) { *a = *b; }
420 // (Technically, the proper sets for this would be those below
421 // Arguments[I] and Arguments[X], but our algorithm will produce
422 // extremely similar, and equally correct, results either way)
423 for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
424 auto &MainVal = Arguments[I];
425 auto &MainInfo = Parameters[I];
426 auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
427 for (unsigned X = I + 1; X != E; ++X) {
428 auto &SubInfo = Parameters[X];
429 auto &SubVal = Arguments[X];
430 auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
431 auto MaybeRelation =
432 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
433
434 if (!MaybeRelation.hasValue())
435 continue;
436
437 auto NewAttrs = SubAttrs | MainAttrs;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000438 Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
Hal Finkel7529c552014-09-02 21:43:13 +0000439 }
440 }
441 }
442 return true;
443 }
444
445 template <typename InstT> void visitCallLikeInst(InstT &Inst) {
446 SmallVector<Function *, 4> Targets;
447 if (getPossibleTargets(&Inst, Targets)) {
448 if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
449 return;
450 // Cleanup from interprocedural analysis
451 Output.clear();
452 }
453
454 for (Value *V : Inst.arg_operands())
Hal Finkel8d1590d2014-09-02 22:52:30 +0000455 Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
Hal Finkel7529c552014-09-02 21:43:13 +0000456 }
457
458 void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
459
460 void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
461
462 // Because vectors/aggregates are immutable and unaddressable,
463 // there's nothing we can do to coax a value out of them, other
464 // than calling Extract{Element,Value}. We can effectively treat
465 // them as pointers to arbitrary memory locations we can store in
466 // and load from.
467 void visitExtractElementInst(ExtractElementInst &Inst) {
468 auto *Ptr = Inst.getVectorOperand();
469 auto *Val = &Inst;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000470 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000471 }
472
473 void visitInsertElementInst(InsertElementInst &Inst) {
474 auto *Vec = Inst.getOperand(0);
475 auto *Val = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000476 Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
477 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000478 }
479
480 void visitLandingPadInst(LandingPadInst &Inst) {
481 // Exceptions come from "nowhere", from our analysis' perspective.
482 // So we place the instruction its own group, noting that said group may
483 // alias externals
Hal Finkel8d1590d2014-09-02 22:52:30 +0000484 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
Hal Finkel7529c552014-09-02 21:43:13 +0000485 }
486
487 void visitInsertValueInst(InsertValueInst &Inst) {
488 auto *Agg = Inst.getOperand(0);
489 auto *Val = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000490 Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
491 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000492 }
493
494 void visitExtractValueInst(ExtractValueInst &Inst) {
495 auto *Ptr = Inst.getAggregateOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000496 Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000497 }
498
499 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
500 auto *From1 = Inst.getOperand(0);
501 auto *From2 = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000502 Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
503 Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000504 }
505};
506
507// For a given instruction, we need to know which Value* to get the
508// users of in order to build our graph. In some cases (i.e. add),
509// we simply need the Instruction*. In other cases (i.e. store),
510// finding the users of the Instruction* is useless; we need to find
511// the users of the first operand. This handles determining which
512// value to follow for us.
513//
514// Note: we *need* to keep this in sync with GetEdgesVisitor. Add
515// something to GetEdgesVisitor, add it here -- remove something from
516// GetEdgesVisitor, remove it here.
517class GetTargetValueVisitor
518 : public InstVisitor<GetTargetValueVisitor, Value *> {
519public:
520 Value *visitInstruction(Instruction &Inst) { return &Inst; }
521
522 Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
523
524 Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
525 return Inst.getPointerOperand();
526 }
527
528 Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
529 return Inst.getPointerOperand();
530 }
531
532 Value *visitInsertElementInst(InsertElementInst &Inst) {
533 return Inst.getOperand(0);
534 }
535
536 Value *visitInsertValueInst(InsertValueInst &Inst) {
537 return Inst.getAggregateOperand();
538 }
539};
540
541// Set building requires a weighted bidirectional graph.
542template <typename EdgeTypeT> class WeightedBidirectionalGraph {
543public:
544 typedef std::size_t Node;
545
546private:
Hal Finkelca616ac2014-09-02 23:29:48 +0000547 const static Node StartNode = Node(0);
Hal Finkel7529c552014-09-02 21:43:13 +0000548
549 struct Edge {
550 EdgeTypeT Weight;
551 Node Other;
552
Hal Finkelca616ac2014-09-02 23:29:48 +0000553 Edge(const EdgeTypeT &W, const Node &N)
554 : Weight(W), Other(N) {}
555
Hal Finkel7529c552014-09-02 21:43:13 +0000556 bool operator==(const Edge &E) const {
557 return Weight == E.Weight && Other == E.Other;
558 }
559
560 bool operator!=(const Edge &E) const { return !operator==(E); }
561 };
562
563 struct NodeImpl {
564 std::vector<Edge> Edges;
565 };
566
567 std::vector<NodeImpl> NodeImpls;
568
569 bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
570
571 const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
572 NodeImpl &getNode(Node N) { return NodeImpls[N]; }
573
574public:
575 // ----- Various Edge iterators for the graph ----- //
576
577 // \brief Iterator for edges. Because this graph is bidirected, we don't
578 // allow modificaiton of the edges using this iterator. Additionally, the
579 // iterator becomes invalid if you add edges to or from the node you're
580 // getting the edges of.
581 struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
582 std::tuple<EdgeTypeT, Node *>> {
583 EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
584 : Current(Iter) {}
585
586 EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
587
588 EdgeIterator &operator++() {
589 ++Current;
590 return *this;
591 }
592
593 EdgeIterator operator++(int) {
594 EdgeIterator Copy(Current);
595 operator++();
596 return Copy;
597 }
598
599 std::tuple<EdgeTypeT, Node> &operator*() {
600 Store = std::make_tuple(Current->Weight, Current->Other);
601 return Store;
602 }
603
604 bool operator==(const EdgeIterator &Other) const {
605 return Current == Other.Current;
606 }
607
608 bool operator!=(const EdgeIterator &Other) const {
609 return !operator==(Other);
610 }
611
612 private:
613 typename std::vector<Edge>::const_iterator Current;
614 std::tuple<EdgeTypeT, Node> Store;
615 };
616
617 // Wrapper for EdgeIterator with begin()/end() calls.
618 struct EdgeIterable {
619 EdgeIterable(const std::vector<Edge> &Edges)
620 : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
621
622 EdgeIterator begin() { return EdgeIterator(BeginIter); }
623
624 EdgeIterator end() { return EdgeIterator(EndIter); }
625
626 private:
627 typename std::vector<Edge>::const_iterator BeginIter;
628 typename std::vector<Edge>::const_iterator EndIter;
629 };
630
631 // ----- Actual graph-related things ----- //
632
Hal Finkelca616ac2014-09-02 23:29:48 +0000633 WeightedBidirectionalGraph() {}
Hal Finkel7529c552014-09-02 21:43:13 +0000634
635 WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
636 : NodeImpls(std::move(Other.NodeImpls)) {}
637
638 WeightedBidirectionalGraph<EdgeTypeT> &
639 operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
640 NodeImpls = std::move(Other.NodeImpls);
641 return *this;
642 }
643
644 Node addNode() {
645 auto Index = NodeImpls.size();
646 auto NewNode = Node(Index);
647 NodeImpls.push_back(NodeImpl());
648 return NewNode;
649 }
650
651 void addEdge(Node From, Node To, const EdgeTypeT &Weight,
652 const EdgeTypeT &ReverseWeight) {
653 assert(inbounds(From));
654 assert(inbounds(To));
655 auto &FromNode = getNode(From);
656 auto &ToNode = getNode(To);
Hal Finkelca616ac2014-09-02 23:29:48 +0000657 FromNode.Edges.push_back(Edge(Weight, To));
658 ToNode.Edges.push_back(Edge(ReverseWeight, From));
Hal Finkel7529c552014-09-02 21:43:13 +0000659 }
660
661 EdgeIterable edgesFor(const Node &N) const {
662 const auto &Node = getNode(N);
663 return EdgeIterable(Node.Edges);
664 }
665
666 bool empty() const { return NodeImpls.empty(); }
667 std::size_t size() const { return NodeImpls.size(); }
668
669 // \brief Gets an arbitrary node in the graph as a starting point for
670 // traversal.
671 Node getEntryNode() {
672 assert(inbounds(StartNode));
673 return StartNode;
674 }
675};
676
677typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
678typedef DenseMap<Value *, GraphT::Node> NodeMapT;
679}
680
681// -- Setting up/registering CFLAA pass -- //
682char CFLAliasAnalysis::ID = 0;
683
684INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
685 "CFL-Based AA implementation", false, true, false)
686
687ImmutablePass *llvm::createCFLAliasAnalysisPass() {
688 return new CFLAliasAnalysis();
689}
690
691//===----------------------------------------------------------------------===//
692// Function declarations that require types defined in the namespace above
693//===----------------------------------------------------------------------===//
694
695// Given an argument number, returns the appropriate Attr index to set.
696static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
697
698// Given a Value, potentially return which AttrIndex it maps to.
699static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
700
701// Gets the inverse of a given EdgeType.
702static EdgeType flipWeight(EdgeType);
703
704// Gets edges of the given Instruction*, writing them to the SmallVector*.
705static void argsToEdges(CFLAliasAnalysis &, Instruction *,
706 SmallVectorImpl<Edge> &);
707
708// Gets the "Level" that one should travel in StratifiedSets
709// given an EdgeType.
710static Level directionOfEdgeType(EdgeType);
711
712// Builds the graph needed for constructing the StratifiedSets for the
713// given function
714static void buildGraphFrom(CFLAliasAnalysis &, Function *,
715 SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
716
717// Builds the graph + StratifiedSets for a function.
718static FunctionInfo buildSetsFrom(CFLAliasAnalysis &, Function *);
719
720static Optional<Function *> parentFunctionOfValue(Value *Val) {
721 if (auto *Inst = dyn_cast<Instruction>(Val)) {
722 auto *Bb = Inst->getParent();
723 return Bb->getParent();
724 }
725
726 if (auto *Arg = dyn_cast<Argument>(Val))
727 return Arg->getParent();
728 return NoneType();
729}
730
731template <typename Inst>
732static bool getPossibleTargets(Inst *Call,
733 SmallVectorImpl<Function *> &Output) {
734 if (auto *Fn = Call->getCalledFunction()) {
735 Output.push_back(Fn);
736 return true;
737 }
738
739 // TODO: If the call is indirect, we might be able to enumerate all potential
740 // targets of the call and return them, rather than just failing.
741 return false;
742}
743
744static Optional<Value *> getTargetValue(Instruction *Inst) {
745 GetTargetValueVisitor V;
746 return V.visit(Inst);
747}
748
749static bool hasUsefulEdges(Instruction *Inst) {
750 bool IsNonInvokeTerminator =
751 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
752 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
753}
754
755static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
756 if (isa<GlobalValue>(Val))
757 return AttrGlobalIndex;
758
759 if (auto *Arg = dyn_cast<Argument>(Val))
760 if (!Arg->hasNoAliasAttr())
761 return argNumberToAttrIndex(Arg->getArgNo());
762 return NoneType();
763}
764
765static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
766 if (ArgNum > AttrMaxNumArgs)
767 return AttrAllIndex;
768 return ArgNum + AttrFirstArgIndex;
769}
770
771static EdgeType flipWeight(EdgeType Initial) {
772 switch (Initial) {
773 case EdgeType::Assign:
774 return EdgeType::Assign;
775 case EdgeType::Dereference:
776 return EdgeType::Reference;
777 case EdgeType::Reference:
778 return EdgeType::Dereference;
779 }
780 llvm_unreachable("Incomplete coverage of EdgeType enum");
781}
782
783static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
784 SmallVectorImpl<Edge> &Output) {
785 GetEdgesVisitor v(Analysis, Output);
786 v.visit(Inst);
787}
788
789static Level directionOfEdgeType(EdgeType Weight) {
790 switch (Weight) {
791 case EdgeType::Reference:
792 return Level::Above;
793 case EdgeType::Dereference:
794 return Level::Below;
795 case EdgeType::Assign:
796 return Level::Same;
797 }
798 llvm_unreachable("Incomplete switch coverage");
799}
800
801// Aside: We may remove graph construction entirely, because it doesn't really
802// buy us much that we don't already have. I'd like to add interprocedural
803// analysis prior to this however, in case that somehow requires the graph
804// produced by this for efficient execution
805static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
806 SmallVectorImpl<Value *> &ReturnedValues,
807 NodeMapT &Map, GraphT &Graph) {
808 const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
809 auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
810 auto &Iter = Pair.first;
811 if (Pair.second) {
812 auto NewNode = Graph.addNode();
813 Iter->second = NewNode;
814 }
815 return Iter->second;
816 };
817
818 SmallVector<Edge, 8> Edges;
819 for (auto &Bb : Fn->getBasicBlockList()) {
820 for (auto &Inst : Bb.getInstList()) {
821 // We don't want the edges of most "return" instructions, but we *do* want
822 // to know what can be returned.
823 if (auto *Ret = dyn_cast<ReturnInst>(&Inst))
824 ReturnedValues.push_back(Ret);
825
826 if (!hasUsefulEdges(&Inst))
827 continue;
828
829 Edges.clear();
830 argsToEdges(Analysis, &Inst, Edges);
831
832 // In the case of an unused alloca (or similar), edges may be empty. Note
833 // that it exists so we can potentially answer NoAlias.
834 if (Edges.empty()) {
835 auto MaybeVal = getTargetValue(&Inst);
836 assert(MaybeVal.hasValue());
837 auto *Target = *MaybeVal;
838 findOrInsertNode(Target);
839 continue;
840 }
841
842 for (const Edge &E : Edges) {
843 auto To = findOrInsertNode(E.To);
844 auto From = findOrInsertNode(E.From);
845 auto FlippedWeight = flipWeight(E.Weight);
846 auto Attrs = E.AdditionalAttrs;
Hal Finkel1ae325f2014-09-02 23:50:01 +0000847 Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
848 std::make_pair(FlippedWeight, Attrs));
Hal Finkel7529c552014-09-02 21:43:13 +0000849 }
850 }
851 }
852}
853
854static FunctionInfo buildSetsFrom(CFLAliasAnalysis &Analysis, Function *Fn) {
855 NodeMapT Map;
856 GraphT Graph;
857 SmallVector<Value *, 4> ReturnedValues;
858
859 buildGraphFrom(Analysis, Fn, ReturnedValues, Map, Graph);
860
861 DenseMap<GraphT::Node, Value *> NodeValueMap;
862 NodeValueMap.resize(Map.size());
863 for (const auto &Pair : Map)
Hal Finkel8d1590d2014-09-02 22:52:30 +0000864 NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
Hal Finkel7529c552014-09-02 21:43:13 +0000865
866 const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
867 auto ValIter = NodeValueMap.find(Node);
868 assert(ValIter != NodeValueMap.end());
869 return ValIter->second;
870 };
871
872 StratifiedSetsBuilder<Value *> Builder;
873
874 SmallVector<GraphT::Node, 16> Worklist;
875 for (auto &Pair : Map) {
876 Worklist.clear();
877
878 auto *Value = Pair.first;
879 Builder.add(Value);
880 auto InitialNode = Pair.second;
881 Worklist.push_back(InitialNode);
882 while (!Worklist.empty()) {
883 auto Node = Worklist.pop_back_val();
884 auto *CurValue = findValueOrDie(Node);
885 if (isa<Constant>(CurValue) && !isa<GlobalValue>(CurValue))
886 continue;
887
888 for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
889 auto Weight = std::get<0>(EdgeTuple);
890 auto Label = Weight.first;
891 auto &OtherNode = std::get<1>(EdgeTuple);
892 auto *OtherValue = findValueOrDie(OtherNode);
893
894 if (isa<Constant>(OtherValue) && !isa<GlobalValue>(OtherValue))
895 continue;
896
897 bool Added;
898 switch (directionOfEdgeType(Label)) {
899 case Level::Above:
900 Added = Builder.addAbove(CurValue, OtherValue);
901 break;
902 case Level::Below:
903 Added = Builder.addBelow(CurValue, OtherValue);
904 break;
905 case Level::Same:
906 Added = Builder.addWith(CurValue, OtherValue);
907 break;
908 }
909
910 if (Added) {
911 auto Aliasing = Weight.second;
912 if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
913 Aliasing.set(*MaybeCurIndex);
914 if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
915 Aliasing.set(*MaybeOtherIndex);
916 Builder.noteAttributes(CurValue, Aliasing);
917 Builder.noteAttributes(OtherValue, Aliasing);
918 Worklist.push_back(OtherNode);
919 }
920 }
921 }
922 }
923
924 // There are times when we end up with parameters not in our graph (i.e. if
925 // it's only used as the condition of a branch). Other bits of code depend on
926 // things that were present during construction being present in the graph.
927 // So, we add all present arguments here.
928 for (auto &Arg : Fn->args()) {
929 Builder.add(&Arg);
930 }
931
Hal Finkel85f26922014-09-03 00:06:47 +0000932 return FunctionInfo(Builder.build(), std::move(ReturnedValues));
Hal Finkel7529c552014-09-02 21:43:13 +0000933}
934
935void CFLAliasAnalysis::scan(Function *Fn) {
Hal Finkel8d1590d2014-09-02 22:52:30 +0000936 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
Hal Finkel7529c552014-09-02 21:43:13 +0000937 (void)InsertPair;
938 assert(InsertPair.second &&
939 "Trying to scan a function that has already been cached");
940
941 FunctionInfo Info(buildSetsFrom(*this, Fn));
942 Cache[Fn] = std::move(Info);
943 Handles.push_front(FunctionHandle(Fn, this));
944}
945
946AliasAnalysis::AliasResult
947CFLAliasAnalysis::query(const AliasAnalysis::Location &LocA,
948 const AliasAnalysis::Location &LocB) {
949 auto *ValA = const_cast<Value *>(LocA.Ptr);
950 auto *ValB = const_cast<Value *>(LocB.Ptr);
951
952 Function *Fn = nullptr;
953 auto MaybeFnA = parentFunctionOfValue(ValA);
954 auto MaybeFnB = parentFunctionOfValue(ValB);
955 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
956 llvm_unreachable("Don't know how to extract the parent function "
957 "from values A or B");
958 }
959
960 if (MaybeFnA.hasValue()) {
961 Fn = *MaybeFnA;
962 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
963 "Interprocedural queries not supported");
964 } else {
965 Fn = *MaybeFnB;
966 }
967
968 assert(Fn != nullptr);
969 auto &MaybeInfo = ensureCached(Fn);
970 assert(MaybeInfo.hasValue());
971
972 auto &Sets = MaybeInfo->Sets;
973 auto MaybeA = Sets.find(ValA);
974 if (!MaybeA.hasValue())
975 return AliasAnalysis::MayAlias;
976
977 auto MaybeB = Sets.find(ValB);
978 if (!MaybeB.hasValue())
979 return AliasAnalysis::MayAlias;
980
981 auto SetA = *MaybeA;
982 auto SetB = *MaybeB;
983
984 if (SetA.Index == SetB.Index)
985 return AliasAnalysis::PartialAlias;
986
987 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
988 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
989 auto CombinedAttrs = AttrsA | AttrsB;
990 if (CombinedAttrs.any())
991 return AliasAnalysis::PartialAlias;
992
993 return AliasAnalysis::NoAlias;
994}