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