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