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