1 //===- LiveIntervals.cpp - Live Interval Analysis -------------------------===// 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 /// \file This file implements the LiveInterval analysis pass which is used 10 /// by the Linear Scan Register allocator. This pass linearizes the 11 /// basic blocks of the function in DFS order and computes live intervals for 12 /// each virtual and physical register. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "llvm/CodeGen/LiveIntervals.h" 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/DepthFirstIterator.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/iterator_range.h" 22 #include "llvm/Analysis/AliasAnalysis.h" 23 #include "llvm/CodeGen/LiveInterval.h" 24 #include "llvm/CodeGen/LiveIntervalCalc.h" 25 #include "llvm/CodeGen/LiveVariables.h" 26 #include "llvm/CodeGen/MachineBasicBlock.h" 27 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 28 #include "llvm/CodeGen/MachineDominators.h" 29 #include "llvm/CodeGen/MachineFunction.h" 30 #include "llvm/CodeGen/MachineInstr.h" 31 #include "llvm/CodeGen/MachineInstrBundle.h" 32 #include "llvm/CodeGen/MachineOperand.h" 33 #include "llvm/CodeGen/MachineRegisterInfo.h" 34 #include "llvm/CodeGen/Passes.h" 35 #include "llvm/CodeGen/SlotIndexes.h" 36 #include "llvm/CodeGen/TargetRegisterInfo.h" 37 #include "llvm/CodeGen/TargetSubtargetInfo.h" 38 #include "llvm/CodeGen/VirtRegMap.h" 39 #include "llvm/Config/llvm-config.h" 40 #include "llvm/MC/LaneBitmask.h" 41 #include "llvm/MC/MCRegisterInfo.h" 42 #include "llvm/Pass.h" 43 #include "llvm/Support/BlockFrequency.h" 44 #include "llvm/Support/CommandLine.h" 45 #include "llvm/Support/Compiler.h" 46 #include "llvm/Support/Debug.h" 47 #include "llvm/Support/MathExtras.h" 48 #include "llvm/Support/raw_ostream.h" 49 #include <algorithm> 50 #include <cassert> 51 #include <cstdint> 52 #include <iterator> 53 #include <tuple> 54 #include <utility> 55 56 using namespace llvm; 57 58 #define DEBUG_TYPE "regalloc" 59 60 char LiveIntervals::ID = 0; 61 char &llvm::LiveIntervalsID = LiveIntervals::ID; 62 INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals", 63 "Live Interval Analysis", false, false) 64 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 65 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 66 INITIALIZE_PASS_DEPENDENCY(SlotIndexes) 67 INITIALIZE_PASS_END(LiveIntervals, "liveintervals", 68 "Live Interval Analysis", false, false) 69 70 #ifndef NDEBUG 71 static cl::opt<bool> EnablePrecomputePhysRegs( 72 "precompute-phys-liveness", cl::Hidden, 73 cl::desc("Eagerly compute live intervals for all physreg units.")); 74 #else 75 static bool EnablePrecomputePhysRegs = false; 76 #endif // NDEBUG 77 78 namespace llvm { 79 80 cl::opt<bool> UseSegmentSetForPhysRegs( 81 "use-segment-set-for-physregs", cl::Hidden, cl::init(true), 82 cl::desc( 83 "Use segment set for the computation of the live ranges of physregs.")); 84 85 } // end namespace llvm 86 87 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const { 88 AU.setPreservesCFG(); 89 AU.addRequired<AAResultsWrapperPass>(); 90 AU.addPreserved<AAResultsWrapperPass>(); 91 AU.addPreserved<LiveVariables>(); 92 AU.addPreservedID(MachineLoopInfoID); 93 AU.addRequiredTransitiveID(MachineDominatorsID); 94 AU.addPreservedID(MachineDominatorsID); 95 AU.addPreserved<SlotIndexes>(); 96 AU.addRequiredTransitive<SlotIndexes>(); 97 MachineFunctionPass::getAnalysisUsage(AU); 98 } 99 100 LiveIntervals::LiveIntervals() : MachineFunctionPass(ID) { 101 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry()); 102 } 103 104 LiveIntervals::~LiveIntervals() { delete LICalc; } 105 106 void LiveIntervals::releaseMemory() { 107 // Free the live intervals themselves. 108 for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i) 109 delete VirtRegIntervals[Register::index2VirtReg(i)]; 110 VirtRegIntervals.clear(); 111 RegMaskSlots.clear(); 112 RegMaskBits.clear(); 113 RegMaskBlocks.clear(); 114 115 for (LiveRange *LR : RegUnitRanges) 116 delete LR; 117 RegUnitRanges.clear(); 118 119 // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd. 120 VNInfoAllocator.Reset(); 121 } 122 123 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) { 124 MF = &fn; 125 MRI = &MF->getRegInfo(); 126 TRI = MF->getSubtarget().getRegisterInfo(); 127 TII = MF->getSubtarget().getInstrInfo(); 128 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 129 Indexes = &getAnalysis<SlotIndexes>(); 130 DomTree = &getAnalysis<MachineDominatorTree>(); 131 132 if (!LICalc) 133 LICalc = new LiveIntervalCalc(); 134 135 // Allocate space for all virtual registers. 136 VirtRegIntervals.resize(MRI->getNumVirtRegs()); 137 138 computeVirtRegs(); 139 computeRegMasks(); 140 computeLiveInRegUnits(); 141 142 if (EnablePrecomputePhysRegs) { 143 // For stress testing, precompute live ranges of all physical register 144 // units, including reserved registers. 145 for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i) 146 getRegUnit(i); 147 } 148 LLVM_DEBUG(dump()); 149 return true; 150 } 151 152 void LiveIntervals::print(raw_ostream &OS, const Module* ) const { 153 OS << "********** INTERVALS **********\n"; 154 155 // Dump the regunits. 156 for (unsigned Unit = 0, UnitE = RegUnitRanges.size(); Unit != UnitE; ++Unit) 157 if (LiveRange *LR = RegUnitRanges[Unit]) 158 OS << printRegUnit(Unit, TRI) << ' ' << *LR << '\n'; 159 160 // Dump the virtregs. 161 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { 162 unsigned Reg = Register::index2VirtReg(i); 163 if (hasInterval(Reg)) 164 OS << getInterval(Reg) << '\n'; 165 } 166 167 OS << "RegMasks:"; 168 for (SlotIndex Idx : RegMaskSlots) 169 OS << ' ' << Idx; 170 OS << '\n'; 171 172 printInstrs(OS); 173 } 174 175 void LiveIntervals::printInstrs(raw_ostream &OS) const { 176 OS << "********** MACHINEINSTRS **********\n"; 177 MF->print(OS, Indexes); 178 } 179 180 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 181 LLVM_DUMP_METHOD void LiveIntervals::dumpInstrs() const { 182 printInstrs(dbgs()); 183 } 184 #endif 185 186 LiveInterval* LiveIntervals::createInterval(unsigned reg) { 187 float Weight = Register::isPhysicalRegister(reg) ? huge_valf : 0.0F; 188 return new LiveInterval(reg, Weight); 189 } 190 191 /// Compute the live interval of a virtual register, based on defs and uses. 192 bool LiveIntervals::computeVirtRegInterval(LiveInterval &LI) { 193 assert(LICalc && "LICalc not initialized."); 194 assert(LI.empty() && "Should only compute empty intervals."); 195 LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator()); 196 LICalc->calculate(LI, MRI->shouldTrackSubRegLiveness(LI.reg())); 197 return computeDeadValues(LI, nullptr); 198 } 199 200 void LiveIntervals::computeVirtRegs() { 201 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { 202 unsigned Reg = Register::index2VirtReg(i); 203 if (MRI->reg_nodbg_empty(Reg)) 204 continue; 205 LiveInterval &LI = createEmptyInterval(Reg); 206 bool NeedSplit = computeVirtRegInterval(LI); 207 if (NeedSplit) { 208 SmallVector<LiveInterval*, 8> SplitLIs; 209 splitSeparateComponents(LI, SplitLIs); 210 } 211 } 212 } 213 214 void LiveIntervals::computeRegMasks() { 215 RegMaskBlocks.resize(MF->getNumBlockIDs()); 216 217 // Find all instructions with regmask operands. 218 for (const MachineBasicBlock &MBB : *MF) { 219 std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB.getNumber()]; 220 RMB.first = RegMaskSlots.size(); 221 222 // Some block starts, such as EH funclets, create masks. 223 if (const uint32_t *Mask = MBB.getBeginClobberMask(TRI)) { 224 RegMaskSlots.push_back(Indexes->getMBBStartIdx(&MBB)); 225 RegMaskBits.push_back(Mask); 226 } 227 228 // Unwinders may clobber additional registers. 229 // FIXME: This functionality can possibly be merged into 230 // MachineBasicBlock::getBeginClobberMask(). 231 if (MBB.isEHPad()) 232 if (auto *Mask = TRI->getCustomEHPadPreservedMask(*MBB.getParent())) { 233 RegMaskSlots.push_back(Indexes->getMBBStartIdx(&MBB)); 234 RegMaskBits.push_back(Mask); 235 } 236 237 for (const MachineInstr &MI : MBB) { 238 for (const MachineOperand &MO : MI.operands()) { 239 if (!MO.isRegMask()) 240 continue; 241 RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot()); 242 RegMaskBits.push_back(MO.getRegMask()); 243 } 244 } 245 246 // Some block ends, such as funclet returns, create masks. Put the mask on 247 // the last instruction of the block, because MBB slot index intervals are 248 // half-open. 249 if (const uint32_t *Mask = MBB.getEndClobberMask(TRI)) { 250 assert(!MBB.empty() && "empty return block?"); 251 RegMaskSlots.push_back( 252 Indexes->getInstructionIndex(MBB.back()).getRegSlot()); 253 RegMaskBits.push_back(Mask); 254 } 255 256 // Compute the number of register mask instructions in this block. 257 RMB.second = RegMaskSlots.size() - RMB.first; 258 } 259 } 260 261 //===----------------------------------------------------------------------===// 262 // Register Unit Liveness 263 //===----------------------------------------------------------------------===// 264 // 265 // Fixed interference typically comes from ABI boundaries: Function arguments 266 // and return values are passed in fixed registers, and so are exception 267 // pointers entering landing pads. Certain instructions require values to be 268 // present in specific registers. That is also represented through fixed 269 // interference. 270 // 271 272 /// Compute the live range of a register unit, based on the uses and defs of 273 /// aliasing registers. The range should be empty, or contain only dead 274 /// phi-defs from ABI blocks. 275 void LiveIntervals::computeRegUnitRange(LiveRange &LR, unsigned Unit) { 276 assert(LICalc && "LICalc not initialized."); 277 LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator()); 278 279 // The physregs aliasing Unit are the roots and their super-registers. 280 // Create all values as dead defs before extending to uses. Note that roots 281 // may share super-registers. That's OK because createDeadDefs() is 282 // idempotent. It is very rare for a register unit to have multiple roots, so 283 // uniquing super-registers is probably not worthwhile. 284 bool IsReserved = false; 285 for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) { 286 bool IsRootReserved = true; 287 for (MCSuperRegIterator Super(*Root, TRI, /*IncludeSelf=*/true); 288 Super.isValid(); ++Super) { 289 unsigned Reg = *Super; 290 if (!MRI->reg_empty(Reg)) 291 LICalc->createDeadDefs(LR, Reg); 292 // A register unit is considered reserved if all its roots and all their 293 // super registers are reserved. 294 if (!MRI->isReserved(Reg)) 295 IsRootReserved = false; 296 } 297 IsReserved |= IsRootReserved; 298 } 299 assert(IsReserved == MRI->isReservedRegUnit(Unit) && 300 "reserved computation mismatch"); 301 302 // Now extend LR to reach all uses. 303 // Ignore uses of reserved registers. We only track defs of those. 304 if (!IsReserved) { 305 for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) { 306 for (MCSuperRegIterator Super(*Root, TRI, /*IncludeSelf=*/true); 307 Super.isValid(); ++Super) { 308 unsigned Reg = *Super; 309 if (!MRI->reg_empty(Reg)) 310 LICalc->extendToUses(LR, Reg); 311 } 312 } 313 } 314 315 // Flush the segment set to the segment vector. 316 if (UseSegmentSetForPhysRegs) 317 LR.flushSegmentSet(); 318 } 319 320 /// Precompute the live ranges of any register units that are live-in to an ABI 321 /// block somewhere. Register values can appear without a corresponding def when 322 /// entering the entry block or a landing pad. 323 void LiveIntervals::computeLiveInRegUnits() { 324 RegUnitRanges.resize(TRI->getNumRegUnits()); 325 LLVM_DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n"); 326 327 // Keep track of the live range sets allocated. 328 SmallVector<unsigned, 8> NewRanges; 329 330 // Check all basic blocks for live-ins. 331 for (const MachineBasicBlock &MBB : *MF) { 332 // We only care about ABI blocks: Entry + landing pads. 333 if ((&MBB != &MF->front() && !MBB.isEHPad()) || MBB.livein_empty()) 334 continue; 335 336 // Create phi-defs at Begin for all live-in registers. 337 SlotIndex Begin = Indexes->getMBBStartIdx(&MBB); 338 LLVM_DEBUG(dbgs() << Begin << "\t" << printMBBReference(MBB)); 339 for (const auto &LI : MBB.liveins()) { 340 for (MCRegUnitIterator Units(LI.PhysReg, TRI); Units.isValid(); ++Units) { 341 unsigned Unit = *Units; 342 LiveRange *LR = RegUnitRanges[Unit]; 343 if (!LR) { 344 // Use segment set to speed-up initial computation of the live range. 345 LR = RegUnitRanges[Unit] = new LiveRange(UseSegmentSetForPhysRegs); 346 NewRanges.push_back(Unit); 347 } 348 VNInfo *VNI = LR->createDeadDef(Begin, getVNInfoAllocator()); 349 (void)VNI; 350 LLVM_DEBUG(dbgs() << ' ' << printRegUnit(Unit, TRI) << '#' << VNI->id); 351 } 352 } 353 LLVM_DEBUG(dbgs() << '\n'); 354 } 355 LLVM_DEBUG(dbgs() << "Created " << NewRanges.size() << " new intervals.\n"); 356 357 // Compute the 'normal' part of the ranges. 358 for (unsigned Unit : NewRanges) 359 computeRegUnitRange(*RegUnitRanges[Unit], Unit); 360 } 361 362 static void createSegmentsForValues(LiveRange &LR, 363 iterator_range<LiveInterval::vni_iterator> VNIs) { 364 for (VNInfo *VNI : VNIs) { 365 if (VNI->isUnused()) 366 continue; 367 SlotIndex Def = VNI->def; 368 LR.addSegment(LiveRange::Segment(Def, Def.getDeadSlot(), VNI)); 369 } 370 } 371 372 void LiveIntervals::extendSegmentsToUses(LiveRange &Segments, 373 ShrinkToUsesWorkList &WorkList, 374 unsigned Reg, LaneBitmask LaneMask) { 375 // Keep track of the PHIs that are in use. 376 SmallPtrSet<VNInfo*, 8> UsedPHIs; 377 // Blocks that have already been added to WorkList as live-out. 378 SmallPtrSet<const MachineBasicBlock*, 16> LiveOut; 379 380 auto getSubRange = [](const LiveInterval &I, LaneBitmask M) 381 -> const LiveRange& { 382 if (M.none()) 383 return I; 384 for (const LiveInterval::SubRange &SR : I.subranges()) { 385 if ((SR.LaneMask & M).any()) { 386 assert(SR.LaneMask == M && "Expecting lane masks to match exactly"); 387 return SR; 388 } 389 } 390 llvm_unreachable("Subrange for mask not found"); 391 }; 392 393 const LiveInterval &LI = getInterval(Reg); 394 const LiveRange &OldRange = getSubRange(LI, LaneMask); 395 396 // Extend intervals to reach all uses in WorkList. 397 while (!WorkList.empty()) { 398 SlotIndex Idx = WorkList.back().first; 399 VNInfo *VNI = WorkList.back().second; 400 WorkList.pop_back(); 401 const MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Idx.getPrevSlot()); 402 SlotIndex BlockStart = Indexes->getMBBStartIdx(MBB); 403 404 // Extend the live range for VNI to be live at Idx. 405 if (VNInfo *ExtVNI = Segments.extendInBlock(BlockStart, Idx)) { 406 assert(ExtVNI == VNI && "Unexpected existing value number"); 407 (void)ExtVNI; 408 // Is this a PHIDef we haven't seen before? 409 if (!VNI->isPHIDef() || VNI->def != BlockStart || 410 !UsedPHIs.insert(VNI).second) 411 continue; 412 // The PHI is live, make sure the predecessors are live-out. 413 for (const MachineBasicBlock *Pred : MBB->predecessors()) { 414 if (!LiveOut.insert(Pred).second) 415 continue; 416 SlotIndex Stop = Indexes->getMBBEndIdx(Pred); 417 // A predecessor is not required to have a live-out value for a PHI. 418 if (VNInfo *PVNI = OldRange.getVNInfoBefore(Stop)) 419 WorkList.push_back(std::make_pair(Stop, PVNI)); 420 } 421 continue; 422 } 423 424 // VNI is live-in to MBB. 425 LLVM_DEBUG(dbgs() << " live-in at " << BlockStart << '\n'); 426 Segments.addSegment(LiveRange::Segment(BlockStart, Idx, VNI)); 427 428 // Make sure VNI is live-out from the predecessors. 429 for (const MachineBasicBlock *Pred : MBB->predecessors()) { 430 if (!LiveOut.insert(Pred).second) 431 continue; 432 SlotIndex Stop = Indexes->getMBBEndIdx(Pred); 433 if (VNInfo *OldVNI = OldRange.getVNInfoBefore(Stop)) { 434 assert(OldVNI == VNI && "Wrong value out of predecessor"); 435 (void)OldVNI; 436 WorkList.push_back(std::make_pair(Stop, VNI)); 437 } else { 438 #ifndef NDEBUG 439 // There was no old VNI. Verify that Stop is jointly dominated 440 // by <undef>s for this live range. 441 assert(LaneMask.any() && 442 "Missing value out of predecessor for main range"); 443 SmallVector<SlotIndex,8> Undefs; 444 LI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes); 445 assert(LiveRangeCalc::isJointlyDominated(Pred, Undefs, *Indexes) && 446 "Missing value out of predecessor for subrange"); 447 #endif 448 } 449 } 450 } 451 } 452 453 bool LiveIntervals::shrinkToUses(LiveInterval *li, 454 SmallVectorImpl<MachineInstr*> *dead) { 455 LLVM_DEBUG(dbgs() << "Shrink: " << *li << '\n'); 456 assert(Register::isVirtualRegister(li->reg()) && 457 "Can only shrink virtual registers"); 458 459 // Shrink subregister live ranges. 460 bool NeedsCleanup = false; 461 for (LiveInterval::SubRange &S : li->subranges()) { 462 shrinkToUses(S, li->reg()); 463 if (S.empty()) 464 NeedsCleanup = true; 465 } 466 if (NeedsCleanup) 467 li->removeEmptySubRanges(); 468 469 // Find all the values used, including PHI kills. 470 ShrinkToUsesWorkList WorkList; 471 472 // Visit all instructions reading li->reg(). 473 unsigned Reg = li->reg(); 474 for (MachineInstr &UseMI : MRI->reg_instructions(Reg)) { 475 if (UseMI.isDebugValue() || !UseMI.readsVirtualRegister(Reg)) 476 continue; 477 SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot(); 478 LiveQueryResult LRQ = li->Query(Idx); 479 VNInfo *VNI = LRQ.valueIn(); 480 if (!VNI) { 481 // This shouldn't happen: readsVirtualRegister returns true, but there is 482 // no live value. It is likely caused by a target getting <undef> flags 483 // wrong. 484 LLVM_DEBUG( 485 dbgs() << Idx << '\t' << UseMI 486 << "Warning: Instr claims to read non-existent value in " 487 << *li << '\n'); 488 continue; 489 } 490 // Special case: An early-clobber tied operand reads and writes the 491 // register one slot early. 492 if (VNInfo *DefVNI = LRQ.valueDefined()) 493 Idx = DefVNI->def; 494 495 WorkList.push_back(std::make_pair(Idx, VNI)); 496 } 497 498 // Create new live ranges with only minimal live segments per def. 499 LiveRange NewLR; 500 createSegmentsForValues(NewLR, make_range(li->vni_begin(), li->vni_end())); 501 extendSegmentsToUses(NewLR, WorkList, Reg, LaneBitmask::getNone()); 502 503 // Move the trimmed segments back. 504 li->segments.swap(NewLR.segments); 505 506 // Handle dead values. 507 bool CanSeparate = computeDeadValues(*li, dead); 508 LLVM_DEBUG(dbgs() << "Shrunk: " << *li << '\n'); 509 return CanSeparate; 510 } 511 512 bool LiveIntervals::computeDeadValues(LiveInterval &LI, 513 SmallVectorImpl<MachineInstr*> *dead) { 514 bool MayHaveSplitComponents = false; 515 bool HaveDeadDef = false; 516 517 for (VNInfo *VNI : LI.valnos) { 518 if (VNI->isUnused()) 519 continue; 520 SlotIndex Def = VNI->def; 521 LiveRange::iterator I = LI.FindSegmentContaining(Def); 522 assert(I != LI.end() && "Missing segment for VNI"); 523 524 // Is the register live before? Otherwise we may have to add a read-undef 525 // flag for subregister defs. 526 unsigned VReg = LI.reg(); 527 if (MRI->shouldTrackSubRegLiveness(VReg)) { 528 if ((I == LI.begin() || std::prev(I)->end < Def) && !VNI->isPHIDef()) { 529 MachineInstr *MI = getInstructionFromIndex(Def); 530 MI->setRegisterDefReadUndef(VReg); 531 } 532 } 533 534 if (I->end != Def.getDeadSlot()) 535 continue; 536 if (VNI->isPHIDef()) { 537 // This is a dead PHI. Remove it. 538 VNI->markUnused(); 539 LI.removeSegment(I); 540 LLVM_DEBUG(dbgs() << "Dead PHI at " << Def << " may separate interval\n"); 541 MayHaveSplitComponents = true; 542 } else { 543 // This is a dead def. Make sure the instruction knows. 544 MachineInstr *MI = getInstructionFromIndex(Def); 545 assert(MI && "No instruction defining live value"); 546 MI->addRegisterDead(LI.reg(), TRI); 547 if (HaveDeadDef) 548 MayHaveSplitComponents = true; 549 HaveDeadDef = true; 550 551 if (dead && MI->allDefsAreDead()) { 552 LLVM_DEBUG(dbgs() << "All defs dead: " << Def << '\t' << *MI); 553 dead->push_back(MI); 554 } 555 } 556 } 557 return MayHaveSplitComponents; 558 } 559 560 void LiveIntervals::shrinkToUses(LiveInterval::SubRange &SR, unsigned Reg) { 561 LLVM_DEBUG(dbgs() << "Shrink: " << SR << '\n'); 562 assert(Register::isVirtualRegister(Reg) && 563 "Can only shrink virtual registers"); 564 // Find all the values used, including PHI kills. 565 ShrinkToUsesWorkList WorkList; 566 567 // Visit all instructions reading Reg. 568 SlotIndex LastIdx; 569 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) { 570 // Skip "undef" uses. 571 if (!MO.readsReg()) 572 continue; 573 // Maybe the operand is for a subregister we don't care about. 574 unsigned SubReg = MO.getSubReg(); 575 if (SubReg != 0) { 576 LaneBitmask LaneMask = TRI->getSubRegIndexLaneMask(SubReg); 577 if ((LaneMask & SR.LaneMask).none()) 578 continue; 579 } 580 // We only need to visit each instruction once. 581 MachineInstr *UseMI = MO.getParent(); 582 SlotIndex Idx = getInstructionIndex(*UseMI).getRegSlot(); 583 if (Idx == LastIdx) 584 continue; 585 LastIdx = Idx; 586 587 LiveQueryResult LRQ = SR.Query(Idx); 588 VNInfo *VNI = LRQ.valueIn(); 589 // For Subranges it is possible that only undef values are left in that 590 // part of the subregister, so there is no real liverange at the use 591 if (!VNI) 592 continue; 593 594 // Special case: An early-clobber tied operand reads and writes the 595 // register one slot early. 596 if (VNInfo *DefVNI = LRQ.valueDefined()) 597 Idx = DefVNI->def; 598 599 WorkList.push_back(std::make_pair(Idx, VNI)); 600 } 601 602 // Create a new live ranges with only minimal live segments per def. 603 LiveRange NewLR; 604 createSegmentsForValues(NewLR, make_range(SR.vni_begin(), SR.vni_end())); 605 extendSegmentsToUses(NewLR, WorkList, Reg, SR.LaneMask); 606 607 // Move the trimmed ranges back. 608 SR.segments.swap(NewLR.segments); 609 610 // Remove dead PHI value numbers 611 for (VNInfo *VNI : SR.valnos) { 612 if (VNI->isUnused()) 613 continue; 614 const LiveRange::Segment *Segment = SR.getSegmentContaining(VNI->def); 615 assert(Segment != nullptr && "Missing segment for VNI"); 616 if (Segment->end != VNI->def.getDeadSlot()) 617 continue; 618 if (VNI->isPHIDef()) { 619 // This is a dead PHI. Remove it. 620 LLVM_DEBUG(dbgs() << "Dead PHI at " << VNI->def 621 << " may separate interval\n"); 622 VNI->markUnused(); 623 SR.removeSegment(*Segment); 624 } 625 } 626 627 LLVM_DEBUG(dbgs() << "Shrunk: " << SR << '\n'); 628 } 629 630 void LiveIntervals::extendToIndices(LiveRange &LR, 631 ArrayRef<SlotIndex> Indices, 632 ArrayRef<SlotIndex> Undefs) { 633 assert(LICalc && "LICalc not initialized."); 634 LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator()); 635 for (SlotIndex Idx : Indices) 636 LICalc->extend(LR, Idx, /*PhysReg=*/0, Undefs); 637 } 638 639 void LiveIntervals::pruneValue(LiveRange &LR, SlotIndex Kill, 640 SmallVectorImpl<SlotIndex> *EndPoints) { 641 LiveQueryResult LRQ = LR.Query(Kill); 642 VNInfo *VNI = LRQ.valueOutOrDead(); 643 if (!VNI) 644 return; 645 646 MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill); 647 SlotIndex MBBEnd = Indexes->getMBBEndIdx(KillMBB); 648 649 // If VNI isn't live out from KillMBB, the value is trivially pruned. 650 if (LRQ.endPoint() < MBBEnd) { 651 LR.removeSegment(Kill, LRQ.endPoint()); 652 if (EndPoints) EndPoints->push_back(LRQ.endPoint()); 653 return; 654 } 655 656 // VNI is live out of KillMBB. 657 LR.removeSegment(Kill, MBBEnd); 658 if (EndPoints) EndPoints->push_back(MBBEnd); 659 660 // Find all blocks that are reachable from KillMBB without leaving VNI's live 661 // range. It is possible that KillMBB itself is reachable, so start a DFS 662 // from each successor. 663 using VisitedTy = df_iterator_default_set<MachineBasicBlock*,9>; 664 VisitedTy Visited; 665 for (MachineBasicBlock *Succ : KillMBB->successors()) { 666 for (df_ext_iterator<MachineBasicBlock*, VisitedTy> 667 I = df_ext_begin(Succ, Visited), E = df_ext_end(Succ, Visited); 668 I != E;) { 669 MachineBasicBlock *MBB = *I; 670 671 // Check if VNI is live in to MBB. 672 SlotIndex MBBStart, MBBEnd; 673 std::tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB); 674 LiveQueryResult LRQ = LR.Query(MBBStart); 675 if (LRQ.valueIn() != VNI) { 676 // This block isn't part of the VNI segment. Prune the search. 677 I.skipChildren(); 678 continue; 679 } 680 681 // Prune the search if VNI is killed in MBB. 682 if (LRQ.endPoint() < MBBEnd) { 683 LR.removeSegment(MBBStart, LRQ.endPoint()); 684 if (EndPoints) EndPoints->push_back(LRQ.endPoint()); 685 I.skipChildren(); 686 continue; 687 } 688 689 // VNI is live through MBB. 690 LR.removeSegment(MBBStart, MBBEnd); 691 if (EndPoints) EndPoints->push_back(MBBEnd); 692 ++I; 693 } 694 } 695 } 696 697 //===----------------------------------------------------------------------===// 698 // Register allocator hooks. 699 // 700 701 void LiveIntervals::addKillFlags(const VirtRegMap *VRM) { 702 // Keep track of regunit ranges. 703 SmallVector<std::pair<const LiveRange*, LiveRange::const_iterator>, 8> RU; 704 // Keep track of subregister ranges. 705 SmallVector<std::pair<const LiveInterval::SubRange*, 706 LiveRange::const_iterator>, 4> SRs; 707 708 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { 709 unsigned Reg = Register::index2VirtReg(i); 710 if (MRI->reg_nodbg_empty(Reg)) 711 continue; 712 const LiveInterval &LI = getInterval(Reg); 713 if (LI.empty()) 714 continue; 715 716 // Find the regunit intervals for the assigned register. They may overlap 717 // the virtual register live range, cancelling any kills. 718 RU.clear(); 719 for (MCRegUnitIterator Unit(VRM->getPhys(Reg), TRI); Unit.isValid(); 720 ++Unit) { 721 const LiveRange &RURange = getRegUnit(*Unit); 722 if (RURange.empty()) 723 continue; 724 RU.push_back(std::make_pair(&RURange, RURange.find(LI.begin()->end))); 725 } 726 727 if (MRI->subRegLivenessEnabled()) { 728 SRs.clear(); 729 for (const LiveInterval::SubRange &SR : LI.subranges()) { 730 SRs.push_back(std::make_pair(&SR, SR.find(LI.begin()->end))); 731 } 732 } 733 734 // Every instruction that kills Reg corresponds to a segment range end 735 // point. 736 for (LiveInterval::const_iterator RI = LI.begin(), RE = LI.end(); RI != RE; 737 ++RI) { 738 // A block index indicates an MBB edge. 739 if (RI->end.isBlock()) 740 continue; 741 MachineInstr *MI = getInstructionFromIndex(RI->end); 742 if (!MI) 743 continue; 744 745 // Check if any of the regunits are live beyond the end of RI. That could 746 // happen when a physreg is defined as a copy of a virtreg: 747 // 748 // %eax = COPY %5 749 // FOO %5 <--- MI, cancel kill because %eax is live. 750 // BAR killed %eax 751 // 752 // There should be no kill flag on FOO when %5 is rewritten as %eax. 753 for (auto &RUP : RU) { 754 const LiveRange &RURange = *RUP.first; 755 LiveRange::const_iterator &I = RUP.second; 756 if (I == RURange.end()) 757 continue; 758 I = RURange.advanceTo(I, RI->end); 759 if (I == RURange.end() || I->start >= RI->end) 760 continue; 761 // I is overlapping RI. 762 goto CancelKill; 763 } 764 765 if (MRI->subRegLivenessEnabled()) { 766 // When reading a partial undefined value we must not add a kill flag. 767 // The regalloc might have used the undef lane for something else. 768 // Example: 769 // %1 = ... ; R32: %1 770 // %2:high16 = ... ; R64: %2 771 // = read killed %2 ; R64: %2 772 // = read %1 ; R32: %1 773 // The <kill> flag is correct for %2, but the register allocator may 774 // assign R0L to %1, and R0 to %2 because the low 32bits of R0 775 // are actually never written by %2. After assignment the <kill> 776 // flag at the read instruction is invalid. 777 LaneBitmask DefinedLanesMask; 778 if (!SRs.empty()) { 779 // Compute a mask of lanes that are defined. 780 DefinedLanesMask = LaneBitmask::getNone(); 781 for (auto &SRP : SRs) { 782 const LiveInterval::SubRange &SR = *SRP.first; 783 LiveRange::const_iterator &I = SRP.second; 784 if (I == SR.end()) 785 continue; 786 I = SR.advanceTo(I, RI->end); 787 if (I == SR.end() || I->start >= RI->end) 788 continue; 789 // I is overlapping RI 790 DefinedLanesMask |= SR.LaneMask; 791 } 792 } else 793 DefinedLanesMask = LaneBitmask::getAll(); 794 795 bool IsFullWrite = false; 796 for (const MachineOperand &MO : MI->operands()) { 797 if (!MO.isReg() || MO.getReg() != Reg) 798 continue; 799 if (MO.isUse()) { 800 // Reading any undefined lanes? 801 LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg()); 802 if ((UseMask & ~DefinedLanesMask).any()) 803 goto CancelKill; 804 } else if (MO.getSubReg() == 0) { 805 // Writing to the full register? 806 assert(MO.isDef()); 807 IsFullWrite = true; 808 } 809 } 810 811 // If an instruction writes to a subregister, a new segment starts in 812 // the LiveInterval. But as this is only overriding part of the register 813 // adding kill-flags is not correct here after registers have been 814 // assigned. 815 if (!IsFullWrite) { 816 // Next segment has to be adjacent in the subregister write case. 817 LiveRange::const_iterator N = std::next(RI); 818 if (N != LI.end() && N->start == RI->end) 819 goto CancelKill; 820 } 821 } 822 823 MI->addRegisterKilled(Reg, nullptr); 824 continue; 825 CancelKill: 826 MI->clearRegisterKills(Reg, nullptr); 827 } 828 } 829 } 830 831 MachineBasicBlock* 832 LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const { 833 // A local live range must be fully contained inside the block, meaning it is 834 // defined and killed at instructions, not at block boundaries. It is not 835 // live in or out of any block. 836 // 837 // It is technically possible to have a PHI-defined live range identical to a 838 // single block, but we are going to return false in that case. 839 840 SlotIndex Start = LI.beginIndex(); 841 if (Start.isBlock()) 842 return nullptr; 843 844 SlotIndex Stop = LI.endIndex(); 845 if (Stop.isBlock()) 846 return nullptr; 847 848 // getMBBFromIndex doesn't need to search the MBB table when both indexes 849 // belong to proper instructions. 850 MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start); 851 MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop); 852 return MBB1 == MBB2 ? MBB1 : nullptr; 853 } 854 855 bool 856 LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const { 857 for (const VNInfo *PHI : LI.valnos) { 858 if (PHI->isUnused() || !PHI->isPHIDef()) 859 continue; 860 const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def); 861 // Conservatively return true instead of scanning huge predecessor lists. 862 if (PHIMBB->pred_size() > 100) 863 return true; 864 for (const MachineBasicBlock *Pred : PHIMBB->predecessors()) 865 if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(Pred))) 866 return true; 867 } 868 return false; 869 } 870 871 float LiveIntervals::getSpillWeight(bool isDef, bool isUse, 872 const MachineBlockFrequencyInfo *MBFI, 873 const MachineInstr &MI) { 874 return getSpillWeight(isDef, isUse, MBFI, MI.getParent()); 875 } 876 877 float LiveIntervals::getSpillWeight(bool isDef, bool isUse, 878 const MachineBlockFrequencyInfo *MBFI, 879 const MachineBasicBlock *MBB) { 880 return (isDef + isUse) * MBFI->getBlockFreqRelativeToEntryBlock(MBB); 881 } 882 883 LiveRange::Segment 884 LiveIntervals::addSegmentToEndOfBlock(unsigned reg, MachineInstr &startInst) { 885 LiveInterval& Interval = createEmptyInterval(reg); 886 VNInfo *VN = Interval.getNextValue( 887 SlotIndex(getInstructionIndex(startInst).getRegSlot()), 888 getVNInfoAllocator()); 889 LiveRange::Segment S(SlotIndex(getInstructionIndex(startInst).getRegSlot()), 890 getMBBEndIdx(startInst.getParent()), VN); 891 Interval.addSegment(S); 892 893 return S; 894 } 895 896 //===----------------------------------------------------------------------===// 897 // Register mask functions 898 //===----------------------------------------------------------------------===// 899 900 bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI, 901 BitVector &UsableRegs) { 902 if (LI.empty()) 903 return false; 904 LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end(); 905 906 // Use a smaller arrays for local live ranges. 907 ArrayRef<SlotIndex> Slots; 908 ArrayRef<const uint32_t*> Bits; 909 if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) { 910 Slots = getRegMaskSlotsInBlock(MBB->getNumber()); 911 Bits = getRegMaskBitsInBlock(MBB->getNumber()); 912 } else { 913 Slots = getRegMaskSlots(); 914 Bits = getRegMaskBits(); 915 } 916 917 // We are going to enumerate all the register mask slots contained in LI. 918 // Start with a binary search of RegMaskSlots to find a starting point. 919 ArrayRef<SlotIndex>::iterator SlotI = llvm::lower_bound(Slots, LiveI->start); 920 ArrayRef<SlotIndex>::iterator SlotE = Slots.end(); 921 922 // No slots in range, LI begins after the last call. 923 if (SlotI == SlotE) 924 return false; 925 926 bool Found = false; 927 while (true) { 928 assert(*SlotI >= LiveI->start); 929 // Loop over all slots overlapping this segment. 930 while (*SlotI < LiveI->end) { 931 // *SlotI overlaps LI. Collect mask bits. 932 if (!Found) { 933 // This is the first overlap. Initialize UsableRegs to all ones. 934 UsableRegs.clear(); 935 UsableRegs.resize(TRI->getNumRegs(), true); 936 Found = true; 937 } 938 // Remove usable registers clobbered by this mask. 939 UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]); 940 if (++SlotI == SlotE) 941 return Found; 942 } 943 // *SlotI is beyond the current LI segment. 944 LiveI = LI.advanceTo(LiveI, *SlotI); 945 if (LiveI == LiveE) 946 return Found; 947 // Advance SlotI until it overlaps. 948 while (*SlotI < LiveI->start) 949 if (++SlotI == SlotE) 950 return Found; 951 } 952 } 953 954 //===----------------------------------------------------------------------===// 955 // IntervalUpdate class. 956 //===----------------------------------------------------------------------===// 957 958 /// Toolkit used by handleMove to trim or extend live intervals. 959 class LiveIntervals::HMEditor { 960 private: 961 LiveIntervals& LIS; 962 const MachineRegisterInfo& MRI; 963 const TargetRegisterInfo& TRI; 964 SlotIndex OldIdx; 965 SlotIndex NewIdx; 966 SmallPtrSet<LiveRange*, 8> Updated; 967 bool UpdateFlags; 968 969 public: 970 HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI, 971 const TargetRegisterInfo& TRI, 972 SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags) 973 : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx), 974 UpdateFlags(UpdateFlags) {} 975 976 // FIXME: UpdateFlags is a workaround that creates live intervals for all 977 // physregs, even those that aren't needed for regalloc, in order to update 978 // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill 979 // flags, and postRA passes will use a live register utility instead. 980 LiveRange *getRegUnitLI(unsigned Unit) { 981 if (UpdateFlags && !MRI.isReservedRegUnit(Unit)) 982 return &LIS.getRegUnit(Unit); 983 return LIS.getCachedRegUnit(Unit); 984 } 985 986 /// Update all live ranges touched by MI, assuming a move from OldIdx to 987 /// NewIdx. 988 void updateAllRanges(MachineInstr *MI) { 989 LLVM_DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": " 990 << *MI); 991 bool hasRegMask = false; 992 for (MachineOperand &MO : MI->operands()) { 993 if (MO.isRegMask()) 994 hasRegMask = true; 995 if (!MO.isReg()) 996 continue; 997 if (MO.isUse()) { 998 if (!MO.readsReg()) 999 continue; 1000 // Aggressively clear all kill flags. 1001 // They are reinserted by VirtRegRewriter. 1002 MO.setIsKill(false); 1003 } 1004 1005 Register Reg = MO.getReg(); 1006 if (!Reg) 1007 continue; 1008 if (Register::isVirtualRegister(Reg)) { 1009 LiveInterval &LI = LIS.getInterval(Reg); 1010 if (LI.hasSubRanges()) { 1011 unsigned SubReg = MO.getSubReg(); 1012 LaneBitmask LaneMask = SubReg ? TRI.getSubRegIndexLaneMask(SubReg) 1013 : MRI.getMaxLaneMaskForVReg(Reg); 1014 for (LiveInterval::SubRange &S : LI.subranges()) { 1015 if ((S.LaneMask & LaneMask).none()) 1016 continue; 1017 updateRange(S, Reg, S.LaneMask); 1018 } 1019 } 1020 updateRange(LI, Reg, LaneBitmask::getNone()); 1021 // If main range has a hole and we are moving a subrange use across 1022 // the hole updateRange() cannot properly handle it since it only 1023 // gets the LiveRange and not the whole LiveInterval. As a result 1024 // we may end up with a main range not covering all subranges. 1025 // This is extremely rare case, so let's check and reconstruct the 1026 // main range. 1027 for (LiveInterval::SubRange &S : LI.subranges()) { 1028 if (LI.covers(S)) 1029 continue; 1030 LI.clear(); 1031 LIS.constructMainRangeFromSubranges(LI); 1032 break; 1033 } 1034 1035 continue; 1036 } 1037 1038 // For physregs, only update the regunits that actually have a 1039 // precomputed live range. 1040 for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units) 1041 if (LiveRange *LR = getRegUnitLI(*Units)) 1042 updateRange(*LR, *Units, LaneBitmask::getNone()); 1043 } 1044 if (hasRegMask) 1045 updateRegMaskSlots(); 1046 } 1047 1048 private: 1049 /// Update a single live range, assuming an instruction has been moved from 1050 /// OldIdx to NewIdx. 1051 void updateRange(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) { 1052 if (!Updated.insert(&LR).second) 1053 return; 1054 LLVM_DEBUG({ 1055 dbgs() << " "; 1056 if (Register::isVirtualRegister(Reg)) { 1057 dbgs() << printReg(Reg); 1058 if (LaneMask.any()) 1059 dbgs() << " L" << PrintLaneMask(LaneMask); 1060 } else { 1061 dbgs() << printRegUnit(Reg, &TRI); 1062 } 1063 dbgs() << ":\t" << LR << '\n'; 1064 }); 1065 if (SlotIndex::isEarlierInstr(OldIdx, NewIdx)) 1066 handleMoveDown(LR); 1067 else 1068 handleMoveUp(LR, Reg, LaneMask); 1069 LLVM_DEBUG(dbgs() << " -->\t" << LR << '\n'); 1070 LR.verify(); 1071 } 1072 1073 /// Update LR to reflect an instruction has been moved downwards from OldIdx 1074 /// to NewIdx (OldIdx < NewIdx). 1075 void handleMoveDown(LiveRange &LR) { 1076 LiveRange::iterator E = LR.end(); 1077 // Segment going into OldIdx. 1078 LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex()); 1079 1080 // No value live before or after OldIdx? Nothing to do. 1081 if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start)) 1082 return; 1083 1084 LiveRange::iterator OldIdxOut; 1085 // Do we have a value live-in to OldIdx? 1086 if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) { 1087 // If the live-in value already extends to NewIdx, there is nothing to do. 1088 if (SlotIndex::isEarlierEqualInstr(NewIdx, OldIdxIn->end)) 1089 return; 1090 // Aggressively remove all kill flags from the old kill point. 1091 // Kill flags shouldn't be used while live intervals exist, they will be 1092 // reinserted by VirtRegRewriter. 1093 if (MachineInstr *KillMI = LIS.getInstructionFromIndex(OldIdxIn->end)) 1094 for (MachineOperand &MOP : mi_bundle_ops(*KillMI)) 1095 if (MOP.isReg() && MOP.isUse()) 1096 MOP.setIsKill(false); 1097 1098 // Is there a def before NewIdx which is not OldIdx? 1099 LiveRange::iterator Next = std::next(OldIdxIn); 1100 if (Next != E && !SlotIndex::isSameInstr(OldIdx, Next->start) && 1101 SlotIndex::isEarlierInstr(Next->start, NewIdx)) { 1102 // If we are here then OldIdx was just a use but not a def. We only have 1103 // to ensure liveness extends to NewIdx. 1104 LiveRange::iterator NewIdxIn = 1105 LR.advanceTo(Next, NewIdx.getBaseIndex()); 1106 // Extend the segment before NewIdx if necessary. 1107 if (NewIdxIn == E || 1108 !SlotIndex::isEarlierInstr(NewIdxIn->start, NewIdx)) { 1109 LiveRange::iterator Prev = std::prev(NewIdxIn); 1110 Prev->end = NewIdx.getRegSlot(); 1111 } 1112 // Extend OldIdxIn. 1113 OldIdxIn->end = Next->start; 1114 return; 1115 } 1116 1117 // Adjust OldIdxIn->end to reach NewIdx. This may temporarily make LR 1118 // invalid by overlapping ranges. 1119 bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end); 1120 OldIdxIn->end = NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber()); 1121 // If this was not a kill, then there was no def and we're done. 1122 if (!isKill) 1123 return; 1124 1125 // Did we have a Def at OldIdx? 1126 OldIdxOut = Next; 1127 if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start)) 1128 return; 1129 } else { 1130 OldIdxOut = OldIdxIn; 1131 } 1132 1133 // If we are here then there is a Definition at OldIdx. OldIdxOut points 1134 // to the segment starting there. 1135 assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) && 1136 "No def?"); 1137 VNInfo *OldIdxVNI = OldIdxOut->valno; 1138 assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def"); 1139 1140 // If the defined value extends beyond NewIdx, just move the beginning 1141 // of the segment to NewIdx. 1142 SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber()); 1143 if (SlotIndex::isEarlierInstr(NewIdxDef, OldIdxOut->end)) { 1144 OldIdxVNI->def = NewIdxDef; 1145 OldIdxOut->start = OldIdxVNI->def; 1146 return; 1147 } 1148 1149 // If we are here then we have a Definition at OldIdx which ends before 1150 // NewIdx. 1151 1152 // Is there an existing Def at NewIdx? 1153 LiveRange::iterator AfterNewIdx 1154 = LR.advanceTo(OldIdxOut, NewIdx.getRegSlot()); 1155 bool OldIdxDefIsDead = OldIdxOut->end.isDead(); 1156 if (!OldIdxDefIsDead && 1157 SlotIndex::isEarlierInstr(OldIdxOut->end, NewIdxDef)) { 1158 // OldIdx is not a dead def, and NewIdxDef is inside a new interval. 1159 VNInfo *DefVNI; 1160 if (OldIdxOut != LR.begin() && 1161 !SlotIndex::isEarlierInstr(std::prev(OldIdxOut)->end, 1162 OldIdxOut->start)) { 1163 // There is no gap between OldIdxOut and its predecessor anymore, 1164 // merge them. 1165 LiveRange::iterator IPrev = std::prev(OldIdxOut); 1166 DefVNI = OldIdxVNI; 1167 IPrev->end = OldIdxOut->end; 1168 } else { 1169 // The value is live in to OldIdx 1170 LiveRange::iterator INext = std::next(OldIdxOut); 1171 assert(INext != E && "Must have following segment"); 1172 // We merge OldIdxOut and its successor. As we're dealing with subreg 1173 // reordering, there is always a successor to OldIdxOut in the same BB 1174 // We don't need INext->valno anymore and will reuse for the new segment 1175 // we create later. 1176 DefVNI = OldIdxVNI; 1177 INext->start = OldIdxOut->end; 1178 INext->valno->def = INext->start; 1179 } 1180 // If NewIdx is behind the last segment, extend that and append a new one. 1181 if (AfterNewIdx == E) { 1182 // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up 1183 // one position. 1184 // |- ?/OldIdxOut -| |- X0 -| ... |- Xn -| end 1185 // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS -| end 1186 std::copy(std::next(OldIdxOut), E, OldIdxOut); 1187 // The last segment is undefined now, reuse it for a dead def. 1188 LiveRange::iterator NewSegment = std::prev(E); 1189 *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(), 1190 DefVNI); 1191 DefVNI->def = NewIdxDef; 1192 1193 LiveRange::iterator Prev = std::prev(NewSegment); 1194 Prev->end = NewIdxDef; 1195 } else { 1196 // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up 1197 // one position. 1198 // |- ?/OldIdxOut -| |- X0 -| ... |- Xn/AfterNewIdx -| |- Next -| 1199 // => |- X0/OldIdxOut -| ... |- Xn -| |- Xn/AfterNewIdx -| |- Next -| 1200 std::copy(std::next(OldIdxOut), std::next(AfterNewIdx), OldIdxOut); 1201 LiveRange::iterator Prev = std::prev(AfterNewIdx); 1202 // We have two cases: 1203 if (SlotIndex::isEarlierInstr(Prev->start, NewIdxDef)) { 1204 // Case 1: NewIdx is inside a liverange. Split this liverange at 1205 // NewIdxDef into the segment "Prev" followed by "NewSegment". 1206 LiveRange::iterator NewSegment = AfterNewIdx; 1207 *NewSegment = LiveRange::Segment(NewIdxDef, Prev->end, Prev->valno); 1208 Prev->valno->def = NewIdxDef; 1209 1210 *Prev = LiveRange::Segment(Prev->start, NewIdxDef, DefVNI); 1211 DefVNI->def = Prev->start; 1212 } else { 1213 // Case 2: NewIdx is in a lifetime hole. Keep AfterNewIdx as is and 1214 // turn Prev into a segment from NewIdx to AfterNewIdx->start. 1215 *Prev = LiveRange::Segment(NewIdxDef, AfterNewIdx->start, DefVNI); 1216 DefVNI->def = NewIdxDef; 1217 assert(DefVNI != AfterNewIdx->valno); 1218 } 1219 } 1220 return; 1221 } 1222 1223 if (AfterNewIdx != E && 1224 SlotIndex::isSameInstr(AfterNewIdx->start, NewIdxDef)) { 1225 // There is an existing def at NewIdx. The def at OldIdx is coalesced into 1226 // that value. 1227 assert(AfterNewIdx->valno != OldIdxVNI && "Multiple defs of value?"); 1228 LR.removeValNo(OldIdxVNI); 1229 } else { 1230 // There was no existing def at NewIdx. We need to create a dead def 1231 // at NewIdx. Shift segments over the old OldIdxOut segment, this frees 1232 // a new segment at the place where we want to construct the dead def. 1233 // |- OldIdxOut -| |- X0 -| ... |- Xn -| |- AfterNewIdx -| 1234 // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS. -| |- AfterNewIdx -| 1235 assert(AfterNewIdx != OldIdxOut && "Inconsistent iterators"); 1236 std::copy(std::next(OldIdxOut), AfterNewIdx, OldIdxOut); 1237 // We can reuse OldIdxVNI now. 1238 LiveRange::iterator NewSegment = std::prev(AfterNewIdx); 1239 VNInfo *NewSegmentVNI = OldIdxVNI; 1240 NewSegmentVNI->def = NewIdxDef; 1241 *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(), 1242 NewSegmentVNI); 1243 } 1244 } 1245 1246 /// Update LR to reflect an instruction has been moved upwards from OldIdx 1247 /// to NewIdx (NewIdx < OldIdx). 1248 void handleMoveUp(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) { 1249 LiveRange::iterator E = LR.end(); 1250 // Segment going into OldIdx. 1251 LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex()); 1252 1253 // No value live before or after OldIdx? Nothing to do. 1254 if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start)) 1255 return; 1256 1257 LiveRange::iterator OldIdxOut; 1258 // Do we have a value live-in to OldIdx? 1259 if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) { 1260 // If the live-in value isn't killed here, then we have no Def at 1261 // OldIdx, moreover the value must be live at NewIdx so there is nothing 1262 // to do. 1263 bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end); 1264 if (!isKill) 1265 return; 1266 1267 // At this point we have to move OldIdxIn->end back to the nearest 1268 // previous use or (dead-)def but no further than NewIdx. 1269 SlotIndex DefBeforeOldIdx 1270 = std::max(OldIdxIn->start.getDeadSlot(), 1271 NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber())); 1272 OldIdxIn->end = findLastUseBefore(DefBeforeOldIdx, Reg, LaneMask); 1273 1274 // Did we have a Def at OldIdx? If not we are done now. 1275 OldIdxOut = std::next(OldIdxIn); 1276 if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start)) 1277 return; 1278 } else { 1279 OldIdxOut = OldIdxIn; 1280 OldIdxIn = OldIdxOut != LR.begin() ? std::prev(OldIdxOut) : E; 1281 } 1282 1283 // If we are here then there is a Definition at OldIdx. OldIdxOut points 1284 // to the segment starting there. 1285 assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) && 1286 "No def?"); 1287 VNInfo *OldIdxVNI = OldIdxOut->valno; 1288 assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def"); 1289 bool OldIdxDefIsDead = OldIdxOut->end.isDead(); 1290 1291 // Is there an existing def at NewIdx? 1292 SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber()); 1293 LiveRange::iterator NewIdxOut = LR.find(NewIdx.getRegSlot()); 1294 if (SlotIndex::isSameInstr(NewIdxOut->start, NewIdx)) { 1295 assert(NewIdxOut->valno != OldIdxVNI && 1296 "Same value defined more than once?"); 1297 // If OldIdx was a dead def remove it. 1298 if (!OldIdxDefIsDead) { 1299 // Remove segment starting at NewIdx and move begin of OldIdxOut to 1300 // NewIdx so it can take its place. 1301 OldIdxVNI->def = NewIdxDef; 1302 OldIdxOut->start = NewIdxDef; 1303 LR.removeValNo(NewIdxOut->valno); 1304 } else { 1305 // Simply remove the dead def at OldIdx. 1306 LR.removeValNo(OldIdxVNI); 1307 } 1308 } else { 1309 // Previously nothing was live after NewIdx, so all we have to do now is 1310 // move the begin of OldIdxOut to NewIdx. 1311 if (!OldIdxDefIsDead) { 1312 // Do we have any intermediate Defs between OldIdx and NewIdx? 1313 if (OldIdxIn != E && 1314 SlotIndex::isEarlierInstr(NewIdxDef, OldIdxIn->start)) { 1315 // OldIdx is not a dead def and NewIdx is before predecessor start. 1316 LiveRange::iterator NewIdxIn = NewIdxOut; 1317 assert(NewIdxIn == LR.find(NewIdx.getBaseIndex())); 1318 const SlotIndex SplitPos = NewIdxDef; 1319 OldIdxVNI = OldIdxIn->valno; 1320 1321 SlotIndex NewDefEndPoint = std::next(NewIdxIn)->end; 1322 LiveRange::iterator Prev = std::prev(OldIdxIn); 1323 if (OldIdxIn != LR.begin() && 1324 SlotIndex::isEarlierInstr(NewIdx, Prev->end)) { 1325 // If the segment before OldIdx read a value defined earlier than 1326 // NewIdx, the moved instruction also reads and forwards that 1327 // value. Extend the lifetime of the new def point. 1328 1329 // Extend to where the previous range started, unless there is 1330 // another redef first. 1331 NewDefEndPoint = std::min(OldIdxIn->start, 1332 std::next(NewIdxOut)->start); 1333 } 1334 1335 // Merge the OldIdxIn and OldIdxOut segments into OldIdxOut. 1336 OldIdxOut->valno->def = OldIdxIn->start; 1337 *OldIdxOut = LiveRange::Segment(OldIdxIn->start, OldIdxOut->end, 1338 OldIdxOut->valno); 1339 // OldIdxIn and OldIdxVNI are now undef and can be overridden. 1340 // We Slide [NewIdxIn, OldIdxIn) down one position. 1341 // |- X0/NewIdxIn -| ... |- Xn-1 -||- Xn/OldIdxIn -||- OldIdxOut -| 1342 // => |- undef/NexIdxIn -| |- X0 -| ... |- Xn-1 -| |- Xn/OldIdxOut -| 1343 std::copy_backward(NewIdxIn, OldIdxIn, OldIdxOut); 1344 // NewIdxIn is now considered undef so we can reuse it for the moved 1345 // value. 1346 LiveRange::iterator NewSegment = NewIdxIn; 1347 LiveRange::iterator Next = std::next(NewSegment); 1348 if (SlotIndex::isEarlierInstr(Next->start, NewIdx)) { 1349 // There is no gap between NewSegment and its predecessor. 1350 *NewSegment = LiveRange::Segment(Next->start, SplitPos, 1351 Next->valno); 1352 1353 *Next = LiveRange::Segment(SplitPos, NewDefEndPoint, OldIdxVNI); 1354 Next->valno->def = SplitPos; 1355 } else { 1356 // There is a gap between NewSegment and its predecessor 1357 // Value becomes live in. 1358 *NewSegment = LiveRange::Segment(SplitPos, Next->start, OldIdxVNI); 1359 NewSegment->valno->def = SplitPos; 1360 } 1361 } else { 1362 // Leave the end point of a live def. 1363 OldIdxOut->start = NewIdxDef; 1364 OldIdxVNI->def = NewIdxDef; 1365 if (OldIdxIn != E && SlotIndex::isEarlierInstr(NewIdx, OldIdxIn->end)) 1366 OldIdxIn->end = NewIdxDef; 1367 } 1368 } else if (OldIdxIn != E 1369 && SlotIndex::isEarlierInstr(NewIdxOut->start, NewIdx) 1370 && SlotIndex::isEarlierInstr(NewIdx, NewIdxOut->end)) { 1371 // OldIdxVNI is a dead def that has been moved into the middle of 1372 // another value in LR. That can happen when LR is a whole register, 1373 // but the dead def is a write to a subreg that is dead at NewIdx. 1374 // The dead def may have been moved across other values 1375 // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut) 1376 // down one position. 1377 // |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - | 1378 // => |- X0/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -| 1379 std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut)); 1380 // Modify the segment at NewIdxOut and the following segment to meet at 1381 // the point of the dead def, with the following segment getting 1382 // OldIdxVNI as its value number. 1383 *NewIdxOut = LiveRange::Segment( 1384 NewIdxOut->start, NewIdxDef.getRegSlot(), NewIdxOut->valno); 1385 *(NewIdxOut + 1) = LiveRange::Segment( 1386 NewIdxDef.getRegSlot(), (NewIdxOut + 1)->end, OldIdxVNI); 1387 OldIdxVNI->def = NewIdxDef; 1388 // Modify subsequent segments to be defined by the moved def OldIdxVNI. 1389 for (auto Idx = NewIdxOut + 2; Idx <= OldIdxOut; ++Idx) 1390 Idx->valno = OldIdxVNI; 1391 // Aggressively remove all dead flags from the former dead definition. 1392 // Kill/dead flags shouldn't be used while live intervals exist; they 1393 // will be reinserted by VirtRegRewriter. 1394 if (MachineInstr *KillMI = LIS.getInstructionFromIndex(NewIdx)) 1395 for (MIBundleOperands MO(*KillMI); MO.isValid(); ++MO) 1396 if (MO->isReg() && !MO->isUse()) 1397 MO->setIsDead(false); 1398 } else { 1399 // OldIdxVNI is a dead def. It may have been moved across other values 1400 // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut) 1401 // down one position. 1402 // |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - | 1403 // => |- undef/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -| 1404 std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut)); 1405 // OldIdxVNI can be reused now to build a new dead def segment. 1406 LiveRange::iterator NewSegment = NewIdxOut; 1407 VNInfo *NewSegmentVNI = OldIdxVNI; 1408 *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(), 1409 NewSegmentVNI); 1410 NewSegmentVNI->def = NewIdxDef; 1411 } 1412 } 1413 } 1414 1415 void updateRegMaskSlots() { 1416 SmallVectorImpl<SlotIndex>::iterator RI = 1417 llvm::lower_bound(LIS.RegMaskSlots, OldIdx); 1418 assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() && 1419 "No RegMask at OldIdx."); 1420 *RI = NewIdx.getRegSlot(); 1421 assert((RI == LIS.RegMaskSlots.begin() || 1422 SlotIndex::isEarlierInstr(*std::prev(RI), *RI)) && 1423 "Cannot move regmask instruction above another call"); 1424 assert((std::next(RI) == LIS.RegMaskSlots.end() || 1425 SlotIndex::isEarlierInstr(*RI, *std::next(RI))) && 1426 "Cannot move regmask instruction below another call"); 1427 } 1428 1429 // Return the last use of reg between NewIdx and OldIdx. 1430 SlotIndex findLastUseBefore(SlotIndex Before, unsigned Reg, 1431 LaneBitmask LaneMask) { 1432 if (Register::isVirtualRegister(Reg)) { 1433 SlotIndex LastUse = Before; 1434 for (MachineOperand &MO : MRI.use_nodbg_operands(Reg)) { 1435 if (MO.isUndef()) 1436 continue; 1437 unsigned SubReg = MO.getSubReg(); 1438 if (SubReg != 0 && LaneMask.any() 1439 && (TRI.getSubRegIndexLaneMask(SubReg) & LaneMask).none()) 1440 continue; 1441 1442 const MachineInstr &MI = *MO.getParent(); 1443 SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI); 1444 if (InstSlot > LastUse && InstSlot < OldIdx) 1445 LastUse = InstSlot.getRegSlot(); 1446 } 1447 return LastUse; 1448 } 1449 1450 // This is a regunit interval, so scanning the use list could be very 1451 // expensive. Scan upwards from OldIdx instead. 1452 assert(Before < OldIdx && "Expected upwards move"); 1453 SlotIndexes *Indexes = LIS.getSlotIndexes(); 1454 MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Before); 1455 1456 // OldIdx may not correspond to an instruction any longer, so set MII to 1457 // point to the next instruction after OldIdx, or MBB->end(). 1458 MachineBasicBlock::iterator MII = MBB->end(); 1459 if (MachineInstr *MI = Indexes->getInstructionFromIndex( 1460 Indexes->getNextNonNullIndex(OldIdx))) 1461 if (MI->getParent() == MBB) 1462 MII = MI; 1463 1464 MachineBasicBlock::iterator Begin = MBB->begin(); 1465 while (MII != Begin) { 1466 if ((--MII)->isDebugInstr()) 1467 continue; 1468 SlotIndex Idx = Indexes->getInstructionIndex(*MII); 1469 1470 // Stop searching when Before is reached. 1471 if (!SlotIndex::isEarlierInstr(Before, Idx)) 1472 return Before; 1473 1474 // Check if MII uses Reg. 1475 for (MIBundleOperands MO(*MII); MO.isValid(); ++MO) 1476 if (MO->isReg() && !MO->isUndef() && 1477 Register::isPhysicalRegister(MO->getReg()) && 1478 TRI.hasRegUnit(MO->getReg(), Reg)) 1479 return Idx.getRegSlot(); 1480 } 1481 // Didn't reach Before. It must be the first instruction in the block. 1482 return Before; 1483 } 1484 }; 1485 1486 void LiveIntervals::handleMove(MachineInstr &MI, bool UpdateFlags) { 1487 // It is fine to move a bundle as a whole, but not an individual instruction 1488 // inside it. 1489 assert((!MI.isBundled() || MI.getOpcode() == TargetOpcode::BUNDLE) && 1490 "Cannot move instruction in bundle"); 1491 SlotIndex OldIndex = Indexes->getInstructionIndex(MI); 1492 Indexes->removeMachineInstrFromMaps(MI); 1493 SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI); 1494 assert(getMBBStartIdx(MI.getParent()) <= OldIndex && 1495 OldIndex < getMBBEndIdx(MI.getParent()) && 1496 "Cannot handle moves across basic block boundaries."); 1497 1498 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags); 1499 HME.updateAllRanges(&MI); 1500 } 1501 1502 void LiveIntervals::handleMoveIntoNewBundle(MachineInstr &BundleStart, 1503 bool UpdateFlags) { 1504 assert((BundleStart.getOpcode() == TargetOpcode::BUNDLE) && 1505 "Bundle start is not a bundle"); 1506 SmallVector<SlotIndex, 16> ToProcess; 1507 const SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(BundleStart); 1508 auto BundleEnd = getBundleEnd(BundleStart.getIterator()); 1509 1510 auto I = BundleStart.getIterator(); 1511 I++; 1512 while (I != BundleEnd) { 1513 if (!Indexes->hasIndex(*I)) 1514 continue; 1515 SlotIndex OldIndex = Indexes->getInstructionIndex(*I, true); 1516 ToProcess.push_back(OldIndex); 1517 Indexes->removeMachineInstrFromMaps(*I, true); 1518 I++; 1519 } 1520 for (SlotIndex OldIndex : ToProcess) { 1521 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags); 1522 HME.updateAllRanges(&BundleStart); 1523 } 1524 1525 // Fix up dead defs 1526 const SlotIndex Index = getInstructionIndex(BundleStart); 1527 for (unsigned Idx = 0, E = BundleStart.getNumOperands(); Idx != E; ++Idx) { 1528 MachineOperand &MO = BundleStart.getOperand(Idx); 1529 if (!MO.isReg()) 1530 continue; 1531 Register Reg = MO.getReg(); 1532 if (Reg.isVirtual() && hasInterval(Reg) && !MO.isUndef()) { 1533 LiveInterval &LI = getInterval(Reg); 1534 LiveQueryResult LRQ = LI.Query(Index); 1535 if (LRQ.isDeadDef()) 1536 MO.setIsDead(); 1537 } 1538 } 1539 } 1540 1541 void LiveIntervals::repairOldRegInRange(const MachineBasicBlock::iterator Begin, 1542 const MachineBasicBlock::iterator End, 1543 const SlotIndex endIdx, 1544 LiveRange &LR, const unsigned Reg, 1545 LaneBitmask LaneMask) { 1546 LiveInterval::iterator LII = LR.find(endIdx); 1547 SlotIndex lastUseIdx; 1548 if (LII == LR.begin()) { 1549 // This happens when the function is called for a subregister that only 1550 // occurs _after_ the range that is to be repaired. 1551 return; 1552 } 1553 if (LII != LR.end() && LII->start < endIdx) 1554 lastUseIdx = LII->end; 1555 else 1556 --LII; 1557 1558 for (MachineBasicBlock::iterator I = End; I != Begin;) { 1559 --I; 1560 MachineInstr &MI = *I; 1561 if (MI.isDebugInstr()) 1562 continue; 1563 1564 SlotIndex instrIdx = getInstructionIndex(MI); 1565 bool isStartValid = getInstructionFromIndex(LII->start); 1566 bool isEndValid = getInstructionFromIndex(LII->end); 1567 1568 // FIXME: This doesn't currently handle early-clobber or multiple removed 1569 // defs inside of the region to repair. 1570 for (MachineInstr::mop_iterator OI = MI.operands_begin(), 1571 OE = MI.operands_end(); 1572 OI != OE; ++OI) { 1573 const MachineOperand &MO = *OI; 1574 if (!MO.isReg() || MO.getReg() != Reg) 1575 continue; 1576 1577 unsigned SubReg = MO.getSubReg(); 1578 LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubReg); 1579 if ((Mask & LaneMask).none()) 1580 continue; 1581 1582 if (MO.isDef()) { 1583 if (!isStartValid) { 1584 if (LII->end.isDead()) { 1585 SlotIndex prevStart; 1586 if (LII != LR.begin()) 1587 prevStart = std::prev(LII)->start; 1588 1589 // FIXME: This could be more efficient if there was a 1590 // removeSegment method that returned an iterator. 1591 LR.removeSegment(*LII, true); 1592 if (prevStart.isValid()) 1593 LII = LR.find(prevStart); 1594 else 1595 LII = LR.begin(); 1596 } else { 1597 LII->start = instrIdx.getRegSlot(); 1598 LII->valno->def = instrIdx.getRegSlot(); 1599 if (MO.getSubReg() && !MO.isUndef()) 1600 lastUseIdx = instrIdx.getRegSlot(); 1601 else 1602 lastUseIdx = SlotIndex(); 1603 continue; 1604 } 1605 } 1606 1607 if (!lastUseIdx.isValid()) { 1608 VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator); 1609 LiveRange::Segment S(instrIdx.getRegSlot(), 1610 instrIdx.getDeadSlot(), VNI); 1611 LII = LR.addSegment(S); 1612 } else if (LII->start != instrIdx.getRegSlot()) { 1613 VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator); 1614 LiveRange::Segment S(instrIdx.getRegSlot(), lastUseIdx, VNI); 1615 LII = LR.addSegment(S); 1616 } 1617 1618 if (MO.getSubReg() && !MO.isUndef()) 1619 lastUseIdx = instrIdx.getRegSlot(); 1620 else 1621 lastUseIdx = SlotIndex(); 1622 } else if (MO.isUse()) { 1623 // FIXME: This should probably be handled outside of this branch, 1624 // either as part of the def case (for defs inside of the region) or 1625 // after the loop over the region. 1626 if (!isEndValid && !LII->end.isBlock()) 1627 LII->end = instrIdx.getRegSlot(); 1628 if (!lastUseIdx.isValid()) 1629 lastUseIdx = instrIdx.getRegSlot(); 1630 } 1631 } 1632 } 1633 } 1634 1635 void 1636 LiveIntervals::repairIntervalsInRange(MachineBasicBlock *MBB, 1637 MachineBasicBlock::iterator Begin, 1638 MachineBasicBlock::iterator End, 1639 ArrayRef<Register> OrigRegs) { 1640 // Find anchor points, which are at the beginning/end of blocks or at 1641 // instructions that already have indexes. 1642 while (Begin != MBB->begin() && !Indexes->hasIndex(*Begin)) 1643 --Begin; 1644 while (End != MBB->end() && !Indexes->hasIndex(*End)) 1645 ++End; 1646 1647 SlotIndex endIdx; 1648 if (End == MBB->end()) 1649 endIdx = getMBBEndIdx(MBB).getPrevSlot(); 1650 else 1651 endIdx = getInstructionIndex(*End); 1652 1653 Indexes->repairIndexesInRange(MBB, Begin, End); 1654 1655 for (MachineBasicBlock::iterator I = End; I != Begin;) { 1656 --I; 1657 MachineInstr &MI = *I; 1658 if (MI.isDebugInstr()) 1659 continue; 1660 for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(), 1661 MOE = MI.operands_end(); 1662 MOI != MOE; ++MOI) { 1663 if (MOI->isReg() && Register::isVirtualRegister(MOI->getReg()) && 1664 !hasInterval(MOI->getReg())) { 1665 createAndComputeVirtRegInterval(MOI->getReg()); 1666 } 1667 } 1668 } 1669 1670 for (Register Reg : OrigRegs) { 1671 if (!Reg.isVirtual()) 1672 continue; 1673 1674 LiveInterval &LI = getInterval(Reg); 1675 // FIXME: Should we support undefs that gain defs? 1676 if (!LI.hasAtLeastOneValue()) 1677 continue; 1678 1679 for (LiveInterval::SubRange &S : LI.subranges()) 1680 repairOldRegInRange(Begin, End, endIdx, S, Reg, S.LaneMask); 1681 1682 repairOldRegInRange(Begin, End, endIdx, LI, Reg); 1683 } 1684 } 1685 1686 void LiveIntervals::removePhysRegDefAt(unsigned Reg, SlotIndex Pos) { 1687 for (MCRegUnitIterator Unit(Reg, TRI); Unit.isValid(); ++Unit) { 1688 if (LiveRange *LR = getCachedRegUnit(*Unit)) 1689 if (VNInfo *VNI = LR->getVNInfoAt(Pos)) 1690 LR->removeValNo(VNI); 1691 } 1692 } 1693 1694 void LiveIntervals::removeVRegDefAt(LiveInterval &LI, SlotIndex Pos) { 1695 // LI may not have the main range computed yet, but its subranges may 1696 // be present. 1697 VNInfo *VNI = LI.getVNInfoAt(Pos); 1698 if (VNI != nullptr) { 1699 assert(VNI->def.getBaseIndex() == Pos.getBaseIndex()); 1700 LI.removeValNo(VNI); 1701 } 1702 1703 // Also remove the value defined in subranges. 1704 for (LiveInterval::SubRange &S : LI.subranges()) { 1705 if (VNInfo *SVNI = S.getVNInfoAt(Pos)) 1706 if (SVNI->def.getBaseIndex() == Pos.getBaseIndex()) 1707 S.removeValNo(SVNI); 1708 } 1709 LI.removeEmptySubRanges(); 1710 } 1711 1712 void LiveIntervals::splitSeparateComponents(LiveInterval &LI, 1713 SmallVectorImpl<LiveInterval*> &SplitLIs) { 1714 ConnectedVNInfoEqClasses ConEQ(*this); 1715 unsigned NumComp = ConEQ.Classify(LI); 1716 if (NumComp <= 1) 1717 return; 1718 LLVM_DEBUG(dbgs() << " Split " << NumComp << " components: " << LI << '\n'); 1719 unsigned Reg = LI.reg(); 1720 const TargetRegisterClass *RegClass = MRI->getRegClass(Reg); 1721 for (unsigned I = 1; I < NumComp; ++I) { 1722 Register NewVReg = MRI->createVirtualRegister(RegClass); 1723 LiveInterval &NewLI = createEmptyInterval(NewVReg); 1724 SplitLIs.push_back(&NewLI); 1725 } 1726 ConEQ.Distribute(LI, SplitLIs.data(), *MRI); 1727 } 1728 1729 void LiveIntervals::constructMainRangeFromSubranges(LiveInterval &LI) { 1730 assert(LICalc && "LICalc not initialized."); 1731 LICalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator()); 1732 LICalc->constructMainRangeFromSubranges(LI); 1733 } 1734