SmallVector.h 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  1. //===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the SmallVector class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #ifndef LLVM_ADT_SMALLVECTOR_H
  13. #define LLVM_ADT_SMALLVECTOR_H
  14. #include "llvm/ADT/iterator_range.h"
  15. #include "llvm/Support/Compiler.h"
  16. #include "llvm/Support/ErrorHandling.h"
  17. #include "llvm/Support/MathExtras.h"
  18. #include "llvm/Support/MemAlloc.h"
  19. #include "llvm/Support/type_traits.h"
  20. #include <algorithm>
  21. #include <cassert>
  22. #include <cstddef>
  23. #include <cstdlib>
  24. #include <cstring>
  25. #include <initializer_list>
  26. #include <iterator>
  27. #include <limits>
  28. #include <memory>
  29. #include <new>
  30. #include <type_traits>
  31. #include <utility>
  32. namespace llvm {
  33. /// This is all the stuff common to all SmallVectors.
  34. ///
  35. /// The template parameter specifies the type which should be used to hold the
  36. /// Size and Capacity of the SmallVector, so it can be adjusted.
  37. /// Using 32 bit size is desirable to shrink the size of the SmallVector.
  38. /// Using 64 bit size is desirable for cases like SmallVector<char>, where a
  39. /// 32 bit size would limit the vector to ~4GB. SmallVectors are used for
  40. /// buffering bitcode output - which can exceed 4GB.
  41. template <class Size_T> class SmallVectorBase {
  42. protected:
  43. void *BeginX;
  44. Size_T Size = 0, Capacity;
  45. /// The maximum value of the Size_T used.
  46. static constexpr size_t SizeTypeMax() {
  47. return std::numeric_limits<Size_T>::max();
  48. }
  49. SmallVectorBase() = delete;
  50. SmallVectorBase(void *FirstEl, size_t TotalCapacity)
  51. : BeginX(FirstEl), Capacity(TotalCapacity) {}
  52. /// This is a helper for \a grow() that's out of line to reduce code
  53. /// duplication. This function will report a fatal error if it can't grow at
  54. /// least to \p MinSize.
  55. void *mallocForGrow(size_t MinSize, size_t TSize, size_t &NewCapacity);
  56. /// This is an implementation of the grow() method which only works
  57. /// on POD-like data types and is out of line to reduce code duplication.
  58. /// This function will report a fatal error if it cannot increase capacity.
  59. void grow_pod(void *FirstEl, size_t MinSize, size_t TSize);
  60. public:
  61. size_t size() const { return Size; }
  62. size_t capacity() const { return Capacity; }
  63. LLVM_NODISCARD bool empty() const { return !Size; }
  64. /// Set the array size to \p N, which the current array must have enough
  65. /// capacity for.
  66. ///
  67. /// This does not construct or destroy any elements in the vector.
  68. ///
  69. /// Clients can use this in conjunction with capacity() to write past the end
  70. /// of the buffer when they know that more elements are available, and only
  71. /// update the size later. This avoids the cost of value initializing elements
  72. /// which will only be overwritten.
  73. void set_size(size_t N) {
  74. assert(N <= capacity());
  75. Size = N;
  76. }
  77. };
  78. template <class T>
  79. using SmallVectorSizeType =
  80. typename std::conditional<sizeof(T) < 4 && sizeof(void *) >= 8, uint64_t,
  81. uint32_t>::type;
  82. /// Figure out the offset of the first element.
  83. template <class T, typename = void> struct SmallVectorAlignmentAndSize {
  84. alignas(SmallVectorBase<SmallVectorSizeType<T>>) char Base[sizeof(
  85. SmallVectorBase<SmallVectorSizeType<T>>)];
  86. alignas(T) char FirstEl[sizeof(T)];
  87. };
  88. /// This is the part of SmallVectorTemplateBase which does not depend on whether
  89. /// the type T is a POD. The extra dummy template argument is used by ArrayRef
  90. /// to avoid unnecessarily requiring T to be complete.
  91. template <typename T, typename = void>
  92. class SmallVectorTemplateCommon
  93. : public SmallVectorBase<SmallVectorSizeType<T>> {
  94. using Base = SmallVectorBase<SmallVectorSizeType<T>>;
  95. /// Find the address of the first element. For this pointer math to be valid
  96. /// with small-size of 0 for T with lots of alignment, it's important that
  97. /// SmallVectorStorage is properly-aligned even for small-size of 0.
  98. void *getFirstEl() const {
  99. return const_cast<void *>(reinterpret_cast<const void *>(
  100. reinterpret_cast<const char *>(this) +
  101. offsetof(SmallVectorAlignmentAndSize<T>, FirstEl)));
  102. }
  103. // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
  104. protected:
  105. SmallVectorTemplateCommon(size_t Size) : Base(getFirstEl(), Size) {}
  106. void grow_pod(size_t MinSize, size_t TSize) {
  107. Base::grow_pod(getFirstEl(), MinSize, TSize);
  108. }
  109. /// Return true if this is a smallvector which has not had dynamic
  110. /// memory allocated for it.
  111. bool isSmall() const { return this->BeginX == getFirstEl(); }
  112. /// Put this vector in a state of being small.
  113. void resetToSmall() {
  114. this->BeginX = getFirstEl();
  115. this->Size = this->Capacity = 0; // FIXME: Setting Capacity to 0 is suspect.
  116. }
  117. /// Return true if V is an internal reference to the given range.
  118. bool isReferenceToRange(const void *V, const void *First, const void *Last) const {
  119. // Use std::less to avoid UB.
  120. std::less<> LessThan;
  121. return !LessThan(V, First) && LessThan(V, Last);
  122. }
  123. /// Return true if V is an internal reference to this vector.
  124. bool isReferenceToStorage(const void *V) const {
  125. return isReferenceToRange(V, this->begin(), this->end());
  126. }
  127. /// Return true if First and Last form a valid (possibly empty) range in this
  128. /// vector's storage.
  129. bool isRangeInStorage(const void *First, const void *Last) const {
  130. // Use std::less to avoid UB.
  131. std::less<> LessThan;
  132. return !LessThan(First, this->begin()) && !LessThan(Last, First) &&
  133. !LessThan(this->end(), Last);
  134. }
  135. /// Return true unless Elt will be invalidated by resizing the vector to
  136. /// NewSize.
  137. bool isSafeToReferenceAfterResize(const void *Elt, size_t NewSize) {
  138. // Past the end.
  139. if (LLVM_LIKELY(!isReferenceToStorage(Elt)))
  140. return true;
  141. // Return false if Elt will be destroyed by shrinking.
  142. if (NewSize <= this->size())
  143. return Elt < this->begin() + NewSize;
  144. // Return false if we need to grow.
  145. return NewSize <= this->capacity();
  146. }
  147. /// Check whether Elt will be invalidated by resizing the vector to NewSize.
  148. void assertSafeToReferenceAfterResize(const void *Elt, size_t NewSize) {
  149. assert(isSafeToReferenceAfterResize(Elt, NewSize) &&
  150. "Attempting to reference an element of the vector in an operation "
  151. "that invalidates it");
  152. }
  153. /// Check whether Elt will be invalidated by increasing the size of the
  154. /// vector by N.
  155. void assertSafeToAdd(const void *Elt, size_t N = 1) {
  156. this->assertSafeToReferenceAfterResize(Elt, this->size() + N);
  157. }
  158. /// Check whether any part of the range will be invalidated by clearing.
  159. void assertSafeToReferenceAfterClear(const T *From, const T *To) {
  160. if (From == To)
  161. return;
  162. this->assertSafeToReferenceAfterResize(From, 0);
  163. this->assertSafeToReferenceAfterResize(To - 1, 0);
  164. }
  165. template <
  166. class ItTy,
  167. std::enable_if_t<!std::is_same<std::remove_const_t<ItTy>, T *>::value,
  168. bool> = false>
  169. void assertSafeToReferenceAfterClear(ItTy, ItTy) {}
  170. /// Check whether any part of the range will be invalidated by growing.
  171. void assertSafeToAddRange(const T *From, const T *To) {
  172. if (From == To)
  173. return;
  174. this->assertSafeToAdd(From, To - From);
  175. this->assertSafeToAdd(To - 1, To - From);
  176. }
  177. template <
  178. class ItTy,
  179. std::enable_if_t<!std::is_same<std::remove_const_t<ItTy>, T *>::value,
  180. bool> = false>
  181. void assertSafeToAddRange(ItTy, ItTy) {}
  182. /// Reserve enough space to add one element, and return the updated element
  183. /// pointer in case it was a reference to the storage.
  184. template <class U>
  185. static const T *reserveForParamAndGetAddressImpl(U *This, const T &Elt,
  186. size_t N) {
  187. size_t NewSize = This->size() + N;
  188. if (LLVM_LIKELY(NewSize <= This->capacity()))
  189. return &Elt;
  190. bool ReferencesStorage = false;
  191. int64_t Index = -1;
  192. if (!U::TakesParamByValue) {
  193. if (LLVM_UNLIKELY(This->isReferenceToStorage(&Elt))) {
  194. ReferencesStorage = true;
  195. Index = &Elt - This->begin();
  196. }
  197. }
  198. This->grow(NewSize);
  199. return ReferencesStorage ? This->begin() + Index : &Elt;
  200. }
  201. public:
  202. using size_type = size_t;
  203. using difference_type = ptrdiff_t;
  204. using value_type = T;
  205. using iterator = T *;
  206. using const_iterator = const T *;
  207. using const_reverse_iterator = std::reverse_iterator<const_iterator>;
  208. using reverse_iterator = std::reverse_iterator<iterator>;
  209. using reference = T &;
  210. using const_reference = const T &;
  211. using pointer = T *;
  212. using const_pointer = const T *;
  213. using Base::capacity;
  214. using Base::empty;
  215. using Base::size;
  216. // forward iterator creation methods.
  217. iterator begin() { return (iterator)this->BeginX; }
  218. const_iterator begin() const { return (const_iterator)this->BeginX; }
  219. iterator end() { return begin() + size(); }
  220. const_iterator end() const { return begin() + size(); }
  221. // reverse iterator creation methods.
  222. reverse_iterator rbegin() { return reverse_iterator(end()); }
  223. const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
  224. reverse_iterator rend() { return reverse_iterator(begin()); }
  225. const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
  226. size_type size_in_bytes() const { return size() * sizeof(T); }
  227. size_type max_size() const {
  228. return std::min(this->SizeTypeMax(), size_type(-1) / sizeof(T));
  229. }
  230. size_t capacity_in_bytes() const { return capacity() * sizeof(T); }
  231. /// Return a pointer to the vector's buffer, even if empty().
  232. pointer data() { return pointer(begin()); }
  233. /// Return a pointer to the vector's buffer, even if empty().
  234. const_pointer data() const { return const_pointer(begin()); }
  235. reference operator[](size_type idx) {
  236. assert(idx < size());
  237. return begin()[idx];
  238. }
  239. const_reference operator[](size_type idx) const {
  240. assert(idx < size());
  241. return begin()[idx];
  242. }
  243. reference front() {
  244. assert(!empty());
  245. return begin()[0];
  246. }
  247. const_reference front() const {
  248. assert(!empty());
  249. return begin()[0];
  250. }
  251. reference back() {
  252. assert(!empty());
  253. return end()[-1];
  254. }
  255. const_reference back() const {
  256. assert(!empty());
  257. return end()[-1];
  258. }
  259. };
  260. /// SmallVectorTemplateBase<TriviallyCopyable = false> - This is where we put
  261. /// method implementations that are designed to work with non-trivial T's.
  262. ///
  263. /// We approximate is_trivially_copyable with trivial move/copy construction and
  264. /// trivial destruction. While the standard doesn't specify that you're allowed
  265. /// copy these types with memcpy, there is no way for the type to observe this.
  266. /// This catches the important case of std::pair<POD, POD>, which is not
  267. /// trivially assignable.
  268. template <typename T, bool = (is_trivially_copy_constructible<T>::value) &&
  269. (is_trivially_move_constructible<T>::value) &&
  270. std::is_trivially_destructible<T>::value>
  271. class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
  272. friend class SmallVectorTemplateCommon<T>;
  273. protected:
  274. static constexpr bool TakesParamByValue = false;
  275. using ValueParamT = const T &;
  276. SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
  277. static void destroy_range(T *S, T *E) {
  278. while (S != E) {
  279. --E;
  280. E->~T();
  281. }
  282. }
  283. /// Move the range [I, E) into the uninitialized memory starting with "Dest",
  284. /// constructing elements as needed.
  285. template<typename It1, typename It2>
  286. static void uninitialized_move(It1 I, It1 E, It2 Dest) {
  287. std::uninitialized_copy(std::make_move_iterator(I),
  288. std::make_move_iterator(E), Dest);
  289. }
  290. /// Copy the range [I, E) onto the uninitialized memory starting with "Dest",
  291. /// constructing elements as needed.
  292. template<typename It1, typename It2>
  293. static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
  294. std::uninitialized_copy(I, E, Dest);
  295. }
  296. /// Grow the allocated memory (without initializing new elements), doubling
  297. /// the size of the allocated memory. Guarantees space for at least one more
  298. /// element, or MinSize more elements if specified.
  299. void grow(size_t MinSize = 0);
  300. /// Create a new allocation big enough for \p MinSize and pass back its size
  301. /// in \p NewCapacity. This is the first section of \a grow().
  302. T *mallocForGrow(size_t MinSize, size_t &NewCapacity) {
  303. return static_cast<T *>(
  304. SmallVectorBase<SmallVectorSizeType<T>>::mallocForGrow(
  305. MinSize, sizeof(T), NewCapacity));
  306. }
  307. /// Move existing elements over to the new allocation \p NewElts, the middle
  308. /// section of \a grow().
  309. void moveElementsForGrow(T *NewElts);
  310. /// Transfer ownership of the allocation, finishing up \a grow().
  311. void takeAllocationForGrow(T *NewElts, size_t NewCapacity);
  312. /// Reserve enough space to add one element, and return the updated element
  313. /// pointer in case it was a reference to the storage.
  314. const T *reserveForParamAndGetAddress(const T &Elt, size_t N = 1) {
  315. return this->reserveForParamAndGetAddressImpl(this, Elt, N);
  316. }
  317. /// Reserve enough space to add one element, and return the updated element
  318. /// pointer in case it was a reference to the storage.
  319. T *reserveForParamAndGetAddress(T &Elt, size_t N = 1) {
  320. return const_cast<T *>(
  321. this->reserveForParamAndGetAddressImpl(this, Elt, N));
  322. }
  323. static T &&forward_value_param(T &&V) { return std::move(V); }
  324. static const T &forward_value_param(const T &V) { return V; }
  325. void growAndAssign(size_t NumElts, const T &Elt) {
  326. // Grow manually in case Elt is an internal reference.
  327. size_t NewCapacity;
  328. T *NewElts = mallocForGrow(NumElts, NewCapacity);
  329. std::uninitialized_fill_n(NewElts, NumElts, Elt);
  330. this->destroy_range(this->begin(), this->end());
  331. takeAllocationForGrow(NewElts, NewCapacity);
  332. this->set_size(NumElts);
  333. }
  334. template <typename... ArgTypes> T &growAndEmplaceBack(ArgTypes &&... Args) {
  335. // Grow manually in case one of Args is an internal reference.
  336. size_t NewCapacity;
  337. T *NewElts = mallocForGrow(0, NewCapacity);
  338. ::new ((void *)(NewElts + this->size())) T(std::forward<ArgTypes>(Args)...);
  339. moveElementsForGrow(NewElts);
  340. takeAllocationForGrow(NewElts, NewCapacity);
  341. this->set_size(this->size() + 1);
  342. return this->back();
  343. }
  344. public:
  345. void push_back(const T &Elt) {
  346. const T *EltPtr = reserveForParamAndGetAddress(Elt);
  347. ::new ((void *)this->end()) T(*EltPtr);
  348. this->set_size(this->size() + 1);
  349. }
  350. void push_back(T &&Elt) {
  351. T *EltPtr = reserveForParamAndGetAddress(Elt);
  352. ::new ((void *)this->end()) T(::std::move(*EltPtr));
  353. this->set_size(this->size() + 1);
  354. }
  355. void pop_back() {
  356. this->set_size(this->size() - 1);
  357. this->end()->~T();
  358. }
  359. };
  360. // Define this out-of-line to dissuade the C++ compiler from inlining it.
  361. template <typename T, bool TriviallyCopyable>
  362. void SmallVectorTemplateBase<T, TriviallyCopyable>::grow(size_t MinSize) {
  363. size_t NewCapacity;
  364. T *NewElts = mallocForGrow(MinSize, NewCapacity);
  365. moveElementsForGrow(NewElts);
  366. takeAllocationForGrow(NewElts, NewCapacity);
  367. }
  368. // Define this out-of-line to dissuade the C++ compiler from inlining it.
  369. template <typename T, bool TriviallyCopyable>
  370. void SmallVectorTemplateBase<T, TriviallyCopyable>::moveElementsForGrow(
  371. T *NewElts) {
  372. // Move the elements over.
  373. this->uninitialized_move(this->begin(), this->end(), NewElts);
  374. // Destroy the original elements.
  375. destroy_range(this->begin(), this->end());
  376. }
  377. // Define this out-of-line to dissuade the C++ compiler from inlining it.
  378. template <typename T, bool TriviallyCopyable>
  379. void SmallVectorTemplateBase<T, TriviallyCopyable>::takeAllocationForGrow(
  380. T *NewElts, size_t NewCapacity) {
  381. // If this wasn't grown from the inline copy, deallocate the old space.
  382. if (!this->isSmall())
  383. free(this->begin());
  384. this->BeginX = NewElts;
  385. this->Capacity = NewCapacity;
  386. }
  387. /// SmallVectorTemplateBase<TriviallyCopyable = true> - This is where we put
  388. /// method implementations that are designed to work with trivially copyable
  389. /// T's. This allows using memcpy in place of copy/move construction and
  390. /// skipping destruction.
  391. template <typename T>
  392. class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<T> {
  393. friend class SmallVectorTemplateCommon<T>;
  394. protected:
  395. /// True if it's cheap enough to take parameters by value. Doing so avoids
  396. /// overhead related to mitigations for reference invalidation.
  397. static constexpr bool TakesParamByValue = sizeof(T) <= 2 * sizeof(void *);
  398. /// Either const T& or T, depending on whether it's cheap enough to take
  399. /// parameters by value.
  400. using ValueParamT =
  401. typename std::conditional<TakesParamByValue, T, const T &>::type;
  402. SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
  403. // No need to do a destroy loop for POD's.
  404. static void destroy_range(T *, T *) {}
  405. /// Move the range [I, E) onto the uninitialized memory
  406. /// starting with "Dest", constructing elements into it as needed.
  407. template<typename It1, typename It2>
  408. static void uninitialized_move(It1 I, It1 E, It2 Dest) {
  409. // Just do a copy.
  410. uninitialized_copy(I, E, Dest);
  411. }
  412. /// Copy the range [I, E) onto the uninitialized memory
  413. /// starting with "Dest", constructing elements into it as needed.
  414. template<typename It1, typename It2>
  415. static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
  416. // Arbitrary iterator types; just use the basic implementation.
  417. std::uninitialized_copy(I, E, Dest);
  418. }
  419. /// Copy the range [I, E) onto the uninitialized memory
  420. /// starting with "Dest", constructing elements into it as needed.
  421. template <typename T1, typename T2>
  422. static void uninitialized_copy(
  423. T1 *I, T1 *E, T2 *Dest,
  424. std::enable_if_t<std::is_same<typename std::remove_const<T1>::type,
  425. T2>::value> * = nullptr) {
  426. // Use memcpy for PODs iterated by pointers (which includes SmallVector
  427. // iterators): std::uninitialized_copy optimizes to memmove, but we can
  428. // use memcpy here. Note that I and E are iterators and thus might be
  429. // invalid for memcpy if they are equal.
  430. if (I != E)
  431. memcpy(reinterpret_cast<void *>(Dest), I, (E - I) * sizeof(T));
  432. }
  433. /// Double the size of the allocated memory, guaranteeing space for at
  434. /// least one more element or MinSize if specified.
  435. void grow(size_t MinSize = 0) { this->grow_pod(MinSize, sizeof(T)); }
  436. /// Reserve enough space to add one element, and return the updated element
  437. /// pointer in case it was a reference to the storage.
  438. const T *reserveForParamAndGetAddress(const T &Elt, size_t N = 1) {
  439. return this->reserveForParamAndGetAddressImpl(this, Elt, N);
  440. }
  441. /// Reserve enough space to add one element, and return the updated element
  442. /// pointer in case it was a reference to the storage.
  443. T *reserveForParamAndGetAddress(T &Elt, size_t N = 1) {
  444. return const_cast<T *>(
  445. this->reserveForParamAndGetAddressImpl(this, Elt, N));
  446. }
  447. /// Copy \p V or return a reference, depending on \a ValueParamT.
  448. static ValueParamT forward_value_param(ValueParamT V) { return V; }
  449. void growAndAssign(size_t NumElts, T Elt) {
  450. // Elt has been copied in case it's an internal reference, side-stepping
  451. // reference invalidation problems without losing the realloc optimization.
  452. this->set_size(0);
  453. this->grow(NumElts);
  454. std::uninitialized_fill_n(this->begin(), NumElts, Elt);
  455. this->set_size(NumElts);
  456. }
  457. template <typename... ArgTypes> T &growAndEmplaceBack(ArgTypes &&... Args) {
  458. // Use push_back with a copy in case Args has an internal reference,
  459. // side-stepping reference invalidation problems without losing the realloc
  460. // optimization.
  461. push_back(T(std::forward<ArgTypes>(Args)...));
  462. return this->back();
  463. }
  464. public:
  465. void push_back(ValueParamT Elt) {
  466. const T *EltPtr = reserveForParamAndGetAddress(Elt);
  467. memcpy(reinterpret_cast<void *>(this->end()), EltPtr, sizeof(T));
  468. this->set_size(this->size() + 1);
  469. }
  470. void pop_back() { this->set_size(this->size() - 1); }
  471. };
  472. /// This class consists of common code factored out of the SmallVector class to
  473. /// reduce code duplication based on the SmallVector 'N' template parameter.
  474. template <typename T>
  475. class SmallVectorImpl : public SmallVectorTemplateBase<T> {
  476. using SuperClass = SmallVectorTemplateBase<T>;
  477. public:
  478. using iterator = typename SuperClass::iterator;
  479. using const_iterator = typename SuperClass::const_iterator;
  480. using reference = typename SuperClass::reference;
  481. using size_type = typename SuperClass::size_type;
  482. protected:
  483. using SmallVectorTemplateBase<T>::TakesParamByValue;
  484. using ValueParamT = typename SuperClass::ValueParamT;
  485. // Default ctor - Initialize to empty.
  486. explicit SmallVectorImpl(unsigned N)
  487. : SmallVectorTemplateBase<T>(N) {}
  488. public:
  489. SmallVectorImpl(const SmallVectorImpl &) = delete;
  490. ~SmallVectorImpl() {
  491. // Subclass has already destructed this vector's elements.
  492. // If this wasn't grown from the inline copy, deallocate the old space.
  493. if (!this->isSmall())
  494. free(this->begin());
  495. }
  496. void clear() {
  497. this->destroy_range(this->begin(), this->end());
  498. this->Size = 0;
  499. }
  500. private:
  501. template <bool ForOverwrite> void resizeImpl(size_type N) {
  502. if (N < this->size()) {
  503. this->pop_back_n(this->size() - N);
  504. } else if (N > this->size()) {
  505. this->reserve(N);
  506. for (auto I = this->end(), E = this->begin() + N; I != E; ++I)
  507. if (ForOverwrite)
  508. new (&*I) T;
  509. else
  510. new (&*I) T();
  511. this->set_size(N);
  512. }
  513. }
  514. public:
  515. void resize(size_type N) { resizeImpl<false>(N); }
  516. /// Like resize, but \ref T is POD, the new values won't be initialized.
  517. void resize_for_overwrite(size_type N) { resizeImpl<true>(N); }
  518. void resize(size_type N, ValueParamT NV) {
  519. if (N == this->size())
  520. return;
  521. if (N < this->size()) {
  522. this->pop_back_n(this->size() - N);
  523. return;
  524. }
  525. // N > this->size(). Defer to append.
  526. this->append(N - this->size(), NV);
  527. }
  528. void reserve(size_type N) {
  529. if (this->capacity() < N)
  530. this->grow(N);
  531. }
  532. void pop_back_n(size_type NumItems) {
  533. assert(this->size() >= NumItems);
  534. this->destroy_range(this->end() - NumItems, this->end());
  535. this->set_size(this->size() - NumItems);
  536. }
  537. LLVM_NODISCARD T pop_back_val() {
  538. T Result = ::std::move(this->back());
  539. this->pop_back();
  540. return Result;
  541. }
  542. void swap(SmallVectorImpl &RHS);
  543. /// Add the specified range to the end of the SmallVector.
  544. template <typename in_iter,
  545. typename = std::enable_if_t<std::is_convertible<
  546. typename std::iterator_traits<in_iter>::iterator_category,
  547. std::input_iterator_tag>::value>>
  548. void append(in_iter in_start, in_iter in_end) {
  549. this->assertSafeToAddRange(in_start, in_end);
  550. size_type NumInputs = std::distance(in_start, in_end);
  551. this->reserve(this->size() + NumInputs);
  552. this->uninitialized_copy(in_start, in_end, this->end());
  553. this->set_size(this->size() + NumInputs);
  554. }
  555. /// Append \p NumInputs copies of \p Elt to the end.
  556. void append(size_type NumInputs, ValueParamT Elt) {
  557. const T *EltPtr = this->reserveForParamAndGetAddress(Elt, NumInputs);
  558. std::uninitialized_fill_n(this->end(), NumInputs, *EltPtr);
  559. this->set_size(this->size() + NumInputs);
  560. }
  561. void append(std::initializer_list<T> IL) {
  562. append(IL.begin(), IL.end());
  563. }
  564. void append(const SmallVectorImpl &RHS) { append(RHS.begin(), RHS.end()); }
  565. void assign(size_type NumElts, ValueParamT Elt) {
  566. // Note that Elt could be an internal reference.
  567. if (NumElts > this->capacity()) {
  568. this->growAndAssign(NumElts, Elt);
  569. return;
  570. }
  571. // Assign over existing elements.
  572. std::fill_n(this->begin(), std::min(NumElts, this->size()), Elt);
  573. if (NumElts > this->size())
  574. std::uninitialized_fill_n(this->end(), NumElts - this->size(), Elt);
  575. else if (NumElts < this->size())
  576. this->destroy_range(this->begin() + NumElts, this->end());
  577. this->set_size(NumElts);
  578. }
  579. // FIXME: Consider assigning over existing elements, rather than clearing &
  580. // re-initializing them - for all assign(...) variants.
  581. template <typename in_iter,
  582. typename = std::enable_if_t<std::is_convertible<
  583. typename std::iterator_traits<in_iter>::iterator_category,
  584. std::input_iterator_tag>::value>>
  585. void assign(in_iter in_start, in_iter in_end) {
  586. this->assertSafeToReferenceAfterClear(in_start, in_end);
  587. clear();
  588. append(in_start, in_end);
  589. }
  590. void assign(std::initializer_list<T> IL) {
  591. clear();
  592. append(IL);
  593. }
  594. void assign(const SmallVectorImpl &RHS) { assign(RHS.begin(), RHS.end()); }
  595. iterator erase(const_iterator CI) {
  596. // Just cast away constness because this is a non-const member function.
  597. iterator I = const_cast<iterator>(CI);
  598. assert(this->isReferenceToStorage(CI) && "Iterator to erase is out of bounds.");
  599. iterator N = I;
  600. // Shift all elts down one.
  601. std::move(I+1, this->end(), I);
  602. // Drop the last elt.
  603. this->pop_back();
  604. return(N);
  605. }
  606. iterator erase(const_iterator CS, const_iterator CE) {
  607. // Just cast away constness because this is a non-const member function.
  608. iterator S = const_cast<iterator>(CS);
  609. iterator E = const_cast<iterator>(CE);
  610. assert(this->isRangeInStorage(S, E) && "Range to erase is out of bounds.");
  611. iterator N = S;
  612. // Shift all elts down.
  613. iterator I = std::move(E, this->end(), S);
  614. // Drop the last elts.
  615. this->destroy_range(I, this->end());
  616. this->set_size(I - this->begin());
  617. return(N);
  618. }
  619. private:
  620. template <class ArgType> iterator insert_one_impl(iterator I, ArgType &&Elt) {
  621. // Callers ensure that ArgType is derived from T.
  622. static_assert(
  623. std::is_same<std::remove_const_t<std::remove_reference_t<ArgType>>,
  624. T>::value,
  625. "ArgType must be derived from T!");
  626. if (I == this->end()) { // Important special case for empty vector.
  627. this->push_back(::std::forward<ArgType>(Elt));
  628. return this->end()-1;
  629. }
  630. assert(this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.");
  631. // Grow if necessary.
  632. size_t Index = I - this->begin();
  633. std::remove_reference_t<ArgType> *EltPtr =
  634. this->reserveForParamAndGetAddress(Elt);
  635. I = this->begin() + Index;
  636. ::new ((void*) this->end()) T(::std::move(this->back()));
  637. // Push everything else over.
  638. std::move_backward(I, this->end()-1, this->end());
  639. this->set_size(this->size() + 1);
  640. // If we just moved the element we're inserting, be sure to update
  641. // the reference (never happens if TakesParamByValue).
  642. static_assert(!TakesParamByValue || std::is_same<ArgType, T>::value,
  643. "ArgType must be 'T' when taking by value!");
  644. if (!TakesParamByValue && this->isReferenceToRange(EltPtr, I, this->end()))
  645. ++EltPtr;
  646. *I = ::std::forward<ArgType>(*EltPtr);
  647. return I;
  648. }
  649. public:
  650. iterator insert(iterator I, T &&Elt) {
  651. return insert_one_impl(I, this->forward_value_param(std::move(Elt)));
  652. }
  653. iterator insert(iterator I, const T &Elt) {
  654. return insert_one_impl(I, this->forward_value_param(Elt));
  655. }
  656. iterator insert(iterator I, size_type NumToInsert, ValueParamT Elt) {
  657. // Convert iterator to elt# to avoid invalidating iterator when we reserve()
  658. size_t InsertElt = I - this->begin();
  659. if (I == this->end()) { // Important special case for empty vector.
  660. append(NumToInsert, Elt);
  661. return this->begin()+InsertElt;
  662. }
  663. assert(this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.");
  664. // Ensure there is enough space, and get the (maybe updated) address of
  665. // Elt.
  666. const T *EltPtr = this->reserveForParamAndGetAddress(Elt, NumToInsert);
  667. // Uninvalidate the iterator.
  668. I = this->begin()+InsertElt;
  669. // If there are more elements between the insertion point and the end of the
  670. // range than there are being inserted, we can use a simple approach to
  671. // insertion. Since we already reserved space, we know that this won't
  672. // reallocate the vector.
  673. if (size_t(this->end()-I) >= NumToInsert) {
  674. T *OldEnd = this->end();
  675. append(std::move_iterator<iterator>(this->end() - NumToInsert),
  676. std::move_iterator<iterator>(this->end()));
  677. // Copy the existing elements that get replaced.
  678. std::move_backward(I, OldEnd-NumToInsert, OldEnd);
  679. // If we just moved the element we're inserting, be sure to update
  680. // the reference (never happens if TakesParamByValue).
  681. if (!TakesParamByValue && I <= EltPtr && EltPtr < this->end())
  682. EltPtr += NumToInsert;
  683. std::fill_n(I, NumToInsert, *EltPtr);
  684. return I;
  685. }
  686. // Otherwise, we're inserting more elements than exist already, and we're
  687. // not inserting at the end.
  688. // Move over the elements that we're about to overwrite.
  689. T *OldEnd = this->end();
  690. this->set_size(this->size() + NumToInsert);
  691. size_t NumOverwritten = OldEnd-I;
  692. this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
  693. // If we just moved the element we're inserting, be sure to update
  694. // the reference (never happens if TakesParamByValue).
  695. if (!TakesParamByValue && I <= EltPtr && EltPtr < this->end())
  696. EltPtr += NumToInsert;
  697. // Replace the overwritten part.
  698. std::fill_n(I, NumOverwritten, *EltPtr);
  699. // Insert the non-overwritten middle part.
  700. std::uninitialized_fill_n(OldEnd, NumToInsert - NumOverwritten, *EltPtr);
  701. return I;
  702. }
  703. template <typename ItTy,
  704. typename = std::enable_if_t<std::is_convertible<
  705. typename std::iterator_traits<ItTy>::iterator_category,
  706. std::input_iterator_tag>::value>>
  707. iterator insert(iterator I, ItTy From, ItTy To) {
  708. // Convert iterator to elt# to avoid invalidating iterator when we reserve()
  709. size_t InsertElt = I - this->begin();
  710. if (I == this->end()) { // Important special case for empty vector.
  711. append(From, To);
  712. return this->begin()+InsertElt;
  713. }
  714. assert(this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.");
  715. // Check that the reserve that follows doesn't invalidate the iterators.
  716. this->assertSafeToAddRange(From, To);
  717. size_t NumToInsert = std::distance(From, To);
  718. // Ensure there is enough space.
  719. reserve(this->size() + NumToInsert);
  720. // Uninvalidate the iterator.
  721. I = this->begin()+InsertElt;
  722. // If there are more elements between the insertion point and the end of the
  723. // range than there are being inserted, we can use a simple approach to
  724. // insertion. Since we already reserved space, we know that this won't
  725. // reallocate the vector.
  726. if (size_t(this->end()-I) >= NumToInsert) {
  727. T *OldEnd = this->end();
  728. append(std::move_iterator<iterator>(this->end() - NumToInsert),
  729. std::move_iterator<iterator>(this->end()));
  730. // Copy the existing elements that get replaced.
  731. std::move_backward(I, OldEnd-NumToInsert, OldEnd);
  732. std::copy(From, To, I);
  733. return I;
  734. }
  735. // Otherwise, we're inserting more elements than exist already, and we're
  736. // not inserting at the end.
  737. // Move over the elements that we're about to overwrite.
  738. T *OldEnd = this->end();
  739. this->set_size(this->size() + NumToInsert);
  740. size_t NumOverwritten = OldEnd-I;
  741. this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
  742. // Replace the overwritten part.
  743. for (T *J = I; NumOverwritten > 0; --NumOverwritten) {
  744. *J = *From;
  745. ++J; ++From;
  746. }
  747. // Insert the non-overwritten middle part.
  748. this->uninitialized_copy(From, To, OldEnd);
  749. return I;
  750. }
  751. void insert(iterator I, std::initializer_list<T> IL) {
  752. insert(I, IL.begin(), IL.end());
  753. }
  754. template <typename... ArgTypes> reference emplace_back(ArgTypes &&... Args) {
  755. if (LLVM_UNLIKELY(this->size() >= this->capacity()))
  756. return this->growAndEmplaceBack(std::forward<ArgTypes>(Args)...);
  757. ::new ((void *)this->end()) T(std::forward<ArgTypes>(Args)...);
  758. this->set_size(this->size() + 1);
  759. return this->back();
  760. }
  761. SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
  762. SmallVectorImpl &operator=(SmallVectorImpl &&RHS);
  763. bool operator==(const SmallVectorImpl &RHS) const {
  764. if (this->size() != RHS.size()) return false;
  765. return std::equal(this->begin(), this->end(), RHS.begin());
  766. }
  767. bool operator!=(const SmallVectorImpl &RHS) const {
  768. return !(*this == RHS);
  769. }
  770. bool operator<(const SmallVectorImpl &RHS) const {
  771. return std::lexicographical_compare(this->begin(), this->end(),
  772. RHS.begin(), RHS.end());
  773. }
  774. };
  775. template <typename T>
  776. void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
  777. if (this == &RHS) return;
  778. // We can only avoid copying elements if neither vector is small.
  779. if (!this->isSmall() && !RHS.isSmall()) {
  780. std::swap(this->BeginX, RHS.BeginX);
  781. std::swap(this->Size, RHS.Size);
  782. std::swap(this->Capacity, RHS.Capacity);
  783. return;
  784. }
  785. this->reserve(RHS.size());
  786. RHS.reserve(this->size());
  787. // Swap the shared elements.
  788. size_t NumShared = this->size();
  789. if (NumShared > RHS.size()) NumShared = RHS.size();
  790. for (size_type i = 0; i != NumShared; ++i)
  791. std::swap((*this)[i], RHS[i]);
  792. // Copy over the extra elts.
  793. if (this->size() > RHS.size()) {
  794. size_t EltDiff = this->size() - RHS.size();
  795. this->uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end());
  796. RHS.set_size(RHS.size() + EltDiff);
  797. this->destroy_range(this->begin()+NumShared, this->end());
  798. this->set_size(NumShared);
  799. } else if (RHS.size() > this->size()) {
  800. size_t EltDiff = RHS.size() - this->size();
  801. this->uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end());
  802. this->set_size(this->size() + EltDiff);
  803. this->destroy_range(RHS.begin()+NumShared, RHS.end());
  804. RHS.set_size(NumShared);
  805. }
  806. }
  807. template <typename T>
  808. SmallVectorImpl<T> &SmallVectorImpl<T>::
  809. operator=(const SmallVectorImpl<T> &RHS) {
  810. // Avoid self-assignment.
  811. if (this == &RHS) return *this;
  812. // If we already have sufficient space, assign the common elements, then
  813. // destroy any excess.
  814. size_t RHSSize = RHS.size();
  815. size_t CurSize = this->size();
  816. if (CurSize >= RHSSize) {
  817. // Assign common elements.
  818. iterator NewEnd;
  819. if (RHSSize)
  820. NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin());
  821. else
  822. NewEnd = this->begin();
  823. // Destroy excess elements.
  824. this->destroy_range(NewEnd, this->end());
  825. // Trim.
  826. this->set_size(RHSSize);
  827. return *this;
  828. }
  829. // If we have to grow to have enough elements, destroy the current elements.
  830. // This allows us to avoid copying them during the grow.
  831. // FIXME: don't do this if they're efficiently moveable.
  832. if (this->capacity() < RHSSize) {
  833. // Destroy current elements.
  834. this->clear();
  835. CurSize = 0;
  836. this->grow(RHSSize);
  837. } else if (CurSize) {
  838. // Otherwise, use assignment for the already-constructed elements.
  839. std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin());
  840. }
  841. // Copy construct the new elements in place.
  842. this->uninitialized_copy(RHS.begin()+CurSize, RHS.end(),
  843. this->begin()+CurSize);
  844. // Set end.
  845. this->set_size(RHSSize);
  846. return *this;
  847. }
  848. template <typename T>
  849. SmallVectorImpl<T> &SmallVectorImpl<T>::operator=(SmallVectorImpl<T> &&RHS) {
  850. // Avoid self-assignment.
  851. if (this == &RHS) return *this;
  852. // If the RHS isn't small, clear this vector and then steal its buffer.
  853. if (!RHS.isSmall()) {
  854. this->destroy_range(this->begin(), this->end());
  855. if (!this->isSmall()) free(this->begin());
  856. this->BeginX = RHS.BeginX;
  857. this->Size = RHS.Size;
  858. this->Capacity = RHS.Capacity;
  859. RHS.resetToSmall();
  860. return *this;
  861. }
  862. // If we already have sufficient space, assign the common elements, then
  863. // destroy any excess.
  864. size_t RHSSize = RHS.size();
  865. size_t CurSize = this->size();
  866. if (CurSize >= RHSSize) {
  867. // Assign common elements.
  868. iterator NewEnd = this->begin();
  869. if (RHSSize)
  870. NewEnd = std::move(RHS.begin(), RHS.end(), NewEnd);
  871. // Destroy excess elements and trim the bounds.
  872. this->destroy_range(NewEnd, this->end());
  873. this->set_size(RHSSize);
  874. // Clear the RHS.
  875. RHS.clear();
  876. return *this;
  877. }
  878. // If we have to grow to have enough elements, destroy the current elements.
  879. // This allows us to avoid copying them during the grow.
  880. // FIXME: this may not actually make any sense if we can efficiently move
  881. // elements.
  882. if (this->capacity() < RHSSize) {
  883. // Destroy current elements.
  884. this->clear();
  885. CurSize = 0;
  886. this->grow(RHSSize);
  887. } else if (CurSize) {
  888. // Otherwise, use assignment for the already-constructed elements.
  889. std::move(RHS.begin(), RHS.begin()+CurSize, this->begin());
  890. }
  891. // Move-construct the new elements in place.
  892. this->uninitialized_move(RHS.begin()+CurSize, RHS.end(),
  893. this->begin()+CurSize);
  894. // Set end.
  895. this->set_size(RHSSize);
  896. RHS.clear();
  897. return *this;
  898. }
  899. /// Storage for the SmallVector elements. This is specialized for the N=0 case
  900. /// to avoid allocating unnecessary storage.
  901. template <typename T, unsigned N>
  902. struct SmallVectorStorage {
  903. alignas(T) char InlineElts[N * sizeof(T)];
  904. };
  905. /// We need the storage to be properly aligned even for small-size of 0 so that
  906. /// the pointer math in \a SmallVectorTemplateCommon::getFirstEl() is
  907. /// well-defined.
  908. template <typename T> struct alignas(T) SmallVectorStorage<T, 0> {};
  909. /// Forward declaration of SmallVector so that
  910. /// calculateSmallVectorDefaultInlinedElements can reference
  911. /// `sizeof(SmallVector<T, 0>)`.
  912. template <typename T, unsigned N> class LLVM_GSL_OWNER SmallVector;
  913. /// Helper class for calculating the default number of inline elements for
  914. /// `SmallVector<T>`.
  915. ///
  916. /// This should be migrated to a constexpr function when our minimum
  917. /// compiler support is enough for multi-statement constexpr functions.
  918. template <typename T> struct CalculateSmallVectorDefaultInlinedElements {
  919. // Parameter controlling the default number of inlined elements
  920. // for `SmallVector<T>`.
  921. //
  922. // The default number of inlined elements ensures that
  923. // 1. There is at least one inlined element.
  924. // 2. `sizeof(SmallVector<T>) <= kPreferredSmallVectorSizeof` unless
  925. // it contradicts 1.
  926. static constexpr size_t kPreferredSmallVectorSizeof = 64;
  927. // static_assert that sizeof(T) is not "too big".
  928. //
  929. // Because our policy guarantees at least one inlined element, it is possible
  930. // for an arbitrarily large inlined element to allocate an arbitrarily large
  931. // amount of inline storage. We generally consider it an antipattern for a
  932. // SmallVector to allocate an excessive amount of inline storage, so we want
  933. // to call attention to these cases and make sure that users are making an
  934. // intentional decision if they request a lot of inline storage.
  935. //
  936. // We want this assertion to trigger in pathological cases, but otherwise
  937. // not be too easy to hit. To accomplish that, the cutoff is actually somewhat
  938. // larger than kPreferredSmallVectorSizeof (otherwise,
  939. // `SmallVector<SmallVector<T>>` would be one easy way to trip it, and that
  940. // pattern seems useful in practice).
  941. //
  942. // One wrinkle is that this assertion is in theory non-portable, since
  943. // sizeof(T) is in general platform-dependent. However, we don't expect this
  944. // to be much of an issue, because most LLVM development happens on 64-bit
  945. // hosts, and therefore sizeof(T) is expected to *decrease* when compiled for
  946. // 32-bit hosts, dodging the issue. The reverse situation, where development
  947. // happens on a 32-bit host and then fails due to sizeof(T) *increasing* on a
  948. // 64-bit host, is expected to be very rare.
  949. static_assert(
  950. sizeof(T) <= 256,
  951. "You are trying to use a default number of inlined elements for "
  952. "`SmallVector<T>` but `sizeof(T)` is really big! Please use an "
  953. "explicit number of inlined elements with `SmallVector<T, N>` to make "
  954. "sure you really want that much inline storage.");
  955. // Discount the size of the header itself when calculating the maximum inline
  956. // bytes.
  957. static constexpr size_t PreferredInlineBytes =
  958. kPreferredSmallVectorSizeof - sizeof(SmallVector<T, 0>);
  959. static constexpr size_t NumElementsThatFit = PreferredInlineBytes / sizeof(T);
  960. static constexpr size_t value =
  961. NumElementsThatFit == 0 ? 1 : NumElementsThatFit;
  962. };
  963. /// This is a 'vector' (really, a variable-sized array), optimized
  964. /// for the case when the array is small. It contains some number of elements
  965. /// in-place, which allows it to avoid heap allocation when the actual number of
  966. /// elements is below that threshold. This allows normal "small" cases to be
  967. /// fast without losing generality for large inputs.
  968. ///
  969. /// \note
  970. /// In the absence of a well-motivated choice for the number of inlined
  971. /// elements \p N, it is recommended to use \c SmallVector<T> (that is,
  972. /// omitting the \p N). This will choose a default number of inlined elements
  973. /// reasonable for allocation on the stack (for example, trying to keep \c
  974. /// sizeof(SmallVector<T>) around 64 bytes).
  975. ///
  976. /// \warning This does not attempt to be exception safe.
  977. ///
  978. /// \see https://llvm.org/docs/ProgrammersManual.html#llvm-adt-smallvector-h
  979. template <typename T,
  980. unsigned N = CalculateSmallVectorDefaultInlinedElements<T>::value>
  981. class LLVM_GSL_OWNER SmallVector : public SmallVectorImpl<T>,
  982. SmallVectorStorage<T, N> {
  983. public:
  984. SmallVector() : SmallVectorImpl<T>(N) {}
  985. ~SmallVector() {
  986. // Destroy the constructed elements in the vector.
  987. this->destroy_range(this->begin(), this->end());
  988. }
  989. explicit SmallVector(size_t Size, const T &Value = T())
  990. : SmallVectorImpl<T>(N) {
  991. this->assign(Size, Value);
  992. }
  993. template <typename ItTy,
  994. typename = std::enable_if_t<std::is_convertible<
  995. typename std::iterator_traits<ItTy>::iterator_category,
  996. std::input_iterator_tag>::value>>
  997. SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(N) {
  998. this->append(S, E);
  999. }
  1000. template <typename RangeTy>
  1001. explicit SmallVector(const iterator_range<RangeTy> &R)
  1002. : SmallVectorImpl<T>(N) {
  1003. this->append(R.begin(), R.end());
  1004. }
  1005. SmallVector(std::initializer_list<T> IL) : SmallVectorImpl<T>(N) {
  1006. this->assign(IL);
  1007. }
  1008. SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(N) {
  1009. if (!RHS.empty())
  1010. SmallVectorImpl<T>::operator=(RHS);
  1011. }
  1012. SmallVector &operator=(const SmallVector &RHS) {
  1013. SmallVectorImpl<T>::operator=(RHS);
  1014. return *this;
  1015. }
  1016. SmallVector(SmallVector &&RHS) : SmallVectorImpl<T>(N) {
  1017. if (!RHS.empty())
  1018. SmallVectorImpl<T>::operator=(::std::move(RHS));
  1019. }
  1020. SmallVector(SmallVectorImpl<T> &&RHS) : SmallVectorImpl<T>(N) {
  1021. if (!RHS.empty())
  1022. SmallVectorImpl<T>::operator=(::std::move(RHS));
  1023. }
  1024. SmallVector &operator=(SmallVector &&RHS) {
  1025. SmallVectorImpl<T>::operator=(::std::move(RHS));
  1026. return *this;
  1027. }
  1028. SmallVector &operator=(SmallVectorImpl<T> &&RHS) {
  1029. SmallVectorImpl<T>::operator=(::std::move(RHS));
  1030. return *this;
  1031. }
  1032. SmallVector &operator=(std::initializer_list<T> IL) {
  1033. this->assign(IL);
  1034. return *this;
  1035. }
  1036. };
  1037. template <typename T, unsigned N>
  1038. inline size_t capacity_in_bytes(const SmallVector<T, N> &X) {
  1039. return X.capacity_in_bytes();
  1040. }
  1041. /// Given a range of type R, iterate the entire range and return a
  1042. /// SmallVector with elements of the vector. This is useful, for example,
  1043. /// when you want to iterate a range and then sort the results.
  1044. template <unsigned Size, typename R>
  1045. SmallVector<typename std::remove_const<typename std::remove_reference<
  1046. decltype(*std::begin(std::declval<R &>()))>::type>::type,
  1047. Size>
  1048. to_vector(R &&Range) {
  1049. return {std::begin(Range), std::end(Range)};
  1050. }
  1051. } // end namespace llvm
  1052. namespace std {
  1053. /// Implement std::swap in terms of SmallVector swap.
  1054. template<typename T>
  1055. inline void
  1056. swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
  1057. LHS.swap(RHS);
  1058. }
  1059. /// Implement std::swap in terms of SmallVector swap.
  1060. template<typename T, unsigned N>
  1061. inline void
  1062. swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
  1063. LHS.swap(RHS);
  1064. }
  1065. } // end namespace std
  1066. #endif // LLVM_ADT_SMALLVECTOR_H