blob: 70b2a77fe80061e40358503c06fb9ad390077486 [file] [log] [blame]
Eugene Zelenko5df3d892017-08-24 21:21:39 +00001//===- LiveInterval.cpp - Live Interval Representation --------------------===//
Chris Lattner78f62e32004-07-23 17:49:16 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chris Lattner78f62e32004-07-23 17:49:16 +00006//
7//===----------------------------------------------------------------------===//
8//
Matthias Braund7df9352013-10-10 21:28:47 +00009// This file implements the LiveRange and LiveInterval classes. Given some
Chris Lattner78f62e32004-07-23 17:49:16 +000010// numbering of each the machine instructions an interval [i, j) is said to be a
Matthias Braund7df9352013-10-10 21:28:47 +000011// live range for register v if there is no instruction with number j' >= j
Bob Wilson5b562902010-01-12 22:18:56 +000012// such that v is live at j' and there is no instruction with number i' < i such
Matthias Braund7df9352013-10-10 21:28:47 +000013// 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.
Chris Lattner78f62e32004-07-23 17:49:16 +000017//
18//===----------------------------------------------------------------------===//
19
Bill Wendling3f6f0fd2006-11-28 02:08:17 +000020#include "llvm/CodeGen/LiveInterval.h"
Matthias Braunf9acaca2016-05-31 22:38:06 +000021#include "LiveRangeUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "RegisterCoalescer.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000023#include "llvm/ADT/ArrayRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/ADT/STLExtras.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000025#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/iterator_range.h"
Matthias Braunf8422972017-12-13 02:51:04 +000028#include "llvm/CodeGen/LiveIntervals.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000029#include "llvm/CodeGen/MachineBasicBlock.h"
30#include "llvm/CodeGen/MachineInstr.h"
31#include "llvm/CodeGen/MachineOperand.h"
Evan Cheng085caf12009-06-14 20:22:55 +000032#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000033#include "llvm/CodeGen/SlotIndexes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000034#include "llvm/CodeGen/TargetRegisterInfo.h"
Nico Weber432a3882018-04-30 14:59:11 +000035#include "llvm/Config/llvm-config.h"
Eugene Zelenko5df3d892017-08-24 21:21:39 +000036#include "llvm/MC/LaneBitmask.h"
37#include "llvm/Support/Compiler.h"
David Greenec2155322010-01-04 22:41:43 +000038#include "llvm/Support/Debug.h"
Daniel Dunbarf26e7402009-07-24 10:47:20 +000039#include "llvm/Support/raw_ostream.h"
Alkis Evlogimenosfc59e0e2004-09-28 02:38:58 +000040#include <algorithm>
Eugene Zelenko5df3d892017-08-24 21:21:39 +000041#include <cassert>
42#include <cstddef>
43#include <iterator>
44#include <utility>
45
Chris Lattner78f62e32004-07-23 17:49:16 +000046using namespace llvm;
47
Benjamin Kramer51f6096c2015-03-23 12:30:58 +000048namespace {
Eugene Zelenko5df3d892017-08-24 21:21:39 +000049
Quentin Colombeta8cb36e2015-02-06 18:42:41 +000050//===----------------------------------------------------------------------===//
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:
Eugene Zelenko5df3d892017-08-24 21:21:39 +000073 using Segment = LiveRange::Segment;
74 using iterator = IteratorT;
Quentin Colombeta8cb36e2015-02-06 18:42:41 +000075
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +000076 /// 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) {
Quentin Colombeta8cb36e2015-02-06 18:42:41 +000089 assert(!Def.isDead() && "Cannot define a value at the dead slot");
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +000090 assert((!ForVNI || ForVNI->def == Def) &&
91 "If ForVNI is specified, it must match Def");
Quentin Colombeta8cb36e2015-02-06 18:42:41 +000092 iterator I = impl().find(Def);
93 if (I == segments().end()) {
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +000094 VNInfo *VNI = ForVNI ? ForVNI : LR->getNextValue(Def, *VNInfoAllocator);
Quentin Colombeta8cb36e2015-02-06 18:42:41 +000095 impl().insertAtEnd(Segment(Def, Def.getDeadSlot(), VNI));
96 return VNI;
97 }
98
99 Segment *S = segmentAt(I);
100 if (SlotIndex::isSameInstr(Def, S->start)) {
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000101 assert((!ForVNI || ForVNI == S->valno) && "Value number mismatch");
Quentin Colombeta8cb36e2015-02-06 18:42:41 +0000102 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(Def, 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");
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000115 VNInfo *VNI = ForVNI ? ForVNI : LR->getNextValue(Def, *VNInfoAllocator);
Quentin Colombeta8cb36e2015-02-06 18:42:41 +0000116 segments().insert(I, Segment(Def, Def.getDeadSlot(), VNI));
117 return VNI;
118 }
119
Matthias Braun11042c82015-02-18 01:50:52 +0000120 VNInfo *extendInBlock(SlotIndex StartIdx, SlotIndex Use) {
Quentin Colombeta8cb36e2015-02-06 18:42:41 +0000121 if (segments().empty())
122 return nullptr;
123 iterator I =
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000124 impl().findInsertPos(Segment(Use.getPrevSlot(), Use, nullptr));
Quentin Colombeta8cb36e2015-02-06 18:42:41 +0000125 if (I == segments().begin())
126 return nullptr;
127 --I;
128 if (I->end <= StartIdx)
129 return nullptr;
Matthias Braun11042c82015-02-18 01:50:52 +0000130 if (I->end < Use)
131 extendSegmentEndTo(I, Use);
Quentin Colombeta8cb36e2015-02-06 18:42:41 +0000132 return I->valno;
133 }
134
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000135 std::pair<VNInfo*,bool> extendInBlock(ArrayRef<SlotIndex> Undefs,
136 SlotIndex StartIdx, SlotIndex Use) {
137 if (segments().empty())
138 return std::make_pair(nullptr, 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(nullptr, LR->isUndefIn(Undefs, StartIdx, BeforeUse));
143 --I;
144 if (I->end <= StartIdx)
145 return std::make_pair(nullptr, LR->isUndefIn(Undefs, StartIdx, BeforeUse));
146 if (I->end < Use) {
147 if (LR->isUndefIn(Undefs, I->end, BeforeUse))
148 return std::make_pair(nullptr, true);
149 extendSegmentEndTo(I, Use);
150 }
151 return std::make_pair(I->valno, false);
152 }
153
Quentin Colombeta8cb36e2015-02-06 18:42:41 +0000154 /// 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(MergeTo)->end = S->end;
207 } else {
208 // Otherwise, extend the segment right after.
209 ++MergeTo;
210 Segment *MergeToSeg = segmentAt(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(B, 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, 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, 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;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000282using CalcLiveRangeUtilVectorBase =
283 CalcLiveRangeUtilBase<CalcLiveRangeUtilVector, LiveRange::iterator,
284 LiveRange::Segments>;
Quentin Colombeta8cb36e2015-02-06 18:42:41 +0000285
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(S); }
296
297 iterator find(SlotIndex Pos) { return LR->find(Pos); }
298
Fangrui Songfb79ff62019-04-12 11:31:16 +0000299 iterator findInsertPos(Segment S) { return llvm::upper_bound(*LR, S.start); }
Quentin Colombeta8cb36e2015-02-06 18:42:41 +0000300};
301
302//===----------------------------------------------------------------------===//
303// Instantiation of the methods for calculation of live ranges
304// based on a segment set.
305//===----------------------------------------------------------------------===//
306
307class CalcLiveRangeUtilSet;
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000308using CalcLiveRangeUtilSetBase =
309 CalcLiveRangeUtilBase<CalcLiveRangeUtilSet, LiveRange::SegmentSet::iterator,
310 LiveRange::SegmentSet>;
Quentin Colombeta8cb36e2015-02-06 18:42:41 +0000311
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(LR->segmentSet->end(), S);
323 }
324
325 iterator find(SlotIndex Pos) {
326 iterator I =
327 LR->segmentSet->upper_bound(Segment(Pos, Pos.getNextSlot(), nullptr));
328 if (I == LR->segmentSet->begin())
329 return I;
330 iterator PrevI = std::prev(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(S);
338 if (I != LR->segmentSet->end() && !(S.start < *I))
339 ++I;
340 return I;
341 }
342};
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000343
344} // end anonymous namespace
Quentin Colombeta8cb36e2015-02-06 18:42:41 +0000345
346//===----------------------------------------------------------------------===//
347// LiveRange methods
348//===----------------------------------------------------------------------===//
349
Matthias Braund7df9352013-10-10 21:28:47 +0000350LiveRange::iterator LiveRange::find(SlotIndex Pos) {
Jakob Stoklund Olesendae1dc12011-03-12 01:50:35 +0000351 // This algorithm is basically std::upper_bound.
352 // Unfortunately, std::upper_bound cannot be used with mixed types until we
353 // adopt C++0x. Many libraries can do it, but not all.
354 if (empty() || Pos >= endIndex())
355 return end();
356 iterator I = begin();
Matthias Braun305ef7f2013-09-06 16:44:32 +0000357 size_t Len = size();
Jakob Stoklund Olesendae1dc12011-03-12 01:50:35 +0000358 do {
359 size_t Mid = Len >> 1;
Richard Trieu7a083812016-02-18 22:09:30 +0000360 if (Pos < I[Mid].end) {
Jakob Stoklund Olesendae1dc12011-03-12 01:50:35 +0000361 Len = Mid;
Richard Trieu7a083812016-02-18 22:09:30 +0000362 } else {
363 I += Mid + 1;
364 Len -= Mid + 1;
365 }
Jakob Stoklund Olesendae1dc12011-03-12 01:50:35 +0000366 } while (Len);
367 return I;
Jakob Stoklund Olesen55d738e22010-06-25 22:53:05 +0000368}
369
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000370VNInfo *LiveRange::createDeadDef(SlotIndex Def, VNInfo::Allocator &VNIAlloc) {
Quentin Colombeta8cb36e2015-02-06 18:42:41 +0000371 // Use the segment set, if it is available.
372 if (segmentSet != nullptr)
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000373 return CalcLiveRangeUtilSet(this).createDeadDef(Def, &VNIAlloc, nullptr);
Quentin Colombeta8cb36e2015-02-06 18:42:41 +0000374 // Otherwise use the segment vector.
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000375 return CalcLiveRangeUtilVector(this).createDeadDef(Def, &VNIAlloc, nullptr);
376}
377
378VNInfo *LiveRange::createDeadDef(VNInfo *VNI) {
379 // Use the segment set, if it is available.
380 if (segmentSet != nullptr)
381 return CalcLiveRangeUtilSet(this).createDeadDef(VNI->def, nullptr, VNI);
382 // Otherwise use the segment vector.
383 return CalcLiveRangeUtilVector(this).createDeadDef(VNI->def, nullptr, VNI);
Jakob Stoklund Olesen989b3b12012-06-05 21:54:09 +0000384}
385
Matthias Braund7df9352013-10-10 21:28:47 +0000386// overlaps - Return true if the intersection of the two live ranges is
Chris Lattnercb0c9652004-11-18 03:47:34 +0000387// not empty.
388//
Chris Lattner78f62e32004-07-23 17:49:16 +0000389// An example for overlaps():
390//
391// 0: A = ...
392// 4: B = ...
393// 8: C = A + B ;; last use of A
394//
Matthias Braund7df9352013-10-10 21:28:47 +0000395// The live ranges should look like:
Chris Lattner78f62e32004-07-23 17:49:16 +0000396//
397// A = [3, 11)
398// B = [7, x)
399// C = [11, y)
400//
401// A->overlaps(C) should return false since we want to be able to join
402// A and C.
Chris Lattnercb0c9652004-11-18 03:47:34 +0000403//
Matthias Braund7df9352013-10-10 21:28:47 +0000404bool LiveRange::overlapsFrom(const LiveRange& other,
405 const_iterator StartPos) const {
406 assert(!empty() && "empty range");
Chris Lattnercb0c9652004-11-18 03:47:34 +0000407 const_iterator i = begin();
408 const_iterator ie = end();
409 const_iterator j = StartPos;
410 const_iterator je = other.end();
411
412 assert((StartPos->start <= i->start || StartPos == other.begin()) &&
Chris Lattner7598c312004-11-18 04:02:11 +0000413 StartPos != other.end() && "Bogus start position hint!");
Chris Lattnerccc75d4f2004-07-25 07:11:19 +0000414
Chris Lattner78f62e32004-07-23 17:49:16 +0000415 if (i->start < j->start) {
Chris Lattner2fcc5e42004-07-23 18:40:00 +0000416 i = std::upper_bound(i, ie, j->start);
Matthias Braun305ef7f2013-09-06 16:44:32 +0000417 if (i != begin()) --i;
Chris Lattner2fcc5e42004-07-23 18:40:00 +0000418 } else if (j->start < i->start) {
Chris Lattner5684f482004-12-04 01:22:09 +0000419 ++StartPos;
420 if (StartPos != other.end() && StartPos->start <= i->start) {
421 assert(StartPos < other.end() && i < end());
Chris Lattner7598c312004-11-18 04:02:11 +0000422 j = std::upper_bound(j, je, i->start);
Matthias Braun305ef7f2013-09-06 16:44:32 +0000423 if (j != other.begin()) --j;
Chris Lattner7598c312004-11-18 04:02:11 +0000424 }
Chris Lattner2fcc5e42004-07-23 18:40:00 +0000425 } else {
426 return true;
Chris Lattner78f62e32004-07-23 17:49:16 +0000427 }
428
Chris Lattnere3b9cb92004-11-18 05:28:21 +0000429 if (j == je) return false;
430
431 while (i != ie) {
Chris Lattner78f62e32004-07-23 17:49:16 +0000432 if (i->start > j->start) {
Alkis Evlogimenoscf72e7f2004-07-24 11:44:15 +0000433 std::swap(i, j);
434 std::swap(ie, je);
Chris Lattner78f62e32004-07-23 17:49:16 +0000435 }
Chris Lattner78f62e32004-07-23 17:49:16 +0000436
437 if (i->end > j->start)
438 return true;
439 ++i;
440 }
441
442 return false;
443}
444
Matthias Braund7df9352013-10-10 21:28:47 +0000445bool LiveRange::overlaps(const LiveRange &Other, const CoalescerPair &CP,
446 const SlotIndexes &Indexes) const {
447 assert(!empty() && "empty range");
Jakob Stoklund Olesen866908c2012-09-06 18:15:23 +0000448 if (Other.empty())
449 return false;
450
451 // Use binary searches to find initial positions.
452 const_iterator I = find(Other.beginIndex());
453 const_iterator IE = end();
454 if (I == IE)
455 return false;
456 const_iterator J = Other.find(I->start);
457 const_iterator JE = Other.end();
458 if (J == JE)
459 return false;
460
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000461 while (true) {
Jakob Stoklund Olesen866908c2012-09-06 18:15:23 +0000462 // J has just been advanced to satisfy:
463 assert(J->end >= I->start);
464 // Check for an overlap.
465 if (J->start < I->end) {
466 // I and J are overlapping. Find the later start.
467 SlotIndex Def = std::max(I->start, J->start);
468 // Allow the overlap if Def is a coalescable copy.
469 if (Def.isBlock() ||
470 !CP.isCoalescable(Indexes.getInstructionFromIndex(Def)))
471 return true;
472 }
473 // Advance the iterator that ends first to check for more overlaps.
474 if (J->end > I->end) {
475 std::swap(I, J);
476 std::swap(IE, JE);
477 }
478 // Advance J until J->end >= I->start.
479 do
480 if (++J == JE)
481 return false;
482 while (J->end < I->start);
483 }
484}
485
Matthias Braund7df9352013-10-10 21:28:47 +0000486/// overlaps - Return true if the live range overlaps an interval specified
Evan Chengb685be02009-04-18 08:52:15 +0000487/// by [Start, End).
Matthias Braund7df9352013-10-10 21:28:47 +0000488bool LiveRange::overlaps(SlotIndex Start, SlotIndex End) const {
Evan Chengb685be02009-04-18 08:52:15 +0000489 assert(Start < End && "Invalid range");
Jakob Stoklund Olesenb43455f2010-07-13 19:42:20 +0000490 const_iterator I = std::lower_bound(begin(), end(), End);
491 return I != begin() && (--I)->end > Start;
Evan Chengb685be02009-04-18 08:52:15 +0000492}
493
Matthias Braune62c2072014-12-10 01:12:06 +0000494bool LiveRange::covers(const LiveRange &Other) const {
495 if (empty())
496 return Other.empty();
497
498 const_iterator I = begin();
Matthias Braun96761952014-12-10 23:07:54 +0000499 for (const Segment &O : Other.segments) {
500 I = advanceTo(I, O.start);
501 if (I == end() || I->start > O.start)
Matthias Braune62c2072014-12-10 01:12:06 +0000502 return false;
503
Matthias Braun96761952014-12-10 23:07:54 +0000504 // Check adjacent live segments and see if we can get behind O.end.
505 while (I->end < O.end) {
Matthias Braune62c2072014-12-10 01:12:06 +0000506 const_iterator Last = I;
507 // Get next segment and abort if it was not adjacent.
508 ++I;
509 if (I == end() || Last->end != I->start)
510 return false;
511 }
512 }
513 return true;
514}
Lang Hames2e3f20b2010-07-26 01:49:41 +0000515
516/// ValNo is dead, remove it. If it is the largest value number, just nuke it
517/// (and any other deleted values neighboring it), otherwise mark it as ~1U so
518/// it can be nuked later.
Matthias Braund7df9352013-10-10 21:28:47 +0000519void LiveRange::markValNoForDeletion(VNInfo *ValNo) {
Lang Hames2e3f20b2010-07-26 01:49:41 +0000520 if (ValNo->id == getNumValNums()-1) {
521 do {
522 valnos.pop_back();
523 } while (!valnos.empty() && valnos.back()->isUnused());
524 } else {
Jakob Stoklund Olesendaae19f2012-08-03 20:59:32 +0000525 ValNo->markUnused();
Lang Hames2e3f20b2010-07-26 01:49:41 +0000526 }
527}
528
Jakob Stoklund Olesen8c0f6932010-08-06 18:46:59 +0000529/// RenumberValues - Renumber all values in order of appearance and delete the
530/// remaining unused values.
Matthias Braund7df9352013-10-10 21:28:47 +0000531void LiveRange::RenumberValues() {
Jakob Stoklund Olesen8c0f6932010-08-06 18:46:59 +0000532 SmallPtrSet<VNInfo*, 8> Seen;
533 valnos.clear();
Matthias Braun96761952014-12-10 23:07:54 +0000534 for (const Segment &S : segments) {
535 VNInfo *VNI = S.valno;
David Blaikie70573dc2014-11-19 07:49:26 +0000536 if (!Seen.insert(VNI).second)
Jakob Stoklund Olesen8c0f6932010-08-06 18:46:59 +0000537 continue;
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000538 assert(!VNI->isUnused() && "Unused valno used by live segment");
Jakob Stoklund Olesen8c0f6932010-08-06 18:46:59 +0000539 VNI->id = (unsigned)valnos.size();
540 valnos.push_back(VNI);
541 }
542}
543
Quentin Colombeta8cb36e2015-02-06 18:42:41 +0000544void LiveRange::addSegmentToSet(Segment S) {
545 CalcLiveRangeUtilSet(this).addSegment(S);
Chris Lattnerb4acba42004-07-23 19:38:44 +0000546}
547
Quentin Colombeta8cb36e2015-02-06 18:42:41 +0000548LiveRange::iterator LiveRange::addSegment(Segment S) {
549 // Use the segment set, if it is available.
550 if (segmentSet != nullptr) {
551 addSegmentToSet(S);
552 return end();
Chris Lattnerb4acba42004-07-23 19:38:44 +0000553 }
Quentin Colombeta8cb36e2015-02-06 18:42:41 +0000554 // Otherwise use the segment vector.
555 return CalcLiveRangeUtilVector(this).addSegment(S);
Chris Lattnerb4acba42004-07-23 19:38:44 +0000556}
557
Matthias Braundbcca0d2014-12-24 02:11:51 +0000558void LiveRange::append(const Segment S) {
559 // Check that the segment belongs to the back of the list.
560 assert(segments.empty() || segments.back().end <= S.start);
561 segments.push_back(S);
562}
563
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000564std::pair<VNInfo*,bool> LiveRange::extendInBlock(ArrayRef<SlotIndex> Undefs,
565 SlotIndex StartIdx, SlotIndex Kill) {
566 // Use the segment set, if it is available.
567 if (segmentSet != nullptr)
568 return CalcLiveRangeUtilSet(this).extendInBlock(Undefs, StartIdx, Kill);
569 // Otherwise use the segment vector.
570 return CalcLiveRangeUtilVector(this).extendInBlock(Undefs, StartIdx, Kill);
571}
572
Matthias Braund7df9352013-10-10 21:28:47 +0000573VNInfo *LiveRange::extendInBlock(SlotIndex StartIdx, SlotIndex Kill) {
Quentin Colombeta8cb36e2015-02-06 18:42:41 +0000574 // Use the segment set, if it is available.
575 if (segmentSet != nullptr)
576 return CalcLiveRangeUtilSet(this).extendInBlock(StartIdx, Kill);
577 // Otherwise use the segment vector.
578 return CalcLiveRangeUtilVector(this).extendInBlock(StartIdx, Kill);
Jakob Stoklund Olesen9e326a82011-03-02 00:06:15 +0000579}
Chris Lattner038747f2004-07-24 02:52:23 +0000580
Matthias Braund7df9352013-10-10 21:28:47 +0000581/// Remove the specified segment from this range. Note that the segment must
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000582/// be in a single Segment in its entirety.
Matthias Braund7df9352013-10-10 21:28:47 +0000583void LiveRange::removeSegment(SlotIndex Start, SlotIndex End,
584 bool RemoveDeadValNo) {
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000585 // Find the Segment containing this span.
Matthias Braun305ef7f2013-09-06 16:44:32 +0000586 iterator I = find(Start);
Matthias Braund7df9352013-10-10 21:28:47 +0000587 assert(I != end() && "Segment is not in range!");
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000588 assert(I->containsInterval(Start, End)
Matthias Braund7df9352013-10-10 21:28:47 +0000589 && "Segment is not entirely in range!");
Chris Lattner038747f2004-07-24 02:52:23 +0000590
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000591 // If the span we are removing is at the start of the Segment, adjust it.
Evan Cheng47f462a2008-02-13 02:48:26 +0000592 VNInfo *ValNo = I->valno;
Chris Lattner038747f2004-07-24 02:52:23 +0000593 if (I->start == Start) {
Evan Cheng05cc4862007-08-11 00:59:19 +0000594 if (I->end == End) {
Evan Cheng47f462a2008-02-13 02:48:26 +0000595 if (RemoveDeadValNo) {
596 // Check if val# is dead.
597 bool isDead = true;
598 for (const_iterator II = begin(), EE = end(); II != EE; ++II)
599 if (II != I && II->valno == ValNo) {
600 isDead = false;
601 break;
Jakob Stoklund Olesen55d738e22010-06-25 22:53:05 +0000602 }
Evan Cheng47f462a2008-02-13 02:48:26 +0000603 if (isDead) {
Lang Hames2e3f20b2010-07-26 01:49:41 +0000604 // Now that ValNo is dead, remove it.
605 markValNoForDeletion(ValNo);
Evan Cheng47f462a2008-02-13 02:48:26 +0000606 }
607 }
608
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000609 segments.erase(I); // Removed the whole Segment.
Evan Cheng05cc4862007-08-11 00:59:19 +0000610 } else
Chris Lattner038747f2004-07-24 02:52:23 +0000611 I->start = End;
612 return;
613 }
614
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000615 // Otherwise if the span we are removing is at the end of the Segment,
Chris Lattner038747f2004-07-24 02:52:23 +0000616 // adjust the other way.
617 if (I->end == End) {
Chris Lattneraf7e8982004-07-25 05:43:53 +0000618 I->end = Start;
Chris Lattner038747f2004-07-24 02:52:23 +0000619 return;
620 }
621
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000622 // Otherwise, we are splitting the Segment into two pieces.
Lang Hames05fb9632009-11-03 23:52:08 +0000623 SlotIndex OldEnd = I->end;
Matthias Braund7df9352013-10-10 21:28:47 +0000624 I->end = Start; // Trim the old segment.
Chris Lattner038747f2004-07-24 02:52:23 +0000625
626 // Insert the new one.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000627 segments.insert(std::next(I), Segment(End, OldEnd, ValNo));
Chris Lattner038747f2004-07-24 02:52:23 +0000628}
629
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000630/// removeValNo - Remove all the segments defined by the specified value#.
Evan Cheng47f462a2008-02-13 02:48:26 +0000631/// Also remove the value# from value# list.
Matthias Braund7df9352013-10-10 21:28:47 +0000632void LiveRange::removeValNo(VNInfo *ValNo) {
Evan Cheng47f462a2008-02-13 02:48:26 +0000633 if (empty()) return;
David Majnemerc7004902016-08-12 04:32:37 +0000634 segments.erase(remove_if(*this, [ValNo](const Segment &S) {
Benjamin Kramer4c5dcb02015-02-28 20:14:27 +0000635 return S.valno == ValNo;
636 }), end());
Lang Hames2e3f20b2010-07-26 01:49:41 +0000637 // Now that ValNo is dead, remove it.
638 markValNoForDeletion(ValNo);
Evan Cheng47f462a2008-02-13 02:48:26 +0000639}
Lang Hames3fffe622009-09-04 20:41:11 +0000640
Matthias Braund7df9352013-10-10 21:28:47 +0000641void LiveRange::join(LiveRange &Other,
642 const int *LHSValNoAssignments,
643 const int *RHSValNoAssignments,
644 SmallVectorImpl<VNInfo *> &NewVNInfo) {
Chandler Carruthac766b92012-07-10 05:06:03 +0000645 verify();
646
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000647 // Determine if any of our values are mapped. This is uncommon, so we want
Matthias Braund7df9352013-10-10 21:28:47 +0000648 // to avoid the range scan if not.
Chris Lattner34434e92006-08-29 23:18:15 +0000649 bool MustMapCurValNos = false;
Evan Cheng2089a212007-09-01 02:03:17 +0000650 unsigned NumVals = getNumValNums();
651 unsigned NumNewVals = NewVNInfo.size();
652 for (unsigned i = 0; i != NumVals; ++i) {
653 unsigned LHSValID = LHSValNoAssignments[i];
654 if (i != LHSValID ||
Lang Hames4d04f752012-02-02 06:55:45 +0000655 (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] != getValNumInfo(i))) {
Chris Lattner34434e92006-08-29 23:18:15 +0000656 MustMapCurValNos = true;
Lang Hames4d04f752012-02-02 06:55:45 +0000657 break;
658 }
Chris Lattnerd9bbbb82004-07-24 03:41:50 +0000659 }
Evan Cheng1ad4a612007-08-29 20:45:00 +0000660
Matthias Braund7df9352013-10-10 21:28:47 +0000661 // If we have to apply a mapping to our base range assignment, rewrite it now.
Jakob Stoklund Olesen4976d0d2012-09-27 21:05:59 +0000662 if (MustMapCurValNos && !empty()) {
Chris Lattner34434e92006-08-29 23:18:15 +0000663 // Map the first live range.
Lang Hames3a20bc32012-02-02 05:37:34 +0000664
Chris Lattner34434e92006-08-29 23:18:15 +0000665 iterator OutIt = begin();
Evan Cheng1ad4a612007-08-29 20:45:00 +0000666 OutIt->valno = NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000667 for (iterator I = std::next(OutIt), E = end(); I != E; ++I) {
Lang Hames3a20bc32012-02-02 05:37:34 +0000668 VNInfo* nextValNo = NewVNInfo[LHSValNoAssignments[I->valno->id]];
Craig Topperc0196b12014-04-14 00:51:57 +0000669 assert(nextValNo && "Huh?");
Jakob Stoklund Olesen073cd802010-08-12 20:01:23 +0000670
Chris Lattner34434e92006-08-29 23:18:15 +0000671 // If this live range has the same value # as its immediate predecessor,
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000672 // and if they are neighbors, remove one Segment. This happens when we
Lang Hames3a20bc32012-02-02 05:37:34 +0000673 // have [0,4:0)[4,7:1) and map 0/1 onto the same value #.
674 if (OutIt->valno == nextValNo && OutIt->end == I->start) {
675 OutIt->end = I->end;
Chris Lattner34434e92006-08-29 23:18:15 +0000676 } else {
Matthias Braund7df9352013-10-10 21:28:47 +0000677 // Didn't merge. Move OutIt to the next segment,
Lang Hames3a20bc32012-02-02 05:37:34 +0000678 ++OutIt;
679 OutIt->valno = nextValNo;
680 if (OutIt != I) {
Chris Lattner34434e92006-08-29 23:18:15 +0000681 OutIt->start = I->start;
682 OutIt->end = I->end;
683 }
Chris Lattner34434e92006-08-29 23:18:15 +0000684 }
685 }
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000686 // If we merge some segments, chop off the end.
Lang Hames3a20bc32012-02-02 05:37:34 +0000687 ++OutIt;
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000688 segments.erase(OutIt, end());
Chris Lattner34434e92006-08-29 23:18:15 +0000689 }
Evan Cheng05cc4862007-08-11 00:59:19 +0000690
Jakob Stoklund Olesen1744fd82013-02-20 23:51:10 +0000691 // Rewrite Other values before changing the VNInfo ids.
692 // This can leave Other in an invalid state because we're not coalescing
693 // touching segments that now have identical values. That's OK since Other is
694 // not supposed to be valid after calling join();
Matthias Braun96761952014-12-10 23:07:54 +0000695 for (Segment &S : Other.segments)
696 S.valno = NewVNInfo[RHSValNoAssignments[S.valno->id]];
Evan Cheng1ad4a612007-08-29 20:45:00 +0000697
698 // Update val# info. Renumber them and make sure they all belong to this
Matthias Braund7df9352013-10-10 21:28:47 +0000699 // LiveRange now. Also remove dead val#'s.
Evan Chengdb53aef2007-09-05 21:46:51 +0000700 unsigned NumValNos = 0;
701 for (unsigned i = 0; i < NumNewVals; ++i) {
Evan Cheng1ad4a612007-08-29 20:45:00 +0000702 VNInfo *VNI = NewVNInfo[i];
Evan Chengdb53aef2007-09-05 21:46:51 +0000703 if (VNI) {
Evan Cheng7e099942009-04-28 06:24:09 +0000704 if (NumValNos >= NumVals)
Evan Chengdb53aef2007-09-05 21:46:51 +0000705 valnos.push_back(VNI);
Jakob Stoklund Olesen073cd802010-08-12 20:01:23 +0000706 else
Evan Chengdb53aef2007-09-05 21:46:51 +0000707 valnos[NumValNos] = VNI;
708 VNI->id = NumValNos++; // Renumber val#.
Evan Cheng2089a212007-09-01 02:03:17 +0000709 }
710 }
Evan Cheng2089a212007-09-01 02:03:17 +0000711 if (NumNewVals < NumVals)
712 valnos.resize(NumNewVals); // shrinkify
Evan Cheng05cc4862007-08-11 00:59:19 +0000713
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000714 // Okay, now insert the RHS live segments into the LHS.
Jakob Stoklund Olesen623d8322013-02-20 18:18:15 +0000715 LiveRangeUpdater Updater(this);
Matthias Braun96761952014-12-10 23:07:54 +0000716 for (Segment &S : Other.segments)
717 Updater.add(S);
Chandler Carruthe18614d2012-07-10 05:16:17 +0000718}
719
Matthias Braund7df9352013-10-10 21:28:47 +0000720/// Merge all of the segments in RHS into this live range as the specified
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000721/// value number. The segments in RHS are allowed to overlap with segments in
Matthias Braund7df9352013-10-10 21:28:47 +0000722/// the current range, but only if the overlapping segments have the
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000723/// specified value number.
Matthias Braund7df9352013-10-10 21:28:47 +0000724void LiveRange::MergeSegmentsInAsValue(const LiveRange &RHS,
725 VNInfo *LHSValNo) {
Jakob Stoklund Olesen623d8322013-02-20 18:18:15 +0000726 LiveRangeUpdater Updater(this);
Matthias Braun96761952014-12-10 23:07:54 +0000727 for (const Segment &S : RHS.segments)
728 Updater.add(S.start, S.end, LHSValNo);
Chris Lattner5a56d302006-09-02 05:26:59 +0000729}
730
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000731/// MergeValueInAsValue - Merge all of the live segments of a specific val#
Matthias Braund7df9352013-10-10 21:28:47 +0000732/// in RHS into this live range as the specified value number.
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000733/// The segments in RHS are allowed to overlap with segments in the
Matthias Braund7df9352013-10-10 21:28:47 +0000734/// current range, it will replace the value numbers of the overlaped
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000735/// segments with the specified value number.
Matthias Braund7df9352013-10-10 21:28:47 +0000736void LiveRange::MergeValueInAsValue(const LiveRange &RHS,
737 const VNInfo *RHSValNo,
738 VNInfo *LHSValNo) {
Jakob Stoklund Olesen623d8322013-02-20 18:18:15 +0000739 LiveRangeUpdater Updater(this);
Matthias Braun96761952014-12-10 23:07:54 +0000740 for (const Segment &S : RHS.segments)
741 if (S.valno == RHSValNo)
742 Updater.add(S.start, S.end, LHSValNo);
Evan Chengaa2d6ef2007-10-12 08:50:34 +0000743}
744
Chris Lattnerbdf12102006-08-24 22:43:55 +0000745/// MergeValueNumberInto - This method is called when two value nubmers
746/// are found to be equivalent. This eliminates V1, replacing all
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000747/// segments with the V1 value number with the V2 value number. This can
Chris Lattnerbdf12102006-08-24 22:43:55 +0000748/// cause merging of V1/V2 values numbers and compaction of the value space.
Matthias Braund7df9352013-10-10 21:28:47 +0000749VNInfo *LiveRange::MergeValueNumberInto(VNInfo *V1, VNInfo *V2) {
Chris Lattnerbdf12102006-08-24 22:43:55 +0000750 assert(V1 != V2 && "Identical value#'s are always equivalent!");
751
752 // This code actually merges the (numerically) larger value number into the
753 // smaller value number, which is likely to allow us to compactify the value
754 // space. The only thing we have to be careful of is to preserve the
755 // instruction that defines the result value.
756
757 // Make sure V2 is smaller than V1.
Evan Cheng1ad4a612007-08-29 20:45:00 +0000758 if (V1->id < V2->id) {
Lang Hames3b90d972009-08-10 23:43:28 +0000759 V1->copyFrom(*V2);
Chris Lattnerbdf12102006-08-24 22:43:55 +0000760 std::swap(V1, V2);
761 }
762
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000763 // Merge V1 segments into V2.
Chris Lattnerbdf12102006-08-24 22:43:55 +0000764 for (iterator I = begin(); I != end(); ) {
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000765 iterator S = I++;
766 if (S->valno != V1) continue; // Not a V1 Segment.
Jakob Stoklund Olesen073cd802010-08-12 20:01:23 +0000767
Chris Lattnerbdf12102006-08-24 22:43:55 +0000768 // Okay, we found a V1 live range. If it had a previous, touching, V2 live
769 // range, extend it.
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000770 if (S != begin()) {
771 iterator Prev = S-1;
772 if (Prev->valno == V2 && Prev->end == S->start) {
773 Prev->end = S->end;
Chris Lattnerbdf12102006-08-24 22:43:55 +0000774
775 // Erase this live-range.
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000776 segments.erase(S);
Chris Lattnerbdf12102006-08-24 22:43:55 +0000777 I = Prev+1;
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000778 S = Prev;
Chris Lattnerbdf12102006-08-24 22:43:55 +0000779 }
780 }
Jakob Stoklund Olesen073cd802010-08-12 20:01:23 +0000781
Chris Lattnerbdf12102006-08-24 22:43:55 +0000782 // Okay, now we have a V1 or V2 live range that is maximally merged forward.
783 // Ensure that it is a V2 live-range.
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000784 S->valno = V2;
Jakob Stoklund Olesen073cd802010-08-12 20:01:23 +0000785
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000786 // If we can merge it into later V2 segments, do so now. We ignore any
787 // following V1 segments, as they will be merged in subsequent iterations
Chris Lattnerbdf12102006-08-24 22:43:55 +0000788 // of the loop.
789 if (I != end()) {
Matthias Braun13ddb7c2013-10-10 21:28:43 +0000790 if (I->start == S->end && I->valno == V2) {
791 S->end = I->end;
792 segments.erase(I);
793 I = S+1;
Chris Lattnerbdf12102006-08-24 22:43:55 +0000794 }
795 }
796 }
Jakob Stoklund Olesen073cd802010-08-12 20:01:23 +0000797
Lang Hames2e3f20b2010-07-26 01:49:41 +0000798 // Now that V1 is dead, remove it.
799 markValNoForDeletion(V1);
Jakob Stoklund Olesen073cd802010-08-12 20:01:23 +0000800
Owen Anderson4eda2cb2009-02-02 22:42:01 +0000801 return V2;
Chris Lattnerbdf12102006-08-24 22:43:55 +0000802}
803
Quentin Colombeta8cb36e2015-02-06 18:42:41 +0000804void LiveRange::flushSegmentSet() {
805 assert(segmentSet != nullptr && "segment set must have been created");
806 assert(
807 segments.empty() &&
808 "segment set can be used only initially before switching to the array");
809 segments.append(segmentSet->begin(), segmentSet->end());
Quentin Colombeta8cb36e2015-02-06 18:42:41 +0000810 segmentSet = nullptr;
811 verify();
812}
813
Andrew Kaylor12244882016-02-08 22:52:51 +0000814bool LiveRange::isLiveAtIndexes(ArrayRef<SlotIndex> Slots) const {
815 ArrayRef<SlotIndex>::iterator SlotI = Slots.begin();
816 ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
817
818 // If there are no regmask slots, we have nothing to search.
819 if (SlotI == SlotE)
820 return false;
821
822 // Start our search at the first segment that ends after the first slot.
823 const_iterator SegmentI = find(*SlotI);
824 const_iterator SegmentE = end();
825
826 // If there are no segments that end after the first slot, we're done.
827 if (SegmentI == SegmentE)
828 return false;
829
830 // Look for each slot in the live range.
831 for ( ; SlotI != SlotE; ++SlotI) {
832 // Go to the next segment that ends after the current slot.
833 // The slot may be within a hole in the range.
834 SegmentI = advanceTo(SegmentI, *SlotI);
835 if (SegmentI == SegmentE)
836 return false;
837
838 // If this segment contains the slot, we're done.
839 if (SegmentI->contains(*SlotI))
840 return true;
841 // Otherwise, look for the next slot.
842 }
843
844 // We didn't find a segment containing any of the slots.
845 return false;
846}
847
Matthias Braun7dc96de2015-02-06 17:28:47 +0000848void LiveInterval::freeSubRange(SubRange *S) {
849 S->~SubRange();
850 // Memory was allocated with BumpPtr allocator and is not freed here.
851}
852
Matthias Braun2079aa92014-12-10 01:12:40 +0000853void LiveInterval::removeEmptySubRanges() {
854 SubRange **NextPtr = &SubRanges;
855 SubRange *I = *NextPtr;
856 while (I != nullptr) {
857 if (!I->empty()) {
858 NextPtr = &I->Next;
859 I = *NextPtr;
860 continue;
861 }
862 // Skip empty subranges until we find the first nonempty one.
863 do {
Matthias Braun7dc96de2015-02-06 17:28:47 +0000864 SubRange *Next = I->Next;
865 freeSubRange(I);
866 I = Next;
Matthias Braun2079aa92014-12-10 01:12:40 +0000867 } while (I != nullptr && I->empty());
868 *NextPtr = I;
869 }
870}
871
Matthias Braun7dc96de2015-02-06 17:28:47 +0000872void LiveInterval::clearSubRanges() {
873 for (SubRange *I = SubRanges, *Next; I != nullptr; I = Next) {
874 Next = I->Next;
875 freeSubRange(I);
876 }
877 SubRanges = nullptr;
878}
879
Quentin Colombetc74271c2019-03-26 21:27:15 +0000880/// For each VNI in \p SR, check whether or not that value defines part
881/// of the mask describe by \p LaneMask and if not, remove that value
882/// from \p SR.
883static void stripValuesNotDefiningMask(unsigned Reg, LiveInterval::SubRange &SR,
884 LaneBitmask LaneMask,
885 const SlotIndexes &Indexes,
886 const TargetRegisterInfo &TRI) {
887 // Phys reg should not be tracked at subreg level.
888 // Same for noreg (Reg == 0).
889 if (!TargetRegisterInfo::isVirtualRegister(Reg) || !Reg)
890 return;
891 // Remove the values that don't define those lanes.
892 SmallVector<VNInfo *, 8> ToBeRemoved;
893 for (VNInfo *VNI : SR.valnos) {
894 if (VNI->isUnused())
895 continue;
896 // PHI definitions don't have MI attached, so there is nothing
897 // we can use to strip the VNI.
898 if (VNI->isPHIDef())
899 continue;
900 const MachineInstr *MI = Indexes.getInstructionFromIndex(VNI->def);
901 assert(MI && "Cannot find the definition of a value");
902 bool hasDef = false;
903 for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
904 if (!MOI->isReg() || !MOI->isDef())
905 continue;
906 if (MOI->getReg() != Reg)
907 continue;
908 if ((TRI.getSubRegIndexLaneMask(MOI->getSubReg()) & LaneMask).none())
909 continue;
910 hasDef = true;
911 break;
912 }
913
914 if (!hasDef)
915 ToBeRemoved.push_back(VNI);
916 }
917 for (VNInfo *VNI : ToBeRemoved)
918 SR.removeValNo(VNI);
919
920 assert(!SR.empty() && "At least one value should be defined by this mask");
921}
922
923void LiveInterval::refineSubRanges(
924 BumpPtrAllocator &Allocator, LaneBitmask LaneMask,
925 std::function<void(LiveInterval::SubRange &)> Apply,
926 const SlotIndexes &Indexes, const TargetRegisterInfo &TRI) {
Matthias Brauna04d7ad2017-03-03 19:05:34 +0000927 LaneBitmask ToApply = LaneMask;
928 for (SubRange &SR : subranges()) {
929 LaneBitmask SRMask = SR.LaneMask;
930 LaneBitmask Matching = SRMask & LaneMask;
931 if (Matching.none())
932 continue;
933
934 SubRange *MatchingRange;
935 if (SRMask == Matching) {
936 // The subrange fits (it does not cover bits outside \p LaneMask).
937 MatchingRange = &SR;
938 } else {
939 // We have to split the subrange into a matching and non-matching part.
940 // Reduce lanemask of existing lane to non-matching part.
941 SR.LaneMask = SRMask & ~Matching;
942 // Create a new subrange for the matching part
943 MatchingRange = createSubRangeFrom(Allocator, Matching, SR);
Quentin Colombetc74271c2019-03-26 21:27:15 +0000944 // Now that the subrange is split in half, make sure we
945 // only keep in the subranges the VNIs that touch the related half.
946 stripValuesNotDefiningMask(reg, *MatchingRange, Matching, Indexes, TRI);
947 stripValuesNotDefiningMask(reg, SR, SR.LaneMask, Indexes, TRI);
Matthias Brauna04d7ad2017-03-03 19:05:34 +0000948 }
949 Apply(*MatchingRange);
950 ToApply &= ~Matching;
951 }
952 // Create a new subrange if there are uncovered bits left.
953 if (ToApply.any()) {
954 SubRange *NewRange = createSubRange(Allocator, ToApply);
955 Apply(*NewRange);
956 }
957}
958
Evan Cheng57b52142007-04-17 20:25:11 +0000959unsigned LiveInterval::getSize() const {
960 unsigned Sum = 0;
Matthias Braun96761952014-12-10 23:07:54 +0000961 for (const Segment &S : segments)
962 Sum += S.start.distance(S.end);
Evan Cheng57b52142007-04-17 20:25:11 +0000963 return Sum;
964}
965
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000966void LiveInterval::computeSubRangeUndefs(SmallVectorImpl<SlotIndex> &Undefs,
967 LaneBitmask LaneMask,
968 const MachineRegisterInfo &MRI,
969 const SlotIndexes &Indexes) const {
970 assert(TargetRegisterInfo::isVirtualRegister(reg));
971 LaneBitmask VRegMask = MRI.getMaxLaneMaskForVReg(reg);
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +0000972 assert((VRegMask & LaneMask).any());
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000973 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
974 for (const MachineOperand &MO : MRI.def_operands(reg)) {
975 if (!MO.isUndef())
976 continue;
977 unsigned SubReg = MO.getSubReg();
978 assert(SubReg != 0 && "Undef should only be set on subreg defs");
979 LaneBitmask DefMask = TRI.getSubRegIndexLaneMask(SubReg);
980 LaneBitmask UndefMask = VRegMask & ~DefMask;
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +0000981 if ((UndefMask & LaneMask).any()) {
Krzysztof Parzyszeka7ed0902016-08-24 13:37:55 +0000982 const MachineInstr &MI = *MO.getParent();
983 bool EarlyClobber = MO.isEarlyClobber();
984 SlotIndex Pos = Indexes.getInstructionIndex(MI).getRegSlot(EarlyClobber);
985 Undefs.push_back(Pos);
986 }
987 }
988}
989
Eugene Zelenko5df3d892017-08-24 21:21:39 +0000990raw_ostream& llvm::operator<<(raw_ostream& OS, const LiveRange::Segment &S) {
991 return OS << '[' << S.start << ',' << S.end << ':' << S.valno->id << ')';
Daniel Dunbar796e43e2009-07-24 10:36:58 +0000992}
Chris Lattner78f62e32004-07-23 17:49:16 +0000993
Aaron Ballman615eb472017-10-15 14:32:27 +0000994#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +0000995LLVM_DUMP_METHOD void LiveRange::Segment::dump() const {
Krzysztof Parzyszekf5b9bb62016-07-12 17:37:44 +0000996 dbgs() << *this << '\n';
Chris Lattner038747f2004-07-24 02:52:23 +0000997}
Manman Ren742534c2012-09-06 19:06:06 +0000998#endif
Chris Lattner038747f2004-07-24 02:52:23 +0000999
Matthias Braund7df9352013-10-10 21:28:47 +00001000void LiveRange::print(raw_ostream &OS) const {
Chris Lattnerc08d7862005-05-14 05:34:15 +00001001 if (empty())
Jakob Stoklund Olesenf3f7d6f2012-06-05 22:51:54 +00001002 OS << "EMPTY";
Chris Lattnerc08d7862005-05-14 05:34:15 +00001003 else {
Matthias Braun96761952014-12-10 23:07:54 +00001004 for (const Segment &S : segments) {
1005 OS << S;
1006 assert(S.valno == getValNumInfo(S.valno->id) && "Bad VNInfo");
Jakob Stoklund Olesen731ea712010-06-23 15:34:36 +00001007 }
Chris Lattnerc08d7862005-05-14 05:34:15 +00001008 }
Jakob Stoklund Olesen55d738e22010-06-25 22:53:05 +00001009
Chris Lattner2e9f1bc2006-08-22 18:19:46 +00001010 // Print value number info.
Chris Lattner34434e92006-08-29 23:18:15 +00001011 if (getNumValNums()) {
Chris Lattner2e9f1bc2006-08-22 18:19:46 +00001012 OS << " ";
Evan Chenga5b10b32007-08-28 08:28:51 +00001013 unsigned vnum = 0;
1014 for (const_vni_iterator i = vni_begin(), e = vni_end(); i != e;
1015 ++i, ++vnum) {
Evan Cheng1ad4a612007-08-29 20:45:00 +00001016 const VNInfo *vni = *i;
Krzysztof Parzyszekf5b9bb62016-07-12 17:37:44 +00001017 if (vnum) OS << ' ';
1018 OS << vnum << '@';
Lang Hames16cab192009-06-17 21:01:20 +00001019 if (vni->isUnused()) {
Krzysztof Parzyszekf5b9bb62016-07-12 17:37:44 +00001020 OS << 'x';
Chris Lattner2e9f1bc2006-08-22 18:19:46 +00001021 } else {
Lang Hames56495682010-09-25 12:04:16 +00001022 OS << vni->def;
Jakob Stoklund Olesen9a414902010-10-05 18:48:57 +00001023 if (vni->isPHIDef())
Jakob Stoklund Olesen9f565e12012-08-03 20:19:44 +00001024 OS << "-phi";
Evan Cheng0d0fee22007-08-07 23:49:57 +00001025 }
Chris Lattner2e9f1bc2006-08-22 18:19:46 +00001026 }
1027 }
Chris Lattner78f62e32004-07-23 17:49:16 +00001028}
Chris Lattner038747f2004-07-24 02:52:23 +00001029
Krzysztof Parzyszekf5b9bb62016-07-12 17:37:44 +00001030void LiveInterval::SubRange::print(raw_ostream &OS) const {
1031 OS << " L" << PrintLaneMask(LaneMask) << ' '
1032 << static_cast<const LiveRange&>(*this);
1033}
1034
Matthias Braunf6fe6bf2013-10-10 21:29:05 +00001035void LiveInterval::print(raw_ostream &OS) const {
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001036 OS << printReg(reg) << ' ';
Matthias Braunf6fe6bf2013-10-10 21:29:05 +00001037 super::print(OS);
Matthias Braun3f1d8fd2014-12-10 01:12:10 +00001038 // Print subranges
Krzysztof Parzyszekf5b9bb62016-07-12 17:37:44 +00001039 for (const SubRange &SR : subranges())
1040 OS << SR;
Matthias Braunbd4bc3f2018-01-29 22:03:00 +00001041 OS << " weight:" << weight;
Matthias Braunf6fe6bf2013-10-10 21:29:05 +00001042}
1043
Aaron Ballman615eb472017-10-15 14:32:27 +00001044#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00001045LLVM_DUMP_METHOD void LiveRange::dump() const {
Krzysztof Parzyszekf5b9bb62016-07-12 17:37:44 +00001046 dbgs() << *this << '\n';
1047}
1048
1049LLVM_DUMP_METHOD void LiveInterval::SubRange::dump() const {
1050 dbgs() << *this << '\n';
Chris Lattner038747f2004-07-24 02:52:23 +00001051}
Matthias Braunf6fe6bf2013-10-10 21:29:05 +00001052
Yaron Kereneb2a2542016-01-29 20:50:44 +00001053LLVM_DUMP_METHOD void LiveInterval::dump() const {
Krzysztof Parzyszekf5b9bb62016-07-12 17:37:44 +00001054 dbgs() << *this << '\n';
Matthias Braunf6fe6bf2013-10-10 21:29:05 +00001055}
Manman Ren742534c2012-09-06 19:06:06 +00001056#endif
Jeff Cohenb82309f2006-12-15 22:57:14 +00001057
Chandler Carruthac766b92012-07-10 05:06:03 +00001058#ifndef NDEBUG
Matthias Braund7df9352013-10-10 21:28:47 +00001059void LiveRange::verify() const {
Chandler Carruthac766b92012-07-10 05:06:03 +00001060 for (const_iterator I = begin(), E = end(); I != E; ++I) {
1061 assert(I->start.isValid());
1062 assert(I->end.isValid());
1063 assert(I->start < I->end);
Craig Topperc0196b12014-04-14 00:51:57 +00001064 assert(I->valno != nullptr);
Matthias Braund7df9352013-10-10 21:28:47 +00001065 assert(I->valno->id < valnos.size());
Chandler Carruthac766b92012-07-10 05:06:03 +00001066 assert(I->valno == valnos[I->valno->id]);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001067 if (std::next(I) != E) {
1068 assert(I->end <= std::next(I)->start);
1069 if (I->end == std::next(I)->start)
1070 assert(I->valno != std::next(I)->valno);
Chandler Carruthac766b92012-07-10 05:06:03 +00001071 }
1072 }
1073}
Matthias Braun3f1d8fd2014-12-10 01:12:10 +00001074
1075void LiveInterval::verify(const MachineRegisterInfo *MRI) const {
1076 super::verify();
1077
1078 // Make sure SubRanges are fine and LaneMasks are disjunct.
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +00001079 LaneBitmask Mask;
1080 LaneBitmask MaxMask = MRI != nullptr ? MRI->getMaxLaneMaskForVReg(reg)
1081 : LaneBitmask::getAll();
Matthias Braun09afa1e2014-12-11 00:59:06 +00001082 for (const SubRange &SR : subranges()) {
Matthias Braun3f1d8fd2014-12-10 01:12:10 +00001083 // Subrange lanemask should be disjunct to any previous subrange masks.
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +00001084 assert((Mask & SR.LaneMask).none());
Matthias Braun09afa1e2014-12-11 00:59:06 +00001085 Mask |= SR.LaneMask;
Matthias Braun3f1d8fd2014-12-10 01:12:10 +00001086
1087 // subrange mask should not contained in maximum lane mask for the vreg.
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +00001088 assert((Mask & ~MaxMask).none());
Matthias Braun0d4cebd2015-07-16 18:55:35 +00001089 // empty subranges must be removed.
1090 assert(!SR.empty());
Matthias Braun3f1d8fd2014-12-10 01:12:10 +00001091
Matthias Braun09afa1e2014-12-11 00:59:06 +00001092 SR.verify();
Matthias Braun3f1d8fd2014-12-10 01:12:10 +00001093 // Main liverange should cover subrange.
Matthias Braun09afa1e2014-12-11 00:59:06 +00001094 assert(covers(SR));
Matthias Braun3f1d8fd2014-12-10 01:12:10 +00001095 }
1096}
Chandler Carruthac766b92012-07-10 05:06:03 +00001097#endif
1098
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001099//===----------------------------------------------------------------------===//
1100// LiveRangeUpdater class
1101//===----------------------------------------------------------------------===//
1102//
1103// The LiveRangeUpdater class always maintains these invariants:
1104//
1105// - When LastStart is invalid, Spills is empty and the iterators are invalid.
1106// This is the initial state, and the state created by flush().
1107// In this state, isDirty() returns false.
1108//
1109// Otherwise, segments are kept in three separate areas:
1110//
Matthias Braund7df9352013-10-10 21:28:47 +00001111// 1. [begin; WriteI) at the front of LR.
1112// 2. [ReadI; end) at the back of LR.
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001113// 3. Spills.
1114//
Matthias Braund7df9352013-10-10 21:28:47 +00001115// - LR.begin() <= WriteI <= ReadI <= LR.end().
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001116// - Segments in all three areas are fully ordered and coalesced.
1117// - Segments in area 1 precede and can't coalesce with segments in area 2.
1118// - Segments in Spills precede and can't coalesce with segments in area 2.
1119// - No coalescing is possible between segments in Spills and segments in area
1120// 1, and there are no overlapping segments.
1121//
1122// The segments in Spills are not ordered with respect to the segments in area
1123// 1. They need to be merged.
1124//
1125// When they exist, Spills.back().start <= LastStart,
1126// and WriteI[-1].start <= LastStart.
1127
Aaron Ballman615eb472017-10-15 14:32:27 +00001128#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001129void LiveRangeUpdater::print(raw_ostream &OS) const {
1130 if (!isDirty()) {
Matthias Braund7df9352013-10-10 21:28:47 +00001131 if (LR)
1132 OS << "Clean updater: " << *LR << '\n';
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001133 else
1134 OS << "Null updater.\n";
1135 return;
1136 }
Matthias Braund7df9352013-10-10 21:28:47 +00001137 assert(LR && "Can't have null LR in dirty updater.");
1138 OS << " updater with gap = " << (ReadI - WriteI)
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001139 << ", last start = " << LastStart
1140 << ":\n Area 1:";
Matthias Braun96761952014-12-10 23:07:54 +00001141 for (const auto &S : make_range(LR->begin(), WriteI))
1142 OS << ' ' << S;
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001143 OS << "\n Spills:";
1144 for (unsigned I = 0, E = Spills.size(); I != E; ++I)
1145 OS << ' ' << Spills[I];
1146 OS << "\n Area 2:";
Matthias Braun96761952014-12-10 23:07:54 +00001147 for (const auto &S : make_range(ReadI, LR->end()))
1148 OS << ' ' << S;
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001149 OS << '\n';
1150}
1151
Yaron Kereneb2a2542016-01-29 20:50:44 +00001152LLVM_DUMP_METHOD void LiveRangeUpdater::dump() const {
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001153 print(errs());
1154}
Matthias Braun8c209aa2017-01-28 02:02:38 +00001155#endif
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001156
1157// Determine if A and B should be coalesced.
Matthias Braund7df9352013-10-10 21:28:47 +00001158static inline bool coalescable(const LiveRange::Segment &A,
1159 const LiveRange::Segment &B) {
Matthias Braun13ddb7c2013-10-10 21:28:43 +00001160 assert(A.start <= B.start && "Unordered live segments.");
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001161 if (A.end == B.start)
1162 return A.valno == B.valno;
1163 if (A.end < B.start)
1164 return false;
1165 assert(A.valno == B.valno && "Cannot overlap different values");
1166 return true;
1167}
1168
Matthias Braund7df9352013-10-10 21:28:47 +00001169void LiveRangeUpdater::add(LiveRange::Segment Seg) {
1170 assert(LR && "Cannot add to a null destination");
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001171
Quentin Colombeta8cb36e2015-02-06 18:42:41 +00001172 // Fall back to the regular add method if the live range
1173 // is using the segment set instead of the segment vector.
1174 if (LR->segmentSet != nullptr) {
1175 LR->addSegmentToSet(Seg);
1176 return;
1177 }
1178
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001179 // Flush the state if Start moves backwards.
1180 if (!LastStart.isValid() || LastStart > Seg.start) {
1181 if (isDirty())
1182 flush();
1183 // This brings us to an uninitialized state. Reinitialize.
1184 assert(Spills.empty() && "Leftover spilled segments");
Matthias Braund7df9352013-10-10 21:28:47 +00001185 WriteI = ReadI = LR->begin();
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001186 }
1187
1188 // Remember start for next time.
1189 LastStart = Seg.start;
1190
1191 // Advance ReadI until it ends after Seg.start.
Matthias Braund7df9352013-10-10 21:28:47 +00001192 LiveRange::iterator E = LR->end();
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001193 if (ReadI != E && ReadI->end <= Seg.start) {
1194 // First try to close the gap between WriteI and ReadI with spills.
1195 if (ReadI != WriteI)
1196 mergeSpills();
1197 // Then advance ReadI.
1198 if (ReadI == WriteI)
Matthias Braund7df9352013-10-10 21:28:47 +00001199 ReadI = WriteI = LR->find(Seg.start);
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001200 else
1201 while (ReadI != E && ReadI->end <= Seg.start)
1202 *WriteI++ = *ReadI++;
1203 }
1204
1205 assert(ReadI == E || ReadI->end > Seg.start);
1206
1207 // Check if the ReadI segment begins early.
1208 if (ReadI != E && ReadI->start <= Seg.start) {
1209 assert(ReadI->valno == Seg.valno && "Cannot overlap different values");
1210 // Bail if Seg is completely contained in ReadI.
1211 if (ReadI->end >= Seg.end)
1212 return;
1213 // Coalesce into Seg.
1214 Seg.start = ReadI->start;
1215 ++ReadI;
1216 }
1217
1218 // Coalesce as much as possible from ReadI into Seg.
1219 while (ReadI != E && coalescable(Seg, *ReadI)) {
1220 Seg.end = std::max(Seg.end, ReadI->end);
1221 ++ReadI;
1222 }
1223
1224 // Try coalescing Spills.back() into Seg.
1225 if (!Spills.empty() && coalescable(Spills.back(), Seg)) {
1226 Seg.start = Spills.back().start;
1227 Seg.end = std::max(Spills.back().end, Seg.end);
1228 Spills.pop_back();
1229 }
1230
1231 // Try coalescing Seg into WriteI[-1].
Matthias Braund7df9352013-10-10 21:28:47 +00001232 if (WriteI != LR->begin() && coalescable(WriteI[-1], Seg)) {
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001233 WriteI[-1].end = std::max(WriteI[-1].end, Seg.end);
1234 return;
1235 }
1236
1237 // Seg doesn't coalesce with anything, and needs to be inserted somewhere.
1238 if (WriteI != ReadI) {
1239 *WriteI++ = Seg;
1240 return;
1241 }
1242
Matthias Braund7df9352013-10-10 21:28:47 +00001243 // Finally, append to LR or Spills.
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001244 if (WriteI == E) {
Matthias Braund7df9352013-10-10 21:28:47 +00001245 LR->segments.push_back(Seg);
1246 WriteI = ReadI = LR->end();
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001247 } else
1248 Spills.push_back(Seg);
1249}
1250
1251// Merge as many spilled segments as possible into the gap between WriteI
1252// and ReadI. Advance WriteI to reflect the inserted instructions.
1253void LiveRangeUpdater::mergeSpills() {
1254 // Perform a backwards merge of Spills and [SpillI;WriteI).
1255 size_t GapSize = ReadI - WriteI;
1256 size_t NumMoved = std::min(Spills.size(), GapSize);
Matthias Braund7df9352013-10-10 21:28:47 +00001257 LiveRange::iterator Src = WriteI;
1258 LiveRange::iterator Dst = Src + NumMoved;
1259 LiveRange::iterator SpillSrc = Spills.end();
1260 LiveRange::iterator B = LR->begin();
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001261
1262 // This is the new WriteI position after merging spills.
1263 WriteI = Dst;
1264
1265 // Now merge Src and Spills backwards.
1266 while (Src != Dst) {
1267 if (Src != B && Src[-1].start > SpillSrc[-1].start)
1268 *--Dst = *--Src;
1269 else
1270 *--Dst = *--SpillSrc;
1271 }
1272 assert(NumMoved == size_t(Spills.end() - SpillSrc));
1273 Spills.erase(SpillSrc, Spills.end());
1274}
1275
1276void LiveRangeUpdater::flush() {
1277 if (!isDirty())
1278 return;
1279 // Clear the dirty state.
1280 LastStart = SlotIndex();
1281
Matthias Braund7df9352013-10-10 21:28:47 +00001282 assert(LR && "Cannot add to a null destination");
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001283
1284 // Nothing to merge?
1285 if (Spills.empty()) {
Matthias Braund7df9352013-10-10 21:28:47 +00001286 LR->segments.erase(WriteI, ReadI);
1287 LR->verify();
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001288 return;
1289 }
1290
1291 // Resize the WriteI - ReadI gap to match Spills.
1292 size_t GapSize = ReadI - WriteI;
1293 if (GapSize < Spills.size()) {
1294 // The gap is too small. Make some room.
Matthias Braund7df9352013-10-10 21:28:47 +00001295 size_t WritePos = WriteI - LR->begin();
1296 LR->segments.insert(ReadI, Spills.size() - GapSize, LiveRange::Segment());
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001297 // This also invalidated ReadI, but it is recomputed below.
Matthias Braund7df9352013-10-10 21:28:47 +00001298 WriteI = LR->begin() + WritePos;
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001299 } else {
1300 // Shrink the gap if necessary.
Matthias Braund7df9352013-10-10 21:28:47 +00001301 LR->segments.erase(WriteI + Spills.size(), ReadI);
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001302 }
1303 ReadI = WriteI + Spills.size();
1304 mergeSpills();
Matthias Braund7df9352013-10-10 21:28:47 +00001305 LR->verify();
Jakob Stoklund Olesen521c7082013-02-20 18:18:12 +00001306}
1307
Matthias Braunbf47f632016-01-08 01:16:35 +00001308unsigned ConnectedVNInfoEqClasses::Classify(const LiveRange &LR) {
Jakob Stoklund Olesen05cae832010-10-08 21:19:28 +00001309 // Create initial equivalence classes.
Jakob Stoklund Olesen315b42c2011-03-17 00:23:45 +00001310 EqClass.clear();
Matthias Braunbf47f632016-01-08 01:16:35 +00001311 EqClass.grow(LR.getNumValNums());
Jakob Stoklund Olesen05cae832010-10-08 21:19:28 +00001312
Craig Topperc0196b12014-04-14 00:51:57 +00001313 const VNInfo *used = nullptr, *unused = nullptr;
Jakob Stoklund Olesendff6a6e2010-10-29 17:37:29 +00001314
Jakob Stoklund Olesen05cae832010-10-08 21:19:28 +00001315 // Determine connections.
Matthias Braunbf47f632016-01-08 01:16:35 +00001316 for (const VNInfo *VNI : LR.valnos) {
Jakob Stoklund Olesendff6a6e2010-10-29 17:37:29 +00001317 // Group all unused values into one class.
1318 if (VNI->isUnused()) {
1319 if (unused)
Jakob Stoklund Olesen315b42c2011-03-17 00:23:45 +00001320 EqClass.join(unused->id, VNI->id);
Jakob Stoklund Olesendff6a6e2010-10-29 17:37:29 +00001321 unused = VNI;
1322 continue;
1323 }
1324 used = VNI;
Jakob Stoklund Olesen0f1677e2010-10-07 23:34:34 +00001325 if (VNI->isPHIDef()) {
Jakob Stoklund Olesen315b42c2011-03-17 00:23:45 +00001326 const MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
Jakob Stoklund Olesen0f1677e2010-10-07 23:34:34 +00001327 assert(MBB && "Phi-def has no defining MBB");
1328 // Connect to values live out of predecessors.
1329 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
1330 PE = MBB->pred_end(); PI != PE; ++PI)
Matthias Braunbf47f632016-01-08 01:16:35 +00001331 if (const VNInfo *PVNI = LR.getVNInfoBefore(LIS.getMBBEndIdx(*PI)))
Jakob Stoklund Olesen315b42c2011-03-17 00:23:45 +00001332 EqClass.join(VNI->id, PVNI->id);
Jakob Stoklund Olesen0f1677e2010-10-07 23:34:34 +00001333 } else {
1334 // Normal value defined by an instruction. Check for two-addr redef.
1335 // FIXME: This could be coincidental. Should we really check for a tied
1336 // operand constraint?
Jakob Stoklund Olesen4c278f82010-12-21 00:48:17 +00001337 // Note that VNI->def may be a use slot for an early clobber def.
Matthias Braunbf47f632016-01-08 01:16:35 +00001338 if (const VNInfo *UVNI = LR.getVNInfoBefore(VNI->def))
Jakob Stoklund Olesen315b42c2011-03-17 00:23:45 +00001339 EqClass.join(VNI->id, UVNI->id);
Jakob Stoklund Olesen0f1677e2010-10-07 23:34:34 +00001340 }
1341 }
Jakob Stoklund Olesendff6a6e2010-10-29 17:37:29 +00001342
1343 // Lump all the unused values in with the last used value.
1344 if (used && unused)
Jakob Stoklund Olesen315b42c2011-03-17 00:23:45 +00001345 EqClass.join(used->id, unused->id);
Jakob Stoklund Olesendff6a6e2010-10-29 17:37:29 +00001346
Jakob Stoklund Olesen315b42c2011-03-17 00:23:45 +00001347 EqClass.compress();
1348 return EqClass.getNumClasses();
Jakob Stoklund Olesen0f1677e2010-10-07 23:34:34 +00001349}
1350
Matthias Braund3dd1352015-09-22 03:44:41 +00001351void ConnectedVNInfoEqClasses::Distribute(LiveInterval &LI, LiveInterval *LIV[],
Jakob Stoklund Olesen315b42c2011-03-17 00:23:45 +00001352 MachineRegisterInfo &MRI) {
Jakob Stoklund Olesen315b42c2011-03-17 00:23:45 +00001353 // Rewrite instructions.
1354 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LI.reg),
1355 RE = MRI.reg_end(); RI != RE;) {
Owen Anderson16c6bf42014-03-13 23:12:04 +00001356 MachineOperand &MO = *RI;
1357 MachineInstr *MI = RI->getParent();
Jakob Stoklund Olesen315b42c2011-03-17 00:23:45 +00001358 ++RI;
Yury Delendik132fc5a2018-08-21 17:48:28 +00001359 const VNInfo *VNI;
1360 if (MI->isDebugValue()) {
1361 // DBG_VALUE instructions don't have slot indexes, so get the index of
1362 // the instruction before them. The value is defined there too.
1363 SlotIndex Idx = LIS.getSlotIndexes()->getIndexBefore(*MI);
1364 VNI = LI.Query(Idx).valueOut();
1365 } else {
1366 SlotIndex Idx = LIS.getInstructionIndex(*MI);
1367 LiveQueryResult LRQ = LI.Query(Idx);
1368 VNI = MO.readsReg() ? LRQ.valueIn() : LRQ.valueDefined();
1369 }
Jakob Stoklund Olesencef9a612012-07-25 17:15:15 +00001370 // In the case of an <undef> use that isn't tied to any def, VNI will be
1371 // NULL. If the use is tied to a def, VNI will be the defined value.
Jakob Stoklund Olesen82d77e82012-05-19 05:25:50 +00001372 if (!VNI)
1373 continue;
Matthias Braund3dd1352015-09-22 03:44:41 +00001374 if (unsigned EqClass = getEqClass(VNI))
1375 MO.setReg(LIV[EqClass-1]->reg);
Jakob Stoklund Olesen315b42c2011-03-17 00:23:45 +00001376 }
1377
Matthias Braun5efe8712015-09-22 22:37:42 +00001378 // Distribute subregister liveranges.
1379 if (LI.hasSubRanges()) {
1380 unsigned NumComponents = EqClass.getNumClasses();
1381 SmallVector<unsigned, 8> VNIMapping;
1382 SmallVector<LiveInterval::SubRange*, 8> SubRanges;
1383 BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
1384 for (LiveInterval::SubRange &SR : LI.subranges()) {
1385 // Create new subranges in the split intervals and construct a mapping
1386 // for the VNInfos in the subrange.
1387 unsigned NumValNos = SR.valnos.size();
1388 VNIMapping.clear();
1389 VNIMapping.reserve(NumValNos);
1390 SubRanges.clear();
1391 SubRanges.resize(NumComponents-1, nullptr);
1392 for (unsigned I = 0; I < NumValNos; ++I) {
1393 const VNInfo &VNI = *SR.valnos[I];
Matthias Braunae81c292016-03-24 21:41:38 +00001394 unsigned ComponentNum;
1395 if (VNI.isUnused()) {
1396 ComponentNum = 0;
1397 } else {
1398 const VNInfo *MainRangeVNI = LI.getVNInfoAt(VNI.def);
1399 assert(MainRangeVNI != nullptr
1400 && "SubRange def must have corresponding main range def");
1401 ComponentNum = getEqClass(MainRangeVNI);
1402 if (ComponentNum > 0 && SubRanges[ComponentNum-1] == nullptr) {
1403 SubRanges[ComponentNum-1]
1404 = LIV[ComponentNum-1]->createSubRange(Allocator, SR.LaneMask);
1405 }
Matthias Braun5efe8712015-09-22 22:37:42 +00001406 }
Matthias Braunae81c292016-03-24 21:41:38 +00001407 VNIMapping.push_back(ComponentNum);
Matthias Braun5efe8712015-09-22 22:37:42 +00001408 }
1409 DistributeRange(SR, SubRanges.data(), VNIMapping);
Jakob Stoklund Olesen0f1677e2010-10-07 23:34:34 +00001410 }
Matthias Braun5efe8712015-09-22 22:37:42 +00001411 LI.removeEmptySubRanges();
Jakob Stoklund Olesen0f1677e2010-10-07 23:34:34 +00001412 }
Matthias Braun5efe8712015-09-22 22:37:42 +00001413
1414 // Distribute main liverange.
1415 DistributeRange(LI, LIV, EqClass);
Jakob Stoklund Olesen0f1677e2010-10-07 23:34:34 +00001416}