blob: c7491ce2a8943a5d5446ea3951f52eba9f2704ea [file] [log] [blame]
Evan Cheng09e8ca82008-10-20 21:44:59 +00001//===-- PreAllocSplitting.cpp - Pre-allocation Interval Spltting Pass. ----===//
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 implements the machine instruction level pre-register allocation
11// live interval splitting pass. It finds live interval barriers, i.e.
12// instructions which will kill all physical registers in certain register
13// classes, and split all live intervals which cross the barrier.
14//
15//===----------------------------------------------------------------------===//
16
17#define DEBUG_TYPE "pre-alloc-split"
18#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Evan Chengd0e32c52008-10-29 05:06:14 +000019#include "llvm/CodeGen/LiveStackAnalysis.h"
Owen Andersonf1f75b12008-11-04 22:22:41 +000020#include "llvm/CodeGen/MachineDominators.h"
Evan Chengf5cd4f02008-10-23 20:43:13 +000021#include "llvm/CodeGen/MachineFrameInfo.h"
Evan Cheng09e8ca82008-10-20 21:44:59 +000022#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineLoopInfo.h"
24#include "llvm/CodeGen/MachineRegisterInfo.h"
25#include "llvm/CodeGen/Passes.h"
26#include "llvm/CodeGen/RegisterCoalescer.h"
Evan Chengf5cd4f02008-10-23 20:43:13 +000027#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng09e8ca82008-10-20 21:44:59 +000028#include "llvm/Target/TargetMachine.h"
29#include "llvm/Target/TargetOptions.h"
30#include "llvm/Target/TargetRegisterInfo.h"
31#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Debug.h"
Evan Chengd0e32c52008-10-29 05:06:14 +000033#include "llvm/ADT/DenseMap.h"
Evan Cheng54898932008-10-29 08:39:34 +000034#include "llvm/ADT/DepthFirstIterator.h"
Evan Cheng09e8ca82008-10-20 21:44:59 +000035#include "llvm/ADT/SmallPtrSet.h"
Evan Chengf5cd4f02008-10-23 20:43:13 +000036#include "llvm/ADT/Statistic.h"
Evan Cheng09e8ca82008-10-20 21:44:59 +000037using namespace llvm;
38
Evan Chengae7fa5b2008-10-28 01:48:24 +000039static cl::opt<int> PreSplitLimit("pre-split-limit", cl::init(-1), cl::Hidden);
40
41STATISTIC(NumSplits, "Number of intervals split");
Owen Anderson75fa96b2008-11-19 04:28:29 +000042STATISTIC(NumRemats, "Number of intervals split by rematerialization");
Owen Anderson7b9d67c2008-12-02 18:53:47 +000043STATISTIC(NumFolds, "Number of intervals split with spill folding");
Owen Anderson25dffa72008-12-17 22:06:59 +000044STATISTIC(NumRenumbers, "Number of intervals renumbered into new registers");
Evan Chengf5cd4f02008-10-23 20:43:13 +000045
Evan Cheng09e8ca82008-10-20 21:44:59 +000046namespace {
47 class VISIBILITY_HIDDEN PreAllocSplitting : public MachineFunctionPass {
Evan Chengd0e32c52008-10-29 05:06:14 +000048 MachineFunction *CurrMF;
Evan Chengf5cd4f02008-10-23 20:43:13 +000049 const TargetMachine *TM;
50 const TargetInstrInfo *TII;
51 MachineFrameInfo *MFI;
52 MachineRegisterInfo *MRI;
53 LiveIntervals *LIs;
Evan Chengd0e32c52008-10-29 05:06:14 +000054 LiveStacks *LSs;
Evan Cheng09e8ca82008-10-20 21:44:59 +000055
Evan Chengf5cd4f02008-10-23 20:43:13 +000056 // Barrier - Current barrier being processed.
57 MachineInstr *Barrier;
58
59 // BarrierMBB - Basic block where the barrier resides in.
60 MachineBasicBlock *BarrierMBB;
61
62 // Barrier - Current barrier index.
63 unsigned BarrierIdx;
64
65 // CurrLI - Current live interval being split.
66 LiveInterval *CurrLI;
67
Evan Chengd0e32c52008-10-29 05:06:14 +000068 // CurrSLI - Current stack slot live interval.
69 LiveInterval *CurrSLI;
70
71 // CurrSValNo - Current val# for the stack slot live interval.
72 VNInfo *CurrSValNo;
73
74 // IntervalSSMap - A map from live interval to spill slots.
75 DenseMap<unsigned, int> IntervalSSMap;
Evan Chengf5cd4f02008-10-23 20:43:13 +000076
Evan Cheng54898932008-10-29 08:39:34 +000077 // Def2SpillMap - A map from a def instruction index to spill index.
78 DenseMap<unsigned, unsigned> Def2SpillMap;
Evan Cheng06587492008-10-24 02:05:00 +000079
Evan Cheng09e8ca82008-10-20 21:44:59 +000080 public:
81 static char ID;
82 PreAllocSplitting() : MachineFunctionPass(&ID) {}
83
84 virtual bool runOnMachineFunction(MachineFunction &MF);
85
86 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
87 AU.addRequired<LiveIntervals>();
88 AU.addPreserved<LiveIntervals>();
Evan Chengd0e32c52008-10-29 05:06:14 +000089 AU.addRequired<LiveStacks>();
90 AU.addPreserved<LiveStacks>();
Evan Cheng09e8ca82008-10-20 21:44:59 +000091 AU.addPreserved<RegisterCoalescer>();
92 if (StrongPHIElim)
93 AU.addPreservedID(StrongPHIEliminationID);
94 else
95 AU.addPreservedID(PHIEliminationID);
Owen Andersonf1f75b12008-11-04 22:22:41 +000096 AU.addRequired<MachineDominatorTree>();
97 AU.addRequired<MachineLoopInfo>();
98 AU.addPreserved<MachineDominatorTree>();
99 AU.addPreserved<MachineLoopInfo>();
Evan Cheng09e8ca82008-10-20 21:44:59 +0000100 MachineFunctionPass::getAnalysisUsage(AU);
101 }
102
103 virtual void releaseMemory() {
Evan Chengd0e32c52008-10-29 05:06:14 +0000104 IntervalSSMap.clear();
Evan Cheng54898932008-10-29 08:39:34 +0000105 Def2SpillMap.clear();
Evan Cheng09e8ca82008-10-20 21:44:59 +0000106 }
107
108 virtual const char *getPassName() const {
109 return "Pre-Register Allocaton Live Interval Splitting";
110 }
Evan Chengf5cd4f02008-10-23 20:43:13 +0000111
112 /// print - Implement the dump method.
113 virtual void print(std::ostream &O, const Module* M = 0) const {
114 LIs->print(O, M);
115 }
116
117 void print(std::ostream *O, const Module* M = 0) const {
118 if (O) print(*O, M);
119 }
120
121 private:
122 MachineBasicBlock::iterator
123 findNextEmptySlot(MachineBasicBlock*, MachineInstr*,
124 unsigned&);
125
126 MachineBasicBlock::iterator
Evan Cheng1f08cc22008-10-28 05:28:21 +0000127 findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
Evan Chengf5cd4f02008-10-23 20:43:13 +0000128 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
129
130 MachineBasicBlock::iterator
Evan Chengf62ce372008-10-28 00:47:49 +0000131 findRestorePoint(MachineBasicBlock*, MachineInstr*, unsigned,
Evan Chengf5cd4f02008-10-23 20:43:13 +0000132 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
133
Evan Chengd0e32c52008-10-29 05:06:14 +0000134 int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000135
Evan Cheng54898932008-10-29 08:39:34 +0000136 bool IsAvailableInStack(MachineBasicBlock*, unsigned, unsigned, unsigned,
137 unsigned&, int&) const;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000138
Evan Chengd0e32c52008-10-29 05:06:14 +0000139 void UpdateSpillSlotInterval(VNInfo*, unsigned, unsigned);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000140
Owen Anderson25dffa72008-12-17 22:06:59 +0000141 VNInfo* UpdateRegisterInterval(VNInfo*, unsigned, unsigned);
Evan Chengd0e32c52008-10-29 05:06:14 +0000142
143 bool ShrinkWrapToLastUse(MachineBasicBlock*, VNInfo*,
Evan Cheng06587492008-10-24 02:05:00 +0000144 SmallVector<MachineOperand*, 4>&,
145 SmallPtrSet<MachineInstr*, 4>&);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000146
Evan Chengaaf510c2008-10-26 07:49:03 +0000147 void ShrinkWrapLiveInterval(VNInfo*, MachineBasicBlock*, MachineBasicBlock*,
Evan Chengf5cd4f02008-10-23 20:43:13 +0000148 MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*, 8>&,
Evan Cheng06587492008-10-24 02:05:00 +0000149 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >&,
150 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >&,
151 SmallVector<MachineBasicBlock*, 4>&);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000152
153 bool SplitRegLiveInterval(LiveInterval*);
154
155 bool SplitRegLiveIntervals(const TargetRegisterClass **);
Owen Andersonf1f75b12008-11-04 22:22:41 +0000156
Owen Anderson6002e992008-12-04 21:20:30 +0000157 void RepairLiveInterval(LiveInterval* CurrLI, VNInfo* ValNo,
158 MachineInstr* DefMI, unsigned RestoreIdx);
159
Owen Andersonf1f75b12008-11-04 22:22:41 +0000160 bool createsNewJoin(LiveRange* LR, MachineBasicBlock* DefMBB,
161 MachineBasicBlock* BarrierMBB);
Owen Anderson75fa96b2008-11-19 04:28:29 +0000162 bool Rematerialize(unsigned vreg, VNInfo* ValNo,
163 MachineInstr* DefMI,
164 MachineBasicBlock::iterator RestorePt,
165 unsigned RestoreIdx,
166 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
Owen Anderson7b9d67c2008-12-02 18:53:47 +0000167 MachineInstr* FoldSpill(unsigned vreg, const TargetRegisterClass* RC,
168 MachineInstr* DefMI,
169 MachineInstr* Barrier,
170 MachineBasicBlock* MBB,
171 int& SS,
172 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000173 void RenumberValno(VNInfo* VN);
Evan Cheng09e8ca82008-10-20 21:44:59 +0000174 };
175} // end anonymous namespace
176
177char PreAllocSplitting::ID = 0;
178
179static RegisterPass<PreAllocSplitting>
180X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
181
182const PassInfo *const llvm::PreAllocSplittingID = &X;
183
Evan Chengf5cd4f02008-10-23 20:43:13 +0000184
185/// findNextEmptySlot - Find a gap after the given machine instruction in the
186/// instruction index map. If there isn't one, return end().
187MachineBasicBlock::iterator
188PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
189 unsigned &SpotIndex) {
190 MachineBasicBlock::iterator MII = MI;
191 if (++MII != MBB->end()) {
192 unsigned Index = LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
193 if (Index) {
194 SpotIndex = Index;
195 return MII;
196 }
197 }
198 return MBB->end();
199}
200
201/// findSpillPoint - Find a gap as far away from the given MI that's suitable
202/// for spilling the current live interval. The index must be before any
203/// defs and uses of the live interval register in the mbb. Return begin() if
204/// none is found.
205MachineBasicBlock::iterator
206PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
Evan Cheng1f08cc22008-10-28 05:28:21 +0000207 MachineInstr *DefMI,
Evan Chengf5cd4f02008-10-23 20:43:13 +0000208 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
209 unsigned &SpillIndex) {
210 MachineBasicBlock::iterator Pt = MBB->begin();
211
212 // Go top down if RefsInMBB is empty.
Evan Cheng1f08cc22008-10-28 05:28:21 +0000213 if (RefsInMBB.empty() && !DefMI) {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000214 MachineBasicBlock::iterator MII = MBB->begin();
215 MachineBasicBlock::iterator EndPt = MI;
216 do {
217 ++MII;
218 unsigned Index = LIs->getInstructionIndex(MII);
219 unsigned Gap = LIs->findGapBeforeInstr(Index);
220 if (Gap) {
221 Pt = MII;
222 SpillIndex = Gap;
223 break;
224 }
225 } while (MII != EndPt);
226 } else {
227 MachineBasicBlock::iterator MII = MI;
Evan Cheng1f08cc22008-10-28 05:28:21 +0000228 MachineBasicBlock::iterator EndPt = DefMI
229 ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
230 while (MII != EndPt && !RefsInMBB.count(MII)) {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000231 unsigned Index = LIs->getInstructionIndex(MII);
232 if (LIs->hasGapBeforeInstr(Index)) {
233 Pt = MII;
234 SpillIndex = LIs->findGapBeforeInstr(Index, true);
235 }
236 --MII;
237 }
238 }
239
240 return Pt;
241}
242
243/// findRestorePoint - Find a gap in the instruction index map that's suitable
244/// for restoring the current live interval value. The index must be before any
245/// uses of the live interval register in the mbb. Return end() if none is
246/// found.
247MachineBasicBlock::iterator
248PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
Evan Chengf62ce372008-10-28 00:47:49 +0000249 unsigned LastIdx,
Evan Chengf5cd4f02008-10-23 20:43:13 +0000250 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
251 unsigned &RestoreIndex) {
Evan Cheng54898932008-10-29 08:39:34 +0000252 // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
253 // begin index accordingly.
Owen Anderson5a92d4e2008-11-18 20:53:59 +0000254 MachineBasicBlock::iterator Pt = MBB->end();
Evan Chengf62ce372008-10-28 00:47:49 +0000255 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000256
Evan Chengf62ce372008-10-28 00:47:49 +0000257 // Go bottom up if RefsInMBB is empty and the end of the mbb isn't beyond
258 // the last index in the live range.
259 if (RefsInMBB.empty() && LastIdx >= EndIdx) {
Owen Anderson711fd3d2008-11-13 21:53:14 +0000260 MachineBasicBlock::iterator MII = MBB->getFirstTerminator();
Evan Chengf5cd4f02008-10-23 20:43:13 +0000261 MachineBasicBlock::iterator EndPt = MI;
Evan Cheng54898932008-10-29 08:39:34 +0000262 --MII;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000263 do {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000264 unsigned Index = LIs->getInstructionIndex(MII);
Evan Cheng56ab0de2008-10-24 18:46:44 +0000265 unsigned Gap = LIs->findGapBeforeInstr(Index);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000266 if (Gap) {
267 Pt = MII;
268 RestoreIndex = Gap;
269 break;
270 }
Evan Cheng54898932008-10-29 08:39:34 +0000271 --MII;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000272 } while (MII != EndPt);
273 } else {
274 MachineBasicBlock::iterator MII = MI;
275 MII = ++MII;
Evan Chengf62ce372008-10-28 00:47:49 +0000276 // FIXME: Limit the number of instructions to examine to reduce
277 // compile time?
Evan Chengf5cd4f02008-10-23 20:43:13 +0000278 while (MII != MBB->end()) {
279 unsigned Index = LIs->getInstructionIndex(MII);
Evan Chengf62ce372008-10-28 00:47:49 +0000280 if (Index > LastIdx)
281 break;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000282 unsigned Gap = LIs->findGapBeforeInstr(Index);
283 if (Gap) {
284 Pt = MII;
285 RestoreIndex = Gap;
286 }
287 if (RefsInMBB.count(MII))
288 break;
289 ++MII;
290 }
291 }
292
293 return Pt;
294}
295
Evan Chengd0e32c52008-10-29 05:06:14 +0000296/// CreateSpillStackSlot - Create a stack slot for the live interval being
297/// split. If the live interval was previously split, just reuse the same
298/// slot.
299int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
300 const TargetRegisterClass *RC) {
301 int SS;
302 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
303 if (I != IntervalSSMap.end()) {
304 SS = I->second;
305 } else {
306 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
307 IntervalSSMap[Reg] = SS;
Evan Cheng06587492008-10-24 02:05:00 +0000308 }
Evan Chengd0e32c52008-10-29 05:06:14 +0000309
310 // Create live interval for stack slot.
311 CurrSLI = &LSs->getOrCreateInterval(SS);
Evan Cheng54898932008-10-29 08:39:34 +0000312 if (CurrSLI->hasAtLeastOneValue())
Evan Chengd0e32c52008-10-29 05:06:14 +0000313 CurrSValNo = CurrSLI->getValNumInfo(0);
314 else
315 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
316 return SS;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000317}
318
Evan Chengd0e32c52008-10-29 05:06:14 +0000319/// IsAvailableInStack - Return true if register is available in a split stack
320/// slot at the specified index.
321bool
Evan Cheng54898932008-10-29 08:39:34 +0000322PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
323 unsigned Reg, unsigned DefIndex,
324 unsigned RestoreIndex, unsigned &SpillIndex,
325 int& SS) const {
326 if (!DefMBB)
327 return false;
328
Evan Chengd0e32c52008-10-29 05:06:14 +0000329 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
330 if (I == IntervalSSMap.end())
Evan Chengf5cd4f02008-10-23 20:43:13 +0000331 return false;
Evan Cheng54898932008-10-29 08:39:34 +0000332 DenseMap<unsigned, unsigned>::iterator II = Def2SpillMap.find(DefIndex);
333 if (II == Def2SpillMap.end())
334 return false;
335
336 // If last spill of def is in the same mbb as barrier mbb (where restore will
337 // be), make sure it's not below the intended restore index.
338 // FIXME: Undo the previous spill?
339 assert(LIs->getMBBFromIndex(II->second) == DefMBB);
340 if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
341 return false;
342
343 SS = I->second;
344 SpillIndex = II->second;
345 return true;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000346}
347
Evan Chengd0e32c52008-10-29 05:06:14 +0000348/// UpdateSpillSlotInterval - Given the specified val# of the register live
349/// interval being split, and the spill and restore indicies, update the live
350/// interval of the spill stack slot.
351void
352PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, unsigned SpillIndex,
353 unsigned RestoreIndex) {
Evan Cheng54898932008-10-29 08:39:34 +0000354 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
355 "Expect restore in the barrier mbb");
356
357 MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
358 if (MBB == BarrierMBB) {
359 // Intra-block spill + restore. We are done.
Evan Chengd0e32c52008-10-29 05:06:14 +0000360 LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
361 CurrSLI->addRange(SLR);
362 return;
363 }
364
Evan Cheng54898932008-10-29 08:39:34 +0000365 SmallPtrSet<MachineBasicBlock*, 4> Processed;
366 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
367 LiveRange SLR(SpillIndex, EndIdx+1, CurrSValNo);
Evan Chengd0e32c52008-10-29 05:06:14 +0000368 CurrSLI->addRange(SLR);
Evan Cheng54898932008-10-29 08:39:34 +0000369 Processed.insert(MBB);
Evan Chengd0e32c52008-10-29 05:06:14 +0000370
371 // Start from the spill mbb, figure out the extend of the spill slot's
372 // live interval.
373 SmallVector<MachineBasicBlock*, 4> WorkList;
Evan Cheng54898932008-10-29 08:39:34 +0000374 const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
375 if (LR->end > EndIdx)
Evan Chengd0e32c52008-10-29 05:06:14 +0000376 // If live range extend beyond end of mbb, add successors to work list.
377 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
378 SE = MBB->succ_end(); SI != SE; ++SI)
379 WorkList.push_back(*SI);
Evan Chengd0e32c52008-10-29 05:06:14 +0000380
381 while (!WorkList.empty()) {
382 MachineBasicBlock *MBB = WorkList.back();
383 WorkList.pop_back();
Evan Cheng54898932008-10-29 08:39:34 +0000384 if (Processed.count(MBB))
385 continue;
Evan Chengd0e32c52008-10-29 05:06:14 +0000386 unsigned Idx = LIs->getMBBStartIdx(MBB);
387 LR = CurrLI->getLiveRangeContaining(Idx);
Evan Cheng54898932008-10-29 08:39:34 +0000388 if (LR && LR->valno == ValNo) {
389 EndIdx = LIs->getMBBEndIdx(MBB);
390 if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
Evan Chengd0e32c52008-10-29 05:06:14 +0000391 // Spill slot live interval stops at the restore.
Evan Cheng54898932008-10-29 08:39:34 +0000392 LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
Evan Chengd0e32c52008-10-29 05:06:14 +0000393 CurrSLI->addRange(SLR);
Evan Cheng54898932008-10-29 08:39:34 +0000394 } else if (LR->end > EndIdx) {
395 // Live range extends beyond end of mbb, process successors.
396 LiveRange SLR(Idx, EndIdx+1, CurrSValNo);
397 CurrSLI->addRange(SLR);
398 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
399 SE = MBB->succ_end(); SI != SE; ++SI)
400 WorkList.push_back(*SI);
Evan Chengd0e32c52008-10-29 05:06:14 +0000401 } else {
Evan Cheng54898932008-10-29 08:39:34 +0000402 LiveRange SLR(Idx, LR->end, CurrSValNo);
Evan Chengd0e32c52008-10-29 05:06:14 +0000403 CurrSLI->addRange(SLR);
Evan Chengd0e32c52008-10-29 05:06:14 +0000404 }
Evan Cheng54898932008-10-29 08:39:34 +0000405 Processed.insert(MBB);
Evan Chengd0e32c52008-10-29 05:06:14 +0000406 }
407 }
408}
409
410/// UpdateRegisterInterval - Given the specified val# of the current live
411/// interval is being split, and the spill and restore indices, update the live
Evan Chengf5cd4f02008-10-23 20:43:13 +0000412/// interval accordingly.
Owen Anderson25dffa72008-12-17 22:06:59 +0000413VNInfo*
Evan Chengd0e32c52008-10-29 05:06:14 +0000414PreAllocSplitting::UpdateRegisterInterval(VNInfo *ValNo, unsigned SpillIndex,
415 unsigned RestoreIndex) {
Evan Cheng54898932008-10-29 08:39:34 +0000416 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
417 "Expect restore in the barrier mbb");
418
Evan Chengf5cd4f02008-10-23 20:43:13 +0000419 SmallVector<std::pair<unsigned,unsigned>, 4> Before;
420 SmallVector<std::pair<unsigned,unsigned>, 4> After;
421 SmallVector<unsigned, 4> BeforeKills;
422 SmallVector<unsigned, 4> AfterKills;
423 SmallPtrSet<const LiveRange*, 4> Processed;
424
425 // First, let's figure out which parts of the live interval is now defined
426 // by the restore, which are defined by the original definition.
Evan Chengd0e32c52008-10-29 05:06:14 +0000427 const LiveRange *LR = CurrLI->getLiveRangeContaining(RestoreIndex);
428 After.push_back(std::make_pair(RestoreIndex, LR->end));
Evan Cheng06587492008-10-24 02:05:00 +0000429 if (CurrLI->isKill(ValNo, LR->end))
430 AfterKills.push_back(LR->end);
431
Evan Chengd0e32c52008-10-29 05:06:14 +0000432 assert(LR->contains(SpillIndex));
433 if (SpillIndex > LR->start) {
434 Before.push_back(std::make_pair(LR->start, SpillIndex));
435 BeforeKills.push_back(SpillIndex);
Evan Cheng06587492008-10-24 02:05:00 +0000436 }
Evan Chengf5cd4f02008-10-23 20:43:13 +0000437 Processed.insert(LR);
438
Evan Chengd0e32c52008-10-29 05:06:14 +0000439 // Start from the restore mbb, figure out what part of the live interval
440 // are defined by the restore.
Evan Chengf5cd4f02008-10-23 20:43:13 +0000441 SmallVector<MachineBasicBlock*, 4> WorkList;
Evan Cheng54898932008-10-29 08:39:34 +0000442 MachineBasicBlock *MBB = BarrierMBB;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000443 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
444 SE = MBB->succ_end(); SI != SE; ++SI)
445 WorkList.push_back(*SI);
446
Owen Anderson75c99c52008-12-07 05:33:18 +0000447 SmallPtrSet<MachineBasicBlock*, 4> ProcessedBlocks;
448 ProcessedBlocks.insert(MBB);
449
Evan Chengf5cd4f02008-10-23 20:43:13 +0000450 while (!WorkList.empty()) {
451 MBB = WorkList.back();
452 WorkList.pop_back();
453 unsigned Idx = LIs->getMBBStartIdx(MBB);
454 LR = CurrLI->getLiveRangeContaining(Idx);
455 if (LR && LR->valno == ValNo && !Processed.count(LR)) {
456 After.push_back(std::make_pair(LR->start, LR->end));
457 if (CurrLI->isKill(ValNo, LR->end))
458 AfterKills.push_back(LR->end);
459 Idx = LIs->getMBBEndIdx(MBB);
460 if (LR->end > Idx) {
Evan Chengd0e32c52008-10-29 05:06:14 +0000461 // Live range extend beyond at least one mbb. Let's see what other
462 // mbbs it reaches.
463 LIs->findReachableMBBs(LR->start, LR->end, WorkList);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000464 }
465 Processed.insert(LR);
466 }
Owen Anderson75c99c52008-12-07 05:33:18 +0000467
468 ProcessedBlocks.insert(MBB);
469 if (LR)
470 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
471 SE = MBB->succ_end(); SI != SE; ++SI)
472 if (!ProcessedBlocks.count(*SI))
473 WorkList.push_back(*SI);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000474 }
475
476 for (LiveInterval::iterator I = CurrLI->begin(), E = CurrLI->end();
477 I != E; ++I) {
478 LiveRange *LR = I;
479 if (LR->valno == ValNo && !Processed.count(LR)) {
480 Before.push_back(std::make_pair(LR->start, LR->end));
481 if (CurrLI->isKill(ValNo, LR->end))
482 BeforeKills.push_back(LR->end);
483 }
484 }
485
486 // Now create new val#s to represent the live ranges defined by the old def
487 // those defined by the restore.
488 unsigned AfterDef = ValNo->def;
489 MachineInstr *AfterCopy = ValNo->copy;
490 bool HasPHIKill = ValNo->hasPHIKill;
491 CurrLI->removeValNo(ValNo);
Evan Cheng06587492008-10-24 02:05:00 +0000492 VNInfo *BValNo = (Before.empty())
493 ? NULL
494 : CurrLI->getNextValue(AfterDef, AfterCopy, LIs->getVNInfoAllocator());
495 if (BValNo)
496 CurrLI->addKills(BValNo, BeforeKills);
497
498 VNInfo *AValNo = (After.empty())
499 ? NULL
Evan Chengd0e32c52008-10-29 05:06:14 +0000500 : CurrLI->getNextValue(RestoreIndex, 0, LIs->getVNInfoAllocator());
Evan Cheng06587492008-10-24 02:05:00 +0000501 if (AValNo) {
502 AValNo->hasPHIKill = HasPHIKill;
503 CurrLI->addKills(AValNo, AfterKills);
504 }
Evan Chengf5cd4f02008-10-23 20:43:13 +0000505
506 for (unsigned i = 0, e = Before.size(); i != e; ++i) {
507 unsigned Start = Before[i].first;
508 unsigned End = Before[i].second;
509 CurrLI->addRange(LiveRange(Start, End, BValNo));
510 }
511 for (unsigned i = 0, e = After.size(); i != e; ++i) {
512 unsigned Start = After[i].first;
513 unsigned End = After[i].second;
514 CurrLI->addRange(LiveRange(Start, End, AValNo));
515 }
Owen Anderson25dffa72008-12-17 22:06:59 +0000516
517 return AValNo;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000518}
519
520/// ShrinkWrapToLastUse - There are uses of the current live interval in the
521/// given block, shrink wrap the live interval to the last use (i.e. remove
522/// from last use to the end of the mbb). In case mbb is the where the barrier
523/// is, remove from the last use to the barrier.
524bool
Evan Chengd0e32c52008-10-29 05:06:14 +0000525PreAllocSplitting::ShrinkWrapToLastUse(MachineBasicBlock *MBB, VNInfo *ValNo,
Evan Cheng06587492008-10-24 02:05:00 +0000526 SmallVector<MachineOperand*, 4> &Uses,
527 SmallPtrSet<MachineInstr*, 4> &UseMIs) {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000528 MachineOperand *LastMO = 0;
529 MachineInstr *LastMI = 0;
530 if (MBB != BarrierMBB && Uses.size() == 1) {
531 // Single use, no need to traverse the block. We can't assume this for the
532 // barrier bb though since the use is probably below the barrier.
533 LastMO = Uses[0];
534 LastMI = LastMO->getParent();
535 } else {
Evan Cheng2efe3fd2008-10-24 05:53:44 +0000536 MachineBasicBlock::iterator MEE = MBB->begin();
Evan Chengf5cd4f02008-10-23 20:43:13 +0000537 MachineBasicBlock::iterator MII;
Evan Cheng2efe3fd2008-10-24 05:53:44 +0000538 if (MBB == BarrierMBB)
Evan Chengf5cd4f02008-10-23 20:43:13 +0000539 MII = Barrier;
Evan Cheng2efe3fd2008-10-24 05:53:44 +0000540 else
Evan Chengf5cd4f02008-10-23 20:43:13 +0000541 MII = MBB->end();
Evan Chengd0e32c52008-10-29 05:06:14 +0000542 while (MII != MEE) {
543 --MII;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000544 MachineInstr *UseMI = &*MII;
545 if (!UseMIs.count(UseMI))
546 continue;
547 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
548 MachineOperand &MO = UseMI->getOperand(i);
549 if (MO.isReg() && MO.getReg() == CurrLI->reg) {
550 LastMO = &MO;
551 break;
552 }
553 }
554 LastMI = UseMI;
555 break;
556 }
557 }
558
559 // Cut off live range from last use (or beginning of the mbb if there
560 // are no uses in it) to the end of the mbb.
561 unsigned RangeStart, RangeEnd = LIs->getMBBEndIdx(MBB)+1;
562 if (LastMI) {
563 RangeStart = LIs->getUseIndex(LIs->getInstructionIndex(LastMI))+1;
564 assert(!LastMO->isKill() && "Last use already terminates the interval?");
565 LastMO->setIsKill();
566 } else {
567 assert(MBB == BarrierMBB);
568 RangeStart = LIs->getMBBStartIdx(MBB);
569 }
570 if (MBB == BarrierMBB)
Evan Cheng06587492008-10-24 02:05:00 +0000571 RangeEnd = LIs->getUseIndex(BarrierIdx)+1;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000572 CurrLI->removeRange(RangeStart, RangeEnd);
Evan Chengd0e32c52008-10-29 05:06:14 +0000573 if (LastMI)
574 CurrLI->addKill(ValNo, RangeStart);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000575
576 // Return true if the last use becomes a new kill.
577 return LastMI;
578}
579
580/// ShrinkWrapLiveInterval - Recursively traverse the predecessor
581/// chain to find the new 'kills' and shrink wrap the live interval to the
582/// new kill indices.
583void
Evan Chengaaf510c2008-10-26 07:49:03 +0000584PreAllocSplitting::ShrinkWrapLiveInterval(VNInfo *ValNo, MachineBasicBlock *MBB,
585 MachineBasicBlock *SuccMBB, MachineBasicBlock *DefMBB,
Evan Cheng06587492008-10-24 02:05:00 +0000586 SmallPtrSet<MachineBasicBlock*, 8> &Visited,
587 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > &Uses,
588 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > &UseMIs,
589 SmallVector<MachineBasicBlock*, 4> &UseMBBs) {
Evan Chengaaf510c2008-10-26 07:49:03 +0000590 if (Visited.count(MBB))
Evan Chengf5cd4f02008-10-23 20:43:13 +0000591 return;
592
Evan Chengaaf510c2008-10-26 07:49:03 +0000593 // If live interval is live in another successor path, then we can't process
594 // this block. But we may able to do so after all the successors have been
595 // processed.
Evan Chengf62ce372008-10-28 00:47:49 +0000596 if (MBB != BarrierMBB) {
597 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
598 SE = MBB->succ_end(); SI != SE; ++SI) {
599 MachineBasicBlock *SMBB = *SI;
600 if (SMBB == SuccMBB)
601 continue;
602 if (CurrLI->liveAt(LIs->getMBBStartIdx(SMBB)))
603 return;
604 }
Evan Chengaaf510c2008-10-26 07:49:03 +0000605 }
606
607 Visited.insert(MBB);
608
Evan Cheng06587492008-10-24 02:05:00 +0000609 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
610 UMII = Uses.find(MBB);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000611 if (UMII != Uses.end()) {
612 // At least one use in this mbb, lets look for the kill.
Evan Cheng06587492008-10-24 02:05:00 +0000613 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
614 UMII2 = UseMIs.find(MBB);
Evan Chengd0e32c52008-10-29 05:06:14 +0000615 if (ShrinkWrapToLastUse(MBB, ValNo, UMII->second, UMII2->second))
Evan Chengf5cd4f02008-10-23 20:43:13 +0000616 // Found a kill, shrink wrapping of this path ends here.
617 return;
Evan Cheng06587492008-10-24 02:05:00 +0000618 } else if (MBB == DefMBB) {
Evan Cheng06587492008-10-24 02:05:00 +0000619 // There are no uses after the def.
620 MachineInstr *DefMI = LIs->getInstructionFromIndex(ValNo->def);
Evan Cheng06587492008-10-24 02:05:00 +0000621 if (UseMBBs.empty()) {
622 // The only use must be below barrier in the barrier block. It's safe to
623 // remove the def.
624 LIs->RemoveMachineInstrFromMaps(DefMI);
625 DefMI->eraseFromParent();
626 CurrLI->removeRange(ValNo->def, LIs->getMBBEndIdx(MBB)+1);
627 }
Evan Cheng79d5b5a2008-10-25 23:49:39 +0000628 } else if (MBB == BarrierMBB) {
629 // Remove entire live range from start of mbb to barrier.
630 CurrLI->removeRange(LIs->getMBBStartIdx(MBB),
631 LIs->getUseIndex(BarrierIdx)+1);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000632 } else {
Evan Cheng79d5b5a2008-10-25 23:49:39 +0000633 // Remove entire live range of the mbb out of the live interval.
Evan Cheng06587492008-10-24 02:05:00 +0000634 CurrLI->removeRange(LIs->getMBBStartIdx(MBB), LIs->getMBBEndIdx(MBB)+1);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000635 }
636
637 if (MBB == DefMBB)
638 // Reached the def mbb, stop traversing this path further.
639 return;
640
641 // Traverse the pathes up the predecessor chains further.
642 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
643 PE = MBB->pred_end(); PI != PE; ++PI) {
644 MachineBasicBlock *Pred = *PI;
645 if (Pred == MBB)
646 continue;
647 if (Pred == DefMBB && ValNo->hasPHIKill)
648 // Pred is the def bb and the def reaches other val#s, we must
649 // allow the value to be live out of the bb.
650 continue;
Owen Anderson80fe8732008-11-11 22:11:27 +0000651 if (!CurrLI->liveAt(LIs->getMBBEndIdx(Pred)-1))
652 return;
Evan Chengaaf510c2008-10-26 07:49:03 +0000653 ShrinkWrapLiveInterval(ValNo, Pred, MBB, DefMBB, Visited,
654 Uses, UseMIs, UseMBBs);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000655 }
656
657 return;
658}
659
Owen Anderson75fa96b2008-11-19 04:28:29 +0000660
Owen Anderson6002e992008-12-04 21:20:30 +0000661void PreAllocSplitting::RepairLiveInterval(LiveInterval* CurrLI,
662 VNInfo* ValNo,
663 MachineInstr* DefMI,
664 unsigned RestoreIdx) {
Owen Anderson75fa96b2008-11-19 04:28:29 +0000665 // Shrink wrap the live interval by walking up the CFG and find the
666 // new kills.
667 // Now let's find all the uses of the val#.
668 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > Uses;
669 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > UseMIs;
670 SmallPtrSet<MachineBasicBlock*, 4> Seen;
671 SmallVector<MachineBasicBlock*, 4> UseMBBs;
672 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(CurrLI->reg),
673 UE = MRI->use_end(); UI != UE; ++UI) {
674 MachineOperand &UseMO = UI.getOperand();
675 MachineInstr *UseMI = UseMO.getParent();
676 unsigned UseIdx = LIs->getInstructionIndex(UseMI);
677 LiveInterval::iterator ULR = CurrLI->FindLiveRangeContaining(UseIdx);
678 if (ULR->valno != ValNo)
679 continue;
680 MachineBasicBlock *UseMBB = UseMI->getParent();
681 // Remember which other mbb's use this val#.
682 if (Seen.insert(UseMBB) && UseMBB != BarrierMBB)
683 UseMBBs.push_back(UseMBB);
684 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
685 UMII = Uses.find(UseMBB);
686 if (UMII != Uses.end()) {
687 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
688 UMII2 = UseMIs.find(UseMBB);
689 UMII->second.push_back(&UseMO);
690 UMII2->second.insert(UseMI);
691 } else {
692 SmallVector<MachineOperand*, 4> Ops;
693 Ops.push_back(&UseMO);
694 Uses.insert(std::make_pair(UseMBB, Ops));
695 SmallPtrSet<MachineInstr*, 4> MIs;
696 MIs.insert(UseMI);
697 UseMIs.insert(std::make_pair(UseMBB, MIs));
698 }
699 }
700
701 // Walk up the predecessor chains.
702 SmallPtrSet<MachineBasicBlock*, 8> Visited;
703 ShrinkWrapLiveInterval(ValNo, BarrierMBB, NULL, DefMI->getParent(), Visited,
704 Uses, UseMIs, UseMBBs);
705
Owen Anderson75fa96b2008-11-19 04:28:29 +0000706 // Remove live range from barrier to the restore. FIXME: Find a better
707 // point to re-start the live interval.
Owen Anderson25dffa72008-12-17 22:06:59 +0000708 VNInfo* AfterValNo = UpdateRegisterInterval(ValNo,
709 LIs->getUseIndex(BarrierIdx)+1,
710 LIs->getDefIndex(RestoreIdx));
711 // Attempt to renumber the new valno into a new vreg.
712 if (!AfterValNo->hasPHIKill)
713 RenumberValno(AfterValNo);
Owen Anderson6002e992008-12-04 21:20:30 +0000714}
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000715
716/// RenumberValno - Split the given valno out into a new vreg, allowing it to
717/// be allocated to a different register. This function creates a new vreg,
718/// copies the valno and its live ranges over to the new vreg's interval,
719/// removes them from the old interval, and rewrites all uses and defs of
720/// the original reg to the new vreg within those ranges.
721void PreAllocSplitting::RenumberValno(VNInfo* VN) {
722 // Create the new vreg
723 unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
724
Owen Anderson25dffa72008-12-17 22:06:59 +0000725 // Create the new live interval
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000726 LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
Owen Anderson25dffa72008-12-17 22:06:59 +0000727 SmallVector<VNInfo*, 4> VNsToCopy;
728 VNsToCopy.push_back(VN);
729
730 // Walk through and copy the valno we care about, and any other valnos
731 // that are two-address redefinitions of the one we care about. These
732 // will need to be rewritten as well.
733 while (!VNsToCopy.empty()) {
734 VNInfo* OldVN = VNsToCopy.back();
735 VNsToCopy.pop_back();
736
737 // Copy the valno over
738 VNInfo* NewVN = NewLI.getNextValue(OldVN->def, OldVN->copy,
739 LIs->getVNInfoAllocator());
740 NewLI.copyValNumInfo(NewVN, OldVN);
741 NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
742
743 // Locate two-address redefinitions
744 for (SmallVector<unsigned, 4>::iterator KI = NewVN->kills.begin(),
745 KE = NewVN->kills.end(); KI != KE; ++KI) {
746 MachineInstr* MI = LIs->getInstructionFromIndex(*KI);
747 unsigned DefIdx = MI->findRegisterDefOperandIdx(CurrLI->reg);
748 if (DefIdx == ~0U) continue;
749 if (MI->isRegReDefinedByTwoAddr(DefIdx)) {
750 VNInfo* NextVN =
751 CurrLI->findDefinedVNInfo(LiveIntervals::getDefIndex(*KI));
752 VNsToCopy.push_back(NextVN);
753 }
754 }
755
756 // Remove the valno from the old interval
757 CurrLI->removeValNo(OldVN);
758 }
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000759
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000760
761 // Rewrite defs and uses. This is done in two stages to avoid invalidating
762 // the reg_iterator.
763 SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
764
765 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
766 E = MRI->reg_end(); I != E; ++I) {
767 MachineOperand& MO = I.getOperand();
768 unsigned InstrIdx = LIs->getInstructionIndex(&*I);
769
770 if ((MO.isUse() && NewLI.liveAt(LiveIntervals::getUseIndex(InstrIdx))) ||
771 (MO.isDef() && NewLI.liveAt(LiveIntervals::getDefIndex(InstrIdx))))
772 OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
773 }
774
775 for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
776 OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
777 MachineInstr* Inst = I->first;
778 unsigned OpIdx = I->second;
779 MachineOperand& MO = Inst->getOperand(OpIdx);
780 MO.setReg(NewVReg);
781 }
Owen Anderson25dffa72008-12-17 22:06:59 +0000782
783 NumRenumbers++;
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000784}
785
Owen Anderson6002e992008-12-04 21:20:30 +0000786bool PreAllocSplitting::Rematerialize(unsigned vreg, VNInfo* ValNo,
787 MachineInstr* DefMI,
788 MachineBasicBlock::iterator RestorePt,
789 unsigned RestoreIdx,
790 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
791 MachineBasicBlock& MBB = *RestorePt->getParent();
792
793 MachineBasicBlock::iterator KillPt = BarrierMBB->end();
794 unsigned KillIdx = 0;
795 if (ValNo->def == ~0U || DefMI->getParent() == BarrierMBB)
796 KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, KillIdx);
797 else
798 KillPt = findNextEmptySlot(DefMI->getParent(), DefMI, KillIdx);
799
800 if (KillPt == DefMI->getParent()->end())
801 return false;
802
803 TII->reMaterialize(MBB, RestorePt, vreg, DefMI);
804 LIs->InsertMachineInstrInMaps(prior(RestorePt), RestoreIdx);
805
806 if (KillPt->getParent() == BarrierMBB) {
807 UpdateRegisterInterval(ValNo, LIs->getUseIndex(KillIdx)+1,
808 LIs->getDefIndex(RestoreIdx));
809
810 ++NumSplits;
811 ++NumRemats;
812 return true;
813 }
814
815 RepairLiveInterval(CurrLI, ValNo, DefMI, RestoreIdx);
Owen Anderson75fa96b2008-11-19 04:28:29 +0000816
817 ++NumSplits;
818 ++NumRemats;
Owen Anderson7b9d67c2008-12-02 18:53:47 +0000819 return true;
820}
821
822MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg,
823 const TargetRegisterClass* RC,
824 MachineInstr* DefMI,
825 MachineInstr* Barrier,
826 MachineBasicBlock* MBB,
827 int& SS,
828 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
829 MachineBasicBlock::iterator Pt = MBB->begin();
830
831 // Go top down if RefsInMBB is empty.
832 if (RefsInMBB.empty())
833 return 0;
Owen Anderson75fa96b2008-11-19 04:28:29 +0000834
Owen Anderson7b9d67c2008-12-02 18:53:47 +0000835 MachineBasicBlock::iterator FoldPt = Barrier;
836 while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
837 !RefsInMBB.count(FoldPt))
838 --FoldPt;
839
840 int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg, false);
841 if (OpIdx == -1)
842 return 0;
843
844 SmallVector<unsigned, 1> Ops;
845 Ops.push_back(OpIdx);
846
847 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
848 return 0;
849
850 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
851 if (I != IntervalSSMap.end()) {
852 SS = I->second;
853 } else {
854 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
855
856 }
857
858 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
859 FoldPt, Ops, SS);
860
861 if (FMI) {
862 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
863 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
864 ++NumFolds;
865
866 IntervalSSMap[vreg] = SS;
867 CurrSLI = &LSs->getOrCreateInterval(SS);
868 if (CurrSLI->hasAtLeastOneValue())
869 CurrSValNo = CurrSLI->getValNumInfo(0);
870 else
871 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
872 }
873
874 return FMI;
Owen Anderson75fa96b2008-11-19 04:28:29 +0000875}
876
Evan Chengf5cd4f02008-10-23 20:43:13 +0000877/// SplitRegLiveInterval - Split (spill and restore) the given live interval
878/// so it would not cross the barrier that's being processed. Shrink wrap
879/// (minimize) the live interval to the last uses.
880bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
881 CurrLI = LI;
882
883 // Find live range where current interval cross the barrier.
884 LiveInterval::iterator LR =
885 CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
886 VNInfo *ValNo = LR->valno;
887
888 if (ValNo->def == ~1U) {
889 // Defined by a dead def? How can this be?
890 assert(0 && "Val# is defined by a dead def?");
891 abort();
892 }
893
Evan Cheng06587492008-10-24 02:05:00 +0000894 MachineInstr *DefMI = (ValNo->def != ~0U)
895 ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
Evan Cheng06587492008-10-24 02:05:00 +0000896
Owen Andersonb214c692008-11-05 00:32:13 +0000897 // If this would create a new join point, do not split.
898 if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent()))
899 return false;
900
Evan Chengf5cd4f02008-10-23 20:43:13 +0000901 // Find all references in the barrier mbb.
902 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
903 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
904 E = MRI->reg_end(); I != E; ++I) {
905 MachineInstr *RefMI = &*I;
906 if (RefMI->getParent() == BarrierMBB)
907 RefsInMBB.insert(RefMI);
908 }
909
910 // Find a point to restore the value after the barrier.
911 unsigned RestoreIndex;
912 MachineBasicBlock::iterator RestorePt =
Evan Chengf62ce372008-10-28 00:47:49 +0000913 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000914 if (RestorePt == BarrierMBB->end())
915 return false;
916
Owen Anderson75fa96b2008-11-19 04:28:29 +0000917 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
918 if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt,
919 RestoreIndex, RefsInMBB))
920 return true;
921
Evan Chengf5cd4f02008-10-23 20:43:13 +0000922 // Add a spill either before the barrier or after the definition.
Evan Cheng06587492008-10-24 02:05:00 +0000923 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000924 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000925 unsigned SpillIndex = 0;
Evan Cheng06587492008-10-24 02:05:00 +0000926 MachineInstr *SpillMI = NULL;
Evan Cheng985921e2008-10-27 23:29:28 +0000927 int SS = -1;
Evan Cheng78dfef72008-10-25 00:52:41 +0000928 if (ValNo->def == ~0U) {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000929 // If it's defined by a phi, we must split just before the barrier.
Owen Anderson7b9d67c2008-12-02 18:53:47 +0000930 if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
931 BarrierMBB, SS, RefsInMBB))) {
932 SpillIndex = LIs->getInstructionIndex(SpillMI);
933 } else {
934 MachineBasicBlock::iterator SpillPt =
935 findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
936 if (SpillPt == BarrierMBB->begin())
937 return false; // No gap to insert spill.
938 // Add spill.
939
940 SS = CreateSpillStackSlot(CurrLI->reg, RC);
941 TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
942 SpillMI = prior(SpillPt);
943 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
944 }
Evan Cheng54898932008-10-29 08:39:34 +0000945 } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
946 RestoreIndex, SpillIndex, SS)) {
Evan Cheng78dfef72008-10-25 00:52:41 +0000947 // If it's already split, just restore the value. There is no need to spill
948 // the def again.
Evan Chengd0e32c52008-10-29 05:06:14 +0000949 if (!DefMI)
950 return false; // Def is dead. Do nothing.
Owen Anderson7b9d67c2008-12-02 18:53:47 +0000951
952 if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
953 BarrierMBB, SS, RefsInMBB))) {
954 SpillIndex = LIs->getInstructionIndex(SpillMI);
Evan Cheng1f08cc22008-10-28 05:28:21 +0000955 } else {
Owen Anderson7b9d67c2008-12-02 18:53:47 +0000956 // Check if it's possible to insert a spill after the def MI.
957 MachineBasicBlock::iterator SpillPt;
958 if (DefMBB == BarrierMBB) {
959 // Add spill after the def and the last use before the barrier.
960 SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
961 RefsInMBB, SpillIndex);
962 if (SpillPt == DefMBB->begin())
963 return false; // No gap to insert spill.
964 } else {
965 SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
966 if (SpillPt == DefMBB->end())
967 return false; // No gap to insert spill.
968 }
969 // Add spill. The store instruction kills the register if def is before
970 // the barrier in the barrier block.
971 SS = CreateSpillStackSlot(CurrLI->reg, RC);
972 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
973 DefMBB == BarrierMBB, SS, RC);
974 SpillMI = prior(SpillPt);
975 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
Evan Cheng1f08cc22008-10-28 05:28:21 +0000976 }
Evan Chengf5cd4f02008-10-23 20:43:13 +0000977 }
978
Evan Cheng54898932008-10-29 08:39:34 +0000979 // Remember def instruction index to spill index mapping.
980 if (DefMI && SpillMI)
981 Def2SpillMap[ValNo->def] = SpillIndex;
982
Evan Chengf5cd4f02008-10-23 20:43:13 +0000983 // Add restore.
Evan Chengf5cd4f02008-10-23 20:43:13 +0000984 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
985 MachineInstr *LoadMI = prior(RestorePt);
986 LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
987
988 // If live interval is spilled in the same block as the barrier, just
989 // create a hole in the interval.
990 if (!DefMBB ||
Evan Cheng78dfef72008-10-25 00:52:41 +0000991 (SpillMI && SpillMI->getParent() == BarrierMBB)) {
Evan Chengd0e32c52008-10-29 05:06:14 +0000992 // Update spill stack slot live interval.
993 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
994 LIs->getDefIndex(RestoreIndex));
Evan Chengf5cd4f02008-10-23 20:43:13 +0000995
Evan Chengd0e32c52008-10-29 05:06:14 +0000996 UpdateRegisterInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
997 LIs->getDefIndex(RestoreIndex));
Evan Chengf5cd4f02008-10-23 20:43:13 +0000998
Evan Chengae7fa5b2008-10-28 01:48:24 +0000999 ++NumSplits;
Evan Chengf5cd4f02008-10-23 20:43:13 +00001000 return true;
1001 }
1002
Evan Chengd0e32c52008-10-29 05:06:14 +00001003 // Update spill stack slot live interval.
Evan Cheng54898932008-10-29 08:39:34 +00001004 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1005 LIs->getDefIndex(RestoreIndex));
Evan Chengd0e32c52008-10-29 05:06:14 +00001006
Owen Anderson6002e992008-12-04 21:20:30 +00001007 RepairLiveInterval(CurrLI, ValNo, DefMI, RestoreIndex);
Evan Chengf5cd4f02008-10-23 20:43:13 +00001008
Evan Chengae7fa5b2008-10-28 01:48:24 +00001009 ++NumSplits;
Evan Chengf5cd4f02008-10-23 20:43:13 +00001010 return true;
1011}
1012
1013/// SplitRegLiveIntervals - Split all register live intervals that cross the
1014/// barrier that's being processed.
1015bool
1016PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs) {
1017 // First find all the virtual registers whose live intervals are intercepted
1018 // by the current barrier.
1019 SmallVector<LiveInterval*, 8> Intervals;
1020 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
Evan Cheng23066282008-10-27 07:14:50 +00001021 if (TII->IgnoreRegisterClassBarriers(*RC))
1022 continue;
Evan Chengf5cd4f02008-10-23 20:43:13 +00001023 std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1024 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1025 unsigned Reg = VRs[i];
1026 if (!LIs->hasInterval(Reg))
1027 continue;
1028 LiveInterval *LI = &LIs->getInterval(Reg);
1029 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1030 // Virtual register live interval is intercepted by the barrier. We
1031 // should split and shrink wrap its interval if possible.
1032 Intervals.push_back(LI);
1033 }
1034 }
1035
1036 // Process the affected live intervals.
1037 bool Change = false;
1038 while (!Intervals.empty()) {
Evan Chengae7fa5b2008-10-28 01:48:24 +00001039 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1040 break;
Evan Chengf5cd4f02008-10-23 20:43:13 +00001041 LiveInterval *LI = Intervals.back();
1042 Intervals.pop_back();
1043 Change |= SplitRegLiveInterval(LI);
1044 }
1045
1046 return Change;
1047}
1048
Owen Andersonf1f75b12008-11-04 22:22:41 +00001049bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1050 MachineBasicBlock* DefMBB,
1051 MachineBasicBlock* BarrierMBB) {
1052 if (DefMBB == BarrierMBB)
1053 return false;
1054
1055 if (LR->valno->hasPHIKill)
1056 return false;
1057
1058 unsigned MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1059 if (LR->end < MBBEnd)
1060 return false;
1061
1062 MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1063 if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1064 return true;
1065
1066 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1067 SmallPtrSet<MachineBasicBlock*, 4> Visited;
1068 typedef std::pair<MachineBasicBlock*,
1069 MachineBasicBlock::succ_iterator> ItPair;
1070 SmallVector<ItPair, 4> Stack;
1071 Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1072
1073 while (!Stack.empty()) {
1074 ItPair P = Stack.back();
1075 Stack.pop_back();
1076
1077 MachineBasicBlock* PredMBB = P.first;
1078 MachineBasicBlock::succ_iterator S = P.second;
1079
1080 if (S == PredMBB->succ_end())
1081 continue;
1082 else if (Visited.count(*S)) {
1083 Stack.push_back(std::make_pair(PredMBB, ++S));
1084 continue;
1085 } else
Owen Andersonb214c692008-11-05 00:32:13 +00001086 Stack.push_back(std::make_pair(PredMBB, S+1));
Owen Andersonf1f75b12008-11-04 22:22:41 +00001087
1088 MachineBasicBlock* MBB = *S;
1089 Visited.insert(MBB);
1090
1091 if (MBB == BarrierMBB)
1092 return true;
1093
1094 MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1095 MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1096 MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1097 while (MDTN) {
1098 if (MDTN == DefMDTN)
1099 return true;
1100 else if (MDTN == BarrierMDTN)
1101 break;
1102 MDTN = MDTN->getIDom();
1103 }
1104
1105 MBBEnd = LIs->getMBBEndIdx(MBB);
1106 if (LR->end > MBBEnd)
1107 Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1108 }
1109
1110 return false;
1111}
1112
1113
Evan Cheng09e8ca82008-10-20 21:44:59 +00001114bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd0e32c52008-10-29 05:06:14 +00001115 CurrMF = &MF;
1116 TM = &MF.getTarget();
1117 TII = TM->getInstrInfo();
1118 MFI = MF.getFrameInfo();
1119 MRI = &MF.getRegInfo();
1120 LIs = &getAnalysis<LiveIntervals>();
1121 LSs = &getAnalysis<LiveStacks>();
Evan Chengf5cd4f02008-10-23 20:43:13 +00001122
1123 bool MadeChange = false;
1124
1125 // Make sure blocks are numbered in order.
1126 MF.RenumberBlocks();
1127
Evan Cheng54898932008-10-29 08:39:34 +00001128 MachineBasicBlock *Entry = MF.begin();
1129 SmallPtrSet<MachineBasicBlock*,16> Visited;
1130
1131 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1132 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1133 DFI != E; ++DFI) {
1134 BarrierMBB = *DFI;
1135 for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1136 E = BarrierMBB->end(); I != E; ++I) {
1137 Barrier = &*I;
1138 const TargetRegisterClass **BarrierRCs =
1139 Barrier->getDesc().getRegClassBarriers();
1140 if (!BarrierRCs)
1141 continue;
1142 BarrierIdx = LIs->getInstructionIndex(Barrier);
1143 MadeChange |= SplitRegLiveIntervals(BarrierRCs);
1144 }
1145 }
Evan Chengf5cd4f02008-10-23 20:43:13 +00001146
1147 return MadeChange;
Evan Cheng09e8ca82008-10-20 21:44:59 +00001148}