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/MachineLoopRanges.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/Passes.h"
39 #include "llvm/CodeGen/RegAllocRegistry.h"
40 #include "llvm/CodeGen/RegisterCoalescer.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 {
65 BitVector ReservedRegs;
70 MachineDominatorTree *DomTree;
71 MachineLoopInfo *Loops;
72 MachineLoopRanges *LoopRanges;
74 SpillPlacement *SpillPlacer;
77 std::auto_ptr<Spiller> SpillerInstance;
78 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
80 // Live ranges pass through a number of stages as we try to allocate them.
81 // Some of the stages may also create new live ranges:
83 // - Region splitting.
84 // - Per-block splitting.
88 // Ranges produced by one of the stages skip the previous stages when they are
89 // dequeued. This improves performance because we can skip interference checks
90 // that are unlikely to give any results. It also guarantees that the live
91 // range splitting algorithm terminates, something that is otherwise hard to
94 RS_New, ///< Never seen before.
95 RS_First, ///< First time in the queue.
96 RS_Second, ///< Second time in the queue.
97 RS_Global, ///< Produced by global splitting.
98 RS_Local, ///< Produced by local splitting.
99 RS_Spill ///< Produced by spilling.
102 IndexedMap<unsigned char, VirtReg2IndexFunctor> LRStage;
104 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
105 return LiveRangeStage(LRStage[VirtReg.reg]);
108 template<typename Iterator>
109 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
110 LRStage.resize(MRI->getNumVirtRegs());
111 for (;Begin != End; ++Begin) {
112 unsigned Reg = (*Begin)->reg;
113 if (LRStage[Reg] == RS_New)
114 LRStage[Reg] = NewStage;
119 std::auto_ptr<SplitAnalysis> SA;
120 std::auto_ptr<SplitEditor> SE;
122 /// Cached per-block interference maps
123 InterferenceCache IntfCache;
125 /// All basic blocks where the current register has uses.
126 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
128 /// Global live range splitting candidate info.
129 struct GlobalSplitCandidate {
131 BitVector LiveBundles;
132 SmallVector<unsigned, 8> ActiveBlocks;
134 void reset(unsigned Reg) {
137 ActiveBlocks.clear();
141 /// Candidate info for for each PhysReg in AllocationOrder.
142 /// This vector never shrinks, but grows to the size of the largest register
144 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
146 /// For every instruction in SA->UseSlots, store the previous non-copy
148 SmallVector<SlotIndex, 8> PrevSlot;
153 /// Return the pass name.
154 virtual const char* getPassName() const {
155 return "Greedy Register Allocator";
158 /// RAGreedy analysis usage.
159 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
160 virtual void releaseMemory();
161 virtual Spiller &spiller() { return *SpillerInstance; }
162 virtual void enqueue(LiveInterval *LI);
163 virtual LiveInterval *dequeue();
164 virtual unsigned selectOrSplit(LiveInterval&,
165 SmallVectorImpl<LiveInterval*>&);
167 /// Perform register allocation.
168 virtual bool runOnMachineFunction(MachineFunction &mf);
173 void LRE_WillEraseInstruction(MachineInstr*);
174 bool LRE_CanEraseVirtReg(unsigned);
175 void LRE_WillShrinkVirtReg(unsigned);
176 void LRE_DidCloneVirtReg(unsigned, unsigned);
178 float calcSpillCost();
179 bool addSplitConstraints(InterferenceCache::Cursor, float&);
180 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
181 void growRegion(GlobalSplitCandidate &Cand, InterferenceCache::Cursor);
182 float calcGlobalSplitCost(GlobalSplitCandidate&, InterferenceCache::Cursor);
183 void splitAroundRegion(LiveInterval&, GlobalSplitCandidate&,
184 SmallVectorImpl<LiveInterval*>&);
185 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
186 SlotIndex getPrevMappedIndex(const MachineInstr*);
187 void calcPrevSlots();
188 unsigned nextSplitPoint(unsigned);
189 bool canEvictInterference(LiveInterval&, unsigned, float&);
191 unsigned tryAssign(LiveInterval&, AllocationOrder&,
192 SmallVectorImpl<LiveInterval*>&);
193 unsigned tryEvict(LiveInterval&, AllocationOrder&,
194 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
195 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
196 SmallVectorImpl<LiveInterval*>&);
197 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
198 SmallVectorImpl<LiveInterval*>&);
199 unsigned trySplit(LiveInterval&, AllocationOrder&,
200 SmallVectorImpl<LiveInterval*>&);
202 } // end anonymous namespace
204 char RAGreedy::ID = 0;
206 // Hysteresis to use when comparing floats.
207 // This helps stabilize decisions based on float comparisons.
208 const float Hysteresis = 0.98f;
211 FunctionPass* llvm::createGreedyRegisterAllocator() {
212 return new RAGreedy();
215 RAGreedy::RAGreedy(): MachineFunctionPass(ID), LRStage(RS_New) {
216 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
217 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
218 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
219 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
220 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
221 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
222 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
223 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
224 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
225 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
226 initializeMachineLoopRangesPass(*PassRegistry::getPassRegistry());
227 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
228 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
229 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
232 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
233 AU.setPreservesCFG();
234 AU.addRequired<AliasAnalysis>();
235 AU.addPreserved<AliasAnalysis>();
236 AU.addRequired<LiveIntervals>();
237 AU.addRequired<SlotIndexes>();
238 AU.addPreserved<SlotIndexes>();
239 AU.addRequired<LiveDebugVariables>();
240 AU.addPreserved<LiveDebugVariables>();
242 AU.addRequiredID(StrongPHIEliminationID);
243 AU.addRequiredTransitive<RegisterCoalescer>();
244 AU.addRequired<CalculateSpillWeights>();
245 AU.addRequired<LiveStacks>();
246 AU.addPreserved<LiveStacks>();
247 AU.addRequired<MachineDominatorTree>();
248 AU.addPreserved<MachineDominatorTree>();
249 AU.addRequired<MachineLoopInfo>();
250 AU.addPreserved<MachineLoopInfo>();
251 AU.addRequired<MachineLoopRanges>();
252 AU.addPreserved<MachineLoopRanges>();
253 AU.addRequired<VirtRegMap>();
254 AU.addPreserved<VirtRegMap>();
255 AU.addRequired<EdgeBundles>();
256 AU.addRequired<SpillPlacement>();
257 MachineFunctionPass::getAnalysisUsage(AU);
261 //===----------------------------------------------------------------------===//
262 // LiveRangeEdit delegate methods
263 //===----------------------------------------------------------------------===//
265 void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
266 // LRE itself will remove from SlotIndexes and parent basic block.
267 VRM->RemoveMachineInstrFromMaps(MI);
270 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
271 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
272 unassign(LIS->getInterval(VirtReg), PhysReg);
275 // Unassigned virtreg is probably in the priority queue.
276 // RegAllocBase will erase it after dequeueing.
280 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
281 unsigned PhysReg = VRM->getPhys(VirtReg);
285 // Register is assigned, put it back on the queue for reassignment.
286 LiveInterval &LI = LIS->getInterval(VirtReg);
287 unassign(LI, PhysReg);
291 void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
292 // LRE may clone a virtual register because dead code elimination causes it to
293 // be split into connected components. Ensure that the new register gets the
294 // same stage as the parent.
296 LRStage[New] = LRStage[Old];
299 void RAGreedy::releaseMemory() {
300 SpillerInstance.reset(0);
303 RegAllocBase::releaseMemory();
306 void RAGreedy::enqueue(LiveInterval *LI) {
307 // Prioritize live ranges by size, assigning larger ranges first.
308 // The queue holds (size, reg) pairs.
309 const unsigned Size = LI->getSize();
310 const unsigned Reg = LI->reg;
311 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
312 "Can only enqueue virtual registers");
316 if (LRStage[Reg] == RS_New)
317 LRStage[Reg] = RS_First;
319 if (LRStage[Reg] == RS_Second)
320 // Unsplit ranges that couldn't be allocated immediately are deferred until
321 // everything else has been allocated. Long ranges are allocated last so
322 // they are split against realistic interference.
323 Prio = (1u << 31) - Size;
325 // Everything else is allocated in long->short order. Long ranges that don't
326 // fit should be spilled ASAP so they don't create interference.
327 Prio = (1u << 31) + Size;
329 // Boost ranges that have a physical register hint.
330 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
334 Queue.push(std::make_pair(Prio, Reg));
337 LiveInterval *RAGreedy::dequeue() {
340 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
346 //===----------------------------------------------------------------------===//
348 //===----------------------------------------------------------------------===//
350 /// tryAssign - Try to assign VirtReg to an available register.
351 unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
352 AllocationOrder &Order,
353 SmallVectorImpl<LiveInterval*> &NewVRegs) {
356 while ((PhysReg = Order.next()))
357 if (!checkPhysRegInterference(VirtReg, PhysReg))
359 if (!PhysReg || Order.isHint(PhysReg))
362 // PhysReg is available. Try to evict interference from a cheaper alternative.
363 unsigned Cost = TRI->getCostPerUse(PhysReg);
365 // Most registers have 0 additional cost.
369 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
371 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
372 return CheapReg ? CheapReg : PhysReg;
376 //===----------------------------------------------------------------------===//
377 // Interference eviction
378 //===----------------------------------------------------------------------===//
380 /// canEvict - Return true if all interferences between VirtReg and PhysReg can
382 /// Return false if any interference is heavier than MaxWeight.
383 /// On return, set MaxWeight to the maximal spill weight of an interference.
384 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
387 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
388 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
389 // If there is 10 or more interferences, chances are one is heavier.
390 if (Q.collectInterferingVRegs(10, MaxWeight) >= 10)
393 // Check if any interfering live range is heavier than MaxWeight.
394 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
395 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
396 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
398 if (Intf->weight >= MaxWeight)
400 Weight = std::max(Weight, Intf->weight);
407 /// tryEvict - Try to evict all interferences for a physreg.
408 /// @param VirtReg Currently unassigned virtual register.
409 /// @param Order Physregs to try.
410 /// @return Physreg to assign VirtReg, or 0.
411 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
412 AllocationOrder &Order,
413 SmallVectorImpl<LiveInterval*> &NewVRegs,
414 unsigned CostPerUseLimit) {
415 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
417 // Keep track of the lightest single interference seen so far.
418 float BestWeight = VirtReg.weight;
419 unsigned BestPhys = 0;
422 while (unsigned PhysReg = Order.next()) {
423 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
425 // The first use of a register in a function has cost 1.
426 if (CostPerUseLimit == 1 && !MRI->isPhysRegUsed(PhysReg))
429 float Weight = BestWeight;
430 if (!canEvictInterference(VirtReg, PhysReg, Weight))
433 // This is an eviction candidate.
434 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " interference = "
436 if (BestPhys && Weight >= BestWeight)
442 // Stop if the hint can be used.
443 if (Order.isHint(PhysReg))
450 DEBUG(dbgs() << "evicting " << PrintReg(BestPhys, TRI) << " interference\n");
451 for (const unsigned *AliasI = TRI->getOverlaps(BestPhys); *AliasI; ++AliasI) {
452 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
453 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
454 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
455 LiveInterval *Intf = Q.interferingVRegs()[i];
456 unassign(*Intf, VRM->getPhys(Intf->reg));
458 NewVRegs.push_back(Intf);
465 //===----------------------------------------------------------------------===//
467 //===----------------------------------------------------------------------===//
469 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
470 /// interference pattern in Physreg and its aliases. Add the constraints to
471 /// SpillPlacement and return the static cost of this split in Cost, assuming
472 /// that all preferences in SplitConstraints are met.
473 /// Return false if there are no bundles with positive bias.
474 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
476 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
478 // Reset interference dependent info.
479 SplitConstraints.resize(UseBlocks.size());
480 float StaticCost = 0;
481 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
482 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
483 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
485 BC.Number = BI.MBB->getNumber();
486 Intf.moveToBlock(BC.Number);
487 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
488 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
490 if (!Intf.hasInterference())
493 // Number of spill code instructions to insert.
496 // Interference for the live-in value.
498 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
499 BC.Entry = SpillPlacement::MustSpill, ++Ins;
500 else if (Intf.first() < BI.FirstUse)
501 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
502 else if (Intf.first() < (BI.LiveThrough ? BI.LastUse : BI.Kill))
506 // Interference for the live-out value.
508 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
509 BC.Exit = SpillPlacement::MustSpill, ++Ins;
510 else if (Intf.last() > BI.LastUse)
511 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
512 else if (Intf.last() > (BI.LiveThrough ? BI.FirstUse : BI.Def))
516 // Accumulate the total frequency of inserted spill code.
518 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
522 // Add constraints for use-blocks. Note that these are the only constraints
523 // that may add a positive bias, it is downhill from here.
524 SpillPlacer->addConstraints(SplitConstraints);
525 return SpillPlacer->scanActiveBundles();
529 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
530 /// live-through blocks in Blocks.
531 void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
532 ArrayRef<unsigned> Blocks) {
533 const unsigned GroupSize = 8;
534 SpillPlacement::BlockConstraint BCS[GroupSize];
535 unsigned TBS[GroupSize];
536 unsigned B = 0, T = 0;
538 for (unsigned i = 0; i != Blocks.size(); ++i) {
539 unsigned Number = Blocks[i];
540 Intf.moveToBlock(Number);
542 if (!Intf.hasInterference()) {
543 assert(T < GroupSize && "Array overflow");
545 if (++T == GroupSize) {
546 SpillPlacer->addLinks(ArrayRef<unsigned>(TBS, T));
552 assert(B < GroupSize && "Array overflow");
553 BCS[B].Number = Number;
555 // Interference for the live-in value.
556 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
557 BCS[B].Entry = SpillPlacement::MustSpill;
559 BCS[B].Entry = SpillPlacement::PrefSpill;
561 // Interference for the live-out value.
562 if (Intf.last() >= SA->getLastSplitPoint(Number))
563 BCS[B].Exit = SpillPlacement::MustSpill;
565 BCS[B].Exit = SpillPlacement::PrefSpill;
567 if (++B == GroupSize) {
568 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
569 SpillPlacer->addConstraints(Array);
574 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
575 SpillPlacer->addConstraints(Array);
576 SpillPlacer->addLinks(ArrayRef<unsigned>(TBS, T));
579 void RAGreedy::growRegion(GlobalSplitCandidate &Cand,
580 InterferenceCache::Cursor Intf) {
581 // Keep track of through blocks that have not been added to SpillPlacer.
582 BitVector Todo = SA->getThroughBlocks();
583 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
584 unsigned AddedTo = 0;
586 unsigned Visited = 0;
590 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
591 if (NewBundles.empty())
593 // Find new through blocks in the periphery of PrefRegBundles.
594 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
595 unsigned Bundle = NewBundles[i];
596 // Look at all blocks connected to Bundle in the full graph.
597 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
598 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
601 if (!Todo.test(Block))
604 // This is a new through block. Add it to SpillPlacer later.
605 ActiveBlocks.push_back(Block);
611 // Any new blocks to add?
612 if (ActiveBlocks.size() > AddedTo) {
613 ArrayRef<unsigned> Add(&ActiveBlocks[AddedTo],
614 ActiveBlocks.size() - AddedTo);
615 addThroughConstraints(Intf, Add);
616 AddedTo = ActiveBlocks.size();
618 // Perhaps iterating can enable more bundles?
619 SpillPlacer->iterate();
621 DEBUG(dbgs() << ", v=" << Visited);
624 /// calcSpillCost - Compute how expensive it would be to split the live range in
625 /// SA around all use blocks instead of forming bundle regions.
626 float RAGreedy::calcSpillCost() {
628 const LiveInterval &LI = SA->getParent();
629 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
630 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
631 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
632 unsigned Number = BI.MBB->getNumber();
633 // We normally only need one spill instruction - a load or a store.
634 Cost += SpillPlacer->getBlockFrequency(Number);
636 // Unless the value is redefined in the block.
637 if (BI.LiveIn && BI.LiveOut) {
638 SlotIndex Start, Stop;
639 tie(Start, Stop) = Indexes->getMBBRange(Number);
640 LiveInterval::const_iterator I = LI.find(Start);
641 assert(I != LI.end() && "Expected live-in value");
642 // Is there a different live-out value? If so, we need an extra spill
645 Cost += SpillPlacer->getBlockFrequency(Number);
651 /// calcGlobalSplitCost - Return the global split cost of following the split
652 /// pattern in LiveBundles. This cost should be added to the local cost of the
653 /// interference pattern in SplitConstraints.
655 float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand,
656 InterferenceCache::Cursor Intf) {
657 float GlobalCost = 0;
658 const BitVector &LiveBundles = Cand.LiveBundles;
659 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
660 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
661 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
662 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
663 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
664 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
668 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
670 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
672 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
675 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
676 unsigned Number = Cand.ActiveBlocks[i];
677 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
678 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
679 if (!RegIn && !RegOut)
681 if (RegIn && RegOut) {
682 // We need double spill code if this block has interference.
683 Intf.moveToBlock(Number);
684 if (Intf.hasInterference())
685 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
688 // live-in / stack-out or stack-in live-out.
689 GlobalCost += SpillPlacer->getBlockFrequency(Number);
694 /// splitAroundRegion - Split VirtReg around the region determined by
695 /// LiveBundles. Make an effort to avoid interference from PhysReg.
697 /// The 'register' interval is going to contain as many uses as possible while
698 /// avoiding interference. The 'stack' interval is the complement constructed by
699 /// SplitEditor. It will contain the rest.
701 void RAGreedy::splitAroundRegion(LiveInterval &VirtReg,
702 GlobalSplitCandidate &Cand,
703 SmallVectorImpl<LiveInterval*> &NewVRegs) {
704 const BitVector &LiveBundles = Cand.LiveBundles;
707 dbgs() << "Splitting around region for " << PrintReg(Cand.PhysReg, TRI)
709 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
710 dbgs() << " EB#" << i;
714 InterferenceCache::Cursor Intf(IntfCache, Cand.PhysReg);
715 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
718 // Create the main cross-block interval.
719 const unsigned MainIntv = SE->openIntv();
721 // First add all defs that are live out of a block.
722 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
723 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
724 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
725 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
726 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
728 // Create separate intervals for isolated blocks with multiple uses.
729 if (!RegIn && !RegOut && BI.FirstUse != BI.LastUse) {
730 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
731 SE->splitSingleBlock(BI);
732 SE->selectIntv(MainIntv);
736 // Should the register be live out?
737 if (!BI.LiveOut || !RegOut)
740 SlotIndex Start, Stop;
741 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
742 Intf.moveToBlock(BI.MBB->getNumber());
743 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " -> EB#"
744 << Bundles->getBundle(BI.MBB->getNumber(), 1)
745 << " [" << Start << ';'
746 << SA->getLastSplitPoint(BI.MBB->getNumber()) << '-' << Stop
747 << ") intf [" << Intf.first() << ';' << Intf.last() << ')');
749 // The interference interval should either be invalid or overlap MBB.
750 assert((!Intf.hasInterference() || Intf.first() < Stop)
751 && "Bad interference");
752 assert((!Intf.hasInterference() || Intf.last() > Start)
753 && "Bad interference");
755 // Check interference leaving the block.
756 if (!Intf.hasInterference()) {
757 // Block is interference-free.
758 DEBUG(dbgs() << ", no interference");
759 if (!BI.LiveThrough) {
760 DEBUG(dbgs() << ", not live-through.\n");
761 SE->useIntv(SE->enterIntvBefore(BI.Def), Stop);
765 // Block is live-through, but entry bundle is on the stack.
766 // Reload just before the first use.
767 DEBUG(dbgs() << ", not live-in, enter before first use.\n");
768 SE->useIntv(SE->enterIntvBefore(BI.FirstUse), Stop);
771 DEBUG(dbgs() << ", live-through.\n");
775 // Block has interference.
776 DEBUG(dbgs() << ", interference to " << Intf.last());
778 if (!BI.LiveThrough && Intf.last() <= BI.Def) {
779 // The interference doesn't reach the outgoing segment.
780 DEBUG(dbgs() << " doesn't affect def from " << BI.Def << '\n');
781 SE->useIntv(BI.Def, Stop);
785 SlotIndex LastSplitPoint = SA->getLastSplitPoint(BI.MBB->getNumber());
786 if (Intf.last().getBoundaryIndex() < BI.LastUse) {
787 // There are interference-free uses at the end of the block.
788 // Find the first use that can get the live-out register.
789 SmallVectorImpl<SlotIndex>::const_iterator UI =
790 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
791 Intf.last().getBoundaryIndex());
792 assert(UI != SA->UseSlots.end() && "Couldn't find last use");
794 assert(Use <= BI.LastUse && "Couldn't find last use");
795 // Only attempt a split befroe the last split point.
796 if (Use.getBaseIndex() <= LastSplitPoint) {
797 DEBUG(dbgs() << ", free use at " << Use << ".\n");
798 SlotIndex SegStart = SE->enterIntvBefore(Use);
799 assert(SegStart >= Intf.last() && "Couldn't avoid interference");
800 assert(SegStart < LastSplitPoint && "Impossible split point");
801 SE->useIntv(SegStart, Stop);
806 // Interference is after the last use.
807 DEBUG(dbgs() << " after last use.\n");
808 SlotIndex SegStart = SE->enterIntvAtEnd(*BI.MBB);
809 assert(SegStart >= Intf.last() && "Couldn't avoid interference");
812 // Now all defs leading to live bundles are handled, do everything else.
813 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
814 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
815 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
816 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
818 // Is the register live-in?
819 if (!BI.LiveIn || !RegIn)
822 // We have an incoming register. Check for interference.
823 SlotIndex Start, Stop;
824 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
825 Intf.moveToBlock(BI.MBB->getNumber());
826 DEBUG(dbgs() << "EB#" << Bundles->getBundle(BI.MBB->getNumber(), 0)
827 << " -> BB#" << BI.MBB->getNumber() << " [" << Start << ';'
828 << SA->getLastSplitPoint(BI.MBB->getNumber()) << '-' << Stop
831 // Check interference entering the block.
832 if (!Intf.hasInterference()) {
833 // Block is interference-free.
834 DEBUG(dbgs() << ", no interference");
835 if (!BI.LiveThrough) {
836 DEBUG(dbgs() << ", killed in block.\n");
837 SE->useIntv(Start, SE->leaveIntvAfter(BI.Kill));
841 SlotIndex LastSplitPoint = SA->getLastSplitPoint(BI.MBB->getNumber());
842 // Block is live-through, but exit bundle is on the stack.
843 // Spill immediately after the last use.
844 if (BI.LastUse < LastSplitPoint) {
845 DEBUG(dbgs() << ", uses, stack-out.\n");
846 SE->useIntv(Start, SE->leaveIntvAfter(BI.LastUse));
849 // The last use is after the last split point, it is probably an
851 DEBUG(dbgs() << ", uses at " << BI.LastUse << " after split point "
852 << LastSplitPoint << ", stack-out.\n");
853 SlotIndex SegEnd = SE->leaveIntvBefore(LastSplitPoint);
854 SE->useIntv(Start, SegEnd);
855 // Run a double interval from the split to the last use.
856 // This makes it possible to spill the complement without affecting the
858 SE->overlapIntv(SegEnd, BI.LastUse);
861 // Register is live-through.
862 DEBUG(dbgs() << ", uses, live-through.\n");
863 SE->useIntv(Start, Stop);
867 // Block has interference.
868 DEBUG(dbgs() << ", interference from " << Intf.first());
870 if (!BI.LiveThrough && Intf.first() >= BI.Kill) {
871 // The interference doesn't reach the outgoing segment.
872 DEBUG(dbgs() << " doesn't affect kill at " << BI.Kill << '\n');
873 SE->useIntv(Start, BI.Kill);
877 if (Intf.first().getBaseIndex() > BI.FirstUse) {
878 // There are interference-free uses at the beginning of the block.
879 // Find the last use that can get the register.
880 SmallVectorImpl<SlotIndex>::const_iterator UI =
881 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
882 Intf.first().getBaseIndex());
883 assert(UI != SA->UseSlots.begin() && "Couldn't find first use");
884 SlotIndex Use = (--UI)->getBoundaryIndex();
885 DEBUG(dbgs() << ", free use at " << *UI << ".\n");
886 SlotIndex SegEnd = SE->leaveIntvAfter(Use);
887 assert(SegEnd <= Intf.first() && "Couldn't avoid interference");
888 SE->useIntv(Start, SegEnd);
892 // Interference is before the first use.
893 DEBUG(dbgs() << " before first use.\n");
894 SlotIndex SegEnd = SE->leaveIntvAtTop(*BI.MBB);
895 assert(SegEnd <= Intf.first() && "Couldn't avoid interference");
898 // Handle live-through blocks.
899 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
900 unsigned Number = Cand.ActiveBlocks[i];
901 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
902 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
903 DEBUG(dbgs() << "Live through BB#" << Number << '\n');
904 if (RegIn && RegOut) {
905 Intf.moveToBlock(Number);
906 if (!Intf.hasInterference()) {
907 SE->useIntv(Indexes->getMBBStartIdx(Number),
908 Indexes->getMBBEndIdx(Number));
912 MachineBasicBlock *MBB = MF->getBlockNumbered(Number);
914 SE->leaveIntvAtTop(*MBB);
916 SE->enterIntvAtEnd(*MBB);
921 SmallVector<unsigned, 8> IntvMap;
922 SE->finish(&IntvMap);
923 LRStage.resize(MRI->getNumVirtRegs());
924 unsigned OrigBlocks = SA->getNumThroughBlocks() + SA->getUseBlocks().size();
926 // Sort out the new intervals created by splitting. We get four kinds:
927 // - Remainder intervals should not be split again.
928 // - Candidate intervals can be assigned to Cand.PhysReg.
929 // - Block-local splits are candidates for local splitting.
930 // - DCE leftovers should go back on the queue.
931 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
932 unsigned Reg = LREdit.get(i)->reg;
934 // Ignore old intervals from DCE.
935 if (LRStage[Reg] != RS_New)
938 // Remainder interval. Don't try splitting again, spill if it doesn't
940 if (IntvMap[i] == 0) {
941 LRStage[Reg] = RS_Global;
945 // Main interval. Allow repeated splitting as long as the number of live
946 // blocks is strictly decreasing.
947 if (IntvMap[i] == MainIntv) {
948 if (SA->countLiveBlocks(LREdit.get(i)) >= OrigBlocks) {
949 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
950 << " blocks as original.\n");
951 // Don't allow repeated splitting as a safe guard against looping.
952 LRStage[Reg] = RS_Global;
957 // Other intervals are treated as new. This includes local intervals created
958 // for blocks with multiple uses, and anything created by DCE.
962 MF->verify(this, "After splitting live range around region");
965 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
966 SmallVectorImpl<LiveInterval*> &NewVRegs) {
967 float BestCost = Hysteresis * calcSpillCost();
968 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
969 const unsigned NoCand = ~0u;
970 unsigned BestCand = NoCand;
973 for (unsigned Cand = 0; unsigned PhysReg = Order.next(); ++Cand) {
974 if (GlobalCand.size() <= Cand)
975 GlobalCand.resize(Cand+1);
976 GlobalCand[Cand].reset(PhysReg);
978 SpillPlacer->prepare(GlobalCand[Cand].LiveBundles);
980 InterferenceCache::Cursor Intf(IntfCache, PhysReg);
981 if (!addSplitConstraints(Intf, Cost)) {
982 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
985 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
986 if (Cost >= BestCost) {
988 if (BestCand == NoCand)
989 dbgs() << " worse than no bundles\n";
991 dbgs() << " worse than "
992 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
996 growRegion(GlobalCand[Cand], Intf);
998 SpillPlacer->finish();
1000 // No live bundles, defer to splitSingleBlocks().
1001 if (!GlobalCand[Cand].LiveBundles.any()) {
1002 DEBUG(dbgs() << " no bundles.\n");
1006 Cost += calcGlobalSplitCost(GlobalCand[Cand], Intf);
1008 dbgs() << ", total = " << Cost << " with bundles";
1009 for (int i = GlobalCand[Cand].LiveBundles.find_first(); i>=0;
1010 i = GlobalCand[Cand].LiveBundles.find_next(i))
1011 dbgs() << " EB#" << i;
1014 if (Cost < BestCost) {
1016 BestCost = Hysteresis * Cost; // Prevent rounding effects.
1020 if (BestCand == NoCand)
1023 splitAroundRegion(VirtReg, GlobalCand[BestCand], NewVRegs);
1028 //===----------------------------------------------------------------------===//
1030 //===----------------------------------------------------------------------===//
1033 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1034 /// in order to use PhysReg between two entries in SA->UseSlots.
1036 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1038 void RAGreedy::calcGapWeights(unsigned PhysReg,
1039 SmallVectorImpl<float> &GapWeight) {
1040 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1041 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1042 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1043 const unsigned NumGaps = Uses.size()-1;
1045 // Start and end points for the interference check.
1046 SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
1047 SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
1049 GapWeight.assign(NumGaps, 0.0f);
1051 // Add interference from each overlapping register.
1052 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
1053 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
1054 .checkInterference())
1057 // We know that VirtReg is a continuous interval from FirstUse to LastUse,
1058 // so we don't need InterferenceQuery.
1060 // Interference that overlaps an instruction is counted in both gaps
1061 // surrounding the instruction. The exception is interference before
1062 // StartIdx and after StopIdx.
1064 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
1065 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1066 // Skip the gaps before IntI.
1067 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1068 if (++Gap == NumGaps)
1073 // Update the gaps covered by IntI.
1074 const float weight = IntI.value()->weight;
1075 for (; Gap != NumGaps; ++Gap) {
1076 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1077 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1086 /// getPrevMappedIndex - Return the slot index of the last non-copy instruction
1087 /// before MI that has a slot index. If MI is the first mapped instruction in
1088 /// its block, return the block start index instead.
1090 SlotIndex RAGreedy::getPrevMappedIndex(const MachineInstr *MI) {
1091 assert(MI && "Missing MachineInstr");
1092 const MachineBasicBlock *MBB = MI->getParent();
1093 MachineBasicBlock::const_iterator B = MBB->begin(), I = MI;
1095 if (!(--I)->isDebugValue() && !I->isCopy())
1096 return Indexes->getInstructionIndex(I);
1097 return Indexes->getMBBStartIdx(MBB);
1100 /// calcPrevSlots - Fill in the PrevSlot array with the index of the previous
1101 /// real non-copy instruction for each instruction in SA->UseSlots.
1103 void RAGreedy::calcPrevSlots() {
1104 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1106 PrevSlot.reserve(Uses.size());
1107 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
1108 const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]);
1109 PrevSlot.push_back(getPrevMappedIndex(MI).getDefIndex());
1113 /// nextSplitPoint - Find the next index into SA->UseSlots > i such that it may
1114 /// be beneficial to split before UseSlots[i].
1116 /// 0 is always a valid split point
1117 unsigned RAGreedy::nextSplitPoint(unsigned i) {
1118 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1119 const unsigned Size = Uses.size();
1120 assert(i != Size && "No split points after the end");
1121 // Allow split before i when Uses[i] is not adjacent to the previous use.
1122 while (++i != Size && PrevSlot[i].getBaseIndex() <= Uses[i-1].getBaseIndex())
1127 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1130 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1131 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1132 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1133 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1135 // Note that it is possible to have an interval that is live-in or live-out
1136 // while only covering a single block - A phi-def can use undef values from
1137 // predecessors, and the block could be a single-block loop.
1138 // We don't bother doing anything clever about such a case, we simply assume
1139 // that the interval is continuous from FirstUse to LastUse. We should make
1140 // sure that we don't do anything illegal to such an interval, though.
1142 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1143 if (Uses.size() <= 2)
1145 const unsigned NumGaps = Uses.size()-1;
1148 dbgs() << "tryLocalSplit: ";
1149 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1150 dbgs() << ' ' << SA->UseSlots[i];
1154 // For every use, find the previous mapped non-copy instruction.
1155 // We use this to detect valid split points, and to estimate new interval
1159 unsigned BestBefore = NumGaps;
1160 unsigned BestAfter = 0;
1163 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
1164 SmallVector<float, 8> GapWeight;
1167 while (unsigned PhysReg = Order.next()) {
1168 // Keep track of the largest spill weight that would need to be evicted in
1169 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1170 calcGapWeights(PhysReg, GapWeight);
1172 // Try to find the best sequence of gaps to close.
1173 // The new spill weight must be larger than any gap interference.
1175 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1176 unsigned SplitBefore = 0, SplitAfter = nextSplitPoint(1) - 1;
1178 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1179 // It is the spill weight that needs to be evicted.
1180 float MaxGap = GapWeight[0];
1181 for (unsigned i = 1; i != SplitAfter; ++i)
1182 MaxGap = std::max(MaxGap, GapWeight[i]);
1185 // Live before/after split?
1186 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1187 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1189 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1190 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1191 << " i=" << MaxGap);
1193 // Stop before the interval gets so big we wouldn't be making progress.
1194 if (!LiveBefore && !LiveAfter) {
1195 DEBUG(dbgs() << " all\n");
1198 // Should the interval be extended or shrunk?
1200 if (MaxGap < HUGE_VALF) {
1201 // Estimate the new spill weight.
1203 // Each instruction reads and writes the register, except the first
1204 // instr doesn't read when !FirstLive, and the last instr doesn't write
1207 // We will be inserting copies before and after, so the total number of
1208 // reads and writes is 2 * EstUses.
1210 const unsigned EstUses = 2*(SplitAfter - SplitBefore) +
1211 2*(LiveBefore + LiveAfter);
1213 // Try to guess the size of the new interval. This should be trivial,
1214 // but the slot index of an inserted copy can be a lot smaller than the
1215 // instruction it is inserted before if there are many dead indexes
1218 // We measure the distance from the instruction before SplitBefore to
1219 // get a conservative estimate.
1221 // The final distance can still be different if inserting copies
1222 // triggers a slot index renumbering.
1224 const float EstWeight = normalizeSpillWeight(blockFreq * EstUses,
1225 PrevSlot[SplitBefore].distance(Uses[SplitAfter]));
1226 // Would this split be possible to allocate?
1227 // Never allocate all gaps, we wouldn't be making progress.
1228 float Diff = EstWeight - MaxGap;
1229 DEBUG(dbgs() << " w=" << EstWeight << " d=" << Diff);
1232 if (Diff > BestDiff) {
1233 DEBUG(dbgs() << " (best)");
1235 BestBefore = SplitBefore;
1236 BestAfter = SplitAfter;
1243 SplitBefore = nextSplitPoint(SplitBefore);
1244 if (SplitBefore < SplitAfter) {
1245 DEBUG(dbgs() << " shrink\n");
1246 // Recompute the max when necessary.
1247 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1248 MaxGap = GapWeight[SplitBefore];
1249 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1250 MaxGap = std::max(MaxGap, GapWeight[i]);
1257 // Try to extend the interval.
1258 if (SplitAfter >= NumGaps) {
1259 DEBUG(dbgs() << " end\n");
1263 DEBUG(dbgs() << " extend\n");
1264 for (unsigned e = nextSplitPoint(SplitAfter + 1) - 1;
1265 SplitAfter != e; ++SplitAfter)
1266 MaxGap = std::max(MaxGap, GapWeight[SplitAfter]);
1271 // Didn't find any candidates?
1272 if (BestBefore == NumGaps)
1275 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1276 << '-' << Uses[BestAfter] << ", " << BestDiff
1277 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1279 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1283 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1284 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1285 SE->useIntv(SegStart, SegStop);
1287 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Local);
1293 //===----------------------------------------------------------------------===//
1294 // Live Range Splitting
1295 //===----------------------------------------------------------------------===//
1297 /// trySplit - Try to split VirtReg or one of its interferences, making it
1299 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1300 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1301 SmallVectorImpl<LiveInterval*>&NewVRegs) {
1302 // Local intervals are handled separately.
1303 if (LIS->intervalIsInOneMBB(VirtReg)) {
1304 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
1305 SA->analyze(&VirtReg);
1306 return tryLocalSplit(VirtReg, Order, NewVRegs);
1309 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
1311 // Don't iterate global splitting.
1312 // Move straight to spilling if this range was produced by a global split.
1313 if (getStage(VirtReg) >= RS_Global)
1316 SA->analyze(&VirtReg);
1318 // First try to split around a region spanning multiple blocks.
1319 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1320 if (PhysReg || !NewVRegs.empty())
1323 // Then isolate blocks with multiple uses.
1324 SplitAnalysis::BlockPtrSet Blocks;
1325 if (SA->getMultiUseBlocks(Blocks)) {
1326 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
1328 SE->splitSingleBlocks(Blocks);
1329 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Global);
1331 MF->verify(this, "After splitting live range around basic blocks");
1334 // Don't assign any physregs.
1339 //===----------------------------------------------------------------------===//
1341 //===----------------------------------------------------------------------===//
1343 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
1344 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1345 // First try assigning a free register.
1346 AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
1347 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1350 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1353 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1355 // The first time we see a live range, don't try to split or spill.
1356 // Wait until the second time, when all smaller ranges have been allocated.
1357 // This gives a better picture of the interference to split around.
1358 LiveRangeStage Stage = getStage(VirtReg);
1359 if (Stage == RS_First) {
1360 LRStage[VirtReg.reg] = RS_Second;
1361 DEBUG(dbgs() << "wait for second round\n");
1362 NewVRegs.push_back(&VirtReg);
1366 assert(Stage < RS_Spill && "Cannot allocate after spilling");
1368 // Try splitting VirtReg or interferences.
1369 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1370 if (PhysReg || !NewVRegs.empty())
1373 // Finally spill VirtReg itself.
1374 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
1375 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1376 spiller().spill(LRE);
1377 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Spill);
1380 MF->verify(this, "After spilling");
1382 // The live virtual register requesting allocation was spilled, so tell
1383 // the caller not to allocate anything during this round.
1387 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1388 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1389 << "********** Function: "
1390 << ((Value*)mf.getFunction())->getName() << '\n');
1394 MF->verify(this, "Before greedy register allocator");
1396 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
1397 Indexes = &getAnalysis<SlotIndexes>();
1398 DomTree = &getAnalysis<MachineDominatorTree>();
1399 ReservedRegs = TRI->getReservedRegs(*MF);
1400 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
1401 Loops = &getAnalysis<MachineLoopInfo>();
1402 LoopRanges = &getAnalysis<MachineLoopRanges>();
1403 Bundles = &getAnalysis<EdgeBundles>();
1404 SpillPlacer = &getAnalysis<SpillPlacement>();
1406 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
1407 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
1409 LRStage.resize(MRI->getNumVirtRegs());
1410 IntfCache.init(MF, &PhysReg2LiveUnion[0], Indexes, TRI);
1414 LIS->addKillFlags();
1418 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
1419 VRM->rewrite(Indexes);
1422 // Write out new DBG_VALUE instructions.
1423 getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
1425 // The pass output is in VirtRegMap. Release all the transient data.