blob: 45c317d4a82d12057a1b672795b32bbcb891105c [file] [log] [blame]
Hal Finkel7529c552014-09-02 21:43:13 +00001//===- StratifiedSets.h - Abstract stratified sets 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#ifndef LLVM_ADT_STRATIFIEDSETS_H
11#define LLVM_ADT_STRATIFIEDSETS_H
12
13#include "llvm/ADT/DenseMap.h"
14#include "llvm/ADT/Optional.h"
Hal Finkel7529c552014-09-02 21:43:13 +000015#include "llvm/ADT/SmallSet.h"
16#include "llvm/ADT/SmallVector.h"
17#include <bitset>
18#include <cassert>
19#include <cmath>
Hal Finkel7529c552014-09-02 21:43:13 +000020#include <type_traits>
Hal Finkel8d1590d2014-09-02 22:52:30 +000021#include <utility>
Hal Finkel7529c552014-09-02 21:43:13 +000022#include <vector>
23
24namespace llvm {
George Burgess IVcae581d2016-04-13 23:27:37 +000025/// An index into Stratified Sets.
Hal Finkel7529c552014-09-02 21:43:13 +000026typedef unsigned StratifiedIndex;
George Burgess IVcae581d2016-04-13 23:27:37 +000027/// NOTE: ^ This can't be a short -- bootstrapping clang has a case where
28/// ~1M sets exist.
Hal Finkel7529c552014-09-02 21:43:13 +000029
30// \brief Container of information related to a value in a StratifiedSet.
31struct StratifiedInfo {
32 StratifiedIndex Index;
George Burgess IVcae581d2016-04-13 23:27:37 +000033 /// For field sensitivity, etc. we can tack fields on here.
Hal Finkel7529c552014-09-02 21:43:13 +000034};
35
George Burgess IVcae581d2016-04-13 23:27:37 +000036/// The number of attributes that StratifiedAttrs should contain. Attributes are
37/// described below, and 32 was an arbitrary choice because it fits nicely in 32
38/// bits (because we use a bitset for StratifiedAttrs).
Hal Finkel981602a2014-09-02 22:26:06 +000039static const unsigned NumStratifiedAttrs = 32;
Hal Finkel7529c552014-09-02 21:43:13 +000040
George Burgess IVcae581d2016-04-13 23:27:37 +000041/// These are attributes that the users of StratifiedSets/StratifiedSetBuilders
42/// may use for various purposes. These also have the special property of that
43/// they are merged down. So, if set A is above set B, and one decides to set an
44/// attribute in set A, then the attribute will automatically be set in set B.
Hal Finkel7529c552014-09-02 21:43:13 +000045typedef std::bitset<NumStratifiedAttrs> StratifiedAttrs;
46
George Burgess IVcae581d2016-04-13 23:27:37 +000047/// A "link" between two StratifiedSets.
Hal Finkel7529c552014-09-02 21:43:13 +000048struct StratifiedLink {
George Burgess IVcae581d2016-04-13 23:27:37 +000049 /// \brief This is a value used to signify "does not exist" where the
50 /// StratifiedIndex type is used.
51 ///
52 /// This is used instead of Optional<StratifiedIndex> because
53 /// Optional<StratifiedIndex> would eat up a considerable amount of extra
54 /// memory, after struct padding/alignment is taken into account.
Hal Finkel1ae325f2014-09-02 23:50:01 +000055 static const StratifiedIndex SetSentinel;
Hal Finkel7529c552014-09-02 21:43:13 +000056
George Burgess IVcae581d2016-04-13 23:27:37 +000057 /// The index for the set "above" current
Hal Finkel7529c552014-09-02 21:43:13 +000058 StratifiedIndex Above;
59
George Burgess IVcae581d2016-04-13 23:27:37 +000060 /// The link for the set "below" current
Hal Finkel7529c552014-09-02 21:43:13 +000061 StratifiedIndex Below;
62
George Burgess IVcae581d2016-04-13 23:27:37 +000063 /// Attributes for these StratifiedSets.
Hal Finkel7529c552014-09-02 21:43:13 +000064 StratifiedAttrs Attrs;
65
66 StratifiedLink() : Above(SetSentinel), Below(SetSentinel) {}
67
68 bool hasBelow() const { return Below != SetSentinel; }
69 bool hasAbove() const { return Above != SetSentinel; }
70
71 void clearBelow() { Below = SetSentinel; }
72 void clearAbove() { Above = SetSentinel; }
73};
74
George Burgess IVcae581d2016-04-13 23:27:37 +000075/// \brief These are stratified sets, as described in "Fast algorithms for
76/// Dyck-CFL-reachability with applications to Alias Analysis" by Zhang Q, Lyu M
77/// R, Yuan H, and Su Z. -- in short, this is meant to represent different sets
78/// of Value*s. If two Value*s are in the same set, or if both sets have
79/// overlapping attributes, then the Value*s are said to alias.
80///
81/// Sets may be related by position, meaning that one set may be considered as
82/// above or below another. In CFL Alias Analysis, this gives us an indication
83/// of how two variables are related; if the set of variable A is below a set
84/// containing variable B, then at some point, a variable that has interacted
85/// with B (or B itself) was either used in order to extract the variable A, or
86/// was used as storage of variable A.
87///
88/// Sets may also have attributes (as noted above). These attributes are
89/// generally used for noting whether a variable in the set has interacted with
90/// a variable whose origins we don't quite know (i.e. globals/arguments), or if
91/// the variable may have had operations performed on it (modified in a function
92/// call). All attributes that exist in a set A must exist in all sets marked as
93/// below set A.
Hal Finkel7529c552014-09-02 21:43:13 +000094template <typename T> class StratifiedSets {
95public:
George Burgess IV60af2262016-06-07 21:41:18 +000096 StratifiedSets() = default;
George Burgess IVfd4e2f72016-06-08 17:56:35 +000097
98 // TODO: Figure out how to make MSVC not call the copy ctor here, and delete
99 // it.
George Burgess IV785f3912016-06-08 17:27:14 +0000100
101 // Can't default these due to compile errors in MSVC2013
102 StratifiedSets(StratifiedSets &&Other) { *this = std::move(Other); }
103 StratifiedSets &operator=(StratifiedSets &&Other) {
104 Values = std::move(Other.Values);
105 Links = std::move(Other.Links);
106 return *this;
107 }
Hal Finkel7529c552014-09-02 21:43:13 +0000108
109 StratifiedSets(DenseMap<T, StratifiedInfo> Map,
110 std::vector<StratifiedLink> Links)
111 : Values(std::move(Map)), Links(std::move(Links)) {}
112
Hal Finkel7529c552014-09-02 21:43:13 +0000113 Optional<StratifiedInfo> find(const T &Elem) const {
114 auto Iter = Values.find(Elem);
George Burgess IVcae581d2016-04-13 23:27:37 +0000115 if (Iter == Values.end())
116 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000117 return Iter->second;
118 }
119
120 const StratifiedLink &getLink(StratifiedIndex Index) const {
121 assert(inbounds(Index));
122 return Links[Index];
123 }
124
125private:
126 DenseMap<T, StratifiedInfo> Values;
127 std::vector<StratifiedLink> Links;
128
129 bool inbounds(StratifiedIndex Idx) const { return Idx < Links.size(); }
130};
131
George Burgess IVcae581d2016-04-13 23:27:37 +0000132/// Generic Builder class that produces StratifiedSets instances.
133///
134/// The goal of this builder is to efficiently produce correct StratifiedSets
135/// instances. To this end, we use a few tricks:
136/// > Set chains (A method for linking sets together)
137/// > Set remaps (A method for marking a set as an alias [irony?] of another)
138///
139/// ==== Set chains ====
140/// This builder has a notion of some value A being above, below, or with some
141/// other value B:
142/// > The `A above B` relationship implies that there is a reference edge
143/// going from A to B. Namely, it notes that A can store anything in B's set.
144/// > The `A below B` relationship is the opposite of `A above B`. It implies
145/// that there's a dereference edge going from A to B.
146/// > The `A with B` relationship states that there's an assignment edge going
147/// from A to B, and that A and B should be treated as equals.
148///
149/// As an example, take the following code snippet:
150///
151/// %a = alloca i32, align 4
152/// %ap = alloca i32*, align 8
153/// %app = alloca i32**, align 8
154/// store %a, %ap
155/// store %ap, %app
George Burgess IV60af2262016-06-07 21:41:18 +0000156/// %aw = getelementptr %ap, i32 0
George Burgess IVcae581d2016-04-13 23:27:37 +0000157///
George Burgess IV60af2262016-06-07 21:41:18 +0000158/// Given this, the following relations exist:
George Burgess IVcae581d2016-04-13 23:27:37 +0000159/// - %a below %ap & %ap above %a
160/// - %ap below %app & %app above %ap
161/// - %aw with %ap & %ap with %aw
162///
163/// These relations produce the following sets:
164/// [{%a}, {%ap, %aw}, {%app}]
165///
George Burgess IV60af2262016-06-07 21:41:18 +0000166/// ...Which state that the only MayAlias relationship in the above program is
George Burgess IVcae581d2016-04-13 23:27:37 +0000167/// between %ap and %aw.
168///
George Burgess IV60af2262016-06-07 21:41:18 +0000169/// Because LLVM allows arbitrary casts, code like the following needs to be
170/// supported:
171/// %ip = alloca i64, align 8
172/// %ipp = alloca i64*, align 8
173/// %i = bitcast i64** ipp to i64
174/// store i64* %ip, i64** %ipp
175/// store i64 %i, i64* %ip
George Burgess IVcae581d2016-04-13 23:27:37 +0000176///
George Burgess IV60af2262016-06-07 21:41:18 +0000177/// Which, because %ipp ends up *both* above and below %ip, is fun.
George Burgess IVcae581d2016-04-13 23:27:37 +0000178///
George Burgess IV60af2262016-06-07 21:41:18 +0000179/// This is solved by merging %i and %ipp into a single set (...which is the
180/// only way to solve this, since their bit patterns are equivalent). Any sets
181/// that ended up in between %i and %ipp at the time of merging (in this case,
182/// the set containing %ip) also get conservatively merged into the set of %i
183/// and %ipp. In short, the resulting StratifiedSet from the above code would be
184/// {%ip, %ipp, %i}.
George Burgess IVcae581d2016-04-13 23:27:37 +0000185///
186/// ==== Set remaps ====
187/// More of an implementation detail than anything -- when merging sets, we need
188/// to update the numbers of all of the elements mapped to those sets. Rather
189/// than doing this at each merge, we note in the BuilderLink structure that a
190/// remap has occurred, and use this information so we can defer renumbering set
191/// elements until build time.
Hal Finkel7529c552014-09-02 21:43:13 +0000192template <typename T> class StratifiedSetsBuilder {
George Burgess IVcae581d2016-04-13 23:27:37 +0000193 /// \brief Represents a Stratified Set, with information about the Stratified
194 /// Set above it, the set below it, and whether the current set has been
195 /// remapped to another.
Hal Finkel7529c552014-09-02 21:43:13 +0000196 struct BuilderLink {
197 const StratifiedIndex Number;
198
199 BuilderLink(StratifiedIndex N) : Number(N) {
200 Remap = StratifiedLink::SetSentinel;
201 }
202
203 bool hasAbove() const {
204 assert(!isRemapped());
205 return Link.hasAbove();
206 }
207
208 bool hasBelow() const {
209 assert(!isRemapped());
210 return Link.hasBelow();
211 }
212
213 void setBelow(StratifiedIndex I) {
214 assert(!isRemapped());
215 Link.Below = I;
216 }
217
218 void setAbove(StratifiedIndex I) {
219 assert(!isRemapped());
220 Link.Above = I;
221 }
222
223 void clearBelow() {
224 assert(!isRemapped());
225 Link.clearBelow();
226 }
227
228 void clearAbove() {
229 assert(!isRemapped());
230 Link.clearAbove();
231 }
232
233 StratifiedIndex getBelow() const {
234 assert(!isRemapped());
235 assert(hasBelow());
236 return Link.Below;
237 }
238
239 StratifiedIndex getAbove() const {
240 assert(!isRemapped());
241 assert(hasAbove());
242 return Link.Above;
243 }
244
245 StratifiedAttrs &getAttrs() {
246 assert(!isRemapped());
247 return Link.Attrs;
248 }
249
Hal Finkel7529c552014-09-02 21:43:13 +0000250 void setAttrs(const StratifiedAttrs &other) {
251 assert(!isRemapped());
252 Link.Attrs |= other;
253 }
254
255 bool isRemapped() const { return Remap != StratifiedLink::SetSentinel; }
256
George Burgess IVcae581d2016-04-13 23:27:37 +0000257 /// For initial remapping to another set
Hal Finkel7529c552014-09-02 21:43:13 +0000258 void remapTo(StratifiedIndex Other) {
259 assert(!isRemapped());
260 Remap = Other;
261 }
262
263 StratifiedIndex getRemapIndex() const {
264 assert(isRemapped());
265 return Remap;
266 }
267
George Burgess IVcae581d2016-04-13 23:27:37 +0000268 /// Should only be called when we're already remapped.
Hal Finkel7529c552014-09-02 21:43:13 +0000269 void updateRemap(StratifiedIndex Other) {
270 assert(isRemapped());
271 Remap = Other;
272 }
273
George Burgess IVcae581d2016-04-13 23:27:37 +0000274 /// Prefer the above functions to calling things directly on what's returned
275 /// from this -- they guard against unexpected calls when the current
276 /// BuilderLink is remapped.
Hal Finkel7529c552014-09-02 21:43:13 +0000277 const StratifiedLink &getLink() const { return Link; }
278
279 private:
280 StratifiedLink Link;
281 StratifiedIndex Remap;
282 };
283
George Burgess IVcae581d2016-04-13 23:27:37 +0000284 /// \brief This function performs all of the set unioning/value renumbering
285 /// that we've been putting off, and generates a vector<StratifiedLink> that
286 /// may be placed in a StratifiedSets instance.
Hal Finkel7529c552014-09-02 21:43:13 +0000287 void finalizeSets(std::vector<StratifiedLink> &StratLinks) {
288 DenseMap<StratifiedIndex, StratifiedIndex> Remaps;
289 for (auto &Link : Links) {
George Burgess IVcae581d2016-04-13 23:27:37 +0000290 if (Link.isRemapped())
Hal Finkel7529c552014-09-02 21:43:13 +0000291 continue;
Hal Finkel7529c552014-09-02 21:43:13 +0000292
293 StratifiedIndex Number = StratLinks.size();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000294 Remaps.insert(std::make_pair(Link.Number, Number));
Hal Finkel7529c552014-09-02 21:43:13 +0000295 StratLinks.push_back(Link.getLink());
296 }
297
298 for (auto &Link : StratLinks) {
299 if (Link.hasAbove()) {
300 auto &Above = linksAt(Link.Above);
301 auto Iter = Remaps.find(Above.Number);
302 assert(Iter != Remaps.end());
303 Link.Above = Iter->second;
304 }
305
306 if (Link.hasBelow()) {
307 auto &Below = linksAt(Link.Below);
308 auto Iter = Remaps.find(Below.Number);
309 assert(Iter != Remaps.end());
310 Link.Below = Iter->second;
311 }
312 }
313
314 for (auto &Pair : Values) {
315 auto &Info = Pair.second;
316 auto &Link = linksAt(Info.Index);
317 auto Iter = Remaps.find(Link.Number);
318 assert(Iter != Remaps.end());
319 Info.Index = Iter->second;
320 }
321 }
322
George Burgess IVcae581d2016-04-13 23:27:37 +0000323 /// \brief There's a guarantee in StratifiedLink where all bits set in a
324 /// Link.externals will be set in all Link.externals "below" it.
Hal Finkel7529c552014-09-02 21:43:13 +0000325 static void propagateAttrs(std::vector<StratifiedLink> &Links) {
326 const auto getHighestParentAbove = [&Links](StratifiedIndex Idx) {
327 const auto *Link = &Links[Idx];
328 while (Link->hasAbove()) {
329 Idx = Link->Above;
330 Link = &Links[Idx];
331 }
332 return Idx;
333 };
334
335 SmallSet<StratifiedIndex, 16> Visited;
336 for (unsigned I = 0, E = Links.size(); I < E; ++I) {
337 auto CurrentIndex = getHighestParentAbove(I);
George Burgess IVcae581d2016-04-13 23:27:37 +0000338 if (!Visited.insert(CurrentIndex).second)
Hal Finkel7529c552014-09-02 21:43:13 +0000339 continue;
Hal Finkel7529c552014-09-02 21:43:13 +0000340
341 while (Links[CurrentIndex].hasBelow()) {
342 auto &CurrentBits = Links[CurrentIndex].Attrs;
343 auto NextIndex = Links[CurrentIndex].Below;
344 auto &NextBits = Links[NextIndex].Attrs;
345 NextBits |= CurrentBits;
346 CurrentIndex = NextIndex;
347 }
348 }
349 }
350
351public:
George Burgess IVcae581d2016-04-13 23:27:37 +0000352 /// Builds a StratifiedSet from the information we've been given since either
353 /// construction or the prior build() call.
Hal Finkel7529c552014-09-02 21:43:13 +0000354 StratifiedSets<T> build() {
355 std::vector<StratifiedLink> StratLinks;
356 finalizeSets(StratLinks);
357 propagateAttrs(StratLinks);
358 Links.clear();
359 return StratifiedSets<T>(std::move(Values), std::move(StratLinks));
360 }
361
Hal Finkel7529c552014-09-02 21:43:13 +0000362 bool has(const T &Elem) const { return get(Elem).hasValue(); }
363
364 bool add(const T &Main) {
365 if (get(Main).hasValue())
366 return false;
367
368 auto NewIndex = getNewUnlinkedIndex();
369 return addAtMerging(Main, NewIndex);
370 }
371
George Burgess IVcae581d2016-04-13 23:27:37 +0000372 /// \brief Restructures the stratified sets as necessary to make "ToAdd" in a
373 /// set above "Main". There are some cases where this is not possible (see
374 /// above), so we merge them such that ToAdd and Main are in the same set.
Hal Finkel7529c552014-09-02 21:43:13 +0000375 bool addAbove(const T &Main, const T &ToAdd) {
376 assert(has(Main));
377 auto Index = *indexOf(Main);
378 if (!linksAt(Index).hasAbove())
379 addLinkAbove(Index);
380
381 auto Above = linksAt(Index).getAbove();
382 return addAtMerging(ToAdd, Above);
383 }
384
George Burgess IVcae581d2016-04-13 23:27:37 +0000385 /// \brief Restructures the stratified sets as necessary to make "ToAdd" in a
386 /// set below "Main". There are some cases where this is not possible (see
387 /// above), so we merge them such that ToAdd and Main are in the same set.
Hal Finkel7529c552014-09-02 21:43:13 +0000388 bool addBelow(const T &Main, const T &ToAdd) {
389 assert(has(Main));
390 auto Index = *indexOf(Main);
391 if (!linksAt(Index).hasBelow())
392 addLinkBelow(Index);
393
394 auto Below = linksAt(Index).getBelow();
395 return addAtMerging(ToAdd, Below);
396 }
397
George Burgess IVa3d62be2016-06-24 01:00:03 +0000398 /// \brief Set the StratifiedAttrs of the set "Level"-levels below "Main". If
399 /// there is no set below "Main", create one for it.
400 void addAttributesBelow(const T &Main, unsigned Level, StratifiedAttrs Attr) {
George Burgess IV652ec4f2016-06-09 23:15:04 +0000401 assert(has(Main));
402 auto Index = *indexOf(Main);
George Burgess IVa3d62be2016-06-24 01:00:03 +0000403 auto *Link = &linksAt(Index);
George Burgess IV652ec4f2016-06-09 23:15:04 +0000404
George Burgess IVa3d62be2016-06-24 01:00:03 +0000405 for (unsigned I = 0; I < Level; ++I) {
406 Index = Link->hasBelow() ? Link->getBelow() : addLinkBelow(Index);
407 Link = &linksAt(Index);
408 }
409 Link->setAttrs(Attr);
George Burgess IV652ec4f2016-06-09 23:15:04 +0000410 }
411
Hal Finkel7529c552014-09-02 21:43:13 +0000412 bool addWith(const T &Main, const T &ToAdd) {
413 assert(has(Main));
414 auto MainIndex = *indexOf(Main);
415 return addAtMerging(ToAdd, MainIndex);
416 }
417
George Burgess IV1f99da52016-06-23 18:55:23 +0000418 /// \brief Merge the set "MainBelow"-levels below "Main" and the set
419 /// "ToAddBelow"-levels below "ToAdd".
420 void addBelowWith(const T &Main, unsigned MainBelow, const T &ToAdd,
421 unsigned ToAddBelow) {
422 assert(has(Main));
423 assert(has(ToAdd));
424
George Burgess IVd14d05a2016-06-23 20:59:13 +0000425 auto GetIndexBelow = [&](StratifiedIndex Index, unsigned NumLevel) {
George Burgess IV1f99da52016-06-23 18:55:23 +0000426 for (unsigned I = 0; I < NumLevel; ++I) {
427 auto Link = linksAt(Index);
428 Index = Link.hasBelow() ? Link.getBelow() : addLinkBelow(Index);
429 }
430 return Index;
431 };
432 auto MainIndex = GetIndexBelow(*indexOf(Main), MainBelow);
433 auto ToAddIndex = GetIndexBelow(*indexOf(ToAdd), ToAddBelow);
434 if (&linksAt(MainIndex) != &linksAt(ToAddIndex))
435 merge(MainIndex, ToAddIndex);
436 }
437
Hal Finkel7529c552014-09-02 21:43:13 +0000438 void noteAttributes(const T &Main, const StratifiedAttrs &NewAttrs) {
439 assert(has(Main));
440 auto *Info = *get(Main);
441 auto &Link = linksAt(Info->Index);
442 Link.setAttrs(NewAttrs);
443 }
444
Hal Finkel7529c552014-09-02 21:43:13 +0000445private:
446 DenseMap<T, StratifiedInfo> Values;
447 std::vector<BuilderLink> Links;
448
George Burgess IVcae581d2016-04-13 23:27:37 +0000449 /// Adds the given element at the given index, merging sets if necessary.
Hal Finkel7529c552014-09-02 21:43:13 +0000450 bool addAtMerging(const T &ToAdd, StratifiedIndex Index) {
451 StratifiedInfo Info = {Index};
Hal Finkel8d1590d2014-09-02 22:52:30 +0000452 auto Pair = Values.insert(std::make_pair(ToAdd, Info));
Hal Finkel7529c552014-09-02 21:43:13 +0000453 if (Pair.second)
454 return true;
455
456 auto &Iter = Pair.first;
457 auto &IterSet = linksAt(Iter->second.Index);
458 auto &ReqSet = linksAt(Index);
459
460 // Failed to add where we wanted to. Merge the sets.
461 if (&IterSet != &ReqSet)
462 merge(IterSet.Number, ReqSet.Number);
463
464 return false;
465 }
466
George Burgess IVcae581d2016-04-13 23:27:37 +0000467 /// Gets the BuilderLink at the given index, taking set remapping into
468 /// account.
Hal Finkel7529c552014-09-02 21:43:13 +0000469 BuilderLink &linksAt(StratifiedIndex Index) {
470 auto *Start = &Links[Index];
471 if (!Start->isRemapped())
472 return *Start;
473
474 auto *Current = Start;
475 while (Current->isRemapped())
476 Current = &Links[Current->getRemapIndex()];
477
478 auto NewRemap = Current->Number;
479
480 // Run through everything that has yet to be updated, and update them to
481 // remap to NewRemap
482 Current = Start;
483 while (Current->isRemapped()) {
484 auto *Next = &Links[Current->getRemapIndex()];
485 Current->updateRemap(NewRemap);
486 Current = Next;
487 }
488
489 return *Current;
490 }
491
George Burgess IVcae581d2016-04-13 23:27:37 +0000492 /// \brief Merges two sets into one another. Assumes that these sets are not
493 /// already one in the same.
Hal Finkel7529c552014-09-02 21:43:13 +0000494 void merge(StratifiedIndex Idx1, StratifiedIndex Idx2) {
495 assert(inbounds(Idx1) && inbounds(Idx2));
496 assert(&linksAt(Idx1) != &linksAt(Idx2) &&
497 "Merging a set into itself is not allowed");
498
499 // CASE 1: If the set at `Idx1` is above or below `Idx2`, we need to merge
500 // both the
501 // given sets, and all sets between them, into one.
502 if (tryMergeUpwards(Idx1, Idx2))
503 return;
504
505 if (tryMergeUpwards(Idx2, Idx1))
506 return;
507
508 // CASE 2: The set at `Idx1` is not in the same chain as the set at `Idx2`.
509 // We therefore need to merge the two chains together.
510 mergeDirect(Idx1, Idx2);
511 }
512
George Burgess IVcae581d2016-04-13 23:27:37 +0000513 /// \brief Merges two sets assuming that the set at `Idx1` is unreachable from
514 /// traversing above or below the set at `Idx2`.
Hal Finkel7529c552014-09-02 21:43:13 +0000515 void mergeDirect(StratifiedIndex Idx1, StratifiedIndex Idx2) {
516 assert(inbounds(Idx1) && inbounds(Idx2));
517
518 auto *LinksInto = &linksAt(Idx1);
519 auto *LinksFrom = &linksAt(Idx2);
520 // Merging everything above LinksInto then proceeding to merge everything
521 // below LinksInto becomes problematic, so we go as far "up" as possible!
522 while (LinksInto->hasAbove() && LinksFrom->hasAbove()) {
523 LinksInto = &linksAt(LinksInto->getAbove());
524 LinksFrom = &linksAt(LinksFrom->getAbove());
525 }
526
527 if (LinksFrom->hasAbove()) {
528 LinksInto->setAbove(LinksFrom->getAbove());
529 auto &NewAbove = linksAt(LinksInto->getAbove());
530 NewAbove.setBelow(LinksInto->Number);
531 }
532
533 // Merging strategy:
534 // > If neither has links below, stop.
535 // > If only `LinksInto` has links below, stop.
536 // > If only `LinksFrom` has links below, reset `LinksInto.Below` to
537 // match `LinksFrom.Below`
538 // > If both have links above, deal with those next.
539 while (LinksInto->hasBelow() && LinksFrom->hasBelow()) {
540 auto &FromAttrs = LinksFrom->getAttrs();
541 LinksInto->setAttrs(FromAttrs);
542
543 // Remap needs to happen after getBelow(), but before
544 // assignment of LinksFrom
545 auto *NewLinksFrom = &linksAt(LinksFrom->getBelow());
546 LinksFrom->remapTo(LinksInto->Number);
547 LinksFrom = NewLinksFrom;
548 LinksInto = &linksAt(LinksInto->getBelow());
549 }
550
551 if (LinksFrom->hasBelow()) {
552 LinksInto->setBelow(LinksFrom->getBelow());
553 auto &NewBelow = linksAt(LinksInto->getBelow());
554 NewBelow.setAbove(LinksInto->Number);
555 }
556
557 LinksFrom->remapTo(LinksInto->Number);
558 }
559
George Burgess IVcae581d2016-04-13 23:27:37 +0000560 /// Checks to see if lowerIndex is at a level lower than upperIndex. If so, it
561 /// will merge lowerIndex with upperIndex (and all of the sets between) and
562 /// return true. Otherwise, it will return false.
Hal Finkel7529c552014-09-02 21:43:13 +0000563 bool tryMergeUpwards(StratifiedIndex LowerIndex, StratifiedIndex UpperIndex) {
564 assert(inbounds(LowerIndex) && inbounds(UpperIndex));
565 auto *Lower = &linksAt(LowerIndex);
566 auto *Upper = &linksAt(UpperIndex);
567 if (Lower == Upper)
568 return true;
569
570 SmallVector<BuilderLink *, 8> Found;
571 auto *Current = Lower;
572 auto Attrs = Current->getAttrs();
573 while (Current->hasAbove() && Current != Upper) {
574 Found.push_back(Current);
575 Attrs |= Current->getAttrs();
576 Current = &linksAt(Current->getAbove());
577 }
578
579 if (Current != Upper)
580 return false;
581
582 Upper->setAttrs(Attrs);
583
584 if (Lower->hasBelow()) {
585 auto NewBelowIndex = Lower->getBelow();
586 Upper->setBelow(NewBelowIndex);
587 auto &NewBelow = linksAt(NewBelowIndex);
588 NewBelow.setAbove(UpperIndex);
589 } else {
590 Upper->clearBelow();
591 }
592
593 for (const auto &Ptr : Found)
594 Ptr->remapTo(Upper->Number);
595
596 return true;
597 }
598
599 Optional<const StratifiedInfo *> get(const T &Val) const {
600 auto Result = Values.find(Val);
601 if (Result == Values.end())
George Burgess IVcae581d2016-04-13 23:27:37 +0000602 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000603 return &Result->second;
604 }
605
606 Optional<StratifiedInfo *> get(const T &Val) {
607 auto Result = Values.find(Val);
608 if (Result == Values.end())
George Burgess IVcae581d2016-04-13 23:27:37 +0000609 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000610 return &Result->second;
611 }
612
613 Optional<StratifiedIndex> indexOf(const T &Val) {
614 auto MaybeVal = get(Val);
615 if (!MaybeVal.hasValue())
George Burgess IVcae581d2016-04-13 23:27:37 +0000616 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000617 auto *Info = *MaybeVal;
618 auto &Link = linksAt(Info->Index);
619 return Link.Number;
620 }
621
622 StratifiedIndex addLinkBelow(StratifiedIndex Set) {
623 auto At = addLinks();
624 Links[Set].setBelow(At);
625 Links[At].setAbove(Set);
626 return At;
627 }
628
629 StratifiedIndex addLinkAbove(StratifiedIndex Set) {
630 auto At = addLinks();
631 Links[At].setBelow(Set);
632 Links[Set].setAbove(At);
633 return At;
634 }
635
636 StratifiedIndex getNewUnlinkedIndex() { return addLinks(); }
637
638 StratifiedIndex addLinks() {
639 auto Link = Links.size();
640 Links.push_back(BuilderLink(Link));
641 return Link;
642 }
643
Hal Finkel42b7e012014-09-02 22:36:58 +0000644 bool inbounds(StratifiedIndex N) const { return N < Links.size(); }
Hal Finkel7529c552014-09-02 21:43:13 +0000645};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000646}
George Burgess IVd14d05a2016-06-23 20:59:13 +0000647#endif // LLVM_ADT_STRATIFIEDSETS_H