fb2f90935551c6c43900ec69a15522ae3047b43c
[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 const PassInfo *const llvm::PreAllocSplittingID = &X;
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     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
680     if (TII->isMoveInstr(*DI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
681       if (DstReg == LI->reg)
682         NewVN->setCopy(&*DI);
683     } else if (DI->isCopyLike() && DI->getOperand(0).getReg() == LI->reg)
684       NewVN->setCopy(&*DI);
685
686     NewVNs[&*DI] = NewVN;
687   }
688   
689   // Cache uses as a separate pass from actually processing them.
690   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
691        UE = MRI->use_end(); UI != UE; ++UI)
692     Uses[(*UI).getParent()].insert(&*UI);
693     
694   // Now, actually process every use and use a phi construction algorithm
695   // to walk from it to its reaching definitions, building VNInfos along
696   // the way.
697   DenseMap<MachineBasicBlock*, VNInfo*> LiveOut;
698   DenseMap<MachineBasicBlock*, VNInfo*> Phis;
699   SmallPtrSet<MachineInstr*, 4> Visited;
700   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
701        UE = MRI->use_end(); UI != UE; ++UI) {
702     PerformPHIConstruction(&*UI, UI->getParent(), LI, Visited, Defs,
703                            Uses, NewVNs, LiveOut, Phis, true, true); 
704   }
705   
706   // Add ranges for dead defs
707   for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
708        DE = MRI->def_end(); DI != DE; ++DI) {
709     SlotIndex DefIdx = LIs->getInstructionIndex(&*DI);
710     DefIdx = DefIdx.getDefIndex();
711     
712     if (LI->liveAt(DefIdx)) continue;
713     
714     VNInfo* DeadVN = NewVNs[&*DI];
715     LI->addRange(LiveRange(DefIdx, DefIdx.getNextSlot(), DeadVN));
716   }
717 }
718
719 /// RenumberValno - Split the given valno out into a new vreg, allowing it to
720 /// be allocated to a different register.  This function creates a new vreg,
721 /// copies the valno and its live ranges over to the new vreg's interval,
722 /// removes them from the old interval, and rewrites all uses and defs of
723 /// the original reg to the new vreg within those ranges.
724 void PreAllocSplitting::RenumberValno(VNInfo* VN) {
725   SmallVector<VNInfo*, 4> Stack;
726   SmallVector<VNInfo*, 4> VNsToCopy;
727   Stack.push_back(VN);
728
729   // Walk through and copy the valno we care about, and any other valnos
730   // that are two-address redefinitions of the one we care about.  These
731   // will need to be rewritten as well.  We also check for safety of the 
732   // renumbering here, by making sure that none of the valno involved has
733   // phi kills.
734   while (!Stack.empty()) {
735     VNInfo* OldVN = Stack.back();
736     Stack.pop_back();
737     
738     // Bail out if we ever encounter a valno that has a PHI kill.  We can't
739     // renumber these.
740     if (OldVN->hasPHIKill()) return;
741     
742     VNsToCopy.push_back(OldVN);
743     
744     // Locate two-address redefinitions
745     for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(CurrLI->reg),
746          DE = MRI->def_end(); DI != DE; ++DI) {
747       if (!DI->isRegTiedToUseOperand(DI.getOperandNo())) continue;
748       SlotIndex DefIdx = LIs->getInstructionIndex(&*DI).getDefIndex();
749       VNInfo* NextVN = CurrLI->findDefinedVNInfoForRegInt(DefIdx);
750       if (std::find(VNsToCopy.begin(), VNsToCopy.end(), NextVN) !=
751           VNsToCopy.end())
752         Stack.push_back(NextVN);
753     }
754   }
755   
756   // Create the new vreg
757   unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
758   
759   // Create the new live interval
760   LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
761   
762   for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE = 
763        VNsToCopy.end(); OI != OE; ++OI) {
764     VNInfo* OldVN = *OI;
765     
766     // Copy the valno over
767     VNInfo* NewVN = NewLI.createValueCopy(OldVN, LIs->getVNInfoAllocator());
768     NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
769
770     // Remove the valno from the old interval
771     CurrLI->removeValNo(OldVN);
772   }
773   
774   // Rewrite defs and uses.  This is done in two stages to avoid invalidating
775   // the reg_iterator.
776   SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
777   
778   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
779          E = MRI->reg_end(); I != E; ++I) {
780     MachineOperand& MO = I.getOperand();
781     SlotIndex InstrIdx = LIs->getInstructionIndex(&*I);
782     
783     if ((MO.isUse() && NewLI.liveAt(InstrIdx.getUseIndex())) ||
784         (MO.isDef() && NewLI.liveAt(InstrIdx.getDefIndex())))
785       OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
786   }
787   
788   for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
789        OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
790     MachineInstr* Inst = I->first;
791     unsigned OpIdx = I->second;
792     MachineOperand& MO = Inst->getOperand(OpIdx);
793     MO.setReg(NewVReg);
794   }
795   
796   // Grow the VirtRegMap, since we've created a new vreg.
797   VRM->grow();
798   
799   // The renumbered vreg shares a stack slot with the old register.
800   if (IntervalSSMap.count(CurrLI->reg))
801     IntervalSSMap[NewVReg] = IntervalSSMap[CurrLI->reg];
802   
803   ++NumRenumbers;
804 }
805
806 bool PreAllocSplitting::Rematerialize(unsigned VReg, VNInfo* ValNo,
807                                       MachineInstr* DefMI,
808                                       MachineBasicBlock::iterator RestorePt,
809                                     SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
810   MachineBasicBlock& MBB = *RestorePt->getParent();
811   
812   MachineBasicBlock::iterator KillPt = BarrierMBB->end();
813   if (!ValNo->isDefAccurate() || DefMI->getParent() == BarrierMBB)
814     KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB);
815   else
816     KillPt = llvm::next(MachineBasicBlock::iterator(DefMI));
817   
818   if (KillPt == DefMI->getParent()->end())
819     return false;
820   
821   TII->reMaterialize(MBB, RestorePt, VReg, 0, DefMI, *TRI);
822   SlotIndex RematIdx = LIs->InsertMachineInstrInMaps(prior(RestorePt));
823   
824   ReconstructLiveInterval(CurrLI);
825   RematIdx = RematIdx.getDefIndex();
826   RenumberValno(CurrLI->findDefinedVNInfoForRegInt(RematIdx));
827   
828   ++NumSplits;
829   ++NumRemats;
830   return true;  
831 }
832
833 MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg, 
834                                            const TargetRegisterClass* RC,
835                                            MachineInstr* DefMI,
836                                            MachineInstr* Barrier,
837                                            MachineBasicBlock* MBB,
838                                            int& SS,
839                                     SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
840   // Go top down if RefsInMBB is empty.
841   if (RefsInMBB.empty())
842     return 0;
843   
844   MachineBasicBlock::iterator FoldPt = Barrier;
845   while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
846          !RefsInMBB.count(FoldPt))
847     --FoldPt;
848   
849   int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg);
850   if (OpIdx == -1)
851     return 0;
852   
853   SmallVector<unsigned, 1> Ops;
854   Ops.push_back(OpIdx);
855   
856   if (!TII->canFoldMemoryOperand(FoldPt, Ops))
857     return 0;
858   
859   DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
860   if (I != IntervalSSMap.end()) {
861     SS = I->second;
862   } else {
863     SS = MFI->CreateSpillStackObject(RC->getSize(), RC->getAlignment());
864   }
865   
866   MachineInstr* FMI = TII->foldMemoryOperand(FoldPt, Ops, SS);
867   
868   if (FMI) {
869     LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
870     FoldPt->eraseFromParent();
871     ++NumFolds;
872     
873     IntervalSSMap[vreg] = SS;
874     CurrSLI = &LSs->getOrCreateInterval(SS, RC);
875     if (CurrSLI->hasAtLeastOneValue())
876       CurrSValNo = CurrSLI->getValNumInfo(0);
877     else
878       CurrSValNo = CurrSLI->getNextValue(SlotIndex(), 0, false,
879                                          LSs->getVNInfoAllocator());
880   }
881   
882   return FMI;
883 }
884
885 MachineInstr* PreAllocSplitting::FoldRestore(unsigned vreg, 
886                                              const TargetRegisterClass* RC,
887                                              MachineInstr* Barrier,
888                                              MachineBasicBlock* MBB,
889                                              int SS,
890                                      SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
891   if ((int)RestoreFoldLimit != -1 && RestoreFoldLimit == (int)NumRestoreFolds)
892     return 0;
893                                        
894   // Go top down if RefsInMBB is empty.
895   if (RefsInMBB.empty())
896     return 0;
897   
898   // Can't fold a restore between a call stack setup and teardown.
899   MachineBasicBlock::iterator FoldPt = Barrier;
900   
901   // Advance from barrier to call frame teardown.
902   while (FoldPt != MBB->getFirstTerminator() &&
903          FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
904     if (RefsInMBB.count(FoldPt))
905       return 0;
906     
907     ++FoldPt;
908   }
909   
910   if (FoldPt == MBB->getFirstTerminator())
911     return 0;
912   else
913     ++FoldPt;
914   
915   // Now find the restore point.
916   while (FoldPt != MBB->getFirstTerminator() && !RefsInMBB.count(FoldPt)) {
917     if (FoldPt->getOpcode() == TRI->getCallFrameSetupOpcode()) {
918       while (FoldPt != MBB->getFirstTerminator() &&
919              FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
920         if (RefsInMBB.count(FoldPt))
921           return 0;
922         
923         ++FoldPt;
924       }
925       
926       if (FoldPt == MBB->getFirstTerminator())
927         return 0;
928     } 
929     
930     ++FoldPt;
931   }
932   
933   if (FoldPt == MBB->getFirstTerminator())
934     return 0;
935   
936   int OpIdx = FoldPt->findRegisterUseOperandIdx(vreg, true);
937   if (OpIdx == -1)
938     return 0;
939   
940   SmallVector<unsigned, 1> Ops;
941   Ops.push_back(OpIdx);
942   
943   if (!TII->canFoldMemoryOperand(FoldPt, Ops))
944     return 0;
945   
946   MachineInstr* FMI = TII->foldMemoryOperand(FoldPt, Ops, SS);
947   
948   if (FMI) {
949     LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
950     FoldPt->eraseFromParent();
951     ++NumRestoreFolds;
952   }
953   
954   return FMI;
955 }
956
957 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
958 /// so it would not cross the barrier that's being processed. Shrink wrap
959 /// (minimize) the live interval to the last uses.
960 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
961   DEBUG(dbgs() << "Pre-alloc splitting " << LI->reg << " for " << *Barrier
962                << "  result: ");
963
964   CurrLI = LI;
965
966   // Find live range where current interval cross the barrier.
967   LiveInterval::iterator LR =
968     CurrLI->FindLiveRangeContaining(BarrierIdx.getUseIndex());
969   VNInfo *ValNo = LR->valno;
970
971   assert(!ValNo->isUnused() && "Val# is defined by a dead def?");
972
973   MachineInstr *DefMI = ValNo->isDefAccurate()
974     ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
975
976   // If this would create a new join point, do not split.
977   if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent())) {
978     DEBUG(dbgs() << "FAILED (would create a new join point).\n");
979     return false;
980   }
981
982   // Find all references in the barrier mbb.
983   SmallPtrSet<MachineInstr*, 4> RefsInMBB;
984   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
985          E = MRI->reg_end(); I != E; ++I) {
986     MachineInstr *RefMI = &*I;
987     if (RefMI->getParent() == BarrierMBB)
988       RefsInMBB.insert(RefMI);
989   }
990
991   // Find a point to restore the value after the barrier.
992   MachineBasicBlock::iterator RestorePt =
993     findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB);
994   if (RestorePt == BarrierMBB->end()) {
995     DEBUG(dbgs() << "FAILED (could not find a suitable restore point).\n");
996     return false;
997   }
998
999   if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
1000     if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt, RefsInMBB)) {
1001       DEBUG(dbgs() << "success (remat).\n");
1002       return true;
1003     }
1004
1005   // Add a spill either before the barrier or after the definition.
1006   MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
1007   const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
1008   SlotIndex SpillIndex;
1009   MachineInstr *SpillMI = NULL;
1010   int SS = -1;
1011   if (!ValNo->isDefAccurate()) {
1012     // If we don't know where the def is we must split just before the barrier.
1013     if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
1014                             BarrierMBB, SS, RefsInMBB))) {
1015       SpillIndex = LIs->getInstructionIndex(SpillMI);
1016     } else {
1017       MachineBasicBlock::iterator SpillPt = 
1018         findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB);
1019       if (SpillPt == BarrierMBB->begin()) {
1020         DEBUG(dbgs() << "FAILED (could not find a suitable spill point).\n");
1021         return false; // No gap to insert spill.
1022       }
1023       // Add spill.
1024     
1025       SS = CreateSpillStackSlot(CurrLI->reg, RC);
1026       TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC,
1027                                TRI);
1028       SpillMI = prior(SpillPt);
1029       SpillIndex = LIs->InsertMachineInstrInMaps(SpillMI);
1030     }
1031   } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
1032                                  LIs->getZeroIndex(), SpillIndex, SS)) {
1033     // If it's already split, just restore the value. There is no need to spill
1034     // the def again.
1035     if (!DefMI) {
1036       DEBUG(dbgs() << "FAILED (def is dead).\n");
1037       return false; // Def is dead. Do nothing.
1038     }
1039     
1040     if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
1041                              BarrierMBB, SS, RefsInMBB))) {
1042       SpillIndex = LIs->getInstructionIndex(SpillMI);
1043     } else {
1044       // Check if it's possible to insert a spill after the def MI.
1045       MachineBasicBlock::iterator SpillPt;
1046       if (DefMBB == BarrierMBB) {
1047         // Add spill after the def and the last use before the barrier.
1048         SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
1049                                  RefsInMBB);
1050         if (SpillPt == DefMBB->begin()) {
1051           DEBUG(dbgs() << "FAILED (could not find a suitable spill point).\n");
1052           return false; // No gap to insert spill.
1053         }
1054       } else {
1055         SpillPt = llvm::next(MachineBasicBlock::iterator(DefMI));
1056         if (SpillPt == DefMBB->end()) {
1057           DEBUG(dbgs() << "FAILED (could not find a suitable spill point).\n");
1058           return false; // No gap to insert spill.
1059         }
1060       }
1061       // Add spill. 
1062       SS = CreateSpillStackSlot(CurrLI->reg, RC);
1063       TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg, false, SS, RC,
1064                                TRI);
1065       SpillMI = prior(SpillPt);
1066       SpillIndex = LIs->InsertMachineInstrInMaps(SpillMI);
1067     }
1068   }
1069
1070   // Remember def instruction index to spill index mapping.
1071   if (DefMI && SpillMI)
1072     Def2SpillMap[ValNo->def] = SpillIndex;
1073
1074   // Add restore.
1075   bool FoldedRestore = false;
1076   SlotIndex RestoreIndex;
1077   if (MachineInstr* LMI = FoldRestore(CurrLI->reg, RC, Barrier,
1078                                       BarrierMBB, SS, RefsInMBB)) {
1079     RestorePt = LMI;
1080     RestoreIndex = LIs->getInstructionIndex(RestorePt);
1081     FoldedRestore = true;
1082   } else {
1083     TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC, TRI);
1084     MachineInstr *LoadMI = prior(RestorePt);
1085     RestoreIndex = LIs->InsertMachineInstrInMaps(LoadMI);
1086   }
1087
1088   // Update spill stack slot live interval.
1089   UpdateSpillSlotInterval(ValNo, SpillIndex.getUseIndex().getNextSlot(),
1090                           RestoreIndex.getDefIndex());
1091
1092   ReconstructLiveInterval(CurrLI);
1093
1094   if (!FoldedRestore) {
1095     SlotIndex RestoreIdx = LIs->getInstructionIndex(prior(RestorePt));
1096     RestoreIdx = RestoreIdx.getDefIndex();
1097     RenumberValno(CurrLI->findDefinedVNInfoForRegInt(RestoreIdx));
1098   }
1099   
1100   ++NumSplits;
1101   DEBUG(dbgs() << "success.\n");
1102   return true;
1103 }
1104
1105 /// SplitRegLiveIntervals - Split all register live intervals that cross the
1106 /// barrier that's being processed.
1107 bool
1108 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs,
1109                                          SmallPtrSet<LiveInterval*, 8>& Split) {
1110   // First find all the virtual registers whose live intervals are intercepted
1111   // by the current barrier.
1112   SmallVector<LiveInterval*, 8> Intervals;
1113   for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
1114     // FIXME: If it's not safe to move any instruction that defines the barrier
1115     // register class, then it means there are some special dependencies which
1116     // codegen is not modelling. Ignore these barriers for now.
1117     if (!TII->isSafeToMoveRegClassDefs(*RC))
1118       continue;
1119     const std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1120     for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1121       unsigned Reg = VRs[i];
1122       if (!LIs->hasInterval(Reg))
1123         continue;
1124       LiveInterval *LI = &LIs->getInterval(Reg);
1125       if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1126         // Virtual register live interval is intercepted by the barrier. We
1127         // should split and shrink wrap its interval if possible.
1128         Intervals.push_back(LI);
1129     }
1130   }
1131
1132   // Process the affected live intervals.
1133   bool Change = false;
1134   while (!Intervals.empty()) {
1135     if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1136       break;
1137     LiveInterval *LI = Intervals.back();
1138     Intervals.pop_back();
1139     bool result = SplitRegLiveInterval(LI);
1140     if (result) Split.insert(LI);
1141     Change |= result;
1142   }
1143
1144   return Change;
1145 }
1146
1147 unsigned PreAllocSplitting::getNumberOfNonSpills(
1148                                   SmallPtrSet<MachineInstr*, 4>& MIs,
1149                                   unsigned Reg, int FrameIndex,
1150                                   bool& FeedsTwoAddr) {
1151   unsigned NonSpills = 0;
1152   for (SmallPtrSet<MachineInstr*, 4>::iterator UI = MIs.begin(), UE = MIs.end();
1153        UI != UE; ++UI) {
1154     int StoreFrameIndex;
1155     unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1156     if (StoreVReg != Reg || StoreFrameIndex != FrameIndex)
1157       ++NonSpills;
1158     
1159     int DefIdx = (*UI)->findRegisterDefOperandIdx(Reg);
1160     if (DefIdx != -1 && (*UI)->isRegTiedToUseOperand(DefIdx))
1161       FeedsTwoAddr = true;
1162   }
1163   
1164   return NonSpills;
1165 }
1166
1167 /// removeDeadSpills - After doing splitting, filter through all intervals we've
1168 /// split, and see if any of the spills are unnecessary.  If so, remove them.
1169 bool PreAllocSplitting::removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split) {
1170   bool changed = false;
1171   
1172   // Walk over all of the live intervals that were touched by the splitter,
1173   // and see if we can do any DCE and/or folding.
1174   for (SmallPtrSet<LiveInterval*, 8>::iterator LI = split.begin(),
1175        LE = split.end(); LI != LE; ++LI) {
1176     DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> > VNUseCount;
1177     
1178     // First, collect all the uses of the vreg, and sort them by their
1179     // reaching definition (VNInfo).
1180     for (MachineRegisterInfo::use_iterator UI = MRI->use_begin((*LI)->reg),
1181          UE = MRI->use_end(); UI != UE; ++UI) {
1182       SlotIndex index = LIs->getInstructionIndex(&*UI);
1183       index = index.getUseIndex();
1184       
1185       const LiveRange* LR = (*LI)->getLiveRangeContaining(index);
1186       VNUseCount[LR->valno].insert(&*UI);
1187     }
1188     
1189     // Now, take the definitions (VNInfo's) one at a time and try to DCE 
1190     // and/or fold them away.
1191     for (LiveInterval::vni_iterator VI = (*LI)->vni_begin(),
1192          VE = (*LI)->vni_end(); VI != VE; ++VI) {
1193       
1194       if (DeadSplitLimit != -1 && (int)NumDeadSpills == DeadSplitLimit) 
1195         return changed;
1196       
1197       VNInfo* CurrVN = *VI;
1198       
1199       // We don't currently try to handle definitions with PHI kills, because
1200       // it would involve processing more than one VNInfo at once.
1201       if (CurrVN->hasPHIKill()) continue;
1202       
1203       // We also don't try to handle the results of PHI joins, since there's
1204       // no defining instruction to analyze.
1205       if (!CurrVN->isDefAccurate() || CurrVN->isUnused()) continue;
1206     
1207       // We're only interested in eliminating cruft introduced by the splitter,
1208       // is of the form load-use or load-use-store.  First, check that the
1209       // definition is a load, and remember what stack slot we loaded it from.
1210       MachineInstr* DefMI = LIs->getInstructionFromIndex(CurrVN->def);
1211       int FrameIndex;
1212       if (!TII->isLoadFromStackSlot(DefMI, FrameIndex)) continue;
1213       
1214       // If the definition has no uses at all, just DCE it.
1215       if (VNUseCount[CurrVN].size() == 0) {
1216         LIs->RemoveMachineInstrFromMaps(DefMI);
1217         (*LI)->removeValNo(CurrVN);
1218         DefMI->eraseFromParent();
1219         VNUseCount.erase(CurrVN);
1220         ++NumDeadSpills;
1221         changed = true;
1222         continue;
1223       }
1224       
1225       // Second, get the number of non-store uses of the definition, as well as
1226       // a flag indicating whether it feeds into a later two-address definition.
1227       bool FeedsTwoAddr = false;
1228       unsigned NonSpillCount = getNumberOfNonSpills(VNUseCount[CurrVN],
1229                                                     (*LI)->reg, FrameIndex,
1230                                                     FeedsTwoAddr);
1231       
1232       // If there's one non-store use and it doesn't feed a two-addr, then
1233       // this is a load-use-store case that we can try to fold.
1234       if (NonSpillCount == 1 && !FeedsTwoAddr) {
1235         // Start by finding the non-store use MachineInstr.
1236         SmallPtrSet<MachineInstr*, 4>::iterator UI = VNUseCount[CurrVN].begin();
1237         int StoreFrameIndex;
1238         unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1239         while (UI != VNUseCount[CurrVN].end() &&
1240                (StoreVReg == (*LI)->reg && StoreFrameIndex == FrameIndex)) {
1241           ++UI;
1242           if (UI != VNUseCount[CurrVN].end())
1243             StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1244         }
1245         if (UI == VNUseCount[CurrVN].end()) continue;
1246         
1247         MachineInstr* use = *UI;
1248         
1249         // Attempt to fold it away!
1250         int OpIdx = use->findRegisterUseOperandIdx((*LI)->reg, false);
1251         if (OpIdx == -1) continue;
1252         SmallVector<unsigned, 1> Ops;
1253         Ops.push_back(OpIdx);
1254         if (!TII->canFoldMemoryOperand(use, Ops)) continue;
1255
1256         MachineInstr* NewMI = TII->foldMemoryOperand(use, Ops, FrameIndex);
1257
1258         if (!NewMI) continue;
1259
1260         // Update relevant analyses.
1261         LIs->RemoveMachineInstrFromMaps(DefMI);
1262         LIs->ReplaceMachineInstrInMaps(use, NewMI);
1263         (*LI)->removeValNo(CurrVN);
1264
1265         DefMI->eraseFromParent();
1266         use->eraseFromParent();
1267         VNUseCount[CurrVN].erase(use);
1268
1269         // Remove deleted instructions.  Note that we need to remove them from 
1270         // the VNInfo->use map as well, just to be safe.
1271         for (SmallPtrSet<MachineInstr*, 4>::iterator II = 
1272              VNUseCount[CurrVN].begin(), IE = VNUseCount[CurrVN].end();
1273              II != IE; ++II) {
1274           for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1275                VNI = VNUseCount.begin(), VNE = VNUseCount.end(); VNI != VNE; 
1276                ++VNI)
1277             if (VNI->first != CurrVN)
1278               VNI->second.erase(*II);
1279           LIs->RemoveMachineInstrFromMaps(*II);
1280           (*II)->eraseFromParent();
1281         }
1282         
1283         VNUseCount.erase(CurrVN);
1284
1285         for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1286              VI = VNUseCount.begin(), VE = VNUseCount.end(); VI != VE; ++VI)
1287           if (VI->second.erase(use))
1288             VI->second.insert(NewMI);
1289
1290         ++NumDeadSpills;
1291         changed = true;
1292         continue;
1293       }
1294       
1295       // If there's more than one non-store instruction, we can't profitably
1296       // fold it, so bail.
1297       if (NonSpillCount) continue;
1298         
1299       // Otherwise, this is a load-store case, so DCE them.
1300       for (SmallPtrSet<MachineInstr*, 4>::iterator UI = 
1301            VNUseCount[CurrVN].begin(), UE = VNUseCount[CurrVN].end();
1302            UI != UE; ++UI) {
1303         LIs->RemoveMachineInstrFromMaps(*UI);
1304         (*UI)->eraseFromParent();
1305       }
1306         
1307       VNUseCount.erase(CurrVN);
1308         
1309       LIs->RemoveMachineInstrFromMaps(DefMI);
1310       (*LI)->removeValNo(CurrVN);
1311       DefMI->eraseFromParent();
1312       ++NumDeadSpills;
1313       changed = true;
1314     }
1315   }
1316   
1317   return changed;
1318 }
1319
1320 bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1321                                        MachineBasicBlock* DefMBB,
1322                                        MachineBasicBlock* BarrierMBB) {
1323   if (DefMBB == BarrierMBB)
1324     return false;
1325   
1326   if (LR->valno->hasPHIKill())
1327     return false;
1328   
1329   SlotIndex MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1330   if (LR->end < MBBEnd)
1331     return false;
1332   
1333   MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1334   if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1335     return true;
1336   
1337   MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1338   SmallPtrSet<MachineBasicBlock*, 4> Visited;
1339   typedef std::pair<MachineBasicBlock*,
1340                     MachineBasicBlock::succ_iterator> ItPair;
1341   SmallVector<ItPair, 4> Stack;
1342   Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1343   
1344   while (!Stack.empty()) {
1345     ItPair P = Stack.back();
1346     Stack.pop_back();
1347     
1348     MachineBasicBlock* PredMBB = P.first;
1349     MachineBasicBlock::succ_iterator S = P.second;
1350     
1351     if (S == PredMBB->succ_end())
1352       continue;
1353     else if (Visited.count(*S)) {
1354       Stack.push_back(std::make_pair(PredMBB, ++S));
1355       continue;
1356     } else
1357       Stack.push_back(std::make_pair(PredMBB, S+1));
1358     
1359     MachineBasicBlock* MBB = *S;
1360     Visited.insert(MBB);
1361     
1362     if (MBB == BarrierMBB)
1363       return true;
1364     
1365     MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1366     MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1367     MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1368     while (MDTN) {
1369       if (MDTN == DefMDTN)
1370         return true;
1371       else if (MDTN == BarrierMDTN)
1372         break;
1373       MDTN = MDTN->getIDom();
1374     }
1375     
1376     MBBEnd = LIs->getMBBEndIdx(MBB);
1377     if (LR->end > MBBEnd)
1378       Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1379   }
1380   
1381   return false;
1382
1383   
1384
1385 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
1386   CurrMF = &MF;
1387   TM     = &MF.getTarget();
1388   TRI    = TM->getRegisterInfo();
1389   TII    = TM->getInstrInfo();
1390   MFI    = MF.getFrameInfo();
1391   MRI    = &MF.getRegInfo();
1392   SIs    = &getAnalysis<SlotIndexes>();
1393   LIs    = &getAnalysis<LiveIntervals>();
1394   LSs    = &getAnalysis<LiveStacks>();
1395   VRM    = &getAnalysis<VirtRegMap>();
1396
1397   bool MadeChange = false;
1398
1399   // Make sure blocks are numbered in order.
1400   MF.RenumberBlocks();
1401
1402   MachineBasicBlock *Entry = MF.begin();
1403   SmallPtrSet<MachineBasicBlock*,16> Visited;
1404
1405   SmallPtrSet<LiveInterval*, 8> Split;
1406
1407   for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1408          DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1409        DFI != E; ++DFI) {
1410     BarrierMBB = *DFI;
1411     for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1412            E = BarrierMBB->end(); I != E; ++I) {
1413       Barrier = &*I;
1414       const TargetRegisterClass **BarrierRCs =
1415         Barrier->getDesc().getRegClassBarriers();
1416       if (!BarrierRCs)
1417         continue;
1418       BarrierIdx = LIs->getInstructionIndex(Barrier);
1419       MadeChange |= SplitRegLiveIntervals(BarrierRCs, Split);
1420     }
1421   }
1422
1423   MadeChange |= removeDeadSpills(Split);
1424
1425   return MadeChange;
1426 }