8e86213f77c3c9e4557148d7c22812120030ff8f
[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 STATISTIC(NumFolds, "Number of intervals split with spill folding");
44 STATISTIC(NumRenumbers, "Number of intervals renumbered into new registers");
45 STATISTIC(NumDeadSpills, "Number of dead spills removed");
46
47 namespace {
48   class VISIBILITY_HIDDEN PreAllocSplitting : public MachineFunctionPass {
49     MachineFunction       *CurrMF;
50     const TargetMachine   *TM;
51     const TargetInstrInfo *TII;
52     MachineFrameInfo      *MFI;
53     MachineRegisterInfo   *MRI;
54     LiveIntervals         *LIs;
55     LiveStacks            *LSs;
56
57     // Barrier - Current barrier being processed.
58     MachineInstr          *Barrier;
59
60     // BarrierMBB - Basic block where the barrier resides in.
61     MachineBasicBlock     *BarrierMBB;
62
63     // Barrier - Current barrier index.
64     unsigned              BarrierIdx;
65
66     // CurrLI - Current live interval being split.
67     LiveInterval          *CurrLI;
68
69     // CurrSLI - Current stack slot live interval.
70     LiveInterval          *CurrSLI;
71
72     // CurrSValNo - Current val# for the stack slot live interval.
73     VNInfo                *CurrSValNo;
74
75     // IntervalSSMap - A map from live interval to spill slots.
76     DenseMap<unsigned, int> IntervalSSMap;
77
78     // Def2SpillMap - A map from a def instruction index to spill index.
79     DenseMap<unsigned, unsigned> Def2SpillMap;
80
81   public:
82     static char ID;
83     PreAllocSplitting() : MachineFunctionPass(&ID) {}
84
85     virtual bool runOnMachineFunction(MachineFunction &MF);
86
87     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
88       AU.addRequired<LiveIntervals>();
89       AU.addPreserved<LiveIntervals>();
90       AU.addRequired<LiveStacks>();
91       AU.addPreserved<LiveStacks>();
92       AU.addPreserved<RegisterCoalescer>();
93       if (StrongPHIElim)
94         AU.addPreservedID(StrongPHIEliminationID);
95       else
96         AU.addPreservedID(PHIEliminationID);
97       AU.addRequired<MachineDominatorTree>();
98       AU.addRequired<MachineLoopInfo>();
99       AU.addPreserved<MachineDominatorTree>();
100       AU.addPreserved<MachineLoopInfo>();
101       MachineFunctionPass::getAnalysisUsage(AU);
102     }
103     
104     virtual void releaseMemory() {
105       IntervalSSMap.clear();
106       Def2SpillMap.clear();
107     }
108
109     virtual const char *getPassName() const {
110       return "Pre-Register Allocaton Live Interval Splitting";
111     }
112
113     /// print - Implement the dump method.
114     virtual void print(std::ostream &O, const Module* M = 0) const {
115       LIs->print(O, M);
116     }
117
118     void print(std::ostream *O, const Module* M = 0) const {
119       if (O) print(*O, M);
120     }
121
122   private:
123     MachineBasicBlock::iterator
124       findNextEmptySlot(MachineBasicBlock*, MachineInstr*,
125                         unsigned&);
126
127     MachineBasicBlock::iterator
128       findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
129                      SmallPtrSet<MachineInstr*, 4>&, unsigned&);
130
131     MachineBasicBlock::iterator
132       findRestorePoint(MachineBasicBlock*, MachineInstr*, unsigned,
133                      SmallPtrSet<MachineInstr*, 4>&, unsigned&);
134
135     int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
136
137     bool IsAvailableInStack(MachineBasicBlock*, unsigned, unsigned, unsigned,
138                             unsigned&, int&) const;
139
140     void UpdateSpillSlotInterval(VNInfo*, unsigned, unsigned);
141
142     VNInfo* UpdateRegisterInterval(VNInfo*, unsigned, unsigned);
143
144     bool ShrinkWrapToLastUse(MachineBasicBlock*, VNInfo*,
145                              SmallVector<MachineOperand*, 4>&,
146                              SmallPtrSet<MachineInstr*, 4>&);
147
148     void ShrinkWrapLiveInterval(VNInfo*, MachineBasicBlock*, MachineBasicBlock*,
149                         MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*, 8>&,
150                 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >&,
151                   DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >&,
152                                 SmallVector<MachineBasicBlock*, 4>&);
153
154     bool SplitRegLiveInterval(LiveInterval*);
155
156     bool SplitRegLiveIntervals(const TargetRegisterClass **,
157                                SmallPtrSet<LiveInterval*, 8>&);
158     
159     void RepairLiveInterval(LiveInterval* CurrLI, VNInfo* ValNo,
160                             MachineInstr* DefMI, unsigned RestoreIdx);
161     
162     bool createsNewJoin(LiveRange* LR, MachineBasicBlock* DefMBB,
163                         MachineBasicBlock* BarrierMBB);
164     bool Rematerialize(unsigned vreg, VNInfo* ValNo,
165                        MachineInstr* DefMI,
166                        MachineBasicBlock::iterator RestorePt,
167                        unsigned RestoreIdx,
168                        SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
169     MachineInstr* FoldSpill(unsigned vreg, const TargetRegisterClass* RC,
170                             MachineInstr* DefMI,
171                             MachineInstr* Barrier,
172                             MachineBasicBlock* MBB,
173                             int& SS,
174                             SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
175     void RenumberValno(VNInfo* VN);
176     void ReconstructLiveInterval(LiveInterval* LI);
177     bool removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split);
178     VNInfo* PerformPHIConstruction(MachineBasicBlock::iterator use,
179                                    MachineBasicBlock* MBB,
180                                    LiveInterval* LI,
181                                    SmallPtrSet<MachineInstr*, 4>& Visited,
182             DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
183             DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
184                                       DenseMap<MachineInstr*, VNInfo*>& NewVNs,
185                                 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
186                                 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
187                                         bool toplevel, bool intrablock);
188 };
189 } // end anonymous namespace
190
191 char PreAllocSplitting::ID = 0;
192
193 static RegisterPass<PreAllocSplitting>
194 X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
195
196 const PassInfo *const llvm::PreAllocSplittingID = &X;
197
198
199 /// findNextEmptySlot - Find a gap after the given machine instruction in the
200 /// instruction index map. If there isn't one, return end().
201 MachineBasicBlock::iterator
202 PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
203                                      unsigned &SpotIndex) {
204   MachineBasicBlock::iterator MII = MI;
205   if (++MII != MBB->end()) {
206     unsigned Index = LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
207     if (Index) {
208       SpotIndex = Index;
209       return MII;
210     }
211   }
212   return MBB->end();
213 }
214
215 /// findSpillPoint - Find a gap as far away from the given MI that's suitable
216 /// for spilling the current live interval. The index must be before any
217 /// defs and uses of the live interval register in the mbb. Return begin() if
218 /// none is found.
219 MachineBasicBlock::iterator
220 PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
221                                   MachineInstr *DefMI,
222                                   SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
223                                   unsigned &SpillIndex) {
224   MachineBasicBlock::iterator Pt = MBB->begin();
225
226   // Go top down if RefsInMBB is empty.
227   if (RefsInMBB.empty() && !DefMI) {
228     MachineBasicBlock::iterator MII = MBB->begin();
229     MachineBasicBlock::iterator EndPt = MI;
230     do {
231       ++MII;
232       unsigned Index = LIs->getInstructionIndex(MII);
233       unsigned Gap = LIs->findGapBeforeInstr(Index);
234       if (Gap) {
235         Pt = MII;
236         SpillIndex = Gap;
237         break;
238       }
239     } while (MII != EndPt);
240   } else {
241     MachineBasicBlock::iterator MII = MI;
242     MachineBasicBlock::iterator EndPt = DefMI
243       ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
244     while (MII != EndPt && !RefsInMBB.count(MII)) {
245       unsigned Index = LIs->getInstructionIndex(MII);
246       if (LIs->hasGapBeforeInstr(Index)) {
247         Pt = MII;
248         SpillIndex = LIs->findGapBeforeInstr(Index, true);
249       }
250       --MII;
251     }
252   }
253
254   return Pt;
255 }
256
257 /// findRestorePoint - Find a gap in the instruction index map that's suitable
258 /// for restoring the current live interval value. The index must be before any
259 /// uses of the live interval register in the mbb. Return end() if none is
260 /// found.
261 MachineBasicBlock::iterator
262 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
263                                     unsigned LastIdx,
264                                     SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
265                                     unsigned &RestoreIndex) {
266   // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
267   // begin index accordingly.
268   MachineBasicBlock::iterator Pt = MBB->end();
269   unsigned EndIdx = LIs->getMBBEndIdx(MBB);
270
271   // Go bottom up if RefsInMBB is empty and the end of the mbb isn't beyond
272   // the last index in the live range.
273   if (RefsInMBB.empty() && LastIdx >= EndIdx) {
274     MachineBasicBlock::iterator MII = MBB->getFirstTerminator();
275     MachineBasicBlock::iterator EndPt = MI;
276     --MII;
277     do {
278       unsigned Index = LIs->getInstructionIndex(MII);
279       unsigned Gap = LIs->findGapBeforeInstr(Index);
280       if (Gap) {
281         Pt = MII;
282         RestoreIndex = Gap;
283         break;
284       }
285       --MII;
286     } while (MII != EndPt);
287   } else {
288     MachineBasicBlock::iterator MII = MI;
289     MII = ++MII;
290     // FIXME: Limit the number of instructions to examine to reduce
291     // compile time?
292     while (MII != MBB->end()) {
293       unsigned Index = LIs->getInstructionIndex(MII);
294       if (Index > LastIdx)
295         break;
296       unsigned Gap = LIs->findGapBeforeInstr(Index);
297       if (Gap) {
298         Pt = MII;
299         RestoreIndex = Gap;
300       }
301       if (RefsInMBB.count(MII))
302         break;
303       ++MII;
304     }
305   }
306
307   return Pt;
308 }
309
310 /// CreateSpillStackSlot - Create a stack slot for the live interval being
311 /// split. If the live interval was previously split, just reuse the same
312 /// slot.
313 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
314                                             const TargetRegisterClass *RC) {
315   int SS;
316   DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
317   if (I != IntervalSSMap.end()) {
318     SS = I->second;
319   } else {
320     SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
321     IntervalSSMap[Reg] = SS;
322   }
323
324   // Create live interval for stack slot.
325   CurrSLI = &LSs->getOrCreateInterval(SS);
326   if (CurrSLI->hasAtLeastOneValue())
327     CurrSValNo = CurrSLI->getValNumInfo(0);
328   else
329     CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
330   return SS;
331 }
332
333 /// IsAvailableInStack - Return true if register is available in a split stack
334 /// slot at the specified index.
335 bool
336 PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
337                                     unsigned Reg, unsigned DefIndex,
338                                     unsigned RestoreIndex, unsigned &SpillIndex,
339                                     int& SS) const {
340   if (!DefMBB)
341     return false;
342
343   DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
344   if (I == IntervalSSMap.end())
345     return false;
346   DenseMap<unsigned, unsigned>::iterator II = Def2SpillMap.find(DefIndex);
347   if (II == Def2SpillMap.end())
348     return false;
349
350   // If last spill of def is in the same mbb as barrier mbb (where restore will
351   // be), make sure it's not below the intended restore index.
352   // FIXME: Undo the previous spill?
353   assert(LIs->getMBBFromIndex(II->second) == DefMBB);
354   if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
355     return false;
356
357   SS = I->second;
358   SpillIndex = II->second;
359   return true;
360 }
361
362 /// UpdateSpillSlotInterval - Given the specified val# of the register live
363 /// interval being split, and the spill and restore indicies, update the live
364 /// interval of the spill stack slot.
365 void
366 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, unsigned SpillIndex,
367                                            unsigned RestoreIndex) {
368   assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
369          "Expect restore in the barrier mbb");
370
371   MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
372   if (MBB == BarrierMBB) {
373     // Intra-block spill + restore. We are done.
374     LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
375     CurrSLI->addRange(SLR);
376     return;
377   }
378
379   SmallPtrSet<MachineBasicBlock*, 4> Processed;
380   unsigned EndIdx = LIs->getMBBEndIdx(MBB);
381   LiveRange SLR(SpillIndex, EndIdx+1, CurrSValNo);
382   CurrSLI->addRange(SLR);
383   Processed.insert(MBB);
384
385   // Start from the spill mbb, figure out the extend of the spill slot's
386   // live interval.
387   SmallVector<MachineBasicBlock*, 4> WorkList;
388   const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
389   if (LR->end > EndIdx)
390     // If live range extend beyond end of mbb, add successors to work list.
391     for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
392            SE = MBB->succ_end(); SI != SE; ++SI)
393       WorkList.push_back(*SI);
394
395   while (!WorkList.empty()) {
396     MachineBasicBlock *MBB = WorkList.back();
397     WorkList.pop_back();
398     if (Processed.count(MBB))
399       continue;
400     unsigned Idx = LIs->getMBBStartIdx(MBB);
401     LR = CurrLI->getLiveRangeContaining(Idx);
402     if (LR && LR->valno == ValNo) {
403       EndIdx = LIs->getMBBEndIdx(MBB);
404       if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
405         // Spill slot live interval stops at the restore.
406         LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
407         CurrSLI->addRange(SLR);
408       } else if (LR->end > EndIdx) {
409         // Live range extends beyond end of mbb, process successors.
410         LiveRange SLR(Idx, EndIdx+1, CurrSValNo);
411         CurrSLI->addRange(SLR);
412         for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
413                SE = MBB->succ_end(); SI != SE; ++SI)
414           WorkList.push_back(*SI);
415       } else {
416         LiveRange SLR(Idx, LR->end, CurrSValNo);
417         CurrSLI->addRange(SLR);
418       }
419       Processed.insert(MBB);
420     }
421   }
422 }
423
424 /// UpdateRegisterInterval - Given the specified val# of the current live
425 /// interval is being split, and the spill and restore indices, update the live
426 /// interval accordingly.
427 VNInfo*
428 PreAllocSplitting::UpdateRegisterInterval(VNInfo *ValNo, unsigned SpillIndex,
429                                           unsigned RestoreIndex) {
430   assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
431          "Expect restore in the barrier mbb");
432
433   SmallVector<std::pair<unsigned,unsigned>, 4> Before;
434   SmallVector<std::pair<unsigned,unsigned>, 4> After;
435   SmallVector<unsigned, 4> BeforeKills;
436   SmallVector<unsigned, 4> AfterKills;
437   SmallPtrSet<const LiveRange*, 4> Processed;
438
439   // First, let's figure out which parts of the live interval is now defined
440   // by the restore, which are defined by the original definition.
441   const LiveRange *LR = CurrLI->getLiveRangeContaining(RestoreIndex);
442   After.push_back(std::make_pair(RestoreIndex, LR->end));
443   if (CurrLI->isKill(ValNo, LR->end))
444     AfterKills.push_back(LR->end);
445
446   assert(LR->contains(SpillIndex));
447   if (SpillIndex > LR->start) {
448     Before.push_back(std::make_pair(LR->start, SpillIndex));
449     BeforeKills.push_back(SpillIndex);
450   }
451   Processed.insert(LR);
452
453   // Start from the restore mbb, figure out what part of the live interval
454   // are defined by the restore.
455   SmallVector<MachineBasicBlock*, 4> WorkList;
456   MachineBasicBlock *MBB = BarrierMBB;
457   for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
458          SE = MBB->succ_end(); SI != SE; ++SI)
459     WorkList.push_back(*SI);
460
461   SmallPtrSet<MachineBasicBlock*, 4> ProcessedBlocks;
462   ProcessedBlocks.insert(MBB);
463
464   while (!WorkList.empty()) {
465     MBB = WorkList.back();
466     WorkList.pop_back();
467     unsigned Idx = LIs->getMBBStartIdx(MBB);
468     LR = CurrLI->getLiveRangeContaining(Idx);
469     if (LR && LR->valno == ValNo && !Processed.count(LR)) {
470       After.push_back(std::make_pair(LR->start, LR->end));
471       if (CurrLI->isKill(ValNo, LR->end))
472         AfterKills.push_back(LR->end);
473       Idx = LIs->getMBBEndIdx(MBB);
474       if (LR->end > Idx) {
475         // Live range extend beyond at least one mbb. Let's see what other
476         // mbbs it reaches.
477         LIs->findReachableMBBs(LR->start, LR->end, WorkList);
478       }
479       Processed.insert(LR);
480     }
481     
482     ProcessedBlocks.insert(MBB);
483     if (LR)
484       for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
485             SE = MBB->succ_end(); SI != SE; ++SI)
486         if (!ProcessedBlocks.count(*SI))
487           WorkList.push_back(*SI);
488   }
489
490   for (LiveInterval::iterator I = CurrLI->begin(), E = CurrLI->end();
491        I != E; ++I) {
492     LiveRange *LR = I;
493     if (LR->valno == ValNo && !Processed.count(LR)) {
494       Before.push_back(std::make_pair(LR->start, LR->end));
495       if (CurrLI->isKill(ValNo, LR->end))
496         BeforeKills.push_back(LR->end);
497     }
498   }
499
500   // Now create new val#s to represent the live ranges defined by the old def
501   // those defined by the restore.
502   unsigned AfterDef = ValNo->def;
503   MachineInstr *AfterCopy = ValNo->copy;
504   bool HasPHIKill = ValNo->hasPHIKill;
505   CurrLI->removeValNo(ValNo);
506   VNInfo *BValNo = (Before.empty())
507     ? NULL
508     : CurrLI->getNextValue(AfterDef, AfterCopy, LIs->getVNInfoAllocator());
509   if (BValNo)
510     CurrLI->addKills(BValNo, BeforeKills);
511
512   VNInfo *AValNo = (After.empty())
513     ? NULL
514     : CurrLI->getNextValue(RestoreIndex, 0, LIs->getVNInfoAllocator());
515   if (AValNo) {
516     AValNo->hasPHIKill = HasPHIKill;
517     CurrLI->addKills(AValNo, AfterKills);
518   }
519
520   for (unsigned i = 0, e = Before.size(); i != e; ++i) {
521     unsigned Start = Before[i].first;
522     unsigned End   = Before[i].second;
523     CurrLI->addRange(LiveRange(Start, End, BValNo));
524   }
525   for (unsigned i = 0, e = After.size(); i != e; ++i) {
526     unsigned Start = After[i].first;
527     unsigned End   = After[i].second;
528     CurrLI->addRange(LiveRange(Start, End, AValNo));
529   }
530   
531   return AValNo;
532 }
533
534 /// ShrinkWrapToLastUse - There are uses of the current live interval in the
535 /// given block, shrink wrap the live interval to the last use (i.e. remove
536 /// from last use to the end of the mbb). In case mbb is the where the barrier
537 /// is, remove from the last use to the barrier.
538 bool
539 PreAllocSplitting::ShrinkWrapToLastUse(MachineBasicBlock *MBB, VNInfo *ValNo,
540                                        SmallVector<MachineOperand*, 4> &Uses,
541                                        SmallPtrSet<MachineInstr*, 4> &UseMIs) {
542   MachineOperand *LastMO = 0;
543   MachineInstr *LastMI = 0;
544   if (MBB != BarrierMBB && Uses.size() == 1) {
545     // Single use, no need to traverse the block. We can't assume this for the
546     // barrier bb though since the use is probably below the barrier.
547     LastMO = Uses[0];
548     LastMI = LastMO->getParent();
549   } else {
550     MachineBasicBlock::iterator MEE = MBB->begin();
551     MachineBasicBlock::iterator MII;
552     if (MBB == BarrierMBB)
553       MII = Barrier;
554     else
555       MII = MBB->end();
556     while (MII != MEE) {
557       --MII;
558       MachineInstr *UseMI = &*MII;
559       if (!UseMIs.count(UseMI))
560         continue;
561       for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
562         MachineOperand &MO = UseMI->getOperand(i);
563         if (MO.isReg() && MO.getReg() == CurrLI->reg) {
564           LastMO = &MO;
565           break;
566         }
567       }
568       LastMI = UseMI;
569       break;
570     }
571   }
572
573   // Cut off live range from last use (or beginning of the mbb if there
574   // are no uses in it) to the end of the mbb.
575   unsigned RangeStart, RangeEnd = LIs->getMBBEndIdx(MBB)+1;
576   if (LastMI) {
577     RangeStart = LIs->getUseIndex(LIs->getInstructionIndex(LastMI))+1;
578     assert(!LastMO->isKill() && "Last use already terminates the interval?");
579     LastMO->setIsKill();
580   } else {
581     assert(MBB == BarrierMBB);
582     RangeStart = LIs->getMBBStartIdx(MBB);
583   }
584   if (MBB == BarrierMBB)
585     RangeEnd = LIs->getUseIndex(BarrierIdx)+1;
586   CurrLI->removeRange(RangeStart, RangeEnd);
587   if (LastMI)
588     CurrLI->addKill(ValNo, RangeStart);
589
590   // Return true if the last use becomes a new kill.
591   return LastMI;
592 }
593
594 /// PerformPHIConstruction - From properly set up use and def lists, use a PHI
595 /// construction algorithm to compute the ranges and valnos for an interval.
596 VNInfo* PreAllocSplitting::PerformPHIConstruction(
597                                                 MachineBasicBlock::iterator use,
598                                                          MachineBasicBlock* MBB,
599                                                                LiveInterval* LI,
600                                        SmallPtrSet<MachineInstr*, 4>& Visited,
601              DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
602              DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
603                                        DenseMap<MachineInstr*, VNInfo*>& NewVNs,
604                                  DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
605                                  DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
606                                               bool toplevel, bool intrablock) {
607   // Return memoized result if it's available.
608   if (toplevel && Visited.count(use) && NewVNs.count(use))
609     return NewVNs[use];
610   else if (!toplevel && intrablock && NewVNs.count(use))
611     return NewVNs[use];
612   else if (!intrablock && LiveOut.count(MBB))
613     return LiveOut[MBB];
614   
615   typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
616   
617   // Check if our block contains any uses or defs.
618   bool ContainsDefs = Defs.count(MBB);
619   bool ContainsUses = Uses.count(MBB);
620   
621   VNInfo* ret = 0;
622   
623   // Enumerate the cases of use/def contaning blocks.
624   if (!ContainsDefs && !ContainsUses) {
625   Fallback:
626     // NOTE: Because this is the fallback case from other cases, we do NOT
627     // assume that we are not intrablock here.
628     if (Phis.count(MBB)) return Phis[MBB];
629     
630     unsigned StartIndex = LIs->getMBBStartIdx(MBB);
631     
632     if (MBB->pred_size() == 1) {
633       Phis[MBB] = ret = PerformPHIConstruction((*MBB->pred_begin())->end(),
634                                           *(MBB->pred_begin()), LI, Visited,
635                                           Defs, Uses, NewVNs, LiveOut, Phis,
636                                           false, false);
637       unsigned EndIndex = 0;
638       if (intrablock) {
639         EndIndex = LIs->getInstructionIndex(use);
640         EndIndex = LiveIntervals::getUseIndex(EndIndex);
641       } else
642         EndIndex = LIs->getMBBEndIdx(MBB);
643       
644       LI->addRange(LiveRange(StartIndex, EndIndex+1, ret));
645       if (intrablock)
646         LI->addKill(ret, EndIndex);
647     } else {
648       Phis[MBB] = ret = LI->getNextValue(~0U, /*FIXME*/ 0,
649                                           LIs->getVNInfoAllocator());
650       if (!intrablock) LiveOut[MBB] = ret;
651     
652       // If there are no uses or defs between our starting point and the
653       // beginning of the block, then recursive perform phi construction
654       // on our predecessors.
655       DenseMap<MachineBasicBlock*, VNInfo*> IncomingVNs;
656       for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
657            PE = MBB->pred_end(); PI != PE; ++PI) {
658         VNInfo* Incoming = PerformPHIConstruction((*PI)->end(), *PI, LI, 
659                                             Visited, Defs, Uses, NewVNs,
660                                             LiveOut, Phis, false, false);
661         if (Incoming != 0)
662           IncomingVNs[*PI] = Incoming;
663       }
664     
665       // Otherwise, merge the incoming VNInfos with a phi join.  Create a new
666       // VNInfo to represent the joined value.
667       for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator I =
668            IncomingVNs.begin(), E = IncomingVNs.end(); I != E; ++I) {
669         I->second->hasPHIKill = true;
670         unsigned KillIndex = LIs->getMBBEndIdx(I->first);
671         LI->addKill(I->second, KillIndex);
672       }
673       
674       unsigned EndIndex = 0;
675       if (intrablock) {
676         EndIndex = LIs->getInstructionIndex(use);
677         EndIndex = LiveIntervals::getUseIndex(EndIndex);
678       } else
679         EndIndex = LIs->getMBBEndIdx(MBB);
680       LI->addRange(LiveRange(StartIndex, EndIndex+1, ret));
681       if (intrablock)
682         LI->addKill(ret, EndIndex);
683     }
684   } else if (ContainsDefs && !ContainsUses) {
685     SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
686
687     // Search for the def in this block.  If we don't find it before the
688     // instruction we care about, go to the fallback case.  Note that that
689     // should never happen: this cannot be intrablock, so use should
690     // always be an end() iterator.
691     assert(use == MBB->end() && "No use marked in intrablock");
692     
693     MachineBasicBlock::iterator walker = use;
694     --walker;
695     while (walker != MBB->begin())
696       if (BlockDefs.count(walker)) {
697         break;
698       } else
699         --walker;
700     
701     // Once we've found it, extend its VNInfo to our instruction.
702     unsigned DefIndex = LIs->getInstructionIndex(walker);
703     DefIndex = LiveIntervals::getDefIndex(DefIndex);
704     unsigned EndIndex = LIs->getMBBEndIdx(MBB);
705     
706     ret = NewVNs[walker];
707     LI->addRange(LiveRange(DefIndex, EndIndex+1, ret));
708   } else if (!ContainsDefs && ContainsUses) {
709     SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
710     
711     // Search for the use in this block that precedes the instruction we care 
712     // about, going to the fallback case if we don't find it.
713     
714     if (use == MBB->begin())
715       goto Fallback;
716     
717     MachineBasicBlock::iterator walker = use;
718     --walker;
719     bool found = false;
720     while (walker != MBB->begin())
721       if (BlockUses.count(walker)) {
722         found = true;
723         break;
724       } else
725         --walker;
726         
727     // Must check begin() too.
728     if (!found) {
729       if (BlockUses.count(walker))
730         found = true;
731       else
732         goto Fallback;
733     }
734
735     unsigned UseIndex = LIs->getInstructionIndex(walker);
736     UseIndex = LiveIntervals::getUseIndex(UseIndex);
737     unsigned EndIndex = 0;
738     if (intrablock) {
739       EndIndex = LIs->getInstructionIndex(use);
740       EndIndex = LiveIntervals::getUseIndex(EndIndex);
741     } else
742       EndIndex = LIs->getMBBEndIdx(MBB);
743
744     // Now, recursively phi construct the VNInfo for the use we found,
745     // and then extend it to include the instruction we care about
746     ret = PerformPHIConstruction(walker, MBB, LI, Visited, Defs, Uses,
747                                  NewVNs, LiveOut, Phis, false, true);
748     
749     // FIXME: Need to set kills properly for inter-block stuff.
750     if (LI->isKill(ret, UseIndex)) LI->removeKill(ret, UseIndex);
751     if (intrablock)
752       LI->addKill(ret, EndIndex);
753     
754     LI->addRange(LiveRange(UseIndex, EndIndex+1, ret));
755   } else if (ContainsDefs && ContainsUses){
756     SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
757     SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
758     
759     // This case is basically a merging of the two preceding case, with the
760     // special note that checking for defs must take precedence over checking
761     // for uses, because of two-address instructions.
762     
763     if (use == MBB->begin())
764       goto Fallback;
765     
766     MachineBasicBlock::iterator walker = use;
767     --walker;
768     bool foundDef = false;
769     bool foundUse = false;
770     while (walker != MBB->begin())
771       if (BlockDefs.count(walker)) {
772         foundDef = true;
773         break;
774       } else if (BlockUses.count(walker)) {
775         foundUse = true;
776         break;
777       } else
778         --walker;
779         
780     // Must check begin() too.
781     if (!foundDef && !foundUse) {
782       if (BlockDefs.count(walker))
783         foundDef = true;
784       else if (BlockUses.count(walker))
785         foundUse = true;
786       else
787         goto Fallback;
788     }
789
790     unsigned StartIndex = LIs->getInstructionIndex(walker);
791     StartIndex = foundDef ? LiveIntervals::getDefIndex(StartIndex) :
792                             LiveIntervals::getUseIndex(StartIndex);
793     unsigned EndIndex = 0;
794     if (intrablock) {
795       EndIndex = LIs->getInstructionIndex(use);
796       EndIndex = LiveIntervals::getUseIndex(EndIndex);
797     } else
798       EndIndex = LIs->getMBBEndIdx(MBB);
799
800     if (foundDef)
801       ret = NewVNs[walker];
802     else
803       ret = PerformPHIConstruction(walker, MBB, LI, Visited, Defs, Uses,
804                                    NewVNs, LiveOut, Phis, false, true);
805
806     if (foundUse && LI->isKill(ret, StartIndex))
807       LI->removeKill(ret, StartIndex);
808     if (intrablock) {
809       LI->addKill(ret, EndIndex);
810     }
811
812     LI->addRange(LiveRange(StartIndex, EndIndex+1, ret));
813   }
814   
815   // Memoize results so we don't have to recompute them.
816   if (!intrablock) LiveOut[MBB] = ret;
817   else {
818     if (!NewVNs.count(use))
819       NewVNs[use] = ret;
820     Visited.insert(use);
821   }
822
823   return ret;
824 }
825
826 /// ReconstructLiveInterval - Recompute a live interval from scratch.
827 void PreAllocSplitting::ReconstructLiveInterval(LiveInterval* LI) {
828   BumpPtrAllocator& Alloc = LIs->getVNInfoAllocator();
829   
830   // Clear the old ranges and valnos;
831   LI->clear();
832   
833   // Cache the uses and defs of the register
834   typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
835   RegMap Defs, Uses;
836   
837   // Keep track of the new VNs we're creating.
838   DenseMap<MachineInstr*, VNInfo*> NewVNs;
839   SmallPtrSet<VNInfo*, 2> PhiVNs;
840   
841   // Cache defs, and create a new VNInfo for each def.
842   for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
843        DE = MRI->def_end(); DI != DE; ++DI) {
844     Defs[(*DI).getParent()].insert(&*DI);
845     
846     unsigned DefIdx = LIs->getInstructionIndex(&*DI);
847     DefIdx = LiveIntervals::getDefIndex(DefIdx);
848     
849     VNInfo* NewVN = LI->getNextValue(DefIdx, 0, Alloc);
850     
851     // If the def is a move, set the copy field.
852     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
853     if (TII->isMoveInstr(*DI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
854       if (DstReg == LI->reg)
855         NewVN->copy = &*DI;
856     
857     NewVNs[&*DI] = NewVN;
858   }
859   
860   // Cache uses as a separate pass from actually processing them.
861   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
862        UE = MRI->use_end(); UI != UE; ++UI)
863     Uses[(*UI).getParent()].insert(&*UI);
864     
865   // Now, actually process every use and use a phi construction algorithm
866   // to walk from it to its reaching definitions, building VNInfos along
867   // the way.
868   DenseMap<MachineBasicBlock*, VNInfo*> LiveOut;
869   DenseMap<MachineBasicBlock*, VNInfo*> Phis;
870   SmallPtrSet<MachineInstr*, 4> Visited;
871   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
872        UE = MRI->use_end(); UI != UE; ++UI) {
873     PerformPHIConstruction(&*UI, UI->getParent(), LI, Visited, Defs,
874                            Uses, NewVNs, LiveOut, Phis, true, true); 
875   }
876   
877   // Add ranges for dead defs
878   for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
879        DE = MRI->def_end(); DI != DE; ++DI) {
880     unsigned DefIdx = LIs->getInstructionIndex(&*DI);
881     DefIdx = LiveIntervals::getDefIndex(DefIdx);
882     
883     if (LI->liveAt(DefIdx)) continue;
884     
885     VNInfo* DeadVN = NewVNs[&*DI];
886     LI->addRange(LiveRange(DefIdx, DefIdx+1, DeadVN));
887     LI->addKill(DeadVN, DefIdx);
888   }
889 }
890
891 /// ShrinkWrapLiveInterval - Recursively traverse the predecessor
892 /// chain to find the new 'kills' and shrink wrap the live interval to the
893 /// new kill indices.
894 void
895 PreAllocSplitting::ShrinkWrapLiveInterval(VNInfo *ValNo, MachineBasicBlock *MBB,
896                           MachineBasicBlock *SuccMBB, MachineBasicBlock *DefMBB,
897                                     SmallPtrSet<MachineBasicBlock*, 8> &Visited,
898            DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > &Uses,
899            DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > &UseMIs,
900                                   SmallVector<MachineBasicBlock*, 4> &UseMBBs) {
901   if (Visited.count(MBB))
902     return;
903
904   // If live interval is live in another successor path, then we can't process
905   // this block. But we may able to do so after all the successors have been
906   // processed.
907   if (MBB != BarrierMBB) {
908     for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
909            SE = MBB->succ_end(); SI != SE; ++SI) {
910       MachineBasicBlock *SMBB = *SI;
911       if (SMBB == SuccMBB)
912         continue;
913       if (CurrLI->liveAt(LIs->getMBBStartIdx(SMBB)))
914         return;
915     }
916   }
917
918   Visited.insert(MBB);
919
920   DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
921     UMII = Uses.find(MBB);
922   if (UMII != Uses.end()) {
923     // At least one use in this mbb, lets look for the kill.
924     DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
925       UMII2 = UseMIs.find(MBB);
926     if (ShrinkWrapToLastUse(MBB, ValNo, UMII->second, UMII2->second))
927       // Found a kill, shrink wrapping of this path ends here.
928       return;
929   } else if (MBB == DefMBB) {
930     // There are no uses after the def.
931     MachineInstr *DefMI = LIs->getInstructionFromIndex(ValNo->def);
932     if (UseMBBs.empty()) {
933       // The only use must be below barrier in the barrier block. It's safe to
934       // remove the def.
935       LIs->RemoveMachineInstrFromMaps(DefMI);
936       DefMI->eraseFromParent();
937       CurrLI->removeRange(ValNo->def, LIs->getMBBEndIdx(MBB)+1);
938     }
939   } else if (MBB == BarrierMBB) {
940     // Remove entire live range from start of mbb to barrier.
941     CurrLI->removeRange(LIs->getMBBStartIdx(MBB),
942                         LIs->getUseIndex(BarrierIdx)+1);
943   } else {
944     // Remove entire live range of the mbb out of the live interval.
945     CurrLI->removeRange(LIs->getMBBStartIdx(MBB), LIs->getMBBEndIdx(MBB)+1);
946   }
947
948   if (MBB == DefMBB)
949     // Reached the def mbb, stop traversing this path further.
950     return;
951
952   // Traverse the pathes up the predecessor chains further.
953   for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
954          PE = MBB->pred_end(); PI != PE; ++PI) {
955     MachineBasicBlock *Pred = *PI;
956     if (Pred == MBB)
957       continue;
958     if (Pred == DefMBB && ValNo->hasPHIKill)
959       // Pred is the def bb and the def reaches other val#s, we must
960       // allow the value to be live out of the bb.
961       continue;
962     if (!CurrLI->liveAt(LIs->getMBBEndIdx(Pred)-1))
963       return;
964     ShrinkWrapLiveInterval(ValNo, Pred, MBB, DefMBB, Visited,
965                            Uses, UseMIs, UseMBBs);
966   }
967
968   return;
969 }
970
971
972 void PreAllocSplitting::RepairLiveInterval(LiveInterval* CurrLI,
973                                            VNInfo* ValNo,
974                                            MachineInstr* DefMI,
975                                            unsigned RestoreIdx) {
976   // Shrink wrap the live interval by walking up the CFG and find the
977   // new kills.
978   // Now let's find all the uses of the val#.
979   DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > Uses;
980   DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > UseMIs;
981   SmallPtrSet<MachineBasicBlock*, 4> Seen;
982   SmallVector<MachineBasicBlock*, 4> UseMBBs;
983   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(CurrLI->reg),
984          UE = MRI->use_end(); UI != UE; ++UI) {
985     MachineOperand &UseMO = UI.getOperand();
986     MachineInstr *UseMI = UseMO.getParent();
987     unsigned UseIdx = LIs->getInstructionIndex(UseMI);
988     LiveInterval::iterator ULR = CurrLI->FindLiveRangeContaining(UseIdx);
989     if (ULR->valno != ValNo)
990       continue;
991     MachineBasicBlock *UseMBB = UseMI->getParent();
992     // Remember which other mbb's use this val#.
993     if (Seen.insert(UseMBB) && UseMBB != BarrierMBB)
994       UseMBBs.push_back(UseMBB);
995     DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
996       UMII = Uses.find(UseMBB);
997     if (UMII != Uses.end()) {
998       DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
999         UMII2 = UseMIs.find(UseMBB);
1000       UMII->second.push_back(&UseMO);
1001       UMII2->second.insert(UseMI);
1002     } else {
1003       SmallVector<MachineOperand*, 4> Ops;
1004       Ops.push_back(&UseMO);
1005       Uses.insert(std::make_pair(UseMBB, Ops));
1006       SmallPtrSet<MachineInstr*, 4> MIs;
1007       MIs.insert(UseMI);
1008       UseMIs.insert(std::make_pair(UseMBB, MIs));
1009     }
1010   }
1011
1012   // Walk up the predecessor chains.
1013   SmallPtrSet<MachineBasicBlock*, 8> Visited;
1014   ShrinkWrapLiveInterval(ValNo, BarrierMBB, NULL, DefMI->getParent(), Visited,
1015                          Uses, UseMIs, UseMBBs);
1016
1017   // Remove live range from barrier to the restore. FIXME: Find a better
1018   // point to re-start the live interval.
1019   VNInfo* AfterValNo = UpdateRegisterInterval(ValNo,
1020                                               LIs->getUseIndex(BarrierIdx)+1,
1021                                               LIs->getDefIndex(RestoreIdx));
1022   
1023   // Attempt to renumber the new valno into a new vreg.
1024   RenumberValno(AfterValNo);
1025 }
1026
1027 /// RenumberValno - Split the given valno out into a new vreg, allowing it to
1028 /// be allocated to a different register.  This function creates a new vreg,
1029 /// copies the valno and its live ranges over to the new vreg's interval,
1030 /// removes them from the old interval, and rewrites all uses and defs of
1031 /// the original reg to the new vreg within those ranges.
1032 void PreAllocSplitting::RenumberValno(VNInfo* VN) {
1033   SmallVector<VNInfo*, 4> Stack;
1034   SmallVector<VNInfo*, 4> VNsToCopy;
1035   Stack.push_back(VN);
1036
1037   // Walk through and copy the valno we care about, and any other valnos
1038   // that are two-address redefinitions of the one we care about.  These
1039   // will need to be rewritten as well.  We also check for safety of the 
1040   // renumbering here, by making sure that none of the valno involved has
1041   // phi kills.
1042   while (!Stack.empty()) {
1043     VNInfo* OldVN = Stack.back();
1044     Stack.pop_back();
1045     
1046     // Bail out if we ever encounter a valno that has a PHI kill.  We can't
1047     // renumber these.
1048     if (OldVN->hasPHIKill) return;
1049     
1050     VNsToCopy.push_back(OldVN);
1051     
1052     // Locate two-address redefinitions
1053     for (SmallVector<unsigned, 4>::iterator KI = OldVN->kills.begin(),
1054          KE = OldVN->kills.end(); KI != KE; ++KI) {
1055       MachineInstr* MI = LIs->getInstructionFromIndex(*KI);
1056       //if (!MI) continue;
1057       unsigned DefIdx = MI->findRegisterDefOperandIdx(CurrLI->reg);
1058       if (DefIdx == ~0U) continue;
1059       if (MI->isRegReDefinedByTwoAddr(DefIdx)) {
1060         VNInfo* NextVN =
1061                      CurrLI->findDefinedVNInfo(LiveIntervals::getDefIndex(*KI));
1062         Stack.push_back(NextVN);
1063       }
1064     }
1065   }
1066   
1067   // Create the new vreg
1068   unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
1069   
1070   // Create the new live interval
1071   LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
1072   
1073   for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE = 
1074        VNsToCopy.end(); OI != OE; ++OI) {
1075     VNInfo* OldVN = *OI;
1076     
1077     // Copy the valno over
1078     VNInfo* NewVN = NewLI.getNextValue(OldVN->def, OldVN->copy, 
1079                                        LIs->getVNInfoAllocator());
1080     NewLI.copyValNumInfo(NewVN, OldVN);
1081     NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
1082
1083     // Remove the valno from the old interval
1084     CurrLI->removeValNo(OldVN);
1085   }
1086   
1087   // Rewrite defs and uses.  This is done in two stages to avoid invalidating
1088   // the reg_iterator.
1089   SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
1090   
1091   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
1092          E = MRI->reg_end(); I != E; ++I) {
1093     MachineOperand& MO = I.getOperand();
1094     unsigned InstrIdx = LIs->getInstructionIndex(&*I);
1095     
1096     if ((MO.isUse() && NewLI.liveAt(LiveIntervals::getUseIndex(InstrIdx))) ||
1097         (MO.isDef() && NewLI.liveAt(LiveIntervals::getDefIndex(InstrIdx))))
1098       OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
1099   }
1100   
1101   for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
1102        OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
1103     MachineInstr* Inst = I->first;
1104     unsigned OpIdx = I->second;
1105     MachineOperand& MO = Inst->getOperand(OpIdx);
1106     MO.setReg(NewVReg);
1107   }
1108   
1109   NumRenumbers++;
1110 }
1111
1112 bool PreAllocSplitting::Rematerialize(unsigned vreg, VNInfo* ValNo,
1113                                       MachineInstr* DefMI,
1114                                       MachineBasicBlock::iterator RestorePt,
1115                                       unsigned RestoreIdx,
1116                                     SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
1117   MachineBasicBlock& MBB = *RestorePt->getParent();
1118   
1119   MachineBasicBlock::iterator KillPt = BarrierMBB->end();
1120   unsigned KillIdx = 0;
1121   if (ValNo->def == ~0U || DefMI->getParent() == BarrierMBB)
1122     KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, KillIdx);
1123   else
1124     KillPt = findNextEmptySlot(DefMI->getParent(), DefMI, KillIdx);
1125   
1126   if (KillPt == DefMI->getParent()->end())
1127     return false;
1128   
1129   TII->reMaterialize(MBB, RestorePt, vreg, DefMI);
1130   LIs->InsertMachineInstrInMaps(prior(RestorePt), RestoreIdx);
1131   
1132   if (KillPt->getParent() == BarrierMBB) {
1133     VNInfo* After = UpdateRegisterInterval(ValNo, LIs->getUseIndex(KillIdx)+1,
1134                            LIs->getDefIndex(RestoreIdx));
1135     
1136     RenumberValno(After);
1137
1138     ++NumSplits;
1139     ++NumRemats;
1140     return true;
1141   }
1142
1143   RepairLiveInterval(CurrLI, ValNo, DefMI, RestoreIdx);
1144   
1145   ++NumSplits;
1146   ++NumRemats;
1147   return true;  
1148 }
1149
1150 MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg, 
1151                                            const TargetRegisterClass* RC,
1152                                            MachineInstr* DefMI,
1153                                            MachineInstr* Barrier,
1154                                            MachineBasicBlock* MBB,
1155                                            int& SS,
1156                                     SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
1157   MachineBasicBlock::iterator Pt = MBB->begin();
1158
1159   // Go top down if RefsInMBB is empty.
1160   if (RefsInMBB.empty())
1161     return 0;
1162   
1163   MachineBasicBlock::iterator FoldPt = Barrier;
1164   while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
1165          !RefsInMBB.count(FoldPt))
1166     --FoldPt;
1167   
1168   int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg, false);
1169   if (OpIdx == -1)
1170     return 0;
1171   
1172   SmallVector<unsigned, 1> Ops;
1173   Ops.push_back(OpIdx);
1174   
1175   if (!TII->canFoldMemoryOperand(FoldPt, Ops))
1176     return 0;
1177   
1178   DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
1179   if (I != IntervalSSMap.end()) {
1180     SS = I->second;
1181   } else {
1182     SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
1183     
1184   }
1185   
1186   MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
1187                                              FoldPt, Ops, SS);
1188   
1189   if (FMI) {
1190     LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
1191     FMI = MBB->insert(MBB->erase(FoldPt), FMI);
1192     ++NumFolds;
1193     
1194     IntervalSSMap[vreg] = SS;
1195     CurrSLI = &LSs->getOrCreateInterval(SS);
1196     if (CurrSLI->hasAtLeastOneValue())
1197       CurrSValNo = CurrSLI->getValNumInfo(0);
1198     else
1199       CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
1200   }
1201   
1202   return FMI;
1203 }
1204
1205 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
1206 /// so it would not cross the barrier that's being processed. Shrink wrap
1207 /// (minimize) the live interval to the last uses.
1208 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
1209   CurrLI = LI;
1210
1211   // Find live range where current interval cross the barrier.
1212   LiveInterval::iterator LR =
1213     CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
1214   VNInfo *ValNo = LR->valno;
1215
1216   if (ValNo->def == ~1U) {
1217     // Defined by a dead def? How can this be?
1218     assert(0 && "Val# is defined by a dead def?");
1219     abort();
1220   }
1221
1222   MachineInstr *DefMI = (ValNo->def != ~0U)
1223     ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
1224
1225   // If this would create a new join point, do not split.
1226   if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent()))
1227     return false;
1228
1229   // Find all references in the barrier mbb.
1230   SmallPtrSet<MachineInstr*, 4> RefsInMBB;
1231   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
1232          E = MRI->reg_end(); I != E; ++I) {
1233     MachineInstr *RefMI = &*I;
1234     if (RefMI->getParent() == BarrierMBB)
1235       RefsInMBB.insert(RefMI);
1236   }
1237
1238   // Find a point to restore the value after the barrier.
1239   unsigned RestoreIndex;
1240   MachineBasicBlock::iterator RestorePt =
1241     findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
1242   if (RestorePt == BarrierMBB->end())
1243     return false;
1244
1245   if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
1246     if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt,
1247                       RestoreIndex, RefsInMBB))
1248     return true;
1249
1250   // Add a spill either before the barrier or after the definition.
1251   MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
1252   const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
1253   unsigned SpillIndex = 0;
1254   MachineInstr *SpillMI = NULL;
1255   int SS = -1;
1256   if (ValNo->def == ~0U) {
1257     // If it's defined by a phi, we must split just before the barrier.
1258     if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
1259                             BarrierMBB, SS, RefsInMBB))) {
1260       SpillIndex = LIs->getInstructionIndex(SpillMI);
1261     } else {
1262       MachineBasicBlock::iterator SpillPt = 
1263         findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
1264       if (SpillPt == BarrierMBB->begin())
1265         return false; // No gap to insert spill.
1266       // Add spill.
1267     
1268       SS = CreateSpillStackSlot(CurrLI->reg, RC);
1269       TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
1270       SpillMI = prior(SpillPt);
1271       LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1272     }
1273   } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
1274                                  RestoreIndex, SpillIndex, SS)) {
1275     // If it's already split, just restore the value. There is no need to spill
1276     // the def again.
1277     if (!DefMI)
1278       return false; // Def is dead. Do nothing.
1279     
1280     if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
1281                             BarrierMBB, SS, RefsInMBB))) {
1282       SpillIndex = LIs->getInstructionIndex(SpillMI);
1283     } else {
1284       // Check if it's possible to insert a spill after the def MI.
1285       MachineBasicBlock::iterator SpillPt;
1286       if (DefMBB == BarrierMBB) {
1287         // Add spill after the def and the last use before the barrier.
1288         SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
1289                                  RefsInMBB, SpillIndex);
1290         if (SpillPt == DefMBB->begin())
1291           return false; // No gap to insert spill.
1292       } else {
1293         SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
1294         if (SpillPt == DefMBB->end())
1295           return false; // No gap to insert spill.
1296       }
1297       // Add spill. The store instruction kills the register if def is before
1298       // the barrier in the barrier block.
1299       SS = CreateSpillStackSlot(CurrLI->reg, RC);
1300       TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
1301                                DefMBB == BarrierMBB, SS, RC);
1302       SpillMI = prior(SpillPt);
1303       LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1304     }
1305   }
1306
1307   // Remember def instruction index to spill index mapping.
1308   if (DefMI && SpillMI)
1309     Def2SpillMap[ValNo->def] = SpillIndex;
1310
1311   // Add restore.
1312   TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
1313   MachineInstr *LoadMI = prior(RestorePt);
1314   LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
1315
1316   // If live interval is spilled in the same block as the barrier, just
1317   // create a hole in the interval.
1318   if (!DefMBB ||
1319       (SpillMI && SpillMI->getParent() == BarrierMBB)) {
1320     // Update spill stack slot live interval.
1321     UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1322                             LIs->getDefIndex(RestoreIndex));
1323
1324     VNInfo* After = UpdateRegisterInterval(ValNo,
1325                            LIs->getUseIndex(SpillIndex)+1,
1326                            LIs->getDefIndex(RestoreIndex));
1327     RenumberValno(After);
1328    
1329     ++NumSplits;
1330     return true;
1331   }
1332
1333   // Update spill stack slot live interval.
1334   UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1335                           LIs->getDefIndex(RestoreIndex));
1336
1337   RepairLiveInterval(CurrLI, ValNo, DefMI, RestoreIndex);
1338   
1339   ++NumSplits;
1340   return true;
1341 }
1342
1343 /// SplitRegLiveIntervals - Split all register live intervals that cross the
1344 /// barrier that's being processed.
1345 bool
1346 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs,
1347                                          SmallPtrSet<LiveInterval*, 8>& Split) {
1348   // First find all the virtual registers whose live intervals are intercepted
1349   // by the current barrier.
1350   SmallVector<LiveInterval*, 8> Intervals;
1351   for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
1352     if (TII->IgnoreRegisterClassBarriers(*RC))
1353       continue;
1354     std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1355     for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1356       unsigned Reg = VRs[i];
1357       if (!LIs->hasInterval(Reg))
1358         continue;
1359       LiveInterval *LI = &LIs->getInterval(Reg);
1360       if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1361         // Virtual register live interval is intercepted by the barrier. We
1362         // should split and shrink wrap its interval if possible.
1363         Intervals.push_back(LI);
1364     }
1365   }
1366
1367   // Process the affected live intervals.
1368   bool Change = false;
1369   while (!Intervals.empty()) {
1370     if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1371       break;
1372     else if (NumSplits == 4)
1373       Change |= Change;
1374     LiveInterval *LI = Intervals.back();
1375     Intervals.pop_back();
1376     bool result = SplitRegLiveInterval(LI);
1377     if (result) Split.insert(LI);
1378     Change |= result;
1379   }
1380
1381   return Change;
1382 }
1383
1384 /// removeDeadSpills - After doing splitting, filter through all intervals we've
1385 /// split, and see if any of the spills are unnecessary.  If so, remove them.
1386 bool PreAllocSplitting::removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split) {
1387   bool changed = false;
1388   
1389   for (SmallPtrSet<LiveInterval*, 8>::iterator LI = split.begin(),
1390        LE = split.end(); LI != LE; ++LI) {
1391     DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> > VNUseCount;
1392     
1393     for (MachineRegisterInfo::use_iterator UI = MRI->use_begin((*LI)->reg),
1394          UE = MRI->use_end(); UI != UE; ++UI) {
1395       unsigned index = LIs->getInstructionIndex(&*UI);
1396       index = LiveIntervals::getUseIndex(index);
1397       
1398       const LiveRange* LR = (*LI)->getLiveRangeContaining(index);
1399       VNUseCount[LR->valno].insert(&*UI);
1400     }
1401     
1402     for (LiveInterval::vni_iterator VI = (*LI)->vni_begin(),
1403          VE = (*LI)->vni_end(); VI != VE; ++VI) {
1404       VNInfo* CurrVN = *VI;
1405       if (CurrVN->hasPHIKill) continue;
1406       
1407       unsigned DefIdx = CurrVN->def;
1408       if (DefIdx == ~0U || DefIdx == ~1U) continue;
1409     
1410       MachineInstr* DefMI = LIs->getInstructionFromIndex(DefIdx);
1411       int FrameIndex;
1412       if (!TII->isLoadFromStackSlot(DefMI, FrameIndex)) continue;
1413       
1414       if (VNUseCount[CurrVN].size() == 0) {
1415         LIs->RemoveMachineInstrFromMaps(DefMI);
1416         (*LI)->removeValNo(CurrVN);
1417         DefMI->eraseFromParent();
1418         NumDeadSpills++;
1419         changed = true;
1420       } else {
1421         bool NonRestore = false;
1422         for (SmallPtrSet<MachineInstr*, 4>::iterator UI = 
1423              VNUseCount[CurrVN].begin(), UE = VNUseCount[CurrVN].end();
1424              UI != UI; ++UI) {
1425           int StoreFrameIndex;
1426           unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1427           if (StoreVReg != (*LI)->reg || StoreFrameIndex != FrameIndex) {
1428             NonRestore = false;
1429             break;
1430           }
1431         }
1432         
1433         if (NonRestore) continue;
1434         
1435         for (SmallPtrSet<MachineInstr*, 4>::iterator UI = 
1436              VNUseCount[CurrVN].begin(), UE = VNUseCount[CurrVN].end();
1437              UI != UI; ++UI) {
1438           LIs->RemoveMachineInstrFromMaps(*UI);
1439           (*UI)->eraseFromParent();
1440         }
1441         
1442         LIs->RemoveMachineInstrFromMaps(DefMI);
1443         (*LI)->removeValNo(CurrVN);
1444         DefMI->eraseFromParent();
1445         NumDeadSpills++;
1446         changed = true;
1447       }
1448     }
1449   }
1450   
1451   return changed;
1452 }
1453
1454 bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1455                                        MachineBasicBlock* DefMBB,
1456                                        MachineBasicBlock* BarrierMBB) {
1457   if (DefMBB == BarrierMBB)
1458     return false;
1459   
1460   if (LR->valno->hasPHIKill)
1461     return false;
1462   
1463   unsigned MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1464   if (LR->end < MBBEnd)
1465     return false;
1466   
1467   MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1468   if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1469     return true;
1470   
1471   MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1472   SmallPtrSet<MachineBasicBlock*, 4> Visited;
1473   typedef std::pair<MachineBasicBlock*,
1474                     MachineBasicBlock::succ_iterator> ItPair;
1475   SmallVector<ItPair, 4> Stack;
1476   Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1477   
1478   while (!Stack.empty()) {
1479     ItPair P = Stack.back();
1480     Stack.pop_back();
1481     
1482     MachineBasicBlock* PredMBB = P.first;
1483     MachineBasicBlock::succ_iterator S = P.second;
1484     
1485     if (S == PredMBB->succ_end())
1486       continue;
1487     else if (Visited.count(*S)) {
1488       Stack.push_back(std::make_pair(PredMBB, ++S));
1489       continue;
1490     } else
1491       Stack.push_back(std::make_pair(PredMBB, S+1));
1492     
1493     MachineBasicBlock* MBB = *S;
1494     Visited.insert(MBB);
1495     
1496     if (MBB == BarrierMBB)
1497       return true;
1498     
1499     MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1500     MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1501     MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1502     while (MDTN) {
1503       if (MDTN == DefMDTN)
1504         return true;
1505       else if (MDTN == BarrierMDTN)
1506         break;
1507       MDTN = MDTN->getIDom();
1508     }
1509     
1510     MBBEnd = LIs->getMBBEndIdx(MBB);
1511     if (LR->end > MBBEnd)
1512       Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1513   }
1514   
1515   return false;
1516
1517   
1518
1519 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
1520   CurrMF = &MF;
1521   TM     = &MF.getTarget();
1522   TII    = TM->getInstrInfo();
1523   MFI    = MF.getFrameInfo();
1524   MRI    = &MF.getRegInfo();
1525   LIs    = &getAnalysis<LiveIntervals>();
1526   LSs    = &getAnalysis<LiveStacks>();
1527
1528   bool MadeChange = false;
1529
1530   // Make sure blocks are numbered in order.
1531   MF.RenumberBlocks();
1532
1533   MachineBasicBlock *Entry = MF.begin();
1534   SmallPtrSet<MachineBasicBlock*,16> Visited;
1535
1536   SmallPtrSet<LiveInterval*, 8> Split;
1537
1538   for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1539          DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1540        DFI != E; ++DFI) {
1541     BarrierMBB = *DFI;
1542     for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1543            E = BarrierMBB->end(); I != E; ++I) {
1544       Barrier = &*I;
1545       const TargetRegisterClass **BarrierRCs =
1546         Barrier->getDesc().getRegClassBarriers();
1547       if (!BarrierRCs)
1548         continue;
1549       BarrierIdx = LIs->getInstructionIndex(Barrier);
1550       MadeChange |= SplitRegLiveIntervals(BarrierRCs, Split);
1551     }
1552   }
1553
1554   MadeChange |= removeDeadSpills(Split);
1555
1556   return MadeChange;
1557 }