blob: f5e540dfbb45b5365ab8eaaf7c9c19f5cd55be62 [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"
Owen Anderson420dd372009-03-14 21:40:05 +000018#include "VirtRegMap.h"
Evan Cheng09e8ca82008-10-20 21:44:59 +000019#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Evan Chengd0e32c52008-10-29 05:06:14 +000020#include "llvm/CodeGen/LiveStackAnalysis.h"
Owen Andersonf1f75b12008-11-04 22:22:41 +000021#include "llvm/CodeGen/MachineDominators.h"
Evan Chengf5cd4f02008-10-23 20:43:13 +000022#include "llvm/CodeGen/MachineFrameInfo.h"
Evan Cheng09e8ca82008-10-20 21:44:59 +000023#include "llvm/CodeGen/MachineFunctionPass.h"
24#include "llvm/CodeGen/MachineLoopInfo.h"
25#include "llvm/CodeGen/MachineRegisterInfo.h"
26#include "llvm/CodeGen/Passes.h"
27#include "llvm/CodeGen/RegisterCoalescer.h"
Evan Chengf5cd4f02008-10-23 20:43:13 +000028#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng09e8ca82008-10-20 21:44:59 +000029#include "llvm/Target/TargetMachine.h"
30#include "llvm/Target/TargetOptions.h"
31#include "llvm/Target/TargetRegisterInfo.h"
32#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/Debug.h"
Evan Chengd0e32c52008-10-29 05:06:14 +000034#include "llvm/ADT/DenseMap.h"
Evan Cheng54898932008-10-29 08:39:34 +000035#include "llvm/ADT/DepthFirstIterator.h"
Evan Cheng09e8ca82008-10-20 21:44:59 +000036#include "llvm/ADT/SmallPtrSet.h"
Evan Chengf5cd4f02008-10-23 20:43:13 +000037#include "llvm/ADT/Statistic.h"
Evan Cheng09e8ca82008-10-20 21:44:59 +000038using namespace llvm;
39
Evan Chengae7fa5b2008-10-28 01:48:24 +000040static cl::opt<int> PreSplitLimit("pre-split-limit", cl::init(-1), cl::Hidden);
Owen Anderson45e68552009-01-29 05:28:55 +000041static cl::opt<int> DeadSplitLimit("dead-split-limit", cl::init(-1), cl::Hidden);
Owen Anderson323c58d2009-03-05 07:19:18 +000042static cl::opt<int> RestoreFoldLimit("restore-fold-limit", cl::init(-1), cl::Hidden);
Evan Chengae7fa5b2008-10-28 01:48:24 +000043
Owen Anderson45e68552009-01-29 05:28:55 +000044STATISTIC(NumSplits, "Number of intervals split");
Owen Anderson75fa96b2008-11-19 04:28:29 +000045STATISTIC(NumRemats, "Number of intervals split by rematerialization");
Owen Anderson7b9d67c2008-12-02 18:53:47 +000046STATISTIC(NumFolds, "Number of intervals split with spill folding");
Owen Anderson323c58d2009-03-05 07:19:18 +000047STATISTIC(NumRestoreFolds, "Number of intervals split with restore folding");
Owen Anderson2ebf63f2008-12-18 01:27:19 +000048STATISTIC(NumRenumbers, "Number of intervals renumbered into new registers");
Owen Anderson956ec272009-01-23 00:23:32 +000049STATISTIC(NumDeadSpills, "Number of dead spills removed");
Evan Chengf5cd4f02008-10-23 20:43:13 +000050
Evan Cheng09e8ca82008-10-20 21:44:59 +000051namespace {
52 class VISIBILITY_HIDDEN PreAllocSplitting : public MachineFunctionPass {
Evan Chengd0e32c52008-10-29 05:06:14 +000053 MachineFunction *CurrMF;
Evan Chengf5cd4f02008-10-23 20:43:13 +000054 const TargetMachine *TM;
55 const TargetInstrInfo *TII;
Owen Anderson3ef45492009-01-29 22:13:06 +000056 const TargetRegisterInfo* TRI;
Evan Chengf5cd4f02008-10-23 20:43:13 +000057 MachineFrameInfo *MFI;
58 MachineRegisterInfo *MRI;
59 LiveIntervals *LIs;
Evan Chengd0e32c52008-10-29 05:06:14 +000060 LiveStacks *LSs;
Owen Anderson420dd372009-03-14 21:40:05 +000061 VirtRegMap *VRM;
Evan Cheng09e8ca82008-10-20 21:44:59 +000062
Evan Chengf5cd4f02008-10-23 20:43:13 +000063 // Barrier - Current barrier being processed.
64 MachineInstr *Barrier;
65
66 // BarrierMBB - Basic block where the barrier resides in.
67 MachineBasicBlock *BarrierMBB;
68
69 // Barrier - Current barrier index.
70 unsigned BarrierIdx;
71
72 // CurrLI - Current live interval being split.
73 LiveInterval *CurrLI;
74
Evan Chengd0e32c52008-10-29 05:06:14 +000075 // CurrSLI - Current stack slot live interval.
76 LiveInterval *CurrSLI;
77
78 // CurrSValNo - Current val# for the stack slot live interval.
79 VNInfo *CurrSValNo;
80
81 // IntervalSSMap - A map from live interval to spill slots.
82 DenseMap<unsigned, int> IntervalSSMap;
Evan Chengf5cd4f02008-10-23 20:43:13 +000083
Evan Cheng54898932008-10-29 08:39:34 +000084 // Def2SpillMap - A map from a def instruction index to spill index.
85 DenseMap<unsigned, unsigned> Def2SpillMap;
Evan Cheng06587492008-10-24 02:05:00 +000086
Evan Cheng09e8ca82008-10-20 21:44:59 +000087 public:
88 static char ID;
89 PreAllocSplitting() : MachineFunctionPass(&ID) {}
90
91 virtual bool runOnMachineFunction(MachineFunction &MF);
92
93 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
94 AU.addRequired<LiveIntervals>();
95 AU.addPreserved<LiveIntervals>();
Evan Chengd0e32c52008-10-29 05:06:14 +000096 AU.addRequired<LiveStacks>();
97 AU.addPreserved<LiveStacks>();
Evan Cheng09e8ca82008-10-20 21:44:59 +000098 AU.addPreserved<RegisterCoalescer>();
99 if (StrongPHIElim)
100 AU.addPreservedID(StrongPHIEliminationID);
101 else
102 AU.addPreservedID(PHIEliminationID);
Owen Andersonf1f75b12008-11-04 22:22:41 +0000103 AU.addRequired<MachineDominatorTree>();
104 AU.addRequired<MachineLoopInfo>();
Owen Anderson420dd372009-03-14 21:40:05 +0000105 AU.addRequired<VirtRegMap>();
Owen Andersonf1f75b12008-11-04 22:22:41 +0000106 AU.addPreserved<MachineDominatorTree>();
107 AU.addPreserved<MachineLoopInfo>();
Owen Anderson420dd372009-03-14 21:40:05 +0000108 AU.addPreserved<VirtRegMap>();
Evan Cheng09e8ca82008-10-20 21:44:59 +0000109 MachineFunctionPass::getAnalysisUsage(AU);
110 }
111
112 virtual void releaseMemory() {
Evan Chengd0e32c52008-10-29 05:06:14 +0000113 IntervalSSMap.clear();
Evan Cheng54898932008-10-29 08:39:34 +0000114 Def2SpillMap.clear();
Evan Cheng09e8ca82008-10-20 21:44:59 +0000115 }
116
117 virtual const char *getPassName() const {
118 return "Pre-Register Allocaton Live Interval Splitting";
119 }
Evan Chengf5cd4f02008-10-23 20:43:13 +0000120
121 /// print - Implement the dump method.
122 virtual void print(std::ostream &O, const Module* M = 0) const {
123 LIs->print(O, M);
124 }
125
126 void print(std::ostream *O, const Module* M = 0) const {
127 if (O) print(*O, M);
128 }
129
130 private:
131 MachineBasicBlock::iterator
132 findNextEmptySlot(MachineBasicBlock*, MachineInstr*,
133 unsigned&);
134
135 MachineBasicBlock::iterator
Evan Cheng1f08cc22008-10-28 05:28:21 +0000136 findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
Evan Chengf5cd4f02008-10-23 20:43:13 +0000137 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
138
139 MachineBasicBlock::iterator
Evan Chengf62ce372008-10-28 00:47:49 +0000140 findRestorePoint(MachineBasicBlock*, MachineInstr*, unsigned,
Evan Chengf5cd4f02008-10-23 20:43:13 +0000141 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
142
Evan Chengd0e32c52008-10-29 05:06:14 +0000143 int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000144
Evan Cheng54898932008-10-29 08:39:34 +0000145 bool IsAvailableInStack(MachineBasicBlock*, unsigned, unsigned, unsigned,
146 unsigned&, int&) const;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000147
Evan Chengd0e32c52008-10-29 05:06:14 +0000148 void UpdateSpillSlotInterval(VNInfo*, unsigned, unsigned);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000149
Evan Chengf5cd4f02008-10-23 20:43:13 +0000150 bool SplitRegLiveInterval(LiveInterval*);
151
Owen Anderson956ec272009-01-23 00:23:32 +0000152 bool SplitRegLiveIntervals(const TargetRegisterClass **,
153 SmallPtrSet<LiveInterval*, 8>&);
Owen Andersonf1f75b12008-11-04 22:22:41 +0000154
155 bool createsNewJoin(LiveRange* LR, MachineBasicBlock* DefMBB,
156 MachineBasicBlock* BarrierMBB);
Owen Anderson75fa96b2008-11-19 04:28:29 +0000157 bool Rematerialize(unsigned vreg, VNInfo* ValNo,
158 MachineInstr* DefMI,
159 MachineBasicBlock::iterator RestorePt,
160 unsigned RestoreIdx,
161 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
Owen Anderson7b9d67c2008-12-02 18:53:47 +0000162 MachineInstr* FoldSpill(unsigned vreg, const TargetRegisterClass* RC,
163 MachineInstr* DefMI,
164 MachineInstr* Barrier,
165 MachineBasicBlock* MBB,
166 int& SS,
167 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
Owen Andersonc93023a2009-03-04 08:52:31 +0000168 MachineInstr* FoldRestore(unsigned vreg,
169 const TargetRegisterClass* RC,
170 MachineInstr* Barrier,
171 MachineBasicBlock* MBB,
172 int SS,
173 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000174 void RenumberValno(VNInfo* VN);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000175 void ReconstructLiveInterval(LiveInterval* LI);
Owen Anderson956ec272009-01-23 00:23:32 +0000176 bool removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split);
Owen Anderson45e68552009-01-29 05:28:55 +0000177 unsigned getNumberOfNonSpills(SmallPtrSet<MachineInstr*, 4>& MIs,
178 unsigned Reg, int FrameIndex, bool& TwoAddr);
Evan Cheng19a72582009-02-02 18:33:18 +0000179 VNInfo* PerformPHIConstruction(MachineBasicBlock::iterator Use,
180 MachineBasicBlock* MBB, LiveInterval* LI,
Owen Anderson200ee7f2009-01-06 07:53:32 +0000181 SmallPtrSet<MachineInstr*, 4>& Visited,
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000182 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
183 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
184 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
Owen Anderson7d211e22008-12-31 02:00:25 +0000185 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
186 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
Evan Cheng19a72582009-02-02 18:33:18 +0000187 bool IsTopLevel, bool IsIntraBlock);
188 VNInfo* PerformPHIConstructionFallBack(MachineBasicBlock::iterator Use,
189 MachineBasicBlock* MBB, LiveInterval* LI,
190 SmallPtrSet<MachineInstr*, 4>& Visited,
191 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
192 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
193 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
194 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
195 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
196 bool IsTopLevel, bool IsIntraBlock);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000197};
Evan Cheng09e8ca82008-10-20 21:44:59 +0000198} // end anonymous namespace
199
200char PreAllocSplitting::ID = 0;
201
202static RegisterPass<PreAllocSplitting>
203X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
204
205const PassInfo *const llvm::PreAllocSplittingID = &X;
206
Evan Chengf5cd4f02008-10-23 20:43:13 +0000207
208/// findNextEmptySlot - Find a gap after the given machine instruction in the
209/// instruction index map. If there isn't one, return end().
210MachineBasicBlock::iterator
211PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
212 unsigned &SpotIndex) {
213 MachineBasicBlock::iterator MII = MI;
214 if (++MII != MBB->end()) {
215 unsigned Index = LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
216 if (Index) {
217 SpotIndex = Index;
218 return MII;
219 }
220 }
221 return MBB->end();
222}
223
224/// findSpillPoint - Find a gap as far away from the given MI that's suitable
225/// for spilling the current live interval. The index must be before any
226/// defs and uses of the live interval register in the mbb. Return begin() if
227/// none is found.
228MachineBasicBlock::iterator
229PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
Evan Cheng1f08cc22008-10-28 05:28:21 +0000230 MachineInstr *DefMI,
Evan Chengf5cd4f02008-10-23 20:43:13 +0000231 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
232 unsigned &SpillIndex) {
233 MachineBasicBlock::iterator Pt = MBB->begin();
234
235 // Go top down if RefsInMBB is empty.
Evan Cheng1f08cc22008-10-28 05:28:21 +0000236 if (RefsInMBB.empty() && !DefMI) {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000237 MachineBasicBlock::iterator MII = MBB->begin();
238 MachineBasicBlock::iterator EndPt = MI;
Owen Anderson4cafbb52009-02-20 10:02:23 +0000239
240 if (MII == EndPt) return Pt;
241
Evan Chengf5cd4f02008-10-23 20:43:13 +0000242 do {
243 ++MII;
244 unsigned Index = LIs->getInstructionIndex(MII);
245 unsigned Gap = LIs->findGapBeforeInstr(Index);
Owen Anderson5734c942009-02-05 05:58:41 +0000246
247 // We can't insert the spill between the barrier (a call), and its
248 // corresponding call frame setup/teardown.
249 if (prior(MII)->getOpcode() == TRI->getCallFrameSetupOpcode()) {
250 bool reachedBarrier = false;
251 do {
252 if (MII == EndPt) {
253 reachedBarrier = true;
254 break;
255 }
256 ++MII;
257 } while (MII->getOpcode() != TRI->getCallFrameDestroyOpcode());
258
259 if (reachedBarrier) break;
260 } else if (Gap) {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000261 Pt = MII;
262 SpillIndex = Gap;
263 break;
Owen Anderson5734c942009-02-05 05:58:41 +0000264 }
Evan Chengf5cd4f02008-10-23 20:43:13 +0000265 } while (MII != EndPt);
266 } else {
267 MachineBasicBlock::iterator MII = MI;
Evan Cheng1f08cc22008-10-28 05:28:21 +0000268 MachineBasicBlock::iterator EndPt = DefMI
269 ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
Owen Anderson3ef45492009-01-29 22:13:06 +0000270
Evan Cheng1f08cc22008-10-28 05:28:21 +0000271 while (MII != EndPt && !RefsInMBB.count(MII)) {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000272 unsigned Index = LIs->getInstructionIndex(MII);
Owen Anderson5734c942009-02-05 05:58:41 +0000273
274 // We can't insert the spill between the barrier (a call), and its
275 // corresponding call frame setup.
276 if (prior(MII)->getOpcode() == TRI->getCallFrameSetupOpcode()) {
277 --MII;
278 continue;
279 } if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
280 bool reachedBarrier = false;
281 while (MII->getOpcode() != TRI->getCallFrameSetupOpcode()) {
282 --MII;
283 if (MII == EndPt) {
284 reachedBarrier = true;
285 break;
286 }
287 }
288
289 if (reachedBarrier) break;
290 else continue;
291 } else if (LIs->hasGapBeforeInstr(Index)) {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000292 Pt = MII;
293 SpillIndex = LIs->findGapBeforeInstr(Index, true);
294 }
295 --MII;
296 }
297 }
298
299 return Pt;
300}
301
302/// findRestorePoint - Find a gap in the instruction index map that's suitable
303/// for restoring the current live interval value. The index must be before any
304/// uses of the live interval register in the mbb. Return end() if none is
305/// found.
306MachineBasicBlock::iterator
307PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
Evan Chengf62ce372008-10-28 00:47:49 +0000308 unsigned LastIdx,
Evan Chengf5cd4f02008-10-23 20:43:13 +0000309 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
310 unsigned &RestoreIndex) {
Evan Cheng54898932008-10-29 08:39:34 +0000311 // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
312 // begin index accordingly.
Owen Anderson5a92d4e2008-11-18 20:53:59 +0000313 MachineBasicBlock::iterator Pt = MBB->end();
Evan Chengf62ce372008-10-28 00:47:49 +0000314 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
Evan Chengf5cd4f02008-10-23 20:43:13 +0000315
Evan Chengf62ce372008-10-28 00:47:49 +0000316 // Go bottom up if RefsInMBB is empty and the end of the mbb isn't beyond
317 // the last index in the live range.
318 if (RefsInMBB.empty() && LastIdx >= EndIdx) {
Owen Anderson711fd3d2008-11-13 21:53:14 +0000319 MachineBasicBlock::iterator MII = MBB->getFirstTerminator();
Evan Chengf5cd4f02008-10-23 20:43:13 +0000320 MachineBasicBlock::iterator EndPt = MI;
Owen Anderson4cafbb52009-02-20 10:02:23 +0000321
322 if (MII == EndPt) return Pt;
323
Evan Cheng54898932008-10-29 08:39:34 +0000324 --MII;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000325 do {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000326 unsigned Index = LIs->getInstructionIndex(MII);
Evan Cheng56ab0de2008-10-24 18:46:44 +0000327 unsigned Gap = LIs->findGapBeforeInstr(Index);
Owen Anderson3ef45492009-01-29 22:13:06 +0000328
329 // We can't insert a restore between the barrier (a call) and its
330 // corresponding call frame teardown.
Owen Anderson5734c942009-02-05 05:58:41 +0000331 if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
332 bool reachedBarrier = false;
333 while (MII->getOpcode() != TRI->getCallFrameSetupOpcode()) {
334 --MII;
335 if (MII == EndPt) {
336 reachedBarrier = true;
337 break;
338 }
339 }
340
341 if (reachedBarrier) break;
342 else continue;
343 } else if (Gap) {
344 Pt = MII;
345 RestoreIndex = Gap;
Owen Anderson3ef45492009-01-29 22:13:06 +0000346 break;
Owen Anderson5734c942009-02-05 05:58:41 +0000347 }
348
Evan Cheng54898932008-10-29 08:39:34 +0000349 --MII;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000350 } while (MII != EndPt);
351 } else {
352 MachineBasicBlock::iterator MII = MI;
353 MII = ++MII;
Owen Anderson3ef45492009-01-29 22:13:06 +0000354
Evan Chengf62ce372008-10-28 00:47:49 +0000355 // FIXME: Limit the number of instructions to examine to reduce
356 // compile time?
Owen Andersonc0f3a032009-01-29 08:22:06 +0000357 while (MII != MBB->getFirstTerminator()) {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000358 unsigned Index = LIs->getInstructionIndex(MII);
Evan Chengf62ce372008-10-28 00:47:49 +0000359 if (Index > LastIdx)
360 break;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000361 unsigned Gap = LIs->findGapBeforeInstr(Index);
Owen Anderson5734c942009-02-05 05:58:41 +0000362
363 // We can't insert a restore between the barrier (a call) and its
364 // corresponding call frame teardown.
365 if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
366 ++MII;
367 continue;
368 } else if (prior(MII)->getOpcode() == TRI->getCallFrameSetupOpcode()) {
369 bool reachedBarrier = false;
370 do {
371 if (MII == MBB->getFirstTerminator() || RefsInMBB.count(MII)) {
372 reachedBarrier = true;
373 break;
374 }
375
376 ++MII;
377 } while (MII->getOpcode() != TRI->getCallFrameDestroyOpcode());
378
379 if (reachedBarrier) break;
380 } else if (Gap) {
Evan Chengf5cd4f02008-10-23 20:43:13 +0000381 Pt = MII;
382 RestoreIndex = Gap;
383 }
Owen Anderson5734c942009-02-05 05:58:41 +0000384
Evan Chengf5cd4f02008-10-23 20:43:13 +0000385 if (RefsInMBB.count(MII))
386 break;
387 ++MII;
388 }
389 }
390
391 return Pt;
392}
393
Evan Chengd0e32c52008-10-29 05:06:14 +0000394/// CreateSpillStackSlot - Create a stack slot for the live interval being
395/// split. If the live interval was previously split, just reuse the same
396/// slot.
397int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
398 const TargetRegisterClass *RC) {
399 int SS;
400 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
401 if (I != IntervalSSMap.end()) {
402 SS = I->second;
403 } else {
404 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
405 IntervalSSMap[Reg] = SS;
Evan Cheng06587492008-10-24 02:05:00 +0000406 }
Evan Chengd0e32c52008-10-29 05:06:14 +0000407
408 // Create live interval for stack slot.
409 CurrSLI = &LSs->getOrCreateInterval(SS);
Evan Cheng54898932008-10-29 08:39:34 +0000410 if (CurrSLI->hasAtLeastOneValue())
Evan Chengd0e32c52008-10-29 05:06:14 +0000411 CurrSValNo = CurrSLI->getValNumInfo(0);
412 else
413 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
414 return SS;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000415}
416
Evan Chengd0e32c52008-10-29 05:06:14 +0000417/// IsAvailableInStack - Return true if register is available in a split stack
418/// slot at the specified index.
419bool
Evan Cheng54898932008-10-29 08:39:34 +0000420PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
421 unsigned Reg, unsigned DefIndex,
422 unsigned RestoreIndex, unsigned &SpillIndex,
423 int& SS) const {
424 if (!DefMBB)
425 return false;
426
Evan Chengd0e32c52008-10-29 05:06:14 +0000427 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
428 if (I == IntervalSSMap.end())
Evan Chengf5cd4f02008-10-23 20:43:13 +0000429 return false;
Evan Cheng54898932008-10-29 08:39:34 +0000430 DenseMap<unsigned, unsigned>::iterator II = Def2SpillMap.find(DefIndex);
431 if (II == Def2SpillMap.end())
432 return false;
433
434 // If last spill of def is in the same mbb as barrier mbb (where restore will
435 // be), make sure it's not below the intended restore index.
436 // FIXME: Undo the previous spill?
437 assert(LIs->getMBBFromIndex(II->second) == DefMBB);
438 if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
439 return false;
440
441 SS = I->second;
442 SpillIndex = II->second;
443 return true;
Evan Chengf5cd4f02008-10-23 20:43:13 +0000444}
445
Evan Chengd0e32c52008-10-29 05:06:14 +0000446/// UpdateSpillSlotInterval - Given the specified val# of the register live
447/// interval being split, and the spill and restore indicies, update the live
448/// interval of the spill stack slot.
449void
450PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, unsigned SpillIndex,
451 unsigned RestoreIndex) {
Evan Cheng54898932008-10-29 08:39:34 +0000452 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
453 "Expect restore in the barrier mbb");
454
455 MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
456 if (MBB == BarrierMBB) {
457 // Intra-block spill + restore. We are done.
Evan Chengd0e32c52008-10-29 05:06:14 +0000458 LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
459 CurrSLI->addRange(SLR);
460 return;
461 }
462
Evan Cheng54898932008-10-29 08:39:34 +0000463 SmallPtrSet<MachineBasicBlock*, 4> Processed;
464 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
465 LiveRange SLR(SpillIndex, EndIdx+1, CurrSValNo);
Evan Chengd0e32c52008-10-29 05:06:14 +0000466 CurrSLI->addRange(SLR);
Evan Cheng54898932008-10-29 08:39:34 +0000467 Processed.insert(MBB);
Evan Chengd0e32c52008-10-29 05:06:14 +0000468
469 // Start from the spill mbb, figure out the extend of the spill slot's
470 // live interval.
471 SmallVector<MachineBasicBlock*, 4> WorkList;
Evan Cheng54898932008-10-29 08:39:34 +0000472 const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
473 if (LR->end > EndIdx)
Evan Chengd0e32c52008-10-29 05:06:14 +0000474 // If live range extend beyond end of mbb, add successors to work list.
475 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
476 SE = MBB->succ_end(); SI != SE; ++SI)
477 WorkList.push_back(*SI);
Evan Chengd0e32c52008-10-29 05:06:14 +0000478
479 while (!WorkList.empty()) {
480 MachineBasicBlock *MBB = WorkList.back();
481 WorkList.pop_back();
Evan Cheng54898932008-10-29 08:39:34 +0000482 if (Processed.count(MBB))
483 continue;
Evan Chengd0e32c52008-10-29 05:06:14 +0000484 unsigned Idx = LIs->getMBBStartIdx(MBB);
485 LR = CurrLI->getLiveRangeContaining(Idx);
Evan Cheng54898932008-10-29 08:39:34 +0000486 if (LR && LR->valno == ValNo) {
487 EndIdx = LIs->getMBBEndIdx(MBB);
488 if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
Evan Chengd0e32c52008-10-29 05:06:14 +0000489 // Spill slot live interval stops at the restore.
Evan Cheng54898932008-10-29 08:39:34 +0000490 LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
Evan Chengd0e32c52008-10-29 05:06:14 +0000491 CurrSLI->addRange(SLR);
Evan Cheng54898932008-10-29 08:39:34 +0000492 } else if (LR->end > EndIdx) {
493 // Live range extends beyond end of mbb, process successors.
494 LiveRange SLR(Idx, EndIdx+1, CurrSValNo);
495 CurrSLI->addRange(SLR);
496 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
497 SE = MBB->succ_end(); SI != SE; ++SI)
498 WorkList.push_back(*SI);
Evan Chengd0e32c52008-10-29 05:06:14 +0000499 } else {
Evan Cheng54898932008-10-29 08:39:34 +0000500 LiveRange SLR(Idx, LR->end, CurrSValNo);
Evan Chengd0e32c52008-10-29 05:06:14 +0000501 CurrSLI->addRange(SLR);
Evan Chengd0e32c52008-10-29 05:06:14 +0000502 }
Evan Cheng54898932008-10-29 08:39:34 +0000503 Processed.insert(MBB);
Evan Chengd0e32c52008-10-29 05:06:14 +0000504 }
505 }
506}
507
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000508/// PerformPHIConstruction - From properly set up use and def lists, use a PHI
509/// construction algorithm to compute the ranges and valnos for an interval.
Evan Cheng19a72582009-02-02 18:33:18 +0000510VNInfo*
511PreAllocSplitting::PerformPHIConstruction(MachineBasicBlock::iterator UseI,
512 MachineBasicBlock* MBB, LiveInterval* LI,
Owen Anderson200ee7f2009-01-06 07:53:32 +0000513 SmallPtrSet<MachineInstr*, 4>& Visited,
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000514 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
515 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
516 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
Owen Anderson7d211e22008-12-31 02:00:25 +0000517 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
518 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
Evan Cheng19a72582009-02-02 18:33:18 +0000519 bool IsTopLevel, bool IsIntraBlock) {
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000520 // Return memoized result if it's available.
Evan Cheng19a72582009-02-02 18:33:18 +0000521 if (IsTopLevel && Visited.count(UseI) && NewVNs.count(UseI))
522 return NewVNs[UseI];
523 else if (!IsTopLevel && IsIntraBlock && NewVNs.count(UseI))
524 return NewVNs[UseI];
525 else if (!IsIntraBlock && LiveOut.count(MBB))
Owen Anderson7d211e22008-12-31 02:00:25 +0000526 return LiveOut[MBB];
527
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000528 // Check if our block contains any uses or defs.
Owen Anderson7d211e22008-12-31 02:00:25 +0000529 bool ContainsDefs = Defs.count(MBB);
530 bool ContainsUses = Uses.count(MBB);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000531
Evan Cheng19a72582009-02-02 18:33:18 +0000532 VNInfo* RetVNI = 0;
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000533
534 // Enumerate the cases of use/def contaning blocks.
535 if (!ContainsDefs && !ContainsUses) {
Evan Cheng19a72582009-02-02 18:33:18 +0000536 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
537 NewVNs, LiveOut, Phis,
538 IsTopLevel, IsIntraBlock);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000539 } else if (ContainsDefs && !ContainsUses) {
Owen Anderson7d211e22008-12-31 02:00:25 +0000540 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000541
542 // Search for the def in this block. If we don't find it before the
543 // instruction we care about, go to the fallback case. Note that that
Owen Anderson7d211e22008-12-31 02:00:25 +0000544 // should never happen: this cannot be intrablock, so use should
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000545 // always be an end() iterator.
Evan Cheng19a72582009-02-02 18:33:18 +0000546 assert(UseI == MBB->end() && "No use marked in intrablock");
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000547
Evan Cheng19a72582009-02-02 18:33:18 +0000548 MachineBasicBlock::iterator Walker = UseI;
549 --Walker;
550 while (Walker != MBB->begin()) {
551 if (BlockDefs.count(Walker))
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000552 break;
Evan Cheng19a72582009-02-02 18:33:18 +0000553 --Walker;
554 }
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000555
556 // Once we've found it, extend its VNInfo to our instruction.
Evan Cheng19a72582009-02-02 18:33:18 +0000557 unsigned DefIndex = LIs->getInstructionIndex(Walker);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000558 DefIndex = LiveIntervals::getDefIndex(DefIndex);
Owen Anderson7d211e22008-12-31 02:00:25 +0000559 unsigned EndIndex = LIs->getMBBEndIdx(MBB);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000560
Evan Cheng19a72582009-02-02 18:33:18 +0000561 RetVNI = NewVNs[Walker];
562 LI->addRange(LiveRange(DefIndex, EndIndex+1, RetVNI));
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000563 } else if (!ContainsDefs && ContainsUses) {
Owen Anderson7d211e22008-12-31 02:00:25 +0000564 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000565
566 // Search for the use in this block that precedes the instruction we care
Evan Cheng19a72582009-02-02 18:33:18 +0000567 // about, going to the fallback case if we don't find it.
568 if (UseI == MBB->begin())
569 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
570 Uses, NewVNs, LiveOut, Phis,
571 IsTopLevel, IsIntraBlock);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000572
Evan Cheng19a72582009-02-02 18:33:18 +0000573 MachineBasicBlock::iterator Walker = UseI;
574 --Walker;
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000575 bool found = false;
Evan Cheng19a72582009-02-02 18:33:18 +0000576 while (Walker != MBB->begin()) {
577 if (BlockUses.count(Walker)) {
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000578 found = true;
579 break;
Evan Cheng19a72582009-02-02 18:33:18 +0000580 }
581 --Walker;
582 }
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000583
584 // Must check begin() too.
Duncan Sands2b7fc1e2008-12-29 08:05:02 +0000585 if (!found) {
Evan Cheng19a72582009-02-02 18:33:18 +0000586 if (BlockUses.count(Walker))
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000587 found = true;
588 else
Evan Cheng19a72582009-02-02 18:33:18 +0000589 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
590 Uses, NewVNs, LiveOut, Phis,
591 IsTopLevel, IsIntraBlock);
Duncan Sands2b7fc1e2008-12-29 08:05:02 +0000592 }
593
Evan Cheng19a72582009-02-02 18:33:18 +0000594 unsigned UseIndex = LIs->getInstructionIndex(Walker);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000595 UseIndex = LiveIntervals::getUseIndex(UseIndex);
596 unsigned EndIndex = 0;
Evan Cheng19a72582009-02-02 18:33:18 +0000597 if (IsIntraBlock) {
598 EndIndex = LIs->getInstructionIndex(UseI);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000599 EndIndex = LiveIntervals::getUseIndex(EndIndex);
600 } else
Owen Anderson7d211e22008-12-31 02:00:25 +0000601 EndIndex = LIs->getMBBEndIdx(MBB);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000602
603 // Now, recursively phi construct the VNInfo for the use we found,
604 // and then extend it to include the instruction we care about
Evan Cheng19a72582009-02-02 18:33:18 +0000605 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
606 NewVNs, LiveOut, Phis, false, true);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000607
Evan Cheng19a72582009-02-02 18:33:18 +0000608 LI->addRange(LiveRange(UseIndex, EndIndex+1, RetVNI));
Owen Andersonb4b84362009-01-26 21:57:31 +0000609
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000610 // FIXME: Need to set kills properly for inter-block stuff.
Evan Cheng19a72582009-02-02 18:33:18 +0000611 if (LI->isKill(RetVNI, UseIndex)) LI->removeKill(RetVNI, UseIndex);
612 if (IsIntraBlock)
613 LI->addKill(RetVNI, EndIndex);
614 } else if (ContainsDefs && ContainsUses) {
Owen Anderson7d211e22008-12-31 02:00:25 +0000615 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
616 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000617
618 // This case is basically a merging of the two preceding case, with the
619 // special note that checking for defs must take precedence over checking
620 // for uses, because of two-address instructions.
621
Evan Cheng19a72582009-02-02 18:33:18 +0000622 if (UseI == MBB->begin())
623 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
624 NewVNs, LiveOut, Phis,
625 IsTopLevel, IsIntraBlock);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000626
Evan Cheng19a72582009-02-02 18:33:18 +0000627 MachineBasicBlock::iterator Walker = UseI;
628 --Walker;
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000629 bool foundDef = false;
630 bool foundUse = false;
Evan Cheng19a72582009-02-02 18:33:18 +0000631 while (Walker != MBB->begin()) {
632 if (BlockDefs.count(Walker)) {
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000633 foundDef = true;
634 break;
Evan Cheng19a72582009-02-02 18:33:18 +0000635 } else if (BlockUses.count(Walker)) {
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000636 foundUse = true;
637 break;
Evan Cheng19a72582009-02-02 18:33:18 +0000638 }
639 --Walker;
640 }
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000641
642 // Must check begin() too.
Duncan Sands2b7fc1e2008-12-29 08:05:02 +0000643 if (!foundDef && !foundUse) {
Evan Cheng19a72582009-02-02 18:33:18 +0000644 if (BlockDefs.count(Walker))
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000645 foundDef = true;
Evan Cheng19a72582009-02-02 18:33:18 +0000646 else if (BlockUses.count(Walker))
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000647 foundUse = true;
648 else
Evan Cheng19a72582009-02-02 18:33:18 +0000649 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
650 Uses, NewVNs, LiveOut, Phis,
651 IsTopLevel, IsIntraBlock);
Duncan Sands2b7fc1e2008-12-29 08:05:02 +0000652 }
653
Evan Cheng19a72582009-02-02 18:33:18 +0000654 unsigned StartIndex = LIs->getInstructionIndex(Walker);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000655 StartIndex = foundDef ? LiveIntervals::getDefIndex(StartIndex) :
656 LiveIntervals::getUseIndex(StartIndex);
657 unsigned EndIndex = 0;
Evan Cheng19a72582009-02-02 18:33:18 +0000658 if (IsIntraBlock) {
659 EndIndex = LIs->getInstructionIndex(UseI);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000660 EndIndex = LiveIntervals::getUseIndex(EndIndex);
661 } else
Owen Anderson7d211e22008-12-31 02:00:25 +0000662 EndIndex = LIs->getMBBEndIdx(MBB);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000663
664 if (foundDef)
Evan Cheng19a72582009-02-02 18:33:18 +0000665 RetVNI = NewVNs[Walker];
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000666 else
Evan Cheng19a72582009-02-02 18:33:18 +0000667 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
668 NewVNs, LiveOut, Phis, false, true);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000669
Evan Cheng19a72582009-02-02 18:33:18 +0000670 LI->addRange(LiveRange(StartIndex, EndIndex+1, RetVNI));
Owen Andersonb4b84362009-01-26 21:57:31 +0000671
Evan Cheng19a72582009-02-02 18:33:18 +0000672 if (foundUse && LI->isKill(RetVNI, StartIndex))
673 LI->removeKill(RetVNI, StartIndex);
674 if (IsIntraBlock) {
675 LI->addKill(RetVNI, EndIndex);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000676 }
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000677 }
678
679 // Memoize results so we don't have to recompute them.
Evan Cheng19a72582009-02-02 18:33:18 +0000680 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
Owen Anderson200ee7f2009-01-06 07:53:32 +0000681 else {
Evan Cheng19a72582009-02-02 18:33:18 +0000682 if (!NewVNs.count(UseI))
683 NewVNs[UseI] = RetVNI;
684 Visited.insert(UseI);
Owen Anderson200ee7f2009-01-06 07:53:32 +0000685 }
686
Evan Cheng19a72582009-02-02 18:33:18 +0000687 return RetVNI;
688}
689
690/// PerformPHIConstructionFallBack - PerformPHIConstruction fall back path.
691///
692VNInfo*
693PreAllocSplitting::PerformPHIConstructionFallBack(MachineBasicBlock::iterator UseI,
694 MachineBasicBlock* MBB, LiveInterval* LI,
695 SmallPtrSet<MachineInstr*, 4>& Visited,
696 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
697 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
698 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
699 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
700 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
701 bool IsTopLevel, bool IsIntraBlock) {
702 // NOTE: Because this is the fallback case from other cases, we do NOT
703 // assume that we are not intrablock here.
704 if (Phis.count(MBB)) return Phis[MBB];
705
706 unsigned StartIndex = LIs->getMBBStartIdx(MBB);
707 VNInfo *RetVNI = Phis[MBB] = LI->getNextValue(~0U, /*FIXME*/ 0,
708 LIs->getVNInfoAllocator());
709 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
710
711 // If there are no uses or defs between our starting point and the
712 // beginning of the block, then recursive perform phi construction
713 // on our predecessors.
714 DenseMap<MachineBasicBlock*, VNInfo*> IncomingVNs;
715 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
716 PE = MBB->pred_end(); PI != PE; ++PI) {
717 VNInfo* Incoming = PerformPHIConstruction((*PI)->end(), *PI, LI,
718 Visited, Defs, Uses, NewVNs,
719 LiveOut, Phis, false, false);
720 if (Incoming != 0)
721 IncomingVNs[*PI] = Incoming;
722 }
723
724 if (MBB->pred_size() == 1 && !RetVNI->hasPHIKill) {
Owen Anderson5b93f6f2009-02-02 22:42:01 +0000725 VNInfo* OldVN = RetVNI;
726 VNInfo* NewVN = IncomingVNs.begin()->second;
727 VNInfo* MergedVN = LI->MergeValueNumberInto(OldVN, NewVN);
728 if (MergedVN == OldVN) std::swap(OldVN, NewVN);
729
730 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator LOI = LiveOut.begin(),
731 LOE = LiveOut.end(); LOI != LOE; ++LOI)
732 if (LOI->second == OldVN)
733 LOI->second = MergedVN;
734 for (DenseMap<MachineInstr*, VNInfo*>::iterator NVI = NewVNs.begin(),
735 NVE = NewVNs.end(); NVI != NVE; ++NVI)
736 if (NVI->second == OldVN)
737 NVI->second = MergedVN;
738 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator PI = Phis.begin(),
739 PE = Phis.end(); PI != PE; ++PI)
740 if (PI->second == OldVN)
741 PI->second = MergedVN;
742 RetVNI = MergedVN;
Evan Cheng19a72582009-02-02 18:33:18 +0000743 } else {
744 // Otherwise, merge the incoming VNInfos with a phi join. Create a new
745 // VNInfo to represent the joined value.
746 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator I =
747 IncomingVNs.begin(), E = IncomingVNs.end(); I != E; ++I) {
748 I->second->hasPHIKill = true;
749 unsigned KillIndex = LIs->getMBBEndIdx(I->first);
750 if (!LiveInterval::isKill(I->second, KillIndex))
751 LI->addKill(I->second, KillIndex);
752 }
753 }
754
755 unsigned EndIndex = 0;
756 if (IsIntraBlock) {
757 EndIndex = LIs->getInstructionIndex(UseI);
758 EndIndex = LiveIntervals::getUseIndex(EndIndex);
759 } else
760 EndIndex = LIs->getMBBEndIdx(MBB);
761 LI->addRange(LiveRange(StartIndex, EndIndex+1, RetVNI));
762 if (IsIntraBlock)
763 LI->addKill(RetVNI, EndIndex);
764
765 // Memoize results so we don't have to recompute them.
766 if (!IsIntraBlock)
767 LiveOut[MBB] = RetVNI;
768 else {
769 if (!NewVNs.count(UseI))
770 NewVNs[UseI] = RetVNI;
771 Visited.insert(UseI);
772 }
773
774 return RetVNI;
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000775}
776
777/// ReconstructLiveInterval - Recompute a live interval from scratch.
778void PreAllocSplitting::ReconstructLiveInterval(LiveInterval* LI) {
779 BumpPtrAllocator& Alloc = LIs->getVNInfoAllocator();
780
781 // Clear the old ranges and valnos;
782 LI->clear();
783
784 // Cache the uses and defs of the register
785 typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
786 RegMap Defs, Uses;
787
788 // Keep track of the new VNs we're creating.
789 DenseMap<MachineInstr*, VNInfo*> NewVNs;
790 SmallPtrSet<VNInfo*, 2> PhiVNs;
791
792 // Cache defs, and create a new VNInfo for each def.
793 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
794 DE = MRI->def_end(); DI != DE; ++DI) {
795 Defs[(*DI).getParent()].insert(&*DI);
796
797 unsigned DefIdx = LIs->getInstructionIndex(&*DI);
798 DefIdx = LiveIntervals::getDefIndex(DefIdx);
799
Owen Anderson200ee7f2009-01-06 07:53:32 +0000800 VNInfo* NewVN = LI->getNextValue(DefIdx, 0, Alloc);
801
802 // If the def is a move, set the copy field.
Evan Cheng04ee5a12009-01-20 19:12:24 +0000803 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
804 if (TII->isMoveInstr(*DI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
805 if (DstReg == LI->reg)
Owen Anderson200ee7f2009-01-06 07:53:32 +0000806 NewVN->copy = &*DI;
807
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000808 NewVNs[&*DI] = NewVN;
809 }
810
811 // Cache uses as a separate pass from actually processing them.
812 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
813 UE = MRI->use_end(); UI != UE; ++UI)
814 Uses[(*UI).getParent()].insert(&*UI);
815
816 // Now, actually process every use and use a phi construction algorithm
817 // to walk from it to its reaching definitions, building VNInfos along
818 // the way.
Owen Anderson7d211e22008-12-31 02:00:25 +0000819 DenseMap<MachineBasicBlock*, VNInfo*> LiveOut;
820 DenseMap<MachineBasicBlock*, VNInfo*> Phis;
Owen Anderson200ee7f2009-01-06 07:53:32 +0000821 SmallPtrSet<MachineInstr*, 4> Visited;
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000822 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
823 UE = MRI->use_end(); UI != UE; ++UI) {
Owen Anderson200ee7f2009-01-06 07:53:32 +0000824 PerformPHIConstruction(&*UI, UI->getParent(), LI, Visited, Defs,
Owen Anderson7d211e22008-12-31 02:00:25 +0000825 Uses, NewVNs, LiveOut, Phis, true, true);
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000826 }
Owen Andersond4f6fe52008-12-28 23:35:13 +0000827
828 // Add ranges for dead defs
829 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
830 DE = MRI->def_end(); DI != DE; ++DI) {
831 unsigned DefIdx = LIs->getInstructionIndex(&*DI);
832 DefIdx = LiveIntervals::getDefIndex(DefIdx);
Owen Andersond4f6fe52008-12-28 23:35:13 +0000833
834 if (LI->liveAt(DefIdx)) continue;
835
836 VNInfo* DeadVN = NewVNs[&*DI];
Owen Anderson7d211e22008-12-31 02:00:25 +0000837 LI->addRange(LiveRange(DefIdx, DefIdx+1, DeadVN));
Owen Andersond4f6fe52008-12-28 23:35:13 +0000838 LI->addKill(DeadVN, DefIdx);
839 }
Owen Anderson60d4f6d2008-12-28 21:48:48 +0000840}
841
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000842/// RenumberValno - Split the given valno out into a new vreg, allowing it to
843/// be allocated to a different register. This function creates a new vreg,
844/// copies the valno and its live ranges over to the new vreg's interval,
845/// removes them from the old interval, and rewrites all uses and defs of
846/// the original reg to the new vreg within those ranges.
847void PreAllocSplitting::RenumberValno(VNInfo* VN) {
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000848 SmallVector<VNInfo*, 4> Stack;
849 SmallVector<VNInfo*, 4> VNsToCopy;
850 Stack.push_back(VN);
851
852 // Walk through and copy the valno we care about, and any other valnos
853 // that are two-address redefinitions of the one we care about. These
854 // will need to be rewritten as well. We also check for safety of the
855 // renumbering here, by making sure that none of the valno involved has
856 // phi kills.
857 while (!Stack.empty()) {
858 VNInfo* OldVN = Stack.back();
859 Stack.pop_back();
860
861 // Bail out if we ever encounter a valno that has a PHI kill. We can't
862 // renumber these.
863 if (OldVN->hasPHIKill) return;
864
865 VNsToCopy.push_back(OldVN);
866
867 // Locate two-address redefinitions
868 for (SmallVector<unsigned, 4>::iterator KI = OldVN->kills.begin(),
869 KE = OldVN->kills.end(); KI != KE; ++KI) {
870 MachineInstr* MI = LIs->getInstructionFromIndex(*KI);
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000871 unsigned DefIdx = MI->findRegisterDefOperandIdx(CurrLI->reg);
872 if (DefIdx == ~0U) continue;
873 if (MI->isRegReDefinedByTwoAddr(DefIdx)) {
874 VNInfo* NextVN =
875 CurrLI->findDefinedVNInfo(LiveIntervals::getDefIndex(*KI));
Owen Andersonb4b84362009-01-26 21:57:31 +0000876 if (NextVN == OldVN) continue;
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000877 Stack.push_back(NextVN);
878 }
879 }
880 }
881
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000882 // Create the new vreg
883 unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
884
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000885 // Create the new live interval
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000886 LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000887
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000888 for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE =
889 VNsToCopy.end(); OI != OE; ++OI) {
890 VNInfo* OldVN = *OI;
891
892 // Copy the valno over
893 VNInfo* NewVN = NewLI.getNextValue(OldVN->def, OldVN->copy,
894 LIs->getVNInfoAllocator());
895 NewLI.copyValNumInfo(NewVN, OldVN);
896 NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
897
898 // Remove the valno from the old interval
899 CurrLI->removeValNo(OldVN);
900 }
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000901
902 // Rewrite defs and uses. This is done in two stages to avoid invalidating
903 // the reg_iterator.
904 SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
905
906 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
907 E = MRI->reg_end(); I != E; ++I) {
908 MachineOperand& MO = I.getOperand();
909 unsigned InstrIdx = LIs->getInstructionIndex(&*I);
910
911 if ((MO.isUse() && NewLI.liveAt(LiveIntervals::getUseIndex(InstrIdx))) ||
912 (MO.isDef() && NewLI.liveAt(LiveIntervals::getDefIndex(InstrIdx))))
913 OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
914 }
915
916 for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
917 OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
918 MachineInstr* Inst = I->first;
919 unsigned OpIdx = I->second;
920 MachineOperand& MO = Inst->getOperand(OpIdx);
921 MO.setReg(NewVReg);
922 }
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000923
Owen Anderson420dd372009-03-14 21:40:05 +0000924 // Grow the VirtRegMap, since we've created a new vreg.
925 VRM->grow();
926
Owen Anderson45e68552009-01-29 05:28:55 +0000927 // The renumbered vreg shares a stack slot with the old register.
928 if (IntervalSSMap.count(CurrLI->reg))
929 IntervalSSMap[NewVReg] = IntervalSSMap[CurrLI->reg];
930
Owen Anderson2ebf63f2008-12-18 01:27:19 +0000931 NumRenumbers++;
Owen Andersond0b6a0d2008-12-16 21:35:08 +0000932}
933
Owen Anderson6002e992008-12-04 21:20:30 +0000934bool PreAllocSplitting::Rematerialize(unsigned vreg, VNInfo* ValNo,
935 MachineInstr* DefMI,
936 MachineBasicBlock::iterator RestorePt,
937 unsigned RestoreIdx,
938 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
939 MachineBasicBlock& MBB = *RestorePt->getParent();
940
941 MachineBasicBlock::iterator KillPt = BarrierMBB->end();
942 unsigned KillIdx = 0;
943 if (ValNo->def == ~0U || DefMI->getParent() == BarrierMBB)
944 KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, KillIdx);
945 else
946 KillPt = findNextEmptySlot(DefMI->getParent(), DefMI, KillIdx);
947
948 if (KillPt == DefMI->getParent()->end())
949 return false;
950
951 TII->reMaterialize(MBB, RestorePt, vreg, DefMI);
952 LIs->InsertMachineInstrInMaps(prior(RestorePt), RestoreIdx);
953
Owen Andersonb4b84362009-01-26 21:57:31 +0000954 ReconstructLiveInterval(CurrLI);
955 unsigned RematIdx = LIs->getInstructionIndex(prior(RestorePt));
956 RematIdx = LiveIntervals::getDefIndex(RematIdx);
957 RenumberValno(CurrLI->findDefinedVNInfo(RematIdx));
Owen Andersone1762c92009-01-12 03:10:40 +0000958
Owen Anderson75fa96b2008-11-19 04:28:29 +0000959 ++NumSplits;
960 ++NumRemats;
Owen Anderson7b9d67c2008-12-02 18:53:47 +0000961 return true;
962}
963
964MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg,
965 const TargetRegisterClass* RC,
966 MachineInstr* DefMI,
967 MachineInstr* Barrier,
968 MachineBasicBlock* MBB,
969 int& SS,
970 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
971 MachineBasicBlock::iterator Pt = MBB->begin();
972
973 // Go top down if RefsInMBB is empty.
974 if (RefsInMBB.empty())
975 return 0;
Owen Anderson75fa96b2008-11-19 04:28:29 +0000976
Owen Anderson7b9d67c2008-12-02 18:53:47 +0000977 MachineBasicBlock::iterator FoldPt = Barrier;
978 while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
979 !RefsInMBB.count(FoldPt))
980 --FoldPt;
981
982 int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg, false);
983 if (OpIdx == -1)
984 return 0;
985
986 SmallVector<unsigned, 1> Ops;
987 Ops.push_back(OpIdx);
988
989 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
990 return 0;
991
992 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
993 if (I != IntervalSSMap.end()) {
994 SS = I->second;
995 } else {
996 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
997
998 }
999
1000 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
1001 FoldPt, Ops, SS);
1002
1003 if (FMI) {
1004 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
1005 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
1006 ++NumFolds;
1007
1008 IntervalSSMap[vreg] = SS;
1009 CurrSLI = &LSs->getOrCreateInterval(SS);
1010 if (CurrSLI->hasAtLeastOneValue())
1011 CurrSValNo = CurrSLI->getValNumInfo(0);
1012 else
1013 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
1014 }
1015
1016 return FMI;
Owen Anderson75fa96b2008-11-19 04:28:29 +00001017}
1018
Owen Andersonc93023a2009-03-04 08:52:31 +00001019MachineInstr* PreAllocSplitting::FoldRestore(unsigned vreg,
1020 const TargetRegisterClass* RC,
1021 MachineInstr* Barrier,
1022 MachineBasicBlock* MBB,
1023 int SS,
1024 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
Owen Andersona2bfb542009-03-05 08:23:20 +00001025 if ((int)RestoreFoldLimit != -1 && RestoreFoldLimit == (int)NumRestoreFolds)
Owen Anderson323c58d2009-03-05 07:19:18 +00001026 return 0;
1027
Owen Andersonc93023a2009-03-04 08:52:31 +00001028 // Go top down if RefsInMBB is empty.
1029 if (RefsInMBB.empty())
1030 return 0;
1031
1032 // Can't fold a restore between a call stack setup and teardown.
1033 MachineBasicBlock::iterator FoldPt = Barrier;
Owen Anderson323c58d2009-03-05 07:19:18 +00001034
1035 // Advance from barrier to call frame teardown.
1036 while (FoldPt != MBB->getFirstTerminator() &&
1037 FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
1038 if (RefsInMBB.count(FoldPt))
1039 return 0;
Owen Andersonc93023a2009-03-04 08:52:31 +00001040
Owen Anderson323c58d2009-03-05 07:19:18 +00001041 ++FoldPt;
1042 }
1043
1044 if (FoldPt == MBB->getFirstTerminator())
1045 return 0;
1046 else
1047 ++FoldPt;
1048
1049 // Now find the restore point.
1050 while (FoldPt != MBB->getFirstTerminator() && !RefsInMBB.count(FoldPt)) {
Owen Andersonc93023a2009-03-04 08:52:31 +00001051 if (FoldPt->getOpcode() == TRI->getCallFrameSetupOpcode()) {
1052 while (FoldPt != MBB->getFirstTerminator() &&
1053 FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
1054 if (RefsInMBB.count(FoldPt))
1055 return 0;
1056
1057 ++FoldPt;
1058 }
1059
Owen Anderson323c58d2009-03-05 07:19:18 +00001060 if (FoldPt == MBB->getFirstTerminator())
1061 return 0;
1062 }
1063
1064 ++FoldPt;
Owen Andersonc93023a2009-03-04 08:52:31 +00001065 }
1066
1067 if (FoldPt == MBB->getFirstTerminator())
1068 return 0;
1069
1070 int OpIdx = FoldPt->findRegisterUseOperandIdx(vreg, true);
1071 if (OpIdx == -1)
1072 return 0;
1073
1074 SmallVector<unsigned, 1> Ops;
1075 Ops.push_back(OpIdx);
1076
1077 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
1078 return 0;
1079
1080 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
1081 FoldPt, Ops, SS);
1082
1083 if (FMI) {
1084 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
1085 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
Owen Anderson323c58d2009-03-05 07:19:18 +00001086 ++NumRestoreFolds;
Owen Andersonc93023a2009-03-04 08:52:31 +00001087 }
1088
1089 return FMI;
1090}
1091
Evan Chengf5cd4f02008-10-23 20:43:13 +00001092/// SplitRegLiveInterval - Split (spill and restore) the given live interval
1093/// so it would not cross the barrier that's being processed. Shrink wrap
1094/// (minimize) the live interval to the last uses.
1095bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
1096 CurrLI = LI;
1097
1098 // Find live range where current interval cross the barrier.
1099 LiveInterval::iterator LR =
1100 CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
1101 VNInfo *ValNo = LR->valno;
1102
1103 if (ValNo->def == ~1U) {
1104 // Defined by a dead def? How can this be?
1105 assert(0 && "Val# is defined by a dead def?");
1106 abort();
1107 }
1108
Evan Cheng06587492008-10-24 02:05:00 +00001109 MachineInstr *DefMI = (ValNo->def != ~0U)
1110 ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
Evan Cheng06587492008-10-24 02:05:00 +00001111
Owen Andersond3be4622009-01-21 08:18:03 +00001112 // If this would create a new join point, do not split.
1113 if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent()))
1114 return false;
1115
Evan Chengf5cd4f02008-10-23 20:43:13 +00001116 // Find all references in the barrier mbb.
1117 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
1118 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
1119 E = MRI->reg_end(); I != E; ++I) {
1120 MachineInstr *RefMI = &*I;
1121 if (RefMI->getParent() == BarrierMBB)
1122 RefsInMBB.insert(RefMI);
1123 }
1124
1125 // Find a point to restore the value after the barrier.
Evan Chengb964f332009-01-26 18:33:51 +00001126 unsigned RestoreIndex = 0;
Evan Chengf5cd4f02008-10-23 20:43:13 +00001127 MachineBasicBlock::iterator RestorePt =
Evan Chengf62ce372008-10-28 00:47:49 +00001128 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
Evan Chengf5cd4f02008-10-23 20:43:13 +00001129 if (RestorePt == BarrierMBB->end())
1130 return false;
1131
Owen Anderson75fa96b2008-11-19 04:28:29 +00001132 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
1133 if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt,
1134 RestoreIndex, RefsInMBB))
1135 return true;
1136
Evan Chengf5cd4f02008-10-23 20:43:13 +00001137 // Add a spill either before the barrier or after the definition.
Evan Cheng06587492008-10-24 02:05:00 +00001138 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
Evan Chengf5cd4f02008-10-23 20:43:13 +00001139 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
Evan Chengf5cd4f02008-10-23 20:43:13 +00001140 unsigned SpillIndex = 0;
Evan Cheng06587492008-10-24 02:05:00 +00001141 MachineInstr *SpillMI = NULL;
Evan Cheng985921e2008-10-27 23:29:28 +00001142 int SS = -1;
Evan Cheng78dfef72008-10-25 00:52:41 +00001143 if (ValNo->def == ~0U) {
Evan Chengf5cd4f02008-10-23 20:43:13 +00001144 // If it's defined by a phi, we must split just before the barrier.
Owen Anderson7b9d67c2008-12-02 18:53:47 +00001145 if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
1146 BarrierMBB, SS, RefsInMBB))) {
1147 SpillIndex = LIs->getInstructionIndex(SpillMI);
1148 } else {
1149 MachineBasicBlock::iterator SpillPt =
1150 findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
1151 if (SpillPt == BarrierMBB->begin())
1152 return false; // No gap to insert spill.
1153 // Add spill.
1154
1155 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1156 TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
1157 SpillMI = prior(SpillPt);
1158 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1159 }
Evan Cheng54898932008-10-29 08:39:34 +00001160 } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
1161 RestoreIndex, SpillIndex, SS)) {
Evan Cheng78dfef72008-10-25 00:52:41 +00001162 // If it's already split, just restore the value. There is no need to spill
1163 // the def again.
Evan Chengd0e32c52008-10-29 05:06:14 +00001164 if (!DefMI)
1165 return false; // Def is dead. Do nothing.
Owen Anderson7b9d67c2008-12-02 18:53:47 +00001166
1167 if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
1168 BarrierMBB, SS, RefsInMBB))) {
1169 SpillIndex = LIs->getInstructionIndex(SpillMI);
Evan Cheng1f08cc22008-10-28 05:28:21 +00001170 } else {
Owen Anderson7b9d67c2008-12-02 18:53:47 +00001171 // Check if it's possible to insert a spill after the def MI.
1172 MachineBasicBlock::iterator SpillPt;
1173 if (DefMBB == BarrierMBB) {
1174 // Add spill after the def and the last use before the barrier.
1175 SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
1176 RefsInMBB, SpillIndex);
1177 if (SpillPt == DefMBB->begin())
1178 return false; // No gap to insert spill.
1179 } else {
1180 SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
1181 if (SpillPt == DefMBB->end())
1182 return false; // No gap to insert spill.
1183 }
1184 // Add spill. The store instruction kills the register if def is before
1185 // the barrier in the barrier block.
1186 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1187 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
1188 DefMBB == BarrierMBB, SS, RC);
1189 SpillMI = prior(SpillPt);
1190 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
Evan Cheng1f08cc22008-10-28 05:28:21 +00001191 }
Evan Chengf5cd4f02008-10-23 20:43:13 +00001192 }
1193
Evan Cheng54898932008-10-29 08:39:34 +00001194 // Remember def instruction index to spill index mapping.
1195 if (DefMI && SpillMI)
1196 Def2SpillMap[ValNo->def] = SpillIndex;
1197
Evan Chengf5cd4f02008-10-23 20:43:13 +00001198 // Add restore.
Owen Andersonc93023a2009-03-04 08:52:31 +00001199 bool FoldedRestore = false;
1200 if (MachineInstr* LMI = FoldRestore(CurrLI->reg, RC, Barrier,
1201 BarrierMBB, SS, RefsInMBB)) {
1202 RestorePt = LMI;
Owen Anderson323c58d2009-03-05 07:19:18 +00001203 RestoreIndex = LIs->getInstructionIndex(RestorePt);
Owen Andersonc93023a2009-03-04 08:52:31 +00001204 FoldedRestore = true;
1205 } else {
1206 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
1207 MachineInstr *LoadMI = prior(RestorePt);
1208 LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
1209 }
Evan Chengf5cd4f02008-10-23 20:43:13 +00001210
Evan Chengd0e32c52008-10-29 05:06:14 +00001211 // Update spill stack slot live interval.
Evan Cheng54898932008-10-29 08:39:34 +00001212 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1213 LIs->getDefIndex(RestoreIndex));
Evan Chengd0e32c52008-10-29 05:06:14 +00001214
Owen Andersonb4b84362009-01-26 21:57:31 +00001215 ReconstructLiveInterval(CurrLI);
Owen Andersonc93023a2009-03-04 08:52:31 +00001216
1217 if (!FoldedRestore) {
1218 unsigned RestoreIdx = LIs->getInstructionIndex(prior(RestorePt));
1219 RestoreIdx = LiveIntervals::getDefIndex(RestoreIdx);
1220 RenumberValno(CurrLI->findDefinedVNInfo(RestoreIdx));
1221 }
Owen Anderson7d211e22008-12-31 02:00:25 +00001222
Evan Chengae7fa5b2008-10-28 01:48:24 +00001223 ++NumSplits;
Evan Chengf5cd4f02008-10-23 20:43:13 +00001224 return true;
1225}
1226
1227/// SplitRegLiveIntervals - Split all register live intervals that cross the
1228/// barrier that's being processed.
1229bool
Owen Anderson956ec272009-01-23 00:23:32 +00001230PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs,
1231 SmallPtrSet<LiveInterval*, 8>& Split) {
Evan Chengf5cd4f02008-10-23 20:43:13 +00001232 // First find all the virtual registers whose live intervals are intercepted
1233 // by the current barrier.
1234 SmallVector<LiveInterval*, 8> Intervals;
1235 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
Evan Cheng4350eb82009-02-06 17:17:30 +00001236 // FIXME: If it's not safe to move any instruction that defines the barrier
1237 // register class, then it means there are some special dependencies which
1238 // codegen is not modelling. Ignore these barriers for now.
1239 if (!TII->isSafeToMoveRegClassDefs(*RC))
Evan Cheng23066282008-10-27 07:14:50 +00001240 continue;
Evan Chengf5cd4f02008-10-23 20:43:13 +00001241 std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1242 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1243 unsigned Reg = VRs[i];
1244 if (!LIs->hasInterval(Reg))
1245 continue;
1246 LiveInterval *LI = &LIs->getInterval(Reg);
1247 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1248 // Virtual register live interval is intercepted by the barrier. We
1249 // should split and shrink wrap its interval if possible.
1250 Intervals.push_back(LI);
1251 }
1252 }
1253
1254 // Process the affected live intervals.
1255 bool Change = false;
1256 while (!Intervals.empty()) {
Evan Chengae7fa5b2008-10-28 01:48:24 +00001257 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1258 break;
Owen Andersone1762c92009-01-12 03:10:40 +00001259 else if (NumSplits == 4)
1260 Change |= Change;
Evan Chengf5cd4f02008-10-23 20:43:13 +00001261 LiveInterval *LI = Intervals.back();
1262 Intervals.pop_back();
Owen Anderson956ec272009-01-23 00:23:32 +00001263 bool result = SplitRegLiveInterval(LI);
1264 if (result) Split.insert(LI);
1265 Change |= result;
Evan Chengf5cd4f02008-10-23 20:43:13 +00001266 }
1267
1268 return Change;
1269}
1270
Owen Anderson45e68552009-01-29 05:28:55 +00001271unsigned PreAllocSplitting::getNumberOfNonSpills(
Owen Anderson32ca8652009-01-24 10:07:43 +00001272 SmallPtrSet<MachineInstr*, 4>& MIs,
Owen Anderson45e68552009-01-29 05:28:55 +00001273 unsigned Reg, int FrameIndex,
1274 bool& FeedsTwoAddr) {
1275 unsigned NonSpills = 0;
Owen Anderson32ca8652009-01-24 10:07:43 +00001276 for (SmallPtrSet<MachineInstr*, 4>::iterator UI = MIs.begin(), UE = MIs.end();
Owen Anderson45e68552009-01-29 05:28:55 +00001277 UI != UE; ++UI) {
Owen Anderson32ca8652009-01-24 10:07:43 +00001278 int StoreFrameIndex;
1279 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
Owen Anderson45e68552009-01-29 05:28:55 +00001280 if (StoreVReg != Reg || StoreFrameIndex != FrameIndex)
1281 NonSpills++;
1282
1283 int DefIdx = (*UI)->findRegisterDefOperandIdx(Reg);
1284 if (DefIdx != -1 && (*UI)->isRegReDefinedByTwoAddr(DefIdx))
1285 FeedsTwoAddr = true;
Owen Anderson32ca8652009-01-24 10:07:43 +00001286 }
1287
Owen Anderson45e68552009-01-29 05:28:55 +00001288 return NonSpills;
Owen Anderson32ca8652009-01-24 10:07:43 +00001289}
1290
Owen Anderson956ec272009-01-23 00:23:32 +00001291/// removeDeadSpills - After doing splitting, filter through all intervals we've
1292/// split, and see if any of the spills are unnecessary. If so, remove them.
1293bool PreAllocSplitting::removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split) {
1294 bool changed = false;
1295
Owen Anderson4bfc2092009-01-29 05:41:02 +00001296 // Walk over all of the live intervals that were touched by the splitter,
1297 // and see if we can do any DCE and/or folding.
Owen Anderson956ec272009-01-23 00:23:32 +00001298 for (SmallPtrSet<LiveInterval*, 8>::iterator LI = split.begin(),
1299 LE = split.end(); LI != LE; ++LI) {
Owen Anderson9ce499a2009-01-23 03:28:53 +00001300 DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> > VNUseCount;
Owen Anderson956ec272009-01-23 00:23:32 +00001301
Owen Anderson4bfc2092009-01-29 05:41:02 +00001302 // First, collect all the uses of the vreg, and sort them by their
1303 // reaching definition (VNInfo).
Owen Anderson956ec272009-01-23 00:23:32 +00001304 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin((*LI)->reg),
1305 UE = MRI->use_end(); UI != UE; ++UI) {
1306 unsigned index = LIs->getInstructionIndex(&*UI);
1307 index = LiveIntervals::getUseIndex(index);
1308
1309 const LiveRange* LR = (*LI)->getLiveRangeContaining(index);
Owen Anderson9ce499a2009-01-23 03:28:53 +00001310 VNUseCount[LR->valno].insert(&*UI);
Owen Anderson956ec272009-01-23 00:23:32 +00001311 }
1312
Owen Anderson4bfc2092009-01-29 05:41:02 +00001313 // Now, take the definitions (VNInfo's) one at a time and try to DCE
1314 // and/or fold them away.
Owen Anderson956ec272009-01-23 00:23:32 +00001315 for (LiveInterval::vni_iterator VI = (*LI)->vni_begin(),
1316 VE = (*LI)->vni_end(); VI != VE; ++VI) {
Owen Anderson45e68552009-01-29 05:28:55 +00001317
1318 if (DeadSplitLimit != -1 && (int)NumDeadSpills == DeadSplitLimit)
1319 return changed;
1320
Owen Anderson956ec272009-01-23 00:23:32 +00001321 VNInfo* CurrVN = *VI;
Owen Anderson4bfc2092009-01-29 05:41:02 +00001322
1323 // We don't currently try to handle definitions with PHI kills, because
1324 // it would involve processing more than one VNInfo at once.
Owen Anderson956ec272009-01-23 00:23:32 +00001325 if (CurrVN->hasPHIKill) continue;
Owen Anderson956ec272009-01-23 00:23:32 +00001326
Owen Anderson4bfc2092009-01-29 05:41:02 +00001327 // We also don't try to handle the results of PHI joins, since there's
1328 // no defining instruction to analyze.
Owen Anderson956ec272009-01-23 00:23:32 +00001329 unsigned DefIdx = CurrVN->def;
1330 if (DefIdx == ~0U || DefIdx == ~1U) continue;
Owen Anderson9ce499a2009-01-23 03:28:53 +00001331
Owen Anderson4bfc2092009-01-29 05:41:02 +00001332 // We're only interested in eliminating cruft introduced by the splitter,
1333 // is of the form load-use or load-use-store. First, check that the
1334 // definition is a load, and remember what stack slot we loaded it from.
Owen Anderson956ec272009-01-23 00:23:32 +00001335 MachineInstr* DefMI = LIs->getInstructionFromIndex(DefIdx);
1336 int FrameIndex;
1337 if (!TII->isLoadFromStackSlot(DefMI, FrameIndex)) continue;
1338
Owen Anderson4bfc2092009-01-29 05:41:02 +00001339 // If the definition has no uses at all, just DCE it.
Owen Anderson9ce499a2009-01-23 03:28:53 +00001340 if (VNUseCount[CurrVN].size() == 0) {
1341 LIs->RemoveMachineInstrFromMaps(DefMI);
1342 (*LI)->removeValNo(CurrVN);
1343 DefMI->eraseFromParent();
Owen Andersonc0f3a032009-01-29 08:22:06 +00001344 VNUseCount.erase(CurrVN);
Owen Anderson9ce499a2009-01-23 03:28:53 +00001345 NumDeadSpills++;
1346 changed = true;
Owen Anderson32ca8652009-01-24 10:07:43 +00001347 continue;
Owen Anderson9ce499a2009-01-23 03:28:53 +00001348 }
Owen Anderson32ca8652009-01-24 10:07:43 +00001349
Owen Anderson4bfc2092009-01-29 05:41:02 +00001350 // Second, get the number of non-store uses of the definition, as well as
1351 // a flag indicating whether it feeds into a later two-address definition.
Owen Anderson45e68552009-01-29 05:28:55 +00001352 bool FeedsTwoAddr = false;
1353 unsigned NonSpillCount = getNumberOfNonSpills(VNUseCount[CurrVN],
1354 (*LI)->reg, FrameIndex,
1355 FeedsTwoAddr);
1356
Owen Anderson4bfc2092009-01-29 05:41:02 +00001357 // If there's one non-store use and it doesn't feed a two-addr, then
1358 // this is a load-use-store case that we can try to fold.
Owen Anderson45e68552009-01-29 05:28:55 +00001359 if (NonSpillCount == 1 && !FeedsTwoAddr) {
Owen Anderson4bfc2092009-01-29 05:41:02 +00001360 // Start by finding the non-store use MachineInstr.
Owen Anderson45e68552009-01-29 05:28:55 +00001361 SmallPtrSet<MachineInstr*, 4>::iterator UI = VNUseCount[CurrVN].begin();
1362 int StoreFrameIndex;
1363 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1364 while (UI != VNUseCount[CurrVN].end() &&
1365 (StoreVReg == (*LI)->reg && StoreFrameIndex == FrameIndex)) {
1366 ++UI;
1367 if (UI != VNUseCount[CurrVN].end())
1368 StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1369 }
Owen Anderson45e68552009-01-29 05:28:55 +00001370 if (UI == VNUseCount[CurrVN].end()) continue;
1371
1372 MachineInstr* use = *UI;
1373
Owen Anderson4bfc2092009-01-29 05:41:02 +00001374 // Attempt to fold it away!
Owen Anderson45e68552009-01-29 05:28:55 +00001375 int OpIdx = use->findRegisterUseOperandIdx((*LI)->reg, false);
1376 if (OpIdx == -1) continue;
Owen Anderson45e68552009-01-29 05:28:55 +00001377 SmallVector<unsigned, 1> Ops;
1378 Ops.push_back(OpIdx);
Owen Anderson45e68552009-01-29 05:28:55 +00001379 if (!TII->canFoldMemoryOperand(use, Ops)) continue;
1380
1381 MachineInstr* NewMI =
1382 TII->foldMemoryOperand(*use->getParent()->getParent(),
1383 use, Ops, FrameIndex);
1384
1385 if (!NewMI) continue;
1386
Owen Anderson4bfc2092009-01-29 05:41:02 +00001387 // Update relevant analyses.
Owen Anderson45e68552009-01-29 05:28:55 +00001388 LIs->RemoveMachineInstrFromMaps(DefMI);
1389 LIs->ReplaceMachineInstrInMaps(use, NewMI);
1390 (*LI)->removeValNo(CurrVN);
1391
1392 DefMI->eraseFromParent();
1393 MachineBasicBlock* MBB = use->getParent();
1394 NewMI = MBB->insert(MBB->erase(use), NewMI);
1395 VNUseCount[CurrVN].erase(use);
1396
Owen Anderson4bfc2092009-01-29 05:41:02 +00001397 // Remove deleted instructions. Note that we need to remove them from
1398 // the VNInfo->use map as well, just to be safe.
Owen Anderson45e68552009-01-29 05:28:55 +00001399 for (SmallPtrSet<MachineInstr*, 4>::iterator II =
1400 VNUseCount[CurrVN].begin(), IE = VNUseCount[CurrVN].end();
1401 II != IE; ++II) {
Owen Anderson4bfc2092009-01-29 05:41:02 +00001402 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
Owen Andersonc0f3a032009-01-29 08:22:06 +00001403 VNI = VNUseCount.begin(), VNE = VNUseCount.end(); VNI != VNE;
1404 ++VNI)
1405 if (VNI->first != CurrVN)
1406 VNI->second.erase(*II);
Owen Anderson45e68552009-01-29 05:28:55 +00001407 LIs->RemoveMachineInstrFromMaps(*II);
1408 (*II)->eraseFromParent();
1409 }
Owen Andersonc0f3a032009-01-29 08:22:06 +00001410
1411 VNUseCount.erase(CurrVN);
Owen Anderson45e68552009-01-29 05:28:55 +00001412
1413 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1414 VI = VNUseCount.begin(), VE = VNUseCount.end(); VI != VE; ++VI)
1415 if (VI->second.erase(use))
1416 VI->second.insert(NewMI);
1417
1418 NumDeadSpills++;
1419 changed = true;
1420 continue;
1421 }
1422
Owen Anderson4bfc2092009-01-29 05:41:02 +00001423 // If there's more than one non-store instruction, we can't profitably
1424 // fold it, so bail.
Owen Anderson45e68552009-01-29 05:28:55 +00001425 if (NonSpillCount) continue;
Owen Anderson32ca8652009-01-24 10:07:43 +00001426
Owen Anderson4bfc2092009-01-29 05:41:02 +00001427 // Otherwise, this is a load-store case, so DCE them.
Owen Anderson32ca8652009-01-24 10:07:43 +00001428 for (SmallPtrSet<MachineInstr*, 4>::iterator UI =
1429 VNUseCount[CurrVN].begin(), UE = VNUseCount[CurrVN].end();
1430 UI != UI; ++UI) {
1431 LIs->RemoveMachineInstrFromMaps(*UI);
1432 (*UI)->eraseFromParent();
1433 }
1434
Owen Andersonc0f3a032009-01-29 08:22:06 +00001435 VNUseCount.erase(CurrVN);
1436
Owen Anderson32ca8652009-01-24 10:07:43 +00001437 LIs->RemoveMachineInstrFromMaps(DefMI);
1438 (*LI)->removeValNo(CurrVN);
1439 DefMI->eraseFromParent();
1440 NumDeadSpills++;
1441 changed = true;
Owen Anderson956ec272009-01-23 00:23:32 +00001442 }
1443 }
1444
1445 return changed;
1446}
1447
Owen Andersonf1f75b12008-11-04 22:22:41 +00001448bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1449 MachineBasicBlock* DefMBB,
1450 MachineBasicBlock* BarrierMBB) {
1451 if (DefMBB == BarrierMBB)
1452 return false;
1453
1454 if (LR->valno->hasPHIKill)
1455 return false;
1456
1457 unsigned MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1458 if (LR->end < MBBEnd)
1459 return false;
1460
1461 MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1462 if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1463 return true;
1464
1465 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1466 SmallPtrSet<MachineBasicBlock*, 4> Visited;
1467 typedef std::pair<MachineBasicBlock*,
1468 MachineBasicBlock::succ_iterator> ItPair;
1469 SmallVector<ItPair, 4> Stack;
1470 Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1471
1472 while (!Stack.empty()) {
1473 ItPair P = Stack.back();
1474 Stack.pop_back();
1475
1476 MachineBasicBlock* PredMBB = P.first;
1477 MachineBasicBlock::succ_iterator S = P.second;
1478
1479 if (S == PredMBB->succ_end())
1480 continue;
1481 else if (Visited.count(*S)) {
1482 Stack.push_back(std::make_pair(PredMBB, ++S));
1483 continue;
1484 } else
Owen Andersonb214c692008-11-05 00:32:13 +00001485 Stack.push_back(std::make_pair(PredMBB, S+1));
Owen Andersonf1f75b12008-11-04 22:22:41 +00001486
1487 MachineBasicBlock* MBB = *S;
1488 Visited.insert(MBB);
1489
1490 if (MBB == BarrierMBB)
1491 return true;
1492
1493 MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1494 MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1495 MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1496 while (MDTN) {
1497 if (MDTN == DefMDTN)
1498 return true;
1499 else if (MDTN == BarrierMDTN)
1500 break;
1501 MDTN = MDTN->getIDom();
1502 }
1503
1504 MBBEnd = LIs->getMBBEndIdx(MBB);
1505 if (LR->end > MBBEnd)
1506 Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1507 }
1508
1509 return false;
1510}
1511
1512
Evan Cheng09e8ca82008-10-20 21:44:59 +00001513bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd0e32c52008-10-29 05:06:14 +00001514 CurrMF = &MF;
1515 TM = &MF.getTarget();
Owen Anderson3ef45492009-01-29 22:13:06 +00001516 TRI = TM->getRegisterInfo();
Evan Chengd0e32c52008-10-29 05:06:14 +00001517 TII = TM->getInstrInfo();
1518 MFI = MF.getFrameInfo();
1519 MRI = &MF.getRegInfo();
1520 LIs = &getAnalysis<LiveIntervals>();
1521 LSs = &getAnalysis<LiveStacks>();
Owen Anderson420dd372009-03-14 21:40:05 +00001522 VRM = &getAnalysis<VirtRegMap>();
Evan Chengf5cd4f02008-10-23 20:43:13 +00001523
1524 bool MadeChange = false;
1525
1526 // Make sure blocks are numbered in order.
1527 MF.RenumberBlocks();
1528
Evan Cheng54898932008-10-29 08:39:34 +00001529 MachineBasicBlock *Entry = MF.begin();
1530 SmallPtrSet<MachineBasicBlock*,16> Visited;
1531
Owen Anderson956ec272009-01-23 00:23:32 +00001532 SmallPtrSet<LiveInterval*, 8> Split;
1533
Evan Cheng54898932008-10-29 08:39:34 +00001534 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1535 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1536 DFI != E; ++DFI) {
1537 BarrierMBB = *DFI;
1538 for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1539 E = BarrierMBB->end(); I != E; ++I) {
1540 Barrier = &*I;
1541 const TargetRegisterClass **BarrierRCs =
1542 Barrier->getDesc().getRegClassBarriers();
1543 if (!BarrierRCs)
1544 continue;
1545 BarrierIdx = LIs->getInstructionIndex(Barrier);
Owen Anderson956ec272009-01-23 00:23:32 +00001546 MadeChange |= SplitRegLiveIntervals(BarrierRCs, Split);
Evan Cheng54898932008-10-29 08:39:34 +00001547 }
1548 }
Evan Chengf5cd4f02008-10-23 20:43:13 +00001549
Owen Anderson956ec272009-01-23 00:23:32 +00001550 MadeChange |= removeDeadSpills(Split);
1551
Evan Chengf5cd4f02008-10-23 20:43:13 +00001552 return MadeChange;
Evan Cheng09e8ca82008-10-20 21:44:59 +00001553}