LLVM API Documentation

PreAllocSplitting.cpp

Go to the documentation of this file.
00001 //===-- PreAllocSplitting.cpp - Pre-allocation Interval Spltting Pass. ----===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the machine instruction level pre-register allocation
00011 // live interval splitting pass. It finds live interval barriers, i.e.
00012 // instructions which will kill all physical registers in certain register
00013 // classes, and split all live intervals which cross the barrier.
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #define DEBUG_TYPE "pre-alloc-split"
00018 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00019 #include "llvm/CodeGen/LiveStackAnalysis.h"
00020 #include "llvm/CodeGen/MachineDominators.h"
00021 #include "llvm/CodeGen/MachineFrameInfo.h"
00022 #include "llvm/CodeGen/MachineFunctionPass.h"
00023 #include "llvm/CodeGen/MachineLoopInfo.h"
00024 #include "llvm/CodeGen/MachineRegisterInfo.h"
00025 #include "llvm/CodeGen/Passes.h"
00026 #include "llvm/CodeGen/RegisterCoalescer.h"
00027 #include "llvm/Target/TargetInstrInfo.h"
00028 #include "llvm/Target/TargetMachine.h"
00029 #include "llvm/Target/TargetOptions.h"
00030 #include "llvm/Target/TargetRegisterInfo.h"
00031 #include "llvm/Support/CommandLine.h"
00032 #include "llvm/Support/Debug.h"
00033 #include "llvm/ADT/DenseMap.h"
00034 #include "llvm/ADT/DepthFirstIterator.h"
00035 #include "llvm/ADT/SmallPtrSet.h"
00036 #include "llvm/ADT/Statistic.h"
00037 using namespace llvm;
00038 
00039 static cl::opt<int> PreSplitLimit("pre-split-limit", cl::init(-1), cl::Hidden);
00040 static cl::opt<int> DeadSplitLimit("dead-split-limit", cl::init(-1), cl::Hidden);
00041 
00042 STATISTIC(NumSplits, "Number of intervals split");
00043 STATISTIC(NumRemats, "Number of intervals split by rematerialization");
00044 STATISTIC(NumFolds, "Number of intervals split with spill folding");
00045 STATISTIC(NumRenumbers, "Number of intervals renumbered into new registers");
00046 STATISTIC(NumDeadSpills, "Number of dead spills removed");
00047 
00048 namespace {
00049   class VISIBILITY_HIDDEN PreAllocSplitting : public MachineFunctionPass {
00050     MachineFunction       *CurrMF;
00051     const TargetMachine   *TM;
00052     const TargetInstrInfo *TII;
00053     const TargetRegisterInfo* TRI;
00054     MachineFrameInfo      *MFI;
00055     MachineRegisterInfo   *MRI;
00056     LiveIntervals         *LIs;
00057     LiveStacks            *LSs;
00058 
00059     // Barrier - Current barrier being processed.
00060     MachineInstr          *Barrier;
00061 
00062     // BarrierMBB - Basic block where the barrier resides in.
00063     MachineBasicBlock     *BarrierMBB;
00064 
00065     // Barrier - Current barrier index.
00066     unsigned              BarrierIdx;
00067 
00068     // CurrLI - Current live interval being split.
00069     LiveInterval          *CurrLI;
00070 
00071     // CurrSLI - Current stack slot live interval.
00072     LiveInterval          *CurrSLI;
00073 
00074     // CurrSValNo - Current val# for the stack slot live interval.
00075     VNInfo                *CurrSValNo;
00076 
00077     // IntervalSSMap - A map from live interval to spill slots.
00078     DenseMap<unsigned, int> IntervalSSMap;
00079 
00080     // Def2SpillMap - A map from a def instruction index to spill index.
00081     DenseMap<unsigned, unsigned> Def2SpillMap;
00082 
00083   public:
00084     static char ID;
00085     PreAllocSplitting() : MachineFunctionPass(&ID) {}
00086 
00087     virtual bool runOnMachineFunction(MachineFunction &MF);
00088 
00089     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00090       AU.addRequired<LiveIntervals>();
00091       AU.addPreserved<LiveIntervals>();
00092       AU.addRequired<LiveStacks>();
00093       AU.addPreserved<LiveStacks>();
00094       AU.addPreserved<RegisterCoalescer>();
00095       if (StrongPHIElim)
00096         AU.addPreservedID(StrongPHIEliminationID);
00097       else
00098         AU.addPreservedID(PHIEliminationID);
00099       AU.addRequired<MachineDominatorTree>();
00100       AU.addRequired<MachineLoopInfo>();
00101       AU.addPreserved<MachineDominatorTree>();
00102       AU.addPreserved<MachineLoopInfo>();
00103       MachineFunctionPass::getAnalysisUsage(AU);
00104     }
00105     
00106     virtual void releaseMemory() {
00107       IntervalSSMap.clear();
00108       Def2SpillMap.clear();
00109     }
00110 
00111     virtual const char *getPassName() const {
00112       return "Pre-Register Allocaton Live Interval Splitting";
00113     }
00114 
00115     /// print - Implement the dump method.
00116     virtual void print(std::ostream &O, const Module* M = 0) const {
00117       LIs->print(O, M);
00118     }
00119 
00120     void print(std::ostream *O, const Module* M = 0) const {
00121       if (O) print(*O, M);
00122     }
00123 
00124   private:
00125     MachineBasicBlock::iterator
00126       findNextEmptySlot(MachineBasicBlock*, MachineInstr*,
00127                         unsigned&);
00128 
00129     MachineBasicBlock::iterator
00130       findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
00131                      SmallPtrSet<MachineInstr*, 4>&, unsigned&);
00132 
00133     MachineBasicBlock::iterator
00134       findRestorePoint(MachineBasicBlock*, MachineInstr*, unsigned,
00135                      SmallPtrSet<MachineInstr*, 4>&, unsigned&);
00136 
00137     int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
00138 
00139     bool IsAvailableInStack(MachineBasicBlock*, unsigned, unsigned, unsigned,
00140                             unsigned&, int&) const;
00141 
00142     void UpdateSpillSlotInterval(VNInfo*, unsigned, unsigned);
00143 
00144     bool SplitRegLiveInterval(LiveInterval*);
00145 
00146     bool SplitRegLiveIntervals(const TargetRegisterClass **,
00147                                SmallPtrSet<LiveInterval*, 8>&);
00148     
00149     bool createsNewJoin(LiveRange* LR, MachineBasicBlock* DefMBB,
00150                         MachineBasicBlock* BarrierMBB);
00151     bool Rematerialize(unsigned vreg, VNInfo* ValNo,
00152                        MachineInstr* DefMI,
00153                        MachineBasicBlock::iterator RestorePt,
00154                        unsigned RestoreIdx,
00155                        SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
00156     MachineInstr* FoldSpill(unsigned vreg, const TargetRegisterClass* RC,
00157                             MachineInstr* DefMI,
00158                             MachineInstr* Barrier,
00159                             MachineBasicBlock* MBB,
00160                             int& SS,
00161                             SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
00162     void RenumberValno(VNInfo* VN);
00163     void ReconstructLiveInterval(LiveInterval* LI);
00164     bool removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split);
00165     unsigned getNumberOfNonSpills(SmallPtrSet<MachineInstr*, 4>& MIs,
00166                                unsigned Reg, int FrameIndex, bool& TwoAddr);
00167     VNInfo* PerformPHIConstruction(MachineBasicBlock::iterator Use,
00168                                    MachineBasicBlock* MBB, LiveInterval* LI,
00169                                    SmallPtrSet<MachineInstr*, 4>& Visited,
00170             DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
00171             DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
00172                                       DenseMap<MachineInstr*, VNInfo*>& NewVNs,
00173                                 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
00174                                 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
00175                                         bool IsTopLevel, bool IsIntraBlock);
00176     VNInfo* PerformPHIConstructionFallBack(MachineBasicBlock::iterator Use,
00177                                    MachineBasicBlock* MBB, LiveInterval* LI,
00178                                    SmallPtrSet<MachineInstr*, 4>& Visited,
00179             DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
00180             DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
00181                                       DenseMap<MachineInstr*, VNInfo*>& NewVNs,
00182                                 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
00183                                 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
00184                                         bool IsTopLevel, bool IsIntraBlock);
00185 };
00186 } // end anonymous namespace
00187 
00188 char PreAllocSplitting::ID = 0;
00189 
00190 static RegisterPass<PreAllocSplitting>
00191 X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
00192 
00193 const PassInfo *const llvm::PreAllocSplittingID = &X;
00194 
00195 
00196 /// findNextEmptySlot - Find a gap after the given machine instruction in the
00197 /// instruction index map. If there isn't one, return end().
00198 MachineBasicBlock::iterator
00199 PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
00200                                      unsigned &SpotIndex) {
00201   MachineBasicBlock::iterator MII = MI;
00202   if (++MII != MBB->end()) {
00203     unsigned Index = LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
00204     if (Index) {
00205       SpotIndex = Index;
00206       return MII;
00207     }
00208   }
00209   return MBB->end();
00210 }
00211 
00212 /// findSpillPoint - Find a gap as far away from the given MI that's suitable
00213 /// for spilling the current live interval. The index must be before any
00214 /// defs and uses of the live interval register in the mbb. Return begin() if
00215 /// none is found.
00216 MachineBasicBlock::iterator
00217 PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
00218                                   MachineInstr *DefMI,
00219                                   SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
00220                                   unsigned &SpillIndex) {
00221   MachineBasicBlock::iterator Pt = MBB->begin();
00222 
00223   // Go top down if RefsInMBB is empty.
00224   if (RefsInMBB.empty() && !DefMI) {
00225     MachineBasicBlock::iterator MII = MBB->begin();
00226     MachineBasicBlock::iterator EndPt = MI;
00227     do {
00228       ++MII;
00229       unsigned Index = LIs->getInstructionIndex(MII);
00230       unsigned Gap = LIs->findGapBeforeInstr(Index);
00231       
00232       // We can't insert the spill between the barrier (a call), and its
00233       // corresponding call frame setup/teardown.
00234       if (prior(MII)->getOpcode() == TRI->getCallFrameSetupOpcode()) {
00235         bool reachedBarrier = false;
00236         do {
00237           if (MII == EndPt) {
00238             reachedBarrier = true;
00239             break;
00240           }
00241           ++MII;
00242         } while (MII->getOpcode() != TRI->getCallFrameDestroyOpcode());
00243         
00244         if (reachedBarrier) break;
00245       } else if (Gap) {
00246         Pt = MII;
00247         SpillIndex = Gap;
00248         break;
00249       }
00250     } while (MII != EndPt);
00251   } else {
00252     MachineBasicBlock::iterator MII = MI;
00253     MachineBasicBlock::iterator EndPt = DefMI
00254       ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
00255     
00256     while (MII != EndPt && !RefsInMBB.count(MII)) {
00257       unsigned Index = LIs->getInstructionIndex(MII);
00258       
00259       // We can't insert the spill between the barrier (a call), and its
00260       // corresponding call frame setup.
00261       if (prior(MII)->getOpcode() == TRI->getCallFrameSetupOpcode()) {
00262         --MII;
00263         continue;
00264       } if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
00265         bool reachedBarrier = false;
00266         while (MII->getOpcode() != TRI->getCallFrameSetupOpcode()) {
00267           --MII;
00268           if (MII == EndPt) {
00269             reachedBarrier = true;
00270             break;
00271           }
00272         }
00273         
00274         if (reachedBarrier) break;
00275         else continue;
00276       } else if (LIs->hasGapBeforeInstr(Index)) {
00277         Pt = MII;
00278         SpillIndex = LIs->findGapBeforeInstr(Index, true);
00279       }
00280       --MII;
00281     }
00282   }
00283 
00284   return Pt;
00285 }
00286 
00287 /// findRestorePoint - Find a gap in the instruction index map that's suitable
00288 /// for restoring the current live interval value. The index must be before any
00289 /// uses of the live interval register in the mbb. Return end() if none is
00290 /// found.
00291 MachineBasicBlock::iterator
00292 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
00293                                     unsigned LastIdx,
00294                                     SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
00295                                     unsigned &RestoreIndex) {
00296   // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
00297   // begin index accordingly.
00298   MachineBasicBlock::iterator Pt = MBB->end();
00299   unsigned EndIdx = LIs->getMBBEndIdx(MBB);
00300 
00301   // Go bottom up if RefsInMBB is empty and the end of the mbb isn't beyond
00302   // the last index in the live range.
00303   if (RefsInMBB.empty() && LastIdx >= EndIdx) {
00304     MachineBasicBlock::iterator MII = MBB->getFirstTerminator();
00305     MachineBasicBlock::iterator EndPt = MI;
00306     --MII;
00307     do {
00308       unsigned Index = LIs->getInstructionIndex(MII);
00309       unsigned Gap = LIs->findGapBeforeInstr(Index);
00310       
00311       // We can't insert a restore between the barrier (a call) and its 
00312       // corresponding call frame teardown.
00313       if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
00314         bool reachedBarrier = false;
00315         while (MII->getOpcode() != TRI->getCallFrameSetupOpcode()) {
00316           --MII;
00317           if (MII == EndPt) {
00318             reachedBarrier = true;
00319             break;
00320           }
00321         }
00322         
00323         if (reachedBarrier) break;
00324         else continue;
00325       } else if (Gap) {
00326         Pt = MII;
00327         RestoreIndex = Gap;
00328         break;
00329       }
00330       
00331       --MII;
00332     } while (MII != EndPt);
00333   } else {
00334     MachineBasicBlock::iterator MII = MI;
00335     MII = ++MII;
00336     
00337     // FIXME: Limit the number of instructions to examine to reduce
00338     // compile time?
00339     while (MII != MBB->getFirstTerminator()) {
00340       unsigned Index = LIs->getInstructionIndex(MII);
00341       if (Index > LastIdx)
00342         break;
00343       unsigned Gap = LIs->findGapBeforeInstr(Index);
00344       
00345       // We can't insert a restore between the barrier (a call) and its 
00346       // corresponding call frame teardown.
00347       if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
00348         ++MII;
00349         continue;
00350       } else if (prior(MII)->getOpcode() == TRI->getCallFrameSetupOpcode()) {
00351         bool reachedBarrier = false;
00352         do {
00353           if (MII == MBB->getFirstTerminator() || RefsInMBB.count(MII)) {
00354             reachedBarrier = true;
00355             break;
00356           }
00357           
00358           ++MII;
00359         } while (MII->getOpcode() != TRI->getCallFrameDestroyOpcode());
00360         
00361         if (reachedBarrier) break;
00362       } else if (Gap) {
00363         Pt = MII;
00364         RestoreIndex = Gap;
00365       }
00366       
00367       if (RefsInMBB.count(MII))
00368         break;
00369       ++MII;
00370     }
00371   }
00372 
00373   return Pt;
00374 }
00375 
00376 /// CreateSpillStackSlot - Create a stack slot for the live interval being
00377 /// split. If the live interval was previously split, just reuse the same
00378 /// slot.
00379 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
00380                                             const TargetRegisterClass *RC) {
00381   int SS;
00382   DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
00383   if (I != IntervalSSMap.end()) {
00384     SS = I->second;
00385   } else {
00386     SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
00387     IntervalSSMap[Reg] = SS;
00388   }
00389 
00390   // Create live interval for stack slot.
00391   CurrSLI = &LSs->getOrCreateInterval(SS);
00392   if (CurrSLI->hasAtLeastOneValue())
00393     CurrSValNo = CurrSLI->getValNumInfo(0);
00394   else
00395     CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
00396   return SS;
00397 }
00398 
00399 /// IsAvailableInStack - Return true if register is available in a split stack
00400 /// slot at the specified index.
00401 bool
00402 PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
00403                                     unsigned Reg, unsigned DefIndex,
00404                                     unsigned RestoreIndex, unsigned &SpillIndex,
00405                                     int& SS) const {
00406   if (!DefMBB)
00407     return false;
00408 
00409   DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
00410   if (I == IntervalSSMap.end())
00411     return false;
00412   DenseMap<unsigned, unsigned>::iterator II = Def2SpillMap.find(DefIndex);
00413   if (II == Def2SpillMap.end())
00414     return false;
00415 
00416   // If last spill of def is in the same mbb as barrier mbb (where restore will
00417   // be), make sure it's not below the intended restore index.
00418   // FIXME: Undo the previous spill?
00419   assert(LIs->getMBBFromIndex(II->second) == DefMBB);
00420   if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
00421     return false;
00422 
00423   SS = I->second;
00424   SpillIndex = II->second;
00425   return true;
00426 }
00427 
00428 /// UpdateSpillSlotInterval - Given the specified val# of the register live
00429 /// interval being split, and the spill and restore indicies, update the live
00430 /// interval of the spill stack slot.
00431 void
00432 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, unsigned SpillIndex,
00433                                            unsigned RestoreIndex) {
00434   assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
00435          "Expect restore in the barrier mbb");
00436 
00437   MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
00438   if (MBB == BarrierMBB) {
00439     // Intra-block spill + restore. We are done.
00440     LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
00441     CurrSLI->addRange(SLR);
00442     return;
00443   }
00444 
00445   SmallPtrSet<MachineBasicBlock*, 4> Processed;
00446   unsigned EndIdx = LIs->getMBBEndIdx(MBB);
00447   LiveRange SLR(SpillIndex, EndIdx+1, CurrSValNo);
00448   CurrSLI->addRange(SLR);
00449   Processed.insert(MBB);
00450 
00451   // Start from the spill mbb, figure out the extend of the spill slot's
00452   // live interval.
00453   SmallVector<MachineBasicBlock*, 4> WorkList;
00454   const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
00455   if (LR->end > EndIdx)
00456     // If live range extend beyond end of mbb, add successors to work list.
00457     for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
00458            SE = MBB->succ_end(); SI != SE; ++SI)
00459       WorkList.push_back(*SI);
00460 
00461   while (!WorkList.empty()) {
00462     MachineBasicBlock *MBB = WorkList.back();
00463     WorkList.pop_back();
00464     if (Processed.count(MBB))
00465       continue;
00466     unsigned Idx = LIs->getMBBStartIdx(MBB);
00467     LR = CurrLI->getLiveRangeContaining(Idx);
00468     if (LR && LR->valno == ValNo) {
00469       EndIdx = LIs->getMBBEndIdx(MBB);
00470       if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
00471         // Spill slot live interval stops at the restore.
00472         LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
00473         CurrSLI->addRange(SLR);
00474       } else if (LR->end > EndIdx) {
00475         // Live range extends beyond end of mbb, process successors.
00476         LiveRange SLR(Idx, EndIdx+1, CurrSValNo);
00477         CurrSLI->addRange(SLR);
00478         for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
00479                SE = MBB->succ_end(); SI != SE; ++SI)
00480           WorkList.push_back(*SI);
00481       } else {
00482         LiveRange SLR(Idx, LR->end, CurrSValNo);
00483         CurrSLI->addRange(SLR);
00484       }
00485       Processed.insert(MBB);
00486     }
00487   }
00488 }
00489 
00490 /// PerformPHIConstruction - From properly set up use and def lists, use a PHI
00491 /// construction algorithm to compute the ranges and valnos for an interval.
00492 VNInfo*
00493 PreAllocSplitting::PerformPHIConstruction(MachineBasicBlock::iterator UseI,
00494                                        MachineBasicBlock* MBB, LiveInterval* LI,
00495                                        SmallPtrSet<MachineInstr*, 4>& Visited,
00496              DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
00497              DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
00498                                        DenseMap<MachineInstr*, VNInfo*>& NewVNs,
00499                                  DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
00500                                  DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
00501                                            bool IsTopLevel, bool IsIntraBlock) {
00502   // Return memoized result if it's available.
00503   if (IsTopLevel && Visited.count(UseI) && NewVNs.count(UseI))
00504     return NewVNs[UseI];
00505   else if (!IsTopLevel && IsIntraBlock && NewVNs.count(UseI))
00506     return NewVNs[UseI];
00507   else if (!IsIntraBlock && LiveOut.count(MBB))
00508     return LiveOut[MBB];
00509   
00510   // Check if our block contains any uses or defs.
00511   bool ContainsDefs = Defs.count(MBB);
00512   bool ContainsUses = Uses.count(MBB);
00513   
00514   VNInfo* RetVNI = 0;
00515   
00516   // Enumerate the cases of use/def contaning blocks.
00517   if (!ContainsDefs && !ContainsUses) {
00518     return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
00519                                           NewVNs, LiveOut, Phis,
00520                                           IsTopLevel, IsIntraBlock);
00521   } else if (ContainsDefs && !ContainsUses) {
00522     SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
00523 
00524     // Search for the def in this block.  If we don't find it before the
00525     // instruction we care about, go to the fallback case.  Note that that
00526     // should never happen: this cannot be intrablock, so use should
00527     // always be an end() iterator.
00528     assert(UseI == MBB->end() && "No use marked in intrablock");
00529     
00530     MachineBasicBlock::iterator Walker = UseI;
00531     --Walker;
00532     while (Walker != MBB->begin()) {
00533       if (BlockDefs.count(Walker))
00534         break;
00535       --Walker;
00536     }
00537     
00538     // Once we've found it, extend its VNInfo to our instruction.
00539     unsigned DefIndex = LIs->getInstructionIndex(Walker);
00540     DefIndex = LiveIntervals::getDefIndex(DefIndex);
00541     unsigned EndIndex = LIs->getMBBEndIdx(MBB);
00542     
00543     RetVNI = NewVNs[Walker];
00544     LI->addRange(LiveRange(DefIndex, EndIndex+1, RetVNI));
00545   } else if (!ContainsDefs && ContainsUses) {
00546     SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
00547     
00548     // Search for the use in this block that precedes the instruction we care 
00549     // about, going to the fallback case if we don't find it.    
00550     if (UseI == MBB->begin())
00551       return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
00552                                             Uses, NewVNs, LiveOut, Phis,
00553                                             IsTopLevel, IsIntraBlock);
00554     
00555     MachineBasicBlock::iterator Walker = UseI;
00556     --Walker;
00557     bool found = false;
00558     while (Walker != MBB->begin()) {
00559       if (BlockUses.count(Walker)) {
00560         found = true;
00561         break;
00562       }
00563       --Walker;
00564     }
00565         
00566     // Must check begin() too.
00567     if (!found) {
00568       if (BlockUses.count(Walker))
00569         found = true;
00570       else
00571         return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
00572                                               Uses, NewVNs, LiveOut, Phis,
00573                                               IsTopLevel, IsIntraBlock);
00574     }
00575 
00576     unsigned UseIndex = LIs->getInstructionIndex(Walker);
00577     UseIndex = LiveIntervals::getUseIndex(UseIndex);
00578     unsigned EndIndex = 0;
00579     if (IsIntraBlock) {
00580       EndIndex = LIs->getInstructionIndex(UseI);
00581       EndIndex = LiveIntervals::getUseIndex(EndIndex);
00582     } else
00583       EndIndex = LIs->getMBBEndIdx(MBB);
00584 
00585     // Now, recursively phi construct the VNInfo for the use we found,
00586     // and then extend it to include the instruction we care about
00587     RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
00588                                     NewVNs, LiveOut, Phis, false, true);
00589     
00590     LI->addRange(LiveRange(UseIndex, EndIndex+1, RetVNI));
00591     
00592     // FIXME: Need to set kills properly for inter-block stuff.
00593     if (LI->isKill(RetVNI, UseIndex)) LI->removeKill(RetVNI, UseIndex);
00594     if (IsIntraBlock)
00595       LI->addKill(RetVNI, EndIndex);
00596   } else if (ContainsDefs && ContainsUses) {
00597     SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
00598     SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
00599     
00600     // This case is basically a merging of the two preceding case, with the
00601     // special note that checking for defs must take precedence over checking
00602     // for uses, because of two-address instructions.
00603     
00604     if (UseI == MBB->begin())
00605       return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
00606                                             NewVNs, LiveOut, Phis,
00607                                             IsTopLevel, IsIntraBlock);
00608     
00609     MachineBasicBlock::iterator Walker = UseI;
00610     --Walker;
00611     bool foundDef = false;
00612     bool foundUse = false;
00613     while (Walker != MBB->begin()) {
00614       if (BlockDefs.count(Walker)) {
00615         foundDef = true;
00616         break;
00617       } else if (BlockUses.count(Walker)) {
00618         foundUse = true;
00619         break;
00620       }
00621       --Walker;
00622     }
00623         
00624     // Must check begin() too.
00625     if (!foundDef && !foundUse) {
00626       if (BlockDefs.count(Walker))
00627         foundDef = true;
00628       else if (BlockUses.count(Walker))
00629         foundUse = true;
00630       else
00631         return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
00632                                               Uses, NewVNs, LiveOut, Phis,
00633                                               IsTopLevel, IsIntraBlock);
00634     }
00635 
00636     unsigned StartIndex = LIs->getInstructionIndex(Walker);
00637     StartIndex = foundDef ? LiveIntervals::getDefIndex(StartIndex) :
00638                             LiveIntervals::getUseIndex(StartIndex);
00639     unsigned EndIndex = 0;
00640     if (IsIntraBlock) {
00641       EndIndex = LIs->getInstructionIndex(UseI);
00642       EndIndex = LiveIntervals::getUseIndex(EndIndex);
00643     } else
00644       EndIndex = LIs->getMBBEndIdx(MBB);
00645 
00646     if (foundDef)
00647       RetVNI = NewVNs[Walker];
00648     else
00649       RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
00650                                       NewVNs, LiveOut, Phis, false, true);
00651 
00652     LI->addRange(LiveRange(StartIndex, EndIndex+1, RetVNI));
00653     
00654     if (foundUse && LI->isKill(RetVNI, StartIndex))
00655       LI->removeKill(RetVNI, StartIndex);
00656     if (IsIntraBlock) {
00657       LI->addKill(RetVNI, EndIndex);
00658     }
00659   }
00660   
00661   // Memoize results so we don't have to recompute them.
00662   if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
00663   else {
00664     if (!NewVNs.count(UseI))
00665       NewVNs[UseI] = RetVNI;
00666     Visited.insert(UseI);
00667   }
00668 
00669   return RetVNI;
00670 }
00671 
00672 /// PerformPHIConstructionFallBack - PerformPHIConstruction fall back path.
00673 ///
00674 VNInfo*
00675 PreAllocSplitting::PerformPHIConstructionFallBack(MachineBasicBlock::iterator UseI,
00676                                        MachineBasicBlock* MBB, LiveInterval* LI,
00677                                        SmallPtrSet<MachineInstr*, 4>& Visited,
00678              DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
00679              DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
00680                                        DenseMap<MachineInstr*, VNInfo*>& NewVNs,
00681                                  DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
00682                                  DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
00683                                            bool IsTopLevel, bool IsIntraBlock) {
00684   // NOTE: Because this is the fallback case from other cases, we do NOT
00685   // assume that we are not intrablock here.
00686   if (Phis.count(MBB)) return Phis[MBB]; 
00687 
00688   unsigned StartIndex = LIs->getMBBStartIdx(MBB);
00689   VNInfo *RetVNI = Phis[MBB] = LI->getNextValue(~0U, /*FIXME*/ 0,
00690                                                 LIs->getVNInfoAllocator());
00691   if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
00692     
00693   // If there are no uses or defs between our starting point and the
00694   // beginning of the block, then recursive perform phi construction
00695   // on our predecessors.
00696   DenseMap<MachineBasicBlock*, VNInfo*> IncomingVNs;
00697   for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
00698          PE = MBB->pred_end(); PI != PE; ++PI) {
00699     VNInfo* Incoming = PerformPHIConstruction((*PI)->end(), *PI, LI, 
00700                                               Visited, Defs, Uses, NewVNs,
00701                                               LiveOut, Phis, false, false);
00702     if (Incoming != 0)
00703       IncomingVNs[*PI] = Incoming;
00704   }
00705     
00706   if (MBB->pred_size() == 1 && !RetVNI->hasPHIKill) {
00707     VNInfo* OldVN = RetVNI;
00708     VNInfo* NewVN = IncomingVNs.begin()->second;
00709     VNInfo* MergedVN = LI->MergeValueNumberInto(OldVN, NewVN);
00710     if (MergedVN == OldVN) std::swap(OldVN, NewVN);
00711     
00712     for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator LOI = LiveOut.begin(),
00713          LOE = LiveOut.end(); LOI != LOE; ++LOI)
00714       if (LOI->second == OldVN)
00715         LOI->second = MergedVN;
00716     for (DenseMap<MachineInstr*, VNInfo*>::iterator NVI = NewVNs.begin(),
00717          NVE = NewVNs.end(); NVI != NVE; ++NVI)
00718       if (NVI->second == OldVN)
00719         NVI->second = MergedVN;
00720     for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator PI = Phis.begin(),
00721          PE = Phis.end(); PI != PE; ++PI)
00722       if (PI->second == OldVN)
00723         PI->second = MergedVN;
00724     RetVNI = MergedVN;
00725   } else {
00726     // Otherwise, merge the incoming VNInfos with a phi join.  Create a new
00727     // VNInfo to represent the joined value.
00728     for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator I =
00729            IncomingVNs.begin(), E = IncomingVNs.end(); I != E; ++I) {
00730       I->second->hasPHIKill = true;
00731       unsigned KillIndex = LIs->getMBBEndIdx(I->first);
00732       if (!LiveInterval::isKill(I->second, KillIndex))
00733         LI->addKill(I->second, KillIndex);
00734     }
00735   }
00736       
00737   unsigned EndIndex = 0;
00738   if (IsIntraBlock) {
00739     EndIndex = LIs->getInstructionIndex(UseI);
00740     EndIndex = LiveIntervals::getUseIndex(EndIndex);
00741   } else
00742     EndIndex = LIs->getMBBEndIdx(MBB);
00743   LI->addRange(LiveRange(StartIndex, EndIndex+1, RetVNI));
00744   if (IsIntraBlock)
00745     LI->addKill(RetVNI, EndIndex);
00746 
00747   // Memoize results so we don't have to recompute them.
00748   if (!IsIntraBlock)
00749     LiveOut[MBB] = RetVNI;
00750   else {
00751     if (!NewVNs.count(UseI))
00752       NewVNs[UseI] = RetVNI;
00753     Visited.insert(UseI);
00754   }
00755 
00756   return RetVNI;
00757 }
00758 
00759 /// ReconstructLiveInterval - Recompute a live interval from scratch.
00760 void PreAllocSplitting::ReconstructLiveInterval(LiveInterval* LI) {
00761   BumpPtrAllocator& Alloc = LIs->getVNInfoAllocator();
00762   
00763   // Clear the old ranges and valnos;
00764   LI->clear();
00765   
00766   // Cache the uses and defs of the register
00767   typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
00768   RegMap Defs, Uses;
00769   
00770   // Keep track of the new VNs we're creating.
00771   DenseMap<MachineInstr*, VNInfo*> NewVNs;
00772   SmallPtrSet<VNInfo*, 2> PhiVNs;
00773   
00774   // Cache defs, and create a new VNInfo for each def.
00775   for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
00776        DE = MRI->def_end(); DI != DE; ++DI) {
00777     Defs[(*DI).getParent()].insert(&*DI);
00778     
00779     unsigned DefIdx = LIs->getInstructionIndex(&*DI);
00780     DefIdx = LiveIntervals::getDefIndex(DefIdx);
00781     
00782     VNInfo* NewVN = LI->getNextValue(DefIdx, 0, Alloc);
00783     
00784     // If the def is a move, set the copy field.
00785     unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
00786     if (TII->isMoveInstr(*DI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
00787       if (DstReg == LI->reg)
00788         NewVN->copy = &*DI;
00789     
00790     NewVNs[&*DI] = NewVN;
00791   }
00792   
00793   // Cache uses as a separate pass from actually processing them.
00794   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
00795        UE = MRI->use_end(); UI != UE; ++UI)
00796     Uses[(*UI).getParent()].insert(&*UI);
00797     
00798   // Now, actually process every use and use a phi construction algorithm
00799   // to walk from it to its reaching definitions, building VNInfos along
00800   // the way.
00801   DenseMap<MachineBasicBlock*, VNInfo*> LiveOut;
00802   DenseMap<MachineBasicBlock*, VNInfo*> Phis;
00803   SmallPtrSet<MachineInstr*, 4> Visited;
00804   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
00805        UE = MRI->use_end(); UI != UE; ++UI) {
00806     PerformPHIConstruction(&*UI, UI->getParent(), LI, Visited, Defs,
00807                            Uses, NewVNs, LiveOut, Phis, true, true); 
00808   }
00809   
00810   // Add ranges for dead defs
00811   for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
00812        DE = MRI->def_end(); DI != DE; ++DI) {
00813     unsigned DefIdx = LIs->getInstructionIndex(&*DI);
00814     DefIdx = LiveIntervals::getDefIndex(DefIdx);
00815     
00816     if (LI->liveAt(DefIdx)) continue;
00817     
00818     VNInfo* DeadVN = NewVNs[&*DI];
00819     LI->addRange(LiveRange(DefIdx, DefIdx+1, DeadVN));
00820     LI->addKill(DeadVN, DefIdx);
00821   }
00822 }
00823 
00824 /// RenumberValno - Split the given valno out into a new vreg, allowing it to
00825 /// be allocated to a different register.  This function creates a new vreg,
00826 /// copies the valno and its live ranges over to the new vreg's interval,
00827 /// removes them from the old interval, and rewrites all uses and defs of
00828 /// the original reg to the new vreg within those ranges.
00829 void PreAllocSplitting::RenumberValno(VNInfo* VN) {
00830   SmallVector<VNInfo*, 4> Stack;
00831   SmallVector<VNInfo*, 4> VNsToCopy;
00832   Stack.push_back(VN);
00833 
00834   // Walk through and copy the valno we care about, and any other valnos
00835   // that are two-address redefinitions of the one we care about.  These
00836   // will need to be rewritten as well.  We also check for safety of the 
00837   // renumbering here, by making sure that none of the valno involved has
00838   // phi kills.
00839   while (!Stack.empty()) {
00840     VNInfo* OldVN = Stack.back();
00841     Stack.pop_back();
00842     
00843     // Bail out if we ever encounter a valno that has a PHI kill.  We can't
00844     // renumber these.
00845     if (OldVN->hasPHIKill) return;
00846     
00847     VNsToCopy.push_back(OldVN);
00848     
00849     // Locate two-address redefinitions
00850     for (SmallVector<unsigned, 4>::iterator KI = OldVN->kills.begin(),
00851          KE = OldVN->kills.end(); KI != KE; ++KI) {
00852       MachineInstr* MI = LIs->getInstructionFromIndex(*KI);
00853       unsigned DefIdx = MI->findRegisterDefOperandIdx(CurrLI->reg);
00854       if (DefIdx == ~0U) continue;
00855       if (MI->isRegReDefinedByTwoAddr(DefIdx)) {
00856         VNInfo* NextVN =
00857                      CurrLI->findDefinedVNInfo(LiveIntervals::getDefIndex(*KI));
00858         if (NextVN == OldVN) continue;
00859         Stack.push_back(NextVN);
00860       }
00861     }
00862   }
00863   
00864   // Create the new vreg
00865   unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
00866   
00867   // Create the new live interval
00868   LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
00869   
00870   for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE = 
00871        VNsToCopy.end(); OI != OE; ++OI) {
00872     VNInfo* OldVN = *OI;
00873     
00874     // Copy the valno over
00875     VNInfo* NewVN = NewLI.getNextValue(OldVN->def, OldVN->copy, 
00876                                        LIs->getVNInfoAllocator());
00877     NewLI.copyValNumInfo(NewVN, OldVN);
00878     NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
00879 
00880     // Remove the valno from the old interval
00881     CurrLI->removeValNo(OldVN);
00882   }
00883   
00884   // Rewrite defs and uses.  This is done in two stages to avoid invalidating
00885   // the reg_iterator.
00886   SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
00887   
00888   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
00889          E = MRI->reg_end(); I != E; ++I) {
00890     MachineOperand& MO = I.getOperand();
00891     unsigned InstrIdx = LIs->getInstructionIndex(&*I);
00892     
00893     if ((MO.isUse() && NewLI.liveAt(LiveIntervals::getUseIndex(InstrIdx))) ||
00894         (MO.isDef() && NewLI.liveAt(LiveIntervals::getDefIndex(InstrIdx))))
00895       OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
00896   }
00897   
00898   for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
00899        OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
00900     MachineInstr* Inst = I->first;
00901     unsigned OpIdx = I->second;
00902     MachineOperand& MO = Inst->getOperand(OpIdx);
00903     MO.setReg(NewVReg);
00904   }
00905   
00906   // The renumbered vreg shares a stack slot with the old register.
00907   if (IntervalSSMap.count(CurrLI->reg))
00908     IntervalSSMap[NewVReg] = IntervalSSMap[CurrLI->reg];
00909   
00910   NumRenumbers++;
00911 }
00912 
00913 bool PreAllocSplitting::Rematerialize(unsigned vreg, VNInfo* ValNo,
00914                                       MachineInstr* DefMI,
00915                                       MachineBasicBlock::iterator RestorePt,
00916                                       unsigned RestoreIdx,
00917                                     SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
00918   MachineBasicBlock& MBB = *RestorePt->getParent();
00919   
00920   MachineBasicBlock::iterator KillPt = BarrierMBB->end();
00921   unsigned KillIdx = 0;
00922   if (ValNo->def == ~0U || DefMI->getParent() == BarrierMBB)
00923     KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, KillIdx);
00924   else
00925     KillPt = findNextEmptySlot(DefMI->getParent(), DefMI, KillIdx);
00926   
00927   if (KillPt == DefMI->getParent()->end())
00928     return false;
00929   
00930   TII->reMaterialize(MBB, RestorePt, vreg, DefMI);
00931   LIs->InsertMachineInstrInMaps(prior(RestorePt), RestoreIdx);
00932   
00933   ReconstructLiveInterval(CurrLI);
00934   unsigned RematIdx = LIs->getInstructionIndex(prior(RestorePt));
00935   RematIdx = LiveIntervals::getDefIndex(RematIdx);
00936   RenumberValno(CurrLI->findDefinedVNInfo(RematIdx));
00937   
00938   ++NumSplits;
00939   ++NumRemats;
00940   return true;  
00941 }
00942 
00943 MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg, 
00944                                            const TargetRegisterClass* RC,
00945                                            MachineInstr* DefMI,
00946                                            MachineInstr* Barrier,
00947                                            MachineBasicBlock* MBB,
00948                                            int& SS,
00949                                     SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
00950   MachineBasicBlock::iterator Pt = MBB->begin();
00951 
00952   // Go top down if RefsInMBB is empty.
00953   if (RefsInMBB.empty())
00954     return 0;
00955   
00956   MachineBasicBlock::iterator FoldPt = Barrier;
00957   while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
00958          !RefsInMBB.count(FoldPt))
00959     --FoldPt;
00960   
00961   int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg, false);
00962   if (OpIdx == -1)
00963     return 0;
00964   
00965   SmallVector<unsigned, 1> Ops;
00966   Ops.push_back(OpIdx);
00967   
00968   if (!TII->canFoldMemoryOperand(FoldPt, Ops))
00969     return 0;
00970   
00971   DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
00972   if (I != IntervalSSMap.end()) {
00973     SS = I->second;
00974   } else {
00975     SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
00976     
00977   }
00978   
00979   MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
00980                                              FoldPt, Ops, SS);
00981   
00982   if (FMI) {
00983     LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
00984     FMI = MBB->insert(MBB->erase(FoldPt), FMI);
00985     ++NumFolds;
00986     
00987     IntervalSSMap[vreg] = SS;
00988     CurrSLI = &LSs->getOrCreateInterval(SS);
00989     if (CurrSLI->hasAtLeastOneValue())
00990       CurrSValNo = CurrSLI->getValNumInfo(0);
00991     else
00992       CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
00993   }
00994   
00995   return FMI;
00996 }
00997 
00998 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
00999 /// so it would not cross the barrier that's being processed. Shrink wrap
01000 /// (minimize) the live interval to the last uses.
01001 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
01002   CurrLI = LI;
01003 
01004   // Find live range where current interval cross the barrier.
01005   LiveInterval::iterator LR =
01006     CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
01007   VNInfo *ValNo = LR->valno;
01008 
01009   if (ValNo->def == ~1U) {
01010     // Defined by a dead def? How can this be?
01011     assert(0 && "Val# is defined by a dead def?");
01012     abort();
01013   }
01014 
01015   MachineInstr *DefMI = (ValNo->def != ~0U)
01016     ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
01017 
01018   // If this would create a new join point, do not split.
01019   if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent()))
01020     return false;
01021 
01022   // Find all references in the barrier mbb.
01023   SmallPtrSet<MachineInstr*, 4> RefsInMBB;
01024   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
01025          E = MRI->reg_end(); I != E; ++I) {
01026     MachineInstr *RefMI = &*I;
01027     if (RefMI->getParent() == BarrierMBB)
01028       RefsInMBB.insert(RefMI);
01029   }
01030 
01031   // Find a point to restore the value after the barrier.
01032   unsigned RestoreIndex = 0;
01033   MachineBasicBlock::iterator RestorePt =
01034     findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
01035   if (RestorePt == BarrierMBB->end())
01036     return false;
01037 
01038   if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
01039     if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt,
01040                       RestoreIndex, RefsInMBB))
01041     return true;
01042 
01043   // Add a spill either before the barrier or after the definition.
01044   MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
01045   const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
01046   unsigned SpillIndex = 0;
01047   MachineInstr *SpillMI = NULL;
01048   int SS = -1;
01049   if (ValNo->def == ~0U) {
01050     // If it's defined by a phi, we must split just before the barrier.
01051     if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
01052                             BarrierMBB, SS, RefsInMBB))) {
01053       SpillIndex = LIs->getInstructionIndex(SpillMI);
01054     } else {
01055       MachineBasicBlock::iterator SpillPt = 
01056         findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
01057       if (SpillPt == BarrierMBB->begin())
01058         return false; // No gap to insert spill.
01059       // Add spill.
01060     
01061       SS = CreateSpillStackSlot(CurrLI->reg, RC);
01062       TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
01063       SpillMI = prior(SpillPt);
01064       LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
01065     }
01066   } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
01067                                  RestoreIndex, SpillIndex, SS)) {
01068     // If it's already split, just restore the value. There is no need to spill
01069     // the def again.
01070     if (!DefMI)
01071       return false; // Def is dead. Do nothing.
01072     
01073     if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
01074                             BarrierMBB, SS, RefsInMBB))) {
01075       SpillIndex = LIs->getInstructionIndex(SpillMI);
01076     } else {
01077       // Check if it's possible to insert a spill after the def MI.
01078       MachineBasicBlock::iterator SpillPt;
01079       if (DefMBB == BarrierMBB) {
01080         // Add spill after the def and the last use before the barrier.
01081         SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
01082                                  RefsInMBB, SpillIndex);
01083         if (SpillPt == DefMBB->begin())
01084           return false; // No gap to insert spill.
01085       } else {
01086         SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
01087         if (SpillPt == DefMBB->end())
01088           return false; // No gap to insert spill.
01089       }
01090       // Add spill. The store instruction kills the register if def is before
01091       // the barrier in the barrier block.
01092       SS = CreateSpillStackSlot(CurrLI->reg, RC);
01093       TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
01094                                DefMBB == BarrierMBB, SS, RC);
01095       SpillMI = prior(SpillPt);
01096       LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
01097     }
01098   }
01099 
01100   // Remember def instruction index to spill index mapping.
01101   if (DefMI && SpillMI)
01102     Def2SpillMap[ValNo->def] = SpillIndex;
01103 
01104   // Add restore.
01105   TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
01106   MachineInstr *LoadMI = prior(RestorePt);
01107   LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
01108 
01109   // Update spill stack slot live interval.
01110   UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
01111                           LIs->getDefIndex(RestoreIndex));
01112 
01113   ReconstructLiveInterval(CurrLI);
01114   unsigned RestoreIdx = LIs->getInstructionIndex(prior(RestorePt));
01115   RestoreIdx = LiveIntervals::getDefIndex(RestoreIdx);
01116   RenumberValno(CurrLI->findDefinedVNInfo(RestoreIdx));
01117   
01118   ++NumSplits;
01119   return true;
01120 }
01121 
01122 /// SplitRegLiveIntervals - Split all register live intervals that cross the
01123 /// barrier that's being processed.
01124 bool
01125 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs,
01126                                          SmallPtrSet<LiveInterval*, 8>& Split) {
01127   // First find all the virtual registers whose live intervals are intercepted
01128   // by the current barrier.
01129   SmallVector<LiveInterval*, 8> Intervals;
01130   for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
01131     if (TII->IgnoreRegisterClassBarriers(*RC))
01132       continue;
01133     std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
01134     for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
01135       unsigned Reg = VRs[i];
01136       if (!LIs->hasInterval(Reg))
01137         continue;
01138       LiveInterval *LI = &LIs->getInterval(Reg);
01139       if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
01140         // Virtual register live interval is intercepted by the barrier. We
01141         // should split and shrink wrap its interval if possible.
01142         Intervals.push_back(LI);
01143     }
01144   }
01145 
01146   // Process the affected live intervals.
01147   bool Change = false;
01148   while (!Intervals.empty()) {
01149     if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
01150       break;
01151     else if (NumSplits == 4)
01152       Change |= Change;
01153     LiveInterval *LI = Intervals.back();
01154     Intervals.pop_back();
01155     bool result = SplitRegLiveInterval(LI);
01156     if (result) Split.insert(LI);
01157     Change |= result;
01158   }
01159 
01160   return Change;
01161 }
01162 
01163 unsigned PreAllocSplitting::getNumberOfNonSpills(
01164                                   SmallPtrSet<MachineInstr*, 4>& MIs,
01165                                   unsigned Reg, int FrameIndex,
01166                                   bool& FeedsTwoAddr) {
01167   unsigned NonSpills = 0;
01168   for (SmallPtrSet<MachineInstr*, 4>::iterator UI = MIs.begin(), UE = MIs.end();
01169        UI != UE; ++UI) {
01170     int StoreFrameIndex;
01171     unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
01172     if (StoreVReg != Reg || StoreFrameIndex != FrameIndex)
01173       NonSpills++;
01174     
01175     int DefIdx = (*UI)->findRegisterDefOperandIdx(Reg);
01176     if (DefIdx != -1 && (*UI)->isRegReDefinedByTwoAddr(DefIdx))
01177       FeedsTwoAddr = true;
01178   }
01179   
01180   return NonSpills;
01181 }
01182 
01183 /// removeDeadSpills - After doing splitting, filter through all intervals we've
01184 /// split, and see if any of the spills are unnecessary.  If so, remove them.
01185 bool PreAllocSplitting::removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split) {
01186   bool changed = false;
01187   
01188   // Walk over all of the live intervals that were touched by the splitter,
01189   // and see if we can do any DCE and/or folding.
01190   for (SmallPtrSet<LiveInterval*, 8>::iterator LI = split.begin(),
01191        LE = split.end(); LI != LE; ++LI) {
01192     DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> > VNUseCount;
01193     
01194     // First, collect all the uses of the vreg, and sort them by their
01195     // reaching definition (VNInfo).
01196     for (MachineRegisterInfo::use_iterator UI = MRI->use_begin((*LI)->reg),
01197          UE = MRI->use_end(); UI != UE; ++UI) {
01198       unsigned index = LIs->getInstructionIndex(&*UI);
01199       index = LiveIntervals::getUseIndex(index);
01200       
01201       const LiveRange* LR = (*LI)->getLiveRangeContaining(index);
01202       VNUseCount[LR->valno].insert(&*UI);
01203     }
01204     
01205     // Now, take the definitions (VNInfo's) one at a time and try to DCE 
01206     // and/or fold them away.
01207     for (LiveInterval::vni_iterator VI = (*LI)->vni_begin(),
01208          VE = (*LI)->vni_end(); VI != VE; ++VI) {
01209       
01210       if (DeadSplitLimit != -1 && (int)NumDeadSpills == DeadSplitLimit) 
01211         return changed;
01212       
01213       VNInfo* CurrVN = *VI;
01214       
01215       // We don't currently try to handle definitions with PHI kills, because
01216       // it would involve processing more than one VNInfo at once.
01217       if (CurrVN->hasPHIKill) continue;
01218       
01219       // We also don't try to handle the results of PHI joins, since there's
01220       // no defining instruction to analyze.
01221       unsigned DefIdx = CurrVN->def;
01222       if (DefIdx == ~0U || DefIdx == ~1U) continue;
01223     
01224       // We're only interested in eliminating cruft introduced by the splitter,
01225       // is of the form load-use or load-use-store.  First, check that the
01226       // definition is a load, and remember what stack slot we loaded it from.
01227       MachineInstr* DefMI = LIs->getInstructionFromIndex(DefIdx);
01228       int FrameIndex;
01229       if (!TII->isLoadFromStackSlot(DefMI, FrameIndex)) continue;
01230       
01231       // If the definition has no uses at all, just DCE it.
01232       if (VNUseCount[CurrVN].size() == 0) {
01233         LIs->RemoveMachineInstrFromMaps(DefMI);
01234         (*LI)->removeValNo(CurrVN);
01235         DefMI->eraseFromParent();
01236         VNUseCount.erase(CurrVN);
01237         NumDeadSpills++;
01238         changed = true;
01239         continue;
01240       }
01241       
01242       // Second, get the number of non-store uses of the definition, as well as
01243       // a flag indicating whether it feeds into a later two-address definition.
01244       bool FeedsTwoAddr = false;
01245       unsigned NonSpillCount = getNumberOfNonSpills(VNUseCount[CurrVN],
01246                                                     (*LI)->reg, FrameIndex,
01247                                                     FeedsTwoAddr);
01248       
01249       // If there's one non-store use and it doesn't feed a two-addr, then
01250       // this is a load-use-store case that we can try to fold.
01251       if (NonSpillCount == 1 && !FeedsTwoAddr) {
01252         // Start by finding the non-store use MachineInstr.
01253         SmallPtrSet<MachineInstr*, 4>::iterator UI = VNUseCount[CurrVN].begin();
01254         int StoreFrameIndex;
01255         unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
01256         while (UI != VNUseCount[CurrVN].end() &&
01257                (StoreVReg == (*LI)->reg && StoreFrameIndex == FrameIndex)) {
01258           ++UI;
01259           if (UI != VNUseCount[CurrVN].end())
01260             StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
01261         }
01262         if (UI == VNUseCount[CurrVN].end()) continue;
01263         
01264         MachineInstr* use = *UI;
01265         
01266         // Attempt to fold it away!
01267         int OpIdx = use->findRegisterUseOperandIdx((*LI)->reg, false);
01268         if (OpIdx == -1) continue;
01269         SmallVector<unsigned, 1> Ops;
01270         Ops.push_back(OpIdx);
01271         if (!TII->canFoldMemoryOperand(use, Ops)) continue;
01272 
01273         MachineInstr* NewMI =
01274                           TII->foldMemoryOperand(*use->getParent()->getParent(),  
01275                                                  use, Ops, FrameIndex);
01276 
01277         if (!NewMI) continue;
01278 
01279         // Update relevant analyses.
01280         LIs->RemoveMachineInstrFromMaps(DefMI);
01281         LIs->ReplaceMachineInstrInMaps(use, NewMI);
01282         (*LI)->removeValNo(CurrVN);
01283 
01284         DefMI->eraseFromParent();
01285         MachineBasicBlock* MBB = use->getParent();
01286         NewMI = MBB->insert(MBB->erase(use), NewMI);
01287         VNUseCount[CurrVN].erase(use);
01288         
01289         // Remove deleted instructions.  Note that we need to remove them from 
01290         // the VNInfo->use map as well, just to be safe.
01291         for (SmallPtrSet<MachineInstr*, 4>::iterator II = 
01292              VNUseCount[CurrVN].begin(), IE = VNUseCount[CurrVN].end();
01293              II != IE; ++II) {
01294           for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
01295                VNI = VNUseCount.begin(), VNE = VNUseCount.end(); VNI != VNE; 
01296                ++VNI)
01297             if (VNI->first != CurrVN)
01298               VNI->second.erase(*II);
01299           LIs->RemoveMachineInstrFromMaps(*II);
01300           (*II)->eraseFromParent();
01301         }
01302         
01303         VNUseCount.erase(CurrVN);
01304 
01305         for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
01306              VI = VNUseCount.begin(), VE = VNUseCount.end(); VI != VE; ++VI)
01307           if (VI->second.erase(use))
01308             VI->second.insert(NewMI);
01309 
01310         NumDeadSpills++;
01311         changed = true;
01312         continue;
01313       }
01314       
01315       // If there's more than one non-store instruction, we can't profitably
01316       // fold it, so bail.
01317       if (NonSpillCount) continue;
01318         
01319       // Otherwise, this is a load-store case, so DCE them.
01320       for (SmallPtrSet<MachineInstr*, 4>::iterator UI = 
01321            VNUseCount[CurrVN].begin(), UE = VNUseCount[CurrVN].end();
01322            UI != UI; ++UI) {
01323         LIs->RemoveMachineInstrFromMaps(*UI);
01324         (*UI)->eraseFromParent();
01325       }
01326         
01327       VNUseCount.erase(CurrVN);
01328         
01329       LIs->RemoveMachineInstrFromMaps(DefMI);
01330       (*LI)->removeValNo(CurrVN);
01331       DefMI->eraseFromParent();
01332       NumDeadSpills++;
01333       changed = true;
01334     }
01335   }
01336   
01337   return changed;
01338 }
01339 
01340 bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
01341                                        MachineBasicBlock* DefMBB,
01342                                        MachineBasicBlock* BarrierMBB) {
01343   if (DefMBB == BarrierMBB)
01344     return false;
01345   
01346   if (LR->valno->hasPHIKill)
01347     return false;
01348   
01349   unsigned MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
01350   if (LR->end < MBBEnd)
01351     return false;
01352   
01353   MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
01354   if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
01355     return true;
01356   
01357   MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
01358   SmallPtrSet<MachineBasicBlock*, 4> Visited;
01359   typedef std::pair<MachineBasicBlock*,
01360                     MachineBasicBlock::succ_iterator> ItPair;
01361   SmallVector<ItPair, 4> Stack;
01362   Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
01363   
01364   while (!Stack.empty()) {
01365     ItPair P = Stack.back();
01366     Stack.pop_back();
01367     
01368     MachineBasicBlock* PredMBB = P.first;
01369     MachineBasicBlock::succ_iterator S = P.second;
01370     
01371     if (S == PredMBB->succ_end())
01372       continue;
01373     else if (Visited.count(*S)) {
01374       Stack.push_back(std::make_pair(PredMBB, ++S));
01375       continue;
01376     } else
01377       Stack.push_back(std::make_pair(PredMBB, S+1));
01378     
01379     MachineBasicBlock* MBB = *S;
01380     Visited.insert(MBB);
01381     
01382     if (MBB == BarrierMBB)
01383       return true;
01384     
01385     MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
01386     MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
01387     MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
01388     while (MDTN) {
01389       if (MDTN == DefMDTN)
01390         return true;
01391       else if (MDTN == BarrierMDTN)
01392         break;
01393       MDTN = MDTN->getIDom();
01394     }
01395     
01396     MBBEnd = LIs->getMBBEndIdx(MBB);
01397     if (LR->end > MBBEnd)
01398       Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
01399   }
01400   
01401   return false;
01402 } 
01403   
01404 
01405 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
01406   CurrMF = &MF;
01407   TM     = &MF.getTarget();
01408   TRI    = TM->getRegisterInfo();
01409   TII    = TM->getInstrInfo();
01410   MFI    = MF.getFrameInfo();
01411   MRI    = &MF.getRegInfo();
01412   LIs    = &getAnalysis<LiveIntervals>();
01413   LSs    = &getAnalysis<LiveStacks>();
01414 
01415   bool MadeChange = false;
01416 
01417   // Make sure blocks are numbered in order.
01418   MF.RenumberBlocks();
01419 
01420   MachineBasicBlock *Entry = MF.begin();
01421   SmallPtrSet<MachineBasicBlock*,16> Visited;
01422 
01423   SmallPtrSet<LiveInterval*, 8> Split;
01424 
01425   for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
01426          DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
01427        DFI != E; ++DFI) {
01428     BarrierMBB = *DFI;
01429     for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
01430            E = BarrierMBB->end(); I != E; ++I) {
01431       Barrier = &*I;
01432       const TargetRegisterClass **BarrierRCs =
01433         Barrier->getDesc().getRegClassBarriers();
01434       if (!BarrierRCs)
01435         continue;
01436       BarrierIdx = LIs->getInstructionIndex(Barrier);
01437       MadeChange |= SplitRegLiveIntervals(BarrierRCs, Split);
01438     }
01439   }
01440 
01441   MadeChange |= removeDeadSpills(Split);
01442 
01443   return MadeChange;
01444 }