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 "llvm/CodeGen/Passes.h"
17 #include "AllocationOrder.h"
18 #include "InterferenceCache.h"
19 #include "LiveDebugVariables.h"
20 #include "RegAllocBase.h"
21 #include "SpillPlacement.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/CodeGen/CalcSpillWeights.h"
27 #include "llvm/CodeGen/EdgeBundles.h"
28 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
29 #include "llvm/CodeGen/LiveRangeEdit.h"
30 #include "llvm/CodeGen/LiveRegMatrix.h"
31 #include "llvm/CodeGen/LiveStackAnalysis.h"
32 #include "llvm/CodeGen/MachineBlockFrequencyInfo.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/RegAllocRegistry.h"
38 #include "llvm/CodeGen/VirtRegMap.h"
39 #include "llvm/PassAnalysisSupport.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/raw_ostream.h"
49 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
50 STATISTIC(NumLocalSplits, "Number of split local live ranges");
51 STATISTIC(NumEvicted, "Number of interferences evicted");
53 static cl::opt<SplitEditor::ComplementSpillMode>
54 SplitSpillMode("split-spill-mode", cl::Hidden,
55 cl::desc("Spill mode for splitting live ranges"),
56 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
57 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
58 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
60 cl::init(SplitEditor::SM_Partition));
62 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
63 createGreedyRegisterAllocator);
66 class RAGreedy : public MachineFunctionPass,
68 private LiveRangeEdit::Delegate {
75 MachineBlockFrequencyInfo *MBFI;
76 MachineDominatorTree *DomTree;
77 MachineLoopInfo *Loops;
79 SpillPlacement *SpillPlacer;
80 LiveDebugVariables *DebugVars;
83 OwningPtr<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 isMax() const { return BrokenHints == ~0u; }
165 bool operator<(const EvictionCost &O) const {
166 if (BrokenHints != O.BrokenHints)
167 return BrokenHints < O.BrokenHints;
168 return MaxWeight < O.MaxWeight;
173 OwningPtr<SplitAnalysis> SA;
174 OwningPtr<SplitEditor> SE;
176 /// Cached per-block interference maps
177 InterferenceCache IntfCache;
179 /// All basic blocks where the current register has uses.
180 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
182 /// Global live range splitting candidate info.
183 struct GlobalSplitCandidate {
184 // Register intended for assignment, or 0.
187 // SplitKit interval index for this candidate.
190 // Interference for PhysReg.
191 InterferenceCache::Cursor Intf;
193 // Bundles where this candidate should be live.
194 BitVector LiveBundles;
195 SmallVector<unsigned, 8> ActiveBlocks;
197 void reset(InterferenceCache &Cache, unsigned Reg) {
200 Intf.setPhysReg(Cache, Reg);
202 ActiveBlocks.clear();
205 // Set B[i] = C for every live bundle where B[i] was NoCand.
206 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
208 for (int i = LiveBundles.find_first(); i >= 0;
209 i = LiveBundles.find_next(i))
210 if (B[i] == NoCand) {
218 /// Candidate info for for each PhysReg in AllocationOrder.
219 /// This vector never shrinks, but grows to the size of the largest register
221 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
223 enum { NoCand = ~0u };
225 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
226 /// NoCand which indicates the stack interval.
227 SmallVector<unsigned, 32> BundleCand;
232 /// Return the pass name.
233 virtual const char* getPassName() const {
234 return "Greedy Register Allocator";
237 /// RAGreedy analysis usage.
238 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
239 virtual void releaseMemory();
240 virtual Spiller &spiller() { return *SpillerInstance; }
241 virtual void enqueue(LiveInterval *LI);
242 virtual LiveInterval *dequeue();
243 virtual unsigned selectOrSplit(LiveInterval&,
244 SmallVectorImpl<LiveInterval*>&);
246 /// Perform register allocation.
247 virtual bool runOnMachineFunction(MachineFunction &mf);
252 bool LRE_CanEraseVirtReg(unsigned);
253 void LRE_WillShrinkVirtReg(unsigned);
254 void LRE_DidCloneVirtReg(unsigned, unsigned);
256 BlockFrequency calcSpillCost();
257 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
258 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
259 void growRegion(GlobalSplitCandidate &Cand);
260 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate&);
261 bool calcCompactRegion(GlobalSplitCandidate&);
262 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
263 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
264 unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
265 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
266 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
267 void evictInterference(LiveInterval&, unsigned,
268 SmallVectorImpl<LiveInterval*>&);
270 unsigned tryAssign(LiveInterval&, AllocationOrder&,
271 SmallVectorImpl<LiveInterval*>&);
272 unsigned tryEvict(LiveInterval&, AllocationOrder&,
273 SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
274 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
275 SmallVectorImpl<LiveInterval*>&);
276 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
277 SmallVectorImpl<LiveInterval*>&);
278 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
279 SmallVectorImpl<LiveInterval*>&);
280 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
281 SmallVectorImpl<LiveInterval*>&);
282 unsigned trySplit(LiveInterval&, AllocationOrder&,
283 SmallVectorImpl<LiveInterval*>&);
285 } // end anonymous namespace
287 char RAGreedy::ID = 0;
290 const char *const RAGreedy::StageName[] = {
300 // Hysteresis to use when comparing floats.
301 // This helps stabilize decisions based on float comparisons.
302 const float Hysteresis = 0.98f;
305 FunctionPass* llvm::createGreedyRegisterAllocator() {
306 return new RAGreedy();
309 RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
310 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
311 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
312 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
313 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
314 initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
315 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
316 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
317 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
318 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
319 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
320 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
321 initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
322 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
323 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
326 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
327 AU.setPreservesCFG();
328 AU.addRequired<MachineBlockFrequencyInfo>();
329 AU.addPreserved<MachineBlockFrequencyInfo>();
330 AU.addRequired<AliasAnalysis>();
331 AU.addPreserved<AliasAnalysis>();
332 AU.addRequired<LiveIntervals>();
333 AU.addPreserved<LiveIntervals>();
334 AU.addRequired<SlotIndexes>();
335 AU.addPreserved<SlotIndexes>();
336 AU.addRequired<LiveDebugVariables>();
337 AU.addPreserved<LiveDebugVariables>();
338 AU.addRequired<LiveStacks>();
339 AU.addPreserved<LiveStacks>();
340 AU.addRequired<CalculateSpillWeights>();
341 AU.addRequired<MachineDominatorTree>();
342 AU.addPreserved<MachineDominatorTree>();
343 AU.addRequired<MachineLoopInfo>();
344 AU.addPreserved<MachineLoopInfo>();
345 AU.addRequired<VirtRegMap>();
346 AU.addPreserved<VirtRegMap>();
347 AU.addRequired<LiveRegMatrix>();
348 AU.addPreserved<LiveRegMatrix>();
349 AU.addRequired<EdgeBundles>();
350 AU.addRequired<SpillPlacement>();
351 MachineFunctionPass::getAnalysisUsage(AU);
355 //===----------------------------------------------------------------------===//
356 // LiveRangeEdit delegate methods
357 //===----------------------------------------------------------------------===//
359 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
360 if (VRM->hasPhys(VirtReg)) {
361 Matrix->unassign(LIS->getInterval(VirtReg));
364 // Unassigned virtreg is probably in the priority queue.
365 // RegAllocBase will erase it after dequeueing.
369 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
370 if (!VRM->hasPhys(VirtReg))
373 // Register is assigned, put it back on the queue for reassignment.
374 LiveInterval &LI = LIS->getInterval(VirtReg);
375 Matrix->unassign(LI);
379 void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
380 // Cloning a register we haven't even heard about yet? Just ignore it.
381 if (!ExtraRegInfo.inBounds(Old))
384 // LRE may clone a virtual register because dead code elimination causes it to
385 // be split into connected components. The new components are much smaller
386 // than the original, so they should get a new chance at being assigned.
387 // same stage as the parent.
388 ExtraRegInfo[Old].Stage = RS_Assign;
389 ExtraRegInfo.grow(New);
390 ExtraRegInfo[New] = ExtraRegInfo[Old];
393 void RAGreedy::releaseMemory() {
394 SpillerInstance.reset(0);
395 ExtraRegInfo.clear();
399 void RAGreedy::enqueue(LiveInterval *LI) {
400 // Prioritize live ranges by size, assigning larger ranges first.
401 // The queue holds (size, reg) pairs.
402 const unsigned Size = LI->getSize();
403 const unsigned Reg = LI->reg;
404 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
405 "Can only enqueue virtual registers");
408 ExtraRegInfo.grow(Reg);
409 if (ExtraRegInfo[Reg].Stage == RS_New)
410 ExtraRegInfo[Reg].Stage = RS_Assign;
412 if (ExtraRegInfo[Reg].Stage == RS_Split) {
413 // Unsplit ranges that couldn't be allocated immediately are deferred until
414 // everything else has been allocated.
417 if (ExtraRegInfo[Reg].Stage == RS_Assign && !LI->empty() &&
418 LIS->intervalIsInOneMBB(*LI)) {
419 // Allocate original local ranges in linear instruction order. Since they
420 // are singly defined, this produces optimal coloring in the absence of
421 // global interference and other constraints.
422 Prio = LI->beginIndex().distance(Indexes->getLastIndex());
425 // Allocate global and split ranges in long->short order. Long ranges that
426 // don't fit should be spilled (or split) ASAP so they don't create
427 // interference. Mark a bit to prioritize global above local ranges.
428 Prio = (1u << 29) + Size;
430 // Mark a higher bit to prioritize global and local above RS_Split.
433 // Boost ranges that have a physical register hint.
434 if (VRM->hasKnownPreference(Reg))
438 Queue.push(std::make_pair(Prio, ~Reg));
441 LiveInterval *RAGreedy::dequeue() {
444 LiveInterval *LI = &LIS->getInterval(~Queue.top().second);
450 //===----------------------------------------------------------------------===//
452 //===----------------------------------------------------------------------===//
454 /// tryAssign - Try to assign VirtReg to an available register.
455 unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
456 AllocationOrder &Order,
457 SmallVectorImpl<LiveInterval*> &NewVRegs) {
460 while ((PhysReg = Order.next()))
461 if (!Matrix->checkInterference(VirtReg, PhysReg))
463 if (!PhysReg || Order.isHint())
466 // PhysReg is available, but there may be a better choice.
468 // If we missed a simple hint, try to cheaply evict interference from the
469 // preferred register.
470 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
471 if (Order.isHint(Hint)) {
472 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
473 EvictionCost MaxCost(1);
474 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
475 evictInterference(VirtReg, Hint, NewVRegs);
480 // Try to evict interference from a cheaper alternative.
481 unsigned Cost = TRI->getCostPerUse(PhysReg);
483 // Most registers have 0 additional cost.
487 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
489 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
490 return CheapReg ? CheapReg : PhysReg;
494 //===----------------------------------------------------------------------===//
495 // Interference eviction
496 //===----------------------------------------------------------------------===//
498 unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
499 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
501 while ((PhysReg = Order.next())) {
502 if (PhysReg == PrevReg)
505 MCRegUnitIterator Units(PhysReg, TRI);
506 for (; Units.isValid(); ++Units) {
507 // Instantiate a "subquery", not to be confused with the Queries array.
508 LiveIntervalUnion::Query subQ(&VirtReg, &Matrix->getLiveUnions()[*Units]);
509 if (subQ.checkInterference())
512 // If no units have interference, break out with the current PhysReg.
513 if (!Units.isValid())
517 DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
518 << PrintReg(PrevReg, TRI) << " to " << PrintReg(PhysReg, TRI)
523 /// shouldEvict - determine if A should evict the assigned live range B. The
524 /// eviction policy defined by this function together with the allocation order
525 /// defined by enqueue() decides which registers ultimately end up being split
528 /// Cascade numbers are used to prevent infinite loops if this function is a
531 /// @param A The live range to be assigned.
532 /// @param IsHint True when A is about to be assigned to its preferred
534 /// @param B The live range to be evicted.
535 /// @param BreaksHint True when B is already assigned to its preferred register.
536 bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
537 LiveInterval &B, bool BreaksHint) {
538 bool CanSplit = getStage(B) < RS_Spill;
540 // Be fairly aggressive about following hints as long as the evictee can be
542 if (CanSplit && IsHint && !BreaksHint)
545 return A.weight > B.weight;
548 /// canEvictInterference - Return true if all interferences between VirtReg and
549 /// PhysReg can be evicted. When OnlyCheap is set, don't do anything
551 /// @param VirtReg Live range that is about to be assigned.
552 /// @param PhysReg Desired register for assignment.
553 /// @param IsHint True when PhysReg is VirtReg's preferred register.
554 /// @param MaxCost Only look for cheaper candidates and update with new cost
555 /// when returning true.
556 /// @returns True when interference can be evicted cheaper than MaxCost.
557 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
558 bool IsHint, EvictionCost &MaxCost) {
559 // It is only possible to evict virtual register interference.
560 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
563 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
565 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
566 // involved in an eviction before. If a cascade number was assigned, deny
567 // evicting anything with the same or a newer cascade number. This prevents
568 // infinite eviction loops.
570 // This works out so a register without a cascade number is allowed to evict
571 // anything, and it can be evicted by anything.
572 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
574 Cascade = NextCascade;
577 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
578 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
579 // If there is 10 or more interferences, chances are one is heavier.
580 if (Q.collectInterferingVRegs(10) >= 10)
583 // Check if any interfering live range is heavier than MaxWeight.
584 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
585 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
586 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
587 "Only expecting virtual register interference from query");
588 // Never evict spill products. They cannot split or spill.
589 if (getStage(*Intf) == RS_Done)
591 // Once a live range becomes small enough, it is urgent that we find a
592 // register for it. This is indicated by an infinite spill weight. These
593 // urgent live ranges get to evict almost anything.
595 // Also allow urgent evictions of unspillable ranges from a strictly
596 // larger allocation order.
597 bool Urgent = !VirtReg.isSpillable() &&
598 (Intf->isSpillable() ||
599 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
600 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
601 // Only evict older cascades or live ranges without a cascade.
602 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
603 if (Cascade <= IntfCascade) {
606 // We permit breaking cascades for urgent evictions. It should be the
607 // last resort, though, so make it really expensive.
608 Cost.BrokenHints += 10;
610 // Would this break a satisfied hint?
611 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
612 // Update eviction cost.
613 Cost.BrokenHints += BreaksHint;
614 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
615 // Abort if this would be too expensive.
616 if (!(Cost < MaxCost))
620 // If !MaxCost.isMax(), then we're just looking for a cheap register.
621 // Evicting another local live range in this case could lead to suboptimal
623 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
624 !canReassign(*Intf, PhysReg)) {
627 // Finally, apply the eviction policy for non-urgent evictions.
628 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
636 /// evictInterference - Evict any interferring registers that prevent VirtReg
637 /// from being assigned to Physreg. This assumes that canEvictInterference
639 void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
640 SmallVectorImpl<LiveInterval*> &NewVRegs) {
641 // Make sure that VirtReg has a cascade number, and assign that cascade
642 // number to every evicted register. These live ranges than then only be
643 // evicted by a newer cascade, preventing infinite loops.
644 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
646 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
648 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
649 << " interference: Cascade " << Cascade << '\n');
651 // Collect all interfering virtregs first.
652 SmallVector<LiveInterval*, 8> Intfs;
653 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
654 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
655 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
656 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
657 Intfs.append(IVR.begin(), IVR.end());
660 // Evict them second. This will invalidate the queries.
661 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
662 LiveInterval *Intf = Intfs[i];
663 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
664 if (!VRM->hasPhys(Intf->reg))
666 Matrix->unassign(*Intf);
667 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
668 VirtReg.isSpillable() < Intf->isSpillable()) &&
669 "Cannot decrease cascade number, illegal eviction");
670 ExtraRegInfo[Intf->reg].Cascade = Cascade;
672 NewVRegs.push_back(Intf);
676 /// tryEvict - Try to evict all interferences for a physreg.
677 /// @param VirtReg Currently unassigned virtual register.
678 /// @param Order Physregs to try.
679 /// @return Physreg to assign VirtReg, or 0.
680 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
681 AllocationOrder &Order,
682 SmallVectorImpl<LiveInterval*> &NewVRegs,
683 unsigned CostPerUseLimit) {
684 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
686 // Keep track of the cheapest interference seen so far.
687 EvictionCost BestCost(~0u);
688 unsigned BestPhys = 0;
689 unsigned OrderLimit = Order.getOrder().size();
691 // When we are just looking for a reduced cost per use, don't break any
692 // hints, and only evict smaller spill weights.
693 if (CostPerUseLimit < ~0u) {
694 BestCost.BrokenHints = 0;
695 BestCost.MaxWeight = VirtReg.weight;
697 // Check of any registers in RC are below CostPerUseLimit.
698 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
699 unsigned MinCost = RegClassInfo.getMinCost(RC);
700 if (MinCost >= CostPerUseLimit) {
701 DEBUG(dbgs() << RC->getName() << " minimum cost = " << MinCost
702 << ", no cheaper registers to be found.\n");
706 // It is normal for register classes to have a long tail of registers with
707 // the same cost. We don't need to look at them if they're too expensive.
708 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
709 OrderLimit = RegClassInfo.getLastCostChange(RC);
710 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
715 while (unsigned PhysReg = Order.nextWithDups(OrderLimit)) {
716 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
718 // The first use of a callee-saved register in a function has cost 1.
719 // Don't start using a CSR when the CostPerUseLimit is low.
720 if (CostPerUseLimit == 1)
721 if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
722 if (!MRI->isPhysRegUsed(CSR)) {
723 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
724 << PrintReg(CSR, TRI) << '\n');
728 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
734 // Stop if the hint can be used.
742 evictInterference(VirtReg, BestPhys, NewVRegs);
747 //===----------------------------------------------------------------------===//
749 //===----------------------------------------------------------------------===//
751 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
752 /// interference pattern in Physreg and its aliases. Add the constraints to
753 /// SpillPlacement and return the static cost of this split in Cost, assuming
754 /// that all preferences in SplitConstraints are met.
755 /// Return false if there are no bundles with positive bias.
756 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
757 BlockFrequency &Cost) {
758 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
760 // Reset interference dependent info.
761 SplitConstraints.resize(UseBlocks.size());
762 BlockFrequency StaticCost = 0;
763 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
764 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
765 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
767 BC.Number = BI.MBB->getNumber();
768 Intf.moveToBlock(BC.Number);
769 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
770 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
771 BC.ChangesValue = BI.FirstDef.isValid();
773 if (!Intf.hasInterference())
776 // Number of spill code instructions to insert.
779 // Interference for the live-in value.
781 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
782 BC.Entry = SpillPlacement::MustSpill, ++Ins;
783 else if (Intf.first() < BI.FirstInstr)
784 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
785 else if (Intf.first() < BI.LastInstr)
789 // Interference for the live-out value.
791 if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
792 BC.Exit = SpillPlacement::MustSpill, ++Ins;
793 else if (Intf.last() > BI.LastInstr)
794 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
795 else if (Intf.last() > BI.FirstInstr)
799 // Accumulate the total frequency of inserted spill code.
801 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
805 // Add constraints for use-blocks. Note that these are the only constraints
806 // that may add a positive bias, it is downhill from here.
807 SpillPlacer->addConstraints(SplitConstraints);
808 return SpillPlacer->scanActiveBundles();
812 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
813 /// live-through blocks in Blocks.
814 void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
815 ArrayRef<unsigned> Blocks) {
816 const unsigned GroupSize = 8;
817 SpillPlacement::BlockConstraint BCS[GroupSize];
818 unsigned TBS[GroupSize];
819 unsigned B = 0, T = 0;
821 for (unsigned i = 0; i != Blocks.size(); ++i) {
822 unsigned Number = Blocks[i];
823 Intf.moveToBlock(Number);
825 if (!Intf.hasInterference()) {
826 assert(T < GroupSize && "Array overflow");
828 if (++T == GroupSize) {
829 SpillPlacer->addLinks(makeArrayRef(TBS, T));
835 assert(B < GroupSize && "Array overflow");
836 BCS[B].Number = Number;
838 // Interference for the live-in value.
839 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
840 BCS[B].Entry = SpillPlacement::MustSpill;
842 BCS[B].Entry = SpillPlacement::PrefSpill;
844 // Interference for the live-out value.
845 if (Intf.last() >= SA->getLastSplitPoint(Number))
846 BCS[B].Exit = SpillPlacement::MustSpill;
848 BCS[B].Exit = SpillPlacement::PrefSpill;
850 if (++B == GroupSize) {
851 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
852 SpillPlacer->addConstraints(Array);
857 ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
858 SpillPlacer->addConstraints(Array);
859 SpillPlacer->addLinks(makeArrayRef(TBS, T));
862 void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
863 // Keep track of through blocks that have not been added to SpillPlacer.
864 BitVector Todo = SA->getThroughBlocks();
865 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
866 unsigned AddedTo = 0;
868 unsigned Visited = 0;
872 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
873 // Find new through blocks in the periphery of PrefRegBundles.
874 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
875 unsigned Bundle = NewBundles[i];
876 // Look at all blocks connected to Bundle in the full graph.
877 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
878 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
881 if (!Todo.test(Block))
884 // This is a new through block. Add it to SpillPlacer later.
885 ActiveBlocks.push_back(Block);
891 // Any new blocks to add?
892 if (ActiveBlocks.size() == AddedTo)
895 // Compute through constraints from the interference, or assume that all
896 // through blocks prefer spilling when forming compact regions.
897 ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
899 addThroughConstraints(Cand.Intf, NewBlocks);
901 // Provide a strong negative bias on through blocks to prevent unwanted
902 // liveness on loop backedges.
903 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
904 AddedTo = ActiveBlocks.size();
906 // Perhaps iterating can enable more bundles?
907 SpillPlacer->iterate();
909 DEBUG(dbgs() << ", v=" << Visited);
912 /// calcCompactRegion - Compute the set of edge bundles that should be live
913 /// when splitting the current live range into compact regions. Compact
914 /// regions can be computed without looking at interference. They are the
915 /// regions formed by removing all the live-through blocks from the live range.
917 /// Returns false if the current live range is already compact, or if the
918 /// compact regions would form single block regions anyway.
919 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
920 // Without any through blocks, the live range is already compact.
921 if (!SA->getNumThroughBlocks())
924 // Compact regions don't correspond to any physreg.
925 Cand.reset(IntfCache, 0);
927 DEBUG(dbgs() << "Compact region bundles");
929 // Use the spill placer to determine the live bundles. GrowRegion pretends
930 // that all the through blocks have interference when PhysReg is unset.
931 SpillPlacer->prepare(Cand.LiveBundles);
933 // The static split cost will be zero since Cand.Intf reports no interference.
935 if (!addSplitConstraints(Cand.Intf, Cost)) {
936 DEBUG(dbgs() << ", none.\n");
941 SpillPlacer->finish();
943 if (!Cand.LiveBundles.any()) {
944 DEBUG(dbgs() << ", none.\n");
949 for (int i = Cand.LiveBundles.find_first(); i>=0;
950 i = Cand.LiveBundles.find_next(i))
951 dbgs() << " EB#" << i;
957 /// calcSpillCost - Compute how expensive it would be to split the live range in
958 /// SA around all use blocks instead of forming bundle regions.
959 BlockFrequency RAGreedy::calcSpillCost() {
960 BlockFrequency Cost = 0;
961 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
962 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
963 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
964 unsigned Number = BI.MBB->getNumber();
965 // We normally only need one spill instruction - a load or a store.
966 Cost += SpillPlacer->getBlockFrequency(Number);
968 // Unless the value is redefined in the block.
969 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
970 Cost += SpillPlacer->getBlockFrequency(Number);
975 /// calcGlobalSplitCost - Return the global split cost of following the split
976 /// pattern in LiveBundles. This cost should be added to the local cost of the
977 /// interference pattern in SplitConstraints.
979 BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
980 BlockFrequency GlobalCost = 0;
981 const BitVector &LiveBundles = Cand.LiveBundles;
982 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
983 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
984 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
985 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
986 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
987 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
991 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
993 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
995 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
998 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
999 unsigned Number = Cand.ActiveBlocks[i];
1000 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
1001 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
1002 if (!RegIn && !RegOut)
1004 if (RegIn && RegOut) {
1005 // We need double spill code if this block has interference.
1006 Cand.Intf.moveToBlock(Number);
1007 if (Cand.Intf.hasInterference()) {
1008 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1009 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1013 // live-in / stack-out or stack-in live-out.
1014 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1019 /// splitAroundRegion - Split the current live range around the regions
1020 /// determined by BundleCand and GlobalCand.
1022 /// Before calling this function, GlobalCand and BundleCand must be initialized
1023 /// so each bundle is assigned to a valid candidate, or NoCand for the
1024 /// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1025 /// objects must be initialized for the current live range, and intervals
1026 /// created for the used candidates.
1028 /// @param LREdit The LiveRangeEdit object handling the current split.
1029 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1030 /// must appear in this list.
1031 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1032 ArrayRef<unsigned> UsedCands) {
1033 // These are the intervals created for new global ranges. We may create more
1034 // intervals for local ranges.
1035 const unsigned NumGlobalIntvs = LREdit.size();
1036 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1037 assert(NumGlobalIntvs && "No global intervals configured");
1039 // Isolate even single instructions when dealing with a proper sub-class.
1040 // That guarantees register class inflation for the stack interval because it
1042 unsigned Reg = SA->getParent().reg;
1043 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1045 // First handle all the blocks with uses.
1046 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1047 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1048 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1049 unsigned Number = BI.MBB->getNumber();
1050 unsigned IntvIn = 0, IntvOut = 0;
1051 SlotIndex IntfIn, IntfOut;
1053 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1054 if (CandIn != NoCand) {
1055 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1056 IntvIn = Cand.IntvIdx;
1057 Cand.Intf.moveToBlock(Number);
1058 IntfIn = Cand.Intf.first();
1062 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1063 if (CandOut != NoCand) {
1064 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1065 IntvOut = Cand.IntvIdx;
1066 Cand.Intf.moveToBlock(Number);
1067 IntfOut = Cand.Intf.last();
1071 // Create separate intervals for isolated blocks with multiple uses.
1072 if (!IntvIn && !IntvOut) {
1073 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
1074 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1075 SE->splitSingleBlock(BI);
1079 if (IntvIn && IntvOut)
1080 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1082 SE->splitRegInBlock(BI, IntvIn, IntfIn);
1084 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
1087 // Handle live-through blocks. The relevant live-through blocks are stored in
1088 // the ActiveBlocks list with each candidate. We need to filter out
1090 BitVector Todo = SA->getThroughBlocks();
1091 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1092 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1093 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1094 unsigned Number = Blocks[i];
1095 if (!Todo.test(Number))
1099 unsigned IntvIn = 0, IntvOut = 0;
1100 SlotIndex IntfIn, IntfOut;
1102 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1103 if (CandIn != NoCand) {
1104 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1105 IntvIn = Cand.IntvIdx;
1106 Cand.Intf.moveToBlock(Number);
1107 IntfIn = Cand.Intf.first();
1110 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1111 if (CandOut != NoCand) {
1112 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1113 IntvOut = Cand.IntvIdx;
1114 Cand.Intf.moveToBlock(Number);
1115 IntfOut = Cand.Intf.last();
1117 if (!IntvIn && !IntvOut)
1119 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1125 SmallVector<unsigned, 8> IntvMap;
1126 SE->finish(&IntvMap);
1127 DebugVars->splitRegister(Reg, LREdit.regs());
1129 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1130 unsigned OrigBlocks = SA->getNumLiveBlocks();
1132 // Sort out the new intervals created by splitting. We get four kinds:
1133 // - Remainder intervals should not be split again.
1134 // - Candidate intervals can be assigned to Cand.PhysReg.
1135 // - Block-local splits are candidates for local splitting.
1136 // - DCE leftovers should go back on the queue.
1137 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1138 LiveInterval &Reg = *LREdit.get(i);
1140 // Ignore old intervals from DCE.
1141 if (getStage(Reg) != RS_New)
1144 // Remainder interval. Don't try splitting again, spill if it doesn't
1146 if (IntvMap[i] == 0) {
1147 setStage(Reg, RS_Spill);
1151 // Global intervals. Allow repeated splitting as long as the number of live
1152 // blocks is strictly decreasing.
1153 if (IntvMap[i] < NumGlobalIntvs) {
1154 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1155 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1156 << " blocks as original.\n");
1157 // Don't allow repeated splitting as a safe guard against looping.
1158 setStage(Reg, RS_Split2);
1163 // Other intervals are treated as new. This includes local intervals created
1164 // for blocks with multiple uses, and anything created by DCE.
1168 MF->verify(this, "After splitting live range around region");
1171 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1172 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1173 unsigned NumCands = 0;
1174 unsigned BestCand = NoCand;
1175 BlockFrequency BestCost;
1176 SmallVector<unsigned, 8> UsedCands;
1178 // Check if we can split this live range around a compact region.
1179 bool HasCompact = calcCompactRegion(GlobalCand.front());
1181 // Yes, keep GlobalCand[0] as the compact region candidate.
1183 BestCost = BlockFrequency::getMaxFrequency();
1185 // No benefit from the compact region, our fallback will be per-block
1186 // splitting. Make sure we find a solution that is cheaper than spilling.
1187 BestCost = calcSpillCost();
1188 DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1192 while (unsigned PhysReg = Order.next()) {
1193 // Discard bad candidates before we run out of interference cache cursors.
1194 // This will only affect register classes with a lot of registers (>32).
1195 if (NumCands == IntfCache.getMaxCursors()) {
1196 unsigned WorstCount = ~0u;
1198 for (unsigned i = 0; i != NumCands; ++i) {
1199 if (i == BestCand || !GlobalCand[i].PhysReg)
1201 unsigned Count = GlobalCand[i].LiveBundles.count();
1202 if (Count < WorstCount)
1203 Worst = i, WorstCount = Count;
1206 GlobalCand[Worst] = GlobalCand[NumCands];
1207 if (BestCand == NumCands)
1211 if (GlobalCand.size() <= NumCands)
1212 GlobalCand.resize(NumCands+1);
1213 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1214 Cand.reset(IntfCache, PhysReg);
1216 SpillPlacer->prepare(Cand.LiveBundles);
1217 BlockFrequency Cost;
1218 if (!addSplitConstraints(Cand.Intf, Cost)) {
1219 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
1222 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
1223 if (Cost >= BestCost) {
1225 if (BestCand == NoCand)
1226 dbgs() << " worse than no bundles\n";
1228 dbgs() << " worse than "
1229 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1235 SpillPlacer->finish();
1237 // No live bundles, defer to splitSingleBlocks().
1238 if (!Cand.LiveBundles.any()) {
1239 DEBUG(dbgs() << " no bundles.\n");
1243 Cost += calcGlobalSplitCost(Cand);
1245 dbgs() << ", total = " << Cost << " with bundles";
1246 for (int i = Cand.LiveBundles.find_first(); i>=0;
1247 i = Cand.LiveBundles.find_next(i))
1248 dbgs() << " EB#" << i;
1251 if (Cost < BestCost) {
1252 BestCand = NumCands;
1258 // No solutions found, fall back to single block splitting.
1259 if (!HasCompact && BestCand == NoCand)
1262 // Prepare split editor.
1263 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1264 SE->reset(LREdit, SplitSpillMode);
1266 // Assign all edge bundles to the preferred candidate, or NoCand.
1267 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1269 // Assign bundles for the best candidate region.
1270 if (BestCand != NoCand) {
1271 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1272 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1273 UsedCands.push_back(BestCand);
1274 Cand.IntvIdx = SE->openIntv();
1275 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1276 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
1281 // Assign bundles for the compact region.
1283 GlobalSplitCandidate &Cand = GlobalCand.front();
1284 assert(!Cand.PhysReg && "Compact region has no physreg");
1285 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1286 UsedCands.push_back(0);
1287 Cand.IntvIdx = SE->openIntv();
1288 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1289 << Cand.IntvIdx << ".\n");
1294 splitAroundRegion(LREdit, UsedCands);
1299 //===----------------------------------------------------------------------===//
1300 // Per-Block Splitting
1301 //===----------------------------------------------------------------------===//
1303 /// tryBlockSplit - Split a global live range around every block with uses. This
1304 /// creates a lot of local live ranges, that will be split by tryLocalSplit if
1305 /// they don't allocate.
1306 unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1307 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1308 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1309 unsigned Reg = VirtReg.reg;
1310 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1311 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1312 SE->reset(LREdit, SplitSpillMode);
1313 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1314 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1315 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1316 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1317 SE->splitSingleBlock(BI);
1319 // No blocks were split.
1323 // We did split for some blocks.
1324 SmallVector<unsigned, 8> IntvMap;
1325 SE->finish(&IntvMap);
1327 // Tell LiveDebugVariables about the new ranges.
1328 DebugVars->splitRegister(Reg, LREdit.regs());
1330 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1332 // Sort out the new intervals created by splitting. The remainder interval
1333 // goes straight to spilling, the new local ranges get to stay RS_New.
1334 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1335 LiveInterval &LI = *LREdit.get(i);
1336 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1337 setStage(LI, RS_Spill);
1341 MF->verify(this, "After splitting live range around basic blocks");
1346 //===----------------------------------------------------------------------===//
1347 // Per-Instruction Splitting
1348 //===----------------------------------------------------------------------===//
1350 /// tryInstructionSplit - Split a live range around individual instructions.
1351 /// This is normally not worthwhile since the spiller is doing essentially the
1352 /// same thing. However, when the live range is in a constrained register
1353 /// class, it may help to insert copies such that parts of the live range can
1354 /// be moved to a larger register class.
1356 /// This is similar to spilling to a larger register class.
1358 RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1359 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1360 // There is no point to this if there are no larger sub-classes.
1361 if (!RegClassInfo.isProperSubClass(MRI->getRegClass(VirtReg.reg)))
1364 // Always enable split spill mode, since we're effectively spilling to a
1366 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1367 SE->reset(LREdit, SplitEditor::SM_Size);
1369 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1370 if (Uses.size() <= 1)
1373 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1375 // Split around every non-copy instruction.
1376 for (unsigned i = 0; i != Uses.size(); ++i) {
1377 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1378 if (MI->isFullCopy()) {
1379 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1383 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1384 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1385 SE->useIntv(SegStart, SegStop);
1388 if (LREdit.empty()) {
1389 DEBUG(dbgs() << "All uses were copies.\n");
1393 SmallVector<unsigned, 8> IntvMap;
1394 SE->finish(&IntvMap);
1395 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1396 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1398 // Assign all new registers to RS_Spill. This was the last chance.
1399 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1404 //===----------------------------------------------------------------------===//
1406 //===----------------------------------------------------------------------===//
1409 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1410 /// in order to use PhysReg between two entries in SA->UseSlots.
1412 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1414 void RAGreedy::calcGapWeights(unsigned PhysReg,
1415 SmallVectorImpl<float> &GapWeight) {
1416 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1417 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1418 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1419 const unsigned NumGaps = Uses.size()-1;
1421 // Start and end points for the interference check.
1422 SlotIndex StartIdx =
1423 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1425 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
1427 GapWeight.assign(NumGaps, 0.0f);
1429 // Add interference from each overlapping register.
1430 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1431 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1432 .checkInterference())
1435 // We know that VirtReg is a continuous interval from FirstInstr to
1436 // LastInstr, so we don't need InterferenceQuery.
1438 // Interference that overlaps an instruction is counted in both gaps
1439 // surrounding the instruction. The exception is interference before
1440 // StartIdx and after StopIdx.
1442 LiveIntervalUnion::SegmentIter IntI =
1443 Matrix->getLiveUnions()[*Units] .find(StartIdx);
1444 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1445 // Skip the gaps before IntI.
1446 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1447 if (++Gap == NumGaps)
1452 // Update the gaps covered by IntI.
1453 const float weight = IntI.value()->weight;
1454 for (; Gap != NumGaps; ++Gap) {
1455 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1456 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1464 // Add fixed interference.
1465 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1466 const LiveInterval &LI = LIS->getRegUnit(*Units);
1467 LiveInterval::const_iterator I = LI.find(StartIdx);
1468 LiveInterval::const_iterator E = LI.end();
1470 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1471 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1472 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1473 if (++Gap == NumGaps)
1478 for (; Gap != NumGaps; ++Gap) {
1479 GapWeight[Gap] = HUGE_VALF;
1480 if (Uses[Gap+1].getBaseIndex() >= I->end)
1489 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1492 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1493 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1494 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1495 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1497 // Note that it is possible to have an interval that is live-in or live-out
1498 // while only covering a single block - A phi-def can use undef values from
1499 // predecessors, and the block could be a single-block loop.
1500 // We don't bother doing anything clever about such a case, we simply assume
1501 // that the interval is continuous from FirstInstr to LastInstr. We should
1502 // make sure that we don't do anything illegal to such an interval, though.
1504 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1505 if (Uses.size() <= 2)
1507 const unsigned NumGaps = Uses.size()-1;
1510 dbgs() << "tryLocalSplit: ";
1511 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1512 dbgs() << ' ' << Uses[i];
1516 // If VirtReg is live across any register mask operands, compute a list of
1517 // gaps with register masks.
1518 SmallVector<unsigned, 8> RegMaskGaps;
1519 if (Matrix->checkRegMaskInterference(VirtReg)) {
1520 // Get regmask slots for the whole block.
1521 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
1522 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
1523 // Constrain to VirtReg's live range.
1524 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1525 Uses.front().getRegSlot()) - RMS.begin();
1526 unsigned re = RMS.size();
1527 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
1528 // Look for Uses[i] <= RMS <= Uses[i+1].
1529 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1530 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
1532 // Skip a regmask on the same instruction as the last use. It doesn't
1533 // overlap the live range.
1534 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1536 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
1537 RegMaskGaps.push_back(i);
1538 // Advance ri to the next gap. A regmask on one of the uses counts in
1540 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1543 DEBUG(dbgs() << '\n');
1546 // Since we allow local split results to be split again, there is a risk of
1547 // creating infinite loops. It is tempting to require that the new live
1548 // ranges have less instructions than the original. That would guarantee
1549 // convergence, but it is too strict. A live range with 3 instructions can be
1550 // split 2+3 (including the COPY), and we want to allow that.
1552 // Instead we use these rules:
1554 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
1555 // noop split, of course).
1556 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
1557 // the new ranges must have fewer instructions than before the split.
1558 // 3. New ranges with the same number of instructions are marked RS_Split2,
1559 // smaller ranges are marked RS_New.
1561 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1562 // excessive splitting and infinite loops.
1564 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
1566 // Best split candidate.
1567 unsigned BestBefore = NumGaps;
1568 unsigned BestAfter = 0;
1571 const float blockFreq =
1572 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
1573 (1.0f / BlockFrequency::getEntryFrequency());
1574 SmallVector<float, 8> GapWeight;
1577 while (unsigned PhysReg = Order.next()) {
1578 // Keep track of the largest spill weight that would need to be evicted in
1579 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1580 calcGapWeights(PhysReg, GapWeight);
1582 // Remove any gaps with regmask clobbers.
1583 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
1584 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1585 GapWeight[RegMaskGaps[i]] = HUGE_VALF;
1587 // Try to find the best sequence of gaps to close.
1588 // The new spill weight must be larger than any gap interference.
1590 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1591 unsigned SplitBefore = 0, SplitAfter = 1;
1593 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1594 // It is the spill weight that needs to be evicted.
1595 float MaxGap = GapWeight[0];
1598 // Live before/after split?
1599 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1600 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1602 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1603 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1604 << " i=" << MaxGap);
1606 // Stop before the interval gets so big we wouldn't be making progress.
1607 if (!LiveBefore && !LiveAfter) {
1608 DEBUG(dbgs() << " all\n");
1611 // Should the interval be extended or shrunk?
1614 // How many gaps would the new range have?
1615 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1617 // Legally, without causing looping?
1618 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1620 if (Legal && MaxGap < HUGE_VALF) {
1621 // Estimate the new spill weight. Each instruction reads or writes the
1622 // register. Conservatively assume there are no read-modify-write
1625 // Try to guess the size of the new interval.
1626 const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1627 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1628 (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
1629 // Would this split be possible to allocate?
1630 // Never allocate all gaps, we wouldn't be making progress.
1631 DEBUG(dbgs() << " w=" << EstWeight);
1632 if (EstWeight * Hysteresis >= MaxGap) {
1634 float Diff = EstWeight - MaxGap;
1635 if (Diff > BestDiff) {
1636 DEBUG(dbgs() << " (best)");
1637 BestDiff = Hysteresis * Diff;
1638 BestBefore = SplitBefore;
1639 BestAfter = SplitAfter;
1646 if (++SplitBefore < SplitAfter) {
1647 DEBUG(dbgs() << " shrink\n");
1648 // Recompute the max when necessary.
1649 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1650 MaxGap = GapWeight[SplitBefore];
1651 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1652 MaxGap = std::max(MaxGap, GapWeight[i]);
1659 // Try to extend the interval.
1660 if (SplitAfter >= NumGaps) {
1661 DEBUG(dbgs() << " end\n");
1665 DEBUG(dbgs() << " extend\n");
1666 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
1670 // Didn't find any candidates?
1671 if (BestBefore == NumGaps)
1674 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1675 << '-' << Uses[BestAfter] << ", " << BestDiff
1676 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1678 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1682 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1683 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1684 SE->useIntv(SegStart, SegStop);
1685 SmallVector<unsigned, 8> IntvMap;
1686 SE->finish(&IntvMap);
1687 DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1689 // If the new range has the same number of instructions as before, mark it as
1690 // RS_Split2 so the next split will be forced to make progress. Otherwise,
1691 // leave the new intervals as RS_New so they can compete.
1692 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1693 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1694 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1695 if (NewGaps >= NumGaps) {
1696 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1697 assert(!ProgressRequired && "Didn't make progress when it was required.");
1698 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1699 if (IntvMap[i] == 1) {
1700 setStage(*LREdit.get(i), RS_Split2);
1701 DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1703 DEBUG(dbgs() << '\n');
1710 //===----------------------------------------------------------------------===//
1711 // Live Range Splitting
1712 //===----------------------------------------------------------------------===//
1714 /// trySplit - Try to split VirtReg or one of its interferences, making it
1716 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1717 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1718 SmallVectorImpl<LiveInterval*>&NewVRegs) {
1719 // Ranges must be Split2 or less.
1720 if (getStage(VirtReg) >= RS_Spill)
1723 // Local intervals are handled separately.
1724 if (LIS->intervalIsInOneMBB(VirtReg)) {
1725 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
1726 SA->analyze(&VirtReg);
1727 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1728 if (PhysReg || !NewVRegs.empty())
1730 return tryInstructionSplit(VirtReg, Order, NewVRegs);
1733 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
1735 SA->analyze(&VirtReg);
1737 // FIXME: SplitAnalysis may repair broken live ranges coming from the
1738 // coalescer. That may cause the range to become allocatable which means that
1739 // tryRegionSplit won't be making progress. This check should be replaced with
1740 // an assertion when the coalescer is fixed.
1741 if (SA->didRepairRange()) {
1742 // VirtReg has changed, so all cached queries are invalid.
1743 Matrix->invalidateVirtRegs();
1744 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1748 // First try to split around a region spanning multiple blocks. RS_Split2
1749 // ranges already made dubious progress with region splitting, so they go
1750 // straight to single block splitting.
1751 if (getStage(VirtReg) < RS_Split2) {
1752 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1753 if (PhysReg || !NewVRegs.empty())
1757 // Then isolate blocks.
1758 return tryBlockSplit(VirtReg, Order, NewVRegs);
1762 //===----------------------------------------------------------------------===//
1764 //===----------------------------------------------------------------------===//
1766 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
1767 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1768 // First try assigning a free register.
1769 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
1770 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1773 LiveRangeStage Stage = getStage(VirtReg);
1774 DEBUG(dbgs() << StageName[Stage]
1775 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
1777 // Try to evict a less worthy live range, but only for ranges from the primary
1778 // queue. The RS_Split ranges already failed to do this, and they should not
1779 // get a second chance until they have been split.
1780 if (Stage != RS_Split)
1781 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1784 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1786 // The first time we see a live range, don't try to split or spill.
1787 // Wait until the second time, when all smaller ranges have been allocated.
1788 // This gives a better picture of the interference to split around.
1789 if (Stage < RS_Split) {
1790 setStage(VirtReg, RS_Split);
1791 DEBUG(dbgs() << "wait for second round\n");
1792 NewVRegs.push_back(&VirtReg);
1796 // If we couldn't allocate a register from spilling, there is probably some
1797 // invalid inline assembly. The base class wil report it.
1798 if (Stage >= RS_Done || !VirtReg.isSpillable())
1801 // Try splitting VirtReg or interferences.
1802 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1803 if (PhysReg || !NewVRegs.empty())
1806 // Finally spill VirtReg itself.
1807 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
1808 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1809 spiller().spill(LRE);
1810 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
1813 MF->verify(this, "After spilling");
1815 // The live virtual register requesting allocation was spilled, so tell
1816 // the caller not to allocate anything during this round.
1820 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1821 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1822 << "********** Function: " << mf.getName() << '\n');
1826 MF->verify(this, "Before greedy register allocator");
1828 RegAllocBase::init(getAnalysis<VirtRegMap>(),
1829 getAnalysis<LiveIntervals>(),
1830 getAnalysis<LiveRegMatrix>());
1831 Indexes = &getAnalysis<SlotIndexes>();
1832 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1833 DomTree = &getAnalysis<MachineDominatorTree>();
1834 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
1835 Loops = &getAnalysis<MachineLoopInfo>();
1836 Bundles = &getAnalysis<EdgeBundles>();
1837 SpillPlacer = &getAnalysis<SpillPlacement>();
1838 DebugVars = &getAnalysis<LiveDebugVariables>();
1842 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
1843 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
1844 ExtraRegInfo.clear();
1845 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1847 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
1848 GlobalCand.resize(32); // This will grow as needed.