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