1 //===- RegAllocGreedy.cpp - greedy register allocator ---------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the RAGreedy function pass for register allocation in 10 // optimized builds. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "RegAllocGreedy.h" 15 #include "AllocationOrder.h" 16 #include "InterferenceCache.h" 17 #include "LiveDebugVariables.h" 18 #include "RegAllocBase.h" 19 #include "RegAllocEvictionAdvisor.h" 20 #include "RegAllocPriorityAdvisor.h" 21 #include "SpillPlacement.h" 22 #include "SplitKit.h" 23 #include "llvm/ADT/ArrayRef.h" 24 #include "llvm/ADT/BitVector.h" 25 #include "llvm/ADT/IndexedMap.h" 26 #include "llvm/ADT/SmallPtrSet.h" 27 #include "llvm/ADT/SmallSet.h" 28 #include "llvm/ADT/SmallVector.h" 29 #include "llvm/ADT/Statistic.h" 30 #include "llvm/ADT/StringRef.h" 31 #include "llvm/Analysis/AliasAnalysis.h" 32 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 33 #include "llvm/CodeGen/CalcSpillWeights.h" 34 #include "llvm/CodeGen/EdgeBundles.h" 35 #include "llvm/CodeGen/LiveInterval.h" 36 #include "llvm/CodeGen/LiveIntervalUnion.h" 37 #include "llvm/CodeGen/LiveIntervals.h" 38 #include "llvm/CodeGen/LiveRangeEdit.h" 39 #include "llvm/CodeGen/LiveRegMatrix.h" 40 #include "llvm/CodeGen/LiveStacks.h" 41 #include "llvm/CodeGen/MachineBasicBlock.h" 42 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 43 #include "llvm/CodeGen/MachineDominators.h" 44 #include "llvm/CodeGen/MachineFrameInfo.h" 45 #include "llvm/CodeGen/MachineFunction.h" 46 #include "llvm/CodeGen/MachineFunctionPass.h" 47 #include "llvm/CodeGen/MachineInstr.h" 48 #include "llvm/CodeGen/MachineLoopInfo.h" 49 #include "llvm/CodeGen/MachineOperand.h" 50 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h" 51 #include "llvm/CodeGen/MachineRegisterInfo.h" 52 #include "llvm/CodeGen/RegAllocRegistry.h" 53 #include "llvm/CodeGen/RegisterClassInfo.h" 54 #include "llvm/CodeGen/SlotIndexes.h" 55 #include "llvm/CodeGen/Spiller.h" 56 #include "llvm/CodeGen/TargetInstrInfo.h" 57 #include "llvm/CodeGen/TargetRegisterInfo.h" 58 #include "llvm/CodeGen/TargetSubtargetInfo.h" 59 #include "llvm/CodeGen/VirtRegMap.h" 60 #include "llvm/IR/DebugInfoMetadata.h" 61 #include "llvm/IR/Function.h" 62 #include "llvm/IR/LLVMContext.h" 63 #include "llvm/InitializePasses.h" 64 #include "llvm/MC/MCRegisterInfo.h" 65 #include "llvm/Pass.h" 66 #include "llvm/Support/BlockFrequency.h" 67 #include "llvm/Support/BranchProbability.h" 68 #include "llvm/Support/CommandLine.h" 69 #include "llvm/Support/Debug.h" 70 #include "llvm/Support/MathExtras.h" 71 #include "llvm/Support/Timer.h" 72 #include "llvm/Support/raw_ostream.h" 73 #include <algorithm> 74 #include <cassert> 75 #include <cstdint> 76 #include <utility> 77 78 using namespace llvm; 79 80 #define DEBUG_TYPE "regalloc" 81 82 STATISTIC(NumGlobalSplits, "Number of split global live ranges"); 83 STATISTIC(NumLocalSplits, "Number of split local live ranges"); 84 STATISTIC(NumEvicted, "Number of interferences evicted"); 85 86 static cl::opt<SplitEditor::ComplementSpillMode> SplitSpillMode( 87 "split-spill-mode", cl::Hidden, 88 cl::desc("Spill mode for splitting live ranges"), 89 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"), 90 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"), 91 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed")), 92 cl::init(SplitEditor::SM_Speed)); 93 94 static cl::opt<unsigned> 95 LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden, 96 cl::desc("Last chance recoloring max depth"), 97 cl::init(5)); 98 99 static cl::opt<unsigned> LastChanceRecoloringMaxInterference( 100 "lcr-max-interf", cl::Hidden, 101 cl::desc("Last chance recoloring maximum number of considered" 102 " interference at a time"), 103 cl::init(8)); 104 105 static cl::opt<bool> ExhaustiveSearch( 106 "exhaustive-register-search", cl::NotHidden, 107 cl::desc("Exhaustive Search for registers bypassing the depth " 108 "and interference cutoffs of last chance recoloring"), 109 cl::Hidden); 110 111 static cl::opt<bool> EnableDeferredSpilling( 112 "enable-deferred-spilling", cl::Hidden, 113 cl::desc("Instead of spilling a variable right away, defer the actual " 114 "code insertion to the end of the allocation. That way the " 115 "allocator might still find a suitable coloring for this " 116 "variable because of other evicted variables."), 117 cl::init(false)); 118 119 // FIXME: Find a good default for this flag and remove the flag. 120 static cl::opt<unsigned> 121 CSRFirstTimeCost("regalloc-csr-first-time-cost", 122 cl::desc("Cost for first time use of callee-saved register."), 123 cl::init(0), cl::Hidden); 124 125 static cl::opt<unsigned long> GrowRegionComplexityBudget( 126 "grow-region-complexity-budget", 127 cl::desc("growRegion() does not scale with the number of BB edges, so " 128 "limit its budget and bail out once we reach the limit."), 129 cl::init(10000), cl::Hidden); 130 131 static cl::opt<bool> GreedyRegClassPriorityTrumpsGlobalness( 132 "greedy-regclass-priority-trumps-globalness", 133 cl::desc("Change the greedy register allocator's live range priority " 134 "calculation to make the AllocationPriority of the register class " 135 "more important then whether the range is global"), 136 cl::Hidden); 137 138 static cl::opt<bool> GreedyReverseLocalAssignment( 139 "greedy-reverse-local-assignment", 140 cl::desc("Reverse allocation order of local live ranges, such that " 141 "shorter local live ranges will tend to be allocated first"), 142 cl::Hidden); 143 144 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator", 145 createGreedyRegisterAllocator); 146 147 char RAGreedy::ID = 0; 148 char &llvm::RAGreedyID = RAGreedy::ID; 149 150 INITIALIZE_PASS_BEGIN(RAGreedy, "greedy", 151 "Greedy Register Allocator", false, false) 152 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables) 153 INITIALIZE_PASS_DEPENDENCY(SlotIndexes) 154 INITIALIZE_PASS_DEPENDENCY(LiveIntervals) 155 INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer) 156 INITIALIZE_PASS_DEPENDENCY(MachineScheduler) 157 INITIALIZE_PASS_DEPENDENCY(LiveStacks) 158 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 159 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 160 INITIALIZE_PASS_DEPENDENCY(VirtRegMap) 161 INITIALIZE_PASS_DEPENDENCY(LiveRegMatrix) 162 INITIALIZE_PASS_DEPENDENCY(EdgeBundles) 163 INITIALIZE_PASS_DEPENDENCY(SpillPlacement) 164 INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass) 165 INITIALIZE_PASS_DEPENDENCY(RegAllocEvictionAdvisorAnalysis) 166 INITIALIZE_PASS_DEPENDENCY(RegAllocPriorityAdvisorAnalysis) 167 INITIALIZE_PASS_END(RAGreedy, "greedy", 168 "Greedy Register Allocator", false, false) 169 170 #ifndef NDEBUG 171 const char *const RAGreedy::StageName[] = { 172 "RS_New", 173 "RS_Assign", 174 "RS_Split", 175 "RS_Split2", 176 "RS_Spill", 177 "RS_Memory", 178 "RS_Done" 179 }; 180 #endif 181 182 // Hysteresis to use when comparing floats. 183 // This helps stabilize decisions based on float comparisons. 184 const float Hysteresis = (2007 / 2048.0f); // 0.97998046875 185 186 FunctionPass* llvm::createGreedyRegisterAllocator() { 187 return new RAGreedy(); 188 } 189 190 FunctionPass *llvm::createGreedyRegisterAllocator(RegClassFilterFunc Ftor) { 191 return new RAGreedy(Ftor); 192 } 193 194 RAGreedy::RAGreedy(RegClassFilterFunc F): 195 MachineFunctionPass(ID), 196 RegAllocBase(F) { 197 } 198 199 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const { 200 AU.setPreservesCFG(); 201 AU.addRequired<MachineBlockFrequencyInfo>(); 202 AU.addPreserved<MachineBlockFrequencyInfo>(); 203 AU.addRequired<LiveIntervals>(); 204 AU.addPreserved<LiveIntervals>(); 205 AU.addRequired<SlotIndexes>(); 206 AU.addPreserved<SlotIndexes>(); 207 AU.addRequired<LiveDebugVariables>(); 208 AU.addPreserved<LiveDebugVariables>(); 209 AU.addRequired<LiveStacks>(); 210 AU.addPreserved<LiveStacks>(); 211 AU.addRequired<MachineDominatorTree>(); 212 AU.addPreserved<MachineDominatorTree>(); 213 AU.addRequired<MachineLoopInfo>(); 214 AU.addPreserved<MachineLoopInfo>(); 215 AU.addRequired<VirtRegMap>(); 216 AU.addPreserved<VirtRegMap>(); 217 AU.addRequired<LiveRegMatrix>(); 218 AU.addPreserved<LiveRegMatrix>(); 219 AU.addRequired<EdgeBundles>(); 220 AU.addRequired<SpillPlacement>(); 221 AU.addRequired<MachineOptimizationRemarkEmitterPass>(); 222 AU.addRequired<RegAllocEvictionAdvisorAnalysis>(); 223 AU.addRequired<RegAllocPriorityAdvisorAnalysis>(); 224 MachineFunctionPass::getAnalysisUsage(AU); 225 } 226 227 //===----------------------------------------------------------------------===// 228 // LiveRangeEdit delegate methods 229 //===----------------------------------------------------------------------===// 230 231 bool RAGreedy::LRE_CanEraseVirtReg(Register VirtReg) { 232 LiveInterval &LI = LIS->getInterval(VirtReg); 233 if (VRM->hasPhys(VirtReg)) { 234 Matrix->unassign(LI); 235 aboutToRemoveInterval(LI); 236 return true; 237 } 238 // Unassigned virtreg is probably in the priority queue. 239 // RegAllocBase will erase it after dequeueing. 240 // Nonetheless, clear the live-range so that the debug 241 // dump will show the right state for that VirtReg. 242 LI.clear(); 243 return false; 244 } 245 246 void RAGreedy::LRE_WillShrinkVirtReg(Register VirtReg) { 247 if (!VRM->hasPhys(VirtReg)) 248 return; 249 250 // Register is assigned, put it back on the queue for reassignment. 251 LiveInterval &LI = LIS->getInterval(VirtReg); 252 Matrix->unassign(LI); 253 RegAllocBase::enqueue(&LI); 254 } 255 256 void RAGreedy::LRE_DidCloneVirtReg(Register New, Register Old) { 257 ExtraInfo->LRE_DidCloneVirtReg(New, Old); 258 } 259 260 void RAGreedy::ExtraRegInfo::LRE_DidCloneVirtReg(Register New, Register Old) { 261 // Cloning a register we haven't even heard about yet? Just ignore it. 262 if (!Info.inBounds(Old)) 263 return; 264 265 // LRE may clone a virtual register because dead code elimination causes it to 266 // be split into connected components. The new components are much smaller 267 // than the original, so they should get a new chance at being assigned. 268 // same stage as the parent. 269 Info[Old].Stage = RS_Assign; 270 Info.grow(New.id()); 271 Info[New] = Info[Old]; 272 } 273 274 void RAGreedy::releaseMemory() { 275 SpillerInstance.reset(); 276 GlobalCand.clear(); 277 } 278 279 void RAGreedy::enqueueImpl(const LiveInterval *LI) { enqueue(Queue, LI); } 280 281 void RAGreedy::enqueue(PQueue &CurQueue, const LiveInterval *LI) { 282 // Prioritize live ranges by size, assigning larger ranges first. 283 // The queue holds (size, reg) pairs. 284 const Register Reg = LI->reg(); 285 assert(Reg.isVirtual() && "Can only enqueue virtual registers"); 286 287 auto Stage = ExtraInfo->getOrInitStage(Reg); 288 if (Stage == RS_New) { 289 Stage = RS_Assign; 290 ExtraInfo->setStage(Reg, Stage); 291 } 292 293 unsigned Ret = PriorityAdvisor->getPriority(*LI); 294 295 // The virtual register number is a tie breaker for same-sized ranges. 296 // Give lower vreg numbers higher priority to assign them first. 297 CurQueue.push(std::make_pair(Ret, ~Reg)); 298 } 299 300 unsigned DefaultPriorityAdvisor::getPriority(const LiveInterval &LI) const { 301 const unsigned Size = LI.getSize(); 302 const Register Reg = LI.reg(); 303 unsigned Prio; 304 LiveRangeStage Stage = RA.getExtraInfo().getStage(LI); 305 306 if (Stage == RS_Split) { 307 // Unsplit ranges that couldn't be allocated immediately are deferred until 308 // everything else has been allocated. 309 Prio = Size; 310 } else if (Stage == RS_Memory) { 311 // Memory operand should be considered last. 312 // Change the priority such that Memory operand are assigned in 313 // the reverse order that they came in. 314 // TODO: Make this a member variable and probably do something about hints. 315 static unsigned MemOp = 0; 316 Prio = MemOp++; 317 } else { 318 // Giant live ranges fall back to the global assignment heuristic, which 319 // prevents excessive spilling in pathological cases. 320 const TargetRegisterClass &RC = *MRI->getRegClass(Reg); 321 bool ForceGlobal = RC.GlobalPriority || 322 (!ReverseLocalAssignment && 323 (Size / SlotIndex::InstrDist) > 324 (2 * RegClassInfo.getNumAllocatableRegs(&RC))); 325 unsigned GlobalBit = 0; 326 327 if (Stage == RS_Assign && !ForceGlobal && !LI.empty() && 328 LIS->intervalIsInOneMBB(LI)) { 329 // Allocate original local ranges in linear instruction order. Since they 330 // are singly defined, this produces optimal coloring in the absence of 331 // global interference and other constraints. 332 if (!ReverseLocalAssignment) 333 Prio = LI.beginIndex().getApproxInstrDistance(Indexes->getLastIndex()); 334 else { 335 // Allocating bottom up may allow many short LRGs to be assigned first 336 // to one of the cheap registers. This could be much faster for very 337 // large blocks on targets with many physical registers. 338 Prio = Indexes->getZeroIndex().getApproxInstrDistance(LI.endIndex()); 339 } 340 } else { 341 // Allocate global and split ranges in long->short order. Long ranges that 342 // don't fit should be spilled (or split) ASAP so they don't create 343 // interference. Mark a bit to prioritize global above local ranges. 344 Prio = Size; 345 GlobalBit = 1; 346 } 347 348 // Priority bit layout: 349 // 31 RS_Assign priority 350 // 30 Preference priority 351 // if (RegClassPriorityTrumpsGlobalness) 352 // 29-25 AllocPriority 353 // 24 GlobalBit 354 // else 355 // 29 Global bit 356 // 28-24 AllocPriority 357 // 0-23 Size/Instr distance 358 359 // Clamp the size to fit with the priority masking scheme 360 Prio = std::min(Prio, (unsigned)maxUIntN(24)); 361 assert(isUInt<5>(RC.AllocationPriority) && "allocation priority overflow"); 362 363 if (RegClassPriorityTrumpsGlobalness) 364 Prio |= RC.AllocationPriority << 25 | GlobalBit << 24; 365 else 366 Prio |= GlobalBit << 29 | RC.AllocationPriority << 24; 367 368 // Mark a higher bit to prioritize global and local above RS_Split. 369 Prio |= (1u << 31); 370 371 // Boost ranges that have a physical register hint. 372 if (VRM->hasKnownPreference(Reg)) 373 Prio |= (1u << 30); 374 } 375 376 return Prio; 377 } 378 379 const LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); } 380 381 const LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) { 382 if (CurQueue.empty()) 383 return nullptr; 384 LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second); 385 CurQueue.pop(); 386 return LI; 387 } 388 389 //===----------------------------------------------------------------------===// 390 // Direct Assignment 391 //===----------------------------------------------------------------------===// 392 393 /// tryAssign - Try to assign VirtReg to an available register. 394 MCRegister RAGreedy::tryAssign(const LiveInterval &VirtReg, 395 AllocationOrder &Order, 396 SmallVectorImpl<Register> &NewVRegs, 397 const SmallVirtRegSet &FixedRegisters) { 398 MCRegister PhysReg; 399 for (auto I = Order.begin(), E = Order.end(); I != E && !PhysReg; ++I) { 400 assert(*I); 401 if (!Matrix->checkInterference(VirtReg, *I)) { 402 if (I.isHint()) 403 return *I; 404 else 405 PhysReg = *I; 406 } 407 } 408 if (!PhysReg.isValid()) 409 return PhysReg; 410 411 // PhysReg is available, but there may be a better choice. 412 413 // If we missed a simple hint, try to cheaply evict interference from the 414 // preferred register. 415 if (Register Hint = MRI->getSimpleHint(VirtReg.reg())) 416 if (Order.isHint(Hint)) { 417 MCRegister PhysHint = Hint.asMCReg(); 418 LLVM_DEBUG(dbgs() << "missed hint " << printReg(PhysHint, TRI) << '\n'); 419 420 if (EvictAdvisor->canEvictHintInterference(VirtReg, PhysHint, 421 FixedRegisters)) { 422 evictInterference(VirtReg, PhysHint, NewVRegs); 423 return PhysHint; 424 } 425 // Record the missed hint, we may be able to recover 426 // at the end if the surrounding allocation changed. 427 SetOfBrokenHints.insert(&VirtReg); 428 } 429 430 // Try to evict interference from a cheaper alternative. 431 uint8_t Cost = RegCosts[PhysReg]; 432 433 // Most registers have 0 additional cost. 434 if (!Cost) 435 return PhysReg; 436 437 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << " is available at cost " 438 << (unsigned)Cost << '\n'); 439 MCRegister CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost, FixedRegisters); 440 return CheapReg ? CheapReg : PhysReg; 441 } 442 443 //===----------------------------------------------------------------------===// 444 // Interference eviction 445 //===----------------------------------------------------------------------===// 446 447 bool RegAllocEvictionAdvisor::canReassign(const LiveInterval &VirtReg, 448 MCRegister FromReg) const { 449 auto HasRegUnitInterference = [&](MCRegUnit Unit) { 450 // Instantiate a "subquery", not to be confused with the Queries array. 451 LiveIntervalUnion::Query SubQ(VirtReg, Matrix->getLiveUnions()[Unit]); 452 return SubQ.checkInterference(); 453 }; 454 455 for (MCRegister Reg : 456 AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix)) { 457 if (Reg == FromReg) 458 continue; 459 // If no units have interference, reassignment is possible. 460 if (none_of(TRI->regunits(Reg), HasRegUnitInterference)) { 461 LLVM_DEBUG(dbgs() << "can reassign: " << VirtReg << " from " 462 << printReg(FromReg, TRI) << " to " 463 << printReg(Reg, TRI) << '\n'); 464 return true; 465 } 466 } 467 return false; 468 } 469 470 /// evictInterference - Evict any interferring registers that prevent VirtReg 471 /// from being assigned to Physreg. This assumes that canEvictInterference 472 /// returned true. 473 void RAGreedy::evictInterference(const LiveInterval &VirtReg, 474 MCRegister PhysReg, 475 SmallVectorImpl<Register> &NewVRegs) { 476 // Make sure that VirtReg has a cascade number, and assign that cascade 477 // number to every evicted register. These live ranges than then only be 478 // evicted by a newer cascade, preventing infinite loops. 479 unsigned Cascade = ExtraInfo->getOrAssignNewCascade(VirtReg.reg()); 480 481 LLVM_DEBUG(dbgs() << "evicting " << printReg(PhysReg, TRI) 482 << " interference: Cascade " << Cascade << '\n'); 483 484 // Collect all interfering virtregs first. 485 SmallVector<const LiveInterval *, 8> Intfs; 486 for (MCRegUnit Unit : TRI->regunits(PhysReg)) { 487 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, Unit); 488 // We usually have the interfering VRegs cached so collectInterferingVRegs() 489 // should be fast, we may need to recalculate if when different physregs 490 // overlap the same register unit so we had different SubRanges queried 491 // against it. 492 ArrayRef<const LiveInterval *> IVR = Q.interferingVRegs(); 493 Intfs.append(IVR.begin(), IVR.end()); 494 } 495 496 // Evict them second. This will invalidate the queries. 497 for (const LiveInterval *Intf : Intfs) { 498 // The same VirtReg may be present in multiple RegUnits. Skip duplicates. 499 if (!VRM->hasPhys(Intf->reg())) 500 continue; 501 502 Matrix->unassign(*Intf); 503 assert((ExtraInfo->getCascade(Intf->reg()) < Cascade || 504 VirtReg.isSpillable() < Intf->isSpillable()) && 505 "Cannot decrease cascade number, illegal eviction"); 506 ExtraInfo->setCascade(Intf->reg(), Cascade); 507 ++NumEvicted; 508 NewVRegs.push_back(Intf->reg()); 509 } 510 } 511 512 /// Returns true if the given \p PhysReg is a callee saved register and has not 513 /// been used for allocation yet. 514 bool RegAllocEvictionAdvisor::isUnusedCalleeSavedReg(MCRegister PhysReg) const { 515 MCRegister CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg); 516 if (!CSR) 517 return false; 518 519 return !Matrix->isPhysRegUsed(PhysReg); 520 } 521 522 std::optional<unsigned> 523 RegAllocEvictionAdvisor::getOrderLimit(const LiveInterval &VirtReg, 524 const AllocationOrder &Order, 525 unsigned CostPerUseLimit) const { 526 unsigned OrderLimit = Order.getOrder().size(); 527 528 if (CostPerUseLimit < uint8_t(~0u)) { 529 // Check of any registers in RC are below CostPerUseLimit. 530 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg()); 531 uint8_t MinCost = RegClassInfo.getMinCost(RC); 532 if (MinCost >= CostPerUseLimit) { 533 LLVM_DEBUG(dbgs() << TRI->getRegClassName(RC) << " minimum cost = " 534 << MinCost << ", no cheaper registers to be found.\n"); 535 return std::nullopt; 536 } 537 538 // It is normal for register classes to have a long tail of registers with 539 // the same cost. We don't need to look at them if they're too expensive. 540 if (RegCosts[Order.getOrder().back()] >= CostPerUseLimit) { 541 OrderLimit = RegClassInfo.getLastCostChange(RC); 542 LLVM_DEBUG(dbgs() << "Only trying the first " << OrderLimit 543 << " regs.\n"); 544 } 545 } 546 return OrderLimit; 547 } 548 549 bool RegAllocEvictionAdvisor::canAllocatePhysReg(unsigned CostPerUseLimit, 550 MCRegister PhysReg) const { 551 if (RegCosts[PhysReg] >= CostPerUseLimit) 552 return false; 553 // The first use of a callee-saved register in a function has cost 1. 554 // Don't start using a CSR when the CostPerUseLimit is low. 555 if (CostPerUseLimit == 1 && isUnusedCalleeSavedReg(PhysReg)) { 556 LLVM_DEBUG( 557 dbgs() << printReg(PhysReg, TRI) << " would clobber CSR " 558 << printReg(RegClassInfo.getLastCalleeSavedAlias(PhysReg), TRI) 559 << '\n'); 560 return false; 561 } 562 return true; 563 } 564 565 /// tryEvict - Try to evict all interferences for a physreg. 566 /// @param VirtReg Currently unassigned virtual register. 567 /// @param Order Physregs to try. 568 /// @return Physreg to assign VirtReg, or 0. 569 MCRegister RAGreedy::tryEvict(const LiveInterval &VirtReg, 570 AllocationOrder &Order, 571 SmallVectorImpl<Register> &NewVRegs, 572 uint8_t CostPerUseLimit, 573 const SmallVirtRegSet &FixedRegisters) { 574 NamedRegionTimer T("evict", "Evict", TimerGroupName, TimerGroupDescription, 575 TimePassesIsEnabled); 576 577 MCRegister BestPhys = EvictAdvisor->tryFindEvictionCandidate( 578 VirtReg, Order, CostPerUseLimit, FixedRegisters); 579 if (BestPhys.isValid()) 580 evictInterference(VirtReg, BestPhys, NewVRegs); 581 return BestPhys; 582 } 583 584 //===----------------------------------------------------------------------===// 585 // Region Splitting 586 //===----------------------------------------------------------------------===// 587 588 /// addSplitConstraints - Fill out the SplitConstraints vector based on the 589 /// interference pattern in Physreg and its aliases. Add the constraints to 590 /// SpillPlacement and return the static cost of this split in Cost, assuming 591 /// that all preferences in SplitConstraints are met. 592 /// Return false if there are no bundles with positive bias. 593 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf, 594 BlockFrequency &Cost) { 595 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks(); 596 597 // Reset interference dependent info. 598 SplitConstraints.resize(UseBlocks.size()); 599 BlockFrequency StaticCost = 0; 600 for (unsigned I = 0; I != UseBlocks.size(); ++I) { 601 const SplitAnalysis::BlockInfo &BI = UseBlocks[I]; 602 SpillPlacement::BlockConstraint &BC = SplitConstraints[I]; 603 604 BC.Number = BI.MBB->getNumber(); 605 Intf.moveToBlock(BC.Number); 606 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare; 607 BC.Exit = (BI.LiveOut && 608 !LIS->getInstructionFromIndex(BI.LastInstr)->isImplicitDef()) 609 ? SpillPlacement::PrefReg 610 : SpillPlacement::DontCare; 611 BC.ChangesValue = BI.FirstDef.isValid(); 612 613 if (!Intf.hasInterference()) 614 continue; 615 616 // Number of spill code instructions to insert. 617 unsigned Ins = 0; 618 619 // Interference for the live-in value. 620 if (BI.LiveIn) { 621 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number)) { 622 BC.Entry = SpillPlacement::MustSpill; 623 ++Ins; 624 } else if (Intf.first() < BI.FirstInstr) { 625 BC.Entry = SpillPlacement::PrefSpill; 626 ++Ins; 627 } else if (Intf.first() < BI.LastInstr) { 628 ++Ins; 629 } 630 631 // Abort if the spill cannot be inserted at the MBB' start 632 if (((BC.Entry == SpillPlacement::MustSpill) || 633 (BC.Entry == SpillPlacement::PrefSpill)) && 634 SlotIndex::isEarlierInstr(BI.FirstInstr, 635 SA->getFirstSplitPoint(BC.Number))) 636 return false; 637 } 638 639 // Interference for the live-out value. 640 if (BI.LiveOut) { 641 if (Intf.last() >= SA->getLastSplitPoint(BC.Number)) { 642 BC.Exit = SpillPlacement::MustSpill; 643 ++Ins; 644 } else if (Intf.last() > BI.LastInstr) { 645 BC.Exit = SpillPlacement::PrefSpill; 646 ++Ins; 647 } else if (Intf.last() > BI.FirstInstr) { 648 ++Ins; 649 } 650 } 651 652 // Accumulate the total frequency of inserted spill code. 653 while (Ins--) 654 StaticCost += SpillPlacer->getBlockFrequency(BC.Number); 655 } 656 Cost = StaticCost; 657 658 // Add constraints for use-blocks. Note that these are the only constraints 659 // that may add a positive bias, it is downhill from here. 660 SpillPlacer->addConstraints(SplitConstraints); 661 return SpillPlacer->scanActiveBundles(); 662 } 663 664 /// addThroughConstraints - Add constraints and links to SpillPlacer from the 665 /// live-through blocks in Blocks. 666 bool RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf, 667 ArrayRef<unsigned> Blocks) { 668 const unsigned GroupSize = 8; 669 SpillPlacement::BlockConstraint BCS[GroupSize]; 670 unsigned TBS[GroupSize]; 671 unsigned B = 0, T = 0; 672 673 for (unsigned Number : Blocks) { 674 Intf.moveToBlock(Number); 675 676 if (!Intf.hasInterference()) { 677 assert(T < GroupSize && "Array overflow"); 678 TBS[T] = Number; 679 if (++T == GroupSize) { 680 SpillPlacer->addLinks(ArrayRef(TBS, T)); 681 T = 0; 682 } 683 continue; 684 } 685 686 assert(B < GroupSize && "Array overflow"); 687 BCS[B].Number = Number; 688 689 // Abort if the spill cannot be inserted at the MBB' start 690 MachineBasicBlock *MBB = MF->getBlockNumbered(Number); 691 auto FirstNonDebugInstr = MBB->getFirstNonDebugInstr(); 692 if (FirstNonDebugInstr != MBB->end() && 693 SlotIndex::isEarlierInstr(LIS->getInstructionIndex(*FirstNonDebugInstr), 694 SA->getFirstSplitPoint(Number))) 695 return false; 696 // Interference for the live-in value. 697 if (Intf.first() <= Indexes->getMBBStartIdx(Number)) 698 BCS[B].Entry = SpillPlacement::MustSpill; 699 else 700 BCS[B].Entry = SpillPlacement::PrefSpill; 701 702 // Interference for the live-out value. 703 if (Intf.last() >= SA->getLastSplitPoint(Number)) 704 BCS[B].Exit = SpillPlacement::MustSpill; 705 else 706 BCS[B].Exit = SpillPlacement::PrefSpill; 707 708 if (++B == GroupSize) { 709 SpillPlacer->addConstraints(ArrayRef(BCS, B)); 710 B = 0; 711 } 712 } 713 714 SpillPlacer->addConstraints(ArrayRef(BCS, B)); 715 SpillPlacer->addLinks(ArrayRef(TBS, T)); 716 return true; 717 } 718 719 bool RAGreedy::growRegion(GlobalSplitCandidate &Cand) { 720 // Keep track of through blocks that have not been added to SpillPlacer. 721 BitVector Todo = SA->getThroughBlocks(); 722 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks; 723 unsigned AddedTo = 0; 724 #ifndef NDEBUG 725 unsigned Visited = 0; 726 #endif 727 728 unsigned long Budget = GrowRegionComplexityBudget; 729 while (true) { 730 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive(); 731 // Find new through blocks in the periphery of PrefRegBundles. 732 for (unsigned Bundle : NewBundles) { 733 // Look at all blocks connected to Bundle in the full graph. 734 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle); 735 // Limit compilation time by bailing out after we use all our budget. 736 if (Blocks.size() >= Budget) 737 return false; 738 Budget -= Blocks.size(); 739 for (unsigned Block : Blocks) { 740 if (!Todo.test(Block)) 741 continue; 742 Todo.reset(Block); 743 // This is a new through block. Add it to SpillPlacer later. 744 ActiveBlocks.push_back(Block); 745 #ifndef NDEBUG 746 ++Visited; 747 #endif 748 } 749 } 750 // Any new blocks to add? 751 if (ActiveBlocks.size() == AddedTo) 752 break; 753 754 // Compute through constraints from the interference, or assume that all 755 // through blocks prefer spilling when forming compact regions. 756 auto NewBlocks = ArrayRef(ActiveBlocks).slice(AddedTo); 757 if (Cand.PhysReg) { 758 if (!addThroughConstraints(Cand.Intf, NewBlocks)) 759 return false; 760 } else 761 // Provide a strong negative bias on through blocks to prevent unwanted 762 // liveness on loop backedges. 763 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true); 764 AddedTo = ActiveBlocks.size(); 765 766 // Perhaps iterating can enable more bundles? 767 SpillPlacer->iterate(); 768 } 769 LLVM_DEBUG(dbgs() << ", v=" << Visited); 770 return true; 771 } 772 773 /// calcCompactRegion - Compute the set of edge bundles that should be live 774 /// when splitting the current live range into compact regions. Compact 775 /// regions can be computed without looking at interference. They are the 776 /// regions formed by removing all the live-through blocks from the live range. 777 /// 778 /// Returns false if the current live range is already compact, or if the 779 /// compact regions would form single block regions anyway. 780 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) { 781 // Without any through blocks, the live range is already compact. 782 if (!SA->getNumThroughBlocks()) 783 return false; 784 785 // Compact regions don't correspond to any physreg. 786 Cand.reset(IntfCache, MCRegister::NoRegister); 787 788 LLVM_DEBUG(dbgs() << "Compact region bundles"); 789 790 // Use the spill placer to determine the live bundles. GrowRegion pretends 791 // that all the through blocks have interference when PhysReg is unset. 792 SpillPlacer->prepare(Cand.LiveBundles); 793 794 // The static split cost will be zero since Cand.Intf reports no interference. 795 BlockFrequency Cost; 796 if (!addSplitConstraints(Cand.Intf, Cost)) { 797 LLVM_DEBUG(dbgs() << ", none.\n"); 798 return false; 799 } 800 801 if (!growRegion(Cand)) { 802 LLVM_DEBUG(dbgs() << ", cannot spill all interferences.\n"); 803 return false; 804 } 805 806 SpillPlacer->finish(); 807 808 if (!Cand.LiveBundles.any()) { 809 LLVM_DEBUG(dbgs() << ", none.\n"); 810 return false; 811 } 812 813 LLVM_DEBUG({ 814 for (int I : Cand.LiveBundles.set_bits()) 815 dbgs() << " EB#" << I; 816 dbgs() << ".\n"; 817 }); 818 return true; 819 } 820 821 /// calcSpillCost - Compute how expensive it would be to split the live range in 822 /// SA around all use blocks instead of forming bundle regions. 823 BlockFrequency RAGreedy::calcSpillCost() { 824 BlockFrequency Cost = 0; 825 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks(); 826 for (const SplitAnalysis::BlockInfo &BI : UseBlocks) { 827 unsigned Number = BI.MBB->getNumber(); 828 // We normally only need one spill instruction - a load or a store. 829 Cost += SpillPlacer->getBlockFrequency(Number); 830 831 // Unless the value is redefined in the block. 832 if (BI.LiveIn && BI.LiveOut && BI.FirstDef) 833 Cost += SpillPlacer->getBlockFrequency(Number); 834 } 835 return Cost; 836 } 837 838 /// calcGlobalSplitCost - Return the global split cost of following the split 839 /// pattern in LiveBundles. This cost should be added to the local cost of the 840 /// interference pattern in SplitConstraints. 841 /// 842 BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand, 843 const AllocationOrder &Order) { 844 BlockFrequency GlobalCost = 0; 845 const BitVector &LiveBundles = Cand.LiveBundles; 846 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks(); 847 for (unsigned I = 0; I != UseBlocks.size(); ++I) { 848 const SplitAnalysis::BlockInfo &BI = UseBlocks[I]; 849 SpillPlacement::BlockConstraint &BC = SplitConstraints[I]; 850 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, false)]; 851 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, true)]; 852 unsigned Ins = 0; 853 854 Cand.Intf.moveToBlock(BC.Number); 855 856 if (BI.LiveIn) 857 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg); 858 if (BI.LiveOut) 859 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg); 860 while (Ins--) 861 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number); 862 } 863 864 for (unsigned Number : Cand.ActiveBlocks) { 865 bool RegIn = LiveBundles[Bundles->getBundle(Number, false)]; 866 bool RegOut = LiveBundles[Bundles->getBundle(Number, true)]; 867 if (!RegIn && !RegOut) 868 continue; 869 if (RegIn && RegOut) { 870 // We need double spill code if this block has interference. 871 Cand.Intf.moveToBlock(Number); 872 if (Cand.Intf.hasInterference()) { 873 GlobalCost += SpillPlacer->getBlockFrequency(Number); 874 GlobalCost += SpillPlacer->getBlockFrequency(Number); 875 } 876 continue; 877 } 878 // live-in / stack-out or stack-in live-out. 879 GlobalCost += SpillPlacer->getBlockFrequency(Number); 880 } 881 return GlobalCost; 882 } 883 884 /// splitAroundRegion - Split the current live range around the regions 885 /// determined by BundleCand and GlobalCand. 886 /// 887 /// Before calling this function, GlobalCand and BundleCand must be initialized 888 /// so each bundle is assigned to a valid candidate, or NoCand for the 889 /// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor 890 /// objects must be initialized for the current live range, and intervals 891 /// created for the used candidates. 892 /// 893 /// @param LREdit The LiveRangeEdit object handling the current split. 894 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value 895 /// must appear in this list. 896 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit, 897 ArrayRef<unsigned> UsedCands) { 898 // These are the intervals created for new global ranges. We may create more 899 // intervals for local ranges. 900 const unsigned NumGlobalIntvs = LREdit.size(); 901 LLVM_DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs 902 << " globals.\n"); 903 assert(NumGlobalIntvs && "No global intervals configured"); 904 905 // Isolate even single instructions when dealing with a proper sub-class. 906 // That guarantees register class inflation for the stack interval because it 907 // is all copies. 908 Register Reg = SA->getParent().reg(); 909 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg)); 910 911 // First handle all the blocks with uses. 912 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks(); 913 for (const SplitAnalysis::BlockInfo &BI : UseBlocks) { 914 unsigned Number = BI.MBB->getNumber(); 915 unsigned IntvIn = 0, IntvOut = 0; 916 SlotIndex IntfIn, IntfOut; 917 if (BI.LiveIn) { 918 unsigned CandIn = BundleCand[Bundles->getBundle(Number, false)]; 919 if (CandIn != NoCand) { 920 GlobalSplitCandidate &Cand = GlobalCand[CandIn]; 921 IntvIn = Cand.IntvIdx; 922 Cand.Intf.moveToBlock(Number); 923 IntfIn = Cand.Intf.first(); 924 } 925 } 926 if (BI.LiveOut) { 927 unsigned CandOut = BundleCand[Bundles->getBundle(Number, true)]; 928 if (CandOut != NoCand) { 929 GlobalSplitCandidate &Cand = GlobalCand[CandOut]; 930 IntvOut = Cand.IntvIdx; 931 Cand.Intf.moveToBlock(Number); 932 IntfOut = Cand.Intf.last(); 933 } 934 } 935 936 // Create separate intervals for isolated blocks with multiple uses. 937 if (!IntvIn && !IntvOut) { 938 LLVM_DEBUG(dbgs() << printMBBReference(*BI.MBB) << " isolated.\n"); 939 if (SA->shouldSplitSingleBlock(BI, SingleInstrs)) 940 SE->splitSingleBlock(BI); 941 continue; 942 } 943 944 if (IntvIn && IntvOut) 945 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut); 946 else if (IntvIn) 947 SE->splitRegInBlock(BI, IntvIn, IntfIn); 948 else 949 SE->splitRegOutBlock(BI, IntvOut, IntfOut); 950 } 951 952 // Handle live-through blocks. The relevant live-through blocks are stored in 953 // the ActiveBlocks list with each candidate. We need to filter out 954 // duplicates. 955 BitVector Todo = SA->getThroughBlocks(); 956 for (unsigned UsedCand : UsedCands) { 957 ArrayRef<unsigned> Blocks = GlobalCand[UsedCand].ActiveBlocks; 958 for (unsigned Number : Blocks) { 959 if (!Todo.test(Number)) 960 continue; 961 Todo.reset(Number); 962 963 unsigned IntvIn = 0, IntvOut = 0; 964 SlotIndex IntfIn, IntfOut; 965 966 unsigned CandIn = BundleCand[Bundles->getBundle(Number, false)]; 967 if (CandIn != NoCand) { 968 GlobalSplitCandidate &Cand = GlobalCand[CandIn]; 969 IntvIn = Cand.IntvIdx; 970 Cand.Intf.moveToBlock(Number); 971 IntfIn = Cand.Intf.first(); 972 } 973 974 unsigned CandOut = BundleCand[Bundles->getBundle(Number, true)]; 975 if (CandOut != NoCand) { 976 GlobalSplitCandidate &Cand = GlobalCand[CandOut]; 977 IntvOut = Cand.IntvIdx; 978 Cand.Intf.moveToBlock(Number); 979 IntfOut = Cand.Intf.last(); 980 } 981 if (!IntvIn && !IntvOut) 982 continue; 983 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut); 984 } 985 } 986 987 ++NumGlobalSplits; 988 989 SmallVector<unsigned, 8> IntvMap; 990 SE->finish(&IntvMap); 991 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS); 992 993 unsigned OrigBlocks = SA->getNumLiveBlocks(); 994 995 // Sort out the new intervals created by splitting. We get four kinds: 996 // - Remainder intervals should not be split again. 997 // - Candidate intervals can be assigned to Cand.PhysReg. 998 // - Block-local splits are candidates for local splitting. 999 // - DCE leftovers should go back on the queue. 1000 for (unsigned I = 0, E = LREdit.size(); I != E; ++I) { 1001 const LiveInterval &Reg = LIS->getInterval(LREdit.get(I)); 1002 1003 // Ignore old intervals from DCE. 1004 if (ExtraInfo->getOrInitStage(Reg.reg()) != RS_New) 1005 continue; 1006 1007 // Remainder interval. Don't try splitting again, spill if it doesn't 1008 // allocate. 1009 if (IntvMap[I] == 0) { 1010 ExtraInfo->setStage(Reg, RS_Spill); 1011 continue; 1012 } 1013 1014 // Global intervals. Allow repeated splitting as long as the number of live 1015 // blocks is strictly decreasing. 1016 if (IntvMap[I] < NumGlobalIntvs) { 1017 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) { 1018 LLVM_DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks 1019 << " blocks as original.\n"); 1020 // Don't allow repeated splitting as a safe guard against looping. 1021 ExtraInfo->setStage(Reg, RS_Split2); 1022 } 1023 continue; 1024 } 1025 1026 // Other intervals are treated as new. This includes local intervals created 1027 // for blocks with multiple uses, and anything created by DCE. 1028 } 1029 1030 if (VerifyEnabled) 1031 MF->verify(this, "After splitting live range around region"); 1032 } 1033 1034 MCRegister RAGreedy::tryRegionSplit(const LiveInterval &VirtReg, 1035 AllocationOrder &Order, 1036 SmallVectorImpl<Register> &NewVRegs) { 1037 if (!TRI->shouldRegionSplitForVirtReg(*MF, VirtReg)) 1038 return MCRegister::NoRegister; 1039 unsigned NumCands = 0; 1040 BlockFrequency SpillCost = calcSpillCost(); 1041 BlockFrequency BestCost; 1042 1043 // Check if we can split this live range around a compact region. 1044 bool HasCompact = calcCompactRegion(GlobalCand.front()); 1045 if (HasCompact) { 1046 // Yes, keep GlobalCand[0] as the compact region candidate. 1047 NumCands = 1; 1048 BestCost = BlockFrequency::getMaxFrequency(); 1049 } else { 1050 // No benefit from the compact region, our fallback will be per-block 1051 // splitting. Make sure we find a solution that is cheaper than spilling. 1052 BestCost = SpillCost; 1053 LLVM_DEBUG(dbgs() << "Cost of isolating all blocks = "; 1054 MBFI->printBlockFreq(dbgs(), BestCost) << '\n'); 1055 } 1056 1057 unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost, 1058 NumCands, false /*IgnoreCSR*/); 1059 1060 // No solutions found, fall back to single block splitting. 1061 if (!HasCompact && BestCand == NoCand) 1062 return MCRegister::NoRegister; 1063 1064 return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs); 1065 } 1066 1067 unsigned RAGreedy::calculateRegionSplitCost(const LiveInterval &VirtReg, 1068 AllocationOrder &Order, 1069 BlockFrequency &BestCost, 1070 unsigned &NumCands, 1071 bool IgnoreCSR) { 1072 unsigned BestCand = NoCand; 1073 for (MCPhysReg PhysReg : Order) { 1074 assert(PhysReg); 1075 if (IgnoreCSR && EvictAdvisor->isUnusedCalleeSavedReg(PhysReg)) 1076 continue; 1077 1078 // Discard bad candidates before we run out of interference cache cursors. 1079 // This will only affect register classes with a lot of registers (>32). 1080 if (NumCands == IntfCache.getMaxCursors()) { 1081 unsigned WorstCount = ~0u; 1082 unsigned Worst = 0; 1083 for (unsigned CandIndex = 0; CandIndex != NumCands; ++CandIndex) { 1084 if (CandIndex == BestCand || !GlobalCand[CandIndex].PhysReg) 1085 continue; 1086 unsigned Count = GlobalCand[CandIndex].LiveBundles.count(); 1087 if (Count < WorstCount) { 1088 Worst = CandIndex; 1089 WorstCount = Count; 1090 } 1091 } 1092 --NumCands; 1093 GlobalCand[Worst] = GlobalCand[NumCands]; 1094 if (BestCand == NumCands) 1095 BestCand = Worst; 1096 } 1097 1098 if (GlobalCand.size() <= NumCands) 1099 GlobalCand.resize(NumCands+1); 1100 GlobalSplitCandidate &Cand = GlobalCand[NumCands]; 1101 Cand.reset(IntfCache, PhysReg); 1102 1103 SpillPlacer->prepare(Cand.LiveBundles); 1104 BlockFrequency Cost; 1105 if (!addSplitConstraints(Cand.Intf, Cost)) { 1106 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << "\tno positive bundles\n"); 1107 continue; 1108 } 1109 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << "\tstatic = "; 1110 MBFI->printBlockFreq(dbgs(), Cost)); 1111 if (Cost >= BestCost) { 1112 LLVM_DEBUG({ 1113 if (BestCand == NoCand) 1114 dbgs() << " worse than no bundles\n"; 1115 else 1116 dbgs() << " worse than " 1117 << printReg(GlobalCand[BestCand].PhysReg, TRI) << '\n'; 1118 }); 1119 continue; 1120 } 1121 if (!growRegion(Cand)) { 1122 LLVM_DEBUG(dbgs() << ", cannot spill all interferences.\n"); 1123 continue; 1124 } 1125 1126 SpillPlacer->finish(); 1127 1128 // No live bundles, defer to splitSingleBlocks(). 1129 if (!Cand.LiveBundles.any()) { 1130 LLVM_DEBUG(dbgs() << " no bundles.\n"); 1131 continue; 1132 } 1133 1134 Cost += calcGlobalSplitCost(Cand, Order); 1135 LLVM_DEBUG({ 1136 dbgs() << ", total = "; 1137 MBFI->printBlockFreq(dbgs(), Cost) << " with bundles"; 1138 for (int I : Cand.LiveBundles.set_bits()) 1139 dbgs() << " EB#" << I; 1140 dbgs() << ".\n"; 1141 }); 1142 if (Cost < BestCost) { 1143 BestCand = NumCands; 1144 BestCost = Cost; 1145 } 1146 ++NumCands; 1147 } 1148 1149 return BestCand; 1150 } 1151 1152 unsigned RAGreedy::doRegionSplit(const LiveInterval &VirtReg, unsigned BestCand, 1153 bool HasCompact, 1154 SmallVectorImpl<Register> &NewVRegs) { 1155 SmallVector<unsigned, 8> UsedCands; 1156 // Prepare split editor. 1157 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats); 1158 SE->reset(LREdit, SplitSpillMode); 1159 1160 // Assign all edge bundles to the preferred candidate, or NoCand. 1161 BundleCand.assign(Bundles->getNumBundles(), NoCand); 1162 1163 // Assign bundles for the best candidate region. 1164 if (BestCand != NoCand) { 1165 GlobalSplitCandidate &Cand = GlobalCand[BestCand]; 1166 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) { 1167 UsedCands.push_back(BestCand); 1168 Cand.IntvIdx = SE->openIntv(); 1169 LLVM_DEBUG(dbgs() << "Split for " << printReg(Cand.PhysReg, TRI) << " in " 1170 << B << " bundles, intv " << Cand.IntvIdx << ".\n"); 1171 (void)B; 1172 } 1173 } 1174 1175 // Assign bundles for the compact region. 1176 if (HasCompact) { 1177 GlobalSplitCandidate &Cand = GlobalCand.front(); 1178 assert(!Cand.PhysReg && "Compact region has no physreg"); 1179 if (unsigned B = Cand.getBundles(BundleCand, 0)) { 1180 UsedCands.push_back(0); 1181 Cand.IntvIdx = SE->openIntv(); 1182 LLVM_DEBUG(dbgs() << "Split for compact region in " << B 1183 << " bundles, intv " << Cand.IntvIdx << ".\n"); 1184 (void)B; 1185 } 1186 } 1187 1188 splitAroundRegion(LREdit, UsedCands); 1189 return 0; 1190 } 1191 1192 //===----------------------------------------------------------------------===// 1193 // Per-Block Splitting 1194 //===----------------------------------------------------------------------===// 1195 1196 /// tryBlockSplit - Split a global live range around every block with uses. This 1197 /// creates a lot of local live ranges, that will be split by tryLocalSplit if 1198 /// they don't allocate. 1199 unsigned RAGreedy::tryBlockSplit(const LiveInterval &VirtReg, 1200 AllocationOrder &Order, 1201 SmallVectorImpl<Register> &NewVRegs) { 1202 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed"); 1203 Register Reg = VirtReg.reg(); 1204 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg)); 1205 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats); 1206 SE->reset(LREdit, SplitSpillMode); 1207 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks(); 1208 for (const SplitAnalysis::BlockInfo &BI : UseBlocks) { 1209 if (SA->shouldSplitSingleBlock(BI, SingleInstrs)) 1210 SE->splitSingleBlock(BI); 1211 } 1212 // No blocks were split. 1213 if (LREdit.empty()) 1214 return 0; 1215 1216 // We did split for some blocks. 1217 SmallVector<unsigned, 8> IntvMap; 1218 SE->finish(&IntvMap); 1219 1220 // Tell LiveDebugVariables about the new ranges. 1221 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS); 1222 1223 // Sort out the new intervals created by splitting. The remainder interval 1224 // goes straight to spilling, the new local ranges get to stay RS_New. 1225 for (unsigned I = 0, E = LREdit.size(); I != E; ++I) { 1226 const LiveInterval &LI = LIS->getInterval(LREdit.get(I)); 1227 if (ExtraInfo->getOrInitStage(LI.reg()) == RS_New && IntvMap[I] == 0) 1228 ExtraInfo->setStage(LI, RS_Spill); 1229 } 1230 1231 if (VerifyEnabled) 1232 MF->verify(this, "After splitting live range around basic blocks"); 1233 return 0; 1234 } 1235 1236 //===----------------------------------------------------------------------===// 1237 // Per-Instruction Splitting 1238 //===----------------------------------------------------------------------===// 1239 1240 /// Get the number of allocatable registers that match the constraints of \p Reg 1241 /// on \p MI and that are also in \p SuperRC. 1242 static unsigned getNumAllocatableRegsForConstraints( 1243 const MachineInstr *MI, Register Reg, const TargetRegisterClass *SuperRC, 1244 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI, 1245 const RegisterClassInfo &RCI) { 1246 assert(SuperRC && "Invalid register class"); 1247 1248 const TargetRegisterClass *ConstrainedRC = 1249 MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI, 1250 /* ExploreBundle */ true); 1251 if (!ConstrainedRC) 1252 return 0; 1253 return RCI.getNumAllocatableRegs(ConstrainedRC); 1254 } 1255 1256 static LaneBitmask getInstReadLaneMask(const MachineRegisterInfo &MRI, 1257 const TargetRegisterInfo &TRI, 1258 const MachineInstr &MI, Register Reg) { 1259 LaneBitmask Mask; 1260 for (const MachineOperand &MO : MI.operands()) { 1261 if (!MO.isReg() || MO.getReg() != Reg) 1262 continue; 1263 1264 unsigned SubReg = MO.getSubReg(); 1265 if (SubReg == 0 && MO.isUse()) { 1266 Mask |= MRI.getMaxLaneMaskForVReg(Reg); 1267 continue; 1268 } 1269 1270 LaneBitmask SubRegMask = TRI.getSubRegIndexLaneMask(SubReg); 1271 if (MO.isDef()) { 1272 if (!MO.isUndef()) 1273 Mask |= ~SubRegMask; 1274 } else 1275 Mask |= SubRegMask; 1276 } 1277 1278 return Mask; 1279 } 1280 1281 /// Return true if \p MI at \P Use reads a subset of the lanes live in \p 1282 /// VirtReg. 1283 static bool readsLaneSubset(const MachineRegisterInfo &MRI, 1284 const MachineInstr *MI, const LiveInterval &VirtReg, 1285 const TargetRegisterInfo *TRI, SlotIndex Use, 1286 const TargetInstrInfo *TII) { 1287 // Early check the common case. 1288 auto DestSrc = TII->isCopyInstr(*MI); 1289 if (DestSrc && 1290 DestSrc->Destination->getSubReg() == DestSrc->Source->getSubReg()) 1291 return false; 1292 1293 // FIXME: We're only considering uses, but should be consider defs too? 1294 LaneBitmask ReadMask = getInstReadLaneMask(MRI, *TRI, *MI, VirtReg.reg()); 1295 1296 LaneBitmask LiveAtMask; 1297 for (const LiveInterval::SubRange &S : VirtReg.subranges()) { 1298 if (S.liveAt(Use)) 1299 LiveAtMask |= S.LaneMask; 1300 } 1301 1302 // If the live lanes aren't different from the lanes used by the instruction, 1303 // this doesn't help. 1304 return (ReadMask & ~(LiveAtMask & TRI->getCoveringLanes())).any(); 1305 } 1306 1307 /// tryInstructionSplit - Split a live range around individual instructions. 1308 /// This is normally not worthwhile since the spiller is doing essentially the 1309 /// same thing. However, when the live range is in a constrained register 1310 /// class, it may help to insert copies such that parts of the live range can 1311 /// be moved to a larger register class. 1312 /// 1313 /// This is similar to spilling to a larger register class. 1314 unsigned RAGreedy::tryInstructionSplit(const LiveInterval &VirtReg, 1315 AllocationOrder &Order, 1316 SmallVectorImpl<Register> &NewVRegs) { 1317 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg()); 1318 // There is no point to this if there are no larger sub-classes. 1319 1320 bool SplitSubClass = true; 1321 if (!RegClassInfo.isProperSubClass(CurRC)) { 1322 if (!VirtReg.hasSubRanges()) 1323 return 0; 1324 SplitSubClass = false; 1325 } 1326 1327 // Always enable split spill mode, since we're effectively spilling to a 1328 // register. 1329 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats); 1330 SE->reset(LREdit, SplitEditor::SM_Size); 1331 1332 ArrayRef<SlotIndex> Uses = SA->getUseSlots(); 1333 if (Uses.size() <= 1) 1334 return 0; 1335 1336 LLVM_DEBUG(dbgs() << "Split around " << Uses.size() 1337 << " individual instrs.\n"); 1338 1339 const TargetRegisterClass *SuperRC = 1340 TRI->getLargestLegalSuperClass(CurRC, *MF); 1341 unsigned SuperRCNumAllocatableRegs = 1342 RegClassInfo.getNumAllocatableRegs(SuperRC); 1343 // Split around every non-copy instruction if this split will relax 1344 // the constraints on the virtual register. 1345 // Otherwise, splitting just inserts uncoalescable copies that do not help 1346 // the allocation. 1347 for (const SlotIndex Use : Uses) { 1348 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Use)) { 1349 if (TII->isFullCopyInstr(*MI) || 1350 (SplitSubClass && 1351 SuperRCNumAllocatableRegs == 1352 getNumAllocatableRegsForConstraints(MI, VirtReg.reg(), SuperRC, 1353 TII, TRI, RegClassInfo)) || 1354 // TODO: Handle split for subranges with subclass constraints? 1355 (!SplitSubClass && VirtReg.hasSubRanges() && 1356 !readsLaneSubset(*MRI, MI, VirtReg, TRI, Use, TII))) { 1357 LLVM_DEBUG(dbgs() << " skip:\t" << Use << '\t' << *MI); 1358 continue; 1359 } 1360 } 1361 SE->openIntv(); 1362 SlotIndex SegStart = SE->enterIntvBefore(Use); 1363 SlotIndex SegStop = SE->leaveIntvAfter(Use); 1364 SE->useIntv(SegStart, SegStop); 1365 } 1366 1367 if (LREdit.empty()) { 1368 LLVM_DEBUG(dbgs() << "All uses were copies.\n"); 1369 return 0; 1370 } 1371 1372 SmallVector<unsigned, 8> IntvMap; 1373 SE->finish(&IntvMap); 1374 DebugVars->splitRegister(VirtReg.reg(), LREdit.regs(), *LIS); 1375 // Assign all new registers to RS_Spill. This was the last chance. 1376 ExtraInfo->setStage(LREdit.begin(), LREdit.end(), RS_Spill); 1377 return 0; 1378 } 1379 1380 //===----------------------------------------------------------------------===// 1381 // Local Splitting 1382 //===----------------------------------------------------------------------===// 1383 1384 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted 1385 /// in order to use PhysReg between two entries in SA->UseSlots. 1386 /// 1387 /// GapWeight[I] represents the gap between UseSlots[I] and UseSlots[I + 1]. 1388 /// 1389 void RAGreedy::calcGapWeights(MCRegister PhysReg, 1390 SmallVectorImpl<float> &GapWeight) { 1391 assert(SA->getUseBlocks().size() == 1 && "Not a local interval"); 1392 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front(); 1393 ArrayRef<SlotIndex> Uses = SA->getUseSlots(); 1394 const unsigned NumGaps = Uses.size()-1; 1395 1396 // Start and end points for the interference check. 1397 SlotIndex StartIdx = 1398 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr; 1399 SlotIndex StopIdx = 1400 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr; 1401 1402 GapWeight.assign(NumGaps, 0.0f); 1403 1404 // Add interference from each overlapping register. 1405 for (MCRegUnit Unit : TRI->regunits(PhysReg)) { 1406 if (!Matrix->query(const_cast<LiveInterval &>(SA->getParent()), Unit) 1407 .checkInterference()) 1408 continue; 1409 1410 // We know that VirtReg is a continuous interval from FirstInstr to 1411 // LastInstr, so we don't need InterferenceQuery. 1412 // 1413 // Interference that overlaps an instruction is counted in both gaps 1414 // surrounding the instruction. The exception is interference before 1415 // StartIdx and after StopIdx. 1416 // 1417 LiveIntervalUnion::SegmentIter IntI = 1418 Matrix->getLiveUnions()[Unit].find(StartIdx); 1419 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) { 1420 // Skip the gaps before IntI. 1421 while (Uses[Gap+1].getBoundaryIndex() < IntI.start()) 1422 if (++Gap == NumGaps) 1423 break; 1424 if (Gap == NumGaps) 1425 break; 1426 1427 // Update the gaps covered by IntI. 1428 const float weight = IntI.value()->weight(); 1429 for (; Gap != NumGaps; ++Gap) { 1430 GapWeight[Gap] = std::max(GapWeight[Gap], weight); 1431 if (Uses[Gap+1].getBaseIndex() >= IntI.stop()) 1432 break; 1433 } 1434 if (Gap == NumGaps) 1435 break; 1436 } 1437 } 1438 1439 // Add fixed interference. 1440 for (MCRegUnit Unit : TRI->regunits(PhysReg)) { 1441 const LiveRange &LR = LIS->getRegUnit(Unit); 1442 LiveRange::const_iterator I = LR.find(StartIdx); 1443 LiveRange::const_iterator E = LR.end(); 1444 1445 // Same loop as above. Mark any overlapped gaps as HUGE_VALF. 1446 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) { 1447 while (Uses[Gap+1].getBoundaryIndex() < I->start) 1448 if (++Gap == NumGaps) 1449 break; 1450 if (Gap == NumGaps) 1451 break; 1452 1453 for (; Gap != NumGaps; ++Gap) { 1454 GapWeight[Gap] = huge_valf; 1455 if (Uses[Gap+1].getBaseIndex() >= I->end) 1456 break; 1457 } 1458 if (Gap == NumGaps) 1459 break; 1460 } 1461 } 1462 } 1463 1464 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only 1465 /// basic block. 1466 /// 1467 unsigned RAGreedy::tryLocalSplit(const LiveInterval &VirtReg, 1468 AllocationOrder &Order, 1469 SmallVectorImpl<Register> &NewVRegs) { 1470 // TODO: the function currently only handles a single UseBlock; it should be 1471 // possible to generalize. 1472 if (SA->getUseBlocks().size() != 1) 1473 return 0; 1474 1475 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front(); 1476 1477 // Note that it is possible to have an interval that is live-in or live-out 1478 // while only covering a single block - A phi-def can use undef values from 1479 // predecessors, and the block could be a single-block loop. 1480 // We don't bother doing anything clever about such a case, we simply assume 1481 // that the interval is continuous from FirstInstr to LastInstr. We should 1482 // make sure that we don't do anything illegal to such an interval, though. 1483 1484 ArrayRef<SlotIndex> Uses = SA->getUseSlots(); 1485 if (Uses.size() <= 2) 1486 return 0; 1487 const unsigned NumGaps = Uses.size()-1; 1488 1489 LLVM_DEBUG({ 1490 dbgs() << "tryLocalSplit: "; 1491 for (const auto &Use : Uses) 1492 dbgs() << ' ' << Use; 1493 dbgs() << '\n'; 1494 }); 1495 1496 // If VirtReg is live across any register mask operands, compute a list of 1497 // gaps with register masks. 1498 SmallVector<unsigned, 8> RegMaskGaps; 1499 if (Matrix->checkRegMaskInterference(VirtReg)) { 1500 // Get regmask slots for the whole block. 1501 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber()); 1502 LLVM_DEBUG(dbgs() << RMS.size() << " regmasks in block:"); 1503 // Constrain to VirtReg's live range. 1504 unsigned RI = 1505 llvm::lower_bound(RMS, Uses.front().getRegSlot()) - RMS.begin(); 1506 unsigned RE = RMS.size(); 1507 for (unsigned I = 0; I != NumGaps && RI != RE; ++I) { 1508 // Look for Uses[I] <= RMS <= Uses[I + 1]. 1509 assert(!SlotIndex::isEarlierInstr(RMS[RI], Uses[I])); 1510 if (SlotIndex::isEarlierInstr(Uses[I + 1], RMS[RI])) 1511 continue; 1512 // Skip a regmask on the same instruction as the last use. It doesn't 1513 // overlap the live range. 1514 if (SlotIndex::isSameInstr(Uses[I + 1], RMS[RI]) && I + 1 == NumGaps) 1515 break; 1516 LLVM_DEBUG(dbgs() << ' ' << RMS[RI] << ':' << Uses[I] << '-' 1517 << Uses[I + 1]); 1518 RegMaskGaps.push_back(I); 1519 // Advance ri to the next gap. A regmask on one of the uses counts in 1520 // both gaps. 1521 while (RI != RE && SlotIndex::isEarlierInstr(RMS[RI], Uses[I + 1])) 1522 ++RI; 1523 } 1524 LLVM_DEBUG(dbgs() << '\n'); 1525 } 1526 1527 // Since we allow local split results to be split again, there is a risk of 1528 // creating infinite loops. It is tempting to require that the new live 1529 // ranges have less instructions than the original. That would guarantee 1530 // convergence, but it is too strict. A live range with 3 instructions can be 1531 // split 2+3 (including the COPY), and we want to allow that. 1532 // 1533 // Instead we use these rules: 1534 // 1535 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the 1536 // noop split, of course). 1537 // 2. Require progress be made for ranges with getStage() == RS_Split2. All 1538 // the new ranges must have fewer instructions than before the split. 1539 // 3. New ranges with the same number of instructions are marked RS_Split2, 1540 // smaller ranges are marked RS_New. 1541 // 1542 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent 1543 // excessive splitting and infinite loops. 1544 // 1545 bool ProgressRequired = ExtraInfo->getStage(VirtReg) >= RS_Split2; 1546 1547 // Best split candidate. 1548 unsigned BestBefore = NumGaps; 1549 unsigned BestAfter = 0; 1550 float BestDiff = 0; 1551 1552 const float blockFreq = 1553 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() * 1554 (1.0f / MBFI->getEntryFreq()); 1555 SmallVector<float, 8> GapWeight; 1556 1557 for (MCPhysReg PhysReg : Order) { 1558 assert(PhysReg); 1559 // Keep track of the largest spill weight that would need to be evicted in 1560 // order to make use of PhysReg between UseSlots[I] and UseSlots[I + 1]. 1561 calcGapWeights(PhysReg, GapWeight); 1562 1563 // Remove any gaps with regmask clobbers. 1564 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg)) 1565 for (unsigned I = 0, E = RegMaskGaps.size(); I != E; ++I) 1566 GapWeight[RegMaskGaps[I]] = huge_valf; 1567 1568 // Try to find the best sequence of gaps to close. 1569 // The new spill weight must be larger than any gap interference. 1570 1571 // We will split before Uses[SplitBefore] and after Uses[SplitAfter]. 1572 unsigned SplitBefore = 0, SplitAfter = 1; 1573 1574 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]). 1575 // It is the spill weight that needs to be evicted. 1576 float MaxGap = GapWeight[0]; 1577 1578 while (true) { 1579 // Live before/after split? 1580 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn; 1581 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut; 1582 1583 LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << ' ' << Uses[SplitBefore] 1584 << '-' << Uses[SplitAfter] << " I=" << MaxGap); 1585 1586 // Stop before the interval gets so big we wouldn't be making progress. 1587 if (!LiveBefore && !LiveAfter) { 1588 LLVM_DEBUG(dbgs() << " all\n"); 1589 break; 1590 } 1591 // Should the interval be extended or shrunk? 1592 bool Shrink = true; 1593 1594 // How many gaps would the new range have? 1595 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter; 1596 1597 // Legally, without causing looping? 1598 bool Legal = !ProgressRequired || NewGaps < NumGaps; 1599 1600 if (Legal && MaxGap < huge_valf) { 1601 // Estimate the new spill weight. Each instruction reads or writes the 1602 // register. Conservatively assume there are no read-modify-write 1603 // instructions. 1604 // 1605 // Try to guess the size of the new interval. 1606 const float EstWeight = normalizeSpillWeight( 1607 blockFreq * (NewGaps + 1), 1608 Uses[SplitBefore].distance(Uses[SplitAfter]) + 1609 (LiveBefore + LiveAfter) * SlotIndex::InstrDist, 1610 1); 1611 // Would this split be possible to allocate? 1612 // Never allocate all gaps, we wouldn't be making progress. 1613 LLVM_DEBUG(dbgs() << " w=" << EstWeight); 1614 if (EstWeight * Hysteresis >= MaxGap) { 1615 Shrink = false; 1616 float Diff = EstWeight - MaxGap; 1617 if (Diff > BestDiff) { 1618 LLVM_DEBUG(dbgs() << " (best)"); 1619 BestDiff = Hysteresis * Diff; 1620 BestBefore = SplitBefore; 1621 BestAfter = SplitAfter; 1622 } 1623 } 1624 } 1625 1626 // Try to shrink. 1627 if (Shrink) { 1628 if (++SplitBefore < SplitAfter) { 1629 LLVM_DEBUG(dbgs() << " shrink\n"); 1630 // Recompute the max when necessary. 1631 if (GapWeight[SplitBefore - 1] >= MaxGap) { 1632 MaxGap = GapWeight[SplitBefore]; 1633 for (unsigned I = SplitBefore + 1; I != SplitAfter; ++I) 1634 MaxGap = std::max(MaxGap, GapWeight[I]); 1635 } 1636 continue; 1637 } 1638 MaxGap = 0; 1639 } 1640 1641 // Try to extend the interval. 1642 if (SplitAfter >= NumGaps) { 1643 LLVM_DEBUG(dbgs() << " end\n"); 1644 break; 1645 } 1646 1647 LLVM_DEBUG(dbgs() << " extend\n"); 1648 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]); 1649 } 1650 } 1651 1652 // Didn't find any candidates? 1653 if (BestBefore == NumGaps) 1654 return 0; 1655 1656 LLVM_DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore] << '-' 1657 << Uses[BestAfter] << ", " << BestDiff << ", " 1658 << (BestAfter - BestBefore + 1) << " instrs\n"); 1659 1660 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats); 1661 SE->reset(LREdit); 1662 1663 SE->openIntv(); 1664 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]); 1665 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]); 1666 SE->useIntv(SegStart, SegStop); 1667 SmallVector<unsigned, 8> IntvMap; 1668 SE->finish(&IntvMap); 1669 DebugVars->splitRegister(VirtReg.reg(), LREdit.regs(), *LIS); 1670 // If the new range has the same number of instructions as before, mark it as 1671 // RS_Split2 so the next split will be forced to make progress. Otherwise, 1672 // leave the new intervals as RS_New so they can compete. 1673 bool LiveBefore = BestBefore != 0 || BI.LiveIn; 1674 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut; 1675 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter; 1676 if (NewGaps >= NumGaps) { 1677 LLVM_DEBUG(dbgs() << "Tagging non-progress ranges:"); 1678 assert(!ProgressRequired && "Didn't make progress when it was required."); 1679 for (unsigned I = 0, E = IntvMap.size(); I != E; ++I) 1680 if (IntvMap[I] == 1) { 1681 ExtraInfo->setStage(LIS->getInterval(LREdit.get(I)), RS_Split2); 1682 LLVM_DEBUG(dbgs() << ' ' << printReg(LREdit.get(I))); 1683 } 1684 LLVM_DEBUG(dbgs() << '\n'); 1685 } 1686 ++NumLocalSplits; 1687 1688 return 0; 1689 } 1690 1691 //===----------------------------------------------------------------------===// 1692 // Live Range Splitting 1693 //===----------------------------------------------------------------------===// 1694 1695 /// trySplit - Try to split VirtReg or one of its interferences, making it 1696 /// assignable. 1697 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs. 1698 unsigned RAGreedy::trySplit(const LiveInterval &VirtReg, AllocationOrder &Order, 1699 SmallVectorImpl<Register> &NewVRegs, 1700 const SmallVirtRegSet &FixedRegisters) { 1701 // Ranges must be Split2 or less. 1702 if (ExtraInfo->getStage(VirtReg) >= RS_Spill) 1703 return 0; 1704 1705 // Local intervals are handled separately. 1706 if (LIS->intervalIsInOneMBB(VirtReg)) { 1707 NamedRegionTimer T("local_split", "Local Splitting", TimerGroupName, 1708 TimerGroupDescription, TimePassesIsEnabled); 1709 SA->analyze(&VirtReg); 1710 Register PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs); 1711 if (PhysReg || !NewVRegs.empty()) 1712 return PhysReg; 1713 return tryInstructionSplit(VirtReg, Order, NewVRegs); 1714 } 1715 1716 NamedRegionTimer T("global_split", "Global Splitting", TimerGroupName, 1717 TimerGroupDescription, TimePassesIsEnabled); 1718 1719 SA->analyze(&VirtReg); 1720 1721 // First try to split around a region spanning multiple blocks. RS_Split2 1722 // ranges already made dubious progress with region splitting, so they go 1723 // straight to single block splitting. 1724 if (ExtraInfo->getStage(VirtReg) < RS_Split2) { 1725 MCRegister PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs); 1726 if (PhysReg || !NewVRegs.empty()) 1727 return PhysReg; 1728 } 1729 1730 // Then isolate blocks. 1731 return tryBlockSplit(VirtReg, Order, NewVRegs); 1732 } 1733 1734 //===----------------------------------------------------------------------===// 1735 // Last Chance Recoloring 1736 //===----------------------------------------------------------------------===// 1737 1738 /// Return true if \p reg has any tied def operand. 1739 static bool hasTiedDef(MachineRegisterInfo *MRI, unsigned reg) { 1740 for (const MachineOperand &MO : MRI->def_operands(reg)) 1741 if (MO.isTied()) 1742 return true; 1743 1744 return false; 1745 } 1746 1747 /// Return true if the existing assignment of \p Intf overlaps, but is not the 1748 /// same, as \p PhysReg. 1749 static bool assignedRegPartiallyOverlaps(const TargetRegisterInfo &TRI, 1750 const VirtRegMap &VRM, 1751 MCRegister PhysReg, 1752 const LiveInterval &Intf) { 1753 MCRegister AssignedReg = VRM.getPhys(Intf.reg()); 1754 if (PhysReg == AssignedReg) 1755 return false; 1756 return TRI.regsOverlap(PhysReg, AssignedReg); 1757 } 1758 1759 /// mayRecolorAllInterferences - Check if the virtual registers that 1760 /// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be 1761 /// recolored to free \p PhysReg. 1762 /// When true is returned, \p RecoloringCandidates has been augmented with all 1763 /// the live intervals that need to be recolored in order to free \p PhysReg 1764 /// for \p VirtReg. 1765 /// \p FixedRegisters contains all the virtual registers that cannot be 1766 /// recolored. 1767 bool RAGreedy::mayRecolorAllInterferences( 1768 MCRegister PhysReg, const LiveInterval &VirtReg, 1769 SmallLISet &RecoloringCandidates, const SmallVirtRegSet &FixedRegisters) { 1770 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg()); 1771 1772 for (MCRegUnit Unit : TRI->regunits(PhysReg)) { 1773 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, Unit); 1774 // If there is LastChanceRecoloringMaxInterference or more interferences, 1775 // chances are one would not be recolorable. 1776 if (Q.interferingVRegs(LastChanceRecoloringMaxInterference).size() >= 1777 LastChanceRecoloringMaxInterference && 1778 !ExhaustiveSearch) { 1779 LLVM_DEBUG(dbgs() << "Early abort: too many interferences.\n"); 1780 CutOffInfo |= CO_Interf; 1781 return false; 1782 } 1783 for (const LiveInterval *Intf : reverse(Q.interferingVRegs())) { 1784 // If Intf is done and sits on the same register class as VirtReg, it 1785 // would not be recolorable as it is in the same state as 1786 // VirtReg. However there are at least two exceptions. 1787 // 1788 // If VirtReg has tied defs and Intf doesn't, then 1789 // there is still a point in examining if it can be recolorable. 1790 // 1791 // Additionally, if the register class has overlapping tuple members, it 1792 // may still be recolorable using a different tuple. This is more likely 1793 // if the existing assignment aliases with the candidate. 1794 // 1795 if (((ExtraInfo->getStage(*Intf) == RS_Done && 1796 MRI->getRegClass(Intf->reg()) == CurRC && 1797 !assignedRegPartiallyOverlaps(*TRI, *VRM, PhysReg, *Intf)) && 1798 !(hasTiedDef(MRI, VirtReg.reg()) && 1799 !hasTiedDef(MRI, Intf->reg()))) || 1800 FixedRegisters.count(Intf->reg())) { 1801 LLVM_DEBUG( 1802 dbgs() << "Early abort: the interference is not recolorable.\n"); 1803 return false; 1804 } 1805 RecoloringCandidates.insert(Intf); 1806 } 1807 } 1808 return true; 1809 } 1810 1811 /// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring 1812 /// its interferences. 1813 /// Last chance recoloring chooses a color for \p VirtReg and recolors every 1814 /// virtual register that was using it. The recoloring process may recursively 1815 /// use the last chance recoloring. Therefore, when a virtual register has been 1816 /// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot 1817 /// be last-chance-recolored again during this recoloring "session". 1818 /// E.g., 1819 /// Let 1820 /// vA can use {R1, R2 } 1821 /// vB can use { R2, R3} 1822 /// vC can use {R1 } 1823 /// Where vA, vB, and vC cannot be split anymore (they are reloads for 1824 /// instance) and they all interfere. 1825 /// 1826 /// vA is assigned R1 1827 /// vB is assigned R2 1828 /// vC tries to evict vA but vA is already done. 1829 /// Regular register allocation fails. 1830 /// 1831 /// Last chance recoloring kicks in: 1832 /// vC does as if vA was evicted => vC uses R1. 1833 /// vC is marked as fixed. 1834 /// vA needs to find a color. 1835 /// None are available. 1836 /// vA cannot evict vC: vC is a fixed virtual register now. 1837 /// vA does as if vB was evicted => vA uses R2. 1838 /// vB needs to find a color. 1839 /// R3 is available. 1840 /// Recoloring => vC = R1, vA = R2, vB = R3 1841 /// 1842 /// \p Order defines the preferred allocation order for \p VirtReg. 1843 /// \p NewRegs will contain any new virtual register that have been created 1844 /// (split, spill) during the process and that must be assigned. 1845 /// \p FixedRegisters contains all the virtual registers that cannot be 1846 /// recolored. 1847 /// 1848 /// \p RecolorStack tracks the original assignments of successfully recolored 1849 /// registers. 1850 /// 1851 /// \p Depth gives the current depth of the last chance recoloring. 1852 /// \return a physical register that can be used for VirtReg or ~0u if none 1853 /// exists. 1854 unsigned RAGreedy::tryLastChanceRecoloring(const LiveInterval &VirtReg, 1855 AllocationOrder &Order, 1856 SmallVectorImpl<Register> &NewVRegs, 1857 SmallVirtRegSet &FixedRegisters, 1858 RecoloringStack &RecolorStack, 1859 unsigned Depth) { 1860 if (!TRI->shouldUseLastChanceRecoloringForVirtReg(*MF, VirtReg)) 1861 return ~0u; 1862 1863 LLVM_DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n'); 1864 1865 const ssize_t EntryStackSize = RecolorStack.size(); 1866 1867 // Ranges must be Done. 1868 assert((ExtraInfo->getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) && 1869 "Last chance recoloring should really be last chance"); 1870 // Set the max depth to LastChanceRecoloringMaxDepth. 1871 // We may want to reconsider that if we end up with a too large search space 1872 // for target with hundreds of registers. 1873 // Indeed, in that case we may want to cut the search space earlier. 1874 if (Depth >= LastChanceRecoloringMaxDepth && !ExhaustiveSearch) { 1875 LLVM_DEBUG(dbgs() << "Abort because max depth has been reached.\n"); 1876 CutOffInfo |= CO_Depth; 1877 return ~0u; 1878 } 1879 1880 // Set of Live intervals that will need to be recolored. 1881 SmallLISet RecoloringCandidates; 1882 1883 // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in 1884 // this recoloring "session". 1885 assert(!FixedRegisters.count(VirtReg.reg())); 1886 FixedRegisters.insert(VirtReg.reg()); 1887 SmallVector<Register, 4> CurrentNewVRegs; 1888 1889 for (MCRegister PhysReg : Order) { 1890 assert(PhysReg.isValid()); 1891 LLVM_DEBUG(dbgs() << "Try to assign: " << VirtReg << " to " 1892 << printReg(PhysReg, TRI) << '\n'); 1893 RecoloringCandidates.clear(); 1894 CurrentNewVRegs.clear(); 1895 1896 // It is only possible to recolor virtual register interference. 1897 if (Matrix->checkInterference(VirtReg, PhysReg) > 1898 LiveRegMatrix::IK_VirtReg) { 1899 LLVM_DEBUG( 1900 dbgs() << "Some interferences are not with virtual registers.\n"); 1901 1902 continue; 1903 } 1904 1905 // Early give up on this PhysReg if it is obvious we cannot recolor all 1906 // the interferences. 1907 if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates, 1908 FixedRegisters)) { 1909 LLVM_DEBUG(dbgs() << "Some interferences cannot be recolored.\n"); 1910 continue; 1911 } 1912 1913 // RecoloringCandidates contains all the virtual registers that interfere 1914 // with VirtReg on PhysReg (or one of its aliases). Enqueue them for 1915 // recoloring and perform the actual recoloring. 1916 PQueue RecoloringQueue; 1917 for (const LiveInterval *RC : RecoloringCandidates) { 1918 Register ItVirtReg = RC->reg(); 1919 enqueue(RecoloringQueue, RC); 1920 assert(VRM->hasPhys(ItVirtReg) && 1921 "Interferences are supposed to be with allocated variables"); 1922 1923 // Record the current allocation. 1924 RecolorStack.push_back(std::make_pair(RC, VRM->getPhys(ItVirtReg))); 1925 1926 // unset the related struct. 1927 Matrix->unassign(*RC); 1928 } 1929 1930 // Do as if VirtReg was assigned to PhysReg so that the underlying 1931 // recoloring has the right information about the interferes and 1932 // available colors. 1933 Matrix->assign(VirtReg, PhysReg); 1934 1935 // Save the current recoloring state. 1936 // If we cannot recolor all the interferences, we will have to start again 1937 // at this point for the next physical register. 1938 SmallVirtRegSet SaveFixedRegisters(FixedRegisters); 1939 if (tryRecoloringCandidates(RecoloringQueue, CurrentNewVRegs, 1940 FixedRegisters, RecolorStack, Depth)) { 1941 // Push the queued vregs into the main queue. 1942 for (Register NewVReg : CurrentNewVRegs) 1943 NewVRegs.push_back(NewVReg); 1944 // Do not mess up with the global assignment process. 1945 // I.e., VirtReg must be unassigned. 1946 Matrix->unassign(VirtReg); 1947 return PhysReg; 1948 } 1949 1950 LLVM_DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to " 1951 << printReg(PhysReg, TRI) << '\n'); 1952 1953 // The recoloring attempt failed, undo the changes. 1954 FixedRegisters = SaveFixedRegisters; 1955 Matrix->unassign(VirtReg); 1956 1957 // For a newly created vreg which is also in RecoloringCandidates, 1958 // don't add it to NewVRegs because its physical register will be restored 1959 // below. Other vregs in CurrentNewVRegs are created by calling 1960 // selectOrSplit and should be added into NewVRegs. 1961 for (Register R : CurrentNewVRegs) { 1962 if (RecoloringCandidates.count(&LIS->getInterval(R))) 1963 continue; 1964 NewVRegs.push_back(R); 1965 } 1966 1967 // Roll back our unsuccessful recoloring. Also roll back any successful 1968 // recolorings in any recursive recoloring attempts, since it's possible 1969 // they would have introduced conflicts with assignments we will be 1970 // restoring further up the stack. Perform all unassignments prior to 1971 // reassigning, since sub-recolorings may have conflicted with the registers 1972 // we are going to restore to their original assignments. 1973 for (ssize_t I = RecolorStack.size() - 1; I >= EntryStackSize; --I) { 1974 const LiveInterval *LI; 1975 MCRegister PhysReg; 1976 std::tie(LI, PhysReg) = RecolorStack[I]; 1977 1978 if (VRM->hasPhys(LI->reg())) 1979 Matrix->unassign(*LI); 1980 } 1981 1982 for (size_t I = EntryStackSize; I != RecolorStack.size(); ++I) { 1983 const LiveInterval *LI; 1984 MCRegister PhysReg; 1985 std::tie(LI, PhysReg) = RecolorStack[I]; 1986 if (!LI->empty() && !MRI->reg_nodbg_empty(LI->reg())) 1987 Matrix->assign(*LI, PhysReg); 1988 } 1989 1990 // Pop the stack of recoloring attempts. 1991 RecolorStack.resize(EntryStackSize); 1992 } 1993 1994 // Last chance recoloring did not worked either, give up. 1995 return ~0u; 1996 } 1997 1998 /// tryRecoloringCandidates - Try to assign a new color to every register 1999 /// in \RecoloringQueue. 2000 /// \p NewRegs will contain any new virtual register created during the 2001 /// recoloring process. 2002 /// \p FixedRegisters[in/out] contains all the registers that have been 2003 /// recolored. 2004 /// \return true if all virtual registers in RecoloringQueue were successfully 2005 /// recolored, false otherwise. 2006 bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue, 2007 SmallVectorImpl<Register> &NewVRegs, 2008 SmallVirtRegSet &FixedRegisters, 2009 RecoloringStack &RecolorStack, 2010 unsigned Depth) { 2011 while (!RecoloringQueue.empty()) { 2012 const LiveInterval *LI = dequeue(RecoloringQueue); 2013 LLVM_DEBUG(dbgs() << "Try to recolor: " << *LI << '\n'); 2014 MCRegister PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters, 2015 RecolorStack, Depth + 1); 2016 // When splitting happens, the live-range may actually be empty. 2017 // In that case, this is okay to continue the recoloring even 2018 // if we did not find an alternative color for it. Indeed, 2019 // there will not be anything to color for LI in the end. 2020 if (PhysReg == ~0u || (!PhysReg && !LI->empty())) 2021 return false; 2022 2023 if (!PhysReg) { 2024 assert(LI->empty() && "Only empty live-range do not require a register"); 2025 LLVM_DEBUG(dbgs() << "Recoloring of " << *LI 2026 << " succeeded. Empty LI.\n"); 2027 continue; 2028 } 2029 LLVM_DEBUG(dbgs() << "Recoloring of " << *LI 2030 << " succeeded with: " << printReg(PhysReg, TRI) << '\n'); 2031 2032 Matrix->assign(*LI, PhysReg); 2033 FixedRegisters.insert(LI->reg()); 2034 } 2035 return true; 2036 } 2037 2038 //===----------------------------------------------------------------------===// 2039 // Main Entry Point 2040 //===----------------------------------------------------------------------===// 2041 2042 MCRegister RAGreedy::selectOrSplit(const LiveInterval &VirtReg, 2043 SmallVectorImpl<Register> &NewVRegs) { 2044 CutOffInfo = CO_None; 2045 LLVMContext &Ctx = MF->getFunction().getContext(); 2046 SmallVirtRegSet FixedRegisters; 2047 RecoloringStack RecolorStack; 2048 MCRegister Reg = 2049 selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters, RecolorStack); 2050 if (Reg == ~0U && (CutOffInfo != CO_None)) { 2051 uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf); 2052 if (CutOffEncountered == CO_Depth) 2053 Ctx.emitError("register allocation failed: maximum depth for recoloring " 2054 "reached. Use -fexhaustive-register-search to skip " 2055 "cutoffs"); 2056 else if (CutOffEncountered == CO_Interf) 2057 Ctx.emitError("register allocation failed: maximum interference for " 2058 "recoloring reached. Use -fexhaustive-register-search " 2059 "to skip cutoffs"); 2060 else if (CutOffEncountered == (CO_Depth | CO_Interf)) 2061 Ctx.emitError("register allocation failed: maximum interference and " 2062 "depth for recoloring reached. Use " 2063 "-fexhaustive-register-search to skip cutoffs"); 2064 } 2065 return Reg; 2066 } 2067 2068 /// Using a CSR for the first time has a cost because it causes push|pop 2069 /// to be added to prologue|epilogue. Splitting a cold section of the live 2070 /// range can have lower cost than using the CSR for the first time; 2071 /// Spilling a live range in the cold path can have lower cost than using 2072 /// the CSR for the first time. Returns the physical register if we decide 2073 /// to use the CSR; otherwise return 0. 2074 MCRegister RAGreedy::tryAssignCSRFirstTime( 2075 const LiveInterval &VirtReg, AllocationOrder &Order, MCRegister PhysReg, 2076 uint8_t &CostPerUseLimit, SmallVectorImpl<Register> &NewVRegs) { 2077 if (ExtraInfo->getStage(VirtReg) == RS_Spill && VirtReg.isSpillable()) { 2078 // We choose spill over using the CSR for the first time if the spill cost 2079 // is lower than CSRCost. 2080 SA->analyze(&VirtReg); 2081 if (calcSpillCost() >= CSRCost) 2082 return PhysReg; 2083 2084 // We are going to spill, set CostPerUseLimit to 1 to make sure that 2085 // we will not use a callee-saved register in tryEvict. 2086 CostPerUseLimit = 1; 2087 return 0; 2088 } 2089 if (ExtraInfo->getStage(VirtReg) < RS_Split) { 2090 // We choose pre-splitting over using the CSR for the first time if 2091 // the cost of splitting is lower than CSRCost. 2092 SA->analyze(&VirtReg); 2093 unsigned NumCands = 0; 2094 BlockFrequency BestCost = CSRCost; // Don't modify CSRCost. 2095 unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost, 2096 NumCands, true /*IgnoreCSR*/); 2097 if (BestCand == NoCand) 2098 // Use the CSR if we can't find a region split below CSRCost. 2099 return PhysReg; 2100 2101 // Perform the actual pre-splitting. 2102 doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs); 2103 return 0; 2104 } 2105 return PhysReg; 2106 } 2107 2108 void RAGreedy::aboutToRemoveInterval(const LiveInterval &LI) { 2109 // Do not keep invalid information around. 2110 SetOfBrokenHints.remove(&LI); 2111 } 2112 2113 void RAGreedy::initializeCSRCost() { 2114 // We use the larger one out of the command-line option and the value report 2115 // by TRI. 2116 CSRCost = BlockFrequency( 2117 std::max((unsigned)CSRFirstTimeCost, TRI->getCSRFirstUseCost())); 2118 if (!CSRCost.getFrequency()) 2119 return; 2120 2121 // Raw cost is relative to Entry == 2^14; scale it appropriately. 2122 uint64_t ActualEntry = MBFI->getEntryFreq(); 2123 if (!ActualEntry) { 2124 CSRCost = 0; 2125 return; 2126 } 2127 uint64_t FixedEntry = 1 << 14; 2128 if (ActualEntry < FixedEntry) 2129 CSRCost *= BranchProbability(ActualEntry, FixedEntry); 2130 else if (ActualEntry <= UINT32_MAX) 2131 // Invert the fraction and divide. 2132 CSRCost /= BranchProbability(FixedEntry, ActualEntry); 2133 else 2134 // Can't use BranchProbability in general, since it takes 32-bit numbers. 2135 CSRCost = CSRCost.getFrequency() * (ActualEntry / FixedEntry); 2136 } 2137 2138 /// Collect the hint info for \p Reg. 2139 /// The results are stored into \p Out. 2140 /// \p Out is not cleared before being populated. 2141 void RAGreedy::collectHintInfo(Register Reg, HintsInfo &Out) { 2142 for (const MachineInstr &Instr : MRI->reg_nodbg_instructions(Reg)) { 2143 if (!TII->isFullCopyInstr(Instr)) 2144 continue; 2145 // Look for the other end of the copy. 2146 Register OtherReg = Instr.getOperand(0).getReg(); 2147 if (OtherReg == Reg) { 2148 OtherReg = Instr.getOperand(1).getReg(); 2149 if (OtherReg == Reg) 2150 continue; 2151 } 2152 // Get the current assignment. 2153 MCRegister OtherPhysReg = 2154 OtherReg.isPhysical() ? OtherReg.asMCReg() : VRM->getPhys(OtherReg); 2155 // Push the collected information. 2156 Out.push_back(HintInfo(MBFI->getBlockFreq(Instr.getParent()), OtherReg, 2157 OtherPhysReg)); 2158 } 2159 } 2160 2161 /// Using the given \p List, compute the cost of the broken hints if 2162 /// \p PhysReg was used. 2163 /// \return The cost of \p List for \p PhysReg. 2164 BlockFrequency RAGreedy::getBrokenHintFreq(const HintsInfo &List, 2165 MCRegister PhysReg) { 2166 BlockFrequency Cost = 0; 2167 for (const HintInfo &Info : List) { 2168 if (Info.PhysReg != PhysReg) 2169 Cost += Info.Freq; 2170 } 2171 return Cost; 2172 } 2173 2174 /// Using the register assigned to \p VirtReg, try to recolor 2175 /// all the live ranges that are copy-related with \p VirtReg. 2176 /// The recoloring is then propagated to all the live-ranges that have 2177 /// been recolored and so on, until no more copies can be coalesced or 2178 /// it is not profitable. 2179 /// For a given live range, profitability is determined by the sum of the 2180 /// frequencies of the non-identity copies it would introduce with the old 2181 /// and new register. 2182 void RAGreedy::tryHintRecoloring(const LiveInterval &VirtReg) { 2183 // We have a broken hint, check if it is possible to fix it by 2184 // reusing PhysReg for the copy-related live-ranges. Indeed, we evicted 2185 // some register and PhysReg may be available for the other live-ranges. 2186 SmallSet<Register, 4> Visited; 2187 SmallVector<unsigned, 2> RecoloringCandidates; 2188 HintsInfo Info; 2189 Register Reg = VirtReg.reg(); 2190 MCRegister PhysReg = VRM->getPhys(Reg); 2191 // Start the recoloring algorithm from the input live-interval, then 2192 // it will propagate to the ones that are copy-related with it. 2193 Visited.insert(Reg); 2194 RecoloringCandidates.push_back(Reg); 2195 2196 LLVM_DEBUG(dbgs() << "Trying to reconcile hints for: " << printReg(Reg, TRI) 2197 << '(' << printReg(PhysReg, TRI) << ")\n"); 2198 2199 do { 2200 Reg = RecoloringCandidates.pop_back_val(); 2201 2202 // We cannot recolor physical register. 2203 if (Reg.isPhysical()) 2204 continue; 2205 2206 // This may be a skipped class 2207 if (!VRM->hasPhys(Reg)) { 2208 assert(!ShouldAllocateClass(*TRI, *MRI->getRegClass(Reg)) && 2209 "We have an unallocated variable which should have been handled"); 2210 continue; 2211 } 2212 2213 // Get the live interval mapped with this virtual register to be able 2214 // to check for the interference with the new color. 2215 LiveInterval &LI = LIS->getInterval(Reg); 2216 MCRegister CurrPhys = VRM->getPhys(Reg); 2217 // Check that the new color matches the register class constraints and 2218 // that it is free for this live range. 2219 if (CurrPhys != PhysReg && (!MRI->getRegClass(Reg)->contains(PhysReg) || 2220 Matrix->checkInterference(LI, PhysReg))) 2221 continue; 2222 2223 LLVM_DEBUG(dbgs() << printReg(Reg, TRI) << '(' << printReg(CurrPhys, TRI) 2224 << ") is recolorable.\n"); 2225 2226 // Gather the hint info. 2227 Info.clear(); 2228 collectHintInfo(Reg, Info); 2229 // Check if recoloring the live-range will increase the cost of the 2230 // non-identity copies. 2231 if (CurrPhys != PhysReg) { 2232 LLVM_DEBUG(dbgs() << "Checking profitability:\n"); 2233 BlockFrequency OldCopiesCost = getBrokenHintFreq(Info, CurrPhys); 2234 BlockFrequency NewCopiesCost = getBrokenHintFreq(Info, PhysReg); 2235 LLVM_DEBUG(dbgs() << "Old Cost: " << OldCopiesCost.getFrequency() 2236 << "\nNew Cost: " << NewCopiesCost.getFrequency() 2237 << '\n'); 2238 if (OldCopiesCost < NewCopiesCost) { 2239 LLVM_DEBUG(dbgs() << "=> Not profitable.\n"); 2240 continue; 2241 } 2242 // At this point, the cost is either cheaper or equal. If it is 2243 // equal, we consider this is profitable because it may expose 2244 // more recoloring opportunities. 2245 LLVM_DEBUG(dbgs() << "=> Profitable.\n"); 2246 // Recolor the live-range. 2247 Matrix->unassign(LI); 2248 Matrix->assign(LI, PhysReg); 2249 } 2250 // Push all copy-related live-ranges to keep reconciling the broken 2251 // hints. 2252 for (const HintInfo &HI : Info) { 2253 if (Visited.insert(HI.Reg).second) 2254 RecoloringCandidates.push_back(HI.Reg); 2255 } 2256 } while (!RecoloringCandidates.empty()); 2257 } 2258 2259 /// Try to recolor broken hints. 2260 /// Broken hints may be repaired by recoloring when an evicted variable 2261 /// freed up a register for a larger live-range. 2262 /// Consider the following example: 2263 /// BB1: 2264 /// a = 2265 /// b = 2266 /// BB2: 2267 /// ... 2268 /// = b 2269 /// = a 2270 /// Let us assume b gets split: 2271 /// BB1: 2272 /// a = 2273 /// b = 2274 /// BB2: 2275 /// c = b 2276 /// ... 2277 /// d = c 2278 /// = d 2279 /// = a 2280 /// Because of how the allocation work, b, c, and d may be assigned different 2281 /// colors. Now, if a gets evicted later: 2282 /// BB1: 2283 /// a = 2284 /// st a, SpillSlot 2285 /// b = 2286 /// BB2: 2287 /// c = b 2288 /// ... 2289 /// d = c 2290 /// = d 2291 /// e = ld SpillSlot 2292 /// = e 2293 /// This is likely that we can assign the same register for b, c, and d, 2294 /// getting rid of 2 copies. 2295 void RAGreedy::tryHintsRecoloring() { 2296 for (const LiveInterval *LI : SetOfBrokenHints) { 2297 assert(LI->reg().isVirtual() && 2298 "Recoloring is possible only for virtual registers"); 2299 // Some dead defs may be around (e.g., because of debug uses). 2300 // Ignore those. 2301 if (!VRM->hasPhys(LI->reg())) 2302 continue; 2303 tryHintRecoloring(*LI); 2304 } 2305 } 2306 2307 MCRegister RAGreedy::selectOrSplitImpl(const LiveInterval &VirtReg, 2308 SmallVectorImpl<Register> &NewVRegs, 2309 SmallVirtRegSet &FixedRegisters, 2310 RecoloringStack &RecolorStack, 2311 unsigned Depth) { 2312 uint8_t CostPerUseLimit = uint8_t(~0u); 2313 // First try assigning a free register. 2314 auto Order = 2315 AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix); 2316 if (MCRegister PhysReg = 2317 tryAssign(VirtReg, Order, NewVRegs, FixedRegisters)) { 2318 // When NewVRegs is not empty, we may have made decisions such as evicting 2319 // a virtual register, go with the earlier decisions and use the physical 2320 // register. 2321 if (CSRCost.getFrequency() && 2322 EvictAdvisor->isUnusedCalleeSavedReg(PhysReg) && NewVRegs.empty()) { 2323 MCRegister CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg, 2324 CostPerUseLimit, NewVRegs); 2325 if (CSRReg || !NewVRegs.empty()) 2326 // Return now if we decide to use a CSR or create new vregs due to 2327 // pre-splitting. 2328 return CSRReg; 2329 } else 2330 return PhysReg; 2331 } 2332 2333 LiveRangeStage Stage = ExtraInfo->getStage(VirtReg); 2334 LLVM_DEBUG(dbgs() << StageName[Stage] << " Cascade " 2335 << ExtraInfo->getCascade(VirtReg.reg()) << '\n'); 2336 2337 // Try to evict a less worthy live range, but only for ranges from the primary 2338 // queue. The RS_Split ranges already failed to do this, and they should not 2339 // get a second chance until they have been split. 2340 if (Stage != RS_Split) 2341 if (Register PhysReg = 2342 tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit, 2343 FixedRegisters)) { 2344 Register Hint = MRI->getSimpleHint(VirtReg.reg()); 2345 // If VirtReg has a hint and that hint is broken record this 2346 // virtual register as a recoloring candidate for broken hint. 2347 // Indeed, since we evicted a variable in its neighborhood it is 2348 // likely we can at least partially recolor some of the 2349 // copy-related live-ranges. 2350 if (Hint && Hint != PhysReg) 2351 SetOfBrokenHints.insert(&VirtReg); 2352 return PhysReg; 2353 } 2354 2355 assert((NewVRegs.empty() || Depth) && "Cannot append to existing NewVRegs"); 2356 2357 // The first time we see a live range, don't try to split or spill. 2358 // Wait until the second time, when all smaller ranges have been allocated. 2359 // This gives a better picture of the interference to split around. 2360 if (Stage < RS_Split) { 2361 ExtraInfo->setStage(VirtReg, RS_Split); 2362 LLVM_DEBUG(dbgs() << "wait for second round\n"); 2363 NewVRegs.push_back(VirtReg.reg()); 2364 return 0; 2365 } 2366 2367 if (Stage < RS_Spill) { 2368 // Try splitting VirtReg or interferences. 2369 unsigned NewVRegSizeBefore = NewVRegs.size(); 2370 Register PhysReg = trySplit(VirtReg, Order, NewVRegs, FixedRegisters); 2371 if (PhysReg || (NewVRegs.size() - NewVRegSizeBefore)) 2372 return PhysReg; 2373 } 2374 2375 // If we couldn't allocate a register from spilling, there is probably some 2376 // invalid inline assembly. The base class will report it. 2377 if (Stage >= RS_Done || !VirtReg.isSpillable()) { 2378 return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters, 2379 RecolorStack, Depth); 2380 } 2381 2382 // Finally spill VirtReg itself. 2383 if ((EnableDeferredSpilling || 2384 TRI->shouldUseDeferredSpillingForVirtReg(*MF, VirtReg)) && 2385 ExtraInfo->getStage(VirtReg) < RS_Memory) { 2386 // TODO: This is experimental and in particular, we do not model 2387 // the live range splitting done by spilling correctly. 2388 // We would need a deep integration with the spiller to do the 2389 // right thing here. Anyway, that is still good for early testing. 2390 ExtraInfo->setStage(VirtReg, RS_Memory); 2391 LLVM_DEBUG(dbgs() << "Do as if this register is in memory\n"); 2392 NewVRegs.push_back(VirtReg.reg()); 2393 } else { 2394 NamedRegionTimer T("spill", "Spiller", TimerGroupName, 2395 TimerGroupDescription, TimePassesIsEnabled); 2396 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats); 2397 spiller().spill(LRE); 2398 ExtraInfo->setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done); 2399 2400 // Tell LiveDebugVariables about the new ranges. Ranges not being covered by 2401 // the new regs are kept in LDV (still mapping to the old register), until 2402 // we rewrite spilled locations in LDV at a later stage. 2403 DebugVars->splitRegister(VirtReg.reg(), LRE.regs(), *LIS); 2404 2405 if (VerifyEnabled) 2406 MF->verify(this, "After spilling"); 2407 } 2408 2409 // The live virtual register requesting allocation was spilled, so tell 2410 // the caller not to allocate anything during this round. 2411 return 0; 2412 } 2413 2414 void RAGreedy::RAGreedyStats::report(MachineOptimizationRemarkMissed &R) { 2415 using namespace ore; 2416 if (Spills) { 2417 R << NV("NumSpills", Spills) << " spills "; 2418 R << NV("TotalSpillsCost", SpillsCost) << " total spills cost "; 2419 } 2420 if (FoldedSpills) { 2421 R << NV("NumFoldedSpills", FoldedSpills) << " folded spills "; 2422 R << NV("TotalFoldedSpillsCost", FoldedSpillsCost) 2423 << " total folded spills cost "; 2424 } 2425 if (Reloads) { 2426 R << NV("NumReloads", Reloads) << " reloads "; 2427 R << NV("TotalReloadsCost", ReloadsCost) << " total reloads cost "; 2428 } 2429 if (FoldedReloads) { 2430 R << NV("NumFoldedReloads", FoldedReloads) << " folded reloads "; 2431 R << NV("TotalFoldedReloadsCost", FoldedReloadsCost) 2432 << " total folded reloads cost "; 2433 } 2434 if (ZeroCostFoldedReloads) 2435 R << NV("NumZeroCostFoldedReloads", ZeroCostFoldedReloads) 2436 << " zero cost folded reloads "; 2437 if (Copies) { 2438 R << NV("NumVRCopies", Copies) << " virtual registers copies "; 2439 R << NV("TotalCopiesCost", CopiesCost) << " total copies cost "; 2440 } 2441 } 2442 2443 RAGreedy::RAGreedyStats RAGreedy::computeStats(MachineBasicBlock &MBB) { 2444 RAGreedyStats Stats; 2445 const MachineFrameInfo &MFI = MF->getFrameInfo(); 2446 int FI; 2447 2448 auto isSpillSlotAccess = [&MFI](const MachineMemOperand *A) { 2449 return MFI.isSpillSlotObjectIndex(cast<FixedStackPseudoSourceValue>( 2450 A->getPseudoValue())->getFrameIndex()); 2451 }; 2452 auto isPatchpointInstr = [](const MachineInstr &MI) { 2453 return MI.getOpcode() == TargetOpcode::PATCHPOINT || 2454 MI.getOpcode() == TargetOpcode::STACKMAP || 2455 MI.getOpcode() == TargetOpcode::STATEPOINT; 2456 }; 2457 for (MachineInstr &MI : MBB) { 2458 auto DestSrc = TII->isCopyInstr(MI); 2459 if (DestSrc) { 2460 const MachineOperand &Dest = *DestSrc->Destination; 2461 const MachineOperand &Src = *DestSrc->Source; 2462 Register SrcReg = Src.getReg(); 2463 Register DestReg = Dest.getReg(); 2464 // Only count `COPY`s with a virtual register as source or destination. 2465 if (SrcReg.isVirtual() || DestReg.isVirtual()) { 2466 if (SrcReg.isVirtual()) { 2467 SrcReg = VRM->getPhys(SrcReg); 2468 if (SrcReg && Src.getSubReg()) 2469 SrcReg = TRI->getSubReg(SrcReg, Src.getSubReg()); 2470 } 2471 if (DestReg.isVirtual()) { 2472 DestReg = VRM->getPhys(DestReg); 2473 if (DestReg && Dest.getSubReg()) 2474 DestReg = TRI->getSubReg(DestReg, Dest.getSubReg()); 2475 } 2476 if (SrcReg != DestReg) 2477 ++Stats.Copies; 2478 } 2479 continue; 2480 } 2481 2482 SmallVector<const MachineMemOperand *, 2> Accesses; 2483 if (TII->isLoadFromStackSlot(MI, FI) && MFI.isSpillSlotObjectIndex(FI)) { 2484 ++Stats.Reloads; 2485 continue; 2486 } 2487 if (TII->isStoreToStackSlot(MI, FI) && MFI.isSpillSlotObjectIndex(FI)) { 2488 ++Stats.Spills; 2489 continue; 2490 } 2491 if (TII->hasLoadFromStackSlot(MI, Accesses) && 2492 llvm::any_of(Accesses, isSpillSlotAccess)) { 2493 if (!isPatchpointInstr(MI)) { 2494 Stats.FoldedReloads += Accesses.size(); 2495 continue; 2496 } 2497 // For statepoint there may be folded and zero cost folded stack reloads. 2498 std::pair<unsigned, unsigned> NonZeroCostRange = 2499 TII->getPatchpointUnfoldableRange(MI); 2500 SmallSet<unsigned, 16> FoldedReloads; 2501 SmallSet<unsigned, 16> ZeroCostFoldedReloads; 2502 for (unsigned Idx = 0, E = MI.getNumOperands(); Idx < E; ++Idx) { 2503 MachineOperand &MO = MI.getOperand(Idx); 2504 if (!MO.isFI() || !MFI.isSpillSlotObjectIndex(MO.getIndex())) 2505 continue; 2506 if (Idx >= NonZeroCostRange.first && Idx < NonZeroCostRange.second) 2507 FoldedReloads.insert(MO.getIndex()); 2508 else 2509 ZeroCostFoldedReloads.insert(MO.getIndex()); 2510 } 2511 // If stack slot is used in folded reload it is not zero cost then. 2512 for (unsigned Slot : FoldedReloads) 2513 ZeroCostFoldedReloads.erase(Slot); 2514 Stats.FoldedReloads += FoldedReloads.size(); 2515 Stats.ZeroCostFoldedReloads += ZeroCostFoldedReloads.size(); 2516 continue; 2517 } 2518 Accesses.clear(); 2519 if (TII->hasStoreToStackSlot(MI, Accesses) && 2520 llvm::any_of(Accesses, isSpillSlotAccess)) { 2521 Stats.FoldedSpills += Accesses.size(); 2522 } 2523 } 2524 // Set cost of collected statistic by multiplication to relative frequency of 2525 // this basic block. 2526 float RelFreq = MBFI->getBlockFreqRelativeToEntryBlock(&MBB); 2527 Stats.ReloadsCost = RelFreq * Stats.Reloads; 2528 Stats.FoldedReloadsCost = RelFreq * Stats.FoldedReloads; 2529 Stats.SpillsCost = RelFreq * Stats.Spills; 2530 Stats.FoldedSpillsCost = RelFreq * Stats.FoldedSpills; 2531 Stats.CopiesCost = RelFreq * Stats.Copies; 2532 return Stats; 2533 } 2534 2535 RAGreedy::RAGreedyStats RAGreedy::reportStats(MachineLoop *L) { 2536 RAGreedyStats Stats; 2537 2538 // Sum up the spill and reloads in subloops. 2539 for (MachineLoop *SubLoop : *L) 2540 Stats.add(reportStats(SubLoop)); 2541 2542 for (MachineBasicBlock *MBB : L->getBlocks()) 2543 // Handle blocks that were not included in subloops. 2544 if (Loops->getLoopFor(MBB) == L) 2545 Stats.add(computeStats(*MBB)); 2546 2547 if (!Stats.isEmpty()) { 2548 using namespace ore; 2549 2550 ORE->emit([&]() { 2551 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "LoopSpillReloadCopies", 2552 L->getStartLoc(), L->getHeader()); 2553 Stats.report(R); 2554 R << "generated in loop"; 2555 return R; 2556 }); 2557 } 2558 return Stats; 2559 } 2560 2561 void RAGreedy::reportStats() { 2562 if (!ORE->allowExtraAnalysis(DEBUG_TYPE)) 2563 return; 2564 RAGreedyStats Stats; 2565 for (MachineLoop *L : *Loops) 2566 Stats.add(reportStats(L)); 2567 // Process non-loop blocks. 2568 for (MachineBasicBlock &MBB : *MF) 2569 if (!Loops->getLoopFor(&MBB)) 2570 Stats.add(computeStats(MBB)); 2571 if (!Stats.isEmpty()) { 2572 using namespace ore; 2573 2574 ORE->emit([&]() { 2575 DebugLoc Loc; 2576 if (auto *SP = MF->getFunction().getSubprogram()) 2577 Loc = DILocation::get(SP->getContext(), SP->getLine(), 1, SP); 2578 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "SpillReloadCopies", Loc, 2579 &MF->front()); 2580 Stats.report(R); 2581 R << "generated in function"; 2582 return R; 2583 }); 2584 } 2585 } 2586 2587 bool RAGreedy::hasVirtRegAlloc() { 2588 for (unsigned I = 0, E = MRI->getNumVirtRegs(); I != E; ++I) { 2589 Register Reg = Register::index2VirtReg(I); 2590 if (MRI->reg_nodbg_empty(Reg)) 2591 continue; 2592 const TargetRegisterClass *RC = MRI->getRegClass(Reg); 2593 if (!RC) 2594 continue; 2595 if (ShouldAllocateClass(*TRI, *RC)) 2596 return true; 2597 } 2598 2599 return false; 2600 } 2601 2602 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) { 2603 LLVM_DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n" 2604 << "********** Function: " << mf.getName() << '\n'); 2605 2606 MF = &mf; 2607 TII = MF->getSubtarget().getInstrInfo(); 2608 2609 if (VerifyEnabled) 2610 MF->verify(this, "Before greedy register allocator"); 2611 2612 RegAllocBase::init(getAnalysis<VirtRegMap>(), 2613 getAnalysis<LiveIntervals>(), 2614 getAnalysis<LiveRegMatrix>()); 2615 2616 // Early return if there is no virtual register to be allocated to a 2617 // physical register. 2618 if (!hasVirtRegAlloc()) 2619 return false; 2620 2621 Indexes = &getAnalysis<SlotIndexes>(); 2622 MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); 2623 DomTree = &getAnalysis<MachineDominatorTree>(); 2624 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE(); 2625 Loops = &getAnalysis<MachineLoopInfo>(); 2626 Bundles = &getAnalysis<EdgeBundles>(); 2627 SpillPlacer = &getAnalysis<SpillPlacement>(); 2628 DebugVars = &getAnalysis<LiveDebugVariables>(); 2629 2630 initializeCSRCost(); 2631 2632 RegCosts = TRI->getRegisterCosts(*MF); 2633 RegClassPriorityTrumpsGlobalness = 2634 GreedyRegClassPriorityTrumpsGlobalness.getNumOccurrences() 2635 ? GreedyRegClassPriorityTrumpsGlobalness 2636 : TRI->regClassPriorityTrumpsGlobalness(*MF); 2637 2638 ReverseLocalAssignment = GreedyReverseLocalAssignment.getNumOccurrences() 2639 ? GreedyReverseLocalAssignment 2640 : TRI->reverseLocalAssignment(); 2641 2642 ExtraInfo.emplace(); 2643 EvictAdvisor = 2644 getAnalysis<RegAllocEvictionAdvisorAnalysis>().getAdvisor(*MF, *this); 2645 PriorityAdvisor = 2646 getAnalysis<RegAllocPriorityAdvisorAnalysis>().getAdvisor(*MF, *this); 2647 2648 VRAI = std::make_unique<VirtRegAuxInfo>(*MF, *LIS, *VRM, *Loops, *MBFI); 2649 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM, *VRAI)); 2650 2651 VRAI->calculateSpillWeightsAndHints(); 2652 2653 LLVM_DEBUG(LIS->dump()); 2654 2655 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops)); 2656 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI, *VRAI)); 2657 2658 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI); 2659 GlobalCand.resize(32); // This will grow as needed. 2660 SetOfBrokenHints.clear(); 2661 2662 allocatePhysRegs(); 2663 tryHintsRecoloring(); 2664 2665 if (VerifyEnabled) 2666 MF->verify(this, "Before post optimization"); 2667 postOptimization(); 2668 reportStats(); 2669 2670 releaseMemory(); 2671 return true; 2672 } 2673