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