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