Include raw_ostream.h unconditionally even if it is only used for debug code.
[oota-llvm.git] / include / llvm / ADT / IntervalMap.h
1 //===- llvm/ADT/IntervalMap.h - A sorted interval map -----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a coalescing interval map for small objects.
11 //
12 // KeyT objects are mapped to ValT objects. Intervals of keys that map to the
13 // same value are represented in a compressed form.
14 //
15 // Iterators provide ordered access to the compressed intervals rather than the
16 // individual keys, and insert and erase operations use key intervals as well.
17 //
18 // Like SmallVector, IntervalMap will store the first N intervals in the map
19 // object itself without any allocations. When space is exhausted it switches to
20 // a B+-tree representation with very small overhead for small key and value
21 // objects.
22 //
23 // A Traits class specifies how keys are compared. It also allows IntervalMap to
24 // work with both closed and half-open intervals.
25 //
26 // Keys and values are not stored next to each other in a std::pair, so we don't
27 // provide such a value_type. Dereferencing iterators only returns the mapped
28 // value. The interval bounds are accessible through the start() and stop()
29 // iterator methods.
30 //
31 // IntervalMap is optimized for small key and value objects, 4 or 8 bytes each
32 // is the optimal size. For large objects use std::map instead.
33 //
34 //===----------------------------------------------------------------------===//
35 //
36 // Synopsis:
37 //
38 // template <typename KeyT, typename ValT, unsigned N, typename Traits>
39 // class IntervalMap {
40 // public:
41 //   typedef KeyT key_type;
42 //   typedef ValT mapped_type;
43 //   typedef RecyclingAllocator<...> Allocator;
44 //   class iterator;
45 //   class const_iterator;
46 //
47 //   explicit IntervalMap(Allocator&);
48 //   ~IntervalMap():
49 //
50 //   bool empty() const;
51 //   KeyT start() const;
52 //   KeyT stop() const;
53 //   ValT lookup(KeyT x, Value NotFound = Value()) const;
54 //
55 //   const_iterator begin() const;
56 //   const_iterator end() const;
57 //   iterator begin();
58 //   iterator end();
59 //   const_iterator find(KeyT x) const;
60 //   iterator find(KeyT x);
61 //
62 //   void insert(KeyT a, KeyT b, ValT y);
63 //   void clear();
64 // };
65 //
66 // template <typename KeyT, typename ValT, unsigned N, typename Traits>
67 // class IntervalMap::const_iterator :
68 //   public std::iterator<std::bidirectional_iterator_tag, ValT> {
69 // public:
70 //   bool operator==(const const_iterator &) const;
71 //   bool operator!=(const const_iterator &) const;
72 //   bool valid() const;
73 //
74 //   const KeyT &start() const;
75 //   const KeyT &stop() const;
76 //   const ValT &value() const;
77 //   const ValT &operator*() const;
78 //   const ValT *operator->() const;
79 //
80 //   const_iterator &operator++();
81 //   const_iterator &operator++(int);
82 //   const_iterator &operator--();
83 //   const_iterator &operator--(int);
84 //   void goToBegin();
85 //   void goToEnd();
86 //   void find(KeyT x);
87 //   void advanceTo(KeyT x);
88 // };
89 //
90 // template <typename KeyT, typename ValT, unsigned N, typename Traits>
91 // class IntervalMap::iterator : public const_iterator {
92 // public:
93 //   void insert(KeyT a, KeyT b, Value y);
94 //   void erase();
95 // };
96 //
97 //===----------------------------------------------------------------------===//
98
99 #ifndef LLVM_ADT_INTERVALMAP_H
100 #define LLVM_ADT_INTERVALMAP_H
101
102 #include "llvm/ADT/SmallVector.h"
103 #include "llvm/ADT/PointerIntPair.h"
104 #include "llvm/Support/Allocator.h"
105 #include "llvm/Support/RecyclingAllocator.h"
106 #include <limits>
107 #include <iterator>
108
109 // FIXME: Remove debugging code.
110 #include "llvm/Support/raw_ostream.h"
111
112 namespace llvm {
113
114
115 //===----------------------------------------------------------------------===//
116 //---                              Key traits                              ---//
117 //===----------------------------------------------------------------------===//
118 //
119 // The IntervalMap works with closed or half-open intervals.
120 // Adjacent intervals that map to the same value are coalesced.
121 //
122 // The IntervalMapInfo traits class is used to determine if a key is contained
123 // in an interval, and if two intervals are adjacent so they can be coalesced.
124 // The provided implementation works for closed integer intervals, other keys
125 // probably need a specialized version.
126 //
127 // The point x is contained in [a;b] when !startLess(x, a) && !stopLess(b, x).
128 //
129 // It is assumed that (a;b] half-open intervals are not used, only [a;b) is
130 // allowed. This is so that stopLess(a, b) can be used to determine if two
131 // intervals overlap.
132 //
133 //===----------------------------------------------------------------------===//
134
135 template <typename T>
136 struct IntervalMapInfo {
137
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 };
157
158 /// IntervalMapImpl - Namespace used for IntervalMap implementation details.
159 /// It should be considered private to the implementation.
160 namespace IntervalMapImpl {
161
162 // Forward declarations.
163 template <typename, typename, unsigned, typename> class LeafNode;
164 template <typename, typename, unsigned, typename> class BranchNode;
165
166 typedef std::pair<unsigned,unsigned> IdxPair;
167
168
169 //===----------------------------------------------------------------------===//
170 //---                            Node Storage                              ---//
171 //===----------------------------------------------------------------------===//
172 //
173 // Both leaf and branch nodes store vectors of (key,value) pairs.
174 // Leaves store ((KeyT, KeyT), ValT) pairs, branches use (KeyT, NodeRef).
175 //
176 // Keys and values are stored in separate arrays to avoid padding caused by
177 // different object alignments. This also helps improve locality of reference
178 // when searching the keys.
179 //
180 // The nodes don't know how many elements they contain - that information is
181 // stored elsewhere. Omitting the size field prevents padding and allows a node
182 // to fill the allocated cache lines completely.
183 //
184 // These are typical key and value sizes, the node branching factor (N), and
185 // wasted space when nodes are sized to fit in three cache lines (192 bytes):
186 //
187 //   KT  VT   N Waste  Used by
188 //    4   4  24   0    Branch<4> (32-bit pointers)
189 //    4   8  16   0    Branch<4>
190 //    8   4  16   0    Leaf<4,4>
191 //    8   8  12   0    Leaf<4,8>, Branch<8>
192 //   16   4   9  12    Leaf<8,4>
193 //   16   8   8   0    Leaf<8,8>
194 //
195 //===----------------------------------------------------------------------===//
196
197 template <typename KT, typename VT, unsigned N>
198 class NodeBase {
199 public:
200   enum { Capacity = N };
201
202   KT key[N];
203   VT val[N];
204
205   /// copy - Copy elements from another node.
206   /// @param other Node elements are copied from.
207   /// @param i     Beginning of the source range in other.
208   /// @param j     Beginning of the destination range in this.
209   /// @param count Number of elements to copy.
210   template <unsigned M>
211   void copy(const NodeBase<KT, VT, M> &Other, unsigned i,
212             unsigned j, unsigned Count) {
213     assert(i + Count <= M && "Invalid source range");
214     assert(j + Count <= N && "Invalid dest range");
215     std::copy(Other.key + i, Other.key + i + Count, key + j);
216     std::copy(Other.val + i, Other.val + i + Count, val + j);
217   }
218
219   /// lmove - Move elements to the left.
220   /// @param i     Beginning of the source range.
221   /// @param j     Beginning of the destination range.
222   /// @param count Number of elements to copy.
223   void lmove(unsigned i, unsigned j, unsigned Count) {
224     assert(j <= i && "Use rmove shift elements right");
225     copy(*this, i, j, Count);
226   }
227
228   /// rmove - Move elements to the right.
229   /// @param i     Beginning of the source range.
230   /// @param j     Beginning of the destination range.
231   /// @param count Number of elements to copy.
232   void rmove(unsigned i, unsigned j, unsigned Count) {
233     assert(i <= j && "Use lmove shift elements left");
234     assert(j + Count <= N && "Invalid range");
235     std::copy_backward(key + i, key + i + Count, key + j + Count);
236     std::copy_backward(val + i, val + i + Count, val + j + Count);
237   }
238
239   /// erase - Erase elements [i;j).
240   /// @param i    Beginning of the range to erase.
241   /// @param j    End of the range. (Exclusive).
242   /// @param size Number of elements in node.
243   void erase(unsigned i, unsigned j, unsigned Size) {
244     lmove(j, i, Size - j);
245   }
246
247   /// shift - Shift elements [i;size) 1 position to the right.
248   /// @param i    Beginning of the range to move.
249   /// @param size Number of elements in node.
250   void shift(unsigned i, unsigned Size) {
251     rmove(i, i + 1, Size - i);
252   }
253
254   /// xferLeft - Transfer elements to a left sibling node.
255   /// @param size  Number of elements in this.
256   /// @param sib   Left sibling node.
257   /// @param ssize Number of elements in sib.
258   /// @param count Number of elements to transfer.
259   void xferLeft(unsigned Size, NodeBase &Sib, unsigned SSize, unsigned Count) {
260     Sib.copy(*this, 0, SSize, Count);
261     erase(0, Count, Size);
262   }
263
264   /// xferRight - Transfer elements to a right sibling node.
265   /// @param size  Number of elements in this.
266   /// @param sib   Right sibling node.
267   /// @param ssize Number of elements in sib.
268   /// @param count Number of elements to transfer.
269   void xferRight(unsigned Size, NodeBase &Sib, unsigned SSize, unsigned Count) {
270     Sib.rmove(0, Count, SSize);
271     Sib.copy(*this, Size-Count, 0, Count);
272   }
273
274   /// adjLeftSib - Adjust the number if elements in this node by moving
275   /// elements to or from a left sibling node.
276   /// @param size  Number of elements in this.
277   /// @param sib   Right sibling node.
278   /// @param ssize Number of elements in sib.
279   /// @param add   The number of elements to add to this node, possibly < 0.
280   /// @return      Number of elements added to this node, possibly negative.
281   int adjLeftSib(unsigned Size, NodeBase &Sib, unsigned SSize, int Add) {
282     if (Add > 0) {
283       // We want to grow, copy from sib.
284       unsigned Count = std::min(std::min(unsigned(Add), SSize), N - Size);
285       Sib.xferRight(SSize, *this, Size, Count);
286       return Count;
287     } else {
288       // We want to shrink, copy to sib.
289       unsigned Count = std::min(std::min(unsigned(-Add), Size), N - SSize);
290       xferLeft(Size, Sib, SSize, Count);
291       return -Count;
292     }
293   }
294 };
295
296
297 //===----------------------------------------------------------------------===//
298 //---                             NodeSizer                                ---//
299 //===----------------------------------------------------------------------===//
300 //
301 // Compute node sizes from key and value types.
302 //
303 // The branching factors are chosen to make nodes fit in three cache lines.
304 // This may not be possible if keys or values are very large. Such large objects
305 // are handled correctly, but a std::map would probably give better performance.
306 //
307 //===----------------------------------------------------------------------===//
308
309 enum {
310   // Cache line size. Most architectures have 32 or 64 byte cache lines.
311   // We use 64 bytes here because it provides good branching factors.
312   Log2CacheLine = 6,
313   CacheLineBytes = 1 << Log2CacheLine,
314   DesiredNodeBytes = 3 * CacheLineBytes
315 };
316
317 template <typename KeyT, typename ValT>
318 struct NodeSizer {
319   enum {
320     // Compute the leaf node branching factor that makes a node fit in three
321     // cache lines. The branching factor must be at least 3, or some B+-tree
322     // balancing algorithms won't work.
323     // LeafSize can't be larger than CacheLineBytes. This is required by the
324     // PointerIntPair used by NodeRef.
325     DesiredLeafSize = DesiredNodeBytes /
326       static_cast<unsigned>(2*sizeof(KeyT)+sizeof(ValT)),
327     MinLeafSize = 3,
328     LeafSize = DesiredLeafSize > MinLeafSize ? DesiredLeafSize : MinLeafSize
329   };
330
331   typedef NodeBase<std::pair<KeyT, KeyT>, ValT, LeafSize> LeafBase;
332
333   enum {
334     // Now that we have the leaf branching factor, compute the actual allocation
335     // unit size by rounding up to a whole number of cache lines.
336     AllocBytes = (sizeof(LeafBase) + CacheLineBytes-1) & ~(CacheLineBytes-1),
337
338     // Determine the branching factor for branch nodes.
339     BranchSize = AllocBytes /
340       static_cast<unsigned>(sizeof(KeyT) + sizeof(void*))
341   };
342
343   /// Allocator - The recycling allocator used for both branch and leaf nodes.
344   /// This typedef is very likely to be identical for all IntervalMaps with
345   /// reasonably sized entries, so the same allocator can be shared among
346   /// different kinds of maps.
347   typedef RecyclingAllocator<BumpPtrAllocator, char,
348                              AllocBytes, CacheLineBytes> Allocator;
349
350 };
351
352
353 //===----------------------------------------------------------------------===//
354 //---                              NodeRef                                 ---//
355 //===----------------------------------------------------------------------===//
356 //
357 // B+-tree nodes can be leaves or branches, so we need a polymorphic node
358 // pointer that can point to both kinds.
359 //
360 // All nodes are cache line aligned and the low 6 bits of a node pointer are
361 // always 0. These bits are used to store the number of elements in the
362 // referenced node. Besides saving space, placing node sizes in the parents
363 // allow tree balancing algorithms to run without faulting cache lines for nodes
364 // that may not need to be modified.
365 //
366 // A NodeRef doesn't know whether it references a leaf node or a branch node.
367 // It is the responsibility of the caller to use the correct types.
368 //
369 // Nodes are never supposed to be empty, and it is invalid to store a node size
370 // of 0 in a NodeRef. The valid range of sizes is 1-64.
371 //
372 //===----------------------------------------------------------------------===//
373
374 struct CacheAlignedPointerTraits {
375   static inline void *getAsVoidPointer(void *P) { return P; }
376   static inline void *getFromVoidPointer(void *P) { return P; }
377   enum { NumLowBitsAvailable = Log2CacheLine };
378 };
379
380 template <typename KeyT, typename ValT, typename Traits>
381 class NodeRef {
382 public:
383   typedef LeafNode<KeyT, ValT, NodeSizer<KeyT, ValT>::LeafSize, Traits> Leaf;
384   typedef BranchNode<KeyT, ValT, NodeSizer<KeyT, ValT>::BranchSize,
385                      Traits> Branch;
386
387 private:
388   PointerIntPair<void*, Log2CacheLine, unsigned, CacheAlignedPointerTraits> pip;
389
390 public:
391   /// NodeRef - Create a null ref.
392   NodeRef() {}
393
394   /// operator bool - Detect a null ref.
395   operator bool() const { return pip.getOpaqueValue(); }
396
397   /// NodeRef - Create a reference to the leaf node p with n elements.
398   NodeRef(Leaf *p, unsigned n) : pip(p, n - 1) {}
399
400   /// NodeRef - Create a reference to the branch node p with n elements.
401   NodeRef(Branch *p, unsigned n) : pip(p, n - 1) {}
402
403   /// size - Return the number of elements in the referenced node.
404   unsigned size() const { return pip.getInt() + 1; }
405
406   /// setSize - Update the node size.
407   void setSize(unsigned n) { pip.setInt(n - 1); }
408
409   /// leaf - Return the referenced leaf node.
410   /// Note there are no dynamic type checks.
411   Leaf &leaf() const {
412     return *reinterpret_cast<Leaf*>(pip.getPointer());
413   }
414
415   /// branch - Return the referenced branch node.
416   /// Note there are no dynamic type checks.
417   Branch &branch() const {
418     return *reinterpret_cast<Branch*>(pip.getPointer());
419   }
420
421   bool operator==(const NodeRef &RHS) const {
422     if (pip == RHS.pip)
423       return true;
424     assert(pip.getPointer() != RHS.pip.getPointer() && "Inconsistent NodeRefs");
425     return false;
426   }
427
428   bool operator!=(const NodeRef &RHS) const {
429     return !operator==(RHS);
430   }
431 };
432
433 //===----------------------------------------------------------------------===//
434 //---                            Leaf nodes                                ---//
435 //===----------------------------------------------------------------------===//
436 //
437 // Leaf nodes store up to N disjoint intervals with corresponding values.
438 //
439 // The intervals are kept sorted and fully coalesced so there are no adjacent
440 // intervals mapping to the same value.
441 //
442 // These constraints are always satisfied:
443 //
444 // - Traits::stopLess(key[i].start, key[i].stop) - Non-empty, sane intervals.
445 //
446 // - Traits::stopLess(key[i].stop, key[i + 1].start) - Sorted.
447 //
448 // - val[i] != val[i + 1] ||
449 //     !Traits::adjacent(key[i].stop, key[i + 1].start) - Fully coalesced.
450 //
451 //===----------------------------------------------------------------------===//
452
453 template <typename KeyT, typename ValT, unsigned N, typename Traits>
454 class LeafNode : public NodeBase<std::pair<KeyT, KeyT>, ValT, N> {
455 public:
456   const KeyT &start(unsigned i) const { return this->key[i].first; }
457   const KeyT &stop(unsigned i) const { return this->key[i].second; }
458   const ValT &value(unsigned i) const { return this->val[i]; }
459
460   KeyT &start(unsigned i) { return this->key[i].first; }
461   KeyT &stop(unsigned i) { return this->key[i].second; }
462   ValT &value(unsigned i) { return this->val[i]; }
463
464   /// findFrom - Find the first interval after i that may contain x.
465   /// @param i    Starting index for the search.
466   /// @param size Number of elements in node.
467   /// @param x    Key to search for.
468   /// @return     First index with !stopLess(key[i].stop, x), or size.
469   ///             This is the first interval that can possibly contain x.
470   unsigned findFrom(unsigned i, unsigned Size, KeyT x) const {
471     assert(i <= Size && Size <= N && "Bad indices");
472     assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
473            "Index is past the needed point");
474     while (i != Size && Traits::stopLess(stop(i), x)) ++i;
475     return i;
476   }
477
478   /// safeFind - Find an interval that is known to exist. This is the same as
479   /// findFrom except is it assumed that x is at least within range of the last
480   /// interval.
481   /// @param i Starting index for the search.
482   /// @param x Key to search for.
483   /// @return  First index with !stopLess(key[i].stop, x), never size.
484   ///          This is the first interval that can possibly contain x.
485   unsigned safeFind(unsigned i, KeyT x) const {
486     assert(i < N && "Bad index");
487     assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
488            "Index is past the needed point");
489     while (Traits::stopLess(stop(i), x)) ++i;
490     assert(i < N && "Unsafe intervals");
491     return i;
492   }
493
494   /// safeLookup - Lookup mapped value for a safe key.
495   /// It is assumed that x is within range of the last entry.
496   /// @param x        Key to search for.
497   /// @param NotFound Value to return if x is not in any interval.
498   /// @return         The mapped value at x or NotFound.
499   ValT safeLookup(KeyT x, ValT NotFound) const {
500     unsigned i = safeFind(0, x);
501     return Traits::startLess(x, start(i)) ? NotFound : value(i);
502   }
503
504   IdxPair insertFrom(unsigned i, unsigned Size, KeyT a, KeyT b, ValT y);
505   unsigned extendStop(unsigned i, unsigned Size, KeyT b);
506
507 #ifndef NDEBUG
508   void dump(unsigned Size) {
509     errs() << "  N" << this << " [shape=record label=\"{ " << Size << '/' << N;
510     for (unsigned i = 0; i != Size; ++i)
511       errs() << " | {" << start(i) << '-' << stop(i) << "|" << value(i) << '}';
512     errs() << "}\"];\n";
513   }
514 #endif
515
516 };
517
518 /// insertFrom - Add mapping of [a;b] to y if possible, coalescing as much as
519 /// possible. This may cause the node to grow by 1, or it may cause the node
520 /// to shrink because of coalescing.
521 /// @param i    Starting index = insertFrom(0, size, a)
522 /// @param size Number of elements in node.
523 /// @param a    Interval start.
524 /// @param b    Interval stop.
525 /// @param y    Value be mapped.
526 /// @return     (insert position, new size), or (i, Capacity+1) on overflow.
527 template <typename KeyT, typename ValT, unsigned N, typename Traits>
528 IdxPair LeafNode<KeyT, ValT, N, Traits>::
529 insertFrom(unsigned i, unsigned Size, KeyT a, KeyT b, ValT y) {
530   assert(i <= Size && Size <= N && "Invalid index");
531   assert(!Traits::stopLess(b, a) && "Invalid interval");
532
533   // Verify the findFrom invariant.
534   assert((i == 0 || Traits::stopLess(stop(i - 1), a)));
535   assert((i == Size || !Traits::stopLess(stop(i), a)));
536
537   // Coalesce with previous interval.
538   if (i && value(i - 1) == y && Traits::adjacent(stop(i - 1), a))
539     return IdxPair(i - 1, extendStop(i - 1, Size, b));
540
541   // Detect overflow.
542   if (i == N)
543     return IdxPair(i, N + 1);
544
545   // Add new interval at end.
546   if (i == Size) {
547     start(i) = a;
548     stop(i) = b;
549     value(i) = y;
550     return IdxPair(i, Size + 1);
551   }
552
553   // Overlapping intervals?
554   if (!Traits::stopLess(b, start(i))) {
555     assert(value(i) == y && "Inconsistent values in overlapping intervals");
556     if (Traits::startLess(a, start(i)))
557       start(i) = a;
558     return IdxPair(i, extendStop(i, Size, b));
559   }
560
561   // Try to coalesce with following interval.
562   if (value(i) == y && Traits::adjacent(b, start(i))) {
563     start(i) = a;
564     return IdxPair(i, Size);
565   }
566
567   // We must insert before i. Detect overflow.
568   if (Size == N)
569     return IdxPair(i, N + 1);
570
571   // Insert before i.
572   this->shift(i, Size);
573   start(i) = a;
574   stop(i) = b;
575   value(i) = y;
576   return IdxPair(i, Size + 1);
577 }
578
579 /// extendStop - Extend stop(i) to b, coalescing with following intervals.
580 /// @param i    Interval to extend.
581 /// @param size Number of elements in node.
582 /// @param b    New interval end point.
583 /// @return     New node size after coalescing.
584 template <typename KeyT, typename ValT, unsigned N, typename Traits>
585 unsigned LeafNode<KeyT, ValT, N, Traits>::
586 extendStop(unsigned i, unsigned Size, KeyT b) {
587   assert(i < Size && Size <= N && "Bad indices");
588
589   // Are we even extending the interval?
590   if (Traits::startLess(b, stop(i)))
591     return Size;
592
593   // Find the first interval that may be preserved.
594   unsigned j = findFrom(i + 1, Size, b);
595   if (j < Size) {
596     // Would key[i] overlap key[j] after the extension?
597     if (Traits::stopLess(b, start(j))) {
598       // Not overlapping. Perhaps adjacent and coalescable?
599       if (value(i) == value(j) && Traits::adjacent(b, start(j)))
600         b = stop(j++);
601     } else {
602       // Overlap. Include key[j] in the new interval.
603       assert(value(i) == value(j) && "Overlapping values");
604       b = stop(j++);
605     }
606   }
607   stop(i) =  b;
608
609   // Entries [i+1;j) were coalesced.
610   if (i + 1 < j && j < Size)
611     this->erase(i + 1, j, Size);
612   return Size - (j - (i + 1));
613 }
614
615
616 //===----------------------------------------------------------------------===//
617 //---                             Branch nodes                             ---//
618 //===----------------------------------------------------------------------===//
619 //
620 // A branch node stores references to 1--N subtrees all of the same height.
621 //
622 // The key array in a branch node holds the rightmost stop key of each subtree.
623 // It is redundant to store the last stop key since it can be found in the
624 // parent node, but doing so makes tree balancing a lot simpler.
625 //
626 // It is unusual for a branch node to only have one subtree, but it can happen
627 // in the root node if it is smaller than the normal nodes.
628 //
629 // When all of the leaf nodes from all the subtrees are concatenated, they must
630 // satisfy the same constraints as a single leaf node. They must be sorted,
631 // sane, and fully coalesced.
632 //
633 //===----------------------------------------------------------------------===//
634
635 template <typename KeyT, typename ValT, unsigned N, typename Traits>
636 class BranchNode : public NodeBase<KeyT, NodeRef<KeyT, ValT, Traits>, N> {
637   typedef  NodeRef<KeyT, ValT, Traits> NodeRefT;
638 public:
639   const KeyT &stop(unsigned i) const { return this->key[i]; }
640   const NodeRefT &subtree(unsigned i) const { return this->val[i]; }
641
642   KeyT &stop(unsigned i) { return this->key[i]; }
643   NodeRefT &subtree(unsigned i) { return this->val[i]; }
644
645   /// findFrom - Find the first subtree after i that may contain x.
646   /// @param i    Starting index for the search.
647   /// @param size Number of elements in node.
648   /// @param x    Key to search for.
649   /// @return     First index with !stopLess(key[i], x), or size.
650   ///             This is the first subtree that can possibly contain x.
651   unsigned findFrom(unsigned i, unsigned Size, KeyT x) const {
652     assert(i <= Size && Size <= N && "Bad indices");
653     assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
654            "Index to findFrom is past the needed point");
655     while (i != Size && Traits::stopLess(stop(i), x)) ++i;
656     return i;
657   }
658
659   /// safeFind - Find a subtree that is known to exist. This is the same as
660   /// findFrom except is it assumed that x is in range.
661   /// @param i Starting index for the search.
662   /// @param x Key to search for.
663   /// @return  First index with !stopLess(key[i], x), never size.
664   ///          This is the first subtree that can possibly contain x.
665   unsigned safeFind(unsigned i, KeyT x) const {
666     assert(i < N && "Bad index");
667     assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
668            "Index is past the needed point");
669     while (Traits::stopLess(stop(i), x)) ++i;
670     assert(i < N && "Unsafe intervals");
671     return i;
672   }
673
674   /// safeLookup - Get the subtree containing x, Assuming that x is in range.
675   /// @param x Key to search for.
676   /// @return  Subtree containing x
677   NodeRefT safeLookup(KeyT x) const {
678     return subtree(safeFind(0, x));
679   }
680
681   /// insert - Insert a new (subtree, stop) pair.
682   /// @param i    Insert position, following entries will be shifted.
683   /// @param size Number of elements in node.
684   /// @param node Subtree to insert.
685   /// @param stp  Last key in subtree.
686   void insert(unsigned i, unsigned Size, NodeRefT Node, KeyT Stop) {
687     assert(Size < N && "branch node overflow");
688     assert(i <= Size && "Bad insert position");
689     this->shift(i, Size);
690     subtree(i) = Node;
691     stop(i) = Stop;
692   }
693
694 #ifndef NDEBUG
695   void dump(unsigned Size) {
696     errs() << "  N" << this << " [shape=record label=\"" << Size << '/' << N;
697     for (unsigned i = 0; i != Size; ++i)
698       errs() << " | <s" << i << "> " << stop(i);
699     errs() << "\"];\n";
700     for (unsigned i = 0; i != Size; ++i)
701       errs() << "  N" << this << ":s" << i << " -> N"
702              << &subtree(i).branch() << ";\n";
703   }
704 #endif
705
706 };
707
708 } // namespace IntervalMapImpl
709
710
711 //===----------------------------------------------------------------------===//
712 //---                          IntervalMap                                ----//
713 //===----------------------------------------------------------------------===//
714
715 template <typename KeyT, typename ValT,
716           unsigned N = IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
717           typename Traits = IntervalMapInfo<KeyT> >
718 class IntervalMap {
719   typedef IntervalMapImpl::NodeRef<KeyT, ValT, Traits> NodeRef;
720   typedef IntervalMapImpl::NodeSizer<KeyT, ValT> NodeSizer;
721   typedef typename NodeRef::Leaf Leaf;
722   typedef typename NodeRef::Branch Branch;
723   typedef IntervalMapImpl::LeafNode<KeyT, ValT, N, Traits> RootLeaf;
724   typedef IntervalMapImpl::IdxPair IdxPair;
725
726   // The RootLeaf capacity is given as a template parameter. We must compute the
727   // corresponding RootBranch capacity.
728   enum {
729     DesiredRootBranchCap = (sizeof(RootLeaf) - sizeof(KeyT)) /
730       (sizeof(KeyT) + sizeof(NodeRef)),
731     RootBranchCap = DesiredRootBranchCap ? DesiredRootBranchCap : 1
732   };
733
734   typedef IntervalMapImpl::BranchNode<KeyT, ValT, RootBranchCap, Traits> RootBranch;
735
736   // When branched, we store a global start key as well as the branch node.
737   struct RootBranchData {
738     KeyT start;
739     RootBranch node;
740   };
741
742   enum {
743     RootDataSize = sizeof(RootBranchData) > sizeof(RootLeaf) ?
744                    sizeof(RootBranchData) : sizeof(RootLeaf)
745   };
746
747 public:
748   typedef typename NodeSizer::Allocator Allocator;
749
750 private:
751   // The root data is either a RootLeaf or a RootBranchData instance.
752   // We can't put them in a union since C++03 doesn't allow non-trivial
753   // constructors in unions.
754   // Instead, we use a char array with pointer alignment. The alignment is
755   // ensured by the allocator member in the class, but still verified in the
756   // constructor. We don't support keys or values that are more aligned than a
757   // pointer.
758   char data[RootDataSize];
759
760   // Tree height.
761   // 0: Leaves in root.
762   // 1: Root points to leaf.
763   // 2: root->branch->leaf ...
764   unsigned height;
765
766   // Number of entries in the root node.
767   unsigned rootSize;
768
769   // Allocator used for creating external nodes.
770   Allocator &allocator;
771
772   /// dataAs - Represent data as a node type without breaking aliasing rules.
773   template <typename T>
774   T &dataAs() const {
775     union {
776       const char *d;
777       T *t;
778     } u;
779     u.d = data;
780     return *u.t;
781   }
782
783   const RootLeaf &rootLeaf() const {
784     assert(!branched() && "Cannot acces leaf data in branched root");
785     return dataAs<RootLeaf>();
786   }
787   RootLeaf &rootLeaf() {
788     assert(!branched() && "Cannot acces leaf data in branched root");
789     return dataAs<RootLeaf>();
790   }
791   RootBranchData &rootBranchData() const {
792     assert(branched() && "Cannot access branch data in non-branched root");
793     return dataAs<RootBranchData>();
794   }
795   RootBranchData &rootBranchData() {
796     assert(branched() && "Cannot access branch data in non-branched root");
797     return dataAs<RootBranchData>();
798   }
799   const RootBranch &rootBranch() const { return rootBranchData().node; }
800   RootBranch &rootBranch()             { return rootBranchData().node; }
801   KeyT rootBranchStart() const { return rootBranchData().start; }
802   KeyT &rootBranchStart()      { return rootBranchData().start; }
803
804   Leaf *allocLeaf()  {
805     return new(allocator.template Allocate<Leaf>()) Leaf();
806   }
807   void freeLeaf(Leaf *P) {
808     P->~Leaf();
809     allocator.Deallocate(P);
810   }
811
812   Branch *allocBranch() {
813     return new(allocator.template Allocate<Branch>()) Branch();
814   }
815   void freeBranch(Branch *P) {
816     P->~Branch();
817     allocator.Deallocate(P);
818   }
819
820
821   IdxPair branchRoot(unsigned Position);
822   IdxPair splitRoot(unsigned Position);
823
824   void switchRootToBranch() {
825     rootLeaf().~RootLeaf();
826     height = 1;
827     new (&rootBranchData()) RootBranchData();
828   }
829
830   void switchRootToLeaf() {
831     rootBranchData().~RootBranchData();
832     height = 0;
833     new(&rootLeaf()) RootLeaf();
834   }
835
836   bool branched() const { return height > 0; }
837
838   ValT treeSafeLookup(KeyT x, ValT NotFound) const;
839
840   void visitNodes(void (IntervalMap::*f)(NodeRef, unsigned Level));
841
842 public:
843   explicit IntervalMap(Allocator &a) : height(0), rootSize(0), allocator(a) {
844     assert((uintptr_t(data) & (alignOf<RootLeaf>() - 1)) == 0 &&
845            "Insufficient alignment");
846     new(&rootLeaf()) RootLeaf();
847   }
848
849   /// empty -  Return true when no intervals are mapped.
850   bool empty() const {
851     return rootSize == 0;
852   }
853
854   /// start - Return the smallest mapped key in a non-empty map.
855   KeyT start() const {
856     assert(!empty() && "Empty IntervalMap has no start");
857     return !branched() ? rootLeaf().start(0) : rootBranchStart();
858   }
859
860   /// stop - Return the largest mapped key in a non-empty map.
861   KeyT stop() const {
862     assert(!empty() && "Empty IntervalMap has no stop");
863     return !branched() ? rootLeaf().stop(rootSize - 1) :
864                          rootBranch().stop(rootSize - 1);
865   }
866
867   /// lookup - Return the mapped value at x or NotFound.
868   ValT lookup(KeyT x, ValT NotFound = ValT()) const {
869     if (empty() || Traits::startLess(x, start()) || Traits::stopLess(stop(), x))
870       return NotFound;
871     return branched() ? treeSafeLookup(x, NotFound) :
872                         rootLeaf().safeLookup(x, NotFound);
873   }
874
875   /// insert - Add a mapping of [a;b] to y, coalesce with adjacent intervals.
876   /// It is assumed that no key in the interval is mapped to another value, but
877   /// overlapping intervals already mapped to y will be coalesced.
878   void insert(KeyT a, KeyT b, ValT y) {
879     find(a).insert(a, b, y);
880   }
881
882   class const_iterator;
883   class iterator;
884   friend class const_iterator;
885   friend class iterator;
886
887   const_iterator begin() const {
888     iterator I(*this);
889     I.goToBegin();
890     return I;
891   }
892
893   iterator begin() {
894     iterator I(*this);
895     I.goToBegin();
896     return I;
897   }
898
899   const_iterator end() const {
900     iterator I(*this);
901     I.goToEnd();
902     return I;
903   }
904
905   iterator end() {
906     iterator I(*this);
907     I.goToEnd();
908     return I;
909   }
910
911   /// find - Return an iterator pointing to the first interval ending at or
912   /// after x, or end().
913   const_iterator find(KeyT x) const {
914     iterator I(*this);
915     I.find(x);
916     return I;
917   }
918
919   iterator find(KeyT x) {
920     iterator I(*this);
921     I.find(x);
922     return I;
923   }
924
925 #ifndef NDEBUG
926   void dump();
927   void dumpNode(NodeRef Node, unsigned Height);
928 #endif
929 };
930
931 /// treeSafeLookup - Return the mapped value at x or NotFound, assuming a
932 /// branched root.
933 template <typename KeyT, typename ValT, unsigned N, typename Traits>
934 ValT IntervalMap<KeyT, ValT, N, Traits>::
935 treeSafeLookup(KeyT x, ValT NotFound) const {
936   assert(branched() && "treeLookup assumes a branched root");
937
938   NodeRef NR = rootBranch().safeLookup(x);
939   for (unsigned h = height-1; h; --h)
940     NR = NR.branch().safeLookup(x);
941   return NR.leaf().safeLookup(x, NotFound);
942 }
943
944
945 // branchRoot - Switch from a leaf root to a branched root.
946 // Return the new (root offset, node offset) corresponding to Position.
947 template <typename KeyT, typename ValT, unsigned N, typename Traits>
948 IntervalMapImpl::IdxPair IntervalMap<KeyT, ValT, N, Traits>::
949 branchRoot(unsigned Position) {
950   // How many external leaf nodes to hold RootLeaf+1?
951   const unsigned Nodes = RootLeaf::Capacity / Leaf::Capacity + 1;
952
953   // Compute element distribution among new nodes.
954   unsigned size[Nodes];
955   IdxPair NewOffset(0, Position);
956
957   // Is is very common for the root node to be smaller than external nodes.
958   if (Nodes == 1)
959     size[0] = rootSize;
960   else
961     NewOffset = distribute(Nodes, rootSize, Leaf::Capacity,  NULL, size,
962                            Position, true);
963
964   // Allocate new nodes.
965   unsigned pos = 0;
966   NodeRef node[Nodes];
967   for (unsigned n = 0; n != Nodes; ++n) {
968     node[n] = NodeRef(allocLeaf(), size[n]);
969     node[n].leaf().copy(rootLeaf(), pos, 0, size[n]);
970     pos += size[n];
971   }
972
973   // Destroy the old leaf node, construct branch node instead.
974   switchRootToBranch();
975   for (unsigned n = 0; n != Nodes; ++n) {
976     rootBranch().stop(n) = node[n].leaf().stop(size[n]-1);
977     rootBranch().subtree(n) = node[n];
978   }
979   rootBranchStart() = node[0].leaf().start(0);
980   rootSize = Nodes;
981   return NewOffset;
982 }
983
984 // splitRoot - Split the current BranchRoot into multiple Branch nodes.
985 // Return the new (root offset, node offset) corresponding to Position.
986 template <typename KeyT, typename ValT, unsigned N, typename Traits>
987 IntervalMapImpl::IdxPair IntervalMap<KeyT, ValT, N, Traits>::
988 splitRoot(unsigned Position) {
989   // How many external leaf nodes to hold RootBranch+1?
990   const unsigned Nodes = RootBranch::Capacity / Branch::Capacity + 1;
991
992   // Compute element distribution among new nodes.
993   unsigned Size[Nodes];
994   IdxPair NewOffset(0, Position);
995
996   // Is is very common for the root node to be smaller than external nodes.
997   if (Nodes == 1)
998     Size[0] = rootSize;
999   else
1000     NewOffset = distribute(Nodes, rootSize, Leaf::Capacity,  NULL, Size,
1001                            Position, true);
1002
1003   // Allocate new nodes.
1004   unsigned Pos = 0;
1005   NodeRef Node[Nodes];
1006   for (unsigned n = 0; n != Nodes; ++n) {
1007     Node[n] = NodeRef(allocBranch(), Size[n]);
1008     Node[n].branch().copy(rootBranch(), Pos, 0, Size[n]);
1009     Pos += Size[n];
1010   }
1011
1012   for (unsigned n = 0; n != Nodes; ++n) {
1013     rootBranch().stop(n) = Node[n].branch().stop(Size[n]-1);
1014     rootBranch().subtree(n) = Node[n];
1015   }
1016   rootSize = Nodes;
1017   return NewOffset;
1018 }
1019
1020 /// visitNodes - Visit each external node.
1021 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1022 void IntervalMap<KeyT, ValT, N, Traits>::
1023 visitNodes(void (IntervalMap::*f)(NodeRef, unsigned Height)) {
1024   if (!branched())
1025     return;
1026   SmallVector<NodeRef, 4> Refs, NextRefs;
1027
1028   // Collect level 0 nodes from the root.
1029   for (unsigned i = 0; i != rootSize; ++i)
1030     Refs.push_back(rootBranch().subtree(i));
1031
1032   // Visit all branch nodes.
1033   for (unsigned h = height - 1; h; --h) {
1034     for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
1035       Branch &B = Refs[i].branch();
1036       for (unsigned j = 0, s = Refs[i].size(); j != s; ++j)
1037         NextRefs.push_back(B.subtree(j));
1038       (this->*f)(Refs[i], h);
1039     }
1040     Refs.clear();
1041     Refs.swap(NextRefs);
1042   }
1043
1044   // Visit all leaf nodes.
1045   for (unsigned i = 0, e = Refs.size(); i != e; ++i)
1046     (this->*f)(Refs[i], 0);
1047 }
1048
1049 #ifndef NDEBUG
1050 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1051 void IntervalMap<KeyT, ValT, N, Traits>::
1052 dumpNode(NodeRef Node, unsigned Height) {
1053   if (Height)
1054     Node.branch().dump(Node.size());
1055   else
1056     Node.leaf().dump(Node.size());
1057 }
1058
1059 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1060 void IntervalMap<KeyT, ValT, N, Traits>::
1061 dump() {
1062   errs() << "digraph {\n";
1063   if (branched())
1064     rootBranch().dump(rootSize);
1065   else
1066     rootLeaf().dump(rootSize);
1067   visitNodes(&IntervalMap::dumpNode);
1068   errs() << "}\n";
1069 }
1070 #endif
1071
1072 //===----------------------------------------------------------------------===//
1073 //---                             const_iterator                          ----//
1074 //===----------------------------------------------------------------------===//
1075
1076 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1077 class IntervalMap<KeyT, ValT, N, Traits>::const_iterator :
1078   public std::iterator<std::bidirectional_iterator_tag, ValT> {
1079 protected:
1080   friend class IntervalMap;
1081   typedef std::pair<NodeRef, unsigned> PathEntry;
1082   typedef SmallVector<PathEntry, 4> Path;
1083
1084   // The map referred to.
1085   IntervalMap *map;
1086
1087   // The offset into map's root node.
1088   unsigned rootOffset;
1089
1090   // We store a full path from the root to the current position.
1091   //
1092   // When rootOffset == map->rootSize, we are at end() and path() is empty.
1093   // Otherwise, when branched these conditions hold:
1094   //
1095   // 1. path.front().first == rootBranch().subtree(rootOffset)
1096   // 2. path[i].first == path[i-1].first.branch().subtree(path[i-1].second)
1097   // 3. path.size() == map->height.
1098   //
1099   // Thus, path.back() always refers to the current leaf node unless the root is
1100   // unbranched.
1101   //
1102   // The path may be partially filled, but never between iterator calls.
1103   Path path;
1104
1105   explicit const_iterator(IntervalMap &map)
1106     : map(&map), rootOffset(map.rootSize) {}
1107
1108   bool branched() const {
1109     assert(map && "Invalid iterator");
1110     return map->branched();
1111   }
1112
1113   NodeRef   pathNode(unsigned h)   const { return path[h].first; }
1114   NodeRef  &pathNode(unsigned h)         { return path[h].first; }
1115   unsigned  pathOffset(unsigned h) const { return path[h].second; }
1116   unsigned &pathOffset(unsigned h)       { return path[h].second; }
1117
1118   Leaf &treeLeaf() const {
1119     assert(branched() && path.size() == map->height);
1120     return path.back().first.leaf();
1121   }
1122   unsigned treeLeafSize() const {
1123     assert(branched() && path.size() == map->height);
1124     return path.back().first.size();
1125   }
1126   unsigned &treeLeafOffset() {
1127     assert(branched() && path.size() == map->height);
1128     return path.back().second;
1129   }
1130   unsigned treeLeafOffset() const {
1131     assert(branched() && path.size() == map->height);
1132     return path.back().second;
1133   }
1134
1135   // Get the next node ptr for an incomplete path.
1136   NodeRef pathNextDown() {
1137     assert(path.size() < map->height && "Path is already complete");
1138
1139     if (path.empty())
1140       return map->rootBranch().subtree(rootOffset);
1141     else
1142       return path.back().first.branch().subtree(path.back().second);
1143   }
1144
1145   void pathFillLeft();
1146   void pathFillFind(KeyT x);
1147   void pathFillRight();
1148
1149   NodeRef leftSibling(unsigned level) const;
1150   NodeRef rightSibling(unsigned level) const;
1151
1152   void treeIncrement();
1153   void treeDecrement();
1154   void treeFind(KeyT x);
1155
1156 public:
1157   /// valid - Return true if the current position is valid, false for end().
1158   bool valid() const {
1159     assert(map && "Invalid iterator");
1160     return rootOffset < map->rootSize;
1161   }
1162
1163   /// start - Return the beginning of the current interval.
1164   const KeyT &start() const {
1165     assert(valid() && "Cannot access invalid iterator");
1166     return branched() ? treeLeaf().start(treeLeafOffset()) :
1167                         map->rootLeaf().start(rootOffset);
1168   }
1169
1170   /// stop - Return the end of the current interval.
1171   const KeyT &stop() const {
1172     assert(valid() && "Cannot access invalid iterator");
1173     return branched() ? treeLeaf().stop(treeLeafOffset()) :
1174                         map->rootLeaf().stop(rootOffset);
1175   }
1176
1177   /// value - Return the mapped value at the current interval.
1178   const ValT &value() const {
1179     assert(valid() && "Cannot access invalid iterator");
1180     return branched() ? treeLeaf().value(treeLeafOffset()) :
1181                         map->rootLeaf().value(rootOffset);
1182   }
1183
1184   const ValT &operator*() const {
1185     return value();
1186   }
1187
1188   bool operator==(const const_iterator &RHS) const {
1189     assert(map == RHS.map && "Cannot compare iterators from different maps");
1190     return rootOffset == RHS.rootOffset &&
1191              (!valid() || !branched() || path.back() == RHS.path.back());
1192   }
1193
1194   bool operator!=(const const_iterator &RHS) const {
1195     return !operator==(RHS);
1196   }
1197
1198   /// goToBegin - Move to the first interval in map.
1199   void goToBegin() {
1200     rootOffset = 0;
1201     path.clear();
1202     if (branched())
1203       pathFillLeft();
1204   }
1205
1206   /// goToEnd - Move beyond the last interval in map.
1207   void goToEnd() {
1208     rootOffset = map->rootSize;
1209     path.clear();
1210   }
1211
1212   /// preincrement - move to the next interval.
1213   const_iterator &operator++() {
1214     assert(valid() && "Cannot increment end()");
1215     if (!branched())
1216       ++rootOffset;
1217     else if (treeLeafOffset() != treeLeafSize() - 1)
1218       ++treeLeafOffset();
1219     else
1220       treeIncrement();
1221     return *this;
1222   }
1223
1224   /// postincrement - Dont do that!
1225   const_iterator operator++(int) {
1226     const_iterator tmp = *this;
1227     operator++();
1228     return tmp;
1229   }
1230
1231   /// predecrement - move to the previous interval.
1232   const_iterator &operator--() {
1233     if (!branched()) {
1234       assert(rootOffset && "Cannot decrement begin()");
1235       --rootOffset;
1236     } else if (treeLeafOffset())
1237       --treeLeafOffset();
1238     else
1239       treeDecrement();
1240     return *this;
1241   }
1242
1243   /// postdecrement - Dont do that!
1244   const_iterator operator--(int) {
1245     const_iterator tmp = *this;
1246     operator--();
1247     return tmp;
1248   }
1249
1250   /// find - Move to the first interval with stop >= x, or end().
1251   /// This is a full search from the root, the current position is ignored.
1252   void find(KeyT x) {
1253     if (branched())
1254       treeFind(x);
1255     else
1256       rootOffset = map->rootLeaf().findFrom(0, map->rootSize, x);
1257   }
1258
1259   /// advanceTo - Move to the first interval with stop >= x, or end().
1260   /// The search is started from the current position, and no earlier positions
1261   /// can be found. This is much faster than find() for small moves.
1262   void advanceTo(KeyT x) {
1263     if (branched())
1264       treeAdvanceTo(x);
1265     else
1266       rootOffset = map->rootLeaf().findFrom(rootOffset, map->rootSize, x);
1267   }
1268
1269 };
1270
1271 // pathFillLeft - Complete path by following left-most branches.
1272 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1273 void IntervalMap<KeyT, ValT, N, Traits>::
1274 const_iterator::pathFillLeft() {
1275   NodeRef NR = pathNextDown();
1276   for (unsigned i = map->height - path.size() - 1; i; --i) {
1277     path.push_back(PathEntry(NR, 0));
1278     NR = NR.branch().subtree(0);
1279   }
1280   path.push_back(PathEntry(NR, 0));
1281 }
1282
1283 // pathFillFind - Complete path by searching for x.
1284 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1285 void IntervalMap<KeyT, ValT, N, Traits>::
1286 const_iterator::pathFillFind(KeyT x) {
1287   NodeRef NR = pathNextDown();
1288   for (unsigned i = map->height - path.size() - 1; i; --i) {
1289     unsigned p = NR.branch().safeFind(0, x);
1290     path.push_back(PathEntry(NR, p));
1291     NR = NR.branch().subtree(p);
1292   }
1293   path.push_back(PathEntry(NR, NR.leaf().safeFind(0, x)));
1294 }
1295
1296 // pathFillRight - Complete path by adding rightmost entries.
1297 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1298 void IntervalMap<KeyT, ValT, N, Traits>::
1299 const_iterator::pathFillRight() {
1300   NodeRef NR = pathNextDown();
1301   for (unsigned i = map->height - path.size() - 1; i; --i) {
1302     unsigned p = NR.size() - 1;
1303     path.push_back(PathEntry(NR, p));
1304     NR = NR.branch().subtree(p);
1305   }
1306   path.push_back(PathEntry(NR, NR.size() - 1));
1307 }
1308
1309 /// leftSibling - find the left sibling node to path[level].
1310 /// @param level 0 is just below the root, map->height - 1 for the leaves.
1311 /// @return The left sibling NodeRef, or NULL.
1312 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1313 typename IntervalMap<KeyT, ValT, N, Traits>::NodeRef
1314 IntervalMap<KeyT, ValT, N, Traits>::
1315 const_iterator::leftSibling(unsigned level) const {
1316   assert(branched() && "Not at a branched node");
1317   assert(level <= path.size() && "Bad level");
1318
1319   // Go up the tree until we can go left.
1320   unsigned h = level;
1321   while (h && pathOffset(h - 1) == 0)
1322     --h;
1323
1324   // We are at the first leaf node, no left sibling.
1325   if (!h && rootOffset == 0)
1326     return NodeRef();
1327
1328   // NR is the subtree containing our left sibling.
1329   NodeRef NR = h ?
1330     pathNode(h - 1).branch().subtree(pathOffset(h - 1) - 1) :
1331     map->rootBranch().subtree(rootOffset - 1);
1332
1333   // Keep right all the way down.
1334   for (; h != level; ++h)
1335     NR = NR.branch().subtree(NR.size() - 1);
1336   return NR;
1337 }
1338
1339 /// rightSibling - find the right sibling node to path[level].
1340 /// @param level 0 is just below the root, map->height - 1 for the leaves.
1341 /// @return The right sibling NodeRef, or NULL.
1342 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1343 typename IntervalMap<KeyT, ValT, N, Traits>::NodeRef
1344 IntervalMap<KeyT, ValT, N, Traits>::
1345 const_iterator::rightSibling(unsigned level) const {
1346   assert(branched() && "Not at a branched node");
1347   assert(level <= this->path.size() && "Bad level");
1348
1349   // Go up the tree until we can go right.
1350   unsigned h = level;
1351   while (h && pathOffset(h - 1) == pathNode(h - 1).size() - 1)
1352     --h;
1353
1354   // We are at the last leaf node, no right sibling.
1355   if (!h && rootOffset == map->rootSize - 1)
1356     return NodeRef();
1357
1358   // NR is the subtree containing our right sibling.
1359   NodeRef NR = h ?
1360     pathNode(h - 1).branch().subtree(pathOffset(h - 1) + 1) :
1361     map->rootBranch().subtree(rootOffset + 1);
1362
1363   // Keep left all the way down.
1364   for (; h != level; ++h)
1365     NR = NR.branch().subtree(0);
1366   return NR;
1367 }
1368
1369 // treeIncrement - Move to the beginning of the next leaf node.
1370 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1371 void IntervalMap<KeyT, ValT, N, Traits>::
1372 const_iterator::treeIncrement() {
1373   assert(branched() && "treeIncrement is not for small maps");
1374   assert(path.size() == map->height && "inconsistent iterator");
1375   do path.pop_back();
1376   while (!path.empty() && path.back().second == path.back().first.size() - 1);
1377   if (path.empty()) {
1378     ++rootOffset;
1379     if (!valid())
1380       return;
1381   } else
1382     ++path.back().second;
1383   pathFillLeft();
1384 }
1385
1386 // treeDecrement - Move to the end of the previous leaf node.
1387 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1388 void IntervalMap<KeyT, ValT, N, Traits>::
1389 const_iterator::treeDecrement() {
1390   assert(branched() && "treeDecrement is not for small maps");
1391   if (valid()) {
1392     assert(path.size() == map->height && "inconsistent iterator");
1393     do path.pop_back();
1394     while (!path.empty() && path.back().second == 0);
1395   }
1396   if (path.empty()) {
1397     assert(rootOffset && "cannot treeDecrement() on begin()");
1398     --rootOffset;
1399   } else
1400     --path.back().second;
1401   pathFillRight();
1402 }
1403
1404 // treeFind - Find in a branched tree.
1405 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1406 void IntervalMap<KeyT, ValT, N, Traits>::
1407 const_iterator::treeFind(KeyT x) {
1408   path.clear();
1409   rootOffset = map->rootBranch().findFrom(0, map->rootSize, x);
1410   if (valid())
1411     pathFillFind(x);
1412 }
1413
1414
1415 //===----------------------------------------------------------------------===//
1416 //---                                iterator                             ----//
1417 //===----------------------------------------------------------------------===//
1418
1419 namespace IntervalMapImpl {
1420
1421   /// distribute - Compute a new distribution of node elements after an overflow
1422   /// or underflow. Reserve space for a new element at Position, and compute the
1423   /// node that will hold Position after redistributing node elements.
1424   ///
1425   /// It is required that
1426   ///
1427   ///   Elements == sum(CurSize), and
1428   ///   Elements + Grow <= Nodes * Capacity.
1429   ///
1430   /// NewSize[] will be filled in such that:
1431   ///
1432   ///   sum(NewSize) == Elements, and
1433   ///   NewSize[i] <= Capacity.
1434   ///
1435   /// The returned index is the node where Position will go, so:
1436   ///
1437   ///   sum(NewSize[0..idx-1]) <= Position
1438   ///   sum(NewSize[0..idx])   >= Position
1439   ///
1440   /// The last equality, sum(NewSize[0..idx]) == Position, can only happen when
1441   /// Grow is set and NewSize[idx] == Capacity-1. The index points to the node
1442   /// before the one holding the Position'th element where there is room for an
1443   /// insertion.
1444   ///
1445   /// @param Nodes    The number of nodes.
1446   /// @param Elements Total elements in all nodes.
1447   /// @param Capacity The capacity of each node.
1448   /// @param CurSize  Array[Nodes] of current node sizes, or NULL.
1449   /// @param NewSize  Array[Nodes] to receive the new node sizes.
1450   /// @param Position Insert position.
1451   /// @param Grow     Reserve space for a new element at Position.
1452   /// @return         (node, offset) for Position.
1453   IdxPair distribute(unsigned Nodes, unsigned Elements, unsigned Capacity,
1454                      const unsigned *CurSize, unsigned NewSize[],
1455                      unsigned Position, bool Grow);
1456
1457 }
1458
1459 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1460 class IntervalMap<KeyT, ValT, N, Traits>::iterator : public const_iterator {
1461   friend class IntervalMap;
1462   typedef IntervalMapImpl::IdxPair IdxPair;
1463
1464   explicit iterator(IntervalMap &map) : const_iterator(map) {}
1465
1466   void setNodeSize(unsigned Level, unsigned Size);
1467   void setNodeStop(unsigned Level, KeyT Stop);
1468   void insertNode(unsigned Level, NodeRef Node, KeyT Stop);
1469   void overflowLeaf();
1470   void treeInsert(KeyT a, KeyT b, ValT y);
1471
1472 public:
1473   /// insert - Insert mapping [a;b] -> y before the current position.
1474   void insert(KeyT a, KeyT b, ValT y);
1475
1476 };
1477
1478 /// setNodeSize - Set the size of the node at path[level], updating both path
1479 /// and the real tree.
1480 /// @param level 0 is just below the root, map->height - 1 for the leaves.
1481 /// @param size  New node size.
1482 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1483 void IntervalMap<KeyT, ValT, N, Traits>::
1484 iterator::setNodeSize(unsigned Level, unsigned Size) {
1485   this->pathNode(Level).setSize(Size);
1486   if (Level)
1487     this->pathNode(Level-1).branch()
1488       .subtree(this->pathOffset(Level-1)).setSize(Size);
1489   else
1490     this->map->rootBranch().subtree(this->rootOffset).setSize(Size);
1491 }
1492
1493 /// setNodeStop - Update the stop key of the current node at level and above.
1494 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1495 void IntervalMap<KeyT, ValT, N, Traits>::
1496 iterator::setNodeStop(unsigned Level, KeyT Stop) {
1497   while (Level--) {
1498     this->pathNode(Level).branch().stop(this->pathOffset(Level)) = Stop;
1499     if (this->pathOffset(Level) != this->pathNode(Level).size() - 1)
1500       return;
1501   }
1502   this->map->rootBranch().stop(this->rootOffset) = Stop;
1503 }
1504
1505 /// insertNode - insert a node before the current path at level.
1506 /// Leave the current path pointing at the new node.
1507 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1508 void IntervalMap<KeyT, ValT, N, Traits>::
1509 iterator::insertNode(unsigned Level, NodeRef Node, KeyT Stop) {
1510   if (!Level) {
1511     // Insert into the root branch node.
1512     IntervalMap &IM = *this->map;
1513     if (IM.rootSize < RootBranch::Capacity) {
1514       IM.rootBranch().insert(this->rootOffset, IM.rootSize, Node, Stop);
1515       ++IM.rootSize;
1516       return;
1517     }
1518
1519     // We need to split the root while keeping our position.
1520     IdxPair Offset = IM.splitRoot(this->rootOffset);
1521     this->rootOffset = Offset.first;
1522     this->path.insert(this->path.begin(),std::make_pair(
1523       this->map->rootBranch().subtree(Offset.first), Offset.second));
1524     Level = 1;
1525   }
1526
1527   // When inserting before end(), make sure we have a valid path.
1528   if (!this->valid()) {
1529     this->treeDecrement();
1530     ++this->pathOffset(Level-1);
1531   }
1532
1533   // Insert into the branch node at level-1.
1534   NodeRef NR = this->pathNode(Level-1);
1535   unsigned Offset = this->pathOffset(Level-1);
1536   assert(NR.size() < Branch::Capacity && "Branch overflow");
1537   NR.branch().insert(Offset, NR.size(), Node, Stop);
1538   setNodeSize(Level - 1, NR.size() + 1);
1539 }
1540
1541 // insert
1542 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1543 void IntervalMap<KeyT, ValT, N, Traits>::
1544 iterator::insert(KeyT a, KeyT b, ValT y) {
1545   if (this->branched())
1546     return treeInsert(a, b, y);
1547   IdxPair IP = this->map->rootLeaf().insertFrom(this->rootOffset,
1548                                                 this->map->rootSize,
1549                                                 a, b, y);
1550   if (IP.second <= RootLeaf::Capacity) {
1551     this->rootOffset = IP.first;
1552     this->map->rootSize = IP.second;
1553     return;
1554   }
1555   IdxPair Offset = this->map->branchRoot(this->rootOffset);
1556   this->rootOffset = Offset.first;
1557   this->path.push_back(std::make_pair(
1558     this->map->rootBranch().subtree(Offset.first), Offset.second));
1559   treeInsert(a, b, y);
1560 }
1561
1562
1563 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1564 void IntervalMap<KeyT, ValT, N, Traits>::
1565 iterator::treeInsert(KeyT a, KeyT b, ValT y) {
1566   if (!this->valid()) {
1567     // end() has an empty path. Go back to the last leaf node and use an
1568     // invalid offset instead.
1569     this->treeDecrement();
1570     ++this->treeLeafOffset();
1571   }
1572   IdxPair IP = this->treeLeaf().insertFrom(this->treeLeafOffset(),
1573                                            this->treeLeafSize(), a, b, y);
1574   this->treeLeafOffset() = IP.first;
1575   if (IP.second <= Leaf::Capacity) {
1576     setNodeSize(this->map->height - 1, IP.second);
1577     if (IP.first == IP.second - 1)
1578       setNodeStop(this->map->height - 1, this->treeLeaf().stop(IP.first));
1579     return;
1580   }
1581   // Leaf node has no space.
1582   overflowLeaf();
1583   IP = this->treeLeaf().insertFrom(this->treeLeafOffset(),
1584                                    this->treeLeafSize(), a, b, y);
1585   this->treeLeafOffset() = IP.first;
1586   setNodeSize(this->map->height-1, IP.second);
1587   if (IP.first == IP.second - 1)
1588     setNodeStop(this->map->height - 1, this->treeLeaf().stop(IP.first));
1589
1590   // FIXME: Handle cross-node coalescing.
1591 }
1592
1593 // overflowLeaf - Distribute entries of the current leaf node evenly among
1594 // its siblings and ensure that the current node is not full.
1595 // This may require allocating a new node.
1596 template <typename KeyT, typename ValT, unsigned N, typename Traits>
1597 void IntervalMap<KeyT, ValT, N, Traits>::
1598 iterator::overflowLeaf() {
1599   unsigned CurSize[4];
1600   Leaf *Node[4];
1601   unsigned Nodes = 0;
1602   unsigned Elements = 0;
1603   unsigned Offset = this->treeLeafOffset();
1604
1605   // Do we have a left sibling?
1606   NodeRef LeftSib = this->leftSibling(this->map->height-1);
1607   if (LeftSib) {
1608     Offset += Elements = CurSize[Nodes] = LeftSib.size();
1609     Node[Nodes++] = &LeftSib.leaf();
1610   }
1611
1612   // Current leaf node.
1613   Elements += CurSize[Nodes] = this->treeLeafSize();
1614   Node[Nodes++] = &this->treeLeaf();
1615
1616   // Do we have a right sibling?
1617   NodeRef RightSib = this->rightSibling(this->map->height-1);
1618   if (RightSib) {
1619     Offset += Elements = CurSize[Nodes] = RightSib.size();
1620     Node[Nodes++] = &RightSib.leaf();
1621   }
1622
1623   // Do we need to allocate a new node?
1624   unsigned NewNode = 0;
1625   if (Elements + 1 > Nodes * Leaf::Capacity) {
1626     // Insert NewNode at the penultimate position, or after a single node.
1627     NewNode = Nodes == 1 ? 1 : Nodes - 1;
1628     CurSize[Nodes] = CurSize[NewNode];
1629     Node[Nodes] = Node[NewNode];
1630     CurSize[NewNode] = 0;
1631     Node[NewNode] = this->map->allocLeaf();
1632     ++Nodes;
1633   }
1634
1635   // Compute the new element distribution.
1636   unsigned NewSize[4];
1637   IdxPair NewOffset =
1638     IntervalMapImpl::distribute(Nodes, Elements, Leaf::Capacity,
1639                                 CurSize, NewSize, Offset, true);
1640
1641   // Move current location to the leftmost node.
1642   if (LeftSib)
1643     this->treeDecrement();
1644
1645   // Move elements right.
1646   for (int n = Nodes - 1; n; --n) {
1647     if (CurSize[n] == NewSize[n])
1648       continue;
1649     for (int m = n - 1; m != -1; --m) {
1650       int d = Node[n]->adjLeftSib(CurSize[n], *Node[m], CurSize[m],
1651                                         NewSize[n] - CurSize[n]);
1652       CurSize[m] -= d;
1653       CurSize[n] += d;
1654       // Keep going if the current node was exhausted.
1655       if (CurSize[n] >= NewSize[n])
1656           break;
1657     }
1658   }
1659
1660   // Move elements left.
1661   for (unsigned n = 0; n != Nodes - 1; ++n) {
1662     if (CurSize[n] == NewSize[n])
1663       continue;
1664     for (unsigned m = n + 1; m != Nodes; ++m) {
1665       int d = Node[m]->adjLeftSib(CurSize[m], *Node[n], CurSize[n],
1666                                         CurSize[n] -  NewSize[n]);
1667       CurSize[m] += d;
1668       CurSize[n] -= d;
1669       // Keep going if the current node was exhausted.
1670       if (CurSize[n] >= NewSize[n])
1671           break;
1672     }
1673   }
1674
1675 #ifndef NDEBUG
1676   for (unsigned n = 0; n != Nodes; n++)
1677     assert(CurSize[n] == NewSize[n] && "Insufficient element shuffle");
1678 #endif
1679
1680   // Elements have been rearranged, now update node sizes and stops.
1681   unsigned Pos = 0;
1682   for (;;) {
1683     KeyT Stop = Node[Pos]->stop(NewSize[Pos]-1);
1684     if (NewNode && Pos == NewNode)
1685       insertNode(this->map->height - 1, NodeRef(Node[Pos], NewSize[Pos]), Stop);
1686     else {
1687       setNodeSize(this->map->height - 1, NewSize[Pos]);
1688       setNodeStop(this->map->height - 1, Stop);
1689     }
1690     if (Pos + 1 == Nodes)
1691       break;
1692     this->treeIncrement();
1693     ++Pos;
1694   }
1695
1696   // Where was I? Find NewOffset.
1697   while(Pos != NewOffset.first) {
1698     this->treeDecrement();
1699     --Pos;
1700   }
1701   this->treeLeafOffset() = NewOffset.second;
1702 }
1703
1704 } // namespace llvm
1705
1706 #endif