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