1 //===-- RegAllocGreedy.cpp - greedy register allocator --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the RAGreedy function pass for register allocation in
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regalloc"
16 #include "llvm/CodeGen/Passes.h"
17 #include "AllocationOrder.h"
18 #include "InterferenceCache.h"
19 #include "LiveDebugVariables.h"
20 #include "RegAllocBase.h"
21 #include "SpillPlacement.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/CodeGen/CalcSpillWeights.h"
27 #include "llvm/CodeGen/EdgeBundles.h"
28 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
29 #include "llvm/CodeGen/LiveRangeEdit.h"
30 #include "llvm/CodeGen/LiveRegMatrix.h"
31 #include "llvm/CodeGen/LiveStackAnalysis.h"
32 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
33 #include "llvm/CodeGen/MachineDominators.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineLoopInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/RegAllocRegistry.h"
38 #include "llvm/CodeGen/RegisterClassInfo.h"
39 #include "llvm/CodeGen/VirtRegMap.h"
40 #include "llvm/IR/LLVMContext.h"
41 #include "llvm/PassAnalysisSupport.h"
42 #include "llvm/Support/BranchProbability.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/Timer.h"
47 #include "llvm/Support/raw_ostream.h"
52 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
53 STATISTIC(NumLocalSplits, "Number of split local live ranges");
54 STATISTIC(NumEvicted, "Number of interferences evicted");
56 static cl::opt<SplitEditor::ComplementSpillMode>
57 SplitSpillMode("split-spill-mode", cl::Hidden,
58 cl::desc("Spill mode for splitting live ranges"),
59 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
60 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
61 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
63 cl::init(SplitEditor::SM_Partition));
65 static cl::opt<unsigned>
66 LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden,
67 cl::desc("Last chance recoloring max depth"),
70 static cl::opt<unsigned> LastChanceRecoloringMaxInterference(
71 "lcr-max-interf", cl::Hidden,
72 cl::desc("Last chance recoloring maximum number of considered"
73 " interference at a time"),
77 ExhaustiveSearch("exhaustive-register-search", cl::NotHidden,
78 cl::desc("Exhaustive Search for registers bypassing the depth "
79 "and interference cutoffs of last chance recoloring"));
81 // FIXME: Find a good default for this flag and remove the flag.
82 static cl::opt<unsigned>
83 CSRFirstTimeCost("regalloc-csr-first-time-cost",
84 cl::desc("Cost for first time use of callee-saved register."),
85 cl::init(0), cl::Hidden);
87 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
88 createGreedyRegisterAllocator);
91 class RAGreedy : public MachineFunctionPass,
93 private LiveRangeEdit::Delegate {
94 // Convenient shortcuts.
95 typedef std::priority_queue<std::pair<unsigned, unsigned> > PQueue;
96 typedef SmallPtrSet<LiveInterval *, 4> SmallLISet;
97 typedef SmallSet<unsigned, 16> SmallVirtRegSet;
102 // Shortcuts to some useful interface.
103 const TargetInstrInfo *TII;
104 const TargetRegisterInfo *TRI;
105 RegisterClassInfo RCI;
108 SlotIndexes *Indexes;
109 MachineBlockFrequencyInfo *MBFI;
110 MachineDominatorTree *DomTree;
111 MachineLoopInfo *Loops;
112 EdgeBundles *Bundles;
113 SpillPlacement *SpillPlacer;
114 LiveDebugVariables *DebugVars;
117 std::unique_ptr<Spiller> SpillerInstance;
119 unsigned NextCascade;
121 // Live ranges pass through a number of stages as we try to allocate them.
122 // Some of the stages may also create new live ranges:
124 // - Region splitting.
125 // - Per-block splitting.
126 // - Local splitting.
129 // Ranges produced by one of the stages skip the previous stages when they are
130 // dequeued. This improves performance because we can skip interference checks
131 // that are unlikely to give any results. It also guarantees that the live
132 // range splitting algorithm terminates, something that is otherwise hard to
134 enum LiveRangeStage {
135 /// Newly created live range that has never been queued.
138 /// Only attempt assignment and eviction. Then requeue as RS_Split.
141 /// Attempt live range splitting if assignment is impossible.
144 /// Attempt more aggressive live range splitting that is guaranteed to make
145 /// progress. This is used for split products that may not be making
149 /// Live range will be spilled. No more splitting will be attempted.
152 /// There is nothing more we can do to this live range. Abort compilation
153 /// if it can't be assigned.
157 // Enum CutOffStage to keep a track whether the register allocation failed
158 // because of the cutoffs encountered in last chance recoloring.
159 // Note: This is used as bitmask. New value should be next power of 2.
161 // No cutoffs encountered
164 // lcr-max-depth cutoff encountered
167 // lcr-max-interf cutoff encountered
174 static const char *const StageName[];
177 // RegInfo - Keep additional information about each live range.
179 LiveRangeStage Stage;
181 // Cascade - Eviction loop prevention. See canEvictInterference().
184 RegInfo() : Stage(RS_New), Cascade(0) {}
187 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
189 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
190 return ExtraRegInfo[VirtReg.reg].Stage;
193 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
194 ExtraRegInfo.resize(MRI->getNumVirtRegs());
195 ExtraRegInfo[VirtReg.reg].Stage = Stage;
198 template<typename Iterator>
199 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
200 ExtraRegInfo.resize(MRI->getNumVirtRegs());
201 for (;Begin != End; ++Begin) {
202 unsigned Reg = *Begin;
203 if (ExtraRegInfo[Reg].Stage == RS_New)
204 ExtraRegInfo[Reg].Stage = NewStage;
208 /// Cost of evicting interference.
209 struct EvictionCost {
210 unsigned BrokenHints; ///< Total number of broken hints.
211 float MaxWeight; ///< Maximum spill weight evicted.
213 EvictionCost(): BrokenHints(0), MaxWeight(0) {}
215 bool isMax() const { return BrokenHints == ~0u; }
217 void setMax() { BrokenHints = ~0u; }
219 void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
221 bool operator<(const EvictionCost &O) const {
222 return std::tie(BrokenHints, MaxWeight) <
223 std::tie(O.BrokenHints, O.MaxWeight);
228 std::unique_ptr<SplitAnalysis> SA;
229 std::unique_ptr<SplitEditor> SE;
231 /// Cached per-block interference maps
232 InterferenceCache IntfCache;
234 /// All basic blocks where the current register has uses.
235 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
237 /// Global live range splitting candidate info.
238 struct GlobalSplitCandidate {
239 // Register intended for assignment, or 0.
242 // SplitKit interval index for this candidate.
245 // Interference for PhysReg.
246 InterferenceCache::Cursor Intf;
248 // Bundles where this candidate should be live.
249 BitVector LiveBundles;
250 SmallVector<unsigned, 8> ActiveBlocks;
252 void reset(InterferenceCache &Cache, unsigned Reg) {
255 Intf.setPhysReg(Cache, Reg);
257 ActiveBlocks.clear();
260 // Set B[i] = C for every live bundle where B[i] was NoCand.
261 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
263 for (int i = LiveBundles.find_first(); i >= 0;
264 i = LiveBundles.find_next(i))
265 if (B[i] == NoCand) {
273 /// Candidate info for each PhysReg in AllocationOrder.
274 /// This vector never shrinks, but grows to the size of the largest register
276 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
278 enum : unsigned { NoCand = ~0u };
280 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
281 /// NoCand which indicates the stack interval.
282 SmallVector<unsigned, 32> BundleCand;
284 /// Callee-save register cost, calculated once per machine function.
285 BlockFrequency CSRCost;
290 /// Return the pass name.
291 const char* getPassName() const override {
292 return "Greedy Register Allocator";
295 /// RAGreedy analysis usage.
296 void getAnalysisUsage(AnalysisUsage &AU) const override;
297 void releaseMemory() override;
298 Spiller &spiller() override { return *SpillerInstance; }
299 void enqueue(LiveInterval *LI) override;
300 LiveInterval *dequeue() override;
301 unsigned selectOrSplit(LiveInterval&, SmallVectorImpl<unsigned>&) override;
303 /// Perform register allocation.
304 bool runOnMachineFunction(MachineFunction &mf) override;
309 unsigned selectOrSplitImpl(LiveInterval &, SmallVectorImpl<unsigned> &,
310 SmallVirtRegSet &, unsigned = 0);
312 bool LRE_CanEraseVirtReg(unsigned) override;
313 void LRE_WillShrinkVirtReg(unsigned) override;
314 void LRE_DidCloneVirtReg(unsigned, unsigned) override;
315 void enqueue(PQueue &CurQueue, LiveInterval *LI);
316 LiveInterval *dequeue(PQueue &CurQueue);
318 BlockFrequency calcSpillCost();
319 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
320 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
321 void growRegion(GlobalSplitCandidate &Cand);
322 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate&);
323 bool calcCompactRegion(GlobalSplitCandidate&);
324 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
325 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
326 unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
327 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
328 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
329 void evictInterference(LiveInterval&, unsigned,
330 SmallVectorImpl<unsigned>&);
331 bool mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
332 SmallLISet &RecoloringCandidates,
333 const SmallVirtRegSet &FixedRegisters);
335 unsigned tryAssign(LiveInterval&, AllocationOrder&,
336 SmallVectorImpl<unsigned>&);
337 unsigned tryEvict(LiveInterval&, AllocationOrder&,
338 SmallVectorImpl<unsigned>&, unsigned = ~0u);
339 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
340 SmallVectorImpl<unsigned>&);
341 /// Calculate cost of region splitting.
342 unsigned calculateRegionSplitCost(LiveInterval &VirtReg,
343 AllocationOrder &Order,
344 BlockFrequency &BestCost,
345 unsigned &NumCands, bool IgnoreCSR);
346 /// Perform region splitting.
347 unsigned doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
349 SmallVectorImpl<unsigned> &NewVRegs);
350 /// Check other options before using a callee-saved register for the first
352 unsigned tryAssignCSRFirstTime(LiveInterval &VirtReg, AllocationOrder &Order,
353 unsigned PhysReg, unsigned &CostPerUseLimit,
354 SmallVectorImpl<unsigned> &NewVRegs);
355 void initializeCSRCost();
356 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
357 SmallVectorImpl<unsigned>&);
358 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
359 SmallVectorImpl<unsigned>&);
360 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
361 SmallVectorImpl<unsigned>&);
362 unsigned trySplit(LiveInterval&, AllocationOrder&,
363 SmallVectorImpl<unsigned>&);
364 unsigned tryLastChanceRecoloring(LiveInterval &, AllocationOrder &,
365 SmallVectorImpl<unsigned> &,
366 SmallVirtRegSet &, unsigned);
367 bool tryRecoloringCandidates(PQueue &, SmallVectorImpl<unsigned> &,
368 SmallVirtRegSet &, unsigned);
370 } // end anonymous namespace
372 char RAGreedy::ID = 0;
375 const char *const RAGreedy::StageName[] = {
385 // Hysteresis to use when comparing floats.
386 // This helps stabilize decisions based on float comparisons.
387 const float Hysteresis = (2007 / 2048.0f); // 0.97998046875
390 FunctionPass* llvm::createGreedyRegisterAllocator() {
391 return new RAGreedy();
394 RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
395 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
396 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
397 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
398 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
399 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
400 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
401 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
402 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
403 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
404 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
405 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
406 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
407 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
410 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
411 AU.setPreservesCFG();
412 AU.addRequired<MachineBlockFrequencyInfo>();
413 AU.addPreserved<MachineBlockFrequencyInfo>();
414 AU.addRequired<AliasAnalysis>();
415 AU.addPreserved<AliasAnalysis>();
416 AU.addRequired<LiveIntervals>();
417 AU.addPreserved<LiveIntervals>();
418 AU.addRequired<SlotIndexes>();
419 AU.addPreserved<SlotIndexes>();
420 AU.addRequired<LiveDebugVariables>();
421 AU.addPreserved<LiveDebugVariables>();
422 AU.addRequired<LiveStacks>();
423 AU.addPreserved<LiveStacks>();
424 AU.addRequired<MachineDominatorTree>();
425 AU.addPreserved<MachineDominatorTree>();
426 AU.addRequired<MachineLoopInfo>();
427 AU.addPreserved<MachineLoopInfo>();
428 AU.addRequired<VirtRegMap>();
429 AU.addPreserved<VirtRegMap>();
430 AU.addRequired<LiveRegMatrix>();
431 AU.addPreserved<LiveRegMatrix>();
432 AU.addRequired<EdgeBundles>();
433 AU.addRequired<SpillPlacement>();
434 MachineFunctionPass::getAnalysisUsage(AU);
438 //===----------------------------------------------------------------------===//
439 // LiveRangeEdit delegate methods
440 //===----------------------------------------------------------------------===//
442 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
443 if (VRM->hasPhys(VirtReg)) {
444 Matrix->unassign(LIS->getInterval(VirtReg));
447 // Unassigned virtreg is probably in the priority queue.
448 // RegAllocBase will erase it after dequeueing.
452 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
453 if (!VRM->hasPhys(VirtReg))
456 // Register is assigned, put it back on the queue for reassignment.
457 LiveInterval &LI = LIS->getInterval(VirtReg);
458 Matrix->unassign(LI);
462 void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
463 // Cloning a register we haven't even heard about yet? Just ignore it.
464 if (!ExtraRegInfo.inBounds(Old))
467 // LRE may clone a virtual register because dead code elimination causes it to
468 // be split into connected components. The new components are much smaller
469 // than the original, so they should get a new chance at being assigned.
470 // same stage as the parent.
471 ExtraRegInfo[Old].Stage = RS_Assign;
472 ExtraRegInfo.grow(New);
473 ExtraRegInfo[New] = ExtraRegInfo[Old];
476 void RAGreedy::releaseMemory() {
477 SpillerInstance.reset(0);
478 ExtraRegInfo.clear();
482 void RAGreedy::enqueue(LiveInterval *LI) { enqueue(Queue, LI); }
484 void RAGreedy::enqueue(PQueue &CurQueue, LiveInterval *LI) {
485 // Prioritize live ranges by size, assigning larger ranges first.
486 // The queue holds (size, reg) pairs.
487 const unsigned Size = LI->getSize();
488 const unsigned Reg = LI->reg;
489 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
490 "Can only enqueue virtual registers");
493 ExtraRegInfo.grow(Reg);
494 if (ExtraRegInfo[Reg].Stage == RS_New)
495 ExtraRegInfo[Reg].Stage = RS_Assign;
497 if (ExtraRegInfo[Reg].Stage == RS_Split) {
498 // Unsplit ranges that couldn't be allocated immediately are deferred until
499 // everything else has been allocated.
502 // Giant live ranges fall back to the global assignment heuristic, which
503 // prevents excessive spilling in pathological cases.
504 bool ReverseLocal = TRI->reverseLocalAssignment();
505 bool ForceGlobal = !ReverseLocal && TRI->mayOverrideLocalAssignment() &&
506 (Size / SlotIndex::InstrDist) > (2 * MRI->getRegClass(Reg)->getNumRegs());
508 if (ExtraRegInfo[Reg].Stage == RS_Assign && !ForceGlobal && !LI->empty() &&
509 LIS->intervalIsInOneMBB(*LI)) {
510 // Allocate original local ranges in linear instruction order. Since they
511 // are singly defined, this produces optimal coloring in the absence of
512 // global interference and other constraints.
514 Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
516 // Allocating bottom up may allow many short LRGs to be assigned first
517 // to one of the cheap registers. This could be much faster for very
518 // large blocks on targets with many physical registers.
519 Prio = Indexes->getZeroIndex().getInstrDistance(LI->beginIndex());
523 // Allocate global and split ranges in long->short order. Long ranges that
524 // don't fit should be spilled (or split) ASAP so they don't create
525 // interference. Mark a bit to prioritize global above local ranges.
526 Prio = (1u << 29) + Size;
528 // Mark a higher bit to prioritize global and local above RS_Split.
531 // Boost ranges that have a physical register hint.
532 if (VRM->hasKnownPreference(Reg))
535 // The virtual register number is a tie breaker for same-sized ranges.
536 // Give lower vreg numbers higher priority to assign them first.
537 CurQueue.push(std::make_pair(Prio, ~Reg));
540 LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); }
542 LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) {
543 if (CurQueue.empty())
545 LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
551 //===----------------------------------------------------------------------===//
553 //===----------------------------------------------------------------------===//
555 /// tryAssign - Try to assign VirtReg to an available register.
556 unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
557 AllocationOrder &Order,
558 SmallVectorImpl<unsigned> &NewVRegs) {
561 while ((PhysReg = Order.next()))
562 if (!Matrix->checkInterference(VirtReg, PhysReg))
564 if (!PhysReg || Order.isHint())
567 // PhysReg is available, but there may be a better choice.
569 // If we missed a simple hint, try to cheaply evict interference from the
570 // preferred register.
571 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
572 if (Order.isHint(Hint)) {
573 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
574 EvictionCost MaxCost;
575 MaxCost.setBrokenHints(1);
576 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
577 evictInterference(VirtReg, Hint, NewVRegs);
582 // Try to evict interference from a cheaper alternative.
583 unsigned Cost = TRI->getCostPerUse(PhysReg);
585 // Most registers have 0 additional cost.
589 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
591 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
592 return CheapReg ? CheapReg : PhysReg;
596 //===----------------------------------------------------------------------===//
597 // Interference eviction
598 //===----------------------------------------------------------------------===//
600 unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
601 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
603 while ((PhysReg = Order.next())) {
604 if (PhysReg == PrevReg)
607 MCRegUnitIterator Units(PhysReg, TRI);
608 for (; Units.isValid(); ++Units) {
609 // Instantiate a "subquery", not to be confused with the Queries array.
610 LiveIntervalUnion::Query subQ(&VirtReg, &Matrix->getLiveUnions()[*Units]);
611 if (subQ.checkInterference())
614 // If no units have interference, break out with the current PhysReg.
615 if (!Units.isValid())
619 DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
620 << PrintReg(PrevReg, TRI) << " to " << PrintReg(PhysReg, TRI)
625 /// shouldEvict - determine if A should evict the assigned live range B. The
626 /// eviction policy defined by this function together with the allocation order
627 /// defined by enqueue() decides which registers ultimately end up being split
630 /// Cascade numbers are used to prevent infinite loops if this function is a
633 /// @param A The live range to be assigned.
634 /// @param IsHint True when A is about to be assigned to its preferred
636 /// @param B The live range to be evicted.
637 /// @param BreaksHint True when B is already assigned to its preferred register.
638 bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
639 LiveInterval &B, bool BreaksHint) {
640 bool CanSplit = getStage(B) < RS_Spill;
642 // Be fairly aggressive about following hints as long as the evictee can be
644 if (CanSplit && IsHint && !BreaksHint)
647 if (A.weight > B.weight) {
648 DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight << '\n');
654 /// canEvictInterference - Return true if all interferences between VirtReg and
655 /// PhysReg can be evicted.
657 /// @param VirtReg Live range that is about to be assigned.
658 /// @param PhysReg Desired register for assignment.
659 /// @param IsHint True when PhysReg is VirtReg's preferred register.
660 /// @param MaxCost Only look for cheaper candidates and update with new cost
661 /// when returning true.
662 /// @returns True when interference can be evicted cheaper than MaxCost.
663 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
664 bool IsHint, EvictionCost &MaxCost) {
665 // It is only possible to evict virtual register interference.
666 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
669 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
671 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
672 // involved in an eviction before. If a cascade number was assigned, deny
673 // evicting anything with the same or a newer cascade number. This prevents
674 // infinite eviction loops.
676 // This works out so a register without a cascade number is allowed to evict
677 // anything, and it can be evicted by anything.
678 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
680 Cascade = NextCascade;
683 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
684 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
685 // If there is 10 or more interferences, chances are one is heavier.
686 if (Q.collectInterferingVRegs(10) >= 10)
689 // Check if any interfering live range is heavier than MaxWeight.
690 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
691 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
692 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
693 "Only expecting virtual register interference from query");
694 // Never evict spill products. They cannot split or spill.
695 if (getStage(*Intf) == RS_Done)
697 // Once a live range becomes small enough, it is urgent that we find a
698 // register for it. This is indicated by an infinite spill weight. These
699 // urgent live ranges get to evict almost anything.
701 // Also allow urgent evictions of unspillable ranges from a strictly
702 // larger allocation order.
703 bool Urgent = !VirtReg.isSpillable() &&
704 (Intf->isSpillable() ||
705 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
706 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
707 // Only evict older cascades or live ranges without a cascade.
708 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
709 if (Cascade <= IntfCascade) {
712 // We permit breaking cascades for urgent evictions. It should be the
713 // last resort, though, so make it really expensive.
714 Cost.BrokenHints += 10;
716 // Would this break a satisfied hint?
717 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
718 // Update eviction cost.
719 Cost.BrokenHints += BreaksHint;
720 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
721 // Abort if this would be too expensive.
722 if (!(Cost < MaxCost))
726 // Apply the eviction policy for non-urgent evictions.
727 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
729 // If !MaxCost.isMax(), then we're just looking for a cheap register.
730 // Evicting another local live range in this case could lead to suboptimal
732 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
733 !canReassign(*Intf, PhysReg)) {
742 /// evictInterference - Evict any interferring registers that prevent VirtReg
743 /// from being assigned to Physreg. This assumes that canEvictInterference
745 void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
746 SmallVectorImpl<unsigned> &NewVRegs) {
747 // Make sure that VirtReg has a cascade number, and assign that cascade
748 // number to every evicted register. These live ranges than then only be
749 // evicted by a newer cascade, preventing infinite loops.
750 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
752 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
754 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
755 << " interference: Cascade " << Cascade << '\n');
757 // Collect all interfering virtregs first.
758 SmallVector<LiveInterval*, 8> Intfs;
759 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
760 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
761 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
762 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
763 Intfs.append(IVR.begin(), IVR.end());
766 // Evict them second. This will invalidate the queries.
767 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
768 LiveInterval *Intf = Intfs[i];
769 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
770 if (!VRM->hasPhys(Intf->reg))
772 Matrix->unassign(*Intf);
773 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
774 VirtReg.isSpillable() < Intf->isSpillable()) &&
775 "Cannot decrease cascade number, illegal eviction");
776 ExtraRegInfo[Intf->reg].Cascade = Cascade;
778 NewVRegs.push_back(Intf->reg);
782 /// tryEvict - Try to evict all interferences for a physreg.
783 /// @param VirtReg Currently unassigned virtual register.
784 /// @param Order Physregs to try.
785 /// @return Physreg to assign VirtReg, or 0.
786 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
787 AllocationOrder &Order,
788 SmallVectorImpl<unsigned> &NewVRegs,
789 unsigned CostPerUseLimit) {
790 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
792 // Keep track of the cheapest interference seen so far.
793 EvictionCost BestCost;
795 unsigned BestPhys = 0;
796 unsigned OrderLimit = Order.getOrder().size();
798 // When we are just looking for a reduced cost per use, don't break any
799 // hints, and only evict smaller spill weights.
800 if (CostPerUseLimit < ~0u) {
801 BestCost.BrokenHints = 0;
802 BestCost.MaxWeight = VirtReg.weight;
804 // Check of any registers in RC are below CostPerUseLimit.
805 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
806 unsigned MinCost = RegClassInfo.getMinCost(RC);
807 if (MinCost >= CostPerUseLimit) {
808 DEBUG(dbgs() << RC->getName() << " minimum cost = " << MinCost
809 << ", no cheaper registers to be found.\n");
813 // It is normal for register classes to have a long tail of registers with
814 // the same cost. We don't need to look at them if they're too expensive.
815 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
816 OrderLimit = RegClassInfo.getLastCostChange(RC);
817 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
822 while (unsigned PhysReg = Order.next(OrderLimit)) {
823 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
825 // The first use of a callee-saved register in a function has cost 1.
826 // Don't start using a CSR when the CostPerUseLimit is low.
827 if (CostPerUseLimit == 1)
828 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
829 if (!MRI->isPhysRegUsed(CSR)) {
830 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
831 << PrintReg(CSR, TRI) << '\n');
835 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
841 // Stop if the hint can be used.
849 evictInterference(VirtReg, BestPhys, NewVRegs);
854 //===----------------------------------------------------------------------===//
856 //===----------------------------------------------------------------------===//
858 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
859 /// interference pattern in Physreg and its aliases. Add the constraints to
860 /// SpillPlacement and return the static cost of this split in Cost, assuming
861 /// that all preferences in SplitConstraints are met.
862 /// Return false if there are no bundles with positive bias.
863 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
864 BlockFrequency &Cost) {
865 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
867 // Reset interference dependent info.
868 SplitConstraints.resize(UseBlocks.size());
869 BlockFrequency StaticCost = 0;
870 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
871 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
872 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
874 BC.Number = BI.MBB->getNumber();
875 Intf.moveToBlock(BC.Number);
876 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
877 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
878 BC.ChangesValue = BI.FirstDef.isValid();
880 if (!Intf.hasInterference())
883 // Number of spill code instructions to insert.
886 // Interference for the live-in value.
888 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
889 BC.Entry = SpillPlacement::MustSpill, ++Ins;
890 else if (Intf.first() < BI.FirstInstr)
891 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
892 else if (Intf.first() < BI.LastInstr)
896 // Interference for the live-out value.
898 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
899 BC.Exit = SpillPlacement::MustSpill, ++Ins;
900 else if (Intf.last() > BI.LastInstr)
901 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
902 else if (Intf.last() > BI.FirstInstr)
906 // Accumulate the total frequency of inserted spill code.
908 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
912 // Add constraints for use-blocks. Note that these are the only constraints
913 // that may add a positive bias, it is downhill from here.
914 SpillPlacer->addConstraints(SplitConstraints);
915 return SpillPlacer->scanActiveBundles();
919 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
920 /// live-through blocks in Blocks.
921 void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
922 ArrayRef<unsigned> Blocks) {
923 const unsigned GroupSize = 8;
924 SpillPlacement::BlockConstraint BCS[GroupSize];
925 unsigned TBS[GroupSize];
926 unsigned B = 0, T = 0;
928 for (unsigned i = 0; i != Blocks.size(); ++i) {
929 unsigned Number = Blocks[i];
930 Intf.moveToBlock(Number);
932 if (!Intf.hasInterference()) {
933 assert(T < GroupSize && "Array overflow");
935 if (++T == GroupSize) {
936 SpillPlacer->addLinks(makeArrayRef(TBS, T));
942 assert(B < GroupSize && "Array overflow");
943 BCS[B].Number = Number;
945 // Interference for the live-in value.
946 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
947 BCS[B].Entry = SpillPlacement::MustSpill;
949 BCS[B].Entry = SpillPlacement::PrefSpill;
951 // Interference for the live-out value.
952 if (Intf.last() >= SA->getLastSplitPoint(Number))
953 BCS[B].Exit = SpillPlacement::MustSpill;
955 BCS[B].Exit = SpillPlacement::PrefSpill;
957 if (++B == GroupSize) {
958 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
959 SpillPlacer->addConstraints(Array);
964 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
965 SpillPlacer->addConstraints(Array);
966 SpillPlacer->addLinks(makeArrayRef(TBS, T));
969 void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
970 // Keep track of through blocks that have not been added to SpillPlacer.
971 BitVector Todo = SA->getThroughBlocks();
972 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
973 unsigned AddedTo = 0;
975 unsigned Visited = 0;
979 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
980 // Find new through blocks in the periphery of PrefRegBundles.
981 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
982 unsigned Bundle = NewBundles[i];
983 // Look at all blocks connected to Bundle in the full graph.
984 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
985 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
988 if (!Todo.test(Block))
991 // This is a new through block. Add it to SpillPlacer later.
992 ActiveBlocks.push_back(Block);
998 // Any new blocks to add?
999 if (ActiveBlocks.size() == AddedTo)
1002 // Compute through constraints from the interference, or assume that all
1003 // through blocks prefer spilling when forming compact regions.
1004 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
1006 addThroughConstraints(Cand.Intf, NewBlocks);
1008 // Provide a strong negative bias on through blocks to prevent unwanted
1009 // liveness on loop backedges.
1010 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
1011 AddedTo = ActiveBlocks.size();
1013 // Perhaps iterating can enable more bundles?
1014 SpillPlacer->iterate();
1016 DEBUG(dbgs() << ", v=" << Visited);
1019 /// calcCompactRegion - Compute the set of edge bundles that should be live
1020 /// when splitting the current live range into compact regions. Compact
1021 /// regions can be computed without looking at interference. They are the
1022 /// regions formed by removing all the live-through blocks from the live range.
1024 /// Returns false if the current live range is already compact, or if the
1025 /// compact regions would form single block regions anyway.
1026 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
1027 // Without any through blocks, the live range is already compact.
1028 if (!SA->getNumThroughBlocks())
1031 // Compact regions don't correspond to any physreg.
1032 Cand.reset(IntfCache, 0);
1034 DEBUG(dbgs() << "Compact region bundles");
1036 // Use the spill placer to determine the live bundles. GrowRegion pretends
1037 // that all the through blocks have interference when PhysReg is unset.
1038 SpillPlacer->prepare(Cand.LiveBundles);
1040 // The static split cost will be zero since Cand.Intf reports no interference.
1041 BlockFrequency Cost;
1042 if (!addSplitConstraints(Cand.Intf, Cost)) {
1043 DEBUG(dbgs() << ", none.\n");
1048 SpillPlacer->finish();
1050 if (!Cand.LiveBundles.any()) {
1051 DEBUG(dbgs() << ", none.\n");
1056 for (int i = Cand.LiveBundles.find_first(); i>=0;
1057 i = Cand.LiveBundles.find_next(i))
1058 dbgs() << " EB#" << i;
1064 /// calcSpillCost - Compute how expensive it would be to split the live range in
1065 /// SA around all use blocks instead of forming bundle regions.
1066 BlockFrequency RAGreedy::calcSpillCost() {
1067 BlockFrequency Cost = 0;
1068 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1069 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1070 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1071 unsigned Number = BI.MBB->getNumber();
1072 // We normally only need one spill instruction - a load or a store.
1073 Cost += SpillPlacer->getBlockFrequency(Number);
1075 // Unless the value is redefined in the block.
1076 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
1077 Cost += SpillPlacer->getBlockFrequency(Number);
1082 /// calcGlobalSplitCost - Return the global split cost of following the split
1083 /// pattern in LiveBundles. This cost should be added to the local cost of the
1084 /// interference pattern in SplitConstraints.
1086 BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
1087 BlockFrequency GlobalCost = 0;
1088 const BitVector &LiveBundles = Cand.LiveBundles;
1089 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1090 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1091 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1092 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
1093 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
1094 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
1098 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
1100 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
1102 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1105 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1106 unsigned Number = Cand.ActiveBlocks[i];
1107 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
1108 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
1109 if (!RegIn && !RegOut)
1111 if (RegIn && RegOut) {
1112 // We need double spill code if this block has interference.
1113 Cand.Intf.moveToBlock(Number);
1114 if (Cand.Intf.hasInterference()) {
1115 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1116 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1120 // live-in / stack-out or stack-in live-out.
1121 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1126 /// splitAroundRegion - Split the current live range around the regions
1127 /// determined by BundleCand and GlobalCand.
1129 /// Before calling this function, GlobalCand and BundleCand must be initialized
1130 /// so each bundle is assigned to a valid candidate, or NoCand for the
1131 /// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1132 /// objects must be initialized for the current live range, and intervals
1133 /// created for the used candidates.
1135 /// @param LREdit The LiveRangeEdit object handling the current split.
1136 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1137 /// must appear in this list.
1138 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1139 ArrayRef<unsigned> UsedCands) {
1140 // These are the intervals created for new global ranges. We may create more
1141 // intervals for local ranges.
1142 const unsigned NumGlobalIntvs = LREdit.size();
1143 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1144 assert(NumGlobalIntvs && "No global intervals configured");
1146 // Isolate even single instructions when dealing with a proper sub-class.
1147 // That guarantees register class inflation for the stack interval because it
1149 unsigned Reg = SA->getParent().reg;
1150 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1152 // First handle all the blocks with uses.
1153 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1154 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1155 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1156 unsigned Number = BI.MBB->getNumber();
1157 unsigned IntvIn = 0, IntvOut = 0;
1158 SlotIndex IntfIn, IntfOut;
1160 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1161 if (CandIn != NoCand) {
1162 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1163 IntvIn = Cand.IntvIdx;
1164 Cand.Intf.moveToBlock(Number);
1165 IntfIn = Cand.Intf.first();
1169 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1170 if (CandOut != NoCand) {
1171 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1172 IntvOut = Cand.IntvIdx;
1173 Cand.Intf.moveToBlock(Number);
1174 IntfOut = Cand.Intf.last();
1178 // Create separate intervals for isolated blocks with multiple uses.
1179 if (!IntvIn && !IntvOut) {
1180 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
1181 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1182 SE->splitSingleBlock(BI);
1186 if (IntvIn && IntvOut)
1187 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1189 SE->splitRegInBlock(BI, IntvIn, IntfIn);
1191 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
1194 // Handle live-through blocks. The relevant live-through blocks are stored in
1195 // the ActiveBlocks list with each candidate. We need to filter out
1197 BitVector Todo = SA->getThroughBlocks();
1198 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1199 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1200 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1201 unsigned Number = Blocks[i];
1202 if (!Todo.test(Number))
1206 unsigned IntvIn = 0, IntvOut = 0;
1207 SlotIndex IntfIn, IntfOut;
1209 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1210 if (CandIn != NoCand) {
1211 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1212 IntvIn = Cand.IntvIdx;
1213 Cand.Intf.moveToBlock(Number);
1214 IntfIn = Cand.Intf.first();
1217 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1218 if (CandOut != NoCand) {
1219 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1220 IntvOut = Cand.IntvIdx;
1221 Cand.Intf.moveToBlock(Number);
1222 IntfOut = Cand.Intf.last();
1224 if (!IntvIn && !IntvOut)
1226 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1232 SmallVector<unsigned, 8> IntvMap;
1233 SE->finish(&IntvMap);
1234 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
1236 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1237 unsigned OrigBlocks = SA->getNumLiveBlocks();
1239 // Sort out the new intervals created by splitting. We get four kinds:
1240 // - Remainder intervals should not be split again.
1241 // - Candidate intervals can be assigned to Cand.PhysReg.
1242 // - Block-local splits are candidates for local splitting.
1243 // - DCE leftovers should go back on the queue.
1244 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1245 LiveInterval &Reg = LIS->getInterval(LREdit.get(i));
1247 // Ignore old intervals from DCE.
1248 if (getStage(Reg) != RS_New)
1251 // Remainder interval. Don't try splitting again, spill if it doesn't
1253 if (IntvMap[i] == 0) {
1254 setStage(Reg, RS_Spill);
1258 // Global intervals. Allow repeated splitting as long as the number of live
1259 // blocks is strictly decreasing.
1260 if (IntvMap[i] < NumGlobalIntvs) {
1261 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1262 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1263 << " blocks as original.\n");
1264 // Don't allow repeated splitting as a safe guard against looping.
1265 setStage(Reg, RS_Split2);
1270 // Other intervals are treated as new. This includes local intervals created
1271 // for blocks with multiple uses, and anything created by DCE.
1275 MF->verify(this, "After splitting live range around region");
1278 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1279 SmallVectorImpl<unsigned> &NewVRegs) {
1280 unsigned NumCands = 0;
1281 BlockFrequency BestCost;
1283 // Check if we can split this live range around a compact region.
1284 bool HasCompact = calcCompactRegion(GlobalCand.front());
1286 // Yes, keep GlobalCand[0] as the compact region candidate.
1288 BestCost = BlockFrequency::getMaxFrequency();
1290 // No benefit from the compact region, our fallback will be per-block
1291 // splitting. Make sure we find a solution that is cheaper than spilling.
1292 BestCost = calcSpillCost();
1293 DEBUG(dbgs() << "Cost of isolating all blocks = ";
1294 MBFI->printBlockFreq(dbgs(), BestCost) << '\n');
1298 calculateRegionSplitCost(VirtReg, Order, BestCost, NumCands,
1299 false/*IgnoreCSR*/);
1301 // No solutions found, fall back to single block splitting.
1302 if (!HasCompact && BestCand == NoCand)
1305 return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
1308 unsigned RAGreedy::calculateRegionSplitCost(LiveInterval &VirtReg,
1309 AllocationOrder &Order,
1310 BlockFrequency &BestCost,
1313 unsigned BestCand = NoCand;
1315 while (unsigned PhysReg = Order.next()) {
1316 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
1317 if (IgnoreCSR && !MRI->isPhysRegUsed(CSR))
1320 // Discard bad candidates before we run out of interference cache cursors.
1321 // This will only affect register classes with a lot of registers (>32).
1322 if (NumCands == IntfCache.getMaxCursors()) {
1323 unsigned WorstCount = ~0u;
1325 for (unsigned i = 0; i != NumCands; ++i) {
1326 if (i == BestCand || !GlobalCand[i].PhysReg)
1328 unsigned Count = GlobalCand[i].LiveBundles.count();
1329 if (Count < WorstCount)
1330 Worst = i, WorstCount = Count;
1333 GlobalCand[Worst] = GlobalCand[NumCands];
1334 if (BestCand == NumCands)
1338 if (GlobalCand.size() <= NumCands)
1339 GlobalCand.resize(NumCands+1);
1340 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1341 Cand.reset(IntfCache, PhysReg);
1343 SpillPlacer->prepare(Cand.LiveBundles);
1344 BlockFrequency Cost;
1345 if (!addSplitConstraints(Cand.Intf, Cost)) {
1346 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
1349 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = ";
1350 MBFI->printBlockFreq(dbgs(), Cost));
1351 if (Cost >= BestCost) {
1353 if (BestCand == NoCand)
1354 dbgs() << " worse than no bundles\n";
1356 dbgs() << " worse than "
1357 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1363 SpillPlacer->finish();
1365 // No live bundles, defer to splitSingleBlocks().
1366 if (!Cand.LiveBundles.any()) {
1367 DEBUG(dbgs() << " no bundles.\n");
1371 Cost += calcGlobalSplitCost(Cand);
1373 dbgs() << ", total = "; MBFI->printBlockFreq(dbgs(), Cost)
1375 for (int i = Cand.LiveBundles.find_first(); i>=0;
1376 i = Cand.LiveBundles.find_next(i))
1377 dbgs() << " EB#" << i;
1380 if (Cost < BestCost) {
1381 BestCand = NumCands;
1389 unsigned RAGreedy::doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
1391 SmallVectorImpl<unsigned> &NewVRegs) {
1392 SmallVector<unsigned, 8> UsedCands;
1393 // Prepare split editor.
1394 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1395 SE->reset(LREdit, SplitSpillMode);
1397 // Assign all edge bundles to the preferred candidate, or NoCand.
1398 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1400 // Assign bundles for the best candidate region.
1401 if (BestCand != NoCand) {
1402 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1403 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1404 UsedCands.push_back(BestCand);
1405 Cand.IntvIdx = SE->openIntv();
1406 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1407 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
1412 // Assign bundles for the compact region.
1414 GlobalSplitCandidate &Cand = GlobalCand.front();
1415 assert(!Cand.PhysReg && "Compact region has no physreg");
1416 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1417 UsedCands.push_back(0);
1418 Cand.IntvIdx = SE->openIntv();
1419 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1420 << Cand.IntvIdx << ".\n");
1425 splitAroundRegion(LREdit, UsedCands);
1430 //===----------------------------------------------------------------------===//
1431 // Per-Block Splitting
1432 //===----------------------------------------------------------------------===//
1434 /// tryBlockSplit - Split a global live range around every block with uses. This
1435 /// creates a lot of local live ranges, that will be split by tryLocalSplit if
1436 /// they don't allocate.
1437 unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1438 SmallVectorImpl<unsigned> &NewVRegs) {
1439 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1440 unsigned Reg = VirtReg.reg;
1441 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1442 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1443 SE->reset(LREdit, SplitSpillMode);
1444 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1445 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1446 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1447 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1448 SE->splitSingleBlock(BI);
1450 // No blocks were split.
1454 // We did split for some blocks.
1455 SmallVector<unsigned, 8> IntvMap;
1456 SE->finish(&IntvMap);
1458 // Tell LiveDebugVariables about the new ranges.
1459 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
1461 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1463 // Sort out the new intervals created by splitting. The remainder interval
1464 // goes straight to spilling, the new local ranges get to stay RS_New.
1465 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1466 LiveInterval &LI = LIS->getInterval(LREdit.get(i));
1467 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1468 setStage(LI, RS_Spill);
1472 MF->verify(this, "After splitting live range around basic blocks");
1477 //===----------------------------------------------------------------------===//
1478 // Per-Instruction Splitting
1479 //===----------------------------------------------------------------------===//
1481 /// Get the number of allocatable registers that match the constraints of \p Reg
1482 /// on \p MI and that are also in \p SuperRC.
1483 static unsigned getNumAllocatableRegsForConstraints(
1484 const MachineInstr *MI, unsigned Reg, const TargetRegisterClass *SuperRC,
1485 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1486 const RegisterClassInfo &RCI) {
1487 assert(SuperRC && "Invalid register class");
1489 const TargetRegisterClass *ConstrainedRC =
1490 MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI,
1491 /* ExploreBundle */ true);
1494 return RCI.getNumAllocatableRegs(ConstrainedRC);
1497 /// tryInstructionSplit - Split a live range around individual instructions.
1498 /// This is normally not worthwhile since the spiller is doing essentially the
1499 /// same thing. However, when the live range is in a constrained register
1500 /// class, it may help to insert copies such that parts of the live range can
1501 /// be moved to a larger register class.
1503 /// This is similar to spilling to a larger register class.
1505 RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1506 SmallVectorImpl<unsigned> &NewVRegs) {
1507 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
1508 // There is no point to this if there are no larger sub-classes.
1509 if (!RegClassInfo.isProperSubClass(CurRC))
1512 // Always enable split spill mode, since we're effectively spilling to a
1514 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1515 SE->reset(LREdit, SplitEditor::SM_Size);
1517 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1518 if (Uses.size() <= 1)
1521 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1523 const TargetRegisterClass *SuperRC = TRI->getLargestLegalSuperClass(CurRC);
1524 unsigned SuperRCNumAllocatableRegs = RCI.getNumAllocatableRegs(SuperRC);
1525 // Split around every non-copy instruction if this split will relax
1526 // the constraints on the virtual register.
1527 // Otherwise, splitting just inserts uncoalescable copies that do not help
1529 for (unsigned i = 0; i != Uses.size(); ++i) {
1530 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1531 if (MI->isFullCopy() ||
1532 SuperRCNumAllocatableRegs ==
1533 getNumAllocatableRegsForConstraints(MI, VirtReg.reg, SuperRC, TII,
1535 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1539 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1540 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1541 SE->useIntv(SegStart, SegStop);
1544 if (LREdit.empty()) {
1545 DEBUG(dbgs() << "All uses were copies.\n");
1549 SmallVector<unsigned, 8> IntvMap;
1550 SE->finish(&IntvMap);
1551 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
1552 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1554 // Assign all new registers to RS_Spill. This was the last chance.
1555 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1560 //===----------------------------------------------------------------------===//
1562 //===----------------------------------------------------------------------===//
1565 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1566 /// in order to use PhysReg between two entries in SA->UseSlots.
1568 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1570 void RAGreedy::calcGapWeights(unsigned PhysReg,
1571 SmallVectorImpl<float> &GapWeight) {
1572 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1573 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1574 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1575 const unsigned NumGaps = Uses.size()-1;
1577 // Start and end points for the interference check.
1578 SlotIndex StartIdx =
1579 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1581 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
1583 GapWeight.assign(NumGaps, 0.0f);
1585 // Add interference from each overlapping register.
1586 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1587 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1588 .checkInterference())
1591 // We know that VirtReg is a continuous interval from FirstInstr to
1592 // LastInstr, so we don't need InterferenceQuery.
1594 // Interference that overlaps an instruction is counted in both gaps
1595 // surrounding the instruction. The exception is interference before
1596 // StartIdx and after StopIdx.
1598 LiveIntervalUnion::SegmentIter IntI =
1599 Matrix->getLiveUnions()[*Units] .find(StartIdx);
1600 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1601 // Skip the gaps before IntI.
1602 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1603 if (++Gap == NumGaps)
1608 // Update the gaps covered by IntI.
1609 const float weight = IntI.value()->weight;
1610 for (; Gap != NumGaps; ++Gap) {
1611 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1612 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1620 // Add fixed interference.
1621 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1622 const LiveRange &LR = LIS->getRegUnit(*Units);
1623 LiveRange::const_iterator I = LR.find(StartIdx);
1624 LiveRange::const_iterator E = LR.end();
1626 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1627 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1628 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1629 if (++Gap == NumGaps)
1634 for (; Gap != NumGaps; ++Gap) {
1635 GapWeight[Gap] = llvm::huge_valf;
1636 if (Uses[Gap+1].getBaseIndex() >= I->end)
1645 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1648 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1649 SmallVectorImpl<unsigned> &NewVRegs) {
1650 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1651 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1653 // Note that it is possible to have an interval that is live-in or live-out
1654 // while only covering a single block - A phi-def can use undef values from
1655 // predecessors, and the block could be a single-block loop.
1656 // We don't bother doing anything clever about such a case, we simply assume
1657 // that the interval is continuous from FirstInstr to LastInstr. We should
1658 // make sure that we don't do anything illegal to such an interval, though.
1660 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1661 if (Uses.size() <= 2)
1663 const unsigned NumGaps = Uses.size()-1;
1666 dbgs() << "tryLocalSplit: ";
1667 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1668 dbgs() << ' ' << Uses[i];
1672 // If VirtReg is live across any register mask operands, compute a list of
1673 // gaps with register masks.
1674 SmallVector<unsigned, 8> RegMaskGaps;
1675 if (Matrix->checkRegMaskInterference(VirtReg)) {
1676 // Get regmask slots for the whole block.
1677 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
1678 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
1679 // Constrain to VirtReg's live range.
1680 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1681 Uses.front().getRegSlot()) - RMS.begin();
1682 unsigned re = RMS.size();
1683 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
1684 // Look for Uses[i] <= RMS <= Uses[i+1].
1685 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1686 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
1688 // Skip a regmask on the same instruction as the last use. It doesn't
1689 // overlap the live range.
1690 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1692 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
1693 RegMaskGaps.push_back(i);
1694 // Advance ri to the next gap. A regmask on one of the uses counts in
1696 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1699 DEBUG(dbgs() << '\n');
1702 // Since we allow local split results to be split again, there is a risk of
1703 // creating infinite loops. It is tempting to require that the new live
1704 // ranges have less instructions than the original. That would guarantee
1705 // convergence, but it is too strict. A live range with 3 instructions can be
1706 // split 2+3 (including the COPY), and we want to allow that.
1708 // Instead we use these rules:
1710 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
1711 // noop split, of course).
1712 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
1713 // the new ranges must have fewer instructions than before the split.
1714 // 3. New ranges with the same number of instructions are marked RS_Split2,
1715 // smaller ranges are marked RS_New.
1717 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1718 // excessive splitting and infinite loops.
1720 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
1722 // Best split candidate.
1723 unsigned BestBefore = NumGaps;
1724 unsigned BestAfter = 0;
1727 const float blockFreq =
1728 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
1729 (1.0f / MBFI->getEntryFreq());
1730 SmallVector<float, 8> GapWeight;
1733 while (unsigned PhysReg = Order.next()) {
1734 // Keep track of the largest spill weight that would need to be evicted in
1735 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1736 calcGapWeights(PhysReg, GapWeight);
1738 // Remove any gaps with regmask clobbers.
1739 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
1740 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1741 GapWeight[RegMaskGaps[i]] = llvm::huge_valf;
1743 // Try to find the best sequence of gaps to close.
1744 // The new spill weight must be larger than any gap interference.
1746 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1747 unsigned SplitBefore = 0, SplitAfter = 1;
1749 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1750 // It is the spill weight that needs to be evicted.
1751 float MaxGap = GapWeight[0];
1754 // Live before/after split?
1755 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1756 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1758 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1759 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1760 << " i=" << MaxGap);
1762 // Stop before the interval gets so big we wouldn't be making progress.
1763 if (!LiveBefore && !LiveAfter) {
1764 DEBUG(dbgs() << " all\n");
1767 // Should the interval be extended or shrunk?
1770 // How many gaps would the new range have?
1771 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1773 // Legally, without causing looping?
1774 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1776 if (Legal && MaxGap < llvm::huge_valf) {
1777 // Estimate the new spill weight. Each instruction reads or writes the
1778 // register. Conservatively assume there are no read-modify-write
1781 // Try to guess the size of the new interval.
1782 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1783 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1784 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
1785 // Would this split be possible to allocate?
1786 // Never allocate all gaps, we wouldn't be making progress.
1787 DEBUG(dbgs() << " w=" << EstWeight);
1788 if (EstWeight * Hysteresis >= MaxGap) {
1790 float Diff = EstWeight - MaxGap;
1791 if (Diff > BestDiff) {
1792 DEBUG(dbgs() << " (best)");
1793 BestDiff = Hysteresis * Diff;
1794 BestBefore = SplitBefore;
1795 BestAfter = SplitAfter;
1802 if (++SplitBefore < SplitAfter) {
1803 DEBUG(dbgs() << " shrink\n");
1804 // Recompute the max when necessary.
1805 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1806 MaxGap = GapWeight[SplitBefore];
1807 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1808 MaxGap = std::max(MaxGap, GapWeight[i]);
1815 // Try to extend the interval.
1816 if (SplitAfter >= NumGaps) {
1817 DEBUG(dbgs() << " end\n");
1821 DEBUG(dbgs() << " extend\n");
1822 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
1826 // Didn't find any candidates?
1827 if (BestBefore == NumGaps)
1830 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1831 << '-' << Uses[BestAfter] << ", " << BestDiff
1832 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1834 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1838 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1839 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1840 SE->useIntv(SegStart, SegStop);
1841 SmallVector<unsigned, 8> IntvMap;
1842 SE->finish(&IntvMap);
1843 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
1845 // If the new range has the same number of instructions as before, mark it as
1846 // RS_Split2 so the next split will be forced to make progress. Otherwise,
1847 // leave the new intervals as RS_New so they can compete.
1848 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1849 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1850 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1851 if (NewGaps >= NumGaps) {
1852 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1853 assert(!ProgressRequired && "Didn't make progress when it was required.");
1854 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1855 if (IntvMap[i] == 1) {
1856 setStage(LIS->getInterval(LREdit.get(i)), RS_Split2);
1857 DEBUG(dbgs() << PrintReg(LREdit.get(i)));
1859 DEBUG(dbgs() << '\n');
1866 //===----------------------------------------------------------------------===//
1867 // Live Range Splitting
1868 //===----------------------------------------------------------------------===//
1870 /// trySplit - Try to split VirtReg or one of its interferences, making it
1872 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1873 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1874 SmallVectorImpl<unsigned>&NewVRegs) {
1875 // Ranges must be Split2 or less.
1876 if (getStage(VirtReg) >= RS_Spill)
1879 // Local intervals are handled separately.
1880 if (LIS->intervalIsInOneMBB(VirtReg)) {
1881 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
1882 SA->analyze(&VirtReg);
1883 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1884 if (PhysReg || !NewVRegs.empty())
1886 return tryInstructionSplit(VirtReg, Order, NewVRegs);
1889 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
1891 SA->analyze(&VirtReg);
1893 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1894 // coalescer. That may cause the range to become allocatable which means that
1895 // tryRegionSplit won't be making progress. This check should be replaced with
1896 // an assertion when the coalescer is fixed.
1897 if (SA->didRepairRange()) {
1898 // VirtReg has changed, so all cached queries are invalid.
1899 Matrix->invalidateVirtRegs();
1900 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1904 // First try to split around a region spanning multiple blocks. RS_Split2
1905 // ranges already made dubious progress with region splitting, so they go
1906 // straight to single block splitting.
1907 if (getStage(VirtReg) < RS_Split2) {
1908 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1909 if (PhysReg || !NewVRegs.empty())
1913 // Then isolate blocks.
1914 return tryBlockSplit(VirtReg, Order, NewVRegs);
1917 //===----------------------------------------------------------------------===//
1918 // Last Chance Recoloring
1919 //===----------------------------------------------------------------------===//
1921 /// mayRecolorAllInterferences - Check if the virtual registers that
1922 /// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be
1923 /// recolored to free \p PhysReg.
1924 /// When true is returned, \p RecoloringCandidates has been augmented with all
1925 /// the live intervals that need to be recolored in order to free \p PhysReg
1927 /// \p FixedRegisters contains all the virtual registers that cannot be
1930 RAGreedy::mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
1931 SmallLISet &RecoloringCandidates,
1932 const SmallVirtRegSet &FixedRegisters) {
1933 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
1935 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1936 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
1937 // If there is LastChanceRecoloringMaxInterference or more interferences,
1938 // chances are one would not be recolorable.
1939 if (Q.collectInterferingVRegs(LastChanceRecoloringMaxInterference) >=
1940 LastChanceRecoloringMaxInterference && !ExhaustiveSearch) {
1941 DEBUG(dbgs() << "Early abort: too many interferences.\n");
1942 CutOffInfo |= CO_Interf;
1945 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
1946 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
1947 // If Intf is done and sit on the same register class as VirtReg,
1948 // it would not be recolorable as it is in the same state as VirtReg.
1949 if ((getStage(*Intf) == RS_Done &&
1950 MRI->getRegClass(Intf->reg) == CurRC) ||
1951 FixedRegisters.count(Intf->reg)) {
1952 DEBUG(dbgs() << "Early abort: the inteference is not recolorable.\n");
1955 RecoloringCandidates.insert(Intf);
1961 /// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring
1962 /// its interferences.
1963 /// Last chance recoloring chooses a color for \p VirtReg and recolors every
1964 /// virtual register that was using it. The recoloring process may recursively
1965 /// use the last chance recoloring. Therefore, when a virtual register has been
1966 /// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot
1967 /// be last-chance-recolored again during this recoloring "session".
1970 /// vA can use {R1, R2 }
1971 /// vB can use { R2, R3}
1972 /// vC can use {R1 }
1973 /// Where vA, vB, and vC cannot be split anymore (they are reloads for
1974 /// instance) and they all interfere.
1976 /// vA is assigned R1
1977 /// vB is assigned R2
1978 /// vC tries to evict vA but vA is already done.
1979 /// Regular register allocation fails.
1981 /// Last chance recoloring kicks in:
1982 /// vC does as if vA was evicted => vC uses R1.
1983 /// vC is marked as fixed.
1984 /// vA needs to find a color.
1985 /// None are available.
1986 /// vA cannot evict vC: vC is a fixed virtual register now.
1987 /// vA does as if vB was evicted => vA uses R2.
1988 /// vB needs to find a color.
1989 /// R3 is available.
1990 /// Recoloring => vC = R1, vA = R2, vB = R3
1992 /// \p Order defines the preferred allocation order for \p VirtReg.
1993 /// \p NewRegs will contain any new virtual register that have been created
1994 /// (split, spill) during the process and that must be assigned.
1995 /// \p FixedRegisters contains all the virtual registers that cannot be
1997 /// \p Depth gives the current depth of the last chance recoloring.
1998 /// \return a physical register that can be used for VirtReg or ~0u if none
2000 unsigned RAGreedy::tryLastChanceRecoloring(LiveInterval &VirtReg,
2001 AllocationOrder &Order,
2002 SmallVectorImpl<unsigned> &NewVRegs,
2003 SmallVirtRegSet &FixedRegisters,
2005 DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n');
2006 // Ranges must be Done.
2007 assert((getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) &&
2008 "Last chance recoloring should really be last chance");
2009 // Set the max depth to LastChanceRecoloringMaxDepth.
2010 // We may want to reconsider that if we end up with a too large search space
2011 // for target with hundreds of registers.
2012 // Indeed, in that case we may want to cut the search space earlier.
2013 if (Depth >= LastChanceRecoloringMaxDepth && !ExhaustiveSearch) {
2014 DEBUG(dbgs() << "Abort because max depth has been reached.\n");
2015 CutOffInfo |= CO_Depth;
2019 // Set of Live intervals that will need to be recolored.
2020 SmallLISet RecoloringCandidates;
2021 // Record the original mapping virtual register to physical register in case
2022 // the recoloring fails.
2023 DenseMap<unsigned, unsigned> VirtRegToPhysReg;
2024 // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in
2025 // this recoloring "session".
2026 FixedRegisters.insert(VirtReg.reg);
2029 while (unsigned PhysReg = Order.next()) {
2030 DEBUG(dbgs() << "Try to assign: " << VirtReg << " to "
2031 << PrintReg(PhysReg, TRI) << '\n');
2032 RecoloringCandidates.clear();
2033 VirtRegToPhysReg.clear();
2035 // It is only possible to recolor virtual register interference.
2036 if (Matrix->checkInterference(VirtReg, PhysReg) >
2037 LiveRegMatrix::IK_VirtReg) {
2038 DEBUG(dbgs() << "Some inteferences are not with virtual registers.\n");
2043 // Early give up on this PhysReg if it is obvious we cannot recolor all
2044 // the interferences.
2045 if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
2047 DEBUG(dbgs() << "Some inteferences cannot be recolored.\n");
2051 // RecoloringCandidates contains all the virtual registers that interfer
2052 // with VirtReg on PhysReg (or one of its aliases).
2053 // Enqueue them for recoloring and perform the actual recoloring.
2054 PQueue RecoloringQueue;
2055 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2056 EndIt = RecoloringCandidates.end();
2057 It != EndIt; ++It) {
2058 unsigned ItVirtReg = (*It)->reg;
2059 enqueue(RecoloringQueue, *It);
2060 assert(VRM->hasPhys(ItVirtReg) &&
2061 "Interferences are supposed to be with allocated vairables");
2063 // Record the current allocation.
2064 VirtRegToPhysReg[ItVirtReg] = VRM->getPhys(ItVirtReg);
2065 // unset the related struct.
2066 Matrix->unassign(**It);
2069 // Do as if VirtReg was assigned to PhysReg so that the underlying
2070 // recoloring has the right information about the interferes and
2071 // available colors.
2072 Matrix->assign(VirtReg, PhysReg);
2074 // Save the current recoloring state.
2075 // If we cannot recolor all the interferences, we will have to start again
2076 // at this point for the next physical register.
2077 SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
2078 if (tryRecoloringCandidates(RecoloringQueue, NewVRegs, FixedRegisters,
2080 // Do not mess up with the global assignment process.
2081 // I.e., VirtReg must be unassigned.
2082 Matrix->unassign(VirtReg);
2086 DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to "
2087 << PrintReg(PhysReg, TRI) << '\n');
2089 // The recoloring attempt failed, undo the changes.
2090 FixedRegisters = SaveFixedRegisters;
2091 Matrix->unassign(VirtReg);
2093 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2094 EndIt = RecoloringCandidates.end();
2095 It != EndIt; ++It) {
2096 unsigned ItVirtReg = (*It)->reg;
2097 if (VRM->hasPhys(ItVirtReg))
2098 Matrix->unassign(**It);
2099 Matrix->assign(**It, VirtRegToPhysReg[ItVirtReg]);
2103 // Last chance recoloring did not worked either, give up.
2107 /// tryRecoloringCandidates - Try to assign a new color to every register
2108 /// in \RecoloringQueue.
2109 /// \p NewRegs will contain any new virtual register created during the
2110 /// recoloring process.
2111 /// \p FixedRegisters[in/out] contains all the registers that have been
2113 /// \return true if all virtual registers in RecoloringQueue were successfully
2114 /// recolored, false otherwise.
2115 bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
2116 SmallVectorImpl<unsigned> &NewVRegs,
2117 SmallVirtRegSet &FixedRegisters,
2119 while (!RecoloringQueue.empty()) {
2120 LiveInterval *LI = dequeue(RecoloringQueue);
2121 DEBUG(dbgs() << "Try to recolor: " << *LI << '\n');
2123 PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters, Depth + 1);
2124 if (PhysReg == ~0u || !PhysReg)
2126 DEBUG(dbgs() << "Recoloring of " << *LI
2127 << " succeeded with: " << PrintReg(PhysReg, TRI) << '\n');
2128 Matrix->assign(*LI, PhysReg);
2129 FixedRegisters.insert(LI->reg);
2134 //===----------------------------------------------------------------------===//
2136 //===----------------------------------------------------------------------===//
2138 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
2139 SmallVectorImpl<unsigned> &NewVRegs) {
2140 CutOffInfo = CO_None;
2141 LLVMContext &Ctx = MF->getFunction()->getContext();
2142 SmallVirtRegSet FixedRegisters;
2143 unsigned Reg = selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters);
2144 if (Reg == ~0U && (CutOffInfo != CO_None)) {
2145 uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf);
2146 if (CutOffEncountered == CO_Depth)
2147 Ctx.emitError("register allocation failed: maximum depth for recoloring "
2148 "reached. Use -fexhaustive-register-search to skip "
2150 else if (CutOffEncountered == CO_Interf)
2151 Ctx.emitError("register allocation failed: maximum interference for "
2152 "recoloring reached. Use -fexhaustive-register-search "
2154 else if (CutOffEncountered == (CO_Depth | CO_Interf))
2155 Ctx.emitError("register allocation failed: maximum interference and "
2156 "depth for recoloring reached. Use "
2157 "-fexhaustive-register-search to skip cutoffs");
2162 /// Using a CSR for the first time has a cost because it causes push|pop
2163 /// to be added to prologue|epilogue. Splitting a cold section of the live
2164 /// range can have lower cost than using the CSR for the first time;
2165 /// Spilling a live range in the cold path can have lower cost than using
2166 /// the CSR for the first time. Returns the physical register if we decide
2167 /// to use the CSR; otherwise return 0.
2168 unsigned RAGreedy::tryAssignCSRFirstTime(LiveInterval &VirtReg,
2169 AllocationOrder &Order,
2171 unsigned &CostPerUseLimit,
2172 SmallVectorImpl<unsigned> &NewVRegs) {
2173 if (getStage(VirtReg) == RS_Spill && VirtReg.isSpillable()) {
2174 // We choose spill over using the CSR for the first time if the spill cost
2175 // is lower than CSRCost.
2176 SA->analyze(&VirtReg);
2177 if (calcSpillCost() >= CSRCost)
2180 // We are going to spill, set CostPerUseLimit to 1 to make sure that
2181 // we will not use a callee-saved register in tryEvict.
2182 CostPerUseLimit = 1;
2185 if (getStage(VirtReg) < RS_Split) {
2186 // We choose pre-splitting over using the CSR for the first time if
2187 // the cost of splitting is lower than CSRCost.
2188 SA->analyze(&VirtReg);
2189 unsigned NumCands = 0;
2190 BlockFrequency BestCost = CSRCost; // Don't modify CSRCost.
2191 unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
2192 NumCands, true /*IgnoreCSR*/);
2193 if (BestCand == NoCand)
2194 // Use the CSR if we can't find a region split below CSRCost.
2197 // Perform the actual pre-splitting.
2198 doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs);
2204 void RAGreedy::initializeCSRCost() {
2205 // We use the larger one out of the command-line option and the value report
2207 CSRCost = BlockFrequency(
2208 std::max((unsigned)CSRFirstTimeCost, TRI->getCSRFirstUseCost()));
2209 if (!CSRCost.getFrequency())
2212 // Raw cost is relative to Entry == 2^14; scale it appropriately.
2213 uint64_t ActualEntry = MBFI->getEntryFreq();
2218 uint64_t FixedEntry = 1 << 14;
2219 if (ActualEntry < FixedEntry)
2220 CSRCost *= BranchProbability(ActualEntry, FixedEntry);
2221 else if (ActualEntry <= UINT32_MAX)
2222 // Invert the fraction and divide.
2223 CSRCost /= BranchProbability(FixedEntry, ActualEntry);
2225 // Can't use BranchProbability in general, since it takes 32-bit numbers.
2226 CSRCost = CSRCost.getFrequency() * (ActualEntry / FixedEntry);
2229 unsigned RAGreedy::selectOrSplitImpl(LiveInterval &VirtReg,
2230 SmallVectorImpl<unsigned> &NewVRegs,
2231 SmallVirtRegSet &FixedRegisters,
2233 unsigned CostPerUseLimit = ~0u;
2234 // First try assigning a free register.
2235 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
2236 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs)) {
2237 // We check other options if we are using a CSR for the first time.
2238 bool CSRFirstUse = false;
2239 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
2240 if (!MRI->isPhysRegUsed(CSR))
2243 // When NewVRegs is not empty, we may have made decisions such as evicting
2244 // a virtual register, go with the earlier decisions and use the physical
2246 if (CSRCost.getFrequency() && CSRFirstUse && NewVRegs.empty()) {
2247 unsigned CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg,
2248 CostPerUseLimit, NewVRegs);
2249 if (CSRReg || !NewVRegs.empty())
2250 // Return now if we decide to use a CSR or create new vregs due to
2257 LiveRangeStage Stage = getStage(VirtReg);
2258 DEBUG(dbgs() << StageName[Stage]
2259 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
2261 // Try to evict a less worthy live range, but only for ranges from the primary
2262 // queue. The RS_Split ranges already failed to do this, and they should not
2263 // get a second chance until they have been split.
2264 if (Stage != RS_Split)
2265 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit))
2268 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
2270 // The first time we see a live range, don't try to split or spill.
2271 // Wait until the second time, when all smaller ranges have been allocated.
2272 // This gives a better picture of the interference to split around.
2273 if (Stage < RS_Split) {
2274 setStage(VirtReg, RS_Split);
2275 DEBUG(dbgs() << "wait for second round\n");
2276 NewVRegs.push_back(VirtReg.reg);
2280 // If we couldn't allocate a register from spilling, there is probably some
2281 // invalid inline assembly. The base class wil report it.
2282 if (Stage >= RS_Done || !VirtReg.isSpillable())
2283 return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
2286 // Try splitting VirtReg or interferences.
2287 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
2288 if (PhysReg || !NewVRegs.empty())
2291 // Finally spill VirtReg itself.
2292 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
2293 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
2294 spiller().spill(LRE);
2295 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
2298 MF->verify(this, "After spilling");
2300 // The live virtual register requesting allocation was spilled, so tell
2301 // the caller not to allocate anything during this round.
2305 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
2306 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
2307 << "********** Function: " << mf.getName() << '\n');
2310 TRI = MF->getTarget().getRegisterInfo();
2311 TII = MF->getTarget().getInstrInfo();
2312 RCI.runOnMachineFunction(mf);
2314 MF->verify(this, "Before greedy register allocator");
2316 RegAllocBase::init(getAnalysis<VirtRegMap>(),
2317 getAnalysis<LiveIntervals>(),
2318 getAnalysis<LiveRegMatrix>());
2319 Indexes = &getAnalysis<SlotIndexes>();
2320 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2321 DomTree = &getAnalysis<MachineDominatorTree>();
2322 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
2323 Loops = &getAnalysis<MachineLoopInfo>();
2324 Bundles = &getAnalysis<EdgeBundles>();
2325 SpillPlacer = &getAnalysis<SpillPlacement>();
2326 DebugVars = &getAnalysis<LiveDebugVariables>();
2328 initializeCSRCost();
2330 calculateSpillWeightsAndHints(*LIS, mf, *Loops, *MBFI);
2334 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
2335 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
2336 ExtraRegInfo.clear();
2337 ExtraRegInfo.resize(MRI->getNumVirtRegs());
2339 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
2340 GlobalCand.resize(32); // This will grow as needed.