Coverage Report

Created: 2018-07-22 10:17

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