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