Revert my last patch until I consult with Evan about it.
[oota-llvm.git] / lib / CodeGen / PreAllocSplitting.cpp
1 //===-- 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"
19 #include "llvm/CodeGen/LiveStackAnalysis.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/RegisterCoalescer.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/DepthFirstIterator.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/Statistic.h"
36 using namespace llvm;
37
38 static cl::opt<int> PreSplitLimit("pre-split-limit", cl::init(-1), cl::Hidden);
39
40 STATISTIC(NumSplits, "Number of intervals split");
41
42 namespace {
43   class VISIBILITY_HIDDEN PreAllocSplitting : public MachineFunctionPass {
44     MachineFunction       *CurrMF;
45     const TargetMachine   *TM;
46     const TargetInstrInfo *TII;
47     MachineFrameInfo      *MFI;
48     MachineRegisterInfo   *MRI;
49     LiveIntervals         *LIs;
50     LiveStacks            *LSs;
51
52     // Barrier - Current barrier being processed.
53     MachineInstr          *Barrier;
54
55     // BarrierMBB - Basic block where the barrier resides in.
56     MachineBasicBlock     *BarrierMBB;
57
58     // Barrier - Current barrier index.
59     unsigned              BarrierIdx;
60
61     // CurrLI - Current live interval being split.
62     LiveInterval          *CurrLI;
63
64     // CurrSLI - Current stack slot live interval.
65     LiveInterval          *CurrSLI;
66
67     // CurrSValNo - Current val# for the stack slot live interval.
68     VNInfo                *CurrSValNo;
69
70     // IntervalSSMap - A map from live interval to spill slots.
71     DenseMap<unsigned, int> IntervalSSMap;
72
73     // Def2SpillMap - A map from a def instruction index to spill index.
74     DenseMap<unsigned, unsigned> Def2SpillMap;
75
76   public:
77     static char ID;
78     PreAllocSplitting() : MachineFunctionPass(&ID) {}
79
80     virtual bool runOnMachineFunction(MachineFunction &MF);
81
82     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
83       AU.addRequired<LiveIntervals>();
84       AU.addPreserved<LiveIntervals>();
85       AU.addRequired<LiveStacks>();
86       AU.addPreserved<LiveStacks>();
87       AU.addPreserved<RegisterCoalescer>();
88       if (StrongPHIElim)
89         AU.addPreservedID(StrongPHIEliminationID);
90       else
91         AU.addPreservedID(PHIEliminationID);
92       MachineFunctionPass::getAnalysisUsage(AU);
93     }
94     
95     virtual void releaseMemory() {
96       IntervalSSMap.clear();
97       Def2SpillMap.clear();
98     }
99
100     virtual const char *getPassName() const {
101       return "Pre-Register Allocaton Live Interval Splitting";
102     }
103
104     /// print - Implement the dump method.
105     virtual void print(std::ostream &O, const Module* M = 0) const {
106       LIs->print(O, M);
107     }
108
109     void print(std::ostream *O, const Module* M = 0) const {
110       if (O) print(*O, M);
111     }
112
113   private:
114     MachineBasicBlock::iterator
115       findNextEmptySlot(MachineBasicBlock*, MachineInstr*,
116                         unsigned&);
117
118     MachineBasicBlock::iterator
119       findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
120                      SmallPtrSet<MachineInstr*, 4>&, unsigned&);
121
122     MachineBasicBlock::iterator
123       findRestorePoint(MachineBasicBlock*, MachineInstr*, unsigned,
124                      SmallPtrSet<MachineInstr*, 4>&, unsigned&);
125
126     int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
127
128     bool IsAvailableInStack(MachineBasicBlock*, unsigned, unsigned, unsigned,
129                             unsigned&, int&) const;
130
131     void UpdateSpillSlotInterval(VNInfo*, unsigned, unsigned);
132
133     void UpdateRegisterInterval(VNInfo*, unsigned, unsigned);
134
135     bool ShrinkWrapToLastUse(MachineBasicBlock*, VNInfo*,
136                              SmallVector<MachineOperand*, 4>&,
137                              SmallPtrSet<MachineInstr*, 4>&);
138
139     void ShrinkWrapLiveInterval(VNInfo*, MachineBasicBlock*, MachineBasicBlock*,
140                         MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*, 8>&,
141                 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >&,
142                   DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >&,
143                                 SmallVector<MachineBasicBlock*, 4>&);
144
145     bool SplitRegLiveInterval(LiveInterval*);
146
147     bool SplitRegLiveIntervals(const TargetRegisterClass **);
148   };
149 } // end anonymous namespace
150
151 char PreAllocSplitting::ID = 0;
152
153 static RegisterPass<PreAllocSplitting>
154 X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
155
156 const PassInfo *const llvm::PreAllocSplittingID = &X;
157
158
159 /// findNextEmptySlot - Find a gap after the given machine instruction in the
160 /// instruction index map. If there isn't one, return end().
161 MachineBasicBlock::iterator
162 PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
163                                      unsigned &SpotIndex) {
164   MachineBasicBlock::iterator MII = MI;
165   if (++MII != MBB->end()) {
166     unsigned Index = LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
167     if (Index) {
168       SpotIndex = Index;
169       return MII;
170     }
171   }
172   return MBB->end();
173 }
174
175 /// findSpillPoint - Find a gap as far away from the given MI that's suitable
176 /// for spilling the current live interval. The index must be before any
177 /// defs and uses of the live interval register in the mbb. Return begin() if
178 /// none is found.
179 MachineBasicBlock::iterator
180 PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
181                                   MachineInstr *DefMI,
182                                   SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
183                                   unsigned &SpillIndex) {
184   MachineBasicBlock::iterator Pt = MBB->begin();
185
186   // Go top down if RefsInMBB is empty.
187   if (RefsInMBB.empty() && !DefMI) {
188     MachineBasicBlock::iterator MII = MBB->begin();
189     MachineBasicBlock::iterator EndPt = MI;
190     do {
191       ++MII;
192       unsigned Index = LIs->getInstructionIndex(MII);
193       unsigned Gap = LIs->findGapBeforeInstr(Index);
194       if (Gap) {
195         Pt = MII;
196         SpillIndex = Gap;
197         break;
198       }
199     } while (MII != EndPt);
200   } else {
201     MachineBasicBlock::iterator MII = MI;
202     MachineBasicBlock::iterator EndPt = DefMI
203       ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
204     while (MII != EndPt && !RefsInMBB.count(MII)) {
205       unsigned Index = LIs->getInstructionIndex(MII);
206       if (LIs->hasGapBeforeInstr(Index)) {
207         Pt = MII;
208         SpillIndex = LIs->findGapBeforeInstr(Index, true);
209       }
210       --MII;
211     }
212   }
213
214   return Pt;
215 }
216
217 /// findRestorePoint - Find a gap in the instruction index map that's suitable
218 /// for restoring the current live interval value. The index must be before any
219 /// uses of the live interval register in the mbb. Return end() if none is
220 /// found.
221 MachineBasicBlock::iterator
222 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
223                                     unsigned LastIdx,
224                                     SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
225                                     unsigned &RestoreIndex) {
226   // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
227   // begin index accordingly.
228   MachineBasicBlock::iterator Pt = MBB->end();
229   unsigned EndIdx = LIs->getMBBEndIdx(MBB);
230
231   // Go bottom up if RefsInMBB is empty and the end of the mbb isn't beyond
232   // the last index in the live range.
233   if (RefsInMBB.empty() && LastIdx >= EndIdx) {
234     MachineBasicBlock::iterator MII = MBB->end();
235     MachineBasicBlock::iterator EndPt = MI;
236     --MII;
237     do {
238       unsigned Index = LIs->getInstructionIndex(MII);
239       unsigned Gap = LIs->findGapBeforeInstr(Index);
240       if (Gap) {
241         Pt = MII;
242         RestoreIndex = Gap;
243         break;
244       }
245       --MII;
246     } while (MII != EndPt);
247   } else {
248     MachineBasicBlock::iterator MII = MI;
249     MII = ++MII;
250     // FIXME: Limit the number of instructions to examine to reduce
251     // compile time?
252     while (MII != MBB->end()) {
253       unsigned Index = LIs->getInstructionIndex(MII);
254       if (Index > LastIdx)
255         break;
256       unsigned Gap = LIs->findGapBeforeInstr(Index);
257       if (Gap) {
258         Pt = MII;
259         RestoreIndex = Gap;
260       }
261       if (RefsInMBB.count(MII))
262         break;
263       ++MII;
264     }
265   }
266
267   return Pt;
268 }
269
270 /// CreateSpillStackSlot - Create a stack slot for the live interval being
271 /// split. If the live interval was previously split, just reuse the same
272 /// slot.
273 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
274                                             const TargetRegisterClass *RC) {
275   int SS;
276   DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
277   if (I != IntervalSSMap.end()) {
278     SS = I->second;
279   } else {
280     SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
281     IntervalSSMap[Reg] = SS;
282   }
283
284   // Create live interval for stack slot.
285   CurrSLI = &LSs->getOrCreateInterval(SS);
286   if (CurrSLI->hasAtLeastOneValue())
287     CurrSValNo = CurrSLI->getValNumInfo(0);
288   else
289     CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
290   return SS;
291 }
292
293 /// IsAvailableInStack - Return true if register is available in a split stack
294 /// slot at the specified index.
295 bool
296 PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
297                                     unsigned Reg, unsigned DefIndex,
298                                     unsigned RestoreIndex, unsigned &SpillIndex,
299                                     int& SS) const {
300   if (!DefMBB)
301     return false;
302
303   DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
304   if (I == IntervalSSMap.end())
305     return false;
306   DenseMap<unsigned, unsigned>::iterator II = Def2SpillMap.find(DefIndex);
307   if (II == Def2SpillMap.end())
308     return false;
309
310   // If last spill of def is in the same mbb as barrier mbb (where restore will
311   // be), make sure it's not below the intended restore index.
312   // FIXME: Undo the previous spill?
313   assert(LIs->getMBBFromIndex(II->second) == DefMBB);
314   if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
315     return false;
316
317   SS = I->second;
318   SpillIndex = II->second;
319   return true;
320 }
321
322 /// UpdateSpillSlotInterval - Given the specified val# of the register live
323 /// interval being split, and the spill and restore indicies, update the live
324 /// interval of the spill stack slot.
325 void
326 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, unsigned SpillIndex,
327                                            unsigned RestoreIndex) {
328   assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
329          "Expect restore in the barrier mbb");
330
331   MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
332   if (MBB == BarrierMBB) {
333     // Intra-block spill + restore. We are done.
334     LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
335     CurrSLI->addRange(SLR);
336     return;
337   }
338
339   SmallPtrSet<MachineBasicBlock*, 4> Processed;
340   unsigned EndIdx = LIs->getMBBEndIdx(MBB);
341   LiveRange SLR(SpillIndex, EndIdx+1, CurrSValNo);
342   CurrSLI->addRange(SLR);
343   Processed.insert(MBB);
344
345   // Start from the spill mbb, figure out the extend of the spill slot's
346   // live interval.
347   SmallVector<MachineBasicBlock*, 4> WorkList;
348   const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
349   if (LR->end > EndIdx)
350     // If live range extend beyond end of mbb, add successors to work list.
351     for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
352            SE = MBB->succ_end(); SI != SE; ++SI)
353       WorkList.push_back(*SI);
354
355   while (!WorkList.empty()) {
356     MachineBasicBlock *MBB = WorkList.back();
357     WorkList.pop_back();
358     if (Processed.count(MBB))
359       continue;
360     unsigned Idx = LIs->getMBBStartIdx(MBB);
361     LR = CurrLI->getLiveRangeContaining(Idx);
362     if (LR && LR->valno == ValNo) {
363       EndIdx = LIs->getMBBEndIdx(MBB);
364       if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
365         // Spill slot live interval stops at the restore.
366         LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
367         CurrSLI->addRange(SLR);
368       } else if (LR->end > EndIdx) {
369         // Live range extends beyond end of mbb, process successors.
370         LiveRange SLR(Idx, EndIdx+1, CurrSValNo);
371         CurrSLI->addRange(SLR);
372         for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
373                SE = MBB->succ_end(); SI != SE; ++SI)
374           WorkList.push_back(*SI);
375       } else {
376         LiveRange SLR(Idx, LR->end, CurrSValNo);
377         CurrSLI->addRange(SLR);
378       }
379       Processed.insert(MBB);
380     }
381   }
382 }
383
384 /// UpdateRegisterInterval - Given the specified val# of the current live
385 /// interval is being split, and the spill and restore indices, update the live
386 /// interval accordingly.
387 void
388 PreAllocSplitting::UpdateRegisterInterval(VNInfo *ValNo, unsigned SpillIndex,
389                                           unsigned RestoreIndex) {
390   assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
391          "Expect restore in the barrier mbb");
392
393   SmallVector<std::pair<unsigned,unsigned>, 4> Before;
394   SmallVector<std::pair<unsigned,unsigned>, 4> After;
395   SmallVector<unsigned, 4> BeforeKills;
396   SmallVector<unsigned, 4> AfterKills;
397   SmallPtrSet<const LiveRange*, 4> Processed;
398
399   // First, let's figure out which parts of the live interval is now defined
400   // by the restore, which are defined by the original definition.
401   const LiveRange *LR = CurrLI->getLiveRangeContaining(RestoreIndex);
402   After.push_back(std::make_pair(RestoreIndex, LR->end));
403   if (CurrLI->isKill(ValNo, LR->end))
404     AfterKills.push_back(LR->end);
405
406   assert(LR->contains(SpillIndex));
407   if (SpillIndex > LR->start) {
408     Before.push_back(std::make_pair(LR->start, SpillIndex));
409     BeforeKills.push_back(SpillIndex);
410   }
411   Processed.insert(LR);
412
413   // Start from the restore mbb, figure out what part of the live interval
414   // are defined by the restore.
415   SmallVector<MachineBasicBlock*, 4> WorkList;
416   MachineBasicBlock *MBB = BarrierMBB;
417   for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
418          SE = MBB->succ_end(); SI != SE; ++SI)
419     WorkList.push_back(*SI);
420
421   while (!WorkList.empty()) {
422     MBB = WorkList.back();
423     WorkList.pop_back();
424     unsigned Idx = LIs->getMBBStartIdx(MBB);
425     LR = CurrLI->getLiveRangeContaining(Idx);
426     if (LR && LR->valno == ValNo && !Processed.count(LR)) {
427       After.push_back(std::make_pair(LR->start, LR->end));
428       if (CurrLI->isKill(ValNo, LR->end))
429         AfterKills.push_back(LR->end);
430       Idx = LIs->getMBBEndIdx(MBB);
431       if (LR->end > Idx) {
432         // Live range extend beyond at least one mbb. Let's see what other
433         // mbbs it reaches.
434         LIs->findReachableMBBs(LR->start, LR->end, WorkList);
435       }
436       Processed.insert(LR);
437     }
438   }
439
440   for (LiveInterval::iterator I = CurrLI->begin(), E = CurrLI->end();
441        I != E; ++I) {
442     LiveRange *LR = I;
443     if (LR->valno == ValNo && !Processed.count(LR)) {
444       Before.push_back(std::make_pair(LR->start, LR->end));
445       if (CurrLI->isKill(ValNo, LR->end))
446         BeforeKills.push_back(LR->end);
447     }
448   }
449
450   // Now create new val#s to represent the live ranges defined by the old def
451   // those defined by the restore.
452   unsigned AfterDef = ValNo->def;
453   MachineInstr *AfterCopy = ValNo->copy;
454   bool HasPHIKill = ValNo->hasPHIKill;
455   CurrLI->removeValNo(ValNo);
456   VNInfo *BValNo = (Before.empty())
457     ? NULL
458     : CurrLI->getNextValue(AfterDef, AfterCopy, LIs->getVNInfoAllocator());
459   if (BValNo)
460     CurrLI->addKills(BValNo, BeforeKills);
461
462   VNInfo *AValNo = (After.empty())
463     ? NULL
464     : CurrLI->getNextValue(RestoreIndex, 0, LIs->getVNInfoAllocator());
465   if (AValNo) {
466     AValNo->hasPHIKill = HasPHIKill;
467     CurrLI->addKills(AValNo, AfterKills);
468   }
469
470   for (unsigned i = 0, e = Before.size(); i != e; ++i) {
471     unsigned Start = Before[i].first;
472     unsigned End   = Before[i].second;
473     CurrLI->addRange(LiveRange(Start, End, BValNo));
474   }
475   for (unsigned i = 0, e = After.size(); i != e; ++i) {
476     unsigned Start = After[i].first;
477     unsigned End   = After[i].second;
478     CurrLI->addRange(LiveRange(Start, End, AValNo));
479   }
480 }
481
482 /// ShrinkWrapToLastUse - There are uses of the current live interval in the
483 /// given block, shrink wrap the live interval to the last use (i.e. remove
484 /// from last use to the end of the mbb). In case mbb is the where the barrier
485 /// is, remove from the last use to the barrier.
486 bool
487 PreAllocSplitting::ShrinkWrapToLastUse(MachineBasicBlock *MBB, VNInfo *ValNo,
488                                        SmallVector<MachineOperand*, 4> &Uses,
489                                        SmallPtrSet<MachineInstr*, 4> &UseMIs) {
490   MachineOperand *LastMO = 0;
491   MachineInstr *LastMI = 0;
492   if (MBB != BarrierMBB && Uses.size() == 1) {
493     // Single use, no need to traverse the block. We can't assume this for the
494     // barrier bb though since the use is probably below the barrier.
495     LastMO = Uses[0];
496     LastMI = LastMO->getParent();
497   } else {
498     MachineBasicBlock::iterator MEE = MBB->begin();
499     MachineBasicBlock::iterator MII;
500     if (MBB == BarrierMBB)
501       MII = Barrier;
502     else
503       MII = MBB->end();
504     while (MII != MEE) {
505       --MII;
506       MachineInstr *UseMI = &*MII;
507       if (!UseMIs.count(UseMI))
508         continue;
509       for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
510         MachineOperand &MO = UseMI->getOperand(i);
511         if (MO.isReg() && MO.getReg() == CurrLI->reg) {
512           LastMO = &MO;
513           break;
514         }
515       }
516       LastMI = UseMI;
517       break;
518     }
519   }
520
521   // Cut off live range from last use (or beginning of the mbb if there
522   // are no uses in it) to the end of the mbb.
523   unsigned RangeStart, RangeEnd = LIs->getMBBEndIdx(MBB)+1;
524   if (LastMI) {
525     RangeStart = LIs->getUseIndex(LIs->getInstructionIndex(LastMI))+1;
526     assert(!LastMO->isKill() && "Last use already terminates the interval?");
527     LastMO->setIsKill();
528   } else {
529     assert(MBB == BarrierMBB);
530     RangeStart = LIs->getMBBStartIdx(MBB);
531   }
532   if (MBB == BarrierMBB)
533     RangeEnd = LIs->getUseIndex(BarrierIdx)+1;
534   CurrLI->removeRange(RangeStart, RangeEnd);
535   if (LastMI)
536     CurrLI->addKill(ValNo, RangeStart);
537
538   // Return true if the last use becomes a new kill.
539   return LastMI;
540 }
541
542 /// ShrinkWrapLiveInterval - Recursively traverse the predecessor
543 /// chain to find the new 'kills' and shrink wrap the live interval to the
544 /// new kill indices.
545 void
546 PreAllocSplitting::ShrinkWrapLiveInterval(VNInfo *ValNo, MachineBasicBlock *MBB,
547                           MachineBasicBlock *SuccMBB, MachineBasicBlock *DefMBB,
548                                     SmallPtrSet<MachineBasicBlock*, 8> &Visited,
549            DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > &Uses,
550            DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > &UseMIs,
551                                   SmallVector<MachineBasicBlock*, 4> &UseMBBs) {
552   if (Visited.count(MBB))
553     return;
554
555   // If live interval is live in another successor path, then we can't process
556   // this block. But we may able to do so after all the successors have been
557   // processed.
558   if (MBB != BarrierMBB) {
559     for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
560            SE = MBB->succ_end(); SI != SE; ++SI) {
561       MachineBasicBlock *SMBB = *SI;
562       if (SMBB == SuccMBB)
563         continue;
564       if (CurrLI->liveAt(LIs->getMBBStartIdx(SMBB)))
565         return;
566     }
567   }
568
569   Visited.insert(MBB);
570
571   DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
572     UMII = Uses.find(MBB);
573   if (UMII != Uses.end()) {
574     // At least one use in this mbb, lets look for the kill.
575     DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
576       UMII2 = UseMIs.find(MBB);
577     if (ShrinkWrapToLastUse(MBB, ValNo, UMII->second, UMII2->second))
578       // Found a kill, shrink wrapping of this path ends here.
579       return;
580   } else if (MBB == DefMBB) {
581     // There are no uses after the def.
582     MachineInstr *DefMI = LIs->getInstructionFromIndex(ValNo->def);
583     if (UseMBBs.empty()) {
584       // The only use must be below barrier in the barrier block. It's safe to
585       // remove the def.
586       LIs->RemoveMachineInstrFromMaps(DefMI);
587       DefMI->eraseFromParent();
588       CurrLI->removeRange(ValNo->def, LIs->getMBBEndIdx(MBB)+1);
589     }
590   } else if (MBB == BarrierMBB) {
591     // Remove entire live range from start of mbb to barrier.
592     CurrLI->removeRange(LIs->getMBBStartIdx(MBB),
593                         LIs->getUseIndex(BarrierIdx)+1);
594   } else {
595     // Remove entire live range of the mbb out of the live interval.
596     CurrLI->removeRange(LIs->getMBBStartIdx(MBB), LIs->getMBBEndIdx(MBB)+1);
597   }
598
599   if (MBB == DefMBB)
600     // Reached the def mbb, stop traversing this path further.
601     return;
602
603   // Traverse the pathes up the predecessor chains further.
604   for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
605          PE = MBB->pred_end(); PI != PE; ++PI) {
606     MachineBasicBlock *Pred = *PI;
607     if (Pred == MBB)
608       continue;
609     if (Pred == DefMBB && ValNo->hasPHIKill)
610       // Pred is the def bb and the def reaches other val#s, we must
611       // allow the value to be live out of the bb.
612       continue;
613     ShrinkWrapLiveInterval(ValNo, Pred, MBB, DefMBB, Visited,
614                            Uses, UseMIs, UseMBBs);
615   }
616
617   return;
618 }
619
620 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
621 /// so it would not cross the barrier that's being processed. Shrink wrap
622 /// (minimize) the live interval to the last uses.
623 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
624   CurrLI = LI;
625
626   // Find live range where current interval cross the barrier.
627   LiveInterval::iterator LR =
628     CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
629   VNInfo *ValNo = LR->valno;
630
631   if (ValNo->def == ~1U) {
632     // Defined by a dead def? How can this be?
633     assert(0 && "Val# is defined by a dead def?");
634     abort();
635   }
636
637   // FIXME: For now, if definition is rematerializable, do not split.
638   MachineInstr *DefMI = (ValNo->def != ~0U)
639     ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
640   if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
641     return false;
642
643   // Find all references in the barrier mbb.
644   SmallPtrSet<MachineInstr*, 4> RefsInMBB;
645   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
646          E = MRI->reg_end(); I != E; ++I) {
647     MachineInstr *RefMI = &*I;
648     if (RefMI->getParent() == BarrierMBB)
649       RefsInMBB.insert(RefMI);
650   }
651
652   // Find a point to restore the value after the barrier.
653   unsigned RestoreIndex;
654   MachineBasicBlock::iterator RestorePt =
655     findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
656   if (RestorePt == BarrierMBB->end())
657     return false;
658
659   // Add a spill either before the barrier or after the definition.
660   MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
661   const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
662   unsigned SpillIndex = 0;
663   MachineInstr *SpillMI = NULL;
664   int SS = -1;
665   if (ValNo->def == ~0U) {
666     // If it's defined by a phi, we must split just before the barrier.
667     MachineBasicBlock::iterator SpillPt = 
668       findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
669     if (SpillPt == BarrierMBB->begin())
670       return false; // No gap to insert spill.
671     // Add spill.
672     SS = CreateSpillStackSlot(CurrLI->reg, RC);
673     TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
674     SpillMI = prior(SpillPt);
675     LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
676   } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
677                                  RestoreIndex, SpillIndex, SS)) {
678     // If it's already split, just restore the value. There is no need to spill
679     // the def again.
680     if (!DefMI)
681       return false; // Def is dead. Do nothing.
682     // Check if it's possible to insert a spill after the def MI.
683     MachineBasicBlock::iterator SpillPt;
684     if (DefMBB == BarrierMBB) {
685       // Add spill after the def and the last use before the barrier.
686       SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI, RefsInMBB, SpillIndex);
687       if (SpillPt == DefMBB->begin())
688         return false; // No gap to insert spill.
689     } else {
690       SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
691       if (SpillPt == DefMBB->end())
692         return false; // No gap to insert spill.
693     }
694     // Add spill. The store instruction kills the register if def is before
695     // the barrier in the barrier block.
696     SS = CreateSpillStackSlot(CurrLI->reg, RC);
697     TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
698                              DefMBB == BarrierMBB, SS, RC);
699     SpillMI = prior(SpillPt);
700     LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
701   }
702
703   // Remember def instruction index to spill index mapping.
704   if (DefMI && SpillMI)
705     Def2SpillMap[ValNo->def] = SpillIndex;
706
707   // Add restore.
708   TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
709   MachineInstr *LoadMI = prior(RestorePt);
710   LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
711
712   // If live interval is spilled in the same block as the barrier, just
713   // create a hole in the interval.
714   if (!DefMBB ||
715       (SpillMI && SpillMI->getParent() == BarrierMBB)) {
716     // Update spill stack slot live interval.
717     UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
718                             LIs->getDefIndex(RestoreIndex));
719
720     UpdateRegisterInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
721                            LIs->getDefIndex(RestoreIndex));
722
723     ++NumSplits;
724     return true;
725   }
726
727   // Update spill stack slot live interval.
728   UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
729                           LIs->getDefIndex(RestoreIndex));
730
731   // Shrink wrap the live interval by walking up the CFG and find the
732   // new kills.
733   // Now let's find all the uses of the val#.
734   DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > Uses;
735   DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > UseMIs;
736   SmallPtrSet<MachineBasicBlock*, 4> Seen;
737   SmallVector<MachineBasicBlock*, 4> UseMBBs;
738   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(CurrLI->reg),
739          UE = MRI->use_end(); UI != UE; ++UI) {
740     MachineOperand &UseMO = UI.getOperand();
741     MachineInstr *UseMI = UseMO.getParent();
742     unsigned UseIdx = LIs->getInstructionIndex(UseMI);
743     LiveInterval::iterator ULR = CurrLI->FindLiveRangeContaining(UseIdx);
744     if (ULR->valno != ValNo)
745       continue;
746     MachineBasicBlock *UseMBB = UseMI->getParent();
747     // Remember which other mbb's use this val#.
748     if (Seen.insert(UseMBB) && UseMBB != BarrierMBB)
749       UseMBBs.push_back(UseMBB);
750     DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
751       UMII = Uses.find(UseMBB);
752     if (UMII != Uses.end()) {
753       DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
754         UMII2 = UseMIs.find(UseMBB);
755       UMII->second.push_back(&UseMO);
756       UMII2->second.insert(UseMI);
757     } else {
758       SmallVector<MachineOperand*, 4> Ops;
759       Ops.push_back(&UseMO);
760       Uses.insert(std::make_pair(UseMBB, Ops));
761       SmallPtrSet<MachineInstr*, 4> MIs;
762       MIs.insert(UseMI);
763       UseMIs.insert(std::make_pair(UseMBB, MIs));
764     }
765   }
766
767   // Walk up the predecessor chains.
768   SmallPtrSet<MachineBasicBlock*, 8> Visited;
769   ShrinkWrapLiveInterval(ValNo, BarrierMBB, NULL, DefMBB, Visited,
770                          Uses, UseMIs, UseMBBs);
771
772   // FIXME: If ValNo->hasPHIKill is false, then renumber the val# by
773   // the restore.
774
775   // Remove live range from barrier to the restore. FIXME: Find a better
776   // point to re-start the live interval.
777   UpdateRegisterInterval(ValNo, LIs->getUseIndex(BarrierIdx)+1,
778                          LIs->getDefIndex(RestoreIndex));
779
780   ++NumSplits;
781   return true;
782 }
783
784 /// SplitRegLiveIntervals - Split all register live intervals that cross the
785 /// barrier that's being processed.
786 bool
787 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs) {
788   // First find all the virtual registers whose live intervals are intercepted
789   // by the current barrier.
790   SmallVector<LiveInterval*, 8> Intervals;
791   for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
792     if (TII->IgnoreRegisterClassBarriers(*RC))
793       continue;
794     std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
795     for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
796       unsigned Reg = VRs[i];
797       if (!LIs->hasInterval(Reg))
798         continue;
799       LiveInterval *LI = &LIs->getInterval(Reg);
800       if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
801         // Virtual register live interval is intercepted by the barrier. We
802         // should split and shrink wrap its interval if possible.
803         Intervals.push_back(LI);
804     }
805   }
806
807   // Process the affected live intervals.
808   bool Change = false;
809   while (!Intervals.empty()) {
810     if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
811       break;
812     LiveInterval *LI = Intervals.back();
813     Intervals.pop_back();
814     Change |= SplitRegLiveInterval(LI);
815   }
816
817   return Change;
818 }
819
820 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
821   CurrMF = &MF;
822   TM     = &MF.getTarget();
823   TII    = TM->getInstrInfo();
824   MFI    = MF.getFrameInfo();
825   MRI    = &MF.getRegInfo();
826   LIs    = &getAnalysis<LiveIntervals>();
827   LSs    = &getAnalysis<LiveStacks>();
828
829   bool MadeChange = false;
830
831   // Make sure blocks are numbered in order.
832   MF.RenumberBlocks();
833
834 #if 0
835   // FIXME: Go top down.
836   MachineBasicBlock *Entry = MF.begin();
837   SmallPtrSet<MachineBasicBlock*,16> Visited;
838
839   for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
840          DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
841        DFI != E; ++DFI) {
842     BarrierMBB = *DFI;
843     for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
844            E = BarrierMBB->end(); I != E; ++I) {
845       Barrier = &*I;
846       const TargetRegisterClass **BarrierRCs =
847         Barrier->getDesc().getRegClassBarriers();
848       if (!BarrierRCs)
849         continue;
850       BarrierIdx = LIs->getInstructionIndex(Barrier);
851       MadeChange |= SplitRegLiveIntervals(BarrierRCs);
852     }
853   }
854 #else
855   for (MachineFunction::reverse_iterator I = MF.rbegin(), E = MF.rend();
856        I != E; ++I) {
857     BarrierMBB = &*I;
858     for (MachineBasicBlock::reverse_iterator II = BarrierMBB->rbegin(),
859            EE = BarrierMBB->rend(); II != EE; ++II) {
860       Barrier = &*II;
861       const TargetRegisterClass **BarrierRCs =
862         Barrier->getDesc().getRegClassBarriers();
863       if (!BarrierRCs)
864         continue;
865       BarrierIdx = LIs->getInstructionIndex(Barrier);
866       MadeChange |= SplitRegLiveIntervals(BarrierRCs);
867     }
868   }
869 #endif
870
871   return MadeChange;
872 }