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