blob: d86e18805e9e4008eec85bff1f6a388db6fed0e3 [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 IV652ec4f2016-06-09 23:15:04 +0000398 /// \brief Set the StratifiedAttrs of the set below "Main". If there is no set
399 /// below "Main", create one for it.
400 void addAttributesBelow(const T &Main, StratifiedAttrs Attr) {
401 assert(has(Main));
402 auto Index = *indexOf(Main);
403 auto Link = linksAt(Index);
404
405 auto BelowIndex = Link.hasBelow() ? Link.getBelow() : addLinkBelow(Index);
406 linksAt(BelowIndex).setAttrs(Attr);
407 }
408
Hal Finkel7529c552014-09-02 21:43:13 +0000409 bool addWith(const T &Main, const T &ToAdd) {
410 assert(has(Main));
411 auto MainIndex = *indexOf(Main);
412 return addAtMerging(ToAdd, MainIndex);
413 }
414
George Burgess IV1f99da52016-06-23 18:55:23 +0000415 /// \brief Merge the set "MainBelow"-levels below "Main" and the set
416 /// "ToAddBelow"-levels below "ToAdd".
417 void addBelowWith(const T &Main, unsigned MainBelow, const T &ToAdd,
418 unsigned ToAddBelow) {
419 assert(has(Main));
420 assert(has(ToAdd));
421
George Burgess IVd14d05a2016-06-23 20:59:13 +0000422 auto GetIndexBelow = [&](StratifiedIndex Index, unsigned NumLevel) {
George Burgess IV1f99da52016-06-23 18:55:23 +0000423 for (unsigned I = 0; I < NumLevel; ++I) {
424 auto Link = linksAt(Index);
425 Index = Link.hasBelow() ? Link.getBelow() : addLinkBelow(Index);
426 }
427 return Index;
428 };
429 auto MainIndex = GetIndexBelow(*indexOf(Main), MainBelow);
430 auto ToAddIndex = GetIndexBelow(*indexOf(ToAdd), ToAddBelow);
431 if (&linksAt(MainIndex) != &linksAt(ToAddIndex))
432 merge(MainIndex, ToAddIndex);
433 }
434
Hal Finkel7529c552014-09-02 21:43:13 +0000435 void noteAttributes(const T &Main, const StratifiedAttrs &NewAttrs) {
436 assert(has(Main));
437 auto *Info = *get(Main);
438 auto &Link = linksAt(Info->Index);
439 Link.setAttrs(NewAttrs);
440 }
441
Hal Finkel7529c552014-09-02 21:43:13 +0000442private:
443 DenseMap<T, StratifiedInfo> Values;
444 std::vector<BuilderLink> Links;
445
George Burgess IVcae581d2016-04-13 23:27:37 +0000446 /// Adds the given element at the given index, merging sets if necessary.
Hal Finkel7529c552014-09-02 21:43:13 +0000447 bool addAtMerging(const T &ToAdd, StratifiedIndex Index) {
448 StratifiedInfo Info = {Index};
Hal Finkel8d1590d2014-09-02 22:52:30 +0000449 auto Pair = Values.insert(std::make_pair(ToAdd, Info));
Hal Finkel7529c552014-09-02 21:43:13 +0000450 if (Pair.second)
451 return true;
452
453 auto &Iter = Pair.first;
454 auto &IterSet = linksAt(Iter->second.Index);
455 auto &ReqSet = linksAt(Index);
456
457 // Failed to add where we wanted to. Merge the sets.
458 if (&IterSet != &ReqSet)
459 merge(IterSet.Number, ReqSet.Number);
460
461 return false;
462 }
463
George Burgess IVcae581d2016-04-13 23:27:37 +0000464 /// Gets the BuilderLink at the given index, taking set remapping into
465 /// account.
Hal Finkel7529c552014-09-02 21:43:13 +0000466 BuilderLink &linksAt(StratifiedIndex Index) {
467 auto *Start = &Links[Index];
468 if (!Start->isRemapped())
469 return *Start;
470
471 auto *Current = Start;
472 while (Current->isRemapped())
473 Current = &Links[Current->getRemapIndex()];
474
475 auto NewRemap = Current->Number;
476
477 // Run through everything that has yet to be updated, and update them to
478 // remap to NewRemap
479 Current = Start;
480 while (Current->isRemapped()) {
481 auto *Next = &Links[Current->getRemapIndex()];
482 Current->updateRemap(NewRemap);
483 Current = Next;
484 }
485
486 return *Current;
487 }
488
George Burgess IVcae581d2016-04-13 23:27:37 +0000489 /// \brief Merges two sets into one another. Assumes that these sets are not
490 /// already one in the same.
Hal Finkel7529c552014-09-02 21:43:13 +0000491 void merge(StratifiedIndex Idx1, StratifiedIndex Idx2) {
492 assert(inbounds(Idx1) && inbounds(Idx2));
493 assert(&linksAt(Idx1) != &linksAt(Idx2) &&
494 "Merging a set into itself is not allowed");
495
496 // CASE 1: If the set at `Idx1` is above or below `Idx2`, we need to merge
497 // both the
498 // given sets, and all sets between them, into one.
499 if (tryMergeUpwards(Idx1, Idx2))
500 return;
501
502 if (tryMergeUpwards(Idx2, Idx1))
503 return;
504
505 // CASE 2: The set at `Idx1` is not in the same chain as the set at `Idx2`.
506 // We therefore need to merge the two chains together.
507 mergeDirect(Idx1, Idx2);
508 }
509
George Burgess IVcae581d2016-04-13 23:27:37 +0000510 /// \brief Merges two sets assuming that the set at `Idx1` is unreachable from
511 /// traversing above or below the set at `Idx2`.
Hal Finkel7529c552014-09-02 21:43:13 +0000512 void mergeDirect(StratifiedIndex Idx1, StratifiedIndex Idx2) {
513 assert(inbounds(Idx1) && inbounds(Idx2));
514
515 auto *LinksInto = &linksAt(Idx1);
516 auto *LinksFrom = &linksAt(Idx2);
517 // Merging everything above LinksInto then proceeding to merge everything
518 // below LinksInto becomes problematic, so we go as far "up" as possible!
519 while (LinksInto->hasAbove() && LinksFrom->hasAbove()) {
520 LinksInto = &linksAt(LinksInto->getAbove());
521 LinksFrom = &linksAt(LinksFrom->getAbove());
522 }
523
524 if (LinksFrom->hasAbove()) {
525 LinksInto->setAbove(LinksFrom->getAbove());
526 auto &NewAbove = linksAt(LinksInto->getAbove());
527 NewAbove.setBelow(LinksInto->Number);
528 }
529
530 // Merging strategy:
531 // > If neither has links below, stop.
532 // > If only `LinksInto` has links below, stop.
533 // > If only `LinksFrom` has links below, reset `LinksInto.Below` to
534 // match `LinksFrom.Below`
535 // > If both have links above, deal with those next.
536 while (LinksInto->hasBelow() && LinksFrom->hasBelow()) {
537 auto &FromAttrs = LinksFrom->getAttrs();
538 LinksInto->setAttrs(FromAttrs);
539
540 // Remap needs to happen after getBelow(), but before
541 // assignment of LinksFrom
542 auto *NewLinksFrom = &linksAt(LinksFrom->getBelow());
543 LinksFrom->remapTo(LinksInto->Number);
544 LinksFrom = NewLinksFrom;
545 LinksInto = &linksAt(LinksInto->getBelow());
546 }
547
548 if (LinksFrom->hasBelow()) {
549 LinksInto->setBelow(LinksFrom->getBelow());
550 auto &NewBelow = linksAt(LinksInto->getBelow());
551 NewBelow.setAbove(LinksInto->Number);
552 }
553
554 LinksFrom->remapTo(LinksInto->Number);
555 }
556
George Burgess IVcae581d2016-04-13 23:27:37 +0000557 /// Checks to see if lowerIndex is at a level lower than upperIndex. If so, it
558 /// will merge lowerIndex with upperIndex (and all of the sets between) and
559 /// return true. Otherwise, it will return false.
Hal Finkel7529c552014-09-02 21:43:13 +0000560 bool tryMergeUpwards(StratifiedIndex LowerIndex, StratifiedIndex UpperIndex) {
561 assert(inbounds(LowerIndex) && inbounds(UpperIndex));
562 auto *Lower = &linksAt(LowerIndex);
563 auto *Upper = &linksAt(UpperIndex);
564 if (Lower == Upper)
565 return true;
566
567 SmallVector<BuilderLink *, 8> Found;
568 auto *Current = Lower;
569 auto Attrs = Current->getAttrs();
570 while (Current->hasAbove() && Current != Upper) {
571 Found.push_back(Current);
572 Attrs |= Current->getAttrs();
573 Current = &linksAt(Current->getAbove());
574 }
575
576 if (Current != Upper)
577 return false;
578
579 Upper->setAttrs(Attrs);
580
581 if (Lower->hasBelow()) {
582 auto NewBelowIndex = Lower->getBelow();
583 Upper->setBelow(NewBelowIndex);
584 auto &NewBelow = linksAt(NewBelowIndex);
585 NewBelow.setAbove(UpperIndex);
586 } else {
587 Upper->clearBelow();
588 }
589
590 for (const auto &Ptr : Found)
591 Ptr->remapTo(Upper->Number);
592
593 return true;
594 }
595
596 Optional<const StratifiedInfo *> get(const T &Val) const {
597 auto Result = Values.find(Val);
598 if (Result == Values.end())
George Burgess IVcae581d2016-04-13 23:27:37 +0000599 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000600 return &Result->second;
601 }
602
603 Optional<StratifiedInfo *> get(const T &Val) {
604 auto Result = Values.find(Val);
605 if (Result == Values.end())
George Burgess IVcae581d2016-04-13 23:27:37 +0000606 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000607 return &Result->second;
608 }
609
610 Optional<StratifiedIndex> indexOf(const T &Val) {
611 auto MaybeVal = get(Val);
612 if (!MaybeVal.hasValue())
George Burgess IVcae581d2016-04-13 23:27:37 +0000613 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000614 auto *Info = *MaybeVal;
615 auto &Link = linksAt(Info->Index);
616 return Link.Number;
617 }
618
619 StratifiedIndex addLinkBelow(StratifiedIndex Set) {
620 auto At = addLinks();
621 Links[Set].setBelow(At);
622 Links[At].setAbove(Set);
623 return At;
624 }
625
626 StratifiedIndex addLinkAbove(StratifiedIndex Set) {
627 auto At = addLinks();
628 Links[At].setBelow(Set);
629 Links[Set].setAbove(At);
630 return At;
631 }
632
633 StratifiedIndex getNewUnlinkedIndex() { return addLinks(); }
634
635 StratifiedIndex addLinks() {
636 auto Link = Links.size();
637 Links.push_back(BuilderLink(Link));
638 return Link;
639 }
640
Hal Finkel42b7e012014-09-02 22:36:58 +0000641 bool inbounds(StratifiedIndex N) const { return N < Links.size(); }
Hal Finkel7529c552014-09-02 21:43:13 +0000642};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000643}
George Burgess IVd14d05a2016-06-23 20:59:13 +0000644#endif // LLVM_ADT_STRATIFIEDSETS_H