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