LLVM API Documentation

SimpleRegisterCoalescing.cpp

Go to the documentation of this file.
00001 //===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
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 a simple register coalescing pass that attempts to
00011 // aggressively coalesce every register copy that it can.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #define DEBUG_TYPE "regcoalescing"
00016 #include "SimpleRegisterCoalescing.h"
00017 #include "VirtRegMap.h"
00018 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00019 #include "llvm/Value.h"
00020 #include "llvm/CodeGen/MachineFrameInfo.h"
00021 #include "llvm/CodeGen/MachineInstr.h"
00022 #include "llvm/CodeGen/MachineLoopInfo.h"
00023 #include "llvm/CodeGen/MachineRegisterInfo.h"
00024 #include "llvm/CodeGen/Passes.h"
00025 #include "llvm/CodeGen/RegisterCoalescer.h"
00026 #include "llvm/Target/TargetInstrInfo.h"
00027 #include "llvm/Target/TargetMachine.h"
00028 #include "llvm/Target/TargetOptions.h"
00029 #include "llvm/Support/CommandLine.h"
00030 #include "llvm/Support/Debug.h"
00031 #include "llvm/ADT/SmallSet.h"
00032 #include "llvm/ADT/Statistic.h"
00033 #include "llvm/ADT/STLExtras.h"
00034 #include <algorithm>
00035 #include <cmath>
00036 using namespace llvm;
00037 
00038 STATISTIC(numJoins    , "Number of interval joins performed");
00039 STATISTIC(numSubJoins , "Number of subclass joins performed");
00040 STATISTIC(numCommutes , "Number of instruction commuting performed");
00041 STATISTIC(numExtends  , "Number of copies extended");
00042 STATISTIC(NumReMats   , "Number of instructions re-materialized");
00043 STATISTIC(numPeep     , "Number of identity moves eliminated after coalescing");
00044 STATISTIC(numAborts   , "Number of times interval joining aborted");
00045 
00046 char SimpleRegisterCoalescing::ID = 0;
00047 static cl::opt<bool>
00048 EnableJoining("join-liveintervals",
00049               cl::desc("Coalesce copies (default=true)"),
00050               cl::init(true));
00051 
00052 static cl::opt<bool>
00053 NewHeuristic("new-coalescer-heuristic",
00054              cl::desc("Use new coalescer heuristic"),
00055              cl::init(false), cl::Hidden);
00056 
00057 static cl::opt<bool>
00058 CrossClassJoin("join-subclass-copies",
00059                cl::desc("Coalesce copies to sub- register class"),
00060                cl::init(false), cl::Hidden);
00061 
00062 static RegisterPass<SimpleRegisterCoalescing> 
00063 X("simple-register-coalescing", "Simple Register Coalescing");
00064 
00065 // Declare that we implement the RegisterCoalescer interface
00066 static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
00067 
00068 const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
00069 
00070 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
00071   AU.addRequired<LiveIntervals>();
00072   AU.addPreserved<LiveIntervals>();
00073   AU.addRequired<MachineLoopInfo>();
00074   AU.addPreserved<MachineLoopInfo>();
00075   AU.addPreservedID(MachineDominatorsID);
00076   if (StrongPHIElim)
00077     AU.addPreservedID(StrongPHIEliminationID);
00078   else
00079     AU.addPreservedID(PHIEliminationID);
00080   AU.addPreservedID(TwoAddressInstructionPassID);
00081   MachineFunctionPass::getAnalysisUsage(AU);
00082 }
00083 
00084 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
00085 /// being the source and IntB being the dest, thus this defines a value number
00086 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
00087 /// see if we can merge these two pieces of B into a single value number,
00088 /// eliminating a copy.  For example:
00089 ///
00090 ///  A3 = B0
00091 ///    ...
00092 ///  B1 = A3      <- this copy
00093 ///
00094 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
00095 /// value number to be replaced with B0 (which simplifies the B liveinterval).
00096 ///
00097 /// This returns true if an interval was modified.
00098 ///
00099 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
00100                                                     LiveInterval &IntB,
00101                                                     MachineInstr *CopyMI) {
00102   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
00103 
00104   // BValNo is a value number in B that is defined by a copy from A.  'B3' in
00105   // the example above.
00106   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
00107   if (BLR == IntB.end()) // Should never happen!
00108     return false;
00109   VNInfo *BValNo = BLR->valno;
00110   
00111   // Get the location that B is defined at.  Two options: either this value has
00112   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
00113   // can't process it.
00114   if (!BValNo->copy) return false;
00115   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
00116   
00117   // AValNo is the value number in A that defines the copy, A3 in the example.
00118   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
00119   if (ALR == IntA.end()) // Should never happen!
00120     return false;
00121   VNInfo *AValNo = ALR->valno;
00122   
00123   // If AValNo is defined as a copy from IntB, we can potentially process this.  
00124   // Get the instruction that defines this value number.
00125   unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
00126   if (!SrcReg) return false;  // Not defined by a copy.
00127     
00128   // If the value number is not defined by a copy instruction, ignore it.
00129 
00130   // If the source register comes from an interval other than IntB, we can't
00131   // handle this.
00132   if (SrcReg != IntB.reg) return false;
00133   
00134   // Get the LiveRange in IntB that this value number starts with.
00135   LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
00136   if (ValLR == IntB.end()) // Should never happen!
00137     return false;
00138   
00139   // Make sure that the end of the live range is inside the same block as
00140   // CopyMI.
00141   MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
00142   if (!ValLREndInst || 
00143       ValLREndInst->getParent() != CopyMI->getParent()) return false;
00144 
00145   // Okay, we now know that ValLR ends in the same block that the CopyMI
00146   // live-range starts.  If there are no intervening live ranges between them in
00147   // IntB, we can merge them.
00148   if (ValLR+1 != BLR) return false;
00149 
00150   // If a live interval is a physical register, conservatively check if any
00151   // of its sub-registers is overlapping the live interval of the virtual
00152   // register. If so, do not coalesce.
00153   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
00154       *tri_->getSubRegisters(IntB.reg)) {
00155     for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
00156       if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
00157         DOUT << "Interfere with sub-register ";
00158         DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
00159         return false;
00160       }
00161   }
00162   
00163   DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
00164   
00165   unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
00166   // We are about to delete CopyMI, so need to remove it as the 'instruction
00167   // that defines this value #'. Update the the valnum with the new defining
00168   // instruction #.
00169   BValNo->def  = FillerStart;
00170   BValNo->copy = NULL;
00171   
00172   // Okay, we can merge them.  We need to insert a new liverange:
00173   // [ValLR.end, BLR.begin) of either value number, then we merge the
00174   // two value numbers.
00175   IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
00176 
00177   // If the IntB live range is assigned to a physical register, and if that
00178   // physreg has aliases, 
00179   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
00180     // Update the liveintervals of sub-registers.
00181     for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
00182       LiveInterval &AliasLI = li_->getInterval(*AS);
00183       AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
00184               AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
00185     }
00186   }
00187 
00188   // Okay, merge "B1" into the same value number as "B0".
00189   if (BValNo != ValLR->valno) {
00190     IntB.addKills(ValLR->valno, BValNo->kills);
00191     IntB.MergeValueNumberInto(BValNo, ValLR->valno);
00192   }
00193   DOUT << "   result = "; IntB.print(DOUT, tri_);
00194   DOUT << "\n";
00195 
00196   // If the source instruction was killing the source register before the
00197   // merge, unset the isKill marker given the live range has been extended.
00198   int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
00199   if (UIdx != -1) {
00200     ValLREndInst->getOperand(UIdx).setIsKill(false);
00201     IntB.removeKill(ValLR->valno, FillerStart);
00202   }
00203 
00204   ++numExtends;
00205   return true;
00206 }
00207 
00208 /// HasOtherReachingDefs - Return true if there are definitions of IntB
00209 /// other than BValNo val# that can reach uses of AValno val# of IntA.
00210 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
00211                                                     LiveInterval &IntB,
00212                                                     VNInfo *AValNo,
00213                                                     VNInfo *BValNo) {
00214   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
00215        AI != AE; ++AI) {
00216     if (AI->valno != AValNo) continue;
00217     LiveInterval::Ranges::iterator BI =
00218       std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
00219     if (BI != IntB.ranges.begin())
00220       --BI;
00221     for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
00222       if (BI->valno == BValNo)
00223         continue;
00224       if (BI->start <= AI->start && BI->end > AI->start)
00225         return true;
00226       if (BI->start > AI->start && BI->start < AI->end)
00227         return true;
00228     }
00229   }
00230   return false;
00231 }
00232 
00233 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
00234 /// being the source and IntB being the dest, thus this defines a value number
00235 /// in IntB.  If the source value number (in IntA) is defined by a commutable
00236 /// instruction and its other operand is coalesced to the copy dest register,
00237 /// see if we can transform the copy into a noop by commuting the definition. For
00238 /// example,
00239 ///
00240 ///  A3 = op A2 B0<kill>
00241 ///    ...
00242 ///  B1 = A3      <- this copy
00243 ///    ...
00244 ///     = op A3   <- more uses
00245 ///
00246 /// ==>
00247 ///
00248 ///  B2 = op B0 A2<kill>
00249 ///    ...
00250 ///  B1 = B2      <- now an identify copy
00251 ///    ...
00252 ///     = op B2   <- more uses
00253 ///
00254 /// This returns true if an interval was modified.
00255 ///
00256 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
00257                                                         LiveInterval &IntB,
00258                                                         MachineInstr *CopyMI) {
00259   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
00260 
00261   // FIXME: For now, only eliminate the copy by commuting its def when the
00262   // source register is a virtual register. We want to guard against cases
00263   // where the copy is a back edge copy and commuting the def lengthen the
00264   // live interval of the source register to the entire loop.
00265   if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
00266     return false;
00267 
00268   // BValNo is a value number in B that is defined by a copy from A. 'B3' in
00269   // the example above.
00270   LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
00271   if (BLR == IntB.end()) // Should never happen!
00272     return false;
00273   VNInfo *BValNo = BLR->valno;
00274   
00275   // Get the location that B is defined at.  Two options: either this value has
00276   // an unknown definition point or it is defined at CopyIdx.  If unknown, we 
00277   // can't process it.
00278   if (!BValNo->copy) return false;
00279   assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
00280   
00281   // AValNo is the value number in A that defines the copy, A3 in the example.
00282   LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
00283   if (ALR == IntA.end()) // Should never happen!
00284     return false;
00285   VNInfo *AValNo = ALR->valno;
00286   // If other defs can reach uses of this def, then it's not safe to perform
00287   // the optimization.
00288   if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
00289     return false;
00290   MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
00291   const TargetInstrDesc &TID = DefMI->getDesc();
00292   unsigned NewDstIdx;
00293   if (!TID.isCommutable() ||
00294       !tii_->CommuteChangesDestination(DefMI, NewDstIdx))
00295     return false;
00296 
00297   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
00298   unsigned NewReg = NewDstMO.getReg();
00299   if (NewReg != IntB.reg || !NewDstMO.isKill())
00300     return false;
00301 
00302   // Make sure there are no other definitions of IntB that would reach the
00303   // uses which the new definition can reach.
00304   if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
00305     return false;
00306 
00307   // If some of the uses of IntA.reg is already coalesced away, return false.
00308   // It's not possible to determine whether it's safe to perform the coalescing.
00309   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
00310          UE = mri_->use_end(); UI != UE; ++UI) {
00311     MachineInstr *UseMI = &*UI;
00312     unsigned UseIdx = li_->getInstructionIndex(UseMI);
00313     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
00314     if (ULR == IntA.end())
00315       continue;
00316     if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
00317       return false;
00318   }
00319 
00320   // At this point we have decided that it is legal to do this
00321   // transformation.  Start by commuting the instruction.
00322   MachineBasicBlock *MBB = DefMI->getParent();
00323   MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
00324   if (!NewMI)
00325     return false;
00326   if (NewMI != DefMI) {
00327     li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
00328     MBB->insert(DefMI, NewMI);
00329     MBB->erase(DefMI);
00330   }
00331   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
00332   NewMI->getOperand(OpIdx).setIsKill();
00333 
00334   bool BHasPHIKill = BValNo->hasPHIKill;
00335   SmallVector<VNInfo*, 4> BDeadValNos;
00336   SmallVector<unsigned, 4> BKills;
00337   std::map<unsigned, unsigned> BExtend;
00338 
00339   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
00340   // A = or A, B
00341   // ...
00342   // B = A
00343   // ...
00344   // C = A<kill>
00345   // ...
00346   //   = B
00347   //
00348   // then do not add kills of A to the newly created B interval.
00349   bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
00350   if (Extended)
00351     BExtend[ALR->end] = BLR->end;
00352 
00353   // Update uses of IntA of the specific Val# with IntB.
00354   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
00355          UE = mri_->use_end(); UI != UE;) {
00356     MachineOperand &UseMO = UI.getOperand();
00357     MachineInstr *UseMI = &*UI;
00358     ++UI;
00359     if (JoinedCopies.count(UseMI))
00360       continue;
00361     unsigned UseIdx = li_->getInstructionIndex(UseMI);
00362     LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
00363     if (ULR == IntA.end() || ULR->valno != AValNo)
00364       continue;
00365     UseMO.setReg(NewReg);
00366     if (UseMI == CopyMI)
00367       continue;
00368     if (UseMO.isKill()) {
00369       if (Extended)
00370         UseMO.setIsKill(false);
00371       else
00372         BKills.push_back(li_->getUseIndex(UseIdx)+1);
00373     }
00374     unsigned SrcReg, DstReg;
00375     if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg))
00376       continue;
00377     if (DstReg == IntB.reg) {
00378       // This copy will become a noop. If it's defining a new val#,
00379       // remove that val# as well. However this live range is being
00380       // extended to the end of the existing live range defined by the copy.
00381       unsigned DefIdx = li_->getDefIndex(UseIdx);
00382       const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
00383       BHasPHIKill |= DLR->valno->hasPHIKill;
00384       assert(DLR->valno->def == DefIdx);
00385       BDeadValNos.push_back(DLR->valno);
00386       BExtend[DLR->start] = DLR->end;
00387       JoinedCopies.insert(UseMI);
00388       // If this is a kill but it's going to be removed, the last use
00389       // of the same val# is the new kill.
00390       if (UseMO.isKill())
00391         BKills.pop_back();
00392     }
00393   }
00394 
00395   // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
00396   // simply extend BLR if CopyMI doesn't end the range.
00397   DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
00398 
00399   // Remove val#'s defined by copies that will be coalesced away.
00400   for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
00401     IntB.removeValNo(BDeadValNos[i]);
00402 
00403   // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
00404   // is updated. Kills are also updated.
00405   VNInfo *ValNo = BValNo;
00406   ValNo->def = AValNo->def;
00407   ValNo->copy = NULL;
00408   for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
00409     unsigned Kill = ValNo->kills[j];
00410     if (Kill != BLR->end)
00411       BKills.push_back(Kill);
00412   }
00413   ValNo->kills.clear();
00414   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
00415        AI != AE; ++AI) {
00416     if (AI->valno != AValNo) continue;
00417     unsigned End = AI->end;
00418     std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
00419     if (EI != BExtend.end())
00420       End = EI->second;
00421     IntB.addRange(LiveRange(AI->start, End, ValNo));
00422   }
00423   IntB.addKills(ValNo, BKills);
00424   ValNo->hasPHIKill = BHasPHIKill;
00425 
00426   DOUT << "   result = "; IntB.print(DOUT, tri_);
00427   DOUT << "\n";
00428 
00429   DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
00430   IntA.removeValNo(AValNo);
00431   DOUT << "   result = "; IntA.print(DOUT, tri_);
00432   DOUT << "\n";
00433 
00434   ++numCommutes;
00435   return true;
00436 }
00437 
00438 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
00439 /// computation, replace the copy by rematerialize the definition.
00440 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
00441                                                        unsigned DstReg,
00442                                                        MachineInstr *CopyMI) {
00443   unsigned CopyIdx = li_->getUseIndex(li_->getInstructionIndex(CopyMI));
00444   LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
00445   if (SrcLR == SrcInt.end()) // Should never happen!
00446     return false;
00447   VNInfo *ValNo = SrcLR->valno;
00448   // If other defs can reach uses of this def, then it's not safe to perform
00449   // the optimization.
00450   if (ValNo->def == ~0U || ValNo->def == ~1U || ValNo->hasPHIKill)
00451     return false;
00452   MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
00453   const TargetInstrDesc &TID = DefMI->getDesc();
00454   if (!TID.isAsCheapAsAMove())
00455     return false;
00456   bool SawStore = false;
00457   if (!DefMI->isSafeToMove(tii_, SawStore))
00458     return false;
00459 
00460   unsigned DefIdx = li_->getDefIndex(CopyIdx);
00461   const LiveRange *DLR= li_->getInterval(DstReg).getLiveRangeContaining(DefIdx);
00462   DLR->valno->copy = NULL;
00463 
00464   MachineBasicBlock::iterator MII = CopyMI;
00465   MachineBasicBlock *MBB = CopyMI->getParent();
00466   tii_->reMaterialize(*MBB, MII, DstReg, DefMI);
00467   MachineInstr *NewMI = prior(MII);
00468   // CopyMI may have implicit instructions, transfer them over to the newly
00469   // rematerialized instruction. And update implicit def interval valnos.
00470   for (unsigned i = CopyMI->getDesc().getNumOperands(),
00471          e = CopyMI->getNumOperands(); i != e; ++i) {
00472     MachineOperand &MO = CopyMI->getOperand(i);
00473     if (MO.isReg() && MO.isImplicit())
00474       NewMI->addOperand(MO);
00475     if (MO.isDef() && li_->hasInterval(MO.getReg())) {
00476       unsigned Reg = MO.getReg();
00477       DLR = li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
00478       if (DLR && DLR->valno->copy == CopyMI)
00479         DLR->valno->copy = NULL;
00480     }
00481   }
00482 
00483   li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
00484   CopyMI->eraseFromParent();
00485   ReMatCopies.insert(CopyMI);
00486   ReMatDefs.insert(DefMI);
00487   ++NumReMats;
00488   return true;
00489 }
00490 
00491 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
00492 ///
00493 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
00494                                               unsigned DstReg) const {
00495   MachineBasicBlock *MBB = CopyMI->getParent();
00496   const MachineLoop *L = loopInfo->getLoopFor(MBB);
00497   if (!L)
00498     return false;
00499   if (MBB != L->getLoopLatch())
00500     return false;
00501 
00502   LiveInterval &LI = li_->getInterval(DstReg);
00503   unsigned DefIdx = li_->getInstructionIndex(CopyMI);
00504   LiveInterval::const_iterator DstLR =
00505     LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
00506   if (DstLR == LI.end())
00507     return false;
00508   unsigned KillIdx = li_->getMBBEndIdx(MBB) + 1;
00509   if (DstLR->valno->kills.size() == 1 &&
00510       DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
00511     return true;
00512   return false;
00513 }
00514 
00515 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
00516 /// update the subregister number if it is not zero. If DstReg is a
00517 /// physical register and the existing subregister number of the def / use
00518 /// being updated is not zero, make sure to set it to the correct physical
00519 /// subregister.
00520 void
00521 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
00522                                             unsigned SubIdx) {
00523   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
00524   if (DstIsPhys && SubIdx) {
00525     // Figure out the real physical register we are updating with.
00526     DstReg = tri_->getSubReg(DstReg, SubIdx);
00527     SubIdx = 0;
00528   }
00529 
00530   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
00531          E = mri_->reg_end(); I != E; ) {
00532     MachineOperand &O = I.getOperand();
00533     MachineInstr *UseMI = &*I;
00534     ++I;
00535     unsigned OldSubIdx = O.getSubReg();
00536     if (DstIsPhys) {
00537       unsigned UseDstReg = DstReg;
00538       if (OldSubIdx)
00539           UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
00540 
00541       unsigned CopySrcReg, CopyDstReg;
00542       if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg) &&
00543           CopySrcReg != CopyDstReg &&
00544           CopySrcReg == SrcReg && CopyDstReg != UseDstReg) {
00545         // If the use is a copy and it won't be coalesced away, and its source
00546         // is defined by a trivial computation, try to rematerialize it instead.
00547         if (ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,UseMI))
00548           continue;
00549       }
00550 
00551       O.setReg(UseDstReg);
00552       O.setSubReg(0);
00553       continue;
00554     }
00555 
00556     // Sub-register indexes goes from small to large. e.g.
00557     // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
00558     // EAX: 1 -> AL, 2 -> AX
00559     // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
00560     // sub-register 2 is also AX.
00561     if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
00562       assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
00563     else if (SubIdx)
00564       O.setSubReg(SubIdx);
00565     // Remove would-be duplicated kill marker.
00566     if (O.isKill() && UseMI->killsRegister(DstReg))
00567       O.setIsKill(false);
00568     O.setReg(DstReg);
00569 
00570     // After updating the operand, check if the machine instruction has
00571     // become a copy. If so, update its val# information.
00572     const TargetInstrDesc &TID = UseMI->getDesc();
00573     unsigned CopySrcReg, CopyDstReg;
00574     if (TID.getNumDefs() == 1 && TID.getNumOperands() > 2 &&
00575         tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg) &&
00576         CopySrcReg != CopyDstReg &&
00577         (TargetRegisterInfo::isVirtualRegister(CopyDstReg) ||
00578          allocatableRegs_[CopyDstReg])) {
00579       LiveInterval &LI = li_->getInterval(CopyDstReg);
00580       unsigned DefIdx = li_->getDefIndex(li_->getInstructionIndex(UseMI));
00581       const LiveRange *DLR = LI.getLiveRangeContaining(DefIdx);
00582       if (DLR->valno->def == DefIdx)
00583         DLR->valno->copy = UseMI;
00584     }
00585   }
00586 }
00587 
00588 /// RemoveDeadImpDef - Remove implicit_def instructions which are "re-defining"
00589 /// registers due to insert_subreg coalescing. e.g.
00590 /// r1024 = op
00591 /// r1025 = implicit_def
00592 /// r1025 = insert_subreg r1025, r1024
00593 ///       = op r1025
00594 /// =>
00595 /// r1025 = op
00596 /// r1025 = implicit_def
00597 /// r1025 = insert_subreg r1025, r1025
00598 ///       = op r1025
00599 void
00600 SimpleRegisterCoalescing::RemoveDeadImpDef(unsigned Reg, LiveInterval &LI) {
00601   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
00602          E = mri_->reg_end(); I != E; ) {
00603     MachineOperand &O = I.getOperand();
00604     MachineInstr *DefMI = &*I;
00605     ++I;
00606     if (!O.isDef())
00607       continue;
00608     if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
00609       continue;
00610     if (!LI.liveBeforeAndAt(li_->getInstructionIndex(DefMI)))
00611       continue;
00612     li_->RemoveMachineInstrFromMaps(DefMI);
00613     DefMI->eraseFromParent();
00614   }
00615 }
00616 
00617 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
00618 /// due to live range lengthening as the result of coalescing.
00619 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
00620                                                       LiveInterval &LI) {
00621   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
00622          UE = mri_->use_end(); UI != UE; ++UI) {
00623     MachineOperand &UseMO = UI.getOperand();
00624     if (UseMO.isKill()) {
00625       MachineInstr *UseMI = UseMO.getParent();
00626       unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
00627       if (JoinedCopies.count(UseMI))
00628         continue;
00629       const LiveRange *UI = LI.getLiveRangeContaining(UseIdx);
00630       if (!UI || !LI.isKill(UI->valno, UseIdx+1))
00631         UseMO.setIsKill(false);
00632     }
00633   }
00634 }
00635 
00636 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
00637 /// from a physical register live interval as well as from the live intervals
00638 /// of its sub-registers.
00639 static void removeRange(LiveInterval &li, unsigned Start, unsigned End,
00640                         LiveIntervals *li_, const TargetRegisterInfo *tri_) {
00641   li.removeRange(Start, End, true);
00642   if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
00643     for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
00644       if (!li_->hasInterval(*SR))
00645         continue;
00646       LiveInterval &sli = li_->getInterval(*SR);
00647       unsigned RemoveEnd = Start;
00648       while (RemoveEnd != End) {
00649         LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
00650         if (LR == sli.end())
00651           break;
00652         RemoveEnd = (LR->end < End) ? LR->end : End;
00653         sli.removeRange(Start, RemoveEnd, true);
00654         Start = RemoveEnd;
00655       }
00656     }
00657   }
00658 }
00659 
00660 /// removeIntervalIfEmpty - Check if the live interval of a physical register
00661 /// is empty, if so remove it and also remove the empty intervals of its
00662 /// sub-registers. Return true if live interval is removed.
00663 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
00664                                   const TargetRegisterInfo *tri_) {
00665   if (li.empty()) {
00666     if (TargetRegisterInfo::isPhysicalRegister(li.reg))
00667       for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
00668         if (!li_->hasInterval(*SR))
00669           continue;
00670         LiveInterval &sli = li_->getInterval(*SR);
00671         if (sli.empty())
00672           li_->removeInterval(*SR);
00673       }
00674     li_->removeInterval(li.reg);
00675     return true;
00676   }
00677   return false;
00678 }
00679 
00680 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
00681 /// Return true if live interval is removed.
00682 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
00683                                                         MachineInstr *CopyMI) {
00684   unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
00685   LiveInterval::iterator MLR =
00686     li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
00687   if (MLR == li.end())
00688     return false;  // Already removed by ShortenDeadCopySrcLiveRange.
00689   unsigned RemoveStart = MLR->start;
00690   unsigned RemoveEnd = MLR->end;
00691   // Remove the liverange that's defined by this.
00692   if (RemoveEnd == li_->getDefIndex(CopyIdx)+1) {
00693     removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
00694     return removeIntervalIfEmpty(li, li_, tri_);
00695   }
00696   return false;
00697 }
00698 
00699 /// PropagateDeadness - Propagate the dead marker to the instruction which
00700 /// defines the val#.
00701 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
00702                               unsigned &LRStart, LiveIntervals *li_,
00703                               const TargetRegisterInfo* tri_) {
00704   MachineInstr *DefMI =
00705     li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
00706   if (DefMI && DefMI != CopyMI) {
00707     int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_);
00708     if (DeadIdx != -1) {
00709       DefMI->getOperand(DeadIdx).setIsDead();
00710       // A dead def should have a single cycle interval.
00711       ++LRStart;
00712     }
00713   }
00714 }
00715 
00716 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
00717 /// fallthoughs to SuccMBB.
00718 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
00719                                   MachineBasicBlock *SuccMBB,
00720                                   const TargetInstrInfo *tii_) {
00721   if (MBB == SuccMBB)
00722     return true;
00723   MachineBasicBlock *TBB = 0, *FBB = 0;
00724   SmallVector<MachineOperand, 4> Cond;
00725   return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
00726     MBB->isSuccessor(SuccMBB);
00727 }
00728 
00729 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
00730 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
00731 /// ends the live range there. If there isn't another use, then this live range
00732 /// is dead. Return true if live interval is removed.
00733 bool
00734 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
00735                                                       MachineInstr *CopyMI) {
00736   unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
00737   if (CopyIdx == 0) {
00738     // FIXME: special case: function live in. It can be a general case if the
00739     // first instruction index starts at > 0 value.
00740     assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
00741     // Live-in to the function but dead. Remove it from entry live-in set.
00742     if (mf_->begin()->isLiveIn(li.reg))
00743       mf_->begin()->removeLiveIn(li.reg);
00744     const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
00745     removeRange(li, LR->start, LR->end, li_, tri_);
00746     return removeIntervalIfEmpty(li, li_, tri_);
00747   }
00748 
00749   LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1);
00750   if (LR == li.end())
00751     // Livein but defined by a phi.
00752     return false;
00753 
00754   unsigned RemoveStart = LR->start;
00755   unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1;
00756   if (LR->end > RemoveEnd)
00757     // More uses past this copy? Nothing to do.
00758     return false;
00759 
00760   MachineBasicBlock *CopyMBB = CopyMI->getParent();
00761   unsigned MBBStart = li_->getMBBStartIdx(CopyMBB);
00762   unsigned LastUseIdx;
00763   MachineOperand *LastUse = lastRegisterUse(LR->start, CopyIdx-1, li.reg,
00764                                             LastUseIdx);
00765   if (LastUse) {
00766     MachineInstr *LastUseMI = LastUse->getParent();
00767     if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
00768       // r1024 = op
00769       // ...
00770       // BB1:
00771       //       = r1024
00772       //
00773       // BB2:
00774       // r1025<dead> = r1024<kill>
00775       if (MBBStart < LR->end)
00776         removeRange(li, MBBStart, LR->end, li_, tri_);
00777       return false;
00778     }
00779 
00780     // There are uses before the copy, just shorten the live range to the end
00781     // of last use.
00782     LastUse->setIsKill();
00783     removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
00784     unsigned SrcReg, DstReg;
00785     if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg) &&
00786         DstReg == li.reg) {
00787       // Last use is itself an identity code.
00788       int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
00789       LastUseMI->getOperand(DeadIdx).setIsDead();
00790     }
00791     return false;
00792   }
00793 
00794   // Is it livein?
00795   if (LR->start <= MBBStart && LR->end > MBBStart) {
00796     if (LR->start == 0) {
00797       assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
00798       // Live-in to the function but dead. Remove it from entry live-in set.
00799       mf_->begin()->removeLiveIn(li.reg);
00800     }
00801     // FIXME: Shorten intervals in BBs that reaches this BB.
00802   }
00803 
00804   if (LR->valno->def == RemoveStart)
00805     // If the def MI defines the val#, propagate the dead marker.
00806     PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
00807 
00808   removeRange(li, RemoveStart, LR->end, li_, tri_);
00809   return removeIntervalIfEmpty(li, li_, tri_);
00810 }
00811 
00812 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
00813 /// from an implicit def to another register can be coalesced away.
00814 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
00815                                                      LiveInterval &li,
00816                                                      LiveInterval &ImpLi) const{
00817   if (!CopyMI->killsRegister(ImpLi.reg))
00818     return false;
00819   unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
00820   LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx);
00821   if (LR == li.end())
00822     return false;
00823   if (LR->valno->hasPHIKill)
00824     return false;
00825   if (LR->valno->def != CopyIdx)
00826     return false;
00827   // Make sure all of val# uses are copies.
00828   for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(li.reg),
00829          UE = mri_->use_end(); UI != UE;) {
00830     MachineInstr *UseMI = &*UI;
00831     ++UI;
00832     if (JoinedCopies.count(UseMI))
00833       continue;
00834     unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
00835     LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
00836     if (ULR == li.end() || ULR->valno != LR->valno)
00837       continue;
00838     // If the use is not a use, then it's not safe to coalesce the move.
00839     unsigned SrcReg, DstReg;
00840     if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg)) {
00841       if (UseMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG &&
00842           UseMI->getOperand(1).getReg() == li.reg)
00843         continue;
00844       return false;
00845     }
00846   }
00847   return true;
00848 }
00849 
00850 
00851 /// RemoveCopiesFromValNo - The specified value# is defined by an implicit
00852 /// def and it is being removed. Turn all copies from this value# into
00853 /// identity copies so they will be removed.
00854 void SimpleRegisterCoalescing::RemoveCopiesFromValNo(LiveInterval &li,
00855                                                      VNInfo *VNI) {
00856   SmallVector<MachineInstr*, 4> ImpDefs;
00857   MachineOperand *LastUse = NULL;
00858   unsigned LastUseIdx = li_->getUseIndex(VNI->def);
00859   for (