blob: 54af04d0ca0b84a9c22e1625c640299d19f3f4b1 [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"
15#include "llvm/ADT/SmallPtrSet.h"
16#include "llvm/ADT/SmallSet.h"
17#include "llvm/ADT/SmallVector.h"
Hal Finkel7d7087c2014-09-02 22:13:00 +000018#include "llvm/Support/Compiler.h"
Hal Finkel7529c552014-09-02 21:43:13 +000019#include <bitset>
20#include <cassert>
21#include <cmath>
22#include <limits>
23#include <type_traits>
Hal Finkel8d1590d2014-09-02 22:52:30 +000024#include <utility>
Hal Finkel7529c552014-09-02 21:43:13 +000025#include <vector>
26
27namespace llvm {
George Burgess IVcae581d2016-04-13 23:27:37 +000028/// An index into Stratified Sets.
Hal Finkel7529c552014-09-02 21:43:13 +000029typedef unsigned StratifiedIndex;
George Burgess IVcae581d2016-04-13 23:27:37 +000030/// NOTE: ^ This can't be a short -- bootstrapping clang has a case where
31/// ~1M sets exist.
Hal Finkel7529c552014-09-02 21:43:13 +000032
33// \brief Container of information related to a value in a StratifiedSet.
34struct StratifiedInfo {
35 StratifiedIndex Index;
George Burgess IVcae581d2016-04-13 23:27:37 +000036 /// For field sensitivity, etc. we can tack fields on here.
Hal Finkel7529c552014-09-02 21:43:13 +000037};
38
George Burgess IVcae581d2016-04-13 23:27:37 +000039/// The number of attributes that StratifiedAttrs should contain. Attributes are
40/// described below, and 32 was an arbitrary choice because it fits nicely in 32
41/// bits (because we use a bitset for StratifiedAttrs).
Hal Finkel981602a2014-09-02 22:26:06 +000042static const unsigned NumStratifiedAttrs = 32;
Hal Finkel7529c552014-09-02 21:43:13 +000043
George Burgess IVcae581d2016-04-13 23:27:37 +000044/// These are attributes that the users of StratifiedSets/StratifiedSetBuilders
45/// may use for various purposes. These also have the special property of that
46/// they are merged down. So, if set A is above set B, and one decides to set an
47/// attribute in set A, then the attribute will automatically be set in set B.
Hal Finkel7529c552014-09-02 21:43:13 +000048typedef std::bitset<NumStratifiedAttrs> StratifiedAttrs;
49
George Burgess IVcae581d2016-04-13 23:27:37 +000050/// A "link" between two StratifiedSets.
Hal Finkel7529c552014-09-02 21:43:13 +000051struct StratifiedLink {
George Burgess IVcae581d2016-04-13 23:27:37 +000052 /// \brief This is a value used to signify "does not exist" where the
53 /// StratifiedIndex type is used.
54 ///
55 /// This is used instead of Optional<StratifiedIndex> because
56 /// Optional<StratifiedIndex> would eat up a considerable amount of extra
57 /// memory, after struct padding/alignment is taken into account.
Hal Finkel1ae325f2014-09-02 23:50:01 +000058 static const StratifiedIndex SetSentinel;
Hal Finkel7529c552014-09-02 21:43:13 +000059
George Burgess IVcae581d2016-04-13 23:27:37 +000060 /// The index for the set "above" current
Hal Finkel7529c552014-09-02 21:43:13 +000061 StratifiedIndex Above;
62
George Burgess IVcae581d2016-04-13 23:27:37 +000063 /// The link for the set "below" current
Hal Finkel7529c552014-09-02 21:43:13 +000064 StratifiedIndex Below;
65
George Burgess IVcae581d2016-04-13 23:27:37 +000066 /// Attributes for these StratifiedSets.
Hal Finkel7529c552014-09-02 21:43:13 +000067 StratifiedAttrs Attrs;
68
69 StratifiedLink() : Above(SetSentinel), Below(SetSentinel) {}
70
71 bool hasBelow() const { return Below != SetSentinel; }
72 bool hasAbove() const { return Above != SetSentinel; }
73
74 void clearBelow() { Below = SetSentinel; }
75 void clearAbove() { Above = SetSentinel; }
76};
77
George Burgess IVcae581d2016-04-13 23:27:37 +000078/// \brief These are stratified sets, as described in "Fast algorithms for
79/// Dyck-CFL-reachability with applications to Alias Analysis" by Zhang Q, Lyu M
80/// R, Yuan H, and Su Z. -- in short, this is meant to represent different sets
81/// of Value*s. If two Value*s are in the same set, or if both sets have
82/// overlapping attributes, then the Value*s are said to alias.
83///
84/// Sets may be related by position, meaning that one set may be considered as
85/// above or below another. In CFL Alias Analysis, this gives us an indication
86/// of how two variables are related; if the set of variable A is below a set
87/// containing variable B, then at some point, a variable that has interacted
88/// with B (or B itself) was either used in order to extract the variable A, or
89/// was used as storage of variable A.
90///
91/// Sets may also have attributes (as noted above). These attributes are
92/// generally used for noting whether a variable in the set has interacted with
93/// a variable whose origins we don't quite know (i.e. globals/arguments), or if
94/// the variable may have had operations performed on it (modified in a function
95/// call). All attributes that exist in a set A must exist in all sets marked as
96/// below set A.
Hal Finkel7529c552014-09-02 21:43:13 +000097template <typename T> class StratifiedSets {
98public:
99 StratifiedSets() {}
100
101 StratifiedSets(DenseMap<T, StratifiedInfo> Map,
102 std::vector<StratifiedLink> Links)
103 : Values(std::move(Map)), Links(std::move(Links)) {}
104
105 StratifiedSets(StratifiedSets<T> &&Other) { *this = std::move(Other); }
106
107 StratifiedSets &operator=(StratifiedSets<T> &&Other) {
108 Values = std::move(Other.Values);
109 Links = std::move(Other.Links);
110 return *this;
111 }
112
113 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
156/// %aw = getelementptr %ap, 0
157///
158/// Given this, the follow relations exist:
159/// - %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///
166/// ...Which states that the only MayAlias relationship in the above program is
167/// between %ap and %aw.
168///
169/// Life gets more complicated when we actually have logic in our programs. So,
170/// we either must remove this logic from our programs, or make consessions for
171/// it in our AA algorithms. In this case, we have decided to select the latter
172/// option.
173///
174/// First complication: Conditionals
175/// Motivation:
176/// %ad = alloca int, align 4
177/// %a = alloca int*, align 8
178/// %b = alloca int*, align 8
179/// %bp = alloca int**, align 8
180/// %c = call i1 @SomeFunc()
181/// %k = select %c, %ad, %bp
182/// store %ad, %a
183/// store %b, %bp
184///
185/// %k has 'with' edges to both %a and %b, which ordinarily would not be linked
186/// together. So, we merge the set that contains %a with the set that contains
187/// %b. We then recursively merge the set above %a with the set above %b, and
188/// the set below %a with the set below %b, etc. Ultimately, the sets for this
Hal Finkel7529c552014-09-02 21:43:13 +0000189// program would end up like: {%ad}, {%a, %b, %k}, {%bp}, where {%ad} is below
George Burgess IVcae581d2016-04-13 23:27:37 +0000190/// {%a, %b, %c} is below {%ad}.
191///
192/// Second complication: Arbitrary casts
193/// Motivation:
194/// %ip = alloca int*, align 8
195/// %ipp = alloca int**, align 8
196/// %i = bitcast ipp to int
197/// store %ip, %ipp
198/// store %i, %ip
199///
200/// This is impossible to construct with any of the rules above, because a set
201/// containing both {%i, %ipp} is supposed to exist, the set with %i is supposed
202/// to be below the set with %ip, and the set with %ip is supposed to be below
203/// the set with %ipp. Because we don't allow circular relationships like this,
204/// we merge all concerned sets into one. So, the above code would generate a
205/// single StratifiedSet: {%ip, %ipp, %i}.
206///
207/// ==== Set remaps ====
208/// More of an implementation detail than anything -- when merging sets, we need
209/// to update the numbers of all of the elements mapped to those sets. Rather
210/// than doing this at each merge, we note in the BuilderLink structure that a
211/// remap has occurred, and use this information so we can defer renumbering set
212/// elements until build time.
Hal Finkel7529c552014-09-02 21:43:13 +0000213template <typename T> class StratifiedSetsBuilder {
George Burgess IVcae581d2016-04-13 23:27:37 +0000214 /// \brief Represents a Stratified Set, with information about the Stratified
215 /// Set above it, the set below it, and whether the current set has been
216 /// remapped to another.
Hal Finkel7529c552014-09-02 21:43:13 +0000217 struct BuilderLink {
218 const StratifiedIndex Number;
219
220 BuilderLink(StratifiedIndex N) : Number(N) {
221 Remap = StratifiedLink::SetSentinel;
222 }
223
224 bool hasAbove() const {
225 assert(!isRemapped());
226 return Link.hasAbove();
227 }
228
229 bool hasBelow() const {
230 assert(!isRemapped());
231 return Link.hasBelow();
232 }
233
234 void setBelow(StratifiedIndex I) {
235 assert(!isRemapped());
236 Link.Below = I;
237 }
238
239 void setAbove(StratifiedIndex I) {
240 assert(!isRemapped());
241 Link.Above = I;
242 }
243
244 void clearBelow() {
245 assert(!isRemapped());
246 Link.clearBelow();
247 }
248
249 void clearAbove() {
250 assert(!isRemapped());
251 Link.clearAbove();
252 }
253
254 StratifiedIndex getBelow() const {
255 assert(!isRemapped());
256 assert(hasBelow());
257 return Link.Below;
258 }
259
260 StratifiedIndex getAbove() const {
261 assert(!isRemapped());
262 assert(hasAbove());
263 return Link.Above;
264 }
265
266 StratifiedAttrs &getAttrs() {
267 assert(!isRemapped());
268 return Link.Attrs;
269 }
270
271 void setAttr(unsigned index) {
272 assert(!isRemapped());
273 assert(index < NumStratifiedAttrs);
274 Link.Attrs.set(index);
275 }
276
277 void setAttrs(const StratifiedAttrs &other) {
278 assert(!isRemapped());
279 Link.Attrs |= other;
280 }
281
282 bool isRemapped() const { return Remap != StratifiedLink::SetSentinel; }
283
George Burgess IVcae581d2016-04-13 23:27:37 +0000284 /// For initial remapping to another set
Hal Finkel7529c552014-09-02 21:43:13 +0000285 void remapTo(StratifiedIndex Other) {
286 assert(!isRemapped());
287 Remap = Other;
288 }
289
290 StratifiedIndex getRemapIndex() const {
291 assert(isRemapped());
292 return Remap;
293 }
294
George Burgess IVcae581d2016-04-13 23:27:37 +0000295 /// Should only be called when we're already remapped.
Hal Finkel7529c552014-09-02 21:43:13 +0000296 void updateRemap(StratifiedIndex Other) {
297 assert(isRemapped());
298 Remap = Other;
299 }
300
George Burgess IVcae581d2016-04-13 23:27:37 +0000301 /// Prefer the above functions to calling things directly on what's returned
302 /// from this -- they guard against unexpected calls when the current
303 /// BuilderLink is remapped.
Hal Finkel7529c552014-09-02 21:43:13 +0000304 const StratifiedLink &getLink() const { return Link; }
305
306 private:
307 StratifiedLink Link;
308 StratifiedIndex Remap;
309 };
310
George Burgess IVcae581d2016-04-13 23:27:37 +0000311 /// \brief This function performs all of the set unioning/value renumbering
312 /// that we've been putting off, and generates a vector<StratifiedLink> that
313 /// may be placed in a StratifiedSets instance.
Hal Finkel7529c552014-09-02 21:43:13 +0000314 void finalizeSets(std::vector<StratifiedLink> &StratLinks) {
315 DenseMap<StratifiedIndex, StratifiedIndex> Remaps;
316 for (auto &Link : Links) {
George Burgess IVcae581d2016-04-13 23:27:37 +0000317 if (Link.isRemapped())
Hal Finkel7529c552014-09-02 21:43:13 +0000318 continue;
Hal Finkel7529c552014-09-02 21:43:13 +0000319
320 StratifiedIndex Number = StratLinks.size();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000321 Remaps.insert(std::make_pair(Link.Number, Number));
Hal Finkel7529c552014-09-02 21:43:13 +0000322 StratLinks.push_back(Link.getLink());
323 }
324
325 for (auto &Link : StratLinks) {
326 if (Link.hasAbove()) {
327 auto &Above = linksAt(Link.Above);
328 auto Iter = Remaps.find(Above.Number);
329 assert(Iter != Remaps.end());
330 Link.Above = Iter->second;
331 }
332
333 if (Link.hasBelow()) {
334 auto &Below = linksAt(Link.Below);
335 auto Iter = Remaps.find(Below.Number);
336 assert(Iter != Remaps.end());
337 Link.Below = Iter->second;
338 }
339 }
340
341 for (auto &Pair : Values) {
342 auto &Info = Pair.second;
343 auto &Link = linksAt(Info.Index);
344 auto Iter = Remaps.find(Link.Number);
345 assert(Iter != Remaps.end());
346 Info.Index = Iter->second;
347 }
348 }
349
George Burgess IVcae581d2016-04-13 23:27:37 +0000350 /// \brief There's a guarantee in StratifiedLink where all bits set in a
351 /// Link.externals will be set in all Link.externals "below" it.
Hal Finkel7529c552014-09-02 21:43:13 +0000352 static void propagateAttrs(std::vector<StratifiedLink> &Links) {
353 const auto getHighestParentAbove = [&Links](StratifiedIndex Idx) {
354 const auto *Link = &Links[Idx];
355 while (Link->hasAbove()) {
356 Idx = Link->Above;
357 Link = &Links[Idx];
358 }
359 return Idx;
360 };
361
362 SmallSet<StratifiedIndex, 16> Visited;
363 for (unsigned I = 0, E = Links.size(); I < E; ++I) {
364 auto CurrentIndex = getHighestParentAbove(I);
George Burgess IVcae581d2016-04-13 23:27:37 +0000365 if (!Visited.insert(CurrentIndex).second)
Hal Finkel7529c552014-09-02 21:43:13 +0000366 continue;
Hal Finkel7529c552014-09-02 21:43:13 +0000367
368 while (Links[CurrentIndex].hasBelow()) {
369 auto &CurrentBits = Links[CurrentIndex].Attrs;
370 auto NextIndex = Links[CurrentIndex].Below;
371 auto &NextBits = Links[NextIndex].Attrs;
372 NextBits |= CurrentBits;
373 CurrentIndex = NextIndex;
374 }
375 }
376 }
377
378public:
George Burgess IVcae581d2016-04-13 23:27:37 +0000379 /// Builds a StratifiedSet from the information we've been given since either
380 /// construction or the prior build() call.
Hal Finkel7529c552014-09-02 21:43:13 +0000381 StratifiedSets<T> build() {
382 std::vector<StratifiedLink> StratLinks;
383 finalizeSets(StratLinks);
384 propagateAttrs(StratLinks);
385 Links.clear();
386 return StratifiedSets<T>(std::move(Values), std::move(StratLinks));
387 }
388
389 std::size_t size() const { return Values.size(); }
390 std::size_t numSets() const { return Links.size(); }
391
392 bool has(const T &Elem) const { return get(Elem).hasValue(); }
393
394 bool add(const T &Main) {
395 if (get(Main).hasValue())
396 return false;
397
398 auto NewIndex = getNewUnlinkedIndex();
399 return addAtMerging(Main, NewIndex);
400 }
401
George Burgess IVcae581d2016-04-13 23:27:37 +0000402 /// \brief Restructures the stratified sets as necessary to make "ToAdd" in a
403 /// set above "Main". There are some cases where this is not possible (see
404 /// above), so we merge them such that ToAdd and Main are in the same set.
Hal Finkel7529c552014-09-02 21:43:13 +0000405 bool addAbove(const T &Main, const T &ToAdd) {
406 assert(has(Main));
407 auto Index = *indexOf(Main);
408 if (!linksAt(Index).hasAbove())
409 addLinkAbove(Index);
410
411 auto Above = linksAt(Index).getAbove();
412 return addAtMerging(ToAdd, Above);
413 }
414
George Burgess IVcae581d2016-04-13 23:27:37 +0000415 /// \brief Restructures the stratified sets as necessary to make "ToAdd" in a
416 /// set below "Main". There are some cases where this is not possible (see
417 /// above), so we merge them such that ToAdd and Main are in the same set.
Hal Finkel7529c552014-09-02 21:43:13 +0000418 bool addBelow(const T &Main, const T &ToAdd) {
419 assert(has(Main));
420 auto Index = *indexOf(Main);
421 if (!linksAt(Index).hasBelow())
422 addLinkBelow(Index);
423
424 auto Below = linksAt(Index).getBelow();
425 return addAtMerging(ToAdd, Below);
426 }
427
428 bool addWith(const T &Main, const T &ToAdd) {
429 assert(has(Main));
430 auto MainIndex = *indexOf(Main);
431 return addAtMerging(ToAdd, MainIndex);
432 }
433
434 void noteAttribute(const T &Main, unsigned AttrNum) {
435 assert(has(Main));
436 assert(AttrNum < StratifiedLink::SetSentinel);
437 auto *Info = *get(Main);
438 auto &Link = linksAt(Info->Index);
439 Link.setAttr(AttrNum);
440 }
441
442 void noteAttributes(const T &Main, const StratifiedAttrs &NewAttrs) {
443 assert(has(Main));
444 auto *Info = *get(Main);
445 auto &Link = linksAt(Info->Index);
446 Link.setAttrs(NewAttrs);
447 }
448
449 StratifiedAttrs getAttributes(const T &Main) {
450 assert(has(Main));
451 auto *Info = *get(Main);
452 auto *Link = &linksAt(Info->Index);
453 auto Attrs = Link->getAttrs();
454 while (Link->hasAbove()) {
455 Link = &linksAt(Link->getAbove());
456 Attrs |= Link->getAttrs();
457 }
458
459 return Attrs;
460 }
461
462 bool getAttribute(const T &Main, unsigned AttrNum) {
463 assert(AttrNum < StratifiedLink::SetSentinel);
464 auto Attrs = getAttributes(Main);
465 return Attrs[AttrNum];
466 }
467
George Burgess IVcae581d2016-04-13 23:27:37 +0000468 /// \brief Gets the attributes that have been applied to the set that Main
469 /// belongs to. It ignores attributes in any sets above the one that Main
470 /// resides in.
Hal Finkel7529c552014-09-02 21:43:13 +0000471 StratifiedAttrs getRawAttributes(const T &Main) {
472 assert(has(Main));
473 auto *Info = *get(Main);
474 auto &Link = linksAt(Info->Index);
475 return Link.getAttrs();
476 }
477
George Burgess IVcae581d2016-04-13 23:27:37 +0000478 /// \brief Gets an attribute from the attributes that have been applied to the
479 /// set that Main belongs to. It ignores attributes in any sets above the one
480 /// that Main resides in.
Hal Finkel7529c552014-09-02 21:43:13 +0000481 bool getRawAttribute(const T &Main, unsigned AttrNum) {
482 assert(AttrNum < StratifiedLink::SetSentinel);
483 auto Attrs = getRawAttributes(Main);
484 return Attrs[AttrNum];
485 }
486
487private:
488 DenseMap<T, StratifiedInfo> Values;
489 std::vector<BuilderLink> Links;
490
George Burgess IVcae581d2016-04-13 23:27:37 +0000491 /// Adds the given element at the given index, merging sets if necessary.
Hal Finkel7529c552014-09-02 21:43:13 +0000492 bool addAtMerging(const T &ToAdd, StratifiedIndex Index) {
493 StratifiedInfo Info = {Index};
Hal Finkel8d1590d2014-09-02 22:52:30 +0000494 auto Pair = Values.insert(std::make_pair(ToAdd, Info));
Hal Finkel7529c552014-09-02 21:43:13 +0000495 if (Pair.second)
496 return true;
497
498 auto &Iter = Pair.first;
499 auto &IterSet = linksAt(Iter->second.Index);
500 auto &ReqSet = linksAt(Index);
501
502 // Failed to add where we wanted to. Merge the sets.
503 if (&IterSet != &ReqSet)
504 merge(IterSet.Number, ReqSet.Number);
505
506 return false;
507 }
508
George Burgess IVcae581d2016-04-13 23:27:37 +0000509 /// Gets the BuilderLink at the given index, taking set remapping into
510 /// account.
Hal Finkel7529c552014-09-02 21:43:13 +0000511 BuilderLink &linksAt(StratifiedIndex Index) {
512 auto *Start = &Links[Index];
513 if (!Start->isRemapped())
514 return *Start;
515
516 auto *Current = Start;
517 while (Current->isRemapped())
518 Current = &Links[Current->getRemapIndex()];
519
520 auto NewRemap = Current->Number;
521
522 // Run through everything that has yet to be updated, and update them to
523 // remap to NewRemap
524 Current = Start;
525 while (Current->isRemapped()) {
526 auto *Next = &Links[Current->getRemapIndex()];
527 Current->updateRemap(NewRemap);
528 Current = Next;
529 }
530
531 return *Current;
532 }
533
George Burgess IVcae581d2016-04-13 23:27:37 +0000534 /// \brief Merges two sets into one another. Assumes that these sets are not
535 /// already one in the same.
Hal Finkel7529c552014-09-02 21:43:13 +0000536 void merge(StratifiedIndex Idx1, StratifiedIndex Idx2) {
537 assert(inbounds(Idx1) && inbounds(Idx2));
538 assert(&linksAt(Idx1) != &linksAt(Idx2) &&
539 "Merging a set into itself is not allowed");
540
541 // CASE 1: If the set at `Idx1` is above or below `Idx2`, we need to merge
542 // both the
543 // given sets, and all sets between them, into one.
544 if (tryMergeUpwards(Idx1, Idx2))
545 return;
546
547 if (tryMergeUpwards(Idx2, Idx1))
548 return;
549
550 // CASE 2: The set at `Idx1` is not in the same chain as the set at `Idx2`.
551 // We therefore need to merge the two chains together.
552 mergeDirect(Idx1, Idx2);
553 }
554
George Burgess IVcae581d2016-04-13 23:27:37 +0000555 /// \brief Merges two sets assuming that the set at `Idx1` is unreachable from
556 /// traversing above or below the set at `Idx2`.
Hal Finkel7529c552014-09-02 21:43:13 +0000557 void mergeDirect(StratifiedIndex Idx1, StratifiedIndex Idx2) {
558 assert(inbounds(Idx1) && inbounds(Idx2));
559
560 auto *LinksInto = &linksAt(Idx1);
561 auto *LinksFrom = &linksAt(Idx2);
562 // Merging everything above LinksInto then proceeding to merge everything
563 // below LinksInto becomes problematic, so we go as far "up" as possible!
564 while (LinksInto->hasAbove() && LinksFrom->hasAbove()) {
565 LinksInto = &linksAt(LinksInto->getAbove());
566 LinksFrom = &linksAt(LinksFrom->getAbove());
567 }
568
569 if (LinksFrom->hasAbove()) {
570 LinksInto->setAbove(LinksFrom->getAbove());
571 auto &NewAbove = linksAt(LinksInto->getAbove());
572 NewAbove.setBelow(LinksInto->Number);
573 }
574
575 // Merging strategy:
576 // > If neither has links below, stop.
577 // > If only `LinksInto` has links below, stop.
578 // > If only `LinksFrom` has links below, reset `LinksInto.Below` to
579 // match `LinksFrom.Below`
580 // > If both have links above, deal with those next.
581 while (LinksInto->hasBelow() && LinksFrom->hasBelow()) {
582 auto &FromAttrs = LinksFrom->getAttrs();
583 LinksInto->setAttrs(FromAttrs);
584
585 // Remap needs to happen after getBelow(), but before
586 // assignment of LinksFrom
587 auto *NewLinksFrom = &linksAt(LinksFrom->getBelow());
588 LinksFrom->remapTo(LinksInto->Number);
589 LinksFrom = NewLinksFrom;
590 LinksInto = &linksAt(LinksInto->getBelow());
591 }
592
593 if (LinksFrom->hasBelow()) {
594 LinksInto->setBelow(LinksFrom->getBelow());
595 auto &NewBelow = linksAt(LinksInto->getBelow());
596 NewBelow.setAbove(LinksInto->Number);
597 }
598
599 LinksFrom->remapTo(LinksInto->Number);
600 }
601
George Burgess IVcae581d2016-04-13 23:27:37 +0000602 /// Checks to see if lowerIndex is at a level lower than upperIndex. If so, it
603 /// will merge lowerIndex with upperIndex (and all of the sets between) and
604 /// return true. Otherwise, it will return false.
Hal Finkel7529c552014-09-02 21:43:13 +0000605 bool tryMergeUpwards(StratifiedIndex LowerIndex, StratifiedIndex UpperIndex) {
606 assert(inbounds(LowerIndex) && inbounds(UpperIndex));
607 auto *Lower = &linksAt(LowerIndex);
608 auto *Upper = &linksAt(UpperIndex);
609 if (Lower == Upper)
610 return true;
611
612 SmallVector<BuilderLink *, 8> Found;
613 auto *Current = Lower;
614 auto Attrs = Current->getAttrs();
615 while (Current->hasAbove() && Current != Upper) {
616 Found.push_back(Current);
617 Attrs |= Current->getAttrs();
618 Current = &linksAt(Current->getAbove());
619 }
620
621 if (Current != Upper)
622 return false;
623
624 Upper->setAttrs(Attrs);
625
626 if (Lower->hasBelow()) {
627 auto NewBelowIndex = Lower->getBelow();
628 Upper->setBelow(NewBelowIndex);
629 auto &NewBelow = linksAt(NewBelowIndex);
630 NewBelow.setAbove(UpperIndex);
631 } else {
632 Upper->clearBelow();
633 }
634
635 for (const auto &Ptr : Found)
636 Ptr->remapTo(Upper->Number);
637
638 return true;
639 }
640
641 Optional<const StratifiedInfo *> get(const T &Val) const {
642 auto Result = Values.find(Val);
643 if (Result == Values.end())
George Burgess IVcae581d2016-04-13 23:27:37 +0000644 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000645 return &Result->second;
646 }
647
648 Optional<StratifiedInfo *> get(const T &Val) {
649 auto Result = Values.find(Val);
650 if (Result == Values.end())
George Burgess IVcae581d2016-04-13 23:27:37 +0000651 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000652 return &Result->second;
653 }
654
655 Optional<StratifiedIndex> indexOf(const T &Val) {
656 auto MaybeVal = get(Val);
657 if (!MaybeVal.hasValue())
George Burgess IVcae581d2016-04-13 23:27:37 +0000658 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000659 auto *Info = *MaybeVal;
660 auto &Link = linksAt(Info->Index);
661 return Link.Number;
662 }
663
664 StratifiedIndex addLinkBelow(StratifiedIndex Set) {
665 auto At = addLinks();
666 Links[Set].setBelow(At);
667 Links[At].setAbove(Set);
668 return At;
669 }
670
671 StratifiedIndex addLinkAbove(StratifiedIndex Set) {
672 auto At = addLinks();
673 Links[At].setBelow(Set);
674 Links[Set].setAbove(At);
675 return At;
676 }
677
678 StratifiedIndex getNewUnlinkedIndex() { return addLinks(); }
679
680 StratifiedIndex addLinks() {
681 auto Link = Links.size();
682 Links.push_back(BuilderLink(Link));
683 return Link;
684 }
685
Hal Finkel42b7e012014-09-02 22:36:58 +0000686 bool inbounds(StratifiedIndex N) const { return N < Links.size(); }
Hal Finkel7529c552014-09-02 21:43:13 +0000687};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000688}
Hal Finkel7529c552014-09-02 21:43:13 +0000689#endif // LLVM_ADT_STRATIFIEDSETS_H