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 "LiveRegMatrix.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/PassAnalysisSupport.h"
28 #include "llvm/CodeGen/CalcSpillWeights.h"
29 #include "llvm/CodeGen/EdgeBundles.h"
30 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
31 #include "llvm/CodeGen/LiveRangeEdit.h"
32 #include "llvm/CodeGen/LiveStackAnalysis.h"
33 #include "llvm/CodeGen/MachineDominators.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineLoopInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/Passes.h"
38 #include "llvm/CodeGen/RegAllocRegistry.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Support/Timer.h"
50 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
51 STATISTIC(NumLocalSplits, "Number of split local live ranges");
52 STATISTIC(NumEvicted, "Number of interferences evicted");
54 static cl::opt<SplitEditor::ComplementSpillMode>
55 SplitSpillMode("split-spill-mode", cl::Hidden,
56 cl::desc("Spill mode for splitting live ranges"),
57 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
58 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
59 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
61 cl::init(SplitEditor::SM_Partition));
63 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
64 createGreedyRegisterAllocator);
67 class RAGreedy : public MachineFunctionPass,
69 private LiveRangeEdit::Delegate {
76 MachineDominatorTree *DomTree;
77 MachineLoopInfo *Loops;
79 SpillPlacement *SpillPlacer;
80 LiveDebugVariables *DebugVars;
83 std::auto_ptr<Spiller> SpillerInstance;
84 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
87 // Live ranges pass through a number of stages as we try to allocate them.
88 // Some of the stages may also create new live ranges:
90 // - Region splitting.
91 // - Per-block splitting.
95 // Ranges produced by one of the stages skip the previous stages when they are
96 // dequeued. This improves performance because we can skip interference checks
97 // that are unlikely to give any results. It also guarantees that the live
98 // range splitting algorithm terminates, something that is otherwise hard to
100 enum LiveRangeStage {
101 /// Newly created live range that has never been queued.
104 /// Only attempt assignment and eviction. Then requeue as RS_Split.
107 /// Attempt live range splitting if assignment is impossible.
110 /// Attempt more aggressive live range splitting that is guaranteed to make
111 /// progress. This is used for split products that may not be making
115 /// Live range will be spilled. No more splitting will be attempted.
118 /// There is nothing more we can do to this live range. Abort compilation
119 /// if it can't be assigned.
123 static const char *const StageName[];
125 // RegInfo - Keep additional information about each live range.
127 LiveRangeStage Stage;
129 // Cascade - Eviction loop prevention. See canEvictInterference().
132 RegInfo() : Stage(RS_New), Cascade(0) {}
135 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
137 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
138 return ExtraRegInfo[VirtReg.reg].Stage;
141 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
142 ExtraRegInfo.resize(MRI->getNumVirtRegs());
143 ExtraRegInfo[VirtReg.reg].Stage = Stage;
146 template<typename Iterator>
147 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
148 ExtraRegInfo.resize(MRI->getNumVirtRegs());
149 for (;Begin != End; ++Begin) {
150 unsigned Reg = (*Begin)->reg;
151 if (ExtraRegInfo[Reg].Stage == RS_New)
152 ExtraRegInfo[Reg].Stage = NewStage;
156 /// Cost of evicting interference.
157 struct EvictionCost {
158 unsigned BrokenHints; ///< Total number of broken hints.
159 float MaxWeight; ///< Maximum spill weight evicted.
161 EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
163 bool operator<(const EvictionCost &O) const {
164 if (BrokenHints != O.BrokenHints)
165 return BrokenHints < O.BrokenHints;
166 return MaxWeight < O.MaxWeight;
171 std::auto_ptr<SplitAnalysis> SA;
172 std::auto_ptr<SplitEditor> SE;
174 /// Cached per-block interference maps
175 InterferenceCache IntfCache;
177 /// All basic blocks where the current register has uses.
178 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
180 /// Global live range splitting candidate info.
181 struct GlobalSplitCandidate {
182 // Register intended for assignment, or 0.
185 // SplitKit interval index for this candidate.
188 // Interference for PhysReg.
189 InterferenceCache::Cursor Intf;
191 // Bundles where this candidate should be live.
192 BitVector LiveBundles;
193 SmallVector<unsigned, 8> ActiveBlocks;
195 void reset(InterferenceCache &Cache, unsigned Reg) {
198 Intf.setPhysReg(Cache, Reg);
200 ActiveBlocks.clear();
203 // Set B[i] = C for every live bundle where B[i] was NoCand.
204 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
206 for (int i = LiveBundles.find_first(); i >= 0;
207 i = LiveBundles.find_next(i))
208 if (B[i] == NoCand) {
216 /// Candidate info for for each PhysReg in AllocationOrder.
217 /// This vector never shrinks, but grows to the size of the largest register
219 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
221 enum { NoCand = ~0u };
223 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
224 /// NoCand which indicates the stack interval.
225 SmallVector<unsigned, 32> BundleCand;
230 /// Return the pass name.
231 virtual const char* getPassName() const {
232 return "Greedy Register Allocator";
235 /// RAGreedy analysis usage.
236 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
237 virtual void releaseMemory();
238 virtual Spiller &spiller() { return *SpillerInstance; }
239 virtual void enqueue(LiveInterval *LI);
240 virtual LiveInterval *dequeue();
241 virtual unsigned selectOrSplit(LiveInterval&,
242 SmallVectorImpl<LiveInterval*>&);
244 /// Perform register allocation.
245 virtual bool runOnMachineFunction(MachineFunction &mf);
250 bool LRE_CanEraseVirtReg(unsigned);
251 void LRE_WillShrinkVirtReg(unsigned);
252 void LRE_DidCloneVirtReg(unsigned, unsigned);
254 float calcSpillCost();
255 bool addSplitConstraints(InterferenceCache::Cursor, float&);
256 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
257 void growRegion(GlobalSplitCandidate &Cand);
258 float calcGlobalSplitCost(GlobalSplitCandidate&);
259 bool calcCompactRegion(GlobalSplitCandidate&);
260 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
261 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
262 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
263 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
264 void evictInterference(LiveInterval&, unsigned,
265 SmallVectorImpl<LiveInterval*>&);
267 unsigned tryAssign(LiveInterval&, AllocationOrder&,
268 SmallVectorImpl<LiveInterval*>&);
269 unsigned tryEvict(LiveInterval&, AllocationOrder&,
270 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
271 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
272 SmallVectorImpl<LiveInterval*>&);
273 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
274 SmallVectorImpl<LiveInterval*>&);
275 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
276 SmallVectorImpl<LiveInterval*>&);
277 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
278 SmallVectorImpl<LiveInterval*>&);
279 unsigned trySplit(LiveInterval&, AllocationOrder&,
280 SmallVectorImpl<LiveInterval*>&);
282 } // end anonymous namespace
284 char RAGreedy::ID = 0;
287 const char *const RAGreedy::StageName[] = {
297 // Hysteresis to use when comparing floats.
298 // This helps stabilize decisions based on float comparisons.
299 const float Hysteresis = 0.98f;
302 FunctionPass* llvm::createGreedyRegisterAllocator() {
303 return new RAGreedy();
306 RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
307 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
308 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
309 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
310 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
311 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
312 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
313 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
314 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
315 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
316 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
317 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
318 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
319 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
320 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
323 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
324 AU.setPreservesCFG();
325 AU.addRequired<AliasAnalysis>();
326 AU.addPreserved<AliasAnalysis>();
327 AU.addRequired<LiveIntervals>();
328 AU.addPreserved<LiveIntervals>();
329 AU.addRequired<SlotIndexes>();
330 AU.addPreserved<SlotIndexes>();
331 AU.addRequired<LiveDebugVariables>();
332 AU.addPreserved<LiveDebugVariables>();
333 AU.addRequired<LiveStacks>();
334 AU.addPreserved<LiveStacks>();
335 AU.addRequired<CalculateSpillWeights>();
336 AU.addRequired<MachineDominatorTree>();
337 AU.addPreserved<MachineDominatorTree>();
338 AU.addRequired<MachineLoopInfo>();
339 AU.addPreserved<MachineLoopInfo>();
340 AU.addRequired<VirtRegMap>();
341 AU.addPreserved<VirtRegMap>();
342 AU.addRequired<LiveRegMatrix>();
343 AU.addPreserved<LiveRegMatrix>();
344 AU.addRequired<EdgeBundles>();
345 AU.addRequired<SpillPlacement>();
346 MachineFunctionPass::getAnalysisUsage(AU);
350 //===----------------------------------------------------------------------===//
351 // LiveRangeEdit delegate methods
352 //===----------------------------------------------------------------------===//
354 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
355 if (VRM->hasPhys(VirtReg)) {
356 Matrix->unassign(LIS->getInterval(VirtReg));
359 // Unassigned virtreg is probably in the priority queue.
360 // RegAllocBase will erase it after dequeueing.
364 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
365 if (!VRM->hasPhys(VirtReg))
368 // Register is assigned, put it back on the queue for reassignment.
369 LiveInterval &LI = LIS->getInterval(VirtReg);
370 Matrix->unassign(LI);
374 void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
375 // Cloning a register we haven't even heard about yet? Just ignore it.
376 if (!ExtraRegInfo.inBounds(Old))
379 // LRE may clone a virtual register because dead code elimination causes it to
380 // be split into connected components. The new components are much smaller
381 // than the original, so they should get a new chance at being assigned.
382 // same stage as the parent.
383 ExtraRegInfo[Old].Stage = RS_Assign;
384 ExtraRegInfo.grow(New);
385 ExtraRegInfo[New] = ExtraRegInfo[Old];
388 void RAGreedy::releaseMemory() {
389 SpillerInstance.reset(0);
390 ExtraRegInfo.clear();
394 void RAGreedy::enqueue(LiveInterval *LI) {
395 // Prioritize live ranges by size, assigning larger ranges first.
396 // The queue holds (size, reg) pairs.
397 const unsigned Size = LI->getSize();
398 const unsigned Reg = LI->reg;
399 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
400 "Can only enqueue virtual registers");
403 ExtraRegInfo.grow(Reg);
404 if (ExtraRegInfo[Reg].Stage == RS_New)
405 ExtraRegInfo[Reg].Stage = RS_Assign;
407 if (ExtraRegInfo[Reg].Stage == RS_Split) {
408 // Unsplit ranges that couldn't be allocated immediately are deferred until
409 // everything else has been allocated.
412 // Everything is allocated in long->short order. Long ranges that don't fit
413 // should be spilled (or split) ASAP so they don't create interference.
414 Prio = (1u << 31) + Size;
416 // Boost ranges that have a physical register hint.
417 if (TargetRegisterInfo::isPhysicalRegister(VRM->getRegAllocPref(Reg)))
421 Queue.push(std::make_pair(Prio, ~Reg));
424 LiveInterval *RAGreedy::dequeue() {
427 LiveInterval *LI = &LIS->getInterval(~Queue.top().second);
433 //===----------------------------------------------------------------------===//
435 //===----------------------------------------------------------------------===//
437 /// tryAssign - Try to assign VirtReg to an available register.
438 unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
439 AllocationOrder &Order,
440 SmallVectorImpl<LiveInterval*> &NewVRegs) {
443 while ((PhysReg = Order.next()))
444 if (!Matrix->checkInterference(VirtReg, PhysReg))
446 if (!PhysReg || Order.isHint(PhysReg))
449 // PhysReg is available, but there may be a better choice.
451 // If we missed a simple hint, try to cheaply evict interference from the
452 // preferred register.
453 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
454 if (Order.isHint(Hint)) {
455 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
456 EvictionCost MaxCost(1);
457 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
458 evictInterference(VirtReg, Hint, NewVRegs);
463 // Try to evict interference from a cheaper alternative.
464 unsigned Cost = TRI->getCostPerUse(PhysReg);
466 // Most registers have 0 additional cost.
470 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
472 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
473 return CheapReg ? CheapReg : PhysReg;
477 //===----------------------------------------------------------------------===//
478 // Interference eviction
479 //===----------------------------------------------------------------------===//
481 /// shouldEvict - determine if A should evict the assigned live range B. The
482 /// eviction policy defined by this function together with the allocation order
483 /// defined by enqueue() decides which registers ultimately end up being split
486 /// Cascade numbers are used to prevent infinite loops if this function is a
489 /// @param A The live range to be assigned.
490 /// @param IsHint True when A is about to be assigned to its preferred
492 /// @param B The live range to be evicted.
493 /// @param BreaksHint True when B is already assigned to its preferred register.
494 bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
495 LiveInterval &B, bool BreaksHint) {
496 bool CanSplit = getStage(B) < RS_Spill;
498 // Be fairly aggressive about following hints as long as the evictee can be
500 if (CanSplit && IsHint && !BreaksHint)
503 return A.weight > B.weight;
506 /// canEvictInterference - Return true if all interferences between VirtReg and
507 /// PhysReg can be evicted. When OnlyCheap is set, don't do anything
509 /// @param VirtReg Live range that is about to be assigned.
510 /// @param PhysReg Desired register for assignment.
511 /// @param IsHint True when PhysReg is VirtReg's preferred register.
512 /// @param MaxCost Only look for cheaper candidates and update with new cost
513 /// when returning true.
514 /// @returns True when interference can be evicted cheaper than MaxCost.
515 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
516 bool IsHint, EvictionCost &MaxCost) {
517 // It is only possible to evict virtual register interference.
518 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
521 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
522 // involved in an eviction before. If a cascade number was assigned, deny
523 // evicting anything with the same or a newer cascade number. This prevents
524 // infinite eviction loops.
526 // This works out so a register without a cascade number is allowed to evict
527 // anything, and it can be evicted by anything.
528 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
530 Cascade = NextCascade;
533 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
534 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
535 // If there is 10 or more interferences, chances are one is heavier.
536 if (Q.collectInterferingVRegs(10) >= 10)
539 // Check if any interfering live range is heavier than MaxWeight.
540 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
541 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
542 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
543 "Only expecting virtual register interference from query");
544 // Never evict spill products. They cannot split or spill.
545 if (getStage(*Intf) == RS_Done)
547 // Once a live range becomes small enough, it is urgent that we find a
548 // register for it. This is indicated by an infinite spill weight. These
549 // urgent live ranges get to evict almost anything.
551 // Also allow urgent evictions of unspillable ranges from a strictly
552 // larger allocation order.
553 bool Urgent = !VirtReg.isSpillable() &&
554 (Intf->isSpillable() ||
555 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
556 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
557 // Only evict older cascades or live ranges without a cascade.
558 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
559 if (Cascade <= IntfCascade) {
562 // We permit breaking cascades for urgent evictions. It should be the
563 // last resort, though, so make it really expensive.
564 Cost.BrokenHints += 10;
566 // Would this break a satisfied hint?
567 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
568 // Update eviction cost.
569 Cost.BrokenHints += BreaksHint;
570 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
571 // Abort if this would be too expensive.
572 if (!(Cost < MaxCost))
574 // Finally, apply the eviction policy for non-urgent evictions.
575 if (!Urgent && !shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
583 /// evictInterference - Evict any interferring registers that prevent VirtReg
584 /// from being assigned to Physreg. This assumes that canEvictInterference
586 void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
587 SmallVectorImpl<LiveInterval*> &NewVRegs) {
588 // Make sure that VirtReg has a cascade number, and assign that cascade
589 // number to every evicted register. These live ranges than then only be
590 // evicted by a newer cascade, preventing infinite loops.
591 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
593 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
595 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
596 << " interference: Cascade " << Cascade << '\n');
598 // Collect all interfering virtregs first.
599 SmallVector<LiveInterval*, 8> Intfs;
600 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
601 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
602 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
603 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
604 Intfs.append(IVR.begin(), IVR.end());
607 // Evict them second. This will invalidate the queries.
608 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
609 LiveInterval *Intf = Intfs[i];
610 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
611 if (!VRM->hasPhys(Intf->reg))
613 Matrix->unassign(*Intf);
614 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
615 VirtReg.isSpillable() < Intf->isSpillable()) &&
616 "Cannot decrease cascade number, illegal eviction");
617 ExtraRegInfo[Intf->reg].Cascade = Cascade;
619 NewVRegs.push_back(Intf);
623 /// tryEvict - Try to evict all interferences for a physreg.
624 /// @param VirtReg Currently unassigned virtual register.
625 /// @param Order Physregs to try.
626 /// @return Physreg to assign VirtReg, or 0.
627 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
628 AllocationOrder &Order,
629 SmallVectorImpl<LiveInterval*> &NewVRegs,
630 unsigned CostPerUseLimit) {
631 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
633 // Keep track of the cheapest interference seen so far.
634 EvictionCost BestCost(~0u);
635 unsigned BestPhys = 0;
637 // When we are just looking for a reduced cost per use, don't break any
638 // hints, and only evict smaller spill weights.
639 if (CostPerUseLimit < ~0u) {
640 BestCost.BrokenHints = 0;
641 BestCost.MaxWeight = VirtReg.weight;
645 while (unsigned PhysReg = Order.next()) {
646 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
648 // The first use of a callee-saved register in a function has cost 1.
649 // Don't start using a CSR when the CostPerUseLimit is low.
650 if (CostPerUseLimit == 1)
651 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
652 if (!MRI->isPhysRegUsed(CSR)) {
653 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
654 << PrintReg(CSR, TRI) << '\n');
658 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
664 // Stop if the hint can be used.
665 if (Order.isHint(PhysReg))
672 evictInterference(VirtReg, BestPhys, NewVRegs);
677 //===----------------------------------------------------------------------===//
679 //===----------------------------------------------------------------------===//
681 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
682 /// interference pattern in Physreg and its aliases. Add the constraints to
683 /// SpillPlacement and return the static cost of this split in Cost, assuming
684 /// that all preferences in SplitConstraints are met.
685 /// Return false if there are no bundles with positive bias.
686 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
688 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
690 // Reset interference dependent info.
691 SplitConstraints.resize(UseBlocks.size());
692 float StaticCost = 0;
693 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
694 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
695 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
697 BC.Number = BI.MBB->getNumber();
698 Intf.moveToBlock(BC.Number);
699 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
700 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
701 BC.ChangesValue = BI.FirstDef;
703 if (!Intf.hasInterference())
706 // Number of spill code instructions to insert.
709 // Interference for the live-in value.
711 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
712 BC.Entry = SpillPlacement::MustSpill, ++Ins;
713 else if (Intf.first() < BI.FirstInstr)
714 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
715 else if (Intf.first() < BI.LastInstr)
719 // Interference for the live-out value.
721 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
722 BC.Exit = SpillPlacement::MustSpill, ++Ins;
723 else if (Intf.last() > BI.LastInstr)
724 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
725 else if (Intf.last() > BI.FirstInstr)
729 // Accumulate the total frequency of inserted spill code.
731 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
735 // Add constraints for use-blocks. Note that these are the only constraints
736 // that may add a positive bias, it is downhill from here.
737 SpillPlacer->addConstraints(SplitConstraints);
738 return SpillPlacer->scanActiveBundles();
742 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
743 /// live-through blocks in Blocks.
744 void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
745 ArrayRef<unsigned> Blocks) {
746 const unsigned GroupSize = 8;
747 SpillPlacement::BlockConstraint BCS[GroupSize];
748 unsigned TBS[GroupSize];
749 unsigned B = 0, T = 0;
751 for (unsigned i = 0; i != Blocks.size(); ++i) {
752 unsigned Number = Blocks[i];
753 Intf.moveToBlock(Number);
755 if (!Intf.hasInterference()) {
756 assert(T < GroupSize && "Array overflow");
758 if (++T == GroupSize) {
759 SpillPlacer->addLinks(makeArrayRef(TBS, T));
765 assert(B < GroupSize && "Array overflow");
766 BCS[B].Number = Number;
768 // Interference for the live-in value.
769 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
770 BCS[B].Entry = SpillPlacement::MustSpill;
772 BCS[B].Entry = SpillPlacement::PrefSpill;
774 // Interference for the live-out value.
775 if (Intf.last() >= SA->getLastSplitPoint(Number))
776 BCS[B].Exit = SpillPlacement::MustSpill;
778 BCS[B].Exit = SpillPlacement::PrefSpill;
780 if (++B == GroupSize) {
781 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
782 SpillPlacer->addConstraints(Array);
787 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
788 SpillPlacer->addConstraints(Array);
789 SpillPlacer->addLinks(makeArrayRef(TBS, T));
792 void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
793 // Keep track of through blocks that have not been added to SpillPlacer.
794 BitVector Todo = SA->getThroughBlocks();
795 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
796 unsigned AddedTo = 0;
798 unsigned Visited = 0;
802 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
803 // Find new through blocks in the periphery of PrefRegBundles.
804 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
805 unsigned Bundle = NewBundles[i];
806 // Look at all blocks connected to Bundle in the full graph.
807 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
808 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
811 if (!Todo.test(Block))
814 // This is a new through block. Add it to SpillPlacer later.
815 ActiveBlocks.push_back(Block);
821 // Any new blocks to add?
822 if (ActiveBlocks.size() == AddedTo)
825 // Compute through constraints from the interference, or assume that all
826 // through blocks prefer spilling when forming compact regions.
827 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
829 addThroughConstraints(Cand.Intf, NewBlocks);
831 // Provide a strong negative bias on through blocks to prevent unwanted
832 // liveness on loop backedges.
833 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
834 AddedTo = ActiveBlocks.size();
836 // Perhaps iterating can enable more bundles?
837 SpillPlacer->iterate();
839 DEBUG(dbgs() << ", v=" << Visited);
842 /// calcCompactRegion - Compute the set of edge bundles that should be live
843 /// when splitting the current live range into compact regions. Compact
844 /// regions can be computed without looking at interference. They are the
845 /// regions formed by removing all the live-through blocks from the live range.
847 /// Returns false if the current live range is already compact, or if the
848 /// compact regions would form single block regions anyway.
849 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
850 // Without any through blocks, the live range is already compact.
851 if (!SA->getNumThroughBlocks())
854 // Compact regions don't correspond to any physreg.
855 Cand.reset(IntfCache, 0);
857 DEBUG(dbgs() << "Compact region bundles");
859 // Use the spill placer to determine the live bundles. GrowRegion pretends
860 // that all the through blocks have interference when PhysReg is unset.
861 SpillPlacer->prepare(Cand.LiveBundles);
863 // The static split cost will be zero since Cand.Intf reports no interference.
865 if (!addSplitConstraints(Cand.Intf, Cost)) {
866 DEBUG(dbgs() << ", none.\n");
871 SpillPlacer->finish();
873 if (!Cand.LiveBundles.any()) {
874 DEBUG(dbgs() << ", none.\n");
879 for (int i = Cand.LiveBundles.find_first(); i>=0;
880 i = Cand.LiveBundles.find_next(i))
881 dbgs() << " EB#" << i;
887 /// calcSpillCost - Compute how expensive it would be to split the live range in
888 /// SA around all use blocks instead of forming bundle regions.
889 float RAGreedy::calcSpillCost() {
891 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
892 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
893 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
894 unsigned Number = BI.MBB->getNumber();
895 // We normally only need one spill instruction - a load or a store.
896 Cost += SpillPlacer->getBlockFrequency(Number);
898 // Unless the value is redefined in the block.
899 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
900 Cost += SpillPlacer->getBlockFrequency(Number);
905 /// calcGlobalSplitCost - Return the global split cost of following the split
906 /// pattern in LiveBundles. This cost should be added to the local cost of the
907 /// interference pattern in SplitConstraints.
909 float RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
910 float GlobalCost = 0;
911 const BitVector &LiveBundles = Cand.LiveBundles;
912 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
913 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
914 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
915 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
916 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
917 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
921 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
923 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
925 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
928 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
929 unsigned Number = Cand.ActiveBlocks[i];
930 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
931 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
932 if (!RegIn && !RegOut)
934 if (RegIn && RegOut) {
935 // We need double spill code if this block has interference.
936 Cand.Intf.moveToBlock(Number);
937 if (Cand.Intf.hasInterference())
938 GlobalCost += 2*SpillPlacer->getBlockFrequency(Number);
941 // live-in / stack-out or stack-in live-out.
942 GlobalCost += SpillPlacer->getBlockFrequency(Number);
947 /// splitAroundRegion - Split the current live range around the regions
948 /// determined by BundleCand and GlobalCand.
950 /// Before calling this function, GlobalCand and BundleCand must be initialized
951 /// so each bundle is assigned to a valid candidate, or NoCand for the
952 /// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
953 /// objects must be initialized for the current live range, and intervals
954 /// created for the used candidates.
956 /// @param LREdit The LiveRangeEdit object handling the current split.
957 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
958 /// must appear in this list.
959 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
960 ArrayRef<unsigned> UsedCands) {
961 // These are the intervals created for new global ranges. We may create more
962 // intervals for local ranges.
963 const unsigned NumGlobalIntvs = LREdit.size();
964 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
965 assert(NumGlobalIntvs && "No global intervals configured");
967 // Isolate even single instructions when dealing with a proper sub-class.
968 // That guarantees register class inflation for the stack interval because it
970 unsigned Reg = SA->getParent().reg;
971 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
973 // First handle all the blocks with uses.
974 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
975 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
976 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
977 unsigned Number = BI.MBB->getNumber();
978 unsigned IntvIn = 0, IntvOut = 0;
979 SlotIndex IntfIn, IntfOut;
981 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
982 if (CandIn != NoCand) {
983 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
984 IntvIn = Cand.IntvIdx;
985 Cand.Intf.moveToBlock(Number);
986 IntfIn = Cand.Intf.first();
990 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
991 if (CandOut != NoCand) {
992 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
993 IntvOut = Cand.IntvIdx;
994 Cand.Intf.moveToBlock(Number);
995 IntfOut = Cand.Intf.last();
999 // Create separate intervals for isolated blocks with multiple uses.
1000 if (!IntvIn && !IntvOut) {
1001 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
1002 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1003 SE->splitSingleBlock(BI);
1007 if (IntvIn && IntvOut)
1008 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1010 SE->splitRegInBlock(BI, IntvIn, IntfIn);
1012 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
1015 // Handle live-through blocks. The relevant live-through blocks are stored in
1016 // the ActiveBlocks list with each candidate. We need to filter out
1018 BitVector Todo = SA->getThroughBlocks();
1019 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1020 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1021 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1022 unsigned Number = Blocks[i];
1023 if (!Todo.test(Number))
1027 unsigned IntvIn = 0, IntvOut = 0;
1028 SlotIndex IntfIn, IntfOut;
1030 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1031 if (CandIn != NoCand) {
1032 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1033 IntvIn = Cand.IntvIdx;
1034 Cand.Intf.moveToBlock(Number);
1035 IntfIn = Cand.Intf.first();
1038 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1039 if (CandOut != NoCand) {
1040 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1041 IntvOut = Cand.IntvIdx;
1042 Cand.Intf.moveToBlock(Number);
1043 IntfOut = Cand.Intf.last();
1045 if (!IntvIn && !IntvOut)
1047 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1053 SmallVector<unsigned, 8> IntvMap;
1054 SE->finish(&IntvMap);
1055 DebugVars->splitRegister(Reg, LREdit.regs());
1057 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1058 unsigned OrigBlocks = SA->getNumLiveBlocks();
1060 // Sort out the new intervals created by splitting. We get four kinds:
1061 // - Remainder intervals should not be split again.
1062 // - Candidate intervals can be assigned to Cand.PhysReg.
1063 // - Block-local splits are candidates for local splitting.
1064 // - DCE leftovers should go back on the queue.
1065 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1066 LiveInterval &Reg = *LREdit.get(i);
1068 // Ignore old intervals from DCE.
1069 if (getStage(Reg) != RS_New)
1072 // Remainder interval. Don't try splitting again, spill if it doesn't
1074 if (IntvMap[i] == 0) {
1075 setStage(Reg, RS_Spill);
1079 // Global intervals. Allow repeated splitting as long as the number of live
1080 // blocks is strictly decreasing.
1081 if (IntvMap[i] < NumGlobalIntvs) {
1082 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1083 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1084 << " blocks as original.\n");
1085 // Don't allow repeated splitting as a safe guard against looping.
1086 setStage(Reg, RS_Split2);
1091 // Other intervals are treated as new. This includes local intervals created
1092 // for blocks with multiple uses, and anything created by DCE.
1096 MF->verify(this, "After splitting live range around region");
1099 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1100 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1101 unsigned NumCands = 0;
1102 unsigned BestCand = NoCand;
1104 SmallVector<unsigned, 8> UsedCands;
1106 // Check if we can split this live range around a compact region.
1107 bool HasCompact = calcCompactRegion(GlobalCand.front());
1109 // Yes, keep GlobalCand[0] as the compact region candidate.
1111 BestCost = HUGE_VALF;
1113 // No benefit from the compact region, our fallback will be per-block
1114 // splitting. Make sure we find a solution that is cheaper than spilling.
1115 BestCost = Hysteresis * calcSpillCost();
1116 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1120 while (unsigned PhysReg = Order.next()) {
1121 // Discard bad candidates before we run out of interference cache cursors.
1122 // This will only affect register classes with a lot of registers (>32).
1123 if (NumCands == IntfCache.getMaxCursors()) {
1124 unsigned WorstCount = ~0u;
1126 for (unsigned i = 0; i != NumCands; ++i) {
1127 if (i == BestCand || !GlobalCand[i].PhysReg)
1129 unsigned Count = GlobalCand[i].LiveBundles.count();
1130 if (Count < WorstCount)
1131 Worst = i, WorstCount = Count;
1134 GlobalCand[Worst] = GlobalCand[NumCands];
1135 if (BestCand == NumCands)
1139 if (GlobalCand.size() <= NumCands)
1140 GlobalCand.resize(NumCands+1);
1141 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1142 Cand.reset(IntfCache, PhysReg);
1144 SpillPlacer->prepare(Cand.LiveBundles);
1146 if (!addSplitConstraints(Cand.Intf, Cost)) {
1147 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
1150 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
1151 if (Cost >= BestCost) {
1153 if (BestCand == NoCand)
1154 dbgs() << " worse than no bundles\n";
1156 dbgs() << " worse than "
1157 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1163 SpillPlacer->finish();
1165 // No live bundles, defer to splitSingleBlocks().
1166 if (!Cand.LiveBundles.any()) {
1167 DEBUG(dbgs() << " no bundles.\n");
1171 Cost += calcGlobalSplitCost(Cand);
1173 dbgs() << ", total = " << Cost << " with bundles";
1174 for (int i = Cand.LiveBundles.find_first(); i>=0;
1175 i = Cand.LiveBundles.find_next(i))
1176 dbgs() << " EB#" << i;
1179 if (Cost < BestCost) {
1180 BestCand = NumCands;
1181 BestCost = Hysteresis * Cost; // Prevent rounding effects.
1186 // No solutions found, fall back to single block splitting.
1187 if (!HasCompact && BestCand == NoCand)
1190 // Prepare split editor.
1191 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1192 SE->reset(LREdit, SplitSpillMode);
1194 // Assign all edge bundles to the preferred candidate, or NoCand.
1195 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1197 // Assign bundles for the best candidate region.
1198 if (BestCand != NoCand) {
1199 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1200 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1201 UsedCands.push_back(BestCand);
1202 Cand.IntvIdx = SE->openIntv();
1203 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1204 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
1209 // Assign bundles for the compact region.
1211 GlobalSplitCandidate &Cand = GlobalCand.front();
1212 assert(!Cand.PhysReg && "Compact region has no physreg");
1213 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1214 UsedCands.push_back(0);
1215 Cand.IntvIdx = SE->openIntv();
1216 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1217 << Cand.IntvIdx << ".\n");
1222 splitAroundRegion(LREdit, UsedCands);
1227 //===----------------------------------------------------------------------===//
1228 // Per-Block Splitting
1229 //===----------------------------------------------------------------------===//
1231 /// tryBlockSplit - Split a global live range around every block with uses. This
1232 /// creates a lot of local live ranges, that will be split by tryLocalSplit if
1233 /// they don't allocate.
1234 unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1235 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1236 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1237 unsigned Reg = VirtReg.reg;
1238 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1239 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1240 SE->reset(LREdit, SplitSpillMode);
1241 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1242 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1243 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1244 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1245 SE->splitSingleBlock(BI);
1247 // No blocks were split.
1251 // We did split for some blocks.
1252 SmallVector<unsigned, 8> IntvMap;
1253 SE->finish(&IntvMap);
1255 // Tell LiveDebugVariables about the new ranges.
1256 DebugVars->splitRegister(Reg, LREdit.regs());
1258 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1260 // Sort out the new intervals created by splitting. The remainder interval
1261 // goes straight to spilling, the new local ranges get to stay RS_New.
1262 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1263 LiveInterval &LI = *LREdit.get(i);
1264 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1265 setStage(LI, RS_Spill);
1269 MF->verify(this, "After splitting live range around basic blocks");
1274 //===----------------------------------------------------------------------===//
1275 // Per-Instruction Splitting
1276 //===----------------------------------------------------------------------===//
1278 /// tryInstructionSplit - Split a live range around individual instructions.
1279 /// This is normally not worthwhile since the spiller is doing essentially the
1280 /// same thing. However, when the live range is in a constrained register
1281 /// class, it may help to insert copies such that parts of the live range can
1282 /// be moved to a larger register class.
1284 /// This is similar to spilling to a larger register class.
1286 RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1287 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1288 // There is no point to this if there are no larger sub-classes.
1289 if (!RegClassInfo.isProperSubClass(MRI->getRegClass(VirtReg.reg)))
1292 // Always enable split spill mode, since we're effectively spilling to a
1294 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1295 SE->reset(LREdit, SplitEditor::SM_Size);
1297 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1298 if (Uses.size() <= 1)
1301 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1303 // Split around every non-copy instruction.
1304 for (unsigned i = 0; i != Uses.size(); ++i) {
1305 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1306 if (MI->isFullCopy()) {
1307 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1311 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1312 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1313 SE->useIntv(SegStart, SegStop);
1316 if (LREdit.empty()) {
1317 DEBUG(dbgs() << "All uses were copies.\n");
1321 SmallVector<unsigned, 8> IntvMap;
1322 SE->finish(&IntvMap);
1323 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1324 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1326 // Assign all new registers to RS_Spill. This was the last chance.
1327 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1332 //===----------------------------------------------------------------------===//
1334 //===----------------------------------------------------------------------===//
1337 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1338 /// in order to use PhysReg between two entries in SA->UseSlots.
1340 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1342 void RAGreedy::calcGapWeights(unsigned PhysReg,
1343 SmallVectorImpl<float> &GapWeight) {
1344 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1345 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1346 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1347 const unsigned NumGaps = Uses.size()-1;
1349 // Start and end points for the interference check.
1350 SlotIndex StartIdx =
1351 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1353 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
1355 GapWeight.assign(NumGaps, 0.0f);
1357 // Add interference from each overlapping register.
1358 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1359 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1360 .checkInterference())
1363 // We know that VirtReg is a continuous interval from FirstInstr to
1364 // LastInstr, so we don't need InterferenceQuery.
1366 // Interference that overlaps an instruction is counted in both gaps
1367 // surrounding the instruction. The exception is interference before
1368 // StartIdx and after StopIdx.
1370 LiveIntervalUnion::SegmentIter IntI =
1371 Matrix->getLiveUnions()[*Units] .find(StartIdx);
1372 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1373 // Skip the gaps before IntI.
1374 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1375 if (++Gap == NumGaps)
1380 // Update the gaps covered by IntI.
1381 const float weight = IntI.value()->weight;
1382 for (; Gap != NumGaps; ++Gap) {
1383 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1384 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1392 // Add fixed interference.
1393 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1394 const LiveInterval &LI = LIS->getRegUnit(*Units);
1395 LiveInterval::const_iterator I = LI.find(StartIdx);
1396 LiveInterval::const_iterator E = LI.end();
1398 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1399 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1400 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1401 if (++Gap == NumGaps)
1406 for (; Gap != NumGaps; ++Gap) {
1407 GapWeight[Gap] = HUGE_VALF;
1408 if (Uses[Gap+1].getBaseIndex() >= I->end)
1417 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1420 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1421 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1422 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1423 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1425 // Note that it is possible to have an interval that is live-in or live-out
1426 // while only covering a single block - A phi-def can use undef values from
1427 // predecessors, and the block could be a single-block loop.
1428 // We don't bother doing anything clever about such a case, we simply assume
1429 // that the interval is continuous from FirstInstr to LastInstr. We should
1430 // make sure that we don't do anything illegal to such an interval, though.
1432 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1433 if (Uses.size() <= 2)
1435 const unsigned NumGaps = Uses.size()-1;
1438 dbgs() << "tryLocalSplit: ";
1439 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1440 dbgs() << ' ' << Uses[i];
1444 // If VirtReg is live across any register mask operands, compute a list of
1445 // gaps with register masks.
1446 SmallVector<unsigned, 8> RegMaskGaps;
1447 if (Matrix->checkRegMaskInterference(VirtReg)) {
1448 // Get regmask slots for the whole block.
1449 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
1450 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
1451 // Constrain to VirtReg's live range.
1452 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1453 Uses.front().getRegSlot()) - RMS.begin();
1454 unsigned re = RMS.size();
1455 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
1456 // Look for Uses[i] <= RMS <= Uses[i+1].
1457 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1458 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
1460 // Skip a regmask on the same instruction as the last use. It doesn't
1461 // overlap the live range.
1462 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1464 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
1465 RegMaskGaps.push_back(i);
1466 // Advance ri to the next gap. A regmask on one of the uses counts in
1468 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1471 DEBUG(dbgs() << '\n');
1474 // Since we allow local split results to be split again, there is a risk of
1475 // creating infinite loops. It is tempting to require that the new live
1476 // ranges have less instructions than the original. That would guarantee
1477 // convergence, but it is too strict. A live range with 3 instructions can be
1478 // split 2+3 (including the COPY), and we want to allow that.
1480 // Instead we use these rules:
1482 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
1483 // noop split, of course).
1484 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
1485 // the new ranges must have fewer instructions than before the split.
1486 // 3. New ranges with the same number of instructions are marked RS_Split2,
1487 // smaller ranges are marked RS_New.
1489 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1490 // excessive splitting and infinite loops.
1492 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
1494 // Best split candidate.
1495 unsigned BestBefore = NumGaps;
1496 unsigned BestAfter = 0;
1499 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
1500 SmallVector<float, 8> GapWeight;
1503 while (unsigned PhysReg = Order.next()) {
1504 // Keep track of the largest spill weight that would need to be evicted in
1505 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1506 calcGapWeights(PhysReg, GapWeight);
1508 // Remove any gaps with regmask clobbers.
1509 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
1510 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1511 GapWeight[RegMaskGaps[i]] = HUGE_VALF;
1513 // Try to find the best sequence of gaps to close.
1514 // The new spill weight must be larger than any gap interference.
1516 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1517 unsigned SplitBefore = 0, SplitAfter = 1;
1519 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1520 // It is the spill weight that needs to be evicted.
1521 float MaxGap = GapWeight[0];
1524 // Live before/after split?
1525 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1526 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1528 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1529 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1530 << " i=" << MaxGap);
1532 // Stop before the interval gets so big we wouldn't be making progress.
1533 if (!LiveBefore && !LiveAfter) {
1534 DEBUG(dbgs() << " all\n");
1537 // Should the interval be extended or shrunk?
1540 // How many gaps would the new range have?
1541 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1543 // Legally, without causing looping?
1544 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1546 if (Legal && MaxGap < HUGE_VALF) {
1547 // Estimate the new spill weight. Each instruction reads or writes the
1548 // register. Conservatively assume there are no read-modify-write
1551 // Try to guess the size of the new interval.
1552 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1553 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1554 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
1555 // Would this split be possible to allocate?
1556 // Never allocate all gaps, we wouldn't be making progress.
1557 DEBUG(dbgs() << " w=" << EstWeight);
1558 if (EstWeight * Hysteresis >= MaxGap) {
1560 float Diff = EstWeight - MaxGap;
1561 if (Diff > BestDiff) {
1562 DEBUG(dbgs() << " (best)");
1563 BestDiff = Hysteresis * Diff;
1564 BestBefore = SplitBefore;
1565 BestAfter = SplitAfter;
1572 if (++SplitBefore < SplitAfter) {
1573 DEBUG(dbgs() << " shrink\n");
1574 // Recompute the max when necessary.
1575 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1576 MaxGap = GapWeight[SplitBefore];
1577 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1578 MaxGap = std::max(MaxGap, GapWeight[i]);
1585 // Try to extend the interval.
1586 if (SplitAfter >= NumGaps) {
1587 DEBUG(dbgs() << " end\n");
1591 DEBUG(dbgs() << " extend\n");
1592 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
1596 // Didn't find any candidates?
1597 if (BestBefore == NumGaps)
1600 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1601 << '-' << Uses[BestAfter] << ", " << BestDiff
1602 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1604 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1608 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1609 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1610 SE->useIntv(SegStart, SegStop);
1611 SmallVector<unsigned, 8> IntvMap;
1612 SE->finish(&IntvMap);
1613 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1615 // If the new range has the same number of instructions as before, mark it as
1616 // RS_Split2 so the next split will be forced to make progress. Otherwise,
1617 // leave the new intervals as RS_New so they can compete.
1618 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1619 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1620 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1621 if (NewGaps >= NumGaps) {
1622 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1623 assert(!ProgressRequired && "Didn't make progress when it was required.");
1624 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1625 if (IntvMap[i] == 1) {
1626 setStage(*LREdit.get(i), RS_Split2);
1627 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1629 DEBUG(dbgs() << '\n');
1636 //===----------------------------------------------------------------------===//
1637 // Live Range Splitting
1638 //===----------------------------------------------------------------------===//
1640 /// trySplit - Try to split VirtReg or one of its interferences, making it
1642 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1643 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1644 SmallVectorImpl<LiveInterval*>&NewVRegs) {
1645 // Ranges must be Split2 or less.
1646 if (getStage(VirtReg) >= RS_Spill)
1649 // Local intervals are handled separately.
1650 if (LIS->intervalIsInOneMBB(VirtReg)) {
1651 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
1652 SA->analyze(&VirtReg);
1653 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1654 if (PhysReg || !NewVRegs.empty())
1656 return tryInstructionSplit(VirtReg, Order, NewVRegs);
1659 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
1661 SA->analyze(&VirtReg);
1663 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1664 // coalescer. That may cause the range to become allocatable which means that
1665 // tryRegionSplit won't be making progress. This check should be replaced with
1666 // an assertion when the coalescer is fixed.
1667 if (SA->didRepairRange()) {
1668 // VirtReg has changed, so all cached queries are invalid.
1669 Matrix->invalidateVirtRegs();
1670 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1674 // First try to split around a region spanning multiple blocks. RS_Split2
1675 // ranges already made dubious progress with region splitting, so they go
1676 // straight to single block splitting.
1677 if (getStage(VirtReg) < RS_Split2) {
1678 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1679 if (PhysReg || !NewVRegs.empty())
1683 // Then isolate blocks.
1684 return tryBlockSplit(VirtReg, Order, NewVRegs);
1688 //===----------------------------------------------------------------------===//
1690 //===----------------------------------------------------------------------===//
1692 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
1693 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1694 // First try assigning a free register.
1695 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
1696 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1699 LiveRangeStage Stage = getStage(VirtReg);
1700 DEBUG(dbgs() << StageName[Stage]
1701 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
1703 // Try to evict a less worthy live range, but only for ranges from the primary
1704 // queue. The RS_Split ranges already failed to do this, and they should not
1705 // get a second chance until they have been split.
1706 if (Stage != RS_Split)
1707 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1710 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1712 // The first time we see a live range, don't try to split or spill.
1713 // Wait until the second time, when all smaller ranges have been allocated.
1714 // This gives a better picture of the interference to split around.
1715 if (Stage < RS_Split) {
1716 setStage(VirtReg, RS_Split);
1717 DEBUG(dbgs() << "wait for second round\n");
1718 NewVRegs.push_back(&VirtReg);
1722 // If we couldn't allocate a register from spilling, there is probably some
1723 // invalid inline assembly. The base class wil report it.
1724 if (Stage >= RS_Done || !VirtReg.isSpillable())
1727 // Try splitting VirtReg or interferences.
1728 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1729 if (PhysReg || !NewVRegs.empty())
1732 // Finally spill VirtReg itself.
1733 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
1734 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1735 spiller().spill(LRE);
1736 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
1739 MF->verify(this, "After spilling");
1741 // The live virtual register requesting allocation was spilled, so tell
1742 // the caller not to allocate anything during this round.
1746 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1747 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1748 << "********** Function: " << mf.getName() << '\n');
1752 MF->verify(this, "Before greedy register allocator");
1754 RegAllocBase::init(getAnalysis<VirtRegMap>(),
1755 getAnalysis<LiveIntervals>(),
1756 getAnalysis<LiveRegMatrix>());
1757 Indexes = &getAnalysis<SlotIndexes>();
1758 DomTree = &getAnalysis<MachineDominatorTree>();
1759 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
1760 Loops = &getAnalysis<MachineLoopInfo>();
1761 Bundles = &getAnalysis<EdgeBundles>();
1762 SpillPlacer = &getAnalysis<SpillPlacement>();
1763 DebugVars = &getAnalysis<LiveDebugVariables>();
1765 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
1766 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
1767 ExtraRegInfo.clear();
1768 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1770 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
1771 GlobalCand.resize(32); // This will grow as needed.