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