One of the 'annoying' things about ilists is that the iterators don't behave
[oota-llvm.git] / include / llvm / ADT / ilist
1 //===-- Support/ilist - Intrusive Linked List Template ----------*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines classes to implement an intrusive doubly linked list class
11 // (ie 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 // provides 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<>::createEndMarker()).  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 SUPPORT_ILIST
39 #define SUPPORT_ILIST
40
41 #include <Support/iterator>
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 // Template traits for intrusive list.  By specializing this template class, you
50 // can change what next/prev fields are used to store the links...
51 template<typename NodeTy>
52 struct ilist_traits {
53   static NodeTy *getPrev(NodeTy *N) { return N->getPrev(); }
54   static NodeTy *getNext(NodeTy *N) { return N->getNext(); }
55   static const NodeTy *getPrev(const NodeTy *N) { return N->getPrev(); }
56   static const NodeTy *getNext(const NodeTy *N) { return N->getNext(); }
57
58   static void setPrev(NodeTy *N, NodeTy *Prev) { N->setPrev(Prev); }
59   static void setNext(NodeTy *N, NodeTy *Next) { N->setNext(Next); }
60
61   static NodeTy *createNode() { return new NodeTy(); }
62   static NodeTy *createNode(const NodeTy &V) { return new NodeTy(V); }
63
64
65   void addNodeToList(NodeTy *NTy) {}
66   void removeNodeFromList(NodeTy *NTy) {}
67   void transferNodesFromList(iplist<NodeTy, ilist_traits> &L2,
68                              ilist_iterator<NodeTy> first,
69                              ilist_iterator<NodeTy> last) {}
70 };
71
72 // Const traits are the same as nonconst traits...
73 template<typename Ty>
74 struct ilist_traits<const Ty> : public ilist_traits<Ty> {};
75
76
77 //===----------------------------------------------------------------------===//
78 // ilist_iterator<Node> - Iterator for intrusive list.
79 //
80 template<typename NodeTy>
81 class ilist_iterator
82   : public bidirectional_iterator<NodeTy, ptrdiff_t> {
83   typedef ilist_traits<NodeTy> Traits;
84   typedef bidirectional_iterator<NodeTy, ptrdiff_t> super;
85
86 public:
87   typedef size_t size_type;
88   typedef typename super::pointer pointer;
89   typedef typename super::reference reference;
90 private:
91   pointer NodePtr;
92 public:
93
94   ilist_iterator(pointer NP) : NodePtr(NP) {}
95   ilist_iterator(reference NR) : NodePtr(&NR) {}
96   ilist_iterator() : NodePtr(0) {}
97
98   // This is templated so that we can allow constructing a const iterator from
99   // a nonconst iterator...
100   template<class node_ty>
101   ilist_iterator(const ilist_iterator<node_ty> &RHS)
102     : NodePtr(RHS.getNodePtrUnchecked()) {}
103
104   // This is templated so that we can allow assigning to a const iterator from
105   // a nonconst iterator...
106   template<class node_ty>
107   const ilist_iterator &operator=(const ilist_iterator<node_ty> &RHS) {
108     NodePtr = RHS.getNodePtrUnchecked();
109     return *this;
110   }
111
112   // Accessors...
113   operator pointer() const {
114     assert(Traits::getNext(NodePtr) != 0 && "Dereferencing end()!");
115     return NodePtr;
116   }
117
118   reference operator*() const {
119     assert(Traits::getNext(NodePtr) != 0 && "Dereferencing end()!");
120     return *NodePtr;
121   }
122   pointer operator->() { return &operator*(); }
123   const pointer operator->() const { return &operator*(); }
124
125   // Comparison operators
126   bool operator==(const ilist_iterator &RHS) const {
127     return NodePtr == RHS.NodePtr;
128   }
129   bool operator!=(const ilist_iterator &RHS) const {
130     return NodePtr != RHS.NodePtr;
131   }
132
133   // Increment and decrement operators...
134   ilist_iterator &operator--() {      // predecrement - Back up
135     NodePtr = Traits::getPrev(NodePtr);
136     assert(NodePtr && "--'d off the beginning of an ilist!");
137     return *this;
138   }
139   ilist_iterator &operator++() {      // preincrement - Advance
140     NodePtr = Traits::getNext(NodePtr);
141     assert(NodePtr && "++'d off the end of an ilist!");
142     return *this;
143   }
144   ilist_iterator operator--(int) {    // postdecrement operators...
145     ilist_iterator tmp = *this;
146     --*this;
147     return tmp;
148   }
149   ilist_iterator operator++(int) {    // postincrement operators...
150     ilist_iterator tmp = *this;
151     ++*this;
152     return tmp;
153   }
154
155   // Internal interface, do not use...
156   pointer getNodePtrUnchecked() const { return NodePtr; }
157 };
158
159 //===----------------------------------------------------------------------===//
160 // ilist_compat_iterator<Node> - Compatibility iterator for intrusive list.
161 // This makes an ilist<X> act like an std::list<X*>, where you have to
162 // dereference stuff multiple times.  This should only be used for temporary
163 // migration purposes.  Because we don't support "changing the pointer", we only
164 // expose constant pointers.
165 //
166 template<typename NodeTy>
167 class ilist_compat_iterator
168   : public bidirectional_iterator<NodeTy* const, ptrdiff_t> {
169   typedef ilist_traits<NodeTy> Traits;
170   typedef bidirectional_iterator<NodeTy* const, ptrdiff_t> super;
171
172 public:
173   typedef size_t size_type;
174   typedef typename super::pointer pointer;
175   typedef typename super::reference reference;
176 private:
177   NodeTy *NodePtr;
178 public:
179
180   ilist_compat_iterator(NodeTy *NP) : NodePtr(NP) {}
181   ilist_compat_iterator() : NodePtr(0) {}
182
183   // This is templated so that we can allow constructing a const iterator from
184   // a nonconst iterator...
185   template<class node_ty>
186   ilist_compat_iterator(const ilist_compat_iterator<node_ty> &RHS)
187     : NodePtr(RHS.getNodePtrUnchecked()) {}
188
189   // This is templated so that we can allow assigning to a const iterator from
190   // a nonconst iterator...
191   template<class node_ty>
192   const ilist_compat_iterator &operator=(const 
193                                          ilist_compat_iterator<node_ty> &RHS) {
194     NodePtr = RHS.getNodePtrUnchecked();
195     return *this;
196   }
197
198   // Accessors...
199   operator pointer() const {
200     assert(Traits::getNext(NodePtr) != 0 && "Dereferencing end()!");
201     return &NodePtr;
202   }
203
204   reference operator*() const {
205     assert(Traits::getNext(NodePtr) != 0 && "Dereferencing end()!");
206     return NodePtr;
207   }
208   pointer operator->() { return &operator*(); }
209   const pointer operator->() const { return &operator*(); }
210
211   // Comparison operators
212   bool operator==(const ilist_compat_iterator &RHS) const {
213     return NodePtr == RHS.NodePtr;
214   }
215   bool operator!=(const ilist_compat_iterator &RHS) const {
216     return NodePtr != RHS.NodePtr;
217   }
218
219   // Increment and decrement operators...
220   ilist_compat_iterator &operator--() {      // predecrement - Back up
221     NodePtr = Traits::getPrev(NodePtr);
222     assert(NodePtr && "--'d off the beginning of an ilist!");
223     return *this;
224   }
225   ilist_compat_iterator &operator++() {      // preincrement - Advance
226     NodePtr = Traits::getNext(NodePtr);
227     assert(NodePtr && "++'d off the end of an ilist!");
228     return *this;
229   }
230   ilist_compat_iterator operator--(int) {    // postdecrement operators...
231     ilist_compat_iterator tmp = *this;
232     --*this;
233     return tmp;
234   }
235   ilist_compat_iterator operator++(int) {    // postincrement operators...
236     ilist_compat_iterator tmp = *this;
237     ++*this;
238     return tmp;
239   }
240
241   // Internal interface, do not use...
242   pointer getNodePtrUnchecked() const { return NodePtr; }
243 };
244
245
246 // Allow ilist_iterators to convert into pointers to a node automatically when
247 // used by the dyn_cast, cast, isa mechanisms...
248
249 template<typename From> struct simplify_type;
250
251 template<typename NodeTy> struct simplify_type<ilist_iterator<NodeTy> > {
252   typedef NodeTy* SimpleType;
253   
254   static SimpleType getSimplifiedValue(const ilist_iterator<NodeTy> &Node) {
255     return &*Node;
256   }
257 };
258 template<typename NodeTy> struct simplify_type<const ilist_iterator<NodeTy> > {
259   typedef NodeTy* SimpleType;
260   
261   static SimpleType getSimplifiedValue(const ilist_iterator<NodeTy> &Node) {
262     return &*Node;
263   }
264 };
265
266
267 //===----------------------------------------------------------------------===//
268 //
269 // iplist - The subset of list functionality that can safely be used on nodes of
270 // polymorphic types, ie a heterogeneus list with a common base class that holds
271 // the next/prev pointers...
272 //
273 template<typename NodeTy, typename Traits=ilist_traits<NodeTy> >
274 class iplist : public Traits {
275   NodeTy *Head, *Tail;
276
277   static bool op_less(NodeTy &L, NodeTy &R) { return L < R; }
278   static bool op_equal(NodeTy &L, NodeTy &R) { return L == R; }
279 public:
280   typedef NodeTy *pointer;
281   typedef const NodeTy *const_pointer;
282   typedef NodeTy &reference;
283   typedef const NodeTy &const_reference;
284   typedef NodeTy value_type;
285   typedef ilist_iterator<NodeTy> iterator;
286   typedef ilist_iterator<const NodeTy> const_iterator;
287   typedef size_t size_type;
288   typedef ptrdiff_t difference_type;
289   typedef std::reverse_iterator<const_iterator>  const_reverse_iterator;
290   typedef std::reverse_iterator<iterator>  reverse_iterator;
291
292   iplist() : Head(this->createNode()), Tail(Head) {
293     setNext(Head, 0);
294     setPrev(Head, 0);
295   }
296   ~iplist() { clear(); delete Tail; }
297
298   // Iterator creation methods.
299   iterator begin()             { return iterator(Head); }
300   const_iterator begin() const { return const_iterator(Head); }
301   iterator end()               { return iterator(Tail); }
302   const_iterator end() const   { return const_iterator(Tail); }
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   // "compatibility" iterator creation methods.
312   typedef ilist_compat_iterator<NodeTy> compat_iterator;
313   compat_iterator compat_begin() const { return compat_iterator(Head); }
314   compat_iterator compat_end()   const { return compat_iterator(Tail); }
315
316   // Miscellaneous inspection routines.
317   size_type max_size() const { return size_type(-1); }
318   bool empty() const { return Head == Tail; }
319
320   // Front and back accessor functions...
321   reference front() {
322     assert(!empty() && "Called front() on empty list!");
323     return *Head;
324   }
325   const_reference front() const {
326     assert(!empty() && "Called front() on empty list!");
327     return *Head;
328   }
329   reference back() {
330     assert(!empty() && "Called back() on empty list!");
331     return *getPrev(Tail);
332   }
333   const_reference back() const {
334     assert(!empty() && "Called back() on empty list!");
335     return *getPrev(Tail);
336   }
337
338   void swap(iplist &RHS) {
339     abort();     // Swap does not use list traits callback correctly yet!
340     std::swap(Head, RHS.Head);
341     std::swap(Tail, RHS.Tail);
342   }
343
344   iterator insert(iterator where, NodeTy *New) {
345     NodeTy *CurNode = where.getNodePtrUnchecked(), *PrevNode = getPrev(CurNode);
346     setNext(New, CurNode);
347     setPrev(New, PrevNode);
348
349     if (PrevNode)
350       setNext(PrevNode, New);
351     else
352       Head = New;
353     setPrev(CurNode, New);
354
355     addNodeToList(New);  // Notify traits that we added a node...
356     return New;
357   }
358
359   NodeTy *remove(iterator &IT) {
360     assert(IT != end() && "Cannot remove end of list!");
361     NodeTy *Node = &*IT;
362     NodeTy *NextNode = getNext(Node);
363     NodeTy *PrevNode = getPrev(Node);
364
365     if (PrevNode)
366       setNext(PrevNode, NextNode);
367     else
368       Head = NextNode;
369     setPrev(NextNode, PrevNode);
370     IT = NextNode;
371     removeNodeFromList(Node);  // Notify traits that we removed a node...
372     return Node;
373   }
374
375   NodeTy *remove(const iterator &IT) {
376     iterator MutIt = IT;
377     return remove(MutIt);
378   }
379
380   // erase - remove a node from the controlled sequence... and delete it.
381   iterator erase(iterator where) {
382     delete remove(where);
383     return where;
384   }
385
386
387 private:
388   // transfer - The heart of the splice function.  Move linked list nodes from
389   // [first, last) into position.
390   //
391   void transfer(iterator position, iplist &L2, iterator first, iterator last) {
392     assert(first != last && "Should be checked by callers");
393     if (position != last) {
394       // Remove [first, last) from its old position.
395       NodeTy *First = &*first, *Prev = getPrev(First);
396       NodeTy *Next = last.getNodePtrUnchecked(), *Last = getPrev(Next);
397       if (Prev)
398         setNext(Prev, Next);
399       else
400         L2.Head = Next;
401       setPrev(Next, Prev);
402
403       // Splice [first, last) into its new position.
404       NodeTy *PosNext = position.getNodePtrUnchecked();
405       NodeTy *PosPrev = getPrev(PosNext);
406
407       // Fix head of list...
408       if (PosPrev)
409         setNext(PosPrev, First);
410       else
411         Head = First;
412       setPrev(First, PosPrev);
413
414       // Fix end of list...
415       setNext(Last, PosNext);
416       setPrev(PosNext, Last);
417
418       transferNodesFromList(L2, First, PosNext);
419     }
420   }
421
422 public:
423
424   //===----------------------------------------------------------------------===
425   // Functionality derived from other functions defined above...
426   //
427
428   size_type size() const {
429 #if __GNUC__ == 3
430     size_type Result = std::distance(begin(), end());
431 #else
432     size_type Result = 0;
433     std::distance(begin(), end(), Result);
434 #endif
435     return Result;
436   }
437
438   iterator erase(iterator first, iterator last) {
439     while (first != last)
440       first = erase(first);
441     return last;
442   }
443
444   void clear() { erase(begin(), end()); }
445
446   // Front and back inserters...
447   void push_front(NodeTy *val) { insert(begin(), val); }
448   void push_back(NodeTy *val) { insert(end(), val); }
449   void pop_front() {
450     assert(!empty() && "pop_front() on empty list!");
451     erase(begin());
452   }
453   void pop_back() {
454     assert(!empty() && "pop_back() on empty list!");
455     iterator t = end(); erase(--t);
456   }
457
458   // Special forms of insert...
459   template<class InIt> void insert(iterator where, InIt first, InIt last) {
460     for (; first != last; ++first) insert(where, *first);
461   }
462
463   // Splice members - defined in terms of transfer...
464   void splice(iterator where, iplist &L2) {
465     if (!L2.empty())
466       transfer(where, L2, L2.begin(), L2.end());
467   }
468   void splice(iterator where, iplist &L2, iterator first) {
469     iterator last = first; ++last;
470     if (where == first || where == last) return; // No change
471     transfer(where, L2, first, last);
472   }
473   void splice(iterator where, iplist &L2, iterator first, iterator last) {
474     if (first != last) transfer(where, L2, first, last);
475   }
476
477
478
479   //===----------------------------------------------------------------------===
480   // High-Level Functionality that shouldn't really be here, but is part of list
481   //
482
483   // These two functions are actually called remove/remove_if in list<>, but
484   // they actually do the job of erase, rename them accordingly.
485   //
486   void erase(const NodeTy &val) {
487     for (iterator I = begin(), E = end(); I != E; ) {
488       iterator next = I; ++next;
489       if (*I == val) erase(I);
490       I = next;
491     }
492   }
493   template<class Pr1> void erase_if(Pr1 pred) {
494     for (iterator I = begin(), E = end(); I != E; ) {
495       iterator next = I; ++next;
496       if (pred(*I)) erase(I);
497       I = next;
498     }
499   }
500
501   template<class Pr2> void unique(Pr2 pred) {
502     if (empty()) return;
503     for (iterator I = begin(), E = end(), Next = begin(); ++Next != E;) {
504       if (pred(*I))
505         erase(Next);
506       else
507         I = Next;
508       Next = I;
509     }
510   }
511   void unique() { unique(op_equal); }
512
513   template<class Pr3> void merge(iplist &right, Pr3 pred) {
514     iterator first1 = begin(), last1 = end();
515     iterator first2 = right.begin(), last2 = right.end();
516     while (first1 != last1 && first2 != last2)
517       if (pred(*first2, *first1)) {
518         iterator next = first2;
519         transfer(first1, right, first2, ++next);
520         first2 = next;
521       } else {
522         ++first1;
523       }
524     if (first2 != last2) transfer(last1, right, first2, last2);
525   }
526   void merge(iplist &right) { return merge(right, op_less); }
527
528   template<class Pr3> void sort(Pr3 pred);
529   void sort() { sort(op_less); }
530   void reverse();
531 };
532
533
534 template<typename NodeTy>
535 struct ilist : public iplist<NodeTy> {
536   typedef typename iplist<NodeTy>::size_type size_type;
537   typedef typename iplist<NodeTy>::iterator iterator;
538
539   ilist() {}
540   ilist(const ilist &right) {
541     insert(this->begin(), right.begin(), right.end());
542   }
543   explicit ilist(size_type count) {
544     insert(this->begin(), count, NodeTy());
545   } 
546   ilist(size_type count, const NodeTy &val) {
547     insert(this->begin(), count, val);
548   }
549   template<class InIt> ilist(InIt first, InIt last) {
550     insert(this->begin(), first, last);
551   }
552
553
554   // Forwarding functions: A workaround for GCC 2.95 which does not correctly
555   // support 'using' declarations to bring a hidden member into scope.
556   //
557   iterator insert(iterator a, NodeTy *b){ return iplist<NodeTy>::insert(a, b); }
558   void push_front(NodeTy *a) { iplist<NodeTy>::push_front(a); }
559   void push_back(NodeTy *a)  { iplist<NodeTy>::push_back(a); }
560   
561
562   // Main implementation here - Insert for a node passed by value...
563   iterator insert(iterator where, const NodeTy &val) {
564     return insert(where, createNode(val));
565   }
566
567
568   // Front and back inserters...
569   void push_front(const NodeTy &val) { insert(this->begin(), val); }
570   void push_back(const NodeTy &val) { insert(this->end(), val); }
571
572   // Special forms of insert...
573   template<class InIt> void insert(iterator where, InIt first, InIt last) {
574     for (; first != last; ++first) insert(where, *first);
575   }
576   void insert(iterator where, size_type count, const NodeTy &val) {
577     for (; count != 0; --count) insert(where, val);
578   }
579
580   // Assign special forms...
581   void assign(size_type count, const NodeTy &val) {
582     iterator I = this->begin();
583     for (; I != this->end() && count != 0; ++I, --count)
584       *I = val;
585     if (count != 0)
586       insert(this->end(), val, val);
587     else
588       erase(I, this->end());
589   }
590   template<class InIt> void assign(InIt first1, InIt last1) {
591     iterator first2 = this->begin(), last2 = this->end();
592     for ( ; first1 != last1 && first2 != last2; ++first1, ++first2)
593       *first1 = *first2;
594     if (first2 == last2)
595       erase(first1, last1);
596     else
597       insert(last1, first2, last2);
598   }
599
600
601   // Resize members...
602   void resize(size_type newsize, NodeTy val) {
603     iterator i = this->begin();
604     size_type len = 0;
605     for ( ; i != this->end() && len < newsize; ++i, ++len) /* empty*/ ;
606
607     if (len == newsize)
608       erase(i, this->end());
609     else                                          // i == end()
610       insert(this->end(), newsize - len, val);
611   }
612   void resize(size_type newsize) { resize(newsize, NodeTy()); }
613 };
614
615 } // End llvm namespace
616
617 namespace std {
618   // Ensure that swap uses the fast list swap...
619   template<class Ty>
620   void swap(llvm::iplist<Ty> &Left, llvm::iplist<Ty> &Right) {
621     Left.swap(Right);
622   }
623 }  // End 'std' extensions...
624
625 #endif