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 "AllocationOrder.h"
17 #include "InterferenceCache.h"
18 #include "LiveDebugVariables.h"
19 #include "LiveRangeEdit.h"
20 #include "RegAllocBase.h"
22 #include "SpillPlacement.h"
24 #include "VirtRegMap.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Function.h"
28 #include "llvm/PassAnalysisSupport.h"
29 #include "llvm/CodeGen/CalcSpillWeights.h"
30 #include "llvm/CodeGen/EdgeBundles.h"
31 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
32 #include "llvm/CodeGen/LiveStackAnalysis.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/Passes.h"
38 #include "llvm/CodeGen/RegAllocRegistry.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Support/Timer.h"
50 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
51 STATISTIC(NumLocalSplits, "Number of split local live ranges");
52 STATISTIC(NumEvicted, "Number of interferences evicted");
54 /// EnableMachineSched - temporary flag to enable the machine scheduling pass
55 /// until we complete the register allocation pass configuration cleanup.
57 EnableMachineSched("enable-misched",
58 cl::desc("Enable the machine instruction scheduling pass."),
59 cl::init(false), cl::Hidden);
61 static cl::opt<SplitEditor::ComplementSpillMode>
62 SplitSpillMode("split-spill-mode", cl::Hidden,
63 cl::desc("Spill mode for splitting live ranges"),
64 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
65 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
66 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
68 cl::init(SplitEditor::SM_Partition));
70 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
71 createGreedyRegisterAllocator);
74 class RAGreedy : public MachineFunctionPass,
76 private LiveRangeEdit::Delegate {
84 MachineDominatorTree *DomTree;
85 MachineLoopInfo *Loops;
87 SpillPlacement *SpillPlacer;
88 LiveDebugVariables *DebugVars;
91 std::auto_ptr<Spiller> SpillerInstance;
92 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
95 // Live ranges pass through a number of stages as we try to allocate them.
96 // Some of the stages may also create new live ranges:
98 // - Region splitting.
99 // - Per-block splitting.
100 // - Local splitting.
103 // Ranges produced by one of the stages skip the previous stages when they are
104 // dequeued. This improves performance because we can skip interference checks
105 // that are unlikely to give any results. It also guarantees that the live
106 // range splitting algorithm terminates, something that is otherwise hard to
108 enum LiveRangeStage {
109 /// Newly created live range that has never been queued.
112 /// Only attempt assignment and eviction. Then requeue as RS_Split.
115 /// Attempt live range splitting if assignment is impossible.
118 /// Attempt more aggressive live range splitting that is guaranteed to make
119 /// progress. This is used for split products that may not be making
123 /// Live range will be spilled. No more splitting will be attempted.
126 /// There is nothing more we can do to this live range. Abort compilation
127 /// if it can't be assigned.
131 static const char *const StageName[];
133 // RegInfo - Keep additional information about each live range.
135 LiveRangeStage Stage;
137 // Cascade - Eviction loop prevention. See canEvictInterference().
140 RegInfo() : Stage(RS_New), Cascade(0) {}
143 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
145 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
146 return ExtraRegInfo[VirtReg.reg].Stage;
149 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
150 ExtraRegInfo.resize(MRI->getNumVirtRegs());
151 ExtraRegInfo[VirtReg.reg].Stage = Stage;
154 template<typename Iterator>
155 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
156 ExtraRegInfo.resize(MRI->getNumVirtRegs());
157 for (;Begin != End; ++Begin) {
158 unsigned Reg = (*Begin)->reg;
159 if (ExtraRegInfo[Reg].Stage == RS_New)
160 ExtraRegInfo[Reg].Stage = NewStage;
164 /// Cost of evicting interference.
165 struct EvictionCost {
166 unsigned BrokenHints; ///< Total number of broken hints.
167 float MaxWeight; ///< Maximum spill weight evicted.
169 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
171 bool operator<(const EvictionCost &O) const {
172 if (BrokenHints != O.BrokenHints)
173 return BrokenHints < O.BrokenHints;
174 return MaxWeight < O.MaxWeight;
178 // Register mask interference. The current VirtReg is checked for register
179 // mask interference on entry to selectOrSplit(). If there is no
180 // interference, UsableRegs is left empty. If there is interference,
181 // UsableRegs has a bit mask of registers that can be used without register
182 // mask interference.
183 BitVector UsableRegs;
185 /// clobberedByRegMask - Returns true if PhysReg is not directly usable
186 /// because of register mask clobbers.
187 bool clobberedByRegMask(unsigned PhysReg) const {
188 return !UsableRegs.empty() && !UsableRegs.test(PhysReg);
192 std::auto_ptr<SplitAnalysis> SA;
193 std::auto_ptr<SplitEditor> SE;
195 /// Cached per-block interference maps
196 InterferenceCache IntfCache;
198 /// All basic blocks where the current register has uses.
199 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
201 /// Global live range splitting candidate info.
202 struct GlobalSplitCandidate {
203 // Register intended for assignment, or 0.
206 // SplitKit interval index for this candidate.
209 // Interference for PhysReg.
210 InterferenceCache::Cursor Intf;
212 // Bundles where this candidate should be live.
213 BitVector LiveBundles;
214 SmallVector<unsigned, 8> ActiveBlocks;
216 void reset(InterferenceCache &Cache, unsigned Reg) {
219 Intf.setPhysReg(Cache, Reg);
221 ActiveBlocks.clear();
224 // Set B[i] = C for every live bundle where B[i] was NoCand.
225 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
227 for (int i = LiveBundles.find_first(); i >= 0;
228 i = LiveBundles.find_next(i))
229 if (B[i] == NoCand) {
237 /// Candidate info for for each PhysReg in AllocationOrder.
238 /// This vector never shrinks, but grows to the size of the largest register
240 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
242 enum { NoCand = ~0u };
244 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
245 /// NoCand which indicates the stack interval.
246 SmallVector<unsigned, 32> BundleCand;
251 /// Return the pass name.
252 virtual const char* getPassName() const {
253 return "Greedy Register Allocator";
256 /// RAGreedy analysis usage.
257 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
258 virtual void releaseMemory();
259 virtual Spiller &spiller() { return *SpillerInstance; }
260 virtual void enqueue(LiveInterval *LI);
261 virtual LiveInterval *dequeue();
262 virtual unsigned selectOrSplit(LiveInterval&,
263 SmallVectorImpl<LiveInterval*>&);
265 /// Perform register allocation.
266 virtual bool runOnMachineFunction(MachineFunction &mf);
271 bool LRE_CanEraseVirtReg(unsigned);
272 void LRE_WillShrinkVirtReg(unsigned);
273 void LRE_DidCloneVirtReg(unsigned, unsigned);
275 float calcSpillCost();
276 bool addSplitConstraints(InterferenceCache::Cursor, float&);
277 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
278 void growRegion(GlobalSplitCandidate &Cand);
279 float calcGlobalSplitCost(GlobalSplitCandidate&);
280 bool calcCompactRegion(GlobalSplitCandidate&);
281 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
282 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
283 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
284 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
285 void evictInterference(LiveInterval&, unsigned,
286 SmallVectorImpl<LiveInterval*>&);
288 unsigned tryAssign(LiveInterval&, AllocationOrder&,
289 SmallVectorImpl<LiveInterval*>&);
290 unsigned tryEvict(LiveInterval&, AllocationOrder&,
291 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
292 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
293 SmallVectorImpl<LiveInterval*>&);
294 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
295 SmallVectorImpl<LiveInterval*>&);
296 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
297 SmallVectorImpl<LiveInterval*>&);
298 unsigned trySplit(LiveInterval&, AllocationOrder&,
299 SmallVectorImpl<LiveInterval*>&);
301 } // end anonymous namespace
303 char RAGreedy::ID = 0;
306 const char *const RAGreedy::StageName[] = {
316 // Hysteresis to use when comparing floats.
317 // This helps stabilize decisions based on float comparisons.
318 const float Hysteresis = 0.98f;
321 FunctionPass* llvm::createGreedyRegisterAllocator() {
322 return new RAGreedy();
325 RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
326 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
327 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
328 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
329 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
330 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
331 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
332 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
333 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
334 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
335 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
336 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
337 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
338 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
339 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
342 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
343 AU.setPreservesCFG();
344 AU.addRequired<AliasAnalysis>();
345 AU.addPreserved<AliasAnalysis>();
346 AU.addRequired<LiveIntervals>();
347 AU.addRequired<SlotIndexes>();
348 AU.addPreserved<SlotIndexes>();
349 AU.addRequired<LiveDebugVariables>();
350 AU.addPreserved<LiveDebugVariables>();
352 AU.addRequiredID(StrongPHIEliminationID);
353 AU.addRequiredTransitiveID(RegisterCoalescerPassID);
354 if (EnableMachineSched)
355 AU.addRequiredID(MachineSchedulerID);
356 AU.addRequired<CalculateSpillWeights>();
357 AU.addRequired<LiveStacks>();
358 AU.addPreserved<LiveStacks>();
359 AU.addRequired<MachineDominatorTree>();
360 AU.addPreserved<MachineDominatorTree>();
361 AU.addRequired<MachineLoopInfo>();
362 AU.addPreserved<MachineLoopInfo>();
363 AU.addRequired<VirtRegMap>();
364 AU.addPreserved<VirtRegMap>();
365 AU.addRequired<EdgeBundles>();
366 AU.addRequired<SpillPlacement>();
367 MachineFunctionPass::getAnalysisUsage(AU);
371 //===----------------------------------------------------------------------===//
372 // LiveRangeEdit delegate methods
373 //===----------------------------------------------------------------------===//
375 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
376 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
377 unassign(LIS->getInterval(VirtReg), PhysReg);
380 // Unassigned virtreg is probably in the priority queue.
381 // RegAllocBase will erase it after dequeueing.
385 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
386 unsigned PhysReg = VRM->getPhys(VirtReg);
390 // Register is assigned, put it back on the queue for reassignment.
391 LiveInterval &LI = LIS->getInterval(VirtReg);
392 unassign(LI, PhysReg);
396 void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
397 // Cloning a register we haven't even heard about yet? Just ignore it.
398 if (!ExtraRegInfo.inBounds(Old))
401 // LRE may clone a virtual register because dead code elimination causes it to
402 // be split into connected components. The new components are much smaller
403 // than the original, so they should get a new chance at being assigned.
404 // same stage as the parent.
405 ExtraRegInfo[Old].Stage = RS_Assign;
406 ExtraRegInfo.grow(New);
407 ExtraRegInfo[New] = ExtraRegInfo[Old];
410 void RAGreedy::releaseMemory() {
411 SpillerInstance.reset(0);
412 ExtraRegInfo.clear();
414 RegAllocBase::releaseMemory();
417 void RAGreedy::enqueue(LiveInterval *LI) {
418 // Prioritize live ranges by size, assigning larger ranges first.
419 // The queue holds (size, reg) pairs.
420 const unsigned Size = LI->getSize();
421 const unsigned Reg = LI->reg;
422 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
423 "Can only enqueue virtual registers");
426 ExtraRegInfo.grow(Reg);
427 if (ExtraRegInfo[Reg].Stage == RS_New)
428 ExtraRegInfo[Reg].Stage = RS_Assign;
430 if (ExtraRegInfo[Reg].Stage == RS_Split) {
431 // Unsplit ranges that couldn't be allocated immediately are deferred until
432 // everything else has been allocated.
435 // Everything is allocated in long->short order. Long ranges that don't fit
436 // should be spilled (or split) ASAP so they don't create interference.
437 Prio = (1u << 31) + Size;
439 // Boost ranges that have a physical register hint.
440 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
444 Queue.push(std::make_pair(Prio, Reg));
447 LiveInterval *RAGreedy::dequeue() {
450 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
456 //===----------------------------------------------------------------------===//
458 //===----------------------------------------------------------------------===//
460 /// tryAssign - Try to assign VirtReg to an available register.
461 unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
462 AllocationOrder &Order,
463 SmallVectorImpl<LiveInterval*> &NewVRegs) {
466 while ((PhysReg = Order.next())) {
467 if (clobberedByRegMask(PhysReg))
469 if (!checkPhysRegInterference(VirtReg, PhysReg))
472 if (!PhysReg || Order.isHint(PhysReg))
475 // PhysReg is available, but there may be a better choice.
477 // If we missed a simple hint, try to cheaply evict interference from the
478 // preferred register.
479 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
480 if (Order.isHint(Hint) && !clobberedByRegMask(Hint)) {
481 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
482 EvictionCost MaxCost(1);
483 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
484 evictInterference(VirtReg, Hint, NewVRegs);
489 // Try to evict interference from a cheaper alternative.
490 unsigned Cost = TRI->getCostPerUse(PhysReg);
492 // Most registers have 0 additional cost.
496 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
498 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
499 return CheapReg ? CheapReg : PhysReg;
503 //===----------------------------------------------------------------------===//
504 // Interference eviction
505 //===----------------------------------------------------------------------===//
507 /// shouldEvict - determine if A should evict the assigned live range B. The
508 /// eviction policy defined by this function together with the allocation order
509 /// defined by enqueue() decides which registers ultimately end up being split
512 /// Cascade numbers are used to prevent infinite loops if this function is a
515 /// @param A The live range to be assigned.
516 /// @param IsHint True when A is about to be assigned to its preferred
518 /// @param B The live range to be evicted.
519 /// @param BreaksHint True when B is already assigned to its preferred register.
520 bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
521 LiveInterval &B, bool BreaksHint) {
522 bool CanSplit = getStage(B) < RS_Spill;
524 // Be fairly aggressive about following hints as long as the evictee can be
526 if (CanSplit && IsHint && !BreaksHint)
529 return A.weight > B.weight;
532 /// canEvictInterference - Return true if all interferences between VirtReg and
533 /// PhysReg can be evicted. When OnlyCheap is set, don't do anything
535 /// @param VirtReg Live range that is about to be assigned.
536 /// @param PhysReg Desired register for assignment.
537 /// @prarm IsHint True when PhysReg is VirtReg's preferred register.
538 /// @param MaxCost Only look for cheaper candidates and update with new cost
539 /// when returning true.
540 /// @returns True when interference can be evicted cheaper than MaxCost.
541 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
542 bool IsHint, EvictionCost &MaxCost) {
543 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
544 // involved in an eviction before. If a cascade number was assigned, deny
545 // evicting anything with the same or a newer cascade number. This prevents
546 // infinite eviction loops.
548 // This works out so a register without a cascade number is allowed to evict
549 // anything, and it can be evicted by anything.
550 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
552 Cascade = NextCascade;
555 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
556 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
557 // If there is 10 or more interferences, chances are one is heavier.
558 if (Q.collectInterferingVRegs(10) >= 10)
561 // Check if any interfering live range is heavier than MaxWeight.
562 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
563 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
564 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
566 // Never evict spill products. They cannot split or spill.
567 if (getStage(*Intf) == RS_Done)
569 // Once a live range becomes small enough, it is urgent that we find a
570 // register for it. This is indicated by an infinite spill weight. These
571 // urgent live ranges get to evict almost anything.
572 bool Urgent = !VirtReg.isSpillable() && Intf->isSpillable();
573 // Only evict older cascades or live ranges without a cascade.
574 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
575 if (Cascade <= IntfCascade) {
578 // We permit breaking cascades for urgent evictions. It should be the
579 // last resort, though, so make it really expensive.
580 Cost.BrokenHints += 10;
582 // Would this break a satisfied hint?
583 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
584 // Update eviction cost.
585 Cost.BrokenHints += BreaksHint;
586 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
587 // Abort if this would be too expensive.
588 if (!(Cost < MaxCost))
590 // Finally, apply the eviction policy for non-urgent evictions.
591 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
599 /// evictInterference - Evict any interferring registers that prevent VirtReg
600 /// from being assigned to Physreg. This assumes that canEvictInterference
602 void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
603 SmallVectorImpl<LiveInterval*> &NewVRegs) {
604 // Make sure that VirtReg has a cascade number, and assign that cascade
605 // number to every evicted register. These live ranges than then only be
606 // evicted by a newer cascade, preventing infinite loops.
607 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
609 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
611 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
612 << " interference: Cascade " << Cascade << '\n');
613 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
614 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
615 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
616 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
617 LiveInterval *Intf = Q.interferingVRegs()[i];
618 unassign(*Intf, VRM->getPhys(Intf->reg));
619 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
620 VirtReg.isSpillable() < Intf->isSpillable()) &&
621 "Cannot decrease cascade number, illegal eviction");
622 ExtraRegInfo[Intf->reg].Cascade = Cascade;
624 NewVRegs.push_back(Intf);
629 /// tryEvict - Try to evict all interferences for a physreg.
630 /// @param VirtReg Currently unassigned virtual register.
631 /// @param Order Physregs to try.
632 /// @return Physreg to assign VirtReg, or 0.
633 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
634 AllocationOrder &Order,
635 SmallVectorImpl<LiveInterval*> &NewVRegs,
636 unsigned CostPerUseLimit) {
637 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
639 // Keep track of the cheapest interference seen so far.
640 EvictionCost BestCost(~0u);
641 unsigned BestPhys = 0;
643 // When we are just looking for a reduced cost per use, don't break any
644 // hints, and only evict smaller spill weights.
645 if (CostPerUseLimit < ~0u) {
646 BestCost.BrokenHints = 0;
647 BestCost.MaxWeight = VirtReg.weight;
651 while (unsigned PhysReg = Order.next()) {
652 if (clobberedByRegMask(PhysReg))
654 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
656 // The first use of a callee-saved register in a function has cost 1.
657 // Don't start using a CSR when the CostPerUseLimit is low.
658 if (CostPerUseLimit == 1)
659 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
660 if (!MRI->isPhysRegUsed(CSR)) {
661 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
662 << PrintReg(CSR, TRI) << '\n');
666 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
672 // Stop if the hint can be used.
673 if (Order.isHint(PhysReg))
680 evictInterference(VirtReg, BestPhys, NewVRegs);
685 //===----------------------------------------------------------------------===//
687 //===----------------------------------------------------------------------===//
689 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
690 /// interference pattern in Physreg and its aliases. Add the constraints to
691 /// SpillPlacement and return the static cost of this split in Cost, assuming
692 /// that all preferences in SplitConstraints are met.
693 /// Return false if there are no bundles with positive bias.
694 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
696 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
698 // Reset interference dependent info.
699 SplitConstraints.resize(UseBlocks.size());
700 float StaticCost = 0;
701 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
702 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
703 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
705 BC.Number = BI.MBB->getNumber();
706 Intf.moveToBlock(BC.Number);
707 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
708 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
709 BC.ChangesValue = BI.FirstDef;
711 if (!Intf.hasInterference())
714 // Number of spill code instructions to insert.
717 // Interference for the live-in value.
719 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
720 BC.Entry = SpillPlacement::MustSpill, ++Ins;
721 else if (Intf.first() < BI.FirstInstr)
722 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
723 else if (Intf.first() < BI.LastInstr)
727 // Interference for the live-out value.
729 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
730 BC.Exit = SpillPlacement::MustSpill, ++Ins;
731 else if (Intf.last() > BI.LastInstr)
732 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
733 else if (Intf.last() > BI.FirstInstr)
737 // Accumulate the total frequency of inserted spill code.
739 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
743 // Add constraints for use-blocks. Note that these are the only constraints
744 // that may add a positive bias, it is downhill from here.
745 SpillPlacer->addConstraints(SplitConstraints);
746 return SpillPlacer->scanActiveBundles();
750 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
751 /// live-through blocks in Blocks.
752 void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
753 ArrayRef<unsigned> Blocks) {
754 const unsigned GroupSize = 8;
755 SpillPlacement::BlockConstraint BCS[GroupSize];
756 unsigned TBS[GroupSize];
757 unsigned B = 0, T = 0;
759 for (unsigned i = 0; i != Blocks.size(); ++i) {
760 unsigned Number = Blocks[i];
761 Intf.moveToBlock(Number);
763 if (!Intf.hasInterference()) {
764 assert(T < GroupSize && "Array overflow");
766 if (++T == GroupSize) {
767 SpillPlacer->addLinks(makeArrayRef(TBS, T));
773 assert(B < GroupSize && "Array overflow");
774 BCS[B].Number = Number;
776 // Interference for the live-in value.
777 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
778 BCS[B].Entry = SpillPlacement::MustSpill;
780 BCS[B].Entry = SpillPlacement::PrefSpill;
782 // Interference for the live-out value.
783 if (Intf.last() >= SA->getLastSplitPoint(Number))
784 BCS[B].Exit = SpillPlacement::MustSpill;
786 BCS[B].Exit = SpillPlacement::PrefSpill;
788 if (++B == GroupSize) {
789 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
790 SpillPlacer->addConstraints(Array);
795 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
796 SpillPlacer->addConstraints(Array);
797 SpillPlacer->addLinks(makeArrayRef(TBS, T));
800 void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
801 // Keep track of through blocks that have not been added to SpillPlacer.
802 BitVector Todo = SA->getThroughBlocks();
803 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
804 unsigned AddedTo = 0;
806 unsigned Visited = 0;
810 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
811 // Find new through blocks in the periphery of PrefRegBundles.
812 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
813 unsigned Bundle = NewBundles[i];
814 // Look at all blocks connected to Bundle in the full graph.
815 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
816 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
819 if (!Todo.test(Block))
822 // This is a new through block. Add it to SpillPlacer later.
823 ActiveBlocks.push_back(Block);
829 // Any new blocks to add?
830 if (ActiveBlocks.size() == AddedTo)
833 // Compute through constraints from the interference, or assume that all
834 // through blocks prefer spilling when forming compact regions.
835 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
837 addThroughConstraints(Cand.Intf, NewBlocks);
839 // Provide a strong negative bias on through blocks to prevent unwanted
840 // liveness on loop backedges.
841 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
842 AddedTo = ActiveBlocks.size();
844 // Perhaps iterating can enable more bundles?
845 SpillPlacer->iterate();
847 DEBUG(dbgs() << ", v=" << Visited);
850 /// calcCompactRegion - Compute the set of edge bundles that should be live
851 /// when splitting the current live range into compact regions. Compact
852 /// regions can be computed without looking at interference. They are the
853 /// regions formed by removing all the live-through blocks from the live range.
855 /// Returns false if the current live range is already compact, or if the
856 /// compact regions would form single block regions anyway.
857 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
858 // Without any through blocks, the live range is already compact.
859 if (!SA->getNumThroughBlocks())
862 // Compact regions don't correspond to any physreg.
863 Cand.reset(IntfCache, 0);
865 DEBUG(dbgs() << "Compact region bundles");
867 // Use the spill placer to determine the live bundles. GrowRegion pretends
868 // that all the through blocks have interference when PhysReg is unset.
869 SpillPlacer->prepare(Cand.LiveBundles);
871 // The static split cost will be zero since Cand.Intf reports no interference.
873 if (!addSplitConstraints(Cand.Intf, Cost)) {
874 DEBUG(dbgs() << ", none.\n");
879 SpillPlacer->finish();
881 if (!Cand.LiveBundles.any()) {
882 DEBUG(dbgs() << ", none.\n");
887 for (int i = Cand.LiveBundles.find_first(); i>=0;
888 i = Cand.LiveBundles.find_next(i))
889 dbgs() << " EB#" << i;
895 /// calcSpillCost - Compute how expensive it would be to split the live range in
896 /// SA around all use blocks instead of forming bundle regions.
897 float RAGreedy::calcSpillCost() {
899 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
900 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
901 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
902 unsigned Number = BI.MBB->getNumber();
903 // We normally only need one spill instruction - a load or a store.
904 Cost += SpillPlacer->getBlockFrequency(Number);
906 // Unless the value is redefined in the block.
907 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
908 Cost += SpillPlacer->getBlockFrequency(Number);
913 /// calcGlobalSplitCost - Return the global split cost of following the split
914 /// pattern in LiveBundles. This cost should be added to the local cost of the
915 /// interference pattern in SplitConstraints.
917 float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
918 float GlobalCost = 0;
919 const BitVector &LiveBundles = Cand.LiveBundles;
920 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
921 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
922 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
923 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
924 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
925 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
929 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
931 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
933 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
936 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
937 unsigned Number = Cand.ActiveBlocks[i];
938 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
939 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
940 if (!RegIn && !RegOut)
942 if (RegIn && RegOut) {
943 // We need double spill code if this block has interference.
944 Cand.Intf.moveToBlock(Number);
945 if (Cand.Intf.hasInterference())
946 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
949 // live-in / stack-out or stack-in live-out.
950 GlobalCost += SpillPlacer->getBlockFrequency(Number);
955 /// splitAroundRegion - Split the current live range around the regions
956 /// determined by BundleCand and GlobalCand.
958 /// Before calling this function, GlobalCand and BundleCand must be initialized
959 /// so each bundle is assigned to a valid candidate, or NoCand for the
960 /// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
961 /// objects must be initialized for the current live range, and intervals
962 /// created for the used candidates.
964 /// @param LREdit The LiveRangeEdit object handling the current split.
965 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
966 /// must appear in this list.
967 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
968 ArrayRef<unsigned> UsedCands) {
969 // These are the intervals created for new global ranges. We may create more
970 // intervals for local ranges.
971 const unsigned NumGlobalIntvs = LREdit.size();
972 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
973 assert(NumGlobalIntvs && "No global intervals configured");
975 // Isolate even single instructions when dealing with a proper sub-class.
976 // That guarantees register class inflation for the stack interval because it
978 unsigned Reg = SA->getParent().reg;
979 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
981 // First handle all the blocks with uses.
982 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
983 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
984 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
985 unsigned Number = BI.MBB->getNumber();
986 unsigned IntvIn = 0, IntvOut = 0;
987 SlotIndex IntfIn, IntfOut;
989 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
990 if (CandIn != NoCand) {
991 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
992 IntvIn = Cand.IntvIdx;
993 Cand.Intf.moveToBlock(Number);
994 IntfIn = Cand.Intf.first();
998 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
999 if (CandOut != NoCand) {
1000 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1001 IntvOut = Cand.IntvIdx;
1002 Cand.Intf.moveToBlock(Number);
1003 IntfOut = Cand.Intf.last();
1007 // Create separate intervals for isolated blocks with multiple uses.
1008 if (!IntvIn && !IntvOut) {
1009 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
1010 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1011 SE->splitSingleBlock(BI);
1015 if (IntvIn && IntvOut)
1016 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1018 SE->splitRegInBlock(BI, IntvIn, IntfIn);
1020 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
1023 // Handle live-through blocks. The relevant live-through blocks are stored in
1024 // the ActiveBlocks list with each candidate. We need to filter out
1026 BitVector Todo = SA->getThroughBlocks();
1027 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1028 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1029 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1030 unsigned Number = Blocks[i];
1031 if (!Todo.test(Number))
1035 unsigned IntvIn = 0, IntvOut = 0;
1036 SlotIndex IntfIn, IntfOut;
1038 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1039 if (CandIn != NoCand) {
1040 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1041 IntvIn = Cand.IntvIdx;
1042 Cand.Intf.moveToBlock(Number);
1043 IntfIn = Cand.Intf.first();
1046 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1047 if (CandOut != NoCand) {
1048 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1049 IntvOut = Cand.IntvIdx;
1050 Cand.Intf.moveToBlock(Number);
1051 IntfOut = Cand.Intf.last();
1053 if (!IntvIn && !IntvOut)
1055 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1061 SmallVector<unsigned, 8> IntvMap;
1062 SE->finish(&IntvMap);
1063 DebugVars->splitRegister(Reg, LREdit.regs());
1065 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1066 unsigned OrigBlocks = SA->getNumLiveBlocks();
1068 // Sort out the new intervals created by splitting. We get four kinds:
1069 // - Remainder intervals should not be split again.
1070 // - Candidate intervals can be assigned to Cand.PhysReg.
1071 // - Block-local splits are candidates for local splitting.
1072 // - DCE leftovers should go back on the queue.
1073 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1074 LiveInterval &Reg = *LREdit.get(i);
1076 // Ignore old intervals from DCE.
1077 if (getStage(Reg) != RS_New)
1080 // Remainder interval. Don't try splitting again, spill if it doesn't
1082 if (IntvMap[i] == 0) {
1083 setStage(Reg, RS_Spill);
1087 // Global intervals. Allow repeated splitting as long as the number of live
1088 // blocks is strictly decreasing.
1089 if (IntvMap[i] < NumGlobalIntvs) {
1090 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1091 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1092 << " blocks as original.\n");
1093 // Don't allow repeated splitting as a safe guard against looping.
1094 setStage(Reg, RS_Split2);
1099 // Other intervals are treated as new. This includes local intervals created
1100 // for blocks with multiple uses, and anything created by DCE.
1104 MF->verify(this, "After splitting live range around region");
1107 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1108 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1109 unsigned NumCands = 0;
1110 unsigned BestCand = NoCand;
1112 SmallVector<unsigned, 8> UsedCands;
1114 // Check if we can split this live range around a compact region.
1115 bool HasCompact = calcCompactRegion(GlobalCand.front());
1117 // Yes, keep GlobalCand[0] as the compact region candidate.
1119 BestCost = HUGE_VALF;
1121 // No benefit from the compact region, our fallback will be per-block
1122 // splitting. Make sure we find a solution that is cheaper than spilling.
1123 BestCost = Hysteresis * calcSpillCost();
1124 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1128 while (unsigned PhysReg = Order.next()) {
1129 // Discard bad candidates before we run out of interference cache cursors.
1130 // This will only affect register classes with a lot of registers (>32).
1131 if (NumCands == IntfCache.getMaxCursors()) {
1132 unsigned WorstCount = ~0u;
1134 for (unsigned i = 0; i != NumCands; ++i) {
1135 if (i == BestCand || !GlobalCand[i].PhysReg)
1137 unsigned Count = GlobalCand[i].LiveBundles.count();
1138 if (Count < WorstCount)
1139 Worst = i, WorstCount = Count;
1142 GlobalCand[Worst] = GlobalCand[NumCands];
1143 if (BestCand == NumCands)
1147 if (GlobalCand.size() <= NumCands)
1148 GlobalCand.resize(NumCands+1);
1149 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1150 Cand.reset(IntfCache, PhysReg);
1152 SpillPlacer->prepare(Cand.LiveBundles);
1154 if (!addSplitConstraints(Cand.Intf, Cost)) {
1155 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
1158 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
1159 if (Cost >= BestCost) {
1161 if (BestCand == NoCand)
1162 dbgs() << " worse than no bundles\n";
1164 dbgs() << " worse than "
1165 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1171 SpillPlacer->finish();
1173 // No live bundles, defer to splitSingleBlocks().
1174 if (!Cand.LiveBundles.any()) {
1175 DEBUG(dbgs() << " no bundles.\n");
1179 Cost += calcGlobalSplitCost(Cand);
1181 dbgs() << ", total = " << Cost << " with bundles";
1182 for (int i = Cand.LiveBundles.find_first(); i>=0;
1183 i = Cand.LiveBundles.find_next(i))
1184 dbgs() << " EB#" << i;
1187 if (Cost < BestCost) {
1188 BestCand = NumCands;
1189 BestCost = Hysteresis * Cost; // Prevent rounding effects.
1194 // No solutions found, fall back to single block splitting.
1195 if (!HasCompact && BestCand == NoCand)
1198 // Prepare split editor.
1199 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1200 SE->reset(LREdit, SplitSpillMode);
1202 // Assign all edge bundles to the preferred candidate, or NoCand.
1203 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1205 // Assign bundles for the best candidate region.
1206 if (BestCand != NoCand) {
1207 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1208 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1209 UsedCands.push_back(BestCand);
1210 Cand.IntvIdx = SE->openIntv();
1211 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1212 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
1217 // Assign bundles for the compact region.
1219 GlobalSplitCandidate &Cand = GlobalCand.front();
1220 assert(!Cand.PhysReg && "Compact region has no physreg");
1221 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1222 UsedCands.push_back(0);
1223 Cand.IntvIdx = SE->openIntv();
1224 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1225 << Cand.IntvIdx << ".\n");
1230 splitAroundRegion(LREdit, UsedCands);
1235 //===----------------------------------------------------------------------===//
1236 // Per-Block Splitting
1237 //===----------------------------------------------------------------------===//
1239 /// tryBlockSplit - Split a global live range around every block with uses. This
1240 /// creates a lot of local live ranges, that will be split by tryLocalSplit if
1241 /// they don't allocate.
1242 unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1243 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1244 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1245 unsigned Reg = VirtReg.reg;
1246 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1247 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1248 SE->reset(LREdit, SplitSpillMode);
1249 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1250 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1251 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1252 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1253 SE->splitSingleBlock(BI);
1255 // No blocks were split.
1259 // We did split for some blocks.
1260 SmallVector<unsigned, 8> IntvMap;
1261 SE->finish(&IntvMap);
1263 // Tell LiveDebugVariables about the new ranges.
1264 DebugVars->splitRegister(Reg, LREdit.regs());
1266 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1268 // Sort out the new intervals created by splitting. The remainder interval
1269 // goes straight to spilling, the new local ranges get to stay RS_New.
1270 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1271 LiveInterval &LI = *LREdit.get(i);
1272 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1273 setStage(LI, RS_Spill);
1277 MF->verify(this, "After splitting live range around basic blocks");
1281 //===----------------------------------------------------------------------===//
1283 //===----------------------------------------------------------------------===//
1286 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1287 /// in order to use PhysReg between two entries in SA->UseSlots.
1289 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1291 void RAGreedy::calcGapWeights(unsigned PhysReg,
1292 SmallVectorImpl<float> &GapWeight) {
1293 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1294 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1295 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1296 const unsigned NumGaps = Uses.size()-1;
1298 // Start and end points for the interference check.
1299 SlotIndex StartIdx =
1300 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1302 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
1304 GapWeight.assign(NumGaps, 0.0f);
1306 // Add interference from each overlapping register.
1307 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
1308 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
1309 .checkInterference())
1312 // We know that VirtReg is a continuous interval from FirstInstr to
1313 // LastInstr, so we don't need InterferenceQuery.
1315 // Interference that overlaps an instruction is counted in both gaps
1316 // surrounding the instruction. The exception is interference before
1317 // StartIdx and after StopIdx.
1319 LiveIntervalUnion::SegmentIter IntI = getLiveUnion(*AI).find(StartIdx);
1320 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1321 // Skip the gaps before IntI.
1322 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1323 if (++Gap == NumGaps)
1328 // Update the gaps covered by IntI.
1329 const float weight = IntI.value()->weight;
1330 for (; Gap != NumGaps; ++Gap) {
1331 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1332 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1341 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1344 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1345 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1346 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1347 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1349 // Note that it is possible to have an interval that is live-in or live-out
1350 // while only covering a single block - A phi-def can use undef values from
1351 // predecessors, and the block could be a single-block loop.
1352 // We don't bother doing anything clever about such a case, we simply assume
1353 // that the interval is continuous from FirstInstr to LastInstr. We should
1354 // make sure that we don't do anything illegal to such an interval, though.
1356 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1357 if (Uses.size() <= 2)
1359 const unsigned NumGaps = Uses.size()-1;
1362 dbgs() << "tryLocalSplit: ";
1363 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1364 dbgs() << ' ' << Uses[i];
1368 // Since we allow local split results to be split again, there is a risk of
1369 // creating infinite loops. It is tempting to require that the new live
1370 // ranges have less instructions than the original. That would guarantee
1371 // convergence, but it is too strict. A live range with 3 instructions can be
1372 // split 2+3 (including the COPY), and we want to allow that.
1374 // Instead we use these rules:
1376 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
1377 // noop split, of course).
1378 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
1379 // the new ranges must have fewer instructions than before the split.
1380 // 3. New ranges with the same number of instructions are marked RS_Split2,
1381 // smaller ranges are marked RS_New.
1383 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1384 // excessive splitting and infinite loops.
1386 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
1388 // Best split candidate.
1389 unsigned BestBefore = NumGaps;
1390 unsigned BestAfter = 0;
1393 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
1394 SmallVector<float, 8> GapWeight;
1397 while (unsigned PhysReg = Order.next()) {
1398 // Keep track of the largest spill weight that would need to be evicted in
1399 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1400 calcGapWeights(PhysReg, GapWeight);
1402 // Try to find the best sequence of gaps to close.
1403 // The new spill weight must be larger than any gap interference.
1405 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1406 unsigned SplitBefore = 0, SplitAfter = 1;
1408 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1409 // It is the spill weight that needs to be evicted.
1410 float MaxGap = GapWeight[0];
1413 // Live before/after split?
1414 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1415 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1417 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1418 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1419 << " i=" << MaxGap);
1421 // Stop before the interval gets so big we wouldn't be making progress.
1422 if (!LiveBefore && !LiveAfter) {
1423 DEBUG(dbgs() << " all\n");
1426 // Should the interval be extended or shrunk?
1429 // How many gaps would the new range have?
1430 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1432 // Legally, without causing looping?
1433 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1435 if (Legal && MaxGap < HUGE_VALF) {
1436 // Estimate the new spill weight. Each instruction reads or writes the
1437 // register. Conservatively assume there are no read-modify-write
1440 // Try to guess the size of the new interval.
1441 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1442 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1443 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
1444 // Would this split be possible to allocate?
1445 // Never allocate all gaps, we wouldn't be making progress.
1446 DEBUG(dbgs() << " w=" << EstWeight);
1447 if (EstWeight * Hysteresis >= MaxGap) {
1449 float Diff = EstWeight - MaxGap;
1450 if (Diff > BestDiff) {
1451 DEBUG(dbgs() << " (best)");
1452 BestDiff = Hysteresis * Diff;
1453 BestBefore = SplitBefore;
1454 BestAfter = SplitAfter;
1461 if (++SplitBefore < SplitAfter) {
1462 DEBUG(dbgs() << " shrink\n");
1463 // Recompute the max when necessary.
1464 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1465 MaxGap = GapWeight[SplitBefore];
1466 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1467 MaxGap = std::max(MaxGap, GapWeight[i]);
1474 // Try to extend the interval.
1475 if (SplitAfter >= NumGaps) {
1476 DEBUG(dbgs() << " end\n");
1480 DEBUG(dbgs() << " extend\n");
1481 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
1485 // Didn't find any candidates?
1486 if (BestBefore == NumGaps)
1489 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1490 << '-' << Uses[BestAfter] << ", " << BestDiff
1491 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1493 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1497 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1498 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1499 SE->useIntv(SegStart, SegStop);
1500 SmallVector<unsigned, 8> IntvMap;
1501 SE->finish(&IntvMap);
1502 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1504 // If the new range has the same number of instructions as before, mark it as
1505 // RS_Split2 so the next split will be forced to make progress. Otherwise,
1506 // leave the new intervals as RS_New so they can compete.
1507 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1508 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1509 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1510 if (NewGaps >= NumGaps) {
1511 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1512 assert(!ProgressRequired && "Didn't make progress when it was required.");
1513 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1514 if (IntvMap[i] == 1) {
1515 setStage(*LREdit.get(i), RS_Split2);
1516 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1518 DEBUG(dbgs() << '\n');
1525 //===----------------------------------------------------------------------===//
1526 // Live Range Splitting
1527 //===----------------------------------------------------------------------===//
1529 /// trySplit - Try to split VirtReg or one of its interferences, making it
1531 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1532 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1533 SmallVectorImpl<LiveInterval*>&NewVRegs) {
1534 // Ranges must be Split2 or less.
1535 if (getStage(VirtReg) >= RS_Spill)
1538 // Local intervals are handled separately.
1539 if (LIS->intervalIsInOneMBB(VirtReg)) {
1540 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
1541 SA->analyze(&VirtReg);
1542 return tryLocalSplit(VirtReg, Order, NewVRegs);
1545 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
1547 SA->analyze(&VirtReg);
1549 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1550 // coalescer. That may cause the range to become allocatable which means that
1551 // tryRegionSplit won't be making progress. This check should be replaced with
1552 // an assertion when the coalescer is fixed.
1553 if (SA->didRepairRange()) {
1554 // VirtReg has changed, so all cached queries are invalid.
1555 invalidateVirtRegs();
1556 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1560 // First try to split around a region spanning multiple blocks. RS_Split2
1561 // ranges already made dubious progress with region splitting, so they go
1562 // straight to single block splitting.
1563 if (getStage(VirtReg) < RS_Split2) {
1564 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1565 if (PhysReg || !NewVRegs.empty())
1569 // Then isolate blocks.
1570 return tryBlockSplit(VirtReg, Order, NewVRegs);
1574 //===----------------------------------------------------------------------===//
1576 //===----------------------------------------------------------------------===//
1578 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
1579 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1580 // Check if VirtReg is live across any calls.
1582 if (LIS->checkRegMaskInterference(VirtReg, UsableRegs))
1583 DEBUG(dbgs() << "Live across regmasks.\n");
1585 // First try assigning a free register.
1586 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
1587 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1590 LiveRangeStage Stage = getStage(VirtReg);
1591 DEBUG(dbgs() << StageName[Stage]
1592 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
1594 // Try to evict a less worthy live range, but only for ranges from the primary
1595 // queue. The RS_Split ranges already failed to do this, and they should not
1596 // get a second chance until they have been split.
1597 if (Stage != RS_Split)
1598 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1601 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1603 // The first time we see a live range, don't try to split or spill.
1604 // Wait until the second time, when all smaller ranges have been allocated.
1605 // This gives a better picture of the interference to split around.
1606 if (Stage < RS_Split) {
1607 setStage(VirtReg, RS_Split);
1608 DEBUG(dbgs() << "wait for second round\n");
1609 NewVRegs.push_back(&VirtReg);
1613 // If we couldn't allocate a register from spilling, there is probably some
1614 // invalid inline assembly. The base class wil report it.
1615 if (Stage >= RS_Done || !VirtReg.isSpillable())
1618 // Try splitting VirtReg or interferences.
1619 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1620 if (PhysReg || !NewVRegs.empty())
1623 // Finally spill VirtReg itself.
1624 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
1625 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1626 spiller().spill(LRE);
1627 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
1630 MF->verify(this, "After spilling");
1632 // The live virtual register requesting allocation was spilled, so tell
1633 // the caller not to allocate anything during this round.
1637 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1638 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1639 << "********** Function: "
1640 << ((Value*)mf.getFunction())->getName() << '\n');
1644 MF->verify(this, "Before greedy register allocator");
1646 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
1647 Indexes = &getAnalysis<SlotIndexes>();
1648 DomTree = &getAnalysis<MachineDominatorTree>();
1649 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
1650 Loops = &getAnalysis<MachineLoopInfo>();
1651 Bundles = &getAnalysis<EdgeBundles>();
1652 SpillPlacer = &getAnalysis<SpillPlacement>();
1653 DebugVars = &getAnalysis<LiveDebugVariables>();
1655 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
1656 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
1657 ExtraRegInfo.clear();
1658 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1660 IntfCache.init(MF, &getLiveUnion(0), Indexes, TRI);
1661 GlobalCand.resize(32); // This will grow as needed.
1665 LIS->addKillFlags();
1669 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
1670 VRM->rewrite(Indexes);
1673 // Write out new DBG_VALUE instructions.
1675 NamedRegionTimer T("Emit Debug Info", TimerGroupName, TimePassesIsEnabled);
1676 DebugVars->emitDebugValues(VRM);
1679 // The pass output is in VirtRegMap. Release all the transient data.