substantial refactoring of SmallVector, now most code is in SmallVectorTemplateCommon,
[oota-llvm.git] / include / llvm / ADT / SmallVector.h
1 //===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- 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 the SmallVector class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_ADT_SMALLVECTOR_H
15 #define LLVM_ADT_SMALLVECTOR_H
16
17 #include "llvm/Support/type_traits.h"
18 #include <algorithm>
19 #include <cassert>
20 #include <cstring>
21 #include <memory>
22
23 #ifdef _MSC_VER
24 namespace std {
25 #if _MSC_VER <= 1310
26   // Work around flawed VC++ implementation of std::uninitialized_copy.  Define
27   // additional overloads so that elements with pointer types are recognized as
28   // scalars and not objects, causing bizarre type conversion errors.
29   template<class T1, class T2>
30   inline _Scalar_ptr_iterator_tag _Ptr_cat(T1 **, T2 **) {
31     _Scalar_ptr_iterator_tag _Cat;
32     return _Cat;
33   }
34
35   template<class T1, class T2>
36   inline _Scalar_ptr_iterator_tag _Ptr_cat(T1* const *, T2 **) {
37     _Scalar_ptr_iterator_tag _Cat;
38     return _Cat;
39   }
40 #else
41 // FIXME: It is not clear if the problem is fixed in VS 2005.  What is clear
42 // is that the above hack won't work if it wasn't fixed.
43 #endif
44 }
45 #endif
46
47 namespace llvm {
48
49 /// SmallVectorBase - This is all the non-templated stuff common to all
50 /// SmallVectors.
51 class SmallVectorBase {
52 protected:
53   void *BeginX, *EndX, *CapacityX;
54
55   // Allocate raw space for N elements of type T.  If T has a ctor or dtor, we
56   // don't want it to be automatically run, so we need to represent the space as
57   // something else.  An array of char would work great, but might not be
58   // aligned sufficiently.  Instead, we either use GCC extensions, or some
59   // number of union instances for the space, which guarantee maximal alignment.
60 #ifdef __GNUC__
61   typedef char U;
62   U FirstEl __attribute__((aligned));
63 #else
64   union U {
65     double D;
66     long double LD;
67     long long L;
68     void *P;
69   } FirstEl;
70 #endif
71   // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
72   
73 protected:
74   SmallVectorBase(size_t Size)
75     : BeginX(&FirstEl), EndX(&FirstEl), CapacityX((char*)&FirstEl+Size) {}
76   
77   /// isSmall - Return true if this is a smallvector which has not had dynamic
78   /// memory allocated for it.
79   bool isSmall() const {
80     return BeginX == static_cast<const void*>(&FirstEl);
81   }
82   
83 public:
84   bool empty() const { return BeginX == EndX; }
85 };
86
87 template <typename T>
88 class SmallVectorTemplateCommon : public SmallVectorBase {
89   void setEnd(T *P) { this->EndX = P; }
90 public:
91   SmallVectorTemplateCommon(size_t Size) : SmallVectorBase(Size) {}
92   
93   ~SmallVectorTemplateCommon() {
94     // Destroy the constructed elements in the vector.
95     destroy_range(begin(), end());
96     
97     // If this wasn't grown from the inline copy, deallocate the old space.
98     if (!this->isSmall())
99       operator delete(begin());
100   }
101   
102   typedef size_t size_type;
103   typedef ptrdiff_t difference_type;
104   typedef T value_type;
105   typedef T *iterator;
106   typedef const T *const_iterator;
107   
108   typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
109   typedef std::reverse_iterator<iterator> reverse_iterator;
110   
111   typedef T &reference;
112   typedef const T &const_reference;
113   typedef T *pointer;
114   typedef const T *const_pointer;
115   
116   // forward iterator creation methods.
117   iterator begin() { return (iterator)this->BeginX; }
118   const_iterator begin() const { return (const_iterator)this->BeginX; }
119   iterator end() { return (iterator)this->EndX; }
120   const_iterator end() const { return (const_iterator)this->EndX; }
121 private:
122   iterator capacity_ptr() { return (iterator)this->CapacityX; }
123   const_iterator capacity_ptr() const { return (const_iterator)this->CapacityX;}
124 public:
125   
126   // reverse iterator creation methods.
127   reverse_iterator rbegin()            { return reverse_iterator(end()); }
128   const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
129   reverse_iterator rend()              { return reverse_iterator(begin()); }
130   const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
131
132   size_type size() const { return end()-begin(); }
133   size_type max_size() const { return size_type(-1) / sizeof(T); }
134   
135   /// capacity - Return the total number of elements in the currently allocated
136   /// buffer.
137   size_t capacity() const { return capacity_ptr() - begin(); }
138   
139   /// data - Return a pointer to the vector's buffer, even if empty().
140   pointer data() { return pointer(begin()); }
141   /// data - Return a pointer to the vector's buffer, even if empty().
142   const_pointer data() const { return const_pointer(begin()); }
143   
144   reference operator[](unsigned idx) {
145     assert(begin() + idx < end());
146     return begin()[idx];
147   }
148   const_reference operator[](unsigned idx) const {
149     assert(begin() + idx < end());
150     return begin()[idx];
151   }
152
153   reference front() {
154     return begin()[0];
155   }
156   const_reference front() const {
157     return begin()[0];
158   }
159
160   reference back() {
161     return end()[-1];
162   }
163   const_reference back() const {
164     return end()[-1];
165   }
166
167   void push_back(const_reference Elt) {
168     if (this->EndX < this->CapacityX) {
169   Retry:
170       new (end()) T(Elt);
171       setEnd(end()+1);
172       return;
173     }
174     grow();
175     goto Retry;
176   }
177
178   void pop_back() {
179     setEnd(end()-1);
180     end()->~T();
181   }
182
183   T pop_back_val() {
184     T Result = back();
185     pop_back();
186     return Result;
187   }
188
189   void clear() {
190     destroy_range(begin(), end());
191     this->EndX = this->BeginX;
192   }
193
194   void resize(unsigned N) {
195     if (N < size()) {
196       destroy_range(begin()+N, end());
197       setEnd(begin()+N);
198     } else if (N > size()) {
199       if (capacity() < N)
200         grow(N);
201       construct_range(end(), begin()+N, T());
202       setEnd(begin()+N);
203     }
204   }
205
206   void resize(unsigned N, const T &NV) {
207     if (N < size()) {
208       destroy_range(begin()+N, end());
209       setEnd(begin()+N);
210     } else if (N > size()) {
211       if (capacity() < N)
212         grow(N);
213       construct_range(end(), begin()+N, NV);
214       setEnd(begin()+N);
215     }
216   }
217
218   void reserve(unsigned N) {
219     if (capacity() < N)
220       grow(N);
221   }
222
223   void swap(SmallVectorTemplateCommon &RHS);
224
225   /// append - Add the specified range to the end of the SmallVector.
226   ///
227   template<typename in_iter>
228   void append(in_iter in_start, in_iter in_end) {
229     size_type NumInputs = std::distance(in_start, in_end);
230     // Grow allocated space if needed.
231     if (NumInputs > size_type(capacity_ptr()-end()))
232       grow(size()+NumInputs);
233
234     // Copy the new elements over.
235     // TODO: NEED To compile time dispatch on whether in_iter is a random access
236     // iterator to use the fast uninitialized_copy.
237     std::uninitialized_copy(in_start, in_end, end());
238     setEnd(end() + NumInputs);
239   }
240
241   /// append - Add the specified range to the end of the SmallVector.
242   ///
243   void append(size_type NumInputs, const T &Elt) {
244     // Grow allocated space if needed.
245     if (NumInputs > size_type(capacity_ptr()-end()))
246       grow(size()+NumInputs);
247
248     // Copy the new elements over.
249     std::uninitialized_fill_n(end(), NumInputs, Elt);
250     setEnd(end() + NumInputs);
251   }
252
253   void assign(unsigned NumElts, const T &Elt) {
254     clear();
255     if (capacity() < NumElts)
256       grow(NumElts);
257     setEnd(begin()+NumElts);
258     construct_range(begin(), end(), Elt);
259   }
260
261   iterator erase(iterator I) {
262     iterator N = I;
263     // Shift all elts down one.
264     std::copy(I+1, end(), I);
265     // Drop the last elt.
266     pop_back();
267     return(N);
268   }
269
270   iterator erase(iterator S, iterator E) {
271     iterator N = S;
272     // Shift all elts down.
273     iterator I = std::copy(E, end(), S);
274     // Drop the last elts.
275     destroy_range(I, end());
276     setEnd(I);
277     return(N);
278   }
279
280   iterator insert(iterator I, const T &Elt) {
281     if (I == end()) {  // Important special case for empty vector.
282       push_back(Elt);
283       return end()-1;
284     }
285
286     if (this->EndX < this->CapacityX) {
287   Retry:
288       new (end()) T(back());
289       setEnd(end()+1);
290       // Push everything else over.
291       std::copy_backward(I, end()-1, end());
292       *I = Elt;
293       return I;
294     }
295     size_t EltNo = I-begin();
296     grow();
297     I = begin()+EltNo;
298     goto Retry;
299   }
300
301   iterator insert(iterator I, size_type NumToInsert, const T &Elt) {
302     if (I == end()) {  // Important special case for empty vector.
303       append(NumToInsert, Elt);
304       return end()-1;
305     }
306
307     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
308     size_t InsertElt = I-begin();
309
310     // Ensure there is enough space.
311     reserve(static_cast<unsigned>(size() + NumToInsert));
312
313     // Uninvalidate the iterator.
314     I = begin()+InsertElt;
315
316     // If there are more elements between the insertion point and the end of the
317     // range than there are being inserted, we can use a simple approach to
318     // insertion.  Since we already reserved space, we know that this won't
319     // reallocate the vector.
320     if (size_t(end()-I) >= NumToInsert) {
321       T *OldEnd = end();
322       append(end()-NumToInsert, end());
323
324       // Copy the existing elements that get replaced.
325       std::copy_backward(I, OldEnd-NumToInsert, OldEnd);
326
327       std::fill_n(I, NumToInsert, Elt);
328       return I;
329     }
330
331     // Otherwise, we're inserting more elements than exist already, and we're
332     // not inserting at the end.
333
334     // Copy over the elements that we're about to overwrite.
335     T *OldEnd = end();
336     setEnd(end() + NumToInsert);
337     size_t NumOverwritten = OldEnd-I;
338     uninitialized_copy(I, OldEnd, end()-NumOverwritten);
339
340     // Replace the overwritten part.
341     std::fill_n(I, NumOverwritten, Elt);
342
343     // Insert the non-overwritten middle part.
344     std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt);
345     return I;
346   }
347
348   template<typename ItTy>
349   iterator insert(iterator I, ItTy From, ItTy To) {
350     if (I == end()) {  // Important special case for empty vector.
351       append(From, To);
352       return end()-1;
353     }
354
355     size_t NumToInsert = std::distance(From, To);
356     // Convert iterator to elt# to avoid invalidating iterator when we reserve()
357     size_t InsertElt = I-begin();
358
359     // Ensure there is enough space.
360     reserve(static_cast<unsigned>(size() + NumToInsert));
361
362     // Uninvalidate the iterator.
363     I = begin()+InsertElt;
364
365     // If there are more elements between the insertion point and the end of the
366     // range than there are being inserted, we can use a simple approach to
367     // insertion.  Since we already reserved space, we know that this won't
368     // reallocate the vector.
369     if (size_t(end()-I) >= NumToInsert) {
370       T *OldEnd = end();
371       append(end()-NumToInsert, end());
372
373       // Copy the existing elements that get replaced.
374       std::copy_backward(I, OldEnd-NumToInsert, OldEnd);
375
376       std::copy(From, To, I);
377       return I;
378     }
379
380     // Otherwise, we're inserting more elements than exist already, and we're
381     // not inserting at the end.
382
383     // Copy over the elements that we're about to overwrite.
384     T *OldEnd = end();
385     setEnd(end() + NumToInsert);
386     size_t NumOverwritten = OldEnd-I;
387     uninitialized_copy(I, OldEnd, end()-NumOverwritten);
388
389     // Replace the overwritten part.
390     std::copy(From, From+NumOverwritten, I);
391
392     // Insert the non-overwritten middle part.
393     uninitialized_copy(From+NumOverwritten, To, OldEnd);
394     return I;
395   }
396
397   const SmallVectorTemplateCommon
398     &operator=(const SmallVectorTemplateCommon &RHS);
399
400   bool operator==(const SmallVectorTemplateCommon &RHS) const {
401     if (size() != RHS.size()) return false;
402     return std::equal(begin(), end(), RHS.begin());
403   }
404   bool operator!=(const SmallVectorTemplateCommon &RHS) const {
405     return !(*this == RHS);
406   }
407
408   bool operator<(const SmallVectorTemplateCommon &RHS) const {
409     return std::lexicographical_compare(begin(), end(),
410                                         RHS.begin(), RHS.end());
411   }
412
413   /// set_size - Set the array size to \arg N, which the current array must have
414   /// enough capacity for.
415   ///
416   /// This does not construct or destroy any elements in the vector.
417   ///
418   /// Clients can use this in conjunction with capacity() to write past the end
419   /// of the buffer when they know that more elements are available, and only
420   /// update the size later. This avoids the cost of value initializing elements
421   /// which will only be overwritten.
422   void set_size(unsigned N) {
423     assert(N <= capacity());
424     setEnd(begin() + N);
425   }
426
427 private:
428   /// grow - double the size of the allocated memory, guaranteeing space for at
429   /// least one more element or MinSize if specified.
430   void grow(size_type MinSize = 0);
431
432   static void construct_range(T *S, T *E, const T &Elt) {
433     for (; S != E; ++S)
434       new (S) T(Elt);
435   }
436
437   static void destroy_range(T *S, T *E) {
438     // No need to do a destroy loop for POD's.
439     if (isPodLike<T>::value) return;
440     
441     while (S != E) {
442       --E;
443       E->~T();
444     }
445   }
446   
447   /// uninitialized_copy - Copy the range [I, E) onto the uninitialized memory
448   /// starting with "Dest", constructing elements into it as needed.
449   template<typename It1, typename It2>
450   static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
451     // Use memcpy for PODs: std::uninitialized_copy optimizes to memmove.
452     if (isPodLike<T>::value)
453       memcpy(&*Dest, &*I, (E-I)*sizeof(T));
454     else
455       std::uninitialized_copy(I, E, Dest);
456   }
457 };
458   
459
460 // Define this out-of-line to dissuade the C++ compiler from inlining it.
461 template <typename T>
462 void SmallVectorTemplateCommon<T>::grow(size_t MinSize) {
463   size_t CurCapacity = capacity();
464   size_t CurSize = size();
465   size_t NewCapacity = 2*CurCapacity;
466   if (NewCapacity < MinSize)
467     NewCapacity = MinSize;
468   T *NewElts = static_cast<T*>(operator new(NewCapacity*sizeof(T)));
469
470   // Copy the elements over.
471   uninitialized_copy(begin(), end(), NewElts);
472
473   // Destroy the original elements.
474   destroy_range(begin(), end());
475
476   // If this wasn't grown from the inline copy, deallocate the old space.
477   if (!this->isSmall())
478     operator delete(begin());
479
480   setEnd(NewElts+CurSize);
481   this->BeginX = NewElts;
482   this->CapacityX = begin()+NewCapacity;
483 }
484
485 template <typename T>
486 void SmallVectorTemplateCommon<T>::swap(SmallVectorTemplateCommon<T> &RHS) {
487   if (this == &RHS) return;
488
489   // We can only avoid copying elements if neither vector is small.
490   if (!this->isSmall() && !RHS.isSmall()) {
491     std::swap(this->BeginX, RHS.BeginX);
492     std::swap(this->EndX, RHS.EndX);
493     std::swap(this->CapacityX, RHS.CapacityX);
494     return;
495   }
496   if (RHS.size() > capacity())
497     grow(RHS.size());
498   if (size() > RHS.capacity())
499     RHS.grow(size());
500
501   // Swap the shared elements.
502   size_t NumShared = size();
503   if (NumShared > RHS.size()) NumShared = RHS.size();
504   for (unsigned i = 0; i != static_cast<unsigned>(NumShared); ++i)
505     std::swap((*this)[i], RHS[i]);
506
507   // Copy over the extra elts.
508   if (size() > RHS.size()) {
509     size_t EltDiff = size() - RHS.size();
510     uninitialized_copy(begin()+NumShared, end(), RHS.end());
511     RHS.setEnd(RHS.end()+EltDiff);
512     destroy_range(begin()+NumShared, end());
513     setEnd(begin()+NumShared);
514   } else if (RHS.size() > size()) {
515     size_t EltDiff = RHS.size() - size();
516     uninitialized_copy(RHS.begin()+NumShared, RHS.end(), end());
517     setEnd(end() + EltDiff);
518     destroy_range(RHS.begin()+NumShared, RHS.end());
519     RHS.setEnd(RHS.begin()+NumShared);
520   }
521 }
522
523 template <typename T>
524 const SmallVectorTemplateCommon<T> &
525 SmallVectorTemplateCommon<T>::
526   operator=(const SmallVectorTemplateCommon<T> &RHS) {
527   // Avoid self-assignment.
528   if (this == &RHS) return *this;
529
530   // If we already have sufficient space, assign the common elements, then
531   // destroy any excess.
532   size_t RHSSize = RHS.size();
533   size_t CurSize = size();
534   if (CurSize >= RHSSize) {
535     // Assign common elements.
536     iterator NewEnd;
537     if (RHSSize)
538       NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, begin());
539     else
540       NewEnd = begin();
541
542     // Destroy excess elements.
543     destroy_range(NewEnd, end());
544
545     // Trim.
546     setEnd(NewEnd);
547     return *this;
548   }
549
550   // If we have to grow to have enough elements, destroy the current elements.
551   // This allows us to avoid copying them during the grow.
552   if (capacity() < RHSSize) {
553     // Destroy current elements.
554     destroy_range(begin(), end());
555     setEnd(begin());
556     CurSize = 0;
557     grow(RHSSize);
558   } else if (CurSize) {
559     // Otherwise, use assignment for the already-constructed elements.
560     std::copy(RHS.begin(), RHS.begin()+CurSize, begin());
561   }
562
563   // Copy construct the new elements in place.
564   uninitialized_copy(RHS.begin()+CurSize, RHS.end(), begin()+CurSize);
565
566   // Set end.
567   setEnd(begin()+RHSSize);
568   return *this;
569 }
570
571   
572 template <typename T, bool isPodLike>
573 class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
574 public:
575   SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
576
577 };
578
579 template <typename T>
580 class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<T> {
581 public:
582   SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
583   
584 };
585   
586   
587 /// SmallVectorImpl - This class consists of common code factored out of the
588 /// SmallVector class to reduce code duplication based on the SmallVector 'N'
589 /// template parameter.
590 template <typename T>
591 class SmallVectorImpl : public SmallVectorTemplateBase<T, isPodLike<T>::value> {
592 public:
593   // Default ctor - Initialize to empty.
594   explicit SmallVectorImpl(unsigned N)
595     : SmallVectorTemplateBase<T, isPodLike<T>::value>(N*sizeof(T)) {
596   }
597 };
598
599 /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
600 /// for the case when the array is small.  It contains some number of elements
601 /// in-place, which allows it to avoid heap allocation when the actual number of
602 /// elements is below that threshold.  This allows normal "small" cases to be
603 /// fast without losing generality for large inputs.
604 ///
605 /// Note that this does not attempt to be exception safe.
606 ///
607 template <typename T, unsigned N>
608 class SmallVector : public SmallVectorImpl<T> {
609   /// InlineElts - These are 'N-1' elements that are stored inline in the body
610   /// of the vector.  The extra '1' element is stored in SmallVectorImpl.
611   typedef typename SmallVectorImpl<T>::U U;
612   enum {
613     // MinUs - The number of U's require to cover N T's.
614     MinUs = (static_cast<unsigned int>(sizeof(T))*N +
615              static_cast<unsigned int>(sizeof(U)) - 1) /
616             static_cast<unsigned int>(sizeof(U)),
617
618     // NumInlineEltsElts - The number of elements actually in this array.  There
619     // is already one in the parent class, and we have to round up to avoid
620     // having a zero-element array.
621     NumInlineEltsElts = MinUs > 1 ? (MinUs - 1) : 1,
622
623     // NumTsAvailable - The number of T's we actually have space for, which may
624     // be more than N due to rounding.
625     NumTsAvailable = (NumInlineEltsElts+1)*static_cast<unsigned int>(sizeof(U))/
626                      static_cast<unsigned int>(sizeof(T))
627   };
628   U InlineElts[NumInlineEltsElts];
629 public:
630   SmallVector() : SmallVectorImpl<T>(NumTsAvailable) {
631   }
632
633   explicit SmallVector(unsigned Size, const T &Value = T())
634     : SmallVectorImpl<T>(NumTsAvailable) {
635     this->reserve(Size);
636     while (Size--)
637       this->push_back(Value);
638   }
639
640   template<typename ItTy>
641   SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(NumTsAvailable) {
642     this->append(S, E);
643   }
644
645   SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(NumTsAvailable) {
646     if (!RHS.empty())
647       SmallVectorImpl<T>::operator=(RHS);
648   }
649
650   const SmallVector &operator=(const SmallVector &RHS) {
651     SmallVectorImpl<T>::operator=(RHS);
652     return *this;
653   }
654
655 };
656
657 } // End llvm namespace
658
659 namespace std {
660   /// Implement std::swap in terms of SmallVector swap.
661   template<typename T>
662   inline void
663   swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
664     LHS.swap(RHS);
665   }
666
667   /// Implement std::swap in terms of SmallVector swap.
668   template<typename T, unsigned N>
669   inline void
670   swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
671     LHS.swap(RHS);
672   }
673 }
674
675 #endif