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