blob: 1529545b86c5f169c3e83d0b67b17059bc2b7cf8 [file] [log] [blame]
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001//===-- RegAllocGreedy.cpp - greedy register allocator --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the RAGreedy function pass for register allocation in
11// optimized builds.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "regalloc"
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +000016#include "AllocationOrder.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000017#include "LiveIntervalUnion.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000018#include "LiveRangeEdit.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000019#include "RegAllocBase.h"
20#include "Spiller.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000021#include "SpillPlacement.h"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000022#include "SplitKit.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000023#include "VirtRegMap.h"
24#include "VirtRegRewriter.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000025#include "llvm/Analysis/AliasAnalysis.h"
26#include "llvm/Function.h"
27#include "llvm/PassAnalysisSupport.h"
28#include "llvm/CodeGen/CalcSpillWeights.h"
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000029#include "llvm/CodeGen/EdgeBundles.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000030#include "llvm/CodeGen/LiveIntervalAnalysis.h"
31#include "llvm/CodeGen/LiveStackAnalysis.h"
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000032#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000033#include "llvm/CodeGen/MachineFunctionPass.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000034#include "llvm/CodeGen/MachineLoopInfo.h"
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000035#include "llvm/CodeGen/MachineLoopRanges.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000036#include "llvm/CodeGen/MachineRegisterInfo.h"
37#include "llvm/CodeGen/Passes.h"
38#include "llvm/CodeGen/RegAllocRegistry.h"
39#include "llvm/CodeGen/RegisterCoalescer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000040#include "llvm/Target/TargetOptions.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000041#include "llvm/Support/Debug.h"
42#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000044#include "llvm/Support/Timer.h"
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000045
46using namespace llvm;
47
48static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
49 createGreedyRegisterAllocator);
50
51namespace {
52class RAGreedy : public MachineFunctionPass, public RegAllocBase {
53 // context
54 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000055 BitVector ReservedRegs;
56
57 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000058 SlotIndexes *Indexes;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000059 LiveStacks *LS;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000060 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000061 MachineLoopInfo *Loops;
62 MachineLoopRanges *LoopRanges;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000063 EdgeBundles *Bundles;
64 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000065
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000066 // state
67 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000068 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000069
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000070 // splitting state.
71
72 /// All basic blocks where the current register is live.
73 SmallVector<SpillPlacement::BlockConstraint, 8> SpillConstraints;
74
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000075public:
76 RAGreedy();
77
78 /// Return the pass name.
79 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +000080 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000081 }
82
83 /// RAGreedy analysis usage.
84 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
85
86 virtual void releaseMemory();
87
88 virtual Spiller &spiller() { return *SpillerInstance; }
89
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +000090 virtual float getPriority(LiveInterval *LI);
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +000091
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +000092 virtual unsigned selectOrSplit(LiveInterval&,
93 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000094
95 /// Perform register allocation.
96 virtual bool runOnMachineFunction(MachineFunction &mf);
97
98 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +000099
100private:
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000101 bool checkUncachedInterference(LiveInterval&, unsigned);
102 LiveInterval *getSingleInterference(LiveInterval&, unsigned);
Andrew Trickb853e6c2010-12-09 18:15:21 +0000103 bool reassignVReg(LiveInterval &InterferingVReg, unsigned OldPhysReg);
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000104 float calcInterferenceWeight(LiveInterval&, unsigned);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000105 float calcInterferenceInfo(LiveInterval&, unsigned);
106 float calcGlobalSplitCost(const BitVector&);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000107 void splitAroundRegion(LiveInterval&, unsigned, const BitVector&,
108 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000109
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000110 unsigned tryReassignOrEvict(LiveInterval&, AllocationOrder&,
111 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000112 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
113 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000114 unsigned trySplit(LiveInterval&, AllocationOrder&,
115 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000116 unsigned trySpillInterferences(LiveInterval&, AllocationOrder&,
117 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000118};
119} // end anonymous namespace
120
121char RAGreedy::ID = 0;
122
123FunctionPass* llvm::createGreedyRegisterAllocator() {
124 return new RAGreedy();
125}
126
127RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000128 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000129 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
130 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
131 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
132 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
133 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
134 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
135 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
136 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000137 initializeMachineLoopRangesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000138 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000139 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
140 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000141}
142
143void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
144 AU.setPreservesCFG();
145 AU.addRequired<AliasAnalysis>();
146 AU.addPreserved<AliasAnalysis>();
147 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000148 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000149 AU.addPreserved<SlotIndexes>();
150 if (StrongPHIElim)
151 AU.addRequiredID(StrongPHIEliminationID);
152 AU.addRequiredTransitive<RegisterCoalescer>();
153 AU.addRequired<CalculateSpillWeights>();
154 AU.addRequired<LiveStacks>();
155 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000156 AU.addRequired<MachineDominatorTree>();
157 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000158 AU.addRequired<MachineLoopInfo>();
159 AU.addPreserved<MachineLoopInfo>();
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000160 AU.addRequired<MachineLoopRanges>();
161 AU.addPreserved<MachineLoopRanges>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000162 AU.addRequired<VirtRegMap>();
163 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000164 AU.addRequired<EdgeBundles>();
165 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000166 MachineFunctionPass::getAnalysisUsage(AU);
167}
168
169void RAGreedy::releaseMemory() {
170 SpillerInstance.reset(0);
171 RegAllocBase::releaseMemory();
172}
173
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000174float RAGreedy::getPriority(LiveInterval *LI) {
175 float Priority = LI->weight;
176
177 // Prioritize hinted registers so they are allocated first.
178 std::pair<unsigned, unsigned> Hint;
179 if (Hint.first || Hint.second) {
180 // The hint can be target specific, a virtual register, or a physreg.
181 Priority *= 2;
182
183 // Prefer physreg hints above anything else.
184 if (Hint.first == 0 && TargetRegisterInfo::isPhysicalRegister(Hint.second))
185 Priority *= 2;
186 }
187 return Priority;
188}
189
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000190
191//===----------------------------------------------------------------------===//
192// Register Reassignment
193//===----------------------------------------------------------------------===//
194
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000195// Check interference without using the cache.
196bool RAGreedy::checkUncachedInterference(LiveInterval &VirtReg,
197 unsigned PhysReg) {
Jakob Stoklund Olesen257c5562010-12-14 23:38:19 +0000198 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
199 LiveIntervalUnion::Query subQ(&VirtReg, &PhysReg2LiveUnion[*AliasI]);
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000200 if (subQ.checkInterference())
201 return true;
202 }
203 return false;
204}
205
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000206/// getSingleInterference - Return the single interfering virtual register
207/// assigned to PhysReg. Return 0 if more than one virtual register is
208/// interfering.
209LiveInterval *RAGreedy::getSingleInterference(LiveInterval &VirtReg,
210 unsigned PhysReg) {
Jakob Stoklund Olesen257c5562010-12-14 23:38:19 +0000211 // Check physreg and aliases.
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000212 LiveInterval *Interference = 0;
Jakob Stoklund Olesen257c5562010-12-14 23:38:19 +0000213 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000214 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
215 if (Q.checkInterference()) {
Jakob Stoklund Olesend84de8c2010-12-14 17:47:36 +0000216 if (Interference)
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000217 return 0;
218 Q.collectInterferingVRegs(1);
Jakob Stoklund Olesend84de8c2010-12-14 17:47:36 +0000219 if (!Q.seenAllInterferences())
220 return 0;
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000221 Interference = Q.interferingVRegs().front();
222 }
223 }
224 return Interference;
225}
226
Andrew Trickb853e6c2010-12-09 18:15:21 +0000227// Attempt to reassign this virtual register to a different physical register.
228//
229// FIXME: we are not yet caching these "second-level" interferences discovered
230// in the sub-queries. These interferences can change with each call to
231// selectOrSplit. However, we could implement a "may-interfere" cache that
232// could be conservatively dirtied when we reassign or split.
233//
234// FIXME: This may result in a lot of alias queries. We could summarize alias
235// live intervals in their parent register's live union, but it's messy.
236bool RAGreedy::reassignVReg(LiveInterval &InterferingVReg,
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000237 unsigned WantedPhysReg) {
238 assert(TargetRegisterInfo::isVirtualRegister(InterferingVReg.reg) &&
239 "Can only reassign virtual registers");
240 assert(TRI->regsOverlap(WantedPhysReg, VRM->getPhys(InterferingVReg.reg)) &&
Andrew Trickb853e6c2010-12-09 18:15:21 +0000241 "inconsistent phys reg assigment");
242
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +0000243 AllocationOrder Order(InterferingVReg.reg, *VRM, ReservedRegs);
244 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000245 // Don't reassign to a WantedPhysReg alias.
246 if (TRI->regsOverlap(PhysReg, WantedPhysReg))
Andrew Trickb853e6c2010-12-09 18:15:21 +0000247 continue;
248
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000249 if (checkUncachedInterference(InterferingVReg, PhysReg))
Andrew Trickb853e6c2010-12-09 18:15:21 +0000250 continue;
251
Andrew Trickb853e6c2010-12-09 18:15:21 +0000252 // Reassign the interfering virtual reg to this physical reg.
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000253 unsigned OldAssign = VRM->getPhys(InterferingVReg.reg);
254 DEBUG(dbgs() << "reassigning: " << InterferingVReg << " from " <<
255 TRI->getName(OldAssign) << " to " << TRI->getName(PhysReg) << '\n');
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000256 unassign(InterferingVReg, OldAssign);
257 assign(InterferingVReg, PhysReg);
Andrew Trickb853e6c2010-12-09 18:15:21 +0000258 return true;
259 }
260 return false;
261}
262
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000263/// tryReassignOrEvict - Try to reassign a single interferences to a different
264/// physreg, or evict a single interference with a lower spill weight.
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000265/// @param VirtReg Currently unassigned virtual register.
266/// @param Order Physregs to try.
267/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000268unsigned RAGreedy::tryReassignOrEvict(LiveInterval &VirtReg,
269 AllocationOrder &Order,
270 SmallVectorImpl<LiveInterval*> &NewVRegs){
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000271 NamedRegionTimer T("Reassign", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000272
273 // Keep track of the lightest single interference seen so far.
274 float BestWeight = VirtReg.weight;
275 LiveInterval *BestVirt = 0;
276 unsigned BestPhys = 0;
277
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000278 Order.rewind();
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000279 while (unsigned PhysReg = Order.next()) {
280 LiveInterval *InterferingVReg = getSingleInterference(VirtReg, PhysReg);
281 if (!InterferingVReg)
282 continue;
283 if (TargetRegisterInfo::isPhysicalRegister(InterferingVReg->reg))
284 continue;
285 if (reassignVReg(*InterferingVReg, PhysReg))
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000286 return PhysReg;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000287
288 // Cannot reassign, is this an eviction candidate?
289 if (InterferingVReg->weight < BestWeight) {
290 BestVirt = InterferingVReg;
291 BestPhys = PhysReg;
292 BestWeight = InterferingVReg->weight;
293 }
294 }
295
296 // Nothing reassigned, can we evict a lighter single interference?
297 if (BestVirt) {
298 DEBUG(dbgs() << "evicting lighter " << *BestVirt << '\n');
299 unassign(*BestVirt, VRM->getPhys(BestVirt->reg));
300 NewVRegs.push_back(BestVirt);
301 return BestPhys;
302 }
303
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000304 return 0;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000305}
306
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000307
308//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000309// Region Splitting
310//===----------------------------------------------------------------------===//
311
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000312/// calcInterferenceInfo - Compute per-block outgoing and ingoing constraints
313/// when considering interference from PhysReg. Also compute an optimistic local
314/// cost of this interference pattern.
315///
316/// The final cost of a split is the local cost + global cost of preferences
317/// broken by SpillPlacement.
318///
319float RAGreedy::calcInterferenceInfo(LiveInterval &VirtReg, unsigned PhysReg) {
320 // Reset interference dependent info.
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000321 SpillConstraints.resize(SA->LiveBlocks.size());
322 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
323 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000324 SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000325 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000326 BC.Entry = (BI.Uses && BI.LiveIn) ?
327 SpillPlacement::PrefReg : SpillPlacement::DontCare;
328 BC.Exit = (BI.Uses && BI.LiveOut) ?
329 SpillPlacement::PrefReg : SpillPlacement::DontCare;
330 BI.OverlapEntry = BI.OverlapExit = false;
331 }
332
333 // Add interference info from each PhysReg alias.
334 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
335 if (!query(VirtReg, *AI).checkInterference())
336 continue;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000337 LiveIntervalUnion::SegmentIter IntI =
338 PhysReg2LiveUnion[*AI].find(VirtReg.beginIndex());
339 if (!IntI.valid())
340 continue;
341
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000342 // Determine which blocks have interference live in or after the last split
343 // point.
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000344 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
345 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000346 SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
347 SlotIndex Start, Stop;
348 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
349
350 // Skip interference-free blocks.
351 if (IntI.start() >= Stop)
352 continue;
353
354 // Is the interference live-in?
355 if (BI.LiveIn) {
356 IntI.advanceTo(Start);
357 if (!IntI.valid())
358 break;
359 if (IntI.start() <= Start)
360 BC.Entry = SpillPlacement::MustSpill;
361 }
362
363 // Is the interference overlapping the last split point?
364 if (BI.LiveOut) {
365 if (IntI.stop() < BI.LastSplitPoint)
366 IntI.advanceTo(BI.LastSplitPoint.getPrevSlot());
367 if (!IntI.valid())
368 break;
369 if (IntI.start() < Stop)
370 BC.Exit = SpillPlacement::MustSpill;
371 }
372 }
373
374 // Rewind iterator and check other interferences.
375 IntI.find(VirtReg.beginIndex());
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000376 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
377 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000378 SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
379 SlotIndex Start, Stop;
380 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
381
382 // Skip interference-free blocks.
383 if (IntI.start() >= Stop)
384 continue;
385
386 // Handle transparent blocks with interference separately.
387 // Transparent blocks never incur any fixed cost.
388 if (BI.LiveThrough && !BI.Uses) {
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000389 IntI.advanceTo(Start);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000390 if (!IntI.valid())
391 break;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000392 if (IntI.start() >= Stop)
393 continue;
394
395 if (BC.Entry != SpillPlacement::MustSpill)
396 BC.Entry = SpillPlacement::PrefSpill;
397 if (BC.Exit != SpillPlacement::MustSpill)
398 BC.Exit = SpillPlacement::PrefSpill;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000399 continue;
400 }
401
402 // Now we only have blocks with uses left.
403 // Check if the interference overlaps the uses.
404 assert(BI.Uses && "Non-transparent block without any uses");
405
406 // Check interference on entry.
407 if (BI.LiveIn && BC.Entry != SpillPlacement::MustSpill) {
408 IntI.advanceTo(Start);
409 if (!IntI.valid())
410 break;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000411 // Not live in, but before the first use.
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000412 if (IntI.start() < BI.FirstUse)
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000413 BC.Entry = SpillPlacement::PrefSpill;
414 }
415
416 // Does interference overlap the uses in the entry segment
417 // [FirstUse;Kill)?
418 if (BI.LiveIn && !BI.OverlapEntry) {
419 IntI.advanceTo(BI.FirstUse);
420 if (!IntI.valid())
421 break;
422 // A live-through interval has no kill.
423 // Check [FirstUse;LastUse) instead.
424 if (IntI.start() < (BI.LiveThrough ? BI.LastUse : BI.Kill))
425 BI.OverlapEntry = true;
426 }
427
428 // Does interference overlap the uses in the exit segment [Def;LastUse)?
429 if (BI.LiveOut && !BI.LiveThrough && !BI.OverlapExit) {
430 IntI.advanceTo(BI.Def);
431 if (!IntI.valid())
432 break;
433 if (IntI.start() < BI.LastUse)
434 BI.OverlapExit = true;
435 }
436
437 // Check interference on exit.
438 if (BI.LiveOut && BC.Exit != SpillPlacement::MustSpill) {
439 // Check interference between LastUse and Stop.
440 if (BC.Exit != SpillPlacement::PrefSpill) {
441 IntI.advanceTo(BI.LastUse);
442 if (!IntI.valid())
443 break;
444 if (IntI.start() < Stop)
445 BC.Exit = SpillPlacement::PrefSpill;
446 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000447 }
448 }
449 }
450
451 // Accumulate a local cost of this interference pattern.
452 float LocalCost = 0;
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000453 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
454 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000455 if (!BI.Uses)
456 continue;
457 SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
458 unsigned Inserts = 0;
459
460 // Do we need spill code for the entry segment?
461 if (BI.LiveIn)
462 Inserts += BI.OverlapEntry || BC.Entry != SpillPlacement::PrefReg;
463
464 // For the exit segment?
465 if (BI.LiveOut)
466 Inserts += BI.OverlapExit || BC.Exit != SpillPlacement::PrefReg;
467
468 // The local cost of spill code in this block is the block frequency times
469 // the number of spill instructions inserted.
470 if (Inserts)
471 LocalCost += Inserts * SpillPlacer->getBlockFrequency(BI.MBB);
472 }
473 DEBUG(dbgs() << "Local cost of " << PrintReg(PhysReg, TRI) << " = "
474 << LocalCost << '\n');
475 return LocalCost;
476}
477
478/// calcGlobalSplitCost - Return the global split cost of following the split
479/// pattern in LiveBundles. This cost should be added to the local cost of the
480/// interference pattern in SpillConstraints.
481///
482float RAGreedy::calcGlobalSplitCost(const BitVector &LiveBundles) {
483 float GlobalCost = 0;
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000484 for (unsigned i = 0, e = SpillConstraints.size(); i != e; ++i) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000485 SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
486 unsigned Inserts = 0;
487 // Broken entry preference?
488 Inserts += LiveBundles[Bundles->getBundle(BC.Number, 0)] !=
489 (BC.Entry == SpillPlacement::PrefReg);
490 // Broken exit preference?
491 Inserts += LiveBundles[Bundles->getBundle(BC.Number, 1)] !=
492 (BC.Exit == SpillPlacement::PrefReg);
493 if (Inserts)
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000494 GlobalCost +=
495 Inserts * SpillPlacer->getBlockFrequency(SA->LiveBlocks[i].MBB);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000496 }
497 DEBUG(dbgs() << "Global cost = " << GlobalCost << '\n');
498 return GlobalCost;
499}
500
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000501/// splitAroundRegion - Split VirtReg around the region determined by
502/// LiveBundles. Make an effort to avoid interference from PhysReg.
503///
504/// The 'register' interval is going to contain as many uses as possible while
505/// avoiding interference. The 'stack' interval is the complement constructed by
506/// SplitEditor. It will contain the rest.
507///
508void RAGreedy::splitAroundRegion(LiveInterval &VirtReg, unsigned PhysReg,
509 const BitVector &LiveBundles,
510 SmallVectorImpl<LiveInterval*> &NewVRegs) {
511 DEBUG({
512 dbgs() << "Splitting around region for " << PrintReg(PhysReg, TRI)
513 << " with bundles";
514 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
515 dbgs() << " EB#" << i;
516 dbgs() << ".\n";
517 });
518
519 // First compute interference ranges in the live blocks.
520 typedef std::pair<SlotIndex, SlotIndex> IndexPair;
521 SmallVector<IndexPair, 8> InterferenceRanges;
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000522 InterferenceRanges.resize(SA->LiveBlocks.size());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000523 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
524 if (!query(VirtReg, *AI).checkInterference())
525 continue;
526 LiveIntervalUnion::SegmentIter IntI =
527 PhysReg2LiveUnion[*AI].find(VirtReg.beginIndex());
528 if (!IntI.valid())
529 continue;
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000530 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
531 const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000532 IndexPair &IP = InterferenceRanges[i];
533 SlotIndex Start, Stop;
534 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
535 // Skip interference-free blocks.
536 if (IntI.start() >= Stop)
537 continue;
538
539 // First interference in block.
540 if (BI.LiveIn) {
541 IntI.advanceTo(Start);
542 if (!IntI.valid())
543 break;
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000544 if (IntI.start() >= Stop)
545 continue;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000546 if (!IP.first.isValid() || IntI.start() < IP.first)
547 IP.first = IntI.start();
548 }
549
550 // Last interference in block.
551 if (BI.LiveOut) {
552 IntI.advanceTo(Stop);
553 if (!IntI.valid() || IntI.start() >= Stop)
554 --IntI;
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000555 if (IntI.stop() <= Start)
556 continue;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000557 if (!IP.second.isValid() || IntI.stop() > IP.second)
558 IP.second = IntI.stop();
559 }
560 }
561 }
562
563 SmallVector<LiveInterval*, 4> SpillRegs;
564 LiveRangeEdit LREdit(VirtReg, NewVRegs, SpillRegs);
565 SplitEditor SE(*SA, *LIS, *VRM, *DomTree, LREdit);
566
567 // Create the main cross-block interval.
568 SE.openIntv();
569
570 // First add all defs that are live out of a block.
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000571 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
572 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000573 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
574 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
575
576 // Should the register be live out?
577 if (!BI.LiveOut || !RegOut)
578 continue;
579
580 IndexPair &IP = InterferenceRanges[i];
581 SlotIndex Start, Stop;
582 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
583
584 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " -> EB#"
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000585 << Bundles->getBundle(BI.MBB->getNumber(), 1)
586 << " intf [" << IP.first << ';' << IP.second << ')');
587
588 // The interference interval should either be invalid or overlap MBB.
589 assert((!IP.first.isValid() || IP.first < Stop) && "Bad interference");
590 assert((!IP.second.isValid() || IP.second > Start) && "Bad interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000591
592 // Check interference leaving the block.
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000593 if (!IP.second.isValid()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000594 // Block is interference-free.
595 DEBUG(dbgs() << ", no interference");
596 if (!BI.Uses) {
597 assert(BI.LiveThrough && "No uses, but not live through block?");
598 // Block is live-through without interference.
599 DEBUG(dbgs() << ", no uses"
600 << (RegIn ? ", live-through.\n" : ", stack in.\n"));
601 if (!RegIn)
602 SE.enterIntvAtEnd(*BI.MBB);
603 continue;
604 }
605 if (!BI.LiveThrough) {
606 DEBUG(dbgs() << ", not live-through.\n");
Jakob Stoklund Olesen207c8682011-02-03 17:04:16 +0000607 SE.useIntv(SE.enterIntvBefore(BI.Def), Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000608 continue;
609 }
610 if (!RegIn) {
611 // Block is live-through, but entry bundle is on the stack.
612 // Reload just before the first use.
613 DEBUG(dbgs() << ", not live-in, enter before first use.\n");
Jakob Stoklund Olesen207c8682011-02-03 17:04:16 +0000614 SE.useIntv(SE.enterIntvBefore(BI.FirstUse), Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000615 continue;
616 }
617 DEBUG(dbgs() << ", live-through.\n");
618 continue;
619 }
620
621 // Block has interference.
622 DEBUG(dbgs() << ", interference to " << IP.second);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000623
624 if (!BI.LiveThrough && IP.second <= BI.Def) {
625 // The interference doesn't reach the outgoing segment.
626 DEBUG(dbgs() << " doesn't affect def from " << BI.Def << '\n');
627 SE.useIntv(BI.Def, Stop);
628 continue;
629 }
630
631
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000632 if (!BI.Uses) {
633 // No uses in block, avoid interference by reloading as late as possible.
634 DEBUG(dbgs() << ", no uses.\n");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000635 SlotIndex SegStart = SE.enterIntvAtEnd(*BI.MBB);
636 assert(SegStart >= IP.second && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000637 continue;
638 }
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000639
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000640 if (IP.second.getBoundaryIndex() < BI.LastUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000641 // There are interference-free uses at the end of the block.
642 // Find the first use that can get the live-out register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000643 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000644 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
645 IP.second.getBoundaryIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000646 assert(UI != SA->UseSlots.end() && "Couldn't find last use");
647 SlotIndex Use = *UI;
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000648 assert(Use <= BI.LastUse && "Couldn't find last use");
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000649 // Only attempt a split befroe the last split point.
650 if (Use.getBaseIndex() <= BI.LastSplitPoint) {
651 DEBUG(dbgs() << ", free use at " << Use << ".\n");
652 SlotIndex SegStart = SE.enterIntvBefore(Use);
653 assert(SegStart >= IP.second && "Couldn't avoid interference");
654 assert(SegStart < BI.LastSplitPoint && "Impossible split point");
655 SE.useIntv(SegStart, Stop);
656 continue;
657 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000658 }
659
660 // Interference is after the last use.
661 DEBUG(dbgs() << " after last use.\n");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000662 SlotIndex SegStart = SE.enterIntvAtEnd(*BI.MBB);
663 assert(SegStart >= IP.second && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000664 }
665
666 // Now all defs leading to live bundles are handled, do everything else.
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000667 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
668 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000669 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
670 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
671
672 // Is the register live-in?
673 if (!BI.LiveIn || !RegIn)
674 continue;
675
676 // We have an incoming register. Check for interference.
677 IndexPair &IP = InterferenceRanges[i];
678 SlotIndex Start, Stop;
679 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
680
681 DEBUG(dbgs() << "EB#" << Bundles->getBundle(BI.MBB->getNumber(), 0)
682 << " -> BB#" << BI.MBB->getNumber());
683
684 // Check interference entering the block.
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000685 if (!IP.first.isValid()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000686 // Block is interference-free.
687 DEBUG(dbgs() << ", no interference");
688 if (!BI.Uses) {
689 assert(BI.LiveThrough && "No uses, but not live through block?");
690 // Block is live-through without interference.
691 if (RegOut) {
692 DEBUG(dbgs() << ", no uses, live-through.\n");
693 SE.useIntv(Start, Stop);
694 } else {
695 DEBUG(dbgs() << ", no uses, stack-out.\n");
696 SE.leaveIntvAtTop(*BI.MBB);
697 }
698 continue;
699 }
700 if (!BI.LiveThrough) {
701 DEBUG(dbgs() << ", killed in block.\n");
Jakob Stoklund Olesen207c8682011-02-03 17:04:16 +0000702 SE.useIntv(Start, SE.leaveIntvAfter(BI.Kill));
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000703 continue;
704 }
705 if (!RegOut) {
706 // Block is live-through, but exit bundle is on the stack.
707 // Spill immediately after the last use.
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000708 if (BI.LastUse < BI.LastSplitPoint) {
709 DEBUG(dbgs() << ", uses, stack-out.\n");
710 SE.useIntv(Start, SE.leaveIntvAfter(BI.LastUse));
711 continue;
712 }
713 // The last use is after the last split point, it is probably an
714 // indirect jump.
715 DEBUG(dbgs() << ", uses at " << BI.LastUse << " after split point "
716 << BI.LastSplitPoint << ", stack-out.\n");
717 SlotIndex SegEnd;
Jakob Stoklund Olesend08d7732011-02-08 21:46:11 +0000718 // Find the last real instruction before the split point.
719 MachineBasicBlock::iterator SplitI =
720 LIS->getInstructionFromIndex(BI.LastSplitPoint);
721 MachineBasicBlock::iterator I = SplitI, B = BI.MBB->begin();
722 while (I != B && (--I)->isDebugValue())
723 ;
724 if (I == SplitI)
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000725 SegEnd = SE.leaveIntvAtTop(*BI.MBB);
726 else {
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000727 SegEnd = SE.leaveIntvAfter(LIS->getInstructionIndex(I));
Jakob Stoklund Olesend08d7732011-02-08 21:46:11 +0000728 SE.useIntv(Start, SegEnd);
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000729 }
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000730 // Run a double interval from the split to the last use.
731 // This makes it possible to spill the complement without affecting the
732 // indirect branch.
733 SE.overlapIntv(SegEnd, BI.LastUse);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000734 continue;
735 }
736 // Register is live-through.
737 DEBUG(dbgs() << ", uses, live-through.\n");
738 SE.useIntv(Start, Stop);
739 continue;
740 }
741
742 // Block has interference.
743 DEBUG(dbgs() << ", interference from " << IP.first);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000744
745 if (!BI.LiveThrough && IP.first >= BI.Kill) {
746 // The interference doesn't reach the outgoing segment.
747 DEBUG(dbgs() << " doesn't affect kill at " << BI.Kill << '\n');
748 SE.useIntv(Start, BI.Kill);
749 continue;
750 }
751
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000752 if (!BI.Uses) {
753 // No uses in block, avoid interference by spilling as soon as possible.
754 DEBUG(dbgs() << ", no uses.\n");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000755 SlotIndex SegEnd = SE.leaveIntvAtTop(*BI.MBB);
756 assert(SegEnd <= IP.first && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000757 continue;
758 }
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000759 if (IP.first.getBaseIndex() > BI.FirstUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000760 // There are interference-free uses at the beginning of the block.
761 // Find the last use that can get the register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000762 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000763 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
764 IP.first.getBaseIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000765 assert(UI != SA->UseSlots.begin() && "Couldn't find first use");
766 SlotIndex Use = (--UI)->getBoundaryIndex();
767 DEBUG(dbgs() << ", free use at " << *UI << ".\n");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000768 SlotIndex SegEnd = SE.leaveIntvAfter(Use);
769 assert(SegEnd <= IP.first && "Couldn't avoid interference");
770 SE.useIntv(Start, SegEnd);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000771 continue;
772 }
773
774 // Interference is before the first use.
775 DEBUG(dbgs() << " before first use.\n");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000776 SlotIndex SegEnd = SE.leaveIntvAtTop(*BI.MBB);
777 assert(SegEnd <= IP.first && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000778 }
779
780 SE.closeIntv();
781
782 // FIXME: Should we be more aggressive about splitting the stack region into
783 // per-block segments? The current approach allows the stack region to
784 // separate into connected components. Some components may be allocatable.
785 SE.finish();
786
Jakob Stoklund Olesen9b3d24b2011-02-04 19:33:07 +0000787 if (VerifyEnabled) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000788 MF->verify(this, "After splitting live range around region");
Jakob Stoklund Olesen9b3d24b2011-02-04 19:33:07 +0000789
790#ifndef NDEBUG
791 // Make sure that at least one of the new intervals can allocate to PhysReg.
792 // That was the whole point of splitting the live range.
793 bool found = false;
794 for (LiveRangeEdit::iterator I = LREdit.begin(), E = LREdit.end(); I != E;
795 ++I)
796 if (!checkUncachedInterference(**I, PhysReg)) {
797 found = true;
798 break;
799 }
800 assert(found && "No allocatable intervals after pointless splitting");
801#endif
802 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000803}
804
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000805unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
806 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000807 BitVector LiveBundles, BestBundles;
808 float BestCost = 0;
809 unsigned BestReg = 0;
810 Order.rewind();
811 while (unsigned PhysReg = Order.next()) {
812 float Cost = calcInterferenceInfo(VirtReg, PhysReg);
813 if (BestReg && Cost >= BestCost)
814 continue;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000815
816 SpillPlacer->placeSpills(SpillConstraints, LiveBundles);
817 // No live bundles, defer to splitSingleBlocks().
818 if (!LiveBundles.any())
819 continue;
820
821 Cost += calcGlobalSplitCost(LiveBundles);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000822 if (!BestReg || Cost < BestCost) {
823 BestReg = PhysReg;
824 BestCost = Cost;
825 BestBundles.swap(LiveBundles);
826 }
827 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000828
829 if (!BestReg)
830 return 0;
831
832 splitAroundRegion(VirtReg, BestReg, BestBundles, NewVRegs);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000833 return 0;
834}
835
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000836
837//===----------------------------------------------------------------------===//
838// Live Range Splitting
839//===----------------------------------------------------------------------===//
840
841/// trySplit - Try to split VirtReg or one of its interferences, making it
842/// assignable.
843/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
844unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
845 SmallVectorImpl<LiveInterval*>&NewVRegs) {
846 NamedRegionTimer T("Splitter", TimerGroupName, TimePassesIsEnabled);
847 SA->analyze(&VirtReg);
848
849 // Don't attempt splitting on local intervals for now. TBD.
850 if (LIS->intervalIsInOneMBB(VirtReg))
851 return 0;
852
853 // First try to split around a region spanning multiple blocks.
854 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
855 if (PhysReg || !NewVRegs.empty())
856 return PhysReg;
857
858 // Then isolate blocks with multiple uses.
859 SplitAnalysis::BlockPtrSet Blocks;
860 if (SA->getMultiUseBlocks(Blocks)) {
861 SmallVector<LiveInterval*, 4> SpillRegs;
862 LiveRangeEdit LREdit(VirtReg, NewVRegs, SpillRegs);
863 SplitEditor(*SA, *LIS, *VRM, *DomTree, LREdit).splitSingleBlocks(Blocks);
Jakob Stoklund Olesen207c8682011-02-03 17:04:16 +0000864 if (VerifyEnabled)
865 MF->verify(this, "After splitting live range around basic blocks");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000866 }
867
868 // Don't assign any physregs.
869 return 0;
870}
871
872
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000873//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000874// Spilling
875//===----------------------------------------------------------------------===//
876
877/// calcInterferenceWeight - Calculate the combined spill weight of
878/// interferences when assigning VirtReg to PhysReg.
879float RAGreedy::calcInterferenceWeight(LiveInterval &VirtReg, unsigned PhysReg){
880 float Sum = 0;
881 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
882 LiveIntervalUnion::Query &Q = query(VirtReg, *AI);
883 Q.collectInterferingVRegs();
884 if (Q.seenUnspillableVReg())
885 return HUGE_VALF;
886 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i)
887 Sum += Q.interferingVRegs()[i]->weight;
888 }
889 return Sum;
890}
891
892/// trySpillInterferences - Try to spill interfering registers instead of the
893/// current one. Only do it if the accumulated spill weight is smaller than the
894/// current spill weight.
895unsigned RAGreedy::trySpillInterferences(LiveInterval &VirtReg,
896 AllocationOrder &Order,
897 SmallVectorImpl<LiveInterval*> &NewVRegs) {
898 NamedRegionTimer T("Spill Interference", TimerGroupName, TimePassesIsEnabled);
899 unsigned BestPhys = 0;
Duncan Sands2aea4902010-12-28 10:07:15 +0000900 float BestWeight = 0;
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000901
902 Order.rewind();
903 while (unsigned PhysReg = Order.next()) {
904 float Weight = calcInterferenceWeight(VirtReg, PhysReg);
905 if (Weight == HUGE_VALF || Weight >= VirtReg.weight)
906 continue;
907 if (!BestPhys || Weight < BestWeight)
908 BestPhys = PhysReg, BestWeight = Weight;
909 }
910
911 // No candidates found.
912 if (!BestPhys)
913 return 0;
914
915 // Collect all interfering registers.
916 SmallVector<LiveInterval*, 8> Spills;
917 for (const unsigned *AI = TRI->getOverlaps(BestPhys); *AI; ++AI) {
918 LiveIntervalUnion::Query &Q = query(VirtReg, *AI);
919 Spills.append(Q.interferingVRegs().begin(), Q.interferingVRegs().end());
920 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
921 LiveInterval *VReg = Q.interferingVRegs()[i];
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000922 unassign(*VReg, *AI);
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000923 }
924 }
925
926 // Spill them all.
927 DEBUG(dbgs() << "spilling " << Spills.size() << " interferences with weight "
928 << BestWeight << '\n');
929 for (unsigned i = 0, e = Spills.size(); i != e; ++i)
930 spiller().spill(Spills[i], NewVRegs, Spills);
931 return BestPhys;
932}
933
934
935//===----------------------------------------------------------------------===//
936// Main Entry Point
937//===----------------------------------------------------------------------===//
938
939unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000940 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000941 // First try assigning a free register.
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +0000942 AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
943 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000944 if (!checkPhysRegInterference(VirtReg, PhysReg))
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000945 return PhysReg;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000946 }
Andrew Trickb853e6c2010-12-09 18:15:21 +0000947
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000948 // Try to reassign interferences.
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000949 if (unsigned PhysReg = tryReassignOrEvict(VirtReg, Order, NewVRegs))
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000950 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000951
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000952 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
953
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000954 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000955 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
956 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000957 return PhysReg;
958
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000959 // Try to spill another interfering reg with less spill weight.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000960 PhysReg = trySpillInterferences(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000961 if (PhysReg)
962 return PhysReg;
963
964 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000965 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000966 SmallVector<LiveInterval*, 1> pendingSpills;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000967 spiller().spill(&VirtReg, NewVRegs, pendingSpills);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000968
969 // The live virtual register requesting allocation was spilled, so tell
970 // the caller not to allocate anything during this round.
971 return 0;
972}
973
974bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
975 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
976 << "********** Function: "
977 << ((Value*)mf.getFunction())->getName() << '\n');
978
979 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +0000980 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +0000981 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +0000982
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +0000983 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000984 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000985 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000986 ReservedRegs = TRI->getReservedRegs(*MF);
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +0000987 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000988 Loops = &getAnalysis<MachineLoopInfo>();
989 LoopRanges = &getAnalysis<MachineLoopRanges>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000990 Bundles = &getAnalysis<EdgeBundles>();
991 SpillPlacer = &getAnalysis<SpillPlacement>();
992
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000993 SA.reset(new SplitAnalysis(*MF, *LIS, *Loops));
994
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000995 allocatePhysRegs();
996 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +0000997 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000998
999 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001000 {
1001 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
1002 std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
1003 rewriter->runOnMachineFunction(*MF, *VRM, LIS);
1004 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001005
1006 // The pass output is in VirtRegMap. Release all the transient data.
1007 releaseMemory();
1008
1009 return true;
1010}