blob: c1d8272dc509cbed54af80a40ceed9cfeaf0f702 [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 {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +000059class RAGreedy : public MachineFunctionPass,
60 public RegAllocBase,
61 private LiveRangeEdit::Delegate {
62
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000063 // context
64 MachineFunction *MF;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000065 BitVector ReservedRegs;
66
67 // analyses
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000068 SlotIndexes *Indexes;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000069 LiveStacks *LS;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000070 MachineDominatorTree *DomTree;
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +000071 MachineLoopInfo *Loops;
72 MachineLoopRanges *LoopRanges;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +000073 EdgeBundles *Bundles;
74 SpillPlacement *SpillPlacer;
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +000075
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +000076 // state
77 std::auto_ptr<Spiller> SpillerInstance;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +000078 std::priority_queue<std::pair<unsigned, unsigned> > Queue;
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +000079
80 // Live ranges pass through a number of stages as we try to allocate them.
81 // Some of the stages may also create new live ranges:
82 //
83 // - Region splitting.
84 // - Per-block splitting.
85 // - Local splitting.
86 // - Spilling.
87 //
88 // Ranges produced by one of the stages skip the previous stages when they are
89 // dequeued. This improves performance because we can skip interference checks
90 // that are unlikely to give any results. It also guarantees that the live
91 // range splitting algorithm terminates, something that is otherwise hard to
92 // ensure.
93 enum LiveRangeStage {
94 RS_Original, ///< Never seen before, never split.
95 RS_Second, ///< Second time in the queue.
96 RS_Region, ///< Produced by region splitting.
97 RS_Block, ///< Produced by per-block splitting.
98 RS_Local, ///< Produced by local splitting.
99 RS_Spill ///< Produced by spilling.
100 };
101
102 IndexedMap<unsigned char, VirtReg2IndexFunctor> LRStage;
103
104 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
105 return LiveRangeStage(LRStage[VirtReg.reg]);
106 }
107
108 template<typename Iterator>
109 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
110 LRStage.resize(MRI->getNumVirtRegs());
111 for (;Begin != End; ++Begin)
112 LRStage[(*Begin)->reg] = NewStage;
113 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000114
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000115 // splitting state.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000116 std::auto_ptr<SplitAnalysis> SA;
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000117 std::auto_ptr<SplitEditor> SE;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000118
119 /// All basic blocks where the current register is live.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000120 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000121
Jakob Stoklund Olesen8b6a9332011-03-04 22:11:11 +0000122 typedef std::pair<SlotIndex, SlotIndex> IndexPair;
123
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000124 /// Global live range splitting candidate info.
125 struct GlobalSplitCandidate {
126 unsigned PhysReg;
127 SmallVector<IndexPair, 8> Interference;
128 BitVector LiveBundles;
129 };
130
131 /// Candidate info for for each PhysReg in AllocationOrder.
132 /// This vector never shrinks, but grows to the size of the largest register
133 /// class.
134 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
135
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000136 /// For every instruction in SA->UseSlots, store the previous non-copy
137 /// instruction.
138 SmallVector<SlotIndex, 8> PrevSlot;
139
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000140public:
141 RAGreedy();
142
143 /// Return the pass name.
144 virtual const char* getPassName() const {
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +0000145 return "Greedy Register Allocator";
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000146 }
147
148 /// RAGreedy analysis usage.
149 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000150 virtual void releaseMemory();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000151 virtual Spiller &spiller() { return *SpillerInstance; }
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000152 virtual void enqueue(LiveInterval *LI);
153 virtual LiveInterval *dequeue();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000154 virtual unsigned selectOrSplit(LiveInterval&,
155 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000156
157 /// Perform register allocation.
158 virtual bool runOnMachineFunction(MachineFunction &mf);
159
160 static char ID;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000161
162private:
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000163 void LRE_WillEraseInstruction(MachineInstr*);
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000164 bool LRE_CanEraseVirtReg(unsigned);
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000165 void LRE_WillShrinkVirtReg(unsigned);
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000166
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000167 bool checkUncachedInterference(LiveInterval&, unsigned);
168 LiveInterval *getSingleInterference(LiveInterval&, unsigned);
Andrew Trickb853e6c2010-12-09 18:15:21 +0000169 bool reassignVReg(LiveInterval &InterferingVReg, unsigned OldPhysReg);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000170
Jakob Stoklund Olesen8b6a9332011-03-04 22:11:11 +0000171 void mapGlobalInterference(unsigned, SmallVectorImpl<IndexPair>&);
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000172 float calcSplitConstraints(const SmallVectorImpl<IndexPair>&);
173
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000174 float calcGlobalSplitCost(const BitVector&);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000175 void splitAroundRegion(LiveInterval&, unsigned, const BitVector&,
176 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000177 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
178 SlotIndex getPrevMappedIndex(const MachineInstr*);
179 void calcPrevSlots();
180 unsigned nextSplitPoint(unsigned);
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000181 bool canEvictInterference(LiveInterval&, unsigned, float&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000182
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000183 unsigned tryReassign(LiveInterval&, AllocationOrder&,
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000184 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000185 unsigned tryEvict(LiveInterval&, AllocationOrder&,
186 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000187 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
188 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000189 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
190 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +0000191 unsigned trySplit(LiveInterval&, AllocationOrder&,
192 SmallVectorImpl<LiveInterval*>&);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000193};
194} // end anonymous namespace
195
196char RAGreedy::ID = 0;
197
198FunctionPass* llvm::createGreedyRegisterAllocator() {
199 return new RAGreedy();
200}
201
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000202RAGreedy::RAGreedy(): MachineFunctionPass(ID), LRStage(RS_Original) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000203 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000204 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
205 initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
206 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
207 initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
208 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
209 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
210 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
211 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000212 initializeMachineLoopRangesPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000213 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000214 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
215 initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000216}
217
218void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
219 AU.setPreservesCFG();
220 AU.addRequired<AliasAnalysis>();
221 AU.addPreserved<AliasAnalysis>();
222 AU.addRequired<LiveIntervals>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000223 AU.addRequired<SlotIndexes>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000224 AU.addPreserved<SlotIndexes>();
225 if (StrongPHIElim)
226 AU.addRequiredID(StrongPHIEliminationID);
227 AU.addRequiredTransitive<RegisterCoalescer>();
228 AU.addRequired<CalculateSpillWeights>();
229 AU.addRequired<LiveStacks>();
230 AU.addPreserved<LiveStacks>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +0000231 AU.addRequired<MachineDominatorTree>();
232 AU.addPreserved<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000233 AU.addRequired<MachineLoopInfo>();
234 AU.addPreserved<MachineLoopInfo>();
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +0000235 AU.addRequired<MachineLoopRanges>();
236 AU.addPreserved<MachineLoopRanges>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000237 AU.addRequired<VirtRegMap>();
238 AU.addPreserved<VirtRegMap>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000239 AU.addRequired<EdgeBundles>();
240 AU.addRequired<SpillPlacement>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000241 MachineFunctionPass::getAnalysisUsage(AU);
242}
243
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000244
245//===----------------------------------------------------------------------===//
246// LiveRangeEdit delegate methods
247//===----------------------------------------------------------------------===//
248
249void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
250 // LRE itself will remove from SlotIndexes and parent basic block.
251 VRM->RemoveMachineInstrFromMaps(MI);
252}
253
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000254bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
255 if (unsigned PhysReg = VRM->getPhys(VirtReg)) {
256 unassign(LIS->getInterval(VirtReg), PhysReg);
257 return true;
258 }
259 // Unassigned virtreg is probably in the priority queue.
260 // RegAllocBase will erase it after dequeueing.
261 return false;
262}
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000263
Jakob Stoklund Olesen1d5b8452011-03-16 22:56:16 +0000264void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
265 unsigned PhysReg = VRM->getPhys(VirtReg);
266 if (!PhysReg)
267 return;
268
269 // Register is assigned, put it back on the queue for reassignment.
270 LiveInterval &LI = LIS->getInterval(VirtReg);
271 unassign(LI, PhysReg);
272 enqueue(&LI);
273}
274
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000275void RAGreedy::releaseMemory() {
276 SpillerInstance.reset(0);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000277 LRStage.clear();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +0000278 RegAllocBase::releaseMemory();
279}
280
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000281void RAGreedy::enqueue(LiveInterval *LI) {
282 // Prioritize live ranges by size, assigning larger ranges first.
283 // The queue holds (size, reg) pairs.
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000284 const unsigned Size = LI->getSize();
285 const unsigned Reg = LI->reg;
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000286 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
287 "Can only enqueue virtual registers");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000288 unsigned Prio;
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000289
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000290 LRStage.grow(Reg);
291 if (LRStage[Reg] == RS_Original)
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000292 // 1st generation ranges are handled first, long -> short.
293 Prio = (1u << 31) + Size;
294 else
295 // Repeat offenders are handled second, short -> long
296 Prio = (1u << 30) - Size;
Jakob Stoklund Olesend2a50732011-02-23 00:56:56 +0000297
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000298 // Boost ranges that have a physical register hint.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000299 const unsigned Hint = VRM->getRegAllocPref(Reg);
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +0000300 if (TargetRegisterInfo::isPhysicalRegister(Hint))
301 Prio |= (1u << 30);
302
303 Queue.push(std::make_pair(Prio, Reg));
Jakob Stoklund Olesen90c1d7d2010-12-08 22:57:16 +0000304}
305
Jakob Stoklund Olesen98d96482011-02-22 23:01:52 +0000306LiveInterval *RAGreedy::dequeue() {
307 if (Queue.empty())
308 return 0;
309 LiveInterval *LI = &LIS->getInterval(Queue.top().second);
310 Queue.pop();
311 return LI;
312}
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000313
314//===----------------------------------------------------------------------===//
315// Register Reassignment
316//===----------------------------------------------------------------------===//
317
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000318// Check interference without using the cache.
319bool RAGreedy::checkUncachedInterference(LiveInterval &VirtReg,
320 unsigned PhysReg) {
Jakob Stoklund Olesen257c5562010-12-14 23:38:19 +0000321 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
322 LiveIntervalUnion::Query subQ(&VirtReg, &PhysReg2LiveUnion[*AliasI]);
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000323 if (subQ.checkInterference())
324 return true;
325 }
326 return false;
327}
328
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000329/// getSingleInterference - Return the single interfering virtual register
330/// assigned to PhysReg. Return 0 if more than one virtual register is
331/// interfering.
332LiveInterval *RAGreedy::getSingleInterference(LiveInterval &VirtReg,
333 unsigned PhysReg) {
Jakob Stoklund Olesen257c5562010-12-14 23:38:19 +0000334 // Check physreg and aliases.
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000335 LiveInterval *Interference = 0;
Jakob Stoklund Olesen257c5562010-12-14 23:38:19 +0000336 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000337 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
338 if (Q.checkInterference()) {
Jakob Stoklund Olesend84de8c2010-12-14 17:47:36 +0000339 if (Interference)
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000340 return 0;
Jakob Stoklund Olesen417df012011-02-23 00:29:55 +0000341 if (Q.collectInterferingVRegs(2) > 1)
Jakob Stoklund Olesend84de8c2010-12-14 17:47:36 +0000342 return 0;
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000343 Interference = Q.interferingVRegs().front();
344 }
345 }
346 return Interference;
347}
348
Andrew Trickb853e6c2010-12-09 18:15:21 +0000349// Attempt to reassign this virtual register to a different physical register.
350//
351// FIXME: we are not yet caching these "second-level" interferences discovered
352// in the sub-queries. These interferences can change with each call to
353// selectOrSplit. However, we could implement a "may-interfere" cache that
354// could be conservatively dirtied when we reassign or split.
355//
356// FIXME: This may result in a lot of alias queries. We could summarize alias
357// live intervals in their parent register's live union, but it's messy.
358bool RAGreedy::reassignVReg(LiveInterval &InterferingVReg,
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000359 unsigned WantedPhysReg) {
360 assert(TargetRegisterInfo::isVirtualRegister(InterferingVReg.reg) &&
361 "Can only reassign virtual registers");
362 assert(TRI->regsOverlap(WantedPhysReg, VRM->getPhys(InterferingVReg.reg)) &&
Andrew Trickb853e6c2010-12-09 18:15:21 +0000363 "inconsistent phys reg assigment");
364
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +0000365 AllocationOrder Order(InterferingVReg.reg, *VRM, ReservedRegs);
366 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000367 // Don't reassign to a WantedPhysReg alias.
368 if (TRI->regsOverlap(PhysReg, WantedPhysReg))
Andrew Trickb853e6c2010-12-09 18:15:21 +0000369 continue;
370
Jakob Stoklund Olesen6ce219e2010-12-10 20:45:04 +0000371 if (checkUncachedInterference(InterferingVReg, PhysReg))
Andrew Trickb853e6c2010-12-09 18:15:21 +0000372 continue;
373
Andrew Trickb853e6c2010-12-09 18:15:21 +0000374 // Reassign the interfering virtual reg to this physical reg.
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000375 unsigned OldAssign = VRM->getPhys(InterferingVReg.reg);
376 DEBUG(dbgs() << "reassigning: " << InterferingVReg << " from " <<
377 TRI->getName(OldAssign) << " to " << TRI->getName(PhysReg) << '\n');
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000378 unassign(InterferingVReg, OldAssign);
379 assign(InterferingVReg, PhysReg);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000380 ++NumReassigned;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000381 return true;
382 }
383 return false;
384}
385
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000386/// tryReassign - Try to reassign a single interference to a different physreg.
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000387/// @param VirtReg Currently unassigned virtual register.
388/// @param Order Physregs to try.
389/// @return Physreg to assign VirtReg, or 0.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000390unsigned RAGreedy::tryReassign(LiveInterval &VirtReg, AllocationOrder &Order,
391 SmallVectorImpl<LiveInterval*> &NewVRegs){
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000392 NamedRegionTimer T("Reassign", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000393
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000394 Order.rewind();
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000395 while (unsigned PhysReg = Order.next()) {
396 LiveInterval *InterferingVReg = getSingleInterference(VirtReg, PhysReg);
397 if (!InterferingVReg)
398 continue;
399 if (TargetRegisterInfo::isPhysicalRegister(InterferingVReg->reg))
400 continue;
401 if (reassignVReg(*InterferingVReg, PhysReg))
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +0000402 return PhysReg;
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000403 }
404 return 0;
405}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000406
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000407
408//===----------------------------------------------------------------------===//
409// Interference eviction
410//===----------------------------------------------------------------------===//
411
412/// canEvict - Return true if all interferences between VirtReg and PhysReg can
413/// be evicted. Set maxWeight to the maximal spill weight of an interference.
414bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000415 float &MaxWeight) {
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000416 float Weight = 0;
417 for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
418 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
419 // If there is 10 or more interferences, chances are one is smaller.
420 if (Q.collectInterferingVRegs(10) >= 10)
421 return false;
422
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000423 // Check if any interfering live range is heavier than VirtReg.
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000424 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
425 LiveInterval *Intf = Q.interferingVRegs()[i];
426 if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
427 return false;
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000428 if (Intf->weight >= VirtReg.weight)
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000429 return false;
430 Weight = std::max(Weight, Intf->weight);
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000431 }
432 }
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000433 MaxWeight = Weight;
434 return true;
435}
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000436
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000437/// tryEvict - Try to evict all interferences for a physreg.
438/// @param VirtReg Currently unassigned virtual register.
439/// @param Order Physregs to try.
440/// @return Physreg to assign VirtReg, or 0.
441unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
442 AllocationOrder &Order,
443 SmallVectorImpl<LiveInterval*> &NewVRegs){
444 NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
445
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000446 // Keep track of the lightest single interference seen so far.
447 float BestWeight = 0;
448 unsigned BestPhys = 0;
449
450 Order.rewind();
451 while (unsigned PhysReg = Order.next()) {
452 float Weight = 0;
Jakob Stoklund Olesend17924b2011-03-04 21:32:50 +0000453 if (!canEvictInterference(VirtReg, PhysReg, Weight))
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000454 continue;
455
456 // This is an eviction candidate.
457 DEBUG(dbgs() << "max " << PrintReg(PhysReg, TRI) << " interference = "
458 << Weight << '\n');
459 if (BestPhys && Weight >= BestWeight)
460 continue;
461
462 // Best so far.
463 BestPhys = PhysReg;
464 BestWeight = Weight;
Jakob Stoklund Olesen57f1e2c2011-02-25 01:04:22 +0000465 // Stop if the hint can be used.
466 if (Order.isHint(PhysReg))
467 break;
Jakob Stoklund Olesen27106382011-02-09 01:14:03 +0000468 }
469
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +0000470 if (!BestPhys)
471 return 0;
472
473 DEBUG(dbgs() << "evicting " << PrintReg(BestPhys, TRI) << " interference\n");
474 for (const unsigned *AliasI = TRI->getOverlaps(BestPhys); *AliasI; ++AliasI) {
475 LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
476 assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
477 for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
478 LiveInterval *Intf = Q.interferingVRegs()[i];
479 unassign(*Intf, VRM->getPhys(Intf->reg));
480 ++NumEvicted;
481 NewVRegs.push_back(Intf);
482 }
483 }
484 return BestPhys;
Andrew Trickb853e6c2010-12-09 18:15:21 +0000485}
486
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +0000487
488//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000489// Region Splitting
490//===----------------------------------------------------------------------===//
491
Jakob Stoklund Olesen8b6a9332011-03-04 22:11:11 +0000492/// mapGlobalInterference - Compute a map of the interference from PhysReg and
493/// its aliases in each block in SA->LiveBlocks.
494/// If LiveBlocks[i] is live-in, Ranges[i].first is the first interference.
495/// If LiveBlocks[i] is live-out, Ranges[i].second is the last interference.
496void RAGreedy::mapGlobalInterference(unsigned PhysReg,
497 SmallVectorImpl<IndexPair> &Ranges) {
498 Ranges.assign(SA->LiveBlocks.size(), IndexPair());
499 LiveInterval &VirtReg = const_cast<LiveInterval&>(SA->getParent());
500 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
501 if (!query(VirtReg, *AI).checkInterference())
502 continue;
503 LiveIntervalUnion::SegmentIter IntI =
504 PhysReg2LiveUnion[*AI].find(VirtReg.beginIndex());
505 if (!IntI.valid())
506 continue;
507 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
508 const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
509 IndexPair &IP = Ranges[i];
510
511 // Skip interference-free blocks.
512 if (IntI.start() >= BI.Stop)
513 continue;
514
515 // First interference in block.
516 if (BI.LiveIn) {
517 IntI.advanceTo(BI.Start);
518 if (!IntI.valid())
519 break;
520 if (IntI.start() >= BI.Stop)
521 continue;
522 if (!IP.first.isValid() || IntI.start() < IP.first)
523 IP.first = IntI.start();
524 }
525
526 // Last interference in block.
527 if (BI.LiveOut) {
528 IntI.advanceTo(BI.Stop);
529 if (!IntI.valid() || IntI.start() >= BI.Stop)
530 --IntI;
531 if (IntI.stop() <= BI.Start)
532 continue;
533 if (!IP.second.isValid() || IntI.stop() > IP.second)
534 IP.second = IntI.stop();
535 }
536 }
537 }
538}
539
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000540/// calcSplitConstraints - Fill out the SplitConstraints vector based on the
541/// interference pattern in Intf. Return the static cost of this split,
542/// assuming that all preferences in SplitConstraints are met.
543float RAGreedy::calcSplitConstraints(const SmallVectorImpl<IndexPair> &Intf) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000544 // Reset interference dependent info.
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000545 SplitConstraints.resize(SA->LiveBlocks.size());
546 float StaticCost = 0;
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000547 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
548 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000549 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
550 IndexPair IP = Intf[i];
551
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000552 BC.Number = BI.MBB->getNumber();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000553 BC.Entry = (BI.Uses && BI.LiveIn) ?
554 SpillPlacement::PrefReg : SpillPlacement::DontCare;
555 BC.Exit = (BI.Uses && BI.LiveOut) ?
556 SpillPlacement::PrefReg : SpillPlacement::DontCare;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000557
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000558 // Number of spill code instructions to insert.
559 unsigned Ins = 0;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000560
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000561 // Interference for the live-in value.
562 if (IP.first.isValid()) {
563 if (IP.first <= BI.Start)
564 BC.Entry = SpillPlacement::MustSpill, Ins += BI.Uses;
565 else if (!BI.Uses)
566 BC.Entry = SpillPlacement::PrefSpill;
567 else if (IP.first < BI.FirstUse)
568 BC.Entry = SpillPlacement::PrefSpill, ++Ins;
569 else if (IP.first < (BI.LiveThrough ? BI.LastUse : BI.Kill))
570 ++Ins;
Jakob Stoklund Olesena50c5392011-02-08 23:02:58 +0000571 }
572
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000573 // Interference for the live-out value.
574 if (IP.second.isValid()) {
575 if (IP.second >= BI.LastSplitPoint)
576 BC.Exit = SpillPlacement::MustSpill, Ins += BI.Uses;
577 else if (!BI.Uses)
578 BC.Exit = SpillPlacement::PrefSpill;
579 else if (IP.second > BI.LastUse)
580 BC.Exit = SpillPlacement::PrefSpill, ++Ins;
581 else if (IP.second > (BI.LiveThrough ? BI.FirstUse : BI.Def))
582 ++Ins;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000583 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000584
585 // Accumulate the total frequency of inserted spill code.
586 if (Ins)
587 StaticCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000588 }
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000589 return StaticCost;
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000590}
591
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000592
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000593/// calcGlobalSplitCost - Return the global split cost of following the split
594/// pattern in LiveBundles. This cost should be added to the local cost of the
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000595/// interference pattern in SplitConstraints.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000596///
597float RAGreedy::calcGlobalSplitCost(const BitVector &LiveBundles) {
598 float GlobalCost = 0;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000599 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
600 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000601 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000602 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
603 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
604 unsigned Ins = 0;
605
606 if (!BI.Uses)
607 Ins += RegIn != RegOut;
608 else {
609 if (BI.LiveIn)
610 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
611 if (BI.LiveOut)
612 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
613 }
614 if (Ins)
615 GlobalCost += Ins * SpillPlacer->getBlockFrequency(BC.Number);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000616 }
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000617 return GlobalCost;
618}
619
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000620/// splitAroundRegion - Split VirtReg around the region determined by
621/// LiveBundles. Make an effort to avoid interference from PhysReg.
622///
623/// The 'register' interval is going to contain as many uses as possible while
624/// avoiding interference. The 'stack' interval is the complement constructed by
625/// SplitEditor. It will contain the rest.
626///
627void RAGreedy::splitAroundRegion(LiveInterval &VirtReg, unsigned PhysReg,
628 const BitVector &LiveBundles,
629 SmallVectorImpl<LiveInterval*> &NewVRegs) {
630 DEBUG({
631 dbgs() << "Splitting around region for " << PrintReg(PhysReg, TRI)
632 << " with bundles";
633 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
634 dbgs() << " EB#" << i;
635 dbgs() << ".\n";
636 });
637
638 // First compute interference ranges in the live blocks.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000639 SmallVector<IndexPair, 8> InterferenceRanges;
Jakob Stoklund Olesen8b6a9332011-03-04 22:11:11 +0000640 mapGlobalInterference(PhysReg, InterferenceRanges);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000641
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +0000642 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000643 SE->reset(LREdit);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000644
645 // Create the main cross-block interval.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000646 SE->openIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000647
648 // First add all defs that are live out of a block.
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000649 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
650 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000651 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
652 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
653
654 // Should the register be live out?
655 if (!BI.LiveOut || !RegOut)
656 continue;
657
658 IndexPair &IP = InterferenceRanges[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000659 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " -> EB#"
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000660 << Bundles->getBundle(BI.MBB->getNumber(), 1)
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +0000661 << " [" << BI.Start << ';' << BI.LastSplitPoint << '-'
662 << BI.Stop << ") intf [" << IP.first << ';' << IP.second
663 << ')');
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000664
665 // The interference interval should either be invalid or overlap MBB.
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000666 assert((!IP.first.isValid() || IP.first < BI.Stop) && "Bad interference");
667 assert((!IP.second.isValid() || IP.second > BI.Start)
668 && "Bad interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000669
670 // Check interference leaving the block.
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000671 if (!IP.second.isValid()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000672 // Block is interference-free.
673 DEBUG(dbgs() << ", no interference");
674 if (!BI.Uses) {
675 assert(BI.LiveThrough && "No uses, but not live through block?");
676 // Block is live-through without interference.
677 DEBUG(dbgs() << ", no uses"
678 << (RegIn ? ", live-through.\n" : ", stack in.\n"));
679 if (!RegIn)
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000680 SE->enterIntvAtEnd(*BI.MBB);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000681 continue;
682 }
683 if (!BI.LiveThrough) {
684 DEBUG(dbgs() << ", not live-through.\n");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000685 SE->useIntv(SE->enterIntvBefore(BI.Def), BI.Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000686 continue;
687 }
688 if (!RegIn) {
689 // Block is live-through, but entry bundle is on the stack.
690 // Reload just before the first use.
691 DEBUG(dbgs() << ", not live-in, enter before first use.\n");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000692 SE->useIntv(SE->enterIntvBefore(BI.FirstUse), BI.Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000693 continue;
694 }
695 DEBUG(dbgs() << ", live-through.\n");
696 continue;
697 }
698
699 // Block has interference.
700 DEBUG(dbgs() << ", interference to " << IP.second);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000701
702 if (!BI.LiveThrough && IP.second <= BI.Def) {
703 // The interference doesn't reach the outgoing segment.
704 DEBUG(dbgs() << " doesn't affect def from " << BI.Def << '\n');
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000705 SE->useIntv(BI.Def, BI.Stop);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000706 continue;
707 }
708
709
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000710 if (!BI.Uses) {
711 // No uses in block, avoid interference by reloading as late as possible.
712 DEBUG(dbgs() << ", no uses.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000713 SlotIndex SegStart = SE->enterIntvAtEnd(*BI.MBB);
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000714 assert(SegStart >= IP.second && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000715 continue;
716 }
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000717
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000718 if (IP.second.getBoundaryIndex() < BI.LastUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000719 // There are interference-free uses at the end of the block.
720 // Find the first use that can get the live-out register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000721 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000722 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
723 IP.second.getBoundaryIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000724 assert(UI != SA->UseSlots.end() && "Couldn't find last use");
725 SlotIndex Use = *UI;
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000726 assert(Use <= BI.LastUse && "Couldn't find last use");
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000727 // Only attempt a split befroe the last split point.
728 if (Use.getBaseIndex() <= BI.LastSplitPoint) {
729 DEBUG(dbgs() << ", free use at " << Use << ".\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000730 SlotIndex SegStart = SE->enterIntvBefore(Use);
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000731 assert(SegStart >= IP.second && "Couldn't avoid interference");
732 assert(SegStart < BI.LastSplitPoint && "Impossible split point");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000733 SE->useIntv(SegStart, BI.Stop);
Jakob Stoklund Olesen8a2bbde2011-02-08 23:26:48 +0000734 continue;
735 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000736 }
737
738 // Interference is after the last use.
739 DEBUG(dbgs() << " after last use.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000740 SlotIndex SegStart = SE->enterIntvAtEnd(*BI.MBB);
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000741 assert(SegStart >= IP.second && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000742 }
743
744 // Now all defs leading to live bundles are handled, do everything else.
Jakob Stoklund Olesenf0ac26c2011-02-09 22:50:26 +0000745 for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
746 SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000747 bool RegIn = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
748 bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
749
750 // Is the register live-in?
751 if (!BI.LiveIn || !RegIn)
752 continue;
753
754 // We have an incoming register. Check for interference.
755 IndexPair &IP = InterferenceRanges[i];
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000756
757 DEBUG(dbgs() << "EB#" << Bundles->getBundle(BI.MBB->getNumber(), 0)
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +0000758 << " -> BB#" << BI.MBB->getNumber() << " [" << BI.Start << ';'
759 << BI.LastSplitPoint << '-' << BI.Stop << ')');
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000760
761 // Check interference entering the block.
Jakob Stoklund Olesen2dfbb3e2011-02-03 20:29:43 +0000762 if (!IP.first.isValid()) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000763 // Block is interference-free.
764 DEBUG(dbgs() << ", no interference");
765 if (!BI.Uses) {
766 assert(BI.LiveThrough && "No uses, but not live through block?");
767 // Block is live-through without interference.
768 if (RegOut) {
769 DEBUG(dbgs() << ", no uses, live-through.\n");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000770 SE->useIntv(BI.Start, BI.Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000771 } else {
772 DEBUG(dbgs() << ", no uses, stack-out.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000773 SE->leaveIntvAtTop(*BI.MBB);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000774 }
775 continue;
776 }
777 if (!BI.LiveThrough) {
778 DEBUG(dbgs() << ", killed in block.\n");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000779 SE->useIntv(BI.Start, SE->leaveIntvAfter(BI.Kill));
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000780 continue;
781 }
782 if (!RegOut) {
783 // Block is live-through, but exit bundle is on the stack.
784 // Spill immediately after the last use.
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000785 if (BI.LastUse < BI.LastSplitPoint) {
786 DEBUG(dbgs() << ", uses, stack-out.\n");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000787 SE->useIntv(BI.Start, SE->leaveIntvAfter(BI.LastUse));
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000788 continue;
789 }
790 // The last use is after the last split point, it is probably an
791 // indirect jump.
792 DEBUG(dbgs() << ", uses at " << BI.LastUse << " after split point "
793 << BI.LastSplitPoint << ", stack-out.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000794 SlotIndex SegEnd = SE->leaveIntvBefore(BI.LastSplitPoint);
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000795 SE->useIntv(BI.Start, SegEnd);
Jakob Stoklund Olesen5c716bd2011-02-08 18:50:21 +0000796 // Run a double interval from the split to the last use.
797 // This makes it possible to spill the complement without affecting the
798 // indirect branch.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000799 SE->overlapIntv(SegEnd, BI.LastUse);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000800 continue;
801 }
802 // Register is live-through.
803 DEBUG(dbgs() << ", uses, live-through.\n");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000804 SE->useIntv(BI.Start, BI.Stop);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000805 continue;
806 }
807
808 // Block has interference.
809 DEBUG(dbgs() << ", interference from " << IP.first);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000810
811 if (!BI.LiveThrough && IP.first >= BI.Kill) {
812 // The interference doesn't reach the outgoing segment.
813 DEBUG(dbgs() << " doesn't affect kill at " << BI.Kill << '\n');
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000814 SE->useIntv(BI.Start, BI.Kill);
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000815 continue;
816 }
817
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000818 if (!BI.Uses) {
819 // No uses in block, avoid interference by spilling as soon as possible.
820 DEBUG(dbgs() << ", no uses.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000821 SlotIndex SegEnd = SE->leaveIntvAtTop(*BI.MBB);
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000822 assert(SegEnd <= IP.first && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000823 continue;
824 }
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000825 if (IP.first.getBaseIndex() > BI.FirstUse) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000826 // There are interference-free uses at the beginning of the block.
827 // Find the last use that can get the register.
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000828 SmallVectorImpl<SlotIndex>::const_iterator UI =
Jakob Stoklund Olesenfe3f99f2011-02-05 01:06:39 +0000829 std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
830 IP.first.getBaseIndex());
Jakob Stoklund Olesenc0de9952011-01-20 17:45:23 +0000831 assert(UI != SA->UseSlots.begin() && "Couldn't find first use");
832 SlotIndex Use = (--UI)->getBoundaryIndex();
833 DEBUG(dbgs() << ", free use at " << *UI << ".\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000834 SlotIndex SegEnd = SE->leaveIntvAfter(Use);
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000835 assert(SegEnd <= IP.first && "Couldn't avoid interference");
Jakob Stoklund Olesen36d61862011-03-03 03:41:29 +0000836 SE->useIntv(BI.Start, SegEnd);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000837 continue;
838 }
839
840 // Interference is before the first use.
841 DEBUG(dbgs() << " before first use.\n");
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000842 SlotIndex SegEnd = SE->leaveIntvAtTop(*BI.MBB);
Jakob Stoklund Olesende710952011-02-05 01:06:36 +0000843 assert(SegEnd <= IP.first && "Couldn't avoid interference");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000844 }
845
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000846 SE->closeIntv();
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000847
848 // FIXME: Should we be more aggressive about splitting the stack region into
849 // per-block segments? The current approach allows the stack region to
850 // separate into connected components. Some components may be allocatable.
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +0000851 SE->finish();
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +0000852 ++NumGlobalSplits;
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000853
Jakob Stoklund Olesen9b3d24b2011-02-04 19:33:07 +0000854 if (VerifyEnabled) {
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000855 MF->verify(this, "After splitting live range around region");
Jakob Stoklund Olesen9b3d24b2011-02-04 19:33:07 +0000856
857#ifndef NDEBUG
858 // Make sure that at least one of the new intervals can allocate to PhysReg.
859 // That was the whole point of splitting the live range.
860 bool found = false;
861 for (LiveRangeEdit::iterator I = LREdit.begin(), E = LREdit.end(); I != E;
862 ++I)
863 if (!checkUncachedInterference(**I, PhysReg)) {
864 found = true;
865 break;
866 }
867 assert(found && "No allocatable intervals after pointless splitting");
868#endif
869 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000870}
871
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000872unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
873 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000874 BitVector LiveBundles, BestBundles;
875 float BestCost = 0;
876 unsigned BestReg = 0;
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000877
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000878 Order.rewind();
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000879 for (unsigned Cand = 0; unsigned PhysReg = Order.next(); ++Cand) {
880 if (GlobalCand.size() <= Cand)
881 GlobalCand.resize(Cand+1);
882 GlobalCand[Cand].PhysReg = PhysReg;
883
884 mapGlobalInterference(PhysReg, GlobalCand[Cand].Interference);
885 float Cost = calcSplitConstraints(GlobalCand[Cand].Interference);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000886 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
887 if (BestReg && Cost >= BestCost) {
888 DEBUG(dbgs() << " higher.\n");
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000889 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000890 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000891
Jakob Stoklund Olesen96dcd952011-03-05 01:10:31 +0000892 SpillPlacer->placeSpills(SplitConstraints, LiveBundles);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000893 // No live bundles, defer to splitSingleBlocks().
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000894 if (!LiveBundles.any()) {
895 DEBUG(dbgs() << " no bundles.\n");
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000896 continue;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000897 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000898
899 Cost += calcGlobalSplitCost(LiveBundles);
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000900 DEBUG({
901 dbgs() << ", total = " << Cost << " with bundles";
902 for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
903 dbgs() << " EB#" << i;
904 dbgs() << ".\n";
905 });
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000906 if (!BestReg || Cost < BestCost) {
907 BestReg = PhysReg;
Jakob Stoklund Olesen874be742011-03-05 03:28:51 +0000908 BestCost = 0.98f * Cost; // Prevent rounding effects.
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000909 BestBundles.swap(LiveBundles);
910 }
911 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000912
913 if (!BestReg)
914 return 0;
915
916 splitAroundRegion(VirtReg, BestReg, BestBundles, NewVRegs);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +0000917 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Region);
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +0000918 return 0;
919}
920
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +0000921
922//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +0000923// Local Splitting
924//===----------------------------------------------------------------------===//
925
926
927/// calcGapWeights - Compute the maximum spill weight that needs to be evicted
928/// in order to use PhysReg between two entries in SA->UseSlots.
929///
930/// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
931///
932void RAGreedy::calcGapWeights(unsigned PhysReg,
933 SmallVectorImpl<float> &GapWeight) {
934 assert(SA->LiveBlocks.size() == 1 && "Not a local interval");
935 const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks.front();
936 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
937 const unsigned NumGaps = Uses.size()-1;
938
939 // Start and end points for the interference check.
940 SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
941 SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
942
943 GapWeight.assign(NumGaps, 0.0f);
944
945 // Add interference from each overlapping register.
946 for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
947 if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
948 .checkInterference())
949 continue;
950
951 // We know that VirtReg is a continuous interval from FirstUse to LastUse,
952 // so we don't need InterferenceQuery.
953 //
954 // Interference that overlaps an instruction is counted in both gaps
955 // surrounding the instruction. The exception is interference before
956 // StartIdx and after StopIdx.
957 //
958 LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
959 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
960 // Skip the gaps before IntI.
961 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
962 if (++Gap == NumGaps)
963 break;
964 if (Gap == NumGaps)
965 break;
966
967 // Update the gaps covered by IntI.
968 const float weight = IntI.value()->weight;
969 for (; Gap != NumGaps; ++Gap) {
970 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
971 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
972 break;
973 }
974 if (Gap == NumGaps)
975 break;
976 }
977 }
978}
979
980/// getPrevMappedIndex - Return the slot index of the last non-copy instruction
981/// before MI that has a slot index. If MI is the first mapped instruction in
982/// its block, return the block start index instead.
983///
984SlotIndex RAGreedy::getPrevMappedIndex(const MachineInstr *MI) {
985 assert(MI && "Missing MachineInstr");
986 const MachineBasicBlock *MBB = MI->getParent();
987 MachineBasicBlock::const_iterator B = MBB->begin(), I = MI;
988 while (I != B)
989 if (!(--I)->isDebugValue() && !I->isCopy())
990 return Indexes->getInstructionIndex(I);
991 return Indexes->getMBBStartIdx(MBB);
992}
993
994/// calcPrevSlots - Fill in the PrevSlot array with the index of the previous
995/// real non-copy instruction for each instruction in SA->UseSlots.
996///
997void RAGreedy::calcPrevSlots() {
998 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
999 PrevSlot.clear();
1000 PrevSlot.reserve(Uses.size());
1001 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
1002 const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]);
1003 PrevSlot.push_back(getPrevMappedIndex(MI).getDefIndex());
1004 }
1005}
1006
1007/// nextSplitPoint - Find the next index into SA->UseSlots > i such that it may
1008/// be beneficial to split before UseSlots[i].
1009///
1010/// 0 is always a valid split point
1011unsigned RAGreedy::nextSplitPoint(unsigned i) {
1012 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1013 const unsigned Size = Uses.size();
1014 assert(i != Size && "No split points after the end");
1015 // Allow split before i when Uses[i] is not adjacent to the previous use.
1016 while (++i != Size && PrevSlot[i].getBaseIndex() <= Uses[i-1].getBaseIndex())
1017 ;
1018 return i;
1019}
1020
1021/// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1022/// basic block.
1023///
1024unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1025 SmallVectorImpl<LiveInterval*> &NewVRegs) {
1026 assert(SA->LiveBlocks.size() == 1 && "Not a local interval");
1027 const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks.front();
1028
1029 // Note that it is possible to have an interval that is live-in or live-out
1030 // while only covering a single block - A phi-def can use undef values from
1031 // predecessors, and the block could be a single-block loop.
1032 // We don't bother doing anything clever about such a case, we simply assume
1033 // that the interval is continuous from FirstUse to LastUse. We should make
1034 // sure that we don't do anything illegal to such an interval, though.
1035
1036 const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1037 if (Uses.size() <= 2)
1038 return 0;
1039 const unsigned NumGaps = Uses.size()-1;
1040
1041 DEBUG({
1042 dbgs() << "tryLocalSplit: ";
1043 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1044 dbgs() << ' ' << SA->UseSlots[i];
1045 dbgs() << '\n';
1046 });
1047
1048 // For every use, find the previous mapped non-copy instruction.
1049 // We use this to detect valid split points, and to estimate new interval
1050 // sizes.
1051 calcPrevSlots();
1052
1053 unsigned BestBefore = NumGaps;
1054 unsigned BestAfter = 0;
1055 float BestDiff = 0;
1056
Jakob Stoklund Olesen40a42a22011-03-04 00:58:40 +00001057 const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001058 SmallVector<float, 8> GapWeight;
1059
1060 Order.rewind();
1061 while (unsigned PhysReg = Order.next()) {
1062 // Keep track of the largest spill weight that would need to be evicted in
1063 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1064 calcGapWeights(PhysReg, GapWeight);
1065
1066 // Try to find the best sequence of gaps to close.
1067 // The new spill weight must be larger than any gap interference.
1068
1069 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1070 unsigned SplitBefore = 0, SplitAfter = nextSplitPoint(1) - 1;
1071
1072 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1073 // It is the spill weight that needs to be evicted.
1074 float MaxGap = GapWeight[0];
1075 for (unsigned i = 1; i != SplitAfter; ++i)
1076 MaxGap = std::max(MaxGap, GapWeight[i]);
1077
1078 for (;;) {
1079 // Live before/after split?
1080 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1081 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1082
1083 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1084 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1085 << " i=" << MaxGap);
1086
1087 // Stop before the interval gets so big we wouldn't be making progress.
1088 if (!LiveBefore && !LiveAfter) {
1089 DEBUG(dbgs() << " all\n");
1090 break;
1091 }
1092 // Should the interval be extended or shrunk?
1093 bool Shrink = true;
1094 if (MaxGap < HUGE_VALF) {
1095 // Estimate the new spill weight.
1096 //
1097 // Each instruction reads and writes the register, except the first
1098 // instr doesn't read when !FirstLive, and the last instr doesn't write
1099 // when !LastLive.
1100 //
1101 // We will be inserting copies before and after, so the total number of
1102 // reads and writes is 2 * EstUses.
1103 //
1104 const unsigned EstUses = 2*(SplitAfter - SplitBefore) +
1105 2*(LiveBefore + LiveAfter);
1106
1107 // Try to guess the size of the new interval. This should be trivial,
1108 // but the slot index of an inserted copy can be a lot smaller than the
1109 // instruction it is inserted before if there are many dead indexes
1110 // between them.
1111 //
1112 // We measure the distance from the instruction before SplitBefore to
1113 // get a conservative estimate.
1114 //
1115 // The final distance can still be different if inserting copies
1116 // triggers a slot index renumbering.
1117 //
1118 const float EstWeight = normalizeSpillWeight(blockFreq * EstUses,
1119 PrevSlot[SplitBefore].distance(Uses[SplitAfter]));
1120 // Would this split be possible to allocate?
1121 // Never allocate all gaps, we wouldn't be making progress.
1122 float Diff = EstWeight - MaxGap;
1123 DEBUG(dbgs() << " w=" << EstWeight << " d=" << Diff);
1124 if (Diff > 0) {
1125 Shrink = false;
1126 if (Diff > BestDiff) {
1127 DEBUG(dbgs() << " (best)");
1128 BestDiff = Diff;
1129 BestBefore = SplitBefore;
1130 BestAfter = SplitAfter;
1131 }
1132 }
1133 }
1134
1135 // Try to shrink.
1136 if (Shrink) {
1137 SplitBefore = nextSplitPoint(SplitBefore);
1138 if (SplitBefore < SplitAfter) {
1139 DEBUG(dbgs() << " shrink\n");
1140 // Recompute the max when necessary.
1141 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1142 MaxGap = GapWeight[SplitBefore];
1143 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1144 MaxGap = std::max(MaxGap, GapWeight[i]);
1145 }
1146 continue;
1147 }
1148 MaxGap = 0;
1149 }
1150
1151 // Try to extend the interval.
1152 if (SplitAfter >= NumGaps) {
1153 DEBUG(dbgs() << " end\n");
1154 break;
1155 }
1156
1157 DEBUG(dbgs() << " extend\n");
1158 for (unsigned e = nextSplitPoint(SplitAfter + 1) - 1;
1159 SplitAfter != e; ++SplitAfter)
1160 MaxGap = std::max(MaxGap, GapWeight[SplitAfter]);
1161 continue;
1162 }
1163 }
1164
1165 // Didn't find any candidates?
1166 if (BestBefore == NumGaps)
1167 return 0;
1168
1169 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1170 << '-' << Uses[BestAfter] << ", " << BestDiff
1171 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1172
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001173 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001174 SE->reset(LREdit);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001175
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001176 SE->openIntv();
1177 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1178 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1179 SE->useIntv(SegStart, SegStop);
1180 SE->closeIntv();
1181 SE->finish();
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001182 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Local);
Jakob Stoklund Olesen0db841f2011-02-17 22:53:48 +00001183 ++NumLocalSplits;
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001184
1185 return 0;
1186}
1187
1188//===----------------------------------------------------------------------===//
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001189// Live Range Splitting
1190//===----------------------------------------------------------------------===//
1191
1192/// trySplit - Try to split VirtReg or one of its interferences, making it
1193/// assignable.
1194/// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1195unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1196 SmallVectorImpl<LiveInterval*>&NewVRegs) {
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001197 // Local intervals are handled separately.
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001198 if (LIS->intervalIsInOneMBB(VirtReg)) {
1199 NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001200 SA->analyze(&VirtReg);
Jakob Stoklund Olesen034a80d2011-02-17 19:13:53 +00001201 return tryLocalSplit(VirtReg, Order, NewVRegs);
Jakob Stoklund Olesena2ebf602011-02-19 00:38:40 +00001202 }
1203
1204 NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001205
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001206 // Don't iterate global splitting.
1207 // Move straight to spilling if this range was produced by a global split.
1208 LiveRangeStage Stage = getStage(VirtReg);
1209 if (Stage >= RS_Block)
1210 return 0;
1211
1212 SA->analyze(&VirtReg);
1213
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001214 // First try to split around a region spanning multiple blocks.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001215 if (Stage < RS_Region) {
1216 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1217 if (PhysReg || !NewVRegs.empty())
1218 return PhysReg;
1219 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001220
1221 // Then isolate blocks with multiple uses.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001222 if (Stage < RS_Block) {
1223 SplitAnalysis::BlockPtrSet Blocks;
1224 if (SA->getMultiUseBlocks(Blocks)) {
Jakob Stoklund Olesen92a55f42011-03-09 00:57:29 +00001225 LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001226 SE->reset(LREdit);
1227 SE->splitSingleBlocks(Blocks);
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001228 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Block);
1229 if (VerifyEnabled)
1230 MF->verify(this, "After splitting live range around basic blocks");
1231 }
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001232 }
1233
1234 // Don't assign any physregs.
1235 return 0;
1236}
1237
1238
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001239//===----------------------------------------------------------------------===//
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001240// Main Entry Point
1241//===----------------------------------------------------------------------===//
1242
1243unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001244 SmallVectorImpl<LiveInterval*> &NewVRegs) {
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001245 LiveRangeStage Stage = getStage(VirtReg);
1246 if (Stage == RS_Original)
1247 LRStage[VirtReg.reg] = RS_Second;
1248
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001249 // First try assigning a free register.
Jakob Stoklund Olesendd479e92010-12-10 22:21:05 +00001250 AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
1251 while (unsigned PhysReg = Order.next()) {
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001252 if (!checkPhysRegInterference(VirtReg, PhysReg))
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001253 return PhysReg;
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001254 }
Andrew Trickb853e6c2010-12-09 18:15:21 +00001255
Jakob Stoklund Olesen98c81412011-02-23 00:29:52 +00001256 if (unsigned PhysReg = tryReassign(VirtReg, Order, NewVRegs))
1257 return PhysReg;
1258
1259 if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001260 return PhysReg;
Andrew Trickb853e6c2010-12-09 18:15:21 +00001261
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001262 assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1263
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001264 // The first time we see a live range, don't try to split or spill.
1265 // Wait until the second time, when all smaller ranges have been allocated.
1266 // This gives a better picture of the interference to split around.
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001267 if (Stage == RS_Original) {
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +00001268 DEBUG(dbgs() << "wait for second round\n");
Jakob Stoklund Olesen107d3662011-02-24 23:21:36 +00001269 NewVRegs.push_back(&VirtReg);
1270 return 0;
1271 }
1272
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001273 assert(Stage < RS_Spill && "Cannot allocate after spilling");
1274
Jakob Stoklund Olesen46c83c82010-12-14 00:37:49 +00001275 // Try splitting VirtReg or interferences.
Jakob Stoklund Olesenccdb3fc2011-01-19 22:11:48 +00001276 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1277 if (PhysReg || !NewVRegs.empty())
Jakob Stoklund Olesenb64d92e2010-12-14 00:37:44 +00001278 return PhysReg;
1279
Jakob Stoklund Olesen770d42d2010-12-22 22:01:30 +00001280 // Finally spill VirtReg itself.
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001281 NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesen47dbf6c2011-03-10 01:51:42 +00001282 LiveRangeEdit LRE(VirtReg, NewVRegs, this);
1283 spiller().spill(LRE);
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001284
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +00001285 if (VerifyEnabled)
1286 MF->verify(this, "After spilling");
1287
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001288 // The live virtual register requesting allocation was spilled, so tell
1289 // the caller not to allocate anything during this round.
1290 return 0;
1291}
1292
1293bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1294 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1295 << "********** Function: "
1296 << ((Value*)mf.getFunction())->getName() << '\n');
1297
1298 MF = &mf;
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001299 if (VerifyEnabled)
Jakob Stoklund Olesen89cab932010-12-18 00:06:56 +00001300 MF->verify(this, "Before greedy register allocator");
Jakob Stoklund Olesenaf249642010-12-17 23:16:35 +00001301
Jakob Stoklund Olesen4680dec2010-12-10 23:49:00 +00001302 RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001303 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenf428eb62010-12-17 23:16:32 +00001304 DomTree = &getAnalysis<MachineDominatorTree>();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001305 ReservedRegs = TRI->getReservedRegs(*MF);
Jakob Stoklund Olesenf6dff842010-12-10 22:54:44 +00001306 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001307 Loops = &getAnalysis<MachineLoopInfo>();
1308 LoopRanges = &getAnalysis<MachineLoopRanges>();
Jakob Stoklund Olesenb5fa9332011-01-18 21:13:27 +00001309 Bundles = &getAnalysis<EdgeBundles>();
1310 SpillPlacer = &getAnalysis<SpillPlacement>();
1311
Jakob Stoklund Olesen1b847de2011-02-19 00:53:42 +00001312 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
Jakob Stoklund Olesenbece06f2011-03-03 01:29:13 +00001313 SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
Jakob Stoklund Olesen22a1df62011-03-01 21:10:07 +00001314 LRStage.clear();
1315 LRStage.resize(MRI->getNumVirtRegs());
Jakob Stoklund Olesend0bb5e22010-12-15 23:46:13 +00001316
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001317 allocatePhysRegs();
1318 addMBBLiveIns(MF);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +00001319 LIS->addKillFlags();
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001320
1321 // Run rewriter
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001322 {
1323 NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
Jakob Stoklund Olesenba05c012011-02-18 22:03:18 +00001324 VRM->rewrite(Indexes);
Jakob Stoklund Olesen533f58e2010-12-11 00:19:56 +00001325 }
Jakob Stoklund Olesencba2e062010-12-08 03:26:16 +00001326
1327 // The pass output is in VirtRegMap. Release all the transient data.
1328 releaseMemory();
1329
1330 return true;
1331}