blob: ee76317ca71efde82057e048a05c76c2aff937e0 [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"
Benjamin Kramer799003b2015-03-23 19:32:43 +000048#include "llvm/Support/raw_ostream.h"
Hal Finkel7529c552014-09-02 21:43:13 +000049#include <algorithm>
50#include <cassert>
51#include <forward_list>
Benjamin Kramer799003b2015-03-23 19:32:43 +000052#include <memory>
Hal Finkel7529c552014-09-02 21:43:13 +000053#include <tuple>
54
55using namespace llvm;
56
George Burgess IV33305e72015-02-12 03:07:07 +000057#define DEBUG_TYPE "cfl-aa"
58
Hal Finkel7529c552014-09-02 21:43:13 +000059// Try to go from a Value* to a Function*. Never returns nullptr.
60static Optional<Function *> parentFunctionOfValue(Value *);
61
62// Returns possible functions called by the Inst* into the given
63// SmallVectorImpl. Returns true if targets found, false otherwise.
64// This is templated because InvokeInst/CallInst give us the same
65// set of functions that we care about, and I don't like repeating
66// myself.
67template <typename Inst>
68static bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &);
69
70// Some instructions need to have their users tracked. Instructions like
71// `add` require you to get the users of the Instruction* itself, other
72// instructions like `store` require you to get the users of the first
73// operand. This function gets the "proper" value to track for each
74// type of instruction we support.
75static Optional<Value *> getTargetValue(Instruction *);
76
77// There are certain instructions (i.e. FenceInst, etc.) that we ignore.
78// This notes that we should ignore those.
79static bool hasUsefulEdges(Instruction *);
80
Hal Finkel1ae325f2014-09-02 23:50:01 +000081const StratifiedIndex StratifiedLink::SetSentinel =
George Burgess IV11d509d2015-03-15 00:52:21 +000082 std::numeric_limits<StratifiedIndex>::max();
Hal Finkel1ae325f2014-09-02 23:50:01 +000083
Hal Finkel7529c552014-09-02 21:43:13 +000084namespace {
85// StratifiedInfo Attribute things.
86typedef unsigned StratifiedAttr;
Hal Finkel7d7087c2014-09-02 22:13:00 +000087LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
88LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
89LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
George Burgess IVb54a8d622015-03-10 02:40:06 +000090LLVM_CONSTEXPR unsigned AttrUnknownIndex = 2;
91LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 3;
Hal Finkel7d7087c2014-09-02 22:13:00 +000092LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
93LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
Hal Finkel7529c552014-09-02 21:43:13 +000094
Hal Finkel7d7087c2014-09-02 22:13:00 +000095LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
George Burgess IVb54a8d622015-03-10 02:40:06 +000096LLVM_CONSTEXPR StratifiedAttr AttrUnknown = 1 << AttrUnknownIndex;
Hal Finkel7d7087c2014-09-02 22:13:00 +000097LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
Hal Finkel7529c552014-09-02 21:43:13 +000098
99// \brief StratifiedSets call for knowledge of "direction", so this is how we
100// represent that locally.
101enum class Level { Same, Above, Below };
102
103// \brief Edges can be one of four "weights" -- each weight must have an inverse
104// weight (Assign has Assign; Reference has Dereference).
105enum class EdgeType {
106 // The weight assigned when assigning from or to a value. For example, in:
107 // %b = getelementptr %a, 0
108 // ...The relationships are %b assign %a, and %a assign %b. This used to be
109 // two edges, but having a distinction bought us nothing.
110 Assign,
111
112 // The edge used when we have an edge going from some handle to a Value.
113 // Examples of this include:
114 // %b = load %a (%b Dereference %a)
115 // %b = extractelement %a, 0 (%a Dereference %b)
116 Dereference,
117
118 // The edge used when our edge goes from a value to a handle that may have
119 // contained it at some point. Examples:
120 // %b = load %a (%a Reference %b)
121 // %b = extractelement %a, 0 (%b Reference %a)
122 Reference
123};
124
125// \brief Encodes the notion of a "use"
126struct Edge {
127 // \brief Which value the edge is coming from
128 Value *From;
129
130 // \brief Which value the edge is pointing to
131 Value *To;
132
133 // \brief Edge weight
134 EdgeType Weight;
135
136 // \brief Whether we aliased any external values along the way that may be
137 // invisible to the analysis (i.e. landingpad for exceptions, calls for
138 // interprocedural analysis, etc.)
139 StratifiedAttrs AdditionalAttrs;
140
141 Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
142 : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
143};
144
145// \brief Information we have about a function and would like to keep around
146struct FunctionInfo {
147 StratifiedSets<Value *> Sets;
148 // Lots of functions have < 4 returns. Adjust as necessary.
149 SmallVector<Value *, 4> ReturnedValues;
Hal Finkel85f26922014-09-03 00:06:47 +0000150
George Burgess IV11d509d2015-03-15 00:52:21 +0000151 FunctionInfo(StratifiedSets<Value *> &&S, SmallVector<Value *, 4> &&RV)
152 : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
Hal Finkel7529c552014-09-02 21:43:13 +0000153};
154
155struct CFLAliasAnalysis;
156
David Blaikie7f1e0562015-03-03 21:18:16 +0000157struct FunctionHandle : public CallbackVH {
Hal Finkel7529c552014-09-02 21:43:13 +0000158 FunctionHandle(Function *Fn, CFLAliasAnalysis *CFLAA)
159 : CallbackVH(Fn), CFLAA(CFLAA) {
160 assert(Fn != nullptr);
161 assert(CFLAA != nullptr);
162 }
163
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000164 ~FunctionHandle() override {}
David Blaikie7f1e0562015-03-03 21:18:16 +0000165
David Blaikie711cd9c2014-11-14 19:06:36 +0000166 void deleted() override { removeSelfFromCache(); }
167 void allUsesReplacedWith(Value *) override { removeSelfFromCache(); }
Hal Finkel7529c552014-09-02 21:43:13 +0000168
169private:
170 CFLAliasAnalysis *CFLAA;
171
172 void removeSelfFromCache();
173};
174
175struct CFLAliasAnalysis : public ImmutablePass, public AliasAnalysis {
176private:
177 /// \brief Cached mapping of Functions to their StratifiedSets.
178 /// If a function's sets are currently being built, it is marked
179 /// in the cache as an Optional without a value. This way, if we
180 /// have any kind of recursion, it is discernable from a function
181 /// that simply has empty sets.
182 DenseMap<Function *, Optional<FunctionInfo>> Cache;
183 std::forward_list<FunctionHandle> Handles;
184
185public:
186 static char ID;
187
188 CFLAliasAnalysis() : ImmutablePass(ID) {
189 initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
190 }
191
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000192 ~CFLAliasAnalysis() override {}
Hal Finkel7529c552014-09-02 21:43:13 +0000193
Argyrios Kyrtzidis0b9f5502014-10-01 21:00:44 +0000194 void getAnalysisUsage(AnalysisUsage &AU) const override {
Hal Finkel7529c552014-09-02 21:43:13 +0000195 AliasAnalysis::getAnalysisUsage(AU);
196 }
197
198 void *getAdjustedAnalysisPointer(const void *ID) override {
199 if (ID == &AliasAnalysis::ID)
200 return (AliasAnalysis *)this;
201 return this;
202 }
203
204 /// \brief Inserts the given Function into the cache.
205 void scan(Function *Fn);
206
207 void evict(Function *Fn) { Cache.erase(Fn); }
208
209 /// \brief Ensures that the given function is available in the cache.
210 /// Returns the appropriate entry from the cache.
211 const Optional<FunctionInfo> &ensureCached(Function *Fn) {
212 auto Iter = Cache.find(Fn);
213 if (Iter == Cache.end()) {
214 scan(Fn);
215 Iter = Cache.find(Fn);
216 assert(Iter != Cache.end());
217 assert(Iter->second.hasValue());
218 }
219 return Iter->second;
220 }
221
Chandler Carruthac80dc72015-06-17 07:18:54 +0000222 AliasResult query(const MemoryLocation &LocA, const MemoryLocation &LocB);
Hal Finkel7529c552014-09-02 21:43:13 +0000223
Chandler Carruthac80dc72015-06-17 07:18:54 +0000224 AliasResult alias(const MemoryLocation &LocA,
225 const MemoryLocation &LocB) override {
Hal Finkel7529c552014-09-02 21:43:13 +0000226 if (LocA.Ptr == LocB.Ptr) {
227 if (LocA.Size == LocB.Size) {
228 return MustAlias;
229 } else {
230 return PartialAlias;
231 }
232 }
233
234 // Comparisons between global variables and other constants should be
235 // handled by BasicAA.
George Burgess IVab03af22015-03-10 02:58:15 +0000236 // TODO: ConstantExpr handling -- CFLAA may report NoAlias when comparing
237 // a GlobalValue and ConstantExpr, but every query needs to have at least
238 // one Value tied to a Function, and neither GlobalValues nor ConstantExprs
239 // are.
Hal Finkel7529c552014-09-02 21:43:13 +0000240 if (isa<Constant>(LocA.Ptr) && isa<Constant>(LocB.Ptr)) {
Daniel Berlin8f10e382015-01-26 17:30:39 +0000241 return AliasAnalysis::alias(LocA, LocB);
Hal Finkel7529c552014-09-02 21:43:13 +0000242 }
George Burgess IV33305e72015-02-12 03:07:07 +0000243
Daniel Berlin8f10e382015-01-26 17:30:39 +0000244 AliasResult QueryResult = query(LocA, LocB);
245 if (QueryResult == MayAlias)
246 return AliasAnalysis::alias(LocA, LocB);
Hal Finkel7529c552014-09-02 21:43:13 +0000247
Daniel Berlin8f10e382015-01-26 17:30:39 +0000248 return QueryResult;
Hal Finkel7529c552014-09-02 21:43:13 +0000249 }
250
Mehdi Amini46a43552015-03-04 18:43:29 +0000251 bool doInitialization(Module &M) override;
Hal Finkel7529c552014-09-02 21:43:13 +0000252};
253
254void FunctionHandle::removeSelfFromCache() {
255 assert(CFLAA != nullptr);
256 auto *Val = getValPtr();
257 CFLAA->evict(cast<Function>(Val));
258 setValPtr(nullptr);
259}
260
261// \brief Gets the edges our graph should have, based on an Instruction*
262class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
263 CFLAliasAnalysis &AA;
264 SmallVectorImpl<Edge> &Output;
265
266public:
267 GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
268 : AA(AA), Output(Output) {}
269
270 void visitInstruction(Instruction &) {
271 llvm_unreachable("Unsupported instruction encountered");
272 }
273
George Burgess IVb54a8d622015-03-10 02:40:06 +0000274 void visitPtrToIntInst(PtrToIntInst &Inst) {
275 auto *Ptr = Inst.getOperand(0);
276 Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
277 }
278
279 void visitIntToPtrInst(IntToPtrInst &Inst) {
280 auto *Ptr = &Inst;
281 Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
282 }
283
Hal Finkel7529c552014-09-02 21:43:13 +0000284 void visitCastInst(CastInst &Inst) {
George Burgess IV11d509d2015-03-15 00:52:21 +0000285 Output.push_back(
286 Edge(&Inst, Inst.getOperand(0), EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000287 }
288
289 void visitBinaryOperator(BinaryOperator &Inst) {
290 auto *Op1 = Inst.getOperand(0);
291 auto *Op2 = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000292 Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
293 Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000294 }
295
296 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
297 auto *Ptr = Inst.getPointerOperand();
298 auto *Val = Inst.getNewValOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000299 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000300 }
301
302 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
303 auto *Ptr = Inst.getPointerOperand();
304 auto *Val = Inst.getValOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000305 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000306 }
307
308 void visitPHINode(PHINode &Inst) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000309 for (Value *Val : Inst.incoming_values()) {
Hal Finkel8d1590d2014-09-02 22:52:30 +0000310 Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000311 }
312 }
313
314 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
315 auto *Op = Inst.getPointerOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000316 Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000317 for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
Hal Finkel8d1590d2014-09-02 22:52:30 +0000318 Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000319 }
320
321 void visitSelectInst(SelectInst &Inst) {
Daniel Berlin16f7a522015-01-26 17:31:17 +0000322 // Condition is not processed here (The actual statement producing
323 // the condition result is processed elsewhere). For select, the
324 // condition is evaluated, but not loaded, stored, or assigned
325 // simply as a result of being the condition of a select.
326
Hal Finkel7529c552014-09-02 21:43:13 +0000327 auto *TrueVal = Inst.getTrueValue();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000328 Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000329 auto *FalseVal = Inst.getFalseValue();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000330 Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000331 }
332
333 void visitAllocaInst(AllocaInst &) {}
334
335 void visitLoadInst(LoadInst &Inst) {
336 auto *Ptr = Inst.getPointerOperand();
337 auto *Val = &Inst;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000338 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000339 }
340
341 void visitStoreInst(StoreInst &Inst) {
342 auto *Ptr = Inst.getPointerOperand();
343 auto *Val = Inst.getValueOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000344 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000345 }
346
Hal Finkeldb5f86a2014-10-14 20:51:26 +0000347 void visitVAArgInst(VAArgInst &Inst) {
348 // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
349 // two things:
350 // 1. Loads a value from *((T*)*Ptr).
351 // 2. Increments (stores to) *Ptr by some target-specific amount.
352 // For now, we'll handle this like a landingpad instruction (by placing the
353 // result in its own group, and having that group alias externals).
354 auto *Val = &Inst;
355 Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll));
356 }
357
Hal Finkel7529c552014-09-02 21:43:13 +0000358 static bool isFunctionExternal(Function *Fn) {
359 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
360 }
361
362 // Gets whether the sets at Index1 above, below, or equal to the sets at
363 // Index2. Returns None if they are not in the same set chain.
364 static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
365 StratifiedIndex Index1,
366 StratifiedIndex Index2) {
367 if (Index1 == Index2)
368 return Level::Same;
369
370 const auto *Current = &Sets.getLink(Index1);
371 while (Current->hasBelow()) {
372 if (Current->Below == Index2)
373 return Level::Below;
374 Current = &Sets.getLink(Current->Below);
375 }
376
377 Current = &Sets.getLink(Index1);
378 while (Current->hasAbove()) {
379 if (Current->Above == Index2)
380 return Level::Above;
381 Current = &Sets.getLink(Current->Above);
382 }
383
384 return NoneType();
385 }
386
387 bool
388 tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
389 Value *FuncValue,
390 const iterator_range<User::op_iterator> &Args) {
Hal Finkelca616ac2014-09-02 23:29:48 +0000391 const unsigned ExpectedMaxArgs = 8;
392 const unsigned MaxSupportedArgs = 50;
Hal Finkel7529c552014-09-02 21:43:13 +0000393 assert(Fns.size() > 0);
394
395 // I put this here to give us an upper bound on time taken by IPA. Is it
396 // really (realistically) needed? Keep in mind that we do have an n^2 algo.
George Burgess IVab03af22015-03-10 02:58:15 +0000397 if (std::distance(Args.begin(), Args.end()) > (int)MaxSupportedArgs)
Hal Finkel7529c552014-09-02 21:43:13 +0000398 return false;
399
400 // Exit early if we'll fail anyway
401 for (auto *Fn : Fns) {
402 if (isFunctionExternal(Fn) || Fn->isVarArg())
403 return false;
404 auto &MaybeInfo = AA.ensureCached(Fn);
405 if (!MaybeInfo.hasValue())
406 return false;
407 }
408
409 SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
410 SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
411 for (auto *Fn : Fns) {
412 auto &Info = *AA.ensureCached(Fn);
413 auto &Sets = Info.Sets;
414 auto &RetVals = Info.ReturnedValues;
415
416 Parameters.clear();
417 for (auto &Param : Fn->args()) {
418 auto MaybeInfo = Sets.find(&Param);
419 // Did a new parameter somehow get added to the function/slip by?
420 if (!MaybeInfo.hasValue())
421 return false;
422 Parameters.push_back(*MaybeInfo);
423 }
424
425 // Adding an edge from argument -> return value for each parameter that
426 // may alias the return value
427 for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
428 auto &ParamInfo = Parameters[I];
429 auto &ArgVal = Arguments[I];
430 bool AddEdge = false;
431 StratifiedAttrs Externals;
432 for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
433 auto MaybeInfo = Sets.find(RetVals[X]);
434 if (!MaybeInfo.hasValue())
435 return false;
436
437 auto &RetInfo = *MaybeInfo;
438 auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
439 auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
440 auto MaybeRelation =
441 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
442 if (MaybeRelation.hasValue()) {
443 AddEdge = true;
444 Externals |= RetAttrs | ParamAttrs;
445 }
446 }
447 if (AddEdge)
Hal Finkelca616ac2014-09-02 23:29:48 +0000448 Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
George Burgess IV11d509d2015-03-15 00:52:21 +0000449 StratifiedAttrs().flip()));
Hal Finkel7529c552014-09-02 21:43:13 +0000450 }
451
452 if (Parameters.size() != Arguments.size())
453 return false;
454
455 // Adding edges between arguments for arguments that may end up aliasing
456 // each other. This is necessary for functions such as
457 // void foo(int** a, int** b) { *a = *b; }
458 // (Technically, the proper sets for this would be those below
459 // Arguments[I] and Arguments[X], but our algorithm will produce
460 // extremely similar, and equally correct, results either way)
461 for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
462 auto &MainVal = Arguments[I];
463 auto &MainInfo = Parameters[I];
464 auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
465 for (unsigned X = I + 1; X != E; ++X) {
466 auto &SubInfo = Parameters[X];
467 auto &SubVal = Arguments[X];
468 auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
469 auto MaybeRelation =
470 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
471
472 if (!MaybeRelation.hasValue())
473 continue;
474
475 auto NewAttrs = SubAttrs | MainAttrs;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000476 Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
Hal Finkel7529c552014-09-02 21:43:13 +0000477 }
478 }
479 }
480 return true;
481 }
482
483 template <typename InstT> void visitCallLikeInst(InstT &Inst) {
484 SmallVector<Function *, 4> Targets;
485 if (getPossibleTargets(&Inst, Targets)) {
486 if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
487 return;
488 // Cleanup from interprocedural analysis
489 Output.clear();
490 }
491
492 for (Value *V : Inst.arg_operands())
Hal Finkel8d1590d2014-09-02 22:52:30 +0000493 Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
Hal Finkel7529c552014-09-02 21:43:13 +0000494 }
495
496 void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
497
498 void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
499
500 // Because vectors/aggregates are immutable and unaddressable,
501 // there's nothing we can do to coax a value out of them, other
502 // than calling Extract{Element,Value}. We can effectively treat
503 // them as pointers to arbitrary memory locations we can store in
504 // and load from.
505 void visitExtractElementInst(ExtractElementInst &Inst) {
506 auto *Ptr = Inst.getVectorOperand();
507 auto *Val = &Inst;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000508 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000509 }
510
511 void visitInsertElementInst(InsertElementInst &Inst) {
512 auto *Vec = Inst.getOperand(0);
513 auto *Val = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000514 Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
515 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000516 }
517
518 void visitLandingPadInst(LandingPadInst &Inst) {
519 // Exceptions come from "nowhere", from our analysis' perspective.
520 // So we place the instruction its own group, noting that said group may
521 // alias externals
Hal Finkel8d1590d2014-09-02 22:52:30 +0000522 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
Hal Finkel7529c552014-09-02 21:43:13 +0000523 }
524
525 void visitInsertValueInst(InsertValueInst &Inst) {
526 auto *Agg = Inst.getOperand(0);
527 auto *Val = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000528 Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
529 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000530 }
531
532 void visitExtractValueInst(ExtractValueInst &Inst) {
533 auto *Ptr = Inst.getAggregateOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000534 Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000535 }
536
537 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
538 auto *From1 = Inst.getOperand(0);
539 auto *From2 = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000540 Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
541 Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000542 }
Pete Cooper36642532015-06-12 16:13:54 +0000543
544 void visitConstantExpr(ConstantExpr *CE) {
545 switch (CE->getOpcode()) {
546 default:
547 llvm_unreachable("Unknown instruction type encountered!");
548// Build the switch statement using the Instruction.def file.
549#define HANDLE_INST(NUM, OPCODE, CLASS) \
550 case Instruction::OPCODE: \
551 visit##OPCODE(*(CLASS *)CE); \
552 break;
553#include "llvm/IR/Instruction.def"
554 }
555 }
Hal Finkel7529c552014-09-02 21:43:13 +0000556};
557
558// For a given instruction, we need to know which Value* to get the
559// users of in order to build our graph. In some cases (i.e. add),
560// we simply need the Instruction*. In other cases (i.e. store),
561// finding the users of the Instruction* is useless; we need to find
562// the users of the first operand. This handles determining which
563// value to follow for us.
564//
565// Note: we *need* to keep this in sync with GetEdgesVisitor. Add
566// something to GetEdgesVisitor, add it here -- remove something from
567// GetEdgesVisitor, remove it here.
568class GetTargetValueVisitor
569 : public InstVisitor<GetTargetValueVisitor, Value *> {
570public:
571 Value *visitInstruction(Instruction &Inst) { return &Inst; }
572
573 Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
574
575 Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
576 return Inst.getPointerOperand();
577 }
578
579 Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
580 return Inst.getPointerOperand();
581 }
582
583 Value *visitInsertElementInst(InsertElementInst &Inst) {
584 return Inst.getOperand(0);
585 }
586
587 Value *visitInsertValueInst(InsertValueInst &Inst) {
588 return Inst.getAggregateOperand();
589 }
590};
591
592// Set building requires a weighted bidirectional graph.
593template <typename EdgeTypeT> class WeightedBidirectionalGraph {
594public:
595 typedef std::size_t Node;
596
597private:
Hal Finkelca616ac2014-09-02 23:29:48 +0000598 const static Node StartNode = Node(0);
Hal Finkel7529c552014-09-02 21:43:13 +0000599
600 struct Edge {
601 EdgeTypeT Weight;
602 Node Other;
603
George Burgess IV11d509d2015-03-15 00:52:21 +0000604 Edge(const EdgeTypeT &W, const Node &N) : Weight(W), Other(N) {}
Hal Finkelca616ac2014-09-02 23:29:48 +0000605
Hal Finkel7529c552014-09-02 21:43:13 +0000606 bool operator==(const Edge &E) const {
607 return Weight == E.Weight && Other == E.Other;
608 }
609
610 bool operator!=(const Edge &E) const { return !operator==(E); }
611 };
612
613 struct NodeImpl {
614 std::vector<Edge> Edges;
615 };
616
617 std::vector<NodeImpl> NodeImpls;
618
619 bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
620
621 const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
622 NodeImpl &getNode(Node N) { return NodeImpls[N]; }
623
624public:
625 // ----- Various Edge iterators for the graph ----- //
626
627 // \brief Iterator for edges. Because this graph is bidirected, we don't
628 // allow modificaiton of the edges using this iterator. Additionally, the
629 // iterator becomes invalid if you add edges to or from the node you're
630 // getting the edges of.
631 struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
632 std::tuple<EdgeTypeT, Node *>> {
633 EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
634 : Current(Iter) {}
635
636 EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
637
638 EdgeIterator &operator++() {
639 ++Current;
640 return *this;
641 }
642
643 EdgeIterator operator++(int) {
644 EdgeIterator Copy(Current);
645 operator++();
646 return Copy;
647 }
648
649 std::tuple<EdgeTypeT, Node> &operator*() {
650 Store = std::make_tuple(Current->Weight, Current->Other);
651 return Store;
652 }
653
654 bool operator==(const EdgeIterator &Other) const {
655 return Current == Other.Current;
656 }
657
658 bool operator!=(const EdgeIterator &Other) const {
659 return !operator==(Other);
660 }
661
662 private:
663 typename std::vector<Edge>::const_iterator Current;
664 std::tuple<EdgeTypeT, Node> Store;
665 };
666
667 // Wrapper for EdgeIterator with begin()/end() calls.
668 struct EdgeIterable {
669 EdgeIterable(const std::vector<Edge> &Edges)
670 : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
671
672 EdgeIterator begin() { return EdgeIterator(BeginIter); }
673
674 EdgeIterator end() { return EdgeIterator(EndIter); }
675
676 private:
677 typename std::vector<Edge>::const_iterator BeginIter;
678 typename std::vector<Edge>::const_iterator EndIter;
679 };
680
681 // ----- Actual graph-related things ----- //
682
Hal Finkelca616ac2014-09-02 23:29:48 +0000683 WeightedBidirectionalGraph() {}
Hal Finkel7529c552014-09-02 21:43:13 +0000684
685 WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
686 : NodeImpls(std::move(Other.NodeImpls)) {}
687
688 WeightedBidirectionalGraph<EdgeTypeT> &
689 operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
690 NodeImpls = std::move(Other.NodeImpls);
691 return *this;
692 }
693
694 Node addNode() {
695 auto Index = NodeImpls.size();
696 auto NewNode = Node(Index);
697 NodeImpls.push_back(NodeImpl());
698 return NewNode;
699 }
700
701 void addEdge(Node From, Node To, const EdgeTypeT &Weight,
702 const EdgeTypeT &ReverseWeight) {
703 assert(inbounds(From));
704 assert(inbounds(To));
705 auto &FromNode = getNode(From);
706 auto &ToNode = getNode(To);
Hal Finkelca616ac2014-09-02 23:29:48 +0000707 FromNode.Edges.push_back(Edge(Weight, To));
708 ToNode.Edges.push_back(Edge(ReverseWeight, From));
Hal Finkel7529c552014-09-02 21:43:13 +0000709 }
710
711 EdgeIterable edgesFor(const Node &N) const {
712 const auto &Node = getNode(N);
713 return EdgeIterable(Node.Edges);
714 }
715
716 bool empty() const { return NodeImpls.empty(); }
717 std::size_t size() const { return NodeImpls.size(); }
718
719 // \brief Gets an arbitrary node in the graph as a starting point for
720 // traversal.
721 Node getEntryNode() {
722 assert(inbounds(StartNode));
723 return StartNode;
724 }
725};
726
727typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
728typedef DenseMap<Value *, GraphT::Node> NodeMapT;
729}
730
731// -- Setting up/registering CFLAA pass -- //
732char CFLAliasAnalysis::ID = 0;
733
734INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
735 "CFL-Based AA implementation", false, true, false)
736
737ImmutablePass *llvm::createCFLAliasAnalysisPass() {
738 return new CFLAliasAnalysis();
739}
740
741//===----------------------------------------------------------------------===//
742// Function declarations that require types defined in the namespace above
743//===----------------------------------------------------------------------===//
744
745// Given an argument number, returns the appropriate Attr index to set.
746static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
747
748// Given a Value, potentially return which AttrIndex it maps to.
749static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
750
751// Gets the inverse of a given EdgeType.
752static EdgeType flipWeight(EdgeType);
753
754// Gets edges of the given Instruction*, writing them to the SmallVector*.
755static void argsToEdges(CFLAliasAnalysis &, Instruction *,
756 SmallVectorImpl<Edge> &);
757
Pete Cooper36642532015-06-12 16:13:54 +0000758// Gets edges of the given ConstantExpr*, writing them to the SmallVector*.
759static void argsToEdges(CFLAliasAnalysis &, ConstantExpr *,
760 SmallVectorImpl<Edge> &);
761
Hal Finkel7529c552014-09-02 21:43:13 +0000762// Gets the "Level" that one should travel in StratifiedSets
763// given an EdgeType.
764static Level directionOfEdgeType(EdgeType);
765
766// Builds the graph needed for constructing the StratifiedSets for the
767// given function
768static void buildGraphFrom(CFLAliasAnalysis &, Function *,
769 SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
770
George Burgess IVab03af22015-03-10 02:58:15 +0000771// Gets the edges of a ConstantExpr as if it was an Instruction. This
772// function also acts on any nested ConstantExprs, adding the edges
773// of those to the given SmallVector as well.
774static void constexprToEdges(CFLAliasAnalysis &, ConstantExpr &,
775 SmallVectorImpl<Edge> &);
776
777// Given an Instruction, this will add it to the graph, along with any
778// Instructions that are potentially only available from said Instruction
779// For example, given the following line:
780// %0 = load i16* getelementptr ([1 x i16]* @a, 0, 0), align 2
781// addInstructionToGraph would add both the `load` and `getelementptr`
782// instructions to the graph appropriately.
783static void addInstructionToGraph(CFLAliasAnalysis &, Instruction &,
784 SmallVectorImpl<Value *> &, NodeMapT &,
785 GraphT &);
786
787// Notes whether it would be pointless to add the given Value to our sets.
788static bool canSkipAddingToSets(Value *Val);
789
Hal Finkel7529c552014-09-02 21:43:13 +0000790// Builds the graph + StratifiedSets for a function.
791static FunctionInfo buildSetsFrom(CFLAliasAnalysis &, Function *);
792
793static Optional<Function *> parentFunctionOfValue(Value *Val) {
794 if (auto *Inst = dyn_cast<Instruction>(Val)) {
795 auto *Bb = Inst->getParent();
796 return Bb->getParent();
797 }
798
799 if (auto *Arg = dyn_cast<Argument>(Val))
800 return Arg->getParent();
801 return NoneType();
802}
803
804template <typename Inst>
805static bool getPossibleTargets(Inst *Call,
806 SmallVectorImpl<Function *> &Output) {
807 if (auto *Fn = Call->getCalledFunction()) {
808 Output.push_back(Fn);
809 return true;
810 }
811
812 // TODO: If the call is indirect, we might be able to enumerate all potential
813 // targets of the call and return them, rather than just failing.
814 return false;
815}
816
817static Optional<Value *> getTargetValue(Instruction *Inst) {
818 GetTargetValueVisitor V;
819 return V.visit(Inst);
820}
821
822static bool hasUsefulEdges(Instruction *Inst) {
823 bool IsNonInvokeTerminator =
824 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
825 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
826}
827
Pete Cooper36642532015-06-12 16:13:54 +0000828static bool hasUsefulEdges(ConstantExpr *CE) {
829 // ConstantExpr doens't have terminators, invokes, or fences, so only needs
830 // to check for compares.
831 return CE->getOpcode() != Instruction::ICmp &&
832 CE->getOpcode() != Instruction::FCmp;
833}
834
Hal Finkel7529c552014-09-02 21:43:13 +0000835static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
836 if (isa<GlobalValue>(Val))
837 return AttrGlobalIndex;
838
839 if (auto *Arg = dyn_cast<Argument>(Val))
Daniel Berlin16f7a522015-01-26 17:31:17 +0000840 // Only pointer arguments should have the argument attribute,
841 // because things can't escape through scalars without us seeing a
842 // cast, and thus, interaction with them doesn't matter.
843 if (!Arg->hasNoAliasAttr() && Arg->getType()->isPointerTy())
Hal Finkel7529c552014-09-02 21:43:13 +0000844 return argNumberToAttrIndex(Arg->getArgNo());
845 return NoneType();
846}
847
848static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
George Burgess IV3c898c22015-01-21 16:37:21 +0000849 if (ArgNum >= AttrMaxNumArgs)
Hal Finkel7529c552014-09-02 21:43:13 +0000850 return AttrAllIndex;
851 return ArgNum + AttrFirstArgIndex;
852}
853
854static EdgeType flipWeight(EdgeType Initial) {
855 switch (Initial) {
856 case EdgeType::Assign:
857 return EdgeType::Assign;
858 case EdgeType::Dereference:
859 return EdgeType::Reference;
860 case EdgeType::Reference:
861 return EdgeType::Dereference;
862 }
863 llvm_unreachable("Incomplete coverage of EdgeType enum");
864}
865
866static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
867 SmallVectorImpl<Edge> &Output) {
George Burgess IVab03af22015-03-10 02:58:15 +0000868 assert(hasUsefulEdges(Inst) &&
869 "Expected instructions to have 'useful' edges");
Hal Finkel7529c552014-09-02 21:43:13 +0000870 GetEdgesVisitor v(Analysis, Output);
871 v.visit(Inst);
872}
873
Pete Cooper36642532015-06-12 16:13:54 +0000874static void argsToEdges(CFLAliasAnalysis &Analysis, ConstantExpr *CE,
875 SmallVectorImpl<Edge> &Output) {
876 assert(hasUsefulEdges(CE) && "Expected constant expr to have 'useful' edges");
877 GetEdgesVisitor v(Analysis, Output);
878 v.visitConstantExpr(CE);
879}
880
Hal Finkel7529c552014-09-02 21:43:13 +0000881static Level directionOfEdgeType(EdgeType Weight) {
882 switch (Weight) {
883 case EdgeType::Reference:
884 return Level::Above;
885 case EdgeType::Dereference:
886 return Level::Below;
887 case EdgeType::Assign:
888 return Level::Same;
889 }
890 llvm_unreachable("Incomplete switch coverage");
891}
892
George Burgess IVab03af22015-03-10 02:58:15 +0000893static void constexprToEdges(CFLAliasAnalysis &Analysis,
894 ConstantExpr &CExprToCollapse,
895 SmallVectorImpl<Edge> &Results) {
896 SmallVector<ConstantExpr *, 4> Worklist;
897 Worklist.push_back(&CExprToCollapse);
898
899 SmallVector<Edge, 8> ConstexprEdges;
Pete Cooper36642532015-06-12 16:13:54 +0000900 SmallPtrSet<ConstantExpr *, 4> Visited;
George Burgess IVab03af22015-03-10 02:58:15 +0000901 while (!Worklist.empty()) {
902 auto *CExpr = Worklist.pop_back_val();
George Burgess IVab03af22015-03-10 02:58:15 +0000903
Pete Cooper36642532015-06-12 16:13:54 +0000904 if (!hasUsefulEdges(CExpr))
George Burgess IVab03af22015-03-10 02:58:15 +0000905 continue;
906
907 ConstexprEdges.clear();
Pete Cooper36642532015-06-12 16:13:54 +0000908 argsToEdges(Analysis, CExpr, ConstexprEdges);
George Burgess IVab03af22015-03-10 02:58:15 +0000909 for (auto &Edge : ConstexprEdges) {
Pete Cooper36642532015-06-12 16:13:54 +0000910 if (auto *Nested = dyn_cast<ConstantExpr>(Edge.From))
911 if (Visited.insert(Nested).second)
912 Worklist.push_back(Nested);
George Burgess IVab03af22015-03-10 02:58:15 +0000913
Pete Cooper36642532015-06-12 16:13:54 +0000914 if (auto *Nested = dyn_cast<ConstantExpr>(Edge.To))
915 if (Visited.insert(Nested).second)
916 Worklist.push_back(Nested);
George Burgess IVab03af22015-03-10 02:58:15 +0000917 }
918
919 Results.append(ConstexprEdges.begin(), ConstexprEdges.end());
920 }
921}
922
923static void addInstructionToGraph(CFLAliasAnalysis &Analysis, Instruction &Inst,
924 SmallVectorImpl<Value *> &ReturnedValues,
925 NodeMapT &Map, GraphT &Graph) {
Hal Finkel7529c552014-09-02 21:43:13 +0000926 const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
927 auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
928 auto &Iter = Pair.first;
929 if (Pair.second) {
930 auto NewNode = Graph.addNode();
931 Iter->second = NewNode;
932 }
933 return Iter->second;
934 };
935
George Burgess IVab03af22015-03-10 02:58:15 +0000936 // We don't want the edges of most "return" instructions, but we *do* want
937 // to know what can be returned.
938 if (isa<ReturnInst>(&Inst))
939 ReturnedValues.push_back(&Inst);
940
941 if (!hasUsefulEdges(&Inst))
942 return;
943
Hal Finkel7529c552014-09-02 21:43:13 +0000944 SmallVector<Edge, 8> Edges;
George Burgess IVab03af22015-03-10 02:58:15 +0000945 argsToEdges(Analysis, &Inst, Edges);
Hal Finkel7529c552014-09-02 21:43:13 +0000946
George Burgess IVab03af22015-03-10 02:58:15 +0000947 // In the case of an unused alloca (or similar), edges may be empty. Note
948 // that it exists so we can potentially answer NoAlias.
949 if (Edges.empty()) {
950 auto MaybeVal = getTargetValue(&Inst);
951 assert(MaybeVal.hasValue());
952 auto *Target = *MaybeVal;
953 findOrInsertNode(Target);
954 return;
Hal Finkel7529c552014-09-02 21:43:13 +0000955 }
George Burgess IVab03af22015-03-10 02:58:15 +0000956
957 const auto addEdgeToGraph = [&Graph, &findOrInsertNode](const Edge &E) {
958 auto To = findOrInsertNode(E.To);
959 auto From = findOrInsertNode(E.From);
960 auto FlippedWeight = flipWeight(E.Weight);
961 auto Attrs = E.AdditionalAttrs;
962 Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
963 std::make_pair(FlippedWeight, Attrs));
964 };
965
966 SmallVector<ConstantExpr *, 4> ConstantExprs;
967 for (const Edge &E : Edges) {
968 addEdgeToGraph(E);
969 if (auto *Constexpr = dyn_cast<ConstantExpr>(E.To))
970 ConstantExprs.push_back(Constexpr);
971 if (auto *Constexpr = dyn_cast<ConstantExpr>(E.From))
972 ConstantExprs.push_back(Constexpr);
973 }
974
975 for (ConstantExpr *CE : ConstantExprs) {
976 Edges.clear();
977 constexprToEdges(Analysis, *CE, Edges);
978 std::for_each(Edges.begin(), Edges.end(), addEdgeToGraph);
979 }
980}
981
982// Aside: We may remove graph construction entirely, because it doesn't really
983// buy us much that we don't already have. I'd like to add interprocedural
984// analysis prior to this however, in case that somehow requires the graph
985// produced by this for efficient execution
986static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
987 SmallVectorImpl<Value *> &ReturnedValues,
988 NodeMapT &Map, GraphT &Graph) {
989 for (auto &Bb : Fn->getBasicBlockList())
990 for (auto &Inst : Bb.getInstList())
991 addInstructionToGraph(Analysis, Inst, ReturnedValues, Map, Graph);
992}
993
994static bool canSkipAddingToSets(Value *Val) {
995 // Constants can share instances, which may falsely unify multiple
996 // sets, e.g. in
997 // store i32* null, i32** %ptr1
998 // store i32* null, i32** %ptr2
999 // clearly ptr1 and ptr2 should not be unified into the same set, so
1000 // we should filter out the (potentially shared) instance to
1001 // i32* null.
1002 if (isa<Constant>(Val)) {
1003 bool Container = isa<ConstantVector>(Val) || isa<ConstantArray>(Val) ||
1004 isa<ConstantStruct>(Val);
1005 // TODO: Because all of these things are constant, we can determine whether
1006 // the data is *actually* mutable at graph building time. This will probably
1007 // come for free/cheap with offset awareness.
1008 bool CanStoreMutableData =
1009 isa<GlobalValue>(Val) || isa<ConstantExpr>(Val) || Container;
1010 return !CanStoreMutableData;
1011 }
1012
1013 return false;
Hal Finkel7529c552014-09-02 21:43:13 +00001014}
1015
1016static FunctionInfo buildSetsFrom(CFLAliasAnalysis &Analysis, Function *Fn) {
1017 NodeMapT Map;
1018 GraphT Graph;
1019 SmallVector<Value *, 4> ReturnedValues;
1020
1021 buildGraphFrom(Analysis, Fn, ReturnedValues, Map, Graph);
1022
1023 DenseMap<GraphT::Node, Value *> NodeValueMap;
1024 NodeValueMap.resize(Map.size());
1025 for (const auto &Pair : Map)
Hal Finkel8d1590d2014-09-02 22:52:30 +00001026 NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
Hal Finkel7529c552014-09-02 21:43:13 +00001027
1028 const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
1029 auto ValIter = NodeValueMap.find(Node);
1030 assert(ValIter != NodeValueMap.end());
1031 return ValIter->second;
1032 };
1033
1034 StratifiedSetsBuilder<Value *> Builder;
1035
1036 SmallVector<GraphT::Node, 16> Worklist;
1037 for (auto &Pair : Map) {
1038 Worklist.clear();
1039
1040 auto *Value = Pair.first;
1041 Builder.add(Value);
1042 auto InitialNode = Pair.second;
1043 Worklist.push_back(InitialNode);
1044 while (!Worklist.empty()) {
1045 auto Node = Worklist.pop_back_val();
1046 auto *CurValue = findValueOrDie(Node);
George Burgess IVab03af22015-03-10 02:58:15 +00001047 if (canSkipAddingToSets(CurValue))
Hal Finkel7529c552014-09-02 21:43:13 +00001048 continue;
1049
1050 for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
1051 auto Weight = std::get<0>(EdgeTuple);
1052 auto Label = Weight.first;
1053 auto &OtherNode = std::get<1>(EdgeTuple);
1054 auto *OtherValue = findValueOrDie(OtherNode);
1055
George Burgess IVab03af22015-03-10 02:58:15 +00001056 if (canSkipAddingToSets(OtherValue))
Hal Finkel7529c552014-09-02 21:43:13 +00001057 continue;
1058
1059 bool Added;
1060 switch (directionOfEdgeType(Label)) {
1061 case Level::Above:
1062 Added = Builder.addAbove(CurValue, OtherValue);
1063 break;
1064 case Level::Below:
1065 Added = Builder.addBelow(CurValue, OtherValue);
1066 break;
1067 case Level::Same:
1068 Added = Builder.addWith(CurValue, OtherValue);
1069 break;
1070 }
1071
George Burgess IVb54a8d622015-03-10 02:40:06 +00001072 auto Aliasing = Weight.second;
1073 if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
1074 Aliasing.set(*MaybeCurIndex);
1075 if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
1076 Aliasing.set(*MaybeOtherIndex);
1077 Builder.noteAttributes(CurValue, Aliasing);
1078 Builder.noteAttributes(OtherValue, Aliasing);
1079
1080 if (Added)
Hal Finkel7529c552014-09-02 21:43:13 +00001081 Worklist.push_back(OtherNode);
Hal Finkel7529c552014-09-02 21:43:13 +00001082 }
1083 }
1084 }
1085
1086 // There are times when we end up with parameters not in our graph (i.e. if
1087 // it's only used as the condition of a branch). Other bits of code depend on
1088 // things that were present during construction being present in the graph.
1089 // So, we add all present arguments here.
1090 for (auto &Arg : Fn->args()) {
George Burgess IVab03af22015-03-10 02:58:15 +00001091 if (!Builder.add(&Arg))
1092 continue;
1093
1094 auto Attrs = valueToAttrIndex(&Arg);
1095 if (Attrs.hasValue())
1096 Builder.noteAttributes(&Arg, *Attrs);
Hal Finkel7529c552014-09-02 21:43:13 +00001097 }
1098
Hal Finkel85f26922014-09-03 00:06:47 +00001099 return FunctionInfo(Builder.build(), std::move(ReturnedValues));
Hal Finkel7529c552014-09-02 21:43:13 +00001100}
1101
1102void CFLAliasAnalysis::scan(Function *Fn) {
Hal Finkel8d1590d2014-09-02 22:52:30 +00001103 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
Hal Finkel7529c552014-09-02 21:43:13 +00001104 (void)InsertPair;
1105 assert(InsertPair.second &&
1106 "Trying to scan a function that has already been cached");
1107
1108 FunctionInfo Info(buildSetsFrom(*this, Fn));
1109 Cache[Fn] = std::move(Info);
1110 Handles.push_front(FunctionHandle(Fn, this));
1111}
1112
Chandler Carruthac80dc72015-06-17 07:18:54 +00001113AliasAnalysis::AliasResult CFLAliasAnalysis::query(const MemoryLocation &LocA,
1114 const MemoryLocation &LocB) {
Hal Finkel7529c552014-09-02 21:43:13 +00001115 auto *ValA = const_cast<Value *>(LocA.Ptr);
1116 auto *ValB = const_cast<Value *>(LocB.Ptr);
1117
1118 Function *Fn = nullptr;
1119 auto MaybeFnA = parentFunctionOfValue(ValA);
1120 auto MaybeFnB = parentFunctionOfValue(ValB);
1121 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
George Burgess IV33305e72015-02-12 03:07:07 +00001122 // The only times this is known to happen are when globals + InlineAsm
1123 // are involved
1124 DEBUG(dbgs() << "CFLAA: could not extract parent function information.\n");
1125 return AliasAnalysis::MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001126 }
1127
1128 if (MaybeFnA.hasValue()) {
1129 Fn = *MaybeFnA;
1130 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
1131 "Interprocedural queries not supported");
1132 } else {
1133 Fn = *MaybeFnB;
1134 }
1135
1136 assert(Fn != nullptr);
1137 auto &MaybeInfo = ensureCached(Fn);
1138 assert(MaybeInfo.hasValue());
1139
1140 auto &Sets = MaybeInfo->Sets;
1141 auto MaybeA = Sets.find(ValA);
1142 if (!MaybeA.hasValue())
1143 return AliasAnalysis::MayAlias;
1144
1145 auto MaybeB = Sets.find(ValB);
1146 if (!MaybeB.hasValue())
1147 return AliasAnalysis::MayAlias;
1148
1149 auto SetA = *MaybeA;
1150 auto SetB = *MaybeB;
Hal Finkel7529c552014-09-02 21:43:13 +00001151 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
1152 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
George Burgess IV33305e72015-02-12 03:07:07 +00001153
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001154 // Stratified set attributes are used as markets to signify whether a member
George Burgess IV33305e72015-02-12 03:07:07 +00001155 // of a StratifiedSet (or a member of a set above the current set) has
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001156 // interacted with either arguments or globals. "Interacted with" meaning
George Burgess IV33305e72015-02-12 03:07:07 +00001157 // its value may be different depending on the value of an argument or
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001158 // global. The thought behind this is that, because arguments and globals
1159 // may alias each other, if AttrsA and AttrsB have touched args/globals,
George Burgess IV33305e72015-02-12 03:07:07 +00001160 // we must conservatively say that they alias. However, if at least one of
1161 // the sets has no values that could legally be altered by changing the value
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001162 // of an argument or global, then we don't have to be as conservative.
1163 if (AttrsA.any() && AttrsB.any())
1164 return AliasAnalysis::MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001165
Daniel Berlin16f7a522015-01-26 17:31:17 +00001166 // We currently unify things even if the accesses to them may not be in
1167 // bounds, so we can't return partial alias here because we don't
1168 // know whether the pointer is really within the object or not.
1169 // IE Given an out of bounds GEP and an alloca'd pointer, we may
1170 // unify the two. We can't return partial alias for this case.
1171 // Since we do not currently track enough information to
1172 // differentiate
1173
1174 if (SetA.Index == SetB.Index)
1175 return AliasAnalysis::MayAlias;
1176
Hal Finkel7529c552014-09-02 21:43:13 +00001177 return AliasAnalysis::NoAlias;
1178}
Mehdi Amini46a43552015-03-04 18:43:29 +00001179
1180bool CFLAliasAnalysis::doInitialization(Module &M) {
1181 InitializeAliasAnalysis(this, &M.getDataLayout());
1182 return true;
1183}