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