DenseMap.h 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/ADT/DenseMap.h - Dense probed hash table ------------*- 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. // This file defines the DenseMap class.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_ADT_DENSEMAP_H
  18. #define LLVM_ADT_DENSEMAP_H
  19. #include "llvm/ADT/DenseMapInfo.h"
  20. #include "llvm/ADT/EpochTracker.h"
  21. #include "llvm/Support/AlignOf.h"
  22. #include "llvm/Support/Compiler.h"
  23. #include "llvm/Support/MathExtras.h"
  24. #include "llvm/Support/MemAlloc.h"
  25. #include "llvm/Support/ReverseIteration.h"
  26. #include "llvm/Support/type_traits.h"
  27. #include <algorithm>
  28. #include <cassert>
  29. #include <cstddef>
  30. #include <cstring>
  31. #include <initializer_list>
  32. #include <iterator>
  33. #include <new>
  34. #include <type_traits>
  35. #include <utility>
  36. namespace llvm {
  37. namespace detail {
  38. // We extend a pair to allow users to override the bucket type with their own
  39. // implementation without requiring two members.
  40. template <typename KeyT, typename ValueT>
  41. struct DenseMapPair : public std::pair<KeyT, ValueT> {
  42. using std::pair<KeyT, ValueT>::pair;
  43. KeyT &getFirst() { return std::pair<KeyT, ValueT>::first; }
  44. const KeyT &getFirst() const { return std::pair<KeyT, ValueT>::first; }
  45. ValueT &getSecond() { return std::pair<KeyT, ValueT>::second; }
  46. const ValueT &getSecond() const { return std::pair<KeyT, ValueT>::second; }
  47. };
  48. } // end namespace detail
  49. template <typename KeyT, typename ValueT,
  50. typename KeyInfoT = DenseMapInfo<KeyT>,
  51. typename Bucket = llvm::detail::DenseMapPair<KeyT, ValueT>,
  52. bool IsConst = false>
  53. class DenseMapIterator;
  54. template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT,
  55. typename BucketT>
  56. class DenseMapBase : public DebugEpochBase {
  57. template <typename T>
  58. using const_arg_type_t = typename const_pointer_or_const_ref<T>::type;
  59. public:
  60. using size_type = unsigned;
  61. using key_type = KeyT;
  62. using mapped_type = ValueT;
  63. using value_type = BucketT;
  64. using iterator = DenseMapIterator<KeyT, ValueT, KeyInfoT, BucketT>;
  65. using const_iterator =
  66. DenseMapIterator<KeyT, ValueT, KeyInfoT, BucketT, true>;
  67. inline iterator begin() {
  68. // When the map is empty, avoid the overhead of advancing/retreating past
  69. // empty buckets.
  70. if (empty())
  71. return end();
  72. if (shouldReverseIterate<KeyT>())
  73. return makeIterator(getBucketsEnd() - 1, getBuckets(), *this);
  74. return makeIterator(getBuckets(), getBucketsEnd(), *this);
  75. }
  76. inline iterator end() {
  77. return makeIterator(getBucketsEnd(), getBucketsEnd(), *this, true);
  78. }
  79. inline const_iterator begin() const {
  80. if (empty())
  81. return end();
  82. if (shouldReverseIterate<KeyT>())
  83. return makeConstIterator(getBucketsEnd() - 1, getBuckets(), *this);
  84. return makeConstIterator(getBuckets(), getBucketsEnd(), *this);
  85. }
  86. inline const_iterator end() const {
  87. return makeConstIterator(getBucketsEnd(), getBucketsEnd(), *this, true);
  88. }
  89. LLVM_NODISCARD bool empty() const {
  90. return getNumEntries() == 0;
  91. }
  92. unsigned size() const { return getNumEntries(); }
  93. /// Grow the densemap so that it can contain at least \p NumEntries items
  94. /// before resizing again.
  95. void reserve(size_type NumEntries) {
  96. auto NumBuckets = getMinBucketToReserveForEntries(NumEntries);
  97. incrementEpoch();
  98. if (NumBuckets > getNumBuckets())
  99. grow(NumBuckets);
  100. }
  101. void clear() {
  102. incrementEpoch();
  103. if (getNumEntries() == 0 && getNumTombstones() == 0) return;
  104. // If the capacity of the array is huge, and the # elements used is small,
  105. // shrink the array.
  106. if (getNumEntries() * 4 < getNumBuckets() && getNumBuckets() > 64) {
  107. shrink_and_clear();
  108. return;
  109. }
  110. const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
  111. if (std::is_trivially_destructible<ValueT>::value) {
  112. // Use a simpler loop when values don't need destruction.
  113. for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P)
  114. P->getFirst() = EmptyKey;
  115. } else {
  116. unsigned NumEntries = getNumEntries();
  117. for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
  118. if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey)) {
  119. if (!KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) {
  120. P->getSecond().~ValueT();
  121. --NumEntries;
  122. }
  123. P->getFirst() = EmptyKey;
  124. }
  125. }
  126. assert(NumEntries == 0 && "Node count imbalance!");
  127. }
  128. setNumEntries(0);
  129. setNumTombstones(0);
  130. }
  131. /// Return 1 if the specified key is in the map, 0 otherwise.
  132. size_type count(const_arg_type_t<KeyT> Val) const {
  133. const BucketT *TheBucket;
  134. return LookupBucketFor(Val, TheBucket) ? 1 : 0;
  135. }
  136. iterator find(const_arg_type_t<KeyT> Val) {
  137. BucketT *TheBucket;
  138. if (LookupBucketFor(Val, TheBucket))
  139. return makeIterator(TheBucket,
  140. shouldReverseIterate<KeyT>() ? getBuckets()
  141. : getBucketsEnd(),
  142. *this, true);
  143. return end();
  144. }
  145. const_iterator find(const_arg_type_t<KeyT> Val) const {
  146. const BucketT *TheBucket;
  147. if (LookupBucketFor(Val, TheBucket))
  148. return makeConstIterator(TheBucket,
  149. shouldReverseIterate<KeyT>() ? getBuckets()
  150. : getBucketsEnd(),
  151. *this, true);
  152. return end();
  153. }
  154. /// Alternate version of find() which allows a different, and possibly
  155. /// less expensive, key type.
  156. /// The DenseMapInfo is responsible for supplying methods
  157. /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
  158. /// type used.
  159. template<class LookupKeyT>
  160. iterator find_as(const LookupKeyT &Val) {
  161. BucketT *TheBucket;
  162. if (LookupBucketFor(Val, TheBucket))
  163. return makeIterator(TheBucket,
  164. shouldReverseIterate<KeyT>() ? getBuckets()
  165. : getBucketsEnd(),
  166. *this, true);
  167. return end();
  168. }
  169. template<class LookupKeyT>
  170. const_iterator find_as(const LookupKeyT &Val) const {
  171. const BucketT *TheBucket;
  172. if (LookupBucketFor(Val, TheBucket))
  173. return makeConstIterator(TheBucket,
  174. shouldReverseIterate<KeyT>() ? getBuckets()
  175. : getBucketsEnd(),
  176. *this, true);
  177. return end();
  178. }
  179. /// lookup - Return the entry for the specified key, or a default
  180. /// constructed value if no such entry exists.
  181. ValueT lookup(const_arg_type_t<KeyT> Val) const {
  182. const BucketT *TheBucket;
  183. if (LookupBucketFor(Val, TheBucket))
  184. return TheBucket->getSecond();
  185. return ValueT();
  186. }
  187. // Inserts key,value pair into the map if the key isn't already in the map.
  188. // If the key is already in the map, it returns false and doesn't update the
  189. // value.
  190. std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
  191. return try_emplace(KV.first, KV.second);
  192. }
  193. // Inserts key,value pair into the map if the key isn't already in the map.
  194. // If the key is already in the map, it returns false and doesn't update the
  195. // value.
  196. std::pair<iterator, bool> insert(std::pair<KeyT, ValueT> &&KV) {
  197. return try_emplace(std::move(KV.first), std::move(KV.second));
  198. }
  199. // Inserts key,value pair into the map if the key isn't already in the map.
  200. // The value is constructed in-place if the key is not in the map, otherwise
  201. // it is not moved.
  202. template <typename... Ts>
  203. std::pair<iterator, bool> try_emplace(KeyT &&Key, Ts &&... Args) {
  204. BucketT *TheBucket;
  205. if (LookupBucketFor(Key, TheBucket))
  206. return std::make_pair(makeIterator(TheBucket,
  207. shouldReverseIterate<KeyT>()
  208. ? getBuckets()
  209. : getBucketsEnd(),
  210. *this, true),
  211. false); // Already in map.
  212. // Otherwise, insert the new element.
  213. TheBucket =
  214. InsertIntoBucket(TheBucket, std::move(Key), std::forward<Ts>(Args)...);
  215. return std::make_pair(makeIterator(TheBucket,
  216. shouldReverseIterate<KeyT>()
  217. ? getBuckets()
  218. : getBucketsEnd(),
  219. *this, true),
  220. true);
  221. }
  222. // Inserts key,value pair into the map if the key isn't already in the map.
  223. // The value is constructed in-place if the key is not in the map, otherwise
  224. // it is not moved.
  225. template <typename... Ts>
  226. std::pair<iterator, bool> try_emplace(const KeyT &Key, Ts &&... Args) {
  227. BucketT *TheBucket;
  228. if (LookupBucketFor(Key, TheBucket))
  229. return std::make_pair(makeIterator(TheBucket,
  230. shouldReverseIterate<KeyT>()
  231. ? getBuckets()
  232. : getBucketsEnd(),
  233. *this, true),
  234. false); // Already in map.
  235. // Otherwise, insert the new element.
  236. TheBucket = InsertIntoBucket(TheBucket, Key, std::forward<Ts>(Args)...);
  237. return std::make_pair(makeIterator(TheBucket,
  238. shouldReverseIterate<KeyT>()
  239. ? getBuckets()
  240. : getBucketsEnd(),
  241. *this, true),
  242. true);
  243. }
  244. /// Alternate version of insert() which allows a different, and possibly
  245. /// less expensive, key type.
  246. /// The DenseMapInfo is responsible for supplying methods
  247. /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
  248. /// type used.
  249. template <typename LookupKeyT>
  250. std::pair<iterator, bool> insert_as(std::pair<KeyT, ValueT> &&KV,
  251. const LookupKeyT &Val) {
  252. BucketT *TheBucket;
  253. if (LookupBucketFor(Val, TheBucket))
  254. return std::make_pair(makeIterator(TheBucket,
  255. shouldReverseIterate<KeyT>()
  256. ? getBuckets()
  257. : getBucketsEnd(),
  258. *this, true),
  259. false); // Already in map.
  260. // Otherwise, insert the new element.
  261. TheBucket = InsertIntoBucketWithLookup(TheBucket, std::move(KV.first),
  262. std::move(KV.second), Val);
  263. return std::make_pair(makeIterator(TheBucket,
  264. shouldReverseIterate<KeyT>()
  265. ? getBuckets()
  266. : getBucketsEnd(),
  267. *this, true),
  268. true);
  269. }
  270. /// insert - Range insertion of pairs.
  271. template<typename InputIt>
  272. void insert(InputIt I, InputIt E) {
  273. for (; I != E; ++I)
  274. insert(*I);
  275. }
  276. bool erase(const KeyT &Val) {
  277. BucketT *TheBucket;
  278. if (!LookupBucketFor(Val, TheBucket))
  279. return false; // not in map.
  280. TheBucket->getSecond().~ValueT();
  281. TheBucket->getFirst() = getTombstoneKey();
  282. decrementNumEntries();
  283. incrementNumTombstones();
  284. return true;
  285. }
  286. void erase(iterator I) {
  287. BucketT *TheBucket = &*I;
  288. TheBucket->getSecond().~ValueT();
  289. TheBucket->getFirst() = getTombstoneKey();
  290. decrementNumEntries();
  291. incrementNumTombstones();
  292. }
  293. value_type& FindAndConstruct(const KeyT &Key) {
  294. BucketT *TheBucket;
  295. if (LookupBucketFor(Key, TheBucket))
  296. return *TheBucket;
  297. return *InsertIntoBucket(TheBucket, Key);
  298. }
  299. ValueT &operator[](const KeyT &Key) {
  300. return FindAndConstruct(Key).second;
  301. }
  302. value_type& FindAndConstruct(KeyT &&Key) {
  303. BucketT *TheBucket;
  304. if (LookupBucketFor(Key, TheBucket))
  305. return *TheBucket;
  306. return *InsertIntoBucket(TheBucket, std::move(Key));
  307. }
  308. ValueT &operator[](KeyT &&Key) {
  309. return FindAndConstruct(std::move(Key)).second;
  310. }
  311. /// isPointerIntoBucketsArray - Return true if the specified pointer points
  312. /// somewhere into the DenseMap's array of buckets (i.e. either to a key or
  313. /// value in the DenseMap).
  314. bool isPointerIntoBucketsArray(const void *Ptr) const {
  315. return Ptr >= getBuckets() && Ptr < getBucketsEnd();
  316. }
  317. /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
  318. /// array. In conjunction with the previous method, this can be used to
  319. /// determine whether an insertion caused the DenseMap to reallocate.
  320. const void *getPointerIntoBucketsArray() const { return getBuckets(); }
  321. protected:
  322. DenseMapBase() = default;
  323. void destroyAll() {
  324. if (getNumBuckets() == 0) // Nothing to do.
  325. return;
  326. const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
  327. for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
  328. if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey) &&
  329. !KeyInfoT::isEqual(P->getFirst(), TombstoneKey))
  330. P->getSecond().~ValueT();
  331. P->getFirst().~KeyT();
  332. }
  333. }
  334. void initEmpty() {
  335. setNumEntries(0);
  336. setNumTombstones(0);
  337. assert((getNumBuckets() & (getNumBuckets()-1)) == 0 &&
  338. "# initial buckets must be a power of two!");
  339. const KeyT EmptyKey = getEmptyKey();
  340. for (BucketT *B = getBuckets(), *E = getBucketsEnd(); B != E; ++B)
  341. ::new (&B->getFirst()) KeyT(EmptyKey);
  342. }
  343. /// Returns the number of buckets to allocate to ensure that the DenseMap can
  344. /// accommodate \p NumEntries without need to grow().
  345. unsigned getMinBucketToReserveForEntries(unsigned NumEntries) {
  346. // Ensure that "NumEntries * 4 < NumBuckets * 3"
  347. if (NumEntries == 0)
  348. return 0;
  349. // +1 is required because of the strict equality.
  350. // For example if NumEntries is 48, we need to return 401.
  351. return NextPowerOf2(NumEntries * 4 / 3 + 1);
  352. }
  353. void moveFromOldBuckets(BucketT *OldBucketsBegin, BucketT *OldBucketsEnd) {
  354. initEmpty();
  355. // Insert all the old elements.
  356. const KeyT EmptyKey = getEmptyKey();
  357. const KeyT TombstoneKey = getTombstoneKey();
  358. for (BucketT *B = OldBucketsBegin, *E = OldBucketsEnd; B != E; ++B) {
  359. if (!KeyInfoT::isEqual(B->getFirst(), EmptyKey) &&
  360. !KeyInfoT::isEqual(B->getFirst(), TombstoneKey)) {
  361. // Insert the key/value into the new table.
  362. BucketT *DestBucket;
  363. bool FoundVal = LookupBucketFor(B->getFirst(), DestBucket);
  364. (void)FoundVal; // silence warning.
  365. assert(!FoundVal && "Key already in new map?");
  366. DestBucket->getFirst() = std::move(B->getFirst());
  367. ::new (&DestBucket->getSecond()) ValueT(std::move(B->getSecond()));
  368. incrementNumEntries();
  369. // Free the value.
  370. B->getSecond().~ValueT();
  371. }
  372. B->getFirst().~KeyT();
  373. }
  374. }
  375. template <typename OtherBaseT>
  376. void copyFrom(
  377. const DenseMapBase<OtherBaseT, KeyT, ValueT, KeyInfoT, BucketT> &other) {
  378. assert(&other != this);
  379. assert(getNumBuckets() == other.getNumBuckets());
  380. setNumEntries(other.getNumEntries());
  381. setNumTombstones(other.getNumTombstones());
  382. if (std::is_trivially_copyable<KeyT>::value &&
  383. std::is_trivially_copyable<ValueT>::value)
  384. memcpy(reinterpret_cast<void *>(getBuckets()), other.getBuckets(),
  385. getNumBuckets() * sizeof(BucketT));
  386. else
  387. for (size_t i = 0; i < getNumBuckets(); ++i) {
  388. ::new (&getBuckets()[i].getFirst())
  389. KeyT(other.getBuckets()[i].getFirst());
  390. if (!KeyInfoT::isEqual(getBuckets()[i].getFirst(), getEmptyKey()) &&
  391. !KeyInfoT::isEqual(getBuckets()[i].getFirst(), getTombstoneKey()))
  392. ::new (&getBuckets()[i].getSecond())
  393. ValueT(other.getBuckets()[i].getSecond());
  394. }
  395. }
  396. static unsigned getHashValue(const KeyT &Val) {
  397. return KeyInfoT::getHashValue(Val);
  398. }
  399. template<typename LookupKeyT>
  400. static unsigned getHashValue(const LookupKeyT &Val) {
  401. return KeyInfoT::getHashValue(Val);
  402. }
  403. static const KeyT getEmptyKey() {
  404. static_assert(std::is_base_of<DenseMapBase, DerivedT>::value,
  405. "Must pass the derived type to this template!");
  406. return KeyInfoT::getEmptyKey();
  407. }
  408. static const KeyT getTombstoneKey() {
  409. return KeyInfoT::getTombstoneKey();
  410. }
  411. private:
  412. iterator makeIterator(BucketT *P, BucketT *E,
  413. DebugEpochBase &Epoch,
  414. bool NoAdvance=false) {
  415. if (shouldReverseIterate<KeyT>()) {
  416. BucketT *B = P == getBucketsEnd() ? getBuckets() : P + 1;
  417. return iterator(B, E, Epoch, NoAdvance);
  418. }
  419. return iterator(P, E, Epoch, NoAdvance);
  420. }
  421. const_iterator makeConstIterator(const BucketT *P, const BucketT *E,
  422. const DebugEpochBase &Epoch,
  423. const bool NoAdvance=false) const {
  424. if (shouldReverseIterate<KeyT>()) {
  425. const BucketT *B = P == getBucketsEnd() ? getBuckets() : P + 1;
  426. return const_iterator(B, E, Epoch, NoAdvance);
  427. }
  428. return const_iterator(P, E, Epoch, NoAdvance);
  429. }
  430. unsigned getNumEntries() const {
  431. return static_cast<const DerivedT *>(this)->getNumEntries();
  432. }
  433. void setNumEntries(unsigned Num) {
  434. static_cast<DerivedT *>(this)->setNumEntries(Num);
  435. }
  436. void incrementNumEntries() {
  437. setNumEntries(getNumEntries() + 1);
  438. }
  439. void decrementNumEntries() {
  440. setNumEntries(getNumEntries() - 1);
  441. }
  442. unsigned getNumTombstones() const {
  443. return static_cast<const DerivedT *>(this)->getNumTombstones();
  444. }
  445. void setNumTombstones(unsigned Num) {
  446. static_cast<DerivedT *>(this)->setNumTombstones(Num);
  447. }
  448. void incrementNumTombstones() {
  449. setNumTombstones(getNumTombstones() + 1);
  450. }
  451. void decrementNumTombstones() {
  452. setNumTombstones(getNumTombstones() - 1);
  453. }
  454. const BucketT *getBuckets() const {
  455. return static_cast<const DerivedT *>(this)->getBuckets();
  456. }
  457. BucketT *getBuckets() {
  458. return static_cast<DerivedT *>(this)->getBuckets();
  459. }
  460. unsigned getNumBuckets() const {
  461. return static_cast<const DerivedT *>(this)->getNumBuckets();
  462. }
  463. BucketT *getBucketsEnd() {
  464. return getBuckets() + getNumBuckets();
  465. }
  466. const BucketT *getBucketsEnd() const {
  467. return getBuckets() + getNumBuckets();
  468. }
  469. void grow(unsigned AtLeast) {
  470. static_cast<DerivedT *>(this)->grow(AtLeast);
  471. }
  472. void shrink_and_clear() {
  473. static_cast<DerivedT *>(this)->shrink_and_clear();
  474. }
  475. template <typename KeyArg, typename... ValueArgs>
  476. BucketT *InsertIntoBucket(BucketT *TheBucket, KeyArg &&Key,
  477. ValueArgs &&... Values) {
  478. TheBucket = InsertIntoBucketImpl(Key, Key, TheBucket);
  479. TheBucket->getFirst() = std::forward<KeyArg>(Key);
  480. ::new (&TheBucket->getSecond()) ValueT(std::forward<ValueArgs>(Values)...);
  481. return TheBucket;
  482. }
  483. template <typename LookupKeyT>
  484. BucketT *InsertIntoBucketWithLookup(BucketT *TheBucket, KeyT &&Key,
  485. ValueT &&Value, LookupKeyT &Lookup) {
  486. TheBucket = InsertIntoBucketImpl(Key, Lookup, TheBucket);
  487. TheBucket->getFirst() = std::move(Key);
  488. ::new (&TheBucket->getSecond()) ValueT(std::move(Value));
  489. return TheBucket;
  490. }
  491. template <typename LookupKeyT>
  492. BucketT *InsertIntoBucketImpl(const KeyT &Key, const LookupKeyT &Lookup,
  493. BucketT *TheBucket) {
  494. incrementEpoch();
  495. // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
  496. // the buckets are empty (meaning that many are filled with tombstones),
  497. // grow the table.
  498. //
  499. // The later case is tricky. For example, if we had one empty bucket with
  500. // tons of tombstones, failing lookups (e.g. for insertion) would have to
  501. // probe almost the entire table until it found the empty bucket. If the
  502. // table completely filled with tombstones, no lookup would ever succeed,
  503. // causing infinite loops in lookup.
  504. unsigned NewNumEntries = getNumEntries() + 1;
  505. unsigned NumBuckets = getNumBuckets();
  506. if (LLVM_UNLIKELY(NewNumEntries * 4 >= NumBuckets * 3)) {
  507. this->grow(NumBuckets * 2);
  508. LookupBucketFor(Lookup, TheBucket);
  509. NumBuckets = getNumBuckets();
  510. } else if (LLVM_UNLIKELY(NumBuckets-(NewNumEntries+getNumTombstones()) <=
  511. NumBuckets/8)) {
  512. this->grow(NumBuckets);
  513. LookupBucketFor(Lookup, TheBucket);
  514. }
  515. assert(TheBucket);
  516. // Only update the state after we've grown our bucket space appropriately
  517. // so that when growing buckets we have self-consistent entry count.
  518. incrementNumEntries();
  519. // If we are writing over a tombstone, remember this.
  520. const KeyT EmptyKey = getEmptyKey();
  521. if (!KeyInfoT::isEqual(TheBucket->getFirst(), EmptyKey))
  522. decrementNumTombstones();
  523. return TheBucket;
  524. }
  525. /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
  526. /// FoundBucket. If the bucket contains the key and a value, this returns
  527. /// true, otherwise it returns a bucket with an empty marker or tombstone and
  528. /// returns false.
  529. template<typename LookupKeyT>
  530. bool LookupBucketFor(const LookupKeyT &Val,
  531. const BucketT *&FoundBucket) const {
  532. const BucketT *BucketsPtr = getBuckets();
  533. const unsigned NumBuckets = getNumBuckets();
  534. if (NumBuckets == 0) {
  535. FoundBucket = nullptr;
  536. return false;
  537. }
  538. // FoundTombstone - Keep track of whether we find a tombstone while probing.
  539. const BucketT *FoundTombstone = nullptr;
  540. const KeyT EmptyKey = getEmptyKey();
  541. const KeyT TombstoneKey = getTombstoneKey();
  542. assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
  543. !KeyInfoT::isEqual(Val, TombstoneKey) &&
  544. "Empty/Tombstone value shouldn't be inserted into map!");
  545. unsigned BucketNo = getHashValue(Val) & (NumBuckets-1);
  546. unsigned ProbeAmt = 1;
  547. while (true) {
  548. const BucketT *ThisBucket = BucketsPtr + BucketNo;
  549. // Found Val's bucket? If so, return it.
  550. if (LLVM_LIKELY(KeyInfoT::isEqual(Val, ThisBucket->getFirst()))) {
  551. FoundBucket = ThisBucket;
  552. return true;
  553. }
  554. // If we found an empty bucket, the key doesn't exist in the set.
  555. // Insert it and return the default value.
  556. if (LLVM_LIKELY(KeyInfoT::isEqual(ThisBucket->getFirst(), EmptyKey))) {
  557. // If we've already seen a tombstone while probing, fill it in instead
  558. // of the empty bucket we eventually probed to.
  559. FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
  560. return false;
  561. }
  562. // If this is a tombstone, remember it. If Val ends up not in the map, we
  563. // prefer to return it than something that would require more probing.
  564. if (KeyInfoT::isEqual(ThisBucket->getFirst(), TombstoneKey) &&
  565. !FoundTombstone)
  566. FoundTombstone = ThisBucket; // Remember the first tombstone found.
  567. // Otherwise, it's a hash collision or a tombstone, continue quadratic
  568. // probing.
  569. BucketNo += ProbeAmt++;
  570. BucketNo &= (NumBuckets-1);
  571. }
  572. }
  573. template <typename LookupKeyT>
  574. bool LookupBucketFor(const LookupKeyT &Val, BucketT *&FoundBucket) {
  575. const BucketT *ConstFoundBucket;
  576. bool Result = const_cast<const DenseMapBase *>(this)
  577. ->LookupBucketFor(Val, ConstFoundBucket);
  578. FoundBucket = const_cast<BucketT *>(ConstFoundBucket);
  579. return Result;
  580. }
  581. public:
  582. /// Return the approximate size (in bytes) of the actual map.
  583. /// This is just the raw memory used by DenseMap.
  584. /// If entries are pointers to objects, the size of the referenced objects
  585. /// are not included.
  586. size_t getMemorySize() const {
  587. return getNumBuckets() * sizeof(BucketT);
  588. }
  589. };
  590. /// Equality comparison for DenseMap.
  591. ///
  592. /// Iterates over elements of LHS confirming that each (key, value) pair in LHS
  593. /// is also in RHS, and that no additional pairs are in RHS.
  594. /// Equivalent to N calls to RHS.find and N value comparisons. Amortized
  595. /// complexity is linear, worst case is O(N^2) (if every hash collides).
  596. template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT,
  597. typename BucketT>
  598. bool operator==(
  599. const DenseMapBase<DerivedT, KeyT, ValueT, KeyInfoT, BucketT> &LHS,
  600. const DenseMapBase<DerivedT, KeyT, ValueT, KeyInfoT, BucketT> &RHS) {
  601. if (LHS.size() != RHS.size())
  602. return false;
  603. for (auto &KV : LHS) {
  604. auto I = RHS.find(KV.first);
  605. if (I == RHS.end() || I->second != KV.second)
  606. return false;
  607. }
  608. return true;
  609. }
  610. /// Inequality comparison for DenseMap.
  611. ///
  612. /// Equivalent to !(LHS == RHS). See operator== for performance notes.
  613. template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT,
  614. typename BucketT>
  615. bool operator!=(
  616. const DenseMapBase<DerivedT, KeyT, ValueT, KeyInfoT, BucketT> &LHS,
  617. const DenseMapBase<DerivedT, KeyT, ValueT, KeyInfoT, BucketT> &RHS) {
  618. return !(LHS == RHS);
  619. }
  620. template <typename KeyT, typename ValueT,
  621. typename KeyInfoT = DenseMapInfo<KeyT>,
  622. typename BucketT = llvm::detail::DenseMapPair<KeyT, ValueT>>
  623. class DenseMap : public DenseMapBase<DenseMap<KeyT, ValueT, KeyInfoT, BucketT>,
  624. KeyT, ValueT, KeyInfoT, BucketT> {
  625. friend class DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
  626. // Lift some types from the dependent base class into this class for
  627. // simplicity of referring to them.
  628. using BaseT = DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
  629. BucketT *Buckets;
  630. unsigned NumEntries;
  631. unsigned NumTombstones;
  632. unsigned NumBuckets;
  633. public:
  634. /// Create a DenseMap with an optional \p InitialReserve that guarantee that
  635. /// this number of elements can be inserted in the map without grow()
  636. explicit DenseMap(unsigned InitialReserve = 0) { init(InitialReserve); }
  637. DenseMap(const DenseMap &other) : BaseT() {
  638. init(0);
  639. copyFrom(other);
  640. }
  641. DenseMap(DenseMap &&other) : BaseT() {
  642. init(0);
  643. swap(other);
  644. }
  645. template<typename InputIt>
  646. DenseMap(const InputIt &I, const InputIt &E) {
  647. init(std::distance(I, E));
  648. this->insert(I, E);
  649. }
  650. DenseMap(std::initializer_list<typename BaseT::value_type> Vals) {
  651. init(Vals.size());
  652. this->insert(Vals.begin(), Vals.end());
  653. }
  654. ~DenseMap() {
  655. this->destroyAll();
  656. deallocate_buffer(Buckets, sizeof(BucketT) * NumBuckets, alignof(BucketT));
  657. }
  658. void swap(DenseMap& RHS) {
  659. this->incrementEpoch();
  660. RHS.incrementEpoch();
  661. std::swap(Buckets, RHS.Buckets);
  662. std::swap(NumEntries, RHS.NumEntries);
  663. std::swap(NumTombstones, RHS.NumTombstones);
  664. std::swap(NumBuckets, RHS.NumBuckets);
  665. }
  666. DenseMap& operator=(const DenseMap& other) {
  667. if (&other != this)
  668. copyFrom(other);
  669. return *this;
  670. }
  671. DenseMap& operator=(DenseMap &&other) {
  672. this->destroyAll();
  673. deallocate_buffer(Buckets, sizeof(BucketT) * NumBuckets, alignof(BucketT));
  674. init(0);
  675. swap(other);
  676. return *this;
  677. }
  678. void copyFrom(const DenseMap& other) {
  679. this->destroyAll();
  680. deallocate_buffer(Buckets, sizeof(BucketT) * NumBuckets, alignof(BucketT));
  681. if (allocateBuckets(other.NumBuckets)) {
  682. this->BaseT::copyFrom(other);
  683. } else {
  684. NumEntries = 0;
  685. NumTombstones = 0;
  686. }
  687. }
  688. void init(unsigned InitNumEntries) {
  689. auto InitBuckets = BaseT::getMinBucketToReserveForEntries(InitNumEntries);
  690. if (allocateBuckets(InitBuckets)) {
  691. this->BaseT::initEmpty();
  692. } else {
  693. NumEntries = 0;
  694. NumTombstones = 0;
  695. }
  696. }
  697. void grow(unsigned AtLeast) {
  698. unsigned OldNumBuckets = NumBuckets;
  699. BucketT *OldBuckets = Buckets;
  700. allocateBuckets(std::max<unsigned>(64, static_cast<unsigned>(NextPowerOf2(AtLeast-1))));
  701. assert(Buckets);
  702. if (!OldBuckets) {
  703. this->BaseT::initEmpty();
  704. return;
  705. }
  706. this->moveFromOldBuckets(OldBuckets, OldBuckets+OldNumBuckets);
  707. // Free the old table.
  708. deallocate_buffer(OldBuckets, sizeof(BucketT) * OldNumBuckets,
  709. alignof(BucketT));
  710. }
  711. void shrink_and_clear() {
  712. unsigned OldNumBuckets = NumBuckets;
  713. unsigned OldNumEntries = NumEntries;
  714. this->destroyAll();
  715. // Reduce the number of buckets.
  716. unsigned NewNumBuckets = 0;
  717. if (OldNumEntries)
  718. NewNumBuckets = std::max(64, 1 << (Log2_32_Ceil(OldNumEntries) + 1));
  719. if (NewNumBuckets == NumBuckets) {
  720. this->BaseT::initEmpty();
  721. return;
  722. }
  723. deallocate_buffer(Buckets, sizeof(BucketT) * OldNumBuckets,
  724. alignof(BucketT));
  725. init(NewNumBuckets);
  726. }
  727. private:
  728. unsigned getNumEntries() const {
  729. return NumEntries;
  730. }
  731. void setNumEntries(unsigned Num) {
  732. NumEntries = Num;
  733. }
  734. unsigned getNumTombstones() const {
  735. return NumTombstones;
  736. }
  737. void setNumTombstones(unsigned Num) {
  738. NumTombstones = Num;
  739. }
  740. BucketT *getBuckets() const {
  741. return Buckets;
  742. }
  743. unsigned getNumBuckets() const {
  744. return NumBuckets;
  745. }
  746. bool allocateBuckets(unsigned Num) {
  747. NumBuckets = Num;
  748. if (NumBuckets == 0) {
  749. Buckets = nullptr;
  750. return false;
  751. }
  752. Buckets = static_cast<BucketT *>(
  753. allocate_buffer(sizeof(BucketT) * NumBuckets, alignof(BucketT)));
  754. return true;
  755. }
  756. };
  757. template <typename KeyT, typename ValueT, unsigned InlineBuckets = 4,
  758. typename KeyInfoT = DenseMapInfo<KeyT>,
  759. typename BucketT = llvm::detail::DenseMapPair<KeyT, ValueT>>
  760. class SmallDenseMap
  761. : public DenseMapBase<
  762. SmallDenseMap<KeyT, ValueT, InlineBuckets, KeyInfoT, BucketT>, KeyT,
  763. ValueT, KeyInfoT, BucketT> {
  764. friend class DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
  765. // Lift some types from the dependent base class into this class for
  766. // simplicity of referring to them.
  767. using BaseT = DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
  768. static_assert(isPowerOf2_64(InlineBuckets),
  769. "InlineBuckets must be a power of 2.");
  770. unsigned Small : 1;
  771. unsigned NumEntries : 31;
  772. unsigned NumTombstones;
  773. struct LargeRep {
  774. BucketT *Buckets;
  775. unsigned NumBuckets;
  776. };
  777. /// A "union" of an inline bucket array and the struct representing
  778. /// a large bucket. This union will be discriminated by the 'Small' bit.
  779. AlignedCharArrayUnion<BucketT[InlineBuckets], LargeRep> storage;
  780. public:
  781. explicit SmallDenseMap(unsigned NumInitBuckets = 0) {
  782. init(NumInitBuckets);
  783. }
  784. SmallDenseMap(const SmallDenseMap &other) : BaseT() {
  785. init(0);
  786. copyFrom(other);
  787. }
  788. SmallDenseMap(SmallDenseMap &&other) : BaseT() {
  789. init(0);
  790. swap(other);
  791. }
  792. template<typename InputIt>
  793. SmallDenseMap(const InputIt &I, const InputIt &E) {
  794. init(NextPowerOf2(std::distance(I, E)));
  795. this->insert(I, E);
  796. }
  797. ~SmallDenseMap() {
  798. this->destroyAll();
  799. deallocateBuckets();
  800. }
  801. void swap(SmallDenseMap& RHS) {
  802. unsigned TmpNumEntries = RHS.NumEntries;
  803. RHS.NumEntries = NumEntries;
  804. NumEntries = TmpNumEntries;
  805. std::swap(NumTombstones, RHS.NumTombstones);
  806. const KeyT EmptyKey = this->getEmptyKey();
  807. const KeyT TombstoneKey = this->getTombstoneKey();
  808. if (Small && RHS.Small) {
  809. // If we're swapping inline bucket arrays, we have to cope with some of
  810. // the tricky bits of DenseMap's storage system: the buckets are not
  811. // fully initialized. Thus we swap every key, but we may have
  812. // a one-directional move of the value.
  813. for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
  814. BucketT *LHSB = &getInlineBuckets()[i],
  815. *RHSB = &RHS.getInlineBuckets()[i];
  816. bool hasLHSValue = (!KeyInfoT::isEqual(LHSB->getFirst(), EmptyKey) &&
  817. !KeyInfoT::isEqual(LHSB->getFirst(), TombstoneKey));
  818. bool hasRHSValue = (!KeyInfoT::isEqual(RHSB->getFirst(), EmptyKey) &&
  819. !KeyInfoT::isEqual(RHSB->getFirst(), TombstoneKey));
  820. if (hasLHSValue && hasRHSValue) {
  821. // Swap together if we can...
  822. std::swap(*LHSB, *RHSB);
  823. continue;
  824. }
  825. // Swap separately and handle any asymmetry.
  826. std::swap(LHSB->getFirst(), RHSB->getFirst());
  827. if (hasLHSValue) {
  828. ::new (&RHSB->getSecond()) ValueT(std::move(LHSB->getSecond()));
  829. LHSB->getSecond().~ValueT();
  830. } else if (hasRHSValue) {
  831. ::new (&LHSB->getSecond()) ValueT(std::move(RHSB->getSecond()));
  832. RHSB->getSecond().~ValueT();
  833. }
  834. }
  835. return;
  836. }
  837. if (!Small && !RHS.Small) {
  838. std::swap(getLargeRep()->Buckets, RHS.getLargeRep()->Buckets);
  839. std::swap(getLargeRep()->NumBuckets, RHS.getLargeRep()->NumBuckets);
  840. return;
  841. }
  842. SmallDenseMap &SmallSide = Small ? *this : RHS;
  843. SmallDenseMap &LargeSide = Small ? RHS : *this;
  844. // First stash the large side's rep and move the small side across.
  845. LargeRep TmpRep = std::move(*LargeSide.getLargeRep());
  846. LargeSide.getLargeRep()->~LargeRep();
  847. LargeSide.Small = true;
  848. // This is similar to the standard move-from-old-buckets, but the bucket
  849. // count hasn't actually rotated in this case. So we have to carefully
  850. // move construct the keys and values into their new locations, but there
  851. // is no need to re-hash things.
  852. for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
  853. BucketT *NewB = &LargeSide.getInlineBuckets()[i],
  854. *OldB = &SmallSide.getInlineBuckets()[i];
  855. ::new (&NewB->getFirst()) KeyT(std::move(OldB->getFirst()));
  856. OldB->getFirst().~KeyT();
  857. if (!KeyInfoT::isEqual(NewB->getFirst(), EmptyKey) &&
  858. !KeyInfoT::isEqual(NewB->getFirst(), TombstoneKey)) {
  859. ::new (&NewB->getSecond()) ValueT(std::move(OldB->getSecond()));
  860. OldB->getSecond().~ValueT();
  861. }
  862. }
  863. // The hard part of moving the small buckets across is done, just move
  864. // the TmpRep into its new home.
  865. SmallSide.Small = false;
  866. new (SmallSide.getLargeRep()) LargeRep(std::move(TmpRep));
  867. }
  868. SmallDenseMap& operator=(const SmallDenseMap& other) {
  869. if (&other != this)
  870. copyFrom(other);
  871. return *this;
  872. }
  873. SmallDenseMap& operator=(SmallDenseMap &&other) {
  874. this->destroyAll();
  875. deallocateBuckets();
  876. init(0);
  877. swap(other);
  878. return *this;
  879. }
  880. void copyFrom(const SmallDenseMap& other) {
  881. this->destroyAll();
  882. deallocateBuckets();
  883. Small = true;
  884. if (other.getNumBuckets() > InlineBuckets) {
  885. Small = false;
  886. new (getLargeRep()) LargeRep(allocateBuckets(other.getNumBuckets()));
  887. }
  888. this->BaseT::copyFrom(other);
  889. }
  890. void init(unsigned InitBuckets) {
  891. Small = true;
  892. if (InitBuckets > InlineBuckets) {
  893. Small = false;
  894. new (getLargeRep()) LargeRep(allocateBuckets(InitBuckets));
  895. }
  896. this->BaseT::initEmpty();
  897. }
  898. void grow(unsigned AtLeast) {
  899. if (AtLeast > InlineBuckets)
  900. AtLeast = std::max<unsigned>(64, NextPowerOf2(AtLeast-1));
  901. if (Small) {
  902. // First move the inline buckets into a temporary storage.
  903. AlignedCharArrayUnion<BucketT[InlineBuckets]> TmpStorage;
  904. BucketT *TmpBegin = reinterpret_cast<BucketT *>(&TmpStorage);
  905. BucketT *TmpEnd = TmpBegin;
  906. // Loop over the buckets, moving non-empty, non-tombstones into the
  907. // temporary storage. Have the loop move the TmpEnd forward as it goes.
  908. const KeyT EmptyKey = this->getEmptyKey();
  909. const KeyT TombstoneKey = this->getTombstoneKey();
  910. for (BucketT *P = getBuckets(), *E = P + InlineBuckets; P != E; ++P) {
  911. if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey) &&
  912. !KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) {
  913. assert(size_t(TmpEnd - TmpBegin) < InlineBuckets &&
  914. "Too many inline buckets!");
  915. ::new (&TmpEnd->getFirst()) KeyT(std::move(P->getFirst()));
  916. ::new (&TmpEnd->getSecond()) ValueT(std::move(P->getSecond()));
  917. ++TmpEnd;
  918. P->getSecond().~ValueT();
  919. }
  920. P->getFirst().~KeyT();
  921. }
  922. // AtLeast == InlineBuckets can happen if there are many tombstones,
  923. // and grow() is used to remove them. Usually we always switch to the
  924. // large rep here.
  925. if (AtLeast > InlineBuckets) {
  926. Small = false;
  927. new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
  928. }
  929. this->moveFromOldBuckets(TmpBegin, TmpEnd);
  930. return;
  931. }
  932. LargeRep OldRep = std::move(*getLargeRep());
  933. getLargeRep()->~LargeRep();
  934. if (AtLeast <= InlineBuckets) {
  935. Small = true;
  936. } else {
  937. new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
  938. }
  939. this->moveFromOldBuckets(OldRep.Buckets, OldRep.Buckets+OldRep.NumBuckets);
  940. // Free the old table.
  941. deallocate_buffer(OldRep.Buckets, sizeof(BucketT) * OldRep.NumBuckets,
  942. alignof(BucketT));
  943. }
  944. void shrink_and_clear() {
  945. unsigned OldSize = this->size();
  946. this->destroyAll();
  947. // Reduce the number of buckets.
  948. unsigned NewNumBuckets = 0;
  949. if (OldSize) {
  950. NewNumBuckets = 1 << (Log2_32_Ceil(OldSize) + 1);
  951. if (NewNumBuckets > InlineBuckets && NewNumBuckets < 64u)
  952. NewNumBuckets = 64;
  953. }
  954. if ((Small && NewNumBuckets <= InlineBuckets) ||
  955. (!Small && NewNumBuckets == getLargeRep()->NumBuckets)) {
  956. this->BaseT::initEmpty();
  957. return;
  958. }
  959. deallocateBuckets();
  960. init(NewNumBuckets);
  961. }
  962. private:
  963. unsigned getNumEntries() const {
  964. return NumEntries;
  965. }
  966. void setNumEntries(unsigned Num) {
  967. // NumEntries is hardcoded to be 31 bits wide.
  968. assert(Num < (1U << 31) && "Cannot support more than 1<<31 entries");
  969. NumEntries = Num;
  970. }
  971. unsigned getNumTombstones() const {
  972. return NumTombstones;
  973. }
  974. void setNumTombstones(unsigned Num) {
  975. NumTombstones = Num;
  976. }
  977. const BucketT *getInlineBuckets() const {
  978. assert(Small);
  979. // Note that this cast does not violate aliasing rules as we assert that
  980. // the memory's dynamic type is the small, inline bucket buffer, and the
  981. // 'storage' is a POD containing a char buffer.
  982. return reinterpret_cast<const BucketT *>(&storage);
  983. }
  984. BucketT *getInlineBuckets() {
  985. return const_cast<BucketT *>(
  986. const_cast<const SmallDenseMap *>(this)->getInlineBuckets());
  987. }
  988. const LargeRep *getLargeRep() const {
  989. assert(!Small);
  990. // Note, same rule about aliasing as with getInlineBuckets.
  991. return reinterpret_cast<const LargeRep *>(&storage);
  992. }
  993. LargeRep *getLargeRep() {
  994. return const_cast<LargeRep *>(
  995. const_cast<const SmallDenseMap *>(this)->getLargeRep());
  996. }
  997. const BucketT *getBuckets() const {
  998. return Small ? getInlineBuckets() : getLargeRep()->Buckets;
  999. }
  1000. BucketT *getBuckets() {
  1001. return const_cast<BucketT *>(
  1002. const_cast<const SmallDenseMap *>(this)->getBuckets());
  1003. }
  1004. unsigned getNumBuckets() const {
  1005. return Small ? InlineBuckets : getLargeRep()->NumBuckets;
  1006. }
  1007. void deallocateBuckets() {
  1008. if (Small)
  1009. return;
  1010. deallocate_buffer(getLargeRep()->Buckets,
  1011. sizeof(BucketT) * getLargeRep()->NumBuckets,
  1012. alignof(BucketT));
  1013. getLargeRep()->~LargeRep();
  1014. }
  1015. LargeRep allocateBuckets(unsigned Num) {
  1016. assert(Num > InlineBuckets && "Must allocate more buckets than are inline");
  1017. LargeRep Rep = {static_cast<BucketT *>(allocate_buffer(
  1018. sizeof(BucketT) * Num, alignof(BucketT))),
  1019. Num};
  1020. return Rep;
  1021. }
  1022. };
  1023. template <typename KeyT, typename ValueT, typename KeyInfoT, typename Bucket,
  1024. bool IsConst>
  1025. class DenseMapIterator : DebugEpochBase::HandleBase {
  1026. friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, true>;
  1027. friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, false>;
  1028. public:
  1029. using difference_type = ptrdiff_t;
  1030. using value_type =
  1031. typename std::conditional<IsConst, const Bucket, Bucket>::type;
  1032. using pointer = value_type *;
  1033. using reference = value_type &;
  1034. using iterator_category = std::forward_iterator_tag;
  1035. private:
  1036. pointer Ptr = nullptr;
  1037. pointer End = nullptr;
  1038. public:
  1039. DenseMapIterator() = default;
  1040. DenseMapIterator(pointer Pos, pointer E, const DebugEpochBase &Epoch,
  1041. bool NoAdvance = false)
  1042. : DebugEpochBase::HandleBase(&Epoch), Ptr(Pos), End(E) {
  1043. assert(isHandleInSync() && "invalid construction!");
  1044. if (NoAdvance) return;
  1045. if (shouldReverseIterate<KeyT>()) {
  1046. RetreatPastEmptyBuckets();
  1047. return;
  1048. }
  1049. AdvancePastEmptyBuckets();
  1050. }
  1051. // Converting ctor from non-const iterators to const iterators. SFINAE'd out
  1052. // for const iterator destinations so it doesn't end up as a user defined copy
  1053. // constructor.
  1054. template <bool IsConstSrc,
  1055. typename = std::enable_if_t<!IsConstSrc && IsConst>>
  1056. DenseMapIterator(
  1057. const DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, IsConstSrc> &I)
  1058. : DebugEpochBase::HandleBase(I), Ptr(I.Ptr), End(I.End) {}
  1059. reference operator*() const {
  1060. assert(isHandleInSync() && "invalid iterator access!");
  1061. assert(Ptr != End && "dereferencing end() iterator");
  1062. if (shouldReverseIterate<KeyT>())
  1063. return Ptr[-1];
  1064. return *Ptr;
  1065. }
  1066. pointer operator->() const {
  1067. assert(isHandleInSync() && "invalid iterator access!");
  1068. assert(Ptr != End && "dereferencing end() iterator");
  1069. if (shouldReverseIterate<KeyT>())
  1070. return &(Ptr[-1]);
  1071. return Ptr;
  1072. }
  1073. friend bool operator==(const DenseMapIterator &LHS,
  1074. const DenseMapIterator &RHS) {
  1075. assert((!LHS.Ptr || LHS.isHandleInSync()) && "handle not in sync!");
  1076. assert((!RHS.Ptr || RHS.isHandleInSync()) && "handle not in sync!");
  1077. assert(LHS.getEpochAddress() == RHS.getEpochAddress() &&
  1078. "comparing incomparable iterators!");
  1079. return LHS.Ptr == RHS.Ptr;
  1080. }
  1081. friend bool operator!=(const DenseMapIterator &LHS,
  1082. const DenseMapIterator &RHS) {
  1083. return !(LHS == RHS);
  1084. }
  1085. inline DenseMapIterator& operator++() { // Preincrement
  1086. assert(isHandleInSync() && "invalid iterator access!");
  1087. assert(Ptr != End && "incrementing end() iterator");
  1088. if (shouldReverseIterate<KeyT>()) {
  1089. --Ptr;
  1090. RetreatPastEmptyBuckets();
  1091. return *this;
  1092. }
  1093. ++Ptr;
  1094. AdvancePastEmptyBuckets();
  1095. return *this;
  1096. }
  1097. DenseMapIterator operator++(int) { // Postincrement
  1098. assert(isHandleInSync() && "invalid iterator access!");
  1099. DenseMapIterator tmp = *this; ++*this; return tmp;
  1100. }
  1101. private:
  1102. void AdvancePastEmptyBuckets() {
  1103. assert(Ptr <= End);
  1104. const KeyT Empty = KeyInfoT::getEmptyKey();
  1105. const KeyT Tombstone = KeyInfoT::getTombstoneKey();
  1106. while (Ptr != End && (KeyInfoT::isEqual(Ptr->getFirst(), Empty) ||
  1107. KeyInfoT::isEqual(Ptr->getFirst(), Tombstone)))
  1108. ++Ptr;
  1109. }
  1110. void RetreatPastEmptyBuckets() {
  1111. assert(Ptr >= End);
  1112. const KeyT Empty = KeyInfoT::getEmptyKey();
  1113. const KeyT Tombstone = KeyInfoT::getTombstoneKey();
  1114. while (Ptr != End && (KeyInfoT::isEqual(Ptr[-1].getFirst(), Empty) ||
  1115. KeyInfoT::isEqual(Ptr[-1].getFirst(), Tombstone)))
  1116. --Ptr;
  1117. }
  1118. };
  1119. template <typename KeyT, typename ValueT, typename KeyInfoT>
  1120. inline size_t capacity_in_bytes(const DenseMap<KeyT, ValueT, KeyInfoT> &X) {
  1121. return X.getMemorySize();
  1122. }
  1123. } // end namespace llvm
  1124. #endif // LLVM_ADT_DENSEMAP_H
  1125. #ifdef __GNUC__
  1126. #pragma GCC diagnostic pop
  1127. #endif