blob: ff0c790f88773f87d8126fc32f0782c1e10c28b3 [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
75 /// Additional information about basic blocks where the current variable is
76 /// live. Such a block will look like one of these templates:
77 ///
78 /// 1. | o---x | Internal to block. Variable is only live in this block.
79 /// 2. |---x | Live-in, kill.
80 /// 3. | o---| Def, live-out.
81 /// 4. |---x o---| Live-in, kill, def, live-out.
82 /// 5. |---o---o---| Live-through with uses or defs.
83 /// 6. |-----------| Live-through without uses. Transparent.
84 ///
85 struct BlockInfo {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +000086 MachineBasicBlock *MBB;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000087 SlotIndex FirstUse; ///< First instr using current reg.
88 SlotIndex LastUse; ///< Last instr using current reg.
89 SlotIndex Kill; ///< Interval end point inside block.
90 SlotIndex Def; ///< Interval start point inside block.
Jakob Stoklund Olesen63935422011-02-04 21:42:06 +000091 /// Last possible point for splitting live ranges.
92 SlotIndex LastSplitPoint;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000093 bool Uses; ///< Current reg has uses or defs in block.
94 bool LiveThrough; ///< Live in whole block (Templ 5. or 6. above).
95 bool LiveIn; ///< Current reg is live in.
96 bool LiveOut; ///< Current reg is live out.
97
98 // Per-interference pattern scratch data.
99 bool OverlapEntry; ///< Interference overlaps entering interval.
100 bool OverlapExit; ///< Interference overlaps exiting interval.
101 };
102
103 /// Basic blocks where var is live. This array is parallel to
104 /// SpillConstraints.
105 SmallVector<BlockInfo, 8> LiveBlocks;
106
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000107public:
108 RAGreedy();
109
110 /// Return the pass name.
111 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000112 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000113 }
114
115 /// RAGreedy analysis usage.
116 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
117
118 virtual void releaseMemory();
119
120 virtual Spiller &spiller() { return *SpillerInstance; }
121
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000122 virtual float getPriority(LiveInterval *LI);
Jakob Stoklund Olesend0bec3e2010-12-08 22:22:41 +0000123
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000124 virtual unsigned selectOrSplit(LiveInterval&,
125 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000126
127 /// Perform register allocation.
128 virtual bool runOnMachineFunction(MachineFunction &mf);
129
130 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000131
132private:
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000133 bool checkUncachedInterference(LiveInterval&, unsigned);
134 LiveInterval *getSingleInterference(LiveInterval&, unsigned);
Andrew Trickb853e6c2010-12-09 18:15:21 +0000135 bool reassignVReg(LiveInterval &InterferingVReg, unsigned OldPhysReg);
136 bool reassignInterferences(LiveInterval &VirtReg, unsigned PhysReg);
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000137 float calcInterferenceWeight(LiveInterval&, unsigned);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000138 void calcLiveBlockInfo(LiveInterval&);
139 float calcInterferenceInfo(LiveInterval&, unsigned);
140 float calcGlobalSplitCost(const BitVector&);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000141 void splitAroundRegion(LiveInterval&, unsigned, const BitVector&,
142 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000143
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000144 unsigned tryReassign(LiveInterval&, AllocationOrder&);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000145 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
146 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000147 unsigned trySplit(LiveInterval&, AllocationOrder&,
148 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000149 unsigned trySpillInterferences(LiveInterval&, AllocationOrder&,
150 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000151};
152} // end anonymous namespace
153
154char RAGreedy::ID = 0;
155
156FunctionPass* llvm::createGreedyRegisterAllocator() {
157 return new RAGreedy();
158}
159
160RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000161 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000162 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
163 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
164 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
165 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
166 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
167 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
168 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
169 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000170 initializeMachineLoopRangesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000171 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000172 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
173 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000174}
175
176void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
177 AU.setPreservesCFG();
178 AU.addRequired<AliasAnalysis>();
179 AU.addPreserved<AliasAnalysis>();
180 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000181 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000182 AU.addPreserved<SlotIndexes>();
183 if (StrongPHIElim)
184 AU.addRequiredID(StrongPHIEliminationID);
185 AU.addRequiredTransitive<RegisterCoalescer>();
186 AU.addRequired<CalculateSpillWeights>();
187 AU.addRequired<LiveStacks>();
188 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000189 AU.addRequired<MachineDominatorTree>();
190 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000191 AU.addRequired<MachineLoopInfo>();
192 AU.addPreserved<MachineLoopInfo>();
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000193 AU.addRequired<MachineLoopRanges>();
194 AU.addPreserved<MachineLoopRanges>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000195 AU.addRequired<VirtRegMap>();
196 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000197 AU.addRequired<EdgeBundles>();
198 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000199 MachineFunctionPass::getAnalysisUsage(AU);
200}
201
202void RAGreedy::releaseMemory() {
203 SpillerInstance.reset(0);
204 RegAllocBase::releaseMemory();
205}
206
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000207float RAGreedy::getPriority(LiveInterval *LI) {
208 float Priority = LI->weight;
209
210 // Prioritize hinted registers so they are allocated first.
211 std::pair<unsigned, unsigned> Hint;
212 if (Hint.first || Hint.second) {
213 // The hint can be target specific, a virtual register, or a physreg.
214 Priority *= 2;
215
216 // Prefer physreg hints above anything else.
217 if (Hint.first == 0 && TargetRegisterInfo::isPhysicalRegister(Hint.second))
218 Priority *= 2;
219 }
220 return Priority;
221}
222
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000223
224//===----------------------------------------------------------------------===//
225// Register Reassignment
226//===----------------------------------------------------------------------===//
227
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000228// Check interference without using the cache.
229bool RAGreedy::checkUncachedInterference(LiveInterval &VirtReg,
230 unsigned PhysReg) {
Jakob Stoklund Olesen257c5562010-12-14 23:38:19 +0000231 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
232 LiveIntervalUnion::Query subQ(&VirtReg, &PhysReg2LiveUnion[*AliasI]);
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000233 if (subQ.checkInterference())
234 return true;
235 }
236 return false;
237}
238
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000239/// getSingleInterference - Return the single interfering virtual register
240/// assigned to PhysReg. Return 0 if more than one virtual register is
241/// interfering.
242LiveInterval *RAGreedy::getSingleInterference(LiveInterval &VirtReg,
243 unsigned PhysReg) {
Jakob Stoklund Olesen257c5562010-12-14 23:38:19 +0000244 // Check physreg and aliases.
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000245 LiveInterval *Interference = 0;
Jakob Stoklund Olesen257c5562010-12-14 23:38:19 +0000246 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000247 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
248 if (Q.checkInterference()) {
Jakob Stoklund Olesend84de8c2010-12-14 17:47:36 +0000249 if (Interference)
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000250 return 0;
251 Q.collectInterferingVRegs(1);
Jakob Stoklund Olesend84de8c2010-12-14 17:47:36 +0000252 if (!Q.seenAllInterferences())
253 return 0;
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000254 Interference = Q.interferingVRegs().front();
255 }
256 }
257 return Interference;
258}
259
Andrew Trickb853e6c2010-12-09 18:15:21 +0000260// Attempt to reassign this virtual register to a different physical register.
261//
262// FIXME: we are not yet caching these "second-level" interferences discovered
263// in the sub-queries. These interferences can change with each call to
264// selectOrSplit. However, we could implement a "may-interfere" cache that
265// could be conservatively dirtied when we reassign or split.
266//
267// FIXME: This may result in a lot of alias queries. We could summarize alias
268// live intervals in their parent register's live union, but it's messy.
269bool RAGreedy::reassignVReg(LiveInterval &InterferingVReg,
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000270 unsigned WantedPhysReg) {
271 assert(TargetRegisterInfo::isVirtualRegister(InterferingVReg.reg) &&
272 "Can only reassign virtual registers");
273 assert(TRI->regsOverlap(WantedPhysReg, VRM->getPhys(InterferingVReg.reg)) &&
Andrew Trickb853e6c2010-12-09 18:15:21 +0000274 "inconsistent phys reg assigment");
275
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +0000276 AllocationOrder Order(InterferingVReg.reg, *VRM, ReservedRegs);
277 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000278 // Don't reassign to a WantedPhysReg alias.
279 if (TRI->regsOverlap(PhysReg, WantedPhysReg))
Andrew Trickb853e6c2010-12-09 18:15:21 +0000280 continue;
281
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000282 if (checkUncachedInterference(InterferingVReg, PhysReg))
Andrew Trickb853e6c2010-12-09 18:15:21 +0000283 continue;
284
Andrew Trickb853e6c2010-12-09 18:15:21 +0000285 // Reassign the interfering virtual reg to this physical reg.
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000286 unsigned OldAssign = VRM->getPhys(InterferingVReg.reg);
287 DEBUG(dbgs() << "reassigning: " << InterferingVReg << " from " <<
288 TRI->getName(OldAssign) << " to " << TRI->getName(PhysReg) << '\n');
289 PhysReg2LiveUnion[OldAssign].extract(InterferingVReg);
Andrew Trickb853e6c2010-12-09 18:15:21 +0000290 VRM->clearVirt(InterferingVReg.reg);
291 VRM->assignVirt2Phys(InterferingVReg.reg, PhysReg);
292 PhysReg2LiveUnion[PhysReg].unify(InterferingVReg);
293
294 return true;
295 }
296 return false;
297}
298
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000299/// reassignInterferences - Reassign all interferences to different physical
300/// registers such that Virtreg can be assigned to PhysReg.
301/// Currently this only works with a single interference.
302/// @param VirtReg Currently unassigned virtual register.
303/// @param PhysReg Physical register to be cleared.
304/// @return True on success, false if nothing was changed.
Andrew Trickb853e6c2010-12-09 18:15:21 +0000305bool RAGreedy::reassignInterferences(LiveInterval &VirtReg, unsigned PhysReg) {
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000306 LiveInterval *InterferingVReg = getSingleInterference(VirtReg, PhysReg);
307 if (!InterferingVReg)
Andrew Trickb853e6c2010-12-09 18:15:21 +0000308 return false;
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000309 if (TargetRegisterInfo::isPhysicalRegister(InterferingVReg->reg))
310 return false;
311 return reassignVReg(*InterferingVReg, PhysReg);
312}
Andrew Trickb853e6c2010-12-09 18:15:21 +0000313
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000314/// tryReassign - Try to reassign interferences to different physregs.
315/// @param VirtReg Currently unassigned virtual register.
316/// @param Order Physregs to try.
317/// @return Physreg to assign VirtReg, or 0.
318unsigned RAGreedy::tryReassign(LiveInterval &VirtReg, AllocationOrder &Order) {
319 NamedRegionTimer T("Reassign", TimerGroupName, TimePassesIsEnabled);
320 Order.rewind();
321 while (unsigned PhysReg = Order.next())
322 if (reassignInterferences(VirtReg, PhysReg))
323 return PhysReg;
324 return 0;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000325}
326
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000327
328//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000329// Region Splitting
330//===----------------------------------------------------------------------===//
331
332/// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks
333/// where VirtReg is live.
334/// The SpillConstraints array is minimally initialized with MBB->getNumber().
335void RAGreedy::calcLiveBlockInfo(LiveInterval &VirtReg) {
336 LiveBlocks.clear();
337 SpillConstraints.clear();
338
339 assert(!VirtReg.empty() && "Cannot allocate an empty interval");
340 LiveInterval::const_iterator LVI = VirtReg.begin();
341 LiveInterval::const_iterator LVE = VirtReg.end();
342
343 SmallVectorImpl<SlotIndex>::const_iterator UseI, UseE;
344 UseI = SA->UseSlots.begin();
345 UseE = SA->UseSlots.end();
346
347 // Loop over basic blocks where VirtReg is live.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000348 MachineFunction::iterator MFI = Indexes->getMBBFromIndex(LVI->start);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000349 for (;;) {
350 // Block constraints depend on the interference pattern.
351 // Just allocate them here, don't compute anything.
352 SpillPlacement::BlockConstraint BC;
353 BC.Number = MFI->getNumber();
354 SpillConstraints.push_back(BC);
355
356 BlockInfo BI;
357 BI.MBB = MFI;
358 SlotIndex Start, Stop;
359 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
360
Jakob Stoklund Olesen63935422011-02-04 21:42:06 +0000361 // The last split point is the latest possible insertion point that dominates
362 // all successor blocks. If interference reaches LastSplitPoint, it is not
363 // possible to insert a split or reload that makes VirtReg live in the
364 // outgoing bundle.
365 MachineBasicBlock::iterator LSP = LIS->getLastSplitPoint(VirtReg, BI.MBB);
366 if (LSP == BI.MBB->end())
367 BI.LastSplitPoint = Stop;
368 else
369 BI.LastSplitPoint = Indexes->getInstructionIndex(LSP);
370
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000371 // LVI is the first live segment overlapping MBB.
372 BI.LiveIn = LVI->start <= Start;
373 if (!BI.LiveIn)
374 BI.Def = LVI->start;
375
376 // Find the first and last uses in the block.
377 BI.Uses = SA->hasUses(MFI);
378 if (BI.Uses && UseI != UseE) {
379 BI.FirstUse = *UseI;
380 assert(BI.FirstUse >= Start);
381 do ++UseI;
382 while (UseI != UseE && *UseI < Stop);
383 BI.LastUse = UseI[-1];
384 assert(BI.LastUse < Stop);
385 }
386
387 // Look for gaps in the live range.
388 bool hasGap = false;
389 BI.LiveOut = true;
390 while (LVI->end < Stop) {
391 SlotIndex LastStop = LVI->end;
392 if (++LVI == LVE || LVI->start >= Stop) {
393 BI.Kill = LastStop;
394 BI.LiveOut = false;
395 break;
396 }
397 if (LastStop < LVI->start) {
398 hasGap = true;
399 BI.Kill = LastStop;
400 BI.Def = LVI->start;
401 }
402 }
403
404 // Don't set LiveThrough when the block has a gap.
405 BI.LiveThrough = !hasGap && BI.LiveIn && BI.LiveOut;
406 LiveBlocks.push_back(BI);
407
408 // LVI is now at LVE or LVI->end >= Stop.
409 if (LVI == LVE)
410 break;
411
412 // Live segment ends exactly at Stop. Move to the next segment.
413 if (LVI->end == Stop && ++LVI == LVE)
414 break;
415
416 // Pick the next basic block.
417 if (LVI->start < Stop)
418 ++MFI;
419 else
420 MFI = Indexes->getMBBFromIndex(LVI->start);
421 }
422}
423
424/// calcInterferenceInfo - Compute per-block outgoing and ingoing constraints
425/// when considering interference from PhysReg. Also compute an optimistic local
426/// cost of this interference pattern.
427///
428/// The final cost of a split is the local cost + global cost of preferences
429/// broken by SpillPlacement.
430///
431float RAGreedy::calcInterferenceInfo(LiveInterval &VirtReg, unsigned PhysReg) {
432 // Reset interference dependent info.
433 for (unsigned i = 0, e = LiveBlocks.size(); i != e; ++i) {
434 BlockInfo &BI = LiveBlocks[i];
435 SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
436 BC.Entry = (BI.Uses && BI.LiveIn) ?
437 SpillPlacement::PrefReg : SpillPlacement::DontCare;
438 BC.Exit = (BI.Uses && BI.LiveOut) ?
439 SpillPlacement::PrefReg : SpillPlacement::DontCare;
440 BI.OverlapEntry = BI.OverlapExit = false;
441 }
442
443 // Add interference info from each PhysReg alias.
444 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
445 if (!query(VirtReg, *AI).checkInterference())
446 continue;
447 DEBUG(PhysReg2LiveUnion[*AI].print(dbgs(), TRI));
448 LiveIntervalUnion::SegmentIter IntI =
449 PhysReg2LiveUnion[*AI].find(VirtReg.beginIndex());
450 if (!IntI.valid())
451 continue;
452
453 for (unsigned i = 0, e = LiveBlocks.size(); i != e; ++i) {
454 BlockInfo &BI = LiveBlocks[i];
455 SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
456 SlotIndex Start, Stop;
457 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
458
459 // Skip interference-free blocks.
460 if (IntI.start() >= Stop)
461 continue;
462
463 // Handle transparent blocks with interference separately.
464 // Transparent blocks never incur any fixed cost.
465 if (BI.LiveThrough && !BI.Uses) {
466 // Check if interference is live-in - force spill.
467 if (BC.Entry != SpillPlacement::MustSpill) {
468 BC.Entry = SpillPlacement::PrefSpill;
469 IntI.advanceTo(Start);
470 if (IntI.valid() && IntI.start() <= Start)
471 BC.Entry = SpillPlacement::MustSpill;
472 }
473
474 // Check if interference is live-out - force spill.
475 if (BC.Exit != SpillPlacement::MustSpill) {
476 BC.Exit = SpillPlacement::PrefSpill;
Jakob Stoklund Olesen63935422011-02-04 21:42:06 +0000477 // Any interference overlapping [LastSplitPoint;Stop) forces a spill.
478 IntI.advanceTo(BI.LastSplitPoint.getPrevSlot());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000479 if (IntI.valid() && IntI.start() < Stop)
480 BC.Exit = SpillPlacement::MustSpill;
481 }
482
483 // Nothing more to do for this transparent block.
484 if (!IntI.valid())
485 break;
486 continue;
487 }
488
489 // Now we only have blocks with uses left.
490 // Check if the interference overlaps the uses.
491 assert(BI.Uses && "Non-transparent block without any uses");
492
493 // Check interference on entry.
494 if (BI.LiveIn && BC.Entry != SpillPlacement::MustSpill) {
495 IntI.advanceTo(Start);
496 if (!IntI.valid())
497 break;
498
499 // Interference is live-in - force spill.
500 if (IntI.start() <= Start)
501 BC.Entry = SpillPlacement::MustSpill;
502 // Not live in, but before the first use.
503 else if (IntI.start() < BI.FirstUse)
504 BC.Entry = SpillPlacement::PrefSpill;
505 }
506
507 // Does interference overlap the uses in the entry segment
508 // [FirstUse;Kill)?
509 if (BI.LiveIn && !BI.OverlapEntry) {
510 IntI.advanceTo(BI.FirstUse);
511 if (!IntI.valid())
512 break;
513 // A live-through interval has no kill.
514 // Check [FirstUse;LastUse) instead.
515 if (IntI.start() < (BI.LiveThrough ? BI.LastUse : BI.Kill))
516 BI.OverlapEntry = true;
517 }
518
519 // Does interference overlap the uses in the exit segment [Def;LastUse)?
520 if (BI.LiveOut && !BI.LiveThrough && !BI.OverlapExit) {
521 IntI.advanceTo(BI.Def);
522 if (!IntI.valid())
523 break;
524 if (IntI.start() < BI.LastUse)
525 BI.OverlapExit = true;
526 }
527
528 // Check interference on exit.
529 if (BI.LiveOut && BC.Exit != SpillPlacement::MustSpill) {
530 // Check interference between LastUse and Stop.
531 if (BC.Exit != SpillPlacement::PrefSpill) {
532 IntI.advanceTo(BI.LastUse);
533 if (!IntI.valid())
534 break;
535 if (IntI.start() < Stop)
536 BC.Exit = SpillPlacement::PrefSpill;
537 }
Jakob Stoklund Olesen63935422011-02-04 21:42:06 +0000538 // Is the interference overlapping the last split point?
539 IntI.advanceTo(BI.LastSplitPoint.getPrevSlot());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000540 if (!IntI.valid())
541 break;
542 if (IntI.start() < Stop)
543 BC.Exit = SpillPlacement::MustSpill;
544 }
545 }
546 }
547
548 // Accumulate a local cost of this interference pattern.
549 float LocalCost = 0;
550 for (unsigned i = 0, e = LiveBlocks.size(); i != e; ++i) {
551 BlockInfo &BI = LiveBlocks[i];
552 if (!BI.Uses)
553 continue;
554 SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
555 unsigned Inserts = 0;
556
557 // Do we need spill code for the entry segment?
558 if (BI.LiveIn)
559 Inserts += BI.OverlapEntry || BC.Entry != SpillPlacement::PrefReg;
560
561 // For the exit segment?
562 if (BI.LiveOut)
563 Inserts += BI.OverlapExit || BC.Exit != SpillPlacement::PrefReg;
564
565 // The local cost of spill code in this block is the block frequency times
566 // the number of spill instructions inserted.
567 if (Inserts)
568 LocalCost += Inserts * SpillPlacer->getBlockFrequency(BI.MBB);
569 }
570 DEBUG(dbgs() << "Local cost of " << PrintReg(PhysReg, TRI) << " = "
571 << LocalCost << '\n');
572 return LocalCost;
573}
574
575/// calcGlobalSplitCost - Return the global split cost of following the split
576/// pattern in LiveBundles. This cost should be added to the local cost of the
577/// interference pattern in SpillConstraints.
578///
579float RAGreedy::calcGlobalSplitCost(const BitVector &LiveBundles) {
580 float GlobalCost = 0;
581 for (unsigned i = 0, e = LiveBlocks.size(); i != e; ++i) {
582 SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
583 unsigned Inserts = 0;
584 // Broken entry preference?
585 Inserts += LiveBundles[Bundles->getBundle(BC.Number, 0)] !=
586 (BC.Entry == SpillPlacement::PrefReg);
587 // Broken exit preference?
588 Inserts += LiveBundles[Bundles->getBundle(BC.Number, 1)] !=
589 (BC.Exit == SpillPlacement::PrefReg);
590 if (Inserts)
591 GlobalCost += Inserts * SpillPlacer->getBlockFrequency(LiveBlocks[i].MBB);
592 }
593 DEBUG(dbgs() << "Global cost = " << GlobalCost << '\n');
594 return GlobalCost;
595}
596
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000597/// splitAroundRegion - Split VirtReg around the region determined by
598/// LiveBundles. Make an effort to avoid interference from PhysReg.
599///
600/// The 'register' interval is going to contain as many uses as possible while
601/// avoiding interference. The 'stack' interval is the complement constructed by
602/// SplitEditor. It will contain the rest.
603///
604void RAGreedy::splitAroundRegion(LiveInterval &VirtReg, unsigned PhysReg,
605 const BitVector &LiveBundles,
606 SmallVectorImpl<LiveInterval*> &NewVRegs) {
607 DEBUG({
608 dbgs() << "Splitting around region for " << PrintReg(PhysReg, TRI)
609 << " with bundles";
610 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
611 dbgs() << " EB#" << i;
612 dbgs() << ".\n";
613 });
614
615 // First compute interference ranges in the live blocks.
616 typedef std::pair<SlotIndex, SlotIndex> IndexPair;
617 SmallVector<IndexPair, 8> InterferenceRanges;
618 InterferenceRanges.resize(LiveBlocks.size());
619 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
620 if (!query(VirtReg, *AI).checkInterference())
621 continue;
622 LiveIntervalUnion::SegmentIter IntI =
623 PhysReg2LiveUnion[*AI].find(VirtReg.beginIndex());
624 if (!IntI.valid())
625 continue;
626 for (unsigned i = 0, e = LiveBlocks.size(); i != e; ++i) {
Jakob Stoklund Olesen45139872011-02-04 00:39:20 +0000627 const BlockInfo &BI = LiveBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000628 IndexPair &IP = InterferenceRanges[i];
629 SlotIndex Start, Stop;
630 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
631 // Skip interference-free blocks.
632 if (IntI.start() >= Stop)
633 continue;
634
635 // First interference in block.
636 if (BI.LiveIn) {
637 IntI.advanceTo(Start);
638 if (!IntI.valid())
639 break;
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000640 if (IntI.start() >= Stop)
641 continue;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000642 if (!IP.first.isValid() || IntI.start() < IP.first)
643 IP.first = IntI.start();
644 }
645
646 // Last interference in block.
647 if (BI.LiveOut) {
648 IntI.advanceTo(Stop);
649 if (!IntI.valid() || IntI.start() >= Stop)
650 --IntI;
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000651 if (IntI.stop() <= Start)
652 continue;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000653 if (!IP.second.isValid() || IntI.stop() > IP.second)
654 IP.second = IntI.stop();
655 }
656 }
657 }
658
659 SmallVector<LiveInterval*, 4> SpillRegs;
660 LiveRangeEdit LREdit(VirtReg, NewVRegs, SpillRegs);
661 SplitEditor SE(*SA, *LIS, *VRM, *DomTree, LREdit);
662
663 // Create the main cross-block interval.
664 SE.openIntv();
665
666 // First add all defs that are live out of a block.
667 for (unsigned i = 0, e = LiveBlocks.size(); i != e; ++i) {
668 BlockInfo &BI = LiveBlocks[i];
669 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
670 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
671
672 // Should the register be live out?
673 if (!BI.LiveOut || !RegOut)
674 continue;
675
676 IndexPair &IP = InterferenceRanges[i];
677 SlotIndex Start, Stop;
678 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
679
680 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " -> EB#"
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000681 << Bundles->getBundle(BI.MBB->getNumber(), 1)
682 << " intf [" << IP.first << ';' << IP.second << ')');
683
684 // The interference interval should either be invalid or overlap MBB.
685 assert((!IP.first.isValid() || IP.first < Stop) && "Bad interference");
686 assert((!IP.second.isValid() || IP.second > Start) && "Bad interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000687
688 // Check interference leaving the block.
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000689 if (!IP.second.isValid()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000690 // Block is interference-free.
691 DEBUG(dbgs() << ", no interference");
692 if (!BI.Uses) {
693 assert(BI.LiveThrough && "No uses, but not live through block?");
694 // Block is live-through without interference.
695 DEBUG(dbgs() << ", no uses"
696 << (RegIn ? ", live-through.\n" : ", stack in.\n"));
697 if (!RegIn)
698 SE.enterIntvAtEnd(*BI.MBB);
699 continue;
700 }
701 if (!BI.LiveThrough) {
702 DEBUG(dbgs() << ", not live-through.\n");
Jakob Stoklund Olesen207c8682011-02-03 17:04:16 +0000703 SE.useIntv(SE.enterIntvBefore(BI.Def), Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000704 continue;
705 }
706 if (!RegIn) {
707 // Block is live-through, but entry bundle is on the stack.
708 // Reload just before the first use.
709 DEBUG(dbgs() << ", not live-in, enter before first use.\n");
Jakob Stoklund Olesen207c8682011-02-03 17:04:16 +0000710 SE.useIntv(SE.enterIntvBefore(BI.FirstUse), Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000711 continue;
712 }
713 DEBUG(dbgs() << ", live-through.\n");
714 continue;
715 }
716
717 // Block has interference.
718 DEBUG(dbgs() << ", interference to " << IP.second);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000719
720 if (!BI.LiveThrough && IP.second <= BI.Def) {
721 // The interference doesn't reach the outgoing segment.
722 DEBUG(dbgs() << " doesn't affect def from " << BI.Def << '\n');
723 SE.useIntv(BI.Def, Stop);
724 continue;
725 }
726
727
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000728 if (!BI.Uses) {
729 // No uses in block, avoid interference by reloading as late as possible.
730 DEBUG(dbgs() << ", no uses.\n");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000731 SlotIndex SegStart = SE.enterIntvAtEnd(*BI.MBB);
732 assert(SegStart >= IP.second && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000733 continue;
734 }
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000735
736 if (IP.second.getBoundaryIndex() < BI.LastUse &&
737 IP.second.getBoundaryIndex() <= BI.LastSplitPoint) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000738 // There are interference-free uses at the end of the block.
739 // Find the first use that can get the live-out register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000740 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000741 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
742 IP.second.getBoundaryIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000743 assert(UI != SA->UseSlots.end() && "Couldn't find last use");
744 SlotIndex Use = *UI;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000745 DEBUG(dbgs() << ", free use at " << Use << ".\n");
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000746 assert(Use <= BI.LastUse && "Couldn't find last use");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000747 SlotIndex SegStart = SE.enterIntvBefore(Use);
748 assert(SegStart >= IP.second && "Couldn't avoid interference");
749 SE.useIntv(SegStart, Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000750 continue;
751 }
752
753 // Interference is after the last use.
754 DEBUG(dbgs() << " after last use.\n");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000755 SlotIndex SegStart = SE.enterIntvAtEnd(*BI.MBB);
756 assert(SegStart >= IP.second && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000757 }
758
759 // Now all defs leading to live bundles are handled, do everything else.
760 for (unsigned i = 0, e = LiveBlocks.size(); i != e; ++i) {
761 BlockInfo &BI = LiveBlocks[i];
762 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
763 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
764
765 // Is the register live-in?
766 if (!BI.LiveIn || !RegIn)
767 continue;
768
769 // We have an incoming register. Check for interference.
770 IndexPair &IP = InterferenceRanges[i];
771 SlotIndex Start, Stop;
772 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
773
774 DEBUG(dbgs() << "EB#" << Bundles->getBundle(BI.MBB->getNumber(), 0)
775 << " -> BB#" << BI.MBB->getNumber());
776
777 // Check interference entering the block.
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000778 if (!IP.first.isValid()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000779 // Block is interference-free.
780 DEBUG(dbgs() << ", no interference");
781 if (!BI.Uses) {
782 assert(BI.LiveThrough && "No uses, but not live through block?");
783 // Block is live-through without interference.
784 if (RegOut) {
785 DEBUG(dbgs() << ", no uses, live-through.\n");
786 SE.useIntv(Start, Stop);
787 } else {
788 DEBUG(dbgs() << ", no uses, stack-out.\n");
789 SE.leaveIntvAtTop(*BI.MBB);
790 }
791 continue;
792 }
793 if (!BI.LiveThrough) {
794 DEBUG(dbgs() << ", killed in block.\n");
Jakob Stoklund Olesen207c8682011-02-03 17:04:16 +0000795 SE.useIntv(Start, SE.leaveIntvAfter(BI.Kill));
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000796 continue;
797 }
798 if (!RegOut) {
799 // Block is live-through, but exit bundle is on the stack.
800 // Spill immediately after the last use.
801 DEBUG(dbgs() << ", uses, stack-out.\n");
Jakob Stoklund Olesen207c8682011-02-03 17:04:16 +0000802 SE.useIntv(Start, SE.leaveIntvAfter(BI.LastUse));
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000803 continue;
804 }
805 // Register is live-through.
806 DEBUG(dbgs() << ", uses, live-through.\n");
807 SE.useIntv(Start, Stop);
808 continue;
809 }
810
811 // Block has interference.
812 DEBUG(dbgs() << ", interference from " << IP.first);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000813
814 if (!BI.LiveThrough && IP.first >= BI.Kill) {
815 // The interference doesn't reach the outgoing segment.
816 DEBUG(dbgs() << " doesn't affect kill at " << BI.Kill << '\n');
817 SE.useIntv(Start, BI.Kill);
818 continue;
819 }
820
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000821 if (!BI.Uses) {
822 // No uses in block, avoid interference by spilling as soon as possible.
823 DEBUG(dbgs() << ", no uses.\n");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000824 SlotIndex SegEnd = SE.leaveIntvAtTop(*BI.MBB);
825 assert(SegEnd <= IP.first && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000826 continue;
827 }
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000828 if (IP.first.getBaseIndex() > BI.FirstUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000829 // There are interference-free uses at the beginning of the block.
830 // Find the last use that can get the register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000831 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000832 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
833 IP.first.getBaseIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000834 assert(UI != SA->UseSlots.begin() && "Couldn't find first use");
835 SlotIndex Use = (--UI)->getBoundaryIndex();
836 DEBUG(dbgs() << ", free use at " << *UI << ".\n");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000837 SlotIndex SegEnd = SE.leaveIntvAfter(Use);
838 assert(SegEnd <= IP.first && "Couldn't avoid interference");
839 SE.useIntv(Start, SegEnd);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000840 continue;
841 }
842
843 // Interference is before the first use.
844 DEBUG(dbgs() << " before first use.\n");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000845 SlotIndex SegEnd = SE.leaveIntvAtTop(*BI.MBB);
846 assert(SegEnd <= IP.first && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000847 }
848
849 SE.closeIntv();
850
851 // FIXME: Should we be more aggressive about splitting the stack region into
852 // per-block segments? The current approach allows the stack region to
853 // separate into connected components. Some components may be allocatable.
854 SE.finish();
855
Jakob Stoklund Olesen9b3d24b2011-02-04 19:33:07 +0000856 if (VerifyEnabled) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000857 MF->verify(this, "After splitting live range around region");
Jakob Stoklund Olesen9b3d24b2011-02-04 19:33:07 +0000858
859#ifndef NDEBUG
860 // Make sure that at least one of the new intervals can allocate to PhysReg.
861 // That was the whole point of splitting the live range.
862 bool found = false;
863 for (LiveRangeEdit::iterator I = LREdit.begin(), E = LREdit.end(); I != E;
864 ++I)
865 if (!checkUncachedInterference(**I, PhysReg)) {
866 found = true;
867 break;
868 }
869 assert(found && "No allocatable intervals after pointless splitting");
870#endif
871 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000872}
873
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000874unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
875 SmallVectorImpl<LiveInterval*> &NewVRegs) {
876 calcLiveBlockInfo(VirtReg);
877 BitVector LiveBundles, BestBundles;
878 float BestCost = 0;
879 unsigned BestReg = 0;
880 Order.rewind();
881 while (unsigned PhysReg = Order.next()) {
882 float Cost = calcInterferenceInfo(VirtReg, PhysReg);
883 if (BestReg && Cost >= BestCost)
884 continue;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000885
886 SpillPlacer->placeSpills(SpillConstraints, LiveBundles);
887 // No live bundles, defer to splitSingleBlocks().
888 if (!LiveBundles.any())
889 continue;
890
891 Cost += calcGlobalSplitCost(LiveBundles);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000892 if (!BestReg || Cost < BestCost) {
893 BestReg = PhysReg;
894 BestCost = Cost;
895 BestBundles.swap(LiveBundles);
896 }
897 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000898
899 if (!BestReg)
900 return 0;
901
902 splitAroundRegion(VirtReg, BestReg, BestBundles, NewVRegs);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000903 return 0;
904}
905
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000906
907//===----------------------------------------------------------------------===//
908// Live Range Splitting
909//===----------------------------------------------------------------------===//
910
911/// trySplit - Try to split VirtReg or one of its interferences, making it
912/// assignable.
913/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
914unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
915 SmallVectorImpl<LiveInterval*>&NewVRegs) {
916 NamedRegionTimer T("Splitter", TimerGroupName, TimePassesIsEnabled);
917 SA->analyze(&VirtReg);
918
919 // Don't attempt splitting on local intervals for now. TBD.
920 if (LIS->intervalIsInOneMBB(VirtReg))
921 return 0;
922
923 // First try to split around a region spanning multiple blocks.
924 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
925 if (PhysReg || !NewVRegs.empty())
926 return PhysReg;
927
928 // Then isolate blocks with multiple uses.
929 SplitAnalysis::BlockPtrSet Blocks;
930 if (SA->getMultiUseBlocks(Blocks)) {
931 SmallVector<LiveInterval*, 4> SpillRegs;
932 LiveRangeEdit LREdit(VirtReg, NewVRegs, SpillRegs);
933 SplitEditor(*SA, *LIS, *VRM, *DomTree, LREdit).splitSingleBlocks(Blocks);
Jakob Stoklund Olesen207c8682011-02-03 17:04:16 +0000934 if (VerifyEnabled)
935 MF->verify(this, "After splitting live range around basic blocks");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000936 }
937
938 // Don't assign any physregs.
939 return 0;
940}
941
942
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000943//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000944// Spilling
945//===----------------------------------------------------------------------===//
946
947/// calcInterferenceWeight - Calculate the combined spill weight of
948/// interferences when assigning VirtReg to PhysReg.
949float RAGreedy::calcInterferenceWeight(LiveInterval &VirtReg, unsigned PhysReg){
950 float Sum = 0;
951 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
952 LiveIntervalUnion::Query &Q = query(VirtReg, *AI);
953 Q.collectInterferingVRegs();
954 if (Q.seenUnspillableVReg())
955 return HUGE_VALF;
956 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i)
957 Sum += Q.interferingVRegs()[i]->weight;
958 }
959 return Sum;
960}
961
962/// trySpillInterferences - Try to spill interfering registers instead of the
963/// current one. Only do it if the accumulated spill weight is smaller than the
964/// current spill weight.
965unsigned RAGreedy::trySpillInterferences(LiveInterval &VirtReg,
966 AllocationOrder &Order,
967 SmallVectorImpl<LiveInterval*> &NewVRegs) {
968 NamedRegionTimer T("Spill Interference", TimerGroupName, TimePassesIsEnabled);
969 unsigned BestPhys = 0;
Duncan Sands2aea4902010-12-28 10:07:15 +0000970 float BestWeight = 0;
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000971
972 Order.rewind();
973 while (unsigned PhysReg = Order.next()) {
974 float Weight = calcInterferenceWeight(VirtReg, PhysReg);
975 if (Weight == HUGE_VALF || Weight >= VirtReg.weight)
976 continue;
977 if (!BestPhys || Weight < BestWeight)
978 BestPhys = PhysReg, BestWeight = Weight;
979 }
980
981 // No candidates found.
982 if (!BestPhys)
983 return 0;
984
985 // Collect all interfering registers.
986 SmallVector<LiveInterval*, 8> Spills;
987 for (const unsigned *AI = TRI->getOverlaps(BestPhys); *AI; ++AI) {
988 LiveIntervalUnion::Query &Q = query(VirtReg, *AI);
989 Spills.append(Q.interferingVRegs().begin(), Q.interferingVRegs().end());
990 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
991 LiveInterval *VReg = Q.interferingVRegs()[i];
992 PhysReg2LiveUnion[*AI].extract(*VReg);
993 VRM->clearVirt(VReg->reg);
994 }
995 }
996
997 // Spill them all.
998 DEBUG(dbgs() << "spilling " << Spills.size() << " interferences with weight "
999 << BestWeight << '\n');
1000 for (unsigned i = 0, e = Spills.size(); i != e; ++i)
1001 spiller().spill(Spills[i], NewVRegs, Spills);
1002 return BestPhys;
1003}
1004
1005
1006//===----------------------------------------------------------------------===//
1007// Main Entry Point
1008//===----------------------------------------------------------------------===//
1009
1010unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001011 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001012 // First try assigning a free register.
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +00001013 AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
1014 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001015 if (!checkPhysRegInterference(VirtReg, PhysReg))
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001016 return PhysReg;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001017 }
Andrew Trickb853e6c2010-12-09 18:15:21 +00001018
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001019 // Try to reassign interferences.
1020 if (unsigned PhysReg = tryReassign(VirtReg, Order))
1021 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001022
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001023 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1024
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001025 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001026 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1027 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001028 return PhysReg;
1029
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001030 // Try to spill another interfering reg with less spill weight.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001031 PhysReg = trySpillInterferences(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001032 if (PhysReg)
1033 return PhysReg;
1034
1035 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001036 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001037 SmallVector<LiveInterval*, 1> pendingSpills;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001038 spiller().spill(&VirtReg, NewVRegs, pendingSpills);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001039
1040 // The live virtual register requesting allocation was spilled, so tell
1041 // the caller not to allocate anything during this round.
1042 return 0;
1043}
1044
1045bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1046 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1047 << "********** Function: "
1048 << ((Value*)mf.getFunction())->getName() << '\n');
1049
1050 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001051 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001052 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001053
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001054 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001055 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001056 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001057 ReservedRegs = TRI->getReservedRegs(*MF);
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001058 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001059 Loops = &getAnalysis<MachineLoopInfo>();
1060 LoopRanges = &getAnalysis<MachineLoopRanges>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001061 Bundles = &getAnalysis<EdgeBundles>();
1062 SpillPlacer = &getAnalysis<SpillPlacement>();
1063
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001064 SA.reset(new SplitAnalysis(*MF, *LIS, *Loops));
1065
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001066 allocatePhysRegs();
1067 addMBBLiveIns(MF);
1068
1069 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001070 {
1071 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
1072 std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
1073 rewriter->runOnMachineFunction(*MF, *VRM, LIS);
1074 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001075
1076 // The pass output is in VirtRegMap. Release all the transient data.
1077 releaseMemory();
1078
1079 return true;
1080}