1 //===---------- SplitKit.cpp - Toolkit for splitting live ranges ----------===// 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 contains the SplitAnalysis class as well as mutator functions for 11 // live range splitting. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "SplitKit.h" 16 #include "llvm/ADT/Statistic.h" 17 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 18 #include "llvm/CodeGen/LiveRangeEdit.h" 19 #include "llvm/CodeGen/MachineDominators.h" 20 #include "llvm/CodeGen/MachineInstrBuilder.h" 21 #include "llvm/CodeGen/MachineLoopInfo.h" 22 #include "llvm/CodeGen/MachineRegisterInfo.h" 23 #include "llvm/CodeGen/VirtRegMap.h" 24 #include "llvm/Support/Debug.h" 25 #include "llvm/Support/raw_ostream.h" 26 #include "llvm/Target/TargetInstrInfo.h" 27 #include "llvm/Target/TargetMachine.h" 28 29 using namespace llvm; 30 31 #define DEBUG_TYPE "regalloc" 32 33 STATISTIC(NumFinished, "Number of splits finished"); 34 STATISTIC(NumSimple, "Number of splits that were simple"); 35 STATISTIC(NumCopies, "Number of copies inserted for splitting"); 36 STATISTIC(NumRemats, "Number of rematerialized defs for splitting"); 37 STATISTIC(NumRepairs, "Number of invalid live ranges repaired"); 38 39 //===----------------------------------------------------------------------===// 40 // Split Analysis 41 //===----------------------------------------------------------------------===// 42 43 SplitAnalysis::SplitAnalysis(const VirtRegMap &vrm, const LiveIntervals &lis, 44 const MachineLoopInfo &mli) 45 : MF(vrm.getMachineFunction()), VRM(vrm), LIS(lis), Loops(mli), 46 TII(*MF.getSubtarget().getInstrInfo()), CurLI(nullptr), 47 LastSplitPoint(MF.getNumBlockIDs()) {} 48 49 void SplitAnalysis::clear() { 50 UseSlots.clear(); 51 UseBlocks.clear(); 52 ThroughBlocks.clear(); 53 CurLI = nullptr; 54 DidRepairRange = false; 55 } 56 57 SlotIndex SplitAnalysis::computeLastSplitPoint(unsigned Num) { 58 const MachineBasicBlock *MBB = MF.getBlockNumbered(Num); 59 const MachineBasicBlock *LPad = MBB->getLandingPadSuccessor(); 60 std::pair<SlotIndex, SlotIndex> &LSP = LastSplitPoint[Num]; 61 SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB); 62 63 // Compute split points on the first call. The pair is independent of the 64 // current live interval. 65 if (!LSP.first.isValid()) { 66 MachineBasicBlock::const_iterator FirstTerm = MBB->getFirstTerminator(); 67 if (FirstTerm == MBB->end()) 68 LSP.first = MBBEnd; 69 else 70 LSP.first = LIS.getInstructionIndex(FirstTerm); 71 72 // If there is a landing pad successor, also find the call instruction. 73 if (!LPad) 74 return LSP.first; 75 // There may not be a call instruction (?) in which case we ignore LPad. 76 LSP.second = LSP.first; 77 for (MachineBasicBlock::const_iterator I = MBB->end(), E = MBB->begin(); 78 I != E;) { 79 --I; 80 if (I->isCall()) { 81 LSP.second = LIS.getInstructionIndex(I); 82 break; 83 } 84 } 85 } 86 87 // If CurLI is live into a landing pad successor, move the last split point 88 // back to the call that may throw. 89 if (!LPad || !LSP.second || !LIS.isLiveInToMBB(*CurLI, LPad)) 90 return LSP.first; 91 92 // Find the value leaving MBB. 93 const VNInfo *VNI = CurLI->getVNInfoBefore(MBBEnd); 94 if (!VNI) 95 return LSP.first; 96 97 // If the value leaving MBB was defined after the call in MBB, it can't 98 // really be live-in to the landing pad. This can happen if the landing pad 99 // has a PHI, and this register is undef on the exceptional edge. 100 // <rdar://problem/10664933> 101 if (!SlotIndex::isEarlierInstr(VNI->def, LSP.second) && VNI->def < MBBEnd) 102 return LSP.first; 103 104 // Value is properly live-in to the landing pad. 105 // Only allow splits before the call. 106 return LSP.second; 107 } 108 109 MachineBasicBlock::iterator 110 SplitAnalysis::getLastSplitPointIter(MachineBasicBlock *MBB) { 111 SlotIndex LSP = getLastSplitPoint(MBB->getNumber()); 112 if (LSP == LIS.getMBBEndIdx(MBB)) 113 return MBB->end(); 114 return LIS.getInstructionFromIndex(LSP); 115 } 116 117 /// analyzeUses - Count instructions, basic blocks, and loops using CurLI. 118 void SplitAnalysis::analyzeUses() { 119 assert(UseSlots.empty() && "Call clear first"); 120 121 // First get all the defs from the interval values. This provides the correct 122 // slots for early clobbers. 123 for (const VNInfo *VNI : CurLI->valnos) 124 if (!VNI->isPHIDef() && !VNI->isUnused()) 125 UseSlots.push_back(VNI->def); 126 127 // Get use slots form the use-def chain. 128 const MachineRegisterInfo &MRI = MF.getRegInfo(); 129 for (MachineOperand &MO : MRI.use_nodbg_operands(CurLI->reg)) 130 if (!MO.isUndef()) 131 UseSlots.push_back(LIS.getInstructionIndex(MO.getParent()).getRegSlot()); 132 133 array_pod_sort(UseSlots.begin(), UseSlots.end()); 134 135 // Remove duplicates, keeping the smaller slot for each instruction. 136 // That is what we want for early clobbers. 137 UseSlots.erase(std::unique(UseSlots.begin(), UseSlots.end(), 138 SlotIndex::isSameInstr), 139 UseSlots.end()); 140 141 // Compute per-live block info. 142 if (!calcLiveBlockInfo()) { 143 // FIXME: calcLiveBlockInfo found inconsistencies in the live range. 144 // I am looking at you, RegisterCoalescer! 145 DidRepairRange = true; 146 ++NumRepairs; 147 DEBUG(dbgs() << "*** Fixing inconsistent live interval! ***\n"); 148 const_cast<LiveIntervals&>(LIS) 149 .shrinkToUses(const_cast<LiveInterval*>(CurLI)); 150 UseBlocks.clear(); 151 ThroughBlocks.clear(); 152 bool fixed = calcLiveBlockInfo(); 153 (void)fixed; 154 assert(fixed && "Couldn't fix broken live interval"); 155 } 156 157 DEBUG(dbgs() << "Analyze counted " 158 << UseSlots.size() << " instrs in " 159 << UseBlocks.size() << " blocks, through " 160 << NumThroughBlocks << " blocks.\n"); 161 } 162 163 /// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks 164 /// where CurLI is live. 165 bool SplitAnalysis::calcLiveBlockInfo() { 166 ThroughBlocks.resize(MF.getNumBlockIDs()); 167 NumThroughBlocks = NumGapBlocks = 0; 168 if (CurLI->empty()) 169 return true; 170 171 LiveInterval::const_iterator LVI = CurLI->begin(); 172 LiveInterval::const_iterator LVE = CurLI->end(); 173 174 SmallVectorImpl<SlotIndex>::const_iterator UseI, UseE; 175 UseI = UseSlots.begin(); 176 UseE = UseSlots.end(); 177 178 // Loop over basic blocks where CurLI is live. 179 MachineFunction::iterator MFI = LIS.getMBBFromIndex(LVI->start); 180 for (;;) { 181 BlockInfo BI; 182 BI.MBB = MFI; 183 SlotIndex Start, Stop; 184 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB); 185 186 // If the block contains no uses, the range must be live through. At one 187 // point, RegisterCoalescer could create dangling ranges that ended 188 // mid-block. 189 if (UseI == UseE || *UseI >= Stop) { 190 ++NumThroughBlocks; 191 ThroughBlocks.set(BI.MBB->getNumber()); 192 // The range shouldn't end mid-block if there are no uses. This shouldn't 193 // happen. 194 if (LVI->end < Stop) 195 return false; 196 } else { 197 // This block has uses. Find the first and last uses in the block. 198 BI.FirstInstr = *UseI; 199 assert(BI.FirstInstr >= Start); 200 do ++UseI; 201 while (UseI != UseE && *UseI < Stop); 202 BI.LastInstr = UseI[-1]; 203 assert(BI.LastInstr < Stop); 204 205 // LVI is the first live segment overlapping MBB. 206 BI.LiveIn = LVI->start <= Start; 207 208 // When not live in, the first use should be a def. 209 if (!BI.LiveIn) { 210 assert(LVI->start == LVI->valno->def && "Dangling Segment start"); 211 assert(LVI->start == BI.FirstInstr && "First instr should be a def"); 212 BI.FirstDef = BI.FirstInstr; 213 } 214 215 // Look for gaps in the live range. 216 BI.LiveOut = true; 217 while (LVI->end < Stop) { 218 SlotIndex LastStop = LVI->end; 219 if (++LVI == LVE || LVI->start >= Stop) { 220 BI.LiveOut = false; 221 BI.LastInstr = LastStop; 222 break; 223 } 224 225 if (LastStop < LVI->start) { 226 // There is a gap in the live range. Create duplicate entries for the 227 // live-in snippet and the live-out snippet. 228 ++NumGapBlocks; 229 230 // Push the Live-in part. 231 BI.LiveOut = false; 232 UseBlocks.push_back(BI); 233 UseBlocks.back().LastInstr = LastStop; 234 235 // Set up BI for the live-out part. 236 BI.LiveIn = false; 237 BI.LiveOut = true; 238 BI.FirstInstr = BI.FirstDef = LVI->start; 239 } 240 241 // A Segment that starts in the middle of the block must be a def. 242 assert(LVI->start == LVI->valno->def && "Dangling Segment start"); 243 if (!BI.FirstDef) 244 BI.FirstDef = LVI->start; 245 } 246 247 UseBlocks.push_back(BI); 248 249 // LVI is now at LVE or LVI->end >= Stop. 250 if (LVI == LVE) 251 break; 252 } 253 254 // Live segment ends exactly at Stop. Move to the next segment. 255 if (LVI->end == Stop && ++LVI == LVE) 256 break; 257 258 // Pick the next basic block. 259 if (LVI->start < Stop) 260 ++MFI; 261 else 262 MFI = LIS.getMBBFromIndex(LVI->start); 263 } 264 265 assert(getNumLiveBlocks() == countLiveBlocks(CurLI) && "Bad block count"); 266 return true; 267 } 268 269 unsigned SplitAnalysis::countLiveBlocks(const LiveInterval *cli) const { 270 if (cli->empty()) 271 return 0; 272 LiveInterval *li = const_cast<LiveInterval*>(cli); 273 LiveInterval::iterator LVI = li->begin(); 274 LiveInterval::iterator LVE = li->end(); 275 unsigned Count = 0; 276 277 // Loop over basic blocks where li is live. 278 MachineFunction::const_iterator MFI = LIS.getMBBFromIndex(LVI->start); 279 SlotIndex Stop = LIS.getMBBEndIdx(MFI); 280 for (;;) { 281 ++Count; 282 LVI = li->advanceTo(LVI, Stop); 283 if (LVI == LVE) 284 return Count; 285 do { 286 ++MFI; 287 Stop = LIS.getMBBEndIdx(MFI); 288 } while (Stop <= LVI->start); 289 } 290 } 291 292 bool SplitAnalysis::isOriginalEndpoint(SlotIndex Idx) const { 293 unsigned OrigReg = VRM.getOriginal(CurLI->reg); 294 const LiveInterval &Orig = LIS.getInterval(OrigReg); 295 assert(!Orig.empty() && "Splitting empty interval?"); 296 LiveInterval::const_iterator I = Orig.find(Idx); 297 298 // Range containing Idx should begin at Idx. 299 if (I != Orig.end() && I->start <= Idx) 300 return I->start == Idx; 301 302 // Range does not contain Idx, previous must end at Idx. 303 return I != Orig.begin() && (--I)->end == Idx; 304 } 305 306 void SplitAnalysis::analyze(const LiveInterval *li) { 307 clear(); 308 CurLI = li; 309 analyzeUses(); 310 } 311 312 313 //===----------------------------------------------------------------------===// 314 // Split Editor 315 //===----------------------------------------------------------------------===// 316 317 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA. 318 SplitEditor::SplitEditor(SplitAnalysis &sa, LiveIntervals &lis, VirtRegMap &vrm, 319 MachineDominatorTree &mdt, 320 MachineBlockFrequencyInfo &mbfi) 321 : SA(sa), LIS(lis), VRM(vrm), MRI(vrm.getMachineFunction().getRegInfo()), 322 MDT(mdt), TII(*vrm.getMachineFunction().getSubtarget().getInstrInfo()), 323 TRI(*vrm.getMachineFunction().getSubtarget().getRegisterInfo()), 324 MBFI(mbfi), Edit(nullptr), OpenIdx(0), SpillMode(SM_Partition), 325 RegAssign(Allocator) {} 326 327 void SplitEditor::reset(LiveRangeEdit &LRE, ComplementSpillMode SM) { 328 Edit = &LRE; 329 SpillMode = SM; 330 OpenIdx = 0; 331 RegAssign.clear(); 332 Values.clear(); 333 334 // Reset the LiveRangeCalc instances needed for this spill mode. 335 LRCalc[0].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT, 336 &LIS.getVNInfoAllocator()); 337 if (SpillMode) 338 LRCalc[1].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT, 339 &LIS.getVNInfoAllocator()); 340 341 // We don't need an AliasAnalysis since we will only be performing 342 // cheap-as-a-copy remats anyway. 343 Edit->anyRematerializable(nullptr); 344 } 345 346 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 347 void SplitEditor::dump() const { 348 if (RegAssign.empty()) { 349 dbgs() << " empty\n"; 350 return; 351 } 352 353 for (RegAssignMap::const_iterator I = RegAssign.begin(); I.valid(); ++I) 354 dbgs() << " [" << I.start() << ';' << I.stop() << "):" << I.value(); 355 dbgs() << '\n'; 356 } 357 #endif 358 359 VNInfo *SplitEditor::defValue(unsigned RegIdx, 360 const VNInfo *ParentVNI, 361 SlotIndex Idx) { 362 assert(ParentVNI && "Mapping NULL value"); 363 assert(Idx.isValid() && "Invalid SlotIndex"); 364 assert(Edit->getParent().getVNInfoAt(Idx) == ParentVNI && "Bad Parent VNI"); 365 LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx)); 366 367 // Create a new value. 368 VNInfo *VNI = LI->getNextValue(Idx, LIS.getVNInfoAllocator()); 369 370 // Use insert for lookup, so we can add missing values with a second lookup. 371 std::pair<ValueMap::iterator, bool> InsP = 372 Values.insert(std::make_pair(std::make_pair(RegIdx, ParentVNI->id), 373 ValueForcePair(VNI, false))); 374 375 // This was the first time (RegIdx, ParentVNI) was mapped. 376 // Keep it as a simple def without any liveness. 377 if (InsP.second) 378 return VNI; 379 380 // If the previous value was a simple mapping, add liveness for it now. 381 if (VNInfo *OldVNI = InsP.first->second.getPointer()) { 382 SlotIndex Def = OldVNI->def; 383 LI->addSegment(LiveInterval::Segment(Def, Def.getDeadSlot(), OldVNI)); 384 // No longer a simple mapping. Switch to a complex, non-forced mapping. 385 InsP.first->second = ValueForcePair(); 386 } 387 388 // This is a complex mapping, add liveness for VNI 389 SlotIndex Def = VNI->def; 390 LI->addSegment(LiveInterval::Segment(Def, Def.getDeadSlot(), VNI)); 391 392 return VNI; 393 } 394 395 void SplitEditor::forceRecompute(unsigned RegIdx, const VNInfo *ParentVNI) { 396 assert(ParentVNI && "Mapping NULL value"); 397 ValueForcePair &VFP = Values[std::make_pair(RegIdx, ParentVNI->id)]; 398 VNInfo *VNI = VFP.getPointer(); 399 400 // ParentVNI was either unmapped or already complex mapped. Either way, just 401 // set the force bit. 402 if (!VNI) { 403 VFP.setInt(true); 404 return; 405 } 406 407 // This was previously a single mapping. Make sure the old def is represented 408 // by a trivial live range. 409 SlotIndex Def = VNI->def; 410 LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx)); 411 LI->addSegment(LiveInterval::Segment(Def, Def.getDeadSlot(), VNI)); 412 // Mark as complex mapped, forced. 413 VFP = ValueForcePair(nullptr, true); 414 } 415 416 VNInfo *SplitEditor::defFromParent(unsigned RegIdx, 417 VNInfo *ParentVNI, 418 SlotIndex UseIdx, 419 MachineBasicBlock &MBB, 420 MachineBasicBlock::iterator I) { 421 MachineInstr *CopyMI = nullptr; 422 SlotIndex Def; 423 LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx)); 424 425 // We may be trying to avoid interference that ends at a deleted instruction, 426 // so always begin RegIdx 0 early and all others late. 427 bool Late = RegIdx != 0; 428 429 // Attempt cheap-as-a-copy rematerialization. 430 LiveRangeEdit::Remat RM(ParentVNI); 431 if (Edit->canRematerializeAt(RM, UseIdx, true)) { 432 Def = Edit->rematerializeAt(MBB, I, LI->reg, RM, TRI, Late); 433 ++NumRemats; 434 } else { 435 // Can't remat, just insert a copy from parent. 436 CopyMI = BuildMI(MBB, I, DebugLoc(), TII.get(TargetOpcode::COPY), LI->reg) 437 .addReg(Edit->getReg()); 438 Def = LIS.getSlotIndexes()->insertMachineInstrInMaps(CopyMI, Late) 439 .getRegSlot(); 440 ++NumCopies; 441 } 442 443 // Define the value in Reg. 444 return defValue(RegIdx, ParentVNI, Def); 445 } 446 447 /// Create a new virtual register and live interval. 448 unsigned SplitEditor::openIntv() { 449 // Create the complement as index 0. 450 if (Edit->empty()) 451 Edit->createEmptyInterval(); 452 453 // Create the open interval. 454 OpenIdx = Edit->size(); 455 Edit->createEmptyInterval(); 456 return OpenIdx; 457 } 458 459 void SplitEditor::selectIntv(unsigned Idx) { 460 assert(Idx != 0 && "Cannot select the complement interval"); 461 assert(Idx < Edit->size() && "Can only select previously opened interval"); 462 DEBUG(dbgs() << " selectIntv " << OpenIdx << " -> " << Idx << '\n'); 463 OpenIdx = Idx; 464 } 465 466 SlotIndex SplitEditor::enterIntvBefore(SlotIndex Idx) { 467 assert(OpenIdx && "openIntv not called before enterIntvBefore"); 468 DEBUG(dbgs() << " enterIntvBefore " << Idx); 469 Idx = Idx.getBaseIndex(); 470 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx); 471 if (!ParentVNI) { 472 DEBUG(dbgs() << ": not live\n"); 473 return Idx; 474 } 475 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 476 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 477 assert(MI && "enterIntvBefore called with invalid index"); 478 479 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), MI); 480 return VNI->def; 481 } 482 483 SlotIndex SplitEditor::enterIntvAfter(SlotIndex Idx) { 484 assert(OpenIdx && "openIntv not called before enterIntvAfter"); 485 DEBUG(dbgs() << " enterIntvAfter " << Idx); 486 Idx = Idx.getBoundaryIndex(); 487 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx); 488 if (!ParentVNI) { 489 DEBUG(dbgs() << ": not live\n"); 490 return Idx; 491 } 492 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 493 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 494 assert(MI && "enterIntvAfter called with invalid index"); 495 496 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), 497 std::next(MachineBasicBlock::iterator(MI))); 498 return VNI->def; 499 } 500 501 SlotIndex SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) { 502 assert(OpenIdx && "openIntv not called before enterIntvAtEnd"); 503 SlotIndex End = LIS.getMBBEndIdx(&MBB); 504 SlotIndex Last = End.getPrevSlot(); 505 DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << Last); 506 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Last); 507 if (!ParentVNI) { 508 DEBUG(dbgs() << ": not live\n"); 509 return End; 510 } 511 DEBUG(dbgs() << ": valno " << ParentVNI->id); 512 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Last, MBB, 513 SA.getLastSplitPointIter(&MBB)); 514 RegAssign.insert(VNI->def, End, OpenIdx); 515 DEBUG(dump()); 516 return VNI->def; 517 } 518 519 /// useIntv - indicate that all instructions in MBB should use OpenLI. 520 void SplitEditor::useIntv(const MachineBasicBlock &MBB) { 521 useIntv(LIS.getMBBStartIdx(&MBB), LIS.getMBBEndIdx(&MBB)); 522 } 523 524 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) { 525 assert(OpenIdx && "openIntv not called before useIntv"); 526 DEBUG(dbgs() << " useIntv [" << Start << ';' << End << "):"); 527 RegAssign.insert(Start, End, OpenIdx); 528 DEBUG(dump()); 529 } 530 531 SlotIndex SplitEditor::leaveIntvAfter(SlotIndex Idx) { 532 assert(OpenIdx && "openIntv not called before leaveIntvAfter"); 533 DEBUG(dbgs() << " leaveIntvAfter " << Idx); 534 535 // The interval must be live beyond the instruction at Idx. 536 SlotIndex Boundary = Idx.getBoundaryIndex(); 537 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Boundary); 538 if (!ParentVNI) { 539 DEBUG(dbgs() << ": not live\n"); 540 return Boundary.getNextSlot(); 541 } 542 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 543 MachineInstr *MI = LIS.getInstructionFromIndex(Boundary); 544 assert(MI && "No instruction at index"); 545 546 // In spill mode, make live ranges as short as possible by inserting the copy 547 // before MI. This is only possible if that instruction doesn't redefine the 548 // value. The inserted COPY is not a kill, and we don't need to recompute 549 // the source live range. The spiller also won't try to hoist this copy. 550 if (SpillMode && !SlotIndex::isSameInstr(ParentVNI->def, Idx) && 551 MI->readsVirtualRegister(Edit->getReg())) { 552 forceRecompute(0, ParentVNI); 553 defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI); 554 return Idx; 555 } 556 557 VNInfo *VNI = defFromParent(0, ParentVNI, Boundary, *MI->getParent(), 558 std::next(MachineBasicBlock::iterator(MI))); 559 return VNI->def; 560 } 561 562 SlotIndex SplitEditor::leaveIntvBefore(SlotIndex Idx) { 563 assert(OpenIdx && "openIntv not called before leaveIntvBefore"); 564 DEBUG(dbgs() << " leaveIntvBefore " << Idx); 565 566 // The interval must be live into the instruction at Idx. 567 Idx = Idx.getBaseIndex(); 568 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx); 569 if (!ParentVNI) { 570 DEBUG(dbgs() << ": not live\n"); 571 return Idx.getNextSlot(); 572 } 573 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 574 575 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 576 assert(MI && "No instruction at index"); 577 VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI); 578 return VNI->def; 579 } 580 581 SlotIndex SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) { 582 assert(OpenIdx && "openIntv not called before leaveIntvAtTop"); 583 SlotIndex Start = LIS.getMBBStartIdx(&MBB); 584 DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start); 585 586 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start); 587 if (!ParentVNI) { 588 DEBUG(dbgs() << ": not live\n"); 589 return Start; 590 } 591 592 VNInfo *VNI = defFromParent(0, ParentVNI, Start, MBB, 593 MBB.SkipPHIsAndLabels(MBB.begin())); 594 RegAssign.insert(Start, VNI->def, OpenIdx); 595 DEBUG(dump()); 596 return VNI->def; 597 } 598 599 void SplitEditor::overlapIntv(SlotIndex Start, SlotIndex End) { 600 assert(OpenIdx && "openIntv not called before overlapIntv"); 601 const VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start); 602 assert(ParentVNI == Edit->getParent().getVNInfoBefore(End) && 603 "Parent changes value in extended range"); 604 assert(LIS.getMBBFromIndex(Start) == LIS.getMBBFromIndex(End) && 605 "Range cannot span basic blocks"); 606 607 // The complement interval will be extended as needed by LRCalc.extend(). 608 if (ParentVNI) 609 forceRecompute(0, ParentVNI); 610 DEBUG(dbgs() << " overlapIntv [" << Start << ';' << End << "):"); 611 RegAssign.insert(Start, End, OpenIdx); 612 DEBUG(dump()); 613 } 614 615 //===----------------------------------------------------------------------===// 616 // Spill modes 617 //===----------------------------------------------------------------------===// 618 619 void SplitEditor::removeBackCopies(SmallVectorImpl<VNInfo*> &Copies) { 620 LiveInterval *LI = &LIS.getInterval(Edit->get(0)); 621 DEBUG(dbgs() << "Removing " << Copies.size() << " back-copies.\n"); 622 RegAssignMap::iterator AssignI; 623 AssignI.setMap(RegAssign); 624 625 for (unsigned i = 0, e = Copies.size(); i != e; ++i) { 626 VNInfo *VNI = Copies[i]; 627 SlotIndex Def = VNI->def; 628 MachineInstr *MI = LIS.getInstructionFromIndex(Def); 629 assert(MI && "No instruction for back-copy"); 630 631 MachineBasicBlock *MBB = MI->getParent(); 632 MachineBasicBlock::iterator MBBI(MI); 633 bool AtBegin; 634 do AtBegin = MBBI == MBB->begin(); 635 while (!AtBegin && (--MBBI)->isDebugValue()); 636 637 DEBUG(dbgs() << "Removing " << Def << '\t' << *MI); 638 LI->removeValNo(VNI); 639 LIS.RemoveMachineInstrFromMaps(MI); 640 MI->eraseFromParent(); 641 642 // Adjust RegAssign if a register assignment is killed at VNI->def. We 643 // want to avoid calculating the live range of the source register if 644 // possible. 645 AssignI.find(Def.getPrevSlot()); 646 if (!AssignI.valid() || AssignI.start() >= Def) 647 continue; 648 // If MI doesn't kill the assigned register, just leave it. 649 if (AssignI.stop() != Def) 650 continue; 651 unsigned RegIdx = AssignI.value(); 652 if (AtBegin || !MBBI->readsVirtualRegister(Edit->getReg())) { 653 DEBUG(dbgs() << " cannot find simple kill of RegIdx " << RegIdx << '\n'); 654 forceRecompute(RegIdx, Edit->getParent().getVNInfoAt(Def)); 655 } else { 656 SlotIndex Kill = LIS.getInstructionIndex(MBBI).getRegSlot(); 657 DEBUG(dbgs() << " move kill to " << Kill << '\t' << *MBBI); 658 AssignI.setStop(Kill); 659 } 660 } 661 } 662 663 MachineBasicBlock* 664 SplitEditor::findShallowDominator(MachineBasicBlock *MBB, 665 MachineBasicBlock *DefMBB) { 666 if (MBB == DefMBB) 667 return MBB; 668 assert(MDT.dominates(DefMBB, MBB) && "MBB must be dominated by the def."); 669 670 const MachineLoopInfo &Loops = SA.Loops; 671 const MachineLoop *DefLoop = Loops.getLoopFor(DefMBB); 672 MachineDomTreeNode *DefDomNode = MDT[DefMBB]; 673 674 // Best candidate so far. 675 MachineBasicBlock *BestMBB = MBB; 676 unsigned BestDepth = UINT_MAX; 677 678 for (;;) { 679 const MachineLoop *Loop = Loops.getLoopFor(MBB); 680 681 // MBB isn't in a loop, it doesn't get any better. All dominators have a 682 // higher frequency by definition. 683 if (!Loop) { 684 DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#" 685 << MBB->getNumber() << " at depth 0\n"); 686 return MBB; 687 } 688 689 // We'll never be able to exit the DefLoop. 690 if (Loop == DefLoop) { 691 DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#" 692 << MBB->getNumber() << " in the same loop\n"); 693 return MBB; 694 } 695 696 // Least busy dominator seen so far. 697 unsigned Depth = Loop->getLoopDepth(); 698 if (Depth < BestDepth) { 699 BestMBB = MBB; 700 BestDepth = Depth; 701 DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#" 702 << MBB->getNumber() << " at depth " << Depth << '\n'); 703 } 704 705 // Leave loop by going to the immediate dominator of the loop header. 706 // This is a bigger stride than simply walking up the dominator tree. 707 MachineDomTreeNode *IDom = MDT[Loop->getHeader()]->getIDom(); 708 709 // Too far up the dominator tree? 710 if (!IDom || !MDT.dominates(DefDomNode, IDom)) 711 return BestMBB; 712 713 MBB = IDom->getBlock(); 714 } 715 } 716 717 void SplitEditor::hoistCopiesForSize() { 718 // Get the complement interval, always RegIdx 0. 719 LiveInterval *LI = &LIS.getInterval(Edit->get(0)); 720 LiveInterval *Parent = &Edit->getParent(); 721 722 // Track the nearest common dominator for all back-copies for each ParentVNI, 723 // indexed by ParentVNI->id. 724 typedef std::pair<MachineBasicBlock*, SlotIndex> DomPair; 725 SmallVector<DomPair, 8> NearestDom(Parent->getNumValNums()); 726 727 // Find the nearest common dominator for parent values with multiple 728 // back-copies. If a single back-copy dominates, put it in DomPair.second. 729 for (VNInfo *VNI : LI->valnos) { 730 if (VNI->isUnused()) 731 continue; 732 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def); 733 assert(ParentVNI && "Parent not live at complement def"); 734 735 // Don't hoist remats. The complement is probably going to disappear 736 // completely anyway. 737 if (Edit->didRematerialize(ParentVNI)) 738 continue; 739 740 MachineBasicBlock *ValMBB = LIS.getMBBFromIndex(VNI->def); 741 DomPair &Dom = NearestDom[ParentVNI->id]; 742 743 // Keep directly defined parent values. This is either a PHI or an 744 // instruction in the complement range. All other copies of ParentVNI 745 // should be eliminated. 746 if (VNI->def == ParentVNI->def) { 747 DEBUG(dbgs() << "Direct complement def at " << VNI->def << '\n'); 748 Dom = DomPair(ValMBB, VNI->def); 749 continue; 750 } 751 // Skip the singly mapped values. There is nothing to gain from hoisting a 752 // single back-copy. 753 if (Values.lookup(std::make_pair(0, ParentVNI->id)).getPointer()) { 754 DEBUG(dbgs() << "Single complement def at " << VNI->def << '\n'); 755 continue; 756 } 757 758 if (!Dom.first) { 759 // First time we see ParentVNI. VNI dominates itself. 760 Dom = DomPair(ValMBB, VNI->def); 761 } else if (Dom.first == ValMBB) { 762 // Two defs in the same block. Pick the earlier def. 763 if (!Dom.second.isValid() || VNI->def < Dom.second) 764 Dom.second = VNI->def; 765 } else { 766 // Different basic blocks. Check if one dominates. 767 MachineBasicBlock *Near = 768 MDT.findNearestCommonDominator(Dom.first, ValMBB); 769 if (Near == ValMBB) 770 // Def ValMBB dominates. 771 Dom = DomPair(ValMBB, VNI->def); 772 else if (Near != Dom.first) 773 // None dominate. Hoist to common dominator, need new def. 774 Dom = DomPair(Near, SlotIndex()); 775 } 776 777 DEBUG(dbgs() << "Multi-mapped complement " << VNI->id << '@' << VNI->def 778 << " for parent " << ParentVNI->id << '@' << ParentVNI->def 779 << " hoist to BB#" << Dom.first->getNumber() << ' ' 780 << Dom.second << '\n'); 781 } 782 783 // Insert the hoisted copies. 784 for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) { 785 DomPair &Dom = NearestDom[i]; 786 if (!Dom.first || Dom.second.isValid()) 787 continue; 788 // This value needs a hoisted copy inserted at the end of Dom.first. 789 VNInfo *ParentVNI = Parent->getValNumInfo(i); 790 MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(ParentVNI->def); 791 // Get a less loopy dominator than Dom.first. 792 Dom.first = findShallowDominator(Dom.first, DefMBB); 793 SlotIndex Last = LIS.getMBBEndIdx(Dom.first).getPrevSlot(); 794 Dom.second = 795 defFromParent(0, ParentVNI, Last, *Dom.first, 796 SA.getLastSplitPointIter(Dom.first))->def; 797 } 798 799 // Remove redundant back-copies that are now known to be dominated by another 800 // def with the same value. 801 SmallVector<VNInfo*, 8> BackCopies; 802 for (VNInfo *VNI : LI->valnos) { 803 if (VNI->isUnused()) 804 continue; 805 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def); 806 const DomPair &Dom = NearestDom[ParentVNI->id]; 807 if (!Dom.first || Dom.second == VNI->def) 808 continue; 809 BackCopies.push_back(VNI); 810 forceRecompute(0, ParentVNI); 811 } 812 removeBackCopies(BackCopies); 813 } 814 815 816 /// transferValues - Transfer all possible values to the new live ranges. 817 /// Values that were rematerialized are left alone, they need LRCalc.extend(). 818 bool SplitEditor::transferValues() { 819 bool Skipped = false; 820 RegAssignMap::const_iterator AssignI = RegAssign.begin(); 821 for (const LiveRange::Segment &S : Edit->getParent()) { 822 DEBUG(dbgs() << " blit " << S << ':'); 823 VNInfo *ParentVNI = S.valno; 824 // RegAssign has holes where RegIdx 0 should be used. 825 SlotIndex Start = S.start; 826 AssignI.advanceTo(Start); 827 do { 828 unsigned RegIdx; 829 SlotIndex End = S.end; 830 if (!AssignI.valid()) { 831 RegIdx = 0; 832 } else if (AssignI.start() <= Start) { 833 RegIdx = AssignI.value(); 834 if (AssignI.stop() < End) { 835 End = AssignI.stop(); 836 ++AssignI; 837 } 838 } else { 839 RegIdx = 0; 840 End = std::min(End, AssignI.start()); 841 } 842 843 // The interval [Start;End) is continuously mapped to RegIdx, ParentVNI. 844 DEBUG(dbgs() << " [" << Start << ';' << End << ")=" << RegIdx); 845 LiveRange &LR = LIS.getInterval(Edit->get(RegIdx)); 846 847 // Check for a simply defined value that can be blitted directly. 848 ValueForcePair VFP = Values.lookup(std::make_pair(RegIdx, ParentVNI->id)); 849 if (VNInfo *VNI = VFP.getPointer()) { 850 DEBUG(dbgs() << ':' << VNI->id); 851 LR.addSegment(LiveInterval::Segment(Start, End, VNI)); 852 Start = End; 853 continue; 854 } 855 856 // Skip values with forced recomputation. 857 if (VFP.getInt()) { 858 DEBUG(dbgs() << "(recalc)"); 859 Skipped = true; 860 Start = End; 861 continue; 862 } 863 864 LiveRangeCalc &LRC = getLRCalc(RegIdx); 865 866 // This value has multiple defs in RegIdx, but it wasn't rematerialized, 867 // so the live range is accurate. Add live-in blocks in [Start;End) to the 868 // LiveInBlocks. 869 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start); 870 SlotIndex BlockStart, BlockEnd; 871 std::tie(BlockStart, BlockEnd) = LIS.getSlotIndexes()->getMBBRange(MBB); 872 873 // The first block may be live-in, or it may have its own def. 874 if (Start != BlockStart) { 875 VNInfo *VNI = LR.extendInBlock(BlockStart, std::min(BlockEnd, End)); 876 assert(VNI && "Missing def for complex mapped value"); 877 DEBUG(dbgs() << ':' << VNI->id << "*BB#" << MBB->getNumber()); 878 // MBB has its own def. Is it also live-out? 879 if (BlockEnd <= End) 880 LRC.setLiveOutValue(MBB, VNI); 881 882 // Skip to the next block for live-in. 883 ++MBB; 884 BlockStart = BlockEnd; 885 } 886 887 // Handle the live-in blocks covered by [Start;End). 888 assert(Start <= BlockStart && "Expected live-in block"); 889 while (BlockStart < End) { 890 DEBUG(dbgs() << ">BB#" << MBB->getNumber()); 891 BlockEnd = LIS.getMBBEndIdx(MBB); 892 if (BlockStart == ParentVNI->def) { 893 // This block has the def of a parent PHI, so it isn't live-in. 894 assert(ParentVNI->isPHIDef() && "Non-phi defined at block start?"); 895 VNInfo *VNI = LR.extendInBlock(BlockStart, std::min(BlockEnd, End)); 896 assert(VNI && "Missing def for complex mapped parent PHI"); 897 if (End >= BlockEnd) 898 LRC.setLiveOutValue(MBB, VNI); // Live-out as well. 899 } else { 900 // This block needs a live-in value. The last block covered may not 901 // be live-out. 902 if (End < BlockEnd) 903 LRC.addLiveInBlock(LR, MDT[MBB], End); 904 else { 905 // Live-through, and we don't know the value. 906 LRC.addLiveInBlock(LR, MDT[MBB]); 907 LRC.setLiveOutValue(MBB, nullptr); 908 } 909 } 910 BlockStart = BlockEnd; 911 ++MBB; 912 } 913 Start = End; 914 } while (Start != S.end); 915 DEBUG(dbgs() << '\n'); 916 } 917 918 LRCalc[0].calculateValues(); 919 if (SpillMode) 920 LRCalc[1].calculateValues(); 921 922 return Skipped; 923 } 924 925 void SplitEditor::extendPHIKillRanges() { 926 // Extend live ranges to be live-out for successor PHI values. 927 for (const VNInfo *PHIVNI : Edit->getParent().valnos) { 928 if (PHIVNI->isUnused() || !PHIVNI->isPHIDef()) 929 continue; 930 unsigned RegIdx = RegAssign.lookup(PHIVNI->def); 931 LiveRange &LR = LIS.getInterval(Edit->get(RegIdx)); 932 LiveRangeCalc &LRC = getLRCalc(RegIdx); 933 MachineBasicBlock *MBB = LIS.getMBBFromIndex(PHIVNI->def); 934 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), 935 PE = MBB->pred_end(); PI != PE; ++PI) { 936 SlotIndex End = LIS.getMBBEndIdx(*PI); 937 SlotIndex LastUse = End.getPrevSlot(); 938 // The predecessor may not have a live-out value. That is OK, like an 939 // undef PHI operand. 940 if (Edit->getParent().liveAt(LastUse)) { 941 assert(RegAssign.lookup(LastUse) == RegIdx && 942 "Different register assignment in phi predecessor"); 943 LRC.extend(LR, End); 944 } 945 } 946 } 947 } 948 949 /// rewriteAssigned - Rewrite all uses of Edit->getReg(). 950 void SplitEditor::rewriteAssigned(bool ExtendRanges) { 951 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit->getReg()), 952 RE = MRI.reg_end(); RI != RE;) { 953 MachineOperand &MO = *RI; 954 MachineInstr *MI = MO.getParent(); 955 ++RI; 956 // LiveDebugVariables should have handled all DBG_VALUE instructions. 957 if (MI->isDebugValue()) { 958 DEBUG(dbgs() << "Zapping " << *MI); 959 MO.setReg(0); 960 continue; 961 } 962 963 // <undef> operands don't really read the register, so it doesn't matter 964 // which register we choose. When the use operand is tied to a def, we must 965 // use the same register as the def, so just do that always. 966 SlotIndex Idx = LIS.getInstructionIndex(MI); 967 if (MO.isDef() || MO.isUndef()) 968 Idx = Idx.getRegSlot(MO.isEarlyClobber()); 969 970 // Rewrite to the mapped register at Idx. 971 unsigned RegIdx = RegAssign.lookup(Idx); 972 LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx)); 973 MO.setReg(LI->reg); 974 DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t' 975 << Idx << ':' << RegIdx << '\t' << *MI); 976 977 // Extend liveness to Idx if the instruction reads reg. 978 if (!ExtendRanges || MO.isUndef()) 979 continue; 980 981 // Skip instructions that don't read Reg. 982 if (MO.isDef()) { 983 if (!MO.getSubReg() && !MO.isEarlyClobber()) 984 continue; 985 // We may wan't to extend a live range for a partial redef, or for a use 986 // tied to an early clobber. 987 Idx = Idx.getPrevSlot(); 988 if (!Edit->getParent().liveAt(Idx)) 989 continue; 990 } else 991 Idx = Idx.getRegSlot(true); 992 993 getLRCalc(RegIdx).extend(*LI, Idx.getNextSlot()); 994 } 995 } 996 997 void SplitEditor::deleteRematVictims() { 998 SmallVector<MachineInstr*, 8> Dead; 999 for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I){ 1000 LiveInterval *LI = &LIS.getInterval(*I); 1001 for (const LiveRange::Segment &S : LI->segments) { 1002 // Dead defs end at the dead slot. 1003 if (S.end != S.valno->def.getDeadSlot()) 1004 continue; 1005 MachineInstr *MI = LIS.getInstructionFromIndex(S.valno->def); 1006 assert(MI && "Missing instruction for dead def"); 1007 MI->addRegisterDead(LI->reg, &TRI); 1008 1009 if (!MI->allDefsAreDead()) 1010 continue; 1011 1012 DEBUG(dbgs() << "All defs dead: " << *MI); 1013 Dead.push_back(MI); 1014 } 1015 } 1016 1017 if (Dead.empty()) 1018 return; 1019 1020 Edit->eliminateDeadDefs(Dead); 1021 } 1022 1023 void SplitEditor::finish(SmallVectorImpl<unsigned> *LRMap) { 1024 ++NumFinished; 1025 1026 // At this point, the live intervals in Edit contain VNInfos corresponding to 1027 // the inserted copies. 1028 1029 // Add the original defs from the parent interval. 1030 for (const VNInfo *ParentVNI : Edit->getParent().valnos) { 1031 if (ParentVNI->isUnused()) 1032 continue; 1033 unsigned RegIdx = RegAssign.lookup(ParentVNI->def); 1034 defValue(RegIdx, ParentVNI, ParentVNI->def); 1035 1036 // Force rematted values to be recomputed everywhere. 1037 // The new live ranges may be truncated. 1038 if (Edit->didRematerialize(ParentVNI)) 1039 for (unsigned i = 0, e = Edit->size(); i != e; ++i) 1040 forceRecompute(i, ParentVNI); 1041 } 1042 1043 // Hoist back-copies to the complement interval when in spill mode. 1044 switch (SpillMode) { 1045 case SM_Partition: 1046 // Leave all back-copies as is. 1047 break; 1048 case SM_Size: 1049 hoistCopiesForSize(); 1050 break; 1051 case SM_Speed: 1052 llvm_unreachable("Spill mode 'speed' not implemented yet"); 1053 } 1054 1055 // Transfer the simply mapped values, check if any are skipped. 1056 bool Skipped = transferValues(); 1057 if (Skipped) 1058 extendPHIKillRanges(); 1059 else 1060 ++NumSimple; 1061 1062 // Rewrite virtual registers, possibly extending ranges. 1063 rewriteAssigned(Skipped); 1064 1065 // Delete defs that were rematted everywhere. 1066 if (Skipped) 1067 deleteRematVictims(); 1068 1069 // Get rid of unused values and set phi-kill flags. 1070 for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I) { 1071 LiveInterval &LI = LIS.getInterval(*I); 1072 LI.RenumberValues(); 1073 } 1074 1075 // Provide a reverse mapping from original indices to Edit ranges. 1076 if (LRMap) { 1077 LRMap->clear(); 1078 for (unsigned i = 0, e = Edit->size(); i != e; ++i) 1079 LRMap->push_back(i); 1080 } 1081 1082 // Now check if any registers were separated into multiple components. 1083 ConnectedVNInfoEqClasses ConEQ(LIS); 1084 for (unsigned i = 0, e = Edit->size(); i != e; ++i) { 1085 // Don't use iterators, they are invalidated by create() below. 1086 LiveInterval *li = &LIS.getInterval(Edit->get(i)); 1087 unsigned NumComp = ConEQ.Classify(li); 1088 if (NumComp <= 1) 1089 continue; 1090 DEBUG(dbgs() << " " << NumComp << " components: " << *li << '\n'); 1091 SmallVector<LiveInterval*, 8> dups; 1092 dups.push_back(li); 1093 for (unsigned j = 1; j != NumComp; ++j) 1094 dups.push_back(&Edit->createEmptyInterval()); 1095 ConEQ.Distribute(&dups[0], MRI); 1096 // The new intervals all map back to i. 1097 if (LRMap) 1098 LRMap->resize(Edit->size(), i); 1099 } 1100 1101 // Calculate spill weight and allocation hints for new intervals. 1102 Edit->calculateRegClassAndHint(VRM.getMachineFunction(), SA.Loops, MBFI); 1103 1104 assert(!LRMap || LRMap->size() == Edit->size()); 1105 } 1106 1107 1108 //===----------------------------------------------------------------------===// 1109 // Single Block Splitting 1110 //===----------------------------------------------------------------------===// 1111 1112 bool SplitAnalysis::shouldSplitSingleBlock(const BlockInfo &BI, 1113 bool SingleInstrs) const { 1114 // Always split for multiple instructions. 1115 if (!BI.isOneInstr()) 1116 return true; 1117 // Don't split for single instructions unless explicitly requested. 1118 if (!SingleInstrs) 1119 return false; 1120 // Splitting a live-through range always makes progress. 1121 if (BI.LiveIn && BI.LiveOut) 1122 return true; 1123 // No point in isolating a copy. It has no register class constraints. 1124 if (LIS.getInstructionFromIndex(BI.FirstInstr)->isCopyLike()) 1125 return false; 1126 // Finally, don't isolate an end point that was created by earlier splits. 1127 return isOriginalEndpoint(BI.FirstInstr); 1128 } 1129 1130 void SplitEditor::splitSingleBlock(const SplitAnalysis::BlockInfo &BI) { 1131 openIntv(); 1132 SlotIndex LastSplitPoint = SA.getLastSplitPoint(BI.MBB->getNumber()); 1133 SlotIndex SegStart = enterIntvBefore(std::min(BI.FirstInstr, 1134 LastSplitPoint)); 1135 if (!BI.LiveOut || BI.LastInstr < LastSplitPoint) { 1136 useIntv(SegStart, leaveIntvAfter(BI.LastInstr)); 1137 } else { 1138 // The last use is after the last valid split point. 1139 SlotIndex SegStop = leaveIntvBefore(LastSplitPoint); 1140 useIntv(SegStart, SegStop); 1141 overlapIntv(SegStop, BI.LastInstr); 1142 } 1143 } 1144 1145 1146 //===----------------------------------------------------------------------===// 1147 // Global Live Range Splitting Support 1148 //===----------------------------------------------------------------------===// 1149 1150 // These methods support a method of global live range splitting that uses a 1151 // global algorithm to decide intervals for CFG edges. They will insert split 1152 // points and color intervals in basic blocks while avoiding interference. 1153 // 1154 // Note that splitSingleBlock is also useful for blocks where both CFG edges 1155 // are on the stack. 1156 1157 void SplitEditor::splitLiveThroughBlock(unsigned MBBNum, 1158 unsigned IntvIn, SlotIndex LeaveBefore, 1159 unsigned IntvOut, SlotIndex EnterAfter){ 1160 SlotIndex Start, Stop; 1161 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(MBBNum); 1162 1163 DEBUG(dbgs() << "BB#" << MBBNum << " [" << Start << ';' << Stop 1164 << ") intf " << LeaveBefore << '-' << EnterAfter 1165 << ", live-through " << IntvIn << " -> " << IntvOut); 1166 1167 assert((IntvIn || IntvOut) && "Use splitSingleBlock for isolated blocks"); 1168 1169 assert((!LeaveBefore || LeaveBefore < Stop) && "Interference after block"); 1170 assert((!IntvIn || !LeaveBefore || LeaveBefore > Start) && "Impossible intf"); 1171 assert((!EnterAfter || EnterAfter >= Start) && "Interference before block"); 1172 1173 MachineBasicBlock *MBB = VRM.getMachineFunction().getBlockNumbered(MBBNum); 1174 1175 if (!IntvOut) { 1176 DEBUG(dbgs() << ", spill on entry.\n"); 1177 // 1178 // <<<<<<<<< Possible LeaveBefore interference. 1179 // |-----------| Live through. 1180 // -____________ Spill on entry. 1181 // 1182 selectIntv(IntvIn); 1183 SlotIndex Idx = leaveIntvAtTop(*MBB); 1184 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1185 (void)Idx; 1186 return; 1187 } 1188 1189 if (!IntvIn) { 1190 DEBUG(dbgs() << ", reload on exit.\n"); 1191 // 1192 // >>>>>>> Possible EnterAfter interference. 1193 // |-----------| Live through. 1194 // ___________-- Reload on exit. 1195 // 1196 selectIntv(IntvOut); 1197 SlotIndex Idx = enterIntvAtEnd(*MBB); 1198 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1199 (void)Idx; 1200 return; 1201 } 1202 1203 if (IntvIn == IntvOut && !LeaveBefore && !EnterAfter) { 1204 DEBUG(dbgs() << ", straight through.\n"); 1205 // 1206 // |-----------| Live through. 1207 // ------------- Straight through, same intv, no interference. 1208 // 1209 selectIntv(IntvOut); 1210 useIntv(Start, Stop); 1211 return; 1212 } 1213 1214 // We cannot legally insert splits after LSP. 1215 SlotIndex LSP = SA.getLastSplitPoint(MBBNum); 1216 assert((!IntvOut || !EnterAfter || EnterAfter < LSP) && "Impossible intf"); 1217 1218 if (IntvIn != IntvOut && (!LeaveBefore || !EnterAfter || 1219 LeaveBefore.getBaseIndex() > EnterAfter.getBoundaryIndex())) { 1220 DEBUG(dbgs() << ", switch avoiding interference.\n"); 1221 // 1222 // >>>> <<<< Non-overlapping EnterAfter/LeaveBefore interference. 1223 // |-----------| Live through. 1224 // ------======= Switch intervals between interference. 1225 // 1226 selectIntv(IntvOut); 1227 SlotIndex Idx; 1228 if (LeaveBefore && LeaveBefore < LSP) { 1229 Idx = enterIntvBefore(LeaveBefore); 1230 useIntv(Idx, Stop); 1231 } else { 1232 Idx = enterIntvAtEnd(*MBB); 1233 } 1234 selectIntv(IntvIn); 1235 useIntv(Start, Idx); 1236 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1237 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1238 return; 1239 } 1240 1241 DEBUG(dbgs() << ", create local intv for interference.\n"); 1242 // 1243 // >>><><><><<<< Overlapping EnterAfter/LeaveBefore interference. 1244 // |-----------| Live through. 1245 // ==---------== Switch intervals before/after interference. 1246 // 1247 assert(LeaveBefore <= EnterAfter && "Missed case"); 1248 1249 selectIntv(IntvOut); 1250 SlotIndex Idx = enterIntvAfter(EnterAfter); 1251 useIntv(Idx, Stop); 1252 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1253 1254 selectIntv(IntvIn); 1255 Idx = leaveIntvBefore(LeaveBefore); 1256 useIntv(Start, Idx); 1257 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1258 } 1259 1260 1261 void SplitEditor::splitRegInBlock(const SplitAnalysis::BlockInfo &BI, 1262 unsigned IntvIn, SlotIndex LeaveBefore) { 1263 SlotIndex Start, Stop; 1264 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB); 1265 1266 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " [" << Start << ';' << Stop 1267 << "), uses " << BI.FirstInstr << '-' << BI.LastInstr 1268 << ", reg-in " << IntvIn << ", leave before " << LeaveBefore 1269 << (BI.LiveOut ? ", stack-out" : ", killed in block")); 1270 1271 assert(IntvIn && "Must have register in"); 1272 assert(BI.LiveIn && "Must be live-in"); 1273 assert((!LeaveBefore || LeaveBefore > Start) && "Bad interference"); 1274 1275 if (!BI.LiveOut && (!LeaveBefore || LeaveBefore >= BI.LastInstr)) { 1276 DEBUG(dbgs() << " before interference.\n"); 1277 // 1278 // <<< Interference after kill. 1279 // |---o---x | Killed in block. 1280 // ========= Use IntvIn everywhere. 1281 // 1282 selectIntv(IntvIn); 1283 useIntv(Start, BI.LastInstr); 1284 return; 1285 } 1286 1287 SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber()); 1288 1289 if (!LeaveBefore || LeaveBefore > BI.LastInstr.getBoundaryIndex()) { 1290 // 1291 // <<< Possible interference after last use. 1292 // |---o---o---| Live-out on stack. 1293 // =========____ Leave IntvIn after last use. 1294 // 1295 // < Interference after last use. 1296 // |---o---o--o| Live-out on stack, late last use. 1297 // ============ Copy to stack after LSP, overlap IntvIn. 1298 // \_____ Stack interval is live-out. 1299 // 1300 if (BI.LastInstr < LSP) { 1301 DEBUG(dbgs() << ", spill after last use before interference.\n"); 1302 selectIntv(IntvIn); 1303 SlotIndex Idx = leaveIntvAfter(BI.LastInstr); 1304 useIntv(Start, Idx); 1305 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1306 } else { 1307 DEBUG(dbgs() << ", spill before last split point.\n"); 1308 selectIntv(IntvIn); 1309 SlotIndex Idx = leaveIntvBefore(LSP); 1310 overlapIntv(Idx, BI.LastInstr); 1311 useIntv(Start, Idx); 1312 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1313 } 1314 return; 1315 } 1316 1317 // The interference is overlapping somewhere we wanted to use IntvIn. That 1318 // means we need to create a local interval that can be allocated a 1319 // different register. 1320 unsigned LocalIntv = openIntv(); 1321 (void)LocalIntv; 1322 DEBUG(dbgs() << ", creating local interval " << LocalIntv << ".\n"); 1323 1324 if (!BI.LiveOut || BI.LastInstr < LSP) { 1325 // 1326 // <<<<<<< Interference overlapping uses. 1327 // |---o---o---| Live-out on stack. 1328 // =====----____ Leave IntvIn before interference, then spill. 1329 // 1330 SlotIndex To = leaveIntvAfter(BI.LastInstr); 1331 SlotIndex From = enterIntvBefore(LeaveBefore); 1332 useIntv(From, To); 1333 selectIntv(IntvIn); 1334 useIntv(Start, From); 1335 assert((!LeaveBefore || From <= LeaveBefore) && "Interference"); 1336 return; 1337 } 1338 1339 // <<<<<<< Interference overlapping uses. 1340 // |---o---o--o| Live-out on stack, late last use. 1341 // =====------- Copy to stack before LSP, overlap LocalIntv. 1342 // \_____ Stack interval is live-out. 1343 // 1344 SlotIndex To = leaveIntvBefore(LSP); 1345 overlapIntv(To, BI.LastInstr); 1346 SlotIndex From = enterIntvBefore(std::min(To, LeaveBefore)); 1347 useIntv(From, To); 1348 selectIntv(IntvIn); 1349 useIntv(Start, From); 1350 assert((!LeaveBefore || From <= LeaveBefore) && "Interference"); 1351 } 1352 1353 void SplitEditor::splitRegOutBlock(const SplitAnalysis::BlockInfo &BI, 1354 unsigned IntvOut, SlotIndex EnterAfter) { 1355 SlotIndex Start, Stop; 1356 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB); 1357 1358 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " [" << Start << ';' << Stop 1359 << "), uses " << BI.FirstInstr << '-' << BI.LastInstr 1360 << ", reg-out " << IntvOut << ", enter after " << EnterAfter 1361 << (BI.LiveIn ? ", stack-in" : ", defined in block")); 1362 1363 SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber()); 1364 1365 assert(IntvOut && "Must have register out"); 1366 assert(BI.LiveOut && "Must be live-out"); 1367 assert((!EnterAfter || EnterAfter < LSP) && "Bad interference"); 1368 1369 if (!BI.LiveIn && (!EnterAfter || EnterAfter <= BI.FirstInstr)) { 1370 DEBUG(dbgs() << " after interference.\n"); 1371 // 1372 // >>>> Interference before def. 1373 // | o---o---| Defined in block. 1374 // ========= Use IntvOut everywhere. 1375 // 1376 selectIntv(IntvOut); 1377 useIntv(BI.FirstInstr, Stop); 1378 return; 1379 } 1380 1381 if (!EnterAfter || EnterAfter < BI.FirstInstr.getBaseIndex()) { 1382 DEBUG(dbgs() << ", reload after interference.\n"); 1383 // 1384 // >>>> Interference before def. 1385 // |---o---o---| Live-through, stack-in. 1386 // ____========= Enter IntvOut before first use. 1387 // 1388 selectIntv(IntvOut); 1389 SlotIndex Idx = enterIntvBefore(std::min(LSP, BI.FirstInstr)); 1390 useIntv(Idx, Stop); 1391 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1392 return; 1393 } 1394 1395 // The interference is overlapping somewhere we wanted to use IntvOut. That 1396 // means we need to create a local interval that can be allocated a 1397 // different register. 1398 DEBUG(dbgs() << ", interference overlaps uses.\n"); 1399 // 1400 // >>>>>>> Interference overlapping uses. 1401 // |---o---o---| Live-through, stack-in. 1402 // ____---====== Create local interval for interference range. 1403 // 1404 selectIntv(IntvOut); 1405 SlotIndex Idx = enterIntvAfter(EnterAfter); 1406 useIntv(Idx, Stop); 1407 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1408 1409 openIntv(); 1410 SlotIndex From = enterIntvBefore(std::min(Idx, BI.FirstInstr)); 1411 useIntv(From, Idx); 1412 } 1413