1 //===- DeltaTree.cpp - B-Tree for Rewrite Delta tracking ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the DeltaTree and related classes.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Rewrite/Core/DeltaTree.h"
15 #include "clang/Basic/LLVM.h"
16 #include "llvm/Support/Casting.h"
20 using namespace clang;
22 /// The DeltaTree class is a multiway search tree (BTree) structure with some
23 /// fancy features. B-Trees are generally more memory and cache efficient
24 /// than binary trees, because they store multiple keys/values in each node.
26 /// DeltaTree implements a key/value mapping from FileIndex to Delta, allowing
27 /// fast lookup by FileIndex. However, an added (important) bonus is that it
28 /// can also efficiently tell us the full accumulated delta for a specific
29 /// file offset as well, without traversing the whole tree.
31 /// The nodes of the tree are made up of instances of two classes:
32 /// DeltaTreeNode and DeltaTreeInteriorNode. The later subclasses the
33 /// former and adds children pointers. Each node knows the full delta of all
34 /// entries (recursively) contained inside of it, which allows us to get the
35 /// full delta implied by a whole subtree in constant time.
39 /// SourceDelta - As code in the original input buffer is added and deleted,
40 /// SourceDelta records are used to keep track of how the input SourceLocation
41 /// object is mapped into the output buffer.
46 static SourceDelta get(unsigned Loc, int D) {
54 /// DeltaTreeNode - The common part of all nodes.
59 DeltaTreeNode *LHS, *RHS;
64 friend class DeltaTreeInteriorNode;
66 /// WidthFactor - This controls the number of K/V slots held in the BTree:
67 /// how wide it is. Each level of the BTree is guaranteed to have at least
68 /// WidthFactor-1 K/V pairs (except the root) and may have at most
69 /// 2*WidthFactor-1 K/V pairs.
70 enum { WidthFactor = 8 };
72 /// Values - This tracks the SourceDelta's currently in this node.
73 SourceDelta Values[2*WidthFactor-1];
75 /// NumValuesUsed - This tracks the number of values this node currently
77 unsigned char NumValuesUsed = 0;
79 /// IsLeaf - This is true if this is a leaf of the btree. If false, this is
80 /// an interior node, and is actually an instance of DeltaTreeInteriorNode.
83 /// FullDelta - This is the full delta of all the values in this node and
84 /// all children nodes.
88 DeltaTreeNode(bool isLeaf = true) : IsLeaf(isLeaf) {}
90 bool isLeaf() const { return IsLeaf; }
91 int getFullDelta() const { return FullDelta; }
92 bool isFull() const { return NumValuesUsed == 2*WidthFactor-1; }
94 unsigned getNumValuesUsed() const { return NumValuesUsed; }
96 const SourceDelta &getValue(unsigned i) const {
97 assert(i < NumValuesUsed && "Invalid value #");
101 SourceDelta &getValue(unsigned i) {
102 assert(i < NumValuesUsed && "Invalid value #");
106 /// DoInsertion - Do an insertion of the specified FileIndex/Delta pair into
107 /// this node. If insertion is easy, do it and return false. Otherwise,
108 /// split the node, populate InsertRes with info about the split, and return
110 bool DoInsertion(unsigned FileIndex, int Delta, InsertResult *InsertRes);
112 void DoSplit(InsertResult &InsertRes);
115 /// RecomputeFullDeltaLocally - Recompute the FullDelta field by doing a
116 /// local walk over our contained deltas.
117 void RecomputeFullDeltaLocally();
122 /// DeltaTreeInteriorNode - When isLeaf = false, a node has child pointers.
123 /// This class tracks them.
124 class DeltaTreeInteriorNode : public DeltaTreeNode {
125 friend class DeltaTreeNode;
127 DeltaTreeNode *Children[2*WidthFactor];
129 ~DeltaTreeInteriorNode() {
130 for (unsigned i = 0, e = NumValuesUsed+1; i != e; ++i)
131 Children[i]->Destroy();
135 DeltaTreeInteriorNode() : DeltaTreeNode(false /*nonleaf*/) {}
137 DeltaTreeInteriorNode(const InsertResult &IR)
138 : DeltaTreeNode(false /*nonleaf*/) {
139 Children[0] = IR.LHS;
140 Children[1] = IR.RHS;
141 Values[0] = IR.Split;
142 FullDelta = IR.LHS->getFullDelta()+IR.RHS->getFullDelta()+IR.Split.Delta;
146 const DeltaTreeNode *getChild(unsigned i) const {
147 assert(i < getNumValuesUsed()+1 && "Invalid child");
151 DeltaTreeNode *getChild(unsigned i) {
152 assert(i < getNumValuesUsed()+1 && "Invalid child");
156 static bool classof(const DeltaTreeNode *N) { return !N->isLeaf(); }
161 /// Destroy - A 'virtual' destructor.
162 void DeltaTreeNode::Destroy() {
166 delete cast<DeltaTreeInteriorNode>(this);
169 /// RecomputeFullDeltaLocally - Recompute the FullDelta field by doing a
170 /// local walk over our contained deltas.
171 void DeltaTreeNode::RecomputeFullDeltaLocally() {
172 int NewFullDelta = 0;
173 for (unsigned i = 0, e = getNumValuesUsed(); i != e; ++i)
174 NewFullDelta += Values[i].Delta;
175 if (auto *IN = dyn_cast<DeltaTreeInteriorNode>(this))
176 for (unsigned i = 0, e = getNumValuesUsed()+1; i != e; ++i)
177 NewFullDelta += IN->getChild(i)->getFullDelta();
178 FullDelta = NewFullDelta;
181 /// DoInsertion - Do an insertion of the specified FileIndex/Delta pair into
182 /// this node. If insertion is easy, do it and return false. Otherwise,
183 /// split the node, populate InsertRes with info about the split, and return
185 bool DeltaTreeNode::DoInsertion(unsigned FileIndex, int Delta,
186 InsertResult *InsertRes) {
187 // Maintain full delta for this node.
190 // Find the insertion point, the first delta whose index is >= FileIndex.
191 unsigned i = 0, e = getNumValuesUsed();
192 while (i != e && FileIndex > getValue(i).FileLoc)
195 // If we found an a record for exactly this file index, just merge this
196 // value into the pre-existing record and finish early.
197 if (i != e && getValue(i).FileLoc == FileIndex) {
198 // NOTE: Delta could drop to zero here. This means that the delta entry is
199 // useless and could be removed. Supporting erases is more complex than
200 // leaving an entry with Delta=0, so we just leave an entry with Delta=0 in
202 Values[i].Delta += Delta;
206 // Otherwise, we found an insertion point, and we know that the value at the
207 // specified index is > FileIndex. Handle the leaf case first.
210 // For an insertion into a non-full leaf node, just insert the value in
211 // its sorted position. This requires moving later values over.
213 memmove(&Values[i+1], &Values[i], sizeof(Values[0])*(e-i));
214 Values[i] = SourceDelta::get(FileIndex, Delta);
219 // Otherwise, if this is leaf is full, split the node at its median, insert
220 // the value into one of the children, and return the result.
221 assert(InsertRes && "No result location specified");
224 if (InsertRes->Split.FileLoc > FileIndex)
225 InsertRes->LHS->DoInsertion(FileIndex, Delta, nullptr /*can't fail*/);
227 InsertRes->RHS->DoInsertion(FileIndex, Delta, nullptr /*can't fail*/);
231 // Otherwise, this is an interior node. Send the request down the tree.
232 auto *IN = cast<DeltaTreeInteriorNode>(this);
233 if (!IN->Children[i]->DoInsertion(FileIndex, Delta, InsertRes))
234 return false; // If there was space in the child, just return.
236 // Okay, this split the subtree, producing a new value and two children to
237 // insert here. If this node is non-full, we can just insert it directly.
239 // Now that we have two nodes and a new element, insert the perclated value
240 // into ourself by moving all the later values/children down, then inserting
243 memmove(&IN->Children[i+2], &IN->Children[i+1],
244 (e-i)*sizeof(IN->Children[0]));
245 IN->Children[i] = InsertRes->LHS;
246 IN->Children[i+1] = InsertRes->RHS;
249 memmove(&Values[i+1], &Values[i], (e-i)*sizeof(Values[0]));
250 Values[i] = InsertRes->Split;
255 // Finally, if this interior node was full and a node is percolated up, split
256 // ourself and return that up the chain. Start by saving all our info to
257 // avoid having the split clobber it.
258 IN->Children[i] = InsertRes->LHS;
259 DeltaTreeNode *SubRHS = InsertRes->RHS;
260 SourceDelta SubSplit = InsertRes->Split;
265 // Figure out where to insert SubRHS/NewSplit.
266 DeltaTreeInteriorNode *InsertSide;
267 if (SubSplit.FileLoc < InsertRes->Split.FileLoc)
268 InsertSide = cast<DeltaTreeInteriorNode>(InsertRes->LHS);
270 InsertSide = cast<DeltaTreeInteriorNode>(InsertRes->RHS);
272 // We now have a non-empty interior node 'InsertSide' to insert
273 // SubRHS/SubSplit into. Find out where to insert SubSplit.
275 // Find the insertion point, the first delta whose index is >SubSplit.FileLoc.
276 i = 0; e = InsertSide->getNumValuesUsed();
277 while (i != e && SubSplit.FileLoc > InsertSide->getValue(i).FileLoc)
280 // Now we know that i is the place to insert the split value into. Insert it
281 // and the child right after it.
283 memmove(&InsertSide->Children[i+2], &InsertSide->Children[i+1],
284 (e-i)*sizeof(IN->Children[0]));
285 InsertSide->Children[i+1] = SubRHS;
288 memmove(&InsertSide->Values[i+1], &InsertSide->Values[i],
289 (e-i)*sizeof(Values[0]));
290 InsertSide->Values[i] = SubSplit;
291 ++InsertSide->NumValuesUsed;
292 InsertSide->FullDelta += SubSplit.Delta + SubRHS->getFullDelta();
296 /// DoSplit - Split the currently full node (which has 2*WidthFactor-1 values)
297 /// into two subtrees each with "WidthFactor-1" values and a pivot value.
298 /// Return the pieces in InsertRes.
299 void DeltaTreeNode::DoSplit(InsertResult &InsertRes) {
300 assert(isFull() && "Why split a non-full node?");
302 // Since this node is full, it contains 2*WidthFactor-1 values. We move
303 // the first 'WidthFactor-1' values to the LHS child (which we leave in this
304 // node), propagate one value up, and move the last 'WidthFactor-1' values
305 // into the RHS child.
307 // Create the new child node.
308 DeltaTreeNode *NewNode;
309 if (auto *IN = dyn_cast<DeltaTreeInteriorNode>(this)) {
310 // If this is an interior node, also move over 'WidthFactor' children
311 // into the new node.
312 DeltaTreeInteriorNode *New = new DeltaTreeInteriorNode();
313 memcpy(&New->Children[0], &IN->Children[WidthFactor],
314 WidthFactor*sizeof(IN->Children[0]));
317 // Just create the new leaf node.
318 NewNode = new DeltaTreeNode();
321 // Move over the last 'WidthFactor-1' values from here to NewNode.
322 memcpy(&NewNode->Values[0], &Values[WidthFactor],
323 (WidthFactor-1)*sizeof(Values[0]));
325 // Decrease the number of values in the two nodes.
326 NewNode->NumValuesUsed = NumValuesUsed = WidthFactor-1;
328 // Recompute the two nodes' full delta.
329 NewNode->RecomputeFullDeltaLocally();
330 RecomputeFullDeltaLocally();
332 InsertRes.LHS = this;
333 InsertRes.RHS = NewNode;
334 InsertRes.Split = Values[WidthFactor-1];
337 //===----------------------------------------------------------------------===//
338 // DeltaTree Implementation
339 //===----------------------------------------------------------------------===//
341 //#define VERIFY_TREE
344 /// VerifyTree - Walk the btree performing assertions on various properties to
345 /// verify consistency. This is useful for debugging new changes to the tree.
346 static void VerifyTree(const DeltaTreeNode *N) {
347 const auto *IN = dyn_cast<DeltaTreeInteriorNode>(N);
349 // Verify leaves, just ensure that FullDelta matches up and the elements
350 // are in proper order.
352 for (unsigned i = 0, e = N->getNumValuesUsed(); i != e; ++i) {
354 assert(N->getValue(i-1).FileLoc < N->getValue(i).FileLoc);
355 FullDelta += N->getValue(i).Delta;
357 assert(FullDelta == N->getFullDelta());
361 // Verify interior nodes: Ensure that FullDelta matches up and the
362 // elements are in proper order and the children are in proper order.
364 for (unsigned i = 0, e = IN->getNumValuesUsed(); i != e; ++i) {
365 const SourceDelta &IVal = N->getValue(i);
366 const DeltaTreeNode *IChild = IN->getChild(i);
368 assert(IN->getValue(i-1).FileLoc < IVal.FileLoc);
369 FullDelta += IVal.Delta;
370 FullDelta += IChild->getFullDelta();
372 // The largest value in child #i should be smaller than FileLoc.
373 assert(IChild->getValue(IChild->getNumValuesUsed()-1).FileLoc <
376 // The smallest value in child #i+1 should be larger than FileLoc.
377 assert(IN->getChild(i+1)->getValue(0).FileLoc > IVal.FileLoc);
381 FullDelta += IN->getChild(IN->getNumValuesUsed())->getFullDelta();
383 assert(FullDelta == N->getFullDelta());
385 #endif // VERIFY_TREE
387 static DeltaTreeNode *getRoot(void *Root) {
388 return (DeltaTreeNode*)Root;
391 DeltaTree::DeltaTree() {
392 Root = new DeltaTreeNode();
395 DeltaTree::DeltaTree(const DeltaTree &RHS) {
396 // Currently we only support copying when the RHS is empty.
397 assert(getRoot(RHS.Root)->getNumValuesUsed() == 0 &&
398 "Can only copy empty tree");
399 Root = new DeltaTreeNode();
402 DeltaTree::~DeltaTree() {
403 getRoot(Root)->Destroy();
406 /// getDeltaAt - Return the accumulated delta at the specified file offset.
407 /// This includes all insertions or delections that occurred *before* the
408 /// specified file index.
409 int DeltaTree::getDeltaAt(unsigned FileIndex) const {
410 const DeltaTreeNode *Node = getRoot(Root);
414 // Walk down the tree.
416 // For all nodes, include any local deltas before the specified file
417 // index by summing them up directly. Keep track of how many were
419 unsigned NumValsGreater = 0;
420 for (unsigned e = Node->getNumValuesUsed(); NumValsGreater != e;
422 const SourceDelta &Val = Node->getValue(NumValsGreater);
424 if (Val.FileLoc >= FileIndex)
429 // If we have an interior node, include information about children and
430 // recurse. Otherwise, if we have a leaf, we're done.
431 const auto *IN = dyn_cast<DeltaTreeInteriorNode>(Node);
432 if (!IN) return Result;
434 // Include any children to the left of the values we skipped, all of
435 // their deltas should be included as well.
436 for (unsigned i = 0; i != NumValsGreater; ++i)
437 Result += IN->getChild(i)->getFullDelta();
439 // If we found exactly the value we were looking for, break off the
440 // search early. There is no need to search the RHS of the value for
442 if (NumValsGreater != Node->getNumValuesUsed() &&
443 Node->getValue(NumValsGreater).FileLoc == FileIndex)
444 return Result+IN->getChild(NumValsGreater)->getFullDelta();
446 // Otherwise, traverse down the tree. The selected subtree may be
447 // partially included in the range.
448 Node = IN->getChild(NumValsGreater);
453 /// AddDelta - When a change is made that shifts around the text buffer,
454 /// this method is used to record that info. It inserts a delta of 'Delta'
455 /// into the current DeltaTree at offset FileIndex.
456 void DeltaTree::AddDelta(unsigned FileIndex, int Delta) {
457 assert(Delta && "Adding a noop?");
458 DeltaTreeNode *MyRoot = getRoot(Root);
460 DeltaTreeNode::InsertResult InsertRes;
461 if (MyRoot->DoInsertion(FileIndex, Delta, &InsertRes)) {
462 Root = MyRoot = new DeltaTreeInteriorNode(InsertRes);