blob: e767bbad7edc8521eb9cdca456a1961646ef2836 [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;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000447 LiveIntervalUnion::SegmentIter IntI =
448 PhysReg2LiveUnion[*AI].find(VirtReg.beginIndex());
449 if (!IntI.valid())
450 continue;
451
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000452 // Determine which blocks have interference live in or after the last split
453 // point.
454 for (unsigned i = 0, e = LiveBlocks.size(); i != e; ++i) {
455 BlockInfo &BI = LiveBlocks[i];
456 SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
457 SlotIndex Start, Stop;
458 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
459
460 // Skip interference-free blocks.
461 if (IntI.start() >= Stop)
462 continue;
463
464 // Is the interference live-in?
465 if (BI.LiveIn) {
466 IntI.advanceTo(Start);
467 if (!IntI.valid())
468 break;
469 if (IntI.start() <= Start)
470 BC.Entry = SpillPlacement::MustSpill;
471 }
472
473 // Is the interference overlapping the last split point?
474 if (BI.LiveOut) {
475 if (IntI.stop() < BI.LastSplitPoint)
476 IntI.advanceTo(BI.LastSplitPoint.getPrevSlot());
477 if (!IntI.valid())
478 break;
479 if (IntI.start() < Stop)
480 BC.Exit = SpillPlacement::MustSpill;
481 }
482 }
483
484 // Rewind iterator and check other interferences.
485 IntI.find(VirtReg.beginIndex());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000486 for (unsigned i = 0, e = LiveBlocks.size(); i != e; ++i) {
487 BlockInfo &BI = LiveBlocks[i];
488 SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
489 SlotIndex Start, Stop;
490 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
491
492 // Skip interference-free blocks.
493 if (IntI.start() >= Stop)
494 continue;
495
496 // Handle transparent blocks with interference separately.
497 // Transparent blocks never incur any fixed cost.
498 if (BI.LiveThrough && !BI.Uses) {
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000499 IntI.advanceTo(Start);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000500 if (!IntI.valid())
501 break;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000502 if (IntI.start() >= Stop)
503 continue;
504
505 if (BC.Entry != SpillPlacement::MustSpill)
506 BC.Entry = SpillPlacement::PrefSpill;
507 if (BC.Exit != SpillPlacement::MustSpill)
508 BC.Exit = SpillPlacement::PrefSpill;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000509 continue;
510 }
511
512 // Now we only have blocks with uses left.
513 // Check if the interference overlaps the uses.
514 assert(BI.Uses && "Non-transparent block without any uses");
515
516 // Check interference on entry.
517 if (BI.LiveIn && BC.Entry != SpillPlacement::MustSpill) {
518 IntI.advanceTo(Start);
519 if (!IntI.valid())
520 break;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000521 // Not live in, but before the first use.
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000522 if (IntI.start() < BI.FirstUse)
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000523 BC.Entry = SpillPlacement::PrefSpill;
524 }
525
526 // Does interference overlap the uses in the entry segment
527 // [FirstUse;Kill)?
528 if (BI.LiveIn && !BI.OverlapEntry) {
529 IntI.advanceTo(BI.FirstUse);
530 if (!IntI.valid())
531 break;
532 // A live-through interval has no kill.
533 // Check [FirstUse;LastUse) instead.
534 if (IntI.start() < (BI.LiveThrough ? BI.LastUse : BI.Kill))
535 BI.OverlapEntry = true;
536 }
537
538 // Does interference overlap the uses in the exit segment [Def;LastUse)?
539 if (BI.LiveOut && !BI.LiveThrough && !BI.OverlapExit) {
540 IntI.advanceTo(BI.Def);
541 if (!IntI.valid())
542 break;
543 if (IntI.start() < BI.LastUse)
544 BI.OverlapExit = true;
545 }
546
547 // Check interference on exit.
548 if (BI.LiveOut && BC.Exit != SpillPlacement::MustSpill) {
549 // Check interference between LastUse and Stop.
550 if (BC.Exit != SpillPlacement::PrefSpill) {
551 IntI.advanceTo(BI.LastUse);
552 if (!IntI.valid())
553 break;
554 if (IntI.start() < Stop)
555 BC.Exit = SpillPlacement::PrefSpill;
556 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000557 }
558 }
559 }
560
561 // Accumulate a local cost of this interference pattern.
562 float LocalCost = 0;
563 for (unsigned i = 0, e = LiveBlocks.size(); i != e; ++i) {
564 BlockInfo &BI = LiveBlocks[i];
565 if (!BI.Uses)
566 continue;
567 SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
568 unsigned Inserts = 0;
569
570 // Do we need spill code for the entry segment?
571 if (BI.LiveIn)
572 Inserts += BI.OverlapEntry || BC.Entry != SpillPlacement::PrefReg;
573
574 // For the exit segment?
575 if (BI.LiveOut)
576 Inserts += BI.OverlapExit || BC.Exit != SpillPlacement::PrefReg;
577
578 // The local cost of spill code in this block is the block frequency times
579 // the number of spill instructions inserted.
580 if (Inserts)
581 LocalCost += Inserts * SpillPlacer->getBlockFrequency(BI.MBB);
582 }
583 DEBUG(dbgs() << "Local cost of " << PrintReg(PhysReg, TRI) << " = "
584 << LocalCost << '\n');
585 return LocalCost;
586}
587
588/// calcGlobalSplitCost - Return the global split cost of following the split
589/// pattern in LiveBundles. This cost should be added to the local cost of the
590/// interference pattern in SpillConstraints.
591///
592float RAGreedy::calcGlobalSplitCost(const BitVector &LiveBundles) {
593 float GlobalCost = 0;
594 for (unsigned i = 0, e = LiveBlocks.size(); i != e; ++i) {
595 SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
596 unsigned Inserts = 0;
597 // Broken entry preference?
598 Inserts += LiveBundles[Bundles->getBundle(BC.Number, 0)] !=
599 (BC.Entry == SpillPlacement::PrefReg);
600 // Broken exit preference?
601 Inserts += LiveBundles[Bundles->getBundle(BC.Number, 1)] !=
602 (BC.Exit == SpillPlacement::PrefReg);
603 if (Inserts)
604 GlobalCost += Inserts * SpillPlacer->getBlockFrequency(LiveBlocks[i].MBB);
605 }
606 DEBUG(dbgs() << "Global cost = " << GlobalCost << '\n');
607 return GlobalCost;
608}
609
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000610/// splitAroundRegion - Split VirtReg around the region determined by
611/// LiveBundles. Make an effort to avoid interference from PhysReg.
612///
613/// The 'register' interval is going to contain as many uses as possible while
614/// avoiding interference. The 'stack' interval is the complement constructed by
615/// SplitEditor. It will contain the rest.
616///
617void RAGreedy::splitAroundRegion(LiveInterval &VirtReg, unsigned PhysReg,
618 const BitVector &LiveBundles,
619 SmallVectorImpl<LiveInterval*> &NewVRegs) {
620 DEBUG({
621 dbgs() << "Splitting around region for " << PrintReg(PhysReg, TRI)
622 << " with bundles";
623 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
624 dbgs() << " EB#" << i;
625 dbgs() << ".\n";
626 });
627
628 // First compute interference ranges in the live blocks.
629 typedef std::pair<SlotIndex, SlotIndex> IndexPair;
630 SmallVector<IndexPair, 8> InterferenceRanges;
631 InterferenceRanges.resize(LiveBlocks.size());
632 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
633 if (!query(VirtReg, *AI).checkInterference())
634 continue;
635 LiveIntervalUnion::SegmentIter IntI =
636 PhysReg2LiveUnion[*AI].find(VirtReg.beginIndex());
637 if (!IntI.valid())
638 continue;
639 for (unsigned i = 0, e = LiveBlocks.size(); i != e; ++i) {
Jakob Stoklund Olesen45139872011-02-04 00:39:20 +0000640 const BlockInfo &BI = LiveBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000641 IndexPair &IP = InterferenceRanges[i];
642 SlotIndex Start, Stop;
643 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
644 // Skip interference-free blocks.
645 if (IntI.start() >= Stop)
646 continue;
647
648 // First interference in block.
649 if (BI.LiveIn) {
650 IntI.advanceTo(Start);
651 if (!IntI.valid())
652 break;
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000653 if (IntI.start() >= Stop)
654 continue;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000655 if (!IP.first.isValid() || IntI.start() < IP.first)
656 IP.first = IntI.start();
657 }
658
659 // Last interference in block.
660 if (BI.LiveOut) {
661 IntI.advanceTo(Stop);
662 if (!IntI.valid() || IntI.start() >= Stop)
663 --IntI;
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000664 if (IntI.stop() <= Start)
665 continue;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000666 if (!IP.second.isValid() || IntI.stop() > IP.second)
667 IP.second = IntI.stop();
668 }
669 }
670 }
671
672 SmallVector<LiveInterval*, 4> SpillRegs;
673 LiveRangeEdit LREdit(VirtReg, NewVRegs, SpillRegs);
674 SplitEditor SE(*SA, *LIS, *VRM, *DomTree, LREdit);
675
676 // Create the main cross-block interval.
677 SE.openIntv();
678
679 // First add all defs that are live out of a block.
680 for (unsigned i = 0, e = LiveBlocks.size(); i != e; ++i) {
681 BlockInfo &BI = LiveBlocks[i];
682 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
683 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
684
685 // Should the register be live out?
686 if (!BI.LiveOut || !RegOut)
687 continue;
688
689 IndexPair &IP = InterferenceRanges[i];
690 SlotIndex Start, Stop;
691 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
692
693 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " -> EB#"
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000694 << Bundles->getBundle(BI.MBB->getNumber(), 1)
695 << " intf [" << IP.first << ';' << IP.second << ')');
696
697 // The interference interval should either be invalid or overlap MBB.
698 assert((!IP.first.isValid() || IP.first < Stop) && "Bad interference");
699 assert((!IP.second.isValid() || IP.second > Start) && "Bad interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000700
701 // Check interference leaving the block.
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000702 if (!IP.second.isValid()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000703 // Block is interference-free.
704 DEBUG(dbgs() << ", no interference");
705 if (!BI.Uses) {
706 assert(BI.LiveThrough && "No uses, but not live through block?");
707 // Block is live-through without interference.
708 DEBUG(dbgs() << ", no uses"
709 << (RegIn ? ", live-through.\n" : ", stack in.\n"));
710 if (!RegIn)
711 SE.enterIntvAtEnd(*BI.MBB);
712 continue;
713 }
714 if (!BI.LiveThrough) {
715 DEBUG(dbgs() << ", not live-through.\n");
Jakob Stoklund Olesen207c8682011-02-03 17:04:16 +0000716 SE.useIntv(SE.enterIntvBefore(BI.Def), Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000717 continue;
718 }
719 if (!RegIn) {
720 // Block is live-through, but entry bundle is on the stack.
721 // Reload just before the first use.
722 DEBUG(dbgs() << ", not live-in, enter before first use.\n");
Jakob Stoklund Olesen207c8682011-02-03 17:04:16 +0000723 SE.useIntv(SE.enterIntvBefore(BI.FirstUse), Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000724 continue;
725 }
726 DEBUG(dbgs() << ", live-through.\n");
727 continue;
728 }
729
730 // Block has interference.
731 DEBUG(dbgs() << ", interference to " << IP.second);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000732
733 if (!BI.LiveThrough && IP.second <= BI.Def) {
734 // The interference doesn't reach the outgoing segment.
735 DEBUG(dbgs() << " doesn't affect def from " << BI.Def << '\n');
736 SE.useIntv(BI.Def, Stop);
737 continue;
738 }
739
740
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000741 if (!BI.Uses) {
742 // No uses in block, avoid interference by reloading as late as possible.
743 DEBUG(dbgs() << ", no uses.\n");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000744 SlotIndex SegStart = SE.enterIntvAtEnd(*BI.MBB);
745 assert(SegStart >= IP.second && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000746 continue;
747 }
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000748
749 if (IP.second.getBoundaryIndex() < BI.LastUse &&
750 IP.second.getBoundaryIndex() <= BI.LastSplitPoint) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000751 // There are interference-free uses at the end of the block.
752 // Find the first use that can get the live-out register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000753 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000754 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
755 IP.second.getBoundaryIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000756 assert(UI != SA->UseSlots.end() && "Couldn't find last use");
757 SlotIndex Use = *UI;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000758 DEBUG(dbgs() << ", free use at " << Use << ".\n");
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000759 assert(Use <= BI.LastUse && "Couldn't find last use");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000760 SlotIndex SegStart = SE.enterIntvBefore(Use);
761 assert(SegStart >= IP.second && "Couldn't avoid interference");
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000762 assert(SegStart < BI.LastSplitPoint && "Impossible split point");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000763 SE.useIntv(SegStart, Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000764 continue;
765 }
766
767 // Interference is after the last use.
768 DEBUG(dbgs() << " after last use.\n");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000769 SlotIndex SegStart = SE.enterIntvAtEnd(*BI.MBB);
770 assert(SegStart >= IP.second && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000771 }
772
773 // Now all defs leading to live bundles are handled, do everything else.
774 for (unsigned i = 0, e = LiveBlocks.size(); i != e; ++i) {
775 BlockInfo &BI = LiveBlocks[i];
776 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
777 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
778
779 // Is the register live-in?
780 if (!BI.LiveIn || !RegIn)
781 continue;
782
783 // We have an incoming register. Check for interference.
784 IndexPair &IP = InterferenceRanges[i];
785 SlotIndex Start, Stop;
786 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
787
788 DEBUG(dbgs() << "EB#" << Bundles->getBundle(BI.MBB->getNumber(), 0)
789 << " -> BB#" << BI.MBB->getNumber());
790
791 // Check interference entering the block.
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000792 if (!IP.first.isValid()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000793 // Block is interference-free.
794 DEBUG(dbgs() << ", no interference");
795 if (!BI.Uses) {
796 assert(BI.LiveThrough && "No uses, but not live through block?");
797 // Block is live-through without interference.
798 if (RegOut) {
799 DEBUG(dbgs() << ", no uses, live-through.\n");
800 SE.useIntv(Start, Stop);
801 } else {
802 DEBUG(dbgs() << ", no uses, stack-out.\n");
803 SE.leaveIntvAtTop(*BI.MBB);
804 }
805 continue;
806 }
807 if (!BI.LiveThrough) {
808 DEBUG(dbgs() << ", killed in block.\n");
Jakob Stoklund Olesen207c8682011-02-03 17:04:16 +0000809 SE.useIntv(Start, SE.leaveIntvAfter(BI.Kill));
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000810 continue;
811 }
812 if (!RegOut) {
813 // Block is live-through, but exit bundle is on the stack.
814 // Spill immediately after the last use.
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000815 if (BI.LastUse < BI.LastSplitPoint) {
816 DEBUG(dbgs() << ", uses, stack-out.\n");
817 SE.useIntv(Start, SE.leaveIntvAfter(BI.LastUse));
818 continue;
819 }
820 // The last use is after the last split point, it is probably an
821 // indirect jump.
822 DEBUG(dbgs() << ", uses at " << BI.LastUse << " after split point "
823 << BI.LastSplitPoint << ", stack-out.\n");
824 SlotIndex SegEnd;
Jakob Stoklund Olesend08d7732011-02-08 21:46:11 +0000825 // Find the last real instruction before the split point.
826 MachineBasicBlock::iterator SplitI =
827 LIS->getInstructionFromIndex(BI.LastSplitPoint);
828 MachineBasicBlock::iterator I = SplitI, B = BI.MBB->begin();
829 while (I != B && (--I)->isDebugValue())
830 ;
831 if (I == SplitI)
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000832 SegEnd = SE.leaveIntvAtTop(*BI.MBB);
833 else {
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000834 SegEnd = SE.leaveIntvAfter(LIS->getInstructionIndex(I));
Jakob Stoklund Olesend08d7732011-02-08 21:46:11 +0000835 SE.useIntv(Start, SegEnd);
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000836 }
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000837 // Run a double interval from the split to the last use.
838 // This makes it possible to spill the complement without affecting the
839 // indirect branch.
840 SE.overlapIntv(SegEnd, BI.LastUse);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000841 continue;
842 }
843 // Register is live-through.
844 DEBUG(dbgs() << ", uses, live-through.\n");
845 SE.useIntv(Start, Stop);
846 continue;
847 }
848
849 // Block has interference.
850 DEBUG(dbgs() << ", interference from " << IP.first);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000851
852 if (!BI.LiveThrough && IP.first >= BI.Kill) {
853 // The interference doesn't reach the outgoing segment.
854 DEBUG(dbgs() << " doesn't affect kill at " << BI.Kill << '\n');
855 SE.useIntv(Start, BI.Kill);
856 continue;
857 }
858
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000859 if (!BI.Uses) {
860 // No uses in block, avoid interference by spilling as soon as possible.
861 DEBUG(dbgs() << ", no uses.\n");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000862 SlotIndex SegEnd = SE.leaveIntvAtTop(*BI.MBB);
863 assert(SegEnd <= IP.first && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000864 continue;
865 }
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000866 if (IP.first.getBaseIndex() > BI.FirstUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000867 // There are interference-free uses at the beginning of the block.
868 // Find the last use that can get the register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000869 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000870 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
871 IP.first.getBaseIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000872 assert(UI != SA->UseSlots.begin() && "Couldn't find first use");
873 SlotIndex Use = (--UI)->getBoundaryIndex();
874 DEBUG(dbgs() << ", free use at " << *UI << ".\n");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000875 SlotIndex SegEnd = SE.leaveIntvAfter(Use);
876 assert(SegEnd <= IP.first && "Couldn't avoid interference");
877 SE.useIntv(Start, SegEnd);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000878 continue;
879 }
880
881 // Interference is before the first use.
882 DEBUG(dbgs() << " before first use.\n");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000883 SlotIndex SegEnd = SE.leaveIntvAtTop(*BI.MBB);
884 assert(SegEnd <= IP.first && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000885 }
886
887 SE.closeIntv();
888
889 // FIXME: Should we be more aggressive about splitting the stack region into
890 // per-block segments? The current approach allows the stack region to
891 // separate into connected components. Some components may be allocatable.
892 SE.finish();
893
Jakob Stoklund Olesen9b3d24b2011-02-04 19:33:07 +0000894 if (VerifyEnabled) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000895 MF->verify(this, "After splitting live range around region");
Jakob Stoklund Olesen9b3d24b2011-02-04 19:33:07 +0000896
897#ifndef NDEBUG
898 // Make sure that at least one of the new intervals can allocate to PhysReg.
899 // That was the whole point of splitting the live range.
900 bool found = false;
901 for (LiveRangeEdit::iterator I = LREdit.begin(), E = LREdit.end(); I != E;
902 ++I)
903 if (!checkUncachedInterference(**I, PhysReg)) {
904 found = true;
905 break;
906 }
907 assert(found && "No allocatable intervals after pointless splitting");
908#endif
909 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000910}
911
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000912unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
913 SmallVectorImpl<LiveInterval*> &NewVRegs) {
914 calcLiveBlockInfo(VirtReg);
915 BitVector LiveBundles, BestBundles;
916 float BestCost = 0;
917 unsigned BestReg = 0;
918 Order.rewind();
919 while (unsigned PhysReg = Order.next()) {
920 float Cost = calcInterferenceInfo(VirtReg, PhysReg);
921 if (BestReg && Cost >= BestCost)
922 continue;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000923
924 SpillPlacer->placeSpills(SpillConstraints, LiveBundles);
925 // No live bundles, defer to splitSingleBlocks().
926 if (!LiveBundles.any())
927 continue;
928
929 Cost += calcGlobalSplitCost(LiveBundles);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000930 if (!BestReg || Cost < BestCost) {
931 BestReg = PhysReg;
932 BestCost = Cost;
933 BestBundles.swap(LiveBundles);
934 }
935 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000936
937 if (!BestReg)
938 return 0;
939
940 splitAroundRegion(VirtReg, BestReg, BestBundles, NewVRegs);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000941 return 0;
942}
943
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000944
945//===----------------------------------------------------------------------===//
946// Live Range Splitting
947//===----------------------------------------------------------------------===//
948
949/// trySplit - Try to split VirtReg or one of its interferences, making it
950/// assignable.
951/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
952unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
953 SmallVectorImpl<LiveInterval*>&NewVRegs) {
954 NamedRegionTimer T("Splitter", TimerGroupName, TimePassesIsEnabled);
955 SA->analyze(&VirtReg);
956
957 // Don't attempt splitting on local intervals for now. TBD.
958 if (LIS->intervalIsInOneMBB(VirtReg))
959 return 0;
960
961 // First try to split around a region spanning multiple blocks.
962 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
963 if (PhysReg || !NewVRegs.empty())
964 return PhysReg;
965
966 // Then isolate blocks with multiple uses.
967 SplitAnalysis::BlockPtrSet Blocks;
968 if (SA->getMultiUseBlocks(Blocks)) {
969 SmallVector<LiveInterval*, 4> SpillRegs;
970 LiveRangeEdit LREdit(VirtReg, NewVRegs, SpillRegs);
971 SplitEditor(*SA, *LIS, *VRM, *DomTree, LREdit).splitSingleBlocks(Blocks);
Jakob Stoklund Olesen207c8682011-02-03 17:04:16 +0000972 if (VerifyEnabled)
973 MF->verify(this, "After splitting live range around basic blocks");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000974 }
975
976 // Don't assign any physregs.
977 return 0;
978}
979
980
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000981//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000982// Spilling
983//===----------------------------------------------------------------------===//
984
985/// calcInterferenceWeight - Calculate the combined spill weight of
986/// interferences when assigning VirtReg to PhysReg.
987float RAGreedy::calcInterferenceWeight(LiveInterval &VirtReg, unsigned PhysReg){
988 float Sum = 0;
989 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
990 LiveIntervalUnion::Query &Q = query(VirtReg, *AI);
991 Q.collectInterferingVRegs();
992 if (Q.seenUnspillableVReg())
993 return HUGE_VALF;
994 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i)
995 Sum += Q.interferingVRegs()[i]->weight;
996 }
997 return Sum;
998}
999
1000/// trySpillInterferences - Try to spill interfering registers instead of the
1001/// current one. Only do it if the accumulated spill weight is smaller than the
1002/// current spill weight.
1003unsigned RAGreedy::trySpillInterferences(LiveInterval &VirtReg,
1004 AllocationOrder &Order,
1005 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1006 NamedRegionTimer T("Spill Interference", TimerGroupName, TimePassesIsEnabled);
1007 unsigned BestPhys = 0;
Duncan Sands2aea4902010-12-28 10:07:15 +00001008 float BestWeight = 0;
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001009
1010 Order.rewind();
1011 while (unsigned PhysReg = Order.next()) {
1012 float Weight = calcInterferenceWeight(VirtReg, PhysReg);
1013 if (Weight == HUGE_VALF || Weight >= VirtReg.weight)
1014 continue;
1015 if (!BestPhys || Weight < BestWeight)
1016 BestPhys = PhysReg, BestWeight = Weight;
1017 }
1018
1019 // No candidates found.
1020 if (!BestPhys)
1021 return 0;
1022
1023 // Collect all interfering registers.
1024 SmallVector<LiveInterval*, 8> Spills;
1025 for (const unsigned *AI = TRI->getOverlaps(BestPhys); *AI; ++AI) {
1026 LiveIntervalUnion::Query &Q = query(VirtReg, *AI);
1027 Spills.append(Q.interferingVRegs().begin(), Q.interferingVRegs().end());
1028 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
1029 LiveInterval *VReg = Q.interferingVRegs()[i];
1030 PhysReg2LiveUnion[*AI].extract(*VReg);
1031 VRM->clearVirt(VReg->reg);
1032 }
1033 }
1034
1035 // Spill them all.
1036 DEBUG(dbgs() << "spilling " << Spills.size() << " interferences with weight "
1037 << BestWeight << '\n');
1038 for (unsigned i = 0, e = Spills.size(); i != e; ++i)
1039 spiller().spill(Spills[i], NewVRegs, Spills);
1040 return BestPhys;
1041}
1042
1043
1044//===----------------------------------------------------------------------===//
1045// Main Entry Point
1046//===----------------------------------------------------------------------===//
1047
1048unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001049 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001050 // First try assigning a free register.
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +00001051 AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
1052 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001053 if (!checkPhysRegInterference(VirtReg, PhysReg))
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001054 return PhysReg;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001055 }
Andrew Trickb853e6c2010-12-09 18:15:21 +00001056
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001057 // Try to reassign interferences.
1058 if (unsigned PhysReg = tryReassign(VirtReg, Order))
1059 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001060
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001061 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1062
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001063 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001064 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1065 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001066 return PhysReg;
1067
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001068 // Try to spill another interfering reg with less spill weight.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001069 PhysReg = trySpillInterferences(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001070 if (PhysReg)
1071 return PhysReg;
1072
1073 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001074 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001075 SmallVector<LiveInterval*, 1> pendingSpills;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001076 spiller().spill(&VirtReg, NewVRegs, pendingSpills);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001077
1078 // The live virtual register requesting allocation was spilled, so tell
1079 // the caller not to allocate anything during this round.
1080 return 0;
1081}
1082
1083bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1084 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1085 << "********** Function: "
1086 << ((Value*)mf.getFunction())->getName() << '\n');
1087
1088 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001089 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001090 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001091
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001092 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001093 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001094 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001095 ReservedRegs = TRI->getReservedRegs(*MF);
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001096 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001097 Loops = &getAnalysis<MachineLoopInfo>();
1098 LoopRanges = &getAnalysis<MachineLoopRanges>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001099 Bundles = &getAnalysis<EdgeBundles>();
1100 SpillPlacer = &getAnalysis<SpillPlacement>();
1101
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001102 SA.reset(new SplitAnalysis(*MF, *LIS, *Loops));
1103
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001104 allocatePhysRegs();
1105 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001106 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001107
1108 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001109 {
1110 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
1111 std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
1112 rewriter->runOnMachineFunction(*MF, *VRM, LIS);
1113 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001114
1115 // The pass output is in VirtRegMap. Release all the transient data.
1116 releaseMemory();
1117
1118 return true;
1119}