DenseMap.h 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  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. // HLSL Change Starts - reorder statement to clean up properly on OOM
  588. if (Num == 0) {
  589. NumBuckets = 0;
  590. Buckets = nullptr;
  591. return false;
  592. }
  593. Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) * Num));
  594. NumBuckets = Num;
  595. // HLSL Change Ends - reorder statement to clean up properly on OOM
  596. return true;
  597. }
  598. };
  599. template <typename KeyT, typename ValueT, unsigned InlineBuckets = 4,
  600. typename KeyInfoT = DenseMapInfo<KeyT>,
  601. typename BucketT = detail::DenseMapPair<KeyT, ValueT>>
  602. class SmallDenseMap
  603. : public DenseMapBase<
  604. SmallDenseMap<KeyT, ValueT, InlineBuckets, KeyInfoT, BucketT>, KeyT,
  605. ValueT, KeyInfoT, BucketT> {
  606. // Lift some types from the dependent base class into this class for
  607. // simplicity of referring to them.
  608. typedef DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT, BucketT> BaseT;
  609. friend class DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
  610. unsigned Small : 1;
  611. unsigned NumEntries : 31;
  612. unsigned NumTombstones;
  613. struct LargeRep {
  614. BucketT *Buckets;
  615. unsigned NumBuckets;
  616. };
  617. /// A "union" of an inline bucket array and the struct representing
  618. /// a large bucket. This union will be discriminated by the 'Small' bit.
  619. AlignedCharArrayUnion<BucketT[InlineBuckets], LargeRep> storage;
  620. public:
  621. explicit SmallDenseMap(unsigned NumInitBuckets = 0) {
  622. init(NumInitBuckets);
  623. }
  624. SmallDenseMap(const SmallDenseMap &other) : BaseT() {
  625. init(0);
  626. copyFrom(other);
  627. }
  628. SmallDenseMap(SmallDenseMap &&other) : BaseT() {
  629. init(0);
  630. swap(other);
  631. }
  632. template<typename InputIt>
  633. SmallDenseMap(const InputIt &I, const InputIt &E) {
  634. init(NextPowerOf2(std::distance(I, E)));
  635. this->insert(I, E);
  636. }
  637. ~SmallDenseMap() {
  638. this->destroyAll();
  639. deallocateBuckets();
  640. }
  641. void swap(SmallDenseMap& RHS) {
  642. unsigned TmpNumEntries = RHS.NumEntries;
  643. RHS.NumEntries = NumEntries;
  644. NumEntries = TmpNumEntries;
  645. std::swap(NumTombstones, RHS.NumTombstones);
  646. const KeyT EmptyKey = this->getEmptyKey();
  647. const KeyT TombstoneKey = this->getTombstoneKey();
  648. if (Small && RHS.Small) {
  649. // If we're swapping inline bucket arrays, we have to cope with some of
  650. // the tricky bits of DenseMap's storage system: the buckets are not
  651. // fully initialized. Thus we swap every key, but we may have
  652. // a one-directional move of the value.
  653. for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
  654. BucketT *LHSB = &getInlineBuckets()[i],
  655. *RHSB = &RHS.getInlineBuckets()[i];
  656. bool hasLHSValue = (!KeyInfoT::isEqual(LHSB->getFirst(), EmptyKey) &&
  657. !KeyInfoT::isEqual(LHSB->getFirst(), TombstoneKey));
  658. bool hasRHSValue = (!KeyInfoT::isEqual(RHSB->getFirst(), EmptyKey) &&
  659. !KeyInfoT::isEqual(RHSB->getFirst(), TombstoneKey));
  660. if (hasLHSValue && hasRHSValue) {
  661. // Swap together if we can...
  662. std::swap(*LHSB, *RHSB);
  663. continue;
  664. }
  665. // Swap separately and handle any assymetry.
  666. std::swap(LHSB->getFirst(), RHSB->getFirst());
  667. if (hasLHSValue) {
  668. new (&RHSB->getSecond()) ValueT(std::move(LHSB->getSecond()));
  669. LHSB->getSecond().~ValueT();
  670. } else if (hasRHSValue) {
  671. new (&LHSB->getSecond()) ValueT(std::move(RHSB->getSecond()));
  672. RHSB->getSecond().~ValueT();
  673. }
  674. }
  675. return;
  676. }
  677. if (!Small && !RHS.Small) {
  678. std::swap(getLargeRep()->Buckets, RHS.getLargeRep()->Buckets);
  679. std::swap(getLargeRep()->NumBuckets, RHS.getLargeRep()->NumBuckets);
  680. return;
  681. }
  682. SmallDenseMap &SmallSide = Small ? *this : RHS;
  683. SmallDenseMap &LargeSide = Small ? RHS : *this;
  684. // First stash the large side's rep and move the small side across.
  685. LargeRep TmpRep = std::move(*LargeSide.getLargeRep());
  686. LargeSide.getLargeRep()->~LargeRep();
  687. LargeSide.Small = true;
  688. // This is similar to the standard move-from-old-buckets, but the bucket
  689. // count hasn't actually rotated in this case. So we have to carefully
  690. // move construct the keys and values into their new locations, but there
  691. // is no need to re-hash things.
  692. for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
  693. BucketT *NewB = &LargeSide.getInlineBuckets()[i],
  694. *OldB = &SmallSide.getInlineBuckets()[i];
  695. new (&NewB->getFirst()) KeyT(std::move(OldB->getFirst()));
  696. OldB->getFirst().~KeyT();
  697. if (!KeyInfoT::isEqual(NewB->getFirst(), EmptyKey) &&
  698. !KeyInfoT::isEqual(NewB->getFirst(), TombstoneKey)) {
  699. new (&NewB->getSecond()) ValueT(std::move(OldB->getSecond()));
  700. OldB->getSecond().~ValueT();
  701. }
  702. }
  703. // The hard part of moving the small buckets across is done, just move
  704. // the TmpRep into its new home.
  705. SmallSide.Small = false;
  706. new (SmallSide.getLargeRep()) LargeRep(std::move(TmpRep));
  707. }
  708. SmallDenseMap& operator=(const SmallDenseMap& other) {
  709. if (&other != this)
  710. copyFrom(other);
  711. return *this;
  712. }
  713. SmallDenseMap& operator=(SmallDenseMap &&other) {
  714. this->destroyAll();
  715. deallocateBuckets();
  716. init(0);
  717. swap(other);
  718. return *this;
  719. }
  720. void copyFrom(const SmallDenseMap& other) {
  721. this->destroyAll();
  722. deallocateBuckets();
  723. Small = true;
  724. if (other.getNumBuckets() > InlineBuckets) {
  725. Small = false;
  726. new (getLargeRep()) LargeRep(allocateBuckets(other.getNumBuckets()));
  727. }
  728. this->BaseT::copyFrom(other);
  729. }
  730. void init(unsigned InitBuckets) {
  731. Small = true;
  732. if (InitBuckets > InlineBuckets) {
  733. Small = false;
  734. new (getLargeRep()) LargeRep(allocateBuckets(InitBuckets));
  735. }
  736. this->BaseT::initEmpty();
  737. }
  738. void grow(unsigned AtLeast) {
  739. if (AtLeast >= InlineBuckets)
  740. AtLeast = std::max<unsigned>(64, NextPowerOf2(AtLeast-1));
  741. if (Small) {
  742. if (AtLeast < InlineBuckets)
  743. return; // Nothing to do.
  744. // First move the inline buckets into a temporary storage.
  745. AlignedCharArrayUnion<BucketT[InlineBuckets]> TmpStorage;
  746. BucketT *TmpBegin = reinterpret_cast<BucketT *>(TmpStorage.buffer);
  747. BucketT *TmpEnd = TmpBegin;
  748. // Loop over the buckets, moving non-empty, non-tombstones into the
  749. // temporary storage. Have the loop move the TmpEnd forward as it goes.
  750. const KeyT EmptyKey = this->getEmptyKey();
  751. const KeyT TombstoneKey = this->getTombstoneKey();
  752. LargeRep LR(allocateBuckets(AtLeast)); // HLSL Change - used to be at 'Now make', but let's fail alloc before invoking .dtors
  753. for (BucketT *P = getBuckets(), *E = P + InlineBuckets; P != E; ++P) {
  754. if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey) &&
  755. !KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) {
  756. assert(size_t(TmpEnd - TmpBegin) < InlineBuckets &&
  757. "Too many inline buckets!");
  758. new (&TmpEnd->getFirst()) KeyT(std::move(P->getFirst()));
  759. new (&TmpEnd->getSecond()) ValueT(std::move(P->getSecond()));
  760. ++TmpEnd;
  761. P->getSecond().~ValueT();
  762. }
  763. P->getFirst().~KeyT();
  764. }
  765. // Now make this map use the large rep, and move all the entries back
  766. // into it.
  767. *getLargeRepForTransition() = LR; // HLSL Change - assign allocated & init'ed block instead
  768. Small = false; // HLSL Change - used to be prior to allocation
  769. this->moveFromOldBuckets(TmpBegin, TmpEnd);
  770. return;
  771. }
  772. LargeRep OldRep = std::move(*getLargeRep());
  773. getLargeRep()->~LargeRep();
  774. if (AtLeast <= InlineBuckets) {
  775. Small = true;
  776. } else {
  777. new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
  778. }
  779. this->moveFromOldBuckets(OldRep.Buckets, OldRep.Buckets+OldRep.NumBuckets);
  780. // Free the old table.
  781. operator delete(OldRep.Buckets);
  782. }
  783. void shrink_and_clear() {
  784. unsigned OldSize = this->size();
  785. this->destroyAll();
  786. // Reduce the number of buckets.
  787. unsigned NewNumBuckets = 0;
  788. if (OldSize) {
  789. NewNumBuckets = 1 << (Log2_32_Ceil(OldSize) + 1);
  790. if (NewNumBuckets > InlineBuckets && NewNumBuckets < 64u)
  791. NewNumBuckets = 64;
  792. }
  793. if ((Small && NewNumBuckets <= InlineBuckets) ||
  794. (!Small && NewNumBuckets == getLargeRep()->NumBuckets)) {
  795. this->BaseT::initEmpty();
  796. return;
  797. }
  798. deallocateBuckets();
  799. init(NewNumBuckets);
  800. }
  801. private:
  802. unsigned getNumEntries() const {
  803. return NumEntries;
  804. }
  805. void setNumEntries(unsigned Num) {
  806. assert(Num < INT_MAX && "Cannot support more than INT_MAX entries");
  807. NumEntries = Num;
  808. }
  809. unsigned getNumTombstones() const {
  810. return NumTombstones;
  811. }
  812. void setNumTombstones(unsigned Num) {
  813. NumTombstones = Num;
  814. }
  815. const BucketT *getInlineBuckets() const {
  816. assert(Small);
  817. // Note that this cast does not violate aliasing rules as we assert that
  818. // the memory's dynamic type is the small, inline bucket buffer, and the
  819. // 'storage.buffer' static type is 'char *'.
  820. return reinterpret_cast<const BucketT *>(storage.buffer);
  821. }
  822. BucketT *getInlineBuckets() {
  823. return const_cast<BucketT *>(
  824. const_cast<const SmallDenseMap *>(this)->getInlineBuckets());
  825. }
  826. const LargeRep *getLargeRep() const {
  827. assert(!Small);
  828. // Note, same rule about aliasing as with getInlineBuckets.
  829. return reinterpret_cast<const LargeRep *>(storage.buffer);
  830. }
  831. LargeRep *getLargeRep() {
  832. return const_cast<LargeRep *>(
  833. const_cast<const SmallDenseMap *>(this)->getLargeRep());
  834. }
  835. // HLSL Change Starts - avoid Small check, as we are in the process of transitioning
  836. const LargeRep *getLargeRepForTransition() const {
  837. // Note, same rule about aliasing as with getInlineBuckets.
  838. return reinterpret_cast<const LargeRep *>(storage.buffer);
  839. }
  840. LargeRep *getLargeRepForTransition() {
  841. return const_cast<LargeRep *>(
  842. const_cast<const SmallDenseMap *>(this)->getLargeRepForTransition());
  843. }
  844. // HLSL Change Ends
  845. const BucketT *getBuckets() const {
  846. return Small ? getInlineBuckets() : getLargeRep()->Buckets;
  847. }
  848. BucketT *getBuckets() {
  849. return const_cast<BucketT *>(
  850. const_cast<const SmallDenseMap *>(this)->getBuckets());
  851. }
  852. unsigned getNumBuckets() const {
  853. return Small ? InlineBuckets : getLargeRep()->NumBuckets;
  854. }
  855. void deallocateBuckets() {
  856. if (Small)
  857. return;
  858. operator delete(getLargeRep()->Buckets);
  859. getLargeRep()->~LargeRep();
  860. }
  861. LargeRep allocateBuckets(unsigned Num) {
  862. assert(Num > InlineBuckets && "Must allocate more buckets than are inline");
  863. LargeRep Rep = {
  864. static_cast<BucketT*>(operator new(sizeof(BucketT) * Num)), Num
  865. };
  866. return Rep;
  867. }
  868. };
  869. template <typename KeyT, typename ValueT, typename KeyInfoT, typename Bucket,
  870. bool IsConst>
  871. class DenseMapIterator : DebugEpochBase::HandleBase {
  872. typedef DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, true> ConstIterator;
  873. friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, true>;
  874. friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, false>;
  875. public:
  876. typedef ptrdiff_t difference_type;
  877. typedef typename std::conditional<IsConst, const Bucket, Bucket>::type
  878. value_type;
  879. typedef value_type *pointer;
  880. typedef value_type &reference;
  881. typedef std::forward_iterator_tag iterator_category;
  882. private:
  883. pointer Ptr, End;
  884. public:
  885. DenseMapIterator() : Ptr(nullptr), End(nullptr) {}
  886. DenseMapIterator(pointer Pos, pointer E, const DebugEpochBase &Epoch,
  887. bool NoAdvance = false)
  888. : DebugEpochBase::HandleBase(&Epoch), Ptr(Pos), End(E) {
  889. assert(isHandleInSync() && "invalid construction!");
  890. if (!NoAdvance) AdvancePastEmptyBuckets();
  891. }
  892. // Converting ctor from non-const iterators to const iterators. SFINAE'd out
  893. // for const iterator destinations so it doesn't end up as a user defined copy
  894. // constructor.
  895. template <bool IsConstSrc,
  896. typename = typename std::enable_if<!IsConstSrc && IsConst>::type>
  897. DenseMapIterator(
  898. const DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, IsConstSrc> &I)
  899. : DebugEpochBase::HandleBase(I), Ptr(I.Ptr), End(I.End) {}
  900. reference operator*() const {
  901. assert(isHandleInSync() && "invalid iterator access!");
  902. return *Ptr;
  903. }
  904. pointer operator->() const {
  905. assert(isHandleInSync() && "invalid iterator access!");
  906. return Ptr;
  907. }
  908. bool operator==(const ConstIterator &RHS) const {
  909. assert((!Ptr || isHandleInSync()) && "handle not in sync!");
  910. assert((!RHS.Ptr || RHS.isHandleInSync()) && "handle not in sync!");
  911. assert(getEpochAddress() == RHS.getEpochAddress() &&
  912. "comparing incomparable iterators!");
  913. return Ptr == RHS.Ptr;
  914. }
  915. bool operator!=(const ConstIterator &RHS) const {
  916. assert((!Ptr || isHandleInSync()) && "handle not in sync!");
  917. assert((!RHS.Ptr || RHS.isHandleInSync()) && "handle not in sync!");
  918. assert(getEpochAddress() == RHS.getEpochAddress() &&
  919. "comparing incomparable iterators!");
  920. return Ptr != RHS.Ptr;
  921. }
  922. inline DenseMapIterator& operator++() { // Preincrement
  923. assert(isHandleInSync() && "invalid iterator access!");
  924. ++Ptr;
  925. AdvancePastEmptyBuckets();
  926. return *this;
  927. }
  928. DenseMapIterator operator++(int) { // Postincrement
  929. assert(isHandleInSync() && "invalid iterator access!");
  930. DenseMapIterator tmp = *this; ++*this; return tmp;
  931. }
  932. private:
  933. void AdvancePastEmptyBuckets() {
  934. const KeyT Empty = KeyInfoT::getEmptyKey();
  935. const KeyT Tombstone = KeyInfoT::getTombstoneKey();
  936. while (Ptr != End && (KeyInfoT::isEqual(Ptr->getFirst(), Empty) ||
  937. KeyInfoT::isEqual(Ptr->getFirst(), Tombstone)))
  938. ++Ptr;
  939. }
  940. };
  941. template<typename KeyT, typename ValueT, typename KeyInfoT>
  942. static inline size_t
  943. capacity_in_bytes(const DenseMap<KeyT, ValueT, KeyInfoT> &X) {
  944. return X.getMemorySize();
  945. }
  946. } // end namespace llvm
  947. #endif