blob: d85121283cc7ab351cf965c517224ca22b0bc581 [file] [log] [blame]
George Burgess IVbfa401e2016-07-06 00:26:41 +00001//- CFLAndersAliasAnalysis.cpp - Unification-based Alias Analysis ---*- C++-*-//
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, summary-based alias analysis algorithm. It
11// differs from CFLSteensAliasAnalysis in its inclusion-based nature while
12// CFLSteensAliasAnalysis is unification-based. This pass has worse performance
13// than CFLSteensAliasAnalysis (the worst case complexity of
14// CFLAndersAliasAnalysis is cubic, while the worst case complexity of
15// CFLSteensAliasAnalysis is almost linear), but it is able to yield more
16// precise analysis result. The precision of this analysis is roughly the same
17// as that of an one level context-sensitive Andersen's algorithm.
18//
George Burgess IV6d30aa02016-07-15 19:53:25 +000019// The algorithm used here is based on recursive state machine matching scheme
20// proposed in "Demand-driven alias analysis for C" by Xin Zheng and Radu
21// Rugina. The general idea is to extend the tranditional transitive closure
22// algorithm to perform CFL matching along the way: instead of recording
23// "whether X is reachable from Y", we keep track of "whether X is reachable
24// from Y at state Z", where the "state" field indicates where we are in the CFL
25// matching process. To understand the matching better, it is advisable to have
26// the state machine shown in Figure 3 of the paper available when reading the
27// codes: all we do here is to selectively expand the transitive closure by
28// discarding edges that are not recognized by the state machine.
29//
George Burgess IVc01b42f2016-07-19 20:38:21 +000030// There are two differences between our current implementation and the one
31// described in the paper:
32// - Our algorithm eagerly computes all alias pairs after the CFLGraph is built,
33// while in the paper the authors did the computation in a demand-driven
34// fashion. We did not implement the demand-driven algorithm due to the
35// additional coding complexity and higher memory profile, but if we found it
36// necessary we may switch to it eventually.
37// - In the paper the authors use a state machine that does not distinguish
38// value reads from value writes. For example, if Y is reachable from X at state
39// S3, it may be the case that X is written into Y, or it may be the case that
40// there's a third value Z that writes into both X and Y. To make that
41// distinction (which is crucial in building function summary as well as
42// retrieving mod-ref info), we choose to duplicate some of the states in the
43// paper's proposed state machine. The duplication does not change the set the
44// machine accepts. Given a pair of reachable values, it only provides more
45// detailed information on which value is being written into and which is being
46// read from.
George Burgess IV6d30aa02016-07-15 19:53:25 +000047//
George Burgess IVbfa401e2016-07-06 00:26:41 +000048//===----------------------------------------------------------------------===//
49
50// N.B. AliasAnalysis as a whole is phrased as a FunctionPass at the moment, and
51// CFLAndersAA is interprocedural. This is *technically* A Bad Thing, because
52// FunctionPasses are only allowed to inspect the Function that they're being
53// run on. Realistically, this likely isn't a problem until we allow
54// FunctionPasses to run concurrently.
55
56#include "llvm/Analysis/CFLAndersAliasAnalysis.h"
George Burgess IV1ca8aff2016-07-06 00:36:12 +000057#include "CFLGraph.h"
George Burgess IV6d30aa02016-07-15 19:53:25 +000058#include "llvm/ADT/DenseSet.h"
George Burgess IVbfa401e2016-07-06 00:26:41 +000059#include "llvm/Pass.h"
60
61using namespace llvm;
George Burgess IV1ca8aff2016-07-06 00:36:12 +000062using namespace llvm::cflaa;
George Burgess IVbfa401e2016-07-06 00:26:41 +000063
64#define DEBUG_TYPE "cfl-anders-aa"
65
George Burgess IV6d30aa02016-07-15 19:53:25 +000066CFLAndersAAResult::CFLAndersAAResult(const TargetLibraryInfo &TLI) : TLI(TLI) {}
67CFLAndersAAResult::CFLAndersAAResult(CFLAndersAAResult &&RHS)
68 : AAResultBase(std::move(RHS)), TLI(RHS.TLI) {}
69CFLAndersAAResult::~CFLAndersAAResult() {}
70
71static const Function *parentFunctionOfValue(const Value *Val) {
72 if (auto *Inst = dyn_cast<Instruction>(Val)) {
73 auto *Bb = Inst->getParent();
74 return Bb->getParent();
75 }
76
77 if (auto *Arg = dyn_cast<Argument>(Val))
78 return Arg->getParent();
79 return nullptr;
80}
81
82namespace {
83
84enum class MatchState : uint8_t {
George Burgess IVc01b42f2016-07-19 20:38:21 +000085 // The following state represents S1 in the paper.
86 FlowFromReadOnly = 0,
87 // The following two states together represent S2 in the paper.
88 // The 'NoReadWrite' suffix indicates that there exists an alias path that
89 // does not contain assignment and reverse assignment edges.
90 // The 'ReadOnly' suffix indicates that there exists an alias path that
91 // contains reverse assignment edges only.
92 FlowFromMemAliasNoReadWrite,
93 FlowFromMemAliasReadOnly,
94 // The following two states together represent S3 in the paper.
95 // The 'WriteOnly' suffix indicates that there exists an alias path that
96 // contains assignment edges only.
97 // The 'ReadWrite' suffix indicates that there exists an alias path that
98 // contains both assignment and reverse assignment edges. Note that if X and Y
99 // are reachable at 'ReadWrite' state, it does NOT mean X is both read from
100 // and written to Y. Instead, it means that a third value Z is written to both
101 // X and Y.
102 FlowToWriteOnly,
103 FlowToReadWrite,
104 // The following two states together represent S4 in the paper.
105 FlowToMemAliasWriteOnly,
106 FlowToMemAliasReadWrite,
George Burgess IV6d30aa02016-07-15 19:53:25 +0000107};
108
George Burgess IV3b059842016-07-19 20:47:15 +0000109typedef std::bitset<7> StateSet;
George Burgess IV22a0f1a2016-07-19 21:35:47 +0000110// N.B. These are unsigned instead of StateSets because some MSVC versions
111// apparently lack constexpr bitset ctors.
112LLVM_CONSTEXPR unsigned ReadOnlyStateMask =
113 (1U << static_cast<uint8_t>(MatchState::FlowFromReadOnly)) |
114 (1U << static_cast<uint8_t>(MatchState::FlowFromMemAliasReadOnly));
115LLVM_CONSTEXPR unsigned WriteOnlyStateMask =
116 (1U << static_cast<uint8_t>(MatchState::FlowToWriteOnly)) |
117 (1U << static_cast<uint8_t>(MatchState::FlowToMemAliasWriteOnly));
George Burgess IV3b059842016-07-19 20:47:15 +0000118
George Burgess IV4ec17532016-07-22 22:30:48 +0000119// A pair that consists of a value and an offset
120struct OffsetValue {
121 const Value *Val;
122 int64_t Offset;
123};
124
125bool operator==(OffsetValue LHS, OffsetValue RHS) {
126 return LHS.Val == RHS.Val && LHS.Offset == RHS.Offset;
127}
128bool operator<(OffsetValue LHS, OffsetValue RHS) {
129 return std::less<const Value *>()(LHS.Val, RHS.Val) ||
130 (LHS.Val == RHS.Val && LHS.Offset < RHS.Offset);
131}
132
133// A pair that consists of an InstantiatedValue and an offset
134struct OffsetInstantiatedValue {
135 InstantiatedValue IVal;
136 int64_t Offset;
137};
138
139bool operator==(OffsetInstantiatedValue LHS, OffsetInstantiatedValue RHS) {
140 return LHS.IVal == RHS.IVal && LHS.Offset == RHS.Offset;
141}
142
George Burgess IV6d30aa02016-07-15 19:53:25 +0000143// We use ReachabilitySet to keep track of value aliases (The nonterminal "V" in
144// the paper) during the analysis.
145class ReachabilitySet {
George Burgess IV6d30aa02016-07-15 19:53:25 +0000146 typedef DenseMap<InstantiatedValue, StateSet> ValueStateMap;
147 typedef DenseMap<InstantiatedValue, ValueStateMap> ValueReachMap;
148 ValueReachMap ReachMap;
149
150public:
151 typedef ValueStateMap::const_iterator const_valuestate_iterator;
152 typedef ValueReachMap::const_iterator const_value_iterator;
153
154 // Insert edge 'From->To' at state 'State'
155 bool insert(InstantiatedValue From, InstantiatedValue To, MatchState State) {
George Burgess IV3b059842016-07-19 20:47:15 +0000156 assert(From != To);
George Burgess IV6d30aa02016-07-15 19:53:25 +0000157 auto &States = ReachMap[To][From];
158 auto Idx = static_cast<size_t>(State);
159 if (!States.test(Idx)) {
160 States.set(Idx);
161 return true;
162 }
163 return false;
164 }
165
166 // Return the set of all ('From', 'State') pair for a given node 'To'
167 iterator_range<const_valuestate_iterator>
168 reachableValueAliases(InstantiatedValue V) const {
169 auto Itr = ReachMap.find(V);
170 if (Itr == ReachMap.end())
171 return make_range<const_valuestate_iterator>(const_valuestate_iterator(),
172 const_valuestate_iterator());
173 return make_range<const_valuestate_iterator>(Itr->second.begin(),
174 Itr->second.end());
175 }
176
177 iterator_range<const_value_iterator> value_mappings() const {
178 return make_range<const_value_iterator>(ReachMap.begin(), ReachMap.end());
179 }
180};
181
182// We use AliasMemSet to keep track of all memory aliases (the nonterminal "M"
183// in the paper) during the analysis.
184class AliasMemSet {
185 typedef DenseSet<InstantiatedValue> MemSet;
186 typedef DenseMap<InstantiatedValue, MemSet> MemMapType;
187 MemMapType MemMap;
188
189public:
190 typedef MemSet::const_iterator const_mem_iterator;
191
192 bool insert(InstantiatedValue LHS, InstantiatedValue RHS) {
193 // Top-level values can never be memory aliases because one cannot take the
194 // addresses of them
195 assert(LHS.DerefLevel > 0 && RHS.DerefLevel > 0);
196 return MemMap[LHS].insert(RHS).second;
197 }
198
199 const MemSet *getMemoryAliases(InstantiatedValue V) const {
200 auto Itr = MemMap.find(V);
201 if (Itr == MemMap.end())
202 return nullptr;
203 return &Itr->second;
204 }
205};
206
George Burgess IV22682e22016-07-15 20:02:49 +0000207// We use AliasAttrMap to keep track of the AliasAttr of each node.
208class AliasAttrMap {
209 typedef DenseMap<InstantiatedValue, AliasAttrs> MapType;
210 MapType AttrMap;
211
212public:
213 typedef MapType::const_iterator const_iterator;
214
215 bool add(InstantiatedValue V, AliasAttrs Attr) {
George Burgess IV22682e22016-07-15 20:02:49 +0000216 auto &OldAttr = AttrMap[V];
217 auto NewAttr = OldAttr | Attr;
218 if (OldAttr == NewAttr)
219 return false;
220 OldAttr = NewAttr;
221 return true;
222 }
223
224 AliasAttrs getAttrs(InstantiatedValue V) const {
225 AliasAttrs Attr;
226 auto Itr = AttrMap.find(V);
227 if (Itr != AttrMap.end())
228 Attr = Itr->second;
229 return Attr;
230 }
231
232 iterator_range<const_iterator> mappings() const {
233 return make_range<const_iterator>(AttrMap.begin(), AttrMap.end());
234 }
235};
236
George Burgess IV6d30aa02016-07-15 19:53:25 +0000237struct WorkListItem {
238 InstantiatedValue From;
239 InstantiatedValue To;
240 MatchState State;
241};
George Burgess IV3b059842016-07-19 20:47:15 +0000242
243struct ValueSummary {
244 struct Record {
245 InterfaceValue IValue;
246 unsigned DerefLevel;
247 };
248 SmallVector<Record, 4> FromRecords, ToRecords;
249};
George Burgess IV6d30aa02016-07-15 19:53:25 +0000250}
251
George Burgess IV4ec17532016-07-22 22:30:48 +0000252namespace llvm {
253// Specialize DenseMapInfo for OffsetValue.
254template <> struct DenseMapInfo<OffsetValue> {
255 static OffsetValue getEmptyKey() {
256 return OffsetValue{DenseMapInfo<const Value *>::getEmptyKey(),
257 DenseMapInfo<int64_t>::getEmptyKey()};
258 }
259 static OffsetValue getTombstoneKey() {
260 return OffsetValue{DenseMapInfo<const Value *>::getTombstoneKey(),
261 DenseMapInfo<int64_t>::getEmptyKey()};
262 }
263 static unsigned getHashValue(const OffsetValue &OVal) {
264 return DenseMapInfo<std::pair<const Value *, int64_t>>::getHashValue(
265 std::make_pair(OVal.Val, OVal.Offset));
266 }
267 static bool isEqual(const OffsetValue &LHS, const OffsetValue &RHS) {
268 return LHS == RHS;
269 }
270};
271
272// Specialize DenseMapInfo for OffsetInstantiatedValue.
273template <> struct DenseMapInfo<OffsetInstantiatedValue> {
274 static OffsetInstantiatedValue getEmptyKey() {
275 return OffsetInstantiatedValue{
276 DenseMapInfo<InstantiatedValue>::getEmptyKey(),
277 DenseMapInfo<int64_t>::getEmptyKey()};
278 }
279 static OffsetInstantiatedValue getTombstoneKey() {
280 return OffsetInstantiatedValue{
281 DenseMapInfo<InstantiatedValue>::getTombstoneKey(),
282 DenseMapInfo<int64_t>::getEmptyKey()};
283 }
284 static unsigned getHashValue(const OffsetInstantiatedValue &OVal) {
285 return DenseMapInfo<std::pair<InstantiatedValue, int64_t>>::getHashValue(
286 std::make_pair(OVal.IVal, OVal.Offset));
287 }
288 static bool isEqual(const OffsetInstantiatedValue &LHS,
289 const OffsetInstantiatedValue &RHS) {
290 return LHS == RHS;
291 }
292};
293}
294
George Burgess IV6d30aa02016-07-15 19:53:25 +0000295class CFLAndersAAResult::FunctionInfo {
296 /// Map a value to other values that may alias it
297 /// Since the alias relation is symmetric, to save some space we assume values
298 /// are properly ordered: if a and b alias each other, and a < b, then b is in
299 /// AliasMap[a] but not vice versa.
George Burgess IV4ec17532016-07-22 22:30:48 +0000300 DenseMap<const Value *, std::vector<OffsetValue>> AliasMap;
George Burgess IV6d30aa02016-07-15 19:53:25 +0000301
George Burgess IV22682e22016-07-15 20:02:49 +0000302 /// Map a value to its corresponding AliasAttrs
303 DenseMap<const Value *, AliasAttrs> AttrMap;
304
George Burgess IV6d30aa02016-07-15 19:53:25 +0000305 /// Summary of externally visible effects.
306 AliasSummary Summary;
307
George Burgess IV777efb12016-08-02 22:17:25 +0000308 Optional<AliasAttrs> getAttrs(const Value *) const;
George Burgess IV22682e22016-07-15 20:02:49 +0000309
George Burgess IV6d30aa02016-07-15 19:53:25 +0000310public:
George Burgess IV3b059842016-07-19 20:47:15 +0000311 FunctionInfo(const Function &, const SmallVectorImpl<Value *> &,
312 const ReachabilitySet &, AliasAttrMap);
George Burgess IV6d30aa02016-07-15 19:53:25 +0000313
George Burgess IV4ec17532016-07-22 22:30:48 +0000314 bool mayAlias(const Value *, uint64_t, const Value *, uint64_t) const;
George Burgess IV6d30aa02016-07-15 19:53:25 +0000315 const AliasSummary &getAliasSummary() const { return Summary; }
316};
317
George Burgess IV3b059842016-07-19 20:47:15 +0000318static bool hasReadOnlyState(StateSet Set) {
George Burgess IV22a0f1a2016-07-19 21:35:47 +0000319 return (Set & StateSet(ReadOnlyStateMask)).any();
George Burgess IV3b059842016-07-19 20:47:15 +0000320}
321
322static bool hasWriteOnlyState(StateSet Set) {
George Burgess IV22a0f1a2016-07-19 21:35:47 +0000323 return (Set & StateSet(WriteOnlyStateMask)).any();
George Burgess IV3b059842016-07-19 20:47:15 +0000324}
325
326static Optional<InterfaceValue>
327getInterfaceValue(InstantiatedValue IValue,
328 const SmallVectorImpl<Value *> &RetVals) {
329 auto Val = IValue.Val;
330
331 Optional<unsigned> Index;
332 if (auto Arg = dyn_cast<Argument>(Val))
333 Index = Arg->getArgNo() + 1;
334 else if (is_contained(RetVals, Val))
335 Index = 0;
336
337 if (Index)
338 return InterfaceValue{*Index, IValue.DerefLevel};
339 return None;
340}
341
342static void populateAttrMap(DenseMap<const Value *, AliasAttrs> &AttrMap,
343 const AliasAttrMap &AMap) {
George Burgess IV22682e22016-07-15 20:02:49 +0000344 for (const auto &Mapping : AMap.mappings()) {
345 auto IVal = Mapping.first;
346
George Burgess IV4c582662016-08-01 18:27:33 +0000347 // Insert IVal into the map
348 auto &Attr = AttrMap[IVal.Val];
George Burgess IV22682e22016-07-15 20:02:49 +0000349 // AttrMap only cares about top-level values
350 if (IVal.DerefLevel == 0)
George Burgess IV4c582662016-08-01 18:27:33 +0000351 Attr |= Mapping.second;
George Burgess IV22682e22016-07-15 20:02:49 +0000352 }
George Burgess IV3b059842016-07-19 20:47:15 +0000353}
George Burgess IV22682e22016-07-15 20:02:49 +0000354
George Burgess IV3b059842016-07-19 20:47:15 +0000355static void
George Burgess IV4ec17532016-07-22 22:30:48 +0000356populateAliasMap(DenseMap<const Value *, std::vector<OffsetValue>> &AliasMap,
George Burgess IV3b059842016-07-19 20:47:15 +0000357 const ReachabilitySet &ReachSet) {
George Burgess IV6d30aa02016-07-15 19:53:25 +0000358 for (const auto &OuterMapping : ReachSet.value_mappings()) {
359 // AliasMap only cares about top-level values
360 if (OuterMapping.first.DerefLevel > 0)
361 continue;
362
363 auto Val = OuterMapping.first.Val;
364 auto &AliasList = AliasMap[Val];
365 for (const auto &InnerMapping : OuterMapping.second) {
366 // Again, AliasMap only cares about top-level values
367 if (InnerMapping.first.DerefLevel == 0)
George Burgess IV4ec17532016-07-22 22:30:48 +0000368 AliasList.push_back(OffsetValue{InnerMapping.first.Val, UnknownOffset});
George Burgess IV6d30aa02016-07-15 19:53:25 +0000369 }
370
371 // Sort AliasList for faster lookup
George Burgess IV4ec17532016-07-22 22:30:48 +0000372 std::sort(AliasList.begin(), AliasList.end());
George Burgess IV6d30aa02016-07-15 19:53:25 +0000373 }
George Burgess IV3b059842016-07-19 20:47:15 +0000374}
George Burgess IV6d30aa02016-07-15 19:53:25 +0000375
George Burgess IV3b059842016-07-19 20:47:15 +0000376static void populateExternalRelations(
377 SmallVectorImpl<ExternalRelation> &ExtRelations, const Function &Fn,
378 const SmallVectorImpl<Value *> &RetVals, const ReachabilitySet &ReachSet) {
379 // If a function only returns one of its argument X, then X will be both an
380 // argument and a return value at the same time. This is an edge case that
381 // needs special handling here.
382 for (const auto &Arg : Fn.args()) {
383 if (is_contained(RetVals, &Arg)) {
384 auto ArgVal = InterfaceValue{Arg.getArgNo() + 1, 0};
385 auto RetVal = InterfaceValue{0, 0};
George Burgess IV4ec17532016-07-22 22:30:48 +0000386 ExtRelations.push_back(ExternalRelation{ArgVal, RetVal, 0});
George Burgess IV3b059842016-07-19 20:47:15 +0000387 }
388 }
389
390 // Below is the core summary construction logic.
391 // A naive solution of adding only the value aliases that are parameters or
392 // return values in ReachSet to the summary won't work: It is possible that a
393 // parameter P is written into an intermediate value I, and the function
394 // subsequently returns *I. In that case, *I is does not value alias anything
395 // in ReachSet, and the naive solution will miss a summary edge from (P, 1) to
396 // (I, 1).
397 // To account for the aforementioned case, we need to check each non-parameter
398 // and non-return value for the possibility of acting as an intermediate.
399 // 'ValueMap' here records, for each value, which InterfaceValues read from or
400 // write into it. If both the read list and the write list of a given value
401 // are non-empty, we know that a particular value is an intermidate and we
402 // need to add summary edges from the writes to the reads.
403 DenseMap<Value *, ValueSummary> ValueMap;
404 for (const auto &OuterMapping : ReachSet.value_mappings()) {
405 if (auto Dst = getInterfaceValue(OuterMapping.first, RetVals)) {
406 for (const auto &InnerMapping : OuterMapping.second) {
407 // If Src is a param/return value, we get a same-level assignment.
408 if (auto Src = getInterfaceValue(InnerMapping.first, RetVals)) {
409 // This may happen if both Dst and Src are return values
410 if (*Dst == *Src)
411 continue;
412
413 if (hasReadOnlyState(InnerMapping.second))
George Burgess IV4ec17532016-07-22 22:30:48 +0000414 ExtRelations.push_back(ExternalRelation{*Dst, *Src, UnknownOffset});
George Burgess IV3b059842016-07-19 20:47:15 +0000415 // No need to check for WriteOnly state, since ReachSet is symmetric
416 } else {
417 // If Src is not a param/return, add it to ValueMap
418 auto SrcIVal = InnerMapping.first;
419 if (hasReadOnlyState(InnerMapping.second))
420 ValueMap[SrcIVal.Val].FromRecords.push_back(
421 ValueSummary::Record{*Dst, SrcIVal.DerefLevel});
422 if (hasWriteOnlyState(InnerMapping.second))
423 ValueMap[SrcIVal.Val].ToRecords.push_back(
424 ValueSummary::Record{*Dst, SrcIVal.DerefLevel});
425 }
426 }
427 }
428 }
429
430 for (const auto &Mapping : ValueMap) {
431 for (const auto &FromRecord : Mapping.second.FromRecords) {
432 for (const auto &ToRecord : Mapping.second.ToRecords) {
433 auto ToLevel = ToRecord.DerefLevel;
434 auto FromLevel = FromRecord.DerefLevel;
435 // Same-level assignments should have already been processed by now
436 if (ToLevel == FromLevel)
437 continue;
438
439 auto SrcIndex = FromRecord.IValue.Index;
440 auto SrcLevel = FromRecord.IValue.DerefLevel;
441 auto DstIndex = ToRecord.IValue.Index;
442 auto DstLevel = ToRecord.IValue.DerefLevel;
443 if (ToLevel > FromLevel)
444 SrcLevel += ToLevel - FromLevel;
445 else
446 DstLevel += FromLevel - ToLevel;
447
George Burgess IV4ec17532016-07-22 22:30:48 +0000448 ExtRelations.push_back(ExternalRelation{
449 InterfaceValue{SrcIndex, SrcLevel},
450 InterfaceValue{DstIndex, DstLevel}, UnknownOffset});
George Burgess IV3b059842016-07-19 20:47:15 +0000451 }
452 }
453 }
454
455 // Remove duplicates in ExtRelations
456 std::sort(ExtRelations.begin(), ExtRelations.end());
457 ExtRelations.erase(std::unique(ExtRelations.begin(), ExtRelations.end()),
458 ExtRelations.end());
459}
460
461static void populateExternalAttributes(
462 SmallVectorImpl<ExternalAttribute> &ExtAttributes, const Function &Fn,
463 const SmallVectorImpl<Value *> &RetVals, const AliasAttrMap &AMap) {
464 for (const auto &Mapping : AMap.mappings()) {
465 if (auto IVal = getInterfaceValue(Mapping.first, RetVals)) {
466 auto Attr = getExternallyVisibleAttrs(Mapping.second);
467 if (Attr.any())
468 ExtAttributes.push_back(ExternalAttribute{*IVal, Attr});
469 }
470 }
471}
472
473CFLAndersAAResult::FunctionInfo::FunctionInfo(
474 const Function &Fn, const SmallVectorImpl<Value *> &RetVals,
475 const ReachabilitySet &ReachSet, AliasAttrMap AMap) {
476 populateAttrMap(AttrMap, AMap);
477 populateExternalAttributes(Summary.RetParamAttributes, Fn, RetVals, AMap);
478 populateAliasMap(AliasMap, ReachSet);
479 populateExternalRelations(Summary.RetParamRelations, Fn, RetVals, ReachSet);
George Burgess IV6d30aa02016-07-15 19:53:25 +0000480}
481
George Burgess IV777efb12016-08-02 22:17:25 +0000482Optional<AliasAttrs>
483CFLAndersAAResult::FunctionInfo::getAttrs(const Value *V) const {
George Burgess IV22682e22016-07-15 20:02:49 +0000484 assert(V != nullptr);
485
George Burgess IV22682e22016-07-15 20:02:49 +0000486 auto Itr = AttrMap.find(V);
487 if (Itr != AttrMap.end())
George Burgess IV777efb12016-08-02 22:17:25 +0000488 return Itr->second;
489 return None;
George Burgess IV22682e22016-07-15 20:02:49 +0000490}
491
George Burgess IV6d30aa02016-07-15 19:53:25 +0000492bool CFLAndersAAResult::FunctionInfo::mayAlias(const Value *LHS,
George Burgess IV4ec17532016-07-22 22:30:48 +0000493 uint64_t LHSSize,
494 const Value *RHS,
495 uint64_t RHSSize) const {
George Burgess IV6d30aa02016-07-15 19:53:25 +0000496 assert(LHS && RHS);
497
George Burgess IV777efb12016-08-02 22:17:25 +0000498 // Check if we've seen LHS and RHS before. Sometimes LHS or RHS can be created
499 // after the analysis gets executed, and we want to be conservative in those
500 // cases.
501 auto MaybeAttrsA = getAttrs(LHS);
502 auto MaybeAttrsB = getAttrs(RHS);
503 if (!MaybeAttrsA || !MaybeAttrsB)
504 return true;
505
506 // Check AliasAttrs before AliasMap lookup since it's cheaper
507 auto AttrsA = *MaybeAttrsA;
508 auto AttrsB = *MaybeAttrsB;
George Burgess IV4ec17532016-07-22 22:30:48 +0000509 if (hasUnknownOrCallerAttr(AttrsA))
510 return AttrsB.any();
511 if (hasUnknownOrCallerAttr(AttrsB))
512 return AttrsA.any();
513 if (isGlobalOrArgAttr(AttrsA))
514 return isGlobalOrArgAttr(AttrsB);
515 if (isGlobalOrArgAttr(AttrsB))
516 return isGlobalOrArgAttr(AttrsA);
517
518 // At this point both LHS and RHS should point to locally allocated objects
519
George Burgess IV6d30aa02016-07-15 19:53:25 +0000520 auto Itr = AliasMap.find(LHS);
George Burgess IV22682e22016-07-15 20:02:49 +0000521 if (Itr != AliasMap.end()) {
George Burgess IV4ec17532016-07-22 22:30:48 +0000522
523 // Find out all (X, Offset) where X == RHS
524 auto Comparator = [](OffsetValue LHS, OffsetValue RHS) {
525 return std::less<const Value *>()(LHS.Val, RHS.Val);
526 };
527#ifdef EXPENSIVE_CHECKS
528 assert(std::is_sorted(Itr->second.begin(), Itr->second.end(), Comparator));
529#endif
530 auto RangePair = std::equal_range(Itr->second.begin(), Itr->second.end(),
531 OffsetValue{RHS, 0}, Comparator);
532
533 if (RangePair.first != RangePair.second) {
534 // Be conservative about UnknownSize
535 if (LHSSize == MemoryLocation::UnknownSize ||
536 RHSSize == MemoryLocation::UnknownSize)
537 return true;
538
539 for (const auto &OVal : make_range(RangePair)) {
540 // Be conservative about UnknownOffset
541 if (OVal.Offset == UnknownOffset)
542 return true;
543
544 // We know that LHS aliases (RHS + OVal.Offset) if the control flow
545 // reaches here. The may-alias query essentially becomes integer
546 // range-overlap queries over two ranges [OVal.Offset, OVal.Offset +
547 // LHSSize) and [0, RHSSize).
548
549 // Try to be conservative on super large offsets
550 if (LLVM_UNLIKELY(LHSSize > INT64_MAX || RHSSize > INT64_MAX))
551 return true;
552
553 auto LHSStart = OVal.Offset;
554 // FIXME: Do we need to guard against integer overflow?
555 auto LHSEnd = OVal.Offset + static_cast<int64_t>(LHSSize);
556 auto RHSStart = 0;
557 auto RHSEnd = static_cast<int64_t>(RHSSize);
558 if (LHSEnd > RHSStart && LHSStart < RHSEnd)
559 return true;
560 }
561 }
George Burgess IV22682e22016-07-15 20:02:49 +0000562 }
563
George Burgess IV22682e22016-07-15 20:02:49 +0000564 return false;
George Burgess IV6d30aa02016-07-15 19:53:25 +0000565}
566
567static void propagate(InstantiatedValue From, InstantiatedValue To,
568 MatchState State, ReachabilitySet &ReachSet,
569 std::vector<WorkListItem> &WorkList) {
570 if (From == To)
571 return;
572 if (ReachSet.insert(From, To, State))
573 WorkList.push_back(WorkListItem{From, To, State});
574}
575
576static void initializeWorkList(std::vector<WorkListItem> &WorkList,
577 ReachabilitySet &ReachSet,
578 const CFLGraph &Graph) {
579 for (const auto &Mapping : Graph.value_mappings()) {
580 auto Val = Mapping.first;
581 auto &ValueInfo = Mapping.second;
582 assert(ValueInfo.getNumLevels() > 0);
583
584 // Insert all immediate assignment neighbors to the worklist
585 for (unsigned I = 0, E = ValueInfo.getNumLevels(); I < E; ++I) {
586 auto Src = InstantiatedValue{Val, I};
587 // If there's an assignment edge from X to Y, it means Y is reachable from
588 // X at S2 and X is reachable from Y at S1
589 for (auto &Edge : ValueInfo.getNodeInfoAtLevel(I).Edges) {
George Burgess IVc01b42f2016-07-19 20:38:21 +0000590 propagate(Edge.Other, Src, MatchState::FlowFromReadOnly, ReachSet,
591 WorkList);
592 propagate(Src, Edge.Other, MatchState::FlowToWriteOnly, ReachSet,
593 WorkList);
George Burgess IV6d30aa02016-07-15 19:53:25 +0000594 }
595 }
596 }
597}
598
599static Optional<InstantiatedValue> getNodeBelow(const CFLGraph &Graph,
600 InstantiatedValue V) {
601 auto NodeBelow = InstantiatedValue{V.Val, V.DerefLevel + 1};
602 if (Graph.getNode(NodeBelow))
603 return NodeBelow;
604 return None;
605}
606
607static void processWorkListItem(const WorkListItem &Item, const CFLGraph &Graph,
608 ReachabilitySet &ReachSet, AliasMemSet &MemSet,
609 std::vector<WorkListItem> &WorkList) {
610 auto FromNode = Item.From;
611 auto ToNode = Item.To;
612
613 auto NodeInfo = Graph.getNode(ToNode);
614 assert(NodeInfo != nullptr);
615
George Burgess IV6d30aa02016-07-15 19:53:25 +0000616 // TODO: propagate field offsets
617
618 // FIXME: Here is a neat trick we can do: since both ReachSet and MemSet holds
619 // relations that are symmetric, we could actually cut the storage by half by
620 // sorting FromNode and ToNode before insertion happens.
621
622 // The newly added value alias pair may pontentially generate more memory
623 // alias pairs. Check for them here.
624 auto FromNodeBelow = getNodeBelow(Graph, FromNode);
625 auto ToNodeBelow = getNodeBelow(Graph, ToNode);
626 if (FromNodeBelow && ToNodeBelow &&
627 MemSet.insert(*FromNodeBelow, *ToNodeBelow)) {
George Burgess IVc01b42f2016-07-19 20:38:21 +0000628 propagate(*FromNodeBelow, *ToNodeBelow,
629 MatchState::FlowFromMemAliasNoReadWrite, ReachSet, WorkList);
George Burgess IV6d30aa02016-07-15 19:53:25 +0000630 for (const auto &Mapping : ReachSet.reachableValueAliases(*FromNodeBelow)) {
631 auto Src = Mapping.first;
George Burgess IVc01b42f2016-07-19 20:38:21 +0000632 auto MemAliasPropagate = [&](MatchState FromState, MatchState ToState) {
633 if (Mapping.second.test(static_cast<size_t>(FromState)))
634 propagate(Src, *ToNodeBelow, ToState, ReachSet, WorkList);
635 };
636
637 MemAliasPropagate(MatchState::FlowFromReadOnly,
638 MatchState::FlowFromMemAliasReadOnly);
639 MemAliasPropagate(MatchState::FlowToWriteOnly,
640 MatchState::FlowToMemAliasWriteOnly);
641 MemAliasPropagate(MatchState::FlowToReadWrite,
642 MatchState::FlowToMemAliasReadWrite);
George Burgess IV6d30aa02016-07-15 19:53:25 +0000643 }
644 }
645
646 // This is the core of the state machine walking algorithm. We expand ReachSet
647 // based on which state we are at (which in turn dictates what edges we
648 // should examine)
649 // From a high-level point of view, the state machine here guarantees two
650 // properties:
651 // - If *X and *Y are memory aliases, then X and Y are value aliases
652 // - If Y is an alias of X, then reverse assignment edges (if there is any)
653 // should precede any assignment edges on the path from X to Y.
George Burgess IVc01b42f2016-07-19 20:38:21 +0000654 auto NextAssignState = [&](MatchState State) {
655 for (const auto &AssignEdge : NodeInfo->Edges)
656 propagate(FromNode, AssignEdge.Other, State, ReachSet, WorkList);
657 };
658 auto NextRevAssignState = [&](MatchState State) {
659 for (const auto &RevAssignEdge : NodeInfo->ReverseEdges)
660 propagate(FromNode, RevAssignEdge.Other, State, ReachSet, WorkList);
661 };
662 auto NextMemState = [&](MatchState State) {
663 if (auto AliasSet = MemSet.getMemoryAliases(ToNode)) {
664 for (const auto &MemAlias : *AliasSet)
665 propagate(FromNode, MemAlias, State, ReachSet, WorkList);
666 }
667 };
668
George Burgess IV6d30aa02016-07-15 19:53:25 +0000669 switch (Item.State) {
George Burgess IVc01b42f2016-07-19 20:38:21 +0000670 case MatchState::FlowFromReadOnly: {
671 NextRevAssignState(MatchState::FlowFromReadOnly);
672 NextAssignState(MatchState::FlowToReadWrite);
673 NextMemState(MatchState::FlowFromMemAliasReadOnly);
George Burgess IV6d30aa02016-07-15 19:53:25 +0000674 break;
675 }
George Burgess IVc01b42f2016-07-19 20:38:21 +0000676 case MatchState::FlowFromMemAliasNoReadWrite: {
677 NextRevAssignState(MatchState::FlowFromReadOnly);
678 NextAssignState(MatchState::FlowToWriteOnly);
George Burgess IV6d30aa02016-07-15 19:53:25 +0000679 break;
680 }
George Burgess IVc01b42f2016-07-19 20:38:21 +0000681 case MatchState::FlowFromMemAliasReadOnly: {
682 NextRevAssignState(MatchState::FlowFromReadOnly);
683 NextAssignState(MatchState::FlowToReadWrite);
George Burgess IV6d30aa02016-07-15 19:53:25 +0000684 break;
685 }
George Burgess IVc01b42f2016-07-19 20:38:21 +0000686 case MatchState::FlowToWriteOnly: {
687 NextAssignState(MatchState::FlowToWriteOnly);
688 NextMemState(MatchState::FlowToMemAliasWriteOnly);
689 break;
690 }
691 case MatchState::FlowToReadWrite: {
692 NextAssignState(MatchState::FlowToReadWrite);
693 NextMemState(MatchState::FlowToMemAliasReadWrite);
694 break;
695 }
696 case MatchState::FlowToMemAliasWriteOnly: {
697 NextAssignState(MatchState::FlowToWriteOnly);
698 break;
699 }
700 case MatchState::FlowToMemAliasReadWrite: {
701 NextAssignState(MatchState::FlowToReadWrite);
George Burgess IV6d30aa02016-07-15 19:53:25 +0000702 break;
703 }
704 }
705}
706
George Burgess IV22682e22016-07-15 20:02:49 +0000707static AliasAttrMap buildAttrMap(const CFLGraph &Graph,
708 const ReachabilitySet &ReachSet) {
709 AliasAttrMap AttrMap;
710 std::vector<InstantiatedValue> WorkList, NextList;
711
712 // Initialize each node with its original AliasAttrs in CFLGraph
713 for (const auto &Mapping : Graph.value_mappings()) {
714 auto Val = Mapping.first;
715 auto &ValueInfo = Mapping.second;
716 for (unsigned I = 0, E = ValueInfo.getNumLevels(); I < E; ++I) {
717 auto Node = InstantiatedValue{Val, I};
718 AttrMap.add(Node, ValueInfo.getNodeInfoAtLevel(I).Attr);
719 WorkList.push_back(Node);
720 }
721 }
722
723 while (!WorkList.empty()) {
724 for (const auto &Dst : WorkList) {
725 auto DstAttr = AttrMap.getAttrs(Dst);
726 if (DstAttr.none())
727 continue;
728
729 // Propagate attr on the same level
730 for (const auto &Mapping : ReachSet.reachableValueAliases(Dst)) {
731 auto Src = Mapping.first;
732 if (AttrMap.add(Src, DstAttr))
733 NextList.push_back(Src);
734 }
735
736 // Propagate attr to the levels below
737 auto DstBelow = getNodeBelow(Graph, Dst);
738 while (DstBelow) {
739 if (AttrMap.add(*DstBelow, DstAttr)) {
740 NextList.push_back(*DstBelow);
741 break;
742 }
743 DstBelow = getNodeBelow(Graph, *DstBelow);
744 }
745 }
746 WorkList.swap(NextList);
747 NextList.clear();
748 }
749
750 return AttrMap;
751}
752
George Burgess IV6d30aa02016-07-15 19:53:25 +0000753CFLAndersAAResult::FunctionInfo
754CFLAndersAAResult::buildInfoFrom(const Function &Fn) {
755 CFLGraphBuilder<CFLAndersAAResult> GraphBuilder(
756 *this, TLI,
757 // Cast away the constness here due to GraphBuilder's API requirement
758 const_cast<Function &>(Fn));
759 auto &Graph = GraphBuilder.getCFLGraph();
760
761 ReachabilitySet ReachSet;
762 AliasMemSet MemSet;
763
764 std::vector<WorkListItem> WorkList, NextList;
765 initializeWorkList(WorkList, ReachSet, Graph);
766 // TODO: make sure we don't stop before the fix point is reached
767 while (!WorkList.empty()) {
768 for (const auto &Item : WorkList)
769 processWorkListItem(Item, Graph, ReachSet, MemSet, NextList);
770
771 NextList.swap(WorkList);
772 NextList.clear();
773 }
774
George Burgess IV22682e22016-07-15 20:02:49 +0000775 // Now that we have all the reachability info, propagate AliasAttrs according
776 // to it
777 auto IValueAttrMap = buildAttrMap(Graph, ReachSet);
778
George Burgess IV3b059842016-07-19 20:47:15 +0000779 return FunctionInfo(Fn, GraphBuilder.getReturnValues(), ReachSet,
780 std::move(IValueAttrMap));
George Burgess IV6d30aa02016-07-15 19:53:25 +0000781}
782
783void CFLAndersAAResult::scan(const Function &Fn) {
784 auto InsertPair = Cache.insert(std::make_pair(&Fn, Optional<FunctionInfo>()));
785 (void)InsertPair;
786 assert(InsertPair.second &&
787 "Trying to scan a function that has already been cached");
788
789 // Note that we can't do Cache[Fn] = buildSetsFrom(Fn) here: the function call
790 // may get evaluated after operator[], potentially triggering a DenseMap
791 // resize and invalidating the reference returned by operator[]
792 auto FunInfo = buildInfoFrom(Fn);
793 Cache[&Fn] = std::move(FunInfo);
794 Handles.push_front(FunctionHandle(const_cast<Function *>(&Fn), this));
795}
796
797void CFLAndersAAResult::evict(const Function &Fn) { Cache.erase(&Fn); }
798
799const Optional<CFLAndersAAResult::FunctionInfo> &
800CFLAndersAAResult::ensureCached(const Function &Fn) {
801 auto Iter = Cache.find(&Fn);
802 if (Iter == Cache.end()) {
803 scan(Fn);
804 Iter = Cache.find(&Fn);
805 assert(Iter != Cache.end());
806 assert(Iter->second.hasValue());
807 }
808 return Iter->second;
809}
810
811const AliasSummary *CFLAndersAAResult::getAliasSummary(const Function &Fn) {
812 auto &FunInfo = ensureCached(Fn);
813 if (FunInfo.hasValue())
814 return &FunInfo->getAliasSummary();
815 else
816 return nullptr;
817}
818
819AliasResult CFLAndersAAResult::query(const MemoryLocation &LocA,
820 const MemoryLocation &LocB) {
821 auto *ValA = LocA.Ptr;
822 auto *ValB = LocB.Ptr;
823
824 if (!ValA->getType()->isPointerTy() || !ValB->getType()->isPointerTy())
825 return NoAlias;
826
827 auto *Fn = parentFunctionOfValue(ValA);
828 if (!Fn) {
829 Fn = parentFunctionOfValue(ValB);
830 if (!Fn) {
831 // The only times this is known to happen are when globals + InlineAsm are
832 // involved
833 DEBUG(dbgs()
834 << "CFLAndersAA: could not extract parent function information.\n");
835 return MayAlias;
836 }
837 } else {
838 assert(!parentFunctionOfValue(ValB) || parentFunctionOfValue(ValB) == Fn);
839 }
840
841 assert(Fn != nullptr);
842 auto &FunInfo = ensureCached(*Fn);
843
844 // AliasMap lookup
George Burgess IV4ec17532016-07-22 22:30:48 +0000845 if (FunInfo->mayAlias(ValA, LocA.Size, ValB, LocB.Size))
George Burgess IV6d30aa02016-07-15 19:53:25 +0000846 return MayAlias;
847 return NoAlias;
848}
849
850AliasResult CFLAndersAAResult::alias(const MemoryLocation &LocA,
851 const MemoryLocation &LocB) {
852 if (LocA.Ptr == LocB.Ptr)
853 return LocA.Size == LocB.Size ? MustAlias : PartialAlias;
854
855 // Comparisons between global variables and other constants should be
856 // handled by BasicAA.
857 // CFLAndersAA may report NoAlias when comparing a GlobalValue and
858 // ConstantExpr, but every query needs to have at least one Value tied to a
859 // Function, and neither GlobalValues nor ConstantExprs are.
860 if (isa<Constant>(LocA.Ptr) && isa<Constant>(LocB.Ptr))
861 return AAResultBase::alias(LocA, LocB);
862
863 AliasResult QueryResult = query(LocA, LocB);
864 if (QueryResult == MayAlias)
865 return AAResultBase::alias(LocA, LocB);
866
867 return QueryResult;
868}
George Burgess IVbfa401e2016-07-06 00:26:41 +0000869
870char CFLAndersAA::PassID;
871
Sean Silva36e0d012016-08-09 00:28:15 +0000872CFLAndersAAResult CFLAndersAA::run(Function &F, FunctionAnalysisManager &AM) {
George Burgess IV6d30aa02016-07-15 19:53:25 +0000873 return CFLAndersAAResult(AM.getResult<TargetLibraryAnalysis>(F));
George Burgess IVbfa401e2016-07-06 00:26:41 +0000874}
875
876char CFLAndersAAWrapperPass::ID = 0;
877INITIALIZE_PASS(CFLAndersAAWrapperPass, "cfl-anders-aa",
878 "Inclusion-Based CFL Alias Analysis", false, true)
879
880ImmutablePass *llvm::createCFLAndersAAWrapperPass() {
881 return new CFLAndersAAWrapperPass();
882}
883
884CFLAndersAAWrapperPass::CFLAndersAAWrapperPass() : ImmutablePass(ID) {
885 initializeCFLAndersAAWrapperPassPass(*PassRegistry::getPassRegistry());
886}
887
George Burgess IV6d30aa02016-07-15 19:53:25 +0000888void CFLAndersAAWrapperPass::initializePass() {
889 auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>();
890 Result.reset(new CFLAndersAAResult(TLIWP.getTLI()));
891}
George Burgess IVbfa401e2016-07-06 00:26:41 +0000892
893void CFLAndersAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
894 AU.setPreservesAll();
George Burgess IV6d30aa02016-07-15 19:53:25 +0000895 AU.addRequired<TargetLibraryInfoWrapperPass>();
George Burgess IVbfa401e2016-07-06 00:26:41 +0000896}