1 //===-- LiveInterval.cpp - Live Interval Representation -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LiveRange and LiveInterval classes. Given some
11 // numbering of each the machine instructions an interval [i, j) is said to be a
12 // live range for register v if there is no instruction with number j' >= j
13 // such that v is live at j' and there is no instruction with number i' < i such
14 // that v is live at i'. In this implementation ranges can have holes,
15 // i.e. a range might look like [1,20), [50,65), [1000,1001). Each
16 // individual segment is represented as an instance of LiveRange::Segment,
17 // and the whole range is represented as an instance of LiveRange.
19 //===----------------------------------------------------------------------===//
21 #include "llvm/CodeGen/LiveInterval.h"
23 #include "LiveRangeUtils.h"
24 #include "RegisterCoalescer.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
36 //===----------------------------------------------------------------------===//
37 // Implementation of various methods necessary for calculation of live ranges.
38 // The implementation of the methods abstracts from the concrete type of the
39 // segment collection.
41 // Implementation of the class follows the Template design pattern. The base
42 // class contains generic algorithms that call collection-specific methods,
43 // which are provided in concrete subclasses. In order to avoid virtual calls
44 // these methods are provided by means of C++ template instantiation.
45 // The base class calls the methods of the subclass through method impl(),
46 // which casts 'this' pointer to the type of the subclass.
48 //===----------------------------------------------------------------------===//
50 template <typename ImplT, typename IteratorT, typename CollectionT>
51 class CalcLiveRangeUtilBase {
56 CalcLiveRangeUtilBase(LiveRange *LR) : LR(LR) {}
59 typedef LiveRange::Segment Segment;
60 typedef IteratorT iterator;
62 /// A counterpart of LiveRange::createDeadDef: Make sure the range has a
63 /// value defined at @p Def.
64 /// If @p ForVNI is null, and there is no value defined at @p Def, a new
65 /// value will be allocated using @p VNInfoAllocator.
66 /// If @p ForVNI is null, the return value is the value defined at @p Def,
67 /// either a pre-existing one, or the one newly created.
68 /// If @p ForVNI is not null, then @p Def should be the location where
69 /// @p ForVNI is defined. If the range does not have a value defined at
70 /// @p Def, the value @p ForVNI will be used instead of allocating a new
71 /// one. If the range already has a value defined at @p Def, it must be
72 /// same as @p ForVNI. In either case, @p ForVNI will be the return value.
73 VNInfo *createDeadDef(SlotIndex Def, VNInfo::Allocator *VNInfoAllocator,
75 assert(!Def.isDead() && "Cannot define a value at the dead slot");
76 assert((!ForVNI || ForVNI->def == Def) &&
77 "If ForVNI is specified, it must match Def");
78 iterator I = impl().find(Def);
79 if (I == segments().end()) {
80 VNInfo *VNI = ForVNI ? ForVNI : LR->getNextValue(Def, *VNInfoAllocator);
81 impl().insertAtEnd(Segment(Def, Def.getDeadSlot(), VNI));
85 Segment *S = segmentAt(I);
86 if (SlotIndex::isSameInstr(Def, S->start)) {
87 assert((!ForVNI || ForVNI == S->valno) && "Value number mismatch");
88 assert(S->valno->def == S->start && "Inconsistent existing value def");
90 // It is possible to have both normal and early-clobber defs of the same
91 // register on an instruction. It doesn't make a lot of sense, but it is
92 // possible to specify in inline assembly.
94 // Just convert everything to early-clobber.
95 Def = std::min(Def, S->start);
97 S->start = S->valno->def = Def;
100 assert(SlotIndex::isEarlierInstr(Def, S->start) && "Already live at def");
101 VNInfo *VNI = ForVNI ? ForVNI : LR->getNextValue(Def, *VNInfoAllocator);
102 segments().insert(I, Segment(Def, Def.getDeadSlot(), VNI));
106 VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Use) {
107 if (segments().empty())
110 impl().findInsertPos(Segment(Use.getPrevSlot(), Use, nullptr));
111 if (I == segments().begin())
114 if (I->end <= StartIdx)
117 extendSegmentEndTo(I, Use);
121 std::pair<VNInfo*,bool> extendInBlock(ArrayRef<SlotIndex> Undefs,
122 SlotIndex StartIdx, SlotIndex Use) {
123 if (segments().empty())
124 return std::make_pair(nullptr, false);
125 SlotIndex BeforeUse = Use.getPrevSlot();
126 iterator I = impl().findInsertPos(Segment(BeforeUse, Use, nullptr));
127 if (I == segments().begin())
128 return std::make_pair(nullptr, LR->isUndefIn(Undefs, StartIdx, BeforeUse));
130 if (I->end <= StartIdx)
131 return std::make_pair(nullptr, LR->isUndefIn(Undefs, StartIdx, BeforeUse));
133 if (LR->isUndefIn(Undefs, I->end, BeforeUse))
134 return std::make_pair(nullptr, true);
135 extendSegmentEndTo(I, Use);
137 return std::make_pair(I->valno, false);
140 /// This method is used when we want to extend the segment specified
141 /// by I to end at the specified endpoint. To do this, we should
142 /// merge and eliminate all segments that this will overlap
143 /// with. The iterator is not invalidated.
144 void extendSegmentEndTo(iterator I, SlotIndex NewEnd) {
145 assert(I != segments().end() && "Not a valid segment!");
146 Segment *S = segmentAt(I);
147 VNInfo *ValNo = I->valno;
149 // Search for the first segment that we can't merge with.
150 iterator MergeTo = std::next(I);
151 for (; MergeTo != segments().end() && NewEnd >= MergeTo->end; ++MergeTo)
152 assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
154 // If NewEnd was in the middle of a segment, make sure to get its endpoint.
155 S->end = std::max(NewEnd, std::prev(MergeTo)->end);
157 // If the newly formed segment now touches the segment after it and if they
158 // have the same value number, merge the two segments into one segment.
159 if (MergeTo != segments().end() && MergeTo->start <= I->end &&
160 MergeTo->valno == ValNo) {
161 S->end = MergeTo->end;
165 // Erase any dead segments.
166 segments().erase(std::next(I), MergeTo);
169 /// This method is used when we want to extend the segment specified
170 /// by I to start at the specified endpoint. To do this, we should
171 /// merge and eliminate all segments that this will overlap with.
172 iterator extendSegmentStartTo(iterator I, SlotIndex NewStart) {
173 assert(I != segments().end() && "Not a valid segment!");
174 Segment *S = segmentAt(I);
175 VNInfo *ValNo = I->valno;
177 // Search for the first segment that we can't merge with.
178 iterator MergeTo = I;
180 if (MergeTo == segments().begin()) {
182 segments().erase(MergeTo, I);
185 assert(MergeTo->valno == ValNo && "Cannot merge with differing values!");
187 } while (NewStart <= MergeTo->start);
189 // If we start in the middle of another segment, just delete a range and
190 // extend that segment.
191 if (MergeTo->end >= NewStart && MergeTo->valno == ValNo) {
192 segmentAt(MergeTo)->end = S->end;
194 // Otherwise, extend the segment right after.
196 Segment *MergeToSeg = segmentAt(MergeTo);
197 MergeToSeg->start = NewStart;
198 MergeToSeg->end = S->end;
201 segments().erase(std::next(MergeTo), std::next(I));
205 iterator addSegment(Segment S) {
206 SlotIndex Start = S.start, End = S.end;
207 iterator I = impl().findInsertPos(S);
209 // If the inserted segment starts in the middle or right at the end of
210 // another segment, just extend that segment to contain the segment of S.
211 if (I != segments().begin()) {
212 iterator B = std::prev(I);
213 if (S.valno == B->valno) {
214 if (B->start <= Start && B->end >= Start) {
215 extendSegmentEndTo(B, End);
219 // Check to make sure that we are not overlapping two live segments with
220 // different valno's.
221 assert(B->end <= Start &&
222 "Cannot overlap two segments with differing ValID's"
223 " (did you def the same reg twice in a MachineInstr?)");
227 // Otherwise, if this segment ends in the middle of, or right next
228 // to, another segment, merge it into that segment.
229 if (I != segments().end()) {
230 if (S.valno == I->valno) {
231 if (I->start <= End) {
232 I = extendSegmentStartTo(I, Start);
234 // If S is a complete superset of a segment, we may need to grow its
237 extendSegmentEndTo(I, End);
241 // Check to make sure that we are not overlapping two live segments with
242 // different valno's.
243 assert(I->start >= End &&
244 "Cannot overlap two segments with differing ValID's");
248 // Otherwise, this is just a new segment that doesn't interact with
251 return segments().insert(I, S);
255 ImplT &impl() { return *static_cast<ImplT *>(this); }
257 CollectionT &segments() { return impl().segmentsColl(); }
259 Segment *segmentAt(iterator I) { return const_cast<Segment *>(&(*I)); }
262 //===----------------------------------------------------------------------===//
263 // Instantiation of the methods for calculation of live ranges
264 // based on a segment vector.
265 //===----------------------------------------------------------------------===//
267 class CalcLiveRangeUtilVector;
268 typedef CalcLiveRangeUtilBase<CalcLiveRangeUtilVector, LiveRange::iterator,
269 LiveRange::Segments> CalcLiveRangeUtilVectorBase;
271 class CalcLiveRangeUtilVector : public CalcLiveRangeUtilVectorBase {
273 CalcLiveRangeUtilVector(LiveRange *LR) : CalcLiveRangeUtilVectorBase(LR) {}
276 friend CalcLiveRangeUtilVectorBase;
278 LiveRange::Segments &segmentsColl() { return LR->segments; }
280 void insertAtEnd(const Segment &S) { LR->segments.push_back(S); }
282 iterator find(SlotIndex Pos) { return LR->find(Pos); }
284 iterator findInsertPos(Segment S) {
285 return std::upper_bound(LR->begin(), LR->end(), S.start);
289 //===----------------------------------------------------------------------===//
290 // Instantiation of the methods for calculation of live ranges
291 // based on a segment set.
292 //===----------------------------------------------------------------------===//
294 class CalcLiveRangeUtilSet;
295 typedef CalcLiveRangeUtilBase<CalcLiveRangeUtilSet,
296 LiveRange::SegmentSet::iterator,
297 LiveRange::SegmentSet> CalcLiveRangeUtilSetBase;
299 class CalcLiveRangeUtilSet : public CalcLiveRangeUtilSetBase {
301 CalcLiveRangeUtilSet(LiveRange *LR) : CalcLiveRangeUtilSetBase(LR) {}
304 friend CalcLiveRangeUtilSetBase;
306 LiveRange::SegmentSet &segmentsColl() { return *LR->segmentSet; }
308 void insertAtEnd(const Segment &S) {
309 LR->segmentSet->insert(LR->segmentSet->end(), S);
312 iterator find(SlotIndex Pos) {
314 LR->segmentSet->upper_bound(Segment(Pos, Pos.getNextSlot(), nullptr));
315 if (I == LR->segmentSet->begin())
317 iterator PrevI = std::prev(I);
318 if (Pos < (*PrevI).end)
323 iterator findInsertPos(Segment S) {
324 iterator I = LR->segmentSet->upper_bound(S);
325 if (I != LR->segmentSet->end() && !(S.start < *I))
332 //===----------------------------------------------------------------------===//
334 //===----------------------------------------------------------------------===//
336 LiveRange::iterator LiveRange::find(SlotIndex Pos) {
337 // This algorithm is basically std::upper_bound.
338 // Unfortunately, std::upper_bound cannot be used with mixed types until we
339 // adopt C++0x. Many libraries can do it, but not all.
340 if (empty() || Pos >= endIndex())
342 iterator I = begin();
345 size_t Mid = Len >> 1;
346 if (Pos < I[Mid].end) {
356 VNInfo *LiveRange::createDeadDef(SlotIndex Def, VNInfo::Allocator &VNIAlloc) {
357 // Use the segment set, if it is available.
358 if (segmentSet != nullptr)
359 return CalcLiveRangeUtilSet(this).createDeadDef(Def, &VNIAlloc, nullptr);
360 // Otherwise use the segment vector.
361 return CalcLiveRangeUtilVector(this).createDeadDef(Def, &VNIAlloc, nullptr);
364 VNInfo *LiveRange::createDeadDef(VNInfo *VNI) {
365 // Use the segment set, if it is available.
366 if (segmentSet != nullptr)
367 return CalcLiveRangeUtilSet(this).createDeadDef(VNI->def, nullptr, VNI);
368 // Otherwise use the segment vector.
369 return CalcLiveRangeUtilVector(this).createDeadDef(VNI->def, nullptr, VNI);
372 // overlaps - Return true if the intersection of the two live ranges is
375 // An example for overlaps():
379 // 8: C = A + B ;; last use of A
381 // The live ranges should look like:
387 // A->overlaps(C) should return false since we want to be able to join
390 bool LiveRange::overlapsFrom(const LiveRange& other,
391 const_iterator StartPos) const {
392 assert(!empty() && "empty range");
393 const_iterator i = begin();
394 const_iterator ie = end();
395 const_iterator j = StartPos;
396 const_iterator je = other.end();
398 assert((StartPos->start <= i->start || StartPos == other.begin()) &&
399 StartPos != other.end() && "Bogus start position hint!");
401 if (i->start < j->start) {
402 i = std::upper_bound(i, ie, j->start);
403 if (i != begin()) --i;
404 } else if (j->start < i->start) {
406 if (StartPos != other.end() && StartPos->start <= i->start) {
407 assert(StartPos < other.end() && i < end());
408 j = std::upper_bound(j, je, i->start);
409 if (j != other.begin()) --j;
415 if (j == je) return false;
418 if (i->start > j->start) {
423 if (i->end > j->start)
431 bool LiveRange::overlaps(const LiveRange &Other, const CoalescerPair &CP,
432 const SlotIndexes &Indexes) const {
433 assert(!empty() && "empty range");
437 // Use binary searches to find initial positions.
438 const_iterator I = find(Other.beginIndex());
439 const_iterator IE = end();
442 const_iterator J = Other.find(I->start);
443 const_iterator JE = Other.end();
448 // J has just been advanced to satisfy:
449 assert(J->end >= I->start);
450 // Check for an overlap.
451 if (J->start < I->end) {
452 // I and J are overlapping. Find the later start.
453 SlotIndex Def = std::max(I->start, J->start);
454 // Allow the overlap if Def is a coalescable copy.
456 !CP.isCoalescable(Indexes.getInstructionFromIndex(Def)))
459 // Advance the iterator that ends first to check for more overlaps.
460 if (J->end > I->end) {
464 // Advance J until J->end >= I->start.
468 while (J->end < I->start);
472 /// overlaps - Return true if the live range overlaps an interval specified
474 bool LiveRange::overlaps(SlotIndex Start, SlotIndex End) const {
475 assert(Start < End && "Invalid range");
476 const_iterator I = std::lower_bound(begin(), end(), End);
477 return I != begin() && (--I)->end > Start;
480 bool LiveRange::covers(const LiveRange &Other) const {
482 return Other.empty();
484 const_iterator I = begin();
485 for (const Segment &O : Other.segments) {
486 I = advanceTo(I, O.start);
487 if (I == end() || I->start > O.start)
490 // Check adjacent live segments and see if we can get behind O.end.
491 while (I->end < O.end) {
492 const_iterator Last = I;
493 // Get next segment and abort if it was not adjacent.
495 if (I == end() || Last->end != I->start)
502 /// ValNo is dead, remove it. If it is the largest value number, just nuke it
503 /// (and any other deleted values neighboring it), otherwise mark it as ~1U so
504 /// it can be nuked later.
505 void LiveRange::markValNoForDeletion(VNInfo *ValNo) {
506 if (ValNo->id == getNumValNums()-1) {
509 } while (!valnos.empty() && valnos.back()->isUnused());
515 /// RenumberValues - Renumber all values in order of appearance and delete the
516 /// remaining unused values.
517 void LiveRange::RenumberValues() {
518 SmallPtrSet<VNInfo*, 8> Seen;
520 for (const Segment &S : segments) {
521 VNInfo *VNI = S.valno;
522 if (!Seen.insert(VNI).second)
524 assert(!VNI->isUnused() && "Unused valno used by live segment");
525 VNI->id = (unsigned)valnos.size();
526 valnos.push_back(VNI);
530 void LiveRange::addSegmentToSet(Segment S) {
531 CalcLiveRangeUtilSet(this).addSegment(S);
534 LiveRange::iterator LiveRange::addSegment(Segment S) {
535 // Use the segment set, if it is available.
536 if (segmentSet != nullptr) {
540 // Otherwise use the segment vector.
541 return CalcLiveRangeUtilVector(this).addSegment(S);
544 void LiveRange::append(const Segment S) {
545 // Check that the segment belongs to the back of the list.
546 assert(segments.empty() || segments.back().end <= S.start);
547 segments.push_back(S);
550 std::pair<VNInfo*,bool> LiveRange::extendInBlock(ArrayRef<SlotIndex> Undefs,
551 SlotIndex StartIdx, SlotIndex Kill) {
552 // Use the segment set, if it is available.
553 if (segmentSet != nullptr)
554 return CalcLiveRangeUtilSet(this).extendInBlock(Undefs, StartIdx, Kill);
555 // Otherwise use the segment vector.
556 return CalcLiveRangeUtilVector(this).extendInBlock(Undefs, StartIdx, Kill);
559 VNInfo *LiveRange::extendInBlock(SlotIndex StartIdx, SlotIndex Kill) {
560 // Use the segment set, if it is available.
561 if (segmentSet != nullptr)
562 return CalcLiveRangeUtilSet(this).extendInBlock(StartIdx, Kill);
563 // Otherwise use the segment vector.
564 return CalcLiveRangeUtilVector(this).extendInBlock(StartIdx, Kill);
567 /// Remove the specified segment from this range. Note that the segment must
568 /// be in a single Segment in its entirety.
569 void LiveRange::removeSegment(SlotIndex Start, SlotIndex End,
570 bool RemoveDeadValNo) {
571 // Find the Segment containing this span.
572 iterator I = find(Start);
573 assert(I != end() && "Segment is not in range!");
574 assert(I->containsInterval(Start, End)
575 && "Segment is not entirely in range!");
577 // If the span we are removing is at the start of the Segment, adjust it.
578 VNInfo *ValNo = I->valno;
579 if (I->start == Start) {
581 if (RemoveDeadValNo) {
582 // Check if val# is dead.
584 for (const_iterator II = begin(), EE = end(); II != EE; ++II)
585 if (II != I && II->valno == ValNo) {
590 // Now that ValNo is dead, remove it.
591 markValNoForDeletion(ValNo);
595 segments.erase(I); // Removed the whole Segment.
601 // Otherwise if the span we are removing is at the end of the Segment,
602 // adjust the other way.
608 // Otherwise, we are splitting the Segment into two pieces.
609 SlotIndex OldEnd = I->end;
610 I->end = Start; // Trim the old segment.
612 // Insert the new one.
613 segments.insert(std::next(I), Segment(End, OldEnd, ValNo));
616 /// removeValNo - Remove all the segments defined by the specified value#.
617 /// Also remove the value# from value# list.
618 void LiveRange::removeValNo(VNInfo *ValNo) {
620 segments.erase(remove_if(*this, [ValNo](const Segment &S) {
621 return S.valno == ValNo;
623 // Now that ValNo is dead, remove it.
624 markValNoForDeletion(ValNo);
627 void LiveRange::join(LiveRange &Other,
628 const int *LHSValNoAssignments,
629 const int *RHSValNoAssignments,
630 SmallVectorImpl<VNInfo *> &NewVNInfo) {
633 // Determine if any of our values are mapped. This is uncommon, so we want
634 // to avoid the range scan if not.
635 bool MustMapCurValNos = false;
636 unsigned NumVals = getNumValNums();
637 unsigned NumNewVals = NewVNInfo.size();
638 for (unsigned i = 0; i != NumVals; ++i) {
639 unsigned LHSValID = LHSValNoAssignments[i];
641 (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i))) {
642 MustMapCurValNos = true;
647 // If we have to apply a mapping to our base range assignment, rewrite it now.
648 if (MustMapCurValNos && !empty()) {
649 // Map the first live range.
651 iterator OutIt = begin();
652 OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
653 for (iterator I = std::next(OutIt), E = end(); I != E; ++I) {
654 VNInfo* nextValNo = NewVNInfo[LHSValNoAssignments[I->valno->id]];
655 assert(nextValNo && "Huh?");
657 // If this live range has the same value # as its immediate predecessor,
658 // and if they are neighbors, remove one Segment. This happens when we
659 // have [0,4:0)[4,7:1) and map 0/1 onto the same value #.
660 if (OutIt->valno == nextValNo && OutIt->end == I->start) {
663 // Didn't merge. Move OutIt to the next segment,
665 OutIt->valno = nextValNo;
667 OutIt->start = I->start;
672 // If we merge some segments, chop off the end.
674 segments.erase(OutIt, end());
677 // Rewrite Other values before changing the VNInfo ids.
678 // This can leave Other in an invalid state because we're not coalescing
679 // touching segments that now have identical values. That's OK since Other is
680 // not supposed to be valid after calling join();
681 for (Segment &S : Other.segments)
682 S.valno = NewVNInfo[RHSValNoAssignments[S.valno->id]];
684 // Update val# info. Renumber them and make sure they all belong to this
685 // LiveRange now. Also remove dead val#'s.
686 unsigned NumValNos = 0;
687 for (unsigned i = 0; i < NumNewVals; ++i) {
688 VNInfo *VNI = NewVNInfo[i];
690 if (NumValNos >= NumVals)
691 valnos.push_back(VNI);
693 valnos[NumValNos] = VNI;
694 VNI->id = NumValNos++; // Renumber val#.
697 if (NumNewVals < NumVals)
698 valnos.resize(NumNewVals); // shrinkify
700 // Okay, now insert the RHS live segments into the LHS.
701 LiveRangeUpdater Updater(this);
702 for (Segment &S : Other.segments)
706 /// Merge all of the segments in RHS into this live range as the specified
707 /// value number. The segments in RHS are allowed to overlap with segments in
708 /// the current range, but only if the overlapping segments have the
709 /// specified value number.
710 void LiveRange::MergeSegmentsInAsValue(const LiveRange &RHS,
712 LiveRangeUpdater Updater(this);
713 for (const Segment &S : RHS.segments)
714 Updater.add(S.start, S.end, LHSValNo);
717 /// MergeValueInAsValue - Merge all of the live segments of a specific val#
718 /// in RHS into this live range as the specified value number.
719 /// The segments in RHS are allowed to overlap with segments in the
720 /// current range, it will replace the value numbers of the overlaped
721 /// segments with the specified value number.
722 void LiveRange::MergeValueInAsValue(const LiveRange &RHS,
723 const VNInfo *RHSValNo,
725 LiveRangeUpdater Updater(this);
726 for (const Segment &S : RHS.segments)
727 if (S.valno == RHSValNo)
728 Updater.add(S.start, S.end, LHSValNo);
731 /// MergeValueNumberInto - This method is called when two value nubmers
732 /// are found to be equivalent. This eliminates V1, replacing all
733 /// segments with the V1 value number with the V2 value number. This can
734 /// cause merging of V1/V2 values numbers and compaction of the value space.
735 VNInfo *LiveRange::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) {
736 assert(V1 != V2 && "Identical value#'s are always equivalent!");
738 // This code actually merges the (numerically) larger value number into the
739 // smaller value number, which is likely to allow us to compactify the value
740 // space. The only thing we have to be careful of is to preserve the
741 // instruction that defines the result value.
743 // Make sure V2 is smaller than V1.
744 if (V1->id < V2->id) {
749 // Merge V1 segments into V2.
750 for (iterator I = begin(); I != end(); ) {
752 if (S->valno != V1) continue; // Not a V1 Segment.
754 // Okay, we found a V1 live range. If it had a previous, touching, V2 live
758 if (Prev->valno == V2 && Prev->end == S->start) {
761 // Erase this live-range.
768 // Okay, now we have a V1 or V2 live range that is maximally merged forward.
769 // Ensure that it is a V2 live-range.
772 // If we can merge it into later V2 segments, do so now. We ignore any
773 // following V1 segments, as they will be merged in subsequent iterations
776 if (I->start == S->end && I->valno == V2) {
784 // Now that V1 is dead, remove it.
785 markValNoForDeletion(V1);
790 void LiveRange::flushSegmentSet() {
791 assert(segmentSet != nullptr && "segment set must have been created");
794 "segment set can be used only initially before switching to the array");
795 segments.append(segmentSet->begin(), segmentSet->end());
796 segmentSet = nullptr;
800 bool LiveRange::isLiveAtIndexes(ArrayRef<SlotIndex> Slots) const {
801 ArrayRef<SlotIndex>::iterator SlotI = Slots.begin();
802 ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
804 // If there are no regmask slots, we have nothing to search.
808 // Start our search at the first segment that ends after the first slot.
809 const_iterator SegmentI = find(*SlotI);
810 const_iterator SegmentE = end();
812 // If there are no segments that end after the first slot, we're done.
813 if (SegmentI == SegmentE)
816 // Look for each slot in the live range.
817 for ( ; SlotI != SlotE; ++SlotI) {
818 // Go to the next segment that ends after the current slot.
819 // The slot may be within a hole in the range.
820 SegmentI = advanceTo(SegmentI, *SlotI);
821 if (SegmentI == SegmentE)
824 // If this segment contains the slot, we're done.
825 if (SegmentI->contains(*SlotI))
827 // Otherwise, look for the next slot.
830 // We didn't find a segment containing any of the slots.
834 void LiveInterval::freeSubRange(SubRange *S) {
836 // Memory was allocated with BumpPtr allocator and is not freed here.
839 void LiveInterval::removeEmptySubRanges() {
840 SubRange **NextPtr = &SubRanges;
841 SubRange *I = *NextPtr;
842 while (I != nullptr) {
848 // Skip empty subranges until we find the first nonempty one.
850 SubRange *Next = I->Next;
853 } while (I != nullptr && I->empty());
858 void LiveInterval::clearSubRanges() {
859 for (SubRange *I = SubRanges, *Next; I != nullptr; I = Next) {
866 unsigned LiveInterval::getSize() const {
868 for (const Segment &S : segments)
869 Sum += S.start.distance(S.end);
873 void LiveInterval::computeSubRangeUndefs(SmallVectorImpl<SlotIndex> &Undefs,
874 LaneBitmask LaneMask,
875 const MachineRegisterInfo &MRI,
876 const SlotIndexes &Indexes) const {
877 assert(TargetRegisterInfo::isVirtualRegister(reg));
878 LaneBitmask VRegMask = MRI.getMaxLaneMaskForVReg(reg);
879 assert((VRegMask & LaneMask).any());
880 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
881 for (const MachineOperand &MO : MRI.def_operands(reg)) {
884 unsigned SubReg = MO.getSubReg();
885 assert(SubReg != 0 && "Undef should only be set on subreg defs");
886 LaneBitmask DefMask = TRI.getSubRegIndexLaneMask(SubReg);
887 LaneBitmask UndefMask = VRegMask & ~DefMask;
888 if ((UndefMask & LaneMask).any()) {
889 const MachineInstr &MI = *MO.getParent();
890 bool EarlyClobber = MO.isEarlyClobber();
891 SlotIndex Pos = Indexes.getInstructionIndex(MI).getRegSlot(EarlyClobber);
892 Undefs.push_back(Pos);
897 raw_ostream& llvm::operator<<(raw_ostream& os, const LiveRange::Segment &S) {
898 return os << '[' << S.start << ',' << S.end << ':' << S.valno->id << ')';
901 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
902 LLVM_DUMP_METHOD void LiveRange::Segment::dump() const {
903 dbgs() << *this << '\n';
907 void LiveRange::print(raw_ostream &OS) const {
911 for (const Segment &S : segments) {
913 assert(S.valno == getValNumInfo(S.valno->id) && "Bad VNInfo");
917 // Print value number info.
918 if (getNumValNums()) {
921 for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e;
923 const VNInfo *vni = *i;
926 if (vni->isUnused()) {
937 void LiveInterval::SubRange::print(raw_ostream &OS) const {
938 OS << " L" << PrintLaneMask(LaneMask) << ' '
939 << static_cast<const LiveRange&>(*this);
942 void LiveInterval::print(raw_ostream &OS) const {
943 OS << PrintReg(reg) << ' ';
946 for (const SubRange &SR : subranges())
950 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
951 LLVM_DUMP_METHOD void LiveRange::dump() const {
952 dbgs() << *this << '\n';
955 LLVM_DUMP_METHOD void LiveInterval::SubRange::dump() const {
956 dbgs() << *this << '\n';
959 LLVM_DUMP_METHOD void LiveInterval::dump() const {
960 dbgs() << *this << '\n';
965 void LiveRange::verify() const {
966 for (const_iterator I = begin(), E = end(); I != E; ++I) {
967 assert(I->start.isValid());
968 assert(I->end.isValid());
969 assert(I->start < I->end);
970 assert(I->valno != nullptr);
971 assert(I->valno->id < valnos.size());
972 assert(I->valno == valnos[I->valno->id]);
973 if (std::next(I) != E) {
974 assert(I->end <= std::next(I)->start);
975 if (I->end == std::next(I)->start)
976 assert(I->valno != std::next(I)->valno);
981 void LiveInterval::verify(const MachineRegisterInfo *MRI) const {
984 // Make sure SubRanges are fine and LaneMasks are disjunct.
986 LaneBitmask MaxMask = MRI != nullptr ? MRI->getMaxLaneMaskForVReg(reg)
987 : LaneBitmask::getAll();
988 for (const SubRange &SR : subranges()) {
989 // Subrange lanemask should be disjunct to any previous subrange masks.
990 assert((Mask & SR.LaneMask).none());
993 // subrange mask should not contained in maximum lane mask for the vreg.
994 assert((Mask & ~MaxMask).none());
995 // empty subranges must be removed.
999 // Main liverange should cover subrange.
1006 //===----------------------------------------------------------------------===//
1007 // LiveRangeUpdater class
1008 //===----------------------------------------------------------------------===//
1010 // The LiveRangeUpdater class always maintains these invariants:
1012 // - When LastStart is invalid, Spills is empty and the iterators are invalid.
1013 // This is the initial state, and the state created by flush().
1014 // In this state, isDirty() returns false.
1016 // Otherwise, segments are kept in three separate areas:
1018 // 1. [begin; WriteI) at the front of LR.
1019 // 2. [ReadI; end) at the back of LR.
1022 // - LR.begin() <= WriteI <= ReadI <= LR.end().
1023 // - Segments in all three areas are fully ordered and coalesced.
1024 // - Segments in area 1 precede and can't coalesce with segments in area 2.
1025 // - Segments in Spills precede and can't coalesce with segments in area 2.
1026 // - No coalescing is possible between segments in Spills and segments in area
1027 // 1, and there are no overlapping segments.
1029 // The segments in Spills are not ordered with respect to the segments in area
1030 // 1. They need to be merged.
1032 // When they exist, Spills.back().start <= LastStart,
1033 // and WriteI[-1].start <= LastStart.
1035 void LiveRangeUpdater::print(raw_ostream &OS) const {
1038 OS << "Clean updater: " << *LR << '\n';
1040 OS << "Null updater.\n";
1043 assert(LR && "Can't have null LR in dirty updater.");
1044 OS << " updater with gap = " << (ReadI - WriteI)
1045 << ", last start = " << LastStart
1047 for (const auto &S : make_range(LR->begin(), WriteI))
1050 for (unsigned I = 0, E = Spills.size(); I != E; ++I)
1051 OS << ' ' << Spills[I];
1053 for (const auto &S : make_range(ReadI, LR->end()))
1058 LLVM_DUMP_METHOD void LiveRangeUpdater::dump() const {
1062 // Determine if A and B should be coalesced.
1063 static inline bool coalescable(const LiveRange::Segment &A,
1064 const LiveRange::Segment &B) {
1065 assert(A.start <= B.start && "Unordered live segments.");
1066 if (A.end == B.start)
1067 return A.valno == B.valno;
1068 if (A.end < B.start)
1070 assert(A.valno == B.valno && "Cannot overlap different values");
1074 void LiveRangeUpdater::add(LiveRange::Segment Seg) {
1075 assert(LR && "Cannot add to a null destination");
1077 // Fall back to the regular add method if the live range
1078 // is using the segment set instead of the segment vector.
1079 if (LR->segmentSet != nullptr) {
1080 LR->addSegmentToSet(Seg);
1084 // Flush the state if Start moves backwards.
1085 if (!LastStart.isValid() || LastStart > Seg.start) {
1088 // This brings us to an uninitialized state. Reinitialize.
1089 assert(Spills.empty() && "Leftover spilled segments");
1090 WriteI = ReadI = LR->begin();
1093 // Remember start for next time.
1094 LastStart = Seg.start;
1096 // Advance ReadI until it ends after Seg.start.
1097 LiveRange::iterator E = LR->end();
1098 if (ReadI != E && ReadI->end <= Seg.start) {
1099 // First try to close the gap between WriteI and ReadI with spills.
1100 if (ReadI != WriteI)
1102 // Then advance ReadI.
1103 if (ReadI == WriteI)
1104 ReadI = WriteI = LR->find(Seg.start);
1106 while (ReadI != E && ReadI->end <= Seg.start)
1107 *WriteI++ = *ReadI++;
1110 assert(ReadI == E || ReadI->end > Seg.start);
1112 // Check if the ReadI segment begins early.
1113 if (ReadI != E && ReadI->start <= Seg.start) {
1114 assert(ReadI->valno == Seg.valno && "Cannot overlap different values");
1115 // Bail if Seg is completely contained in ReadI.
1116 if (ReadI->end >= Seg.end)
1118 // Coalesce into Seg.
1119 Seg.start = ReadI->start;
1123 // Coalesce as much as possible from ReadI into Seg.
1124 while (ReadI != E && coalescable(Seg, *ReadI)) {
1125 Seg.end = std::max(Seg.end, ReadI->end);
1129 // Try coalescing Spills.back() into Seg.
1130 if (!Spills.empty() && coalescable(Spills.back(), Seg)) {
1131 Seg.start = Spills.back().start;
1132 Seg.end = std::max(Spills.back().end, Seg.end);
1136 // Try coalescing Seg into WriteI[-1].
1137 if (WriteI != LR->begin() && coalescable(WriteI[-1], Seg)) {
1138 WriteI[-1].end = std::max(WriteI[-1].end, Seg.end);
1142 // Seg doesn't coalesce with anything, and needs to be inserted somewhere.
1143 if (WriteI != ReadI) {
1148 // Finally, append to LR or Spills.
1150 LR->segments.push_back(Seg);
1151 WriteI = ReadI = LR->end();
1153 Spills.push_back(Seg);
1156 // Merge as many spilled segments as possible into the gap between WriteI
1157 // and ReadI. Advance WriteI to reflect the inserted instructions.
1158 void LiveRangeUpdater::mergeSpills() {
1159 // Perform a backwards merge of Spills and [SpillI;WriteI).
1160 size_t GapSize = ReadI - WriteI;
1161 size_t NumMoved = std::min(Spills.size(), GapSize);
1162 LiveRange::iterator Src = WriteI;
1163 LiveRange::iterator Dst = Src + NumMoved;
1164 LiveRange::iterator SpillSrc = Spills.end();
1165 LiveRange::iterator B = LR->begin();
1167 // This is the new WriteI position after merging spills.
1170 // Now merge Src and Spills backwards.
1171 while (Src != Dst) {
1172 if (Src != B && Src[-1].start > SpillSrc[-1].start)
1175 *--Dst = *--SpillSrc;
1177 assert(NumMoved == size_t(Spills.end() - SpillSrc));
1178 Spills.erase(SpillSrc, Spills.end());
1181 void LiveRangeUpdater::flush() {
1184 // Clear the dirty state.
1185 LastStart = SlotIndex();
1187 assert(LR && "Cannot add to a null destination");
1189 // Nothing to merge?
1190 if (Spills.empty()) {
1191 LR->segments.erase(WriteI, ReadI);
1196 // Resize the WriteI - ReadI gap to match Spills.
1197 size_t GapSize = ReadI - WriteI;
1198 if (GapSize < Spills.size()) {
1199 // The gap is too small. Make some room.
1200 size_t WritePos = WriteI - LR->begin();
1201 LR->segments.insert(ReadI, Spills.size() - GapSize, LiveRange::Segment());
1202 // This also invalidated ReadI, but it is recomputed below.
1203 WriteI = LR->begin() + WritePos;
1205 // Shrink the gap if necessary.
1206 LR->segments.erase(WriteI + Spills.size(), ReadI);
1208 ReadI = WriteI + Spills.size();
1213 unsigned ConnectedVNInfoEqClasses::Classify(const LiveRange &LR) {
1214 // Create initial equivalence classes.
1216 EqClass.grow(LR.getNumValNums());
1218 const VNInfo *used = nullptr, *unused = nullptr;
1220 // Determine connections.
1221 for (const VNInfo *VNI : LR.valnos) {
1222 // Group all unused values into one class.
1223 if (VNI->isUnused()) {
1225 EqClass.join(unused->id, VNI->id);
1230 if (VNI->isPHIDef()) {
1231 const MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
1232 assert(MBB && "Phi-def has no defining MBB");
1233 // Connect to values live out of predecessors.
1234 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
1235 PE = MBB->pred_end(); PI != PE; ++PI)
1236 if (const VNInfo *PVNI = LR.getVNInfoBefore(LIS.getMBBEndIdx(*PI)))
1237 EqClass.join(VNI->id, PVNI->id);
1239 // Normal value defined by an instruction. Check for two-addr redef.
1240 // FIXME: This could be coincidental. Should we really check for a tied
1241 // operand constraint?
1242 // Note that VNI->def may be a use slot for an early clobber def.
1243 if (const VNInfo *UVNI = LR.getVNInfoBefore(VNI->def))
1244 EqClass.join(VNI->id, UVNI->id);
1248 // Lump all the unused values in with the last used value.
1250 EqClass.join(used->id, unused->id);
1253 return EqClass.getNumClasses();
1256 void ConnectedVNInfoEqClasses::Distribute(LiveInterval &LI, LiveInterval *LIV[],
1257 MachineRegisterInfo &MRI) {
1258 // Rewrite instructions.
1259 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LI.reg),
1260 RE = MRI.reg_end(); RI != RE;) {
1261 MachineOperand &MO = *RI;
1262 MachineInstr *MI = RI->getParent();
1264 // DBG_VALUE instructions don't have slot indexes, so get the index of the
1265 // instruction before them.
1266 // Normally, DBG_VALUE instructions are removed before this function is
1267 // called, but it is not a requirement.
1269 if (MI->isDebugValue())
1270 Idx = LIS.getSlotIndexes()->getIndexBefore(*MI);
1272 Idx = LIS.getInstructionIndex(*MI);
1273 LiveQueryResult LRQ = LI.Query(Idx);
1274 const VNInfo *VNI = MO.readsReg() ? LRQ.valueIn() : LRQ.valueDefined();
1275 // In the case of an <undef> use that isn't tied to any def, VNI will be
1276 // NULL. If the use is tied to a def, VNI will be the defined value.
1279 if (unsigned EqClass = getEqClass(VNI))
1280 MO.setReg(LIV[EqClass-1]->reg);
1283 // Distribute subregister liveranges.
1284 if (LI.hasSubRanges()) {
1285 unsigned NumComponents = EqClass.getNumClasses();
1286 SmallVector<unsigned, 8> VNIMapping;
1287 SmallVector<LiveInterval::SubRange*, 8> SubRanges;
1288 BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
1289 for (LiveInterval::SubRange &SR : LI.subranges()) {
1290 // Create new subranges in the split intervals and construct a mapping
1291 // for the VNInfos in the subrange.
1292 unsigned NumValNos = SR.valnos.size();
1294 VNIMapping.reserve(NumValNos);
1296 SubRanges.resize(NumComponents-1, nullptr);
1297 for (unsigned I = 0; I < NumValNos; ++I) {
1298 const VNInfo &VNI = *SR.valnos[I];
1299 unsigned ComponentNum;
1300 if (VNI.isUnused()) {
1303 const VNInfo *MainRangeVNI = LI.getVNInfoAt(VNI.def);
1304 assert(MainRangeVNI != nullptr
1305 && "SubRange def must have corresponding main range def");
1306 ComponentNum = getEqClass(MainRangeVNI);
1307 if (ComponentNum > 0 && SubRanges[ComponentNum-1] == nullptr) {
1308 SubRanges[ComponentNum-1]
1309 = LIV[ComponentNum-1]->createSubRange(Allocator, SR.LaneMask);
1312 VNIMapping.push_back(ComponentNum);
1314 DistributeRange(SR, SubRanges.data(), VNIMapping);
1316 LI.removeEmptySubRanges();
1319 // Distribute main liverange.
1320 DistributeRange(LI, LIV, EqClass);