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