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