DeltaTree.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. //===--- DeltaTree.cpp - B-Tree for Rewrite Delta tracking ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the DeltaTree and related classes.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Rewrite/DeltaTree.h"
  14. #include "llvm/Support/Casting.h"
  15. #include <cstring>
  16. #include <cstdio>
  17. using namespace clang;
  18. using llvm::cast;
  19. using llvm::dyn_cast;
  20. /// The DeltaTree class is a multiway search tree (BTree) structure with some
  21. /// fancy features. B-Trees are generally more memory and cache efficient
  22. /// than binary trees, because they store multiple keys/values in each node.
  23. ///
  24. /// DeltaTree implements a key/value mapping from FileIndex to Delta, allowing
  25. /// fast lookup by FileIndex. However, an added (important) bonus is that it
  26. /// can also efficiently tell us the full accumulated delta for a specific
  27. /// file offset as well, without traversing the whole tree.
  28. ///
  29. /// The nodes of the tree are made up of instances of two classes:
  30. /// DeltaTreeNode and DeltaTreeInteriorNode. The later subclasses the
  31. /// former and adds children pointers. Each node knows the full delta of all
  32. /// entries (recursively) contained inside of it, which allows us to get the
  33. /// full delta implied by a whole subtree in constant time.
  34. namespace {
  35. /// SourceDelta - As code in the original input buffer is added and deleted,
  36. /// SourceDelta records are used to keep track of how the input SourceLocation
  37. /// object is mapped into the output buffer.
  38. struct SourceDelta {
  39. unsigned FileLoc;
  40. int Delta;
  41. static SourceDelta get(unsigned Loc, int D) {
  42. SourceDelta Delta;
  43. Delta.FileLoc = Loc;
  44. Delta.Delta = D;
  45. return Delta;
  46. }
  47. };
  48. /// DeltaTreeNode - The common part of all nodes.
  49. ///
  50. class DeltaTreeNode {
  51. public:
  52. struct InsertResult {
  53. DeltaTreeNode *LHS, *RHS;
  54. SourceDelta Split;
  55. };
  56. private:
  57. friend class DeltaTreeInteriorNode;
  58. /// WidthFactor - This controls the number of K/V slots held in the BTree:
  59. /// how wide it is. Each level of the BTree is guaranteed to have at least
  60. /// WidthFactor-1 K/V pairs (except the root) and may have at most
  61. /// 2*WidthFactor-1 K/V pairs.
  62. enum { WidthFactor = 8 };
  63. /// Values - This tracks the SourceDelta's currently in this node.
  64. ///
  65. SourceDelta Values[2*WidthFactor-1];
  66. /// NumValuesUsed - This tracks the number of values this node currently
  67. /// holds.
  68. unsigned char NumValuesUsed;
  69. /// IsLeaf - This is true if this is a leaf of the btree. If false, this is
  70. /// an interior node, and is actually an instance of DeltaTreeInteriorNode.
  71. bool IsLeaf;
  72. /// FullDelta - This is the full delta of all the values in this node and
  73. /// all children nodes.
  74. int FullDelta;
  75. public:
  76. DeltaTreeNode(bool isLeaf = true)
  77. : NumValuesUsed(0), IsLeaf(isLeaf), FullDelta(0) {}
  78. bool isLeaf() const { return IsLeaf; }
  79. int getFullDelta() const { return FullDelta; }
  80. bool isFull() const { return NumValuesUsed == 2*WidthFactor-1; }
  81. unsigned getNumValuesUsed() const { return NumValuesUsed; }
  82. const SourceDelta &getValue(unsigned i) const {
  83. assert(i < NumValuesUsed && "Invalid value #");
  84. return Values[i];
  85. }
  86. SourceDelta &getValue(unsigned i) {
  87. assert(i < NumValuesUsed && "Invalid value #");
  88. return Values[i];
  89. }
  90. /// DoInsertion - Do an insertion of the specified FileIndex/Delta pair into
  91. /// this node. If insertion is easy, do it and return false. Otherwise,
  92. /// split the node, populate InsertRes with info about the split, and return
  93. /// true.
  94. bool DoInsertion(unsigned FileIndex, int Delta, InsertResult *InsertRes);
  95. void DoSplit(InsertResult &InsertRes);
  96. /// RecomputeFullDeltaLocally - Recompute the FullDelta field by doing a
  97. /// local walk over our contained deltas.
  98. void RecomputeFullDeltaLocally();
  99. void Destroy();
  100. static inline bool classof(const DeltaTreeNode *) { return true; }
  101. };
  102. } // end anonymous namespace
  103. namespace {
  104. /// DeltaTreeInteriorNode - When isLeaf = false, a node has child pointers.
  105. /// This class tracks them.
  106. class DeltaTreeInteriorNode : public DeltaTreeNode {
  107. DeltaTreeNode *Children[2*WidthFactor];
  108. ~DeltaTreeInteriorNode() {
  109. for (unsigned i = 0, e = NumValuesUsed+1; i != e; ++i)
  110. Children[i]->Destroy();
  111. }
  112. friend class DeltaTreeNode;
  113. public:
  114. DeltaTreeInteriorNode() : DeltaTreeNode(false /*nonleaf*/) {}
  115. DeltaTreeInteriorNode(DeltaTreeNode *FirstChild)
  116. : DeltaTreeNode(false /*nonleaf*/) {
  117. FullDelta = FirstChild->FullDelta;
  118. Children[0] = FirstChild;
  119. }
  120. DeltaTreeInteriorNode(const InsertResult &IR)
  121. : DeltaTreeNode(false /*nonleaf*/) {
  122. Children[0] = IR.LHS;
  123. Children[1] = IR.RHS;
  124. Values[0] = IR.Split;
  125. FullDelta = IR.LHS->getFullDelta()+IR.RHS->getFullDelta()+IR.Split.Delta;
  126. NumValuesUsed = 1;
  127. }
  128. const DeltaTreeNode *getChild(unsigned i) const {
  129. assert(i < getNumValuesUsed()+1 && "Invalid child");
  130. return Children[i];
  131. }
  132. DeltaTreeNode *getChild(unsigned i) {
  133. assert(i < getNumValuesUsed()+1 && "Invalid child");
  134. return Children[i];
  135. }
  136. static inline bool classof(const DeltaTreeInteriorNode *) { return true; }
  137. static inline bool classof(const DeltaTreeNode *N) { return !N->isLeaf(); }
  138. };
  139. }
  140. /// Destroy - A 'virtual' destructor.
  141. void DeltaTreeNode::Destroy() {
  142. if (isLeaf())
  143. delete this;
  144. else
  145. delete cast<DeltaTreeInteriorNode>(this);
  146. }
  147. /// RecomputeFullDeltaLocally - Recompute the FullDelta field by doing a
  148. /// local walk over our contained deltas.
  149. void DeltaTreeNode::RecomputeFullDeltaLocally() {
  150. int NewFullDelta = 0;
  151. for (unsigned i = 0, e = getNumValuesUsed(); i != e; ++i)
  152. NewFullDelta += Values[i].Delta;
  153. if (DeltaTreeInteriorNode *IN = dyn_cast<DeltaTreeInteriorNode>(this))
  154. for (unsigned i = 0, e = getNumValuesUsed()+1; i != e; ++i)
  155. NewFullDelta += IN->getChild(i)->getFullDelta();
  156. FullDelta = NewFullDelta;
  157. }
  158. /// DoInsertion - Do an insertion of the specified FileIndex/Delta pair into
  159. /// this node. If insertion is easy, do it and return false. Otherwise,
  160. /// split the node, populate InsertRes with info about the split, and return
  161. /// true.
  162. bool DeltaTreeNode::DoInsertion(unsigned FileIndex, int Delta,
  163. InsertResult *InsertRes) {
  164. // Maintain full delta for this node.
  165. FullDelta += Delta;
  166. // Find the insertion point, the first delta whose index is >= FileIndex.
  167. unsigned i = 0, e = getNumValuesUsed();
  168. while (i != e && FileIndex > getValue(i).FileLoc)
  169. ++i;
  170. // If we found an a record for exactly this file index, just merge this
  171. // value into the pre-existing record and finish early.
  172. if (i != e && getValue(i).FileLoc == FileIndex) {
  173. // NOTE: Delta could drop to zero here. This means that the delta entry is
  174. // useless and could be removed. Supporting erases is more complex than
  175. // leaving an entry with Delta=0, so we just leave an entry with Delta=0 in
  176. // the tree.
  177. Values[i].Delta += Delta;
  178. return false;
  179. }
  180. // Otherwise, we found an insertion point, and we know that the value at the
  181. // specified index is > FileIndex. Handle the leaf case first.
  182. if (isLeaf()) {
  183. if (!isFull()) {
  184. // For an insertion into a non-full leaf node, just insert the value in
  185. // its sorted position. This requires moving later values over.
  186. if (i != e)
  187. memmove(&Values[i+1], &Values[i], sizeof(Values[0])*(e-i));
  188. Values[i] = SourceDelta::get(FileIndex, Delta);
  189. ++NumValuesUsed;
  190. return false;
  191. }
  192. // Otherwise, if this is leaf is full, split the node at its median, insert
  193. // the value into one of the children, and return the result.
  194. assert(InsertRes && "No result location specified");
  195. DoSplit(*InsertRes);
  196. if (InsertRes->Split.FileLoc > FileIndex)
  197. InsertRes->LHS->DoInsertion(FileIndex, Delta, 0 /*can't fail*/);
  198. else
  199. InsertRes->RHS->DoInsertion(FileIndex, Delta, 0 /*can't fail*/);
  200. return true;
  201. }
  202. // Otherwise, this is an interior node. Send the request down the tree.
  203. DeltaTreeInteriorNode *IN = cast<DeltaTreeInteriorNode>(this);
  204. if (!IN->Children[i]->DoInsertion(FileIndex, Delta, InsertRes))
  205. return false; // If there was space in the child, just return.
  206. // Okay, this split the subtree, producing a new value and two children to
  207. // insert here. If this node is non-full, we can just insert it directly.
  208. if (!isFull()) {
  209. // Now that we have two nodes and a new element, insert the perclated value
  210. // into ourself by moving all the later values/children down, then inserting
  211. // the new one.
  212. if (i != e)
  213. memmove(&IN->Children[i+2], &IN->Children[i+1],
  214. (e-i)*sizeof(IN->Children[0]));
  215. IN->Children[i] = InsertRes->LHS;
  216. IN->Children[i+1] = InsertRes->RHS;
  217. if (e != i)
  218. memmove(&Values[i+1], &Values[i], (e-i)*sizeof(Values[0]));
  219. Values[i] = InsertRes->Split;
  220. ++NumValuesUsed;
  221. return false;
  222. }
  223. // Finally, if this interior node was full and a node is percolated up, split
  224. // ourself and return that up the chain. Start by saving all our info to
  225. // avoid having the split clobber it.
  226. IN->Children[i] = InsertRes->LHS;
  227. DeltaTreeNode *SubRHS = InsertRes->RHS;
  228. SourceDelta SubSplit = InsertRes->Split;
  229. // Do the split.
  230. DoSplit(*InsertRes);
  231. // Figure out where to insert SubRHS/NewSplit.
  232. DeltaTreeInteriorNode *InsertSide;
  233. if (SubSplit.FileLoc < InsertRes->Split.FileLoc)
  234. InsertSide = cast<DeltaTreeInteriorNode>(InsertRes->LHS);
  235. else
  236. InsertSide = cast<DeltaTreeInteriorNode>(InsertRes->RHS);
  237. // We now have a non-empty interior node 'InsertSide' to insert
  238. // SubRHS/SubSplit into. Find out where to insert SubSplit.
  239. // Find the insertion point, the first delta whose index is >SubSplit.FileLoc.
  240. i = 0; e = InsertSide->getNumValuesUsed();
  241. while (i != e && SubSplit.FileLoc > InsertSide->getValue(i).FileLoc)
  242. ++i;
  243. // Now we know that i is the place to insert the split value into. Insert it
  244. // and the child right after it.
  245. if (i != e)
  246. memmove(&InsertSide->Children[i+2], &InsertSide->Children[i+1],
  247. (e-i)*sizeof(IN->Children[0]));
  248. InsertSide->Children[i+1] = SubRHS;
  249. if (e != i)
  250. memmove(&InsertSide->Values[i+1], &InsertSide->Values[i],
  251. (e-i)*sizeof(Values[0]));
  252. InsertSide->Values[i] = SubSplit;
  253. ++InsertSide->NumValuesUsed;
  254. InsertSide->FullDelta += SubSplit.Delta + SubRHS->getFullDelta();
  255. return true;
  256. }
  257. /// DoSplit - Split the currently full node (which has 2*WidthFactor-1 values)
  258. /// into two subtrees each with "WidthFactor-1" values and a pivot value.
  259. /// Return the pieces in InsertRes.
  260. void DeltaTreeNode::DoSplit(InsertResult &InsertRes) {
  261. assert(isFull() && "Why split a non-full node?");
  262. // Since this node is full, it contains 2*WidthFactor-1 values. We move
  263. // the first 'WidthFactor-1' values to the LHS child (which we leave in this
  264. // node), propagate one value up, and move the last 'WidthFactor-1' values
  265. // into the RHS child.
  266. // Create the new child node.
  267. DeltaTreeNode *NewNode;
  268. if (DeltaTreeInteriorNode *IN = dyn_cast<DeltaTreeInteriorNode>(this)) {
  269. // If this is an interior node, also move over 'WidthFactor' children
  270. // into the new node.
  271. DeltaTreeInteriorNode *New = new DeltaTreeInteriorNode();
  272. memcpy(&New->Children[0], &IN->Children[WidthFactor],
  273. WidthFactor*sizeof(IN->Children[0]));
  274. NewNode = New;
  275. } else {
  276. // Just create the new leaf node.
  277. NewNode = new DeltaTreeNode();
  278. }
  279. // Move over the last 'WidthFactor-1' values from here to NewNode.
  280. memcpy(&NewNode->Values[0], &Values[WidthFactor],
  281. (WidthFactor-1)*sizeof(Values[0]));
  282. // Decrease the number of values in the two nodes.
  283. NewNode->NumValuesUsed = NumValuesUsed = WidthFactor-1;
  284. // Recompute the two nodes' full delta.
  285. NewNode->RecomputeFullDeltaLocally();
  286. RecomputeFullDeltaLocally();
  287. InsertRes.LHS = this;
  288. InsertRes.RHS = NewNode;
  289. InsertRes.Split = Values[WidthFactor-1];
  290. }
  291. //===----------------------------------------------------------------------===//
  292. // DeltaTree Implementation
  293. //===----------------------------------------------------------------------===//
  294. //#define VERIFY_TREE
  295. #ifdef VERIFY_TREE
  296. /// VerifyTree - Walk the btree performing assertions on various properties to
  297. /// verify consistency. This is useful for debugging new changes to the tree.
  298. static void VerifyTree(const DeltaTreeNode *N) {
  299. const DeltaTreeInteriorNode *IN = dyn_cast<DeltaTreeInteriorNode>(N);
  300. if (IN == 0) {
  301. // Verify leaves, just ensure that FullDelta matches up and the elements
  302. // are in proper order.
  303. int FullDelta = 0;
  304. for (unsigned i = 0, e = N->getNumValuesUsed(); i != e; ++i) {
  305. if (i)
  306. assert(N->getValue(i-1).FileLoc < N->getValue(i).FileLoc);
  307. FullDelta += N->getValue(i).Delta;
  308. }
  309. assert(FullDelta == N->getFullDelta());
  310. return;
  311. }
  312. // Verify interior nodes: Ensure that FullDelta matches up and the
  313. // elements are in proper order and the children are in proper order.
  314. int FullDelta = 0;
  315. for (unsigned i = 0, e = IN->getNumValuesUsed(); i != e; ++i) {
  316. const SourceDelta &IVal = N->getValue(i);
  317. const DeltaTreeNode *IChild = IN->getChild(i);
  318. if (i)
  319. assert(IN->getValue(i-1).FileLoc < IVal.FileLoc);
  320. FullDelta += IVal.Delta;
  321. FullDelta += IChild->getFullDelta();
  322. // The largest value in child #i should be smaller than FileLoc.
  323. assert(IChild->getValue(IChild->getNumValuesUsed()-1).FileLoc <
  324. IVal.FileLoc);
  325. // The smallest value in child #i+1 should be larger than FileLoc.
  326. assert(IN->getChild(i+1)->getValue(0).FileLoc > IVal.FileLoc);
  327. VerifyTree(IChild);
  328. }
  329. FullDelta += IN->getChild(IN->getNumValuesUsed())->getFullDelta();
  330. assert(FullDelta == N->getFullDelta());
  331. }
  332. #endif // VERIFY_TREE
  333. static DeltaTreeNode *getRoot(void *Root) {
  334. return (DeltaTreeNode*)Root;
  335. }
  336. DeltaTree::DeltaTree() {
  337. Root = new DeltaTreeNode();
  338. }
  339. DeltaTree::DeltaTree(const DeltaTree &RHS) {
  340. // Currently we only support copying when the RHS is empty.
  341. assert(getRoot(RHS.Root)->getNumValuesUsed() == 0 &&
  342. "Can only copy empty tree");
  343. Root = new DeltaTreeNode();
  344. }
  345. DeltaTree::~DeltaTree() {
  346. getRoot(Root)->Destroy();
  347. }
  348. /// getDeltaAt - Return the accumulated delta at the specified file offset.
  349. /// This includes all insertions or delections that occurred *before* the
  350. /// specified file index.
  351. int DeltaTree::getDeltaAt(unsigned FileIndex) const {
  352. const DeltaTreeNode *Node = getRoot(Root);
  353. int Result = 0;
  354. // Walk down the tree.
  355. while (1) {
  356. // For all nodes, include any local deltas before the specified file
  357. // index by summing them up directly. Keep track of how many were
  358. // included.
  359. unsigned NumValsGreater = 0;
  360. for (unsigned e = Node->getNumValuesUsed(); NumValsGreater != e;
  361. ++NumValsGreater) {
  362. const SourceDelta &Val = Node->getValue(NumValsGreater);
  363. if (Val.FileLoc >= FileIndex)
  364. break;
  365. Result += Val.Delta;
  366. }
  367. // If we have an interior node, include information about children and
  368. // recurse. Otherwise, if we have a leaf, we're done.
  369. const DeltaTreeInteriorNode *IN = dyn_cast<DeltaTreeInteriorNode>(Node);
  370. if (!IN) return Result;
  371. // Include any children to the left of the values we skipped, all of
  372. // their deltas should be included as well.
  373. for (unsigned i = 0; i != NumValsGreater; ++i)
  374. Result += IN->getChild(i)->getFullDelta();
  375. // If we found exactly the value we were looking for, break off the
  376. // search early. There is no need to search the RHS of the value for
  377. // partial results.
  378. if (NumValsGreater != Node->getNumValuesUsed() &&
  379. Node->getValue(NumValsGreater).FileLoc == FileIndex)
  380. return Result+IN->getChild(NumValsGreater)->getFullDelta();
  381. // Otherwise, traverse down the tree. The selected subtree may be
  382. // partially included in the range.
  383. Node = IN->getChild(NumValsGreater);
  384. }
  385. // NOT REACHED.
  386. }
  387. /// AddDelta - When a change is made that shifts around the text buffer,
  388. /// this method is used to record that info. It inserts a delta of 'Delta'
  389. /// into the current DeltaTree at offset FileIndex.
  390. void DeltaTree::AddDelta(unsigned FileIndex, int Delta) {
  391. assert(Delta && "Adding a noop?");
  392. DeltaTreeNode *MyRoot = getRoot(Root);
  393. DeltaTreeNode::InsertResult InsertRes;
  394. if (MyRoot->DoInsertion(FileIndex, Delta, &InsertRes)) {
  395. Root = MyRoot = new DeltaTreeInteriorNode(InsertRes);
  396. }
  397. #ifdef VERIFY_TREE
  398. VerifyTree(MyRoot);
  399. #endif
  400. }