Coverage Report

Created: 2020-09-22 08:39

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Rewrite/RewriteRope.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- RewriteRope.cpp - Rope specialized for rewriter --------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements the RewriteRope class, which is a powerful string.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Rewrite/Core/RewriteRope.h"
14
#include "clang/Basic/LLVM.h"
15
#include "llvm/Support/Casting.h"
16
#include <algorithm>
17
#include <cassert>
18
#include <cstring>
19
20
using namespace clang;
21
22
/// RewriteRope is a "strong" string class, designed to make insertions and
23
/// deletions in the middle of the string nearly constant time (really, they are
24
/// O(log N), but with a very low constant factor).
25
///
26
/// The implementation of this datastructure is a conceptual linear sequence of
27
/// RopePiece elements.  Each RopePiece represents a view on a separately
28
/// allocated and reference counted string.  This means that splitting a very
29
/// long string can be done in constant time by splitting a RopePiece that
30
/// references the whole string into two rope pieces that reference each half.
31
/// Once split, another string can be inserted in between the two halves by
32
/// inserting a RopePiece in between the two others.  All of this is very
33
/// inexpensive: it takes time proportional to the number of RopePieces, not the
34
/// length of the strings they represent.
35
///
36
/// While a linear sequences of RopePieces is the conceptual model, the actual
37
/// implementation captures them in an adapted B+ Tree.  Using a B+ tree (which
38
/// is a tree that keeps the values in the leaves and has where each node
39
/// contains a reasonable number of pointers to children/values) allows us to
40
/// maintain efficient operation when the RewriteRope contains a *huge* number
41
/// of RopePieces.  The basic idea of the B+ Tree is that it allows us to find
42
/// the RopePiece corresponding to some offset very efficiently, and it
43
/// automatically balances itself on insertions of RopePieces (which can happen
44
/// for both insertions and erases of string ranges).
45
///
46
/// The one wrinkle on the theory is that we don't attempt to keep the tree
47
/// properly balanced when erases happen.  Erases of string data can both insert
48
/// new RopePieces (e.g. when the middle of some other rope piece is deleted,
49
/// which results in two rope pieces, which is just like an insert) or it can
50
/// reduce the number of RopePieces maintained by the B+Tree.  In the case when
51
/// the number of RopePieces is reduced, we don't attempt to maintain the
52
/// standard 'invariant' that each node in the tree contains at least
53
/// 'WidthFactor' children/values.  For our use cases, this doesn't seem to
54
/// matter.
55
///
56
/// The implementation below is primarily implemented in terms of three classes:
57
///   RopePieceBTreeNode - Common base class for:
58
///
59
///     RopePieceBTreeLeaf - Directly manages up to '2*WidthFactor' RopePiece
60
///          nodes.  This directly represents a chunk of the string with those
61
///          RopePieces concatenated.
62
///     RopePieceBTreeInterior - An interior node in the B+ Tree, which manages
63
///          up to '2*WidthFactor' other nodes in the tree.
64
65
namespace {
66
67
//===----------------------------------------------------------------------===//
68
// RopePieceBTreeNode Class
69
//===----------------------------------------------------------------------===//
70
71
  /// RopePieceBTreeNode - Common base class of RopePieceBTreeLeaf and
72
  /// RopePieceBTreeInterior.  This provides some 'virtual' dispatching methods
73
  /// and a flag that determines which subclass the instance is.  Also
74
  /// important, this node knows the full extend of the node, including any
75
  /// children that it has.  This allows efficient skipping over entire subtrees
76
  /// when looking for an offset in the BTree.
77
  class RopePieceBTreeNode {
78
  protected:
79
    /// WidthFactor - This controls the number of K/V slots held in the BTree:
80
    /// how wide it is.  Each level of the BTree is guaranteed to have at least
81
    /// 'WidthFactor' elements in it (either ropepieces or children), (except
82
    /// the root, which may have less) and may have at most 2*WidthFactor
83
    /// elements.
84
    enum { WidthFactor = 8 };
85
86
    /// Size - This is the number of bytes of file this node (including any
87
    /// potential children) covers.
88
    unsigned Size = 0;
89
90
    /// IsLeaf - True if this is an instance of RopePieceBTreeLeaf, false if it
91
    /// is an instance of RopePieceBTreeInterior.
92
    bool IsLeaf;
93
94
62.6k
    RopePieceBTreeNode(bool isLeaf) : IsLeaf(isLeaf) {}
95
    ~RopePieceBTreeNode() = default;
96
97
  public:
98
1.73M
    bool isLeaf() const { return IsLeaf; }
99
6.50M
    unsigned size() const { return Size; }
100
101
    void Destroy();
102
103
    /// split - Split the range containing the specified offset so that we are
104
    /// guaranteed that there is a place to do an insertion at the specified
105
    /// offset.  The offset is relative, so "0" is the start of the node.
106
    ///
107
    /// If there is no space in this subtree for the extra piece, the extra tree
108
    /// node is returned and must be inserted into a parent.
109
    RopePieceBTreeNode *split(unsigned Offset);
110
111
    /// insert - Insert the specified ropepiece into this tree node at the
112
    /// specified offset.  The offset is relative, so "0" is the start of the
113
    /// node.
114
    ///
115
    /// If there is no space in this subtree for the extra piece, the extra tree
116
    /// node is returned and must be inserted into a parent.
117
    RopePieceBTreeNode *insert(unsigned Offset, const RopePiece &R);
118
119
    /// erase - Remove NumBytes from this node at the specified offset.  We are
120
    /// guaranteed that there is a split at Offset.
121
    void erase(unsigned Offset, unsigned NumBytes);
122
  };
123
124
//===----------------------------------------------------------------------===//
125
// RopePieceBTreeLeaf Class
126
//===----------------------------------------------------------------------===//
127
128
  /// RopePieceBTreeLeaf - Directly manages up to '2*WidthFactor' RopePiece
129
  /// nodes.  This directly represents a chunk of the string with those
130
  /// RopePieces concatenated.  Since this is a B+Tree, all values (in this case
131
  /// instances of RopePiece) are stored in leaves like this.  To make iteration
132
  /// over the leaves efficient, they maintain a singly linked list through the
133
  /// NextLeaf field.  This allows the B+Tree forward iterator to be constant
134
  /// time for all increments.
135
  class RopePieceBTreeLeaf : public RopePieceBTreeNode {
136
    /// NumPieces - This holds the number of rope pieces currently active in the
137
    /// Pieces array.
138
    unsigned char NumPieces = 0;
139
140
    /// Pieces - This tracks the file chunks currently in this leaf.
141
    RopePiece Pieces[2*WidthFactor];
142
143
    /// NextLeaf - This is a pointer to the next leaf in the tree, allowing
144
    /// efficient in-order forward iteration of the tree without traversal.
145
    RopePieceBTreeLeaf **PrevLeaf = nullptr;
146
    RopePieceBTreeLeaf *NextLeaf = nullptr;
147
148
  public:
149
60.0k
    RopePieceBTreeLeaf() : RopePieceBTreeNode(true) {}
150
151
60.0k
    ~RopePieceBTreeLeaf() {
152
60.0k
      if (PrevLeaf || 
NextLeaf60.0k
)
153
15.2k
        removeFromLeafInOrder();
154
60.0k
      clear();
155
60.0k
    }
156
157
268k
    bool isFull() const { return NumPieces == 2*WidthFactor; }
158
159
    /// clear - Remove all rope pieces from this leaf.
160
75.0k
    void clear() {
161
327k
      while (NumPieces)
162
252k
        Pieces[--NumPieces] = RopePiece();
163
75.0k
      Size = 0;
164
75.0k
    }
165
166
2.36M
    unsigned getNumPieces() const { return NumPieces; }
167
168
1.77M
    const RopePiece &getPiece(unsigned i) const {
169
1.77M
      assert(i < getNumPieces() && "Invalid piece ID");
170
1.77M
      return Pieces[i];
171
1.77M
    }
172
173
31.3k
    const RopePieceBTreeLeaf *getNextLeafInOrder() const { return NextLeaf; }
174
175
15.2k
    void insertAfterLeafInOrder(RopePieceBTreeLeaf *Node) {
176
15.2k
      assert(!PrevLeaf && !NextLeaf && "Already in ordering");
177
178
15.2k
      NextLeaf = Node->NextLeaf;
179
15.2k
      if (NextLeaf)
180
12.0k
        NextLeaf->PrevLeaf = &NextLeaf;
181
15.2k
      PrevLeaf = &Node->NextLeaf;
182
15.2k
      Node->NextLeaf = this;
183
15.2k
    }
184
185
15.2k
    void removeFromLeafInOrder() {
186
15.2k
      if (PrevLeaf) {
187
1
        *PrevLeaf = NextLeaf;
188
1
        if (NextLeaf)
189
1
          NextLeaf->PrevLeaf = PrevLeaf;
190
15.2k
      } else if (NextLeaf) {
191
15.2k
        NextLeaf->PrevLeaf = nullptr;
192
15.2k
      }
193
15.2k
    }
194
195
    /// FullRecomputeSizeLocally - This method recomputes the 'Size' field by
196
    /// summing the size of all RopePieces.
197
30.4k
    void FullRecomputeSizeLocally() {
198
30.4k
      Size = 0;
199
274k
      for (unsigned i = 0, e = getNumPieces(); i != e; 
++i243k
)
200
243k
        Size += getPiece(i).size();
201
30.4k
    }
202
203
    /// split - Split the range containing the specified offset so that we are
204
    /// guaranteed that there is a place to do an insertion at the specified
205
    /// offset.  The offset is relative, so "0" is the start of the node.
206
    ///
207
    /// If there is no space in this subtree for the extra piece, the extra tree
208
    /// node is returned and must be inserted into a parent.
209
    RopePieceBTreeNode *split(unsigned Offset);
210
211
    /// insert - Insert the specified ropepiece into this tree node at the
212
    /// specified offset.  The offset is relative, so "0" is the start of the
213
    /// node.
214
    ///
215
    /// If there is no space in this subtree for the extra piece, the extra tree
216
    /// node is returned and must be inserted into a parent.
217
    RopePieceBTreeNode *insert(unsigned Offset, const RopePiece &R);
218
219
    /// erase - Remove NumBytes from this node at the specified offset.  We are
220
    /// guaranteed that there is a split at Offset.
221
    void erase(unsigned Offset, unsigned NumBytes);
222
223
1.31M
    static bool classof(const RopePieceBTreeNode *N) {
224
1.31M
      return N->isLeaf();
225
1.31M
    }
226
  };
227
228
} // namespace
229
230
/// split - Split the range containing the specified offset so that we are
231
/// guaranteed that there is a place to do an insertion at the specified
232
/// offset.  The offset is relative, so "0" is the start of the node.
233
///
234
/// If there is no space in this subtree for the extra piece, the extra tree
235
/// node is returned and must be inserted into a parent.
236
187k
RopePieceBTreeNode *RopePieceBTreeLeaf::split(unsigned Offset) {
237
  // Find the insertion point.  We are guaranteed that there is a split at the
238
  // specified offset so find it.
239
187k
  if (Offset == 0 || 
Offset == size()171k
) {
240
    // Fastpath for a common case.  There is already a splitpoint at the end.
241
16.5k
    return nullptr;
242
16.5k
  }
243
244
  // Find the piece that this offset lands in.
245
170k
  unsigned PieceOffs = 0;
246
170k
  unsigned i = 0;
247
869k
  while (Offset >= PieceOffs+Pieces[i].size()) {
248
699k
    PieceOffs += Pieces[i].size();
249
699k
    ++i;
250
699k
  }
251
252
  // If there is already a split point at the specified offset, just return
253
  // success.
254
170k
  if (PieceOffs == Offset)
255
58.4k
    return nullptr;
256
257
  // Otherwise, we need to split piece 'i' at Offset-PieceOffs.  Convert Offset
258
  // to being Piece relative.
259
112k
  unsigned IntraPieceOffset = Offset-PieceOffs;
260
261
  // We do this by shrinking the RopePiece and then doing an insert of the tail.
262
112k
  RopePiece Tail(Pieces[i].StrData, Pieces[i].StartOffs+IntraPieceOffset,
263
112k
                 Pieces[i].EndOffs);
264
112k
  Size -= Pieces[i].size();
265
112k
  Pieces[i].EndOffs = Pieces[i].StartOffs+IntraPieceOffset;
266
112k
  Size += Pieces[i].size();
267
268
112k
  return insert(Offset, Tail);
269
112k
}
270
271
/// insert - Insert the specified RopePiece into this tree node at the
272
/// specified offset.  The offset is relative, so "0" is the start of the node.
273
///
274
/// If there is no space in this subtree for the extra piece, the extra tree
275
/// node is returned and must be inserted into a parent.
276
RopePieceBTreeNode *RopePieceBTreeLeaf::insert(unsigned Offset,
277
268k
                                               const RopePiece &R) {
278
  // If this node is not full, insert the piece.
279
268k
  if (!isFull()) {
280
    // Find the insertion point.  We are guaranteed that there is a split at the
281
    // specified offset so find it.
282
253k
    unsigned i = 0, e = getNumPieces();
283
253k
    if (Offset == size()) {
284
      // Fastpath for a common case.
285
48.5k
      i = e;
286
205k
    } else {
287
205k
      unsigned SlotOffs = 0;
288
1.18M
      for (; Offset > SlotOffs; 
++i980k
)
289
980k
        SlotOffs += getPiece(i).size();
290
205k
      assert(SlotOffs == Offset && "Split didn't occur before insertion!");
291
205k
    }
292
293
    // For an insertion into a non-full leaf node, just insert the value in
294
    // its sorted position.  This requires moving later values over.
295
1.18M
    for (; i != e; 
--e928k
)
296
928k
      Pieces[e] = Pieces[e-1];
297
253k
    Pieces[i] = R;
298
253k
    ++NumPieces;
299
253k
    Size += R.size();
300
253k
    return nullptr;
301
253k
  }
302
303
  // Otherwise, if this is leaf is full, split it in two halves.  Since this
304
  // node is full, it contains 2*WidthFactor values.  We move the first
305
  // 'WidthFactor' values to the LHS child (which we leave in this node) and
306
  // move the last 'WidthFactor' values into the RHS child.
307
308
  // Create the new node.
309
15.2k
  RopePieceBTreeLeaf *NewNode = new RopePieceBTreeLeaf();
310
311
  // Move over the last 'WidthFactor' values from here to NewNode.
312
15.2k
  std::copy(&Pieces[WidthFactor], &Pieces[2*WidthFactor],
313
15.2k
            &NewNode->Pieces[0]);
314
  // Replace old pieces with null RopePieces to drop refcounts.
315
15.2k
  std::fill(&Pieces[WidthFactor], &Pieces[2*WidthFactor], RopePiece());
316
317
  // Decrease the number of values in the two nodes.
318
15.2k
  NewNode->NumPieces = NumPieces = WidthFactor;
319
320
  // Recompute the two nodes' size.
321
15.2k
  NewNode->FullRecomputeSizeLocally();
322
15.2k
  FullRecomputeSizeLocally();
323
324
  // Update the list of leaves.
325
15.2k
  NewNode->insertAfterLeafInOrder(this);
326
327
  // These insertions can't fail.
328
15.2k
  if (this->size() >= Offset)
329
2.52k
    this->insert(Offset, R);
330
12.7k
  else
331
12.7k
    NewNode->insert(Offset - this->size(), R);
332
15.2k
  return NewNode;
333
15.2k
}
334
335
/// erase - Remove NumBytes from this node at the specified offset.  We are
336
/// guaranteed that there is a split at Offset.
337
48.3k
void RopePieceBTreeLeaf::erase(unsigned Offset, unsigned NumBytes) {
338
  // Since we are guaranteed that there is a split at Offset, we start by
339
  // finding the Piece that starts there.
340
48.3k
  unsigned PieceOffs = 0;
341
48.3k
  unsigned i = 0;
342
148k
  for (; Offset > PieceOffs; 
++i99.8k
)
343
99.8k
    PieceOffs += getPiece(i).size();
344
48.3k
  assert(PieceOffs == Offset && "Split didn't occur before erase!");
345
346
48.3k
  unsigned StartPiece = i;
347
348
  // Figure out how many pieces completely cover 'NumBytes'.  We want to remove
349
  // all of them.
350
48.9k
  for (; Offset+NumBytes > PieceOffs+getPiece(i).size(); 
++i564
)
351
564
    PieceOffs += getPiece(i).size();
352
353
  // If we exactly include the last one, include it in the region to delete.
354
48.3k
  if (Offset+NumBytes == PieceOffs+getPiece(i).size()) {
355
860
    PieceOffs += getPiece(i).size();
356
860
    ++i;
357
860
  }
358
359
  // If we completely cover some RopePieces, erase them now.
360
48.3k
  if (i != StartPiece) {
361
1.09k
    unsigned NumDeleted = i-StartPiece;
362
4.30k
    for (; i != getNumPieces(); 
++i3.20k
)
363
3.20k
      Pieces[i-NumDeleted] = Pieces[i];
364
365
    // Drop references to dead rope pieces.
366
1.09k
    std::fill(&Pieces[getNumPieces()-NumDeleted], &Pieces[getNumPieces()],
367
1.09k
              RopePiece());
368
1.09k
    NumPieces -= NumDeleted;
369
370
1.09k
    unsigned CoverBytes = PieceOffs-Offset;
371
1.09k
    NumBytes -= CoverBytes;
372
1.09k
    Size -= CoverBytes;
373
1.09k
  }
374
375
  // If we completely removed some stuff, we could be done.
376
48.3k
  if (NumBytes == 0) 
return860
;
377
378
  // Okay, now might be erasing part of some Piece.  If this is the case, then
379
  // move the start point of the piece.
380
47.4k
  assert(getPiece(StartPiece).size() > NumBytes);
381
47.4k
  Pieces[StartPiece].StartOffs += NumBytes;
382
383
  // The size of this node just shrunk by NumBytes.
384
47.4k
  Size -= NumBytes;
385
47.4k
}
386
387
//===----------------------------------------------------------------------===//
388
// RopePieceBTreeInterior Class
389
//===----------------------------------------------------------------------===//
390
391
namespace {
392
393
  /// RopePieceBTreeInterior - This represents an interior node in the B+Tree,
394
  /// which holds up to 2*WidthFactor pointers to child nodes.
395
  class RopePieceBTreeInterior : public RopePieceBTreeNode {
396
    /// NumChildren - This holds the number of children currently active in the
397
    /// Children array.
398
    unsigned char NumChildren = 0;
399
400
    RopePieceBTreeNode *Children[2*WidthFactor];
401
402
  public:
403
1.25k
    RopePieceBTreeInterior() : RopePieceBTreeNode(false) {}
404
405
    RopePieceBTreeInterior(RopePieceBTreeNode *LHS, RopePieceBTreeNode *RHS)
406
1.29k
        : RopePieceBTreeNode(false) {
407
1.29k
      Children[0] = LHS;
408
1.29k
      Children[1] = RHS;
409
1.29k
      NumChildren = 2;
410
1.29k
      Size = LHS->size() + RHS->size();
411
1.29k
    }
412
413
2.54k
    ~RopePieceBTreeInterior() {
414
20.3k
      for (unsigned i = 0, e = getNumChildren(); i != e; 
++i17.7k
)
415
17.7k
        Children[i]->Destroy();
416
2.54k
    }
417
418
16.4k
    bool isFull() const { return NumChildren == 2*WidthFactor; }
419
420
220k
    unsigned getNumChildren() const { return NumChildren; }
421
422
1.86k
    const RopePieceBTreeNode *getChild(unsigned i) const {
423
1.86k
      assert(i < NumChildren && "invalid child #");
424
1.86k
      return Children[i];
425
1.86k
    }
426
427
5.05M
    RopePieceBTreeNode *getChild(unsigned i) {
428
5.05M
      assert(i < NumChildren && "invalid child #");
429
5.05M
      return Children[i];
430
5.05M
    }
431
432
    /// FullRecomputeSizeLocally - Recompute the Size field of this node by
433
    /// summing up the sizes of the child nodes.
434
2.51k
    void FullRecomputeSizeLocally() {
435
2.51k
      Size = 0;
436
23.8k
      for (unsigned i = 0, e = getNumChildren(); i != e; 
++i21.3k
)
437
21.3k
        Size += getChild(i)->size();
438
2.51k
    }
439
440
    /// split - Split the range containing the specified offset so that we are
441
    /// guaranteed that there is a place to do an insertion at the specified
442
    /// offset.  The offset is relative, so "0" is the start of the node.
443
    ///
444
    /// If there is no space in this subtree for the extra piece, the extra tree
445
    /// node is returned and must be inserted into a parent.
446
    RopePieceBTreeNode *split(unsigned Offset);
447
448
    /// insert - Insert the specified ropepiece into this tree node at the
449
    /// specified offset.  The offset is relative, so "0" is the start of the
450
    /// node.
451
    ///
452
    /// If there is no space in this subtree for the extra piece, the extra tree
453
    /// node is returned and must be inserted into a parent.
454
    RopePieceBTreeNode *insert(unsigned Offset, const RopePiece &R);
455
456
    /// HandleChildPiece - A child propagated an insertion result up to us.
457
    /// Insert the new child, and/or propagate the result further up the tree.
458
    RopePieceBTreeNode *HandleChildPiece(unsigned i, RopePieceBTreeNode *RHS);
459
460
    /// erase - Remove NumBytes from this node at the specified offset.  We are
461
    /// guaranteed that there is a split at Offset.
462
    void erase(unsigned Offset, unsigned NumBytes);
463
464
418k
    static bool classof(const RopePieceBTreeNode *N) {
465
418k
      return !N->isLeaf();
466
418k
    }
467
  };
468
469
} // namespace
470
471
/// split - Split the range containing the specified offset so that we are
472
/// guaranteed that there is a place to do an insertion at the specified
473
/// offset.  The offset is relative, so "0" is the start of the node.
474
///
475
/// If there is no space in this subtree for the extra piece, the extra tree
476
/// node is returned and must be inserted into a parent.
477
197k
RopePieceBTreeNode *RopePieceBTreeInterior::split(unsigned Offset) {
478
  // Figure out which child to split.
479
197k
  if (Offset == 0 || 
Offset == size()196k
)
480
1.13k
    return nullptr; // If we have an exact offset, we're already split.
481
482
196k
  unsigned ChildOffset = 0;
483
196k
  unsigned i = 0;
484
1.25M
  for (; Offset >= ChildOffset+getChild(i)->size(); 
++i1.06M
)
485
1.06M
    ChildOffset += getChild(i)->size();
486
487
  // If already split there, we're done.
488
196k
  if (ChildOffset == Offset)
489
1.36k
    return nullptr;
490
491
  // Otherwise, recursively split the child.
492
195k
  if (RopePieceBTreeNode *RHS = getChild(i)->split(Offset-ChildOffset))
493
10.1k
    return HandleChildPiece(i, RHS);
494
184k
  return nullptr; // Done!
495
184k
}
496
497
/// insert - Insert the specified ropepiece into this tree node at the
498
/// specified offset.  The offset is relative, so "0" is the start of the
499
/// node.
500
///
501
/// If there is no space in this subtree for the extra piece, the extra tree
502
/// node is returned and must be inserted into a parent.
503
RopePieceBTreeNode *RopePieceBTreeInterior::insert(unsigned Offset,
504
188k
                                                   const RopePiece &R) {
505
  // Find the insertion point.  We are guaranteed that there is a split at the
506
  // specified offset so find it.
507
188k
  unsigned i = 0, e = getNumChildren();
508
509
188k
  unsigned ChildOffs = 0;
510
188k
  if (Offset == size()) {
511
    // Fastpath for a common case.  Insert at end of last child.
512
499
    i = e-1;
513
499
    ChildOffs = size()-getChild(i)->size();
514
187k
  } else {
515
1.21M
    for (; Offset > ChildOffs+getChild(i)->size(); 
++i1.02M
)
516
1.02M
      ChildOffs += getChild(i)->size();
517
187k
  }
518
519
188k
  Size += R.size();
520
521
  // Insert at the end of this child.
522
188k
  if (RopePieceBTreeNode *RHS = getChild(i)->insert(Offset-ChildOffs, R))
523
5.02k
    return HandleChildPiece(i, RHS);
524
525
183k
  return nullptr;
526
183k
}
527
528
/// HandleChildPiece - A child propagated an insertion result up to us.
529
/// Insert the new child, and/or propagate the result further up the tree.
530
RopePieceBTreeNode *
531
16.4k
RopePieceBTreeInterior::HandleChildPiece(unsigned i, RopePieceBTreeNode *RHS) {
532
  // Otherwise the child propagated a subtree up to us as a new child.  See if
533
  // we have space for it here.
534
16.4k
  if (!isFull()) {
535
    // Insert RHS after child 'i'.
536
15.1k
    if (i + 1 != getNumChildren())
537
11.6k
      memmove(&Children[i+2], &Children[i+1],
538
11.6k
              (getNumChildren()-i-1)*sizeof(Children[0]));
539
15.1k
    Children[i+1] = RHS;
540
15.1k
    ++NumChildren;
541
15.1k
    return nullptr;
542
15.1k
  }
543
544
  // Okay, this node is full.  Split it in half, moving WidthFactor children to
545
  // a newly allocated interior node.
546
547
  // Create the new node.
548
1.25k
  RopePieceBTreeInterior *NewNode = new RopePieceBTreeInterior();
549
550
  // Move over the last 'WidthFactor' values from here to NewNode.
551
1.25k
  memcpy(&NewNode->Children[0], &Children[WidthFactor],
552
1.25k
         WidthFactor*sizeof(Children[0]));
553
554
  // Decrease the number of values in the two nodes.
555
1.25k
  NewNode->NumChildren = NumChildren = WidthFactor;
556
557
  // Finally, insert the two new children in the side the can (now) hold them.
558
  // These insertions can't fail.
559
1.25k
  if (i < WidthFactor)
560
31
    this->HandleChildPiece(i, RHS);
561
1.22k
  else
562
1.22k
    NewNode->HandleChildPiece(i-WidthFactor, RHS);
563
564
  // Recompute the two nodes' size.
565
1.25k
  NewNode->FullRecomputeSizeLocally();
566
1.25k
  FullRecomputeSizeLocally();
567
1.25k
  return NewNode;
568
1.25k
}
569
570
/// erase - Remove NumBytes from this node at the specified offset.  We are
571
/// guaranteed that there is a split at Offset.
572
10.5k
void RopePieceBTreeInterior::erase(unsigned Offset, unsigned NumBytes) {
573
  // This will shrink this node by NumBytes.
574
10.5k
  Size -= NumBytes;
575
576
  // Find the first child that overlaps with Offset.
577
10.5k
  unsigned i = 0;
578
47.3k
  for (; Offset >= getChild(i)->size(); 
++i36.7k
)
579
36.7k
    Offset -= getChild(i)->size();
580
581
  // Propagate the delete request into overlapping children, or completely
582
  // delete the children as appropriate.
583
10.5k
  while (NumBytes) {
584
10.5k
    RopePieceBTreeNode *CurChild = getChild(i);
585
586
    // If we are deleting something contained entirely in the child, pass on the
587
    // request.
588
10.5k
    if (Offset+NumBytes < CurChild->size()) {
589
10.5k
      CurChild->erase(Offset, NumBytes);
590
10.5k
      return;
591
10.5k
    }
592
593
    // If this deletion request starts somewhere in the middle of the child, it
594
    // must be deleting to the end of the child.
595
9
    if (Offset) {
596
8
      unsigned BytesFromChild = CurChild->size()-Offset;
597
8
      CurChild->erase(Offset, BytesFromChild);
598
8
      NumBytes -= BytesFromChild;
599
      // Start at the beginning of the next child.
600
8
      Offset = 0;
601
8
      ++i;
602
8
      continue;
603
8
    }
604
605
    // If the deletion request completely covers the child, delete it and move
606
    // the rest down.
607
1
    NumBytes -= CurChild->size();
608
1
    CurChild->Destroy();
609
1
    --NumChildren;
610
1
    if (i != getNumChildren())
611
1
      memmove(&Children[i], &Children[i+1],
612
1
              (getNumChildren()-i)*sizeof(Children[0]));
613
1
  }
614
10.5k
}
615
616
//===----------------------------------------------------------------------===//
617
// RopePieceBTreeNode Implementation
618
//===----------------------------------------------------------------------===//
619
620
62.6k
void RopePieceBTreeNode::Destroy() {
621
62.6k
  if (auto *Leaf = dyn_cast<RopePieceBTreeLeaf>(this))
622
60.0k
    delete Leaf;
623
2.54k
  else
624
2.54k
    delete cast<RopePieceBTreeInterior>(this);
625
62.6k
}
626
627
/// split - Split the range containing the specified offset so that we are
628
/// guaranteed that there is a place to do an insertion at the specified
629
/// offset.  The offset is relative, so "0" is the start of the node.
630
///
631
/// If there is no space in this subtree for the extra piece, the extra tree
632
/// node is returned and must be inserted into a parent.
633
384k
RopePieceBTreeNode *RopePieceBTreeNode::split(unsigned Offset) {
634
384k
  assert(Offset <= size() && "Invalid offset to split!");
635
384k
  if (auto *Leaf = dyn_cast<RopePieceBTreeLeaf>(this))
636
187k
    return Leaf->split(Offset);
637
197k
  return cast<RopePieceBTreeInterior>(this)->split(Offset);
638
197k
}
639
640
/// insert - Insert the specified ropepiece into this tree node at the
641
/// specified offset.  The offset is relative, so "0" is the start of the
642
/// node.
643
///
644
/// If there is no space in this subtree for the extra piece, the extra tree
645
/// node is returned and must be inserted into a parent.
646
RopePieceBTreeNode *RopePieceBTreeNode::insert(unsigned Offset,
647
329k
                                               const RopePiece &R) {
648
329k
  assert(Offset <= size() && "Invalid offset to insert!");
649
329k
  if (auto *Leaf = dyn_cast<RopePieceBTreeLeaf>(this))
650
141k
    return Leaf->insert(Offset, R);
651
188k
  return cast<RopePieceBTreeInterior>(this)->insert(Offset, R);
652
188k
}
653
654
/// erase - Remove NumBytes from this node at the specified offset.  We are
655
/// guaranteed that there is a split at Offset.
656
58.9k
void RopePieceBTreeNode::erase(unsigned Offset, unsigned NumBytes) {
657
58.9k
  assert(Offset+NumBytes <= size() && "Invalid offset to erase!");
658
58.9k
  if (auto *Leaf = dyn_cast<RopePieceBTreeLeaf>(this))
659
48.3k
    return Leaf->erase(Offset, NumBytes);
660
10.5k
  return cast<RopePieceBTreeInterior>(this)->erase(Offset, NumBytes);
661
10.5k
}
662
663
//===----------------------------------------------------------------------===//
664
// RopePieceBTreeIterator Implementation
665
//===----------------------------------------------------------------------===//
666
667
632k
static const RopePieceBTreeLeaf *getCN(const void *P) {
668
632k
  return static_cast<const RopePieceBTreeLeaf*>(P);
669
632k
}
670
671
// begin iterator.
672
15.6k
RopePieceBTreeIterator::RopePieceBTreeIterator(const void *n) {
673
15.6k
  const auto *N = static_cast<const RopePieceBTreeNode *>(n);
674
675
  // Walk down the left side of the tree until we get to a leaf.
676
17.5k
  while (const auto *IN = dyn_cast<RopePieceBTreeInterior>(N))
677
1.86k
    N = IN->getChild(0);
678
679
  // We must have at least one leaf.
680
15.6k
  CurNode = cast<RopePieceBTreeLeaf>(N);
681
682
  // If we found a leaf that happens to be empty, skip over it until we get
683
  // to something full.
684
15.6k
  while (CurNode && 
getCN(CurNode)->getNumPieces() == 015.6k
)
685
7
    CurNode = getCN(CurNode)->getNextLeafInOrder();
686
687
15.6k
  if (CurNode)
688
15.6k
    CurPiece = &getCN(CurNode)->getPiece(0);
689
7
  else  // Empty tree, this is an end() iterator.
690
7
    CurPiece = nullptr;
691
15.6k
  CurChar = 0;
692
15.6k
}
693
694
268k
void RopePieceBTreeIterator::MoveToNextPiece() {
695
268k
  if (CurPiece != &getCN(CurNode)->getPiece(getCN(CurNode)->getNumPieces()-1)) {
696
237k
    CurChar = 0;
697
237k
    ++CurPiece;
698
237k
    return;
699
237k
  }
700
701
  // Find the next non-empty leaf node.
702
31.2k
  do
703
31.2k
    CurNode = getCN(CurNode)->getNextLeafInOrder();
704
31.2k
  while (CurNode && 
getCN(CurNode)->getNumPieces() == 016.4k
);
705
706
31.2k
  if (CurNode)
707
16.4k
    CurPiece = &getCN(CurNode)->getPiece(0);
708
14.8k
  else // Hit end().
709
14.8k
    CurPiece = nullptr;
710
31.2k
  CurChar = 0;
711
31.2k
}
712
713
//===----------------------------------------------------------------------===//
714
// RopePieceBTree Implementation
715
//===----------------------------------------------------------------------===//
716
717
651k
static RopePieceBTreeNode *getRoot(void *P) {
718
651k
  return static_cast<RopePieceBTreeNode*>(P);
719
651k
}
720
721
14.9k
RopePieceBTree::RopePieceBTree() {
722
14.9k
  Root = new RopePieceBTreeLeaf();
723
14.9k
}
724
725
29.9k
RopePieceBTree::RopePieceBTree(const RopePieceBTree &RHS) {
726
29.9k
  assert(RHS.empty() && "Can't copy non-empty tree yet");
727
29.9k
  Root = new RopePieceBTreeLeaf();
728
29.9k
}
729
730
44.8k
RopePieceBTree::~RopePieceBTree() {
731
44.8k
  getRoot(Root)->Destroy();
732
44.8k
}
733
734
210k
unsigned RopePieceBTree::size() const {
735
210k
  return getRoot(Root)->size();
736
210k
}
737
738
14.9k
void RopePieceBTree::clear() {
739
14.9k
  if (auto *Leaf = dyn_cast<RopePieceBTreeLeaf>(getRoot(Root)))
740
14.9k
    Leaf->clear();
741
0
  else {
742
0
    getRoot(Root)->Destroy();
743
0
    Root = new RopePieceBTreeLeaf();
744
0
  }
745
14.9k
}
746
747
141k
void RopePieceBTree::insert(unsigned Offset, const RopePiece &R) {
748
  // #1. Split at Offset.
749
141k
  if (RopePieceBTreeNode *RHS = getRoot(Root)->split(Offset))
750
95
    Root = new RopePieceBTreeInterior(getRoot(Root), RHS);
751
752
  // #2. Do the insertion.
753
141k
  if (RopePieceBTreeNode *RHS = getRoot(Root)->insert(Offset, R))
754
1.02k
    Root = new RopePieceBTreeInterior(getRoot(Root), RHS);
755
141k
}
756
757
48.3k
void RopePieceBTree::erase(unsigned Offset, unsigned NumBytes) {
758
  // #1. Split at Offset.
759
48.3k
  if (RopePieceBTreeNode *RHS = getRoot(Root)->split(Offset))
760
172
    Root = new RopePieceBTreeInterior(getRoot(Root), RHS);
761
762
  // #2. Do the erasing.
763
48.3k
  getRoot(Root)->erase(Offset, NumBytes);
764
48.3k
}
765
766
//===----------------------------------------------------------------------===//
767
// RewriteRope Implementation
768
//===----------------------------------------------------------------------===//
769
770
/// MakeRopeString - This copies the specified byte range into some instance of
771
/// RopeRefCountString, and return a RopePiece that represents it.  This uses
772
/// the AllocBuffer object to aggregate requests for small strings into one
773
/// allocation instead of doing tons of tiny allocations.
774
141k
RopePiece RewriteRope::MakeRopeString(const char *Start, const char *End) {
775
141k
  unsigned Len = End-Start;
776
141k
  assert(Len && "Zero length RopePiece is invalid!");
777
778
  // If we have space for this string in the current alloc buffer, use it.
779
141k
  if (AllocOffs+Len <= AllocChunkSize) {
780
125k
    memcpy(AllocBuffer->Data+AllocOffs, Start, Len);
781
125k
    AllocOffs += Len;
782
125k
    return RopePiece(AllocBuffer, AllocOffs-Len, AllocOffs);
783
125k
  }
784
785
  // If we don't have enough room because this specific allocation is huge,
786
  // just allocate a new rope piece for it alone.
787
16.2k
  if (Len > AllocChunkSize) {
788
274
    unsigned Size = End-Start+sizeof(RopeRefCountString)-1;
789
274
    auto *Res = reinterpret_cast<RopeRefCountString *>(new char[Size]);
790
274
    Res->RefCount = 0;
791
274
    memcpy(Res->Data, Start, End-Start);
792
274
    return RopePiece(Res, 0, End-Start);
793
274
  }
794
795
  // Otherwise, this was a small request but we just don't have space for it
796
  // Make a new chunk and share it with later allocations.
797
798
15.9k
  unsigned AllocSize = offsetof(RopeRefCountString, Data) + AllocChunkSize;
799
15.9k
  auto *Res = reinterpret_cast<RopeRefCountString *>(new char[AllocSize]);
800
15.9k
  Res->RefCount = 0;
801
15.9k
  memcpy(Res->Data, Start, Len);
802
15.9k
  AllocBuffer = Res;
803
15.9k
  AllocOffs = Len;
804
805
15.9k
  return RopePiece(AllocBuffer, 0, Len);
806
15.9k
}