1 //===- SplitKit.cpp - Toolkit for splitting live ranges -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the SplitAnalysis class as well as mutator functions for 10 // live range splitting. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "SplitKit.h" 15 #include "llvm/ADT/None.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/Statistic.h" 18 #include "llvm/Analysis/AliasAnalysis.h" 19 #include "llvm/CodeGen/LiveRangeEdit.h" 20 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 21 #include "llvm/CodeGen/MachineDominators.h" 22 #include "llvm/CodeGen/MachineInstr.h" 23 #include "llvm/CodeGen/MachineInstrBuilder.h" 24 #include "llvm/CodeGen/MachineLoopInfo.h" 25 #include "llvm/CodeGen/MachineOperand.h" 26 #include "llvm/CodeGen/MachineRegisterInfo.h" 27 #include "llvm/CodeGen/TargetInstrInfo.h" 28 #include "llvm/CodeGen/TargetOpcodes.h" 29 #include "llvm/CodeGen/TargetRegisterInfo.h" 30 #include "llvm/CodeGen/TargetSubtargetInfo.h" 31 #include "llvm/CodeGen/VirtRegMap.h" 32 #include "llvm/Config/llvm-config.h" 33 #include "llvm/IR/DebugLoc.h" 34 #include "llvm/Support/Allocator.h" 35 #include "llvm/Support/BlockFrequency.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/raw_ostream.h" 39 #include <algorithm> 40 #include <cassert> 41 #include <iterator> 42 #include <limits> 43 #include <tuple> 44 45 using namespace llvm; 46 47 #define DEBUG_TYPE "regalloc" 48 49 STATISTIC(NumFinished, "Number of splits finished"); 50 STATISTIC(NumSimple, "Number of splits that were simple"); 51 STATISTIC(NumCopies, "Number of copies inserted for splitting"); 52 STATISTIC(NumRemats, "Number of rematerialized defs for splitting"); 53 STATISTIC(NumRepairs, "Number of invalid live ranges repaired"); 54 55 //===----------------------------------------------------------------------===// 56 // Last Insert Point Analysis 57 //===----------------------------------------------------------------------===// 58 59 InsertPointAnalysis::InsertPointAnalysis(const LiveIntervals &lis, 60 unsigned BBNum) 61 : LIS(lis), LastInsertPoint(BBNum) {} 62 63 SlotIndex 64 InsertPointAnalysis::computeLastInsertPoint(const LiveInterval &CurLI, 65 const MachineBasicBlock &MBB) { 66 unsigned Num = MBB.getNumber(); 67 std::pair<SlotIndex, SlotIndex> &LIP = LastInsertPoint[Num]; 68 SlotIndex MBBEnd = LIS.getMBBEndIdx(&MBB); 69 70 SmallVector<const MachineBasicBlock *, 1> ExceptionalSuccessors; 71 bool EHPadSuccessor = false; 72 for (const MachineBasicBlock *SMBB : MBB.successors()) { 73 if (SMBB->isEHPad()) { 74 ExceptionalSuccessors.push_back(SMBB); 75 EHPadSuccessor = true; 76 } else if (SMBB->isInlineAsmBrIndirectTarget()) 77 ExceptionalSuccessors.push_back(SMBB); 78 } 79 80 // Compute insert points on the first call. The pair is independent of the 81 // current live interval. 82 if (!LIP.first.isValid()) { 83 MachineBasicBlock::const_iterator FirstTerm = MBB.getFirstTerminator(); 84 if (FirstTerm == MBB.end()) 85 LIP.first = MBBEnd; 86 else 87 LIP.first = LIS.getInstructionIndex(*FirstTerm); 88 89 // If there is a landing pad or inlineasm_br successor, also find the 90 // instruction. If there is no such instruction, we don't need to do 91 // anything special. We assume there cannot be multiple instructions that 92 // are Calls with EHPad successors or INLINEASM_BR in a block. Further, we 93 // assume that if there are any, they will be after any other call 94 // instructions in the block. 95 if (ExceptionalSuccessors.empty()) 96 return LIP.first; 97 for (const MachineInstr &MI : llvm::reverse(MBB)) { 98 if ((EHPadSuccessor && MI.isCall()) || 99 MI.getOpcode() == TargetOpcode::INLINEASM_BR) { 100 LIP.second = LIS.getInstructionIndex(MI); 101 break; 102 } 103 } 104 } 105 106 // If CurLI is live into a landing pad successor, move the last insert point 107 // back to the call that may throw. 108 if (!LIP.second) 109 return LIP.first; 110 111 if (none_of(ExceptionalSuccessors, [&](const MachineBasicBlock *EHPad) { 112 return LIS.isLiveInToMBB(CurLI, EHPad); 113 })) 114 return LIP.first; 115 116 // Find the value leaving MBB. 117 const VNInfo *VNI = CurLI.getVNInfoBefore(MBBEnd); 118 if (!VNI) 119 return LIP.first; 120 121 // The def of statepoint instruction is a gc relocation and it should be alive 122 // in landing pad. So we cannot split interval after statepoint instruction. 123 if (SlotIndex::isSameInstr(VNI->def, LIP.second)) 124 if (auto *I = LIS.getInstructionFromIndex(LIP.second)) 125 if (I->getOpcode() == TargetOpcode::STATEPOINT) 126 return LIP.second; 127 128 // If the value leaving MBB was defined after the call in MBB, it can't 129 // really be live-in to the landing pad. This can happen if the landing pad 130 // has a PHI, and this register is undef on the exceptional edge. 131 // <rdar://problem/10664933> 132 if (!SlotIndex::isEarlierInstr(VNI->def, LIP.second) && VNI->def < MBBEnd) 133 return LIP.first; 134 135 // Value is properly live-in to the landing pad. 136 // Only allow inserts before the call. 137 return LIP.second; 138 } 139 140 MachineBasicBlock::iterator 141 InsertPointAnalysis::getLastInsertPointIter(const LiveInterval &CurLI, 142 MachineBasicBlock &MBB) { 143 SlotIndex LIP = getLastInsertPoint(CurLI, MBB); 144 if (LIP == LIS.getMBBEndIdx(&MBB)) 145 return MBB.end(); 146 return LIS.getInstructionFromIndex(LIP); 147 } 148 149 //===----------------------------------------------------------------------===// 150 // Split Analysis 151 //===----------------------------------------------------------------------===// 152 153 SplitAnalysis::SplitAnalysis(const VirtRegMap &vrm, const LiveIntervals &lis, 154 const MachineLoopInfo &mli) 155 : MF(vrm.getMachineFunction()), VRM(vrm), LIS(lis), Loops(mli), 156 TII(*MF.getSubtarget().getInstrInfo()), IPA(lis, MF.getNumBlockIDs()) {} 157 158 void SplitAnalysis::clear() { 159 UseSlots.clear(); 160 UseBlocks.clear(); 161 ThroughBlocks.clear(); 162 CurLI = nullptr; 163 DidRepairRange = false; 164 } 165 166 /// analyzeUses - Count instructions, basic blocks, and loops using CurLI. 167 void SplitAnalysis::analyzeUses() { 168 assert(UseSlots.empty() && "Call clear first"); 169 170 // First get all the defs from the interval values. This provides the correct 171 // slots for early clobbers. 172 for (const VNInfo *VNI : CurLI->valnos) 173 if (!VNI->isPHIDef() && !VNI->isUnused()) 174 UseSlots.push_back(VNI->def); 175 176 // Get use slots form the use-def chain. 177 const MachineRegisterInfo &MRI = MF.getRegInfo(); 178 for (MachineOperand &MO : MRI.use_nodbg_operands(CurLI->reg())) 179 if (!MO.isUndef()) 180 UseSlots.push_back(LIS.getInstructionIndex(*MO.getParent()).getRegSlot()); 181 182 array_pod_sort(UseSlots.begin(), UseSlots.end()); 183 184 // Remove duplicates, keeping the smaller slot for each instruction. 185 // That is what we want for early clobbers. 186 UseSlots.erase(std::unique(UseSlots.begin(), UseSlots.end(), 187 SlotIndex::isSameInstr), 188 UseSlots.end()); 189 190 // Compute per-live block info. 191 if (!calcLiveBlockInfo()) { 192 // FIXME: calcLiveBlockInfo found inconsistencies in the live range. 193 // I am looking at you, RegisterCoalescer! 194 DidRepairRange = true; 195 ++NumRepairs; 196 LLVM_DEBUG(dbgs() << "*** Fixing inconsistent live interval! ***\n"); 197 const_cast<LiveIntervals&>(LIS) 198 .shrinkToUses(const_cast<LiveInterval*>(CurLI)); 199 UseBlocks.clear(); 200 ThroughBlocks.clear(); 201 bool fixed = calcLiveBlockInfo(); 202 (void)fixed; 203 assert(fixed && "Couldn't fix broken live interval"); 204 } 205 206 LLVM_DEBUG(dbgs() << "Analyze counted " << UseSlots.size() << " instrs in " 207 << UseBlocks.size() << " blocks, through " 208 << NumThroughBlocks << " blocks.\n"); 209 } 210 211 /// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks 212 /// where CurLI is live. 213 bool SplitAnalysis::calcLiveBlockInfo() { 214 ThroughBlocks.resize(MF.getNumBlockIDs()); 215 NumThroughBlocks = NumGapBlocks = 0; 216 if (CurLI->empty()) 217 return true; 218 219 LiveInterval::const_iterator LVI = CurLI->begin(); 220 LiveInterval::const_iterator LVE = CurLI->end(); 221 222 SmallVectorImpl<SlotIndex>::const_iterator UseI, UseE; 223 UseI = UseSlots.begin(); 224 UseE = UseSlots.end(); 225 226 // Loop over basic blocks where CurLI is live. 227 MachineFunction::iterator MFI = 228 LIS.getMBBFromIndex(LVI->start)->getIterator(); 229 while (true) { 230 BlockInfo BI; 231 BI.MBB = &*MFI; 232 SlotIndex Start, Stop; 233 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB); 234 235 // If the block contains no uses, the range must be live through. At one 236 // point, RegisterCoalescer could create dangling ranges that ended 237 // mid-block. 238 if (UseI == UseE || *UseI >= Stop) { 239 ++NumThroughBlocks; 240 ThroughBlocks.set(BI.MBB->getNumber()); 241 // The range shouldn't end mid-block if there are no uses. This shouldn't 242 // happen. 243 if (LVI->end < Stop) 244 return false; 245 } else { 246 // This block has uses. Find the first and last uses in the block. 247 BI.FirstInstr = *UseI; 248 assert(BI.FirstInstr >= Start); 249 do ++UseI; 250 while (UseI != UseE && *UseI < Stop); 251 BI.LastInstr = UseI[-1]; 252 assert(BI.LastInstr < Stop); 253 254 // LVI is the first live segment overlapping MBB. 255 BI.LiveIn = LVI->start <= Start; 256 257 // When not live in, the first use should be a def. 258 if (!BI.LiveIn) { 259 assert(LVI->start == LVI->valno->def && "Dangling Segment start"); 260 assert(LVI->start == BI.FirstInstr && "First instr should be a def"); 261 BI.FirstDef = BI.FirstInstr; 262 } 263 264 // Look for gaps in the live range. 265 BI.LiveOut = true; 266 while (LVI->end < Stop) { 267 SlotIndex LastStop = LVI->end; 268 if (++LVI == LVE || LVI->start >= Stop) { 269 BI.LiveOut = false; 270 BI.LastInstr = LastStop; 271 break; 272 } 273 274 if (LastStop < LVI->start) { 275 // There is a gap in the live range. Create duplicate entries for the 276 // live-in snippet and the live-out snippet. 277 ++NumGapBlocks; 278 279 // Push the Live-in part. 280 BI.LiveOut = false; 281 UseBlocks.push_back(BI); 282 UseBlocks.back().LastInstr = LastStop; 283 284 // Set up BI for the live-out part. 285 BI.LiveIn = false; 286 BI.LiveOut = true; 287 BI.FirstInstr = BI.FirstDef = LVI->start; 288 } 289 290 // A Segment that starts in the middle of the block must be a def. 291 assert(LVI->start == LVI->valno->def && "Dangling Segment start"); 292 if (!BI.FirstDef) 293 BI.FirstDef = LVI->start; 294 } 295 296 UseBlocks.push_back(BI); 297 298 // LVI is now at LVE or LVI->end >= Stop. 299 if (LVI == LVE) 300 break; 301 } 302 303 // Live segment ends exactly at Stop. Move to the next segment. 304 if (LVI->end == Stop && ++LVI == LVE) 305 break; 306 307 // Pick the next basic block. 308 if (LVI->start < Stop) 309 ++MFI; 310 else 311 MFI = LIS.getMBBFromIndex(LVI->start)->getIterator(); 312 } 313 314 assert(getNumLiveBlocks() == countLiveBlocks(CurLI) && "Bad block count"); 315 return true; 316 } 317 318 unsigned SplitAnalysis::countLiveBlocks(const LiveInterval *cli) const { 319 if (cli->empty()) 320 return 0; 321 LiveInterval *li = const_cast<LiveInterval*>(cli); 322 LiveInterval::iterator LVI = li->begin(); 323 LiveInterval::iterator LVE = li->end(); 324 unsigned Count = 0; 325 326 // Loop over basic blocks where li is live. 327 MachineFunction::const_iterator MFI = 328 LIS.getMBBFromIndex(LVI->start)->getIterator(); 329 SlotIndex Stop = LIS.getMBBEndIdx(&*MFI); 330 while (true) { 331 ++Count; 332 LVI = li->advanceTo(LVI, Stop); 333 if (LVI == LVE) 334 return Count; 335 do { 336 ++MFI; 337 Stop = LIS.getMBBEndIdx(&*MFI); 338 } while (Stop <= LVI->start); 339 } 340 } 341 342 bool SplitAnalysis::isOriginalEndpoint(SlotIndex Idx) const { 343 unsigned OrigReg = VRM.getOriginal(CurLI->reg()); 344 const LiveInterval &Orig = LIS.getInterval(OrigReg); 345 assert(!Orig.empty() && "Splitting empty interval?"); 346 LiveInterval::const_iterator I = Orig.find(Idx); 347 348 // Range containing Idx should begin at Idx. 349 if (I != Orig.end() && I->start <= Idx) 350 return I->start == Idx; 351 352 // Range does not contain Idx, previous must end at Idx. 353 return I != Orig.begin() && (--I)->end == Idx; 354 } 355 356 void SplitAnalysis::analyze(const LiveInterval *li) { 357 clear(); 358 CurLI = li; 359 analyzeUses(); 360 } 361 362 //===----------------------------------------------------------------------===// 363 // Split Editor 364 //===----------------------------------------------------------------------===// 365 366 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA. 367 SplitEditor::SplitEditor(SplitAnalysis &SA, AliasAnalysis &AA, 368 LiveIntervals &LIS, VirtRegMap &VRM, 369 MachineDominatorTree &MDT, 370 MachineBlockFrequencyInfo &MBFI, VirtRegAuxInfo &VRAI) 371 : SA(SA), AA(AA), LIS(LIS), VRM(VRM), 372 MRI(VRM.getMachineFunction().getRegInfo()), MDT(MDT), 373 TII(*VRM.getMachineFunction().getSubtarget().getInstrInfo()), 374 TRI(*VRM.getMachineFunction().getSubtarget().getRegisterInfo()), 375 MBFI(MBFI), VRAI(VRAI), RegAssign(Allocator) {} 376 377 void SplitEditor::reset(LiveRangeEdit &LRE, ComplementSpillMode SM) { 378 Edit = &LRE; 379 SpillMode = SM; 380 OpenIdx = 0; 381 RegAssign.clear(); 382 Values.clear(); 383 384 // Reset the LiveIntervalCalc instances needed for this spill mode. 385 LICalc[0].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT, 386 &LIS.getVNInfoAllocator()); 387 if (SpillMode) 388 LICalc[1].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT, 389 &LIS.getVNInfoAllocator()); 390 391 // We don't need an AliasAnalysis since we will only be performing 392 // cheap-as-a-copy remats anyway. 393 Edit->anyRematerializable(nullptr); 394 } 395 396 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 397 LLVM_DUMP_METHOD void SplitEditor::dump() const { 398 if (RegAssign.empty()) { 399 dbgs() << " empty\n"; 400 return; 401 } 402 403 for (RegAssignMap::const_iterator I = RegAssign.begin(); I.valid(); ++I) 404 dbgs() << " [" << I.start() << ';' << I.stop() << "):" << I.value(); 405 dbgs() << '\n'; 406 } 407 #endif 408 409 LiveInterval::SubRange &SplitEditor::getSubRangeForMaskExact(LaneBitmask LM, 410 LiveInterval &LI) { 411 for (LiveInterval::SubRange &S : LI.subranges()) 412 if (S.LaneMask == LM) 413 return S; 414 llvm_unreachable("SubRange for this mask not found"); 415 } 416 417 LiveInterval::SubRange &SplitEditor::getSubRangeForMask(LaneBitmask LM, 418 LiveInterval &LI) { 419 for (LiveInterval::SubRange &S : LI.subranges()) 420 if ((S.LaneMask & LM) == LM) 421 return S; 422 llvm_unreachable("SubRange for this mask not found"); 423 } 424 425 void SplitEditor::addDeadDef(LiveInterval &LI, VNInfo *VNI, bool Original) { 426 if (!LI.hasSubRanges()) { 427 LI.createDeadDef(VNI); 428 return; 429 } 430 431 SlotIndex Def = VNI->def; 432 if (Original) { 433 // If we are transferring a def from the original interval, make sure 434 // to only update the subranges for which the original subranges had 435 // a def at this location. 436 for (LiveInterval::SubRange &S : LI.subranges()) { 437 auto &PS = getSubRangeForMask(S.LaneMask, Edit->getParent()); 438 VNInfo *PV = PS.getVNInfoAt(Def); 439 if (PV != nullptr && PV->def == Def) 440 S.createDeadDef(Def, LIS.getVNInfoAllocator()); 441 } 442 } else { 443 // This is a new def: either from rematerialization, or from an inserted 444 // copy. Since rematerialization can regenerate a definition of a sub- 445 // register, we need to check which subranges need to be updated. 446 const MachineInstr *DefMI = LIS.getInstructionFromIndex(Def); 447 assert(DefMI != nullptr); 448 LaneBitmask LM; 449 for (const MachineOperand &DefOp : DefMI->defs()) { 450 Register R = DefOp.getReg(); 451 if (R != LI.reg()) 452 continue; 453 if (unsigned SR = DefOp.getSubReg()) 454 LM |= TRI.getSubRegIndexLaneMask(SR); 455 else { 456 LM = MRI.getMaxLaneMaskForVReg(R); 457 break; 458 } 459 } 460 for (LiveInterval::SubRange &S : LI.subranges()) 461 if ((S.LaneMask & LM).any()) 462 S.createDeadDef(Def, LIS.getVNInfoAllocator()); 463 } 464 } 465 466 VNInfo *SplitEditor::defValue(unsigned RegIdx, 467 const VNInfo *ParentVNI, 468 SlotIndex Idx, 469 bool Original) { 470 assert(ParentVNI && "Mapping NULL value"); 471 assert(Idx.isValid() && "Invalid SlotIndex"); 472 assert(Edit->getParent().getVNInfoAt(Idx) == ParentVNI && "Bad Parent VNI"); 473 LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx)); 474 475 // Create a new value. 476 VNInfo *VNI = LI->getNextValue(Idx, LIS.getVNInfoAllocator()); 477 478 bool Force = LI->hasSubRanges(); 479 ValueForcePair FP(Force ? nullptr : VNI, Force); 480 // Use insert for lookup, so we can add missing values with a second lookup. 481 std::pair<ValueMap::iterator, bool> InsP = 482 Values.insert(std::make_pair(std::make_pair(RegIdx, ParentVNI->id), FP)); 483 484 // This was the first time (RegIdx, ParentVNI) was mapped, and it is not 485 // forced. Keep it as a simple def without any liveness. 486 if (!Force && InsP.second) 487 return VNI; 488 489 // If the previous value was a simple mapping, add liveness for it now. 490 if (VNInfo *OldVNI = InsP.first->second.getPointer()) { 491 addDeadDef(*LI, OldVNI, Original); 492 493 // No longer a simple mapping. Switch to a complex mapping. If the 494 // interval has subranges, make it a forced mapping. 495 InsP.first->second = ValueForcePair(nullptr, Force); 496 } 497 498 // This is a complex mapping, add liveness for VNI 499 addDeadDef(*LI, VNI, Original); 500 return VNI; 501 } 502 503 void SplitEditor::forceRecompute(unsigned RegIdx, const VNInfo &ParentVNI) { 504 ValueForcePair &VFP = Values[std::make_pair(RegIdx, ParentVNI.id)]; 505 VNInfo *VNI = VFP.getPointer(); 506 507 // ParentVNI was either unmapped or already complex mapped. Either way, just 508 // set the force bit. 509 if (!VNI) { 510 VFP.setInt(true); 511 return; 512 } 513 514 // This was previously a single mapping. Make sure the old def is represented 515 // by a trivial live range. 516 addDeadDef(LIS.getInterval(Edit->get(RegIdx)), VNI, false); 517 518 // Mark as complex mapped, forced. 519 VFP = ValueForcePair(nullptr, true); 520 } 521 522 SlotIndex SplitEditor::buildSingleSubRegCopy(Register FromReg, Register ToReg, 523 MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore, 524 unsigned SubIdx, LiveInterval &DestLI, bool Late, SlotIndex Def) { 525 const MCInstrDesc &Desc = TII.get(TargetOpcode::COPY); 526 bool FirstCopy = !Def.isValid(); 527 MachineInstr *CopyMI = BuildMI(MBB, InsertBefore, DebugLoc(), Desc) 528 .addReg(ToReg, RegState::Define | getUndefRegState(FirstCopy) 529 | getInternalReadRegState(!FirstCopy), SubIdx) 530 .addReg(FromReg, 0, SubIdx); 531 532 SlotIndexes &Indexes = *LIS.getSlotIndexes(); 533 if (FirstCopy) { 534 Def = Indexes.insertMachineInstrInMaps(*CopyMI, Late).getRegSlot(); 535 } else { 536 CopyMI->bundleWithPred(); 537 } 538 return Def; 539 } 540 541 SlotIndex SplitEditor::buildCopy(Register FromReg, Register ToReg, 542 LaneBitmask LaneMask, MachineBasicBlock &MBB, 543 MachineBasicBlock::iterator InsertBefore, bool Late, unsigned RegIdx) { 544 const MCInstrDesc &Desc = TII.get(TargetOpcode::COPY); 545 SlotIndexes &Indexes = *LIS.getSlotIndexes(); 546 if (LaneMask.all() || LaneMask == MRI.getMaxLaneMaskForVReg(FromReg)) { 547 // The full vreg is copied. 548 MachineInstr *CopyMI = 549 BuildMI(MBB, InsertBefore, DebugLoc(), Desc, ToReg).addReg(FromReg); 550 return Indexes.insertMachineInstrInMaps(*CopyMI, Late).getRegSlot(); 551 } 552 553 // Only a subset of lanes needs to be copied. The following is a simple 554 // heuristic to construct a sequence of COPYs. We could add a target 555 // specific callback if this turns out to be suboptimal. 556 LiveInterval &DestLI = LIS.getInterval(Edit->get(RegIdx)); 557 558 // First pass: Try to find a perfectly matching subregister index. If none 559 // exists find the one covering the most lanemask bits. 560 const TargetRegisterClass *RC = MRI.getRegClass(FromReg); 561 assert(RC == MRI.getRegClass(ToReg) && "Should have same reg class"); 562 563 SmallVector<unsigned, 8> SubIndexes; 564 565 // Abort if we cannot possibly implement the COPY with the given indexes. 566 if (!TRI.getCoveringSubRegIndexes(MRI, RC, LaneMask, SubIndexes)) 567 report_fatal_error("Impossible to implement partial COPY"); 568 569 SlotIndex Def; 570 for (unsigned BestIdx : SubIndexes) { 571 Def = buildSingleSubRegCopy(FromReg, ToReg, MBB, InsertBefore, BestIdx, 572 DestLI, Late, Def); 573 } 574 575 BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator(); 576 DestLI.refineSubRanges( 577 Allocator, LaneMask, 578 [Def, &Allocator](LiveInterval::SubRange &SR) { 579 SR.createDeadDef(Def, Allocator); 580 }, 581 Indexes, TRI); 582 583 return Def; 584 } 585 586 VNInfo *SplitEditor::defFromParent(unsigned RegIdx, 587 VNInfo *ParentVNI, 588 SlotIndex UseIdx, 589 MachineBasicBlock &MBB, 590 MachineBasicBlock::iterator I) { 591 SlotIndex Def; 592 LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx)); 593 594 // We may be trying to avoid interference that ends at a deleted instruction, 595 // so always begin RegIdx 0 early and all others late. 596 bool Late = RegIdx != 0; 597 598 // Attempt cheap-as-a-copy rematerialization. 599 unsigned Original = VRM.getOriginal(Edit->get(RegIdx)); 600 LiveInterval &OrigLI = LIS.getInterval(Original); 601 VNInfo *OrigVNI = OrigLI.getVNInfoAt(UseIdx); 602 603 Register Reg = LI->reg(); 604 bool DidRemat = false; 605 if (OrigVNI) { 606 LiveRangeEdit::Remat RM(ParentVNI); 607 RM.OrigMI = LIS.getInstructionFromIndex(OrigVNI->def); 608 if (Edit->canRematerializeAt(RM, OrigVNI, UseIdx, true)) { 609 Def = Edit->rematerializeAt(MBB, I, Reg, RM, TRI, Late); 610 ++NumRemats; 611 DidRemat = true; 612 } 613 } 614 if (!DidRemat) { 615 LaneBitmask LaneMask; 616 if (OrigLI.hasSubRanges()) { 617 LaneMask = LaneBitmask::getNone(); 618 for (LiveInterval::SubRange &S : OrigLI.subranges()) { 619 if (S.liveAt(UseIdx)) 620 LaneMask |= S.LaneMask; 621 } 622 } else { 623 LaneMask = LaneBitmask::getAll(); 624 } 625 626 if (LaneMask.none()) { 627 const MCInstrDesc &Desc = TII.get(TargetOpcode::IMPLICIT_DEF); 628 MachineInstr *ImplicitDef = BuildMI(MBB, I, DebugLoc(), Desc, Reg); 629 SlotIndexes &Indexes = *LIS.getSlotIndexes(); 630 Def = Indexes.insertMachineInstrInMaps(*ImplicitDef, Late).getRegSlot(); 631 } else { 632 ++NumCopies; 633 Def = buildCopy(Edit->getReg(), Reg, LaneMask, MBB, I, Late, RegIdx); 634 } 635 } 636 637 // Define the value in Reg. 638 return defValue(RegIdx, ParentVNI, Def, false); 639 } 640 641 /// Create a new virtual register and live interval. 642 unsigned SplitEditor::openIntv() { 643 // Create the complement as index 0. 644 if (Edit->empty()) 645 Edit->createEmptyInterval(); 646 647 // Create the open interval. 648 OpenIdx = Edit->size(); 649 Edit->createEmptyInterval(); 650 return OpenIdx; 651 } 652 653 void SplitEditor::selectIntv(unsigned Idx) { 654 assert(Idx != 0 && "Cannot select the complement interval"); 655 assert(Idx < Edit->size() && "Can only select previously opened interval"); 656 LLVM_DEBUG(dbgs() << " selectIntv " << OpenIdx << " -> " << Idx << '\n'); 657 OpenIdx = Idx; 658 } 659 660 SlotIndex SplitEditor::enterIntvBefore(SlotIndex Idx) { 661 assert(OpenIdx && "openIntv not called before enterIntvBefore"); 662 LLVM_DEBUG(dbgs() << " enterIntvBefore " << Idx); 663 Idx = Idx.getBaseIndex(); 664 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx); 665 if (!ParentVNI) { 666 LLVM_DEBUG(dbgs() << ": not live\n"); 667 return Idx; 668 } 669 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 670 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 671 assert(MI && "enterIntvBefore called with invalid index"); 672 673 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), MI); 674 return VNI->def; 675 } 676 677 SlotIndex SplitEditor::enterIntvAfter(SlotIndex Idx) { 678 assert(OpenIdx && "openIntv not called before enterIntvAfter"); 679 LLVM_DEBUG(dbgs() << " enterIntvAfter " << Idx); 680 Idx = Idx.getBoundaryIndex(); 681 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx); 682 if (!ParentVNI) { 683 LLVM_DEBUG(dbgs() << ": not live\n"); 684 return Idx; 685 } 686 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 687 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 688 assert(MI && "enterIntvAfter called with invalid index"); 689 690 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), 691 std::next(MachineBasicBlock::iterator(MI))); 692 return VNI->def; 693 } 694 695 SlotIndex SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) { 696 assert(OpenIdx && "openIntv not called before enterIntvAtEnd"); 697 SlotIndex End = LIS.getMBBEndIdx(&MBB); 698 SlotIndex Last = End.getPrevSlot(); 699 LLVM_DEBUG(dbgs() << " enterIntvAtEnd " << printMBBReference(MBB) << ", " 700 << Last); 701 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Last); 702 if (!ParentVNI) { 703 LLVM_DEBUG(dbgs() << ": not live\n"); 704 return End; 705 } 706 SlotIndex LSP = SA.getLastSplitPoint(&MBB); 707 if (LSP < Last) { 708 // It could be that the use after LSP is a def, and thus the ParentVNI 709 // just selected starts at that def. For this case to exist, the def 710 // must be part of a tied def/use pair (as otherwise we'd have split 711 // distinct live ranges into individual live intervals), and thus we 712 // can insert the def into the VNI of the use and the tied def/use 713 // pair can live in the resulting interval. 714 Last = LSP; 715 ParentVNI = Edit->getParent().getVNInfoAt(Last); 716 if (!ParentVNI) { 717 // undef use --> undef tied def 718 LLVM_DEBUG(dbgs() << ": tied use not live\n"); 719 return End; 720 } 721 } 722 723 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id); 724 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Last, MBB, 725 SA.getLastSplitPointIter(&MBB)); 726 RegAssign.insert(VNI->def, End, OpenIdx); 727 LLVM_DEBUG(dump()); 728 return VNI->def; 729 } 730 731 /// useIntv - indicate that all instructions in MBB should use OpenLI. 732 void SplitEditor::useIntv(const MachineBasicBlock &MBB) { 733 useIntv(LIS.getMBBStartIdx(&MBB), LIS.getMBBEndIdx(&MBB)); 734 } 735 736 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) { 737 assert(OpenIdx && "openIntv not called before useIntv"); 738 LLVM_DEBUG(dbgs() << " useIntv [" << Start << ';' << End << "):"); 739 RegAssign.insert(Start, End, OpenIdx); 740 LLVM_DEBUG(dump()); 741 } 742 743 SlotIndex SplitEditor::leaveIntvAfter(SlotIndex Idx) { 744 assert(OpenIdx && "openIntv not called before leaveIntvAfter"); 745 LLVM_DEBUG(dbgs() << " leaveIntvAfter " << Idx); 746 747 // The interval must be live beyond the instruction at Idx. 748 SlotIndex Boundary = Idx.getBoundaryIndex(); 749 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Boundary); 750 if (!ParentVNI) { 751 LLVM_DEBUG(dbgs() << ": not live\n"); 752 return Boundary.getNextSlot(); 753 } 754 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 755 MachineInstr *MI = LIS.getInstructionFromIndex(Boundary); 756 assert(MI && "No instruction at index"); 757 758 // In spill mode, make live ranges as short as possible by inserting the copy 759 // before MI. This is only possible if that instruction doesn't redefine the 760 // value. The inserted COPY is not a kill, and we don't need to recompute 761 // the source live range. The spiller also won't try to hoist this copy. 762 if (SpillMode && !SlotIndex::isSameInstr(ParentVNI->def, Idx) && 763 MI->readsVirtualRegister(Edit->getReg())) { 764 forceRecompute(0, *ParentVNI); 765 defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI); 766 return Idx; 767 } 768 769 VNInfo *VNI = defFromParent(0, ParentVNI, Boundary, *MI->getParent(), 770 std::next(MachineBasicBlock::iterator(MI))); 771 return VNI->def; 772 } 773 774 SlotIndex SplitEditor::leaveIntvBefore(SlotIndex Idx) { 775 assert(OpenIdx && "openIntv not called before leaveIntvBefore"); 776 LLVM_DEBUG(dbgs() << " leaveIntvBefore " << Idx); 777 778 // The interval must be live into the instruction at Idx. 779 Idx = Idx.getBaseIndex(); 780 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx); 781 if (!ParentVNI) { 782 LLVM_DEBUG(dbgs() << ": not live\n"); 783 return Idx.getNextSlot(); 784 } 785 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n'); 786 787 MachineInstr *MI = LIS.getInstructionFromIndex(Idx); 788 assert(MI && "No instruction at index"); 789 VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI); 790 return VNI->def; 791 } 792 793 SlotIndex SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) { 794 assert(OpenIdx && "openIntv not called before leaveIntvAtTop"); 795 SlotIndex Start = LIS.getMBBStartIdx(&MBB); 796 LLVM_DEBUG(dbgs() << " leaveIntvAtTop " << printMBBReference(MBB) << ", " 797 << Start); 798 799 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start); 800 if (!ParentVNI) { 801 LLVM_DEBUG(dbgs() << ": not live\n"); 802 return Start; 803 } 804 805 VNInfo *VNI = defFromParent(0, ParentVNI, Start, MBB, 806 MBB.SkipPHIsLabelsAndDebug(MBB.begin())); 807 RegAssign.insert(Start, VNI->def, OpenIdx); 808 LLVM_DEBUG(dump()); 809 return VNI->def; 810 } 811 812 static bool hasTiedUseOf(MachineInstr &MI, unsigned Reg) { 813 return any_of(MI.defs(), [Reg](const MachineOperand &MO) { 814 return MO.isReg() && MO.isTied() && MO.getReg() == Reg; 815 }); 816 } 817 818 void SplitEditor::overlapIntv(SlotIndex Start, SlotIndex End) { 819 assert(OpenIdx && "openIntv not called before overlapIntv"); 820 const VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start); 821 assert(ParentVNI == Edit->getParent().getVNInfoBefore(End) && 822 "Parent changes value in extended range"); 823 assert(LIS.getMBBFromIndex(Start) == LIS.getMBBFromIndex(End) && 824 "Range cannot span basic blocks"); 825 826 // The complement interval will be extended as needed by LICalc.extend(). 827 if (ParentVNI) 828 forceRecompute(0, *ParentVNI); 829 830 // If the last use is tied to a def, we can't mark it as live for the 831 // interval which includes only the use. That would cause the tied pair 832 // to end up in two different intervals. 833 if (auto *MI = LIS.getInstructionFromIndex(End)) 834 if (hasTiedUseOf(*MI, Edit->getReg())) { 835 LLVM_DEBUG(dbgs() << "skip overlap due to tied def at end\n"); 836 return; 837 } 838 839 LLVM_DEBUG(dbgs() << " overlapIntv [" << Start << ';' << End << "):"); 840 RegAssign.insert(Start, End, OpenIdx); 841 LLVM_DEBUG(dump()); 842 } 843 844 //===----------------------------------------------------------------------===// 845 // Spill modes 846 //===----------------------------------------------------------------------===// 847 848 void SplitEditor::removeBackCopies(SmallVectorImpl<VNInfo*> &Copies) { 849 LiveInterval *LI = &LIS.getInterval(Edit->get(0)); 850 LLVM_DEBUG(dbgs() << "Removing " << Copies.size() << " back-copies.\n"); 851 RegAssignMap::iterator AssignI; 852 AssignI.setMap(RegAssign); 853 854 for (const VNInfo *C : Copies) { 855 SlotIndex Def = C->def; 856 MachineInstr *MI = LIS.getInstructionFromIndex(Def); 857 assert(MI && "No instruction for back-copy"); 858 859 MachineBasicBlock *MBB = MI->getParent(); 860 MachineBasicBlock::iterator MBBI(MI); 861 bool AtBegin; 862 do AtBegin = MBBI == MBB->begin(); 863 while (!AtBegin && (--MBBI)->isDebugOrPseudoInstr()); 864 865 LLVM_DEBUG(dbgs() << "Removing " << Def << '\t' << *MI); 866 LIS.removeVRegDefAt(*LI, Def); 867 LIS.RemoveMachineInstrFromMaps(*MI); 868 MI->eraseFromParent(); 869 870 // Adjust RegAssign if a register assignment is killed at Def. We want to 871 // avoid calculating the live range of the source register if possible. 872 AssignI.find(Def.getPrevSlot()); 873 if (!AssignI.valid() || AssignI.start() >= Def) 874 continue; 875 // If MI doesn't kill the assigned register, just leave it. 876 if (AssignI.stop() != Def) 877 continue; 878 unsigned RegIdx = AssignI.value(); 879 // We could hoist back-copy right after another back-copy. As a result 880 // MMBI points to copy instruction which is actually dead now. 881 // We cannot set its stop to MBBI which will be the same as start and 882 // interval does not support that. 883 SlotIndex Kill = 884 AtBegin ? SlotIndex() : LIS.getInstructionIndex(*MBBI).getRegSlot(); 885 if (AtBegin || !MBBI->readsVirtualRegister(Edit->getReg()) || 886 Kill <= AssignI.start()) { 887 LLVM_DEBUG(dbgs() << " cannot find simple kill of RegIdx " << RegIdx 888 << '\n'); 889 forceRecompute(RegIdx, *Edit->getParent().getVNInfoAt(Def)); 890 } else { 891 LLVM_DEBUG(dbgs() << " move kill to " << Kill << '\t' << *MBBI); 892 AssignI.setStop(Kill); 893 } 894 } 895 } 896 897 MachineBasicBlock* 898 SplitEditor::findShallowDominator(MachineBasicBlock *MBB, 899 MachineBasicBlock *DefMBB) { 900 if (MBB == DefMBB) 901 return MBB; 902 assert(MDT.dominates(DefMBB, MBB) && "MBB must be dominated by the def."); 903 904 const MachineLoopInfo &Loops = SA.Loops; 905 const MachineLoop *DefLoop = Loops.getLoopFor(DefMBB); 906 MachineDomTreeNode *DefDomNode = MDT[DefMBB]; 907 908 // Best candidate so far. 909 MachineBasicBlock *BestMBB = MBB; 910 unsigned BestDepth = std::numeric_limits<unsigned>::max(); 911 912 while (true) { 913 const MachineLoop *Loop = Loops.getLoopFor(MBB); 914 915 // MBB isn't in a loop, it doesn't get any better. All dominators have a 916 // higher frequency by definition. 917 if (!Loop) { 918 LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB) 919 << " dominates " << printMBBReference(*MBB) 920 << " at depth 0\n"); 921 return MBB; 922 } 923 924 // We'll never be able to exit the DefLoop. 925 if (Loop == DefLoop) { 926 LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB) 927 << " dominates " << printMBBReference(*MBB) 928 << " in the same loop\n"); 929 return MBB; 930 } 931 932 // Least busy dominator seen so far. 933 unsigned Depth = Loop->getLoopDepth(); 934 if (Depth < BestDepth) { 935 BestMBB = MBB; 936 BestDepth = Depth; 937 LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB) 938 << " dominates " << printMBBReference(*MBB) 939 << " at depth " << Depth << '\n'); 940 } 941 942 // Leave loop by going to the immediate dominator of the loop header. 943 // This is a bigger stride than simply walking up the dominator tree. 944 MachineDomTreeNode *IDom = MDT[Loop->getHeader()]->getIDom(); 945 946 // Too far up the dominator tree? 947 if (!IDom || !MDT.dominates(DefDomNode, IDom)) 948 return BestMBB; 949 950 MBB = IDom->getBlock(); 951 } 952 } 953 954 void SplitEditor::computeRedundantBackCopies( 955 DenseSet<unsigned> &NotToHoistSet, SmallVectorImpl<VNInfo *> &BackCopies) { 956 LiveInterval *LI = &LIS.getInterval(Edit->get(0)); 957 LiveInterval *Parent = &Edit->getParent(); 958 SmallVector<SmallPtrSet<VNInfo *, 8>, 8> EqualVNs(Parent->getNumValNums()); 959 SmallPtrSet<VNInfo *, 8> DominatedVNIs; 960 961 // Aggregate VNIs having the same value as ParentVNI. 962 for (VNInfo *VNI : LI->valnos) { 963 if (VNI->isUnused()) 964 continue; 965 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def); 966 EqualVNs[ParentVNI->id].insert(VNI); 967 } 968 969 // For VNI aggregation of each ParentVNI, collect dominated, i.e., 970 // redundant VNIs to BackCopies. 971 for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) { 972 VNInfo *ParentVNI = Parent->getValNumInfo(i); 973 if (!NotToHoistSet.count(ParentVNI->id)) 974 continue; 975 SmallPtrSetIterator<VNInfo *> It1 = EqualVNs[ParentVNI->id].begin(); 976 SmallPtrSetIterator<VNInfo *> It2 = It1; 977 for (; It1 != EqualVNs[ParentVNI->id].end(); ++It1) { 978 It2 = It1; 979 for (++It2; It2 != EqualVNs[ParentVNI->id].end(); ++It2) { 980 if (DominatedVNIs.count(*It1) || DominatedVNIs.count(*It2)) 981 continue; 982 983 MachineBasicBlock *MBB1 = LIS.getMBBFromIndex((*It1)->def); 984 MachineBasicBlock *MBB2 = LIS.getMBBFromIndex((*It2)->def); 985 if (MBB1 == MBB2) { 986 DominatedVNIs.insert((*It1)->def < (*It2)->def ? (*It2) : (*It1)); 987 } else if (MDT.dominates(MBB1, MBB2)) { 988 DominatedVNIs.insert(*It2); 989 } else if (MDT.dominates(MBB2, MBB1)) { 990 DominatedVNIs.insert(*It1); 991 } 992 } 993 } 994 if (!DominatedVNIs.empty()) { 995 forceRecompute(0, *ParentVNI); 996 append_range(BackCopies, DominatedVNIs); 997 DominatedVNIs.clear(); 998 } 999 } 1000 } 1001 1002 /// For SM_Size mode, find a common dominator for all the back-copies for 1003 /// the same ParentVNI and hoist the backcopies to the dominator BB. 1004 /// For SM_Speed mode, if the common dominator is hot and it is not beneficial 1005 /// to do the hoisting, simply remove the dominated backcopies for the same 1006 /// ParentVNI. 1007 void SplitEditor::hoistCopies() { 1008 // Get the complement interval, always RegIdx 0. 1009 LiveInterval *LI = &LIS.getInterval(Edit->get(0)); 1010 LiveInterval *Parent = &Edit->getParent(); 1011 1012 // Track the nearest common dominator for all back-copies for each ParentVNI, 1013 // indexed by ParentVNI->id. 1014 using DomPair = std::pair<MachineBasicBlock *, SlotIndex>; 1015 SmallVector<DomPair, 8> NearestDom(Parent->getNumValNums()); 1016 // The total cost of all the back-copies for each ParentVNI. 1017 SmallVector<BlockFrequency, 8> Costs(Parent->getNumValNums()); 1018 // The ParentVNI->id set for which hoisting back-copies are not beneficial 1019 // for Speed. 1020 DenseSet<unsigned> NotToHoistSet; 1021 1022 // Find the nearest common dominator for parent values with multiple 1023 // back-copies. If a single back-copy dominates, put it in DomPair.second. 1024 for (VNInfo *VNI : LI->valnos) { 1025 if (VNI->isUnused()) 1026 continue; 1027 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def); 1028 assert(ParentVNI && "Parent not live at complement def"); 1029 1030 // Don't hoist remats. The complement is probably going to disappear 1031 // completely anyway. 1032 if (Edit->didRematerialize(ParentVNI)) 1033 continue; 1034 1035 MachineBasicBlock *ValMBB = LIS.getMBBFromIndex(VNI->def); 1036 1037 DomPair &Dom = NearestDom[ParentVNI->id]; 1038 1039 // Keep directly defined parent values. This is either a PHI or an 1040 // instruction in the complement range. All other copies of ParentVNI 1041 // should be eliminated. 1042 if (VNI->def == ParentVNI->def) { 1043 LLVM_DEBUG(dbgs() << "Direct complement def at " << VNI->def << '\n'); 1044 Dom = DomPair(ValMBB, VNI->def); 1045 continue; 1046 } 1047 // Skip the singly mapped values. There is nothing to gain from hoisting a 1048 // single back-copy. 1049 if (Values.lookup(std::make_pair(0, ParentVNI->id)).getPointer()) { 1050 LLVM_DEBUG(dbgs() << "Single complement def at " << VNI->def << '\n'); 1051 continue; 1052 } 1053 1054 if (!Dom.first) { 1055 // First time we see ParentVNI. VNI dominates itself. 1056 Dom = DomPair(ValMBB, VNI->def); 1057 } else if (Dom.first == ValMBB) { 1058 // Two defs in the same block. Pick the earlier def. 1059 if (!Dom.second.isValid() || VNI->def < Dom.second) 1060 Dom.second = VNI->def; 1061 } else { 1062 // Different basic blocks. Check if one dominates. 1063 MachineBasicBlock *Near = 1064 MDT.findNearestCommonDominator(Dom.first, ValMBB); 1065 if (Near == ValMBB) 1066 // Def ValMBB dominates. 1067 Dom = DomPair(ValMBB, VNI->def); 1068 else if (Near != Dom.first) 1069 // None dominate. Hoist to common dominator, need new def. 1070 Dom = DomPair(Near, SlotIndex()); 1071 Costs[ParentVNI->id] += MBFI.getBlockFreq(ValMBB); 1072 } 1073 1074 LLVM_DEBUG(dbgs() << "Multi-mapped complement " << VNI->id << '@' 1075 << VNI->def << " for parent " << ParentVNI->id << '@' 1076 << ParentVNI->def << " hoist to " 1077 << printMBBReference(*Dom.first) << ' ' << Dom.second 1078 << '\n'); 1079 } 1080 1081 // Insert the hoisted copies. 1082 for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) { 1083 DomPair &Dom = NearestDom[i]; 1084 if (!Dom.first || Dom.second.isValid()) 1085 continue; 1086 // This value needs a hoisted copy inserted at the end of Dom.first. 1087 VNInfo *ParentVNI = Parent->getValNumInfo(i); 1088 MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(ParentVNI->def); 1089 // Get a less loopy dominator than Dom.first. 1090 Dom.first = findShallowDominator(Dom.first, DefMBB); 1091 if (SpillMode == SM_Speed && 1092 MBFI.getBlockFreq(Dom.first) > Costs[ParentVNI->id]) { 1093 NotToHoistSet.insert(ParentVNI->id); 1094 continue; 1095 } 1096 SlotIndex LSP = SA.getLastSplitPoint(Dom.first); 1097 if (LSP <= ParentVNI->def) { 1098 NotToHoistSet.insert(ParentVNI->id); 1099 continue; 1100 } 1101 Dom.second = defFromParent(0, ParentVNI, LSP, *Dom.first, 1102 SA.getLastSplitPointIter(Dom.first))->def; 1103 } 1104 1105 // Remove redundant back-copies that are now known to be dominated by another 1106 // def with the same value. 1107 SmallVector<VNInfo*, 8> BackCopies; 1108 for (VNInfo *VNI : LI->valnos) { 1109 if (VNI->isUnused()) 1110 continue; 1111 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def); 1112 const DomPair &Dom = NearestDom[ParentVNI->id]; 1113 if (!Dom.first || Dom.second == VNI->def || 1114 NotToHoistSet.count(ParentVNI->id)) 1115 continue; 1116 BackCopies.push_back(VNI); 1117 forceRecompute(0, *ParentVNI); 1118 } 1119 1120 // If it is not beneficial to hoist all the BackCopies, simply remove 1121 // redundant BackCopies in speed mode. 1122 if (SpillMode == SM_Speed && !NotToHoistSet.empty()) 1123 computeRedundantBackCopies(NotToHoistSet, BackCopies); 1124 1125 removeBackCopies(BackCopies); 1126 } 1127 1128 /// transferValues - Transfer all possible values to the new live ranges. 1129 /// Values that were rematerialized are left alone, they need LICalc.extend(). 1130 bool SplitEditor::transferValues() { 1131 bool Skipped = false; 1132 RegAssignMap::const_iterator AssignI = RegAssign.begin(); 1133 for (const LiveRange::Segment &S : Edit->getParent()) { 1134 LLVM_DEBUG(dbgs() << " blit " << S << ':'); 1135 VNInfo *ParentVNI = S.valno; 1136 // RegAssign has holes where RegIdx 0 should be used. 1137 SlotIndex Start = S.start; 1138 AssignI.advanceTo(Start); 1139 do { 1140 unsigned RegIdx; 1141 SlotIndex End = S.end; 1142 if (!AssignI.valid()) { 1143 RegIdx = 0; 1144 } else if (AssignI.start() <= Start) { 1145 RegIdx = AssignI.value(); 1146 if (AssignI.stop() < End) { 1147 End = AssignI.stop(); 1148 ++AssignI; 1149 } 1150 } else { 1151 RegIdx = 0; 1152 End = std::min(End, AssignI.start()); 1153 } 1154 1155 // The interval [Start;End) is continuously mapped to RegIdx, ParentVNI. 1156 LLVM_DEBUG(dbgs() << " [" << Start << ';' << End << ")=" << RegIdx << '(' 1157 << printReg(Edit->get(RegIdx)) << ')'); 1158 LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx)); 1159 1160 // Check for a simply defined value that can be blitted directly. 1161 ValueForcePair VFP = Values.lookup(std::make_pair(RegIdx, ParentVNI->id)); 1162 if (VNInfo *VNI = VFP.getPointer()) { 1163 LLVM_DEBUG(dbgs() << ':' << VNI->id); 1164 LI.addSegment(LiveInterval::Segment(Start, End, VNI)); 1165 Start = End; 1166 continue; 1167 } 1168 1169 // Skip values with forced recomputation. 1170 if (VFP.getInt()) { 1171 LLVM_DEBUG(dbgs() << "(recalc)"); 1172 Skipped = true; 1173 Start = End; 1174 continue; 1175 } 1176 1177 LiveIntervalCalc &LIC = getLICalc(RegIdx); 1178 1179 // This value has multiple defs in RegIdx, but it wasn't rematerialized, 1180 // so the live range is accurate. Add live-in blocks in [Start;End) to the 1181 // LiveInBlocks. 1182 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator(); 1183 SlotIndex BlockStart, BlockEnd; 1184 std::tie(BlockStart, BlockEnd) = LIS.getSlotIndexes()->getMBBRange(&*MBB); 1185 1186 // The first block may be live-in, or it may have its own def. 1187 if (Start != BlockStart) { 1188 VNInfo *VNI = LI.extendInBlock(BlockStart, std::min(BlockEnd, End)); 1189 assert(VNI && "Missing def for complex mapped value"); 1190 LLVM_DEBUG(dbgs() << ':' << VNI->id << "*" << printMBBReference(*MBB)); 1191 // MBB has its own def. Is it also live-out? 1192 if (BlockEnd <= End) 1193 LIC.setLiveOutValue(&*MBB, VNI); 1194 1195 // Skip to the next block for live-in. 1196 ++MBB; 1197 BlockStart = BlockEnd; 1198 } 1199 1200 // Handle the live-in blocks covered by [Start;End). 1201 assert(Start <= BlockStart && "Expected live-in block"); 1202 while (BlockStart < End) { 1203 LLVM_DEBUG(dbgs() << ">" << printMBBReference(*MBB)); 1204 BlockEnd = LIS.getMBBEndIdx(&*MBB); 1205 if (BlockStart == ParentVNI->def) { 1206 // This block has the def of a parent PHI, so it isn't live-in. 1207 assert(ParentVNI->isPHIDef() && "Non-phi defined at block start?"); 1208 VNInfo *VNI = LI.extendInBlock(BlockStart, std::min(BlockEnd, End)); 1209 assert(VNI && "Missing def for complex mapped parent PHI"); 1210 if (End >= BlockEnd) 1211 LIC.setLiveOutValue(&*MBB, VNI); // Live-out as well. 1212 } else { 1213 // This block needs a live-in value. The last block covered may not 1214 // be live-out. 1215 if (End < BlockEnd) 1216 LIC.addLiveInBlock(LI, MDT[&*MBB], End); 1217 else { 1218 // Live-through, and we don't know the value. 1219 LIC.addLiveInBlock(LI, MDT[&*MBB]); 1220 LIC.setLiveOutValue(&*MBB, nullptr); 1221 } 1222 } 1223 BlockStart = BlockEnd; 1224 ++MBB; 1225 } 1226 Start = End; 1227 } while (Start != S.end); 1228 LLVM_DEBUG(dbgs() << '\n'); 1229 } 1230 1231 LICalc[0].calculateValues(); 1232 if (SpillMode) 1233 LICalc[1].calculateValues(); 1234 1235 return Skipped; 1236 } 1237 1238 static bool removeDeadSegment(SlotIndex Def, LiveRange &LR) { 1239 const LiveRange::Segment *Seg = LR.getSegmentContaining(Def); 1240 if (Seg == nullptr) 1241 return true; 1242 if (Seg->end != Def.getDeadSlot()) 1243 return false; 1244 // This is a dead PHI. Remove it. 1245 LR.removeSegment(*Seg, true); 1246 return true; 1247 } 1248 1249 void SplitEditor::extendPHIRange(MachineBasicBlock &B, LiveIntervalCalc &LIC, 1250 LiveRange &LR, LaneBitmask LM, 1251 ArrayRef<SlotIndex> Undefs) { 1252 for (MachineBasicBlock *P : B.predecessors()) { 1253 SlotIndex End = LIS.getMBBEndIdx(P); 1254 SlotIndex LastUse = End.getPrevSlot(); 1255 // The predecessor may not have a live-out value. That is OK, like an 1256 // undef PHI operand. 1257 LiveInterval &PLI = Edit->getParent(); 1258 // Need the cast because the inputs to ?: would otherwise be deemed 1259 // "incompatible": SubRange vs LiveInterval. 1260 LiveRange &PSR = !LM.all() ? getSubRangeForMaskExact(LM, PLI) 1261 : static_cast<LiveRange &>(PLI); 1262 if (PSR.liveAt(LastUse)) 1263 LIC.extend(LR, End, /*PhysReg=*/0, Undefs); 1264 } 1265 } 1266 1267 void SplitEditor::extendPHIKillRanges() { 1268 // Extend live ranges to be live-out for successor PHI values. 1269 1270 // Visit each PHI def slot in the parent live interval. If the def is dead, 1271 // remove it. Otherwise, extend the live interval to reach the end indexes 1272 // of all predecessor blocks. 1273 1274 LiveInterval &ParentLI = Edit->getParent(); 1275 for (const VNInfo *V : ParentLI.valnos) { 1276 if (V->isUnused() || !V->isPHIDef()) 1277 continue; 1278 1279 unsigned RegIdx = RegAssign.lookup(V->def); 1280 LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx)); 1281 LiveIntervalCalc &LIC = getLICalc(RegIdx); 1282 MachineBasicBlock &B = *LIS.getMBBFromIndex(V->def); 1283 if (!removeDeadSegment(V->def, LI)) 1284 extendPHIRange(B, LIC, LI, LaneBitmask::getAll(), /*Undefs=*/{}); 1285 } 1286 1287 SmallVector<SlotIndex, 4> Undefs; 1288 LiveIntervalCalc SubLIC; 1289 1290 for (LiveInterval::SubRange &PS : ParentLI.subranges()) { 1291 for (const VNInfo *V : PS.valnos) { 1292 if (V->isUnused() || !V->isPHIDef()) 1293 continue; 1294 unsigned RegIdx = RegAssign.lookup(V->def); 1295 LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx)); 1296 LiveInterval::SubRange &S = getSubRangeForMaskExact(PS.LaneMask, LI); 1297 if (removeDeadSegment(V->def, S)) 1298 continue; 1299 1300 MachineBasicBlock &B = *LIS.getMBBFromIndex(V->def); 1301 SubLIC.reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT, 1302 &LIS.getVNInfoAllocator()); 1303 Undefs.clear(); 1304 LI.computeSubRangeUndefs(Undefs, PS.LaneMask, MRI, *LIS.getSlotIndexes()); 1305 extendPHIRange(B, SubLIC, S, PS.LaneMask, Undefs); 1306 } 1307 } 1308 } 1309 1310 /// rewriteAssigned - Rewrite all uses of Edit->getReg(). 1311 void SplitEditor::rewriteAssigned(bool ExtendRanges) { 1312 struct ExtPoint { 1313 ExtPoint(const MachineOperand &O, unsigned R, SlotIndex N) 1314 : MO(O), RegIdx(R), Next(N) {} 1315 1316 MachineOperand MO; 1317 unsigned RegIdx; 1318 SlotIndex Next; 1319 }; 1320 1321 SmallVector<ExtPoint,4> ExtPoints; 1322 1323 for (MachineOperand &MO : 1324 llvm::make_early_inc_range(MRI.reg_operands(Edit->getReg()))) { 1325 MachineInstr *MI = MO.getParent(); 1326 // LiveDebugVariables should have handled all DBG_VALUE instructions. 1327 if (MI->isDebugValue()) { 1328 LLVM_DEBUG(dbgs() << "Zapping " << *MI); 1329 MO.setReg(0); 1330 continue; 1331 } 1332 1333 // <undef> operands don't really read the register, so it doesn't matter 1334 // which register we choose. When the use operand is tied to a def, we must 1335 // use the same register as the def, so just do that always. 1336 SlotIndex Idx = LIS.getInstructionIndex(*MI); 1337 if (MO.isDef() || MO.isUndef()) 1338 Idx = Idx.getRegSlot(MO.isEarlyClobber()); 1339 1340 // Rewrite to the mapped register at Idx. 1341 unsigned RegIdx = RegAssign.lookup(Idx); 1342 LiveInterval &LI = LIS.getInterval(Edit->get(RegIdx)); 1343 MO.setReg(LI.reg()); 1344 LLVM_DEBUG(dbgs() << " rewr " << printMBBReference(*MI->getParent()) 1345 << '\t' << Idx << ':' << RegIdx << '\t' << *MI); 1346 1347 // Extend liveness to Idx if the instruction reads reg. 1348 if (!ExtendRanges || MO.isUndef()) 1349 continue; 1350 1351 // Skip instructions that don't read Reg. 1352 if (MO.isDef()) { 1353 if (!MO.getSubReg() && !MO.isEarlyClobber()) 1354 continue; 1355 // We may want to extend a live range for a partial redef, or for a use 1356 // tied to an early clobber. 1357 Idx = Idx.getPrevSlot(); 1358 if (!Edit->getParent().liveAt(Idx)) 1359 continue; 1360 } else 1361 Idx = Idx.getRegSlot(true); 1362 1363 SlotIndex Next = Idx.getNextSlot(); 1364 if (LI.hasSubRanges()) { 1365 // We have to delay extending subranges until we have seen all operands 1366 // defining the register. This is because a <def,read-undef> operand 1367 // will create an "undef" point, and we cannot extend any subranges 1368 // until all of them have been accounted for. 1369 if (MO.isUse()) 1370 ExtPoints.push_back(ExtPoint(MO, RegIdx, Next)); 1371 } else { 1372 LiveIntervalCalc &LIC = getLICalc(RegIdx); 1373 LIC.extend(LI, Next, 0, ArrayRef<SlotIndex>()); 1374 } 1375 } 1376 1377 for (ExtPoint &EP : ExtPoints) { 1378 LiveInterval &LI = LIS.getInterval(Edit->get(EP.RegIdx)); 1379 assert(LI.hasSubRanges()); 1380 1381 LiveIntervalCalc SubLIC; 1382 Register Reg = EP.MO.getReg(), Sub = EP.MO.getSubReg(); 1383 LaneBitmask LM = Sub != 0 ? TRI.getSubRegIndexLaneMask(Sub) 1384 : MRI.getMaxLaneMaskForVReg(Reg); 1385 for (LiveInterval::SubRange &S : LI.subranges()) { 1386 if ((S.LaneMask & LM).none()) 1387 continue; 1388 // The problem here can be that the new register may have been created 1389 // for a partially defined original register. For example: 1390 // %0:subreg_hireg<def,read-undef> = ... 1391 // ... 1392 // %1 = COPY %0 1393 if (S.empty()) 1394 continue; 1395 SubLIC.reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT, 1396 &LIS.getVNInfoAllocator()); 1397 SmallVector<SlotIndex, 4> Undefs; 1398 LI.computeSubRangeUndefs(Undefs, S.LaneMask, MRI, *LIS.getSlotIndexes()); 1399 SubLIC.extend(S, EP.Next, 0, Undefs); 1400 } 1401 } 1402 1403 for (Register R : *Edit) { 1404 LiveInterval &LI = LIS.getInterval(R); 1405 if (!LI.hasSubRanges()) 1406 continue; 1407 LI.clear(); 1408 LI.removeEmptySubRanges(); 1409 LIS.constructMainRangeFromSubranges(LI); 1410 } 1411 } 1412 1413 void SplitEditor::deleteRematVictims() { 1414 SmallVector<MachineInstr*, 8> Dead; 1415 for (const Register &R : *Edit) { 1416 LiveInterval *LI = &LIS.getInterval(R); 1417 for (const LiveRange::Segment &S : LI->segments) { 1418 // Dead defs end at the dead slot. 1419 if (S.end != S.valno->def.getDeadSlot()) 1420 continue; 1421 if (S.valno->isPHIDef()) 1422 continue; 1423 MachineInstr *MI = LIS.getInstructionFromIndex(S.valno->def); 1424 assert(MI && "Missing instruction for dead def"); 1425 MI->addRegisterDead(LI->reg(), &TRI); 1426 1427 if (!MI->allDefsAreDead()) 1428 continue; 1429 1430 LLVM_DEBUG(dbgs() << "All defs dead: " << *MI); 1431 Dead.push_back(MI); 1432 } 1433 } 1434 1435 if (Dead.empty()) 1436 return; 1437 1438 Edit->eliminateDeadDefs(Dead, None, &AA); 1439 } 1440 1441 void SplitEditor::forceRecomputeVNI(const VNInfo &ParentVNI) { 1442 // Fast-path for common case. 1443 if (!ParentVNI.isPHIDef()) { 1444 for (unsigned I = 0, E = Edit->size(); I != E; ++I) 1445 forceRecompute(I, ParentVNI); 1446 return; 1447 } 1448 1449 // Trace value through phis. 1450 SmallPtrSet<const VNInfo *, 8> Visited; ///< whether VNI was/is in worklist. 1451 SmallVector<const VNInfo *, 4> WorkList; 1452 Visited.insert(&ParentVNI); 1453 WorkList.push_back(&ParentVNI); 1454 1455 const LiveInterval &ParentLI = Edit->getParent(); 1456 const SlotIndexes &Indexes = *LIS.getSlotIndexes(); 1457 do { 1458 const VNInfo &VNI = *WorkList.back(); 1459 WorkList.pop_back(); 1460 for (unsigned I = 0, E = Edit->size(); I != E; ++I) 1461 forceRecompute(I, VNI); 1462 if (!VNI.isPHIDef()) 1463 continue; 1464 1465 MachineBasicBlock &MBB = *Indexes.getMBBFromIndex(VNI.def); 1466 for (const MachineBasicBlock *Pred : MBB.predecessors()) { 1467 SlotIndex PredEnd = Indexes.getMBBEndIdx(Pred); 1468 VNInfo *PredVNI = ParentLI.getVNInfoBefore(PredEnd); 1469 assert(PredVNI && "Value available in PhiVNI predecessor"); 1470 if (Visited.insert(PredVNI).second) 1471 WorkList.push_back(PredVNI); 1472 } 1473 } while(!WorkList.empty()); 1474 } 1475 1476 void SplitEditor::finish(SmallVectorImpl<unsigned> *LRMap) { 1477 ++NumFinished; 1478 1479 // At this point, the live intervals in Edit contain VNInfos corresponding to 1480 // the inserted copies. 1481 1482 // Add the original defs from the parent interval. 1483 for (const VNInfo *ParentVNI : Edit->getParent().valnos) { 1484 if (ParentVNI->isUnused()) 1485 continue; 1486 unsigned RegIdx = RegAssign.lookup(ParentVNI->def); 1487 defValue(RegIdx, ParentVNI, ParentVNI->def, true); 1488 1489 // Force rematted values to be recomputed everywhere. 1490 // The new live ranges may be truncated. 1491 if (Edit->didRematerialize(ParentVNI)) 1492 forceRecomputeVNI(*ParentVNI); 1493 } 1494 1495 // Hoist back-copies to the complement interval when in spill mode. 1496 switch (SpillMode) { 1497 case SM_Partition: 1498 // Leave all back-copies as is. 1499 break; 1500 case SM_Size: 1501 case SM_Speed: 1502 // hoistCopies will behave differently between size and speed. 1503 hoistCopies(); 1504 } 1505 1506 // Transfer the simply mapped values, check if any are skipped. 1507 bool Skipped = transferValues(); 1508 1509 // Rewrite virtual registers, possibly extending ranges. 1510 rewriteAssigned(Skipped); 1511 1512 if (Skipped) 1513 extendPHIKillRanges(); 1514 else 1515 ++NumSimple; 1516 1517 // Delete defs that were rematted everywhere. 1518 if (Skipped) 1519 deleteRematVictims(); 1520 1521 // Get rid of unused values and set phi-kill flags. 1522 for (Register Reg : *Edit) { 1523 LiveInterval &LI = LIS.getInterval(Reg); 1524 LI.removeEmptySubRanges(); 1525 LI.RenumberValues(); 1526 } 1527 1528 // Provide a reverse mapping from original indices to Edit ranges. 1529 if (LRMap) { 1530 LRMap->clear(); 1531 for (unsigned i = 0, e = Edit->size(); i != e; ++i) 1532 LRMap->push_back(i); 1533 } 1534 1535 // Now check if any registers were separated into multiple components. 1536 ConnectedVNInfoEqClasses ConEQ(LIS); 1537 for (unsigned i = 0, e = Edit->size(); i != e; ++i) { 1538 // Don't use iterators, they are invalidated by create() below. 1539 Register VReg = Edit->get(i); 1540 LiveInterval &LI = LIS.getInterval(VReg); 1541 SmallVector<LiveInterval*, 8> SplitLIs; 1542 LIS.splitSeparateComponents(LI, SplitLIs); 1543 Register Original = VRM.getOriginal(VReg); 1544 for (LiveInterval *SplitLI : SplitLIs) 1545 VRM.setIsSplitFromReg(SplitLI->reg(), Original); 1546 1547 // The new intervals all map back to i. 1548 if (LRMap) 1549 LRMap->resize(Edit->size(), i); 1550 } 1551 1552 // Calculate spill weight and allocation hints for new intervals. 1553 Edit->calculateRegClassAndHint(VRM.getMachineFunction(), VRAI); 1554 1555 assert(!LRMap || LRMap->size() == Edit->size()); 1556 } 1557 1558 //===----------------------------------------------------------------------===// 1559 // Single Block Splitting 1560 //===----------------------------------------------------------------------===// 1561 1562 bool SplitAnalysis::shouldSplitSingleBlock(const BlockInfo &BI, 1563 bool SingleInstrs) const { 1564 // Always split for multiple instructions. 1565 if (!BI.isOneInstr()) 1566 return true; 1567 // Don't split for single instructions unless explicitly requested. 1568 if (!SingleInstrs) 1569 return false; 1570 // Splitting a live-through range always makes progress. 1571 if (BI.LiveIn && BI.LiveOut) 1572 return true; 1573 // No point in isolating a copy. It has no register class constraints. 1574 if (LIS.getInstructionFromIndex(BI.FirstInstr)->isCopyLike()) 1575 return false; 1576 // Finally, don't isolate an end point that was created by earlier splits. 1577 return isOriginalEndpoint(BI.FirstInstr); 1578 } 1579 1580 void SplitEditor::splitSingleBlock(const SplitAnalysis::BlockInfo &BI) { 1581 openIntv(); 1582 SlotIndex LastSplitPoint = SA.getLastSplitPoint(BI.MBB); 1583 SlotIndex SegStart = enterIntvBefore(std::min(BI.FirstInstr, 1584 LastSplitPoint)); 1585 if (!BI.LiveOut || BI.LastInstr < LastSplitPoint) { 1586 useIntv(SegStart, leaveIntvAfter(BI.LastInstr)); 1587 } else { 1588 // The last use is after the last valid split point. 1589 SlotIndex SegStop = leaveIntvBefore(LastSplitPoint); 1590 useIntv(SegStart, SegStop); 1591 overlapIntv(SegStop, BI.LastInstr); 1592 } 1593 } 1594 1595 //===----------------------------------------------------------------------===// 1596 // Global Live Range Splitting Support 1597 //===----------------------------------------------------------------------===// 1598 1599 // These methods support a method of global live range splitting that uses a 1600 // global algorithm to decide intervals for CFG edges. They will insert split 1601 // points and color intervals in basic blocks while avoiding interference. 1602 // 1603 // Note that splitSingleBlock is also useful for blocks where both CFG edges 1604 // are on the stack. 1605 1606 void SplitEditor::splitLiveThroughBlock(unsigned MBBNum, 1607 unsigned IntvIn, SlotIndex LeaveBefore, 1608 unsigned IntvOut, SlotIndex EnterAfter){ 1609 SlotIndex Start, Stop; 1610 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(MBBNum); 1611 1612 LLVM_DEBUG(dbgs() << "%bb." << MBBNum << " [" << Start << ';' << Stop 1613 << ") intf " << LeaveBefore << '-' << EnterAfter 1614 << ", live-through " << IntvIn << " -> " << IntvOut); 1615 1616 assert((IntvIn || IntvOut) && "Use splitSingleBlock for isolated blocks"); 1617 1618 assert((!LeaveBefore || LeaveBefore < Stop) && "Interference after block"); 1619 assert((!IntvIn || !LeaveBefore || LeaveBefore > Start) && "Impossible intf"); 1620 assert((!EnterAfter || EnterAfter >= Start) && "Interference before block"); 1621 1622 MachineBasicBlock *MBB = VRM.getMachineFunction().getBlockNumbered(MBBNum); 1623 1624 if (!IntvOut) { 1625 LLVM_DEBUG(dbgs() << ", spill on entry.\n"); 1626 // 1627 // <<<<<<<<< Possible LeaveBefore interference. 1628 // |-----------| Live through. 1629 // -____________ Spill on entry. 1630 // 1631 selectIntv(IntvIn); 1632 SlotIndex Idx = leaveIntvAtTop(*MBB); 1633 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1634 (void)Idx; 1635 return; 1636 } 1637 1638 if (!IntvIn) { 1639 LLVM_DEBUG(dbgs() << ", reload on exit.\n"); 1640 // 1641 // >>>>>>> Possible EnterAfter interference. 1642 // |-----------| Live through. 1643 // ___________-- Reload on exit. 1644 // 1645 selectIntv(IntvOut); 1646 SlotIndex Idx = enterIntvAtEnd(*MBB); 1647 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1648 (void)Idx; 1649 return; 1650 } 1651 1652 if (IntvIn == IntvOut && !LeaveBefore && !EnterAfter) { 1653 LLVM_DEBUG(dbgs() << ", straight through.\n"); 1654 // 1655 // |-----------| Live through. 1656 // ------------- Straight through, same intv, no interference. 1657 // 1658 selectIntv(IntvOut); 1659 useIntv(Start, Stop); 1660 return; 1661 } 1662 1663 // We cannot legally insert splits after LSP. 1664 SlotIndex LSP = SA.getLastSplitPoint(MBBNum); 1665 assert((!IntvOut || !EnterAfter || EnterAfter < LSP) && "Impossible intf"); 1666 1667 if (IntvIn != IntvOut && (!LeaveBefore || !EnterAfter || 1668 LeaveBefore.getBaseIndex() > EnterAfter.getBoundaryIndex())) { 1669 LLVM_DEBUG(dbgs() << ", switch avoiding interference.\n"); 1670 // 1671 // >>>> <<<< Non-overlapping EnterAfter/LeaveBefore interference. 1672 // |-----------| Live through. 1673 // ------======= Switch intervals between interference. 1674 // 1675 selectIntv(IntvOut); 1676 SlotIndex Idx; 1677 if (LeaveBefore && LeaveBefore < LSP) { 1678 Idx = enterIntvBefore(LeaveBefore); 1679 useIntv(Idx, Stop); 1680 } else { 1681 Idx = enterIntvAtEnd(*MBB); 1682 } 1683 selectIntv(IntvIn); 1684 useIntv(Start, Idx); 1685 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1686 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1687 return; 1688 } 1689 1690 LLVM_DEBUG(dbgs() << ", create local intv for interference.\n"); 1691 // 1692 // >>><><><><<<< Overlapping EnterAfter/LeaveBefore interference. 1693 // |-----------| Live through. 1694 // ==---------== Switch intervals before/after interference. 1695 // 1696 assert(LeaveBefore <= EnterAfter && "Missed case"); 1697 1698 selectIntv(IntvOut); 1699 SlotIndex Idx = enterIntvAfter(EnterAfter); 1700 useIntv(Idx, Stop); 1701 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1702 1703 selectIntv(IntvIn); 1704 Idx = leaveIntvBefore(LeaveBefore); 1705 useIntv(Start, Idx); 1706 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1707 } 1708 1709 void SplitEditor::splitRegInBlock(const SplitAnalysis::BlockInfo &BI, 1710 unsigned IntvIn, SlotIndex LeaveBefore) { 1711 SlotIndex Start, Stop; 1712 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB); 1713 1714 LLVM_DEBUG(dbgs() << printMBBReference(*BI.MBB) << " [" << Start << ';' 1715 << Stop << "), uses " << BI.FirstInstr << '-' 1716 << BI.LastInstr << ", reg-in " << IntvIn 1717 << ", leave before " << LeaveBefore 1718 << (BI.LiveOut ? ", stack-out" : ", killed in block")); 1719 1720 assert(IntvIn && "Must have register in"); 1721 assert(BI.LiveIn && "Must be live-in"); 1722 assert((!LeaveBefore || LeaveBefore > Start) && "Bad interference"); 1723 1724 if (!BI.LiveOut && (!LeaveBefore || LeaveBefore >= BI.LastInstr)) { 1725 LLVM_DEBUG(dbgs() << " before interference.\n"); 1726 // 1727 // <<< Interference after kill. 1728 // |---o---x | Killed in block. 1729 // ========= Use IntvIn everywhere. 1730 // 1731 selectIntv(IntvIn); 1732 useIntv(Start, BI.LastInstr); 1733 return; 1734 } 1735 1736 SlotIndex LSP = SA.getLastSplitPoint(BI.MBB); 1737 1738 if (!LeaveBefore || LeaveBefore > BI.LastInstr.getBoundaryIndex()) { 1739 // 1740 // <<< Possible interference after last use. 1741 // |---o---o---| Live-out on stack. 1742 // =========____ Leave IntvIn after last use. 1743 // 1744 // < Interference after last use. 1745 // |---o---o--o| Live-out on stack, late last use. 1746 // ============ Copy to stack after LSP, overlap IntvIn. 1747 // \_____ Stack interval is live-out. 1748 // 1749 if (BI.LastInstr < LSP) { 1750 LLVM_DEBUG(dbgs() << ", spill after last use before interference.\n"); 1751 selectIntv(IntvIn); 1752 SlotIndex Idx = leaveIntvAfter(BI.LastInstr); 1753 useIntv(Start, Idx); 1754 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1755 } else { 1756 LLVM_DEBUG(dbgs() << ", spill before last split point.\n"); 1757 selectIntv(IntvIn); 1758 SlotIndex Idx = leaveIntvBefore(LSP); 1759 overlapIntv(Idx, BI.LastInstr); 1760 useIntv(Start, Idx); 1761 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference"); 1762 } 1763 return; 1764 } 1765 1766 // The interference is overlapping somewhere we wanted to use IntvIn. That 1767 // means we need to create a local interval that can be allocated a 1768 // different register. 1769 unsigned LocalIntv = openIntv(); 1770 (void)LocalIntv; 1771 LLVM_DEBUG(dbgs() << ", creating local interval " << LocalIntv << ".\n"); 1772 1773 if (!BI.LiveOut || BI.LastInstr < LSP) { 1774 // 1775 // <<<<<<< Interference overlapping uses. 1776 // |---o---o---| Live-out on stack. 1777 // =====----____ Leave IntvIn before interference, then spill. 1778 // 1779 SlotIndex To = leaveIntvAfter(BI.LastInstr); 1780 SlotIndex From = enterIntvBefore(LeaveBefore); 1781 useIntv(From, To); 1782 selectIntv(IntvIn); 1783 useIntv(Start, From); 1784 assert((!LeaveBefore || From <= LeaveBefore) && "Interference"); 1785 return; 1786 } 1787 1788 // <<<<<<< Interference overlapping uses. 1789 // |---o---o--o| Live-out on stack, late last use. 1790 // =====------- Copy to stack before LSP, overlap LocalIntv. 1791 // \_____ Stack interval is live-out. 1792 // 1793 SlotIndex To = leaveIntvBefore(LSP); 1794 overlapIntv(To, BI.LastInstr); 1795 SlotIndex From = enterIntvBefore(std::min(To, LeaveBefore)); 1796 useIntv(From, To); 1797 selectIntv(IntvIn); 1798 useIntv(Start, From); 1799 assert((!LeaveBefore || From <= LeaveBefore) && "Interference"); 1800 } 1801 1802 void SplitEditor::splitRegOutBlock(const SplitAnalysis::BlockInfo &BI, 1803 unsigned IntvOut, SlotIndex EnterAfter) { 1804 SlotIndex Start, Stop; 1805 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB); 1806 1807 LLVM_DEBUG(dbgs() << printMBBReference(*BI.MBB) << " [" << Start << ';' 1808 << Stop << "), uses " << BI.FirstInstr << '-' 1809 << BI.LastInstr << ", reg-out " << IntvOut 1810 << ", enter after " << EnterAfter 1811 << (BI.LiveIn ? ", stack-in" : ", defined in block")); 1812 1813 SlotIndex LSP = SA.getLastSplitPoint(BI.MBB); 1814 1815 assert(IntvOut && "Must have register out"); 1816 assert(BI.LiveOut && "Must be live-out"); 1817 assert((!EnterAfter || EnterAfter < LSP) && "Bad interference"); 1818 1819 if (!BI.LiveIn && (!EnterAfter || EnterAfter <= BI.FirstInstr)) { 1820 LLVM_DEBUG(dbgs() << " after interference.\n"); 1821 // 1822 // >>>> Interference before def. 1823 // | o---o---| Defined in block. 1824 // ========= Use IntvOut everywhere. 1825 // 1826 selectIntv(IntvOut); 1827 useIntv(BI.FirstInstr, Stop); 1828 return; 1829 } 1830 1831 if (!EnterAfter || EnterAfter < BI.FirstInstr.getBaseIndex()) { 1832 LLVM_DEBUG(dbgs() << ", reload after interference.\n"); 1833 // 1834 // >>>> Interference before def. 1835 // |---o---o---| Live-through, stack-in. 1836 // ____========= Enter IntvOut before first use. 1837 // 1838 selectIntv(IntvOut); 1839 SlotIndex Idx = enterIntvBefore(std::min(LSP, BI.FirstInstr)); 1840 useIntv(Idx, Stop); 1841 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1842 return; 1843 } 1844 1845 // The interference is overlapping somewhere we wanted to use IntvOut. That 1846 // means we need to create a local interval that can be allocated a 1847 // different register. 1848 LLVM_DEBUG(dbgs() << ", interference overlaps uses.\n"); 1849 // 1850 // >>>>>>> Interference overlapping uses. 1851 // |---o---o---| Live-through, stack-in. 1852 // ____---====== Create local interval for interference range. 1853 // 1854 selectIntv(IntvOut); 1855 SlotIndex Idx = enterIntvAfter(EnterAfter); 1856 useIntv(Idx, Stop); 1857 assert((!EnterAfter || Idx >= EnterAfter) && "Interference"); 1858 1859 openIntv(); 1860 SlotIndex From = enterIntvBefore(std::min(Idx, BI.FirstInstr)); 1861 useIntv(From, Idx); 1862 } 1863 1864 void SplitAnalysis::BlockInfo::print(raw_ostream &OS) const { 1865 OS << "{" << printMBBReference(*MBB) << ", " 1866 << "uses " << FirstInstr << " to " << LastInstr << ", " 1867 << "1st def " << FirstDef << ", " 1868 << (LiveIn ? "live in" : "dead in") << ", " 1869 << (LiveOut ? "live out" : "dead out") << "}"; 1870 } 1871 1872 void SplitAnalysis::BlockInfo::dump() const { 1873 print(dbgs()); 1874 dbgs() << "\n"; 1875 } 1876