blob: 729f7e412a89060618df527e86cd6cd80997a56c [file] [log] [blame]
Hal Finkel7529c552014-09-02 21:43:13 +00001//===- CFLAliasAnalysis.cpp - CFL-Based Alias Analysis Implementation ------==//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a CFL-based context-insensitive alias analysis
11// algorithm. It does not depend on types. The algorithm is a mixture of the one
12// described in "Demand-driven alias analysis for C" by Xin Zheng and Radu
13// Rugina, and "Fast algorithms for Dyck-CFL-reachability with applications to
14// Alias Analysis" by Zhang Q, Lyu M R, Yuan H, and Su Z. -- to summarize the
15// papers, we build a graph of the uses of a variable, where each node is a
16// memory location, and each edge is an action that happened on that memory
Chad Rosier38c6ad22015-06-19 17:32:57 +000017// location. The "actions" can be one of Dereference, Reference, or Assign.
Hal Finkel7529c552014-09-02 21:43:13 +000018//
19// Two variables are considered as aliasing iff you can reach one value's node
20// from the other value's node and the language formed by concatenating all of
21// the edge labels (actions) conforms to a context-free grammar.
22//
23// Because this algorithm requires a graph search on each query, we execute the
24// algorithm outlined in "Fast algorithms..." (mentioned above)
25// in order to transform the graph into sets of variables that may alias in
26// ~nlogn time (n = number of variables.), which makes queries take constant
27// time.
28//===----------------------------------------------------------------------===//
29
Chandler Carruth8b046a42015-08-14 02:42:20 +000030#include "llvm/Analysis/CFLAliasAnalysis.h"
Hal Finkel7529c552014-09-02 21:43:13 +000031#include "StratifiedSets.h"
Hal Finkel7529c552014-09-02 21:43:13 +000032#include "llvm/ADT/BitVector.h"
33#include "llvm/ADT/DenseMap.h"
Hal Finkel7529c552014-09-02 21:43:13 +000034#include "llvm/ADT/None.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000035#include "llvm/ADT/Optional.h"
Hal Finkel7529c552014-09-02 21:43:13 +000036#include "llvm/Analysis/AliasAnalysis.h"
37#include "llvm/IR/Constants.h"
38#include "llvm/IR/Function.h"
Hal Finkel7529c552014-09-02 21:43:13 +000039#include "llvm/IR/InstVisitor.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000040#include "llvm/IR/Instructions.h"
Hal Finkel7529c552014-09-02 21:43:13 +000041#include "llvm/Pass.h"
42#include "llvm/Support/Allocator.h"
Hal Finkel7d7087c2014-09-02 22:13:00 +000043#include "llvm/Support/Compiler.h"
George Burgess IV33305e72015-02-12 03:07:07 +000044#include "llvm/Support/Debug.h"
Hal Finkel7529c552014-09-02 21:43:13 +000045#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000046#include "llvm/Support/raw_ostream.h"
Hal Finkel7529c552014-09-02 21:43:13 +000047#include <algorithm>
48#include <cassert>
Benjamin Kramer799003b2015-03-23 19:32:43 +000049#include <memory>
Hal Finkel7529c552014-09-02 21:43:13 +000050#include <tuple>
51
52using namespace llvm;
53
George Burgess IV33305e72015-02-12 03:07:07 +000054#define DEBUG_TYPE "cfl-aa"
55
Chandler Carruth8b046a42015-08-14 02:42:20 +000056// -- Setting up/registering CFLAA pass -- //
57char CFLAliasAnalysis::ID = 0;
58
59INITIALIZE_AG_PASS(CFLAliasAnalysis, AliasAnalysis, "cfl-aa",
60 "CFL-Based AA implementation", false, true, false)
61
62ImmutablePass *llvm::createCFLAliasAnalysisPass() {
63 return new CFLAliasAnalysis();
64}
65
66// \brief Information we have about a function and would like to keep around
67struct CFLAliasAnalysis::FunctionInfo {
68 StratifiedSets<Value *> Sets;
69 // Lots of functions have < 4 returns. Adjust as necessary.
70 SmallVector<Value *, 4> ReturnedValues;
71
72 FunctionInfo(StratifiedSets<Value *> &&S, SmallVector<Value *, 4> &&RV)
73 : Sets(std::move(S)), ReturnedValues(std::move(RV)) {}
74};
75
Chandler Carruth8b046a42015-08-14 02:42:20 +000076CFLAliasAnalysis::CFLAliasAnalysis() : ImmutablePass(ID) {
77 initializeCFLAliasAnalysisPass(*PassRegistry::getPassRegistry());
78}
79
80CFLAliasAnalysis::~CFLAliasAnalysis() {}
81
82void CFLAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
83 AliasAnalysis::getAnalysisUsage(AU);
84}
85
86void *CFLAliasAnalysis::getAdjustedAnalysisPointer(const void *ID) {
87 if (ID == &AliasAnalysis::ID)
88 return (AliasAnalysis *)this;
89 return this;
90}
91
Hal Finkel7529c552014-09-02 21:43:13 +000092// Try to go from a Value* to a Function*. Never returns nullptr.
93static Optional<Function *> parentFunctionOfValue(Value *);
94
95// Returns possible functions called by the Inst* into the given
96// SmallVectorImpl. Returns true if targets found, false otherwise.
97// This is templated because InvokeInst/CallInst give us the same
98// set of functions that we care about, and I don't like repeating
99// myself.
100template <typename Inst>
101static bool getPossibleTargets(Inst *, SmallVectorImpl<Function *> &);
102
103// Some instructions need to have their users tracked. Instructions like
104// `add` require you to get the users of the Instruction* itself, other
105// instructions like `store` require you to get the users of the first
106// operand. This function gets the "proper" value to track for each
107// type of instruction we support.
108static Optional<Value *> getTargetValue(Instruction *);
109
110// There are certain instructions (i.e. FenceInst, etc.) that we ignore.
111// This notes that we should ignore those.
112static bool hasUsefulEdges(Instruction *);
113
Hal Finkel1ae325f2014-09-02 23:50:01 +0000114const StratifiedIndex StratifiedLink::SetSentinel =
George Burgess IV11d509d2015-03-15 00:52:21 +0000115 std::numeric_limits<StratifiedIndex>::max();
Hal Finkel1ae325f2014-09-02 23:50:01 +0000116
Hal Finkel7529c552014-09-02 21:43:13 +0000117namespace {
118// StratifiedInfo Attribute things.
119typedef unsigned StratifiedAttr;
Hal Finkel7d7087c2014-09-02 22:13:00 +0000120LLVM_CONSTEXPR unsigned MaxStratifiedAttrIndex = NumStratifiedAttrs;
121LLVM_CONSTEXPR unsigned AttrAllIndex = 0;
122LLVM_CONSTEXPR unsigned AttrGlobalIndex = 1;
George Burgess IVb54a8d622015-03-10 02:40:06 +0000123LLVM_CONSTEXPR unsigned AttrUnknownIndex = 2;
124LLVM_CONSTEXPR unsigned AttrFirstArgIndex = 3;
Hal Finkel7d7087c2014-09-02 22:13:00 +0000125LLVM_CONSTEXPR unsigned AttrLastArgIndex = MaxStratifiedAttrIndex;
126LLVM_CONSTEXPR unsigned AttrMaxNumArgs = AttrLastArgIndex - AttrFirstArgIndex;
Hal Finkel7529c552014-09-02 21:43:13 +0000127
Hal Finkel7d7087c2014-09-02 22:13:00 +0000128LLVM_CONSTEXPR StratifiedAttr AttrNone = 0;
George Burgess IVb54a8d622015-03-10 02:40:06 +0000129LLVM_CONSTEXPR StratifiedAttr AttrUnknown = 1 << AttrUnknownIndex;
Hal Finkel7d7087c2014-09-02 22:13:00 +0000130LLVM_CONSTEXPR StratifiedAttr AttrAll = ~AttrNone;
Hal Finkel7529c552014-09-02 21:43:13 +0000131
132// \brief StratifiedSets call for knowledge of "direction", so this is how we
133// represent that locally.
134enum class Level { Same, Above, Below };
135
136// \brief Edges can be one of four "weights" -- each weight must have an inverse
137// weight (Assign has Assign; Reference has Dereference).
138enum class EdgeType {
139 // The weight assigned when assigning from or to a value. For example, in:
140 // %b = getelementptr %a, 0
141 // ...The relationships are %b assign %a, and %a assign %b. This used to be
142 // two edges, but having a distinction bought us nothing.
143 Assign,
144
145 // The edge used when we have an edge going from some handle to a Value.
146 // Examples of this include:
147 // %b = load %a (%b Dereference %a)
148 // %b = extractelement %a, 0 (%a Dereference %b)
149 Dereference,
150
151 // The edge used when our edge goes from a value to a handle that may have
152 // contained it at some point. Examples:
153 // %b = load %a (%a Reference %b)
154 // %b = extractelement %a, 0 (%b Reference %a)
155 Reference
156};
157
158// \brief Encodes the notion of a "use"
159struct Edge {
160 // \brief Which value the edge is coming from
161 Value *From;
162
163 // \brief Which value the edge is pointing to
164 Value *To;
165
166 // \brief Edge weight
167 EdgeType Weight;
168
169 // \brief Whether we aliased any external values along the way that may be
170 // invisible to the analysis (i.e. landingpad for exceptions, calls for
171 // interprocedural analysis, etc.)
172 StratifiedAttrs AdditionalAttrs;
173
174 Edge(Value *From, Value *To, EdgeType W, StratifiedAttrs A)
175 : From(From), To(To), Weight(W), AdditionalAttrs(A) {}
176};
177
Hal Finkel7529c552014-09-02 21:43:13 +0000178// \brief Gets the edges our graph should have, based on an Instruction*
179class GetEdgesVisitor : public InstVisitor<GetEdgesVisitor, void> {
180 CFLAliasAnalysis &AA;
181 SmallVectorImpl<Edge> &Output;
182
183public:
184 GetEdgesVisitor(CFLAliasAnalysis &AA, SmallVectorImpl<Edge> &Output)
185 : AA(AA), Output(Output) {}
186
187 void visitInstruction(Instruction &) {
188 llvm_unreachable("Unsupported instruction encountered");
189 }
190
George Burgess IVb54a8d622015-03-10 02:40:06 +0000191 void visitPtrToIntInst(PtrToIntInst &Inst) {
192 auto *Ptr = Inst.getOperand(0);
193 Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
194 }
195
196 void visitIntToPtrInst(IntToPtrInst &Inst) {
197 auto *Ptr = &Inst;
198 Output.push_back(Edge(Ptr, Ptr, EdgeType::Assign, AttrUnknown));
199 }
200
Hal Finkel7529c552014-09-02 21:43:13 +0000201 void visitCastInst(CastInst &Inst) {
George Burgess IV11d509d2015-03-15 00:52:21 +0000202 Output.push_back(
203 Edge(&Inst, Inst.getOperand(0), EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000204 }
205
206 void visitBinaryOperator(BinaryOperator &Inst) {
207 auto *Op1 = Inst.getOperand(0);
208 auto *Op2 = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000209 Output.push_back(Edge(&Inst, Op1, EdgeType::Assign, AttrNone));
210 Output.push_back(Edge(&Inst, Op2, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000211 }
212
213 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
214 auto *Ptr = Inst.getPointerOperand();
215 auto *Val = Inst.getNewValOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000216 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000217 }
218
219 void visitAtomicRMWInst(AtomicRMWInst &Inst) {
220 auto *Ptr = Inst.getPointerOperand();
221 auto *Val = Inst.getValOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000222 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000223 }
224
225 void visitPHINode(PHINode &Inst) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000226 for (Value *Val : Inst.incoming_values()) {
Hal Finkel8d1590d2014-09-02 22:52:30 +0000227 Output.push_back(Edge(&Inst, Val, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000228 }
229 }
230
231 void visitGetElementPtrInst(GetElementPtrInst &Inst) {
232 auto *Op = Inst.getPointerOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000233 Output.push_back(Edge(&Inst, Op, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000234 for (auto I = Inst.idx_begin(), E = Inst.idx_end(); I != E; ++I)
Hal Finkel8d1590d2014-09-02 22:52:30 +0000235 Output.push_back(Edge(&Inst, *I, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000236 }
237
238 void visitSelectInst(SelectInst &Inst) {
Daniel Berlin16f7a522015-01-26 17:31:17 +0000239 // Condition is not processed here (The actual statement producing
240 // the condition result is processed elsewhere). For select, the
241 // condition is evaluated, but not loaded, stored, or assigned
242 // simply as a result of being the condition of a select.
243
Hal Finkel7529c552014-09-02 21:43:13 +0000244 auto *TrueVal = Inst.getTrueValue();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000245 Output.push_back(Edge(&Inst, TrueVal, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000246 auto *FalseVal = Inst.getFalseValue();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000247 Output.push_back(Edge(&Inst, FalseVal, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000248 }
249
250 void visitAllocaInst(AllocaInst &) {}
251
252 void visitLoadInst(LoadInst &Inst) {
253 auto *Ptr = Inst.getPointerOperand();
254 auto *Val = &Inst;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000255 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000256 }
257
258 void visitStoreInst(StoreInst &Inst) {
259 auto *Ptr = Inst.getPointerOperand();
260 auto *Val = Inst.getValueOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000261 Output.push_back(Edge(Ptr, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000262 }
263
Hal Finkeldb5f86a2014-10-14 20:51:26 +0000264 void visitVAArgInst(VAArgInst &Inst) {
265 // We can't fully model va_arg here. For *Ptr = Inst.getOperand(0), it does
266 // two things:
267 // 1. Loads a value from *((T*)*Ptr).
268 // 2. Increments (stores to) *Ptr by some target-specific amount.
269 // For now, we'll handle this like a landingpad instruction (by placing the
270 // result in its own group, and having that group alias externals).
271 auto *Val = &Inst;
272 Output.push_back(Edge(Val, Val, EdgeType::Assign, AttrAll));
273 }
274
Hal Finkel7529c552014-09-02 21:43:13 +0000275 static bool isFunctionExternal(Function *Fn) {
276 return Fn->isDeclaration() || !Fn->hasLocalLinkage();
277 }
278
279 // Gets whether the sets at Index1 above, below, or equal to the sets at
280 // Index2. Returns None if they are not in the same set chain.
281 static Optional<Level> getIndexRelation(const StratifiedSets<Value *> &Sets,
282 StratifiedIndex Index1,
283 StratifiedIndex Index2) {
284 if (Index1 == Index2)
285 return Level::Same;
286
287 const auto *Current = &Sets.getLink(Index1);
288 while (Current->hasBelow()) {
289 if (Current->Below == Index2)
290 return Level::Below;
291 Current = &Sets.getLink(Current->Below);
292 }
293
294 Current = &Sets.getLink(Index1);
295 while (Current->hasAbove()) {
296 if (Current->Above == Index2)
297 return Level::Above;
298 Current = &Sets.getLink(Current->Above);
299 }
300
301 return NoneType();
302 }
303
304 bool
305 tryInterproceduralAnalysis(const SmallVectorImpl<Function *> &Fns,
306 Value *FuncValue,
307 const iterator_range<User::op_iterator> &Args) {
Hal Finkelca616ac2014-09-02 23:29:48 +0000308 const unsigned ExpectedMaxArgs = 8;
309 const unsigned MaxSupportedArgs = 50;
Hal Finkel7529c552014-09-02 21:43:13 +0000310 assert(Fns.size() > 0);
311
312 // I put this here to give us an upper bound on time taken by IPA. Is it
313 // really (realistically) needed? Keep in mind that we do have an n^2 algo.
George Burgess IVab03af22015-03-10 02:58:15 +0000314 if (std::distance(Args.begin(), Args.end()) > (int)MaxSupportedArgs)
Hal Finkel7529c552014-09-02 21:43:13 +0000315 return false;
316
317 // Exit early if we'll fail anyway
318 for (auto *Fn : Fns) {
319 if (isFunctionExternal(Fn) || Fn->isVarArg())
320 return false;
321 auto &MaybeInfo = AA.ensureCached(Fn);
322 if (!MaybeInfo.hasValue())
323 return false;
324 }
325
326 SmallVector<Value *, ExpectedMaxArgs> Arguments(Args.begin(), Args.end());
327 SmallVector<StratifiedInfo, ExpectedMaxArgs> Parameters;
328 for (auto *Fn : Fns) {
329 auto &Info = *AA.ensureCached(Fn);
330 auto &Sets = Info.Sets;
331 auto &RetVals = Info.ReturnedValues;
332
333 Parameters.clear();
334 for (auto &Param : Fn->args()) {
335 auto MaybeInfo = Sets.find(&Param);
336 // Did a new parameter somehow get added to the function/slip by?
337 if (!MaybeInfo.hasValue())
338 return false;
339 Parameters.push_back(*MaybeInfo);
340 }
341
342 // Adding an edge from argument -> return value for each parameter that
343 // may alias the return value
344 for (unsigned I = 0, E = Parameters.size(); I != E; ++I) {
345 auto &ParamInfo = Parameters[I];
346 auto &ArgVal = Arguments[I];
347 bool AddEdge = false;
348 StratifiedAttrs Externals;
349 for (unsigned X = 0, XE = RetVals.size(); X != XE; ++X) {
350 auto MaybeInfo = Sets.find(RetVals[X]);
351 if (!MaybeInfo.hasValue())
352 return false;
353
354 auto &RetInfo = *MaybeInfo;
355 auto RetAttrs = Sets.getLink(RetInfo.Index).Attrs;
356 auto ParamAttrs = Sets.getLink(ParamInfo.Index).Attrs;
357 auto MaybeRelation =
358 getIndexRelation(Sets, ParamInfo.Index, RetInfo.Index);
359 if (MaybeRelation.hasValue()) {
360 AddEdge = true;
361 Externals |= RetAttrs | ParamAttrs;
362 }
363 }
364 if (AddEdge)
Hal Finkelca616ac2014-09-02 23:29:48 +0000365 Output.push_back(Edge(FuncValue, ArgVal, EdgeType::Assign,
George Burgess IV11d509d2015-03-15 00:52:21 +0000366 StratifiedAttrs().flip()));
Hal Finkel7529c552014-09-02 21:43:13 +0000367 }
368
369 if (Parameters.size() != Arguments.size())
370 return false;
371
372 // Adding edges between arguments for arguments that may end up aliasing
373 // each other. This is necessary for functions such as
374 // void foo(int** a, int** b) { *a = *b; }
375 // (Technically, the proper sets for this would be those below
376 // Arguments[I] and Arguments[X], but our algorithm will produce
377 // extremely similar, and equally correct, results either way)
378 for (unsigned I = 0, E = Arguments.size(); I != E; ++I) {
379 auto &MainVal = Arguments[I];
380 auto &MainInfo = Parameters[I];
381 auto &MainAttrs = Sets.getLink(MainInfo.Index).Attrs;
382 for (unsigned X = I + 1; X != E; ++X) {
383 auto &SubInfo = Parameters[X];
384 auto &SubVal = Arguments[X];
385 auto &SubAttrs = Sets.getLink(SubInfo.Index).Attrs;
386 auto MaybeRelation =
387 getIndexRelation(Sets, MainInfo.Index, SubInfo.Index);
388
389 if (!MaybeRelation.hasValue())
390 continue;
391
392 auto NewAttrs = SubAttrs | MainAttrs;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000393 Output.push_back(Edge(MainVal, SubVal, EdgeType::Assign, NewAttrs));
Hal Finkel7529c552014-09-02 21:43:13 +0000394 }
395 }
396 }
397 return true;
398 }
399
400 template <typename InstT> void visitCallLikeInst(InstT &Inst) {
George Burgess IV68b36e02015-08-28 00:16:18 +0000401 // TODO: Add support for noalias args/all the other fun function attributes
402 // that we can tack on.
Hal Finkel7529c552014-09-02 21:43:13 +0000403 SmallVector<Function *, 4> Targets;
404 if (getPossibleTargets(&Inst, Targets)) {
405 if (tryInterproceduralAnalysis(Targets, &Inst, Inst.arg_operands()))
406 return;
407 // Cleanup from interprocedural analysis
408 Output.clear();
409 }
410
George Burgess IV68b36e02015-08-28 00:16:18 +0000411 // Because the function is opaque, we need to note that anything
412 // could have happened to the arguments, and that the result could alias
413 // just about anything, too.
414 // The goal of the loop is in part to unify many Values into one set, so we
415 // don't care if the function is void there.
Hal Finkel7529c552014-09-02 21:43:13 +0000416 for (Value *V : Inst.arg_operands())
Hal Finkel8d1590d2014-09-02 22:52:30 +0000417 Output.push_back(Edge(&Inst, V, EdgeType::Assign, AttrAll));
George Burgess IV68b36e02015-08-28 00:16:18 +0000418 if (Inst.getNumArgOperands() == 0 &&
419 Inst.getType() != Type::getVoidTy(Inst.getContext()))
420 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
Hal Finkel7529c552014-09-02 21:43:13 +0000421 }
422
423 void visitCallInst(CallInst &Inst) { visitCallLikeInst(Inst); }
424
425 void visitInvokeInst(InvokeInst &Inst) { visitCallLikeInst(Inst); }
426
427 // Because vectors/aggregates are immutable and unaddressable,
428 // there's nothing we can do to coax a value out of them, other
429 // than calling Extract{Element,Value}. We can effectively treat
430 // them as pointers to arbitrary memory locations we can store in
431 // and load from.
432 void visitExtractElementInst(ExtractElementInst &Inst) {
433 auto *Ptr = Inst.getVectorOperand();
434 auto *Val = &Inst;
Hal Finkel8d1590d2014-09-02 22:52:30 +0000435 Output.push_back(Edge(Val, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000436 }
437
438 void visitInsertElementInst(InsertElementInst &Inst) {
439 auto *Vec = Inst.getOperand(0);
440 auto *Val = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000441 Output.push_back(Edge(&Inst, Vec, EdgeType::Assign, AttrNone));
442 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000443 }
444
445 void visitLandingPadInst(LandingPadInst &Inst) {
446 // Exceptions come from "nowhere", from our analysis' perspective.
447 // So we place the instruction its own group, noting that said group may
448 // alias externals
Hal Finkel8d1590d2014-09-02 22:52:30 +0000449 Output.push_back(Edge(&Inst, &Inst, EdgeType::Assign, AttrAll));
Hal Finkel7529c552014-09-02 21:43:13 +0000450 }
451
452 void visitInsertValueInst(InsertValueInst &Inst) {
453 auto *Agg = Inst.getOperand(0);
454 auto *Val = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000455 Output.push_back(Edge(&Inst, Agg, EdgeType::Assign, AttrNone));
456 Output.push_back(Edge(&Inst, Val, EdgeType::Dereference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000457 }
458
459 void visitExtractValueInst(ExtractValueInst &Inst) {
460 auto *Ptr = Inst.getAggregateOperand();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000461 Output.push_back(Edge(&Inst, Ptr, EdgeType::Reference, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000462 }
463
464 void visitShuffleVectorInst(ShuffleVectorInst &Inst) {
465 auto *From1 = Inst.getOperand(0);
466 auto *From2 = Inst.getOperand(1);
Hal Finkel8d1590d2014-09-02 22:52:30 +0000467 Output.push_back(Edge(&Inst, From1, EdgeType::Assign, AttrNone));
468 Output.push_back(Edge(&Inst, From2, EdgeType::Assign, AttrNone));
Hal Finkel7529c552014-09-02 21:43:13 +0000469 }
Pete Cooper36642532015-06-12 16:13:54 +0000470
471 void visitConstantExpr(ConstantExpr *CE) {
472 switch (CE->getOpcode()) {
473 default:
474 llvm_unreachable("Unknown instruction type encountered!");
475// Build the switch statement using the Instruction.def file.
476#define HANDLE_INST(NUM, OPCODE, CLASS) \
477 case Instruction::OPCODE: \
478 visit##OPCODE(*(CLASS *)CE); \
479 break;
480#include "llvm/IR/Instruction.def"
481 }
482 }
Hal Finkel7529c552014-09-02 21:43:13 +0000483};
484
485// For a given instruction, we need to know which Value* to get the
486// users of in order to build our graph. In some cases (i.e. add),
487// we simply need the Instruction*. In other cases (i.e. store),
488// finding the users of the Instruction* is useless; we need to find
489// the users of the first operand. This handles determining which
490// value to follow for us.
491//
492// Note: we *need* to keep this in sync with GetEdgesVisitor. Add
493// something to GetEdgesVisitor, add it here -- remove something from
494// GetEdgesVisitor, remove it here.
495class GetTargetValueVisitor
496 : public InstVisitor<GetTargetValueVisitor, Value *> {
497public:
498 Value *visitInstruction(Instruction &Inst) { return &Inst; }
499
500 Value *visitStoreInst(StoreInst &Inst) { return Inst.getPointerOperand(); }
501
502 Value *visitAtomicCmpXchgInst(AtomicCmpXchgInst &Inst) {
503 return Inst.getPointerOperand();
504 }
505
506 Value *visitAtomicRMWInst(AtomicRMWInst &Inst) {
507 return Inst.getPointerOperand();
508 }
509
510 Value *visitInsertElementInst(InsertElementInst &Inst) {
511 return Inst.getOperand(0);
512 }
513
514 Value *visitInsertValueInst(InsertValueInst &Inst) {
515 return Inst.getAggregateOperand();
516 }
517};
518
519// Set building requires a weighted bidirectional graph.
520template <typename EdgeTypeT> class WeightedBidirectionalGraph {
521public:
522 typedef std::size_t Node;
523
524private:
Hal Finkelca616ac2014-09-02 23:29:48 +0000525 const static Node StartNode = Node(0);
Hal Finkel7529c552014-09-02 21:43:13 +0000526
527 struct Edge {
528 EdgeTypeT Weight;
529 Node Other;
530
George Burgess IV11d509d2015-03-15 00:52:21 +0000531 Edge(const EdgeTypeT &W, const Node &N) : Weight(W), Other(N) {}
Hal Finkelca616ac2014-09-02 23:29:48 +0000532
Hal Finkel7529c552014-09-02 21:43:13 +0000533 bool operator==(const Edge &E) const {
534 return Weight == E.Weight && Other == E.Other;
535 }
536
537 bool operator!=(const Edge &E) const { return !operator==(E); }
538 };
539
540 struct NodeImpl {
541 std::vector<Edge> Edges;
542 };
543
544 std::vector<NodeImpl> NodeImpls;
545
546 bool inbounds(Node NodeIndex) const { return NodeIndex < NodeImpls.size(); }
547
548 const NodeImpl &getNode(Node N) const { return NodeImpls[N]; }
549 NodeImpl &getNode(Node N) { return NodeImpls[N]; }
550
551public:
552 // ----- Various Edge iterators for the graph ----- //
553
554 // \brief Iterator for edges. Because this graph is bidirected, we don't
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000555 // allow modification of the edges using this iterator. Additionally, the
Hal Finkel7529c552014-09-02 21:43:13 +0000556 // iterator becomes invalid if you add edges to or from the node you're
557 // getting the edges of.
558 struct EdgeIterator : public std::iterator<std::forward_iterator_tag,
559 std::tuple<EdgeTypeT, Node *>> {
560 EdgeIterator(const typename std::vector<Edge>::const_iterator &Iter)
561 : Current(Iter) {}
562
563 EdgeIterator(NodeImpl &Impl) : Current(Impl.begin()) {}
564
565 EdgeIterator &operator++() {
566 ++Current;
567 return *this;
568 }
569
570 EdgeIterator operator++(int) {
571 EdgeIterator Copy(Current);
572 operator++();
573 return Copy;
574 }
575
576 std::tuple<EdgeTypeT, Node> &operator*() {
577 Store = std::make_tuple(Current->Weight, Current->Other);
578 return Store;
579 }
580
581 bool operator==(const EdgeIterator &Other) const {
582 return Current == Other.Current;
583 }
584
585 bool operator!=(const EdgeIterator &Other) const {
586 return !operator==(Other);
587 }
588
589 private:
590 typename std::vector<Edge>::const_iterator Current;
591 std::tuple<EdgeTypeT, Node> Store;
592 };
593
594 // Wrapper for EdgeIterator with begin()/end() calls.
595 struct EdgeIterable {
596 EdgeIterable(const std::vector<Edge> &Edges)
597 : BeginIter(Edges.begin()), EndIter(Edges.end()) {}
598
599 EdgeIterator begin() { return EdgeIterator(BeginIter); }
600
601 EdgeIterator end() { return EdgeIterator(EndIter); }
602
603 private:
604 typename std::vector<Edge>::const_iterator BeginIter;
605 typename std::vector<Edge>::const_iterator EndIter;
606 };
607
608 // ----- Actual graph-related things ----- //
609
Hal Finkelca616ac2014-09-02 23:29:48 +0000610 WeightedBidirectionalGraph() {}
Hal Finkel7529c552014-09-02 21:43:13 +0000611
612 WeightedBidirectionalGraph(WeightedBidirectionalGraph<EdgeTypeT> &&Other)
613 : NodeImpls(std::move(Other.NodeImpls)) {}
614
615 WeightedBidirectionalGraph<EdgeTypeT> &
616 operator=(WeightedBidirectionalGraph<EdgeTypeT> &&Other) {
617 NodeImpls = std::move(Other.NodeImpls);
618 return *this;
619 }
620
621 Node addNode() {
622 auto Index = NodeImpls.size();
623 auto NewNode = Node(Index);
624 NodeImpls.push_back(NodeImpl());
625 return NewNode;
626 }
627
628 void addEdge(Node From, Node To, const EdgeTypeT &Weight,
629 const EdgeTypeT &ReverseWeight) {
630 assert(inbounds(From));
631 assert(inbounds(To));
632 auto &FromNode = getNode(From);
633 auto &ToNode = getNode(To);
Hal Finkelca616ac2014-09-02 23:29:48 +0000634 FromNode.Edges.push_back(Edge(Weight, To));
635 ToNode.Edges.push_back(Edge(ReverseWeight, From));
Hal Finkel7529c552014-09-02 21:43:13 +0000636 }
637
638 EdgeIterable edgesFor(const Node &N) const {
639 const auto &Node = getNode(N);
640 return EdgeIterable(Node.Edges);
641 }
642
643 bool empty() const { return NodeImpls.empty(); }
644 std::size_t size() const { return NodeImpls.size(); }
645
646 // \brief Gets an arbitrary node in the graph as a starting point for
647 // traversal.
648 Node getEntryNode() {
649 assert(inbounds(StartNode));
650 return StartNode;
651 }
652};
653
654typedef WeightedBidirectionalGraph<std::pair<EdgeType, StratifiedAttrs>> GraphT;
655typedef DenseMap<Value *, GraphT::Node> NodeMapT;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000656}
Hal Finkel7529c552014-09-02 21:43:13 +0000657
Hal Finkel7529c552014-09-02 21:43:13 +0000658//===----------------------------------------------------------------------===//
659// Function declarations that require types defined in the namespace above
660//===----------------------------------------------------------------------===//
661
662// Given an argument number, returns the appropriate Attr index to set.
663static StratifiedAttr argNumberToAttrIndex(StratifiedAttr);
664
665// Given a Value, potentially return which AttrIndex it maps to.
666static Optional<StratifiedAttr> valueToAttrIndex(Value *Val);
667
668// Gets the inverse of a given EdgeType.
669static EdgeType flipWeight(EdgeType);
670
671// Gets edges of the given Instruction*, writing them to the SmallVector*.
672static void argsToEdges(CFLAliasAnalysis &, Instruction *,
673 SmallVectorImpl<Edge> &);
674
Pete Cooper36642532015-06-12 16:13:54 +0000675// Gets edges of the given ConstantExpr*, writing them to the SmallVector*.
676static void argsToEdges(CFLAliasAnalysis &, ConstantExpr *,
677 SmallVectorImpl<Edge> &);
678
Hal Finkel7529c552014-09-02 21:43:13 +0000679// Gets the "Level" that one should travel in StratifiedSets
680// given an EdgeType.
681static Level directionOfEdgeType(EdgeType);
682
683// Builds the graph needed for constructing the StratifiedSets for the
684// given function
685static void buildGraphFrom(CFLAliasAnalysis &, Function *,
686 SmallVectorImpl<Value *> &, NodeMapT &, GraphT &);
687
George Burgess IVab03af22015-03-10 02:58:15 +0000688// Gets the edges of a ConstantExpr as if it was an Instruction. This
689// function also acts on any nested ConstantExprs, adding the edges
690// of those to the given SmallVector as well.
691static void constexprToEdges(CFLAliasAnalysis &, ConstantExpr &,
692 SmallVectorImpl<Edge> &);
693
694// Given an Instruction, this will add it to the graph, along with any
695// Instructions that are potentially only available from said Instruction
696// For example, given the following line:
697// %0 = load i16* getelementptr ([1 x i16]* @a, 0, 0), align 2
698// addInstructionToGraph would add both the `load` and `getelementptr`
699// instructions to the graph appropriately.
700static void addInstructionToGraph(CFLAliasAnalysis &, Instruction &,
701 SmallVectorImpl<Value *> &, NodeMapT &,
702 GraphT &);
703
704// Notes whether it would be pointless to add the given Value to our sets.
705static bool canSkipAddingToSets(Value *Val);
706
Hal Finkel7529c552014-09-02 21:43:13 +0000707static Optional<Function *> parentFunctionOfValue(Value *Val) {
708 if (auto *Inst = dyn_cast<Instruction>(Val)) {
709 auto *Bb = Inst->getParent();
710 return Bb->getParent();
711 }
712
713 if (auto *Arg = dyn_cast<Argument>(Val))
714 return Arg->getParent();
715 return NoneType();
716}
717
718template <typename Inst>
719static bool getPossibleTargets(Inst *Call,
720 SmallVectorImpl<Function *> &Output) {
721 if (auto *Fn = Call->getCalledFunction()) {
722 Output.push_back(Fn);
723 return true;
724 }
725
726 // TODO: If the call is indirect, we might be able to enumerate all potential
727 // targets of the call and return them, rather than just failing.
728 return false;
729}
730
731static Optional<Value *> getTargetValue(Instruction *Inst) {
732 GetTargetValueVisitor V;
733 return V.visit(Inst);
734}
735
736static bool hasUsefulEdges(Instruction *Inst) {
737 bool IsNonInvokeTerminator =
738 isa<TerminatorInst>(Inst) && !isa<InvokeInst>(Inst);
739 return !isa<CmpInst>(Inst) && !isa<FenceInst>(Inst) && !IsNonInvokeTerminator;
740}
741
Pete Cooper36642532015-06-12 16:13:54 +0000742static bool hasUsefulEdges(ConstantExpr *CE) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000743 // ConstantExpr doesn't have terminators, invokes, or fences, so only needs
Pete Cooper36642532015-06-12 16:13:54 +0000744 // to check for compares.
745 return CE->getOpcode() != Instruction::ICmp &&
746 CE->getOpcode() != Instruction::FCmp;
747}
748
Hal Finkel7529c552014-09-02 21:43:13 +0000749static Optional<StratifiedAttr> valueToAttrIndex(Value *Val) {
750 if (isa<GlobalValue>(Val))
751 return AttrGlobalIndex;
752
753 if (auto *Arg = dyn_cast<Argument>(Val))
Daniel Berlin16f7a522015-01-26 17:31:17 +0000754 // Only pointer arguments should have the argument attribute,
755 // because things can't escape through scalars without us seeing a
756 // cast, and thus, interaction with them doesn't matter.
757 if (!Arg->hasNoAliasAttr() && Arg->getType()->isPointerTy())
Hal Finkel7529c552014-09-02 21:43:13 +0000758 return argNumberToAttrIndex(Arg->getArgNo());
759 return NoneType();
760}
761
762static StratifiedAttr argNumberToAttrIndex(unsigned ArgNum) {
George Burgess IV3c898c22015-01-21 16:37:21 +0000763 if (ArgNum >= AttrMaxNumArgs)
Hal Finkel7529c552014-09-02 21:43:13 +0000764 return AttrAllIndex;
765 return ArgNum + AttrFirstArgIndex;
766}
767
768static EdgeType flipWeight(EdgeType Initial) {
769 switch (Initial) {
770 case EdgeType::Assign:
771 return EdgeType::Assign;
772 case EdgeType::Dereference:
773 return EdgeType::Reference;
774 case EdgeType::Reference:
775 return EdgeType::Dereference;
776 }
777 llvm_unreachable("Incomplete coverage of EdgeType enum");
778}
779
780static void argsToEdges(CFLAliasAnalysis &Analysis, Instruction *Inst,
781 SmallVectorImpl<Edge> &Output) {
George Burgess IVab03af22015-03-10 02:58:15 +0000782 assert(hasUsefulEdges(Inst) &&
783 "Expected instructions to have 'useful' edges");
Hal Finkel7529c552014-09-02 21:43:13 +0000784 GetEdgesVisitor v(Analysis, Output);
785 v.visit(Inst);
786}
787
Pete Cooper36642532015-06-12 16:13:54 +0000788static void argsToEdges(CFLAliasAnalysis &Analysis, ConstantExpr *CE,
789 SmallVectorImpl<Edge> &Output) {
790 assert(hasUsefulEdges(CE) && "Expected constant expr to have 'useful' edges");
791 GetEdgesVisitor v(Analysis, Output);
792 v.visitConstantExpr(CE);
793}
794
Hal Finkel7529c552014-09-02 21:43:13 +0000795static Level directionOfEdgeType(EdgeType Weight) {
796 switch (Weight) {
797 case EdgeType::Reference:
798 return Level::Above;
799 case EdgeType::Dereference:
800 return Level::Below;
801 case EdgeType::Assign:
802 return Level::Same;
803 }
804 llvm_unreachable("Incomplete switch coverage");
805}
806
George Burgess IVab03af22015-03-10 02:58:15 +0000807static void constexprToEdges(CFLAliasAnalysis &Analysis,
808 ConstantExpr &CExprToCollapse,
809 SmallVectorImpl<Edge> &Results) {
810 SmallVector<ConstantExpr *, 4> Worklist;
811 Worklist.push_back(&CExprToCollapse);
812
813 SmallVector<Edge, 8> ConstexprEdges;
Pete Cooper36642532015-06-12 16:13:54 +0000814 SmallPtrSet<ConstantExpr *, 4> Visited;
George Burgess IVab03af22015-03-10 02:58:15 +0000815 while (!Worklist.empty()) {
816 auto *CExpr = Worklist.pop_back_val();
George Burgess IVab03af22015-03-10 02:58:15 +0000817
Pete Cooper36642532015-06-12 16:13:54 +0000818 if (!hasUsefulEdges(CExpr))
George Burgess IVab03af22015-03-10 02:58:15 +0000819 continue;
820
821 ConstexprEdges.clear();
Pete Cooper36642532015-06-12 16:13:54 +0000822 argsToEdges(Analysis, CExpr, ConstexprEdges);
George Burgess IVab03af22015-03-10 02:58:15 +0000823 for (auto &Edge : ConstexprEdges) {
Pete Cooper36642532015-06-12 16:13:54 +0000824 if (auto *Nested = dyn_cast<ConstantExpr>(Edge.From))
825 if (Visited.insert(Nested).second)
826 Worklist.push_back(Nested);
George Burgess IVab03af22015-03-10 02:58:15 +0000827
Pete Cooper36642532015-06-12 16:13:54 +0000828 if (auto *Nested = dyn_cast<ConstantExpr>(Edge.To))
829 if (Visited.insert(Nested).second)
830 Worklist.push_back(Nested);
George Burgess IVab03af22015-03-10 02:58:15 +0000831 }
832
833 Results.append(ConstexprEdges.begin(), ConstexprEdges.end());
834 }
835}
836
837static void addInstructionToGraph(CFLAliasAnalysis &Analysis, Instruction &Inst,
838 SmallVectorImpl<Value *> &ReturnedValues,
839 NodeMapT &Map, GraphT &Graph) {
Hal Finkel7529c552014-09-02 21:43:13 +0000840 const auto findOrInsertNode = [&Map, &Graph](Value *Val) {
841 auto Pair = Map.insert(std::make_pair(Val, GraphT::Node()));
842 auto &Iter = Pair.first;
843 if (Pair.second) {
844 auto NewNode = Graph.addNode();
845 Iter->second = NewNode;
846 }
847 return Iter->second;
848 };
849
George Burgess IVab03af22015-03-10 02:58:15 +0000850 // We don't want the edges of most "return" instructions, but we *do* want
851 // to know what can be returned.
852 if (isa<ReturnInst>(&Inst))
853 ReturnedValues.push_back(&Inst);
854
855 if (!hasUsefulEdges(&Inst))
856 return;
857
Hal Finkel7529c552014-09-02 21:43:13 +0000858 SmallVector<Edge, 8> Edges;
George Burgess IVab03af22015-03-10 02:58:15 +0000859 argsToEdges(Analysis, &Inst, Edges);
Hal Finkel7529c552014-09-02 21:43:13 +0000860
George Burgess IVab03af22015-03-10 02:58:15 +0000861 // In the case of an unused alloca (or similar), edges may be empty. Note
862 // that it exists so we can potentially answer NoAlias.
863 if (Edges.empty()) {
864 auto MaybeVal = getTargetValue(&Inst);
865 assert(MaybeVal.hasValue());
866 auto *Target = *MaybeVal;
867 findOrInsertNode(Target);
868 return;
Hal Finkel7529c552014-09-02 21:43:13 +0000869 }
George Burgess IVab03af22015-03-10 02:58:15 +0000870
871 const auto addEdgeToGraph = [&Graph, &findOrInsertNode](const Edge &E) {
872 auto To = findOrInsertNode(E.To);
873 auto From = findOrInsertNode(E.From);
874 auto FlippedWeight = flipWeight(E.Weight);
875 auto Attrs = E.AdditionalAttrs;
876 Graph.addEdge(From, To, std::make_pair(E.Weight, Attrs),
877 std::make_pair(FlippedWeight, Attrs));
878 };
879
880 SmallVector<ConstantExpr *, 4> ConstantExprs;
881 for (const Edge &E : Edges) {
882 addEdgeToGraph(E);
883 if (auto *Constexpr = dyn_cast<ConstantExpr>(E.To))
884 ConstantExprs.push_back(Constexpr);
885 if (auto *Constexpr = dyn_cast<ConstantExpr>(E.From))
886 ConstantExprs.push_back(Constexpr);
887 }
888
889 for (ConstantExpr *CE : ConstantExprs) {
890 Edges.clear();
891 constexprToEdges(Analysis, *CE, Edges);
892 std::for_each(Edges.begin(), Edges.end(), addEdgeToGraph);
893 }
894}
895
896// Aside: We may remove graph construction entirely, because it doesn't really
897// buy us much that we don't already have. I'd like to add interprocedural
898// analysis prior to this however, in case that somehow requires the graph
899// produced by this for efficient execution
900static void buildGraphFrom(CFLAliasAnalysis &Analysis, Function *Fn,
901 SmallVectorImpl<Value *> &ReturnedValues,
902 NodeMapT &Map, GraphT &Graph) {
903 for (auto &Bb : Fn->getBasicBlockList())
904 for (auto &Inst : Bb.getInstList())
905 addInstructionToGraph(Analysis, Inst, ReturnedValues, Map, Graph);
906}
907
908static bool canSkipAddingToSets(Value *Val) {
909 // Constants can share instances, which may falsely unify multiple
910 // sets, e.g. in
911 // store i32* null, i32** %ptr1
912 // store i32* null, i32** %ptr2
913 // clearly ptr1 and ptr2 should not be unified into the same set, so
914 // we should filter out the (potentially shared) instance to
915 // i32* null.
916 if (isa<Constant>(Val)) {
917 bool Container = isa<ConstantVector>(Val) || isa<ConstantArray>(Val) ||
918 isa<ConstantStruct>(Val);
919 // TODO: Because all of these things are constant, we can determine whether
920 // the data is *actually* mutable at graph building time. This will probably
921 // come for free/cheap with offset awareness.
922 bool CanStoreMutableData =
923 isa<GlobalValue>(Val) || isa<ConstantExpr>(Val) || Container;
924 return !CanStoreMutableData;
925 }
926
927 return false;
Hal Finkel7529c552014-09-02 21:43:13 +0000928}
929
Chandler Carruth8b046a42015-08-14 02:42:20 +0000930// Builds the graph + StratifiedSets for a function.
931CFLAliasAnalysis::FunctionInfo CFLAliasAnalysis::buildSetsFrom(Function *Fn) {
Hal Finkel7529c552014-09-02 21:43:13 +0000932 NodeMapT Map;
933 GraphT Graph;
934 SmallVector<Value *, 4> ReturnedValues;
935
Chandler Carruth8b046a42015-08-14 02:42:20 +0000936 buildGraphFrom(*this, Fn, ReturnedValues, Map, Graph);
Hal Finkel7529c552014-09-02 21:43:13 +0000937
938 DenseMap<GraphT::Node, Value *> NodeValueMap;
939 NodeValueMap.resize(Map.size());
940 for (const auto &Pair : Map)
Hal Finkel8d1590d2014-09-02 22:52:30 +0000941 NodeValueMap.insert(std::make_pair(Pair.second, Pair.first));
Hal Finkel7529c552014-09-02 21:43:13 +0000942
943 const auto findValueOrDie = [&NodeValueMap](GraphT::Node Node) {
944 auto ValIter = NodeValueMap.find(Node);
945 assert(ValIter != NodeValueMap.end());
946 return ValIter->second;
947 };
948
949 StratifiedSetsBuilder<Value *> Builder;
950
951 SmallVector<GraphT::Node, 16> Worklist;
952 for (auto &Pair : Map) {
953 Worklist.clear();
954
955 auto *Value = Pair.first;
956 Builder.add(Value);
957 auto InitialNode = Pair.second;
958 Worklist.push_back(InitialNode);
959 while (!Worklist.empty()) {
960 auto Node = Worklist.pop_back_val();
961 auto *CurValue = findValueOrDie(Node);
George Burgess IVab03af22015-03-10 02:58:15 +0000962 if (canSkipAddingToSets(CurValue))
Hal Finkel7529c552014-09-02 21:43:13 +0000963 continue;
964
965 for (const auto &EdgeTuple : Graph.edgesFor(Node)) {
966 auto Weight = std::get<0>(EdgeTuple);
967 auto Label = Weight.first;
968 auto &OtherNode = std::get<1>(EdgeTuple);
969 auto *OtherValue = findValueOrDie(OtherNode);
970
George Burgess IVab03af22015-03-10 02:58:15 +0000971 if (canSkipAddingToSets(OtherValue))
Hal Finkel7529c552014-09-02 21:43:13 +0000972 continue;
973
974 bool Added;
975 switch (directionOfEdgeType(Label)) {
976 case Level::Above:
977 Added = Builder.addAbove(CurValue, OtherValue);
978 break;
979 case Level::Below:
980 Added = Builder.addBelow(CurValue, OtherValue);
981 break;
982 case Level::Same:
983 Added = Builder.addWith(CurValue, OtherValue);
984 break;
985 }
986
George Burgess IVb54a8d622015-03-10 02:40:06 +0000987 auto Aliasing = Weight.second;
988 if (auto MaybeCurIndex = valueToAttrIndex(CurValue))
989 Aliasing.set(*MaybeCurIndex);
990 if (auto MaybeOtherIndex = valueToAttrIndex(OtherValue))
991 Aliasing.set(*MaybeOtherIndex);
992 Builder.noteAttributes(CurValue, Aliasing);
993 Builder.noteAttributes(OtherValue, Aliasing);
994
995 if (Added)
Hal Finkel7529c552014-09-02 21:43:13 +0000996 Worklist.push_back(OtherNode);
Hal Finkel7529c552014-09-02 21:43:13 +0000997 }
998 }
999 }
1000
1001 // There are times when we end up with parameters not in our graph (i.e. if
1002 // it's only used as the condition of a branch). Other bits of code depend on
1003 // things that were present during construction being present in the graph.
1004 // So, we add all present arguments here.
1005 for (auto &Arg : Fn->args()) {
George Burgess IVab03af22015-03-10 02:58:15 +00001006 if (!Builder.add(&Arg))
1007 continue;
1008
1009 auto Attrs = valueToAttrIndex(&Arg);
1010 if (Attrs.hasValue())
1011 Builder.noteAttributes(&Arg, *Attrs);
Hal Finkel7529c552014-09-02 21:43:13 +00001012 }
1013
Hal Finkel85f26922014-09-03 00:06:47 +00001014 return FunctionInfo(Builder.build(), std::move(ReturnedValues));
Hal Finkel7529c552014-09-02 21:43:13 +00001015}
1016
1017void CFLAliasAnalysis::scan(Function *Fn) {
Hal Finkel8d1590d2014-09-02 22:52:30 +00001018 auto InsertPair = Cache.insert(std::make_pair(Fn, Optional<FunctionInfo>()));
Hal Finkel7529c552014-09-02 21:43:13 +00001019 (void)InsertPair;
1020 assert(InsertPair.second &&
1021 "Trying to scan a function that has already been cached");
1022
Chandler Carruth8b046a42015-08-14 02:42:20 +00001023 FunctionInfo Info(buildSetsFrom(Fn));
Hal Finkel7529c552014-09-02 21:43:13 +00001024 Cache[Fn] = std::move(Info);
1025 Handles.push_front(FunctionHandle(Fn, this));
1026}
1027
Chandler Carruth8b046a42015-08-14 02:42:20 +00001028void CFLAliasAnalysis::evict(Function *Fn) { Cache.erase(Fn); }
1029
1030/// \brief Ensures that the given function is available in the cache.
1031/// Returns the appropriate entry from the cache.
1032const Optional<CFLAliasAnalysis::FunctionInfo> &
1033CFLAliasAnalysis::ensureCached(Function *Fn) {
1034 auto Iter = Cache.find(Fn);
1035 if (Iter == Cache.end()) {
1036 scan(Fn);
1037 Iter = Cache.find(Fn);
1038 assert(Iter != Cache.end());
1039 assert(Iter->second.hasValue());
1040 }
1041 return Iter->second;
1042}
1043
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001044AliasResult CFLAliasAnalysis::query(const MemoryLocation &LocA,
1045 const MemoryLocation &LocB) {
Hal Finkel7529c552014-09-02 21:43:13 +00001046 auto *ValA = const_cast<Value *>(LocA.Ptr);
1047 auto *ValB = const_cast<Value *>(LocB.Ptr);
1048
1049 Function *Fn = nullptr;
1050 auto MaybeFnA = parentFunctionOfValue(ValA);
1051 auto MaybeFnB = parentFunctionOfValue(ValB);
1052 if (!MaybeFnA.hasValue() && !MaybeFnB.hasValue()) {
George Burgess IV33305e72015-02-12 03:07:07 +00001053 // The only times this is known to happen are when globals + InlineAsm
1054 // are involved
1055 DEBUG(dbgs() << "CFLAA: could not extract parent function information.\n");
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001056 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001057 }
1058
1059 if (MaybeFnA.hasValue()) {
1060 Fn = *MaybeFnA;
1061 assert((!MaybeFnB.hasValue() || *MaybeFnB == *MaybeFnA) &&
1062 "Interprocedural queries not supported");
1063 } else {
1064 Fn = *MaybeFnB;
1065 }
1066
1067 assert(Fn != nullptr);
1068 auto &MaybeInfo = ensureCached(Fn);
1069 assert(MaybeInfo.hasValue());
1070
1071 auto &Sets = MaybeInfo->Sets;
1072 auto MaybeA = Sets.find(ValA);
1073 if (!MaybeA.hasValue())
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001074 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001075
1076 auto MaybeB = Sets.find(ValB);
1077 if (!MaybeB.hasValue())
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001078 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001079
1080 auto SetA = *MaybeA;
1081 auto SetB = *MaybeB;
Hal Finkel7529c552014-09-02 21:43:13 +00001082 auto AttrsA = Sets.getLink(SetA.Index).Attrs;
1083 auto AttrsB = Sets.getLink(SetB.Index).Attrs;
George Burgess IV33305e72015-02-12 03:07:07 +00001084
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001085 // Stratified set attributes are used as markets to signify whether a member
George Burgess IV33305e72015-02-12 03:07:07 +00001086 // of a StratifiedSet (or a member of a set above the current set) has
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001087 // interacted with either arguments or globals. "Interacted with" meaning
George Burgess IV33305e72015-02-12 03:07:07 +00001088 // its value may be different depending on the value of an argument or
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001089 // global. The thought behind this is that, because arguments and globals
1090 // may alias each other, if AttrsA and AttrsB have touched args/globals,
George Burgess IV33305e72015-02-12 03:07:07 +00001091 // we must conservatively say that they alias. However, if at least one of
1092 // the sets has no values that could legally be altered by changing the value
Hal Finkel8eae3ad2014-10-06 14:42:56 +00001093 // of an argument or global, then we don't have to be as conservative.
1094 if (AttrsA.any() && AttrsB.any())
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001095 return MayAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001096
Daniel Berlin16f7a522015-01-26 17:31:17 +00001097 // We currently unify things even if the accesses to them may not be in
1098 // bounds, so we can't return partial alias here because we don't
1099 // know whether the pointer is really within the object or not.
1100 // IE Given an out of bounds GEP and an alloca'd pointer, we may
1101 // unify the two. We can't return partial alias for this case.
1102 // Since we do not currently track enough information to
1103 // differentiate
1104
1105 if (SetA.Index == SetB.Index)
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001106 return MayAlias;
Daniel Berlin16f7a522015-01-26 17:31:17 +00001107
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00001108 return NoAlias;
Hal Finkel7529c552014-09-02 21:43:13 +00001109}
Mehdi Amini46a43552015-03-04 18:43:29 +00001110
1111bool CFLAliasAnalysis::doInitialization(Module &M) {
1112 InitializeAliasAnalysis(this, &M.getDataLayout());
1113 return true;
1114}