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