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 "RegisterCoalescer.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Function.h"
29 #include "llvm/PassAnalysisSupport.h"
30 #include "llvm/CodeGen/CalcSpillWeights.h"
31 #include "llvm/CodeGen/EdgeBundles.h"
32 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
33 #include "llvm/CodeGen/LiveStackAnalysis.h"
34 #include "llvm/CodeGen/MachineDominators.h"
35 #include "llvm/CodeGen/MachineFunctionPass.h"
36 #include "llvm/CodeGen/MachineLoopInfo.h"
37 #include "llvm/CodeGen/MachineLoopRanges.h"
38 #include "llvm/CodeGen/MachineRegisterInfo.h"
39 #include "llvm/CodeGen/Passes.h"
40 #include "llvm/CodeGen/RegAllocRegistry.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Support/Timer.h"
51 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
52 STATISTIC(NumLocalSplits, "Number of split local live ranges");
53 STATISTIC(NumEvicted, "Number of interferences evicted");
55 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
56 createGreedyRegisterAllocator);
59 class RAGreedy : public MachineFunctionPass,
61 private LiveRangeEdit::Delegate {
69 MachineDominatorTree *DomTree;
70 MachineLoopInfo *Loops;
71 MachineLoopRanges *LoopRanges;
73 SpillPlacement *SpillPlacer;
74 LiveDebugVariables *DebugVars;
77 std::auto_ptr<Spiller> SpillerInstance;
78 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
81 // Live ranges pass through a number of stages as we try to allocate them.
82 // Some of the stages may also create new live ranges:
84 // - Region splitting.
85 // - Per-block splitting.
89 // Ranges produced by one of the stages skip the previous stages when they are
90 // dequeued. This improves performance because we can skip interference checks
91 // that are unlikely to give any results. It also guarantees that the live
92 // range splitting algorithm terminates, something that is otherwise hard to
95 RS_New, ///< Never seen before.
96 RS_First, ///< First time in the queue.
97 RS_Second, ///< Second time in the queue.
98 RS_Global, ///< Produced by global splitting.
99 RS_Local, ///< Produced by local splitting.
100 RS_Spill ///< Produced by spilling.
103 static const char *const StageName[];
105 // RegInfo - Keep additional information about each live range.
107 LiveRangeStage Stage;
109 // Cascade - Eviction loop prevention. See canEvictInterference().
112 RegInfo() : Stage(RS_New), Cascade(0) {}
115 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
117 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
118 return ExtraRegInfo[VirtReg.reg].Stage;
121 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
122 ExtraRegInfo.resize(MRI->getNumVirtRegs());
123 ExtraRegInfo[VirtReg.reg].Stage = Stage;
126 template<typename Iterator>
127 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
128 ExtraRegInfo.resize(MRI->getNumVirtRegs());
129 for (;Begin != End; ++Begin) {
130 unsigned Reg = (*Begin)->reg;
131 if (ExtraRegInfo[Reg].Stage == RS_New)
132 ExtraRegInfo[Reg].Stage = NewStage;
137 std::auto_ptr<SplitAnalysis> SA;
138 std::auto_ptr<SplitEditor> SE;
140 /// Cached per-block interference maps
141 InterferenceCache IntfCache;
143 /// All basic blocks where the current register has uses.
144 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
146 /// Global live range splitting candidate info.
147 struct GlobalSplitCandidate {
149 BitVector LiveBundles;
150 SmallVector<unsigned, 8> ActiveBlocks;
152 void reset(unsigned Reg) {
155 ActiveBlocks.clear();
159 /// Candidate info for for each PhysReg in AllocationOrder.
160 /// This vector never shrinks, but grows to the size of the largest register
162 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
167 /// Return the pass name.
168 virtual const char* getPassName() const {
169 return "Greedy Register Allocator";
172 /// RAGreedy analysis usage.
173 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
174 virtual void releaseMemory();
175 virtual Spiller &spiller() { return *SpillerInstance; }
176 virtual void enqueue(LiveInterval *LI);
177 virtual LiveInterval *dequeue();
178 virtual unsigned selectOrSplit(LiveInterval&,
179 SmallVectorImpl<LiveInterval*>&);
181 /// Perform register allocation.
182 virtual bool runOnMachineFunction(MachineFunction &mf);
187 void LRE_WillEraseInstruction(MachineInstr*);
188 bool LRE_CanEraseVirtReg(unsigned);
189 void LRE_WillShrinkVirtReg(unsigned);
190 void LRE_DidCloneVirtReg(unsigned, unsigned);
192 float calcSpillCost();
193 bool addSplitConstraints(InterferenceCache::Cursor, float&);
194 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
195 void growRegion(GlobalSplitCandidate &Cand, InterferenceCache::Cursor);
196 float calcGlobalSplitCost(GlobalSplitCandidate&, InterferenceCache::Cursor);
197 void splitAroundRegion(LiveInterval&, GlobalSplitCandidate&,
198 SmallVectorImpl<LiveInterval*>&);
199 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
200 bool canEvict(LiveInterval &A, LiveInterval &B);
201 bool canEvictInterference(LiveInterval&, unsigned, float&);
203 unsigned tryAssign(LiveInterval&, AllocationOrder&,
204 SmallVectorImpl<LiveInterval*>&);
205 unsigned tryEvict(LiveInterval&, AllocationOrder&,
206 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
207 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
208 SmallVectorImpl<LiveInterval*>&);
209 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
210 SmallVectorImpl<LiveInterval*>&);
211 unsigned trySplit(LiveInterval&, AllocationOrder&,
212 SmallVectorImpl<LiveInterval*>&);
214 } // end anonymous namespace
216 char RAGreedy::ID = 0;
219 const char *const RAGreedy::StageName[] = {
229 // Hysteresis to use when comparing floats.
230 // This helps stabilize decisions based on float comparisons.
231 const float Hysteresis = 0.98f;
234 FunctionPass* llvm::createGreedyRegisterAllocator() {
235 return new RAGreedy();
238 RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
239 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
240 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
241 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
242 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
243 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
244 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
245 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
246 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
247 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
248 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
249 initializeMachineLoopRangesPass(*PassRegistry::getPassRegistry());
250 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
251 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
252 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
255 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
256 AU.setPreservesCFG();
257 AU.addRequired<AliasAnalysis>();
258 AU.addPreserved<AliasAnalysis>();
259 AU.addRequired<LiveIntervals>();
260 AU.addRequired<SlotIndexes>();
261 AU.addPreserved<SlotIndexes>();
262 AU.addRequired<LiveDebugVariables>();
263 AU.addPreserved<LiveDebugVariables>();
265 AU.addRequiredID(StrongPHIEliminationID);
266 AU.addRequiredTransitive<RegisterCoalescer>();
267 AU.addRequired<CalculateSpillWeights>();
268 AU.addRequired<LiveStacks>();
269 AU.addPreserved<LiveStacks>();
270 AU.addRequired<MachineDominatorTree>();
271 AU.addPreserved<MachineDominatorTree>();
272 AU.addRequired<MachineLoopInfo>();
273 AU.addPreserved<MachineLoopInfo>();
274 AU.addRequired<MachineLoopRanges>();
275 AU.addPreserved<MachineLoopRanges>();
276 AU.addRequired<VirtRegMap>();
277 AU.addPreserved<VirtRegMap>();
278 AU.addRequired<EdgeBundles>();
279 AU.addRequired<SpillPlacement>();
280 MachineFunctionPass::getAnalysisUsage(AU);
284 //===----------------------------------------------------------------------===//
285 // LiveRangeEdit delegate methods
286 //===----------------------------------------------------------------------===//
288 void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
289 // LRE itself will remove from SlotIndexes and parent basic block.
290 VRM->RemoveMachineInstrFromMaps(MI);
293 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
294 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
295 unassign(LIS->getInterval(VirtReg), PhysReg);
298 // Unassigned virtreg is probably in the priority queue.
299 // RegAllocBase will erase it after dequeueing.
303 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
304 unsigned PhysReg = VRM->getPhys(VirtReg);
308 // Register is assigned, put it back on the queue for reassignment.
309 LiveInterval &LI = LIS->getInterval(VirtReg);
310 unassign(LI, PhysReg);
314 void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
315 // LRE may clone a virtual register because dead code elimination causes it to
316 // be split into connected components. Ensure that the new register gets the
317 // same stage as the parent.
318 ExtraRegInfo.grow(New);
319 ExtraRegInfo[New] = ExtraRegInfo[Old];
322 void RAGreedy::releaseMemory() {
323 SpillerInstance.reset(0);
324 ExtraRegInfo.clear();
326 RegAllocBase::releaseMemory();
329 void RAGreedy::enqueue(LiveInterval *LI) {
330 // Prioritize live ranges by size, assigning larger ranges first.
331 // The queue holds (size, reg) pairs.
332 const unsigned Size = LI->getSize();
333 const unsigned Reg = LI->reg;
334 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
335 "Can only enqueue virtual registers");
338 ExtraRegInfo.grow(Reg);
339 if (ExtraRegInfo[Reg].Stage == RS_New)
340 ExtraRegInfo[Reg].Stage = RS_First;
342 if (ExtraRegInfo[Reg].Stage == RS_Second)
343 // Unsplit ranges that couldn't be allocated immediately are deferred until
344 // everything else has been allocated. Long ranges are allocated last so
345 // they are split against realistic interference.
346 Prio = (1u << 31) - Size;
348 // Everything else is allocated in long->short order. Long ranges that don't
349 // fit should be spilled ASAP so they don't create interference.
350 Prio = (1u << 31) + Size;
352 // Boost ranges that have a physical register hint.
353 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
357 Queue.push(std::make_pair(Prio, Reg));
360 LiveInterval *RAGreedy::dequeue() {
363 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
369 //===----------------------------------------------------------------------===//
371 //===----------------------------------------------------------------------===//
373 /// tryAssign - Try to assign VirtReg to an available register.
374 unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
375 AllocationOrder &Order,
376 SmallVectorImpl<LiveInterval*> &NewVRegs) {
379 while ((PhysReg = Order.next()))
380 if (!checkPhysRegInterference(VirtReg, PhysReg))
382 if (!PhysReg || Order.isHint(PhysReg))
385 // PhysReg is available. Try to evict interference from a cheaper alternative.
386 unsigned Cost = TRI->getCostPerUse(PhysReg);
388 // Most registers have 0 additional cost.
392 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
394 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
395 return CheapReg ? CheapReg : PhysReg;
399 //===----------------------------------------------------------------------===//
400 // Interference eviction
401 //===----------------------------------------------------------------------===//
403 /// canEvict - determine if A can evict the assigned live range B. The eviction
404 /// policy defined by this function together with the allocation order defined
405 /// by enqueue() decides which registers ultimately end up being split and
408 /// Cascade numbers are used to prevent infinite loops if this function is a
410 bool RAGreedy::canEvict(LiveInterval &A, LiveInterval &B) {
411 return A.weight > B.weight;
414 /// canEvict - Return true if all interferences between VirtReg and PhysReg can
416 /// Return false if any interference is heavier than MaxWeight.
417 /// On return, set MaxWeight to the maximal spill weight of an interference.
418 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
420 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
421 // involved in an eviction before. If a cascade number was assigned, deny
422 // evicting anything with the same or a newer cascade number. This prevents
423 // infinite eviction loops.
425 // This works out so a register without a cascade number is allowed to evict
426 // anything, and it can be evicted by anything.
427 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
429 Cascade = NextCascade;
432 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
433 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
434 // If there is 10 or more interferences, chances are one is heavier.
435 if (Q.collectInterferingVRegs(10, MaxWeight) >= 10)
438 // Check if any interfering live range is heavier than MaxWeight.
439 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
440 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
441 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
443 if (Cascade <= ExtraRegInfo[Intf->reg].Cascade)
445 if (Intf->weight >= MaxWeight)
447 if (!canEvict(VirtReg, *Intf))
449 Weight = std::max(Weight, Intf->weight);
456 /// tryEvict - Try to evict all interferences for a physreg.
457 /// @param VirtReg Currently unassigned virtual register.
458 /// @param Order Physregs to try.
459 /// @return Physreg to assign VirtReg, or 0.
460 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
461 AllocationOrder &Order,
462 SmallVectorImpl<LiveInterval*> &NewVRegs,
463 unsigned CostPerUseLimit) {
464 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
466 // Keep track of the lightest single interference seen so far.
467 float BestWeight = HUGE_VALF;
468 unsigned BestPhys = 0;
471 while (unsigned PhysReg = Order.next()) {
472 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
474 // The first use of a register in a function has cost 1.
475 if (CostPerUseLimit == 1 && !MRI->isPhysRegUsed(PhysReg))
478 float Weight = BestWeight;
479 if (!canEvictInterference(VirtReg, PhysReg, Weight))
482 // This is an eviction candidate.
483 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " interference = "
485 if (BestPhys && Weight >= BestWeight)
491 // Stop if the hint can be used.
492 if (Order.isHint(PhysReg))
499 // We will evict interference. Make sure that VirtReg has a cascade number,
500 // and assign that cascade number to every evicted register. These live
501 // ranges than then only be evicted by a newer cascade, preventing infinite
503 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
505 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
507 DEBUG(dbgs() << "evicting " << PrintReg(BestPhys, TRI)
508 << " interference: Cascade " << Cascade << '\n');
509 for (const unsigned *AliasI = TRI->getOverlaps(BestPhys); *AliasI; ++AliasI) {
510 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
511 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
512 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
513 LiveInterval *Intf = Q.interferingVRegs()[i];
514 unassign(*Intf, VRM->getPhys(Intf->reg));
515 assert(ExtraRegInfo[Intf->reg].Cascade < Cascade &&
516 "Cannot decrease cascade number, illegal eviction");
517 ExtraRegInfo[Intf->reg].Cascade = Cascade;
519 NewVRegs.push_back(Intf);
526 //===----------------------------------------------------------------------===//
528 //===----------------------------------------------------------------------===//
530 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
531 /// interference pattern in Physreg and its aliases. Add the constraints to
532 /// SpillPlacement and return the static cost of this split in Cost, assuming
533 /// that all preferences in SplitConstraints are met.
534 /// Return false if there are no bundles with positive bias.
535 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
537 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
539 // Reset interference dependent info.
540 SplitConstraints.resize(UseBlocks.size());
541 float StaticCost = 0;
542 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
543 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
544 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
546 BC.Number = BI.MBB->getNumber();
547 Intf.moveToBlock(BC.Number);
548 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
549 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
551 if (!Intf.hasInterference())
554 // Number of spill code instructions to insert.
557 // Interference for the live-in value.
559 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
560 BC.Entry = SpillPlacement::MustSpill, ++Ins;
561 else if (Intf.first() < BI.FirstUse)
562 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
563 else if (Intf.first() < BI.LastUse)
567 // Interference for the live-out value.
569 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
570 BC.Exit = SpillPlacement::MustSpill, ++Ins;
571 else if (Intf.last() > BI.LastUse)
572 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
573 else if (Intf.last() > BI.FirstUse)
577 // Accumulate the total frequency of inserted spill code.
579 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
583 // Add constraints for use-blocks. Note that these are the only constraints
584 // that may add a positive bias, it is downhill from here.
585 SpillPlacer->addConstraints(SplitConstraints);
586 return SpillPlacer->scanActiveBundles();
590 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
591 /// live-through blocks in Blocks.
592 void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
593 ArrayRef<unsigned> Blocks) {
594 const unsigned GroupSize = 8;
595 SpillPlacement::BlockConstraint BCS[GroupSize];
596 unsigned TBS[GroupSize];
597 unsigned B = 0, T = 0;
599 for (unsigned i = 0; i != Blocks.size(); ++i) {
600 unsigned Number = Blocks[i];
601 Intf.moveToBlock(Number);
603 if (!Intf.hasInterference()) {
604 assert(T < GroupSize && "Array overflow");
606 if (++T == GroupSize) {
607 SpillPlacer->addLinks(ArrayRef<unsigned>(TBS, T));
613 assert(B < GroupSize && "Array overflow");
614 BCS[B].Number = Number;
616 // Interference for the live-in value.
617 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
618 BCS[B].Entry = SpillPlacement::MustSpill;
620 BCS[B].Entry = SpillPlacement::PrefSpill;
622 // Interference for the live-out value.
623 if (Intf.last() >= SA->getLastSplitPoint(Number))
624 BCS[B].Exit = SpillPlacement::MustSpill;
626 BCS[B].Exit = SpillPlacement::PrefSpill;
628 if (++B == GroupSize) {
629 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
630 SpillPlacer->addConstraints(Array);
635 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
636 SpillPlacer->addConstraints(Array);
637 SpillPlacer->addLinks(ArrayRef<unsigned>(TBS, T));
640 void RAGreedy::growRegion(GlobalSplitCandidate &Cand,
641 InterferenceCache::Cursor Intf) {
642 // Keep track of through blocks that have not been added to SpillPlacer.
643 BitVector Todo = SA->getThroughBlocks();
644 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
645 unsigned AddedTo = 0;
647 unsigned Visited = 0;
651 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
652 if (NewBundles.empty())
654 // Find new through blocks in the periphery of PrefRegBundles.
655 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
656 unsigned Bundle = NewBundles[i];
657 // Look at all blocks connected to Bundle in the full graph.
658 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
659 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
662 if (!Todo.test(Block))
665 // This is a new through block. Add it to SpillPlacer later.
666 ActiveBlocks.push_back(Block);
672 // Any new blocks to add?
673 if (ActiveBlocks.size() > AddedTo) {
674 ArrayRef<unsigned> Add(&ActiveBlocks[AddedTo],
675 ActiveBlocks.size() - AddedTo);
676 addThroughConstraints(Intf, Add);
677 AddedTo = ActiveBlocks.size();
679 // Perhaps iterating can enable more bundles?
680 SpillPlacer->iterate();
682 DEBUG(dbgs() << ", v=" << Visited);
685 /// calcSpillCost - Compute how expensive it would be to split the live range in
686 /// SA around all use blocks instead of forming bundle regions.
687 float RAGreedy::calcSpillCost() {
689 const LiveInterval &LI = SA->getParent();
690 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
691 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
692 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
693 unsigned Number = BI.MBB->getNumber();
694 // We normally only need one spill instruction - a load or a store.
695 Cost += SpillPlacer->getBlockFrequency(Number);
697 // Unless the value is redefined in the block.
698 if (BI.LiveIn && BI.LiveOut) {
699 SlotIndex Start, Stop;
700 tie(Start, Stop) = Indexes->getMBBRange(Number);
701 LiveInterval::const_iterator I = LI.find(Start);
702 assert(I != LI.end() && "Expected live-in value");
703 // Is there a different live-out value? If so, we need an extra spill
706 Cost += SpillPlacer->getBlockFrequency(Number);
712 /// calcGlobalSplitCost - Return the global split cost of following the split
713 /// pattern in LiveBundles. This cost should be added to the local cost of the
714 /// interference pattern in SplitConstraints.
716 float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand,
717 InterferenceCache::Cursor Intf) {
718 float GlobalCost = 0;
719 const BitVector &LiveBundles = Cand.LiveBundles;
720 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
721 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
722 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
723 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
724 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
725 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
729 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
731 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
733 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
736 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
737 unsigned Number = Cand.ActiveBlocks[i];
738 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
739 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
740 if (!RegIn && !RegOut)
742 if (RegIn && RegOut) {
743 // We need double spill code if this block has interference.
744 Intf.moveToBlock(Number);
745 if (Intf.hasInterference())
746 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
749 // live-in / stack-out or stack-in live-out.
750 GlobalCost += SpillPlacer->getBlockFrequency(Number);
755 /// splitAroundRegion - Split VirtReg around the region determined by
756 /// LiveBundles. Make an effort to avoid interference from PhysReg.
758 /// The 'register' interval is going to contain as many uses as possible while
759 /// avoiding interference. The 'stack' interval is the complement constructed by
760 /// SplitEditor. It will contain the rest.
762 void RAGreedy::splitAroundRegion(LiveInterval &VirtReg,
763 GlobalSplitCandidate &Cand,
764 SmallVectorImpl<LiveInterval*> &NewVRegs) {
765 const BitVector &LiveBundles = Cand.LiveBundles;
768 dbgs() << "Splitting around region for " << PrintReg(Cand.PhysReg, TRI)
770 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
771 dbgs() << " EB#" << i;
775 InterferenceCache::Cursor Intf(IntfCache, Cand.PhysReg);
776 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
779 // Create the main cross-block interval.
780 const unsigned MainIntv = SE->openIntv();
782 // First handle all the blocks with uses.
783 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
784 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
785 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
786 bool RegIn = BI.LiveIn &&
787 LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
788 bool RegOut = BI.LiveOut &&
789 LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
791 // Create separate intervals for isolated blocks with multiple uses.
793 // |---o---o---| Enter and leave on the stack.
794 // ____-----____ Create local interval for uses.
796 // | o---o---| Defined in block, leave on stack.
797 // -----____ Create local interval for uses.
799 // |---o---x | Enter on stack, killed in block.
800 // ____----- Create local interval for uses.
802 if (!RegIn && !RegOut) {
803 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
804 if (!BI.isOneInstr()) {
805 SE->splitSingleBlock(BI);
806 SE->selectIntv(MainIntv);
811 SlotIndex Start, Stop;
812 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
813 Intf.moveToBlock(BI.MBB->getNumber());
814 DEBUG(dbgs() << "EB#" << Bundles->getBundle(BI.MBB->getNumber(), 0)
815 << (BI.LiveIn ? (RegIn ? " => " : " -> ") : " ")
816 << "BB#" << BI.MBB->getNumber()
817 << (BI.LiveOut ? (RegOut ? " => " : " -> ") : " ")
818 << " EB#" << Bundles->getBundle(BI.MBB->getNumber(), 1)
819 << " [" << Start << ';'
820 << SA->getLastSplitPoint(BI.MBB->getNumber()) << '-' << Stop
821 << ") uses [" << BI.FirstUse << ';' << BI.LastUse
822 << ") intf [" << Intf.first() << ';' << Intf.last() << ')');
824 // The interference interval should either be invalid or overlap MBB.
825 assert((!Intf.hasInterference() || Intf.first() < Stop)
826 && "Bad interference");
827 assert((!Intf.hasInterference() || Intf.last() > Start)
828 && "Bad interference");
830 // We are now ready to decide where to split in the current block. There
831 // are many variables guiding the decision:
833 // - RegIn / RegOut: The global splitting algorithm's decisions for our
834 // ingoing and outgoing bundles.
836 // - BI.BlockIn / BI.BlockOut: Is the live range live-in and/or live-out
839 // - Intf.hasInterference(): Is there interference in this block.
841 // - Intf.first() / Inft.last(): The range of interference.
843 // The live range should be split such that MainIntv is live-in when RegIn
844 // is set, and live-out when RegOut is set. MainIntv should never overlap
845 // the interference, and the stack interval should never have more than one
848 // No splits can be inserted after LastSplitPoint, overlap instead.
849 SlotIndex LastSplitPoint = Stop;
851 LastSplitPoint = SA->getLastSplitPoint(BI.MBB->getNumber());
853 // At this point, we know that either RegIn or RegOut is set. We dealt with
854 // the all-stack case above.
856 // Blocks without interference are relatively easy.
857 if (!Intf.hasInterference()) {
858 DEBUG(dbgs() << ", no interference.\n");
859 SE->selectIntv(MainIntv);
860 // The easiest case has MainIntv live through.
862 // |---o---o---| Live-in, live-out.
863 // ============= Use MainIntv everywhere.
865 SlotIndex From = Start, To = Stop;
867 // Block entry. Reload before the first use if MainIntv is not live-in.
869 // |---o-- Enter on stack.
870 // ____=== Reload before first use.
872 // | o-- Defined in block.
873 // === Use MainIntv from def.
876 From = SE->enterIntvBefore(BI.FirstUse);
878 // Block exit. Handle cases where MainIntv is not live-out.
881 // --x | Killed in block.
882 // === Use MainIntv up to kill.
884 To = SE->leaveIntvAfter(BI.LastUse);
887 // --o---| Live-out on stack.
888 // ===____ Use MainIntv up to last use, switch to stack.
890 // -----o| Live-out on stack, last use after last split point.
891 // ====== Extend MainIntv to last use, overlapping.
892 // \____ Copy to stack interval before last split point.
894 if (BI.LastUse < LastSplitPoint)
895 To = SE->leaveIntvAfter(BI.LastUse);
897 // The last use is after the last split point, it is probably an
899 To = SE->leaveIntvBefore(LastSplitPoint);
900 // Run a double interval from the split to the last use. This makes
901 // it possible to spill the complement without affecting the indirect
903 SE->overlapIntv(To, BI.LastUse);
907 // Paint in MainIntv liveness for this block.
908 SE->useIntv(From, To);
912 // We are now looking at a block with interference, and we know that either
913 // RegIn or RegOut is set.
914 assert(Intf.hasInterference() && (RegIn || RegOut) && "Bad invariant");
916 // If the live range is not live through the block, it is possible that the
917 // interference doesn't even overlap. Deal with those cases first. Since
918 // no copy instructions are required, we can tolerate interference starting
919 // or ending at the same instruction that kills or defines our live range.
921 // Live-in, killed before interference.
923 // ~~~ Interference after kill.
924 // |---o---x | Killed in block.
925 // ========= Use MainIntv everywhere.
927 if (RegIn && !BI.LiveOut && BI.LastUse <= Intf.first()) {
928 DEBUG(dbgs() << ", live-in, killed before interference.\n");
929 SE->selectIntv(MainIntv);
930 SlotIndex To = SE->leaveIntvAfter(BI.LastUse);
931 SE->useIntv(Start, To);
935 // Live-out, defined after interference.
937 // ~~~ Interference before def.
938 // | o---o---| Defined in block.
939 // ========= Use MainIntv everywhere.
941 if (RegOut && !BI.LiveIn && BI.FirstUse >= Intf.last()) {
942 DEBUG(dbgs() << ", live-out, defined after interference.\n");
943 SE->selectIntv(MainIntv);
944 SlotIndex From = SE->enterIntvBefore(BI.FirstUse);
945 SE->useIntv(From, Stop);
949 // The interference is now known to overlap the live range, but it may
950 // still be easy to avoid if all the interference is on one side of the
951 // uses, and we enter or leave on the stack.
953 // Live-out on stack, interference after last use.
955 // ~~~ Interference after last use.
956 // |---o---o---| Live-out on stack.
957 // =========____ Leave MainIntv after last use.
959 // ~ Interference after last use.
960 // |---o---o--o| Live-out on stack, late last use.
961 // ============ Copy to stack after LSP, overlap MainIntv.
962 // \_____ Stack interval is live-out.
964 if (!RegOut && Intf.first() > BI.LastUse.getBoundaryIndex()) {
965 assert(RegIn && "Stack-in, stack-out should already be handled");
966 if (BI.LastUse < LastSplitPoint) {
967 DEBUG(dbgs() << ", live-in, stack-out, interference after last use.\n");
968 SE->selectIntv(MainIntv);
969 SlotIndex To = SE->leaveIntvAfter(BI.LastUse);
970 assert(To <= Intf.first() && "Expected to avoid interference");
971 SE->useIntv(Start, To);
973 DEBUG(dbgs() << ", live-in, stack-out, avoid last split point\n");
974 SE->selectIntv(MainIntv);
975 SlotIndex To = SE->leaveIntvBefore(LastSplitPoint);
976 assert(To <= Intf.first() && "Expected to avoid interference");
977 SE->overlapIntv(To, BI.LastUse);
978 SE->useIntv(Start, To);
983 // Live-in on stack, interference before first use.
985 // ~~~ Interference before first use.
986 // |---o---o---| Live-in on stack.
987 // ____========= Enter MainIntv before first use.
989 if (!RegIn && Intf.last() < BI.FirstUse.getBaseIndex()) {
990 assert(RegOut && "Stack-in, stack-out should already be handled");
991 DEBUG(dbgs() << ", stack-in, interference before first use.\n");
992 SE->selectIntv(MainIntv);
993 SlotIndex From = SE->enterIntvBefore(BI.FirstUse);
994 assert(From >= Intf.last() && "Expected to avoid interference");
995 SE->useIntv(From, Stop);
999 // The interference is overlapping somewhere we wanted to use MainIntv. That
1000 // means we need to create a local interval that can be allocated a
1001 // different register.
1002 unsigned LocalIntv = SE->openIntv();
1003 DEBUG(dbgs() << ", creating local interval " << LocalIntv << ".\n");
1005 // We may be creating copies directly between MainIntv and LocalIntv,
1006 // bypassing the stack interval. When we do that, we should never use the
1007 // leaveIntv* methods as they define values in the stack interval. By
1008 // starting from the end of the block and working our way backwards, we can
1009 // get by with only enterIntv* methods.
1011 // When selecting split points, we generally try to maximize the stack
1012 // interval as long at it contains no uses, maximize the main interval as
1013 // long as it doesn't overlap interference, and minimize the local interval
1014 // that we don't know how to allocate yet.
1016 // Handle the block exit, set Pos to the first handled slot.
1017 SlotIndex Pos = BI.LastUse;
1019 assert(Intf.last() < LastSplitPoint && "Cannot be live-out in register");
1020 // Create a snippet of MainIntv that is live-out.
1022 // ~~~ Interference overlapping uses.
1023 // --o---| Live-out in MainIntv.
1024 // ----=== Switch from LocalIntv to MainIntv after interference.
1026 SE->selectIntv(MainIntv);
1027 Pos = SE->enterIntvAfter(Intf.last());
1028 assert(Pos >= Intf.last() && "Expected to avoid interference");
1029 SE->useIntv(Pos, Stop);
1030 SE->selectIntv(LocalIntv);
1031 } else if (BI.LiveOut) {
1032 if (BI.LastUse < LastSplitPoint) {
1033 // Live-out on the stack.
1035 // ~~~ Interference overlapping uses.
1036 // --o---| Live-out on stack.
1037 // ---____ Switch from LocalIntv to stack after last use.
1039 Pos = SE->leaveIntvAfter(BI.LastUse);
1041 // Live-out on the stack, last use after last split point.
1043 // ~~~ Interference overlapping uses.
1044 // --o--o| Live-out on stack, late use.
1045 // ------ Copy to stack before LSP, overlap LocalIntv.
1048 Pos = SE->leaveIntvBefore(LastSplitPoint);
1049 // We need to overlap LocalIntv so it can reach LastUse.
1050 SE->overlapIntv(Pos, BI.LastUse);
1054 // When not live-out, leave Pos at LastUse. We have handled everything from
1055 // Pos to Stop. Find the starting point for LocalIntv.
1056 assert(SE->currentIntv() == LocalIntv && "Expecting local interval");
1059 assert(Start < Intf.first() && "Cannot be live-in with interference");
1060 // Live-in in MainIntv, only use LocalIntv for interference.
1062 // ~~~ Interference overlapping uses.
1063 // |---o-- Live-in in MainIntv.
1064 // ====--- Switch to LocalIntv before interference.
1066 SlotIndex Switch = SE->enterIntvBefore(std::min(Pos, Intf.first()));
1067 assert(Switch <= Intf.first() && "Expected to avoid interference");
1068 SE->useIntv(Switch, Pos);
1069 SE->selectIntv(MainIntv);
1070 SE->useIntv(Start, Switch);
1072 // Live-in on stack, enter LocalIntv before first use.
1074 // ~~~ Interference overlapping uses.
1075 // |---o-- Live-in in MainIntv.
1076 // ____--- Reload to LocalIntv before interference.
1078 // Defined in block.
1080 // ~~~ Interference overlapping uses.
1081 // | o-- Defined in block.
1082 // --- Begin LocalIntv at first use.
1084 SlotIndex Switch = SE->enterIntvBefore(std::min(Pos, BI.FirstUse));
1085 SE->useIntv(Switch, Pos);
1089 // Handle live-through blocks.
1090 SE->selectIntv(MainIntv);
1091 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1092 unsigned Number = Cand.ActiveBlocks[i];
1093 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
1094 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
1095 DEBUG(dbgs() << "Live through BB#" << Number << '\n');
1096 if (RegIn && RegOut) {
1097 Intf.moveToBlock(Number);
1098 if (!Intf.hasInterference()) {
1099 SE->useIntv(Indexes->getMBBStartIdx(Number),
1100 Indexes->getMBBEndIdx(Number));
1104 MachineBasicBlock *MBB = MF->getBlockNumbered(Number);
1106 SE->leaveIntvAtTop(*MBB);
1108 SE->enterIntvAtEnd(*MBB);
1113 SmallVector<unsigned, 8> IntvMap;
1114 SE->finish(&IntvMap);
1115 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1117 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1118 unsigned OrigBlocks = SA->getNumLiveBlocks();
1120 // Sort out the new intervals created by splitting. We get four kinds:
1121 // - Remainder intervals should not be split again.
1122 // - Candidate intervals can be assigned to Cand.PhysReg.
1123 // - Block-local splits are candidates for local splitting.
1124 // - DCE leftovers should go back on the queue.
1125 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1126 LiveInterval &Reg = *LREdit.get(i);
1128 // Ignore old intervals from DCE.
1129 if (getStage(Reg) != RS_New)
1132 // Remainder interval. Don't try splitting again, spill if it doesn't
1134 if (IntvMap[i] == 0) {
1135 setStage(Reg, RS_Global);
1139 // Main interval. Allow repeated splitting as long as the number of live
1140 // blocks is strictly decreasing.
1141 if (IntvMap[i] == MainIntv) {
1142 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1143 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1144 << " blocks as original.\n");
1145 // Don't allow repeated splitting as a safe guard against looping.
1146 setStage(Reg, RS_Global);
1151 // Other intervals are treated as new. This includes local intervals created
1152 // for blocks with multiple uses, and anything created by DCE.
1156 MF->verify(this, "After splitting live range around region");
1159 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1160 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1161 float BestCost = Hysteresis * calcSpillCost();
1162 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1163 const unsigned NoCand = ~0u;
1164 unsigned BestCand = NoCand;
1167 for (unsigned Cand = 0; unsigned PhysReg = Order.next(); ++Cand) {
1168 if (GlobalCand.size() <= Cand)
1169 GlobalCand.resize(Cand+1);
1170 GlobalCand[Cand].reset(PhysReg);
1172 SpillPlacer->prepare(GlobalCand[Cand].LiveBundles);
1174 InterferenceCache::Cursor Intf(IntfCache, PhysReg);
1175 if (!addSplitConstraints(Intf, Cost)) {
1176 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
1179 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
1180 if (Cost >= BestCost) {
1182 if (BestCand == NoCand)
1183 dbgs() << " worse than no bundles\n";
1185 dbgs() << " worse than "
1186 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1190 growRegion(GlobalCand[Cand], Intf);
1192 SpillPlacer->finish();
1194 // No live bundles, defer to splitSingleBlocks().
1195 if (!GlobalCand[Cand].LiveBundles.any()) {
1196 DEBUG(dbgs() << " no bundles.\n");
1200 Cost += calcGlobalSplitCost(GlobalCand[Cand], Intf);
1202 dbgs() << ", total = " << Cost << " with bundles";
1203 for (int i = GlobalCand[Cand].LiveBundles.find_first(); i>=0;
1204 i = GlobalCand[Cand].LiveBundles.find_next(i))
1205 dbgs() << " EB#" << i;
1208 if (Cost < BestCost) {
1210 BestCost = Hysteresis * Cost; // Prevent rounding effects.
1214 if (BestCand == NoCand)
1217 splitAroundRegion(VirtReg, GlobalCand[BestCand], NewVRegs);
1222 //===----------------------------------------------------------------------===//
1224 //===----------------------------------------------------------------------===//
1227 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1228 /// in order to use PhysReg between two entries in SA->UseSlots.
1230 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1232 void RAGreedy::calcGapWeights(unsigned PhysReg,
1233 SmallVectorImpl<float> &GapWeight) {
1234 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1235 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1236 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1237 const unsigned NumGaps = Uses.size()-1;
1239 // Start and end points for the interference check.
1240 SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
1241 SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
1243 GapWeight.assign(NumGaps, 0.0f);
1245 // Add interference from each overlapping register.
1246 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
1247 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
1248 .checkInterference())
1251 // We know that VirtReg is a continuous interval from FirstUse to LastUse,
1252 // so we don't need InterferenceQuery.
1254 // Interference that overlaps an instruction is counted in both gaps
1255 // surrounding the instruction. The exception is interference before
1256 // StartIdx and after StopIdx.
1258 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
1259 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1260 // Skip the gaps before IntI.
1261 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1262 if (++Gap == NumGaps)
1267 // Update the gaps covered by IntI.
1268 const float weight = IntI.value()->weight;
1269 for (; Gap != NumGaps; ++Gap) {
1270 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1271 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1280 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1283 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1284 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1285 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1286 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1288 // Note that it is possible to have an interval that is live-in or live-out
1289 // while only covering a single block - A phi-def can use undef values from
1290 // predecessors, and the block could be a single-block loop.
1291 // We don't bother doing anything clever about such a case, we simply assume
1292 // that the interval is continuous from FirstUse to LastUse. We should make
1293 // sure that we don't do anything illegal to such an interval, though.
1295 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1296 if (Uses.size() <= 2)
1298 const unsigned NumGaps = Uses.size()-1;
1301 dbgs() << "tryLocalSplit: ";
1302 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1303 dbgs() << ' ' << SA->UseSlots[i];
1307 // Since we allow local split results to be split again, there is a risk of
1308 // creating infinite loops. It is tempting to require that the new live
1309 // ranges have less instructions than the original. That would guarantee
1310 // convergence, but it is too strict. A live range with 3 instructions can be
1311 // split 2+3 (including the COPY), and we want to allow that.
1313 // Instead we use these rules:
1315 // 1. Allow any split for ranges with getStage() < RS_Local. (Except for the
1316 // noop split, of course).
1317 // 2. Require progress be made for ranges with getStage() >= RS_Local. All
1318 // the new ranges must have fewer instructions than before the split.
1319 // 3. New ranges with the same number of instructions are marked RS_Local,
1320 // smaller ranges are marked RS_New.
1322 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1323 // excessive splitting and infinite loops.
1325 bool ProgressRequired = getStage(VirtReg) >= RS_Local;
1327 // Best split candidate.
1328 unsigned BestBefore = NumGaps;
1329 unsigned BestAfter = 0;
1332 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
1333 SmallVector<float, 8> GapWeight;
1336 while (unsigned PhysReg = Order.next()) {
1337 // Keep track of the largest spill weight that would need to be evicted in
1338 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1339 calcGapWeights(PhysReg, GapWeight);
1341 // Try to find the best sequence of gaps to close.
1342 // The new spill weight must be larger than any gap interference.
1344 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1345 unsigned SplitBefore = 0, SplitAfter = 1;
1347 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1348 // It is the spill weight that needs to be evicted.
1349 float MaxGap = GapWeight[0];
1352 // Live before/after split?
1353 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1354 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1356 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1357 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1358 << " i=" << MaxGap);
1360 // Stop before the interval gets so big we wouldn't be making progress.
1361 if (!LiveBefore && !LiveAfter) {
1362 DEBUG(dbgs() << " all\n");
1365 // Should the interval be extended or shrunk?
1368 // How many gaps would the new range have?
1369 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1371 // Legally, without causing looping?
1372 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1374 if (Legal && MaxGap < HUGE_VALF) {
1375 // Estimate the new spill weight. Each instruction reads or writes the
1376 // register. Conservatively assume there are no read-modify-write
1379 // Try to guess the size of the new interval.
1380 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1381 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1382 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
1383 // Would this split be possible to allocate?
1384 // Never allocate all gaps, we wouldn't be making progress.
1385 DEBUG(dbgs() << " w=" << EstWeight);
1386 if (EstWeight * Hysteresis >= MaxGap) {
1388 float Diff = EstWeight - MaxGap;
1389 if (Diff > BestDiff) {
1390 DEBUG(dbgs() << " (best)");
1391 BestDiff = Hysteresis * Diff;
1392 BestBefore = SplitBefore;
1393 BestAfter = SplitAfter;
1400 if (++SplitBefore < SplitAfter) {
1401 DEBUG(dbgs() << " shrink\n");
1402 // Recompute the max when necessary.
1403 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1404 MaxGap = GapWeight[SplitBefore];
1405 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1406 MaxGap = std::max(MaxGap, GapWeight[i]);
1413 // Try to extend the interval.
1414 if (SplitAfter >= NumGaps) {
1415 DEBUG(dbgs() << " end\n");
1419 DEBUG(dbgs() << " extend\n");
1420 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
1424 // Didn't find any candidates?
1425 if (BestBefore == NumGaps)
1428 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1429 << '-' << Uses[BestAfter] << ", " << BestDiff
1430 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1432 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1436 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1437 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1438 SE->useIntv(SegStart, SegStop);
1439 SmallVector<unsigned, 8> IntvMap;
1440 SE->finish(&IntvMap);
1441 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1443 // If the new range has the same number of instructions as before, mark it as
1444 // RS_Local so the next split will be forced to make progress. Otherwise,
1445 // leave the new intervals as RS_New so they can compete.
1446 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1447 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1448 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1449 if (NewGaps >= NumGaps) {
1450 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1451 assert(!ProgressRequired && "Didn't make progress when it was required.");
1452 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1453 if (IntvMap[i] == 1) {
1454 setStage(*LREdit.get(i), RS_Local);
1455 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1457 DEBUG(dbgs() << '\n');
1464 //===----------------------------------------------------------------------===//
1465 // Live Range Splitting
1466 //===----------------------------------------------------------------------===//
1468 /// trySplit - Try to split VirtReg or one of its interferences, making it
1470 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1471 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1472 SmallVectorImpl<LiveInterval*>&NewVRegs) {
1473 // Local intervals are handled separately.
1474 if (LIS->intervalIsInOneMBB(VirtReg)) {
1475 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
1476 SA->analyze(&VirtReg);
1477 return tryLocalSplit(VirtReg, Order, NewVRegs);
1480 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
1482 // Don't iterate global splitting.
1483 // Move straight to spilling if this range was produced by a global split.
1484 if (getStage(VirtReg) >= RS_Global)
1487 SA->analyze(&VirtReg);
1489 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1490 // coalescer. That may cause the range to become allocatable which means that
1491 // tryRegionSplit won't be making progress. This check should be replaced with
1492 // an assertion when the coalescer is fixed.
1493 if (SA->didRepairRange()) {
1494 // VirtReg has changed, so all cached queries are invalid.
1495 invalidateVirtRegs();
1496 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1500 // First try to split around a region spanning multiple blocks.
1501 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1502 if (PhysReg || !NewVRegs.empty())
1505 // Then isolate blocks with multiple uses.
1506 SplitAnalysis::BlockPtrSet Blocks;
1507 if (SA->getMultiUseBlocks(Blocks)) {
1508 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1510 SE->splitSingleBlocks(Blocks);
1511 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Global);
1513 MF->verify(this, "After splitting live range around basic blocks");
1516 // Don't assign any physregs.
1521 //===----------------------------------------------------------------------===//
1523 //===----------------------------------------------------------------------===//
1525 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
1526 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1527 // First try assigning a free register.
1528 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
1529 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1532 LiveRangeStage Stage = getStage(VirtReg);
1533 DEBUG(dbgs() << StageName[Stage]
1534 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
1536 // Try to evict a less worthy live range, but only for ranges from the primary
1537 // queue. The RS_Second ranges already failed to do this, and they should not
1538 // get a second chance until they have been split.
1539 if (Stage != RS_Second)
1540 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1543 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1545 // The first time we see a live range, don't try to split or spill.
1546 // Wait until the second time, when all smaller ranges have been allocated.
1547 // This gives a better picture of the interference to split around.
1548 if (Stage == RS_First) {
1549 setStage(VirtReg, RS_Second);
1550 DEBUG(dbgs() << "wait for second round\n");
1551 NewVRegs.push_back(&VirtReg);
1555 // If we couldn't allocate a register from spilling, there is probably some
1556 // invalid inline assembly. The base class wil report it.
1557 if (Stage >= RS_Spill)
1560 // Try splitting VirtReg or interferences.
1561 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1562 if (PhysReg || !NewVRegs.empty())
1565 // Finally spill VirtReg itself.
1566 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
1567 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1568 spiller().spill(LRE);
1569 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Spill);
1572 MF->verify(this, "After spilling");
1574 // The live virtual register requesting allocation was spilled, so tell
1575 // the caller not to allocate anything during this round.
1579 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1580 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1581 << "********** Function: "
1582 << ((Value*)mf.getFunction())->getName() << '\n');
1586 MF->verify(this, "Before greedy register allocator");
1588 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
1589 Indexes = &getAnalysis<SlotIndexes>();
1590 DomTree = &getAnalysis<MachineDominatorTree>();
1591 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
1592 Loops = &getAnalysis<MachineLoopInfo>();
1593 LoopRanges = &getAnalysis<MachineLoopRanges>();
1594 Bundles = &getAnalysis<EdgeBundles>();
1595 SpillPlacer = &getAnalysis<SpillPlacement>();
1596 DebugVars = &getAnalysis<LiveDebugVariables>();
1598 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
1599 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
1600 ExtraRegInfo.clear();
1601 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1603 IntfCache.init(MF, &PhysReg2LiveUnion[0], Indexes, TRI);
1607 LIS->addKillFlags();
1611 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
1612 VRM->rewrite(Indexes);
1615 // Write out new DBG_VALUE instructions.
1616 DebugVars->emitDebugValues(VRM);
1618 // The pass output is in VirtRegMap. Release all the transient data.