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