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