SmallVector.h 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. ///
  14. /// /file
  15. /// This file defines the SmallVector class.
  16. ///
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_ADT_SMALLVECTOR_H
  19. #define LLVM_ADT_SMALLVECTOR_H
  20. #include "llvm/Support/Compiler.h"
  21. #include "llvm/Support/type_traits.h"
  22. #include <algorithm>
  23. #include <cassert>
  24. #include <cstddef>
  25. #include <cstdlib>
  26. #include <cstring>
  27. #include <functional>
  28. #include <initializer_list>
  29. #include <iterator>
  30. #include <limits>
  31. #include <memory>
  32. #include <new>
  33. #include <type_traits>
  34. #include <utility>
  35. namespace llvm {
  36. template <typename IteratorT> class iterator_range;
  37. /// This is all the stuff common to all SmallVectors.
  38. ///
  39. /// The template parameter specifies the type which should be used to hold the
  40. /// Size and Capacity of the SmallVector, so it can be adjusted.
  41. /// Using 32 bit size is desirable to shrink the size of the SmallVector.
  42. /// Using 64 bit size is desirable for cases like SmallVector<char>, where a
  43. /// 32 bit size would limit the vector to ~4GB. SmallVectors are used for
  44. /// buffering bitcode output - which can exceed 4GB.
  45. template <class Size_T> class SmallVectorBase {
  46. protected:
  47. void *BeginX;
  48. Size_T Size = 0, Capacity;
  49. /// The maximum value of the Size_T used.
  50. static constexpr size_t SizeTypeMax() {
  51. return std::numeric_limits<Size_T>::max();
  52. }
  53. SmallVectorBase() = delete;
  54. SmallVectorBase(void *FirstEl, size_t TotalCapacity)
  55. : BeginX(FirstEl), Capacity(TotalCapacity) {}
  56. /// This is a helper for \a grow() that's out of line to reduce code
  57. /// duplication. This function will report a fatal error if it can't grow at
  58. /// least to \p MinSize.
  59. void *mallocForGrow(size_t MinSize, size_t TSize, size_t &NewCapacity);
  60. /// This is an implementation of the grow() method which only works
  61. /// on POD-like data types and is out of line to reduce code duplication.
  62. /// This function will report a fatal error if it cannot increase capacity.
  63. void grow_pod(void *FirstEl, size_t MinSize, size_t TSize);
  64. public:
  65. size_t size() const { return Size; }
  66. size_t capacity() const { return Capacity; }
  67. LLVM_NODISCARD bool empty() const { return !Size; }
  68. protected:
  69. /// Set the array size to \p N, which the current array must have enough
  70. /// capacity for.
  71. ///
  72. /// This does not construct or destroy any elements in the vector.
  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. void assignRemote(SmallVectorImpl &&RHS) {
  489. this->destroy_range(this->begin(), this->end());
  490. if (!this->isSmall())
  491. free(this->begin());
  492. this->BeginX = RHS.BeginX;
  493. this->Size = RHS.Size;
  494. this->Capacity = RHS.Capacity;
  495. RHS.resetToSmall();
  496. }
  497. public:
  498. SmallVectorImpl(const SmallVectorImpl &) = delete;
  499. ~SmallVectorImpl() {
  500. // Subclass has already destructed this vector's elements.
  501. // If this wasn't grown from the inline copy, deallocate the old space.
  502. if (!this->isSmall())
  503. free(this->begin());
  504. }
  505. void clear() {
  506. this->destroy_range(this->begin(), this->end());
  507. this->Size = 0;
  508. }
  509. private:
  510. // Make set_size() private to avoid misuse in subclasses.
  511. using SuperClass::set_size;
  512. template <bool ForOverwrite> void resizeImpl(size_type N) {
  513. if (N == this->size())
  514. return;
  515. if (N < this->size()) {
  516. this->truncate(N);
  517. return;
  518. }
  519. this->reserve(N);
  520. for (auto I = this->end(), E = this->begin() + N; I != E; ++I)
  521. if (ForOverwrite)
  522. new (&*I) T;
  523. else
  524. new (&*I) T();
  525. this->set_size(N);
  526. }
  527. public:
  528. void resize(size_type N) { resizeImpl<false>(N); }
  529. /// Like resize, but \ref T is POD, the new values won't be initialized.
  530. void resize_for_overwrite(size_type N) { resizeImpl<true>(N); }
  531. /// Like resize, but requires that \p N is less than \a size().
  532. void truncate(size_type N) {
  533. assert(this->size() >= N && "Cannot increase size with truncate");
  534. this->destroy_range(this->begin() + N, this->end());
  535. this->set_size(N);
  536. }
  537. void resize(size_type N, ValueParamT NV) {
  538. if (N == this->size())
  539. return;
  540. if (N < this->size()) {
  541. this->truncate(N);
  542. return;
  543. }
  544. // N > this->size(). Defer to append.
  545. this->append(N - this->size(), NV);
  546. }
  547. void reserve(size_type N) {
  548. if (this->capacity() < N)
  549. this->grow(N);
  550. }
  551. void pop_back_n(size_type NumItems) {
  552. assert(this->size() >= NumItems);
  553. truncate(this->size() - NumItems);
  554. }
  555. LLVM_NODISCARD T pop_back_val() {
  556. T Result = ::std::move(this->back());
  557. this->pop_back();
  558. return Result;
  559. }
  560. void swap(SmallVectorImpl &RHS);
  561. /// Add the specified range to the end of the SmallVector.
  562. template <typename in_iter,
  563. typename = std::enable_if_t<std::is_convertible<
  564. typename std::iterator_traits<in_iter>::iterator_category,
  565. std::input_iterator_tag>::value>>
  566. void append(in_iter in_start, in_iter in_end) {
  567. this->assertSafeToAddRange(in_start, in_end);
  568. size_type NumInputs = std::distance(in_start, in_end);
  569. this->reserve(this->size() + NumInputs);
  570. this->uninitialized_copy(in_start, in_end, this->end());
  571. this->set_size(this->size() + NumInputs);
  572. }
  573. /// Append \p NumInputs copies of \p Elt to the end.
  574. void append(size_type NumInputs, ValueParamT Elt) {
  575. const T *EltPtr = this->reserveForParamAndGetAddress(Elt, NumInputs);
  576. std::uninitialized_fill_n(this->end(), NumInputs, *EltPtr);
  577. this->set_size(this->size() + NumInputs);
  578. }
  579. void append(std::initializer_list<T> IL) {
  580. append(IL.begin(), IL.end());
  581. }
  582. void append(const SmallVectorImpl &RHS) { append(RHS.begin(), RHS.end()); }
  583. void assign(size_type NumElts, ValueParamT Elt) {
  584. // Note that Elt could be an internal reference.
  585. if (NumElts > this->capacity()) {
  586. this->growAndAssign(NumElts, Elt);
  587. return;
  588. }
  589. // Assign over existing elements.
  590. std::fill_n(this->begin(), std::min(NumElts, this->size()), Elt);
  591. if (NumElts > this->size())
  592. std::uninitialized_fill_n(this->end(), NumElts - this->size(), Elt);
  593. else if (NumElts < this->size())
  594. this->destroy_range(this->begin() + NumElts, this->end());
  595. this->set_size(NumElts);
  596. }
  597. // FIXME: Consider assigning over existing elements, rather than clearing &
  598. // re-initializing them - for all assign(...) variants.
  599. template <typename in_iter,
  600. typename = std::enable_if_t<std::is_convertible<
  601. typename std::iterator_traits<in_iter>::iterator_category,
  602. std::input_iterator_tag>::value>>
  603. void assign(in_iter in_start, in_iter in_end) {
  604. this->assertSafeToReferenceAfterClear(in_start, in_end);
  605. clear();
  606. append(in_start, in_end);
  607. }
  608. void assign(std::initializer_list<T> IL) {
  609. clear();
  610. append(IL);
  611. }
  612. void assign(const SmallVectorImpl &RHS) { assign(RHS.begin(), RHS.end()); }
  613. iterator erase(const_iterator CI) {
  614. // Just cast away constness because this is a non-const member function.
  615. iterator I = const_cast<iterator>(CI);
  616. assert(this->isReferenceToStorage(CI) && "Iterator to erase is out of bounds.");
  617. iterator N = I;
  618. // Shift all elts down one.
  619. std::move(I+1, this->end(), I);
  620. // Drop the last elt.
  621. this->pop_back();
  622. return(N);
  623. }
  624. iterator erase(const_iterator CS, const_iterator CE) {
  625. // Just cast away constness because this is a non-const member function.
  626. iterator S = const_cast<iterator>(CS);
  627. iterator E = const_cast<iterator>(CE);
  628. assert(this->isRangeInStorage(S, E) && "Range to erase is out of bounds.");
  629. iterator N = S;
  630. // Shift all elts down.
  631. iterator I = std::move(E, this->end(), S);
  632. // Drop the last elts.
  633. this->destroy_range(I, this->end());
  634. this->set_size(I - this->begin());
  635. return(N);
  636. }
  637. private:
  638. template <class ArgType> iterator insert_one_impl(iterator I, ArgType &&Elt) {
  639. // Callers ensure that ArgType is derived from T.
  640. static_assert(
  641. std::is_same<std::remove_const_t<std::remove_reference_t<ArgType>>,
  642. T>::value,
  643. "ArgType must be derived from T!");
  644. if (I == this->end()) { // Important special case for empty vector.
  645. this->push_back(::std::forward<ArgType>(Elt));
  646. return this->end()-1;
  647. }
  648. assert(this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.");
  649. // Grow if necessary.
  650. size_t Index = I - this->begin();
  651. std::remove_reference_t<ArgType> *EltPtr =
  652. this->reserveForParamAndGetAddress(Elt);
  653. I = this->begin() + Index;
  654. ::new ((void*) this->end()) T(::std::move(this->back()));
  655. // Push everything else over.
  656. std::move_backward(I, this->end()-1, this->end());
  657. this->set_size(this->size() + 1);
  658. // If we just moved the element we're inserting, be sure to update
  659. // the reference (never happens if TakesParamByValue).
  660. static_assert(!TakesParamByValue || std::is_same<ArgType, T>::value,
  661. "ArgType must be 'T' when taking by value!");
  662. if (!TakesParamByValue && this->isReferenceToRange(EltPtr, I, this->end()))
  663. ++EltPtr;
  664. *I = ::std::forward<ArgType>(*EltPtr);
  665. return I;
  666. }
  667. public:
  668. iterator insert(iterator I, T &&Elt) {
  669. return insert_one_impl(I, this->forward_value_param(std::move(Elt)));
  670. }
  671. iterator insert(iterator I, const T &Elt) {
  672. return insert_one_impl(I, this->forward_value_param(Elt));
  673. }
  674. iterator insert(iterator I, size_type NumToInsert, ValueParamT Elt) {
  675. // Convert iterator to elt# to avoid invalidating iterator when we reserve()
  676. size_t InsertElt = I - this->begin();
  677. if (I == this->end()) { // Important special case for empty vector.
  678. append(NumToInsert, Elt);
  679. return this->begin()+InsertElt;
  680. }
  681. assert(this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.");
  682. // Ensure there is enough space, and get the (maybe updated) address of
  683. // Elt.
  684. const T *EltPtr = this->reserveForParamAndGetAddress(Elt, NumToInsert);
  685. // Uninvalidate the iterator.
  686. I = this->begin()+InsertElt;
  687. // If there are more elements between the insertion point and the end of the
  688. // range than there are being inserted, we can use a simple approach to
  689. // insertion. Since we already reserved space, we know that this won't
  690. // reallocate the vector.
  691. if (size_t(this->end()-I) >= NumToInsert) {
  692. T *OldEnd = this->end();
  693. append(std::move_iterator<iterator>(this->end() - NumToInsert),
  694. std::move_iterator<iterator>(this->end()));
  695. // Copy the existing elements that get replaced.
  696. std::move_backward(I, OldEnd-NumToInsert, OldEnd);
  697. // If we just moved the element we're inserting, be sure to update
  698. // the reference (never happens if TakesParamByValue).
  699. if (!TakesParamByValue && I <= EltPtr && EltPtr < this->end())
  700. EltPtr += NumToInsert;
  701. std::fill_n(I, NumToInsert, *EltPtr);
  702. return I;
  703. }
  704. // Otherwise, we're inserting more elements than exist already, and we're
  705. // not inserting at the end.
  706. // Move over the elements that we're about to overwrite.
  707. T *OldEnd = this->end();
  708. this->set_size(this->size() + NumToInsert);
  709. size_t NumOverwritten = OldEnd-I;
  710. this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
  711. // If we just moved the element we're inserting, be sure to update
  712. // the reference (never happens if TakesParamByValue).
  713. if (!TakesParamByValue && I <= EltPtr && EltPtr < this->end())
  714. EltPtr += NumToInsert;
  715. // Replace the overwritten part.
  716. std::fill_n(I, NumOverwritten, *EltPtr);
  717. // Insert the non-overwritten middle part.
  718. std::uninitialized_fill_n(OldEnd, NumToInsert - NumOverwritten, *EltPtr);
  719. return I;
  720. }
  721. template <typename ItTy,
  722. typename = std::enable_if_t<std::is_convertible<
  723. typename std::iterator_traits<ItTy>::iterator_category,
  724. std::input_iterator_tag>::value>>
  725. iterator insert(iterator I, ItTy From, ItTy To) {
  726. // Convert iterator to elt# to avoid invalidating iterator when we reserve()
  727. size_t InsertElt = I - this->begin();
  728. if (I == this->end()) { // Important special case for empty vector.
  729. append(From, To);
  730. return this->begin()+InsertElt;
  731. }
  732. assert(this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.");
  733. // Check that the reserve that follows doesn't invalidate the iterators.
  734. this->assertSafeToAddRange(From, To);
  735. size_t NumToInsert = std::distance(From, To);
  736. // Ensure there is enough space.
  737. reserve(this->size() + NumToInsert);
  738. // Uninvalidate the iterator.
  739. I = this->begin()+InsertElt;
  740. // If there are more elements between the insertion point and the end of the
  741. // range than there are being inserted, we can use a simple approach to
  742. // insertion. Since we already reserved space, we know that this won't
  743. // reallocate the vector.
  744. if (size_t(this->end()-I) >= NumToInsert) {
  745. T *OldEnd = this->end();
  746. append(std::move_iterator<iterator>(this->end() - NumToInsert),
  747. std::move_iterator<iterator>(this->end()));
  748. // Copy the existing elements that get replaced.
  749. std::move_backward(I, OldEnd-NumToInsert, OldEnd);
  750. std::copy(From, To, I);
  751. return I;
  752. }
  753. // Otherwise, we're inserting more elements than exist already, and we're
  754. // not inserting at the end.
  755. // Move over the elements that we're about to overwrite.
  756. T *OldEnd = this->end();
  757. this->set_size(this->size() + NumToInsert);
  758. size_t NumOverwritten = OldEnd-I;
  759. this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
  760. // Replace the overwritten part.
  761. for (T *J = I; NumOverwritten > 0; --NumOverwritten) {
  762. *J = *From;
  763. ++J; ++From;
  764. }
  765. // Insert the non-overwritten middle part.
  766. this->uninitialized_copy(From, To, OldEnd);
  767. return I;
  768. }
  769. void insert(iterator I, std::initializer_list<T> IL) {
  770. insert(I, IL.begin(), IL.end());
  771. }
  772. template <typename... ArgTypes> reference emplace_back(ArgTypes &&... Args) {
  773. if (LLVM_UNLIKELY(this->size() >= this->capacity()))
  774. return this->growAndEmplaceBack(std::forward<ArgTypes>(Args)...);
  775. ::new ((void *)this->end()) T(std::forward<ArgTypes>(Args)...);
  776. this->set_size(this->size() + 1);
  777. return this->back();
  778. }
  779. SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
  780. SmallVectorImpl &operator=(SmallVectorImpl &&RHS);
  781. bool operator==(const SmallVectorImpl &RHS) const {
  782. if (this->size() != RHS.size()) return false;
  783. return std::equal(this->begin(), this->end(), RHS.begin());
  784. }
  785. bool operator!=(const SmallVectorImpl &RHS) const {
  786. return !(*this == RHS);
  787. }
  788. bool operator<(const SmallVectorImpl &RHS) const {
  789. return std::lexicographical_compare(this->begin(), this->end(),
  790. RHS.begin(), RHS.end());
  791. }
  792. };
  793. template <typename T>
  794. void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
  795. if (this == &RHS) return;
  796. // We can only avoid copying elements if neither vector is small.
  797. if (!this->isSmall() && !RHS.isSmall()) {
  798. std::swap(this->BeginX, RHS.BeginX);
  799. std::swap(this->Size, RHS.Size);
  800. std::swap(this->Capacity, RHS.Capacity);
  801. return;
  802. }
  803. this->reserve(RHS.size());
  804. RHS.reserve(this->size());
  805. // Swap the shared elements.
  806. size_t NumShared = this->size();
  807. if (NumShared > RHS.size()) NumShared = RHS.size();
  808. for (size_type i = 0; i != NumShared; ++i)
  809. std::swap((*this)[i], RHS[i]);
  810. // Copy over the extra elts.
  811. if (this->size() > RHS.size()) {
  812. size_t EltDiff = this->size() - RHS.size();
  813. this->uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end());
  814. RHS.set_size(RHS.size() + EltDiff);
  815. this->destroy_range(this->begin()+NumShared, this->end());
  816. this->set_size(NumShared);
  817. } else if (RHS.size() > this->size()) {
  818. size_t EltDiff = RHS.size() - this->size();
  819. this->uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end());
  820. this->set_size(this->size() + EltDiff);
  821. this->destroy_range(RHS.begin()+NumShared, RHS.end());
  822. RHS.set_size(NumShared);
  823. }
  824. }
  825. template <typename T>
  826. SmallVectorImpl<T> &SmallVectorImpl<T>::
  827. operator=(const SmallVectorImpl<T> &RHS) {
  828. // Avoid self-assignment.
  829. if (this == &RHS) return *this;
  830. // If we already have sufficient space, assign the common elements, then
  831. // destroy any excess.
  832. size_t RHSSize = RHS.size();
  833. size_t CurSize = this->size();
  834. if (CurSize >= RHSSize) {
  835. // Assign common elements.
  836. iterator NewEnd;
  837. if (RHSSize)
  838. NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin());
  839. else
  840. NewEnd = this->begin();
  841. // Destroy excess elements.
  842. this->destroy_range(NewEnd, this->end());
  843. // Trim.
  844. this->set_size(RHSSize);
  845. return *this;
  846. }
  847. // If we have to grow to have enough elements, destroy the current elements.
  848. // This allows us to avoid copying them during the grow.
  849. // FIXME: don't do this if they're efficiently moveable.
  850. if (this->capacity() < RHSSize) {
  851. // Destroy current elements.
  852. this->clear();
  853. CurSize = 0;
  854. this->grow(RHSSize);
  855. } else if (CurSize) {
  856. // Otherwise, use assignment for the already-constructed elements.
  857. std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin());
  858. }
  859. // Copy construct the new elements in place.
  860. this->uninitialized_copy(RHS.begin()+CurSize, RHS.end(),
  861. this->begin()+CurSize);
  862. // Set end.
  863. this->set_size(RHSSize);
  864. return *this;
  865. }
  866. template <typename T>
  867. SmallVectorImpl<T> &SmallVectorImpl<T>::operator=(SmallVectorImpl<T> &&RHS) {
  868. // Avoid self-assignment.
  869. if (this == &RHS) return *this;
  870. // If the RHS isn't small, clear this vector and then steal its buffer.
  871. if (!RHS.isSmall()) {
  872. this->assignRemote(std::move(RHS));
  873. return *this;
  874. }
  875. // If we already have sufficient space, assign the common elements, then
  876. // destroy any excess.
  877. size_t RHSSize = RHS.size();
  878. size_t CurSize = this->size();
  879. if (CurSize >= RHSSize) {
  880. // Assign common elements.
  881. iterator NewEnd = this->begin();
  882. if (RHSSize)
  883. NewEnd = std::move(RHS.begin(), RHS.end(), NewEnd);
  884. // Destroy excess elements and trim the bounds.
  885. this->destroy_range(NewEnd, this->end());
  886. this->set_size(RHSSize);
  887. // Clear the RHS.
  888. RHS.clear();
  889. return *this;
  890. }
  891. // If we have to grow to have enough elements, destroy the current elements.
  892. // This allows us to avoid copying them during the grow.
  893. // FIXME: this may not actually make any sense if we can efficiently move
  894. // elements.
  895. if (this->capacity() < RHSSize) {
  896. // Destroy current elements.
  897. this->clear();
  898. CurSize = 0;
  899. this->grow(RHSSize);
  900. } else if (CurSize) {
  901. // Otherwise, use assignment for the already-constructed elements.
  902. std::move(RHS.begin(), RHS.begin()+CurSize, this->begin());
  903. }
  904. // Move-construct the new elements in place.
  905. this->uninitialized_move(RHS.begin()+CurSize, RHS.end(),
  906. this->begin()+CurSize);
  907. // Set end.
  908. this->set_size(RHSSize);
  909. RHS.clear();
  910. return *this;
  911. }
  912. /// Storage for the SmallVector elements. This is specialized for the N=0 case
  913. /// to avoid allocating unnecessary storage.
  914. template <typename T, unsigned N>
  915. struct SmallVectorStorage {
  916. alignas(T) char InlineElts[N * sizeof(T)];
  917. };
  918. /// We need the storage to be properly aligned even for small-size of 0 so that
  919. /// the pointer math in \a SmallVectorTemplateCommon::getFirstEl() is
  920. /// well-defined.
  921. template <typename T> struct alignas(T) SmallVectorStorage<T, 0> {};
  922. /// Forward declaration of SmallVector so that
  923. /// calculateSmallVectorDefaultInlinedElements can reference
  924. /// `sizeof(SmallVector<T, 0>)`.
  925. template <typename T, unsigned N> class LLVM_GSL_OWNER SmallVector;
  926. /// Helper class for calculating the default number of inline elements for
  927. /// `SmallVector<T>`.
  928. ///
  929. /// This should be migrated to a constexpr function when our minimum
  930. /// compiler support is enough for multi-statement constexpr functions.
  931. template <typename T> struct CalculateSmallVectorDefaultInlinedElements {
  932. // Parameter controlling the default number of inlined elements
  933. // for `SmallVector<T>`.
  934. //
  935. // The default number of inlined elements ensures that
  936. // 1. There is at least one inlined element.
  937. // 2. `sizeof(SmallVector<T>) <= kPreferredSmallVectorSizeof` unless
  938. // it contradicts 1.
  939. static constexpr size_t kPreferredSmallVectorSizeof = 64;
  940. // static_assert that sizeof(T) is not "too big".
  941. //
  942. // Because our policy guarantees at least one inlined element, it is possible
  943. // for an arbitrarily large inlined element to allocate an arbitrarily large
  944. // amount of inline storage. We generally consider it an antipattern for a
  945. // SmallVector to allocate an excessive amount of inline storage, so we want
  946. // to call attention to these cases and make sure that users are making an
  947. // intentional decision if they request a lot of inline storage.
  948. //
  949. // We want this assertion to trigger in pathological cases, but otherwise
  950. // not be too easy to hit. To accomplish that, the cutoff is actually somewhat
  951. // larger than kPreferredSmallVectorSizeof (otherwise,
  952. // `SmallVector<SmallVector<T>>` would be one easy way to trip it, and that
  953. // pattern seems useful in practice).
  954. //
  955. // One wrinkle is that this assertion is in theory non-portable, since
  956. // sizeof(T) is in general platform-dependent. However, we don't expect this
  957. // to be much of an issue, because most LLVM development happens on 64-bit
  958. // hosts, and therefore sizeof(T) is expected to *decrease* when compiled for
  959. // 32-bit hosts, dodging the issue. The reverse situation, where development
  960. // happens on a 32-bit host and then fails due to sizeof(T) *increasing* on a
  961. // 64-bit host, is expected to be very rare.
  962. static_assert(
  963. sizeof(T) <= 256,
  964. "You are trying to use a default number of inlined elements for "
  965. "`SmallVector<T>` but `sizeof(T)` is really big! Please use an "
  966. "explicit number of inlined elements with `SmallVector<T, N>` to make "
  967. "sure you really want that much inline storage.");
  968. // Discount the size of the header itself when calculating the maximum inline
  969. // bytes.
  970. static constexpr size_t PreferredInlineBytes =
  971. kPreferredSmallVectorSizeof - sizeof(SmallVector<T, 0>);
  972. static constexpr size_t NumElementsThatFit = PreferredInlineBytes / sizeof(T);
  973. static constexpr size_t value =
  974. NumElementsThatFit == 0 ? 1 : NumElementsThatFit;
  975. };
  976. /// This is a 'vector' (really, a variable-sized array), optimized
  977. /// for the case when the array is small. It contains some number of elements
  978. /// in-place, which allows it to avoid heap allocation when the actual number of
  979. /// elements is below that threshold. This allows normal "small" cases to be
  980. /// fast without losing generality for large inputs.
  981. ///
  982. /// \note
  983. /// In the absence of a well-motivated choice for the number of inlined
  984. /// elements \p N, it is recommended to use \c SmallVector<T> (that is,
  985. /// omitting the \p N). This will choose a default number of inlined elements
  986. /// reasonable for allocation on the stack (for example, trying to keep \c
  987. /// sizeof(SmallVector<T>) around 64 bytes).
  988. ///
  989. /// \warning This does not attempt to be exception safe.
  990. ///
  991. /// \see https://llvm.org/docs/ProgrammersManual.html#llvm-adt-smallvector-h
  992. template <typename T,
  993. unsigned N = CalculateSmallVectorDefaultInlinedElements<T>::value>
  994. class LLVM_GSL_OWNER SmallVector : public SmallVectorImpl<T>,
  995. SmallVectorStorage<T, N> {
  996. public:
  997. SmallVector() : SmallVectorImpl<T>(N) {}
  998. ~SmallVector() {
  999. // Destroy the constructed elements in the vector.
  1000. this->destroy_range(this->begin(), this->end());
  1001. }
  1002. explicit SmallVector(size_t Size, const T &Value = T())
  1003. : SmallVectorImpl<T>(N) {
  1004. this->assign(Size, Value);
  1005. }
  1006. template <typename ItTy,
  1007. typename = std::enable_if_t<std::is_convertible<
  1008. typename std::iterator_traits<ItTy>::iterator_category,
  1009. std::input_iterator_tag>::value>>
  1010. SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(N) {
  1011. this->append(S, E);
  1012. }
  1013. template <typename RangeTy>
  1014. explicit SmallVector(const iterator_range<RangeTy> &R)
  1015. : SmallVectorImpl<T>(N) {
  1016. this->append(R.begin(), R.end());
  1017. }
  1018. SmallVector(std::initializer_list<T> IL) : SmallVectorImpl<T>(N) {
  1019. this->assign(IL);
  1020. }
  1021. SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(N) {
  1022. if (!RHS.empty())
  1023. SmallVectorImpl<T>::operator=(RHS);
  1024. }
  1025. SmallVector &operator=(const SmallVector &RHS) {
  1026. SmallVectorImpl<T>::operator=(RHS);
  1027. return *this;
  1028. }
  1029. SmallVector(SmallVector &&RHS) : SmallVectorImpl<T>(N) {
  1030. if (!RHS.empty())
  1031. SmallVectorImpl<T>::operator=(::std::move(RHS));
  1032. }
  1033. SmallVector(SmallVectorImpl<T> &&RHS) : SmallVectorImpl<T>(N) {
  1034. if (!RHS.empty())
  1035. SmallVectorImpl<T>::operator=(::std::move(RHS));
  1036. }
  1037. SmallVector &operator=(SmallVector &&RHS) {
  1038. if (N) {
  1039. SmallVectorImpl<T>::operator=(::std::move(RHS));
  1040. return *this;
  1041. }
  1042. // SmallVectorImpl<T>::operator= does not leverage N==0. Optimize the
  1043. // case.
  1044. if (this == &RHS)
  1045. return *this;
  1046. if (RHS.empty()) {
  1047. this->destroy_range(this->begin(), this->end());
  1048. this->Size = 0;
  1049. } else {
  1050. this->assignRemote(std::move(RHS));
  1051. }
  1052. return *this;
  1053. }
  1054. SmallVector &operator=(SmallVectorImpl<T> &&RHS) {
  1055. SmallVectorImpl<T>::operator=(::std::move(RHS));
  1056. return *this;
  1057. }
  1058. SmallVector &operator=(std::initializer_list<T> IL) {
  1059. this->assign(IL);
  1060. return *this;
  1061. }
  1062. };
  1063. template <typename T, unsigned N>
  1064. inline size_t capacity_in_bytes(const SmallVector<T, N> &X) {
  1065. return X.capacity_in_bytes();
  1066. }
  1067. template <typename RangeType>
  1068. using ValueTypeFromRangeType =
  1069. typename std::remove_const<typename std::remove_reference<
  1070. decltype(*std::begin(std::declval<RangeType &>()))>::type>::type;
  1071. /// Given a range of type R, iterate the entire range and return a
  1072. /// SmallVector with elements of the vector. This is useful, for example,
  1073. /// when you want to iterate a range and then sort the results.
  1074. template <unsigned Size, typename R>
  1075. SmallVector<ValueTypeFromRangeType<R>, Size> to_vector(R &&Range) {
  1076. return {std::begin(Range), std::end(Range)};
  1077. }
  1078. template <typename R>
  1079. SmallVector<ValueTypeFromRangeType<R>,
  1080. CalculateSmallVectorDefaultInlinedElements<
  1081. ValueTypeFromRangeType<R>>::value>
  1082. to_vector(R &&Range) {
  1083. return {std::begin(Range), std::end(Range)};
  1084. }
  1085. } // end namespace llvm
  1086. namespace std {
  1087. /// Implement std::swap in terms of SmallVector swap.
  1088. template<typename T>
  1089. inline void
  1090. swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
  1091. LHS.swap(RHS);
  1092. }
  1093. /// Implement std::swap in terms of SmallVector swap.
  1094. template<typename T, unsigned N>
  1095. inline void
  1096. swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
  1097. LHS.swap(RHS);
  1098. }
  1099. } // end namespace std
  1100. #endif // LLVM_ADT_SMALLVECTOR_H
  1101. #ifdef __GNUC__
  1102. #pragma GCC diagnostic pop
  1103. #endif