1 //===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the SmallVector class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_SMALLVECTOR_H
15 #define LLVM_ADT_SMALLVECTOR_H
17 #include "llvm/ADT/iterator"
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;
33 template<class T1, class T2>
34 inline _Scalar_ptr_iterator_tag _Ptr_cat(T1* const *, T2 **) {
35 _Scalar_ptr_iterator_tag _Cat;
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.
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.
51 class SmallVectorImpl {
53 T *Begin, *End, *Capacity;
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.
63 U FirstEl __attribute__((aligned));
72 // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
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) {
82 // Destroy the constructed elements in the vector.
83 destroy_range(Begin, End);
85 // If this wasn't grown from the inline copy, deallocate the old space.
87 delete[] reinterpret_cast<char*>(Begin);
90 typedef size_t size_type;
92 typedef const T* const_iterator;
94 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
95 typedef std::reverse_iterator<iterator> reverse_iterator;
98 typedef const T& const_reference;
100 bool empty() const { return Begin == End; }
101 size_type size() const { return End-Begin; }
103 // forward iterator creation methods.
104 iterator begin() { return Begin; }
105 const_iterator begin() const { return Begin; }
106 iterator end() { return End; }
107 const_iterator end() const { return End; }
109 // reverse iterator creation methods.
110 reverse_iterator rbegin() { return reverse_iterator(end()); }
111 const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
112 reverse_iterator rend() { return reverse_iterator(begin()); }
113 const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
116 reference operator[](unsigned idx) {
119 const_reference operator[](unsigned idx) const {
126 const_reference front() const {
133 const_reference back() const {
137 void push_back(const_reference Elt) {
138 if (End < Capacity) {
154 destroy_range(Begin, End);
158 void resize(unsigned N) {
160 destroy_range(Begin+N, End);
162 } else if (N > size()) {
163 if (unsigned(Capacity-Begin) < N)
165 construct_range(End, Begin+N, T());
170 void resize(unsigned N, const T &NV) {
172 destroy_range(Begin+N, End);
174 } else if (N > size()) {
175 if (unsigned(Capacity-Begin) < N)
177 construct_range(End, Begin+N, NV);
182 void reserve(unsigned N) {
183 if (unsigned(Capacity-Begin) < N)
187 void swap(SmallVectorImpl &RHS);
189 /// append - Add the specified range to the end of the SmallVector.
191 template<typename in_iter>
192 void append(in_iter in_start, in_iter in_end) {
193 unsigned NumInputs = std::distance(in_start, in_end);
194 // Grow allocated space if needed.
195 if (End+NumInputs > Capacity)
196 grow(size()+NumInputs);
198 // Copy the new elements over.
199 std::uninitialized_copy(in_start, in_end, End);
203 void assign(unsigned NumElts, const T &Elt) {
205 if (unsigned(Capacity-Begin) < NumElts)
208 construct_range(Begin, End, Elt);
211 void erase(iterator I) {
212 // Shift all elts down one.
213 std::copy(I+1, End, I);
214 // Drop the last elt.
218 void erase(iterator S, iterator E) {
219 // Shift all elts down.
220 iterator I = std::copy(E, End, S);
221 // Drop the last elts.
222 destroy_range(I, End);
226 iterator insert(iterator I, const T &Elt) {
227 if (I == End) { // Important special case for empty vector.
232 if (End < Capacity) {
236 // Push everything else over.
237 std::copy_backward(I, End-1, End);
241 unsigned EltNo = I-Begin;
247 template<typename ItTy>
248 iterator insert(iterator I, ItTy From, ItTy To) {
249 if (I == End) { // Important special case for empty vector.
254 unsigned NumToInsert = std::distance(From, To);
255 // Convert iterator to elt# to avoid invalidating iterator when we reserve()
256 unsigned InsertElt = I-begin();
258 // Ensure there is enough space.
259 reserve(size() + NumToInsert);
261 // Uninvalidate the iterator.
262 I = begin()+InsertElt;
264 // If we already have this many elements in the collection, append the
265 // dest elements at the end, then copy over the appropriate elements. Since
266 // we already reserved space, we know that this won't reallocate the vector.
267 if (size() >= NumToInsert) {
269 append(End-NumToInsert, End);
271 // Copy the existing elements that get replaced.
272 std::copy(I, OldEnd-NumToInsert, I+NumToInsert);
274 std::copy(From, To, I);
278 // Otherwise, we're inserting more elements than exist already, and we're
279 // not inserting at the end.
281 // Copy over the elements that we're about to overwrite.
284 unsigned NumOverwritten = OldEnd-I;
285 std::uninitialized_copy(I, OldEnd, End-NumOverwritten);
287 // Replace the overwritten part.
288 std::copy(From, From+NumOverwritten, I);
290 // Insert the non-overwritten middle part.
291 std::uninitialized_copy(From+NumOverwritten, To, OldEnd);
295 const SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
297 bool operator==(const SmallVectorImpl &RHS) const {
298 if (size() != RHS.size()) return false;
299 for (T *This = Begin, *That = RHS.Begin, *End = Begin+size();
300 This != End; ++This, ++That)
305 bool operator!=(const SmallVectorImpl &RHS) const { return !(*this == RHS); }
308 /// isSmall - Return true if this is a smallvector which has not had dynamic
309 /// memory allocated for it.
310 bool isSmall() const {
311 return reinterpret_cast<const void*>(Begin) ==
312 reinterpret_cast<const void*>(&FirstEl);
315 /// grow - double the size of the allocated memory, guaranteeing space for at
316 /// least one more element or MinSize if specified.
317 void grow(unsigned MinSize = 0);
319 void construct_range(T *S, T *E, const T &Elt) {
324 void destroy_range(T *S, T *E) {
332 // Define this out-of-line to dissuade the C++ compiler from inlining it.
333 template <typename T>
334 void SmallVectorImpl<T>::grow(unsigned MinSize) {
335 unsigned CurCapacity = unsigned(Capacity-Begin);
336 unsigned CurSize = unsigned(size());
337 unsigned NewCapacity = 2*CurCapacity;
338 if (NewCapacity < MinSize)
339 NewCapacity = MinSize;
340 T *NewElts = reinterpret_cast<T*>(new char[NewCapacity*sizeof(T)]);
342 // Copy the elements over.
343 std::uninitialized_copy(Begin, End, NewElts);
345 // Destroy the original elements.
346 destroy_range(Begin, End);
348 // If this wasn't grown from the inline copy, deallocate the old space.
350 delete[] reinterpret_cast<char*>(Begin);
353 End = NewElts+CurSize;
354 Capacity = Begin+NewCapacity;
357 template <typename T>
358 void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
359 if (this == &RHS) return;
361 // We can only avoid copying elements if neither vector is small.
362 if (!isSmall() && !RHS.isSmall()) {
363 std::swap(Begin, RHS.Begin);
364 std::swap(End, RHS.End);
365 std::swap(Capacity, RHS.Capacity);
368 if (Begin+RHS.size() > Capacity)
370 if (RHS.begin()+size() > RHS.Capacity)
373 // Swap the shared elements.
374 unsigned NumShared = size();
375 if (NumShared > RHS.size()) NumShared = RHS.size();
376 for (unsigned i = 0; i != NumShared; ++i)
377 std::swap(Begin[i], RHS[i]);
379 // Copy over the extra elts.
380 if (size() > RHS.size()) {
381 unsigned EltDiff = size() - RHS.size();
382 std::uninitialized_copy(Begin+NumShared, End, RHS.End);
384 destroy_range(Begin+NumShared, End);
385 End = Begin+NumShared;
386 } else if (RHS.size() > size()) {
387 unsigned EltDiff = RHS.size() - size();
388 std::uninitialized_copy(RHS.Begin+NumShared, RHS.End, End);
390 destroy_range(RHS.Begin+NumShared, RHS.End);
391 RHS.End = RHS.Begin+NumShared;
395 template <typename T>
396 const SmallVectorImpl<T> &
397 SmallVectorImpl<T>::operator=(const SmallVectorImpl<T> &RHS) {
398 // Avoid self-assignment.
399 if (this == &RHS) return *this;
401 // If we already have sufficient space, assign the common elements, then
402 // destroy any excess.
403 unsigned RHSSize = unsigned(RHS.size());
404 unsigned CurSize = unsigned(size());
405 if (CurSize >= RHSSize) {
406 // Assign common elements.
409 NewEnd = std::copy(RHS.Begin, RHS.Begin+RHSSize, Begin);
413 // Destroy excess elements.
414 destroy_range(NewEnd, End);
421 // If we have to grow to have enough elements, destroy the current elements.
422 // This allows us to avoid copying them during the grow.
423 if (unsigned(Capacity-Begin) < RHSSize) {
424 // Destroy current elements.
425 destroy_range(Begin, End);
429 } else if (CurSize) {
430 // Otherwise, use assignment for the already-constructed elements.
431 std::copy(RHS.Begin, RHS.Begin+CurSize, Begin);
434 // Copy construct the new elements in place.
435 std::uninitialized_copy(RHS.Begin+CurSize, RHS.End, Begin+CurSize);
442 /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized
443 /// for the case when the array is small. It contains some number of elements
444 /// in-place, which allows it to avoid heap allocation when the actual number of
445 /// elements is below that threshold. This allows normal "small" cases to be
446 /// fast without losing generality for large inputs.
448 /// Note that this does not attempt to be exception safe.
450 template <typename T, unsigned N>
451 class SmallVector : public SmallVectorImpl<T> {
452 /// InlineElts - These are 'N-1' elements that are stored inline in the body
453 /// of the vector. The extra '1' element is stored in SmallVectorImpl.
454 typedef typename SmallVectorImpl<T>::U U;
456 // MinUs - The number of U's require to cover N T's.
457 MinUs = (sizeof(T)*N+sizeof(U)-1)/sizeof(U),
459 // NumInlineEltsElts - The number of elements actually in this array. There
460 // is already one in the parent class, and we have to round up to avoid
461 // having a zero-element array.
462 NumInlineEltsElts = (MinUs - 1) > 0 ? (MinUs - 1) : 1,
464 // NumTsAvailable - The number of T's we actually have space for, which may
465 // be more than N due to rounding.
466 NumTsAvailable = (NumInlineEltsElts+1)*sizeof(U) / sizeof(T)
468 U InlineElts[NumInlineEltsElts];
470 SmallVector() : SmallVectorImpl<T>(NumTsAvailable) {
473 explicit SmallVector(unsigned Size, const T &Value = T())
474 : SmallVectorImpl<T>(NumTsAvailable) {
480 template<typename ItTy>
481 SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(NumTsAvailable) {
485 SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(NumTsAvailable) {
490 const SmallVector &operator=(const SmallVector &RHS) {
491 SmallVectorImpl<T>::operator=(RHS);
496 } // End llvm namespace
499 /// Implement std::swap in terms of SmallVector swap.
502 swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
506 /// Implement std::swap in terms of SmallVector swap.
507 template<typename T, unsigned N>
509 swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {