blob: 321b57b433c992c09ccbfa161972cdc7d755e808 [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"
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
David Blaikie711cd9c2014-11-14 19:06:36 +0000160 void deleted() override { removeSelfFromCache(); }
161 void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
Hal Finkel7529c552014-09-02 21:43:13 +0000162
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)) {
Daniel Berlin8f10e382015-01-26 17:30:39 +0000230 return AliasAnalysis::alias(LocA, LocB);
Hal Finkel7529c552014-09-02 21:43:13 +0000231 }
Daniel Berlin8f10e382015-01-26 17:30:39 +0000232 AliasResult QueryResult = query(LocA, LocB);
233 if (QueryResult == MayAlias)
234 return AliasAnalysis::alias(LocA, LocB);
Hal Finkel7529c552014-09-02 21:43:13 +0000235
Daniel Berlin8f10e382015-01-26 17:30:39 +0000236 return QueryResult;
Hal Finkel7529c552014-09-02 21:43:13 +0000237 }
238
239 void initializePass() override { InitializeAliasAnalysis(this); }
240};
241
242void FunctionHandle::removeSelfFromCache() {
243 assert(CFLAA != nullptr);
244 auto *Val = getValPtr();
245 CFLAA->evict(cast<Function>(Val));
246 setValPtr(nullptr);
247}
248
249// \brief Gets the edges our graph should have, based on an Instruction*
250class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
251 CFLAliasAnalysis &AA;
252 SmallVectorImpl<Edge> &Output;
253
254public:
255 GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
256 : AA(AA), Output(Output) {}
257
258 void visitInstruction(Instruction &) {
259 llvm_unreachable("Unsupported instruction encountered");
260 }
261
262 void visitCastInst(CastInst &Inst) {
Hal Finkel8d1590d2014-09-02 22:52:30 +0000263 Output.push_back(Edge(&Inst, Inst.getOperand(0), EdgeType::Assign,
264 AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000265 }
266
267 void visitBinaryOperator(BinaryOperator &Inst) {
268 auto *Op1 = Inst.getOperand(0);
269 auto *Op2 = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000270 Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
271 Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000272 }
273
274 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
275 auto *Ptr = Inst.getPointerOperand();
276 auto *Val = Inst.getNewValOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000277 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000278 }
279
280 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
281 auto *Ptr = Inst.getPointerOperand();
282 auto *Val = Inst.getValOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000283 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000284 }
285
286 void visitPHINode(PHINode &Inst) {
287 for (unsigned I = 0, E = Inst.getNumIncomingValues(); I != E; ++I) {
288 Value *Val = Inst.getIncomingValue(I);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000289 Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000290 }
291 }
292
293 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
294 auto *Op = Inst.getPointerOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000295 Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000296 for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
Hal Finkel8d1590d2014-09-02 22:52:30 +0000297 Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000298 }
299
300 void visitSelectInst(SelectInst &Inst) {
301 auto *Condition = Inst.getCondition();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000302 Output.push_back(Edge(&Inst, Condition, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000303 auto *TrueVal = Inst.getTrueValue();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000304 Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000305 auto *FalseVal = Inst.getFalseValue();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000306 Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000307 }
308
309 void visitAllocaInst(AllocaInst &) {}
310
311 void visitLoadInst(LoadInst &Inst) {
312 auto *Ptr = Inst.getPointerOperand();
313 auto *Val = &Inst;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000314 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000315 }
316
317 void visitStoreInst(StoreInst &Inst) {
318 auto *Ptr = Inst.getPointerOperand();
319 auto *Val = Inst.getValueOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000320 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000321 }
322
Hal Finkeldb5f86a2014-10-14 20:51:26 +0000323 void visitVAArgInst(VAArgInst &Inst) {
324 // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
325 // two things:
326 // 1. Loads a value from *((T*)*Ptr).
327 // 2. Increments (stores to) *Ptr by some target-specific amount.
328 // For now, we'll handle this like a landingpad instruction (by placing the
329 // result in its own group, and having that group alias externals).
330 auto *Val = &Inst;
331 Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll));
332 }
333
Hal Finkel7529c552014-09-02 21:43:13 +0000334 static bool isFunctionExternal(Function *Fn) {
335 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
336 }
337
338 // Gets whether the sets at Index1 above, below, or equal to the sets at
339 // Index2. Returns None if they are not in the same set chain.
340 static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
341 StratifiedIndex Index1,
342 StratifiedIndex Index2) {
343 if (Index1 == Index2)
344 return Level::Same;
345
346 const auto *Current = &Sets.getLink(Index1);
347 while (Current->hasBelow()) {
348 if (Current->Below == Index2)
349 return Level::Below;
350 Current = &Sets.getLink(Current->Below);
351 }
352
353 Current = &Sets.getLink(Index1);
354 while (Current->hasAbove()) {
355 if (Current->Above == Index2)
356 return Level::Above;
357 Current = &Sets.getLink(Current->Above);
358 }
359
360 return NoneType();
361 }
362
363 bool
364 tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
365 Value *FuncValue,
366 const iterator_range<User::op_iterator> &Args) {
Hal Finkelca616ac2014-09-02 23:29:48 +0000367 const unsigned ExpectedMaxArgs = 8;
368 const unsigned MaxSupportedArgs = 50;
Hal Finkel7529c552014-09-02 21:43:13 +0000369 assert(Fns.size() > 0);
370
371 // I put this here to give us an upper bound on time taken by IPA. Is it
372 // really (realistically) needed? Keep in mind that we do have an n^2 algo.
Hal Finkelca616ac2014-09-02 23:29:48 +0000373 if (std::distance(Args.begin(), Args.end()) > (int) MaxSupportedArgs)
Hal Finkel7529c552014-09-02 21:43:13 +0000374 return false;
375
376 // Exit early if we'll fail anyway
377 for (auto *Fn : Fns) {
378 if (isFunctionExternal(Fn) || Fn->isVarArg())
379 return false;
380 auto &MaybeInfo = AA.ensureCached(Fn);
381 if (!MaybeInfo.hasValue())
382 return false;
383 }
384
385 SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
386 SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
387 for (auto *Fn : Fns) {
388 auto &Info = *AA.ensureCached(Fn);
389 auto &Sets = Info.Sets;
390 auto &RetVals = Info.ReturnedValues;
391
392 Parameters.clear();
393 for (auto &Param : Fn->args()) {
394 auto MaybeInfo = Sets.find(&Param);
395 // Did a new parameter somehow get added to the function/slip by?
396 if (!MaybeInfo.hasValue())
397 return false;
398 Parameters.push_back(*MaybeInfo);
399 }
400
401 // Adding an edge from argument -> return value for each parameter that
402 // may alias the return value
403 for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
404 auto &ParamInfo = Parameters[I];
405 auto &ArgVal = Arguments[I];
406 bool AddEdge = false;
407 StratifiedAttrs Externals;
408 for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
409 auto MaybeInfo = Sets.find(RetVals[X]);
410 if (!MaybeInfo.hasValue())
411 return false;
412
413 auto &RetInfo = *MaybeInfo;
414 auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
415 auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
416 auto MaybeRelation =
417 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
418 if (MaybeRelation.hasValue()) {
419 AddEdge = true;
420 Externals |= RetAttrs | ParamAttrs;
421 }
422 }
423 if (AddEdge)
Hal Finkelca616ac2014-09-02 23:29:48 +0000424 Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
425 StratifiedAttrs().flip()));
Hal Finkel7529c552014-09-02 21:43:13 +0000426 }
427
428 if (Parameters.size() != Arguments.size())
429 return false;
430
431 // Adding edges between arguments for arguments that may end up aliasing
432 // each other. This is necessary for functions such as
433 // void foo(int** a, int** b) { *a = *b; }
434 // (Technically, the proper sets for this would be those below
435 // Arguments[I] and Arguments[X], but our algorithm will produce
436 // extremely similar, and equally correct, results either way)
437 for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
438 auto &MainVal = Arguments[I];
439 auto &MainInfo = Parameters[I];
440 auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
441 for (unsigned X = I + 1; X != E; ++X) {
442 auto &SubInfo = Parameters[X];
443 auto &SubVal = Arguments[X];
444 auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
445 auto MaybeRelation =
446 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
447
448 if (!MaybeRelation.hasValue())
449 continue;
450
451 auto NewAttrs = SubAttrs | MainAttrs;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000452 Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
Hal Finkel7529c552014-09-02 21:43:13 +0000453 }
454 }
455 }
456 return true;
457 }
458
459 template <typename InstT> void visitCallLikeInst(InstT &Inst) {
460 SmallVector<Function *, 4> Targets;
461 if (getPossibleTargets(&Inst, Targets)) {
462 if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
463 return;
464 // Cleanup from interprocedural analysis
465 Output.clear();
466 }
467
468 for (Value *V : Inst.arg_operands())
Hal Finkel8d1590d2014-09-02 22:52:30 +0000469 Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
Hal Finkel7529c552014-09-02 21:43:13 +0000470 }
471
472 void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
473
474 void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
475
476 // Because vectors/aggregates are immutable and unaddressable,
477 // there's nothing we can do to coax a value out of them, other
478 // than calling Extract{Element,Value}. We can effectively treat
479 // them as pointers to arbitrary memory locations we can store in
480 // and load from.
481 void visitExtractElementInst(ExtractElementInst &Inst) {
482 auto *Ptr = Inst.getVectorOperand();
483 auto *Val = &Inst;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000484 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000485 }
486
487 void visitInsertElementInst(InsertElementInst &Inst) {
488 auto *Vec = Inst.getOperand(0);
489 auto *Val = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000490 Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
491 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000492 }
493
494 void visitLandingPadInst(LandingPadInst &Inst) {
495 // Exceptions come from "nowhere", from our analysis' perspective.
496 // So we place the instruction its own group, noting that said group may
497 // alias externals
Hal Finkel8d1590d2014-09-02 22:52:30 +0000498 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
Hal Finkel7529c552014-09-02 21:43:13 +0000499 }
500
501 void visitInsertValueInst(InsertValueInst &Inst) {
502 auto *Agg = Inst.getOperand(0);
503 auto *Val = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000504 Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
505 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000506 }
507
508 void visitExtractValueInst(ExtractValueInst &Inst) {
509 auto *Ptr = Inst.getAggregateOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000510 Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000511 }
512
513 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
514 auto *From1 = Inst.getOperand(0);
515 auto *From2 = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000516 Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
517 Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000518 }
519};
520
521// For a given instruction, we need to know which Value* to get the
522// users of in order to build our graph. In some cases (i.e. add),
523// we simply need the Instruction*. In other cases (i.e. store),
524// finding the users of the Instruction* is useless; we need to find
525// the users of the first operand. This handles determining which
526// value to follow for us.
527//
528// Note: we *need* to keep this in sync with GetEdgesVisitor. Add
529// something to GetEdgesVisitor, add it here -- remove something from
530// GetEdgesVisitor, remove it here.
531class GetTargetValueVisitor
532 : public InstVisitor<GetTargetValueVisitor, Value *> {
533public:
534 Value *visitInstruction(Instruction &Inst) { return &Inst; }
535
536 Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
537
538 Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
539 return Inst.getPointerOperand();
540 }
541
542 Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
543 return Inst.getPointerOperand();
544 }
545
546 Value *visitInsertElementInst(InsertElementInst &Inst) {
547 return Inst.getOperand(0);
548 }
549
550 Value *visitInsertValueInst(InsertValueInst &Inst) {
551 return Inst.getAggregateOperand();
552 }
553};
554
555// Set building requires a weighted bidirectional graph.
556template <typename EdgeTypeT> class WeightedBidirectionalGraph {
557public:
558 typedef std::size_t Node;
559
560private:
Hal Finkelca616ac2014-09-02 23:29:48 +0000561 const static Node StartNode = Node(0);
Hal Finkel7529c552014-09-02 21:43:13 +0000562
563 struct Edge {
564 EdgeTypeT Weight;
565 Node Other;
566
Hal Finkelca616ac2014-09-02 23:29:48 +0000567 Edge(const EdgeTypeT &W, const Node &N)
568 : Weight(W), Other(N) {}
569
Hal Finkel7529c552014-09-02 21:43:13 +0000570 bool operator==(const Edge &E) const {
571 return Weight == E.Weight && Other == E.Other;
572 }
573
574 bool operator!=(const Edge &E) const { return !operator==(E); }
575 };
576
577 struct NodeImpl {
578 std::vector<Edge> Edges;
579 };
580
581 std::vector<NodeImpl> NodeImpls;
582
583 bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
584
585 const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
586 NodeImpl &getNode(Node N) { return NodeImpls[N]; }
587
588public:
589 // ----- Various Edge iterators for the graph ----- //
590
591 // \brief Iterator for edges. Because this graph is bidirected, we don't
592 // allow modificaiton of the edges using this iterator. Additionally, the
593 // iterator becomes invalid if you add edges to or from the node you're
594 // getting the edges of.
595 struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
596 std::tuple<EdgeTypeT, Node *>> {
597 EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
598 : Current(Iter) {}
599
600 EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
601
602 EdgeIterator &operator++() {
603 ++Current;
604 return *this;
605 }
606
607 EdgeIterator operator++(int) {
608 EdgeIterator Copy(Current);
609 operator++();
610 return Copy;
611 }
612
613 std::tuple<EdgeTypeT, Node> &operator*() {
614 Store = std::make_tuple(Current->Weight, Current->Other);
615 return Store;
616 }
617
618 bool operator==(const EdgeIterator &Other) const {
619 return Current == Other.Current;
620 }
621
622 bool operator!=(const EdgeIterator &Other) const {
623 return !operator==(Other);
624 }
625
626 private:
627 typename std::vector<Edge>::const_iterator Current;
628 std::tuple<EdgeTypeT, Node> Store;
629 };
630
631 // Wrapper for EdgeIterator with begin()/end() calls.
632 struct EdgeIterable {
633 EdgeIterable(const std::vector<Edge> &Edges)
634 : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
635
636 EdgeIterator begin() { return EdgeIterator(BeginIter); }
637
638 EdgeIterator end() { return EdgeIterator(EndIter); }
639
640 private:
641 typename std::vector<Edge>::const_iterator BeginIter;
642 typename std::vector<Edge>::const_iterator EndIter;
643 };
644
645 // ----- Actual graph-related things ----- //
646
Hal Finkelca616ac2014-09-02 23:29:48 +0000647 WeightedBidirectionalGraph() {}
Hal Finkel7529c552014-09-02 21:43:13 +0000648
649 WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
650 : NodeImpls(std::move(Other.NodeImpls)) {}
651
652 WeightedBidirectionalGraph<EdgeTypeT> &
653 operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
654 NodeImpls = std::move(Other.NodeImpls);
655 return *this;
656 }
657
658 Node addNode() {
659 auto Index = NodeImpls.size();
660 auto NewNode = Node(Index);
661 NodeImpls.push_back(NodeImpl());
662 return NewNode;
663 }
664
665 void addEdge(Node From, Node To, const EdgeTypeT &Weight,
666 const EdgeTypeT &ReverseWeight) {
667 assert(inbounds(From));
668 assert(inbounds(To));
669 auto &FromNode = getNode(From);
670 auto &ToNode = getNode(To);
Hal Finkelca616ac2014-09-02 23:29:48 +0000671 FromNode.Edges.push_back(Edge(Weight, To));
672 ToNode.Edges.push_back(Edge(ReverseWeight, From));
Hal Finkel7529c552014-09-02 21:43:13 +0000673 }
674
675 EdgeIterable edgesFor(const Node &N) const {
676 const auto &Node = getNode(N);
677 return EdgeIterable(Node.Edges);
678 }
679
680 bool empty() const { return NodeImpls.empty(); }
681 std::size_t size() const { return NodeImpls.size(); }
682
683 // \brief Gets an arbitrary node in the graph as a starting point for
684 // traversal.
685 Node getEntryNode() {
686 assert(inbounds(StartNode));
687 return StartNode;
688 }
689};
690
691typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
692typedef DenseMap<Value *, GraphT::Node> NodeMapT;
693}
694
695// -- Setting up/registering CFLAA pass -- //
696char CFLAliasAnalysis::ID = 0;
697
698INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
699 "CFL-Based AA implementation", false, true, false)
700
701ImmutablePass *llvm::createCFLAliasAnalysisPass() {
702 return new CFLAliasAnalysis();
703}
704
705//===----------------------------------------------------------------------===//
706// Function declarations that require types defined in the namespace above
707//===----------------------------------------------------------------------===//
708
709// Given an argument number, returns the appropriate Attr index to set.
710static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
711
712// Given a Value, potentially return which AttrIndex it maps to.
713static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
714
715// Gets the inverse of a given EdgeType.
716static EdgeType flipWeight(EdgeType);
717
718// Gets edges of the given Instruction*, writing them to the SmallVector*.
719static void argsToEdges(CFLAliasAnalysis &, Instruction *,
720 SmallVectorImpl<Edge> &);
721
722// Gets the "Level" that one should travel in StratifiedSets
723// given an EdgeType.
724static Level directionOfEdgeType(EdgeType);
725
726// Builds the graph needed for constructing the StratifiedSets for the
727// given function
728static void buildGraphFrom(CFLAliasAnalysis &, Function *,
729 SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
730
731// Builds the graph + StratifiedSets for a function.
732static FunctionInfo buildSetsFrom(CFLAliasAnalysis &, Function *);
733
734static Optional<Function *> parentFunctionOfValue(Value *Val) {
735 if (auto *Inst = dyn_cast<Instruction>(Val)) {
736 auto *Bb = Inst->getParent();
737 return Bb->getParent();
738 }
739
740 if (auto *Arg = dyn_cast<Argument>(Val))
741 return Arg->getParent();
742 return NoneType();
743}
744
745template <typename Inst>
746static bool getPossibleTargets(Inst *Call,
747 SmallVectorImpl<Function *> &Output) {
748 if (auto *Fn = Call->getCalledFunction()) {
749 Output.push_back(Fn);
750 return true;
751 }
752
753 // TODO: If the call is indirect, we might be able to enumerate all potential
754 // targets of the call and return them, rather than just failing.
755 return false;
756}
757
758static Optional<Value *> getTargetValue(Instruction *Inst) {
759 GetTargetValueVisitor V;
760 return V.visit(Inst);
761}
762
763static bool hasUsefulEdges(Instruction *Inst) {
764 bool IsNonInvokeTerminator =
765 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
766 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
767}
768
769static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
770 if (isa<GlobalValue>(Val))
771 return AttrGlobalIndex;
772
773 if (auto *Arg = dyn_cast<Argument>(Val))
774 if (!Arg->hasNoAliasAttr())
775 return argNumberToAttrIndex(Arg->getArgNo());
776 return NoneType();
777}
778
779static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
George Burgess IV3c898c22015-01-21 16:37:21 +0000780 if (ArgNum >= AttrMaxNumArgs)
Hal Finkel7529c552014-09-02 21:43:13 +0000781 return AttrAllIndex;
782 return ArgNum + AttrFirstArgIndex;
783}
784
785static EdgeType flipWeight(EdgeType Initial) {
786 switch (Initial) {
787 case EdgeType::Assign:
788 return EdgeType::Assign;
789 case EdgeType::Dereference:
790 return EdgeType::Reference;
791 case EdgeType::Reference:
792 return EdgeType::Dereference;
793 }
794 llvm_unreachable("Incomplete coverage of EdgeType enum");
795}
796
797static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
798 SmallVectorImpl<Edge> &Output) {
799 GetEdgesVisitor v(Analysis, Output);
800 v.visit(Inst);
801}
802
803static Level directionOfEdgeType(EdgeType Weight) {
804 switch (Weight) {
805 case EdgeType::Reference:
806 return Level::Above;
807 case EdgeType::Dereference:
808 return Level::Below;
809 case EdgeType::Assign:
810 return Level::Same;
811 }
812 llvm_unreachable("Incomplete switch coverage");
813}
814
815// Aside: We may remove graph construction entirely, because it doesn't really
816// buy us much that we don't already have. I'd like to add interprocedural
817// analysis prior to this however, in case that somehow requires the graph
818// produced by this for efficient execution
819static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
820 SmallVectorImpl<Value *> &ReturnedValues,
821 NodeMapT &Map, GraphT &Graph) {
822 const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
823 auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
824 auto &Iter = Pair.first;
825 if (Pair.second) {
826 auto NewNode = Graph.addNode();
827 Iter->second = NewNode;
828 }
829 return Iter->second;
830 };
831
832 SmallVector<Edge, 8> Edges;
833 for (auto &Bb : Fn->getBasicBlockList()) {
834 for (auto &Inst : Bb.getInstList()) {
835 // We don't want the edges of most "return" instructions, but we *do* want
836 // to know what can be returned.
837 if (auto *Ret = dyn_cast<ReturnInst>(&Inst))
838 ReturnedValues.push_back(Ret);
839
840 if (!hasUsefulEdges(&Inst))
841 continue;
842
843 Edges.clear();
844 argsToEdges(Analysis, &Inst, Edges);
845
846 // In the case of an unused alloca (or similar), edges may be empty. Note
847 // that it exists so we can potentially answer NoAlias.
848 if (Edges.empty()) {
849 auto MaybeVal = getTargetValue(&Inst);
850 assert(MaybeVal.hasValue());
851 auto *Target = *MaybeVal;
852 findOrInsertNode(Target);
853 continue;
854 }
855
856 for (const Edge &E : Edges) {
857 auto To = findOrInsertNode(E.To);
858 auto From = findOrInsertNode(E.From);
859 auto FlippedWeight = flipWeight(E.Weight);
860 auto Attrs = E.AdditionalAttrs;
Hal Finkel1ae325f2014-09-02 23:50:01 +0000861 Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
862 std::make_pair(FlippedWeight, Attrs));
Hal Finkel7529c552014-09-02 21:43:13 +0000863 }
864 }
865 }
866}
867
868static FunctionInfo buildSetsFrom(CFLAliasAnalysis &Analysis, Function *Fn) {
869 NodeMapT Map;
870 GraphT Graph;
871 SmallVector<Value *, 4> ReturnedValues;
872
873 buildGraphFrom(Analysis, Fn, ReturnedValues, Map, Graph);
874
875 DenseMap<GraphT::Node, Value *> NodeValueMap;
876 NodeValueMap.resize(Map.size());
877 for (const auto &Pair : Map)
Hal Finkel8d1590d2014-09-02 22:52:30 +0000878 NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
Hal Finkel7529c552014-09-02 21:43:13 +0000879
880 const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
881 auto ValIter = NodeValueMap.find(Node);
882 assert(ValIter != NodeValueMap.end());
883 return ValIter->second;
884 };
885
886 StratifiedSetsBuilder<Value *> Builder;
887
888 SmallVector<GraphT::Node, 16> Worklist;
889 for (auto &Pair : Map) {
890 Worklist.clear();
891
892 auto *Value = Pair.first;
893 Builder.add(Value);
894 auto InitialNode = Pair.second;
895 Worklist.push_back(InitialNode);
896 while (!Worklist.empty()) {
897 auto Node = Worklist.pop_back_val();
898 auto *CurValue = findValueOrDie(Node);
899 if (isa<Constant>(CurValue) && !isa<GlobalValue>(CurValue))
900 continue;
901
902 for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
903 auto Weight = std::get<0>(EdgeTuple);
904 auto Label = Weight.first;
905 auto &OtherNode = std::get<1>(EdgeTuple);
906 auto *OtherValue = findValueOrDie(OtherNode);
907
908 if (isa<Constant>(OtherValue) && !isa<GlobalValue>(OtherValue))
909 continue;
910
911 bool Added;
912 switch (directionOfEdgeType(Label)) {
913 case Level::Above:
914 Added = Builder.addAbove(CurValue, OtherValue);
915 break;
916 case Level::Below:
917 Added = Builder.addBelow(CurValue, OtherValue);
918 break;
919 case Level::Same:
920 Added = Builder.addWith(CurValue, OtherValue);
921 break;
922 }
923
924 if (Added) {
925 auto Aliasing = Weight.second;
926 if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
927 Aliasing.set(*MaybeCurIndex);
928 if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
929 Aliasing.set(*MaybeOtherIndex);
930 Builder.noteAttributes(CurValue, Aliasing);
931 Builder.noteAttributes(OtherValue, Aliasing);
932 Worklist.push_back(OtherNode);
933 }
934 }
935 }
936 }
937
938 // There are times when we end up with parameters not in our graph (i.e. if
939 // it's only used as the condition of a branch). Other bits of code depend on
940 // things that were present during construction being present in the graph.
941 // So, we add all present arguments here.
942 for (auto &Arg : Fn->args()) {
943 Builder.add(&Arg);
944 }
945
Hal Finkel85f26922014-09-03 00:06:47 +0000946 return FunctionInfo(Builder.build(), std::move(ReturnedValues));
Hal Finkel7529c552014-09-02 21:43:13 +0000947}
948
949void CFLAliasAnalysis::scan(Function *Fn) {
Hal Finkel8d1590d2014-09-02 22:52:30 +0000950 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
Hal Finkel7529c552014-09-02 21:43:13 +0000951 (void)InsertPair;
952 assert(InsertPair.second &&
953 "Trying to scan a function that has already been cached");
954
955 FunctionInfo Info(buildSetsFrom(*this, Fn));
956 Cache[Fn] = std::move(Info);
957 Handles.push_front(FunctionHandle(Fn, this));
958}
959
960AliasAnalysis::AliasResult
961CFLAliasAnalysis::query(const AliasAnalysis::Location &LocA,
962 const AliasAnalysis::Location &LocB) {
963 auto *ValA = const_cast<Value *>(LocA.Ptr);
964 auto *ValB = const_cast<Value *>(LocB.Ptr);
965
966 Function *Fn = nullptr;
967 auto MaybeFnA = parentFunctionOfValue(ValA);
968 auto MaybeFnB = parentFunctionOfValue(ValB);
969 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
970 llvm_unreachable("Don't know how to extract the parent function "
971 "from values A or B");
972 }
973
974 if (MaybeFnA.hasValue()) {
975 Fn = *MaybeFnA;
976 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
977 "Interprocedural queries not supported");
978 } else {
979 Fn = *MaybeFnB;
980 }
981
982 assert(Fn != nullptr);
983 auto &MaybeInfo = ensureCached(Fn);
984 assert(MaybeInfo.hasValue());
985
986 auto &Sets = MaybeInfo->Sets;
987 auto MaybeA = Sets.find(ValA);
988 if (!MaybeA.hasValue())
989 return AliasAnalysis::MayAlias;
990
991 auto MaybeB = Sets.find(ValB);
992 if (!MaybeB.hasValue())
993 return AliasAnalysis::MayAlias;
994
995 auto SetA = *MaybeA;
996 auto SetB = *MaybeB;
997
998 if (SetA.Index == SetB.Index)
999 return AliasAnalysis::PartialAlias;
1000
1001 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
1002 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001003 // Stratified set attributes are used as markets to signify whether a member
1004 // of a StratifiedSet (or a member of a set above the current set) has
1005 // interacted with either arguments or globals. "Interacted with" meaning
1006 // its value may be different depending on the value of an argument or
1007 // global. The thought behind this is that, because arguments and globals
1008 // may alias each other, if AttrsA and AttrsB have touched args/globals,
1009 // we must conservatively say that they alias. However, if at least one of
1010 // the sets has no values that could legally be altered by changing the value
1011 // of an argument or global, then we don't have to be as conservative.
1012 if (AttrsA.any() && AttrsB.any())
1013 return AliasAnalysis::MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001014
1015 return AliasAnalysis::NoAlias;
1016}