blob: f08041cd6e7eca33d29cf70648b764ca9d950b82 [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"
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000024#include "llvm/ADT/Statistic.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
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000046#include <queue>
47
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000048using namespace llvm;
49
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +000050STATISTIC(NumGlobalSplits, "Number of split global live ranges");
51STATISTIC(NumLocalSplits, "Number of split local live ranges");
52STATISTIC(NumReassigned, "Number of interferences reassigned");
53STATISTIC(NumEvicted, "Number of interferences evicted");
54
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000055static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
56 createGreedyRegisterAllocator);
57
58namespace {
59class RAGreedy : public MachineFunctionPass, public RegAllocBase {
60 // context
61 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000062 BitVector ReservedRegs;
63
64 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000065 SlotIndexes *Indexes;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000066 LiveStacks *LS;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000067 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000068 MachineLoopInfo *Loops;
69 MachineLoopRanges *LoopRanges;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000070 EdgeBundles *Bundles;
71 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000072
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000073 // state
74 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000075 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000076
77 // Live ranges pass through a number of stages as we try to allocate them.
78 // Some of the stages may also create new live ranges:
79 //
80 // - Region splitting.
81 // - Per-block splitting.
82 // - Local splitting.
83 // - Spilling.
84 //
85 // Ranges produced by one of the stages skip the previous stages when they are
86 // dequeued. This improves performance because we can skip interference checks
87 // that are unlikely to give any results. It also guarantees that the live
88 // range splitting algorithm terminates, something that is otherwise hard to
89 // ensure.
90 enum LiveRangeStage {
91 RS_Original, ///< Never seen before, never split.
92 RS_Second, ///< Second time in the queue.
93 RS_Region, ///< Produced by region splitting.
94 RS_Block, ///< Produced by per-block splitting.
95 RS_Local, ///< Produced by local splitting.
96 RS_Spill ///< Produced by spilling.
97 };
98
99 IndexedMap<unsigned char, VirtReg2IndexFunctor> LRStage;
100
101 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
102 return LiveRangeStage(LRStage[VirtReg.reg]);
103 }
104
105 template<typename Iterator>
106 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
107 LRStage.resize(MRI->getNumVirtRegs());
108 for (;Begin != End; ++Begin)
109 LRStage[(*Begin)->reg] = NewStage;
110 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000111
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000112 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000113 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000114
115 /// All basic blocks where the current register is live.
116 SmallVector<SpillPlacement::BlockConstraint, 8> SpillConstraints;
117
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000118 /// For every instruction in SA->UseSlots, store the previous non-copy
119 /// instruction.
120 SmallVector<SlotIndex, 8> PrevSlot;
121
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000122public:
123 RAGreedy();
124
125 /// Return the pass name.
126 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000127 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000128 }
129
130 /// RAGreedy analysis usage.
131 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000132 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000133 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000134 virtual void enqueue(LiveInterval *LI);
135 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000136 virtual unsigned selectOrSplit(LiveInterval&,
137 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000138
139 /// Perform register allocation.
140 virtual bool runOnMachineFunction(MachineFunction &mf);
141
142 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000143
144private:
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000145 bool checkUncachedInterference(LiveInterval&, unsigned);
146 LiveInterval *getSingleInterference(LiveInterval&, unsigned);
Andrew Trickb853e6c2010-12-09 18:15:21 +0000147 bool reassignVReg(LiveInterval &InterferingVReg, unsigned OldPhysReg);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000148 float calcInterferenceInfo(LiveInterval&, unsigned);
149 float calcGlobalSplitCost(const BitVector&);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000150 void splitAroundRegion(LiveInterval&, unsigned, const BitVector&,
151 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000152 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
153 SlotIndex getPrevMappedIndex(const MachineInstr*);
154 void calcPrevSlots();
155 unsigned nextSplitPoint(unsigned);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000156 bool canEvictInterference(LiveInterval&, unsigned, unsigned, float&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000157
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000158 unsigned tryReassign(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000159 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000160 unsigned tryEvict(LiveInterval&, AllocationOrder&,
161 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000162 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
163 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000164 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
165 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000166 unsigned trySplit(LiveInterval&, AllocationOrder&,
167 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000168};
169} // end anonymous namespace
170
171char RAGreedy::ID = 0;
172
173FunctionPass* llvm::createGreedyRegisterAllocator() {
174 return new RAGreedy();
175}
176
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000177RAGreedy::RAGreedy(): MachineFunctionPass(ID), LRStage(RS_Original) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000178 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000179 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
180 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
181 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
182 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
183 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
184 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
185 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
186 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000187 initializeMachineLoopRangesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000188 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000189 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
190 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000191}
192
193void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
194 AU.setPreservesCFG();
195 AU.addRequired<AliasAnalysis>();
196 AU.addPreserved<AliasAnalysis>();
197 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000198 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000199 AU.addPreserved<SlotIndexes>();
200 if (StrongPHIElim)
201 AU.addRequiredID(StrongPHIEliminationID);
202 AU.addRequiredTransitive<RegisterCoalescer>();
203 AU.addRequired<CalculateSpillWeights>();
204 AU.addRequired<LiveStacks>();
205 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000206 AU.addRequired<MachineDominatorTree>();
207 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000208 AU.addRequired<MachineLoopInfo>();
209 AU.addPreserved<MachineLoopInfo>();
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000210 AU.addRequired<MachineLoopRanges>();
211 AU.addPreserved<MachineLoopRanges>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000212 AU.addRequired<VirtRegMap>();
213 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000214 AU.addRequired<EdgeBundles>();
215 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000216 MachineFunctionPass::getAnalysisUsage(AU);
217}
218
219void RAGreedy::releaseMemory() {
220 SpillerInstance.reset(0);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000221 LRStage.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000222 RegAllocBase::releaseMemory();
223}
224
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000225void RAGreedy::enqueue(LiveInterval *LI) {
226 // Prioritize live ranges by size, assigning larger ranges first.
227 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000228 const unsigned Size = LI->getSize();
229 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000230 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
231 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000232 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000233
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000234 LRStage.grow(Reg);
235 if (LRStage[Reg] == RS_Original)
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000236 // 1st generation ranges are handled first, long -> short.
237 Prio = (1u << 31) + Size;
238 else
239 // Repeat offenders are handled second, short -> long
240 Prio = (1u << 30) - Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000241
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000242 // Boost ranges that have a physical register hint.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000243 const unsigned Hint = VRM->getRegAllocPref(Reg);
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000244 if (TargetRegisterInfo::isPhysicalRegister(Hint))
245 Prio |= (1u << 30);
246
247 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000248}
249
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000250LiveInterval *RAGreedy::dequeue() {
251 if (Queue.empty())
252 return 0;
253 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
254 Queue.pop();
255 return LI;
256}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000257
258//===----------------------------------------------------------------------===//
259// Register Reassignment
260//===----------------------------------------------------------------------===//
261
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000262// Check interference without using the cache.
263bool RAGreedy::checkUncachedInterference(LiveInterval &VirtReg,
264 unsigned PhysReg) {
Jakob Stoklund Olesen257c5562010-12-14 23:38:19 +0000265 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
266 LiveIntervalUnion::Query subQ(&VirtReg, &PhysReg2LiveUnion[*AliasI]);
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000267 if (subQ.checkInterference())
268 return true;
269 }
270 return false;
271}
272
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000273/// getSingleInterference - Return the single interfering virtual register
274/// assigned to PhysReg. Return 0 if more than one virtual register is
275/// interfering.
276LiveInterval *RAGreedy::getSingleInterference(LiveInterval &VirtReg,
277 unsigned PhysReg) {
Jakob Stoklund Olesen257c5562010-12-14 23:38:19 +0000278 // Check physreg and aliases.
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000279 LiveInterval *Interference = 0;
Jakob Stoklund Olesen257c5562010-12-14 23:38:19 +0000280 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000281 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
282 if (Q.checkInterference()) {
Jakob Stoklund Olesend84de8c2010-12-14 17:47:36 +0000283 if (Interference)
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000284 return 0;
Jakob Stoklund Olesen417df012011-02-23 00:29:55 +0000285 if (Q.collectInterferingVRegs(2) > 1)
Jakob Stoklund Olesend84de8c2010-12-14 17:47:36 +0000286 return 0;
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000287 Interference = Q.interferingVRegs().front();
288 }
289 }
290 return Interference;
291}
292
Andrew Trickb853e6c2010-12-09 18:15:21 +0000293// Attempt to reassign this virtual register to a different physical register.
294//
295// FIXME: we are not yet caching these "second-level" interferences discovered
296// in the sub-queries. These interferences can change with each call to
297// selectOrSplit. However, we could implement a "may-interfere" cache that
298// could be conservatively dirtied when we reassign or split.
299//
300// FIXME: This may result in a lot of alias queries. We could summarize alias
301// live intervals in their parent register's live union, but it's messy.
302bool RAGreedy::reassignVReg(LiveInterval &InterferingVReg,
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000303 unsigned WantedPhysReg) {
304 assert(TargetRegisterInfo::isVirtualRegister(InterferingVReg.reg) &&
305 "Can only reassign virtual registers");
306 assert(TRI->regsOverlap(WantedPhysReg, VRM->getPhys(InterferingVReg.reg)) &&
Andrew Trickb853e6c2010-12-09 18:15:21 +0000307 "inconsistent phys reg assigment");
308
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +0000309 AllocationOrder Order(InterferingVReg.reg, *VRM, ReservedRegs);
310 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000311 // Don't reassign to a WantedPhysReg alias.
312 if (TRI->regsOverlap(PhysReg, WantedPhysReg))
Andrew Trickb853e6c2010-12-09 18:15:21 +0000313 continue;
314
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000315 if (checkUncachedInterference(InterferingVReg, PhysReg))
Andrew Trickb853e6c2010-12-09 18:15:21 +0000316 continue;
317
Andrew Trickb853e6c2010-12-09 18:15:21 +0000318 // Reassign the interfering virtual reg to this physical reg.
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000319 unsigned OldAssign = VRM->getPhys(InterferingVReg.reg);
320 DEBUG(dbgs() << "reassigning: " << InterferingVReg << " from " <<
321 TRI->getName(OldAssign) << " to " << TRI->getName(PhysReg) << '\n');
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000322 unassign(InterferingVReg, OldAssign);
323 assign(InterferingVReg, PhysReg);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000324 ++NumReassigned;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000325 return true;
326 }
327 return false;
328}
329
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000330/// tryReassign - Try to reassign a single interference to a different physreg.
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000331/// @param VirtReg Currently unassigned virtual register.
332/// @param Order Physregs to try.
333/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000334unsigned RAGreedy::tryReassign(LiveInterval &VirtReg, AllocationOrder &Order,
335 SmallVectorImpl<LiveInterval*> &NewVRegs){
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000336 NamedRegionTimer T("Reassign", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000337
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000338 Order.rewind();
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000339 while (unsigned PhysReg = Order.next()) {
340 LiveInterval *InterferingVReg = getSingleInterference(VirtReg, PhysReg);
341 if (!InterferingVReg)
342 continue;
343 if (TargetRegisterInfo::isPhysicalRegister(InterferingVReg->reg))
344 continue;
345 if (reassignVReg(*InterferingVReg, PhysReg))
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000346 return PhysReg;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000347 }
348 return 0;
349}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000350
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000351
352//===----------------------------------------------------------------------===//
353// Interference eviction
354//===----------------------------------------------------------------------===//
355
356/// canEvict - Return true if all interferences between VirtReg and PhysReg can
357/// be evicted. Set maxWeight to the maximal spill weight of an interference.
358bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
359 unsigned Size, float &MaxWeight) {
360 float Weight = 0;
361 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
362 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
363 // If there is 10 or more interferences, chances are one is smaller.
364 if (Q.collectInterferingVRegs(10) >= 10)
365 return false;
366
367 // CHeck if any interfering live range is shorter than VirtReg.
368 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
369 LiveInterval *Intf = Q.interferingVRegs()[i];
370 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
371 return false;
372 if (Intf->getSize() <= Size)
373 return false;
374 Weight = std::max(Weight, Intf->weight);
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000375 }
376 }
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000377 MaxWeight = Weight;
378 return true;
379}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000380
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000381/// tryEvict - Try to evict all interferences for a physreg.
382/// @param VirtReg Currently unassigned virtual register.
383/// @param Order Physregs to try.
384/// @return Physreg to assign VirtReg, or 0.
385unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
386 AllocationOrder &Order,
387 SmallVectorImpl<LiveInterval*> &NewVRegs){
388 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
389
390 // We can only evict interference if all interfering registers are virtual and
391 // longer than VirtReg.
392 const unsigned Size = VirtReg.getSize();
393
394 // Keep track of the lightest single interference seen so far.
395 float BestWeight = 0;
396 unsigned BestPhys = 0;
397
398 Order.rewind();
399 while (unsigned PhysReg = Order.next()) {
400 float Weight = 0;
401 if (!canEvictInterference(VirtReg, PhysReg, Size, Weight))
402 continue;
403
404 // This is an eviction candidate.
405 DEBUG(dbgs() << "max " << PrintReg(PhysReg, TRI) << " interference = "
406 << Weight << '\n');
407 if (BestPhys && Weight >= BestWeight)
408 continue;
409
410 // Best so far.
411 BestPhys = PhysReg;
412 BestWeight = Weight;
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000413 // Stop if the hint can be used.
414 if (Order.isHint(PhysReg))
415 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000416 }
417
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000418 if (!BestPhys)
419 return 0;
420
421 DEBUG(dbgs() << "evicting " << PrintReg(BestPhys, TRI) << " interference\n");
422 for (const unsigned *AliasI = TRI->getOverlaps(BestPhys); *AliasI; ++AliasI) {
423 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
424 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
425 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
426 LiveInterval *Intf = Q.interferingVRegs()[i];
427 unassign(*Intf, VRM->getPhys(Intf->reg));
428 ++NumEvicted;
429 NewVRegs.push_back(Intf);
430 }
431 }
432 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000433}
434
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000435
436//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000437// Region Splitting
438//===----------------------------------------------------------------------===//
439
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000440/// calcInterferenceInfo - Compute per-block outgoing and ingoing constraints
441/// when considering interference from PhysReg. Also compute an optimistic local
442/// cost of this interference pattern.
443///
444/// The final cost of a split is the local cost + global cost of preferences
445/// broken by SpillPlacement.
446///
447float RAGreedy::calcInterferenceInfo(LiveInterval &VirtReg, unsigned PhysReg) {
448 // Reset interference dependent info.
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000449 SpillConstraints.resize(SA->LiveBlocks.size());
450 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
451 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000452 SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000453 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000454 BC.Entry = (BI.Uses && BI.LiveIn) ?
455 SpillPlacement::PrefReg : SpillPlacement::DontCare;
456 BC.Exit = (BI.Uses && BI.LiveOut) ?
457 SpillPlacement::PrefReg : SpillPlacement::DontCare;
458 BI.OverlapEntry = BI.OverlapExit = false;
459 }
460
461 // Add interference info from each PhysReg alias.
462 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
463 if (!query(VirtReg, *AI).checkInterference())
464 continue;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000465 LiveIntervalUnion::SegmentIter IntI =
466 PhysReg2LiveUnion[*AI].find(VirtReg.beginIndex());
467 if (!IntI.valid())
468 continue;
469
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000470 // Determine which blocks have interference live in or after the last split
471 // point.
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000472 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
473 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000474 SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
475 SlotIndex Start, Stop;
476 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
477
478 // Skip interference-free blocks.
479 if (IntI.start() >= Stop)
480 continue;
481
482 // Is the interference live-in?
483 if (BI.LiveIn) {
484 IntI.advanceTo(Start);
485 if (!IntI.valid())
486 break;
487 if (IntI.start() <= Start)
488 BC.Entry = SpillPlacement::MustSpill;
489 }
490
491 // Is the interference overlapping the last split point?
492 if (BI.LiveOut) {
493 if (IntI.stop() < BI.LastSplitPoint)
494 IntI.advanceTo(BI.LastSplitPoint.getPrevSlot());
495 if (!IntI.valid())
496 break;
497 if (IntI.start() < Stop)
498 BC.Exit = SpillPlacement::MustSpill;
499 }
500 }
501
502 // Rewind iterator and check other interferences.
503 IntI.find(VirtReg.beginIndex());
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000504 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
505 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000506 SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
507 SlotIndex Start, Stop;
508 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
509
510 // Skip interference-free blocks.
511 if (IntI.start() >= Stop)
512 continue;
513
514 // Handle transparent blocks with interference separately.
515 // Transparent blocks never incur any fixed cost.
516 if (BI.LiveThrough && !BI.Uses) {
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000517 IntI.advanceTo(Start);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000518 if (!IntI.valid())
519 break;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000520 if (IntI.start() >= Stop)
521 continue;
522
523 if (BC.Entry != SpillPlacement::MustSpill)
524 BC.Entry = SpillPlacement::PrefSpill;
525 if (BC.Exit != SpillPlacement::MustSpill)
526 BC.Exit = SpillPlacement::PrefSpill;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000527 continue;
528 }
529
530 // Now we only have blocks with uses left.
531 // Check if the interference overlaps the uses.
532 assert(BI.Uses && "Non-transparent block without any uses");
533
534 // Check interference on entry.
535 if (BI.LiveIn && BC.Entry != SpillPlacement::MustSpill) {
536 IntI.advanceTo(Start);
537 if (!IntI.valid())
538 break;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000539 // Not live in, but before the first use.
Jakob Stoklund Olesen06c0f252011-02-21 23:09:46 +0000540 if (IntI.start() < BI.FirstUse) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000541 BC.Entry = SpillPlacement::PrefSpill;
Jakob Stoklund Olesen06c0f252011-02-21 23:09:46 +0000542 // If the block contains a kill from an earlier split, never split
543 // again in the same block.
544 if (!BI.LiveThrough && !SA->isOriginalEndpoint(BI.Kill))
545 BC.Entry = SpillPlacement::MustSpill;
546 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000547 }
548
549 // Does interference overlap the uses in the entry segment
550 // [FirstUse;Kill)?
551 if (BI.LiveIn && !BI.OverlapEntry) {
552 IntI.advanceTo(BI.FirstUse);
553 if (!IntI.valid())
554 break;
555 // A live-through interval has no kill.
556 // Check [FirstUse;LastUse) instead.
557 if (IntI.start() < (BI.LiveThrough ? BI.LastUse : BI.Kill))
558 BI.OverlapEntry = true;
559 }
560
561 // Does interference overlap the uses in the exit segment [Def;LastUse)?
562 if (BI.LiveOut && !BI.LiveThrough && !BI.OverlapExit) {
563 IntI.advanceTo(BI.Def);
564 if (!IntI.valid())
565 break;
566 if (IntI.start() < BI.LastUse)
567 BI.OverlapExit = true;
568 }
569
570 // Check interference on exit.
571 if (BI.LiveOut && BC.Exit != SpillPlacement::MustSpill) {
572 // Check interference between LastUse and Stop.
573 if (BC.Exit != SpillPlacement::PrefSpill) {
574 IntI.advanceTo(BI.LastUse);
575 if (!IntI.valid())
576 break;
Jakob Stoklund Olesen06c0f252011-02-21 23:09:46 +0000577 if (IntI.start() < Stop) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000578 BC.Exit = SpillPlacement::PrefSpill;
Jakob Stoklund Olesen06c0f252011-02-21 23:09:46 +0000579 // Avoid splitting twice in the same block.
580 if (!BI.LiveThrough && !SA->isOriginalEndpoint(BI.Def))
581 BC.Exit = SpillPlacement::MustSpill;
582 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000583 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000584 }
585 }
586 }
587
588 // Accumulate a local cost of this interference pattern.
589 float LocalCost = 0;
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000590 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
591 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000592 if (!BI.Uses)
593 continue;
594 SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
595 unsigned Inserts = 0;
596
597 // Do we need spill code for the entry segment?
598 if (BI.LiveIn)
599 Inserts += BI.OverlapEntry || BC.Entry != SpillPlacement::PrefReg;
600
601 // For the exit segment?
602 if (BI.LiveOut)
603 Inserts += BI.OverlapExit || BC.Exit != SpillPlacement::PrefReg;
604
605 // The local cost of spill code in this block is the block frequency times
606 // the number of spill instructions inserted.
607 if (Inserts)
608 LocalCost += Inserts * SpillPlacer->getBlockFrequency(BI.MBB);
609 }
610 DEBUG(dbgs() << "Local cost of " << PrintReg(PhysReg, TRI) << " = "
611 << LocalCost << '\n');
612 return LocalCost;
613}
614
615/// calcGlobalSplitCost - Return the global split cost of following the split
616/// pattern in LiveBundles. This cost should be added to the local cost of the
617/// interference pattern in SpillConstraints.
618///
619float RAGreedy::calcGlobalSplitCost(const BitVector &LiveBundles) {
620 float GlobalCost = 0;
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000621 for (unsigned i = 0, e = SpillConstraints.size(); i != e; ++i) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000622 SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
623 unsigned Inserts = 0;
624 // Broken entry preference?
625 Inserts += LiveBundles[Bundles->getBundle(BC.Number, 0)] !=
626 (BC.Entry == SpillPlacement::PrefReg);
627 // Broken exit preference?
628 Inserts += LiveBundles[Bundles->getBundle(BC.Number, 1)] !=
629 (BC.Exit == SpillPlacement::PrefReg);
630 if (Inserts)
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000631 GlobalCost +=
632 Inserts * SpillPlacer->getBlockFrequency(SA->LiveBlocks[i].MBB);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000633 }
634 DEBUG(dbgs() << "Global cost = " << GlobalCost << '\n');
635 return GlobalCost;
636}
637
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000638/// splitAroundRegion - Split VirtReg around the region determined by
639/// LiveBundles. Make an effort to avoid interference from PhysReg.
640///
641/// The 'register' interval is going to contain as many uses as possible while
642/// avoiding interference. The 'stack' interval is the complement constructed by
643/// SplitEditor. It will contain the rest.
644///
645void RAGreedy::splitAroundRegion(LiveInterval &VirtReg, unsigned PhysReg,
646 const BitVector &LiveBundles,
647 SmallVectorImpl<LiveInterval*> &NewVRegs) {
648 DEBUG({
649 dbgs() << "Splitting around region for " << PrintReg(PhysReg, TRI)
650 << " with bundles";
651 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
652 dbgs() << " EB#" << i;
653 dbgs() << ".\n";
654 });
655
656 // First compute interference ranges in the live blocks.
657 typedef std::pair<SlotIndex, SlotIndex> IndexPair;
658 SmallVector<IndexPair, 8> InterferenceRanges;
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000659 InterferenceRanges.resize(SA->LiveBlocks.size());
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000660 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
661 if (!query(VirtReg, *AI).checkInterference())
662 continue;
663 LiveIntervalUnion::SegmentIter IntI =
664 PhysReg2LiveUnion[*AI].find(VirtReg.beginIndex());
665 if (!IntI.valid())
666 continue;
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000667 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
668 const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000669 IndexPair &IP = InterferenceRanges[i];
670 SlotIndex Start, Stop;
671 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
672 // Skip interference-free blocks.
673 if (IntI.start() >= Stop)
674 continue;
675
676 // First interference in block.
677 if (BI.LiveIn) {
678 IntI.advanceTo(Start);
679 if (!IntI.valid())
680 break;
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000681 if (IntI.start() >= Stop)
682 continue;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000683 if (!IP.first.isValid() || IntI.start() < IP.first)
684 IP.first = IntI.start();
685 }
686
687 // Last interference in block.
688 if (BI.LiveOut) {
689 IntI.advanceTo(Stop);
690 if (!IntI.valid() || IntI.start() >= Stop)
691 --IntI;
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000692 if (IntI.stop() <= Start)
693 continue;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000694 if (!IP.second.isValid() || IntI.stop() > IP.second)
695 IP.second = IntI.stop();
696 }
697 }
698 }
699
700 SmallVector<LiveInterval*, 4> SpillRegs;
701 LiveRangeEdit LREdit(VirtReg, NewVRegs, SpillRegs);
702 SplitEditor SE(*SA, *LIS, *VRM, *DomTree, LREdit);
703
704 // Create the main cross-block interval.
705 SE.openIntv();
706
707 // First add all defs that are live out of a block.
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000708 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
709 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000710 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
711 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
712
713 // Should the register be live out?
714 if (!BI.LiveOut || !RegOut)
715 continue;
716
717 IndexPair &IP = InterferenceRanges[i];
718 SlotIndex Start, Stop;
719 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
720
721 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " -> EB#"
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000722 << Bundles->getBundle(BI.MBB->getNumber(), 1)
723 << " intf [" << IP.first << ';' << IP.second << ')');
724
725 // The interference interval should either be invalid or overlap MBB.
726 assert((!IP.first.isValid() || IP.first < Stop) && "Bad interference");
727 assert((!IP.second.isValid() || IP.second > Start) && "Bad interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000728
729 // Check interference leaving the block.
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000730 if (!IP.second.isValid()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000731 // Block is interference-free.
732 DEBUG(dbgs() << ", no interference");
733 if (!BI.Uses) {
734 assert(BI.LiveThrough && "No uses, but not live through block?");
735 // Block is live-through without interference.
736 DEBUG(dbgs() << ", no uses"
737 << (RegIn ? ", live-through.\n" : ", stack in.\n"));
738 if (!RegIn)
739 SE.enterIntvAtEnd(*BI.MBB);
740 continue;
741 }
742 if (!BI.LiveThrough) {
743 DEBUG(dbgs() << ", not live-through.\n");
Jakob Stoklund Olesen207c8682011-02-03 17:04:16 +0000744 SE.useIntv(SE.enterIntvBefore(BI.Def), Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000745 continue;
746 }
747 if (!RegIn) {
748 // Block is live-through, but entry bundle is on the stack.
749 // Reload just before the first use.
750 DEBUG(dbgs() << ", not live-in, enter before first use.\n");
Jakob Stoklund Olesen207c8682011-02-03 17:04:16 +0000751 SE.useIntv(SE.enterIntvBefore(BI.FirstUse), Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000752 continue;
753 }
754 DEBUG(dbgs() << ", live-through.\n");
755 continue;
756 }
757
758 // Block has interference.
759 DEBUG(dbgs() << ", interference to " << IP.second);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000760
761 if (!BI.LiveThrough && IP.second <= BI.Def) {
762 // The interference doesn't reach the outgoing segment.
763 DEBUG(dbgs() << " doesn't affect def from " << BI.Def << '\n');
764 SE.useIntv(BI.Def, Stop);
765 continue;
766 }
767
768
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000769 if (!BI.Uses) {
770 // No uses in block, avoid interference by reloading as late as possible.
771 DEBUG(dbgs() << ", no uses.\n");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000772 SlotIndex SegStart = SE.enterIntvAtEnd(*BI.MBB);
773 assert(SegStart >= IP.second && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000774 continue;
775 }
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000776
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000777 if (IP.second.getBoundaryIndex() < BI.LastUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000778 // There are interference-free uses at the end of the block.
779 // Find the first use that can get the live-out register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000780 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000781 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
782 IP.second.getBoundaryIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000783 assert(UI != SA->UseSlots.end() && "Couldn't find last use");
784 SlotIndex Use = *UI;
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000785 assert(Use <= BI.LastUse && "Couldn't find last use");
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000786 // Only attempt a split befroe the last split point.
787 if (Use.getBaseIndex() <= BI.LastSplitPoint) {
788 DEBUG(dbgs() << ", free use at " << Use << ".\n");
789 SlotIndex SegStart = SE.enterIntvBefore(Use);
790 assert(SegStart >= IP.second && "Couldn't avoid interference");
791 assert(SegStart < BI.LastSplitPoint && "Impossible split point");
792 SE.useIntv(SegStart, Stop);
793 continue;
794 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000795 }
796
797 // Interference is after the last use.
798 DEBUG(dbgs() << " after last use.\n");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000799 SlotIndex SegStart = SE.enterIntvAtEnd(*BI.MBB);
800 assert(SegStart >= IP.second && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000801 }
802
803 // Now all defs leading to live bundles are handled, do everything else.
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000804 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
805 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000806 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
807 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
808
809 // Is the register live-in?
810 if (!BI.LiveIn || !RegIn)
811 continue;
812
813 // We have an incoming register. Check for interference.
814 IndexPair &IP = InterferenceRanges[i];
815 SlotIndex Start, Stop;
816 tie(Start, Stop) = Indexes->getMBBRange(BI.MBB);
817
818 DEBUG(dbgs() << "EB#" << Bundles->getBundle(BI.MBB->getNumber(), 0)
819 << " -> BB#" << BI.MBB->getNumber());
820
821 // Check interference entering the block.
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000822 if (!IP.first.isValid()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000823 // Block is interference-free.
824 DEBUG(dbgs() << ", no interference");
825 if (!BI.Uses) {
826 assert(BI.LiveThrough && "No uses, but not live through block?");
827 // Block is live-through without interference.
828 if (RegOut) {
829 DEBUG(dbgs() << ", no uses, live-through.\n");
830 SE.useIntv(Start, Stop);
831 } else {
832 DEBUG(dbgs() << ", no uses, stack-out.\n");
833 SE.leaveIntvAtTop(*BI.MBB);
834 }
835 continue;
836 }
837 if (!BI.LiveThrough) {
838 DEBUG(dbgs() << ", killed in block.\n");
Jakob Stoklund Olesen207c8682011-02-03 17:04:16 +0000839 SE.useIntv(Start, SE.leaveIntvAfter(BI.Kill));
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000840 continue;
841 }
842 if (!RegOut) {
843 // Block is live-through, but exit bundle is on the stack.
844 // Spill immediately after the last use.
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000845 if (BI.LastUse < BI.LastSplitPoint) {
846 DEBUG(dbgs() << ", uses, stack-out.\n");
847 SE.useIntv(Start, SE.leaveIntvAfter(BI.LastUse));
848 continue;
849 }
850 // The last use is after the last split point, it is probably an
851 // indirect jump.
852 DEBUG(dbgs() << ", uses at " << BI.LastUse << " after split point "
853 << BI.LastSplitPoint << ", stack-out.\n");
Jakob Stoklund Olesen23cd57c2011-02-09 23:33:02 +0000854 SlotIndex SegEnd = SE.leaveIntvBefore(BI.LastSplitPoint);
855 SE.useIntv(Start, SegEnd);
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000856 // Run a double interval from the split to the last use.
857 // This makes it possible to spill the complement without affecting the
858 // indirect branch.
859 SE.overlapIntv(SegEnd, BI.LastUse);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000860 continue;
861 }
862 // Register is live-through.
863 DEBUG(dbgs() << ", uses, live-through.\n");
864 SE.useIntv(Start, Stop);
865 continue;
866 }
867
868 // Block has interference.
869 DEBUG(dbgs() << ", interference from " << IP.first);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000870
871 if (!BI.LiveThrough && IP.first >= BI.Kill) {
872 // The interference doesn't reach the outgoing segment.
873 DEBUG(dbgs() << " doesn't affect kill at " << BI.Kill << '\n');
874 SE.useIntv(Start, BI.Kill);
875 continue;
876 }
877
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000878 if (!BI.Uses) {
879 // No uses in block, avoid interference by spilling as soon as possible.
880 DEBUG(dbgs() << ", no uses.\n");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000881 SlotIndex SegEnd = SE.leaveIntvAtTop(*BI.MBB);
882 assert(SegEnd <= IP.first && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000883 continue;
884 }
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000885 if (IP.first.getBaseIndex() > BI.FirstUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000886 // There are interference-free uses at the beginning of the block.
887 // Find the last use that can get the register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000888 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000889 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
890 IP.first.getBaseIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000891 assert(UI != SA->UseSlots.begin() && "Couldn't find first use");
892 SlotIndex Use = (--UI)->getBoundaryIndex();
893 DEBUG(dbgs() << ", free use at " << *UI << ".\n");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000894 SlotIndex SegEnd = SE.leaveIntvAfter(Use);
895 assert(SegEnd <= IP.first && "Couldn't avoid interference");
896 SE.useIntv(Start, SegEnd);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000897 continue;
898 }
899
900 // Interference is before the first use.
901 DEBUG(dbgs() << " before first use.\n");
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000902 SlotIndex SegEnd = SE.leaveIntvAtTop(*BI.MBB);
903 assert(SegEnd <= IP.first && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000904 }
905
906 SE.closeIntv();
907
908 // FIXME: Should we be more aggressive about splitting the stack region into
909 // per-block segments? The current approach allows the stack region to
910 // separate into connected components. Some components may be allocatable.
911 SE.finish();
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000912 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000913
Jakob Stoklund Olesen9b3d24b2011-02-04 19:33:07 +0000914 if (VerifyEnabled) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000915 MF->verify(this, "After splitting live range around region");
Jakob Stoklund Olesen9b3d24b2011-02-04 19:33:07 +0000916
917#ifndef NDEBUG
918 // Make sure that at least one of the new intervals can allocate to PhysReg.
919 // That was the whole point of splitting the live range.
920 bool found = false;
921 for (LiveRangeEdit::iterator I = LREdit.begin(), E = LREdit.end(); I != E;
922 ++I)
923 if (!checkUncachedInterference(**I, PhysReg)) {
924 found = true;
925 break;
926 }
927 assert(found && "No allocatable intervals after pointless splitting");
928#endif
929 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000930}
931
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000932unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
933 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000934 BitVector LiveBundles, BestBundles;
935 float BestCost = 0;
936 unsigned BestReg = 0;
937 Order.rewind();
938 while (unsigned PhysReg = Order.next()) {
939 float Cost = calcInterferenceInfo(VirtReg, PhysReg);
940 if (BestReg && Cost >= BestCost)
941 continue;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000942
943 SpillPlacer->placeSpills(SpillConstraints, LiveBundles);
944 // No live bundles, defer to splitSingleBlocks().
945 if (!LiveBundles.any())
946 continue;
947
948 Cost += calcGlobalSplitCost(LiveBundles);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000949 if (!BestReg || Cost < BestCost) {
950 BestReg = PhysReg;
951 BestCost = Cost;
952 BestBundles.swap(LiveBundles);
953 }
954 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000955
956 if (!BestReg)
957 return 0;
958
959 splitAroundRegion(VirtReg, BestReg, BestBundles, NewVRegs);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000960 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Region);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000961 return 0;
962}
963
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000964
965//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000966// Local Splitting
967//===----------------------------------------------------------------------===//
968
969
970/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
971/// in order to use PhysReg between two entries in SA->UseSlots.
972///
973/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
974///
975void RAGreedy::calcGapWeights(unsigned PhysReg,
976 SmallVectorImpl<float> &GapWeight) {
977 assert(SA->LiveBlocks.size() == 1 && "Not a local interval");
978 const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks.front();
979 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
980 const unsigned NumGaps = Uses.size()-1;
981
982 // Start and end points for the interference check.
983 SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
984 SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
985
986 GapWeight.assign(NumGaps, 0.0f);
987
988 // Add interference from each overlapping register.
989 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
990 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
991 .checkInterference())
992 continue;
993
994 // We know that VirtReg is a continuous interval from FirstUse to LastUse,
995 // so we don't need InterferenceQuery.
996 //
997 // Interference that overlaps an instruction is counted in both gaps
998 // surrounding the instruction. The exception is interference before
999 // StartIdx and after StopIdx.
1000 //
1001 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
1002 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1003 // Skip the gaps before IntI.
1004 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1005 if (++Gap == NumGaps)
1006 break;
1007 if (Gap == NumGaps)
1008 break;
1009
1010 // Update the gaps covered by IntI.
1011 const float weight = IntI.value()->weight;
1012 for (; Gap != NumGaps; ++Gap) {
1013 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1014 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1015 break;
1016 }
1017 if (Gap == NumGaps)
1018 break;
1019 }
1020 }
1021}
1022
1023/// getPrevMappedIndex - Return the slot index of the last non-copy instruction
1024/// before MI that has a slot index. If MI is the first mapped instruction in
1025/// its block, return the block start index instead.
1026///
1027SlotIndex RAGreedy::getPrevMappedIndex(const MachineInstr *MI) {
1028 assert(MI && "Missing MachineInstr");
1029 const MachineBasicBlock *MBB = MI->getParent();
1030 MachineBasicBlock::const_iterator B = MBB->begin(), I = MI;
1031 while (I != B)
1032 if (!(--I)->isDebugValue() && !I->isCopy())
1033 return Indexes->getInstructionIndex(I);
1034 return Indexes->getMBBStartIdx(MBB);
1035}
1036
1037/// calcPrevSlots - Fill in the PrevSlot array with the index of the previous
1038/// real non-copy instruction for each instruction in SA->UseSlots.
1039///
1040void RAGreedy::calcPrevSlots() {
1041 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1042 PrevSlot.clear();
1043 PrevSlot.reserve(Uses.size());
1044 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
1045 const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]);
1046 PrevSlot.push_back(getPrevMappedIndex(MI).getDefIndex());
1047 }
1048}
1049
1050/// nextSplitPoint - Find the next index into SA->UseSlots > i such that it may
1051/// be beneficial to split before UseSlots[i].
1052///
1053/// 0 is always a valid split point
1054unsigned RAGreedy::nextSplitPoint(unsigned i) {
1055 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1056 const unsigned Size = Uses.size();
1057 assert(i != Size && "No split points after the end");
1058 // Allow split before i when Uses[i] is not adjacent to the previous use.
1059 while (++i != Size && PrevSlot[i].getBaseIndex() <= Uses[i-1].getBaseIndex())
1060 ;
1061 return i;
1062}
1063
1064/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1065/// basic block.
1066///
1067unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1068 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1069 assert(SA->LiveBlocks.size() == 1 && "Not a local interval");
1070 const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks.front();
1071
1072 // Note that it is possible to have an interval that is live-in or live-out
1073 // while only covering a single block - A phi-def can use undef values from
1074 // predecessors, and the block could be a single-block loop.
1075 // We don't bother doing anything clever about such a case, we simply assume
1076 // that the interval is continuous from FirstUse to LastUse. We should make
1077 // sure that we don't do anything illegal to such an interval, though.
1078
1079 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1080 if (Uses.size() <= 2)
1081 return 0;
1082 const unsigned NumGaps = Uses.size()-1;
1083
1084 DEBUG({
1085 dbgs() << "tryLocalSplit: ";
1086 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1087 dbgs() << ' ' << SA->UseSlots[i];
1088 dbgs() << '\n';
1089 });
1090
1091 // For every use, find the previous mapped non-copy instruction.
1092 // We use this to detect valid split points, and to estimate new interval
1093 // sizes.
1094 calcPrevSlots();
1095
1096 unsigned BestBefore = NumGaps;
1097 unsigned BestAfter = 0;
1098 float BestDiff = 0;
1099
1100 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB);
1101 SmallVector<float, 8> GapWeight;
1102
1103 Order.rewind();
1104 while (unsigned PhysReg = Order.next()) {
1105 // Keep track of the largest spill weight that would need to be evicted in
1106 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1107 calcGapWeights(PhysReg, GapWeight);
1108
1109 // Try to find the best sequence of gaps to close.
1110 // The new spill weight must be larger than any gap interference.
1111
1112 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1113 unsigned SplitBefore = 0, SplitAfter = nextSplitPoint(1) - 1;
1114
1115 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1116 // It is the spill weight that needs to be evicted.
1117 float MaxGap = GapWeight[0];
1118 for (unsigned i = 1; i != SplitAfter; ++i)
1119 MaxGap = std::max(MaxGap, GapWeight[i]);
1120
1121 for (;;) {
1122 // Live before/after split?
1123 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1124 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1125
1126 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1127 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1128 << " i=" << MaxGap);
1129
1130 // Stop before the interval gets so big we wouldn't be making progress.
1131 if (!LiveBefore && !LiveAfter) {
1132 DEBUG(dbgs() << " all\n");
1133 break;
1134 }
1135 // Should the interval be extended or shrunk?
1136 bool Shrink = true;
1137 if (MaxGap < HUGE_VALF) {
1138 // Estimate the new spill weight.
1139 //
1140 // Each instruction reads and writes the register, except the first
1141 // instr doesn't read when !FirstLive, and the last instr doesn't write
1142 // when !LastLive.
1143 //
1144 // We will be inserting copies before and after, so the total number of
1145 // reads and writes is 2 * EstUses.
1146 //
1147 const unsigned EstUses = 2*(SplitAfter - SplitBefore) +
1148 2*(LiveBefore + LiveAfter);
1149
1150 // Try to guess the size of the new interval. This should be trivial,
1151 // but the slot index of an inserted copy can be a lot smaller than the
1152 // instruction it is inserted before if there are many dead indexes
1153 // between them.
1154 //
1155 // We measure the distance from the instruction before SplitBefore to
1156 // get a conservative estimate.
1157 //
1158 // The final distance can still be different if inserting copies
1159 // triggers a slot index renumbering.
1160 //
1161 const float EstWeight = normalizeSpillWeight(blockFreq * EstUses,
1162 PrevSlot[SplitBefore].distance(Uses[SplitAfter]));
1163 // Would this split be possible to allocate?
1164 // Never allocate all gaps, we wouldn't be making progress.
1165 float Diff = EstWeight - MaxGap;
1166 DEBUG(dbgs() << " w=" << EstWeight << " d=" << Diff);
1167 if (Diff > 0) {
1168 Shrink = false;
1169 if (Diff > BestDiff) {
1170 DEBUG(dbgs() << " (best)");
1171 BestDiff = Diff;
1172 BestBefore = SplitBefore;
1173 BestAfter = SplitAfter;
1174 }
1175 }
1176 }
1177
1178 // Try to shrink.
1179 if (Shrink) {
1180 SplitBefore = nextSplitPoint(SplitBefore);
1181 if (SplitBefore < SplitAfter) {
1182 DEBUG(dbgs() << " shrink\n");
1183 // Recompute the max when necessary.
1184 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1185 MaxGap = GapWeight[SplitBefore];
1186 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1187 MaxGap = std::max(MaxGap, GapWeight[i]);
1188 }
1189 continue;
1190 }
1191 MaxGap = 0;
1192 }
1193
1194 // Try to extend the interval.
1195 if (SplitAfter >= NumGaps) {
1196 DEBUG(dbgs() << " end\n");
1197 break;
1198 }
1199
1200 DEBUG(dbgs() << " extend\n");
1201 for (unsigned e = nextSplitPoint(SplitAfter + 1) - 1;
1202 SplitAfter != e; ++SplitAfter)
1203 MaxGap = std::max(MaxGap, GapWeight[SplitAfter]);
1204 continue;
1205 }
1206 }
1207
1208 // Didn't find any candidates?
1209 if (BestBefore == NumGaps)
1210 return 0;
1211
1212 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1213 << '-' << Uses[BestAfter] << ", " << BestDiff
1214 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1215
1216 SmallVector<LiveInterval*, 4> SpillRegs;
1217 LiveRangeEdit LREdit(VirtReg, NewVRegs, SpillRegs);
1218 SplitEditor SE(*SA, *LIS, *VRM, *DomTree, LREdit);
1219
1220 SE.openIntv();
1221 SlotIndex SegStart = SE.enterIntvBefore(Uses[BestBefore]);
1222 SlotIndex SegStop = SE.leaveIntvAfter(Uses[BestAfter]);
1223 SE.useIntv(SegStart, SegStop);
1224 SE.closeIntv();
1225 SE.finish();
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001226 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Local);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001227 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001228
1229 return 0;
1230}
1231
1232//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001233// Live Range Splitting
1234//===----------------------------------------------------------------------===//
1235
1236/// trySplit - Try to split VirtReg or one of its interferences, making it
1237/// assignable.
1238/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1239unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1240 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001241 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001242 if (LIS->intervalIsInOneMBB(VirtReg)) {
1243 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001244 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001245 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001246 }
1247
1248 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001249
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001250 // Don't iterate global splitting.
1251 // Move straight to spilling if this range was produced by a global split.
1252 LiveRangeStage Stage = getStage(VirtReg);
1253 if (Stage >= RS_Block)
1254 return 0;
1255
1256 SA->analyze(&VirtReg);
1257
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001258 // First try to split around a region spanning multiple blocks.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001259 if (Stage < RS_Region) {
1260 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1261 if (PhysReg || !NewVRegs.empty())
1262 return PhysReg;
1263 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001264
1265 // Then isolate blocks with multiple uses.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001266 if (Stage < RS_Block) {
1267 SplitAnalysis::BlockPtrSet Blocks;
1268 if (SA->getMultiUseBlocks(Blocks)) {
1269 SmallVector<LiveInterval*, 4> SpillRegs;
1270 LiveRangeEdit LREdit(VirtReg, NewVRegs, SpillRegs);
1271 SplitEditor(*SA, *LIS, *VRM, *DomTree, LREdit).splitSingleBlocks(Blocks);
1272 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Block);
1273 if (VerifyEnabled)
1274 MF->verify(this, "After splitting live range around basic blocks");
1275 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001276 }
1277
1278 // Don't assign any physregs.
1279 return 0;
1280}
1281
1282
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001283//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001284// Main Entry Point
1285//===----------------------------------------------------------------------===//
1286
1287unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001288 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001289 LiveRangeStage Stage = getStage(VirtReg);
1290 if (Stage == RS_Original)
1291 LRStage[VirtReg.reg] = RS_Second;
1292
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001293 // First try assigning a free register.
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +00001294 AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
1295 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001296 if (!checkPhysRegInterference(VirtReg, PhysReg))
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001297 return PhysReg;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001298 }
Andrew Trickb853e6c2010-12-09 18:15:21 +00001299
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +00001300 if (unsigned PhysReg = tryReassign(VirtReg, Order, NewVRegs))
1301 return PhysReg;
1302
1303 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001304 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001305
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001306 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1307
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001308 // The first time we see a live range, don't try to split or spill.
1309 // Wait until the second time, when all smaller ranges have been allocated.
1310 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001311 if (Stage == RS_Original) {
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001312 NewVRegs.push_back(&VirtReg);
1313 return 0;
1314 }
1315
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001316 assert(Stage < RS_Spill && "Cannot allocate after spilling");
1317
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001318 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001319 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1320 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001321 return PhysReg;
1322
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001323 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001324 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001325 SmallVector<LiveInterval*, 1> pendingSpills;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001326 spiller().spill(&VirtReg, NewVRegs, pendingSpills);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001327
1328 // The live virtual register requesting allocation was spilled, so tell
1329 // the caller not to allocate anything during this round.
1330 return 0;
1331}
1332
1333bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1334 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1335 << "********** Function: "
1336 << ((Value*)mf.getFunction())->getName() << '\n');
1337
1338 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001339 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001340 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001341
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001342 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001343 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001344 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001345 ReservedRegs = TRI->getReservedRegs(*MF);
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001346 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001347 Loops = &getAnalysis<MachineLoopInfo>();
1348 LoopRanges = &getAnalysis<MachineLoopRanges>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001349 Bundles = &getAnalysis<EdgeBundles>();
1350 SpillPlacer = &getAnalysis<SpillPlacement>();
1351
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001352 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001353 LRStage.clear();
1354 LRStage.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001355
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001356 allocatePhysRegs();
1357 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001358 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001359
1360 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001361 {
1362 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001363 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001364 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001365
1366 // The pass output is in VirtRegMap. Release all the transient data.
1367 releaseMemory();
1368
1369 return true;
1370}