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