1//===- LiveInterval.cpp - Live Interval Representation --------------------===//
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 LiveRange and LiveInterval classes. Given some
10// numbering of each the machine instructions an interval [i, j) is said to be a
11// live range for register v if there is no instruction with number j' >= j
12// such that v is live at j' and there is no instruction with number i' < i such
13// that v is live at i'. In this implementation ranges can have holes,
14// i.e. a range might look like [1,20), [50,65), [1000,1001). Each
15// individual segment is represented as an instance of LiveRange::Segment,
16// and the whole range is represented as an instance of LiveRange.
17//
18//===----------------------------------------------------------------------===//
19
20#include "llvm/CodeGen/LiveInterval.h"
21#include "LiveRangeUtils.h"
22#include "RegisterCoalescer.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/iterator_range.h"
28#include "llvm/CodeGen/LiveIntervals.h"
29#include "llvm/CodeGen/MachineBasicBlock.h"
30#include "llvm/CodeGen/MachineInstr.h"
31#include "llvm/CodeGen/MachineOperand.h"
32#include "llvm/CodeGen/MachineRegisterInfo.h"
33#include "llvm/CodeGen/SlotIndexes.h"
34#include "llvm/CodeGen/TargetRegisterInfo.h"
35#include "llvm/Config/llvm-config.h"
36#include "llvm/MC/LaneBitmask.h"
37#include "llvm/Support/Compiler.h"
38#include "llvm/Support/Debug.h"
39#include "llvm/Support/raw_ostream.h"
40#include <algorithm>
41#include <cassert>
42#include <cstddef>
43#include <iterator>
44#include <utility>
45
46using namespace llvm;
47
48namespace {
49
50//===----------------------------------------------------------------------===//
51// Implementation of various methods necessary for calculation of live ranges.
52// The implementation of the methods abstracts from the concrete type of the
53// segment collection.
54//
55// Implementation of the class follows the Template design pattern. The base
56// class contains generic algorithms that call collection-specific methods,
57// which are provided in concrete subclasses. In order to avoid virtual calls
58// these methods are provided by means of C++ template instantiation.
59// The base class calls the methods of the subclass through method impl(),
60// which casts 'this' pointer to the type of the subclass.
61//
62//===----------------------------------------------------------------------===//
63
64template <typename ImplT, typename IteratorT, typename CollectionT>
65class CalcLiveRangeUtilBase {
66protected:
67 LiveRange *LR;
68
69protected:
70 CalcLiveRangeUtilBase(LiveRange *LR) : LR(LR) {}
71
72public:
73 using Segment = LiveRange::Segment;
74 using iterator = IteratorT;
75
76 /// A counterpart of LiveRange::createDeadDef: Make sure the range has a
77 /// value defined at @p Def.
78 /// If @p ForVNI is null, and there is no value defined at @p Def, a new
79 /// value will be allocated using @p VNInfoAllocator.
80 /// If @p ForVNI is null, the return value is the value defined at @p Def,
81 /// either a pre-existing one, or the one newly created.
82 /// If @p ForVNI is not null, then @p Def should be the location where
83 /// @p ForVNI is defined. If the range does not have a value defined at
84 /// @p Def, the value @p ForVNI will be used instead of allocating a new
85 /// one. If the range already has a value defined at @p Def, it must be
86 /// same as @p ForVNI. In either case, @p ForVNI will be the return value.
87 VNInfo *createDeadDef(SlotIndex Def, VNInfo::Allocator *VNInfoAllocator,
88 VNInfo *ForVNI) {
89 assert(!Def.isDead() && "Cannot define a value at the dead slot");
90 assert((!ForVNI || ForVNI->def == Def) &&
91 "If ForVNI is specified, it must match Def");
92 iterator I = impl().find(Def);
93 if (I == segments().end()) {
94 VNInfo *VNI = ForVNI ? ForVNI : LR->getNextValue(Def, VNInfoAllocator&: *VNInfoAllocator);
95 impl().insertAtEnd(Segment(Def, Def.getDeadSlot(), VNI));
96 return VNI;
97 }
98
99 Segment *S = segmentAt(I);
100 if (SlotIndex::isSameInstr(A: Def, B: S->start)) {
101 assert((!ForVNI || ForVNI == S->valno) && "Value number mismatch");
102 assert(S->valno->def == S->start && "Inconsistent existing value def");
103
104 // It is possible to have both normal and early-clobber defs of the same
105 // register on an instruction. It doesn't make a lot of sense, but it is
106 // possible to specify in inline assembly.
107 //
108 // Just convert everything to early-clobber.
109 Def = std::min(a: Def, b: S->start);
110 if (Def != S->start)
111 S->start = S->valno->def = Def;
112 return S->valno;
113 }
114 assert(SlotIndex::isEarlierInstr(Def, S->start) && "Already live at def");
115 VNInfo *VNI = ForVNI ? ForVNI : LR->getNextValue(Def, VNInfoAllocator&: *VNInfoAllocator);
116 segments().insert(I, Segment(Def, Def.getDeadSlot(), VNI));
117 return VNI;
118 }
119
120 VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Use) {
121 if (segments().empty())
122 return nullptr;
123 iterator I =
124 impl().findInsertPos(Segment(Use.getPrevSlot(), Use, nullptr));
125 if (I == segments().begin())
126 return nullptr;
127 --I;
128 if (I->end <= StartIdx)
129 return nullptr;
130 if (I->end < Use)
131 extendSegmentEndTo(I, NewEnd: Use);
132 return I->valno;
133 }
134
135 std::pair<VNInfo*,bool> extendInBlock(ArrayRef<SlotIndex> Undefs,
136 SlotIndex StartIdx, SlotIndex Use) {
137 if (segments().empty())
138 return std::make_pair(x: nullptr, y: false);
139 SlotIndex BeforeUse = Use.getPrevSlot();
140 iterator I = impl().findInsertPos(Segment(BeforeUse, Use, nullptr));
141 if (I == segments().begin())
142 return std::make_pair(x: nullptr, y: LR->isUndefIn(Undefs, Begin: StartIdx, End: BeforeUse));
143 --I;
144 if (I->end <= StartIdx)
145 return std::make_pair(x: nullptr, y: LR->isUndefIn(Undefs, Begin: StartIdx, End: BeforeUse));
146 if (I->end < Use) {
147 if (LR->isUndefIn(Undefs, Begin: I->end, End: BeforeUse))
148 return std::make_pair(x: nullptr, y: true);
149 extendSegmentEndTo(I, NewEnd: Use);
150 }
151 return std::make_pair(I->valno, false);
152 }
153
154 /// This method is used when we want to extend the segment specified
155 /// by I to end at the specified endpoint. To do this, we should
156 /// merge and eliminate all segments that this will overlap
157 /// with. The iterator is not invalidated.
158 void extendSegmentEndTo(iterator I, SlotIndex NewEnd) {
159 assert(I != segments().end() && "Not a valid segment!");
160 Segment *S = segmentAt(I);
161 VNInfo *ValNo = I->valno;
162
163 // Search for the first segment that we can't merge with.
164 iterator MergeTo = std::next(I);
165 for (; MergeTo != segments().end() && NewEnd >= MergeTo->end; ++MergeTo)
166 assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
167
168 // If NewEnd was in the middle of a segment, make sure to get its endpoint.
169 S->end = std::max(NewEnd, std::prev(MergeTo)->end);
170
171 // If the newly formed segment now touches the segment after it and if they
172 // have the same value number, merge the two segments into one segment.
173 if (MergeTo != segments().end() && MergeTo->start <= I->end &&
174 MergeTo->valno == ValNo) {
175 S->end = MergeTo->end;
176 ++MergeTo;
177 }
178
179 // Erase any dead segments.
180 segments().erase(std::next(I), MergeTo);
181 }
182
183 /// This method is used when we want to extend the segment specified
184 /// by I to start at the specified endpoint. To do this, we should
185 /// merge and eliminate all segments that this will overlap with.
186 iterator extendSegmentStartTo(iterator I, SlotIndex NewStart) {
187 assert(I != segments().end() && "Not a valid segment!");
188 Segment *S = segmentAt(I);
189 VNInfo *ValNo = I->valno;
190
191 // Search for the first segment that we can't merge with.
192 iterator MergeTo = I;
193 do {
194 if (MergeTo == segments().begin()) {
195 S->start = NewStart;
196 segments().erase(MergeTo, I);
197 return I;
198 }
199 assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
200 --MergeTo;
201 } while (NewStart <= MergeTo->start);
202
203 // If we start in the middle of another segment, just delete a range and
204 // extend that segment.
205 if (MergeTo->end >= NewStart && MergeTo->valno == ValNo) {
206 segmentAt(I: MergeTo)->end = S->end;
207 } else {
208 // Otherwise, extend the segment right after.
209 ++MergeTo;
210 Segment *MergeToSeg = segmentAt(I: MergeTo);
211 MergeToSeg->start = NewStart;
212 MergeToSeg->end = S->end;
213 }
214
215 segments().erase(std::next(MergeTo), std::next(I));
216 return MergeTo;
217 }
218
219 iterator addSegment(Segment S) {
220 SlotIndex Start = S.start, End = S.end;
221 iterator I = impl().findInsertPos(S);
222
223 // If the inserted segment starts in the middle or right at the end of
224 // another segment, just extend that segment to contain the segment of S.
225 if (I != segments().begin()) {
226 iterator B = std::prev(I);
227 if (S.valno == B->valno) {
228 if (B->start <= Start && B->end >= Start) {
229 extendSegmentEndTo(I: B, NewEnd: End);
230 return B;
231 }
232 } else {
233 // Check to make sure that we are not overlapping two live segments with
234 // different valno's.
235 assert(B->end <= Start &&
236 "Cannot overlap two segments with differing ValID's"
237 " (did you def the same reg twice in a MachineInstr?)");
238 }
239 }
240
241 // Otherwise, if this segment ends in the middle of, or right next
242 // to, another segment, merge it into that segment.
243 if (I != segments().end()) {
244 if (S.valno == I->valno) {
245 if (I->start <= End) {
246 I = extendSegmentStartTo(I, NewStart: Start);
247
248 // If S is a complete superset of a segment, we may need to grow its
249 // endpoint as well.
250 if (End > I->end)
251 extendSegmentEndTo(I, NewEnd: End);
252 return I;
253 }
254 } else {
255 // Check to make sure that we are not overlapping two live segments with
256 // different valno's.
257 assert(I->start >= End &&
258 "Cannot overlap two segments with differing ValID's");
259 }
260 }
261
262 // Otherwise, this is just a new segment that doesn't interact with
263 // anything.
264 // Insert it.
265 return segments().insert(I, S);
266 }
267
268private:
269 ImplT &impl() { return *static_cast<ImplT *>(this); }
270
271 CollectionT &segments() { return impl().segmentsColl(); }
272
273 Segment *segmentAt(iterator I) { return const_cast<Segment *>(&(*I)); }
274};
275
276//===----------------------------------------------------------------------===//
277// Instantiation of the methods for calculation of live ranges
278// based on a segment vector.
279//===----------------------------------------------------------------------===//
280
281class CalcLiveRangeUtilVector;
282using CalcLiveRangeUtilVectorBase =
283 CalcLiveRangeUtilBase<CalcLiveRangeUtilVector, LiveRange::iterator,
284 LiveRange::Segments>;
285
286class CalcLiveRangeUtilVector : public CalcLiveRangeUtilVectorBase {
287public:
288 CalcLiveRangeUtilVector(LiveRange *LR) : CalcLiveRangeUtilVectorBase(LR) {}
289
290private:
291 friend CalcLiveRangeUtilVectorBase;
292
293 LiveRange::Segments &segmentsColl() { return LR->segments; }
294
295 void insertAtEnd(const Segment &S) { LR->segments.push_back(Elt: S); }
296
297 iterator find(SlotIndex Pos) { return LR->find(Pos); }
298
299 iterator findInsertPos(Segment S) { return llvm::upper_bound(Range&: *LR, Value&: S.start); }
300};
301
302//===----------------------------------------------------------------------===//
303// Instantiation of the methods for calculation of live ranges
304// based on a segment set.
305//===----------------------------------------------------------------------===//
306
307class CalcLiveRangeUtilSet;
308using CalcLiveRangeUtilSetBase =
309 CalcLiveRangeUtilBase<CalcLiveRangeUtilSet, LiveRange::SegmentSet::iterator,
310 LiveRange::SegmentSet>;
311
312class CalcLiveRangeUtilSet : public CalcLiveRangeUtilSetBase {
313public:
314 CalcLiveRangeUtilSet(LiveRange *LR) : CalcLiveRangeUtilSetBase(LR) {}
315
316private:
317 friend CalcLiveRangeUtilSetBase;
318
319 LiveRange::SegmentSet &segmentsColl() { return *LR->segmentSet; }
320
321 void insertAtEnd(const Segment &S) {
322 LR->segmentSet->insert(position: LR->segmentSet->end(), x: S);
323 }
324
325 iterator find(SlotIndex Pos) {
326 iterator I =
327 LR->segmentSet->upper_bound(x: Segment(Pos, Pos.getNextSlot(), nullptr));
328 if (I == LR->segmentSet->begin())
329 return I;
330 iterator PrevI = std::prev(x: I);
331 if (Pos < (*PrevI).end)
332 return PrevI;
333 return I;
334 }
335
336 iterator findInsertPos(Segment S) {
337 iterator I = LR->segmentSet->upper_bound(x: S);
338 if (I != LR->segmentSet->end() && !(S.start < *I))
339 ++I;
340 return I;
341 }
342};
343
344} // end anonymous namespace
345
346//===----------------------------------------------------------------------===//
347// LiveRange methods
348//===----------------------------------------------------------------------===//
349
350LiveRange::iterator LiveRange::find(SlotIndex Pos) {
351 return llvm::partition_point(Range&: *this,
352 P: [&](const Segment &X) { return X.end <= Pos; });
353}
354
355VNInfo *LiveRange::createDeadDef(SlotIndex Def, VNInfo::Allocator &VNIAlloc) {
356 // Use the segment set, if it is available.
357 if (segmentSet != nullptr)
358 return CalcLiveRangeUtilSet(this).createDeadDef(Def, VNInfoAllocator: &VNIAlloc, ForVNI: nullptr);
359 // Otherwise use the segment vector.
360 return CalcLiveRangeUtilVector(this).createDeadDef(Def, VNInfoAllocator: &VNIAlloc, ForVNI: nullptr);
361}
362
363VNInfo *LiveRange::createDeadDef(VNInfo *VNI) {
364 // Use the segment set, if it is available.
365 if (segmentSet != nullptr)
366 return CalcLiveRangeUtilSet(this).createDeadDef(Def: VNI->def, VNInfoAllocator: nullptr, ForVNI: VNI);
367 // Otherwise use the segment vector.
368 return CalcLiveRangeUtilVector(this).createDeadDef(Def: VNI->def, VNInfoAllocator: nullptr, ForVNI: VNI);
369}
370
371// overlaps - Return true if the intersection of the two live ranges is
372// not empty.
373//
374// An example for overlaps():
375//
376// 0: A = ...
377// 4: B = ...
378// 8: C = A + B ;; last use of A
379//
380// The live ranges should look like:
381//
382// A = [3, 11)
383// B = [7, x)
384// C = [11, y)
385//
386// A->overlaps(C) should return false since we want to be able to join
387// A and C.
388//
389bool LiveRange::overlapsFrom(const LiveRange& other,
390 const_iterator StartPos) const {
391 assert(!empty() && "empty range");
392 const_iterator i = begin();
393 const_iterator ie = end();
394 const_iterator j = StartPos;
395 const_iterator je = other.end();
396
397 assert((StartPos->start <= i->start || StartPos == other.begin()) &&
398 StartPos != other.end() && "Bogus start position hint!");
399
400 if (i->start < j->start) {
401 i = std::upper_bound(first: i, last: ie, val: j->start);
402 if (i != begin()) --i;
403 } else if (j->start < i->start) {
404 ++StartPos;
405 if (StartPos != other.end() && StartPos->start <= i->start) {
406 assert(StartPos < other.end() && i < end());
407 j = std::upper_bound(first: j, last: je, val: i->start);
408 if (j != other.begin()) --j;
409 }
410 } else {
411 return true;
412 }
413
414 if (j == je) return false;
415
416 while (i != ie) {
417 if (i->start > j->start) {
418 std::swap(a&: i, b&: j);
419 std::swap(a&: ie, b&: je);
420 }
421
422 if (i->end > j->start)
423 return true;
424 ++i;
425 }
426
427 return false;
428}
429
430bool LiveRange::overlaps(const LiveRange &Other, const CoalescerPair &CP,
431 const SlotIndexes &Indexes) const {
432 assert(!empty() && "empty range");
433 if (Other.empty())
434 return false;
435
436 // Use binary searches to find initial positions.
437 const_iterator I = find(Pos: Other.beginIndex());
438 const_iterator IE = end();
439 if (I == IE)
440 return false;
441 const_iterator J = Other.find(Pos: I->start);
442 const_iterator JE = Other.end();
443 if (J == JE)
444 return false;
445
446 while (true) {
447 // J has just been advanced to satisfy:
448 assert(J->end > I->start);
449 // Check for an overlap.
450 if (J->start < I->end) {
451 // I and J are overlapping. Find the later start.
452 SlotIndex Def = std::max(a: I->start, b: J->start);
453 // Allow the overlap if Def is a coalescable copy.
454 if (Def.isBlock() ||
455 !CP.isCoalescable(Indexes.getInstructionFromIndex(index: Def)))
456 return true;
457 }
458 // Advance the iterator that ends first to check for more overlaps.
459 if (J->end > I->end) {
460 std::swap(a&: I, b&: J);
461 std::swap(a&: IE, b&: JE);
462 }
463 // Advance J until J->end > I->start.
464 do
465 if (++J == JE)
466 return false;
467 while (J->end <= I->start);
468 }
469}
470
471/// overlaps - Return true if the live range overlaps an interval specified
472/// by [Start, End).
473bool LiveRange::overlaps(SlotIndex Start, SlotIndex End) const {
474 assert(Start < End && "Invalid range");
475 const_iterator I = lower_bound(Range: *this, Value&: End);
476 return I != begin() && (--I)->end > Start;
477}
478
479bool LiveRange::covers(const LiveRange &Other) const {
480 if (empty())
481 return Other.empty();
482
483 const_iterator I = begin();
484 for (const Segment &O : Other.segments) {
485 I = advanceTo(I, Pos: O.start);
486 if (I == end() || I->start > O.start)
487 return false;
488
489 // Check adjacent live segments and see if we can get behind O.end.
490 while (I->end < O.end) {
491 const_iterator Last = I;
492 // Get next segment and abort if it was not adjacent.
493 ++I;
494 if (I == end() || Last->end != I->start)
495 return false;
496 }
497 }
498 return true;
499}
500
501/// ValNo is dead, remove it. If it is the largest value number, just nuke it
502/// (and any other deleted values neighboring it), otherwise mark it as ~1U so
503/// it can be nuked later.
504void LiveRange::markValNoForDeletion(VNInfo *ValNo) {
505 if (ValNo->id == getNumValNums()-1) {
506 do {
507 valnos.pop_back();
508 } while (!valnos.empty() && valnos.back()->isUnused());
509 } else {
510 ValNo->markUnused();
511 }
512}
513
514/// RenumberValues - Renumber all values in order of appearance and delete the
515/// remaining unused values.
516void LiveRange::RenumberValues() {
517 SmallPtrSet<VNInfo*, 8> Seen;
518 valnos.clear();
519 for (const Segment &S : segments) {
520 VNInfo *VNI = S.valno;
521 if (!Seen.insert(Ptr: VNI).second)
522 continue;
523 assert(!VNI->isUnused() && "Unused valno used by live segment");
524 VNI->id = (unsigned)valnos.size();
525 valnos.push_back(Elt: VNI);
526 }
527}
528
529void LiveRange::addSegmentToSet(Segment S) {
530 CalcLiveRangeUtilSet(this).addSegment(S);
531}
532
533LiveRange::iterator LiveRange::addSegment(Segment S) {
534 // Use the segment set, if it is available.
535 if (segmentSet != nullptr) {
536 addSegmentToSet(S);
537 return end();
538 }
539 // Otherwise use the segment vector.
540 return CalcLiveRangeUtilVector(this).addSegment(S);
541}
542
543LiveRange::iterator LiveRange::mergeAdjacentSegments(iterator I) {
544 assert(segmentSet == nullptr && "Cannot merge with active segment set");
545 assert(I != end() && "Cannot merge end iterator");
546
547 if (I != begin()) {
548 iterator Prev = std::prev(x: I);
549 if (Prev->valno == I->valno && Prev->end == I->start) {
550 Prev->end = I->end;
551 segments.erase(CI: I);
552 I = Prev;
553 }
554 }
555
556 iterator Next = std::next(x: I);
557 if (Next != end() && I->valno == Next->valno && I->end == Next->start) {
558 I->end = Next->end;
559 segments.erase(CI: Next);
560 }
561
562 return I;
563}
564
565void LiveRange::append(const Segment S) {
566 // Check that the segment belongs to the back of the list.
567 assert(segments.empty() || segments.back().end <= S.start);
568 segments.push_back(Elt: S);
569}
570
571std::pair<VNInfo*,bool> LiveRange::extendInBlock(ArrayRef<SlotIndex> Undefs,
572 SlotIndex StartIdx, SlotIndex Kill) {
573 // Use the segment set, if it is available.
574 if (segmentSet != nullptr)
575 return CalcLiveRangeUtilSet(this).extendInBlock(Undefs, StartIdx, Use: Kill);
576 // Otherwise use the segment vector.
577 return CalcLiveRangeUtilVector(this).extendInBlock(Undefs, StartIdx, Use: Kill);
578}
579
580VNInfo *LiveRange::extendInBlock(SlotIndex StartIdx, SlotIndex Kill) {
581 // Use the segment set, if it is available.
582 if (segmentSet != nullptr)
583 return CalcLiveRangeUtilSet(this).extendInBlock(StartIdx, Use: Kill);
584 // Otherwise use the segment vector.
585 return CalcLiveRangeUtilVector(this).extendInBlock(StartIdx, Use: Kill);
586}
587
588void LiveRange::removeSegment(SlotIndex Start, SlotIndex End,
589 bool RemoveDeadValNo) {
590 // Find the Segment containing this span.
591 iterator I = find(Pos: Start);
592
593 // No Segment found, so nothing to do.
594 if (I == end())
595 return;
596
597 assert(I->containsInterval(Start, End)
598 && "Segment is not entirely in range!");
599
600 // If the span we are removing is at the start of the Segment, adjust it.
601 VNInfo *ValNo = I->valno;
602 if (I->start == Start) {
603 if (I->end == End) {
604 segments.erase(CI: I); // Removed the whole Segment.
605
606 if (RemoveDeadValNo)
607 removeValNoIfDead(ValNo);
608 } else
609 I->start = End;
610 return;
611 }
612
613 // Otherwise if the span we are removing is at the end of the Segment,
614 // adjust the other way.
615 if (I->end == End) {
616 I->end = Start;
617 return;
618 }
619
620 // Otherwise, we are splitting the Segment into two pieces.
621 SlotIndex OldEnd = I->end;
622 I->end = Start; // Trim the old segment.
623
624 // Insert the new one.
625 segments.insert(I: std::next(x: I), Elt: Segment(End, OldEnd, ValNo));
626}
627
628LiveRange::iterator LiveRange::removeSegment(iterator I, bool RemoveDeadValNo) {
629 VNInfo *ValNo = I->valno;
630 I = segments.erase(CI: I);
631 if (RemoveDeadValNo)
632 removeValNoIfDead(ValNo);
633 return I;
634}
635
636void LiveRange::removeValNoIfDead(VNInfo *ValNo) {
637 if (none_of(Range&: *this, P: [=](const Segment &S) { return S.valno == ValNo; }))
638 markValNoForDeletion(ValNo);
639}
640
641/// removeValNo - Remove all the segments defined by the specified value#.
642/// Also remove the value# from value# list.
643void LiveRange::removeValNo(VNInfo *ValNo) {
644 if (empty()) return;
645 llvm::erase_if(C&: segments,
646 P: [ValNo](const Segment &S) { return S.valno == ValNo; });
647 // Now that ValNo is dead, remove it.
648 markValNoForDeletion(ValNo);
649}
650
651void LiveRange::join(LiveRange &Other,
652 const int *LHSValNoAssignments,
653 const int *RHSValNoAssignments,
654 SmallVectorImpl<VNInfo *> &NewVNInfo) {
655 assert(verify());
656 assert(Other.verify());
657
658 // Determine if any of our values are mapped. This is uncommon, so we want
659 // to avoid the range scan if not.
660 bool MustMapCurValNos = false;
661 unsigned NumVals = getNumValNums();
662 unsigned NumNewVals = NewVNInfo.size();
663 for (unsigned i = 0; i != NumVals; ++i) {
664 unsigned LHSValID = LHSValNoAssignments[i];
665 if (i != LHSValID ||
666 (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(ValNo: i))) {
667 MustMapCurValNos = true;
668 break;
669 }
670 }
671
672 // If we have to apply a mapping to our base range assignment, rewrite it now.
673 if (MustMapCurValNos && !empty()) {
674 // Map the first live range.
675
676 iterator OutIt = begin();
677 OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
678 for (iterator I = std::next(x: OutIt), E = end(); I != E; ++I) {
679 VNInfo* nextValNo = NewVNInfo[LHSValNoAssignments[I->valno->id]];
680 assert(nextValNo && "Huh?");
681
682 // If this live range has the same value # as its immediate predecessor,
683 // and if they are neighbors, remove one Segment. This happens when we
684 // have [0,4:0)[4,7:1) and map 0/1 onto the same value #.
685 if (OutIt->valno == nextValNo && OutIt->end == I->start) {
686 OutIt->end = I->end;
687 } else {
688 // Didn't merge. Move OutIt to the next segment,
689 ++OutIt;
690 OutIt->valno = nextValNo;
691 if (OutIt != I) {
692 OutIt->start = I->start;
693 OutIt->end = I->end;
694 }
695 }
696 }
697 // If we merge some segments, chop off the end.
698 ++OutIt;
699 segments.erase(CS: OutIt, CE: end());
700 }
701
702 // Rewrite Other values before changing the VNInfo ids.
703 // This can leave Other in an invalid state because we're not coalescing
704 // touching segments that now have identical values. That's OK since Other is
705 // not supposed to be valid after calling join();
706 for (Segment &S : Other.segments)
707 S.valno = NewVNInfo[RHSValNoAssignments[S.valno->id]];
708
709 // Update val# info. Renumber them and make sure they all belong to this
710 // LiveRange now. Also remove dead val#'s.
711 unsigned NumValNos = 0;
712 for (unsigned i = 0; i < NumNewVals; ++i) {
713 VNInfo *VNI = NewVNInfo[i];
714 if (VNI) {
715 if (NumValNos >= NumVals)
716 valnos.push_back(Elt: VNI);
717 else
718 valnos[NumValNos] = VNI;
719 VNI->id = NumValNos++; // Renumber val#.
720 }
721 }
722 if (NumNewVals < NumVals)
723 valnos.resize(N: NumNewVals); // shrinkify
724
725 // Okay, now insert the RHS live segments into the LHS.
726 LiveRangeUpdater Updater(this);
727 for (Segment &S : Other.segments)
728 Updater.add(S);
729}
730
731/// Merge all of the segments in RHS into this live range as the specified
732/// value number. The segments in RHS are allowed to overlap with segments in
733/// the current range, but only if the overlapping segments have the
734/// specified value number.
735void LiveRange::MergeSegmentsInAsValue(const LiveRange &RHS,
736 VNInfo *LHSValNo) {
737 LiveRangeUpdater Updater(this);
738 for (const Segment &S : RHS.segments)
739 Updater.add(Start: S.start, End: S.end, VNI: LHSValNo);
740}
741
742/// MergeValueInAsValue - Merge all of the live segments of a specific val#
743/// in RHS into this live range as the specified value number.
744/// The segments in RHS are allowed to overlap with segments in the
745/// current range, it will replace the value numbers of the overlaped
746/// segments with the specified value number.
747void LiveRange::MergeValueInAsValue(const LiveRange &RHS,
748 const VNInfo *RHSValNo,
749 VNInfo *LHSValNo) {
750 LiveRangeUpdater Updater(this);
751 for (const Segment &S : RHS.segments)
752 if (S.valno == RHSValNo)
753 Updater.add(Start: S.start, End: S.end, VNI: LHSValNo);
754}
755
756/// MergeValueNumberInto - This method is called when two value nubmers
757/// are found to be equivalent. This eliminates V1, replacing all
758/// segments with the V1 value number with the V2 value number. This can
759/// cause merging of V1/V2 values numbers and compaction of the value space.
760VNInfo *LiveRange::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) {
761 assert(V1 != V2 && "Identical value#'s are always equivalent!");
762
763 // This code actually merges the (numerically) larger value number into the
764 // smaller value number, which is likely to allow us to compactify the value
765 // space. The only thing we have to be careful of is to preserve the
766 // instruction that defines the result value.
767
768 // Make sure V2 is smaller than V1.
769 if (V1->id < V2->id) {
770 V1->copyFrom(src&: *V2);
771 std::swap(a&: V1, b&: V2);
772 }
773
774 // Merge V1 segments into V2.
775 for (iterator I = begin(); I != end(); ) {
776 iterator S = I++;
777 if (S->valno != V1) continue; // Not a V1 Segment.
778
779 // After changing this segment to V2, it may touch an adjacent V2 segment.
780 // Merge with either neighbor before continuing.
781 S->valno = V2;
782 I = std::next(x: mergeAdjacentSegments(I: S));
783 }
784
785 // Now that V1 is dead, remove it.
786 markValNoForDeletion(ValNo: V1);
787
788 return V2;
789}
790
791void LiveRange::flushSegmentSet() {
792 assert(segmentSet != nullptr && "segment set must have been created");
793 assert(
794 segments.empty() &&
795 "segment set can be used only initially before switching to the array");
796 segments.append(in_start: segmentSet->begin(), in_end: segmentSet->end());
797 segmentSet = nullptr;
798 assert(verify());
799}
800
801bool LiveRange::isLiveAtIndexes(ArrayRef<SlotIndex> Slots) const {
802 ArrayRef<SlotIndex>::iterator SlotI = Slots.begin();
803 ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
804
805 // If there are no regmask slots, we have nothing to search.
806 if (SlotI == SlotE)
807 return false;
808
809 // Start our search at the first segment that ends after the first slot.
810 const_iterator SegmentI = find(Pos: *SlotI);
811 const_iterator SegmentE = end();
812
813 // If there are no segments that end after the first slot, we're done.
814 if (SegmentI == SegmentE)
815 return false;
816
817 // Look for each slot in the live range.
818 for ( ; SlotI != SlotE; ++SlotI) {
819 // Go to the next segment that ends after the current slot.
820 // The slot may be within a hole in the range.
821 SegmentI = advanceTo(I: SegmentI, Pos: *SlotI);
822 if (SegmentI == SegmentE)
823 return false;
824
825 // If this segment contains the slot, we're done.
826 if (SegmentI->contains(I: *SlotI))
827 return true;
828 // Otherwise, look for the next slot.
829 }
830
831 // We didn't find a segment containing any of the slots.
832 return false;
833}
834
835void LiveInterval::freeSubRange(SubRange *S) {
836 S->~SubRange();
837 // Memory was allocated with BumpPtr allocator and is not freed here.
838}
839
840void LiveInterval::removeEmptySubRanges() {
841 SubRange **NextPtr = &SubRanges;
842 SubRange *I = *NextPtr;
843 while (I != nullptr) {
844 if (!I->empty()) {
845 NextPtr = &I->Next;
846 I = *NextPtr;
847 continue;
848 }
849 // Skip empty subranges until we find the first nonempty one.
850 do {
851 SubRange *Next = I->Next;
852 freeSubRange(S: I);
853 I = Next;
854 } while (I != nullptr && I->empty());
855 *NextPtr = I;
856 }
857}
858
859void LiveInterval::clearSubRanges() {
860 for (SubRange *I = SubRanges, *Next; I != nullptr; I = Next) {
861 Next = I->Next;
862 freeSubRange(S: I);
863 }
864 SubRanges = nullptr;
865}
866
867/// For each VNI in \p SR, check whether or not that value defines part
868/// of the mask describe by \p LaneMask and if not, remove that value
869/// from \p SR.
870static void stripValuesNotDefiningMask(Register Reg, LiveInterval::SubRange &SR,
871 LaneBitmask LaneMask,
872 const SlotIndexes &Indexes,
873 const TargetRegisterInfo &TRI,
874 unsigned ComposeSubRegIdx) {
875 // Phys reg should not be tracked at subreg level.
876 // Same for noreg (Reg == 0).
877 if (!Reg || !Reg.isVirtual())
878 return;
879 // Remove the values that don't define those lanes.
880 SmallVector<VNInfo *, 8> ToBeRemoved;
881 for (VNInfo *VNI : SR.valnos) {
882 if (VNI->isUnused())
883 continue;
884 // PHI definitions don't have MI attached, so there is nothing
885 // we can use to strip the VNI.
886 if (VNI->isPHIDef())
887 continue;
888 const MachineInstr *MI = Indexes.getInstructionFromIndex(index: VNI->def);
889 assert(MI && "Cannot find the definition of a value");
890 bool hasDef = false;
891 for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
892 if (!MOI->isReg() || !MOI->isDef())
893 continue;
894 if (MOI->getReg() != Reg)
895 continue;
896 LaneBitmask OrigMask = TRI.getSubRegIndexLaneMask(SubIdx: MOI->getSubReg());
897 LaneBitmask ExpectedDefMask =
898 ComposeSubRegIdx
899 ? TRI.composeSubRegIndexLaneMask(IdxA: ComposeSubRegIdx, Mask: OrigMask)
900 : OrigMask;
901 if ((ExpectedDefMask & LaneMask).none())
902 continue;
903 hasDef = true;
904 break;
905 }
906
907 if (!hasDef)
908 ToBeRemoved.push_back(Elt: VNI);
909 }
910 for (VNInfo *VNI : ToBeRemoved)
911 SR.removeValNo(ValNo: VNI);
912
913 // If the subrange is empty at this point, the MIR is invalid. Do not assert
914 // and let the verifier catch this case.
915}
916
917void LiveInterval::refineSubRanges(
918 BumpPtrAllocator &Allocator, LaneBitmask LaneMask,
919 std::function<void(LiveInterval::SubRange &)> Apply,
920 const SlotIndexes &Indexes, const TargetRegisterInfo &TRI,
921 unsigned ComposeSubRegIdx) {
922 LaneBitmask ToApply = LaneMask;
923 for (SubRange &SR : subranges()) {
924 LaneBitmask SRMask = SR.LaneMask;
925 LaneBitmask Matching = SRMask & LaneMask;
926 if (Matching.none())
927 continue;
928
929 SubRange *MatchingRange;
930 if (SRMask == Matching) {
931 // The subrange fits (it does not cover bits outside \p LaneMask).
932 MatchingRange = &SR;
933 } else {
934 // We have to split the subrange into a matching and non-matching part.
935 // Reduce lanemask of existing lane to non-matching part.
936 SR.LaneMask = SRMask & ~Matching;
937 // Create a new subrange for the matching part
938 MatchingRange = createSubRangeFrom(Allocator, LaneMask: Matching, CopyFrom: SR);
939 // Now that the subrange is split in half, make sure we
940 // only keep in the subranges the VNIs that touch the related half.
941 stripValuesNotDefiningMask(Reg: reg(), SR&: *MatchingRange, LaneMask: Matching, Indexes, TRI,
942 ComposeSubRegIdx);
943 stripValuesNotDefiningMask(Reg: reg(), SR, LaneMask: SR.LaneMask, Indexes, TRI,
944 ComposeSubRegIdx);
945 }
946 Apply(*MatchingRange);
947 ToApply &= ~Matching;
948 }
949 // Create a new subrange if there are uncovered bits left.
950 if (ToApply.any()) {
951 SubRange *NewRange = createSubRange(Allocator, LaneMask: ToApply);
952 Apply(*NewRange);
953 }
954}
955
956unsigned LiveInterval::getSize() const {
957 unsigned Sum = 0;
958 for (const Segment &S : segments)
959 Sum += S.start.distance(other: S.end);
960 return Sum;
961}
962
963void LiveInterval::computeSubRangeUndefs(SmallVectorImpl<SlotIndex> &Undefs,
964 LaneBitmask LaneMask,
965 const MachineRegisterInfo &MRI,
966 const SlotIndexes &Indexes) const {
967 assert(reg().isVirtual());
968 LaneBitmask VRegMask = MRI.getMaxLaneMaskForVReg(Reg: reg());
969 assert((VRegMask & LaneMask).any());
970 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
971 for (const MachineOperand &MO : MRI.def_operands(Reg: reg())) {
972 if (!MO.isUndef())
973 continue;
974 unsigned SubReg = MO.getSubReg();
975 assert(SubReg != 0 && "Undef should only be set on subreg defs");
976 LaneBitmask DefMask = TRI.getSubRegIndexLaneMask(SubIdx: SubReg);
977 LaneBitmask UndefMask = VRegMask & ~DefMask;
978 if ((UndefMask & LaneMask).any()) {
979 const MachineInstr &MI = *MO.getParent();
980 bool EarlyClobber = MO.isEarlyClobber();
981 SlotIndex Pos = Indexes.getInstructionIndex(MI).getRegSlot(EC: EarlyClobber);
982 Undefs.push_back(Elt: Pos);
983 }
984 }
985}
986
987raw_ostream& llvm::operator<<(raw_ostream& OS, const LiveRange::Segment &S) {
988 return OS << '[' << S.start << ',' << S.end << ':' << S.valno->id << ')';
989}
990
991#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
992LLVM_DUMP_METHOD void LiveRange::Segment::dump() const {
993 dbgs() << *this << '\n';
994}
995#endif
996
997void VNInfo::print(raw_ostream &OS) const {
998 OS << id << '@';
999 if (isUnused()) {
1000 OS << 'x';
1001 } else {
1002 OS << def;
1003 if (isPHIDef())
1004 OS << "-phi";
1005 }
1006}
1007
1008void LiveRange::print(raw_ostream &OS) const {
1009 if (empty())
1010 OS << "EMPTY";
1011 else {
1012 for (const Segment &S : segments) {
1013 OS << S;
1014 assert(S.valno == getValNumInfo(S.valno->id) && "Bad VNInfo");
1015 }
1016 }
1017
1018 // Print value number info.
1019 if (getNumValNums()) {
1020 OS << ' ';
1021 unsigned vnum = 0;
1022 for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e;
1023 ++i, ++vnum) {
1024 const VNInfo *vni = *i;
1025 if (vnum)
1026 OS << ' ';
1027 OS << *vni;
1028 assert(vnum == vni->id && "Bad VNInfo");
1029 }
1030 }
1031}
1032
1033void LiveInterval::SubRange::print(raw_ostream &OS) const {
1034 OS << " L" << PrintLaneMask(LaneMask) << ' '
1035 << static_cast<const LiveRange &>(*this);
1036}
1037
1038void LiveInterval::print(raw_ostream &OS) const {
1039 OS << printReg(Reg: reg()) << ' ';
1040 super::print(OS);
1041 // Print subranges
1042 for (const SubRange &SR : subranges())
1043 OS << SR;
1044 OS << " weight:" << Weight;
1045}
1046
1047#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1048LLVM_DUMP_METHOD void VNInfo::dump() const { dbgs() << *this << '\n'; }
1049
1050LLVM_DUMP_METHOD void LiveRange::dump() const { dbgs() << *this << '\n'; }
1051
1052LLVM_DUMP_METHOD void LiveInterval::SubRange::dump() const {
1053 dbgs() << *this << '\n';
1054}
1055
1056LLVM_DUMP_METHOD void LiveInterval::dump() const {
1057 dbgs() << *this << '\n';
1058}
1059#endif
1060
1061#ifndef NDEBUG
1062bool LiveRange::verify() const {
1063 for (const_iterator I = begin(), E = end(); I != E; ++I) {
1064 if (!I->start.isValid())
1065 return false;
1066 if (!I->end.isValid())
1067 return false;
1068 if (I->start >= I->end)
1069 return false;
1070 if (I->valno == nullptr)
1071 return false;
1072 if (I->valno->id >= valnos.size())
1073 return false;
1074 if (I->valno != valnos[I->valno->id])
1075 return false;
1076 if (std::next(I) != E) {
1077 if (I->end > std::next(I)->start)
1078 return false;
1079 if (I->end == std::next(I)->start) {
1080 if (I->valno == std::next(I)->valno)
1081 return false;
1082 }
1083 }
1084 }
1085
1086 return true;
1087}
1088
1089bool LiveInterval::verify(const MachineRegisterInfo *MRI) const {
1090 if (!super::verify())
1091 return false;
1092
1093 // Make sure SubRanges are fine and LaneMasks are disjunct.
1094 LaneBitmask Mask;
1095 LaneBitmask MaxMask = MRI != nullptr ? MRI->getMaxLaneMaskForVReg(reg())
1096 : LaneBitmask::getAll();
1097 for (const SubRange &SR : subranges()) {
1098 // Subrange lanemask should be disjunct to any previous subrange masks.
1099 if ((Mask & SR.LaneMask).any())
1100 return false;
1101
1102 Mask |= SR.LaneMask;
1103
1104 // subrange mask should not contained in maximum lane mask for the vreg.
1105 if ((Mask & ~MaxMask).any())
1106 return false;
1107
1108 // empty subranges must be removed.
1109 if (SR.empty())
1110 return false;
1111
1112 if (!SR.verify())
1113 return false;
1114
1115 // Main liverange should cover subrange.
1116 if (!covers(SR))
1117 return false;
1118 }
1119
1120 return true;
1121}
1122#endif
1123
1124//===----------------------------------------------------------------------===//
1125// LiveRangeUpdater class
1126//===----------------------------------------------------------------------===//
1127//
1128// The LiveRangeUpdater class always maintains these invariants:
1129//
1130// - When LastStart is invalid, Spills is empty and the iterators are invalid.
1131// This is the initial state, and the state created by flush().
1132// In this state, isDirty() returns false.
1133//
1134// Otherwise, segments are kept in three separate areas:
1135//
1136// 1. [begin; WriteI) at the front of LR.
1137// 2. [ReadI; end) at the back of LR.
1138// 3. Spills.
1139//
1140// - LR.begin() <= WriteI <= ReadI <= LR.end().
1141// - Segments in all three areas are fully ordered and coalesced.
1142// - Segments in area 1 precede and can't coalesce with segments in area 2.
1143// - Segments in Spills precede and can't coalesce with segments in area 2.
1144// - No coalescing is possible between segments in Spills and segments in area
1145// 1, and there are no overlapping segments.
1146//
1147// The segments in Spills are not ordered with respect to the segments in area
1148// 1. They need to be merged.
1149//
1150// When they exist, Spills.back().start <= LastStart,
1151// and WriteI[-1].start <= LastStart.
1152
1153#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1154void LiveRangeUpdater::print(raw_ostream &OS) const {
1155 if (!isDirty()) {
1156 if (LR)
1157 OS << "Clean updater: " << *LR << '\n';
1158 else
1159 OS << "Null updater.\n";
1160 return;
1161 }
1162 assert(LR && "Can't have null LR in dirty updater.");
1163 OS << " updater with gap = " << (ReadI - WriteI)
1164 << ", last start = " << LastStart
1165 << ":\n Area 1:";
1166 for (const auto &S : make_range(LR->begin(), WriteI))
1167 OS << ' ' << S;
1168 OS << "\n Spills:";
1169 for (const LiveRange::Segment &Spill : Spills)
1170 OS << ' ' << Spill;
1171 OS << "\n Area 2:";
1172 for (const auto &S : make_range(ReadI, LR->end()))
1173 OS << ' ' << S;
1174 OS << '\n';
1175}
1176
1177LLVM_DUMP_METHOD void LiveRangeUpdater::dump() const {
1178 print(errs());
1179}
1180#endif
1181
1182// Determine if A and B should be coalesced.
1183static inline bool coalescable(const LiveRange::Segment &A,
1184 const LiveRange::Segment &B) {
1185 assert(A.start <= B.start && "Unordered live segments.");
1186 if (A.end == B.start)
1187 return A.valno == B.valno;
1188 if (A.end < B.start)
1189 return false;
1190 assert(A.valno == B.valno && "Cannot overlap different values");
1191 return true;
1192}
1193
1194void LiveRangeUpdater::add(LiveRange::Segment Seg) {
1195 assert(LR && "Cannot add to a null destination");
1196
1197 // Fall back to the regular add method if the live range
1198 // is using the segment set instead of the segment vector.
1199 if (LR->segmentSet != nullptr) {
1200 LR->addSegmentToSet(S: Seg);
1201 return;
1202 }
1203
1204 // Flush the state if Start moves backwards.
1205 if (!LastStart.isValid() || LastStart > Seg.start) {
1206 if (isDirty())
1207 flush();
1208 // This brings us to an uninitialized state. Reinitialize.
1209 assert(Spills.empty() && "Leftover spilled segments");
1210 WriteI = ReadI = LR->begin();
1211 }
1212
1213 // Remember start for next time.
1214 LastStart = Seg.start;
1215
1216 // Advance ReadI until it ends after Seg.start.
1217 LiveRange::iterator E = LR->end();
1218 if (ReadI != E && ReadI->end <= Seg.start) {
1219 // First try to close the gap between WriteI and ReadI with spills.
1220 if (ReadI != WriteI)
1221 mergeSpills();
1222 // Then advance ReadI.
1223 if (ReadI == WriteI)
1224 ReadI = WriteI = LR->find(Pos: Seg.start);
1225 else
1226 while (ReadI != E && ReadI->end <= Seg.start)
1227 *WriteI++ = *ReadI++;
1228 }
1229
1230 assert(ReadI == E || ReadI->end > Seg.start);
1231
1232 // Check if the ReadI segment begins early.
1233 if (ReadI != E && ReadI->start <= Seg.start) {
1234 assert(ReadI->valno == Seg.valno && "Cannot overlap different values");
1235 // Bail if Seg is completely contained in ReadI.
1236 if (ReadI->end >= Seg.end)
1237 return;
1238 // Coalesce into Seg.
1239 Seg.start = ReadI->start;
1240 ++ReadI;
1241 }
1242
1243 // Coalesce as much as possible from ReadI into Seg.
1244 while (ReadI != E && coalescable(A: Seg, B: *ReadI)) {
1245 Seg.end = std::max(a: Seg.end, b: ReadI->end);
1246 ++ReadI;
1247 }
1248
1249 // Try coalescing Spills.back() into Seg.
1250 if (!Spills.empty() && coalescable(A: Spills.back(), B: Seg)) {
1251 Seg.start = Spills.back().start;
1252 Seg.end = std::max(a: Spills.back().end, b: Seg.end);
1253 Spills.pop_back();
1254 }
1255
1256 // Try coalescing Seg into WriteI[-1].
1257 if (WriteI != LR->begin() && coalescable(A: WriteI[-1], B: Seg)) {
1258 WriteI[-1].end = std::max(a: WriteI[-1].end, b: Seg.end);
1259 return;
1260 }
1261
1262 // Seg doesn't coalesce with anything, and needs to be inserted somewhere.
1263 if (WriteI != ReadI) {
1264 *WriteI++ = Seg;
1265 return;
1266 }
1267
1268 // Finally, append to LR or Spills.
1269 if (WriteI == E) {
1270 LR->segments.push_back(Elt: Seg);
1271 WriteI = ReadI = LR->end();
1272 } else
1273 Spills.push_back(Elt: Seg);
1274}
1275
1276// Merge as many spilled segments as possible into the gap between WriteI
1277// and ReadI. Advance WriteI to reflect the inserted instructions.
1278void LiveRangeUpdater::mergeSpills() {
1279 // Perform a backwards merge of Spills and [SpillI;WriteI).
1280 size_t GapSize = ReadI - WriteI;
1281 size_t NumMoved = std::min(a: Spills.size(), b: GapSize);
1282 LiveRange::iterator Src = WriteI;
1283 LiveRange::iterator Dst = Src + NumMoved;
1284 LiveRange::iterator SpillSrc = Spills.end();
1285 LiveRange::iterator B = LR->begin();
1286
1287 // This is the new WriteI position after merging spills.
1288 WriteI = Dst;
1289
1290 // Now merge Src and Spills backwards.
1291 while (Src != Dst) {
1292 if (Src != B && Src[-1].start > SpillSrc[-1].start)
1293 *--Dst = *--Src;
1294 else
1295 *--Dst = *--SpillSrc;
1296 }
1297 assert(NumMoved == size_t(Spills.end() - SpillSrc));
1298 Spills.erase(CS: SpillSrc, CE: Spills.end());
1299}
1300
1301void LiveRangeUpdater::flush() {
1302 if (!isDirty())
1303 return;
1304 // Clear the dirty state.
1305 LastStart = SlotIndex();
1306
1307 assert(LR && "Cannot add to a null destination");
1308
1309 // Nothing to merge?
1310 if (Spills.empty()) {
1311 LR->segments.erase(CS: WriteI, CE: ReadI);
1312 assert(LR->verify());
1313 return;
1314 }
1315
1316 // Resize the WriteI - ReadI gap to match Spills.
1317 size_t GapSize = ReadI - WriteI;
1318 if (GapSize < Spills.size()) {
1319 // The gap is too small. Make some room.
1320 size_t WritePos = WriteI - LR->begin();
1321 LR->segments.insert(I: ReadI, NumToInsert: Spills.size() - GapSize, Elt: LiveRange::Segment());
1322 // This also invalidated ReadI, but it is recomputed below.
1323 WriteI = LR->begin() + WritePos;
1324 } else {
1325 // Shrink the gap if necessary.
1326 LR->segments.erase(CS: WriteI + Spills.size(), CE: ReadI);
1327 }
1328 ReadI = WriteI + Spills.size();
1329 mergeSpills();
1330 assert(LR->verify());
1331}
1332
1333unsigned ConnectedVNInfoEqClasses::Classify(const LiveRange &LR) {
1334 // Create initial equivalence classes.
1335 EqClass.clear();
1336 EqClass.grow(N: LR.getNumValNums());
1337
1338 const VNInfo *used = nullptr, *unused = nullptr;
1339
1340 // Determine connections.
1341 for (const VNInfo *VNI : LR.valnos) {
1342 // Group all unused values into one class.
1343 if (VNI->isUnused()) {
1344 if (unused)
1345 EqClass.join(a: unused->id, b: VNI->id);
1346 unused = VNI;
1347 continue;
1348 }
1349 used = VNI;
1350 if (VNI->isPHIDef()) {
1351 const MachineBasicBlock *MBB = LIS.getMBBFromIndex(index: VNI->def);
1352 assert(MBB && "Phi-def has no defining MBB");
1353 // Connect to values live out of predecessors.
1354 for (MachineBasicBlock *Pred : MBB->predecessors())
1355 if (const VNInfo *PVNI = LR.getVNInfoBefore(Idx: LIS.getMBBEndIdx(mbb: Pred)))
1356 EqClass.join(a: VNI->id, b: PVNI->id);
1357 } else {
1358 // Normal value defined by an instruction. Check for two-addr redef.
1359 // FIXME: This could be coincidental. Should we really check for a tied
1360 // operand constraint?
1361 // Note that VNI->def may be a use slot for an early clobber def.
1362 if (const VNInfo *UVNI = LR.getVNInfoBefore(Idx: VNI->def))
1363 EqClass.join(a: VNI->id, b: UVNI->id);
1364 }
1365 }
1366
1367 // Lump all the unused values in with the last used value.
1368 if (used && unused)
1369 EqClass.join(a: used->id, b: unused->id);
1370
1371 EqClass.compress();
1372 return EqClass.getNumClasses();
1373}
1374
1375void ConnectedVNInfoEqClasses::Distribute(LiveInterval &LI, LiveInterval *LIV[],
1376 MachineRegisterInfo &MRI) {
1377 // Rewrite instructions.
1378 for (MachineOperand &MO :
1379 llvm::make_early_inc_range(Range: MRI.reg_operands(Reg: LI.reg()))) {
1380 MachineInstr *MI = MO.getParent();
1381 const VNInfo *VNI;
1382 if (MI->isDebugValue()) {
1383 // DBG_VALUE instructions don't have slot indexes, so get the index of
1384 // the instruction before them. The value is defined there too.
1385 SlotIndex Idx = LIS.getSlotIndexes()->getIndexBefore(MI: *MI);
1386 VNI = LI.Query(Idx).valueOut();
1387 } else {
1388 SlotIndex Idx = LIS.getInstructionIndex(Instr: *MI);
1389 LiveQueryResult LRQ = LI.Query(Idx);
1390 VNI = MO.readsReg() ? LRQ.valueIn() : LRQ.valueDefined();
1391 }
1392 // In the case of an <undef> use that isn't tied to any def, VNI will be
1393 // NULL. If the use is tied to a def, VNI will be the defined value.
1394 if (!VNI)
1395 continue;
1396 if (unsigned EqClass = getEqClass(VNI))
1397 MO.setReg(LIV[EqClass - 1]->reg());
1398 }
1399
1400 // Distribute subregister liveranges.
1401 if (LI.hasSubRanges()) {
1402 unsigned NumComponents = EqClass.getNumClasses();
1403 SmallVector<unsigned, 8> VNIMapping;
1404 SmallVector<LiveInterval::SubRange*, 8> SubRanges;
1405 BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
1406 for (LiveInterval::SubRange &SR : LI.subranges()) {
1407 // Create new subranges in the split intervals and construct a mapping
1408 // for the VNInfos in the subrange.
1409 unsigned NumValNos = SR.valnos.size();
1410 VNIMapping.clear();
1411 VNIMapping.reserve(N: NumValNos);
1412 SubRanges.clear();
1413 SubRanges.resize(N: NumComponents-1, NV: nullptr);
1414 for (unsigned I = 0; I < NumValNos; ++I) {
1415 const VNInfo &VNI = *SR.valnos[I];
1416 unsigned ComponentNum;
1417 if (VNI.isUnused()) {
1418 ComponentNum = 0;
1419 } else {
1420 const VNInfo *MainRangeVNI = LI.getVNInfoAt(Idx: VNI.def);
1421 assert(MainRangeVNI != nullptr
1422 && "SubRange def must have corresponding main range def");
1423 ComponentNum = getEqClass(VNI: MainRangeVNI);
1424 if (ComponentNum > 0 && SubRanges[ComponentNum-1] == nullptr) {
1425 SubRanges[ComponentNum-1]
1426 = LIV[ComponentNum-1]->createSubRange(Allocator, LaneMask: SR.LaneMask);
1427 }
1428 }
1429 VNIMapping.push_back(Elt: ComponentNum);
1430 }
1431 DistributeRange(LR&: SR, SplitLRs: SubRanges.data(), VNIClasses: VNIMapping);
1432 }
1433 LI.removeEmptySubRanges();
1434 }
1435
1436 // Distribute main liverange.
1437 DistributeRange(LR&: LI, SplitLRs: LIV, VNIClasses: EqClass);
1438}
1439