Andrew Scull | 5e1ddfa | 2018-08-14 10:06:54 +0100 | [diff] [blame] | 1 | //===- llvm/ADT/IntervalMap.h - A sorted interval map -----------*- C++ -*-===// |
| 2 | // |
Andrew Walbran | 16937d0 | 2019-10-22 13:54:20 +0100 | [diff] [blame] | 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
Andrew Scull | 5e1ddfa | 2018-08-14 10:06:54 +0100 | [diff] [blame] | 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // This file implements a coalescing interval map for small objects. |
| 10 | // |
| 11 | // KeyT objects are mapped to ValT objects. Intervals of keys that map to the |
| 12 | // same value are represented in a compressed form. |
| 13 | // |
| 14 | // Iterators provide ordered access to the compressed intervals rather than the |
| 15 | // individual keys, and insert and erase operations use key intervals as well. |
| 16 | // |
| 17 | // Like SmallVector, IntervalMap will store the first N intervals in the map |
| 18 | // object itself without any allocations. When space is exhausted it switches to |
| 19 | // a B+-tree representation with very small overhead for small key and value |
| 20 | // objects. |
| 21 | // |
| 22 | // A Traits class specifies how keys are compared. It also allows IntervalMap to |
| 23 | // work with both closed and half-open intervals. |
| 24 | // |
| 25 | // Keys and values are not stored next to each other in a std::pair, so we don't |
| 26 | // provide such a value_type. Dereferencing iterators only returns the mapped |
| 27 | // value. The interval bounds are accessible through the start() and stop() |
| 28 | // iterator methods. |
| 29 | // |
| 30 | // IntervalMap is optimized for small key and value objects, 4 or 8 bytes each |
| 31 | // is the optimal size. For large objects use std::map instead. |
| 32 | // |
| 33 | //===----------------------------------------------------------------------===// |
| 34 | // |
| 35 | // Synopsis: |
| 36 | // |
| 37 | // template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 38 | // class IntervalMap { |
| 39 | // public: |
| 40 | // typedef KeyT key_type; |
| 41 | // typedef ValT mapped_type; |
| 42 | // typedef RecyclingAllocator<...> Allocator; |
| 43 | // class iterator; |
| 44 | // class const_iterator; |
| 45 | // |
| 46 | // explicit IntervalMap(Allocator&); |
| 47 | // ~IntervalMap(): |
| 48 | // |
| 49 | // bool empty() const; |
| 50 | // KeyT start() const; |
| 51 | // KeyT stop() const; |
| 52 | // ValT lookup(KeyT x, Value NotFound = Value()) const; |
| 53 | // |
| 54 | // const_iterator begin() const; |
| 55 | // const_iterator end() const; |
| 56 | // iterator begin(); |
| 57 | // iterator end(); |
| 58 | // const_iterator find(KeyT x) const; |
| 59 | // iterator find(KeyT x); |
| 60 | // |
| 61 | // void insert(KeyT a, KeyT b, ValT y); |
| 62 | // void clear(); |
| 63 | // }; |
| 64 | // |
| 65 | // template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 66 | // class IntervalMap::const_iterator : |
| 67 | // public std::iterator<std::bidirectional_iterator_tag, ValT> { |
| 68 | // public: |
| 69 | // bool operator==(const const_iterator &) const; |
| 70 | // bool operator!=(const const_iterator &) const; |
| 71 | // bool valid() const; |
| 72 | // |
| 73 | // const KeyT &start() const; |
| 74 | // const KeyT &stop() const; |
| 75 | // const ValT &value() const; |
| 76 | // const ValT &operator*() const; |
| 77 | // const ValT *operator->() const; |
| 78 | // |
| 79 | // const_iterator &operator++(); |
| 80 | // const_iterator &operator++(int); |
| 81 | // const_iterator &operator--(); |
| 82 | // const_iterator &operator--(int); |
| 83 | // void goToBegin(); |
| 84 | // void goToEnd(); |
| 85 | // void find(KeyT x); |
| 86 | // void advanceTo(KeyT x); |
| 87 | // }; |
| 88 | // |
| 89 | // template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 90 | // class IntervalMap::iterator : public const_iterator { |
| 91 | // public: |
| 92 | // void insert(KeyT a, KeyT b, Value y); |
| 93 | // void erase(); |
| 94 | // }; |
| 95 | // |
| 96 | //===----------------------------------------------------------------------===// |
| 97 | |
| 98 | #ifndef LLVM_ADT_INTERVALMAP_H |
| 99 | #define LLVM_ADT_INTERVALMAP_H |
| 100 | |
| 101 | #include "llvm/ADT/PointerIntPair.h" |
| 102 | #include "llvm/ADT/SmallVector.h" |
Andrew Scull | 0372a57 | 2018-11-16 15:47:06 +0000 | [diff] [blame] | 103 | #include "llvm/ADT/bit.h" |
Andrew Scull | 5e1ddfa | 2018-08-14 10:06:54 +0100 | [diff] [blame] | 104 | #include "llvm/Support/AlignOf.h" |
| 105 | #include "llvm/Support/Allocator.h" |
| 106 | #include "llvm/Support/RecyclingAllocator.h" |
| 107 | #include <algorithm> |
| 108 | #include <cassert> |
| 109 | #include <cstdint> |
| 110 | #include <iterator> |
| 111 | #include <new> |
| 112 | #include <utility> |
| 113 | |
| 114 | namespace llvm { |
| 115 | |
| 116 | //===----------------------------------------------------------------------===// |
| 117 | //--- Key traits ---// |
| 118 | //===----------------------------------------------------------------------===// |
| 119 | // |
| 120 | // The IntervalMap works with closed or half-open intervals. |
| 121 | // Adjacent intervals that map to the same value are coalesced. |
| 122 | // |
| 123 | // The IntervalMapInfo traits class is used to determine if a key is contained |
| 124 | // in an interval, and if two intervals are adjacent so they can be coalesced. |
| 125 | // The provided implementation works for closed integer intervals, other keys |
| 126 | // probably need a specialized version. |
| 127 | // |
| 128 | // The point x is contained in [a;b] when !startLess(x, a) && !stopLess(b, x). |
| 129 | // |
| 130 | // It is assumed that (a;b] half-open intervals are not used, only [a;b) is |
| 131 | // allowed. This is so that stopLess(a, b) can be used to determine if two |
| 132 | // intervals overlap. |
| 133 | // |
| 134 | //===----------------------------------------------------------------------===// |
| 135 | |
| 136 | template <typename T> |
| 137 | struct IntervalMapInfo { |
| 138 | /// startLess - Return true if x is not in [a;b]. |
| 139 | /// This is x < a both for closed intervals and for [a;b) half-open intervals. |
| 140 | static inline bool startLess(const T &x, const T &a) { |
| 141 | return x < a; |
| 142 | } |
| 143 | |
| 144 | /// stopLess - Return true if x is not in [a;b]. |
| 145 | /// This is b < x for a closed interval, b <= x for [a;b) half-open intervals. |
| 146 | static inline bool stopLess(const T &b, const T &x) { |
| 147 | return b < x; |
| 148 | } |
| 149 | |
| 150 | /// adjacent - Return true when the intervals [x;a] and [b;y] can coalesce. |
| 151 | /// This is a+1 == b for closed intervals, a == b for half-open intervals. |
| 152 | static inline bool adjacent(const T &a, const T &b) { |
| 153 | return a+1 == b; |
| 154 | } |
| 155 | |
| 156 | /// nonEmpty - Return true if [a;b] is non-empty. |
| 157 | /// This is a <= b for a closed interval, a < b for [a;b) half-open intervals. |
| 158 | static inline bool nonEmpty(const T &a, const T &b) { |
| 159 | return a <= b; |
| 160 | } |
| 161 | }; |
| 162 | |
| 163 | template <typename T> |
| 164 | struct IntervalMapHalfOpenInfo { |
| 165 | /// startLess - Return true if x is not in [a;b). |
| 166 | static inline bool startLess(const T &x, const T &a) { |
| 167 | return x < a; |
| 168 | } |
| 169 | |
| 170 | /// stopLess - Return true if x is not in [a;b). |
| 171 | static inline bool stopLess(const T &b, const T &x) { |
| 172 | return b <= x; |
| 173 | } |
| 174 | |
| 175 | /// adjacent - Return true when the intervals [x;a) and [b;y) can coalesce. |
| 176 | static inline bool adjacent(const T &a, const T &b) { |
| 177 | return a == b; |
| 178 | } |
| 179 | |
| 180 | /// nonEmpty - Return true if [a;b) is non-empty. |
| 181 | static inline bool nonEmpty(const T &a, const T &b) { |
| 182 | return a < b; |
| 183 | } |
| 184 | }; |
| 185 | |
| 186 | /// IntervalMapImpl - Namespace used for IntervalMap implementation details. |
| 187 | /// It should be considered private to the implementation. |
| 188 | namespace IntervalMapImpl { |
| 189 | |
| 190 | using IdxPair = std::pair<unsigned,unsigned>; |
| 191 | |
| 192 | //===----------------------------------------------------------------------===// |
| 193 | //--- IntervalMapImpl::NodeBase ---// |
| 194 | //===----------------------------------------------------------------------===// |
| 195 | // |
| 196 | // Both leaf and branch nodes store vectors of pairs. |
| 197 | // Leaves store ((KeyT, KeyT), ValT) pairs, branches use (NodeRef, KeyT). |
| 198 | // |
| 199 | // Keys and values are stored in separate arrays to avoid padding caused by |
| 200 | // different object alignments. This also helps improve locality of reference |
| 201 | // when searching the keys. |
| 202 | // |
| 203 | // The nodes don't know how many elements they contain - that information is |
| 204 | // stored elsewhere. Omitting the size field prevents padding and allows a node |
| 205 | // to fill the allocated cache lines completely. |
| 206 | // |
| 207 | // These are typical key and value sizes, the node branching factor (N), and |
| 208 | // wasted space when nodes are sized to fit in three cache lines (192 bytes): |
| 209 | // |
| 210 | // T1 T2 N Waste Used by |
| 211 | // 4 4 24 0 Branch<4> (32-bit pointers) |
| 212 | // 8 4 16 0 Leaf<4,4>, Branch<4> |
| 213 | // 8 8 12 0 Leaf<4,8>, Branch<8> |
| 214 | // 16 4 9 12 Leaf<8,4> |
| 215 | // 16 8 8 0 Leaf<8,8> |
| 216 | // |
| 217 | //===----------------------------------------------------------------------===// |
| 218 | |
| 219 | template <typename T1, typename T2, unsigned N> |
| 220 | class NodeBase { |
| 221 | public: |
| 222 | enum { Capacity = N }; |
| 223 | |
| 224 | T1 first[N]; |
| 225 | T2 second[N]; |
| 226 | |
| 227 | /// copy - Copy elements from another node. |
| 228 | /// @param Other Node elements are copied from. |
| 229 | /// @param i Beginning of the source range in other. |
| 230 | /// @param j Beginning of the destination range in this. |
| 231 | /// @param Count Number of elements to copy. |
| 232 | template <unsigned M> |
| 233 | void copy(const NodeBase<T1, T2, M> &Other, unsigned i, |
| 234 | unsigned j, unsigned Count) { |
| 235 | assert(i + Count <= M && "Invalid source range"); |
| 236 | assert(j + Count <= N && "Invalid dest range"); |
| 237 | for (unsigned e = i + Count; i != e; ++i, ++j) { |
| 238 | first[j] = Other.first[i]; |
| 239 | second[j] = Other.second[i]; |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | /// moveLeft - Move elements to the left. |
| 244 | /// @param i Beginning of the source range. |
| 245 | /// @param j Beginning of the destination range. |
| 246 | /// @param Count Number of elements to copy. |
| 247 | void moveLeft(unsigned i, unsigned j, unsigned Count) { |
| 248 | assert(j <= i && "Use moveRight shift elements right"); |
| 249 | copy(*this, i, j, Count); |
| 250 | } |
| 251 | |
| 252 | /// moveRight - Move elements to the right. |
| 253 | /// @param i Beginning of the source range. |
| 254 | /// @param j Beginning of the destination range. |
| 255 | /// @param Count Number of elements to copy. |
| 256 | void moveRight(unsigned i, unsigned j, unsigned Count) { |
| 257 | assert(i <= j && "Use moveLeft shift elements left"); |
| 258 | assert(j + Count <= N && "Invalid range"); |
| 259 | while (Count--) { |
| 260 | first[j + Count] = first[i + Count]; |
| 261 | second[j + Count] = second[i + Count]; |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | /// erase - Erase elements [i;j). |
| 266 | /// @param i Beginning of the range to erase. |
| 267 | /// @param j End of the range. (Exclusive). |
| 268 | /// @param Size Number of elements in node. |
| 269 | void erase(unsigned i, unsigned j, unsigned Size) { |
| 270 | moveLeft(j, i, Size - j); |
| 271 | } |
| 272 | |
| 273 | /// erase - Erase element at i. |
| 274 | /// @param i Index of element to erase. |
| 275 | /// @param Size Number of elements in node. |
| 276 | void erase(unsigned i, unsigned Size) { |
| 277 | erase(i, i+1, Size); |
| 278 | } |
| 279 | |
| 280 | /// shift - Shift elements [i;size) 1 position to the right. |
| 281 | /// @param i Beginning of the range to move. |
| 282 | /// @param Size Number of elements in node. |
| 283 | void shift(unsigned i, unsigned Size) { |
| 284 | moveRight(i, i + 1, Size - i); |
| 285 | } |
| 286 | |
| 287 | /// transferToLeftSib - Transfer elements to a left sibling node. |
| 288 | /// @param Size Number of elements in this. |
| 289 | /// @param Sib Left sibling node. |
| 290 | /// @param SSize Number of elements in sib. |
| 291 | /// @param Count Number of elements to transfer. |
| 292 | void transferToLeftSib(unsigned Size, NodeBase &Sib, unsigned SSize, |
| 293 | unsigned Count) { |
| 294 | Sib.copy(*this, 0, SSize, Count); |
| 295 | erase(0, Count, Size); |
| 296 | } |
| 297 | |
| 298 | /// transferToRightSib - Transfer elements to a right sibling node. |
| 299 | /// @param Size Number of elements in this. |
| 300 | /// @param Sib Right sibling node. |
| 301 | /// @param SSize Number of elements in sib. |
| 302 | /// @param Count Number of elements to transfer. |
| 303 | void transferToRightSib(unsigned Size, NodeBase &Sib, unsigned SSize, |
| 304 | unsigned Count) { |
| 305 | Sib.moveRight(0, Count, SSize); |
| 306 | Sib.copy(*this, Size-Count, 0, Count); |
| 307 | } |
| 308 | |
| 309 | /// adjustFromLeftSib - Adjust the number if elements in this node by moving |
| 310 | /// elements to or from a left sibling node. |
| 311 | /// @param Size Number of elements in this. |
| 312 | /// @param Sib Right sibling node. |
| 313 | /// @param SSize Number of elements in sib. |
| 314 | /// @param Add The number of elements to add to this node, possibly < 0. |
| 315 | /// @return Number of elements added to this node, possibly negative. |
| 316 | int adjustFromLeftSib(unsigned Size, NodeBase &Sib, unsigned SSize, int Add) { |
| 317 | if (Add > 0) { |
| 318 | // We want to grow, copy from sib. |
| 319 | unsigned Count = std::min(std::min(unsigned(Add), SSize), N - Size); |
| 320 | Sib.transferToRightSib(SSize, *this, Size, Count); |
| 321 | return Count; |
| 322 | } else { |
| 323 | // We want to shrink, copy to sib. |
| 324 | unsigned Count = std::min(std::min(unsigned(-Add), Size), N - SSize); |
| 325 | transferToLeftSib(Size, Sib, SSize, Count); |
| 326 | return -Count; |
| 327 | } |
| 328 | } |
| 329 | }; |
| 330 | |
| 331 | /// IntervalMapImpl::adjustSiblingSizes - Move elements between sibling nodes. |
| 332 | /// @param Node Array of pointers to sibling nodes. |
| 333 | /// @param Nodes Number of nodes. |
| 334 | /// @param CurSize Array of current node sizes, will be overwritten. |
| 335 | /// @param NewSize Array of desired node sizes. |
| 336 | template <typename NodeT> |
| 337 | void adjustSiblingSizes(NodeT *Node[], unsigned Nodes, |
| 338 | unsigned CurSize[], const unsigned NewSize[]) { |
| 339 | // Move elements right. |
| 340 | for (int n = Nodes - 1; n; --n) { |
| 341 | if (CurSize[n] == NewSize[n]) |
| 342 | continue; |
| 343 | for (int m = n - 1; m != -1; --m) { |
| 344 | int d = Node[n]->adjustFromLeftSib(CurSize[n], *Node[m], CurSize[m], |
| 345 | NewSize[n] - CurSize[n]); |
| 346 | CurSize[m] -= d; |
| 347 | CurSize[n] += d; |
| 348 | // Keep going if the current node was exhausted. |
| 349 | if (CurSize[n] >= NewSize[n]) |
| 350 | break; |
| 351 | } |
| 352 | } |
| 353 | |
| 354 | if (Nodes == 0) |
| 355 | return; |
| 356 | |
| 357 | // Move elements left. |
| 358 | for (unsigned n = 0; n != Nodes - 1; ++n) { |
| 359 | if (CurSize[n] == NewSize[n]) |
| 360 | continue; |
| 361 | for (unsigned m = n + 1; m != Nodes; ++m) { |
| 362 | int d = Node[m]->adjustFromLeftSib(CurSize[m], *Node[n], CurSize[n], |
| 363 | CurSize[n] - NewSize[n]); |
| 364 | CurSize[m] += d; |
| 365 | CurSize[n] -= d; |
| 366 | // Keep going if the current node was exhausted. |
| 367 | if (CurSize[n] >= NewSize[n]) |
| 368 | break; |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | #ifndef NDEBUG |
| 373 | for (unsigned n = 0; n != Nodes; n++) |
| 374 | assert(CurSize[n] == NewSize[n] && "Insufficient element shuffle"); |
| 375 | #endif |
| 376 | } |
| 377 | |
| 378 | /// IntervalMapImpl::distribute - Compute a new distribution of node elements |
| 379 | /// after an overflow or underflow. Reserve space for a new element at Position, |
| 380 | /// and compute the node that will hold Position after redistributing node |
| 381 | /// elements. |
| 382 | /// |
| 383 | /// It is required that |
| 384 | /// |
| 385 | /// Elements == sum(CurSize), and |
| 386 | /// Elements + Grow <= Nodes * Capacity. |
| 387 | /// |
| 388 | /// NewSize[] will be filled in such that: |
| 389 | /// |
| 390 | /// sum(NewSize) == Elements, and |
| 391 | /// NewSize[i] <= Capacity. |
| 392 | /// |
| 393 | /// The returned index is the node where Position will go, so: |
| 394 | /// |
| 395 | /// sum(NewSize[0..idx-1]) <= Position |
| 396 | /// sum(NewSize[0..idx]) >= Position |
| 397 | /// |
| 398 | /// The last equality, sum(NewSize[0..idx]) == Position, can only happen when |
| 399 | /// Grow is set and NewSize[idx] == Capacity-1. The index points to the node |
| 400 | /// before the one holding the Position'th element where there is room for an |
| 401 | /// insertion. |
| 402 | /// |
| 403 | /// @param Nodes The number of nodes. |
| 404 | /// @param Elements Total elements in all nodes. |
| 405 | /// @param Capacity The capacity of each node. |
| 406 | /// @param CurSize Array[Nodes] of current node sizes, or NULL. |
| 407 | /// @param NewSize Array[Nodes] to receive the new node sizes. |
| 408 | /// @param Position Insert position. |
| 409 | /// @param Grow Reserve space for a new element at Position. |
| 410 | /// @return (node, offset) for Position. |
| 411 | IdxPair distribute(unsigned Nodes, unsigned Elements, unsigned Capacity, |
| 412 | const unsigned *CurSize, unsigned NewSize[], |
| 413 | unsigned Position, bool Grow); |
| 414 | |
| 415 | //===----------------------------------------------------------------------===// |
| 416 | //--- IntervalMapImpl::NodeSizer ---// |
| 417 | //===----------------------------------------------------------------------===// |
| 418 | // |
| 419 | // Compute node sizes from key and value types. |
| 420 | // |
| 421 | // The branching factors are chosen to make nodes fit in three cache lines. |
| 422 | // This may not be possible if keys or values are very large. Such large objects |
| 423 | // are handled correctly, but a std::map would probably give better performance. |
| 424 | // |
| 425 | //===----------------------------------------------------------------------===// |
| 426 | |
| 427 | enum { |
| 428 | // Cache line size. Most architectures have 32 or 64 byte cache lines. |
| 429 | // We use 64 bytes here because it provides good branching factors. |
| 430 | Log2CacheLine = 6, |
| 431 | CacheLineBytes = 1 << Log2CacheLine, |
| 432 | DesiredNodeBytes = 3 * CacheLineBytes |
| 433 | }; |
| 434 | |
| 435 | template <typename KeyT, typename ValT> |
| 436 | struct NodeSizer { |
| 437 | enum { |
| 438 | // Compute the leaf node branching factor that makes a node fit in three |
| 439 | // cache lines. The branching factor must be at least 3, or some B+-tree |
| 440 | // balancing algorithms won't work. |
| 441 | // LeafSize can't be larger than CacheLineBytes. This is required by the |
| 442 | // PointerIntPair used by NodeRef. |
| 443 | DesiredLeafSize = DesiredNodeBytes / |
| 444 | static_cast<unsigned>(2*sizeof(KeyT)+sizeof(ValT)), |
| 445 | MinLeafSize = 3, |
| 446 | LeafSize = DesiredLeafSize > MinLeafSize ? DesiredLeafSize : MinLeafSize |
| 447 | }; |
| 448 | |
| 449 | using LeafBase = NodeBase<std::pair<KeyT, KeyT>, ValT, LeafSize>; |
| 450 | |
| 451 | enum { |
| 452 | // Now that we have the leaf branching factor, compute the actual allocation |
| 453 | // unit size by rounding up to a whole number of cache lines. |
| 454 | AllocBytes = (sizeof(LeafBase) + CacheLineBytes-1) & ~(CacheLineBytes-1), |
| 455 | |
| 456 | // Determine the branching factor for branch nodes. |
| 457 | BranchSize = AllocBytes / |
| 458 | static_cast<unsigned>(sizeof(KeyT) + sizeof(void*)) |
| 459 | }; |
| 460 | |
| 461 | /// Allocator - The recycling allocator used for both branch and leaf nodes. |
| 462 | /// This typedef is very likely to be identical for all IntervalMaps with |
| 463 | /// reasonably sized entries, so the same allocator can be shared among |
| 464 | /// different kinds of maps. |
| 465 | using Allocator = |
| 466 | RecyclingAllocator<BumpPtrAllocator, char, AllocBytes, CacheLineBytes>; |
| 467 | }; |
| 468 | |
| 469 | //===----------------------------------------------------------------------===// |
| 470 | //--- IntervalMapImpl::NodeRef ---// |
| 471 | //===----------------------------------------------------------------------===// |
| 472 | // |
| 473 | // B+-tree nodes can be leaves or branches, so we need a polymorphic node |
| 474 | // pointer that can point to both kinds. |
| 475 | // |
| 476 | // All nodes are cache line aligned and the low 6 bits of a node pointer are |
| 477 | // always 0. These bits are used to store the number of elements in the |
| 478 | // referenced node. Besides saving space, placing node sizes in the parents |
| 479 | // allow tree balancing algorithms to run without faulting cache lines for nodes |
| 480 | // that may not need to be modified. |
| 481 | // |
| 482 | // A NodeRef doesn't know whether it references a leaf node or a branch node. |
| 483 | // It is the responsibility of the caller to use the correct types. |
| 484 | // |
| 485 | // Nodes are never supposed to be empty, and it is invalid to store a node size |
| 486 | // of 0 in a NodeRef. The valid range of sizes is 1-64. |
| 487 | // |
| 488 | //===----------------------------------------------------------------------===// |
| 489 | |
| 490 | class NodeRef { |
| 491 | struct CacheAlignedPointerTraits { |
| 492 | static inline void *getAsVoidPointer(void *P) { return P; } |
| 493 | static inline void *getFromVoidPointer(void *P) { return P; } |
Olivier Deprez | f4ef2d0 | 2021-04-20 13:36:24 +0200 | [diff] [blame] | 494 | static constexpr int NumLowBitsAvailable = Log2CacheLine; |
Andrew Scull | 5e1ddfa | 2018-08-14 10:06:54 +0100 | [diff] [blame] | 495 | }; |
| 496 | PointerIntPair<void*, Log2CacheLine, unsigned, CacheAlignedPointerTraits> pip; |
| 497 | |
| 498 | public: |
| 499 | /// NodeRef - Create a null ref. |
| 500 | NodeRef() = default; |
| 501 | |
| 502 | /// operator bool - Detect a null ref. |
| 503 | explicit operator bool() const { return pip.getOpaqueValue(); } |
| 504 | |
| 505 | /// NodeRef - Create a reference to the node p with n elements. |
| 506 | template <typename NodeT> |
| 507 | NodeRef(NodeT *p, unsigned n) : pip(p, n - 1) { |
| 508 | assert(n <= NodeT::Capacity && "Size too big for node"); |
| 509 | } |
| 510 | |
| 511 | /// size - Return the number of elements in the referenced node. |
| 512 | unsigned size() const { return pip.getInt() + 1; } |
| 513 | |
| 514 | /// setSize - Update the node size. |
| 515 | void setSize(unsigned n) { pip.setInt(n - 1); } |
| 516 | |
| 517 | /// subtree - Access the i'th subtree reference in a branch node. |
| 518 | /// This depends on branch nodes storing the NodeRef array as their first |
| 519 | /// member. |
| 520 | NodeRef &subtree(unsigned i) const { |
| 521 | return reinterpret_cast<NodeRef*>(pip.getPointer())[i]; |
| 522 | } |
| 523 | |
| 524 | /// get - Dereference as a NodeT reference. |
| 525 | template <typename NodeT> |
| 526 | NodeT &get() const { |
| 527 | return *reinterpret_cast<NodeT*>(pip.getPointer()); |
| 528 | } |
| 529 | |
| 530 | bool operator==(const NodeRef &RHS) const { |
| 531 | if (pip == RHS.pip) |
| 532 | return true; |
| 533 | assert(pip.getPointer() != RHS.pip.getPointer() && "Inconsistent NodeRefs"); |
| 534 | return false; |
| 535 | } |
| 536 | |
| 537 | bool operator!=(const NodeRef &RHS) const { |
| 538 | return !operator==(RHS); |
| 539 | } |
| 540 | }; |
| 541 | |
| 542 | //===----------------------------------------------------------------------===// |
| 543 | //--- IntervalMapImpl::LeafNode ---// |
| 544 | //===----------------------------------------------------------------------===// |
| 545 | // |
| 546 | // Leaf nodes store up to N disjoint intervals with corresponding values. |
| 547 | // |
| 548 | // The intervals are kept sorted and fully coalesced so there are no adjacent |
| 549 | // intervals mapping to the same value. |
| 550 | // |
| 551 | // These constraints are always satisfied: |
| 552 | // |
| 553 | // - Traits::stopLess(start(i), stop(i)) - Non-empty, sane intervals. |
| 554 | // |
| 555 | // - Traits::stopLess(stop(i), start(i + 1) - Sorted. |
| 556 | // |
| 557 | // - value(i) != value(i + 1) || !Traits::adjacent(stop(i), start(i + 1)) |
| 558 | // - Fully coalesced. |
| 559 | // |
| 560 | //===----------------------------------------------------------------------===// |
| 561 | |
| 562 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 563 | class LeafNode : public NodeBase<std::pair<KeyT, KeyT>, ValT, N> { |
| 564 | public: |
| 565 | const KeyT &start(unsigned i) const { return this->first[i].first; } |
| 566 | const KeyT &stop(unsigned i) const { return this->first[i].second; } |
| 567 | const ValT &value(unsigned i) const { return this->second[i]; } |
| 568 | |
| 569 | KeyT &start(unsigned i) { return this->first[i].first; } |
| 570 | KeyT &stop(unsigned i) { return this->first[i].second; } |
| 571 | ValT &value(unsigned i) { return this->second[i]; } |
| 572 | |
| 573 | /// findFrom - Find the first interval after i that may contain x. |
| 574 | /// @param i Starting index for the search. |
| 575 | /// @param Size Number of elements in node. |
| 576 | /// @param x Key to search for. |
| 577 | /// @return First index with !stopLess(key[i].stop, x), or size. |
| 578 | /// This is the first interval that can possibly contain x. |
| 579 | unsigned findFrom(unsigned i, unsigned Size, KeyT x) const { |
| 580 | assert(i <= Size && Size <= N && "Bad indices"); |
| 581 | assert((i == 0 || Traits::stopLess(stop(i - 1), x)) && |
| 582 | "Index is past the needed point"); |
| 583 | while (i != Size && Traits::stopLess(stop(i), x)) ++i; |
| 584 | return i; |
| 585 | } |
| 586 | |
| 587 | /// safeFind - Find an interval that is known to exist. This is the same as |
| 588 | /// findFrom except is it assumed that x is at least within range of the last |
| 589 | /// interval. |
| 590 | /// @param i Starting index for the search. |
| 591 | /// @param x Key to search for. |
| 592 | /// @return First index with !stopLess(key[i].stop, x), never size. |
| 593 | /// This is the first interval that can possibly contain x. |
| 594 | unsigned safeFind(unsigned i, KeyT x) const { |
| 595 | assert(i < N && "Bad index"); |
| 596 | assert((i == 0 || Traits::stopLess(stop(i - 1), x)) && |
| 597 | "Index is past the needed point"); |
| 598 | while (Traits::stopLess(stop(i), x)) ++i; |
| 599 | assert(i < N && "Unsafe intervals"); |
| 600 | return i; |
| 601 | } |
| 602 | |
| 603 | /// safeLookup - Lookup mapped value for a safe key. |
| 604 | /// It is assumed that x is within range of the last entry. |
| 605 | /// @param x Key to search for. |
| 606 | /// @param NotFound Value to return if x is not in any interval. |
| 607 | /// @return The mapped value at x or NotFound. |
| 608 | ValT safeLookup(KeyT x, ValT NotFound) const { |
| 609 | unsigned i = safeFind(0, x); |
| 610 | return Traits::startLess(x, start(i)) ? NotFound : value(i); |
| 611 | } |
| 612 | |
| 613 | unsigned insertFrom(unsigned &Pos, unsigned Size, KeyT a, KeyT b, ValT y); |
| 614 | }; |
| 615 | |
| 616 | /// insertFrom - Add mapping of [a;b] to y if possible, coalescing as much as |
| 617 | /// possible. This may cause the node to grow by 1, or it may cause the node |
| 618 | /// to shrink because of coalescing. |
| 619 | /// @param Pos Starting index = insertFrom(0, size, a) |
| 620 | /// @param Size Number of elements in node. |
| 621 | /// @param a Interval start. |
| 622 | /// @param b Interval stop. |
| 623 | /// @param y Value be mapped. |
| 624 | /// @return (insert position, new size), or (i, Capacity+1) on overflow. |
| 625 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 626 | unsigned LeafNode<KeyT, ValT, N, Traits>:: |
| 627 | insertFrom(unsigned &Pos, unsigned Size, KeyT a, KeyT b, ValT y) { |
| 628 | unsigned i = Pos; |
| 629 | assert(i <= Size && Size <= N && "Invalid index"); |
| 630 | assert(!Traits::stopLess(b, a) && "Invalid interval"); |
| 631 | |
| 632 | // Verify the findFrom invariant. |
| 633 | assert((i == 0 || Traits::stopLess(stop(i - 1), a))); |
| 634 | assert((i == Size || !Traits::stopLess(stop(i), a))); |
| 635 | assert((i == Size || Traits::stopLess(b, start(i))) && "Overlapping insert"); |
| 636 | |
| 637 | // Coalesce with previous interval. |
| 638 | if (i && value(i - 1) == y && Traits::adjacent(stop(i - 1), a)) { |
| 639 | Pos = i - 1; |
| 640 | // Also coalesce with next interval? |
| 641 | if (i != Size && value(i) == y && Traits::adjacent(b, start(i))) { |
| 642 | stop(i - 1) = stop(i); |
| 643 | this->erase(i, Size); |
| 644 | return Size - 1; |
| 645 | } |
| 646 | stop(i - 1) = b; |
| 647 | return Size; |
| 648 | } |
| 649 | |
| 650 | // Detect overflow. |
| 651 | if (i == N) |
| 652 | return N + 1; |
| 653 | |
| 654 | // Add new interval at end. |
| 655 | if (i == Size) { |
| 656 | start(i) = a; |
| 657 | stop(i) = b; |
| 658 | value(i) = y; |
| 659 | return Size + 1; |
| 660 | } |
| 661 | |
| 662 | // Try to coalesce with following interval. |
| 663 | if (value(i) == y && Traits::adjacent(b, start(i))) { |
| 664 | start(i) = a; |
| 665 | return Size; |
| 666 | } |
| 667 | |
| 668 | // We must insert before i. Detect overflow. |
| 669 | if (Size == N) |
| 670 | return N + 1; |
| 671 | |
| 672 | // Insert before i. |
| 673 | this->shift(i, Size); |
| 674 | start(i) = a; |
| 675 | stop(i) = b; |
| 676 | value(i) = y; |
| 677 | return Size + 1; |
| 678 | } |
| 679 | |
| 680 | //===----------------------------------------------------------------------===// |
| 681 | //--- IntervalMapImpl::BranchNode ---// |
| 682 | //===----------------------------------------------------------------------===// |
| 683 | // |
| 684 | // A branch node stores references to 1--N subtrees all of the same height. |
| 685 | // |
| 686 | // The key array in a branch node holds the rightmost stop key of each subtree. |
| 687 | // It is redundant to store the last stop key since it can be found in the |
| 688 | // parent node, but doing so makes tree balancing a lot simpler. |
| 689 | // |
| 690 | // It is unusual for a branch node to only have one subtree, but it can happen |
| 691 | // in the root node if it is smaller than the normal nodes. |
| 692 | // |
| 693 | // When all of the leaf nodes from all the subtrees are concatenated, they must |
| 694 | // satisfy the same constraints as a single leaf node. They must be sorted, |
| 695 | // sane, and fully coalesced. |
| 696 | // |
| 697 | //===----------------------------------------------------------------------===// |
| 698 | |
| 699 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 700 | class BranchNode : public NodeBase<NodeRef, KeyT, N> { |
| 701 | public: |
| 702 | const KeyT &stop(unsigned i) const { return this->second[i]; } |
| 703 | const NodeRef &subtree(unsigned i) const { return this->first[i]; } |
| 704 | |
| 705 | KeyT &stop(unsigned i) { return this->second[i]; } |
| 706 | NodeRef &subtree(unsigned i) { return this->first[i]; } |
| 707 | |
| 708 | /// findFrom - Find the first subtree after i that may contain x. |
| 709 | /// @param i Starting index for the search. |
| 710 | /// @param Size Number of elements in node. |
| 711 | /// @param x Key to search for. |
| 712 | /// @return First index with !stopLess(key[i], x), or size. |
| 713 | /// This is the first subtree that can possibly contain x. |
| 714 | unsigned findFrom(unsigned i, unsigned Size, KeyT x) const { |
| 715 | assert(i <= Size && Size <= N && "Bad indices"); |
| 716 | assert((i == 0 || Traits::stopLess(stop(i - 1), x)) && |
| 717 | "Index to findFrom is past the needed point"); |
| 718 | while (i != Size && Traits::stopLess(stop(i), x)) ++i; |
| 719 | return i; |
| 720 | } |
| 721 | |
| 722 | /// safeFind - Find a subtree that is known to exist. This is the same as |
| 723 | /// findFrom except is it assumed that x is in range. |
| 724 | /// @param i Starting index for the search. |
| 725 | /// @param x Key to search for. |
| 726 | /// @return First index with !stopLess(key[i], x), never size. |
| 727 | /// This is the first subtree that can possibly contain x. |
| 728 | unsigned safeFind(unsigned i, KeyT x) const { |
| 729 | assert(i < N && "Bad index"); |
| 730 | assert((i == 0 || Traits::stopLess(stop(i - 1), x)) && |
| 731 | "Index is past the needed point"); |
| 732 | while (Traits::stopLess(stop(i), x)) ++i; |
| 733 | assert(i < N && "Unsafe intervals"); |
| 734 | return i; |
| 735 | } |
| 736 | |
| 737 | /// safeLookup - Get the subtree containing x, Assuming that x is in range. |
| 738 | /// @param x Key to search for. |
| 739 | /// @return Subtree containing x |
| 740 | NodeRef safeLookup(KeyT x) const { |
| 741 | return subtree(safeFind(0, x)); |
| 742 | } |
| 743 | |
| 744 | /// insert - Insert a new (subtree, stop) pair. |
| 745 | /// @param i Insert position, following entries will be shifted. |
| 746 | /// @param Size Number of elements in node. |
| 747 | /// @param Node Subtree to insert. |
| 748 | /// @param Stop Last key in subtree. |
| 749 | void insert(unsigned i, unsigned Size, NodeRef Node, KeyT Stop) { |
| 750 | assert(Size < N && "branch node overflow"); |
| 751 | assert(i <= Size && "Bad insert position"); |
| 752 | this->shift(i, Size); |
| 753 | subtree(i) = Node; |
| 754 | stop(i) = Stop; |
| 755 | } |
| 756 | }; |
| 757 | |
| 758 | //===----------------------------------------------------------------------===// |
| 759 | //--- IntervalMapImpl::Path ---// |
| 760 | //===----------------------------------------------------------------------===// |
| 761 | // |
| 762 | // A Path is used by iterators to represent a position in a B+-tree, and the |
| 763 | // path to get there from the root. |
| 764 | // |
| 765 | // The Path class also contains the tree navigation code that doesn't have to |
| 766 | // be templatized. |
| 767 | // |
| 768 | //===----------------------------------------------------------------------===// |
| 769 | |
| 770 | class Path { |
| 771 | /// Entry - Each step in the path is a node pointer and an offset into that |
| 772 | /// node. |
| 773 | struct Entry { |
| 774 | void *node; |
| 775 | unsigned size; |
| 776 | unsigned offset; |
| 777 | |
| 778 | Entry(void *Node, unsigned Size, unsigned Offset) |
| 779 | : node(Node), size(Size), offset(Offset) {} |
| 780 | |
| 781 | Entry(NodeRef Node, unsigned Offset) |
| 782 | : node(&Node.subtree(0)), size(Node.size()), offset(Offset) {} |
| 783 | |
| 784 | NodeRef &subtree(unsigned i) const { |
| 785 | return reinterpret_cast<NodeRef*>(node)[i]; |
| 786 | } |
| 787 | }; |
| 788 | |
| 789 | /// path - The path entries, path[0] is the root node, path.back() is a leaf. |
| 790 | SmallVector<Entry, 4> path; |
| 791 | |
| 792 | public: |
| 793 | // Node accessors. |
| 794 | template <typename NodeT> NodeT &node(unsigned Level) const { |
| 795 | return *reinterpret_cast<NodeT*>(path[Level].node); |
| 796 | } |
| 797 | unsigned size(unsigned Level) const { return path[Level].size; } |
| 798 | unsigned offset(unsigned Level) const { return path[Level].offset; } |
| 799 | unsigned &offset(unsigned Level) { return path[Level].offset; } |
| 800 | |
| 801 | // Leaf accessors. |
| 802 | template <typename NodeT> NodeT &leaf() const { |
| 803 | return *reinterpret_cast<NodeT*>(path.back().node); |
| 804 | } |
| 805 | unsigned leafSize() const { return path.back().size; } |
| 806 | unsigned leafOffset() const { return path.back().offset; } |
| 807 | unsigned &leafOffset() { return path.back().offset; } |
| 808 | |
| 809 | /// valid - Return true if path is at a valid node, not at end(). |
| 810 | bool valid() const { |
| 811 | return !path.empty() && path.front().offset < path.front().size; |
| 812 | } |
| 813 | |
| 814 | /// height - Return the height of the tree corresponding to this path. |
| 815 | /// This matches map->height in a full path. |
| 816 | unsigned height() const { return path.size() - 1; } |
| 817 | |
| 818 | /// subtree - Get the subtree referenced from Level. When the path is |
| 819 | /// consistent, node(Level + 1) == subtree(Level). |
| 820 | /// @param Level 0..height-1. The leaves have no subtrees. |
| 821 | NodeRef &subtree(unsigned Level) const { |
| 822 | return path[Level].subtree(path[Level].offset); |
| 823 | } |
| 824 | |
| 825 | /// reset - Reset cached information about node(Level) from subtree(Level -1). |
Olivier Deprez | f4ef2d0 | 2021-04-20 13:36:24 +0200 | [diff] [blame] | 826 | /// @param Level 1..height. The node to update after parent node changed. |
Andrew Scull | 5e1ddfa | 2018-08-14 10:06:54 +0100 | [diff] [blame] | 827 | void reset(unsigned Level) { |
| 828 | path[Level] = Entry(subtree(Level - 1), offset(Level)); |
| 829 | } |
| 830 | |
| 831 | /// push - Add entry to path. |
| 832 | /// @param Node Node to add, should be subtree(path.size()-1). |
| 833 | /// @param Offset Offset into Node. |
| 834 | void push(NodeRef Node, unsigned Offset) { |
| 835 | path.push_back(Entry(Node, Offset)); |
| 836 | } |
| 837 | |
| 838 | /// pop - Remove the last path entry. |
| 839 | void pop() { |
| 840 | path.pop_back(); |
| 841 | } |
| 842 | |
| 843 | /// setSize - Set the size of a node both in the path and in the tree. |
| 844 | /// @param Level 0..height. Note that setting the root size won't change |
| 845 | /// map->rootSize. |
| 846 | /// @param Size New node size. |
| 847 | void setSize(unsigned Level, unsigned Size) { |
| 848 | path[Level].size = Size; |
| 849 | if (Level) |
| 850 | subtree(Level - 1).setSize(Size); |
| 851 | } |
| 852 | |
| 853 | /// setRoot - Clear the path and set a new root node. |
| 854 | /// @param Node New root node. |
| 855 | /// @param Size New root size. |
| 856 | /// @param Offset Offset into root node. |
| 857 | void setRoot(void *Node, unsigned Size, unsigned Offset) { |
| 858 | path.clear(); |
| 859 | path.push_back(Entry(Node, Size, Offset)); |
| 860 | } |
| 861 | |
| 862 | /// replaceRoot - Replace the current root node with two new entries after the |
| 863 | /// tree height has increased. |
| 864 | /// @param Root The new root node. |
| 865 | /// @param Size Number of entries in the new root. |
| 866 | /// @param Offsets Offsets into the root and first branch nodes. |
| 867 | void replaceRoot(void *Root, unsigned Size, IdxPair Offsets); |
| 868 | |
| 869 | /// getLeftSibling - Get the left sibling node at Level, or a null NodeRef. |
| 870 | /// @param Level Get the sibling to node(Level). |
| 871 | /// @return Left sibling, or NodeRef(). |
| 872 | NodeRef getLeftSibling(unsigned Level) const; |
| 873 | |
| 874 | /// moveLeft - Move path to the left sibling at Level. Leave nodes below Level |
| 875 | /// unaltered. |
| 876 | /// @param Level Move node(Level). |
| 877 | void moveLeft(unsigned Level); |
| 878 | |
| 879 | /// fillLeft - Grow path to Height by taking leftmost branches. |
| 880 | /// @param Height The target height. |
| 881 | void fillLeft(unsigned Height) { |
| 882 | while (height() < Height) |
| 883 | push(subtree(height()), 0); |
| 884 | } |
| 885 | |
| 886 | /// getLeftSibling - Get the left sibling node at Level, or a null NodeRef. |
Olivier Deprez | f4ef2d0 | 2021-04-20 13:36:24 +0200 | [diff] [blame] | 887 | /// @param Level Get the sibling to node(Level). |
Andrew Scull | 5e1ddfa | 2018-08-14 10:06:54 +0100 | [diff] [blame] | 888 | /// @return Left sibling, or NodeRef(). |
| 889 | NodeRef getRightSibling(unsigned Level) const; |
| 890 | |
| 891 | /// moveRight - Move path to the left sibling at Level. Leave nodes below |
| 892 | /// Level unaltered. |
| 893 | /// @param Level Move node(Level). |
| 894 | void moveRight(unsigned Level); |
| 895 | |
| 896 | /// atBegin - Return true if path is at begin(). |
| 897 | bool atBegin() const { |
| 898 | for (unsigned i = 0, e = path.size(); i != e; ++i) |
| 899 | if (path[i].offset != 0) |
| 900 | return false; |
| 901 | return true; |
| 902 | } |
| 903 | |
| 904 | /// atLastEntry - Return true if the path is at the last entry of the node at |
| 905 | /// Level. |
| 906 | /// @param Level Node to examine. |
| 907 | bool atLastEntry(unsigned Level) const { |
| 908 | return path[Level].offset == path[Level].size - 1; |
| 909 | } |
| 910 | |
| 911 | /// legalizeForInsert - Prepare the path for an insertion at Level. When the |
| 912 | /// path is at end(), node(Level) may not be a legal node. legalizeForInsert |
| 913 | /// ensures that node(Level) is real by moving back to the last node at Level, |
| 914 | /// and setting offset(Level) to size(Level) if required. |
| 915 | /// @param Level The level where an insertion is about to take place. |
| 916 | void legalizeForInsert(unsigned Level) { |
| 917 | if (valid()) |
| 918 | return; |
| 919 | moveLeft(Level); |
| 920 | ++path[Level].offset; |
| 921 | } |
| 922 | }; |
| 923 | |
| 924 | } // end namespace IntervalMapImpl |
| 925 | |
| 926 | //===----------------------------------------------------------------------===// |
| 927 | //--- IntervalMap ----// |
| 928 | //===----------------------------------------------------------------------===// |
| 929 | |
| 930 | template <typename KeyT, typename ValT, |
| 931 | unsigned N = IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize, |
| 932 | typename Traits = IntervalMapInfo<KeyT>> |
| 933 | class IntervalMap { |
| 934 | using Sizer = IntervalMapImpl::NodeSizer<KeyT, ValT>; |
| 935 | using Leaf = IntervalMapImpl::LeafNode<KeyT, ValT, Sizer::LeafSize, Traits>; |
| 936 | using Branch = |
| 937 | IntervalMapImpl::BranchNode<KeyT, ValT, Sizer::BranchSize, Traits>; |
| 938 | using RootLeaf = IntervalMapImpl::LeafNode<KeyT, ValT, N, Traits>; |
| 939 | using IdxPair = IntervalMapImpl::IdxPair; |
| 940 | |
| 941 | // The RootLeaf capacity is given as a template parameter. We must compute the |
| 942 | // corresponding RootBranch capacity. |
| 943 | enum { |
| 944 | DesiredRootBranchCap = (sizeof(RootLeaf) - sizeof(KeyT)) / |
| 945 | (sizeof(KeyT) + sizeof(IntervalMapImpl::NodeRef)), |
| 946 | RootBranchCap = DesiredRootBranchCap ? DesiredRootBranchCap : 1 |
| 947 | }; |
| 948 | |
| 949 | using RootBranch = |
| 950 | IntervalMapImpl::BranchNode<KeyT, ValT, RootBranchCap, Traits>; |
| 951 | |
| 952 | // When branched, we store a global start key as well as the branch node. |
| 953 | struct RootBranchData { |
| 954 | KeyT start; |
| 955 | RootBranch node; |
| 956 | }; |
| 957 | |
| 958 | public: |
| 959 | using Allocator = typename Sizer::Allocator; |
| 960 | using KeyType = KeyT; |
| 961 | using ValueType = ValT; |
| 962 | using KeyTraits = Traits; |
| 963 | |
| 964 | private: |
| 965 | // The root data is either a RootLeaf or a RootBranchData instance. |
| 966 | AlignedCharArrayUnion<RootLeaf, RootBranchData> data; |
| 967 | |
| 968 | // Tree height. |
| 969 | // 0: Leaves in root. |
| 970 | // 1: Root points to leaf. |
| 971 | // 2: root->branch->leaf ... |
| 972 | unsigned height; |
| 973 | |
| 974 | // Number of entries in the root node. |
| 975 | unsigned rootSize; |
| 976 | |
| 977 | // Allocator used for creating external nodes. |
| 978 | Allocator &allocator; |
| 979 | |
Andrew Scull | 0372a57 | 2018-11-16 15:47:06 +0000 | [diff] [blame] | 980 | /// Represent data as a node type without breaking aliasing rules. |
Olivier Deprez | f4ef2d0 | 2021-04-20 13:36:24 +0200 | [diff] [blame] | 981 | template <typename T> T &dataAs() const { return *bit_cast<T *>(&data); } |
Andrew Scull | 5e1ddfa | 2018-08-14 10:06:54 +0100 | [diff] [blame] | 982 | |
| 983 | const RootLeaf &rootLeaf() const { |
| 984 | assert(!branched() && "Cannot acces leaf data in branched root"); |
| 985 | return dataAs<RootLeaf>(); |
| 986 | } |
| 987 | RootLeaf &rootLeaf() { |
| 988 | assert(!branched() && "Cannot acces leaf data in branched root"); |
| 989 | return dataAs<RootLeaf>(); |
| 990 | } |
| 991 | |
| 992 | RootBranchData &rootBranchData() const { |
| 993 | assert(branched() && "Cannot access branch data in non-branched root"); |
| 994 | return dataAs<RootBranchData>(); |
| 995 | } |
| 996 | RootBranchData &rootBranchData() { |
| 997 | assert(branched() && "Cannot access branch data in non-branched root"); |
| 998 | return dataAs<RootBranchData>(); |
| 999 | } |
| 1000 | |
| 1001 | const RootBranch &rootBranch() const { return rootBranchData().node; } |
| 1002 | RootBranch &rootBranch() { return rootBranchData().node; } |
| 1003 | KeyT rootBranchStart() const { return rootBranchData().start; } |
| 1004 | KeyT &rootBranchStart() { return rootBranchData().start; } |
| 1005 | |
| 1006 | template <typename NodeT> NodeT *newNode() { |
| 1007 | return new(allocator.template Allocate<NodeT>()) NodeT(); |
| 1008 | } |
| 1009 | |
| 1010 | template <typename NodeT> void deleteNode(NodeT *P) { |
| 1011 | P->~NodeT(); |
| 1012 | allocator.Deallocate(P); |
| 1013 | } |
| 1014 | |
| 1015 | IdxPair branchRoot(unsigned Position); |
| 1016 | IdxPair splitRoot(unsigned Position); |
| 1017 | |
| 1018 | void switchRootToBranch() { |
| 1019 | rootLeaf().~RootLeaf(); |
| 1020 | height = 1; |
| 1021 | new (&rootBranchData()) RootBranchData(); |
| 1022 | } |
| 1023 | |
| 1024 | void switchRootToLeaf() { |
| 1025 | rootBranchData().~RootBranchData(); |
| 1026 | height = 0; |
| 1027 | new(&rootLeaf()) RootLeaf(); |
| 1028 | } |
| 1029 | |
| 1030 | bool branched() const { return height > 0; } |
| 1031 | |
| 1032 | ValT treeSafeLookup(KeyT x, ValT NotFound) const; |
| 1033 | void visitNodes(void (IntervalMap::*f)(IntervalMapImpl::NodeRef, |
| 1034 | unsigned Level)); |
| 1035 | void deleteNode(IntervalMapImpl::NodeRef Node, unsigned Level); |
| 1036 | |
| 1037 | public: |
| 1038 | explicit IntervalMap(Allocator &a) : height(0), rootSize(0), allocator(a) { |
Olivier Deprez | f4ef2d0 | 2021-04-20 13:36:24 +0200 | [diff] [blame] | 1039 | assert((uintptr_t(&data) & (alignof(RootLeaf) - 1)) == 0 && |
Andrew Scull | 5e1ddfa | 2018-08-14 10:06:54 +0100 | [diff] [blame] | 1040 | "Insufficient alignment"); |
| 1041 | new(&rootLeaf()) RootLeaf(); |
| 1042 | } |
| 1043 | |
| 1044 | ~IntervalMap() { |
| 1045 | clear(); |
| 1046 | rootLeaf().~RootLeaf(); |
| 1047 | } |
| 1048 | |
| 1049 | /// empty - Return true when no intervals are mapped. |
| 1050 | bool empty() const { |
| 1051 | return rootSize == 0; |
| 1052 | } |
| 1053 | |
| 1054 | /// start - Return the smallest mapped key in a non-empty map. |
| 1055 | KeyT start() const { |
| 1056 | assert(!empty() && "Empty IntervalMap has no start"); |
| 1057 | return !branched() ? rootLeaf().start(0) : rootBranchStart(); |
| 1058 | } |
| 1059 | |
| 1060 | /// stop - Return the largest mapped key in a non-empty map. |
| 1061 | KeyT stop() const { |
| 1062 | assert(!empty() && "Empty IntervalMap has no stop"); |
| 1063 | return !branched() ? rootLeaf().stop(rootSize - 1) : |
| 1064 | rootBranch().stop(rootSize - 1); |
| 1065 | } |
| 1066 | |
| 1067 | /// lookup - Return the mapped value at x or NotFound. |
| 1068 | ValT lookup(KeyT x, ValT NotFound = ValT()) const { |
| 1069 | if (empty() || Traits::startLess(x, start()) || Traits::stopLess(stop(), x)) |
| 1070 | return NotFound; |
| 1071 | return branched() ? treeSafeLookup(x, NotFound) : |
| 1072 | rootLeaf().safeLookup(x, NotFound); |
| 1073 | } |
| 1074 | |
| 1075 | /// insert - Add a mapping of [a;b] to y, coalesce with adjacent intervals. |
| 1076 | /// It is assumed that no key in the interval is mapped to another value, but |
| 1077 | /// overlapping intervals already mapped to y will be coalesced. |
| 1078 | void insert(KeyT a, KeyT b, ValT y) { |
| 1079 | if (branched() || rootSize == RootLeaf::Capacity) |
| 1080 | return find(a).insert(a, b, y); |
| 1081 | |
| 1082 | // Easy insert into root leaf. |
| 1083 | unsigned p = rootLeaf().findFrom(0, rootSize, a); |
| 1084 | rootSize = rootLeaf().insertFrom(p, rootSize, a, b, y); |
| 1085 | } |
| 1086 | |
| 1087 | /// clear - Remove all entries. |
| 1088 | void clear(); |
| 1089 | |
| 1090 | class const_iterator; |
| 1091 | class iterator; |
| 1092 | friend class const_iterator; |
| 1093 | friend class iterator; |
| 1094 | |
| 1095 | const_iterator begin() const { |
| 1096 | const_iterator I(*this); |
| 1097 | I.goToBegin(); |
| 1098 | return I; |
| 1099 | } |
| 1100 | |
| 1101 | iterator begin() { |
| 1102 | iterator I(*this); |
| 1103 | I.goToBegin(); |
| 1104 | return I; |
| 1105 | } |
| 1106 | |
| 1107 | const_iterator end() const { |
| 1108 | const_iterator I(*this); |
| 1109 | I.goToEnd(); |
| 1110 | return I; |
| 1111 | } |
| 1112 | |
| 1113 | iterator end() { |
| 1114 | iterator I(*this); |
| 1115 | I.goToEnd(); |
| 1116 | return I; |
| 1117 | } |
| 1118 | |
| 1119 | /// find - Return an iterator pointing to the first interval ending at or |
| 1120 | /// after x, or end(). |
| 1121 | const_iterator find(KeyT x) const { |
| 1122 | const_iterator I(*this); |
| 1123 | I.find(x); |
| 1124 | return I; |
| 1125 | } |
| 1126 | |
| 1127 | iterator find(KeyT x) { |
| 1128 | iterator I(*this); |
| 1129 | I.find(x); |
| 1130 | return I; |
| 1131 | } |
Andrew Walbran | 16937d0 | 2019-10-22 13:54:20 +0100 | [diff] [blame] | 1132 | |
| 1133 | /// overlaps(a, b) - Return true if the intervals in this map overlap with the |
| 1134 | /// interval [a;b]. |
| 1135 | bool overlaps(KeyT a, KeyT b) { |
| 1136 | assert(Traits::nonEmpty(a, b)); |
| 1137 | const_iterator I = find(a); |
| 1138 | if (!I.valid()) |
| 1139 | return false; |
| 1140 | // [a;b] and [x;y] overlap iff x<=b and a<=y. The find() call guarantees the |
| 1141 | // second part (y = find(a).stop()), so it is sufficient to check the first |
| 1142 | // one. |
| 1143 | return !Traits::stopLess(b, I.start()); |
| 1144 | } |
Andrew Scull | 5e1ddfa | 2018-08-14 10:06:54 +0100 | [diff] [blame] | 1145 | }; |
| 1146 | |
| 1147 | /// treeSafeLookup - Return the mapped value at x or NotFound, assuming a |
| 1148 | /// branched root. |
| 1149 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1150 | ValT IntervalMap<KeyT, ValT, N, Traits>:: |
| 1151 | treeSafeLookup(KeyT x, ValT NotFound) const { |
| 1152 | assert(branched() && "treeLookup assumes a branched root"); |
| 1153 | |
| 1154 | IntervalMapImpl::NodeRef NR = rootBranch().safeLookup(x); |
| 1155 | for (unsigned h = height-1; h; --h) |
| 1156 | NR = NR.get<Branch>().safeLookup(x); |
| 1157 | return NR.get<Leaf>().safeLookup(x, NotFound); |
| 1158 | } |
| 1159 | |
| 1160 | // branchRoot - Switch from a leaf root to a branched root. |
| 1161 | // Return the new (root offset, node offset) corresponding to Position. |
| 1162 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1163 | IntervalMapImpl::IdxPair IntervalMap<KeyT, ValT, N, Traits>:: |
| 1164 | branchRoot(unsigned Position) { |
| 1165 | using namespace IntervalMapImpl; |
| 1166 | // How many external leaf nodes to hold RootLeaf+1? |
| 1167 | const unsigned Nodes = RootLeaf::Capacity / Leaf::Capacity + 1; |
| 1168 | |
| 1169 | // Compute element distribution among new nodes. |
| 1170 | unsigned size[Nodes]; |
| 1171 | IdxPair NewOffset(0, Position); |
| 1172 | |
| 1173 | // Is is very common for the root node to be smaller than external nodes. |
| 1174 | if (Nodes == 1) |
| 1175 | size[0] = rootSize; |
| 1176 | else |
| 1177 | NewOffset = distribute(Nodes, rootSize, Leaf::Capacity, nullptr, size, |
| 1178 | Position, true); |
| 1179 | |
| 1180 | // Allocate new nodes. |
| 1181 | unsigned pos = 0; |
| 1182 | NodeRef node[Nodes]; |
| 1183 | for (unsigned n = 0; n != Nodes; ++n) { |
| 1184 | Leaf *L = newNode<Leaf>(); |
| 1185 | L->copy(rootLeaf(), pos, 0, size[n]); |
| 1186 | node[n] = NodeRef(L, size[n]); |
| 1187 | pos += size[n]; |
| 1188 | } |
| 1189 | |
| 1190 | // Destroy the old leaf node, construct branch node instead. |
| 1191 | switchRootToBranch(); |
| 1192 | for (unsigned n = 0; n != Nodes; ++n) { |
| 1193 | rootBranch().stop(n) = node[n].template get<Leaf>().stop(size[n]-1); |
| 1194 | rootBranch().subtree(n) = node[n]; |
| 1195 | } |
| 1196 | rootBranchStart() = node[0].template get<Leaf>().start(0); |
| 1197 | rootSize = Nodes; |
| 1198 | return NewOffset; |
| 1199 | } |
| 1200 | |
| 1201 | // splitRoot - Split the current BranchRoot into multiple Branch nodes. |
| 1202 | // Return the new (root offset, node offset) corresponding to Position. |
| 1203 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1204 | IntervalMapImpl::IdxPair IntervalMap<KeyT, ValT, N, Traits>:: |
| 1205 | splitRoot(unsigned Position) { |
| 1206 | using namespace IntervalMapImpl; |
| 1207 | // How many external leaf nodes to hold RootBranch+1? |
| 1208 | const unsigned Nodes = RootBranch::Capacity / Branch::Capacity + 1; |
| 1209 | |
| 1210 | // Compute element distribution among new nodes. |
| 1211 | unsigned Size[Nodes]; |
| 1212 | IdxPair NewOffset(0, Position); |
| 1213 | |
| 1214 | // Is is very common for the root node to be smaller than external nodes. |
| 1215 | if (Nodes == 1) |
| 1216 | Size[0] = rootSize; |
| 1217 | else |
| 1218 | NewOffset = distribute(Nodes, rootSize, Leaf::Capacity, nullptr, Size, |
| 1219 | Position, true); |
| 1220 | |
| 1221 | // Allocate new nodes. |
| 1222 | unsigned Pos = 0; |
| 1223 | NodeRef Node[Nodes]; |
| 1224 | for (unsigned n = 0; n != Nodes; ++n) { |
| 1225 | Branch *B = newNode<Branch>(); |
| 1226 | B->copy(rootBranch(), Pos, 0, Size[n]); |
| 1227 | Node[n] = NodeRef(B, Size[n]); |
| 1228 | Pos += Size[n]; |
| 1229 | } |
| 1230 | |
| 1231 | for (unsigned n = 0; n != Nodes; ++n) { |
| 1232 | rootBranch().stop(n) = Node[n].template get<Branch>().stop(Size[n]-1); |
| 1233 | rootBranch().subtree(n) = Node[n]; |
| 1234 | } |
| 1235 | rootSize = Nodes; |
| 1236 | ++height; |
| 1237 | return NewOffset; |
| 1238 | } |
| 1239 | |
| 1240 | /// visitNodes - Visit each external node. |
| 1241 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1242 | void IntervalMap<KeyT, ValT, N, Traits>:: |
| 1243 | visitNodes(void (IntervalMap::*f)(IntervalMapImpl::NodeRef, unsigned Height)) { |
| 1244 | if (!branched()) |
| 1245 | return; |
| 1246 | SmallVector<IntervalMapImpl::NodeRef, 4> Refs, NextRefs; |
| 1247 | |
| 1248 | // Collect level 0 nodes from the root. |
| 1249 | for (unsigned i = 0; i != rootSize; ++i) |
| 1250 | Refs.push_back(rootBranch().subtree(i)); |
| 1251 | |
| 1252 | // Visit all branch nodes. |
| 1253 | for (unsigned h = height - 1; h; --h) { |
| 1254 | for (unsigned i = 0, e = Refs.size(); i != e; ++i) { |
| 1255 | for (unsigned j = 0, s = Refs[i].size(); j != s; ++j) |
| 1256 | NextRefs.push_back(Refs[i].subtree(j)); |
| 1257 | (this->*f)(Refs[i], h); |
| 1258 | } |
| 1259 | Refs.clear(); |
| 1260 | Refs.swap(NextRefs); |
| 1261 | } |
| 1262 | |
| 1263 | // Visit all leaf nodes. |
| 1264 | for (unsigned i = 0, e = Refs.size(); i != e; ++i) |
| 1265 | (this->*f)(Refs[i], 0); |
| 1266 | } |
| 1267 | |
| 1268 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1269 | void IntervalMap<KeyT, ValT, N, Traits>:: |
| 1270 | deleteNode(IntervalMapImpl::NodeRef Node, unsigned Level) { |
| 1271 | if (Level) |
| 1272 | deleteNode(&Node.get<Branch>()); |
| 1273 | else |
| 1274 | deleteNode(&Node.get<Leaf>()); |
| 1275 | } |
| 1276 | |
| 1277 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1278 | void IntervalMap<KeyT, ValT, N, Traits>:: |
| 1279 | clear() { |
| 1280 | if (branched()) { |
| 1281 | visitNodes(&IntervalMap::deleteNode); |
| 1282 | switchRootToLeaf(); |
| 1283 | } |
| 1284 | rootSize = 0; |
| 1285 | } |
| 1286 | |
| 1287 | //===----------------------------------------------------------------------===// |
| 1288 | //--- IntervalMap::const_iterator ----// |
| 1289 | //===----------------------------------------------------------------------===// |
| 1290 | |
| 1291 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1292 | class IntervalMap<KeyT, ValT, N, Traits>::const_iterator : |
| 1293 | public std::iterator<std::bidirectional_iterator_tag, ValT> { |
| 1294 | |
| 1295 | protected: |
| 1296 | friend class IntervalMap; |
| 1297 | |
| 1298 | // The map referred to. |
| 1299 | IntervalMap *map = nullptr; |
| 1300 | |
| 1301 | // We store a full path from the root to the current position. |
| 1302 | // The path may be partially filled, but never between iterator calls. |
| 1303 | IntervalMapImpl::Path path; |
| 1304 | |
| 1305 | explicit const_iterator(const IntervalMap &map) : |
| 1306 | map(const_cast<IntervalMap*>(&map)) {} |
| 1307 | |
| 1308 | bool branched() const { |
| 1309 | assert(map && "Invalid iterator"); |
| 1310 | return map->branched(); |
| 1311 | } |
| 1312 | |
| 1313 | void setRoot(unsigned Offset) { |
| 1314 | if (branched()) |
| 1315 | path.setRoot(&map->rootBranch(), map->rootSize, Offset); |
| 1316 | else |
| 1317 | path.setRoot(&map->rootLeaf(), map->rootSize, Offset); |
| 1318 | } |
| 1319 | |
| 1320 | void pathFillFind(KeyT x); |
| 1321 | void treeFind(KeyT x); |
| 1322 | void treeAdvanceTo(KeyT x); |
| 1323 | |
| 1324 | /// unsafeStart - Writable access to start() for iterator. |
| 1325 | KeyT &unsafeStart() const { |
| 1326 | assert(valid() && "Cannot access invalid iterator"); |
| 1327 | return branched() ? path.leaf<Leaf>().start(path.leafOffset()) : |
| 1328 | path.leaf<RootLeaf>().start(path.leafOffset()); |
| 1329 | } |
| 1330 | |
| 1331 | /// unsafeStop - Writable access to stop() for iterator. |
| 1332 | KeyT &unsafeStop() const { |
| 1333 | assert(valid() && "Cannot access invalid iterator"); |
| 1334 | return branched() ? path.leaf<Leaf>().stop(path.leafOffset()) : |
| 1335 | path.leaf<RootLeaf>().stop(path.leafOffset()); |
| 1336 | } |
| 1337 | |
| 1338 | /// unsafeValue - Writable access to value() for iterator. |
| 1339 | ValT &unsafeValue() const { |
| 1340 | assert(valid() && "Cannot access invalid iterator"); |
| 1341 | return branched() ? path.leaf<Leaf>().value(path.leafOffset()) : |
| 1342 | path.leaf<RootLeaf>().value(path.leafOffset()); |
| 1343 | } |
| 1344 | |
| 1345 | public: |
| 1346 | /// const_iterator - Create an iterator that isn't pointing anywhere. |
| 1347 | const_iterator() = default; |
| 1348 | |
| 1349 | /// setMap - Change the map iterated over. This call must be followed by a |
| 1350 | /// call to goToBegin(), goToEnd(), or find() |
| 1351 | void setMap(const IntervalMap &m) { map = const_cast<IntervalMap*>(&m); } |
| 1352 | |
| 1353 | /// valid - Return true if the current position is valid, false for end(). |
| 1354 | bool valid() const { return path.valid(); } |
| 1355 | |
| 1356 | /// atBegin - Return true if the current position is the first map entry. |
| 1357 | bool atBegin() const { return path.atBegin(); } |
| 1358 | |
| 1359 | /// start - Return the beginning of the current interval. |
| 1360 | const KeyT &start() const { return unsafeStart(); } |
| 1361 | |
| 1362 | /// stop - Return the end of the current interval. |
| 1363 | const KeyT &stop() const { return unsafeStop(); } |
| 1364 | |
| 1365 | /// value - Return the mapped value at the current interval. |
| 1366 | const ValT &value() const { return unsafeValue(); } |
| 1367 | |
| 1368 | const ValT &operator*() const { return value(); } |
| 1369 | |
| 1370 | bool operator==(const const_iterator &RHS) const { |
| 1371 | assert(map == RHS.map && "Cannot compare iterators from different maps"); |
| 1372 | if (!valid()) |
| 1373 | return !RHS.valid(); |
| 1374 | if (path.leafOffset() != RHS.path.leafOffset()) |
| 1375 | return false; |
| 1376 | return &path.template leaf<Leaf>() == &RHS.path.template leaf<Leaf>(); |
| 1377 | } |
| 1378 | |
| 1379 | bool operator!=(const const_iterator &RHS) const { |
| 1380 | return !operator==(RHS); |
| 1381 | } |
| 1382 | |
| 1383 | /// goToBegin - Move to the first interval in map. |
| 1384 | void goToBegin() { |
| 1385 | setRoot(0); |
| 1386 | if (branched()) |
| 1387 | path.fillLeft(map->height); |
| 1388 | } |
| 1389 | |
| 1390 | /// goToEnd - Move beyond the last interval in map. |
| 1391 | void goToEnd() { |
| 1392 | setRoot(map->rootSize); |
| 1393 | } |
| 1394 | |
Olivier Deprez | f4ef2d0 | 2021-04-20 13:36:24 +0200 | [diff] [blame] | 1395 | /// preincrement - Move to the next interval. |
Andrew Scull | 5e1ddfa | 2018-08-14 10:06:54 +0100 | [diff] [blame] | 1396 | const_iterator &operator++() { |
| 1397 | assert(valid() && "Cannot increment end()"); |
| 1398 | if (++path.leafOffset() == path.leafSize() && branched()) |
| 1399 | path.moveRight(map->height); |
| 1400 | return *this; |
| 1401 | } |
| 1402 | |
Olivier Deprez | f4ef2d0 | 2021-04-20 13:36:24 +0200 | [diff] [blame] | 1403 | /// postincrement - Don't do that! |
Andrew Scull | 5e1ddfa | 2018-08-14 10:06:54 +0100 | [diff] [blame] | 1404 | const_iterator operator++(int) { |
| 1405 | const_iterator tmp = *this; |
| 1406 | operator++(); |
| 1407 | return tmp; |
| 1408 | } |
| 1409 | |
Olivier Deprez | f4ef2d0 | 2021-04-20 13:36:24 +0200 | [diff] [blame] | 1410 | /// predecrement - Move to the previous interval. |
Andrew Scull | 5e1ddfa | 2018-08-14 10:06:54 +0100 | [diff] [blame] | 1411 | const_iterator &operator--() { |
| 1412 | if (path.leafOffset() && (valid() || !branched())) |
| 1413 | --path.leafOffset(); |
| 1414 | else |
| 1415 | path.moveLeft(map->height); |
| 1416 | return *this; |
| 1417 | } |
| 1418 | |
Olivier Deprez | f4ef2d0 | 2021-04-20 13:36:24 +0200 | [diff] [blame] | 1419 | /// postdecrement - Don't do that! |
Andrew Scull | 5e1ddfa | 2018-08-14 10:06:54 +0100 | [diff] [blame] | 1420 | const_iterator operator--(int) { |
| 1421 | const_iterator tmp = *this; |
| 1422 | operator--(); |
| 1423 | return tmp; |
| 1424 | } |
| 1425 | |
| 1426 | /// find - Move to the first interval with stop >= x, or end(). |
| 1427 | /// This is a full search from the root, the current position is ignored. |
| 1428 | void find(KeyT x) { |
| 1429 | if (branched()) |
| 1430 | treeFind(x); |
| 1431 | else |
| 1432 | setRoot(map->rootLeaf().findFrom(0, map->rootSize, x)); |
| 1433 | } |
| 1434 | |
| 1435 | /// advanceTo - Move to the first interval with stop >= x, or end(). |
| 1436 | /// The search is started from the current position, and no earlier positions |
| 1437 | /// can be found. This is much faster than find() for small moves. |
| 1438 | void advanceTo(KeyT x) { |
| 1439 | if (!valid()) |
| 1440 | return; |
| 1441 | if (branched()) |
| 1442 | treeAdvanceTo(x); |
| 1443 | else |
| 1444 | path.leafOffset() = |
| 1445 | map->rootLeaf().findFrom(path.leafOffset(), map->rootSize, x); |
| 1446 | } |
| 1447 | }; |
| 1448 | |
| 1449 | /// pathFillFind - Complete path by searching for x. |
| 1450 | /// @param x Key to search for. |
| 1451 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1452 | void IntervalMap<KeyT, ValT, N, Traits>:: |
| 1453 | const_iterator::pathFillFind(KeyT x) { |
| 1454 | IntervalMapImpl::NodeRef NR = path.subtree(path.height()); |
| 1455 | for (unsigned i = map->height - path.height() - 1; i; --i) { |
| 1456 | unsigned p = NR.get<Branch>().safeFind(0, x); |
| 1457 | path.push(NR, p); |
| 1458 | NR = NR.subtree(p); |
| 1459 | } |
| 1460 | path.push(NR, NR.get<Leaf>().safeFind(0, x)); |
| 1461 | } |
| 1462 | |
| 1463 | /// treeFind - Find in a branched tree. |
| 1464 | /// @param x Key to search for. |
| 1465 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1466 | void IntervalMap<KeyT, ValT, N, Traits>:: |
| 1467 | const_iterator::treeFind(KeyT x) { |
| 1468 | setRoot(map->rootBranch().findFrom(0, map->rootSize, x)); |
| 1469 | if (valid()) |
| 1470 | pathFillFind(x); |
| 1471 | } |
| 1472 | |
| 1473 | /// treeAdvanceTo - Find position after the current one. |
| 1474 | /// @param x Key to search for. |
| 1475 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1476 | void IntervalMap<KeyT, ValT, N, Traits>:: |
| 1477 | const_iterator::treeAdvanceTo(KeyT x) { |
| 1478 | // Can we stay on the same leaf node? |
| 1479 | if (!Traits::stopLess(path.leaf<Leaf>().stop(path.leafSize() - 1), x)) { |
| 1480 | path.leafOffset() = path.leaf<Leaf>().safeFind(path.leafOffset(), x); |
| 1481 | return; |
| 1482 | } |
| 1483 | |
| 1484 | // Drop the current leaf. |
| 1485 | path.pop(); |
| 1486 | |
| 1487 | // Search towards the root for a usable subtree. |
| 1488 | if (path.height()) { |
| 1489 | for (unsigned l = path.height() - 1; l; --l) { |
| 1490 | if (!Traits::stopLess(path.node<Branch>(l).stop(path.offset(l)), x)) { |
| 1491 | // The branch node at l+1 is usable |
| 1492 | path.offset(l + 1) = |
| 1493 | path.node<Branch>(l + 1).safeFind(path.offset(l + 1), x); |
| 1494 | return pathFillFind(x); |
| 1495 | } |
| 1496 | path.pop(); |
| 1497 | } |
| 1498 | // Is the level-1 Branch usable? |
| 1499 | if (!Traits::stopLess(map->rootBranch().stop(path.offset(0)), x)) { |
| 1500 | path.offset(1) = path.node<Branch>(1).safeFind(path.offset(1), x); |
| 1501 | return pathFillFind(x); |
| 1502 | } |
| 1503 | } |
| 1504 | |
| 1505 | // We reached the root. |
| 1506 | setRoot(map->rootBranch().findFrom(path.offset(0), map->rootSize, x)); |
| 1507 | if (valid()) |
| 1508 | pathFillFind(x); |
| 1509 | } |
| 1510 | |
| 1511 | //===----------------------------------------------------------------------===// |
| 1512 | //--- IntervalMap::iterator ----// |
| 1513 | //===----------------------------------------------------------------------===// |
| 1514 | |
| 1515 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1516 | class IntervalMap<KeyT, ValT, N, Traits>::iterator : public const_iterator { |
| 1517 | friend class IntervalMap; |
| 1518 | |
| 1519 | using IdxPair = IntervalMapImpl::IdxPair; |
| 1520 | |
| 1521 | explicit iterator(IntervalMap &map) : const_iterator(map) {} |
| 1522 | |
| 1523 | void setNodeStop(unsigned Level, KeyT Stop); |
| 1524 | bool insertNode(unsigned Level, IntervalMapImpl::NodeRef Node, KeyT Stop); |
| 1525 | template <typename NodeT> bool overflow(unsigned Level); |
| 1526 | void treeInsert(KeyT a, KeyT b, ValT y); |
| 1527 | void eraseNode(unsigned Level); |
| 1528 | void treeErase(bool UpdateRoot = true); |
| 1529 | bool canCoalesceLeft(KeyT Start, ValT x); |
| 1530 | bool canCoalesceRight(KeyT Stop, ValT x); |
| 1531 | |
| 1532 | public: |
| 1533 | /// iterator - Create null iterator. |
| 1534 | iterator() = default; |
| 1535 | |
| 1536 | /// setStart - Move the start of the current interval. |
| 1537 | /// This may cause coalescing with the previous interval. |
| 1538 | /// @param a New start key, must not overlap the previous interval. |
| 1539 | void setStart(KeyT a); |
| 1540 | |
| 1541 | /// setStop - Move the end of the current interval. |
| 1542 | /// This may cause coalescing with the following interval. |
| 1543 | /// @param b New stop key, must not overlap the following interval. |
| 1544 | void setStop(KeyT b); |
| 1545 | |
| 1546 | /// setValue - Change the mapped value of the current interval. |
| 1547 | /// This may cause coalescing with the previous and following intervals. |
| 1548 | /// @param x New value. |
| 1549 | void setValue(ValT x); |
| 1550 | |
| 1551 | /// setStartUnchecked - Move the start of the current interval without |
| 1552 | /// checking for coalescing or overlaps. |
| 1553 | /// This should only be used when it is known that coalescing is not required. |
| 1554 | /// @param a New start key. |
| 1555 | void setStartUnchecked(KeyT a) { this->unsafeStart() = a; } |
| 1556 | |
| 1557 | /// setStopUnchecked - Move the end of the current interval without checking |
| 1558 | /// for coalescing or overlaps. |
| 1559 | /// This should only be used when it is known that coalescing is not required. |
| 1560 | /// @param b New stop key. |
| 1561 | void setStopUnchecked(KeyT b) { |
| 1562 | this->unsafeStop() = b; |
| 1563 | // Update keys in branch nodes as well. |
| 1564 | if (this->path.atLastEntry(this->path.height())) |
| 1565 | setNodeStop(this->path.height(), b); |
| 1566 | } |
| 1567 | |
| 1568 | /// setValueUnchecked - Change the mapped value of the current interval |
| 1569 | /// without checking for coalescing. |
| 1570 | /// @param x New value. |
| 1571 | void setValueUnchecked(ValT x) { this->unsafeValue() = x; } |
| 1572 | |
| 1573 | /// insert - Insert mapping [a;b] -> y before the current position. |
| 1574 | void insert(KeyT a, KeyT b, ValT y); |
| 1575 | |
| 1576 | /// erase - Erase the current interval. |
| 1577 | void erase(); |
| 1578 | |
| 1579 | iterator &operator++() { |
| 1580 | const_iterator::operator++(); |
| 1581 | return *this; |
| 1582 | } |
| 1583 | |
| 1584 | iterator operator++(int) { |
| 1585 | iterator tmp = *this; |
| 1586 | operator++(); |
| 1587 | return tmp; |
| 1588 | } |
| 1589 | |
| 1590 | iterator &operator--() { |
| 1591 | const_iterator::operator--(); |
| 1592 | return *this; |
| 1593 | } |
| 1594 | |
| 1595 | iterator operator--(int) { |
| 1596 | iterator tmp = *this; |
| 1597 | operator--(); |
| 1598 | return tmp; |
| 1599 | } |
| 1600 | }; |
| 1601 | |
| 1602 | /// canCoalesceLeft - Can the current interval coalesce to the left after |
| 1603 | /// changing start or value? |
| 1604 | /// @param Start New start of current interval. |
| 1605 | /// @param Value New value for current interval. |
| 1606 | /// @return True when updating the current interval would enable coalescing. |
| 1607 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1608 | bool IntervalMap<KeyT, ValT, N, Traits>:: |
| 1609 | iterator::canCoalesceLeft(KeyT Start, ValT Value) { |
| 1610 | using namespace IntervalMapImpl; |
| 1611 | Path &P = this->path; |
| 1612 | if (!this->branched()) { |
| 1613 | unsigned i = P.leafOffset(); |
| 1614 | RootLeaf &Node = P.leaf<RootLeaf>(); |
| 1615 | return i && Node.value(i-1) == Value && |
| 1616 | Traits::adjacent(Node.stop(i-1), Start); |
| 1617 | } |
| 1618 | // Branched. |
| 1619 | if (unsigned i = P.leafOffset()) { |
| 1620 | Leaf &Node = P.leaf<Leaf>(); |
| 1621 | return Node.value(i-1) == Value && Traits::adjacent(Node.stop(i-1), Start); |
| 1622 | } else if (NodeRef NR = P.getLeftSibling(P.height())) { |
| 1623 | unsigned i = NR.size() - 1; |
| 1624 | Leaf &Node = NR.get<Leaf>(); |
| 1625 | return Node.value(i) == Value && Traits::adjacent(Node.stop(i), Start); |
| 1626 | } |
| 1627 | return false; |
| 1628 | } |
| 1629 | |
| 1630 | /// canCoalesceRight - Can the current interval coalesce to the right after |
| 1631 | /// changing stop or value? |
| 1632 | /// @param Stop New stop of current interval. |
| 1633 | /// @param Value New value for current interval. |
| 1634 | /// @return True when updating the current interval would enable coalescing. |
| 1635 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1636 | bool IntervalMap<KeyT, ValT, N, Traits>:: |
| 1637 | iterator::canCoalesceRight(KeyT Stop, ValT Value) { |
| 1638 | using namespace IntervalMapImpl; |
| 1639 | Path &P = this->path; |
| 1640 | unsigned i = P.leafOffset() + 1; |
| 1641 | if (!this->branched()) { |
| 1642 | if (i >= P.leafSize()) |
| 1643 | return false; |
| 1644 | RootLeaf &Node = P.leaf<RootLeaf>(); |
| 1645 | return Node.value(i) == Value && Traits::adjacent(Stop, Node.start(i)); |
| 1646 | } |
| 1647 | // Branched. |
| 1648 | if (i < P.leafSize()) { |
| 1649 | Leaf &Node = P.leaf<Leaf>(); |
| 1650 | return Node.value(i) == Value && Traits::adjacent(Stop, Node.start(i)); |
| 1651 | } else if (NodeRef NR = P.getRightSibling(P.height())) { |
| 1652 | Leaf &Node = NR.get<Leaf>(); |
| 1653 | return Node.value(0) == Value && Traits::adjacent(Stop, Node.start(0)); |
| 1654 | } |
| 1655 | return false; |
| 1656 | } |
| 1657 | |
| 1658 | /// setNodeStop - Update the stop key of the current node at level and above. |
| 1659 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1660 | void IntervalMap<KeyT, ValT, N, Traits>:: |
| 1661 | iterator::setNodeStop(unsigned Level, KeyT Stop) { |
| 1662 | // There are no references to the root node, so nothing to update. |
| 1663 | if (!Level) |
| 1664 | return; |
| 1665 | IntervalMapImpl::Path &P = this->path; |
| 1666 | // Update nodes pointing to the current node. |
| 1667 | while (--Level) { |
| 1668 | P.node<Branch>(Level).stop(P.offset(Level)) = Stop; |
| 1669 | if (!P.atLastEntry(Level)) |
| 1670 | return; |
| 1671 | } |
| 1672 | // Update root separately since it has a different layout. |
| 1673 | P.node<RootBranch>(Level).stop(P.offset(Level)) = Stop; |
| 1674 | } |
| 1675 | |
| 1676 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1677 | void IntervalMap<KeyT, ValT, N, Traits>:: |
| 1678 | iterator::setStart(KeyT a) { |
| 1679 | assert(Traits::nonEmpty(a, this->stop()) && "Cannot move start beyond stop"); |
| 1680 | KeyT &CurStart = this->unsafeStart(); |
| 1681 | if (!Traits::startLess(a, CurStart) || !canCoalesceLeft(a, this->value())) { |
| 1682 | CurStart = a; |
| 1683 | return; |
| 1684 | } |
| 1685 | // Coalesce with the interval to the left. |
| 1686 | --*this; |
| 1687 | a = this->start(); |
| 1688 | erase(); |
| 1689 | setStartUnchecked(a); |
| 1690 | } |
| 1691 | |
| 1692 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1693 | void IntervalMap<KeyT, ValT, N, Traits>:: |
| 1694 | iterator::setStop(KeyT b) { |
| 1695 | assert(Traits::nonEmpty(this->start(), b) && "Cannot move stop beyond start"); |
| 1696 | if (Traits::startLess(b, this->stop()) || |
| 1697 | !canCoalesceRight(b, this->value())) { |
| 1698 | setStopUnchecked(b); |
| 1699 | return; |
| 1700 | } |
| 1701 | // Coalesce with interval to the right. |
| 1702 | KeyT a = this->start(); |
| 1703 | erase(); |
| 1704 | setStartUnchecked(a); |
| 1705 | } |
| 1706 | |
| 1707 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1708 | void IntervalMap<KeyT, ValT, N, Traits>:: |
| 1709 | iterator::setValue(ValT x) { |
| 1710 | setValueUnchecked(x); |
| 1711 | if (canCoalesceRight(this->stop(), x)) { |
| 1712 | KeyT a = this->start(); |
| 1713 | erase(); |
| 1714 | setStartUnchecked(a); |
| 1715 | } |
| 1716 | if (canCoalesceLeft(this->start(), x)) { |
| 1717 | --*this; |
| 1718 | KeyT a = this->start(); |
| 1719 | erase(); |
| 1720 | setStartUnchecked(a); |
| 1721 | } |
| 1722 | } |
| 1723 | |
| 1724 | /// insertNode - insert a node before the current path at level. |
| 1725 | /// Leave the current path pointing at the new node. |
| 1726 | /// @param Level path index of the node to be inserted. |
| 1727 | /// @param Node The node to be inserted. |
| 1728 | /// @param Stop The last index in the new node. |
| 1729 | /// @return True if the tree height was increased. |
| 1730 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1731 | bool IntervalMap<KeyT, ValT, N, Traits>:: |
| 1732 | iterator::insertNode(unsigned Level, IntervalMapImpl::NodeRef Node, KeyT Stop) { |
| 1733 | assert(Level && "Cannot insert next to the root"); |
| 1734 | bool SplitRoot = false; |
| 1735 | IntervalMap &IM = *this->map; |
| 1736 | IntervalMapImpl::Path &P = this->path; |
| 1737 | |
| 1738 | if (Level == 1) { |
| 1739 | // Insert into the root branch node. |
| 1740 | if (IM.rootSize < RootBranch::Capacity) { |
| 1741 | IM.rootBranch().insert(P.offset(0), IM.rootSize, Node, Stop); |
| 1742 | P.setSize(0, ++IM.rootSize); |
| 1743 | P.reset(Level); |
| 1744 | return SplitRoot; |
| 1745 | } |
| 1746 | |
| 1747 | // We need to split the root while keeping our position. |
| 1748 | SplitRoot = true; |
| 1749 | IdxPair Offset = IM.splitRoot(P.offset(0)); |
| 1750 | P.replaceRoot(&IM.rootBranch(), IM.rootSize, Offset); |
| 1751 | |
| 1752 | // Fall through to insert at the new higher level. |
| 1753 | ++Level; |
| 1754 | } |
| 1755 | |
| 1756 | // When inserting before end(), make sure we have a valid path. |
| 1757 | P.legalizeForInsert(--Level); |
| 1758 | |
| 1759 | // Insert into the branch node at Level-1. |
| 1760 | if (P.size(Level) == Branch::Capacity) { |
| 1761 | // Branch node is full, handle handle the overflow. |
| 1762 | assert(!SplitRoot && "Cannot overflow after splitting the root"); |
| 1763 | SplitRoot = overflow<Branch>(Level); |
| 1764 | Level += SplitRoot; |
| 1765 | } |
| 1766 | P.node<Branch>(Level).insert(P.offset(Level), P.size(Level), Node, Stop); |
| 1767 | P.setSize(Level, P.size(Level) + 1); |
| 1768 | if (P.atLastEntry(Level)) |
| 1769 | setNodeStop(Level, Stop); |
| 1770 | P.reset(Level + 1); |
| 1771 | return SplitRoot; |
| 1772 | } |
| 1773 | |
| 1774 | // insert |
| 1775 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1776 | void IntervalMap<KeyT, ValT, N, Traits>:: |
| 1777 | iterator::insert(KeyT a, KeyT b, ValT y) { |
| 1778 | if (this->branched()) |
| 1779 | return treeInsert(a, b, y); |
| 1780 | IntervalMap &IM = *this->map; |
| 1781 | IntervalMapImpl::Path &P = this->path; |
| 1782 | |
| 1783 | // Try simple root leaf insert. |
| 1784 | unsigned Size = IM.rootLeaf().insertFrom(P.leafOffset(), IM.rootSize, a, b, y); |
| 1785 | |
| 1786 | // Was the root node insert successful? |
| 1787 | if (Size <= RootLeaf::Capacity) { |
| 1788 | P.setSize(0, IM.rootSize = Size); |
| 1789 | return; |
| 1790 | } |
| 1791 | |
| 1792 | // Root leaf node is full, we must branch. |
| 1793 | IdxPair Offset = IM.branchRoot(P.leafOffset()); |
| 1794 | P.replaceRoot(&IM.rootBranch(), IM.rootSize, Offset); |
| 1795 | |
| 1796 | // Now it fits in the new leaf. |
| 1797 | treeInsert(a, b, y); |
| 1798 | } |
| 1799 | |
| 1800 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1801 | void IntervalMap<KeyT, ValT, N, Traits>:: |
| 1802 | iterator::treeInsert(KeyT a, KeyT b, ValT y) { |
| 1803 | using namespace IntervalMapImpl; |
| 1804 | Path &P = this->path; |
| 1805 | |
| 1806 | if (!P.valid()) |
| 1807 | P.legalizeForInsert(this->map->height); |
| 1808 | |
| 1809 | // Check if this insertion will extend the node to the left. |
| 1810 | if (P.leafOffset() == 0 && Traits::startLess(a, P.leaf<Leaf>().start(0))) { |
| 1811 | // Node is growing to the left, will it affect a left sibling node? |
| 1812 | if (NodeRef Sib = P.getLeftSibling(P.height())) { |
| 1813 | Leaf &SibLeaf = Sib.get<Leaf>(); |
| 1814 | unsigned SibOfs = Sib.size() - 1; |
| 1815 | if (SibLeaf.value(SibOfs) == y && |
| 1816 | Traits::adjacent(SibLeaf.stop(SibOfs), a)) { |
| 1817 | // This insertion will coalesce with the last entry in SibLeaf. We can |
| 1818 | // handle it in two ways: |
| 1819 | // 1. Extend SibLeaf.stop to b and be done, or |
| 1820 | // 2. Extend a to SibLeaf, erase the SibLeaf entry and continue. |
| 1821 | // We prefer 1., but need 2 when coalescing to the right as well. |
| 1822 | Leaf &CurLeaf = P.leaf<Leaf>(); |
| 1823 | P.moveLeft(P.height()); |
| 1824 | if (Traits::stopLess(b, CurLeaf.start(0)) && |
| 1825 | (y != CurLeaf.value(0) || !Traits::adjacent(b, CurLeaf.start(0)))) { |
| 1826 | // Easy, just extend SibLeaf and we're done. |
| 1827 | setNodeStop(P.height(), SibLeaf.stop(SibOfs) = b); |
| 1828 | return; |
| 1829 | } else { |
| 1830 | // We have both left and right coalescing. Erase the old SibLeaf entry |
| 1831 | // and continue inserting the larger interval. |
| 1832 | a = SibLeaf.start(SibOfs); |
| 1833 | treeErase(/* UpdateRoot= */false); |
| 1834 | } |
| 1835 | } |
| 1836 | } else { |
| 1837 | // No left sibling means we are at begin(). Update cached bound. |
| 1838 | this->map->rootBranchStart() = a; |
| 1839 | } |
| 1840 | } |
| 1841 | |
| 1842 | // When we are inserting at the end of a leaf node, we must update stops. |
| 1843 | unsigned Size = P.leafSize(); |
| 1844 | bool Grow = P.leafOffset() == Size; |
| 1845 | Size = P.leaf<Leaf>().insertFrom(P.leafOffset(), Size, a, b, y); |
| 1846 | |
| 1847 | // Leaf insertion unsuccessful? Overflow and try again. |
| 1848 | if (Size > Leaf::Capacity) { |
| 1849 | overflow<Leaf>(P.height()); |
| 1850 | Grow = P.leafOffset() == P.leafSize(); |
| 1851 | Size = P.leaf<Leaf>().insertFrom(P.leafOffset(), P.leafSize(), a, b, y); |
| 1852 | assert(Size <= Leaf::Capacity && "overflow() didn't make room"); |
| 1853 | } |
| 1854 | |
| 1855 | // Inserted, update offset and leaf size. |
| 1856 | P.setSize(P.height(), Size); |
| 1857 | |
| 1858 | // Insert was the last node entry, update stops. |
| 1859 | if (Grow) |
| 1860 | setNodeStop(P.height(), b); |
| 1861 | } |
| 1862 | |
| 1863 | /// erase - erase the current interval and move to the next position. |
| 1864 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1865 | void IntervalMap<KeyT, ValT, N, Traits>:: |
| 1866 | iterator::erase() { |
| 1867 | IntervalMap &IM = *this->map; |
| 1868 | IntervalMapImpl::Path &P = this->path; |
| 1869 | assert(P.valid() && "Cannot erase end()"); |
| 1870 | if (this->branched()) |
| 1871 | return treeErase(); |
| 1872 | IM.rootLeaf().erase(P.leafOffset(), IM.rootSize); |
| 1873 | P.setSize(0, --IM.rootSize); |
| 1874 | } |
| 1875 | |
| 1876 | /// treeErase - erase() for a branched tree. |
| 1877 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1878 | void IntervalMap<KeyT, ValT, N, Traits>:: |
| 1879 | iterator::treeErase(bool UpdateRoot) { |
| 1880 | IntervalMap &IM = *this->map; |
| 1881 | IntervalMapImpl::Path &P = this->path; |
| 1882 | Leaf &Node = P.leaf<Leaf>(); |
| 1883 | |
| 1884 | // Nodes are not allowed to become empty. |
| 1885 | if (P.leafSize() == 1) { |
| 1886 | IM.deleteNode(&Node); |
| 1887 | eraseNode(IM.height); |
| 1888 | // Update rootBranchStart if we erased begin(). |
| 1889 | if (UpdateRoot && IM.branched() && P.valid() && P.atBegin()) |
| 1890 | IM.rootBranchStart() = P.leaf<Leaf>().start(0); |
| 1891 | return; |
| 1892 | } |
| 1893 | |
| 1894 | // Erase current entry. |
| 1895 | Node.erase(P.leafOffset(), P.leafSize()); |
| 1896 | unsigned NewSize = P.leafSize() - 1; |
| 1897 | P.setSize(IM.height, NewSize); |
| 1898 | // When we erase the last entry, update stop and move to a legal position. |
| 1899 | if (P.leafOffset() == NewSize) { |
| 1900 | setNodeStop(IM.height, Node.stop(NewSize - 1)); |
| 1901 | P.moveRight(IM.height); |
| 1902 | } else if (UpdateRoot && P.atBegin()) |
| 1903 | IM.rootBranchStart() = P.leaf<Leaf>().start(0); |
| 1904 | } |
| 1905 | |
| 1906 | /// eraseNode - Erase the current node at Level from its parent and move path to |
| 1907 | /// the first entry of the next sibling node. |
| 1908 | /// The node must be deallocated by the caller. |
| 1909 | /// @param Level 1..height, the root node cannot be erased. |
| 1910 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1911 | void IntervalMap<KeyT, ValT, N, Traits>:: |
| 1912 | iterator::eraseNode(unsigned Level) { |
| 1913 | assert(Level && "Cannot erase root node"); |
| 1914 | IntervalMap &IM = *this->map; |
| 1915 | IntervalMapImpl::Path &P = this->path; |
| 1916 | |
| 1917 | if (--Level == 0) { |
| 1918 | IM.rootBranch().erase(P.offset(0), IM.rootSize); |
| 1919 | P.setSize(0, --IM.rootSize); |
| 1920 | // If this cleared the root, switch to height=0. |
| 1921 | if (IM.empty()) { |
| 1922 | IM.switchRootToLeaf(); |
| 1923 | this->setRoot(0); |
| 1924 | return; |
| 1925 | } |
| 1926 | } else { |
| 1927 | // Remove node ref from branch node at Level. |
| 1928 | Branch &Parent = P.node<Branch>(Level); |
| 1929 | if (P.size(Level) == 1) { |
| 1930 | // Branch node became empty, remove it recursively. |
| 1931 | IM.deleteNode(&Parent); |
| 1932 | eraseNode(Level); |
| 1933 | } else { |
| 1934 | // Branch node won't become empty. |
| 1935 | Parent.erase(P.offset(Level), P.size(Level)); |
| 1936 | unsigned NewSize = P.size(Level) - 1; |
| 1937 | P.setSize(Level, NewSize); |
| 1938 | // If we removed the last branch, update stop and move to a legal pos. |
| 1939 | if (P.offset(Level) == NewSize) { |
| 1940 | setNodeStop(Level, Parent.stop(NewSize - 1)); |
| 1941 | P.moveRight(Level); |
| 1942 | } |
| 1943 | } |
| 1944 | } |
| 1945 | // Update path cache for the new right sibling position. |
| 1946 | if (P.valid()) { |
| 1947 | P.reset(Level + 1); |
| 1948 | P.offset(Level + 1) = 0; |
| 1949 | } |
| 1950 | } |
| 1951 | |
| 1952 | /// overflow - Distribute entries of the current node evenly among |
| 1953 | /// its siblings and ensure that the current node is not full. |
| 1954 | /// This may require allocating a new node. |
| 1955 | /// @tparam NodeT The type of node at Level (Leaf or Branch). |
| 1956 | /// @param Level path index of the overflowing node. |
| 1957 | /// @return True when the tree height was changed. |
| 1958 | template <typename KeyT, typename ValT, unsigned N, typename Traits> |
| 1959 | template <typename NodeT> |
| 1960 | bool IntervalMap<KeyT, ValT, N, Traits>:: |
| 1961 | iterator::overflow(unsigned Level) { |
| 1962 | using namespace IntervalMapImpl; |
| 1963 | Path &P = this->path; |
| 1964 | unsigned CurSize[4]; |
| 1965 | NodeT *Node[4]; |
| 1966 | unsigned Nodes = 0; |
| 1967 | unsigned Elements = 0; |
| 1968 | unsigned Offset = P.offset(Level); |
| 1969 | |
| 1970 | // Do we have a left sibling? |
| 1971 | NodeRef LeftSib = P.getLeftSibling(Level); |
| 1972 | if (LeftSib) { |
| 1973 | Offset += Elements = CurSize[Nodes] = LeftSib.size(); |
| 1974 | Node[Nodes++] = &LeftSib.get<NodeT>(); |
| 1975 | } |
| 1976 | |
| 1977 | // Current node. |
| 1978 | Elements += CurSize[Nodes] = P.size(Level); |
| 1979 | Node[Nodes++] = &P.node<NodeT>(Level); |
| 1980 | |
| 1981 | // Do we have a right sibling? |
| 1982 | NodeRef RightSib = P.getRightSibling(Level); |
| 1983 | if (RightSib) { |
| 1984 | Elements += CurSize[Nodes] = RightSib.size(); |
| 1985 | Node[Nodes++] = &RightSib.get<NodeT>(); |
| 1986 | } |
| 1987 | |
| 1988 | // Do we need to allocate a new node? |
| 1989 | unsigned NewNode = 0; |
| 1990 | if (Elements + 1 > Nodes * NodeT::Capacity) { |
| 1991 | // Insert NewNode at the penultimate position, or after a single node. |
| 1992 | NewNode = Nodes == 1 ? 1 : Nodes - 1; |
| 1993 | CurSize[Nodes] = CurSize[NewNode]; |
| 1994 | Node[Nodes] = Node[NewNode]; |
| 1995 | CurSize[NewNode] = 0; |
| 1996 | Node[NewNode] = this->map->template newNode<NodeT>(); |
| 1997 | ++Nodes; |
| 1998 | } |
| 1999 | |
| 2000 | // Compute the new element distribution. |
| 2001 | unsigned NewSize[4]; |
| 2002 | IdxPair NewOffset = distribute(Nodes, Elements, NodeT::Capacity, |
| 2003 | CurSize, NewSize, Offset, true); |
| 2004 | adjustSiblingSizes(Node, Nodes, CurSize, NewSize); |
| 2005 | |
| 2006 | // Move current location to the leftmost node. |
| 2007 | if (LeftSib) |
| 2008 | P.moveLeft(Level); |
| 2009 | |
| 2010 | // Elements have been rearranged, now update node sizes and stops. |
| 2011 | bool SplitRoot = false; |
| 2012 | unsigned Pos = 0; |
| 2013 | while (true) { |
| 2014 | KeyT Stop = Node[Pos]->stop(NewSize[Pos]-1); |
| 2015 | if (NewNode && Pos == NewNode) { |
| 2016 | SplitRoot = insertNode(Level, NodeRef(Node[Pos], NewSize[Pos]), Stop); |
| 2017 | Level += SplitRoot; |
| 2018 | } else { |
| 2019 | P.setSize(Level, NewSize[Pos]); |
| 2020 | setNodeStop(Level, Stop); |
| 2021 | } |
| 2022 | if (Pos + 1 == Nodes) |
| 2023 | break; |
| 2024 | P.moveRight(Level); |
| 2025 | ++Pos; |
| 2026 | } |
| 2027 | |
| 2028 | // Where was I? Find NewOffset. |
| 2029 | while(Pos != NewOffset.first) { |
| 2030 | P.moveLeft(Level); |
| 2031 | --Pos; |
| 2032 | } |
| 2033 | P.offset(Level) = NewOffset.second; |
| 2034 | return SplitRoot; |
| 2035 | } |
| 2036 | |
| 2037 | //===----------------------------------------------------------------------===// |
| 2038 | //--- IntervalMapOverlaps ----// |
| 2039 | //===----------------------------------------------------------------------===// |
| 2040 | |
| 2041 | /// IntervalMapOverlaps - Iterate over the overlaps of mapped intervals in two |
| 2042 | /// IntervalMaps. The maps may be different, but the KeyT and Traits types |
| 2043 | /// should be the same. |
| 2044 | /// |
| 2045 | /// Typical uses: |
| 2046 | /// |
| 2047 | /// 1. Test for overlap: |
| 2048 | /// bool overlap = IntervalMapOverlaps(a, b).valid(); |
| 2049 | /// |
| 2050 | /// 2. Enumerate overlaps: |
| 2051 | /// for (IntervalMapOverlaps I(a, b); I.valid() ; ++I) { ... } |
| 2052 | /// |
| 2053 | template <typename MapA, typename MapB> |
| 2054 | class IntervalMapOverlaps { |
| 2055 | using KeyType = typename MapA::KeyType; |
| 2056 | using Traits = typename MapA::KeyTraits; |
| 2057 | |
| 2058 | typename MapA::const_iterator posA; |
| 2059 | typename MapB::const_iterator posB; |
| 2060 | |
| 2061 | /// advance - Move posA and posB forward until reaching an overlap, or until |
| 2062 | /// either meets end. |
| 2063 | /// Don't move the iterators if they are already overlapping. |
| 2064 | void advance() { |
| 2065 | if (!valid()) |
| 2066 | return; |
| 2067 | |
| 2068 | if (Traits::stopLess(posA.stop(), posB.start())) { |
| 2069 | // A ends before B begins. Catch up. |
| 2070 | posA.advanceTo(posB.start()); |
| 2071 | if (!posA.valid() || !Traits::stopLess(posB.stop(), posA.start())) |
| 2072 | return; |
| 2073 | } else if (Traits::stopLess(posB.stop(), posA.start())) { |
| 2074 | // B ends before A begins. Catch up. |
| 2075 | posB.advanceTo(posA.start()); |
| 2076 | if (!posB.valid() || !Traits::stopLess(posA.stop(), posB.start())) |
| 2077 | return; |
| 2078 | } else |
| 2079 | // Already overlapping. |
| 2080 | return; |
| 2081 | |
| 2082 | while (true) { |
| 2083 | // Make a.end > b.start. |
| 2084 | posA.advanceTo(posB.start()); |
| 2085 | if (!posA.valid() || !Traits::stopLess(posB.stop(), posA.start())) |
| 2086 | return; |
| 2087 | // Make b.end > a.start. |
| 2088 | posB.advanceTo(posA.start()); |
| 2089 | if (!posB.valid() || !Traits::stopLess(posA.stop(), posB.start())) |
| 2090 | return; |
| 2091 | } |
| 2092 | } |
| 2093 | |
| 2094 | public: |
| 2095 | /// IntervalMapOverlaps - Create an iterator for the overlaps of a and b. |
| 2096 | IntervalMapOverlaps(const MapA &a, const MapB &b) |
| 2097 | : posA(b.empty() ? a.end() : a.find(b.start())), |
| 2098 | posB(posA.valid() ? b.find(posA.start()) : b.end()) { advance(); } |
| 2099 | |
| 2100 | /// valid - Return true if iterator is at an overlap. |
| 2101 | bool valid() const { |
| 2102 | return posA.valid() && posB.valid(); |
| 2103 | } |
| 2104 | |
| 2105 | /// a - access the left hand side in the overlap. |
| 2106 | const typename MapA::const_iterator &a() const { return posA; } |
| 2107 | |
| 2108 | /// b - access the right hand side in the overlap. |
| 2109 | const typename MapB::const_iterator &b() const { return posB; } |
| 2110 | |
| 2111 | /// start - Beginning of the overlapping interval. |
| 2112 | KeyType start() const { |
| 2113 | KeyType ak = a().start(); |
| 2114 | KeyType bk = b().start(); |
| 2115 | return Traits::startLess(ak, bk) ? bk : ak; |
| 2116 | } |
| 2117 | |
| 2118 | /// stop - End of the overlapping interval. |
| 2119 | KeyType stop() const { |
| 2120 | KeyType ak = a().stop(); |
| 2121 | KeyType bk = b().stop(); |
| 2122 | return Traits::startLess(ak, bk) ? ak : bk; |
| 2123 | } |
| 2124 | |
| 2125 | /// skipA - Move to the next overlap that doesn't involve a(). |
| 2126 | void skipA() { |
| 2127 | ++posA; |
| 2128 | advance(); |
| 2129 | } |
| 2130 | |
| 2131 | /// skipB - Move to the next overlap that doesn't involve b(). |
| 2132 | void skipB() { |
| 2133 | ++posB; |
| 2134 | advance(); |
| 2135 | } |
| 2136 | |
| 2137 | /// Preincrement - Move to the next overlap. |
| 2138 | IntervalMapOverlaps &operator++() { |
| 2139 | // Bump the iterator that ends first. The other one may have more overlaps. |
| 2140 | if (Traits::startLess(posB.stop(), posA.stop())) |
| 2141 | skipB(); |
| 2142 | else |
| 2143 | skipA(); |
| 2144 | return *this; |
| 2145 | } |
| 2146 | |
| 2147 | /// advanceTo - Move to the first overlapping interval with |
| 2148 | /// stopLess(x, stop()). |
| 2149 | void advanceTo(KeyType x) { |
| 2150 | if (!valid()) |
| 2151 | return; |
| 2152 | // Make sure advanceTo sees monotonic keys. |
| 2153 | if (Traits::stopLess(posA.stop(), x)) |
| 2154 | posA.advanceTo(x); |
| 2155 | if (Traits::stopLess(posB.stop(), x)) |
| 2156 | posB.advanceTo(x); |
| 2157 | advance(); |
| 2158 | } |
| 2159 | }; |
| 2160 | |
| 2161 | } // end namespace llvm |
| 2162 | |
| 2163 | #endif // LLVM_ADT_INTERVALMAP_H |