SmallVector.h 48 KB

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