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