DenseMap.h 34 KB

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