We have logic in there to emit a default debugging label at the beginning of a
[oota-llvm.git] / include / llvm / ADT / ilist.h
1 //==-- llvm/ADT/ilist.h - Intrusive Linked List Template ---------*- 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 defines classes to implement an intrusive doubly linked list class
11 // (i.e. each node of the list must contain a next and previous field for the
12 // list.
13 //
14 // The ilist_traits trait class is used to gain access to the next and previous
15 // fields of the node type that the list is instantiated with.  If it is not
16 // specialized, the list defaults to using the getPrev(), getNext() method calls
17 // to get the next and previous pointers.
18 //
19 // The ilist class itself, should be a plug in replacement for list, assuming
20 // that the nodes contain next/prev pointers.  This list replacement does not
21 // provide a constant time size() method, so be careful to use empty() when you
22 // really want to know if it's empty.
23 //
24 // The ilist class is implemented by allocating a 'tail' node when the list is
25 // created (using ilist_traits<>::createSentinel()).  This tail node is
26 // absolutely required because the user must be able to compute end()-1. Because
27 // of this, users of the direct next/prev links will see an extra link on the
28 // end of the list, which should be ignored.
29 //
30 // Requirements for a user of this list:
31 //
32 //   1. The user must provide {g|s}et{Next|Prev} methods, or specialize
33 //      ilist_traits to provide an alternate way of getting and setting next and
34 //      prev links.
35 //
36 //===----------------------------------------------------------------------===//
37
38 #ifndef LLVM_ADT_ILIST_H
39 #define LLVM_ADT_ILIST_H
40
41 #include "llvm/ADT/iterator.h"
42 #include <cassert>
43
44 namespace llvm {
45
46 template<typename NodeTy, typename Traits> class iplist;
47 template<typename NodeTy> class ilist_iterator;
48
49 /// ilist_nextprev_traits - A fragment for template traits for intrusive list
50 /// that provides default next/prev implementations for common operations.
51 ///
52 template<typename NodeTy>
53 struct ilist_nextprev_traits {
54   static NodeTy *getPrev(NodeTy *N) { return N->getPrev(); }
55   static NodeTy *getNext(NodeTy *N) { return N->getNext(); }
56   static const NodeTy *getPrev(const NodeTy *N) { return N->getPrev(); }
57   static const NodeTy *getNext(const NodeTy *N) { return N->getNext(); }
58
59   static void setPrev(NodeTy *N, NodeTy *Prev) { N->setPrev(Prev); }
60   static void setNext(NodeTy *N, NodeTy *Next) { N->setNext(Next); }
61 };
62
63 /// ilist_sentinel_traits - A fragment for template traits for intrusive list
64 /// that provides default sentinel implementations for common operations.
65 ///
66 template<typename NodeTy>
67 struct ilist_sentinel_traits {
68   static NodeTy *createSentinel() { return new NodeTy(); }
69   static void destroySentinel(NodeTy *N) { delete N; }
70 };
71
72 /// ilist_default_traits - Default template traits for intrusive list.
73 /// By inheriting from this, you can easily use default implementations
74 /// for all common operations.
75 ///
76 template<typename NodeTy>
77 struct ilist_default_traits : ilist_nextprev_traits<NodeTy>,
78                               ilist_sentinel_traits<NodeTy> {
79   static NodeTy *createNode(const NodeTy &V) { return new NodeTy(V); }
80   static void deleteNode(NodeTy *V) { delete V; }
81
82   void addNodeToList(NodeTy *) {}
83   void removeNodeFromList(NodeTy *) {}
84   void transferNodesFromList(ilist_default_traits & /*SrcTraits*/,
85                              ilist_iterator<NodeTy> /*first*/,
86                              ilist_iterator<NodeTy> /*last*/) {}
87 };
88
89 // Template traits for intrusive list.  By specializing this template class, you
90 // can change what next/prev fields are used to store the links...
91 template<typename NodeTy>
92 struct ilist_traits : ilist_default_traits<NodeTy> {};
93
94 // Const traits are the same as nonconst traits...
95 template<typename Ty>
96 struct ilist_traits<const Ty> : public ilist_traits<Ty> {};
97
98 //===----------------------------------------------------------------------===//
99 // ilist_iterator<Node> - Iterator for intrusive list.
100 //
101 template<typename NodeTy>
102 class ilist_iterator
103   : public bidirectional_iterator<NodeTy, ptrdiff_t> {
104
105 public:
106   typedef ilist_traits<NodeTy> Traits;
107   typedef bidirectional_iterator<NodeTy, ptrdiff_t> super;
108
109   typedef typename super::value_type value_type;
110   typedef typename super::difference_type difference_type;
111   typedef typename super::pointer pointer;
112   typedef typename super::reference reference;
113 private:
114   pointer NodePtr;
115
116   // ilist_iterator is not a random-access iterator, but it has an
117   // implicit conversion to pointer-type, which is. Declare (but
118   // don't define) these functions as private to help catch
119   // accidental misuse.
120   void operator[](difference_type) const;
121   void operator+(difference_type) const;
122   void operator-(difference_type) const;
123   void operator+=(difference_type) const;
124   void operator-=(difference_type) const;
125   template<class T> void operator<(T) const;
126   template<class T> void operator<=(T) const;
127   template<class T> void operator>(T) const;
128   template<class T> void operator>=(T) const;
129   template<class T> void operator-(T) const;
130 public:
131
132   ilist_iterator(pointer NP) : NodePtr(NP) {}
133   ilist_iterator(reference NR) : NodePtr(&NR) {}
134   ilist_iterator() : NodePtr(0) {}
135
136   // This is templated so that we can allow constructing a const iterator from
137   // a nonconst iterator...
138   template<class node_ty>
139   ilist_iterator(const ilist_iterator<node_ty> &RHS)
140     : NodePtr(RHS.getNodePtrUnchecked()) {}
141
142   // This is templated so that we can allow assigning to a const iterator from
143   // a nonconst iterator...
144   template<class node_ty>
145   const ilist_iterator &operator=(const ilist_iterator<node_ty> &RHS) {
146     NodePtr = RHS.getNodePtrUnchecked();
147     return *this;
148   }
149
150   // Accessors...
151   operator pointer() const {
152     assert(Traits::getNext(NodePtr) != 0 && "Dereferencing end()!");
153     return NodePtr;
154   }
155
156   reference operator*() const {
157     assert(Traits::getNext(NodePtr) != 0 && "Dereferencing end()!");
158     return *NodePtr;
159   }
160   pointer operator->() const { return &operator*(); }
161
162   // Comparison operators
163   bool operator==(const ilist_iterator &RHS) const {
164     return NodePtr == RHS.NodePtr;
165   }
166   bool operator!=(const ilist_iterator &RHS) const {
167     return NodePtr != RHS.NodePtr;
168   }
169
170   // Increment and decrement operators...
171   ilist_iterator &operator--() {      // predecrement - Back up
172     NodePtr = Traits::getPrev(NodePtr);
173     assert(Traits::getNext(NodePtr) && "--'d off the beginning of an ilist!");
174     return *this;
175   }
176   ilist_iterator &operator++() {      // preincrement - Advance
177     NodePtr = Traits::getNext(NodePtr);
178     assert(NodePtr && "++'d off the end of an ilist!");
179     return *this;
180   }
181   ilist_iterator operator--(int) {    // postdecrement operators...
182     ilist_iterator tmp = *this;
183     --*this;
184     return tmp;
185   }
186   ilist_iterator operator++(int) {    // postincrement operators...
187     ilist_iterator tmp = *this;
188     ++*this;
189     return tmp;
190   }
191
192   // Internal interface, do not use...
193   pointer getNodePtrUnchecked() const { return NodePtr; }
194 };
195
196 // do not implement. this is to catch errors when people try to use
197 // them as random access iterators
198 template<typename T>
199 void operator-(int, ilist_iterator<T>);
200 template<typename T>
201 void operator-(ilist_iterator<T>,int);
202
203 template<typename T>
204 void operator+(int, ilist_iterator<T>);
205 template<typename T>
206 void operator+(ilist_iterator<T>,int);
207
208 // operator!=/operator== - Allow mixed comparisons without dereferencing
209 // the iterator, which could very likely be pointing to end().
210 template<typename T>
211 bool operator!=(const T* LHS, const ilist_iterator<const T> &RHS) {
212   return LHS != RHS.getNodePtrUnchecked();
213 }
214 template<typename T>
215 bool operator==(const T* LHS, const ilist_iterator<const T> &RHS) {
216   return LHS == RHS.getNodePtrUnchecked();
217 }
218 template<typename T>
219 bool operator!=(T* LHS, const ilist_iterator<T> &RHS) {
220   return LHS != RHS.getNodePtrUnchecked();
221 }
222 template<typename T>
223 bool operator==(T* LHS, const ilist_iterator<T> &RHS) {
224   return LHS == RHS.getNodePtrUnchecked();
225 }
226
227
228 // Allow ilist_iterators to convert into pointers to a node automatically when
229 // used by the dyn_cast, cast, isa mechanisms...
230
231 template<typename From> struct simplify_type;
232
233 template<typename NodeTy> struct simplify_type<ilist_iterator<NodeTy> > {
234   typedef NodeTy* SimpleType;
235
236   static SimpleType getSimplifiedValue(const ilist_iterator<NodeTy> &Node) {
237     return &*Node;
238   }
239 };
240 template<typename NodeTy> struct simplify_type<const ilist_iterator<NodeTy> > {
241   typedef NodeTy* SimpleType;
242
243   static SimpleType getSimplifiedValue(const ilist_iterator<NodeTy> &Node) {
244     return &*Node;
245   }
246 };
247
248
249 //===----------------------------------------------------------------------===//
250 //
251 /// iplist - The subset of list functionality that can safely be used on nodes
252 /// of polymorphic types, i.e. a heterogenous list with a common base class that
253 /// holds the next/prev pointers.  The only state of the list itself is a single
254 /// pointer to the head of the list.
255 ///
256 /// This list can be in one of three interesting states:
257 /// 1. The list may be completely unconstructed.  In this case, the head
258 ///    pointer is null.  When in this form, any query for an iterator (e.g.
259 ///    begin() or end()) causes the list to transparently change to state #2.
260 /// 2. The list may be empty, but contain a sentinel for the end iterator. This
261 ///    sentinel is created by the Traits::createSentinel method and is a link
262 ///    in the list.  When the list is empty, the pointer in the iplist points
263 ///    to the sentinel.  Once the sentinel is constructed, it
264 ///    is not destroyed until the list is.
265 /// 3. The list may contain actual objects in it, which are stored as a doubly
266 ///    linked list of nodes.  One invariant of the list is that the predecessor
267 ///    of the first node in the list always points to the last node in the list,
268 ///    and the successor pointer for the sentinel (which always stays at the
269 ///    end of the list) is always null.
270 ///
271 template<typename NodeTy, typename Traits=ilist_traits<NodeTy> >
272 class iplist : public Traits {
273   mutable NodeTy *Head;
274
275   // Use the prev node pointer of 'head' as the tail pointer.  This is really a
276   // circularly linked list where we snip the 'next' link from the sentinel node
277   // back to the first node in the list (to preserve assertions about going off
278   // the end of the list).
279   NodeTy *getTail() { return this->getPrev(Head); }
280   const NodeTy *getTail() const { return this->getPrev(Head); }
281   void setTail(NodeTy *N) const { this->setPrev(Head, N); }
282
283   /// CreateLazySentinel - This method verifies whether the sentinel for the
284   /// list has been created and lazily makes it if not.
285   void CreateLazySentinel() const {
286     if (Head != 0) return;
287     Head = Traits::createSentinel();
288     this->setNext(Head, 0);
289     setTail(Head);
290   }
291
292   static bool op_less(NodeTy &L, NodeTy &R) { return L < R; }
293   static bool op_equal(NodeTy &L, NodeTy &R) { return L == R; }
294
295   // No fundamental reason why iplist can't by copyable, but the default
296   // copy/copy-assign won't do.
297   iplist(const iplist &);         // do not implement
298   void operator=(const iplist &); // do not implement
299
300 public:
301   typedef NodeTy *pointer;
302   typedef const NodeTy *const_pointer;
303   typedef NodeTy &reference;
304   typedef const NodeTy &const_reference;
305   typedef NodeTy value_type;
306   typedef ilist_iterator<NodeTy> iterator;
307   typedef ilist_iterator<const NodeTy> const_iterator;
308   typedef size_t size_type;
309   typedef ptrdiff_t difference_type;
310   typedef std::reverse_iterator<const_iterator>  const_reverse_iterator;
311   typedef std::reverse_iterator<iterator>  reverse_iterator;
312
313   iplist() : Head(0) {}
314   ~iplist() {
315     if (!Head) return;
316     clear();
317     Traits::destroySentinel(getTail());
318   }
319
320   // Iterator creation methods.
321   iterator begin() {
322     CreateLazySentinel();
323     return iterator(Head);
324   }
325   const_iterator begin() const {
326     CreateLazySentinel();
327     return const_iterator(Head);
328   }
329   iterator end() {
330     CreateLazySentinel();
331     return iterator(getTail());
332   }
333   const_iterator end() const {
334     CreateLazySentinel();
335     return const_iterator(getTail());
336   }
337
338   // reverse iterator creation methods.
339   reverse_iterator rbegin()            { return reverse_iterator(end()); }
340   const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
341   reverse_iterator rend()              { return reverse_iterator(begin()); }
342   const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
343
344
345   // Miscellaneous inspection routines.
346   size_type max_size() const { return size_type(-1); }
347   bool empty() const { return Head == 0 || Head == getTail(); }
348
349   // Front and back accessor functions...
350   reference front() {
351     assert(!empty() && "Called front() on empty list!");
352     return *Head;
353   }
354   const_reference front() const {
355     assert(!empty() && "Called front() on empty list!");
356     return *Head;
357   }
358   reference back() {
359     assert(!empty() && "Called back() on empty list!");
360     return *this->getPrev(getTail());
361   }
362   const_reference back() const {
363     assert(!empty() && "Called back() on empty list!");
364     return *this->getPrev(getTail());
365   }
366
367   void swap(iplist &RHS) {
368     assert(0 && "Swap does not use list traits callback correctly yet!");
369     std::swap(Head, RHS.Head);
370   }
371
372   iterator insert(iterator where, NodeTy *New) {
373     NodeTy *CurNode = where.getNodePtrUnchecked(), *PrevNode = this->getPrev(CurNode);
374     this->setNext(New, CurNode);
375     this->setPrev(New, PrevNode);
376
377     if (CurNode != Head)  // Is PrevNode off the beginning of the list?
378       this->setNext(PrevNode, New);
379     else
380       Head = New;
381     this->setPrev(CurNode, New);
382
383     this->addNodeToList(New);  // Notify traits that we added a node...
384     return New;
385   }
386
387   iterator insertAfter(iterator where, NodeTy *New) {
388     if (empty()) 
389       return insert(begin(), New);
390     else
391       return insert(++where, New);
392   }
393
394   NodeTy *remove(iterator &IT) {
395     assert(IT != end() && "Cannot remove end of list!");
396     NodeTy *Node = &*IT;
397     NodeTy *NextNode = this->getNext(Node);
398     NodeTy *PrevNode = this->getPrev(Node);
399
400     if (Node != Head)  // Is PrevNode off the beginning of the list?
401       this->setNext(PrevNode, NextNode);
402     else
403       Head = NextNode;
404     this->setPrev(NextNode, PrevNode);
405     IT = NextNode;
406     this->removeNodeFromList(Node);  // Notify traits that we removed a node...
407
408     // Set the next/prev pointers of the current node to null.  This isn't
409     // strictly required, but this catches errors where a node is removed from
410     // an ilist (and potentially deleted) with iterators still pointing at it.
411     // When those iterators are incremented or decremented, they will assert on
412     // the null next/prev pointer instead of "usually working".
413     this->setNext(Node, 0);
414     this->setPrev(Node, 0);
415     return Node;
416   }
417
418   NodeTy *remove(const iterator &IT) {
419     iterator MutIt = IT;
420     return remove(MutIt);
421   }
422
423   // erase - remove a node from the controlled sequence... and delete it.
424   iterator erase(iterator where) {
425     this->deleteNode(remove(where));
426     return where;
427   }
428
429
430 private:
431   // transfer - The heart of the splice function.  Move linked list nodes from
432   // [first, last) into position.
433   //
434   void transfer(iterator position, iplist &L2, iterator first, iterator last) {
435     assert(first != last && "Should be checked by callers");
436
437     if (position != last) {
438       // Note: we have to be careful about the case when we move the first node
439       // in the list.  This node is the list sentinel node and we can't move it.
440       NodeTy *ThisSentinel = getTail();
441       setTail(0);
442       NodeTy *L2Sentinel = L2.getTail();
443       L2.setTail(0);
444
445       // Remove [first, last) from its old position.
446       NodeTy *First = &*first, *Prev = getPrev(First);
447       NodeTy *Next = last.getNodePtrUnchecked(), *Last = getPrev(Next);
448       if (Prev)
449         this->setNext(Prev, Next);
450       else
451         L2.Head = Next;
452       this->setPrev(Next, Prev);
453
454       // Splice [first, last) into its new position.
455       NodeTy *PosNext = position.getNodePtrUnchecked();
456       NodeTy *PosPrev = getPrev(PosNext);
457
458       // Fix head of list...
459       if (PosPrev)
460         this->setNext(PosPrev, First);
461       else
462         Head = First;
463       this->setPrev(First, PosPrev);
464
465       // Fix end of list...
466       this->setNext(Last, PosNext);
467       this->setPrev(PosNext, Last);
468
469       transferNodesFromList(L2, First, PosNext);
470
471       // Now that everything is set, restore the pointers to the list sentinels.
472       L2.setTail(L2Sentinel);
473       setTail(ThisSentinel);
474     }
475   }
476
477 public:
478
479   //===----------------------------------------------------------------------===
480   // Functionality derived from other functions defined above...
481   //
482
483   size_type size() const {
484     if (Head == 0) return 0; // Don't require construction of sentinel if empty.
485 #if __GNUC__ == 2
486     // GCC 2.95 has a broken std::distance
487     size_type Result = 0;
488     std::distance(begin(), end(), Result);
489     return Result;
490 #else
491     return std::distance(begin(), end());
492 #endif
493   }
494
495   iterator erase(iterator first, iterator last) {
496     while (first != last)
497       first = erase(first);
498     return last;
499   }
500
501   void clear() { if (Head) erase(begin(), end()); }
502
503   // Front and back inserters...
504   void push_front(NodeTy *val) { insert(begin(), val); }
505   void push_back(NodeTy *val) { insert(end(), val); }
506   void pop_front() {
507     assert(!empty() && "pop_front() on empty list!");
508     erase(begin());
509   }
510   void pop_back() {
511     assert(!empty() && "pop_back() on empty list!");
512     iterator t = end(); erase(--t);
513   }
514
515   // Special forms of insert...
516   template<class InIt> void insert(iterator where, InIt first, InIt last) {
517     for (; first != last; ++first) insert(where, *first);
518   }
519
520   // Splice members - defined in terms of transfer...
521   void splice(iterator where, iplist &L2) {
522     if (!L2.empty())
523       transfer(where, L2, L2.begin(), L2.end());
524   }
525   void splice(iterator where, iplist &L2, iterator first) {
526     iterator last = first; ++last;
527     if (where == first || where == last) return; // No change
528     transfer(where, L2, first, last);
529   }
530   void splice(iterator where, iplist &L2, iterator first, iterator last) {
531     if (first != last) transfer(where, L2, first, last);
532   }
533
534
535
536   //===----------------------------------------------------------------------===
537   // High-Level Functionality that shouldn't really be here, but is part of list
538   //
539
540   // These two functions are actually called remove/remove_if in list<>, but
541   // they actually do the job of erase, rename them accordingly.
542   //
543   void erase(const NodeTy &val) {
544     for (iterator I = begin(), E = end(); I != E; ) {
545       iterator next = I; ++next;
546       if (*I == val) erase(I);
547       I = next;
548     }
549   }
550   template<class Pr1> void erase_if(Pr1 pred) {
551     for (iterator I = begin(), E = end(); I != E; ) {
552       iterator next = I; ++next;
553       if (pred(*I)) erase(I);
554       I = next;
555     }
556   }
557
558   template<class Pr2> void unique(Pr2 pred) {
559     if (empty()) return;
560     for (iterator I = begin(), E = end(), Next = begin(); ++Next != E;) {
561       if (pred(*I))
562         erase(Next);
563       else
564         I = Next;
565       Next = I;
566     }
567   }
568   void unique() { unique(op_equal); }
569
570   template<class Pr3> void merge(iplist &right, Pr3 pred) {
571     iterator first1 = begin(), last1 = end();
572     iterator first2 = right.begin(), last2 = right.end();
573     while (first1 != last1 && first2 != last2)
574       if (pred(*first2, *first1)) {
575         iterator next = first2;
576         transfer(first1, right, first2, ++next);
577         first2 = next;
578       } else {
579         ++first1;
580       }
581     if (first2 != last2) transfer(last1, right, first2, last2);
582   }
583   void merge(iplist &right) { return merge(right, op_less); }
584
585   template<class Pr3> void sort(Pr3 pred);
586   void sort() { sort(op_less); }
587   void reverse();
588 };
589
590
591 template<typename NodeTy>
592 struct ilist : public iplist<NodeTy> {
593   typedef typename iplist<NodeTy>::size_type size_type;
594   typedef typename iplist<NodeTy>::iterator iterator;
595
596   ilist() {}
597   ilist(const ilist &right) {
598     insert(this->begin(), right.begin(), right.end());
599   }
600   explicit ilist(size_type count) {
601     insert(this->begin(), count, NodeTy());
602   }
603   ilist(size_type count, const NodeTy &val) {
604     insert(this->begin(), count, val);
605   }
606   template<class InIt> ilist(InIt first, InIt last) {
607     insert(this->begin(), first, last);
608   }
609
610
611   // Forwarding functions: A workaround for GCC 2.95 which does not correctly
612   // support 'using' declarations to bring a hidden member into scope.
613   //
614   iterator insert(iterator a, NodeTy *b){ return iplist<NodeTy>::insert(a, b); }
615   void push_front(NodeTy *a) { iplist<NodeTy>::push_front(a); }
616   void push_back(NodeTy *a)  { iplist<NodeTy>::push_back(a); }
617
618
619   // Main implementation here - Insert for a node passed by value...
620   iterator insert(iterator where, const NodeTy &val) {
621     return insert(where, createNode(val));
622   }
623
624
625   // Front and back inserters...
626   void push_front(const NodeTy &val) { insert(this->begin(), val); }
627   void push_back(const NodeTy &val) { insert(this->end(), val); }
628
629   // Special forms of insert...
630   template<class InIt> void insert(iterator where, InIt first, InIt last) {
631     for (; first != last; ++first) insert(where, *first);
632   }
633   void insert(iterator where, size_type count, const NodeTy &val) {
634     for (; count != 0; --count) insert(where, val);
635   }
636
637   // Assign special forms...
638   void assign(size_type count, const NodeTy &val) {
639     iterator I = this->begin();
640     for (; I != this->end() && count != 0; ++I, --count)
641       *I = val;
642     if (count != 0)
643       insert(this->end(), val, val);
644     else
645       erase(I, this->end());
646   }
647   template<class InIt> void assign(InIt first1, InIt last1) {
648     iterator first2 = this->begin(), last2 = this->end();
649     for ( ; first1 != last1 && first2 != last2; ++first1, ++first2)
650       *first1 = *first2;
651     if (first2 == last2)
652       erase(first1, last1);
653     else
654       insert(last1, first2, last2);
655   }
656
657
658   // Resize members...
659   void resize(size_type newsize, NodeTy val) {
660     iterator i = this->begin();
661     size_type len = 0;
662     for ( ; i != this->end() && len < newsize; ++i, ++len) /* empty*/ ;
663
664     if (len == newsize)
665       erase(i, this->end());
666     else                                          // i == end()
667       insert(this->end(), newsize - len, val);
668   }
669   void resize(size_type newsize) { resize(newsize, NodeTy()); }
670 };
671
672 } // End llvm namespace
673
674 namespace std {
675   // Ensure that swap uses the fast list swap...
676   template<class Ty>
677   void swap(llvm::iplist<Ty> &Left, llvm::iplist<Ty> &Right) {
678     Left.swap(Right);
679   }
680 }  // End 'std' extensions...
681
682 #endif // LLVM_ADT_ILIST_H