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 static cl::opt<SplitEditor::ComplementSpillMode>
55 SplitSpillMode("split-spill-mode", cl::Hidden,
56 cl::desc("Spill mode for splitting live ranges"),
57 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
58 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
59 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
61 cl::init(SplitEditor::SM_Partition));
63 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
64 createGreedyRegisterAllocator);
67 class RAGreedy : public MachineFunctionPass,
69 private LiveRangeEdit::Delegate {
77 MachineDominatorTree *DomTree;
78 MachineLoopInfo *Loops;
80 SpillPlacement *SpillPlacer;
81 LiveDebugVariables *DebugVars;
84 std::auto_ptr<Spiller> SpillerInstance;
85 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
88 // Live ranges pass through a number of stages as we try to allocate them.
89 // Some of the stages may also create new live ranges:
91 // - Region splitting.
92 // - Per-block splitting.
96 // Ranges produced by one of the stages skip the previous stages when they are
97 // dequeued. This improves performance because we can skip interference checks
98 // that are unlikely to give any results. It also guarantees that the live
99 // range splitting algorithm terminates, something that is otherwise hard to
101 enum LiveRangeStage {
102 /// Newly created live range that has never been queued.
105 /// Only attempt assignment and eviction. Then requeue as RS_Split.
108 /// Attempt live range splitting if assignment is impossible.
111 /// Attempt more aggressive live range splitting that is guaranteed to make
112 /// progress. This is used for split products that may not be making
116 /// Live range will be spilled. No more splitting will be attempted.
119 /// There is nothing more we can do to this live range. Abort compilation
120 /// if it can't be assigned.
124 static const char *const StageName[];
126 // RegInfo - Keep additional information about each live range.
128 LiveRangeStage Stage;
130 // Cascade - Eviction loop prevention. See canEvictInterference().
133 RegInfo() : Stage(RS_New), Cascade(0) {}
136 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
138 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
139 return ExtraRegInfo[VirtReg.reg].Stage;
142 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
143 ExtraRegInfo.resize(MRI->getNumVirtRegs());
144 ExtraRegInfo[VirtReg.reg].Stage = Stage;
147 template<typename Iterator>
148 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
149 ExtraRegInfo.resize(MRI->getNumVirtRegs());
150 for (;Begin != End; ++Begin) {
151 unsigned Reg = (*Begin)->reg;
152 if (ExtraRegInfo[Reg].Stage == RS_New)
153 ExtraRegInfo[Reg].Stage = NewStage;
157 /// Cost of evicting interference.
158 struct EvictionCost {
159 unsigned BrokenHints; ///< Total number of broken hints.
160 float MaxWeight; ///< Maximum spill weight evicted.
162 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
164 bool operator<(const EvictionCost &O) const {
165 if (BrokenHints != O.BrokenHints)
166 return BrokenHints < O.BrokenHints;
167 return MaxWeight < O.MaxWeight;
172 std::auto_ptr<SplitAnalysis> SA;
173 std::auto_ptr<SplitEditor> SE;
175 /// Cached per-block interference maps
176 InterferenceCache IntfCache;
178 /// All basic blocks where the current register has uses.
179 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
181 /// Global live range splitting candidate info.
182 struct GlobalSplitCandidate {
183 // Register intended for assignment, or 0.
186 // SplitKit interval index for this candidate.
189 // Interference for PhysReg.
190 InterferenceCache::Cursor Intf;
192 // Bundles where this candidate should be live.
193 BitVector LiveBundles;
194 SmallVector<unsigned, 8> ActiveBlocks;
196 void reset(InterferenceCache &Cache, unsigned Reg) {
199 Intf.setPhysReg(Cache, Reg);
201 ActiveBlocks.clear();
204 // Set B[i] = C for every live bundle where B[i] was NoCand.
205 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
207 for (int i = LiveBundles.find_first(); i >= 0;
208 i = LiveBundles.find_next(i))
209 if (B[i] == NoCand) {
217 /// Candidate info for for each PhysReg in AllocationOrder.
218 /// This vector never shrinks, but grows to the size of the largest register
220 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
222 enum { NoCand = ~0u };
224 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
225 /// NoCand which indicates the stack interval.
226 SmallVector<unsigned, 32> BundleCand;
231 /// Return the pass name.
232 virtual const char* getPassName() const {
233 return "Greedy Register Allocator";
236 /// RAGreedy analysis usage.
237 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
238 virtual void releaseMemory();
239 virtual Spiller &spiller() { return *SpillerInstance; }
240 virtual void enqueue(LiveInterval *LI);
241 virtual LiveInterval *dequeue();
242 virtual unsigned selectOrSplit(LiveInterval&,
243 SmallVectorImpl<LiveInterval*>&);
245 /// Perform register allocation.
246 virtual bool runOnMachineFunction(MachineFunction &mf);
251 void LRE_WillEraseInstruction(MachineInstr*);
252 bool LRE_CanEraseVirtReg(unsigned);
253 void LRE_WillShrinkVirtReg(unsigned);
254 void LRE_DidCloneVirtReg(unsigned, unsigned);
256 float calcSpillCost();
257 bool addSplitConstraints(InterferenceCache::Cursor, float&);
258 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
259 void growRegion(GlobalSplitCandidate &Cand);
260 float calcGlobalSplitCost(GlobalSplitCandidate&);
261 bool calcCompactRegion(GlobalSplitCandidate&);
262 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
263 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
264 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
265 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
266 void evictInterference(LiveInterval&, unsigned,
267 SmallVectorImpl<LiveInterval*>&);
269 unsigned tryAssign(LiveInterval&, AllocationOrder&,
270 SmallVectorImpl<LiveInterval*>&);
271 unsigned tryEvict(LiveInterval&, AllocationOrder&,
272 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
273 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
274 SmallVectorImpl<LiveInterval*>&);
275 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
276 SmallVectorImpl<LiveInterval*>&);
277 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
278 SmallVectorImpl<LiveInterval*>&);
279 unsigned trySplit(LiveInterval&, AllocationOrder&,
280 SmallVectorImpl<LiveInterval*>&);
282 } // end anonymous namespace
284 char RAGreedy::ID = 0;
287 const char *const RAGreedy::StageName[] = {
297 // Hysteresis to use when comparing floats.
298 // This helps stabilize decisions based on float comparisons.
299 const float Hysteresis = 0.98f;
302 FunctionPass* llvm::createGreedyRegisterAllocator() {
303 return new RAGreedy();
306 RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
307 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
308 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
309 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
310 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
311 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
312 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
313 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
314 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
315 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
316 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
317 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
318 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
319 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
322 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
323 AU.setPreservesCFG();
324 AU.addRequired<AliasAnalysis>();
325 AU.addPreserved<AliasAnalysis>();
326 AU.addRequired<LiveIntervals>();
327 AU.addRequired<SlotIndexes>();
328 AU.addPreserved<SlotIndexes>();
329 AU.addRequired<LiveDebugVariables>();
330 AU.addPreserved<LiveDebugVariables>();
332 AU.addRequiredID(StrongPHIEliminationID);
333 AU.addRequiredTransitiveID(RegisterCoalescerPassID);
334 AU.addRequired<CalculateSpillWeights>();
335 AU.addRequired<LiveStacks>();
336 AU.addPreserved<LiveStacks>();
337 AU.addRequired<MachineDominatorTree>();
338 AU.addPreserved<MachineDominatorTree>();
339 AU.addRequired<MachineLoopInfo>();
340 AU.addPreserved<MachineLoopInfo>();
341 AU.addRequired<VirtRegMap>();
342 AU.addPreserved<VirtRegMap>();
343 AU.addRequired<EdgeBundles>();
344 AU.addRequired<SpillPlacement>();
345 MachineFunctionPass::getAnalysisUsage(AU);
349 //===----------------------------------------------------------------------===//
350 // LiveRangeEdit delegate methods
351 //===----------------------------------------------------------------------===//
353 void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
354 // LRE itself will remove from SlotIndexes and parent basic block.
355 VRM->RemoveMachineInstrFromMaps(MI);
358 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
359 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
360 unassign(LIS->getInterval(VirtReg), PhysReg);
363 // Unassigned virtreg is probably in the priority queue.
364 // RegAllocBase will erase it after dequeueing.
368 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
369 unsigned PhysReg = VRM->getPhys(VirtReg);
373 // Register is assigned, put it back on the queue for reassignment.
374 LiveInterval &LI = LIS->getInterval(VirtReg);
375 unassign(LI, PhysReg);
379 void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
380 // LRE may clone a virtual register because dead code elimination causes it to
381 // be split into connected components. The new components are much smaller
382 // than the original, so they should get a new chance at being assigned.
383 // same stage as the parent.
384 ExtraRegInfo[Old].Stage = RS_Assign;
385 ExtraRegInfo.grow(New);
386 ExtraRegInfo[New] = ExtraRegInfo[Old];
389 void RAGreedy::releaseMemory() {
390 SpillerInstance.reset(0);
391 ExtraRegInfo.clear();
393 RegAllocBase::releaseMemory();
396 void RAGreedy::enqueue(LiveInterval *LI) {
397 // Prioritize live ranges by size, assigning larger ranges first.
398 // The queue holds (size, reg) pairs.
399 const unsigned Size = LI->getSize();
400 const unsigned Reg = LI->reg;
401 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
402 "Can only enqueue virtual registers");
405 ExtraRegInfo.grow(Reg);
406 if (ExtraRegInfo[Reg].Stage == RS_New)
407 ExtraRegInfo[Reg].Stage = RS_Assign;
409 if (ExtraRegInfo[Reg].Stage == RS_Split) {
410 // Unsplit ranges that couldn't be allocated immediately are deferred until
411 // everything else has been allocated.
414 // Everything is allocated in long->short order. Long ranges that don't fit
415 // should be spilled (or split) ASAP so they don't create interference.
416 Prio = (1u << 31) + Size;
418 // Boost ranges that have a physical register hint.
419 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
423 Queue.push(std::make_pair(Prio, Reg));
426 LiveInterval *RAGreedy::dequeue() {
429 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
435 //===----------------------------------------------------------------------===//
437 //===----------------------------------------------------------------------===//
439 /// tryAssign - Try to assign VirtReg to an available register.
440 unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
441 AllocationOrder &Order,
442 SmallVectorImpl<LiveInterval*> &NewVRegs) {
445 while ((PhysReg = Order.next()))
446 if (!checkPhysRegInterference(VirtReg, PhysReg))
448 if (!PhysReg || Order.isHint(PhysReg))
451 // PhysReg is available, but there may be a better choice.
453 // If we missed a simple hint, try to cheaply evict interference from the
454 // preferred register.
455 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
456 if (Order.isHint(Hint)) {
457 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
458 EvictionCost MaxCost(1);
459 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
460 evictInterference(VirtReg, Hint, NewVRegs);
465 // Try to evict interference from a cheaper alternative.
466 unsigned Cost = TRI->getCostPerUse(PhysReg);
468 // Most registers have 0 additional cost.
472 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
474 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
475 return CheapReg ? CheapReg : PhysReg;
479 //===----------------------------------------------------------------------===//
480 // Interference eviction
481 //===----------------------------------------------------------------------===//
483 /// shouldEvict - determine if A should evict the assigned live range B. The
484 /// eviction policy defined by this function together with the allocation order
485 /// defined by enqueue() decides which registers ultimately end up being split
488 /// Cascade numbers are used to prevent infinite loops if this function is a
491 /// @param A The live range to be assigned.
492 /// @param IsHint True when A is about to be assigned to its preferred
494 /// @param B The live range to be evicted.
495 /// @param BreaksHint True when B is already assigned to its preferred register.
496 bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
497 LiveInterval &B, bool BreaksHint) {
498 bool CanSplit = getStage(B) < RS_Spill;
500 // Be fairly aggressive about following hints as long as the evictee can be
502 if (CanSplit && IsHint && !BreaksHint)
505 return A.weight > B.weight;
508 /// canEvictInterference - Return true if all interferences between VirtReg and
509 /// PhysReg can be evicted. When OnlyCheap is set, don't do anything
511 /// @param VirtReg Live range that is about to be assigned.
512 /// @param PhysReg Desired register for assignment.
513 /// @prarm IsHint True when PhysReg is VirtReg's preferred register.
514 /// @param MaxCost Only look for cheaper candidates and update with new cost
515 /// when returning true.
516 /// @returns True when interference can be evicted cheaper than MaxCost.
517 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
518 bool IsHint, EvictionCost &MaxCost) {
519 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
520 // involved in an eviction before. If a cascade number was assigned, deny
521 // evicting anything with the same or a newer cascade number. This prevents
522 // infinite eviction loops.
524 // This works out so a register without a cascade number is allowed to evict
525 // anything, and it can be evicted by anything.
526 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
528 Cascade = NextCascade;
531 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
532 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
533 // If there is 10 or more interferences, chances are one is heavier.
534 if (Q.collectInterferingVRegs(10) >= 10)
537 // Check if any interfering live range is heavier than MaxWeight.
538 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
539 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
540 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
542 // Never evict spill products. They cannot split or spill.
543 if (getStage(*Intf) == RS_Done)
545 // Once a live range becomes small enough, it is urgent that we find a
546 // register for it. This is indicated by an infinite spill weight. These
547 // urgent live ranges get to evict almost anything.
548 bool Urgent = !VirtReg.isSpillable() && Intf->isSpillable();
549 // Only evict older cascades or live ranges without a cascade.
550 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
551 if (Cascade <= IntfCascade) {
554 // We permit breaking cascades for urgent evictions. It should be the
555 // last resort, though, so make it really expensive.
556 Cost.BrokenHints += 10;
558 // Would this break a satisfied hint?
559 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
560 // Update eviction cost.
561 Cost.BrokenHints += BreaksHint;
562 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
563 // Abort if this would be too expensive.
564 if (!(Cost < MaxCost))
566 // Finally, apply the eviction policy for non-urgent evictions.
567 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
575 /// evictInterference - Evict any interferring registers that prevent VirtReg
576 /// from being assigned to Physreg. This assumes that canEvictInterference
578 void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
579 SmallVectorImpl<LiveInterval*> &NewVRegs) {
580 // Make sure that VirtReg has a cascade number, and assign that cascade
581 // number to every evicted register. These live ranges than then only be
582 // evicted by a newer cascade, preventing infinite loops.
583 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
585 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
587 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
588 << " interference: Cascade " << Cascade << '\n');
589 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
590 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
591 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
592 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
593 LiveInterval *Intf = Q.interferingVRegs()[i];
594 unassign(*Intf, VRM->getPhys(Intf->reg));
595 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
596 VirtReg.isSpillable() < Intf->isSpillable()) &&
597 "Cannot decrease cascade number, illegal eviction");
598 ExtraRegInfo[Intf->reg].Cascade = Cascade;
600 NewVRegs.push_back(Intf);
605 /// tryEvict - Try to evict all interferences for a physreg.
606 /// @param VirtReg Currently unassigned virtual register.
607 /// @param Order Physregs to try.
608 /// @return Physreg to assign VirtReg, or 0.
609 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
610 AllocationOrder &Order,
611 SmallVectorImpl<LiveInterval*> &NewVRegs,
612 unsigned CostPerUseLimit) {
613 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
615 // Keep track of the cheapest interference seen so far.
616 EvictionCost BestCost(~0u);
617 unsigned BestPhys = 0;
619 // When we are just looking for a reduced cost per use, don't break any
620 // hints, and only evict smaller spill weights.
621 if (CostPerUseLimit < ~0u) {
622 BestCost.BrokenHints = 0;
623 BestCost.MaxWeight = VirtReg.weight;
627 while (unsigned PhysReg = Order.next()) {
628 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
630 // The first use of a callee-saved register in a function has cost 1.
631 // Don't start using a CSR when the CostPerUseLimit is low.
632 if (CostPerUseLimit == 1)
633 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
634 if (!MRI->isPhysRegUsed(CSR)) {
635 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
636 << PrintReg(CSR, TRI) << '\n');
640 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
646 // Stop if the hint can be used.
647 if (Order.isHint(PhysReg))
654 evictInterference(VirtReg, BestPhys, NewVRegs);
659 //===----------------------------------------------------------------------===//
661 //===----------------------------------------------------------------------===//
663 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
664 /// interference pattern in Physreg and its aliases. Add the constraints to
665 /// SpillPlacement and return the static cost of this split in Cost, assuming
666 /// that all preferences in SplitConstraints are met.
667 /// Return false if there are no bundles with positive bias.
668 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
670 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
672 // Reset interference dependent info.
673 SplitConstraints.resize(UseBlocks.size());
674 float StaticCost = 0;
675 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
676 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
677 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
679 BC.Number = BI.MBB->getNumber();
680 Intf.moveToBlock(BC.Number);
681 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
682 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
683 BC.ChangesValue = BI.FirstDef;
685 if (!Intf.hasInterference())
688 // Number of spill code instructions to insert.
691 // Interference for the live-in value.
693 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
694 BC.Entry = SpillPlacement::MustSpill, ++Ins;
695 else if (Intf.first() < BI.FirstInstr)
696 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
697 else if (Intf.first() < BI.LastInstr)
701 // Interference for the live-out value.
703 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
704 BC.Exit = SpillPlacement::MustSpill, ++Ins;
705 else if (Intf.last() > BI.LastInstr)
706 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
707 else if (Intf.last() > BI.FirstInstr)
711 // Accumulate the total frequency of inserted spill code.
713 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
717 // Add constraints for use-blocks. Note that these are the only constraints
718 // that may add a positive bias, it is downhill from here.
719 SpillPlacer->addConstraints(SplitConstraints);
720 return SpillPlacer->scanActiveBundles();
724 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
725 /// live-through blocks in Blocks.
726 void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
727 ArrayRef<unsigned> Blocks) {
728 const unsigned GroupSize = 8;
729 SpillPlacement::BlockConstraint BCS[GroupSize];
730 unsigned TBS[GroupSize];
731 unsigned B = 0, T = 0;
733 for (unsigned i = 0; i != Blocks.size(); ++i) {
734 unsigned Number = Blocks[i];
735 Intf.moveToBlock(Number);
737 if (!Intf.hasInterference()) {
738 assert(T < GroupSize && "Array overflow");
740 if (++T == GroupSize) {
741 SpillPlacer->addLinks(makeArrayRef(TBS, T));
747 assert(B < GroupSize && "Array overflow");
748 BCS[B].Number = Number;
750 // Interference for the live-in value.
751 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
752 BCS[B].Entry = SpillPlacement::MustSpill;
754 BCS[B].Entry = SpillPlacement::PrefSpill;
756 // Interference for the live-out value.
757 if (Intf.last() >= SA->getLastSplitPoint(Number))
758 BCS[B].Exit = SpillPlacement::MustSpill;
760 BCS[B].Exit = SpillPlacement::PrefSpill;
762 if (++B == GroupSize) {
763 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
764 SpillPlacer->addConstraints(Array);
769 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
770 SpillPlacer->addConstraints(Array);
771 SpillPlacer->addLinks(makeArrayRef(TBS, T));
774 void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
775 // Keep track of through blocks that have not been added to SpillPlacer.
776 BitVector Todo = SA->getThroughBlocks();
777 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
778 unsigned AddedTo = 0;
780 unsigned Visited = 0;
784 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
785 // Find new through blocks in the periphery of PrefRegBundles.
786 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
787 unsigned Bundle = NewBundles[i];
788 // Look at all blocks connected to Bundle in the full graph.
789 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
790 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
793 if (!Todo.test(Block))
796 // This is a new through block. Add it to SpillPlacer later.
797 ActiveBlocks.push_back(Block);
803 // Any new blocks to add?
804 if (ActiveBlocks.size() == AddedTo)
807 // Compute through constraints from the interference, or assume that all
808 // through blocks prefer spilling when forming compact regions.
809 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
811 addThroughConstraints(Cand.Intf, NewBlocks);
813 // Provide a strong negative bias on through blocks to prevent unwanted
814 // liveness on loop backedges.
815 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
816 AddedTo = ActiveBlocks.size();
818 // Perhaps iterating can enable more bundles?
819 SpillPlacer->iterate();
821 DEBUG(dbgs() << ", v=" << Visited);
824 /// calcCompactRegion - Compute the set of edge bundles that should be live
825 /// when splitting the current live range into compact regions. Compact
826 /// regions can be computed without looking at interference. They are the
827 /// regions formed by removing all the live-through blocks from the live range.
829 /// Returns false if the current live range is already compact, or if the
830 /// compact regions would form single block regions anyway.
831 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
832 // Without any through blocks, the live range is already compact.
833 if (!SA->getNumThroughBlocks())
836 // Compact regions don't correspond to any physreg.
837 Cand.reset(IntfCache, 0);
839 DEBUG(dbgs() << "Compact region bundles");
841 // Use the spill placer to determine the live bundles. GrowRegion pretends
842 // that all the through blocks have interference when PhysReg is unset.
843 SpillPlacer->prepare(Cand.LiveBundles);
845 // The static split cost will be zero since Cand.Intf reports no interference.
847 if (!addSplitConstraints(Cand.Intf, Cost)) {
848 DEBUG(dbgs() << ", none.\n");
853 SpillPlacer->finish();
855 if (!Cand.LiveBundles.any()) {
856 DEBUG(dbgs() << ", none.\n");
861 for (int i = Cand.LiveBundles.find_first(); i>=0;
862 i = Cand.LiveBundles.find_next(i))
863 dbgs() << " EB#" << i;
869 /// calcSpillCost - Compute how expensive it would be to split the live range in
870 /// SA around all use blocks instead of forming bundle regions.
871 float RAGreedy::calcSpillCost() {
873 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
874 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
875 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
876 unsigned Number = BI.MBB->getNumber();
877 // We normally only need one spill instruction - a load or a store.
878 Cost += SpillPlacer->getBlockFrequency(Number);
880 // Unless the value is redefined in the block.
881 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
882 Cost += SpillPlacer->getBlockFrequency(Number);
887 /// calcGlobalSplitCost - Return the global split cost of following the split
888 /// pattern in LiveBundles. This cost should be added to the local cost of the
889 /// interference pattern in SplitConstraints.
891 float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
892 float GlobalCost = 0;
893 const BitVector &LiveBundles = Cand.LiveBundles;
894 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
895 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
896 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
897 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
898 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
899 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
903 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
905 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
907 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
910 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
911 unsigned Number = Cand.ActiveBlocks[i];
912 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
913 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
914 if (!RegIn && !RegOut)
916 if (RegIn && RegOut) {
917 // We need double spill code if this block has interference.
918 Cand.Intf.moveToBlock(Number);
919 if (Cand.Intf.hasInterference())
920 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
923 // live-in / stack-out or stack-in live-out.
924 GlobalCost += SpillPlacer->getBlockFrequency(Number);
929 /// splitAroundRegion - Split the current live range around the regions
930 /// determined by BundleCand and GlobalCand.
932 /// Before calling this function, GlobalCand and BundleCand must be initialized
933 /// so each bundle is assigned to a valid candidate, or NoCand for the
934 /// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
935 /// objects must be initialized for the current live range, and intervals
936 /// created for the used candidates.
938 /// @param LREdit The LiveRangeEdit object handling the current split.
939 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
940 /// must appear in this list.
941 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
942 ArrayRef<unsigned> UsedCands) {
943 // These are the intervals created for new global ranges. We may create more
944 // intervals for local ranges.
945 const unsigned NumGlobalIntvs = LREdit.size();
946 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
947 assert(NumGlobalIntvs && "No global intervals configured");
949 // Isolate even single instructions when dealing with a proper sub-class.
950 // That guarantees register class inflation for the stack interval because it
952 unsigned Reg = SA->getParent().reg;
953 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
955 // First handle all the blocks with uses.
956 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
957 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
958 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
959 unsigned Number = BI.MBB->getNumber();
960 unsigned IntvIn = 0, IntvOut = 0;
961 SlotIndex IntfIn, IntfOut;
963 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
964 if (CandIn != NoCand) {
965 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
966 IntvIn = Cand.IntvIdx;
967 Cand.Intf.moveToBlock(Number);
968 IntfIn = Cand.Intf.first();
972 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
973 if (CandOut != NoCand) {
974 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
975 IntvOut = Cand.IntvIdx;
976 Cand.Intf.moveToBlock(Number);
977 IntfOut = Cand.Intf.last();
981 // Create separate intervals for isolated blocks with multiple uses.
982 if (!IntvIn && !IntvOut) {
983 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
984 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
985 SE->splitSingleBlock(BI);
989 if (IntvIn && IntvOut)
990 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
992 SE->splitRegInBlock(BI, IntvIn, IntfIn);
994 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
997 // Handle live-through blocks. The relevant live-through blocks are stored in
998 // the ActiveBlocks list with each candidate. We need to filter out
1000 BitVector Todo = SA->getThroughBlocks();
1001 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1002 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1003 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1004 unsigned Number = Blocks[i];
1005 if (!Todo.test(Number))
1009 unsigned IntvIn = 0, IntvOut = 0;
1010 SlotIndex IntfIn, IntfOut;
1012 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1013 if (CandIn != NoCand) {
1014 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1015 IntvIn = Cand.IntvIdx;
1016 Cand.Intf.moveToBlock(Number);
1017 IntfIn = Cand.Intf.first();
1020 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1021 if (CandOut != NoCand) {
1022 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1023 IntvOut = Cand.IntvIdx;
1024 Cand.Intf.moveToBlock(Number);
1025 IntfOut = Cand.Intf.last();
1027 if (!IntvIn && !IntvOut)
1029 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1035 SmallVector<unsigned, 8> IntvMap;
1036 SE->finish(&IntvMap);
1037 DebugVars->splitRegister(Reg, LREdit.regs());
1039 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1040 unsigned OrigBlocks = SA->getNumLiveBlocks();
1042 // Sort out the new intervals created by splitting. We get four kinds:
1043 // - Remainder intervals should not be split again.
1044 // - Candidate intervals can be assigned to Cand.PhysReg.
1045 // - Block-local splits are candidates for local splitting.
1046 // - DCE leftovers should go back on the queue.
1047 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1048 LiveInterval &Reg = *LREdit.get(i);
1050 // Ignore old intervals from DCE.
1051 if (getStage(Reg) != RS_New)
1054 // Remainder interval. Don't try splitting again, spill if it doesn't
1056 if (IntvMap[i] == 0) {
1057 setStage(Reg, RS_Spill);
1061 // Global intervals. Allow repeated splitting as long as the number of live
1062 // blocks is strictly decreasing.
1063 if (IntvMap[i] < NumGlobalIntvs) {
1064 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1065 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1066 << " blocks as original.\n");
1067 // Don't allow repeated splitting as a safe guard against looping.
1068 setStage(Reg, RS_Split2);
1073 // Other intervals are treated as new. This includes local intervals created
1074 // for blocks with multiple uses, and anything created by DCE.
1078 MF->verify(this, "After splitting live range around region");
1081 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1082 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1083 unsigned NumCands = 0;
1084 unsigned BestCand = NoCand;
1086 SmallVector<unsigned, 8> UsedCands;
1088 // Check if we can split this live range around a compact region.
1089 bool HasCompact = calcCompactRegion(GlobalCand.front());
1091 // Yes, keep GlobalCand[0] as the compact region candidate.
1093 BestCost = HUGE_VALF;
1095 // No benefit from the compact region, our fallback will be per-block
1096 // splitting. Make sure we find a solution that is cheaper than spilling.
1097 BestCost = Hysteresis * calcSpillCost();
1098 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1102 while (unsigned PhysReg = Order.next()) {
1103 // Discard bad candidates before we run out of interference cache cursors.
1104 // This will only affect register classes with a lot of registers (>32).
1105 if (NumCands == IntfCache.getMaxCursors()) {
1106 unsigned WorstCount = ~0u;
1108 for (unsigned i = 0; i != NumCands; ++i) {
1109 if (i == BestCand || !GlobalCand[i].PhysReg)
1111 unsigned Count = GlobalCand[i].LiveBundles.count();
1112 if (Count < WorstCount)
1113 Worst = i, WorstCount = Count;
1116 GlobalCand[Worst] = GlobalCand[NumCands];
1119 if (GlobalCand.size() <= NumCands)
1120 GlobalCand.resize(NumCands+1);
1121 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1122 Cand.reset(IntfCache, PhysReg);
1124 SpillPlacer->prepare(Cand.LiveBundles);
1126 if (!addSplitConstraints(Cand.Intf, Cost)) {
1127 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
1130 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
1131 if (Cost >= BestCost) {
1133 if (BestCand == NoCand)
1134 dbgs() << " worse than no bundles\n";
1136 dbgs() << " worse than "
1137 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1143 SpillPlacer->finish();
1145 // No live bundles, defer to splitSingleBlocks().
1146 if (!Cand.LiveBundles.any()) {
1147 DEBUG(dbgs() << " no bundles.\n");
1151 Cost += calcGlobalSplitCost(Cand);
1153 dbgs() << ", total = " << Cost << " with bundles";
1154 for (int i = Cand.LiveBundles.find_first(); i>=0;
1155 i = Cand.LiveBundles.find_next(i))
1156 dbgs() << " EB#" << i;
1159 if (Cost < BestCost) {
1160 BestCand = NumCands;
1161 BestCost = Hysteresis * Cost; // Prevent rounding effects.
1166 // No solutions found, fall back to single block splitting.
1167 if (!HasCompact && BestCand == NoCand)
1170 // Prepare split editor.
1171 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1172 SE->reset(LREdit, SplitSpillMode);
1174 // Assign all edge bundles to the preferred candidate, or NoCand.
1175 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1177 // Assign bundles for the best candidate region.
1178 if (BestCand != NoCand) {
1179 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1180 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1181 UsedCands.push_back(BestCand);
1182 Cand.IntvIdx = SE->openIntv();
1183 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1184 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
1189 // Assign bundles for the compact region.
1191 GlobalSplitCandidate &Cand = GlobalCand.front();
1192 assert(!Cand.PhysReg && "Compact region has no physreg");
1193 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1194 UsedCands.push_back(0);
1195 Cand.IntvIdx = SE->openIntv();
1196 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1197 << Cand.IntvIdx << ".\n");
1202 splitAroundRegion(LREdit, UsedCands);
1207 //===----------------------------------------------------------------------===//
1208 // Per-Block Splitting
1209 //===----------------------------------------------------------------------===//
1211 /// tryBlockSplit - Split a global live range around every block with uses. This
1212 /// creates a lot of local live ranges, that will be split by tryLocalSplit if
1213 /// they don't allocate.
1214 unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1215 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1216 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1217 unsigned Reg = VirtReg.reg;
1218 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1219 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1220 SE->reset(LREdit, SplitSpillMode);
1221 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1222 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1223 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1224 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1225 SE->splitSingleBlock(BI);
1227 // No blocks were split.
1231 // We did split for some blocks.
1232 SmallVector<unsigned, 8> IntvMap;
1233 SE->finish(&IntvMap);
1235 // Tell LiveDebugVariables about the new ranges.
1236 DebugVars->splitRegister(Reg, LREdit.regs());
1238 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1240 // Sort out the new intervals created by splitting. The remainder interval
1241 // goes straight to spilling, the new local ranges get to stay RS_New.
1242 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1243 LiveInterval &LI = *LREdit.get(i);
1244 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1245 setStage(LI, RS_Spill);
1249 MF->verify(this, "After splitting live range around basic blocks");
1253 //===----------------------------------------------------------------------===//
1255 //===----------------------------------------------------------------------===//
1258 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1259 /// in order to use PhysReg between two entries in SA->UseSlots.
1261 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1263 void RAGreedy::calcGapWeights(unsigned PhysReg,
1264 SmallVectorImpl<float> &GapWeight) {
1265 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1266 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1267 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1268 const unsigned NumGaps = Uses.size()-1;
1270 // Start and end points for the interference check.
1271 SlotIndex StartIdx =
1272 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1274 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
1276 GapWeight.assign(NumGaps, 0.0f);
1278 // Add interference from each overlapping register.
1279 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
1280 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
1281 .checkInterference())
1284 // We know that VirtReg is a continuous interval from FirstInstr to
1285 // LastInstr, so we don't need InterferenceQuery.
1287 // Interference that overlaps an instruction is counted in both gaps
1288 // surrounding the instruction. The exception is interference before
1289 // StartIdx and after StopIdx.
1291 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
1292 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1293 // Skip the gaps before IntI.
1294 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1295 if (++Gap == NumGaps)
1300 // Update the gaps covered by IntI.
1301 const float weight = IntI.value()->weight;
1302 for (; Gap != NumGaps; ++Gap) {
1303 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1304 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1313 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1316 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1317 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1318 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1319 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1321 // Note that it is possible to have an interval that is live-in or live-out
1322 // while only covering a single block - A phi-def can use undef values from
1323 // predecessors, and the block could be a single-block loop.
1324 // We don't bother doing anything clever about such a case, we simply assume
1325 // that the interval is continuous from FirstInstr to LastInstr. We should
1326 // make sure that we don't do anything illegal to such an interval, though.
1328 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1329 if (Uses.size() <= 2)
1331 const unsigned NumGaps = Uses.size()-1;
1334 dbgs() << "tryLocalSplit: ";
1335 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1336 dbgs() << ' ' << SA->UseSlots[i];
1340 // Since we allow local split results to be split again, there is a risk of
1341 // creating infinite loops. It is tempting to require that the new live
1342 // ranges have less instructions than the original. That would guarantee
1343 // convergence, but it is too strict. A live range with 3 instructions can be
1344 // split 2+3 (including the COPY), and we want to allow that.
1346 // Instead we use these rules:
1348 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
1349 // noop split, of course).
1350 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
1351 // the new ranges must have fewer instructions than before the split.
1352 // 3. New ranges with the same number of instructions are marked RS_Split2,
1353 // smaller ranges are marked RS_New.
1355 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1356 // excessive splitting and infinite loops.
1358 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
1360 // Best split candidate.
1361 unsigned BestBefore = NumGaps;
1362 unsigned BestAfter = 0;
1365 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
1366 SmallVector<float, 8> GapWeight;
1369 while (unsigned PhysReg = Order.next()) {
1370 // Keep track of the largest spill weight that would need to be evicted in
1371 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1372 calcGapWeights(PhysReg, GapWeight);
1374 // Try to find the best sequence of gaps to close.
1375 // The new spill weight must be larger than any gap interference.
1377 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1378 unsigned SplitBefore = 0, SplitAfter = 1;
1380 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1381 // It is the spill weight that needs to be evicted.
1382 float MaxGap = GapWeight[0];
1385 // Live before/after split?
1386 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1387 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1389 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1390 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1391 << " i=" << MaxGap);
1393 // Stop before the interval gets so big we wouldn't be making progress.
1394 if (!LiveBefore && !LiveAfter) {
1395 DEBUG(dbgs() << " all\n");
1398 // Should the interval be extended or shrunk?
1401 // How many gaps would the new range have?
1402 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1404 // Legally, without causing looping?
1405 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1407 if (Legal && MaxGap < HUGE_VALF) {
1408 // Estimate the new spill weight. Each instruction reads or writes the
1409 // register. Conservatively assume there are no read-modify-write
1412 // Try to guess the size of the new interval.
1413 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1414 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1415 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
1416 // Would this split be possible to allocate?
1417 // Never allocate all gaps, we wouldn't be making progress.
1418 DEBUG(dbgs() << " w=" << EstWeight);
1419 if (EstWeight * Hysteresis >= MaxGap) {
1421 float Diff = EstWeight - MaxGap;
1422 if (Diff > BestDiff) {
1423 DEBUG(dbgs() << " (best)");
1424 BestDiff = Hysteresis * Diff;
1425 BestBefore = SplitBefore;
1426 BestAfter = SplitAfter;
1433 if (++SplitBefore < SplitAfter) {
1434 DEBUG(dbgs() << " shrink\n");
1435 // Recompute the max when necessary.
1436 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1437 MaxGap = GapWeight[SplitBefore];
1438 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1439 MaxGap = std::max(MaxGap, GapWeight[i]);
1446 // Try to extend the interval.
1447 if (SplitAfter >= NumGaps) {
1448 DEBUG(dbgs() << " end\n");
1452 DEBUG(dbgs() << " extend\n");
1453 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
1457 // Didn't find any candidates?
1458 if (BestBefore == NumGaps)
1461 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1462 << '-' << Uses[BestAfter] << ", " << BestDiff
1463 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1465 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1469 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1470 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1471 SE->useIntv(SegStart, SegStop);
1472 SmallVector<unsigned, 8> IntvMap;
1473 SE->finish(&IntvMap);
1474 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1476 // If the new range has the same number of instructions as before, mark it as
1477 // RS_Split2 so the next split will be forced to make progress. Otherwise,
1478 // leave the new intervals as RS_New so they can compete.
1479 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1480 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1481 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1482 if (NewGaps >= NumGaps) {
1483 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1484 assert(!ProgressRequired && "Didn't make progress when it was required.");
1485 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1486 if (IntvMap[i] == 1) {
1487 setStage(*LREdit.get(i), RS_Split2);
1488 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1490 DEBUG(dbgs() << '\n');
1497 //===----------------------------------------------------------------------===//
1498 // Live Range Splitting
1499 //===----------------------------------------------------------------------===//
1501 /// trySplit - Try to split VirtReg or one of its interferences, making it
1503 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1504 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1505 SmallVectorImpl<LiveInterval*>&NewVRegs) {
1506 // Ranges must be Split2 or less.
1507 if (getStage(VirtReg) >= RS_Spill)
1510 // Local intervals are handled separately.
1511 if (LIS->intervalIsInOneMBB(VirtReg)) {
1512 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
1513 SA->analyze(&VirtReg);
1514 return tryLocalSplit(VirtReg, Order, NewVRegs);
1517 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
1519 SA->analyze(&VirtReg);
1521 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1522 // coalescer. That may cause the range to become allocatable which means that
1523 // tryRegionSplit won't be making progress. This check should be replaced with
1524 // an assertion when the coalescer is fixed.
1525 if (SA->didRepairRange()) {
1526 // VirtReg has changed, so all cached queries are invalid.
1527 invalidateVirtRegs();
1528 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1532 // First try to split around a region spanning multiple blocks. RS_Split2
1533 // ranges already made dubious progress with region splitting, so they go
1534 // straight to single block splitting.
1535 if (getStage(VirtReg) < RS_Split2) {
1536 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1537 if (PhysReg || !NewVRegs.empty())
1541 // Then isolate blocks.
1542 return tryBlockSplit(VirtReg, Order, NewVRegs);
1546 //===----------------------------------------------------------------------===//
1548 //===----------------------------------------------------------------------===//
1550 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
1551 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1552 // First try assigning a free register.
1553 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
1554 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1557 LiveRangeStage Stage = getStage(VirtReg);
1558 DEBUG(dbgs() << StageName[Stage]
1559 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
1561 // Try to evict a less worthy live range, but only for ranges from the primary
1562 // queue. The RS_Split ranges already failed to do this, and they should not
1563 // get a second chance until they have been split.
1564 if (Stage != RS_Split)
1565 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1568 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1570 // The first time we see a live range, don't try to split or spill.
1571 // Wait until the second time, when all smaller ranges have been allocated.
1572 // This gives a better picture of the interference to split around.
1573 if (Stage < RS_Split) {
1574 setStage(VirtReg, RS_Split);
1575 DEBUG(dbgs() << "wait for second round\n");
1576 NewVRegs.push_back(&VirtReg);
1580 // If we couldn't allocate a register from spilling, there is probably some
1581 // invalid inline assembly. The base class wil report it.
1582 if (Stage >= RS_Done || !VirtReg.isSpillable())
1585 // Try splitting VirtReg or interferences.
1586 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1587 if (PhysReg || !NewVRegs.empty())
1590 // Finally spill VirtReg itself.
1591 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
1592 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1593 spiller().spill(LRE);
1594 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
1597 MF->verify(this, "After spilling");
1599 // The live virtual register requesting allocation was spilled, so tell
1600 // the caller not to allocate anything during this round.
1604 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1605 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1606 << "********** Function: "
1607 << ((Value*)mf.getFunction())->getName() << '\n');
1611 MF->verify(this, "Before greedy register allocator");
1613 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
1614 Indexes = &getAnalysis<SlotIndexes>();
1615 DomTree = &getAnalysis<MachineDominatorTree>();
1616 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
1617 Loops = &getAnalysis<MachineLoopInfo>();
1618 Bundles = &getAnalysis<EdgeBundles>();
1619 SpillPlacer = &getAnalysis<SpillPlacement>();
1620 DebugVars = &getAnalysis<LiveDebugVariables>();
1622 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
1623 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
1624 ExtraRegInfo.clear();
1625 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1627 IntfCache.init(MF, &PhysReg2LiveUnion[0], Indexes, TRI);
1628 GlobalCand.resize(32); // This will grow as needed.
1632 LIS->addKillFlags();
1636 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
1637 VRM->rewrite(Indexes);
1640 // Write out new DBG_VALUE instructions.
1642 NamedRegionTimer T("Emit Debug Info", TimerGroupName, TimePassesIsEnabled);
1643 DebugVars->emitDebugValues(VRM);
1646 // The pass output is in VirtRegMap. Release all the transient data.