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