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