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