IntervalMap.h 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/ADT/IntervalMap.h - A sorted interval map -----------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. ///
  14. /// \file
  15. /// This file implements a coalescing interval map for small objects.
  16. ///
  17. /// KeyT objects are mapped to ValT objects. Intervals of keys that map to the
  18. /// same value are represented in a compressed form.
  19. ///
  20. /// Iterators provide ordered access to the compressed intervals rather than the
  21. /// individual keys, and insert and erase operations use key intervals as well.
  22. ///
  23. /// Like SmallVector, IntervalMap will store the first N intervals in the map
  24. /// object itself without any allocations. When space is exhausted it switches
  25. /// to a B+-tree representation with very small overhead for small key and
  26. /// value objects.
  27. ///
  28. /// A Traits class specifies how keys are compared. It also allows IntervalMap
  29. /// to work with both closed and half-open intervals.
  30. ///
  31. /// Keys and values are not stored next to each other in a std::pair, so we
  32. /// don't provide such a value_type. Dereferencing iterators only returns the
  33. /// mapped value. The interval bounds are accessible through the start() and
  34. /// stop() iterator methods.
  35. ///
  36. /// IntervalMap is optimized for small key and value objects, 4 or 8 bytes
  37. /// each is the optimal size. For large objects use std::map instead.
  38. //
  39. //===----------------------------------------------------------------------===//
  40. //
  41. // Synopsis:
  42. //
  43. // template <typename KeyT, typename ValT, unsigned N, typename Traits>
  44. // class IntervalMap {
  45. // public:
  46. // typedef KeyT key_type;
  47. // typedef ValT mapped_type;
  48. // typedef RecyclingAllocator<...> Allocator;
  49. // class iterator;
  50. // class const_iterator;
  51. //
  52. // explicit IntervalMap(Allocator&);
  53. // ~IntervalMap():
  54. //
  55. // bool empty() const;
  56. // KeyT start() const;
  57. // KeyT stop() const;
  58. // ValT lookup(KeyT x, Value NotFound = Value()) const;
  59. //
  60. // const_iterator begin() const;
  61. // const_iterator end() const;
  62. // iterator begin();
  63. // iterator end();
  64. // const_iterator find(KeyT x) const;
  65. // iterator find(KeyT x);
  66. //
  67. // void insert(KeyT a, KeyT b, ValT y);
  68. // void clear();
  69. // };
  70. //
  71. // template <typename KeyT, typename ValT, unsigned N, typename Traits>
  72. // class IntervalMap::const_iterator {
  73. // public:
  74. // using iterator_category = std::bidirectional_iterator_tag;
  75. // using value_type = ValT;
  76. // using difference_type = std::ptrdiff_t;
  77. // using pointer = value_type *;
  78. // using reference = value_type &;
  79. //
  80. // bool operator==(const const_iterator &) const;
  81. // bool operator!=(const const_iterator &) const;
  82. // bool valid() const;
  83. //
  84. // const KeyT &start() const;
  85. // const KeyT &stop() const;
  86. // const ValT &value() const;
  87. // const ValT &operator*() const;
  88. // const ValT *operator->() const;
  89. //
  90. // const_iterator &operator++();
  91. // const_iterator &operator++(int);
  92. // const_iterator &operator--();
  93. // const_iterator &operator--(int);
  94. // void goToBegin();
  95. // void goToEnd();
  96. // void find(KeyT x);
  97. // void advanceTo(KeyT x);
  98. // };
  99. //
  100. // template <typename KeyT, typename ValT, unsigned N, typename Traits>
  101. // class IntervalMap::iterator : public const_iterator {
  102. // public:
  103. // void insert(KeyT a, KeyT b, Value y);
  104. // void erase();
  105. // };
  106. //
  107. //===----------------------------------------------------------------------===//
  108. #ifndef LLVM_ADT_INTERVALMAP_H
  109. #define LLVM_ADT_INTERVALMAP_H
  110. #include "llvm/ADT/PointerIntPair.h"
  111. #include "llvm/ADT/SmallVector.h"
  112. #include "llvm/Support/Allocator.h"
  113. #include "llvm/Support/RecyclingAllocator.h"
  114. #include <algorithm>
  115. #include <cassert>
  116. #include <iterator>
  117. #include <new>
  118. #include <utility>
  119. namespace llvm {
  120. //===----------------------------------------------------------------------===//
  121. //--- Key traits ---//
  122. //===----------------------------------------------------------------------===//
  123. //
  124. // The IntervalMap works with closed or half-open intervals.
  125. // Adjacent intervals that map to the same value are coalesced.
  126. //
  127. // The IntervalMapInfo traits class is used to determine if a key is contained
  128. // in an interval, and if two intervals are adjacent so they can be coalesced.
  129. // The provided implementation works for closed integer intervals, other keys
  130. // probably need a specialized version.
  131. //
  132. // The point x is contained in [a;b] when !startLess(x, a) && !stopLess(b, x).
  133. //
  134. // It is assumed that (a;b] half-open intervals are not used, only [a;b) is
  135. // allowed. This is so that stopLess(a, b) can be used to determine if two
  136. // intervals overlap.
  137. //
  138. //===----------------------------------------------------------------------===//
  139. template <typename T>
  140. struct IntervalMapInfo {
  141. /// startLess - Return true if x is not in [a;b].
  142. /// This is x < a both for closed intervals and for [a;b) half-open intervals.
  143. static inline bool startLess(const T &x, const T &a) {
  144. return x < a;
  145. }
  146. /// stopLess - Return true if x is not in [a;b].
  147. /// This is b < x for a closed interval, b <= x for [a;b) half-open intervals.
  148. static inline bool stopLess(const T &b, const T &x) {
  149. return b < x;
  150. }
  151. /// adjacent - Return true when the intervals [x;a] and [b;y] can coalesce.
  152. /// This is a+1 == b for closed intervals, a == b for half-open intervals.
  153. static inline bool adjacent(const T &a, const T &b) {
  154. return a+1 == b;
  155. }
  156. /// nonEmpty - Return true if [a;b] is non-empty.
  157. /// This is a <= b for a closed interval, a < b for [a;b) half-open intervals.
  158. static inline bool nonEmpty(const T &a, const T &b) {
  159. return a <= b;
  160. }
  161. };
  162. template <typename T>
  163. struct IntervalMapHalfOpenInfo {
  164. /// startLess - Return true if x is not in [a;b).
  165. static inline bool startLess(const T &x, const T &a) {
  166. return x < a;
  167. }
  168. /// stopLess - Return true if x is not in [a;b).
  169. static inline bool stopLess(const T &b, const T &x) {
  170. return b <= x;
  171. }
  172. /// adjacent - Return true when the intervals [x;a) and [b;y) can coalesce.
  173. static inline bool adjacent(const T &a, const T &b) {
  174. return a == b;
  175. }
  176. /// nonEmpty - Return true if [a;b) is non-empty.
  177. static inline bool nonEmpty(const T &a, const T &b) {
  178. return a < b;
  179. }
  180. };
  181. /// IntervalMapImpl - Namespace used for IntervalMap implementation details.
  182. /// It should be considered private to the implementation.
  183. namespace IntervalMapImpl {
  184. using IdxPair = std::pair<unsigned,unsigned>;
  185. //===----------------------------------------------------------------------===//
  186. //--- IntervalMapImpl::NodeBase ---//
  187. //===----------------------------------------------------------------------===//
  188. //
  189. // Both leaf and branch nodes store vectors of pairs.
  190. // Leaves store ((KeyT, KeyT), ValT) pairs, branches use (NodeRef, KeyT).
  191. //
  192. // Keys and values are stored in separate arrays to avoid padding caused by
  193. // different object alignments. This also helps improve locality of reference
  194. // when searching the keys.
  195. //
  196. // The nodes don't know how many elements they contain - that information is
  197. // stored elsewhere. Omitting the size field prevents padding and allows a node
  198. // to fill the allocated cache lines completely.
  199. //
  200. // These are typical key and value sizes, the node branching factor (N), and
  201. // wasted space when nodes are sized to fit in three cache lines (192 bytes):
  202. //
  203. // T1 T2 N Waste Used by
  204. // 4 4 24 0 Branch<4> (32-bit pointers)
  205. // 8 4 16 0 Leaf<4,4>, Branch<4>
  206. // 8 8 12 0 Leaf<4,8>, Branch<8>
  207. // 16 4 9 12 Leaf<8,4>
  208. // 16 8 8 0 Leaf<8,8>
  209. //
  210. //===----------------------------------------------------------------------===//
  211. template <typename T1, typename T2, unsigned N>
  212. class NodeBase {
  213. public:
  214. enum { Capacity = N };
  215. T1 first[N];
  216. T2 second[N];
  217. /// copy - Copy elements from another node.
  218. /// @param Other Node elements are copied from.
  219. /// @param i Beginning of the source range in other.
  220. /// @param j Beginning of the destination range in this.
  221. /// @param Count Number of elements to copy.
  222. template <unsigned M>
  223. void copy(const NodeBase<T1, T2, M> &Other, unsigned i,
  224. unsigned j, unsigned Count) {
  225. assert(i + Count <= M && "Invalid source range");
  226. assert(j + Count <= N && "Invalid dest range");
  227. for (unsigned e = i + Count; i != e; ++i, ++j) {
  228. first[j] = Other.first[i];
  229. second[j] = Other.second[i];
  230. }
  231. }
  232. /// moveLeft - Move elements to the left.
  233. /// @param i Beginning of the source range.
  234. /// @param j Beginning of the destination range.
  235. /// @param Count Number of elements to copy.
  236. void moveLeft(unsigned i, unsigned j, unsigned Count) {
  237. assert(j <= i && "Use moveRight shift elements right");
  238. copy(*this, i, j, Count);
  239. }
  240. /// moveRight - Move elements to the right.
  241. /// @param i Beginning of the source range.
  242. /// @param j Beginning of the destination range.
  243. /// @param Count Number of elements to copy.
  244. void moveRight(unsigned i, unsigned j, unsigned Count) {
  245. assert(i <= j && "Use moveLeft shift elements left");
  246. assert(j + Count <= N && "Invalid range");
  247. while (Count--) {
  248. first[j + Count] = first[i + Count];
  249. second[j + Count] = second[i + Count];
  250. }
  251. }
  252. /// erase - Erase elements [i;j).
  253. /// @param i Beginning of the range to erase.
  254. /// @param j End of the range. (Exclusive).
  255. /// @param Size Number of elements in node.
  256. void erase(unsigned i, unsigned j, unsigned Size) {
  257. moveLeft(j, i, Size - j);
  258. }
  259. /// erase - Erase element at i.
  260. /// @param i Index of element to erase.
  261. /// @param Size Number of elements in node.
  262. void erase(unsigned i, unsigned Size) {
  263. erase(i, i+1, Size);
  264. }
  265. /// shift - Shift elements [i;size) 1 position to the right.
  266. /// @param i Beginning of the range to move.
  267. /// @param Size Number of elements in node.
  268. void shift(unsigned i, unsigned Size) {
  269. moveRight(i, i + 1, Size - i);
  270. }
  271. /// transferToLeftSib - Transfer elements to a left sibling node.
  272. /// @param Size Number of elements in this.
  273. /// @param Sib Left sibling node.
  274. /// @param SSize Number of elements in sib.
  275. /// @param Count Number of elements to transfer.
  276. void transferToLeftSib(unsigned Size, NodeBase &Sib, unsigned SSize,
  277. unsigned Count) {
  278. Sib.copy(*this, 0, SSize, Count);
  279. erase(0, Count, Size);
  280. }
  281. /// transferToRightSib - Transfer elements to a right sibling node.
  282. /// @param Size Number of elements in this.
  283. /// @param Sib Right sibling node.
  284. /// @param SSize Number of elements in sib.
  285. /// @param Count Number of elements to transfer.
  286. void transferToRightSib(unsigned Size, NodeBase &Sib, unsigned SSize,
  287. unsigned Count) {
  288. Sib.moveRight(0, Count, SSize);
  289. Sib.copy(*this, Size-Count, 0, Count);
  290. }
  291. /// adjustFromLeftSib - Adjust the number if elements in this node by moving
  292. /// elements to or from a left sibling node.
  293. /// @param Size Number of elements in this.
  294. /// @param Sib Right sibling node.
  295. /// @param SSize Number of elements in sib.
  296. /// @param Add The number of elements to add to this node, possibly < 0.
  297. /// @return Number of elements added to this node, possibly negative.
  298. int adjustFromLeftSib(unsigned Size, NodeBase &Sib, unsigned SSize, int Add) {
  299. if (Add > 0) {
  300. // We want to grow, copy from sib.
  301. unsigned Count = std::min(std::min(unsigned(Add), SSize), N - Size);
  302. Sib.transferToRightSib(SSize, *this, Size, Count);
  303. return Count;
  304. } else {
  305. // We want to shrink, copy to sib.
  306. unsigned Count = std::min(std::min(unsigned(-Add), Size), N - SSize);
  307. transferToLeftSib(Size, Sib, SSize, Count);
  308. return -Count;
  309. }
  310. }
  311. };
  312. /// IntervalMapImpl::adjustSiblingSizes - Move elements between sibling nodes.
  313. /// @param Node Array of pointers to sibling nodes.
  314. /// @param Nodes Number of nodes.
  315. /// @param CurSize Array of current node sizes, will be overwritten.
  316. /// @param NewSize Array of desired node sizes.
  317. template <typename NodeT>
  318. void adjustSiblingSizes(NodeT *Node[], unsigned Nodes,
  319. unsigned CurSize[], const unsigned NewSize[]) {
  320. // Move elements right.
  321. for (int n = Nodes - 1; n; --n) {
  322. if (CurSize[n] == NewSize[n])
  323. continue;
  324. for (int m = n - 1; m != -1; --m) {
  325. int d = Node[n]->adjustFromLeftSib(CurSize[n], *Node[m], CurSize[m],
  326. NewSize[n] - CurSize[n]);
  327. CurSize[m] -= d;
  328. CurSize[n] += d;
  329. // Keep going if the current node was exhausted.
  330. if (CurSize[n] >= NewSize[n])
  331. break;
  332. }
  333. }
  334. if (Nodes == 0)
  335. return;
  336. // Move elements left.
  337. for (unsigned n = 0; n != Nodes - 1; ++n) {
  338. if (CurSize[n] == NewSize[n])
  339. continue;
  340. for (unsigned m = n + 1; m != Nodes; ++m) {
  341. int d = Node[m]->adjustFromLeftSib(CurSize[m], *Node[n], CurSize[n],
  342. CurSize[n] - NewSize[n]);
  343. CurSize[m] += d;
  344. CurSize[n] -= d;
  345. // Keep going if the current node was exhausted.
  346. if (CurSize[n] >= NewSize[n])
  347. break;
  348. }
  349. }
  350. #ifndef NDEBUG
  351. for (unsigned n = 0; n != Nodes; n++)
  352. assert(CurSize[n] == NewSize[n] && "Insufficient element shuffle");
  353. #endif
  354. }
  355. /// IntervalMapImpl::distribute - Compute a new distribution of node elements
  356. /// after an overflow or underflow. Reserve space for a new element at Position,
  357. /// and compute the node that will hold Position after redistributing node
  358. /// elements.
  359. ///
  360. /// It is required that
  361. ///
  362. /// Elements == sum(CurSize), and
  363. /// Elements + Grow <= Nodes * Capacity.
  364. ///
  365. /// NewSize[] will be filled in such that:
  366. ///
  367. /// sum(NewSize) == Elements, and
  368. /// NewSize[i] <= Capacity.
  369. ///
  370. /// The returned index is the node where Position will go, so:
  371. ///
  372. /// sum(NewSize[0..idx-1]) <= Position
  373. /// sum(NewSize[0..idx]) >= Position
  374. ///
  375. /// The last equality, sum(NewSize[0..idx]) == Position, can only happen when
  376. /// Grow is set and NewSize[idx] == Capacity-1. The index points to the node
  377. /// before the one holding the Position'th element where there is room for an
  378. /// insertion.
  379. ///
  380. /// @param Nodes The number of nodes.
  381. /// @param Elements Total elements in all nodes.
  382. /// @param Capacity The capacity of each node.
  383. /// @param CurSize Array[Nodes] of current node sizes, or NULL.
  384. /// @param NewSize Array[Nodes] to receive the new node sizes.
  385. /// @param Position Insert position.
  386. /// @param Grow Reserve space for a new element at Position.
  387. /// @return (node, offset) for Position.
  388. IdxPair distribute(unsigned Nodes, unsigned Elements, unsigned Capacity,
  389. const unsigned *CurSize, unsigned NewSize[],
  390. unsigned Position, bool Grow);
  391. //===----------------------------------------------------------------------===//
  392. //--- IntervalMapImpl::NodeSizer ---//
  393. //===----------------------------------------------------------------------===//
  394. //
  395. // Compute node sizes from key and value types.
  396. //
  397. // The branching factors are chosen to make nodes fit in three cache lines.
  398. // This may not be possible if keys or values are very large. Such large objects
  399. // are handled correctly, but a std::map would probably give better performance.
  400. //
  401. //===----------------------------------------------------------------------===//
  402. enum {
  403. // Cache line size. Most architectures have 32 or 64 byte cache lines.
  404. // We use 64 bytes here because it provides good branching factors.
  405. Log2CacheLine = 6,
  406. CacheLineBytes = 1 << Log2CacheLine,
  407. DesiredNodeBytes = 3 * CacheLineBytes
  408. };
  409. template <typename KeyT, typename ValT>
  410. struct NodeSizer {
  411. enum {
  412. // Compute the leaf node branching factor that makes a node fit in three
  413. // cache lines. The branching factor must be at least 3, or some B+-tree
  414. // balancing algorithms won't work.
  415. // LeafSize can't be larger than CacheLineBytes. This is required by the
  416. // PointerIntPair used by NodeRef.
  417. DesiredLeafSize = DesiredNodeBytes /
  418. static_cast<unsigned>(2*sizeof(KeyT)+sizeof(ValT)),
  419. MinLeafSize = 3,
  420. LeafSize = DesiredLeafSize > MinLeafSize ? DesiredLeafSize : MinLeafSize
  421. };
  422. using LeafBase = NodeBase<std::pair<KeyT, KeyT>, ValT, LeafSize>;
  423. enum {
  424. // Now that we have the leaf branching factor, compute the actual allocation
  425. // unit size by rounding up to a whole number of cache lines.
  426. AllocBytes = (sizeof(LeafBase) + CacheLineBytes-1) & ~(CacheLineBytes-1),
  427. // Determine the branching factor for branch nodes.
  428. BranchSize = AllocBytes /
  429. static_cast<unsigned>(sizeof(KeyT) + sizeof(void*))
  430. };
  431. /// Allocator - The recycling allocator used for both branch and leaf nodes.
  432. /// This typedef is very likely to be identical for all IntervalMaps with
  433. /// reasonably sized entries, so the same allocator can be shared among
  434. /// different kinds of maps.
  435. using Allocator =
  436. RecyclingAllocator<BumpPtrAllocator, char, AllocBytes, CacheLineBytes>;
  437. };
  438. //===----------------------------------------------------------------------===//
  439. //--- IntervalMapImpl::NodeRef ---//
  440. //===----------------------------------------------------------------------===//
  441. //
  442. // B+-tree nodes can be leaves or branches, so we need a polymorphic node
  443. // pointer that can point to both kinds.
  444. //
  445. // All nodes are cache line aligned and the low 6 bits of a node pointer are
  446. // always 0. These bits are used to store the number of elements in the
  447. // referenced node. Besides saving space, placing node sizes in the parents
  448. // allow tree balancing algorithms to run without faulting cache lines for nodes
  449. // that may not need to be modified.
  450. //
  451. // A NodeRef doesn't know whether it references a leaf node or a branch node.
  452. // It is the responsibility of the caller to use the correct types.
  453. //
  454. // Nodes are never supposed to be empty, and it is invalid to store a node size
  455. // of 0 in a NodeRef. The valid range of sizes is 1-64.
  456. //
  457. //===----------------------------------------------------------------------===//
  458. class NodeRef {
  459. struct CacheAlignedPointerTraits {
  460. static inline void *getAsVoidPointer(void *P) { return P; }
  461. static inline void *getFromVoidPointer(void *P) { return P; }
  462. static constexpr int NumLowBitsAvailable = Log2CacheLine;
  463. };
  464. PointerIntPair<void*, Log2CacheLine, unsigned, CacheAlignedPointerTraits> pip;
  465. public:
  466. /// NodeRef - Create a null ref.
  467. NodeRef() = default;
  468. /// operator bool - Detect a null ref.
  469. explicit operator bool() const { return pip.getOpaqueValue(); }
  470. /// NodeRef - Create a reference to the node p with n elements.
  471. template <typename NodeT>
  472. NodeRef(NodeT *p, unsigned n) : pip(p, n - 1) {
  473. assert(n <= NodeT::Capacity && "Size too big for node");
  474. }
  475. /// size - Return the number of elements in the referenced node.
  476. unsigned size() const { return pip.getInt() + 1; }
  477. /// setSize - Update the node size.
  478. void setSize(unsigned n) { pip.setInt(n - 1); }
  479. /// subtree - Access the i'th subtree reference in a branch node.
  480. /// This depends on branch nodes storing the NodeRef array as their first
  481. /// member.
  482. NodeRef &subtree(unsigned i) const {
  483. return reinterpret_cast<NodeRef*>(pip.getPointer())[i];
  484. }
  485. /// get - Dereference as a NodeT reference.
  486. template <typename NodeT>
  487. NodeT &get() const {
  488. return *reinterpret_cast<NodeT*>(pip.getPointer());
  489. }
  490. bool operator==(const NodeRef &RHS) const {
  491. if (pip == RHS.pip)
  492. return true;
  493. assert(pip.getPointer() != RHS.pip.getPointer() && "Inconsistent NodeRefs");
  494. return false;
  495. }
  496. bool operator!=(const NodeRef &RHS) const {
  497. return !operator==(RHS);
  498. }
  499. };
  500. //===----------------------------------------------------------------------===//
  501. //--- IntervalMapImpl::LeafNode ---//
  502. //===----------------------------------------------------------------------===//
  503. //
  504. // Leaf nodes store up to N disjoint intervals with corresponding values.
  505. //
  506. // The intervals are kept sorted and fully coalesced so there are no adjacent
  507. // intervals mapping to the same value.
  508. //
  509. // These constraints are always satisfied:
  510. //
  511. // - Traits::stopLess(start(i), stop(i)) - Non-empty, sane intervals.
  512. //
  513. // - Traits::stopLess(stop(i), start(i + 1) - Sorted.
  514. //
  515. // - value(i) != value(i + 1) || !Traits::adjacent(stop(i), start(i + 1))
  516. // - Fully coalesced.
  517. //
  518. //===----------------------------------------------------------------------===//
  519. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  520. class LeafNode : public NodeBase<std::pair<KeyT, KeyT>, ValT, N> {
  521. public:
  522. const KeyT &start(unsigned i) const { return this->first[i].first; }
  523. const KeyT &stop(unsigned i) const { return this->first[i].second; }
  524. const ValT &value(unsigned i) const { return this->second[i]; }
  525. KeyT &start(unsigned i) { return this->first[i].first; }
  526. KeyT &stop(unsigned i) { return this->first[i].second; }
  527. ValT &value(unsigned i) { return this->second[i]; }
  528. /// findFrom - Find the first interval after i that may contain x.
  529. /// @param i Starting index for the search.
  530. /// @param Size Number of elements in node.
  531. /// @param x Key to search for.
  532. /// @return First index with !stopLess(key[i].stop, x), or size.
  533. /// This is the first interval that can possibly contain x.
  534. unsigned findFrom(unsigned i, unsigned Size, KeyT x) const {
  535. assert(i <= Size && Size <= N && "Bad indices");
  536. assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
  537. "Index is past the needed point");
  538. while (i != Size && Traits::stopLess(stop(i), x)) ++i;
  539. return i;
  540. }
  541. /// safeFind - Find an interval that is known to exist. This is the same as
  542. /// findFrom except is it assumed that x is at least within range of the last
  543. /// interval.
  544. /// @param i Starting index for the search.
  545. /// @param x Key to search for.
  546. /// @return First index with !stopLess(key[i].stop, x), never size.
  547. /// This is the first interval that can possibly contain x.
  548. unsigned safeFind(unsigned i, KeyT x) const {
  549. assert(i < N && "Bad index");
  550. assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
  551. "Index is past the needed point");
  552. while (Traits::stopLess(stop(i), x)) ++i;
  553. assert(i < N && "Unsafe intervals");
  554. return i;
  555. }
  556. /// safeLookup - Lookup mapped value for a safe key.
  557. /// It is assumed that x is within range of the last entry.
  558. /// @param x Key to search for.
  559. /// @param NotFound Value to return if x is not in any interval.
  560. /// @return The mapped value at x or NotFound.
  561. ValT safeLookup(KeyT x, ValT NotFound) const {
  562. unsigned i = safeFind(0, x);
  563. return Traits::startLess(x, start(i)) ? NotFound : value(i);
  564. }
  565. unsigned insertFrom(unsigned &Pos, unsigned Size, KeyT a, KeyT b, ValT y);
  566. };
  567. /// insertFrom - Add mapping of [a;b] to y if possible, coalescing as much as
  568. /// possible. This may cause the node to grow by 1, or it may cause the node
  569. /// to shrink because of coalescing.
  570. /// @param Pos Starting index = insertFrom(0, size, a)
  571. /// @param Size Number of elements in node.
  572. /// @param a Interval start.
  573. /// @param b Interval stop.
  574. /// @param y Value be mapped.
  575. /// @return (insert position, new size), or (i, Capacity+1) on overflow.
  576. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  577. unsigned LeafNode<KeyT, ValT, N, Traits>::
  578. insertFrom(unsigned &Pos, unsigned Size, KeyT a, KeyT b, ValT y) {
  579. unsigned i = Pos;
  580. assert(i <= Size && Size <= N && "Invalid index");
  581. assert(!Traits::stopLess(b, a) && "Invalid interval");
  582. // Verify the findFrom invariant.
  583. assert((i == 0 || Traits::stopLess(stop(i - 1), a)));
  584. assert((i == Size || !Traits::stopLess(stop(i), a)));
  585. assert((i == Size || Traits::stopLess(b, start(i))) && "Overlapping insert");
  586. // Coalesce with previous interval.
  587. if (i && value(i - 1) == y && Traits::adjacent(stop(i - 1), a)) {
  588. Pos = i - 1;
  589. // Also coalesce with next interval?
  590. if (i != Size && value(i) == y && Traits::adjacent(b, start(i))) {
  591. stop(i - 1) = stop(i);
  592. this->erase(i, Size);
  593. return Size - 1;
  594. }
  595. stop(i - 1) = b;
  596. return Size;
  597. }
  598. // Detect overflow.
  599. if (i == N)
  600. return N + 1;
  601. // Add new interval at end.
  602. if (i == Size) {
  603. start(i) = a;
  604. stop(i) = b;
  605. value(i) = y;
  606. return Size + 1;
  607. }
  608. // Try to coalesce with following interval.
  609. if (value(i) == y && Traits::adjacent(b, start(i))) {
  610. start(i) = a;
  611. return Size;
  612. }
  613. // We must insert before i. Detect overflow.
  614. if (Size == N)
  615. return N + 1;
  616. // Insert before i.
  617. this->shift(i, Size);
  618. start(i) = a;
  619. stop(i) = b;
  620. value(i) = y;
  621. return Size + 1;
  622. }
  623. //===----------------------------------------------------------------------===//
  624. //--- IntervalMapImpl::BranchNode ---//
  625. //===----------------------------------------------------------------------===//
  626. //
  627. // A branch node stores references to 1--N subtrees all of the same height.
  628. //
  629. // The key array in a branch node holds the rightmost stop key of each subtree.
  630. // It is redundant to store the last stop key since it can be found in the
  631. // parent node, but doing so makes tree balancing a lot simpler.
  632. //
  633. // It is unusual for a branch node to only have one subtree, but it can happen
  634. // in the root node if it is smaller than the normal nodes.
  635. //
  636. // When all of the leaf nodes from all the subtrees are concatenated, they must
  637. // satisfy the same constraints as a single leaf node. They must be sorted,
  638. // sane, and fully coalesced.
  639. //
  640. //===----------------------------------------------------------------------===//
  641. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  642. class BranchNode : public NodeBase<NodeRef, KeyT, N> {
  643. public:
  644. const KeyT &stop(unsigned i) const { return this->second[i]; }
  645. const NodeRef &subtree(unsigned i) const { return this->first[i]; }
  646. KeyT &stop(unsigned i) { return this->second[i]; }
  647. NodeRef &subtree(unsigned i) { return this->first[i]; }
  648. /// findFrom - Find the first subtree after i that may contain x.
  649. /// @param i Starting index for the search.
  650. /// @param Size Number of elements in node.
  651. /// @param x Key to search for.
  652. /// @return First index with !stopLess(key[i], x), or size.
  653. /// This is the first subtree that can possibly contain x.
  654. unsigned findFrom(unsigned i, unsigned Size, KeyT x) const {
  655. assert(i <= Size && Size <= N && "Bad indices");
  656. assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
  657. "Index to findFrom is past the needed point");
  658. while (i != Size && Traits::stopLess(stop(i), x)) ++i;
  659. return i;
  660. }
  661. /// safeFind - Find a subtree that is known to exist. This is the same as
  662. /// findFrom except is it assumed that x is in range.
  663. /// @param i Starting index for the search.
  664. /// @param x Key to search for.
  665. /// @return First index with !stopLess(key[i], x), never size.
  666. /// This is the first subtree that can possibly contain x.
  667. unsigned safeFind(unsigned i, KeyT x) const {
  668. assert(i < N && "Bad index");
  669. assert((i == 0 || Traits::stopLess(stop(i - 1), x)) &&
  670. "Index is past the needed point");
  671. while (Traits::stopLess(stop(i), x)) ++i;
  672. assert(i < N && "Unsafe intervals");
  673. return i;
  674. }
  675. /// safeLookup - Get the subtree containing x, Assuming that x is in range.
  676. /// @param x Key to search for.
  677. /// @return Subtree containing x
  678. NodeRef safeLookup(KeyT x) const {
  679. return subtree(safeFind(0, x));
  680. }
  681. /// insert - Insert a new (subtree, stop) pair.
  682. /// @param i Insert position, following entries will be shifted.
  683. /// @param Size Number of elements in node.
  684. /// @param Node Subtree to insert.
  685. /// @param Stop Last key in subtree.
  686. void insert(unsigned i, unsigned Size, NodeRef Node, KeyT Stop) {
  687. assert(Size < N && "branch node overflow");
  688. assert(i <= Size && "Bad insert position");
  689. this->shift(i, Size);
  690. subtree(i) = Node;
  691. stop(i) = Stop;
  692. }
  693. };
  694. //===----------------------------------------------------------------------===//
  695. //--- IntervalMapImpl::Path ---//
  696. //===----------------------------------------------------------------------===//
  697. //
  698. // A Path is used by iterators to represent a position in a B+-tree, and the
  699. // path to get there from the root.
  700. //
  701. // The Path class also contains the tree navigation code that doesn't have to
  702. // be templatized.
  703. //
  704. //===----------------------------------------------------------------------===//
  705. class Path {
  706. /// Entry - Each step in the path is a node pointer and an offset into that
  707. /// node.
  708. struct Entry {
  709. void *node;
  710. unsigned size;
  711. unsigned offset;
  712. Entry(void *Node, unsigned Size, unsigned Offset)
  713. : node(Node), size(Size), offset(Offset) {}
  714. Entry(NodeRef Node, unsigned Offset)
  715. : node(&Node.subtree(0)), size(Node.size()), offset(Offset) {}
  716. NodeRef &subtree(unsigned i) const {
  717. return reinterpret_cast<NodeRef*>(node)[i];
  718. }
  719. };
  720. /// path - The path entries, path[0] is the root node, path.back() is a leaf.
  721. SmallVector<Entry, 4> path;
  722. public:
  723. // Node accessors.
  724. template <typename NodeT> NodeT &node(unsigned Level) const {
  725. return *reinterpret_cast<NodeT*>(path[Level].node);
  726. }
  727. unsigned size(unsigned Level) const { return path[Level].size; }
  728. unsigned offset(unsigned Level) const { return path[Level].offset; }
  729. unsigned &offset(unsigned Level) { return path[Level].offset; }
  730. // Leaf accessors.
  731. template <typename NodeT> NodeT &leaf() const {
  732. return *reinterpret_cast<NodeT*>(path.back().node);
  733. }
  734. unsigned leafSize() const { return path.back().size; }
  735. unsigned leafOffset() const { return path.back().offset; }
  736. unsigned &leafOffset() { return path.back().offset; }
  737. /// valid - Return true if path is at a valid node, not at end().
  738. bool valid() const {
  739. return !path.empty() && path.front().offset < path.front().size;
  740. }
  741. /// height - Return the height of the tree corresponding to this path.
  742. /// This matches map->height in a full path.
  743. unsigned height() const { return path.size() - 1; }
  744. /// subtree - Get the subtree referenced from Level. When the path is
  745. /// consistent, node(Level + 1) == subtree(Level).
  746. /// @param Level 0..height-1. The leaves have no subtrees.
  747. NodeRef &subtree(unsigned Level) const {
  748. return path[Level].subtree(path[Level].offset);
  749. }
  750. /// reset - Reset cached information about node(Level) from subtree(Level -1).
  751. /// @param Level 1..height. The node to update after parent node changed.
  752. void reset(unsigned Level) {
  753. path[Level] = Entry(subtree(Level - 1), offset(Level));
  754. }
  755. /// push - Add entry to path.
  756. /// @param Node Node to add, should be subtree(path.size()-1).
  757. /// @param Offset Offset into Node.
  758. void push(NodeRef Node, unsigned Offset) {
  759. path.push_back(Entry(Node, Offset));
  760. }
  761. /// pop - Remove the last path entry.
  762. void pop() {
  763. path.pop_back();
  764. }
  765. /// setSize - Set the size of a node both in the path and in the tree.
  766. /// @param Level 0..height. Note that setting the root size won't change
  767. /// map->rootSize.
  768. /// @param Size New node size.
  769. void setSize(unsigned Level, unsigned Size) {
  770. path[Level].size = Size;
  771. if (Level)
  772. subtree(Level - 1).setSize(Size);
  773. }
  774. /// setRoot - Clear the path and set a new root node.
  775. /// @param Node New root node.
  776. /// @param Size New root size.
  777. /// @param Offset Offset into root node.
  778. void setRoot(void *Node, unsigned Size, unsigned Offset) {
  779. path.clear();
  780. path.push_back(Entry(Node, Size, Offset));
  781. }
  782. /// replaceRoot - Replace the current root node with two new entries after the
  783. /// tree height has increased.
  784. /// @param Root The new root node.
  785. /// @param Size Number of entries in the new root.
  786. /// @param Offsets Offsets into the root and first branch nodes.
  787. void replaceRoot(void *Root, unsigned Size, IdxPair Offsets);
  788. /// getLeftSibling - Get the left sibling node at Level, or a null NodeRef.
  789. /// @param Level Get the sibling to node(Level).
  790. /// @return Left sibling, or NodeRef().
  791. NodeRef getLeftSibling(unsigned Level) const;
  792. /// moveLeft - Move path to the left sibling at Level. Leave nodes below Level
  793. /// unaltered.
  794. /// @param Level Move node(Level).
  795. void moveLeft(unsigned Level);
  796. /// fillLeft - Grow path to Height by taking leftmost branches.
  797. /// @param Height The target height.
  798. void fillLeft(unsigned Height) {
  799. while (height() < Height)
  800. push(subtree(height()), 0);
  801. }
  802. /// getLeftSibling - Get the left sibling node at Level, or a null NodeRef.
  803. /// @param Level Get the sibling to node(Level).
  804. /// @return Left sibling, or NodeRef().
  805. NodeRef getRightSibling(unsigned Level) const;
  806. /// moveRight - Move path to the left sibling at Level. Leave nodes below
  807. /// Level unaltered.
  808. /// @param Level Move node(Level).
  809. void moveRight(unsigned Level);
  810. /// atBegin - Return true if path is at begin().
  811. bool atBegin() const {
  812. for (unsigned i = 0, e = path.size(); i != e; ++i)
  813. if (path[i].offset != 0)
  814. return false;
  815. return true;
  816. }
  817. /// atLastEntry - Return true if the path is at the last entry of the node at
  818. /// Level.
  819. /// @param Level Node to examine.
  820. bool atLastEntry(unsigned Level) const {
  821. return path[Level].offset == path[Level].size - 1;
  822. }
  823. /// legalizeForInsert - Prepare the path for an insertion at Level. When the
  824. /// path is at end(), node(Level) may not be a legal node. legalizeForInsert
  825. /// ensures that node(Level) is real by moving back to the last node at Level,
  826. /// and setting offset(Level) to size(Level) if required.
  827. /// @param Level The level where an insertion is about to take place.
  828. void legalizeForInsert(unsigned Level) {
  829. if (valid())
  830. return;
  831. moveLeft(Level);
  832. ++path[Level].offset;
  833. }
  834. };
  835. } // end namespace IntervalMapImpl
  836. //===----------------------------------------------------------------------===//
  837. //--- IntervalMap ----//
  838. //===----------------------------------------------------------------------===//
  839. template <typename KeyT, typename ValT,
  840. unsigned N = IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
  841. typename Traits = IntervalMapInfo<KeyT>>
  842. class IntervalMap {
  843. using Sizer = IntervalMapImpl::NodeSizer<KeyT, ValT>;
  844. using Leaf = IntervalMapImpl::LeafNode<KeyT, ValT, Sizer::LeafSize, Traits>;
  845. using Branch =
  846. IntervalMapImpl::BranchNode<KeyT, ValT, Sizer::BranchSize, Traits>;
  847. using RootLeaf = IntervalMapImpl::LeafNode<KeyT, ValT, N, Traits>;
  848. using IdxPair = IntervalMapImpl::IdxPair;
  849. // The RootLeaf capacity is given as a template parameter. We must compute the
  850. // corresponding RootBranch capacity.
  851. enum {
  852. DesiredRootBranchCap = (sizeof(RootLeaf) - sizeof(KeyT)) /
  853. (sizeof(KeyT) + sizeof(IntervalMapImpl::NodeRef)),
  854. RootBranchCap = DesiredRootBranchCap ? DesiredRootBranchCap : 1
  855. };
  856. using RootBranch =
  857. IntervalMapImpl::BranchNode<KeyT, ValT, RootBranchCap, Traits>;
  858. // When branched, we store a global start key as well as the branch node.
  859. struct RootBranchData {
  860. KeyT start;
  861. RootBranch node;
  862. };
  863. public:
  864. using Allocator = typename Sizer::Allocator;
  865. using KeyType = KeyT;
  866. using ValueType = ValT;
  867. using KeyTraits = Traits;
  868. private:
  869. // The root data is either a RootLeaf or a RootBranchData instance.
  870. union {
  871. RootLeaf leaf;
  872. RootBranchData branchData;
  873. };
  874. // Tree height.
  875. // 0: Leaves in root.
  876. // 1: Root points to leaf.
  877. // 2: root->branch->leaf ...
  878. unsigned height = 0;
  879. // Number of entries in the root node.
  880. unsigned rootSize = 0;
  881. // Allocator used for creating external nodes.
  882. Allocator *allocator = nullptr;
  883. const RootLeaf &rootLeaf() const {
  884. assert(!branched() && "Cannot acces leaf data in branched root");
  885. return leaf;
  886. }
  887. RootLeaf &rootLeaf() {
  888. assert(!branched() && "Cannot acces leaf data in branched root");
  889. return leaf;
  890. }
  891. const RootBranchData &rootBranchData() const {
  892. assert(branched() && "Cannot access branch data in non-branched root");
  893. return branchData;
  894. }
  895. RootBranchData &rootBranchData() {
  896. assert(branched() && "Cannot access branch data in non-branched root");
  897. return branchData;
  898. }
  899. const RootBranch &rootBranch() const { return rootBranchData().node; }
  900. RootBranch &rootBranch() { return rootBranchData().node; }
  901. KeyT rootBranchStart() const { return rootBranchData().start; }
  902. KeyT &rootBranchStart() { return rootBranchData().start; }
  903. template <typename NodeT> NodeT *newNode() {
  904. return new (allocator->template Allocate<NodeT>()) NodeT();
  905. }
  906. template <typename NodeT> void deleteNode(NodeT *P) {
  907. P->~NodeT();
  908. allocator->Deallocate(P);
  909. }
  910. IdxPair branchRoot(unsigned Position);
  911. IdxPair splitRoot(unsigned Position);
  912. void switchRootToBranch() {
  913. rootLeaf().~RootLeaf();
  914. height = 1;
  915. new (&rootBranchData()) RootBranchData();
  916. }
  917. void switchRootToLeaf() {
  918. rootBranchData().~RootBranchData();
  919. height = 0;
  920. new(&rootLeaf()) RootLeaf();
  921. }
  922. bool branched() const { return height > 0; }
  923. ValT treeSafeLookup(KeyT x, ValT NotFound) const;
  924. void visitNodes(void (IntervalMap::*f)(IntervalMapImpl::NodeRef,
  925. unsigned Level));
  926. void deleteNode(IntervalMapImpl::NodeRef Node, unsigned Level);
  927. public:
  928. explicit IntervalMap(Allocator &a) : allocator(&a) {
  929. new (&rootLeaf()) RootLeaf();
  930. }
  931. ///@{
  932. /// NOTE: The moved-from or copied-from object's allocator needs to have a
  933. /// lifetime equal to or exceeding the moved-to or copied-to object to avoid
  934. /// undefined behaviour.
  935. IntervalMap(IntervalMap const &RHS) : IntervalMap(*RHS.allocator) {
  936. // Future-proofing assertion: this function assumes the IntervalMap
  937. // constructor doesn't add any nodes.
  938. assert(empty() && "Expected emptry tree");
  939. *this = RHS;
  940. }
  941. IntervalMap &operator=(IntervalMap const &RHS) {
  942. clear();
  943. allocator = RHS.allocator;
  944. for (auto It = RHS.begin(), End = RHS.end(); It != End; ++It)
  945. insert(It.start(), It.stop(), It.value());
  946. return *this;
  947. }
  948. IntervalMap(IntervalMap &&RHS) : IntervalMap(*RHS.allocator) {
  949. // Future-proofing assertion: this function assumes the IntervalMap
  950. // constructor doesn't add any nodes.
  951. assert(empty() && "Expected emptry tree");
  952. *this = std::move(RHS);
  953. }
  954. IntervalMap &operator=(IntervalMap &&RHS) {
  955. // Calling clear deallocates memory and switches to rootLeaf.
  956. clear();
  957. // Destroy the new rootLeaf.
  958. rootLeaf().~RootLeaf();
  959. height = RHS.height;
  960. rootSize = RHS.rootSize;
  961. allocator = RHS.allocator;
  962. // rootLeaf and rootBranch are both uninitialized. Move RHS data into
  963. // appropriate field.
  964. if (RHS.branched()) {
  965. rootBranch() = std::move(RHS.rootBranch());
  966. // Prevent RHS deallocating memory LHS now owns by replacing RHS
  967. // rootBranch with a new rootLeaf.
  968. RHS.rootBranch().~RootBranch();
  969. RHS.height = 0;
  970. new (&RHS.rootLeaf()) RootLeaf();
  971. } else {
  972. rootLeaf() = std::move(RHS.rootLeaf());
  973. }
  974. return *this;
  975. }
  976. ///@}
  977. ~IntervalMap() {
  978. clear();
  979. rootLeaf().~RootLeaf();
  980. }
  981. /// empty - Return true when no intervals are mapped.
  982. bool empty() const {
  983. return rootSize == 0;
  984. }
  985. /// start - Return the smallest mapped key in a non-empty map.
  986. KeyT start() const {
  987. assert(!empty() && "Empty IntervalMap has no start");
  988. return !branched() ? rootLeaf().start(0) : rootBranchStart();
  989. }
  990. /// stop - Return the largest mapped key in a non-empty map.
  991. KeyT stop() const {
  992. assert(!empty() && "Empty IntervalMap has no stop");
  993. return !branched() ? rootLeaf().stop(rootSize - 1) :
  994. rootBranch().stop(rootSize - 1);
  995. }
  996. /// lookup - Return the mapped value at x or NotFound.
  997. ValT lookup(KeyT x, ValT NotFound = ValT()) const {
  998. if (empty() || Traits::startLess(x, start()) || Traits::stopLess(stop(), x))
  999. return NotFound;
  1000. return branched() ? treeSafeLookup(x, NotFound) :
  1001. rootLeaf().safeLookup(x, NotFound);
  1002. }
  1003. /// insert - Add a mapping of [a;b] to y, coalesce with adjacent intervals.
  1004. /// It is assumed that no key in the interval is mapped to another value, but
  1005. /// overlapping intervals already mapped to y will be coalesced.
  1006. void insert(KeyT a, KeyT b, ValT y) {
  1007. if (branched() || rootSize == RootLeaf::Capacity)
  1008. return find(a).insert(a, b, y);
  1009. // Easy insert into root leaf.
  1010. unsigned p = rootLeaf().findFrom(0, rootSize, a);
  1011. rootSize = rootLeaf().insertFrom(p, rootSize, a, b, y);
  1012. }
  1013. /// clear - Remove all entries.
  1014. void clear();
  1015. class const_iterator;
  1016. class iterator;
  1017. friend class const_iterator;
  1018. friend class iterator;
  1019. const_iterator begin() const {
  1020. const_iterator I(*this);
  1021. I.goToBegin();
  1022. return I;
  1023. }
  1024. iterator begin() {
  1025. iterator I(*this);
  1026. I.goToBegin();
  1027. return I;
  1028. }
  1029. const_iterator end() const {
  1030. const_iterator I(*this);
  1031. I.goToEnd();
  1032. return I;
  1033. }
  1034. iterator end() {
  1035. iterator I(*this);
  1036. I.goToEnd();
  1037. return I;
  1038. }
  1039. /// find - Return an iterator pointing to the first interval ending at or
  1040. /// after x, or end().
  1041. const_iterator find(KeyT x) const {
  1042. const_iterator I(*this);
  1043. I.find(x);
  1044. return I;
  1045. }
  1046. iterator find(KeyT x) {
  1047. iterator I(*this);
  1048. I.find(x);
  1049. return I;
  1050. }
  1051. /// overlaps(a, b) - Return true if the intervals in this map overlap with the
  1052. /// interval [a;b].
  1053. bool overlaps(KeyT a, KeyT b) const {
  1054. assert(Traits::nonEmpty(a, b));
  1055. const_iterator I = find(a);
  1056. if (!I.valid())
  1057. return false;
  1058. // [a;b] and [x;y] overlap iff x<=b and a<=y. The find() call guarantees the
  1059. // second part (y = find(a).stop()), so it is sufficient to check the first
  1060. // one.
  1061. return !Traits::stopLess(b, I.start());
  1062. }
  1063. };
  1064. /// treeSafeLookup - Return the mapped value at x or NotFound, assuming a
  1065. /// branched root.
  1066. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1067. ValT IntervalMap<KeyT, ValT, N, Traits>::
  1068. treeSafeLookup(KeyT x, ValT NotFound) const {
  1069. assert(branched() && "treeLookup assumes a branched root");
  1070. IntervalMapImpl::NodeRef NR = rootBranch().safeLookup(x);
  1071. for (unsigned h = height-1; h; --h)
  1072. NR = NR.get<Branch>().safeLookup(x);
  1073. return NR.get<Leaf>().safeLookup(x, NotFound);
  1074. }
  1075. // branchRoot - Switch from a leaf root to a branched root.
  1076. // Return the new (root offset, node offset) corresponding to Position.
  1077. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1078. IntervalMapImpl::IdxPair IntervalMap<KeyT, ValT, N, Traits>::
  1079. branchRoot(unsigned Position) {
  1080. using namespace IntervalMapImpl;
  1081. // How many external leaf nodes to hold RootLeaf+1?
  1082. const unsigned Nodes = RootLeaf::Capacity / Leaf::Capacity + 1;
  1083. // Compute element distribution among new nodes.
  1084. unsigned size[Nodes];
  1085. IdxPair NewOffset(0, Position);
  1086. // Is is very common for the root node to be smaller than external nodes.
  1087. if (Nodes == 1)
  1088. size[0] = rootSize;
  1089. else
  1090. NewOffset = distribute(Nodes, rootSize, Leaf::Capacity, nullptr, size,
  1091. Position, true);
  1092. // Allocate new nodes.
  1093. unsigned pos = 0;
  1094. NodeRef node[Nodes];
  1095. for (unsigned n = 0; n != Nodes; ++n) {
  1096. Leaf *L = newNode<Leaf>();
  1097. L->copy(rootLeaf(), pos, 0, size[n]);
  1098. node[n] = NodeRef(L, size[n]);
  1099. pos += size[n];
  1100. }
  1101. // Destroy the old leaf node, construct branch node instead.
  1102. switchRootToBranch();
  1103. for (unsigned n = 0; n != Nodes; ++n) {
  1104. rootBranch().stop(n) = node[n].template get<Leaf>().stop(size[n]-1);
  1105. rootBranch().subtree(n) = node[n];
  1106. }
  1107. rootBranchStart() = node[0].template get<Leaf>().start(0);
  1108. rootSize = Nodes;
  1109. return NewOffset;
  1110. }
  1111. // splitRoot - Split the current BranchRoot into multiple Branch nodes.
  1112. // Return the new (root offset, node offset) corresponding to Position.
  1113. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1114. IntervalMapImpl::IdxPair IntervalMap<KeyT, ValT, N, Traits>::
  1115. splitRoot(unsigned Position) {
  1116. using namespace IntervalMapImpl;
  1117. // How many external leaf nodes to hold RootBranch+1?
  1118. const unsigned Nodes = RootBranch::Capacity / Branch::Capacity + 1;
  1119. // Compute element distribution among new nodes.
  1120. unsigned Size[Nodes];
  1121. IdxPair NewOffset(0, Position);
  1122. // Is is very common for the root node to be smaller than external nodes.
  1123. if (Nodes == 1)
  1124. Size[0] = rootSize;
  1125. else
  1126. NewOffset = distribute(Nodes, rootSize, Leaf::Capacity, nullptr, Size,
  1127. Position, true);
  1128. // Allocate new nodes.
  1129. unsigned Pos = 0;
  1130. NodeRef Node[Nodes];
  1131. for (unsigned n = 0; n != Nodes; ++n) {
  1132. Branch *B = newNode<Branch>();
  1133. B->copy(rootBranch(), Pos, 0, Size[n]);
  1134. Node[n] = NodeRef(B, Size[n]);
  1135. Pos += Size[n];
  1136. }
  1137. for (unsigned n = 0; n != Nodes; ++n) {
  1138. rootBranch().stop(n) = Node[n].template get<Branch>().stop(Size[n]-1);
  1139. rootBranch().subtree(n) = Node[n];
  1140. }
  1141. rootSize = Nodes;
  1142. ++height;
  1143. return NewOffset;
  1144. }
  1145. /// visitNodes - Visit each external node.
  1146. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1147. void IntervalMap<KeyT, ValT, N, Traits>::
  1148. visitNodes(void (IntervalMap::*f)(IntervalMapImpl::NodeRef, unsigned Height)) {
  1149. if (!branched())
  1150. return;
  1151. SmallVector<IntervalMapImpl::NodeRef, 4> Refs, NextRefs;
  1152. // Collect level 0 nodes from the root.
  1153. for (unsigned i = 0; i != rootSize; ++i)
  1154. Refs.push_back(rootBranch().subtree(i));
  1155. // Visit all branch nodes.
  1156. for (unsigned h = height - 1; h; --h) {
  1157. for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
  1158. for (unsigned j = 0, s = Refs[i].size(); j != s; ++j)
  1159. NextRefs.push_back(Refs[i].subtree(j));
  1160. (this->*f)(Refs[i], h);
  1161. }
  1162. Refs.clear();
  1163. Refs.swap(NextRefs);
  1164. }
  1165. // Visit all leaf nodes.
  1166. for (unsigned i = 0, e = Refs.size(); i != e; ++i)
  1167. (this->*f)(Refs[i], 0);
  1168. }
  1169. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1170. void IntervalMap<KeyT, ValT, N, Traits>::
  1171. deleteNode(IntervalMapImpl::NodeRef Node, unsigned Level) {
  1172. if (Level)
  1173. deleteNode(&Node.get<Branch>());
  1174. else
  1175. deleteNode(&Node.get<Leaf>());
  1176. }
  1177. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1178. void IntervalMap<KeyT, ValT, N, Traits>::
  1179. clear() {
  1180. if (branched()) {
  1181. visitNodes(&IntervalMap::deleteNode);
  1182. switchRootToLeaf();
  1183. }
  1184. rootSize = 0;
  1185. }
  1186. //===----------------------------------------------------------------------===//
  1187. //--- IntervalMap::const_iterator ----//
  1188. //===----------------------------------------------------------------------===//
  1189. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1190. class IntervalMap<KeyT, ValT, N, Traits>::const_iterator {
  1191. friend class IntervalMap;
  1192. public:
  1193. using iterator_category = std::bidirectional_iterator_tag;
  1194. using value_type = ValT;
  1195. using difference_type = std::ptrdiff_t;
  1196. using pointer = value_type *;
  1197. using reference = value_type &;
  1198. protected:
  1199. // The map referred to.
  1200. IntervalMap *map = nullptr;
  1201. // We store a full path from the root to the current position.
  1202. // The path may be partially filled, but never between iterator calls.
  1203. IntervalMapImpl::Path path;
  1204. explicit const_iterator(const IntervalMap &map) :
  1205. map(const_cast<IntervalMap*>(&map)) {}
  1206. bool branched() const {
  1207. assert(map && "Invalid iterator");
  1208. return map->branched();
  1209. }
  1210. void setRoot(unsigned Offset) {
  1211. if (branched())
  1212. path.setRoot(&map->rootBranch(), map->rootSize, Offset);
  1213. else
  1214. path.setRoot(&map->rootLeaf(), map->rootSize, Offset);
  1215. }
  1216. void pathFillFind(KeyT x);
  1217. void treeFind(KeyT x);
  1218. void treeAdvanceTo(KeyT x);
  1219. /// unsafeStart - Writable access to start() for iterator.
  1220. KeyT &unsafeStart() const {
  1221. assert(valid() && "Cannot access invalid iterator");
  1222. return branched() ? path.leaf<Leaf>().start(path.leafOffset()) :
  1223. path.leaf<RootLeaf>().start(path.leafOffset());
  1224. }
  1225. /// unsafeStop - Writable access to stop() for iterator.
  1226. KeyT &unsafeStop() const {
  1227. assert(valid() && "Cannot access invalid iterator");
  1228. return branched() ? path.leaf<Leaf>().stop(path.leafOffset()) :
  1229. path.leaf<RootLeaf>().stop(path.leafOffset());
  1230. }
  1231. /// unsafeValue - Writable access to value() for iterator.
  1232. ValT &unsafeValue() const {
  1233. assert(valid() && "Cannot access invalid iterator");
  1234. return branched() ? path.leaf<Leaf>().value(path.leafOffset()) :
  1235. path.leaf<RootLeaf>().value(path.leafOffset());
  1236. }
  1237. public:
  1238. /// const_iterator - Create an iterator that isn't pointing anywhere.
  1239. const_iterator() = default;
  1240. /// setMap - Change the map iterated over. This call must be followed by a
  1241. /// call to goToBegin(), goToEnd(), or find()
  1242. void setMap(const IntervalMap &m) { map = const_cast<IntervalMap*>(&m); }
  1243. /// valid - Return true if the current position is valid, false for end().
  1244. bool valid() const { return path.valid(); }
  1245. /// atBegin - Return true if the current position is the first map entry.
  1246. bool atBegin() const { return path.atBegin(); }
  1247. /// start - Return the beginning of the current interval.
  1248. const KeyT &start() const { return unsafeStart(); }
  1249. /// stop - Return the end of the current interval.
  1250. const KeyT &stop() const { return unsafeStop(); }
  1251. /// value - Return the mapped value at the current interval.
  1252. const ValT &value() const { return unsafeValue(); }
  1253. const ValT &operator*() const { return value(); }
  1254. bool operator==(const const_iterator &RHS) const {
  1255. assert(map == RHS.map && "Cannot compare iterators from different maps");
  1256. if (!valid())
  1257. return !RHS.valid();
  1258. if (path.leafOffset() != RHS.path.leafOffset())
  1259. return false;
  1260. return &path.template leaf<Leaf>() == &RHS.path.template leaf<Leaf>();
  1261. }
  1262. bool operator!=(const const_iterator &RHS) const {
  1263. return !operator==(RHS);
  1264. }
  1265. /// goToBegin - Move to the first interval in map.
  1266. void goToBegin() {
  1267. setRoot(0);
  1268. if (branched())
  1269. path.fillLeft(map->height);
  1270. }
  1271. /// goToEnd - Move beyond the last interval in map.
  1272. void goToEnd() {
  1273. setRoot(map->rootSize);
  1274. }
  1275. /// preincrement - Move to the next interval.
  1276. const_iterator &operator++() {
  1277. assert(valid() && "Cannot increment end()");
  1278. if (++path.leafOffset() == path.leafSize() && branched())
  1279. path.moveRight(map->height);
  1280. return *this;
  1281. }
  1282. /// postincrement - Don't do that!
  1283. const_iterator operator++(int) {
  1284. const_iterator tmp = *this;
  1285. operator++();
  1286. return tmp;
  1287. }
  1288. /// predecrement - Move to the previous interval.
  1289. const_iterator &operator--() {
  1290. if (path.leafOffset() && (valid() || !branched()))
  1291. --path.leafOffset();
  1292. else
  1293. path.moveLeft(map->height);
  1294. return *this;
  1295. }
  1296. /// postdecrement - Don't do that!
  1297. const_iterator operator--(int) {
  1298. const_iterator tmp = *this;
  1299. operator--();
  1300. return tmp;
  1301. }
  1302. /// find - Move to the first interval with stop >= x, or end().
  1303. /// This is a full search from the root, the current position is ignored.
  1304. void find(KeyT x) {
  1305. if (branched())
  1306. treeFind(x);
  1307. else
  1308. setRoot(map->rootLeaf().findFrom(0, map->rootSize, x));
  1309. }
  1310. /// advanceTo - Move to the first interval with stop >= x, or end().
  1311. /// The search is started from the current position, and no earlier positions
  1312. /// can be found. This is much faster than find() for small moves.
  1313. void advanceTo(KeyT x) {
  1314. if (!valid())
  1315. return;
  1316. if (branched())
  1317. treeAdvanceTo(x);
  1318. else
  1319. path.leafOffset() =
  1320. map->rootLeaf().findFrom(path.leafOffset(), map->rootSize, x);
  1321. }
  1322. };
  1323. /// pathFillFind - Complete path by searching for x.
  1324. /// @param x Key to search for.
  1325. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1326. void IntervalMap<KeyT, ValT, N, Traits>::
  1327. const_iterator::pathFillFind(KeyT x) {
  1328. IntervalMapImpl::NodeRef NR = path.subtree(path.height());
  1329. for (unsigned i = map->height - path.height() - 1; i; --i) {
  1330. unsigned p = NR.get<Branch>().safeFind(0, x);
  1331. path.push(NR, p);
  1332. NR = NR.subtree(p);
  1333. }
  1334. path.push(NR, NR.get<Leaf>().safeFind(0, x));
  1335. }
  1336. /// treeFind - Find in a branched tree.
  1337. /// @param x Key to search for.
  1338. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1339. void IntervalMap<KeyT, ValT, N, Traits>::
  1340. const_iterator::treeFind(KeyT x) {
  1341. setRoot(map->rootBranch().findFrom(0, map->rootSize, x));
  1342. if (valid())
  1343. pathFillFind(x);
  1344. }
  1345. /// treeAdvanceTo - Find position after the current one.
  1346. /// @param x Key to search for.
  1347. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1348. void IntervalMap<KeyT, ValT, N, Traits>::
  1349. const_iterator::treeAdvanceTo(KeyT x) {
  1350. // Can we stay on the same leaf node?
  1351. if (!Traits::stopLess(path.leaf<Leaf>().stop(path.leafSize() - 1), x)) {
  1352. path.leafOffset() = path.leaf<Leaf>().safeFind(path.leafOffset(), x);
  1353. return;
  1354. }
  1355. // Drop the current leaf.
  1356. path.pop();
  1357. // Search towards the root for a usable subtree.
  1358. if (path.height()) {
  1359. for (unsigned l = path.height() - 1; l; --l) {
  1360. if (!Traits::stopLess(path.node<Branch>(l).stop(path.offset(l)), x)) {
  1361. // The branch node at l+1 is usable
  1362. path.offset(l + 1) =
  1363. path.node<Branch>(l + 1).safeFind(path.offset(l + 1), x);
  1364. return pathFillFind(x);
  1365. }
  1366. path.pop();
  1367. }
  1368. // Is the level-1 Branch usable?
  1369. if (!Traits::stopLess(map->rootBranch().stop(path.offset(0)), x)) {
  1370. path.offset(1) = path.node<Branch>(1).safeFind(path.offset(1), x);
  1371. return pathFillFind(x);
  1372. }
  1373. }
  1374. // We reached the root.
  1375. setRoot(map->rootBranch().findFrom(path.offset(0), map->rootSize, x));
  1376. if (valid())
  1377. pathFillFind(x);
  1378. }
  1379. //===----------------------------------------------------------------------===//
  1380. //--- IntervalMap::iterator ----//
  1381. //===----------------------------------------------------------------------===//
  1382. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1383. class IntervalMap<KeyT, ValT, N, Traits>::iterator : public const_iterator {
  1384. friend class IntervalMap;
  1385. using IdxPair = IntervalMapImpl::IdxPair;
  1386. explicit iterator(IntervalMap &map) : const_iterator(map) {}
  1387. void setNodeStop(unsigned Level, KeyT Stop);
  1388. bool insertNode(unsigned Level, IntervalMapImpl::NodeRef Node, KeyT Stop);
  1389. template <typename NodeT> bool overflow(unsigned Level);
  1390. void treeInsert(KeyT a, KeyT b, ValT y);
  1391. void eraseNode(unsigned Level);
  1392. void treeErase(bool UpdateRoot = true);
  1393. bool canCoalesceLeft(KeyT Start, ValT x);
  1394. bool canCoalesceRight(KeyT Stop, ValT x);
  1395. public:
  1396. /// iterator - Create null iterator.
  1397. iterator() = default;
  1398. /// setStart - Move the start of the current interval.
  1399. /// This may cause coalescing with the previous interval.
  1400. /// @param a New start key, must not overlap the previous interval.
  1401. void setStart(KeyT a);
  1402. /// setStop - Move the end of the current interval.
  1403. /// This may cause coalescing with the following interval.
  1404. /// @param b New stop key, must not overlap the following interval.
  1405. void setStop(KeyT b);
  1406. /// setValue - Change the mapped value of the current interval.
  1407. /// This may cause coalescing with the previous and following intervals.
  1408. /// @param x New value.
  1409. void setValue(ValT x);
  1410. /// setStartUnchecked - Move the start of the current interval without
  1411. /// checking for coalescing or overlaps.
  1412. /// This should only be used when it is known that coalescing is not required.
  1413. /// @param a New start key.
  1414. void setStartUnchecked(KeyT a) { this->unsafeStart() = a; }
  1415. /// setStopUnchecked - Move the end of the current interval without checking
  1416. /// for coalescing or overlaps.
  1417. /// This should only be used when it is known that coalescing is not required.
  1418. /// @param b New stop key.
  1419. void setStopUnchecked(KeyT b) {
  1420. this->unsafeStop() = b;
  1421. // Update keys in branch nodes as well.
  1422. if (this->path.atLastEntry(this->path.height()))
  1423. setNodeStop(this->path.height(), b);
  1424. }
  1425. /// setValueUnchecked - Change the mapped value of the current interval
  1426. /// without checking for coalescing.
  1427. /// @param x New value.
  1428. void setValueUnchecked(ValT x) { this->unsafeValue() = x; }
  1429. /// insert - Insert mapping [a;b] -> y before the current position.
  1430. void insert(KeyT a, KeyT b, ValT y);
  1431. /// erase - Erase the current interval.
  1432. void erase();
  1433. iterator &operator++() {
  1434. const_iterator::operator++();
  1435. return *this;
  1436. }
  1437. iterator operator++(int) {
  1438. iterator tmp = *this;
  1439. operator++();
  1440. return tmp;
  1441. }
  1442. iterator &operator--() {
  1443. const_iterator::operator--();
  1444. return *this;
  1445. }
  1446. iterator operator--(int) {
  1447. iterator tmp = *this;
  1448. operator--();
  1449. return tmp;
  1450. }
  1451. };
  1452. /// canCoalesceLeft - Can the current interval coalesce to the left after
  1453. /// changing start or value?
  1454. /// @param Start New start of current interval.
  1455. /// @param Value New value for current interval.
  1456. /// @return True when updating the current interval would enable coalescing.
  1457. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1458. bool IntervalMap<KeyT, ValT, N, Traits>::
  1459. iterator::canCoalesceLeft(KeyT Start, ValT Value) {
  1460. using namespace IntervalMapImpl;
  1461. Path &P = this->path;
  1462. if (!this->branched()) {
  1463. unsigned i = P.leafOffset();
  1464. RootLeaf &Node = P.leaf<RootLeaf>();
  1465. return i && Node.value(i-1) == Value &&
  1466. Traits::adjacent(Node.stop(i-1), Start);
  1467. }
  1468. // Branched.
  1469. if (unsigned i = P.leafOffset()) {
  1470. Leaf &Node = P.leaf<Leaf>();
  1471. return Node.value(i-1) == Value && Traits::adjacent(Node.stop(i-1), Start);
  1472. } else if (NodeRef NR = P.getLeftSibling(P.height())) {
  1473. unsigned i = NR.size() - 1;
  1474. Leaf &Node = NR.get<Leaf>();
  1475. return Node.value(i) == Value && Traits::adjacent(Node.stop(i), Start);
  1476. }
  1477. return false;
  1478. }
  1479. /// canCoalesceRight - Can the current interval coalesce to the right after
  1480. /// changing stop or value?
  1481. /// @param Stop New stop of current interval.
  1482. /// @param Value New value for current interval.
  1483. /// @return True when updating the current interval would enable coalescing.
  1484. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1485. bool IntervalMap<KeyT, ValT, N, Traits>::
  1486. iterator::canCoalesceRight(KeyT Stop, ValT Value) {
  1487. using namespace IntervalMapImpl;
  1488. Path &P = this->path;
  1489. unsigned i = P.leafOffset() + 1;
  1490. if (!this->branched()) {
  1491. if (i >= P.leafSize())
  1492. return false;
  1493. RootLeaf &Node = P.leaf<RootLeaf>();
  1494. return Node.value(i) == Value && Traits::adjacent(Stop, Node.start(i));
  1495. }
  1496. // Branched.
  1497. if (i < P.leafSize()) {
  1498. Leaf &Node = P.leaf<Leaf>();
  1499. return Node.value(i) == Value && Traits::adjacent(Stop, Node.start(i));
  1500. } else if (NodeRef NR = P.getRightSibling(P.height())) {
  1501. Leaf &Node = NR.get<Leaf>();
  1502. return Node.value(0) == Value && Traits::adjacent(Stop, Node.start(0));
  1503. }
  1504. return false;
  1505. }
  1506. /// setNodeStop - Update the stop key of the current node at level and above.
  1507. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1508. void IntervalMap<KeyT, ValT, N, Traits>::
  1509. iterator::setNodeStop(unsigned Level, KeyT Stop) {
  1510. // There are no references to the root node, so nothing to update.
  1511. if (!Level)
  1512. return;
  1513. IntervalMapImpl::Path &P = this->path;
  1514. // Update nodes pointing to the current node.
  1515. while (--Level) {
  1516. P.node<Branch>(Level).stop(P.offset(Level)) = Stop;
  1517. if (!P.atLastEntry(Level))
  1518. return;
  1519. }
  1520. // Update root separately since it has a different layout.
  1521. P.node<RootBranch>(Level).stop(P.offset(Level)) = Stop;
  1522. }
  1523. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1524. void IntervalMap<KeyT, ValT, N, Traits>::
  1525. iterator::setStart(KeyT a) {
  1526. assert(Traits::nonEmpty(a, this->stop()) && "Cannot move start beyond stop");
  1527. KeyT &CurStart = this->unsafeStart();
  1528. if (!Traits::startLess(a, CurStart) || !canCoalesceLeft(a, this->value())) {
  1529. CurStart = a;
  1530. return;
  1531. }
  1532. // Coalesce with the interval to the left.
  1533. --*this;
  1534. a = this->start();
  1535. erase();
  1536. setStartUnchecked(a);
  1537. }
  1538. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1539. void IntervalMap<KeyT, ValT, N, Traits>::
  1540. iterator::setStop(KeyT b) {
  1541. assert(Traits::nonEmpty(this->start(), b) && "Cannot move stop beyond start");
  1542. if (Traits::startLess(b, this->stop()) ||
  1543. !canCoalesceRight(b, this->value())) {
  1544. setStopUnchecked(b);
  1545. return;
  1546. }
  1547. // Coalesce with interval to the right.
  1548. KeyT a = this->start();
  1549. erase();
  1550. setStartUnchecked(a);
  1551. }
  1552. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1553. void IntervalMap<KeyT, ValT, N, Traits>::
  1554. iterator::setValue(ValT x) {
  1555. setValueUnchecked(x);
  1556. if (canCoalesceRight(this->stop(), x)) {
  1557. KeyT a = this->start();
  1558. erase();
  1559. setStartUnchecked(a);
  1560. }
  1561. if (canCoalesceLeft(this->start(), x)) {
  1562. --*this;
  1563. KeyT a = this->start();
  1564. erase();
  1565. setStartUnchecked(a);
  1566. }
  1567. }
  1568. /// insertNode - insert a node before the current path at level.
  1569. /// Leave the current path pointing at the new node.
  1570. /// @param Level path index of the node to be inserted.
  1571. /// @param Node The node to be inserted.
  1572. /// @param Stop The last index in the new node.
  1573. /// @return True if the tree height was increased.
  1574. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1575. bool IntervalMap<KeyT, ValT, N, Traits>::
  1576. iterator::insertNode(unsigned Level, IntervalMapImpl::NodeRef Node, KeyT Stop) {
  1577. assert(Level && "Cannot insert next to the root");
  1578. bool SplitRoot = false;
  1579. IntervalMap &IM = *this->map;
  1580. IntervalMapImpl::Path &P = this->path;
  1581. if (Level == 1) {
  1582. // Insert into the root branch node.
  1583. if (IM.rootSize < RootBranch::Capacity) {
  1584. IM.rootBranch().insert(P.offset(0), IM.rootSize, Node, Stop);
  1585. P.setSize(0, ++IM.rootSize);
  1586. P.reset(Level);
  1587. return SplitRoot;
  1588. }
  1589. // We need to split the root while keeping our position.
  1590. SplitRoot = true;
  1591. IdxPair Offset = IM.splitRoot(P.offset(0));
  1592. P.replaceRoot(&IM.rootBranch(), IM.rootSize, Offset);
  1593. // Fall through to insert at the new higher level.
  1594. ++Level;
  1595. }
  1596. // When inserting before end(), make sure we have a valid path.
  1597. P.legalizeForInsert(--Level);
  1598. // Insert into the branch node at Level-1.
  1599. if (P.size(Level) == Branch::Capacity) {
  1600. // Branch node is full, handle handle the overflow.
  1601. assert(!SplitRoot && "Cannot overflow after splitting the root");
  1602. SplitRoot = overflow<Branch>(Level);
  1603. Level += SplitRoot;
  1604. }
  1605. P.node<Branch>(Level).insert(P.offset(Level), P.size(Level), Node, Stop);
  1606. P.setSize(Level, P.size(Level) + 1);
  1607. if (P.atLastEntry(Level))
  1608. setNodeStop(Level, Stop);
  1609. P.reset(Level + 1);
  1610. return SplitRoot;
  1611. }
  1612. // insert
  1613. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1614. void IntervalMap<KeyT, ValT, N, Traits>::
  1615. iterator::insert(KeyT a, KeyT b, ValT y) {
  1616. if (this->branched())
  1617. return treeInsert(a, b, y);
  1618. IntervalMap &IM = *this->map;
  1619. IntervalMapImpl::Path &P = this->path;
  1620. // Try simple root leaf insert.
  1621. unsigned Size = IM.rootLeaf().insertFrom(P.leafOffset(), IM.rootSize, a, b, y);
  1622. // Was the root node insert successful?
  1623. if (Size <= RootLeaf::Capacity) {
  1624. P.setSize(0, IM.rootSize = Size);
  1625. return;
  1626. }
  1627. // Root leaf node is full, we must branch.
  1628. IdxPair Offset = IM.branchRoot(P.leafOffset());
  1629. P.replaceRoot(&IM.rootBranch(), IM.rootSize, Offset);
  1630. // Now it fits in the new leaf.
  1631. treeInsert(a, b, y);
  1632. }
  1633. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1634. void IntervalMap<KeyT, ValT, N, Traits>::
  1635. iterator::treeInsert(KeyT a, KeyT b, ValT y) {
  1636. using namespace IntervalMapImpl;
  1637. Path &P = this->path;
  1638. if (!P.valid())
  1639. P.legalizeForInsert(this->map->height);
  1640. // Check if this insertion will extend the node to the left.
  1641. if (P.leafOffset() == 0 && Traits::startLess(a, P.leaf<Leaf>().start(0))) {
  1642. // Node is growing to the left, will it affect a left sibling node?
  1643. if (NodeRef Sib = P.getLeftSibling(P.height())) {
  1644. Leaf &SibLeaf = Sib.get<Leaf>();
  1645. unsigned SibOfs = Sib.size() - 1;
  1646. if (SibLeaf.value(SibOfs) == y &&
  1647. Traits::adjacent(SibLeaf.stop(SibOfs), a)) {
  1648. // This insertion will coalesce with the last entry in SibLeaf. We can
  1649. // handle it in two ways:
  1650. // 1. Extend SibLeaf.stop to b and be done, or
  1651. // 2. Extend a to SibLeaf, erase the SibLeaf entry and continue.
  1652. // We prefer 1., but need 2 when coalescing to the right as well.
  1653. Leaf &CurLeaf = P.leaf<Leaf>();
  1654. P.moveLeft(P.height());
  1655. if (Traits::stopLess(b, CurLeaf.start(0)) &&
  1656. (y != CurLeaf.value(0) || !Traits::adjacent(b, CurLeaf.start(0)))) {
  1657. // Easy, just extend SibLeaf and we're done.
  1658. setNodeStop(P.height(), SibLeaf.stop(SibOfs) = b);
  1659. return;
  1660. } else {
  1661. // We have both left and right coalescing. Erase the old SibLeaf entry
  1662. // and continue inserting the larger interval.
  1663. a = SibLeaf.start(SibOfs);
  1664. treeErase(/* UpdateRoot= */false);
  1665. }
  1666. }
  1667. } else {
  1668. // No left sibling means we are at begin(). Update cached bound.
  1669. this->map->rootBranchStart() = a;
  1670. }
  1671. }
  1672. // When we are inserting at the end of a leaf node, we must update stops.
  1673. unsigned Size = P.leafSize();
  1674. bool Grow = P.leafOffset() == Size;
  1675. Size = P.leaf<Leaf>().insertFrom(P.leafOffset(), Size, a, b, y);
  1676. // Leaf insertion unsuccessful? Overflow and try again.
  1677. if (Size > Leaf::Capacity) {
  1678. overflow<Leaf>(P.height());
  1679. Grow = P.leafOffset() == P.leafSize();
  1680. Size = P.leaf<Leaf>().insertFrom(P.leafOffset(), P.leafSize(), a, b, y);
  1681. assert(Size <= Leaf::Capacity && "overflow() didn't make room");
  1682. }
  1683. // Inserted, update offset and leaf size.
  1684. P.setSize(P.height(), Size);
  1685. // Insert was the last node entry, update stops.
  1686. if (Grow)
  1687. setNodeStop(P.height(), b);
  1688. }
  1689. /// erase - erase the current interval and move to the next position.
  1690. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1691. void IntervalMap<KeyT, ValT, N, Traits>::
  1692. iterator::erase() {
  1693. IntervalMap &IM = *this->map;
  1694. IntervalMapImpl::Path &P = this->path;
  1695. assert(P.valid() && "Cannot erase end()");
  1696. if (this->branched())
  1697. return treeErase();
  1698. IM.rootLeaf().erase(P.leafOffset(), IM.rootSize);
  1699. P.setSize(0, --IM.rootSize);
  1700. }
  1701. /// treeErase - erase() for a branched tree.
  1702. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1703. void IntervalMap<KeyT, ValT, N, Traits>::
  1704. iterator::treeErase(bool UpdateRoot) {
  1705. IntervalMap &IM = *this->map;
  1706. IntervalMapImpl::Path &P = this->path;
  1707. Leaf &Node = P.leaf<Leaf>();
  1708. // Nodes are not allowed to become empty.
  1709. if (P.leafSize() == 1) {
  1710. IM.deleteNode(&Node);
  1711. eraseNode(IM.height);
  1712. // Update rootBranchStart if we erased begin().
  1713. if (UpdateRoot && IM.branched() && P.valid() && P.atBegin())
  1714. IM.rootBranchStart() = P.leaf<Leaf>().start(0);
  1715. return;
  1716. }
  1717. // Erase current entry.
  1718. Node.erase(P.leafOffset(), P.leafSize());
  1719. unsigned NewSize = P.leafSize() - 1;
  1720. P.setSize(IM.height, NewSize);
  1721. // When we erase the last entry, update stop and move to a legal position.
  1722. if (P.leafOffset() == NewSize) {
  1723. setNodeStop(IM.height, Node.stop(NewSize - 1));
  1724. P.moveRight(IM.height);
  1725. } else if (UpdateRoot && P.atBegin())
  1726. IM.rootBranchStart() = P.leaf<Leaf>().start(0);
  1727. }
  1728. /// eraseNode - Erase the current node at Level from its parent and move path to
  1729. /// the first entry of the next sibling node.
  1730. /// The node must be deallocated by the caller.
  1731. /// @param Level 1..height, the root node cannot be erased.
  1732. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1733. void IntervalMap<KeyT, ValT, N, Traits>::
  1734. iterator::eraseNode(unsigned Level) {
  1735. assert(Level && "Cannot erase root node");
  1736. IntervalMap &IM = *this->map;
  1737. IntervalMapImpl::Path &P = this->path;
  1738. if (--Level == 0) {
  1739. IM.rootBranch().erase(P.offset(0), IM.rootSize);
  1740. P.setSize(0, --IM.rootSize);
  1741. // If this cleared the root, switch to height=0.
  1742. if (IM.empty()) {
  1743. IM.switchRootToLeaf();
  1744. this->setRoot(0);
  1745. return;
  1746. }
  1747. } else {
  1748. // Remove node ref from branch node at Level.
  1749. Branch &Parent = P.node<Branch>(Level);
  1750. if (P.size(Level) == 1) {
  1751. // Branch node became empty, remove it recursively.
  1752. IM.deleteNode(&Parent);
  1753. eraseNode(Level);
  1754. } else {
  1755. // Branch node won't become empty.
  1756. Parent.erase(P.offset(Level), P.size(Level));
  1757. unsigned NewSize = P.size(Level) - 1;
  1758. P.setSize(Level, NewSize);
  1759. // If we removed the last branch, update stop and move to a legal pos.
  1760. if (P.offset(Level) == NewSize) {
  1761. setNodeStop(Level, Parent.stop(NewSize - 1));
  1762. P.moveRight(Level);
  1763. }
  1764. }
  1765. }
  1766. // Update path cache for the new right sibling position.
  1767. if (P.valid()) {
  1768. P.reset(Level + 1);
  1769. P.offset(Level + 1) = 0;
  1770. }
  1771. }
  1772. /// overflow - Distribute entries of the current node evenly among
  1773. /// its siblings and ensure that the current node is not full.
  1774. /// This may require allocating a new node.
  1775. /// @tparam NodeT The type of node at Level (Leaf or Branch).
  1776. /// @param Level path index of the overflowing node.
  1777. /// @return True when the tree height was changed.
  1778. template <typename KeyT, typename ValT, unsigned N, typename Traits>
  1779. template <typename NodeT>
  1780. bool IntervalMap<KeyT, ValT, N, Traits>::
  1781. iterator::overflow(unsigned Level) {
  1782. using namespace IntervalMapImpl;
  1783. Path &P = this->path;
  1784. unsigned CurSize[4];
  1785. NodeT *Node[4];
  1786. unsigned Nodes = 0;
  1787. unsigned Elements = 0;
  1788. unsigned Offset = P.offset(Level);
  1789. // Do we have a left sibling?
  1790. NodeRef LeftSib = P.getLeftSibling(Level);
  1791. if (LeftSib) {
  1792. Offset += Elements = CurSize[Nodes] = LeftSib.size();
  1793. Node[Nodes++] = &LeftSib.get<NodeT>();
  1794. }
  1795. // Current node.
  1796. Elements += CurSize[Nodes] = P.size(Level);
  1797. Node[Nodes++] = &P.node<NodeT>(Level);
  1798. // Do we have a right sibling?
  1799. NodeRef RightSib = P.getRightSibling(Level);
  1800. if (RightSib) {
  1801. Elements += CurSize[Nodes] = RightSib.size();
  1802. Node[Nodes++] = &RightSib.get<NodeT>();
  1803. }
  1804. // Do we need to allocate a new node?
  1805. unsigned NewNode = 0;
  1806. if (Elements + 1 > Nodes * NodeT::Capacity) {
  1807. // Insert NewNode at the penultimate position, or after a single node.
  1808. NewNode = Nodes == 1 ? 1 : Nodes - 1;
  1809. CurSize[Nodes] = CurSize[NewNode];
  1810. Node[Nodes] = Node[NewNode];
  1811. CurSize[NewNode] = 0;
  1812. Node[NewNode] = this->map->template newNode<NodeT>();
  1813. ++Nodes;
  1814. }
  1815. // Compute the new element distribution.
  1816. unsigned NewSize[4];
  1817. IdxPair NewOffset = distribute(Nodes, Elements, NodeT::Capacity,
  1818. CurSize, NewSize, Offset, true);
  1819. adjustSiblingSizes(Node, Nodes, CurSize, NewSize);
  1820. // Move current location to the leftmost node.
  1821. if (LeftSib)
  1822. P.moveLeft(Level);
  1823. // Elements have been rearranged, now update node sizes and stops.
  1824. bool SplitRoot = false;
  1825. unsigned Pos = 0;
  1826. while (true) {
  1827. KeyT Stop = Node[Pos]->stop(NewSize[Pos]-1);
  1828. if (NewNode && Pos == NewNode) {
  1829. SplitRoot = insertNode(Level, NodeRef(Node[Pos], NewSize[Pos]), Stop);
  1830. Level += SplitRoot;
  1831. } else {
  1832. P.setSize(Level, NewSize[Pos]);
  1833. setNodeStop(Level, Stop);
  1834. }
  1835. if (Pos + 1 == Nodes)
  1836. break;
  1837. P.moveRight(Level);
  1838. ++Pos;
  1839. }
  1840. // Where was I? Find NewOffset.
  1841. while(Pos != NewOffset.first) {
  1842. P.moveLeft(Level);
  1843. --Pos;
  1844. }
  1845. P.offset(Level) = NewOffset.second;
  1846. return SplitRoot;
  1847. }
  1848. //===----------------------------------------------------------------------===//
  1849. //--- IntervalMapOverlaps ----//
  1850. //===----------------------------------------------------------------------===//
  1851. /// IntervalMapOverlaps - Iterate over the overlaps of mapped intervals in two
  1852. /// IntervalMaps. The maps may be different, but the KeyT and Traits types
  1853. /// should be the same.
  1854. ///
  1855. /// Typical uses:
  1856. ///
  1857. /// 1. Test for overlap:
  1858. /// bool overlap = IntervalMapOverlaps(a, b).valid();
  1859. ///
  1860. /// 2. Enumerate overlaps:
  1861. /// for (IntervalMapOverlaps I(a, b); I.valid() ; ++I) { ... }
  1862. ///
  1863. template <typename MapA, typename MapB>
  1864. class IntervalMapOverlaps {
  1865. using KeyType = typename MapA::KeyType;
  1866. using Traits = typename MapA::KeyTraits;
  1867. typename MapA::const_iterator posA;
  1868. typename MapB::const_iterator posB;
  1869. /// advance - Move posA and posB forward until reaching an overlap, or until
  1870. /// either meets end.
  1871. /// Don't move the iterators if they are already overlapping.
  1872. void advance() {
  1873. if (!valid())
  1874. return;
  1875. if (Traits::stopLess(posA.stop(), posB.start())) {
  1876. // A ends before B begins. Catch up.
  1877. posA.advanceTo(posB.start());
  1878. if (!posA.valid() || !Traits::stopLess(posB.stop(), posA.start()))
  1879. return;
  1880. } else if (Traits::stopLess(posB.stop(), posA.start())) {
  1881. // B ends before A begins. Catch up.
  1882. posB.advanceTo(posA.start());
  1883. if (!posB.valid() || !Traits::stopLess(posA.stop(), posB.start()))
  1884. return;
  1885. } else
  1886. // Already overlapping.
  1887. return;
  1888. while (true) {
  1889. // Make a.end > b.start.
  1890. posA.advanceTo(posB.start());
  1891. if (!posA.valid() || !Traits::stopLess(posB.stop(), posA.start()))
  1892. return;
  1893. // Make b.end > a.start.
  1894. posB.advanceTo(posA.start());
  1895. if (!posB.valid() || !Traits::stopLess(posA.stop(), posB.start()))
  1896. return;
  1897. }
  1898. }
  1899. public:
  1900. /// IntervalMapOverlaps - Create an iterator for the overlaps of a and b.
  1901. IntervalMapOverlaps(const MapA &a, const MapB &b)
  1902. : posA(b.empty() ? a.end() : a.find(b.start())),
  1903. posB(posA.valid() ? b.find(posA.start()) : b.end()) { advance(); }
  1904. /// valid - Return true if iterator is at an overlap.
  1905. bool valid() const {
  1906. return posA.valid() && posB.valid();
  1907. }
  1908. /// a - access the left hand side in the overlap.
  1909. const typename MapA::const_iterator &a() const { return posA; }
  1910. /// b - access the right hand side in the overlap.
  1911. const typename MapB::const_iterator &b() const { return posB; }
  1912. /// start - Beginning of the overlapping interval.
  1913. KeyType start() const {
  1914. KeyType ak = a().start();
  1915. KeyType bk = b().start();
  1916. return Traits::startLess(ak, bk) ? bk : ak;
  1917. }
  1918. /// stop - End of the overlapping interval.
  1919. KeyType stop() const {
  1920. KeyType ak = a().stop();
  1921. KeyType bk = b().stop();
  1922. return Traits::startLess(ak, bk) ? ak : bk;
  1923. }
  1924. /// skipA - Move to the next overlap that doesn't involve a().
  1925. void skipA() {
  1926. ++posA;
  1927. advance();
  1928. }
  1929. /// skipB - Move to the next overlap that doesn't involve b().
  1930. void skipB() {
  1931. ++posB;
  1932. advance();
  1933. }
  1934. /// Preincrement - Move to the next overlap.
  1935. IntervalMapOverlaps &operator++() {
  1936. // Bump the iterator that ends first. The other one may have more overlaps.
  1937. if (Traits::startLess(posB.stop(), posA.stop()))
  1938. skipB();
  1939. else
  1940. skipA();
  1941. return *this;
  1942. }
  1943. /// advanceTo - Move to the first overlapping interval with
  1944. /// stopLess(x, stop()).
  1945. void advanceTo(KeyType x) {
  1946. if (!valid())
  1947. return;
  1948. // Make sure advanceTo sees monotonic keys.
  1949. if (Traits::stopLess(posA.stop(), x))
  1950. posA.advanceTo(x);
  1951. if (Traits::stopLess(posB.stop(), x))
  1952. posB.advanceTo(x);
  1953. advance();
  1954. }
  1955. };
  1956. } // end namespace llvm
  1957. #endif // LLVM_ADT_INTERVALMAP_H
  1958. #ifdef __GNUC__
  1959. #pragma GCC diagnostic pop
  1960. #endif