LLVM API Documentation

RegisterCoalescer.cpp
Go to the documentation of this file.
00001 //===- RegisterCoalescer.cpp - Generic Register Coalescing Interface -------==//
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 generic RegisterCoalescer interface which
00011 // is used as the common interface used by all clients and
00012 // implementations of register coalescing.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "RegisterCoalescer.h"
00017 #include "llvm/ADT/STLExtras.h"
00018 #include "llvm/ADT/SmallSet.h"
00019 #include "llvm/ADT/Statistic.h"
00020 #include "llvm/Analysis/AliasAnalysis.h"
00021 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00022 #include "llvm/CodeGen/LiveRangeEdit.h"
00023 #include "llvm/CodeGen/MachineFrameInfo.h"
00024 #include "llvm/CodeGen/MachineInstr.h"
00025 #include "llvm/CodeGen/MachineLoopInfo.h"
00026 #include "llvm/CodeGen/MachineRegisterInfo.h"
00027 #include "llvm/CodeGen/Passes.h"
00028 #include "llvm/CodeGen/RegisterClassInfo.h"
00029 #include "llvm/CodeGen/VirtRegMap.h"
00030 #include "llvm/IR/Value.h"
00031 #include "llvm/Pass.h"
00032 #include "llvm/Support/CommandLine.h"
00033 #include "llvm/Support/Debug.h"
00034 #include "llvm/Support/ErrorHandling.h"
00035 #include "llvm/Support/raw_ostream.h"
00036 #include "llvm/Target/TargetInstrInfo.h"
00037 #include "llvm/Target/TargetMachine.h"
00038 #include "llvm/Target/TargetRegisterInfo.h"
00039 #include "llvm/Target/TargetSubtargetInfo.h"
00040 #include <algorithm>
00041 #include <cmath>
00042 using namespace llvm;
00043 
00044 #define DEBUG_TYPE "regalloc"
00045 
00046 STATISTIC(numJoins    , "Number of interval joins performed");
00047 STATISTIC(numCrossRCs , "Number of cross class joins performed");
00048 STATISTIC(numCommutes , "Number of instruction commuting performed");
00049 STATISTIC(numExtends  , "Number of copies extended");
00050 STATISTIC(NumReMats   , "Number of instructions re-materialized");
00051 STATISTIC(NumInflated , "Number of register classes inflated");
00052 STATISTIC(NumLaneConflicts, "Number of dead lane conflicts tested");
00053 STATISTIC(NumLaneResolves,  "Number of dead lane conflicts resolved");
00054 
00055 static cl::opt<bool>
00056 EnableJoining("join-liveintervals",
00057               cl::desc("Coalesce copies (default=true)"),
00058               cl::init(true));
00059 
00060 // Temporary flag to test critical edge unsplitting.
00061 static cl::opt<bool>
00062 EnableJoinSplits("join-splitedges",
00063   cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden);
00064 
00065 // Temporary flag to test global copy optimization.
00066 static cl::opt<cl::boolOrDefault>
00067 EnableGlobalCopies("join-globalcopies",
00068   cl::desc("Coalesce copies that span blocks (default=subtarget)"),
00069   cl::init(cl::BOU_UNSET), cl::Hidden);
00070 
00071 static cl::opt<bool>
00072 VerifyCoalescing("verify-coalescing",
00073          cl::desc("Verify machine instrs before and after register coalescing"),
00074          cl::Hidden);
00075 
00076 namespace {
00077   class RegisterCoalescer : public MachineFunctionPass,
00078                             private LiveRangeEdit::Delegate {
00079     MachineFunction* MF;
00080     MachineRegisterInfo* MRI;
00081     const TargetMachine* TM;
00082     const TargetRegisterInfo* TRI;
00083     const TargetInstrInfo* TII;
00084     LiveIntervals *LIS;
00085     const MachineLoopInfo* Loops;
00086     AliasAnalysis *AA;
00087     RegisterClassInfo RegClassInfo;
00088 
00089     /// \brief True if the coalescer should aggressively coalesce global copies
00090     /// in favor of keeping local copies.
00091     bool JoinGlobalCopies;
00092 
00093     /// \brief True if the coalescer should aggressively coalesce fall-thru
00094     /// blocks exclusively containing copies.
00095     bool JoinSplitEdges;
00096 
00097     /// WorkList - Copy instructions yet to be coalesced.
00098     SmallVector<MachineInstr*, 8> WorkList;
00099     SmallVector<MachineInstr*, 8> LocalWorkList;
00100 
00101     /// ErasedInstrs - Set of instruction pointers that have been erased, and
00102     /// that may be present in WorkList.
00103     SmallPtrSet<MachineInstr*, 8> ErasedInstrs;
00104 
00105     /// Dead instructions that are about to be deleted.
00106     SmallVector<MachineInstr*, 8> DeadDefs;
00107 
00108     /// Virtual registers to be considered for register class inflation.
00109     SmallVector<unsigned, 8> InflateRegs;
00110 
00111     /// Recursively eliminate dead defs in DeadDefs.
00112     void eliminateDeadDefs();
00113 
00114     /// LiveRangeEdit callback.
00115     void LRE_WillEraseInstruction(MachineInstr *MI) override;
00116 
00117     /// coalesceLocals - coalesce the LocalWorkList.
00118     void coalesceLocals();
00119 
00120     /// joinAllIntervals - join compatible live intervals
00121     void joinAllIntervals();
00122 
00123     /// copyCoalesceInMBB - Coalesce copies in the specified MBB, putting
00124     /// copies that cannot yet be coalesced into WorkList.
00125     void copyCoalesceInMBB(MachineBasicBlock *MBB);
00126 
00127     /// copyCoalesceWorkList - Try to coalesce all copies in CurrList. Return
00128     /// true if any progress was made.
00129     bool copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList);
00130 
00131     /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
00132     /// which are the src/dst of the copy instruction CopyMI.  This returns
00133     /// true if the copy was successfully coalesced away. If it is not
00134     /// currently possible to coalesce this interval, but it may be possible if
00135     /// other things get coalesced, then it returns true by reference in
00136     /// 'Again'.
00137     bool joinCopy(MachineInstr *TheCopy, bool &Again);
00138 
00139     /// joinIntervals - Attempt to join these two intervals.  On failure, this
00140     /// returns false.  The output "SrcInt" will not have been modified, so we
00141     /// can use this information below to update aliases.
00142     bool joinIntervals(CoalescerPair &CP);
00143 
00144     /// Attempt joining two virtual registers. Return true on success.
00145     bool joinVirtRegs(CoalescerPair &CP);
00146 
00147     /// Attempt joining with a reserved physreg.
00148     bool joinReservedPhysReg(CoalescerPair &CP);
00149 
00150     /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy. If
00151     /// the source value number is defined by a copy from the destination reg
00152     /// see if we can merge these two destination reg valno# into a single
00153     /// value number, eliminating a copy.
00154     bool adjustCopiesBackFrom(const CoalescerPair &CP, MachineInstr *CopyMI);
00155 
00156     /// hasOtherReachingDefs - Return true if there are definitions of IntB
00157     /// other than BValNo val# that can reach uses of AValno val# of IntA.
00158     bool hasOtherReachingDefs(LiveInterval &IntA, LiveInterval &IntB,
00159                               VNInfo *AValNo, VNInfo *BValNo);
00160 
00161     /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy.
00162     /// If the source value number is defined by a commutable instruction and
00163     /// its other operand is coalesced to the copy dest register, see if we
00164     /// can transform the copy into a noop by commuting the definition.
00165     bool removeCopyByCommutingDef(const CoalescerPair &CP,MachineInstr *CopyMI);
00166 
00167     /// reMaterializeTrivialDef - If the source of a copy is defined by a
00168     /// trivial computation, replace the copy by rematerialize the definition.
00169     bool reMaterializeTrivialDef(CoalescerPair &CP, MachineInstr *CopyMI,
00170                                  bool &IsDefCopy);
00171 
00172     /// canJoinPhys - Return true if a physreg copy should be joined.
00173     bool canJoinPhys(const CoalescerPair &CP);
00174 
00175     /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
00176     /// update the subregister number if it is not zero. If DstReg is a
00177     /// physical register and the existing subregister number of the def / use
00178     /// being updated is not zero, make sure to set it to the correct physical
00179     /// subregister.
00180     void updateRegDefsUses(unsigned SrcReg, unsigned DstReg, unsigned SubIdx);
00181 
00182     /// eliminateUndefCopy - Handle copies of undef values.
00183     bool eliminateUndefCopy(MachineInstr *CopyMI, const CoalescerPair &CP);
00184 
00185   public:
00186     static char ID; // Class identification, replacement for typeinfo
00187     RegisterCoalescer() : MachineFunctionPass(ID) {
00188       initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
00189     }
00190 
00191     void getAnalysisUsage(AnalysisUsage &AU) const override;
00192 
00193     void releaseMemory() override;
00194 
00195     /// runOnMachineFunction - pass entry point
00196     bool runOnMachineFunction(MachineFunction&) override;
00197 
00198     /// print - Implement the dump method.
00199     void print(raw_ostream &O, const Module* = nullptr) const override;
00200   };
00201 } /// end anonymous namespace
00202 
00203 char &llvm::RegisterCoalescerID = RegisterCoalescer::ID;
00204 
00205 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
00206                       "Simple Register Coalescing", false, false)
00207 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
00208 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
00209 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
00210 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
00211 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
00212                     "Simple Register Coalescing", false, false)
00213 
00214 char RegisterCoalescer::ID = 0;
00215 
00216 static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI,
00217                         unsigned &Src, unsigned &Dst,
00218                         unsigned &SrcSub, unsigned &DstSub) {
00219   if (MI->isCopy()) {
00220     Dst = MI->getOperand(0).getReg();
00221     DstSub = MI->getOperand(0).getSubReg();
00222     Src = MI->getOperand(1).getReg();
00223     SrcSub = MI->getOperand(1).getSubReg();
00224   } else if (MI->isSubregToReg()) {
00225     Dst = MI->getOperand(0).getReg();
00226     DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
00227                                       MI->getOperand(3).getImm());
00228     Src = MI->getOperand(2).getReg();
00229     SrcSub = MI->getOperand(2).getSubReg();
00230   } else
00231     return false;
00232   return true;
00233 }
00234 
00235 // Return true if this block should be vacated by the coalescer to eliminate
00236 // branches. The important cases to handle in the coalescer are critical edges
00237 // split during phi elimination which contain only copies. Simple blocks that
00238 // contain non-branches should also be vacated, but this can be handled by an
00239 // earlier pass similar to early if-conversion.
00240 static bool isSplitEdge(const MachineBasicBlock *MBB) {
00241   if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
00242     return false;
00243 
00244   for (const auto &MI : *MBB) {
00245     if (!MI.isCopyLike() && !MI.isUnconditionalBranch())
00246       return false;
00247   }
00248   return true;
00249 }
00250 
00251 bool CoalescerPair::setRegisters(const MachineInstr *MI) {
00252   SrcReg = DstReg = 0;
00253   SrcIdx = DstIdx = 0;
00254   NewRC = nullptr;
00255   Flipped = CrossClass = false;
00256 
00257   unsigned Src, Dst, SrcSub, DstSub;
00258   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
00259     return false;
00260   Partial = SrcSub || DstSub;
00261 
00262   // If one register is a physreg, it must be Dst.
00263   if (TargetRegisterInfo::isPhysicalRegister(Src)) {
00264     if (TargetRegisterInfo::isPhysicalRegister(Dst))
00265       return false;
00266     std::swap(Src, Dst);
00267     std::swap(SrcSub, DstSub);
00268     Flipped = true;
00269   }
00270 
00271   const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
00272 
00273   if (TargetRegisterInfo::isPhysicalRegister(Dst)) {
00274     // Eliminate DstSub on a physreg.
00275     if (DstSub) {
00276       Dst = TRI.getSubReg(Dst, DstSub);
00277       if (!Dst) return false;
00278       DstSub = 0;
00279     }
00280 
00281     // Eliminate SrcSub by picking a corresponding Dst superregister.
00282     if (SrcSub) {
00283       Dst = TRI.getMatchingSuperReg(Dst, SrcSub, MRI.getRegClass(Src));
00284       if (!Dst) return false;
00285     } else if (!MRI.getRegClass(Src)->contains(Dst)) {
00286       return false;
00287     }
00288   } else {
00289     // Both registers are virtual.
00290     const TargetRegisterClass *SrcRC = MRI.getRegClass(Src);
00291     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
00292 
00293     // Both registers have subreg indices.
00294     if (SrcSub && DstSub) {
00295       // Copies between different sub-registers are never coalescable.
00296       if (Src == Dst && SrcSub != DstSub)
00297         return false;
00298 
00299       NewRC = TRI.getCommonSuperRegClass(SrcRC, SrcSub, DstRC, DstSub,
00300                                          SrcIdx, DstIdx);
00301       if (!NewRC)
00302         return false;
00303     } else if (DstSub) {
00304       // SrcReg will be merged with a sub-register of DstReg.
00305       SrcIdx = DstSub;
00306       NewRC = TRI.getMatchingSuperRegClass(DstRC, SrcRC, DstSub);
00307     } else if (SrcSub) {
00308       // DstReg will be merged with a sub-register of SrcReg.
00309       DstIdx = SrcSub;
00310       NewRC = TRI.getMatchingSuperRegClass(SrcRC, DstRC, SrcSub);
00311     } else {
00312       // This is a straight copy without sub-registers.
00313       NewRC = TRI.getCommonSubClass(DstRC, SrcRC);
00314     }
00315 
00316     // The combined constraint may be impossible to satisfy.
00317     if (!NewRC)
00318       return false;
00319 
00320     // Prefer SrcReg to be a sub-register of DstReg.
00321     // FIXME: Coalescer should support subregs symmetrically.
00322     if (DstIdx && !SrcIdx) {
00323       std::swap(Src, Dst);
00324       std::swap(SrcIdx, DstIdx);
00325       Flipped = !Flipped;
00326     }
00327 
00328     CrossClass = NewRC != DstRC || NewRC != SrcRC;
00329   }
00330   // Check our invariants
00331   assert(TargetRegisterInfo::isVirtualRegister(Src) && "Src must be virtual");
00332   assert(!(TargetRegisterInfo::isPhysicalRegister(Dst) && DstSub) &&
00333          "Cannot have a physical SubIdx");
00334   SrcReg = Src;
00335   DstReg = Dst;
00336   return true;
00337 }
00338 
00339 bool CoalescerPair::flip() {
00340   if (TargetRegisterInfo::isPhysicalRegister(DstReg))
00341     return false;
00342   std::swap(SrcReg, DstReg);
00343   std::swap(SrcIdx, DstIdx);
00344   Flipped = !Flipped;
00345   return true;
00346 }
00347 
00348 bool CoalescerPair::isCoalescable(const MachineInstr *MI) const {
00349   if (!MI)
00350     return false;
00351   unsigned Src, Dst, SrcSub, DstSub;
00352   if (!isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
00353     return false;
00354 
00355   // Find the virtual register that is SrcReg.
00356   if (Dst == SrcReg) {
00357     std::swap(Src, Dst);
00358     std::swap(SrcSub, DstSub);
00359   } else if (Src != SrcReg) {
00360     return false;
00361   }
00362 
00363   // Now check that Dst matches DstReg.
00364   if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
00365     if (!TargetRegisterInfo::isPhysicalRegister(Dst))
00366       return false;
00367     assert(!DstIdx && !SrcIdx && "Inconsistent CoalescerPair state.");
00368     // DstSub could be set for a physreg from INSERT_SUBREG.
00369     if (DstSub)
00370       Dst = TRI.getSubReg(Dst, DstSub);
00371     // Full copy of Src.
00372     if (!SrcSub)
00373       return DstReg == Dst;
00374     // This is a partial register copy. Check that the parts match.
00375     return TRI.getSubReg(DstReg, SrcSub) == Dst;
00376   } else {
00377     // DstReg is virtual.
00378     if (DstReg != Dst)
00379       return false;
00380     // Registers match, do the subregisters line up?
00381     return TRI.composeSubRegIndices(SrcIdx, SrcSub) ==
00382            TRI.composeSubRegIndices(DstIdx, DstSub);
00383   }
00384 }
00385 
00386 void RegisterCoalescer::getAnalysisUsage(AnalysisUsage &AU) const {
00387   AU.setPreservesCFG();
00388   AU.addRequired<AliasAnalysis>();
00389   AU.addRequired<LiveIntervals>();
00390   AU.addPreserved<LiveIntervals>();
00391   AU.addPreserved<SlotIndexes>();
00392   AU.addRequired<MachineLoopInfo>();
00393   AU.addPreserved<MachineLoopInfo>();
00394   AU.addPreservedID(MachineDominatorsID);
00395   MachineFunctionPass::getAnalysisUsage(AU);
00396 }
00397 
00398 void RegisterCoalescer::eliminateDeadDefs() {
00399   SmallVector<unsigned, 8> NewRegs;
00400   LiveRangeEdit(nullptr, NewRegs, *MF, *LIS,
00401                 nullptr, this).eliminateDeadDefs(DeadDefs);
00402 }
00403 
00404 // Callback from eliminateDeadDefs().
00405 void RegisterCoalescer::LRE_WillEraseInstruction(MachineInstr *MI) {
00406   // MI may be in WorkList. Make sure we don't visit it.
00407   ErasedInstrs.insert(MI);
00408 }
00409 
00410 /// adjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
00411 /// being the source and IntB being the dest, thus this defines a value number
00412 /// in IntB.  If the source value number (in IntA) is defined by a copy from B,
00413 /// see if we can merge these two pieces of B into a single value number,
00414 /// eliminating a copy.  For example:
00415 ///
00416 ///  A3 = B0
00417 ///    ...
00418 ///  B1 = A3      <- this copy
00419 ///
00420 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
00421 /// value number to be replaced with B0 (which simplifies the B liveinterval).
00422 ///
00423 /// This returns true if an interval was modified.
00424 ///
00425 bool RegisterCoalescer::adjustCopiesBackFrom(const CoalescerPair &CP,
00426                                              MachineInstr *CopyMI) {
00427   assert(!CP.isPartial() && "This doesn't work for partial copies.");
00428   assert(!CP.isPhys() && "This doesn't work for physreg copies.");
00429 
00430   LiveInterval &IntA =
00431     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
00432   LiveInterval &IntB =
00433     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
00434   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
00435 
00436   // BValNo is a value number in B that is defined by a copy from A.  'B1' in
00437   // the example above.
00438   LiveInterval::iterator BS = IntB.FindSegmentContaining(CopyIdx);
00439   if (BS == IntB.end()) return false;
00440   VNInfo *BValNo = BS->valno;
00441 
00442   // Get the location that B is defined at.  Two options: either this value has
00443   // an unknown definition point or it is defined at CopyIdx.  If unknown, we
00444   // can't process it.
00445   if (BValNo->def != CopyIdx) return false;
00446 
00447   // AValNo is the value number in A that defines the copy, A3 in the example.
00448   SlotIndex CopyUseIdx = CopyIdx.getRegSlot(true);
00449   LiveInterval::iterator AS = IntA.FindSegmentContaining(CopyUseIdx);
00450   // The live segment might not exist after fun with physreg coalescing.
00451   if (AS == IntA.end()) return false;
00452   VNInfo *AValNo = AS->valno;
00453 
00454   // If AValNo is defined as a copy from IntB, we can potentially process this.
00455   // Get the instruction that defines this value number.
00456   MachineInstr *ACopyMI = LIS->getInstructionFromIndex(AValNo->def);
00457   // Don't allow any partial copies, even if isCoalescable() allows them.
00458   if (!CP.isCoalescable(ACopyMI) || !ACopyMI->isFullCopy())
00459     return false;
00460 
00461   // Get the Segment in IntB that this value number starts with.
00462   LiveInterval::iterator ValS =
00463     IntB.FindSegmentContaining(AValNo->def.getPrevSlot());
00464   if (ValS == IntB.end())
00465     return false;
00466 
00467   // Make sure that the end of the live segment is inside the same block as
00468   // CopyMI.
00469   MachineInstr *ValSEndInst =
00470     LIS->getInstructionFromIndex(ValS->end.getPrevSlot());
00471   if (!ValSEndInst || ValSEndInst->getParent() != CopyMI->getParent())
00472     return false;
00473 
00474   // Okay, we now know that ValS ends in the same block that the CopyMI
00475   // live-range starts.  If there are no intervening live segments between them
00476   // in IntB, we can merge them.
00477   if (ValS+1 != BS) return false;
00478 
00479   DEBUG(dbgs() << "Extending: " << PrintReg(IntB.reg, TRI));
00480 
00481   SlotIndex FillerStart = ValS->end, FillerEnd = BS->start;
00482   // We are about to delete CopyMI, so need to remove it as the 'instruction
00483   // that defines this value #'. Update the valnum with the new defining
00484   // instruction #.
00485   BValNo->def = FillerStart;
00486 
00487   // Okay, we can merge them.  We need to insert a new liverange:
00488   // [ValS.end, BS.begin) of either value number, then we merge the
00489   // two value numbers.
00490   IntB.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo));
00491 
00492   // Okay, merge "B1" into the same value number as "B0".
00493   if (BValNo != ValS->valno)
00494     IntB.MergeValueNumberInto(BValNo, ValS->valno);
00495   DEBUG(dbgs() << "   result = " << IntB << '\n');
00496 
00497   // If the source instruction was killing the source register before the
00498   // merge, unset the isKill marker given the live range has been extended.
00499   int UIdx = ValSEndInst->findRegisterUseOperandIdx(IntB.reg, true);
00500   if (UIdx != -1) {
00501     ValSEndInst->getOperand(UIdx).setIsKill(false);
00502   }
00503 
00504   // Rewrite the copy. If the copy instruction was killing the destination
00505   // register before the merge, find the last use and trim the live range. That
00506   // will also add the isKill marker.
00507   CopyMI->substituteRegister(IntA.reg, IntB.reg, 0, *TRI);
00508   if (AS->end == CopyIdx)
00509     LIS->shrinkToUses(&IntA);
00510 
00511   ++numExtends;
00512   return true;
00513 }
00514 
00515 /// hasOtherReachingDefs - Return true if there are definitions of IntB
00516 /// other than BValNo val# that can reach uses of AValno val# of IntA.
00517 bool RegisterCoalescer::hasOtherReachingDefs(LiveInterval &IntA,
00518                                              LiveInterval &IntB,
00519                                              VNInfo *AValNo,
00520                                              VNInfo *BValNo) {
00521   // If AValNo has PHI kills, conservatively assume that IntB defs can reach
00522   // the PHI values.
00523   if (LIS->hasPHIKill(IntA, AValNo))
00524     return true;
00525 
00526   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
00527        AI != AE; ++AI) {
00528     if (AI->valno != AValNo) continue;
00529     LiveInterval::iterator BI =
00530       std::upper_bound(IntB.begin(), IntB.end(), AI->start);
00531     if (BI != IntB.begin())
00532       --BI;
00533     for (; BI != IntB.end() && AI->end >= BI->start; ++BI) {
00534       if (BI->valno == BValNo)
00535         continue;
00536       if (BI->start <= AI->start && BI->end > AI->start)
00537         return true;
00538       if (BI->start > AI->start && BI->start < AI->end)
00539         return true;
00540     }
00541   }
00542   return false;
00543 }
00544 
00545 /// removeCopyByCommutingDef - We found a non-trivially-coalescable copy with
00546 /// IntA being the source and IntB being the dest, thus this defines a value
00547 /// number in IntB.  If the source value number (in IntA) is defined by a
00548 /// commutable instruction and its other operand is coalesced to the copy dest
00549 /// register, see if we can transform the copy into a noop by commuting the
00550 /// definition. For example,
00551 ///
00552 ///  A3 = op A2 B0<kill>
00553 ///    ...
00554 ///  B1 = A3      <- this copy
00555 ///    ...
00556 ///     = op A3   <- more uses
00557 ///
00558 /// ==>
00559 ///
00560 ///  B2 = op B0 A2<kill>
00561 ///    ...
00562 ///  B1 = B2      <- now an identify copy
00563 ///    ...
00564 ///     = op B2   <- more uses
00565 ///
00566 /// This returns true if an interval was modified.
00567 ///
00568 bool RegisterCoalescer::removeCopyByCommutingDef(const CoalescerPair &CP,
00569                                                  MachineInstr *CopyMI) {
00570   assert (!CP.isPhys());
00571 
00572   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI).getRegSlot();
00573 
00574   LiveInterval &IntA =
00575     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
00576   LiveInterval &IntB =
00577     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
00578 
00579   // BValNo is a value number in B that is defined by a copy from A. 'B1' in
00580   // the example above.
00581   VNInfo *BValNo = IntB.getVNInfoAt(CopyIdx);
00582   if (!BValNo || BValNo->def != CopyIdx)
00583     return false;
00584 
00585   // AValNo is the value number in A that defines the copy, A3 in the example.
00586   VNInfo *AValNo = IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
00587   assert(AValNo && "COPY source not live");
00588   if (AValNo->isPHIDef() || AValNo->isUnused())
00589     return false;
00590   MachineInstr *DefMI = LIS->getInstructionFromIndex(AValNo->def);
00591   if (!DefMI)
00592     return false;
00593   if (!DefMI->isCommutable())
00594     return false;
00595   // If DefMI is a two-address instruction then commuting it will change the
00596   // destination register.
00597   int DefIdx = DefMI->findRegisterDefOperandIdx(IntA.reg);
00598   assert(DefIdx != -1);
00599   unsigned UseOpIdx;
00600   if (!DefMI->isRegTiedToUseOperand(DefIdx, &UseOpIdx))
00601     return false;
00602   unsigned Op1, Op2, NewDstIdx;
00603   if (!TII->findCommutedOpIndices(DefMI, Op1, Op2))
00604     return false;
00605   if (Op1 == UseOpIdx)
00606     NewDstIdx = Op2;
00607   else if (Op2 == UseOpIdx)
00608     NewDstIdx = Op1;
00609   else
00610     return false;
00611 
00612   MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
00613   unsigned NewReg = NewDstMO.getReg();
00614   if (NewReg != IntB.reg || !IntB.Query(AValNo->def).isKill())
00615     return false;
00616 
00617   // Make sure there are no other definitions of IntB that would reach the
00618   // uses which the new definition can reach.
00619   if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
00620     return false;
00621 
00622   // If some of the uses of IntA.reg is already coalesced away, return false.
00623   // It's not possible to determine whether it's safe to perform the coalescing.
00624   for (MachineOperand &MO : MRI->use_nodbg_operands(IntA.reg)) {
00625     MachineInstr *UseMI = MO.getParent();
00626     unsigned OpNo = &MO - &UseMI->getOperand(0);
00627     SlotIndex UseIdx = LIS->getInstructionIndex(UseMI);
00628     LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
00629     if (US == IntA.end() || US->valno != AValNo)
00630       continue;
00631     // If this use is tied to a def, we can't rewrite the register.
00632     if (UseMI->isRegTiedToDefOperand(OpNo))
00633       return false;
00634   }
00635 
00636   DEBUG(dbgs() << "\tremoveCopyByCommutingDef: " << AValNo->def << '\t'
00637                << *DefMI);
00638 
00639   // At this point we have decided that it is legal to do this
00640   // transformation.  Start by commuting the instruction.
00641   MachineBasicBlock *MBB = DefMI->getParent();
00642   MachineInstr *NewMI = TII->commuteInstruction(DefMI);
00643   if (!NewMI)
00644     return false;
00645   if (TargetRegisterInfo::isVirtualRegister(IntA.reg) &&
00646       TargetRegisterInfo::isVirtualRegister(IntB.reg) &&
00647       !MRI->constrainRegClass(IntB.reg, MRI->getRegClass(IntA.reg)))
00648     return false;
00649   if (NewMI != DefMI) {
00650     LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
00651     MachineBasicBlock::iterator Pos = DefMI;
00652     MBB->insert(Pos, NewMI);
00653     MBB->erase(DefMI);
00654   }
00655   unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
00656   NewMI->getOperand(OpIdx).setIsKill();
00657 
00658   // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
00659   // A = or A, B
00660   // ...
00661   // B = A
00662   // ...
00663   // C = A<kill>
00664   // ...
00665   //   = B
00666 
00667   // Update uses of IntA of the specific Val# with IntB.
00668   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(IntA.reg),
00669          UE = MRI->use_end(); UI != UE;) {
00670     MachineOperand &UseMO = *UI;
00671     MachineInstr *UseMI = UseMO.getParent();
00672     ++UI;
00673     if (UseMI->isDebugValue()) {
00674       // FIXME These don't have an instruction index.  Not clear we have enough
00675       // info to decide whether to do this replacement or not.  For now do it.
00676       UseMO.setReg(NewReg);
00677       continue;
00678     }
00679     SlotIndex UseIdx = LIS->getInstructionIndex(UseMI).getRegSlot(true);
00680     LiveInterval::iterator US = IntA.FindSegmentContaining(UseIdx);
00681     if (US == IntA.end() || US->valno != AValNo)
00682       continue;
00683     // Kill flags are no longer accurate. They are recomputed after RA.
00684     UseMO.setIsKill(false);
00685     if (TargetRegisterInfo::isPhysicalRegister(NewReg))
00686       UseMO.substPhysReg(NewReg, *TRI);
00687     else
00688       UseMO.setReg(NewReg);
00689     if (UseMI == CopyMI)
00690       continue;
00691     if (!UseMI->isCopy())
00692       continue;
00693     if (UseMI->getOperand(0).getReg() != IntB.reg ||
00694         UseMI->getOperand(0).getSubReg())
00695       continue;
00696 
00697     // This copy will become a noop. If it's defining a new val#, merge it into
00698     // BValNo.
00699     SlotIndex DefIdx = UseIdx.getRegSlot();
00700     VNInfo *DVNI = IntB.getVNInfoAt(DefIdx);
00701     if (!DVNI)
00702       continue;
00703     DEBUG(dbgs() << "\t\tnoop: " << DefIdx << '\t' << *UseMI);
00704     assert(DVNI->def == DefIdx);
00705     BValNo = IntB.MergeValueNumberInto(BValNo, DVNI);
00706     ErasedInstrs.insert(UseMI);
00707     LIS->RemoveMachineInstrFromMaps(UseMI);
00708     UseMI->eraseFromParent();
00709   }
00710 
00711   // Extend BValNo by merging in IntA live segments of AValNo. Val# definition
00712   // is updated.
00713   VNInfo *ValNo = BValNo;
00714   ValNo->def = AValNo->def;
00715   for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
00716        AI != AE; ++AI) {
00717     if (AI->valno != AValNo) continue;
00718     IntB.addSegment(LiveInterval::Segment(AI->start, AI->end, ValNo));
00719   }
00720   DEBUG(dbgs() << "\t\textended: " << IntB << '\n');
00721 
00722   IntA.removeValNo(AValNo);
00723   DEBUG(dbgs() << "\t\ttrimmed:  " << IntA << '\n');
00724   ++numCommutes;
00725   return true;
00726 }
00727 
00728 /// reMaterializeTrivialDef - If the source of a copy is defined by a trivial
00729 /// computation, replace the copy by rematerialize the definition.
00730 bool RegisterCoalescer::reMaterializeTrivialDef(CoalescerPair &CP,
00731                                                 MachineInstr *CopyMI,
00732                                                 bool &IsDefCopy) {
00733   IsDefCopy = false;
00734   unsigned SrcReg = CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg();
00735   unsigned SrcIdx = CP.isFlipped() ? CP.getDstIdx() : CP.getSrcIdx();
00736   unsigned DstReg = CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg();
00737   unsigned DstIdx = CP.isFlipped() ? CP.getSrcIdx() : CP.getDstIdx();
00738   if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
00739     return false;
00740 
00741   LiveInterval &SrcInt = LIS->getInterval(SrcReg);
00742   SlotIndex CopyIdx = LIS->getInstructionIndex(CopyMI);
00743   VNInfo *ValNo = SrcInt.Query(CopyIdx).valueIn();
00744   assert(ValNo && "CopyMI input register not live");
00745   if (ValNo->isPHIDef() || ValNo->isUnused())
00746     return false;
00747   MachineInstr *DefMI = LIS->getInstructionFromIndex(ValNo->def);
00748   if (!DefMI)
00749     return false;
00750   if (DefMI->isCopyLike()) {
00751     IsDefCopy = true;
00752     return false;
00753   }
00754   if (!TII->isAsCheapAsAMove(DefMI))
00755     return false;
00756   if (!TII->isTriviallyReMaterializable(DefMI, AA))
00757     return false;
00758   bool SawStore = false;
00759   if (!DefMI->isSafeToMove(TII, AA, SawStore))
00760     return false;
00761   const MCInstrDesc &MCID = DefMI->getDesc();
00762   if (MCID.getNumDefs() != 1)
00763     return false;
00764   // Only support subregister destinations when the def is read-undef.
00765   MachineOperand &DstOperand = CopyMI->getOperand(0);
00766   unsigned CopyDstReg = DstOperand.getReg();
00767   if (DstOperand.getSubReg() && !DstOperand.isUndef())
00768     return false;
00769 
00770   // If both SrcIdx and DstIdx are set, correct rematerialization would widen
00771   // the register substantially (beyond both source and dest size). This is bad
00772   // for performance since it can cascade through a function, introducing many
00773   // extra spills and fills (e.g. ARM can easily end up copying QQQQPR registers
00774   // around after a few subreg copies).
00775   if (SrcIdx && DstIdx)
00776     return false;
00777 
00778   const TargetRegisterClass *DefRC = TII->getRegClass(MCID, 0, TRI, *MF);
00779   if (!DefMI->isImplicitDef()) {
00780     if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
00781       unsigned NewDstReg = DstReg;
00782 
00783       unsigned NewDstIdx = TRI->composeSubRegIndices(CP.getSrcIdx(),
00784                                               DefMI->getOperand(0).getSubReg());
00785       if (NewDstIdx)
00786         NewDstReg = TRI->getSubReg(DstReg, NewDstIdx);
00787 
00788       // Finally, make sure that the physical subregister that will be
00789       // constructed later is permitted for the instruction.
00790       if (!DefRC->contains(NewDstReg))
00791         return false;
00792     } else {
00793       // Theoretically, some stack frame reference could exist. Just make sure
00794       // it hasn't actually happened.
00795       assert(TargetRegisterInfo::isVirtualRegister(DstReg) &&
00796              "Only expect to deal with virtual or physical registers");
00797     }
00798   }
00799 
00800   MachineBasicBlock *MBB = CopyMI->getParent();
00801   MachineBasicBlock::iterator MII =
00802     std::next(MachineBasicBlock::iterator(CopyMI));
00803   TII->reMaterialize(*MBB, MII, DstReg, SrcIdx, DefMI, *TRI);
00804   MachineInstr *NewMI = std::prev(MII);
00805 
00806   LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
00807   CopyMI->eraseFromParent();
00808   ErasedInstrs.insert(CopyMI);
00809 
00810   // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86).
00811   // We need to remember these so we can add intervals once we insert
00812   // NewMI into SlotIndexes.
00813   SmallVector<unsigned, 4> NewMIImplDefs;
00814   for (unsigned i = NewMI->getDesc().getNumOperands(),
00815          e = NewMI->getNumOperands(); i != e; ++i) {
00816     MachineOperand &MO = NewMI->getOperand(i);
00817     if (MO.isReg()) {
00818       assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
00819              TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
00820       NewMIImplDefs.push_back(MO.getReg());
00821     }
00822   }
00823 
00824   if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
00825     const TargetRegisterClass *NewRC = CP.getNewRC();
00826     unsigned NewIdx = NewMI->getOperand(0).getSubReg();
00827 
00828     if (NewIdx)
00829       NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx);
00830     else
00831       NewRC = TRI->getCommonSubClass(NewRC, DefRC);
00832 
00833     assert(NewRC && "subreg chosen for remat incompatible with instruction");
00834     MRI->setRegClass(DstReg, NewRC);
00835 
00836     updateRegDefsUses(DstReg, DstReg, DstIdx);
00837     NewMI->getOperand(0).setSubReg(NewIdx);
00838   } else if (NewMI->getOperand(0).getReg() != CopyDstReg) {
00839     // The New instruction may be defining a sub-register of what's actually
00840     // been asked for. If so it must implicitly define the whole thing.
00841     assert(TargetRegisterInfo::isPhysicalRegister(DstReg) &&
00842            "Only expect virtual or physical registers in remat");
00843     NewMI->getOperand(0).setIsDead(true);
00844     NewMI->addOperand(MachineOperand::CreateReg(CopyDstReg,
00845                                                 true  /*IsDef*/,
00846                                                 true  /*IsImp*/,
00847                                                 false /*IsKill*/));
00848     // Record small dead def live-ranges for all the subregisters
00849     // of the destination register.
00850     // Otherwise, variables that live through may miss some
00851     // interferences, thus creating invalid allocation.
00852     // E.g., i386 code:
00853     // vreg1 = somedef ; vreg1 GR8
00854     // vreg2 = remat ; vreg2 GR32
00855     // CL = COPY vreg2.sub_8bit
00856     // = somedef vreg1 ; vreg1 GR8
00857     // =>
00858     // vreg1 = somedef ; vreg1 GR8
00859     // ECX<def, dead> = remat ; CL<imp-def>
00860     // = somedef vreg1 ; vreg1 GR8
00861     // vreg1 will see the inteferences with CL but not with CH since
00862     // no live-ranges would have been created for ECX.
00863     // Fix that!
00864     SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
00865     for (MCRegUnitIterator Units(NewMI->getOperand(0).getReg(), TRI);
00866          Units.isValid(); ++Units)
00867       if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
00868         LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
00869   }
00870 
00871   if (NewMI->getOperand(0).getSubReg())
00872     NewMI->getOperand(0).setIsUndef();
00873 
00874   // CopyMI may have implicit operands, transfer them over to the newly
00875   // rematerialized instruction. And update implicit def interval valnos.
00876   for (unsigned i = CopyMI->getDesc().getNumOperands(),
00877          e = CopyMI->getNumOperands(); i != e; ++i) {
00878     MachineOperand &MO = CopyMI->getOperand(i);
00879     if (MO.isReg()) {
00880       assert(MO.isImplicit() && "No explicit operands after implict operands.");
00881       // Discard VReg implicit defs.
00882       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
00883         NewMI->addOperand(MO);
00884       }
00885     }
00886   }
00887 
00888   SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
00889   for (unsigned i = 0, e = NewMIImplDefs.size(); i != e; ++i) {
00890     unsigned Reg = NewMIImplDefs[i];
00891     for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units)
00892       if (LiveRange *LR = LIS->getCachedRegUnit(*Units))
00893         LR->createDeadDef(NewMIIdx.getRegSlot(), LIS->getVNInfoAllocator());
00894   }
00895 
00896   DEBUG(dbgs() << "Remat: " << *NewMI);
00897   ++NumReMats;
00898 
00899   // The source interval can become smaller because we removed a use.
00900   LIS->shrinkToUses(&SrcInt, &DeadDefs);
00901   if (!DeadDefs.empty())
00902     eliminateDeadDefs();
00903 
00904   return true;
00905 }
00906 
00907 /// eliminateUndefCopy - ProcessImpicitDefs may leave some copies of <undef>
00908 /// values, it only removes local variables. When we have a copy like:
00909 ///
00910 ///   %vreg1 = COPY %vreg2<undef>
00911 ///
00912 /// We delete the copy and remove the corresponding value number from %vreg1.
00913 /// Any uses of that value number are marked as <undef>.
00914 bool RegisterCoalescer::eliminateUndefCopy(MachineInstr *CopyMI,
00915                                            const CoalescerPair &CP) {
00916   SlotIndex Idx = LIS->getInstructionIndex(CopyMI);
00917   LiveInterval *SrcInt = &LIS->getInterval(CP.getSrcReg());
00918   if (SrcInt->liveAt(Idx))
00919     return false;
00920   LiveInterval *DstInt = &LIS->getInterval(CP.getDstReg());
00921   if (DstInt->liveAt(Idx))
00922     return false;
00923 
00924   // No intervals are live-in to CopyMI - it is undef.
00925   if (CP.isFlipped())
00926     DstInt = SrcInt;
00927   SrcInt = nullptr;
00928 
00929   VNInfo *DeadVNI = DstInt->getVNInfoAt(Idx.getRegSlot());
00930   assert(DeadVNI && "No value defined in DstInt");
00931   DstInt->removeValNo(DeadVNI);
00932 
00933   // Find new undef uses.
00934   for (MachineOperand &MO : MRI->reg_nodbg_operands(DstInt->reg)) {
00935     if (MO.isDef() || MO.isUndef())
00936       continue;
00937     MachineInstr *MI = MO.getParent();
00938     SlotIndex Idx = LIS->getInstructionIndex(MI);
00939     if (DstInt->liveAt(Idx))
00940       continue;
00941     MO.setIsUndef(true);
00942     DEBUG(dbgs() << "\tnew undef: " << Idx << '\t' << *MI);
00943   }
00944   return true;
00945 }
00946 
00947 /// updateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
00948 /// update the subregister number if it is not zero. If DstReg is a
00949 /// physical register and the existing subregister number of the def / use
00950 /// being updated is not zero, make sure to set it to the correct physical
00951 /// subregister.
00952 void RegisterCoalescer::updateRegDefsUses(unsigned SrcReg,
00953                                           unsigned DstReg,
00954                                           unsigned SubIdx) {
00955   bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
00956   LiveInterval *DstInt = DstIsPhys ? nullptr : &LIS->getInterval(DstReg);
00957 
00958   SmallPtrSet<MachineInstr*, 8> Visited;
00959   for (MachineRegisterInfo::reg_instr_iterator
00960        I = MRI->reg_instr_begin(SrcReg), E = MRI->reg_instr_end();
00961        I != E; ) {
00962     MachineInstr *UseMI = &*(I++);
00963 
00964     // Each instruction can only be rewritten once because sub-register
00965     // composition is not always idempotent. When SrcReg != DstReg, rewriting
00966     // the UseMI operands removes them from the SrcReg use-def chain, but when
00967     // SrcReg is DstReg we could encounter UseMI twice if it has multiple
00968     // operands mentioning the virtual register.
00969     if (SrcReg == DstReg && !Visited.insert(UseMI))
00970       continue;
00971 
00972     SmallVector<unsigned,8> Ops;
00973     bool Reads, Writes;
00974     std::tie(Reads, Writes) = UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
00975 
00976     // If SrcReg wasn't read, it may still be the case that DstReg is live-in
00977     // because SrcReg is a sub-register.
00978     if (DstInt && !Reads && SubIdx)
00979       Reads = DstInt->liveAt(LIS->getInstructionIndex(UseMI));
00980 
00981     // Replace SrcReg with DstReg in all UseMI operands.
00982     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
00983       MachineOperand &MO = UseMI->getOperand(Ops[i]);
00984 
00985       // Adjust <undef> flags in case of sub-register joins. We don't want to
00986       // turn a full def into a read-modify-write sub-register def and vice
00987       // versa.
00988       if (SubIdx && MO.isDef())
00989         MO.setIsUndef(!Reads);
00990 
00991       if (DstIsPhys)
00992         MO.substPhysReg(DstReg, *TRI);
00993       else
00994         MO.substVirtReg(DstReg, SubIdx, *TRI);
00995     }
00996 
00997     DEBUG({
00998         dbgs() << "\t\tupdated: ";
00999         if (!UseMI->isDebugValue())
01000           dbgs() << LIS->getInstructionIndex(UseMI) << "\t";
01001         dbgs() << *UseMI;
01002       });
01003   }
01004 }
01005 
01006 /// canJoinPhys - Return true if a copy involving a physreg should be joined.
01007 bool RegisterCoalescer::canJoinPhys(const CoalescerPair &CP) {
01008   /// Always join simple intervals that are defined by a single copy from a
01009   /// reserved register. This doesn't increase register pressure, so it is
01010   /// always beneficial.
01011   if (!MRI->isReserved(CP.getDstReg())) {
01012     DEBUG(dbgs() << "\tCan only merge into reserved registers.\n");
01013     return false;
01014   }
01015 
01016   LiveInterval &JoinVInt = LIS->getInterval(CP.getSrcReg());
01017   if (CP.isFlipped() && JoinVInt.containsOneValue())
01018     return true;
01019 
01020   DEBUG(dbgs() << "\tCannot join defs into reserved register.\n");
01021   return false;
01022 }
01023 
01024 /// joinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
01025 /// which are the src/dst of the copy instruction CopyMI.  This returns true
01026 /// if the copy was successfully coalesced away. If it is not currently
01027 /// possible to coalesce this interval, but it may be possible if other
01028 /// things get coalesced, then it returns true by reference in 'Again'.
01029 bool RegisterCoalescer::joinCopy(MachineInstr *CopyMI, bool &Again) {
01030 
01031   Again = false;
01032   DEBUG(dbgs() << LIS->getInstructionIndex(CopyMI) << '\t' << *CopyMI);
01033 
01034   CoalescerPair CP(*TRI);
01035   if (!CP.setRegisters(CopyMI)) {
01036     DEBUG(dbgs() << "\tNot coalescable.\n");
01037     return false;
01038   }
01039 
01040   if (CP.getNewRC()) {
01041     auto SrcRC = MRI->getRegClass(CP.getSrcReg());
01042     auto DstRC = MRI->getRegClass(CP.getDstReg());
01043     unsigned SrcIdx = CP.getSrcIdx();
01044     unsigned DstIdx = CP.getDstIdx();
01045     if (CP.isFlipped()) {
01046       std::swap(SrcIdx, DstIdx);
01047       std::swap(SrcRC, DstRC);
01048     }
01049     if (!TRI->shouldCoalesce(CopyMI, SrcRC, SrcIdx, DstRC, DstIdx,
01050                             CP.getNewRC())) {
01051       DEBUG(dbgs() << "\tSubtarget bailed on coalescing.\n");
01052       return false;
01053     }
01054   }
01055 
01056   // Dead code elimination. This really should be handled by MachineDCE, but
01057   // sometimes dead copies slip through, and we can't generate invalid live
01058   // ranges.
01059   if (!CP.isPhys() && CopyMI->allDefsAreDead()) {
01060     DEBUG(dbgs() << "\tCopy is dead.\n");
01061     DeadDefs.push_back(CopyMI);
01062     eliminateDeadDefs();
01063     return true;
01064   }
01065 
01066   // Eliminate undefs.
01067   if (!CP.isPhys() && eliminateUndefCopy(CopyMI, CP)) {
01068     DEBUG(dbgs() << "\tEliminated copy of <undef> value.\n");
01069     LIS->RemoveMachineInstrFromMaps(CopyMI);
01070     CopyMI->eraseFromParent();
01071     return false;  // Not coalescable.
01072   }
01073 
01074   // Coalesced copies are normally removed immediately, but transformations
01075   // like removeCopyByCommutingDef() can inadvertently create identity copies.
01076   // When that happens, just join the values and remove the copy.
01077   if (CP.getSrcReg() == CP.getDstReg()) {
01078     LiveInterval &LI = LIS->getInterval(CP.getSrcReg());
01079     DEBUG(dbgs() << "\tCopy already coalesced: " << LI << '\n');
01080     LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(CopyMI));
01081     if (VNInfo *DefVNI = LRQ.valueDefined()) {
01082       VNInfo *ReadVNI = LRQ.valueIn();
01083       assert(ReadVNI && "No value before copy and no <undef> flag.");
01084       assert(ReadVNI != DefVNI && "Cannot read and define the same value.");
01085       LI.MergeValueNumberInto(DefVNI, ReadVNI);
01086       DEBUG(dbgs() << "\tMerged values:          " << LI << '\n');
01087     }
01088     LIS->RemoveMachineInstrFromMaps(CopyMI);
01089     CopyMI->eraseFromParent();
01090     return true;
01091   }
01092 
01093   // Enforce policies.
01094   if (CP.isPhys()) {
01095     DEBUG(dbgs() << "\tConsidering merging " << PrintReg(CP.getSrcReg(), TRI)
01096                  << " with " << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx())
01097                  << '\n');
01098     if (!canJoinPhys(CP)) {
01099       // Before giving up coalescing, if definition of source is defined by
01100       // trivial computation, try rematerializing it.
01101       bool IsDefCopy;
01102       if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
01103         return true;
01104       if (IsDefCopy)
01105         Again = true;  // May be possible to coalesce later.
01106       return false;
01107     }
01108   } else {
01109     DEBUG({
01110       dbgs() << "\tConsidering merging to " << CP.getNewRC()->getName()
01111              << " with ";
01112       if (CP.getDstIdx() && CP.getSrcIdx())
01113         dbgs() << PrintReg(CP.getDstReg()) << " in "
01114                << TRI->getSubRegIndexName(CP.getDstIdx()) << " and "
01115                << PrintReg(CP.getSrcReg()) << " in "
01116                << TRI->getSubRegIndexName(CP.getSrcIdx()) << '\n';
01117       else
01118         dbgs() << PrintReg(CP.getSrcReg(), TRI) << " in "
01119                << PrintReg(CP.getDstReg(), TRI, CP.getSrcIdx()) << '\n';
01120     });
01121 
01122     // When possible, let DstReg be the larger interval.
01123     if (!CP.isPartial() && LIS->getInterval(CP.getSrcReg()).size() >
01124                            LIS->getInterval(CP.getDstReg()).size())
01125       CP.flip();
01126   }
01127 
01128   // Okay, attempt to join these two intervals.  On failure, this returns false.
01129   // Otherwise, if one of the intervals being joined is a physreg, this method
01130   // always canonicalizes DstInt to be it.  The output "SrcInt" will not have
01131   // been modified, so we can use this information below to update aliases.
01132   if (!joinIntervals(CP)) {
01133     // Coalescing failed.
01134 
01135     // If definition of source is defined by trivial computation, try
01136     // rematerializing it.
01137     bool IsDefCopy;
01138     if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
01139       return true;
01140 
01141     // If we can eliminate the copy without merging the live segments, do so
01142     // now.
01143     if (!CP.isPartial() && !CP.isPhys()) {
01144       if (adjustCopiesBackFrom(CP, CopyMI) ||
01145           removeCopyByCommutingDef(CP, CopyMI)) {
01146         LIS->RemoveMachineInstrFromMaps(CopyMI);
01147         CopyMI->eraseFromParent();
01148         DEBUG(dbgs() << "\tTrivial!\n");
01149         return true;
01150       }
01151     }
01152 
01153     // Otherwise, we are unable to join the intervals.
01154     DEBUG(dbgs() << "\tInterference!\n");
01155     Again = true;  // May be possible to coalesce later.
01156     return false;
01157   }
01158 
01159   // Coalescing to a virtual register that is of a sub-register class of the
01160   // other. Make sure the resulting register is set to the right register class.
01161   if (CP.isCrossClass()) {
01162     ++numCrossRCs;
01163     MRI->setRegClass(CP.getDstReg(), CP.getNewRC());
01164   }
01165 
01166   // Removing sub-register copies can ease the register class constraints.
01167   // Make sure we attempt to inflate the register class of DstReg.
01168   if (!CP.isPhys() && RegClassInfo.isProperSubClass(CP.getNewRC()))
01169     InflateRegs.push_back(CP.getDstReg());
01170 
01171   // CopyMI has been erased by joinIntervals at this point. Remove it from
01172   // ErasedInstrs since copyCoalesceWorkList() won't add a successful join back
01173   // to the work list. This keeps ErasedInstrs from growing needlessly.
01174   ErasedInstrs.erase(CopyMI);
01175 
01176   // Rewrite all SrcReg operands to DstReg.
01177   // Also update DstReg operands to include DstIdx if it is set.
01178   if (CP.getDstIdx())
01179     updateRegDefsUses(CP.getDstReg(), CP.getDstReg(), CP.getDstIdx());
01180   updateRegDefsUses(CP.getSrcReg(), CP.getDstReg(), CP.getSrcIdx());
01181 
01182   // SrcReg is guaranteed to be the register whose live interval that is
01183   // being merged.
01184   LIS->removeInterval(CP.getSrcReg());
01185 
01186   // Update regalloc hint.
01187   TRI->UpdateRegAllocHint(CP.getSrcReg(), CP.getDstReg(), *MF);
01188 
01189   DEBUG({
01190     dbgs() << "\tJoined. Result = ";
01191     if (CP.isPhys())
01192       dbgs() << PrintReg(CP.getDstReg(), TRI);
01193     else
01194       dbgs() << LIS->getInterval(CP.getDstReg());
01195     dbgs() << '\n';
01196   });
01197 
01198   ++numJoins;
01199   return true;
01200 }
01201 
01202 /// Attempt joining with a reserved physreg.
01203 bool RegisterCoalescer::joinReservedPhysReg(CoalescerPair &CP) {
01204   assert(CP.isPhys() && "Must be a physreg copy");
01205   assert(MRI->isReserved(CP.getDstReg()) && "Not a reserved register");
01206   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
01207   DEBUG(dbgs() << "\t\tRHS = " << RHS << '\n');
01208 
01209   assert(CP.isFlipped() && RHS.containsOneValue() &&
01210          "Invalid join with reserved register");
01211 
01212   // Optimization for reserved registers like ESP. We can only merge with a
01213   // reserved physreg if RHS has a single value that is a copy of CP.DstReg().
01214   // The live range of the reserved register will look like a set of dead defs
01215   // - we don't properly track the live range of reserved registers.
01216 
01217   // Deny any overlapping intervals.  This depends on all the reserved
01218   // register live ranges to look like dead defs.
01219   for (MCRegUnitIterator UI(CP.getDstReg(), TRI); UI.isValid(); ++UI)
01220     if (RHS.overlaps(LIS->getRegUnit(*UI))) {
01221       DEBUG(dbgs() << "\t\tInterference: " << PrintRegUnit(*UI, TRI) << '\n');
01222       return false;
01223     }
01224 
01225   // Skip any value computations, we are not adding new values to the
01226   // reserved register.  Also skip merging the live ranges, the reserved
01227   // register live range doesn't need to be accurate as long as all the
01228   // defs are there.
01229 
01230   // Delete the identity copy.
01231   MachineInstr *CopyMI = MRI->getVRegDef(RHS.reg);
01232   LIS->RemoveMachineInstrFromMaps(CopyMI);
01233   CopyMI->eraseFromParent();
01234 
01235   // We don't track kills for reserved registers.
01236   MRI->clearKillFlags(CP.getSrcReg());
01237 
01238   return true;
01239 }
01240 
01241 //===----------------------------------------------------------------------===//
01242 //                 Interference checking and interval joining
01243 //===----------------------------------------------------------------------===//
01244 //
01245 // In the easiest case, the two live ranges being joined are disjoint, and
01246 // there is no interference to consider. It is quite common, though, to have
01247 // overlapping live ranges, and we need to check if the interference can be
01248 // resolved.
01249 //
01250 // The live range of a single SSA value forms a sub-tree of the dominator tree.
01251 // This means that two SSA values overlap if and only if the def of one value
01252 // is contained in the live range of the other value. As a special case, the
01253 // overlapping values can be defined at the same index.
01254 //
01255 // The interference from an overlapping def can be resolved in these cases:
01256 //
01257 // 1. Coalescable copies. The value is defined by a copy that would become an
01258 //    identity copy after joining SrcReg and DstReg. The copy instruction will
01259 //    be removed, and the value will be merged with the source value.
01260 //
01261 //    There can be several copies back and forth, causing many values to be
01262 //    merged into one. We compute a list of ultimate values in the joined live
01263 //    range as well as a mappings from the old value numbers.
01264 //
01265 // 2. IMPLICIT_DEF. This instruction is only inserted to ensure all PHI
01266 //    predecessors have a live out value. It doesn't cause real interference,
01267 //    and can be merged into the value it overlaps. Like a coalescable copy, it
01268 //    can be erased after joining.
01269 //
01270 // 3. Copy of external value. The overlapping def may be a copy of a value that
01271 //    is already in the other register. This is like a coalescable copy, but
01272 //    the live range of the source register must be trimmed after erasing the
01273 //    copy instruction:
01274 //
01275 //      %src = COPY %ext
01276 //      %dst = COPY %ext  <-- Remove this COPY, trim the live range of %ext.
01277 //
01278 // 4. Clobbering undefined lanes. Vector registers are sometimes built by
01279 //    defining one lane at a time:
01280 //
01281 //      %dst:ssub0<def,read-undef> = FOO
01282 //      %src = BAR
01283 //      %dst:ssub1<def> = COPY %src
01284 //
01285 //    The live range of %src overlaps the %dst value defined by FOO, but
01286 //    merging %src into %dst:ssub1 is only going to clobber the ssub1 lane
01287 //    which was undef anyway.
01288 //
01289 //    The value mapping is more complicated in this case. The final live range
01290 //    will have different value numbers for both FOO and BAR, but there is no
01291 //    simple mapping from old to new values. It may even be necessary to add
01292 //    new PHI values.
01293 //
01294 // 5. Clobbering dead lanes. A def may clobber a lane of a vector register that
01295 //    is live, but never read. This can happen because we don't compute
01296 //    individual live ranges per lane.
01297 //
01298 //      %dst<def> = FOO
01299 //      %src = BAR
01300 //      %dst:ssub1<def> = COPY %src
01301 //
01302 //    This kind of interference is only resolved locally. If the clobbered
01303 //    lane value escapes the block, the join is aborted.
01304 
01305 namespace {
01306 /// Track information about values in a single virtual register about to be
01307 /// joined. Objects of this class are always created in pairs - one for each
01308 /// side of the CoalescerPair.
01309 class JoinVals {
01310   LiveInterval &LI;
01311 
01312   // Location of this register in the final joined register.
01313   // Either CP.DstIdx or CP.SrcIdx.
01314   unsigned SubIdx;
01315 
01316   // Values that will be present in the final live range.
01317   SmallVectorImpl<VNInfo*> &NewVNInfo;
01318 
01319   const CoalescerPair &CP;
01320   LiveIntervals *LIS;
01321   SlotIndexes *Indexes;
01322   const TargetRegisterInfo *TRI;
01323 
01324   // Value number assignments. Maps value numbers in LI to entries in NewVNInfo.
01325   // This is suitable for passing to LiveInterval::join().
01326   SmallVector<int, 8> Assignments;
01327 
01328   // Conflict resolution for overlapping values.
01329   enum ConflictResolution {
01330     // No overlap, simply keep this value.
01331     CR_Keep,
01332 
01333     // Merge this value into OtherVNI and erase the defining instruction.
01334     // Used for IMPLICIT_DEF, coalescable copies, and copies from external
01335     // values.
01336     CR_Erase,
01337 
01338     // Merge this value into OtherVNI but keep the defining instruction.
01339     // This is for the special case where OtherVNI is defined by the same
01340     // instruction.
01341     CR_Merge,
01342 
01343     // Keep this value, and have it replace OtherVNI where possible. This
01344     // complicates value mapping since OtherVNI maps to two different values
01345     // before and after this def.
01346     // Used when clobbering undefined or dead lanes.
01347     CR_Replace,
01348 
01349     // Unresolved conflict. Visit later when all values have been mapped.
01350     CR_Unresolved,
01351 
01352     // Unresolvable conflict. Abort the join.
01353     CR_Impossible
01354   };
01355 
01356   // Per-value info for LI. The lane bit masks are all relative to the final
01357   // joined register, so they can be compared directly between SrcReg and
01358   // DstReg.
01359   struct Val {
01360     ConflictResolution Resolution;
01361 
01362     // Lanes written by this def, 0 for unanalyzed values.
01363     unsigned WriteLanes;
01364 
01365     // Lanes with defined values in this register. Other lanes are undef and
01366     // safe to clobber.
01367     unsigned ValidLanes;
01368 
01369     // Value in LI being redefined by this def.
01370     VNInfo *RedefVNI;
01371 
01372     // Value in the other live range that overlaps this def, if any.
01373     VNInfo *OtherVNI;
01374 
01375     // Is this value an IMPLICIT_DEF that can be erased?
01376     //
01377     // IMPLICIT_DEF values should only exist at the end of a basic block that
01378     // is a predecessor to a phi-value. These IMPLICIT_DEF instructions can be
01379     // safely erased if they are overlapping a live value in the other live
01380     // interval.
01381     //
01382     // Weird control flow graphs and incomplete PHI handling in
01383     // ProcessImplicitDefs can very rarely create IMPLICIT_DEF values with
01384     // longer live ranges. Such IMPLICIT_DEF values should be treated like
01385     // normal values.
01386     bool ErasableImplicitDef;
01387 
01388     // True when the live range of this value will be pruned because of an
01389     // overlapping CR_Replace value in the other live range.
01390     bool Pruned;
01391 
01392     // True once Pruned above has been computed.
01393     bool PrunedComputed;
01394 
01395     Val() : Resolution(CR_Keep), WriteLanes(0), ValidLanes(0),
01396             RedefVNI(nullptr), OtherVNI(nullptr), ErasableImplicitDef(false),
01397             Pruned(false), PrunedComputed(false) {}
01398 
01399     bool isAnalyzed() const { return WriteLanes != 0; }
01400   };
01401 
01402   // One entry per value number in LI.
01403   SmallVector<Val, 8> Vals;
01404 
01405   unsigned computeWriteLanes(const MachineInstr *DefMI, bool &Redef);
01406   VNInfo *stripCopies(VNInfo *VNI);
01407   ConflictResolution analyzeValue(unsigned ValNo, JoinVals &Other);
01408   void computeAssignment(unsigned ValNo, JoinVals &Other);
01409   bool taintExtent(unsigned, unsigned, JoinVals&,
01410                    SmallVectorImpl<std::pair<SlotIndex, unsigned> >&);
01411   bool usesLanes(MachineInstr *MI, unsigned, unsigned, unsigned);
01412   bool isPrunedValue(unsigned ValNo, JoinVals &Other);
01413 
01414 public:
01415   JoinVals(LiveInterval &li, unsigned subIdx,
01416            SmallVectorImpl<VNInfo*> &newVNInfo,
01417            const CoalescerPair &cp,
01418            LiveIntervals *lis,
01419            const TargetRegisterInfo *tri)
01420     : LI(li), SubIdx(subIdx), NewVNInfo(newVNInfo), CP(cp), LIS(lis),
01421       Indexes(LIS->getSlotIndexes()), TRI(tri),
01422       Assignments(LI.getNumValNums(), -1), Vals(LI.getNumValNums())
01423   {}
01424 
01425   /// Analyze defs in LI and compute a value mapping in NewVNInfo.
01426   /// Returns false if any conflicts were impossible to resolve.
01427   bool mapValues(JoinVals &Other);
01428 
01429   /// Try to resolve conflicts that require all values to be mapped.
01430   /// Returns false if any conflicts were impossible to resolve.
01431   bool resolveConflicts(JoinVals &Other);
01432 
01433   /// Prune the live range of values in Other.LI where they would conflict with
01434   /// CR_Replace values in LI. Collect end points for restoring the live range
01435   /// after joining.
01436   void pruneValues(JoinVals &Other, SmallVectorImpl<SlotIndex> &EndPoints);
01437 
01438   /// Erase any machine instructions that have been coalesced away.
01439   /// Add erased instructions to ErasedInstrs.
01440   /// Add foreign virtual registers to ShrinkRegs if their live range ended at
01441   /// the erased instrs.
01442   void eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
01443                    SmallVectorImpl<unsigned> &ShrinkRegs);
01444 
01445   /// Get the value assignments suitable for passing to LiveInterval::join.
01446   const int *getAssignments() const { return Assignments.data(); }
01447 };
01448 } // end anonymous namespace
01449 
01450 /// Compute the bitmask of lanes actually written by DefMI.
01451 /// Set Redef if there are any partial register definitions that depend on the
01452 /// previous value of the register.
01453 unsigned JoinVals::computeWriteLanes(const MachineInstr *DefMI, bool &Redef) {
01454   unsigned L = 0;
01455   for (ConstMIOperands MO(DefMI); MO.isValid(); ++MO) {
01456     if (!MO->isReg() || MO->getReg() != LI.reg || !MO->isDef())
01457       continue;
01458     L |= TRI->getSubRegIndexLaneMask(
01459            TRI->composeSubRegIndices(SubIdx, MO->getSubReg()));
01460     if (MO->readsReg())
01461       Redef = true;
01462   }
01463   return L;
01464 }
01465 
01466 /// Find the ultimate value that VNI was copied from.
01467 VNInfo *JoinVals::stripCopies(VNInfo *VNI) {
01468   while (!VNI->isPHIDef()) {
01469     MachineInstr *MI = Indexes->getInstructionFromIndex(VNI->def);
01470     assert(MI && "No defining instruction");
01471     if (!MI->isFullCopy())
01472       break;
01473     unsigned Reg = MI->getOperand(1).getReg();
01474     if (!TargetRegisterInfo::isVirtualRegister(Reg))
01475       break;
01476     LiveQueryResult LRQ = LIS->getInterval(Reg).Query(VNI->def);
01477     if (!LRQ.valueIn())
01478       break;
01479     VNI = LRQ.valueIn();
01480   }
01481   return VNI;
01482 }
01483 
01484 /// Analyze ValNo in this live range, and set all fields of Vals[ValNo].
01485 /// Return a conflict resolution when possible, but leave the hard cases as
01486 /// CR_Unresolved.
01487 /// Recursively calls computeAssignment() on this and Other, guaranteeing that
01488 /// both OtherVNI and RedefVNI have been analyzed and mapped before returning.
01489 /// The recursion always goes upwards in the dominator tree, making loops
01490 /// impossible.
01491 JoinVals::ConflictResolution
01492 JoinVals::analyzeValue(unsigned ValNo, JoinVals &Other) {
01493   Val &V = Vals[ValNo];
01494   assert(!V.isAnalyzed() && "Value has already been analyzed!");
01495   VNInfo *VNI = LI.getValNumInfo(ValNo);
01496   if (VNI->isUnused()) {
01497     V.WriteLanes = ~0u;
01498     return CR_Keep;
01499   }
01500 
01501   // Get the instruction defining this value, compute the lanes written.
01502   const MachineInstr *DefMI = nullptr;
01503   if (VNI->isPHIDef()) {
01504     // Conservatively assume that all lanes in a PHI are valid.
01505     V.ValidLanes = V.WriteLanes = TRI->getSubRegIndexLaneMask(SubIdx);
01506   } else {
01507     DefMI = Indexes->getInstructionFromIndex(VNI->def);
01508     bool Redef = false;
01509     V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
01510 
01511     // If this is a read-modify-write instruction, there may be more valid
01512     // lanes than the ones written by this instruction.
01513     // This only covers partial redef operands. DefMI may have normal use
01514     // operands reading the register. They don't contribute valid lanes.
01515     //
01516     // This adds ssub1 to the set of valid lanes in %src:
01517     //
01518     //   %src:ssub1<def> = FOO
01519     //
01520     // This leaves only ssub1 valid, making any other lanes undef:
01521     //
01522     //   %src:ssub1<def,read-undef> = FOO %src:ssub2
01523     //
01524     // The <read-undef> flag on the def operand means that old lane values are
01525     // not important.
01526     if (Redef) {
01527       V.RedefVNI = LI.Query(VNI->def).valueIn();
01528       assert(V.RedefVNI && "Instruction is reading nonexistent value");
01529       computeAssignment(V.RedefVNI->id, Other);
01530       V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
01531     }
01532 
01533     // An IMPLICIT_DEF writes undef values.
01534     if (DefMI->isImplicitDef()) {
01535       // We normally expect IMPLICIT_DEF values to be live only until the end
01536       // of their block. If the value is really live longer and gets pruned in
01537       // another block, this flag is cleared again.
01538       V.ErasableImplicitDef = true;
01539       V.ValidLanes &= ~V.WriteLanes;
01540     }
01541   }
01542 
01543   // Find the value in Other that overlaps VNI->def, if any.
01544   LiveQueryResult OtherLRQ = Other.LI.Query(VNI->def);
01545 
01546   // It is possible that both values are defined by the same instruction, or
01547   // the values are PHIs defined in the same block. When that happens, the two
01548   // values should be merged into one, but not into any preceding value.
01549   // The first value defined or visited gets CR_Keep, the other gets CR_Merge.
01550   if (VNInfo *OtherVNI = OtherLRQ.valueDefined()) {
01551     assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) && "Broken LRQ");
01552 
01553     // One value stays, the other is merged. Keep the earlier one, or the first
01554     // one we see.
01555     if (OtherVNI->def < VNI->def)
01556       Other.computeAssignment(OtherVNI->id, *this);
01557     else if (VNI->def < OtherVNI->def && OtherLRQ.valueIn()) {
01558       // This is an early-clobber def overlapping a live-in value in the other
01559       // register. Not mergeable.
01560       V.OtherVNI = OtherLRQ.valueIn();
01561       return CR_Impossible;
01562     }
01563     V.OtherVNI = OtherVNI;
01564     Val &OtherV = Other.Vals[OtherVNI->id];
01565     // Keep this value, check for conflicts when analyzing OtherVNI.
01566     if (!OtherV.isAnalyzed())
01567       return CR_Keep;
01568     // Both sides have been analyzed now.
01569     // Allow overlapping PHI values. Any real interference would show up in a
01570     // predecessor, the PHI itself can't introduce any conflicts.
01571     if (VNI->isPHIDef())
01572       return CR_Merge;
01573     if (V.ValidLanes & OtherV.ValidLanes)
01574       // Overlapping lanes can't be resolved.
01575       return CR_Impossible;
01576     else
01577       return CR_Merge;
01578   }
01579 
01580   // No simultaneous def. Is Other live at the def?
01581   V.OtherVNI = OtherLRQ.valueIn();
01582   if (!V.OtherVNI)
01583     // No overlap, no conflict.
01584     return CR_Keep;
01585 
01586   assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) && "Broken LRQ");
01587 
01588   // We have overlapping values, or possibly a kill of Other.
01589   // Recursively compute assignments up the dominator tree.
01590   Other.computeAssignment(V.OtherVNI->id, *this);
01591   Val &OtherV = Other.Vals[V.OtherVNI->id];
01592 
01593   // Check if OtherV is an IMPLICIT_DEF that extends beyond its basic block.
01594   // This shouldn't normally happen, but ProcessImplicitDefs can leave such
01595   // IMPLICIT_DEF instructions behind, and there is nothing wrong with it
01596   // technically.
01597   //
01598   // WHen it happens, treat that IMPLICIT_DEF as a normal value, and don't try
01599   // to erase the IMPLICIT_DEF instruction.
01600   if (OtherV.ErasableImplicitDef && DefMI &&
01601       DefMI->getParent() != Indexes->getMBBFromIndex(V.OtherVNI->def)) {
01602     DEBUG(dbgs() << "IMPLICIT_DEF defined at " << V.OtherVNI->def
01603                  << " extends into BB#" << DefMI->getParent()->getNumber()
01604                  << ", keeping it.\n");
01605     OtherV.ErasableImplicitDef = false;
01606   }
01607 
01608   // Allow overlapping PHI values. Any real interference would show up in a
01609   // predecessor, the PHI itself can't introduce any conflicts.
01610   if (VNI->isPHIDef())
01611     return CR_Replace;
01612 
01613   // Check for simple erasable conflicts.
01614   if (DefMI->isImplicitDef())
01615     return CR_Erase;
01616 
01617   // Include the non-conflict where DefMI is a coalescable copy that kills
01618   // OtherVNI. We still want the copy erased and value numbers merged.
01619   if (CP.isCoalescable(DefMI)) {
01620     // Some of the lanes copied from OtherVNI may be undef, making them undef
01621     // here too.
01622     V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
01623     return CR_Erase;
01624   }
01625 
01626   // This may not be a real conflict if DefMI simply kills Other and defines
01627   // VNI.
01628   if (OtherLRQ.isKill() && OtherLRQ.endPoint() <= VNI->def)
01629     return CR_Keep;
01630 
01631   // Handle the case where VNI and OtherVNI can be proven to be identical:
01632   //
01633   //   %other = COPY %ext
01634   //   %this  = COPY %ext <-- Erase this copy
01635   //
01636   if (DefMI->isFullCopy() && !CP.isPartial() &&
01637       stripCopies(VNI) == stripCopies(V.OtherVNI))
01638     return CR_Erase;
01639 
01640   // If the lanes written by this instruction were all undef in OtherVNI, it is
01641   // still safe to join the live ranges. This can't be done with a simple value
01642   // mapping, though - OtherVNI will map to multiple values:
01643   //
01644   //   1 %dst:ssub0 = FOO                <-- OtherVNI
01645   //   2 %src = BAR                      <-- VNI
01646   //   3 %dst:ssub1 = COPY %src<kill>    <-- Eliminate this copy.
01647   //   4 BAZ %dst<kill>
01648   //   5 QUUX %src<kill>
01649   //
01650   // Here OtherVNI will map to itself in [1;2), but to VNI in [2;5). CR_Replace
01651   // handles this complex value mapping.
01652   if ((V.WriteLanes & OtherV.ValidLanes) == 0)
01653     return CR_Replace;
01654 
01655   // If the other live range is killed by DefMI and the live ranges are still
01656   // overlapping, it must be because we're looking at an early clobber def:
01657   //
01658   //   %dst<def,early-clobber> = ASM %src<kill>
01659   //
01660   // In this case, it is illegal to merge the two live ranges since the early
01661   // clobber def would clobber %src before it was read.
01662   if (OtherLRQ.isKill()) {
01663     // This case where the def doesn't overlap the kill is handled above.
01664     assert(VNI->def.isEarlyClobber() &&
01665            "Only early clobber defs can overlap a kill");
01666     return CR_Impossible;
01667   }
01668 
01669   // VNI is clobbering live lanes in OtherVNI, but there is still the
01670   // possibility that no instructions actually read the clobbered lanes.
01671   // If we're clobbering all the lanes in OtherVNI, at least one must be read.
01672   // Otherwise Other.LI wouldn't be live here.
01673   if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes) == 0)
01674     return CR_Impossible;
01675 
01676   // We need to verify that no instructions are reading the clobbered lanes. To
01677   // save compile time, we'll only check that locally. Don't allow the tainted
01678   // value to escape the basic block.
01679   MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
01680   if (OtherLRQ.endPoint() >= Indexes->getMBBEndIdx(MBB))
01681     return CR_Impossible;
01682 
01683   // There are still some things that could go wrong besides clobbered lanes
01684   // being read, for example OtherVNI may be only partially redefined in MBB,
01685   // and some clobbered lanes could escape the block. Save this analysis for
01686   // resolveConflicts() when all values have been mapped. We need to know
01687   // RedefVNI and WriteLanes for any later defs in MBB, and we can't compute
01688   // that now - the recursive analyzeValue() calls must go upwards in the
01689   // dominator tree.
01690   return CR_Unresolved;
01691 }
01692 
01693 /// Compute the value assignment for ValNo in LI.
01694 /// This may be called recursively by analyzeValue(), but never for a ValNo on
01695 /// the stack.
01696 void JoinVals::computeAssignment(unsigned ValNo, JoinVals &Other) {
01697   Val &V = Vals[ValNo];
01698   if (V.isAnalyzed()) {
01699     // Recursion should always move up the dominator tree, so ValNo is not
01700     // supposed to reappear before it has been assigned.
01701     assert(Assignments[ValNo] != -1 && "Bad recursion?");
01702     return;
01703   }
01704   switch ((V.Resolution = analyzeValue(ValNo, Other))) {
01705   case CR_Erase:
01706   case CR_Merge:
01707     // Merge this ValNo into OtherVNI.
01708     assert(V.OtherVNI && "OtherVNI not assigned, can't merge.");
01709     assert(Other.Vals[V.OtherVNI->id].isAnalyzed() && "Missing recursion");
01710     Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
01711     DEBUG(dbgs() << "\t\tmerge " << PrintReg(LI.reg) << ':' << ValNo << '@'
01712                  << LI.getValNumInfo(ValNo)->def << " into "
01713                  << PrintReg(Other.LI.reg) << ':' << V.OtherVNI->id << '@'
01714                  << V.OtherVNI->def << " --> @"
01715                  << NewVNInfo[Assignments[ValNo]]->def << '\n');
01716     break;
01717   case CR_Replace:
01718   case CR_Unresolved:
01719     // The other value is going to be pruned if this join is successful.
01720     assert(V.OtherVNI && "OtherVNI not assigned, can't prune");
01721     Other.Vals[V.OtherVNI->id].Pruned = true;
01722     // Fall through.
01723   default:
01724     // This value number needs to go in the final joined live range.
01725     Assignments[ValNo] = NewVNInfo.size();
01726     NewVNInfo.push_back(LI.getValNumInfo(ValNo));
01727     break;
01728   }
01729 }
01730 
01731 bool JoinVals::mapValues(JoinVals &Other) {
01732   for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
01733     computeAssignment(i, Other);
01734     if (Vals[i].Resolution == CR_Impossible) {
01735       DEBUG(dbgs() << "\t\tinterference at " << PrintReg(LI.reg) << ':' << i
01736                    << '@' << LI.getValNumInfo(i)->def << '\n');
01737       return false;
01738     }
01739   }
01740   return true;
01741 }
01742 
01743 /// Assuming ValNo is going to clobber some valid lanes in Other.LI, compute
01744 /// the extent of the tainted lanes in the block.
01745 ///
01746 /// Multiple values in Other.LI can be affected since partial redefinitions can
01747 /// preserve previously tainted lanes.
01748 ///
01749 ///   1 %dst = VLOAD           <-- Define all lanes in %dst
01750 ///   2 %src = FOO             <-- ValNo to be joined with %dst:ssub0
01751 ///   3 %dst:ssub1 = BAR       <-- Partial redef doesn't clear taint in ssub0
01752 ///   4 %dst:ssub0 = COPY %src <-- Conflict resolved, ssub0 wasn't read
01753 ///
01754 /// For each ValNo in Other that is affected, add an (EndIndex, TaintedLanes)
01755 /// entry to TaintedVals.
01756 ///
01757 /// Returns false if the tainted lanes extend beyond the basic block.
01758 bool JoinVals::
01759 taintExtent(unsigned ValNo, unsigned TaintedLanes, JoinVals &Other,
01760             SmallVectorImpl<std::pair<SlotIndex, unsigned> > &TaintExtent) {
01761   VNInfo *VNI = LI.getValNumInfo(ValNo);
01762   MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
01763   SlotIndex MBBEnd = Indexes->getMBBEndIdx(MBB);
01764 
01765   // Scan Other.LI from VNI.def to MBBEnd.
01766   LiveInterval::iterator OtherI = Other.LI.find(VNI->def);
01767   assert(OtherI != Other.LI.end() && "No conflict?");
01768   do {
01769     // OtherI is pointing to a tainted value. Abort the join if the tainted
01770     // lanes escape the block.
01771     SlotIndex End = OtherI->end;
01772     if (End >= MBBEnd) {
01773       DEBUG(dbgs() << "\t\ttaints global " << PrintReg(Other.LI.reg) << ':'
01774                    << OtherI->valno->id << '@' << OtherI->start << '\n');
01775       return false;
01776     }
01777     DEBUG(dbgs() << "\t\ttaints local " << PrintReg(Other.LI.reg) << ':'
01778                  << OtherI->valno->id << '@' << OtherI->start
01779                  << " to " << End << '\n');
01780     // A dead def is not a problem.
01781     if (End.isDead())
01782       break;
01783     TaintExtent.push_back(std::make_pair(End, TaintedLanes));
01784 
01785     // Check for another def in the MBB.
01786     if (++OtherI == Other.LI.end() || OtherI->start >= MBBEnd)
01787       break;
01788 
01789     // Lanes written by the new def are no longer tainted.
01790     const Val &OV = Other.Vals[OtherI->valno->id];
01791     TaintedLanes &= ~OV.WriteLanes;
01792     if (!OV.RedefVNI)
01793       break;
01794   } while (TaintedLanes);
01795   return true;
01796 }
01797 
01798 /// Return true if MI uses any of the given Lanes from Reg.
01799 /// This does not include partial redefinitions of Reg.
01800 bool JoinVals::usesLanes(MachineInstr *MI, unsigned Reg, unsigned SubIdx,
01801                          unsigned Lanes) {
01802   if (MI->isDebugValue())
01803     return false;
01804   for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
01805     if (!MO->isReg() || MO->isDef() || MO->getReg() != Reg)
01806       continue;
01807     if (!MO->readsReg())
01808       continue;
01809     if (Lanes & TRI->getSubRegIndexLaneMask(
01810                   TRI->composeSubRegIndices(SubIdx, MO->getSubReg())))
01811       return true;
01812   }
01813   return false;
01814 }
01815 
01816 bool JoinVals::resolveConflicts(JoinVals &Other) {
01817   for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
01818     Val &V = Vals[i];
01819     assert (V.Resolution != CR_Impossible && "Unresolvable conflict");
01820     if (V.Resolution != CR_Unresolved)
01821       continue;
01822     DEBUG(dbgs() << "\t\tconflict at " << PrintReg(LI.reg) << ':' << i
01823                  << '@' << LI.getValNumInfo(i)->def << '\n');
01824     ++NumLaneConflicts;
01825     assert(V.OtherVNI && "Inconsistent conflict resolution.");
01826     VNInfo *VNI = LI.getValNumInfo(i);
01827     const Val &OtherV = Other.Vals[V.OtherVNI->id];
01828 
01829     // VNI is known to clobber some lanes in OtherVNI. If we go ahead with the
01830     // join, those lanes will be tainted with a wrong value. Get the extent of
01831     // the tainted lanes.
01832     unsigned TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
01833     SmallVector<std::pair<SlotIndex, unsigned>, 8> TaintExtent;
01834     if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
01835       // Tainted lanes would extend beyond the basic block.
01836       return false;
01837 
01838     assert(!TaintExtent.empty() && "There should be at least one conflict.");
01839 
01840     // Now look at the instructions from VNI->def to TaintExtent (inclusive).
01841     MachineBasicBlock *MBB = Indexes->getMBBFromIndex(VNI->def);
01842     MachineBasicBlock::iterator MI = MBB->begin();
01843     if (!VNI->isPHIDef()) {
01844       MI = Indexes->getInstructionFromIndex(VNI->def);
01845       // No need to check the instruction defining VNI for reads.
01846       ++MI;
01847     }
01848     assert(!SlotIndex::isSameInstr(VNI->def, TaintExtent.front().first) &&
01849            "Interference ends on VNI->def. Should have been handled earlier");
01850     MachineInstr *LastMI =
01851       Indexes->getInstructionFromIndex(TaintExtent.front().first);
01852     assert(LastMI && "Range must end at a proper instruction");
01853     unsigned TaintNum = 0;
01854     for(;;) {
01855       assert(MI != MBB->end() && "Bad LastMI");
01856       if (usesLanes(MI, Other.LI.reg, Other.SubIdx, TaintedLanes)) {
01857         DEBUG(dbgs() << "\t\ttainted lanes used by: " << *MI);
01858         return false;
01859       }
01860       // LastMI is the last instruction to use the current value.
01861       if (&*MI == LastMI) {
01862         if (++TaintNum == TaintExtent.size())
01863           break;
01864         LastMI = Indexes->getInstructionFromIndex(TaintExtent[TaintNum].first);
01865         assert(LastMI && "Range must end at a proper instruction");
01866         TaintedLanes = TaintExtent[TaintNum].second;
01867       }
01868       ++MI;
01869     }
01870 
01871     // The tainted lanes are unused.
01872     V.Resolution = CR_Replace;
01873     ++NumLaneResolves;
01874   }
01875   return true;
01876 }
01877 
01878 // Determine if ValNo is a copy of a value number in LI or Other.LI that will
01879 // be pruned:
01880 //
01881 //   %dst = COPY %src
01882 //   %src = COPY %dst  <-- This value to be pruned.
01883 //   %dst = COPY %src  <-- This value is a copy of a pruned value.
01884 //
01885 bool JoinVals::isPrunedValue(unsigned ValNo, JoinVals &Other) {
01886   Val &V = Vals[ValNo];
01887   if (V.Pruned || V.PrunedComputed)
01888     return V.Pruned;
01889 
01890   if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
01891     return V.Pruned;
01892 
01893   // Follow copies up the dominator tree and check if any intermediate value
01894   // has been pruned.
01895   V.PrunedComputed = true;
01896   V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *this);
01897   return V.Pruned;
01898 }
01899 
01900 void JoinVals::pruneValues(JoinVals &Other,
01901                            SmallVectorImpl<SlotIndex> &EndPoints) {
01902   for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
01903     SlotIndex Def = LI.getValNumInfo(i)->def;
01904     switch (Vals[i].Resolution) {
01905     case CR_Keep:
01906       break;
01907     case CR_Replace: {
01908       // This value takes precedence over the value in Other.LI.
01909       LIS->pruneValue(&Other.LI, Def, &EndPoints);
01910       // Check if we're replacing an IMPLICIT_DEF value. The IMPLICIT_DEF
01911       // instructions are only inserted to provide a live-out value for PHI
01912       // predecessors, so the instruction should simply go away once its value
01913       // has been replaced.
01914       Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
01915       bool EraseImpDef = OtherV.ErasableImplicitDef &&
01916                          OtherV.Resolution == CR_Keep;
01917       if (!Def.isBlock()) {
01918         // Remove <def,read-undef> flags. This def is now a partial redef.
01919         // Also remove <def,dead> flags since the joined live range will
01920         // continue past this instruction.
01921         for (MIOperands MO(Indexes->getInstructionFromIndex(Def));
01922              MO.isValid(); ++MO)
01923           if (MO->isReg() && MO->isDef() && MO->getReg() == LI.reg) {
01924             MO->setIsUndef(EraseImpDef);
01925             MO->setIsDead(false);
01926           }
01927         // This value will reach instructions below, but we need to make sure
01928         // the live range also reaches the instruction at Def.
01929         if (!EraseImpDef)
01930           EndPoints.push_back(Def);
01931       }
01932       DEBUG(dbgs() << "\t\tpruned " << PrintReg(Other.LI.reg) << " at " << Def
01933                    << ": " << Other.LI << '\n');
01934       break;
01935     }
01936     case CR_Erase:
01937     case CR_Merge:
01938       if (isPrunedValue(i, Other)) {
01939         // This value is ultimately a copy of a pruned value in LI or Other.LI.
01940         // We can no longer trust the value mapping computed by
01941         // computeAssignment(), the value that was originally copied could have
01942         // been replaced.
01943         LIS->pruneValue(&LI, Def, &EndPoints);
01944         DEBUG(dbgs() << "\t\tpruned all of " << PrintReg(LI.reg) << " at "
01945                      << Def << ": " << LI << '\n');
01946       }
01947       break;
01948     case CR_Unresolved:
01949     case CR_Impossible:
01950       llvm_unreachable("Unresolved conflicts");
01951     }
01952   }
01953 }
01954 
01955 void JoinVals::eraseInstrs(SmallPtrSetImpl<MachineInstr*> &ErasedInstrs,
01956                            SmallVectorImpl<unsigned> &ShrinkRegs) {
01957   for (unsigned i = 0, e = LI.getNumValNums(); i != e; ++i) {
01958     // Get the def location before markUnused() below invalidates it.
01959     SlotIndex Def = LI.getValNumInfo(i)->def;
01960     switch (Vals[i].Resolution) {
01961     case CR_Keep:
01962       // If an IMPLICIT_DEF value is pruned, it doesn't serve a purpose any
01963       // longer. The IMPLICIT_DEF instructions are only inserted by
01964       // PHIElimination to guarantee that all PHI predecessors have a value.
01965       if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned)
01966         break;
01967       // Remove value number i from LI. Note that this VNInfo is still present
01968       // in NewVNInfo, so it will appear as an unused value number in the final
01969       // joined interval.
01970       LI.getValNumInfo(i)->markUnused();
01971       LI.removeValNo(LI.getValNumInfo(i));
01972       DEBUG(dbgs() << "\t\tremoved " << i << '@' << Def << ": " << LI << '\n');
01973       // FALL THROUGH.
01974 
01975     case CR_Erase: {
01976       MachineInstr *MI = Indexes->getInstructionFromIndex(Def);
01977       assert(MI && "No instruction to erase");
01978       if (MI->isCopy()) {
01979         unsigned Reg = MI->getOperand(1).getReg();
01980         if (TargetRegisterInfo::isVirtualRegister(Reg) &&
01981             Reg != CP.getSrcReg() && Reg != CP.getDstReg())
01982           ShrinkRegs.push_back(Reg);
01983       }
01984       ErasedInstrs.insert(MI);
01985       DEBUG(dbgs() << "\t\terased:\t" << Def << '\t' << *MI);
01986       LIS->RemoveMachineInstrFromMaps(MI);
01987       MI->eraseFromParent();
01988       break;
01989     }
01990     default:
01991       break;
01992     }
01993   }
01994 }
01995 
01996 bool RegisterCoalescer::joinVirtRegs(CoalescerPair &CP) {
01997   SmallVector<VNInfo*, 16> NewVNInfo;
01998   LiveInterval &RHS = LIS->getInterval(CP.getSrcReg());
01999   LiveInterval &LHS = LIS->getInterval(CP.getDstReg());
02000   JoinVals RHSVals(RHS, CP.getSrcIdx(), NewVNInfo, CP, LIS, TRI);
02001   JoinVals LHSVals(LHS, CP.getDstIdx(), NewVNInfo, CP, LIS, TRI);
02002 
02003   DEBUG(dbgs() << "\t\tRHS = " << RHS
02004                << "\n\t\tLHS = " << LHS
02005                << '\n');
02006 
02007   // First compute NewVNInfo and the simple value mappings.
02008   // Detect impossible conflicts early.
02009   if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
02010     return false;
02011 
02012   // Some conflicts can only be resolved after all values have been mapped.
02013   if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
02014     return false;
02015 
02016   // All clear, the live ranges can be merged.
02017 
02018   // The merging algorithm in LiveInterval::join() can't handle conflicting
02019   // value mappings, so we need to remove any live ranges that overlap a
02020   // CR_Replace resolution. Collect a set of end points that can be used to
02021   // restore the live range after joining.
02022   SmallVector<SlotIndex, 8> EndPoints;
02023   LHSVals.pruneValues(RHSVals, EndPoints);
02024   RHSVals.pruneValues(LHSVals, EndPoints);
02025 
02026   // Erase COPY and IMPLICIT_DEF instructions. This may cause some external
02027   // registers to require trimming.
02028   SmallVector<unsigned, 8> ShrinkRegs;
02029   LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
02030   RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
02031   while (!ShrinkRegs.empty())
02032     LIS->shrinkToUses(&LIS->getInterval(ShrinkRegs.pop_back_val()));
02033 
02034   // Join RHS into LHS.
02035   LHS.join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo);
02036 
02037   // Kill flags are going to be wrong if the live ranges were overlapping.
02038   // Eventually, we should simply clear all kill flags when computing live
02039   // ranges. They are reinserted after register allocation.
02040   MRI->clearKillFlags(LHS.reg);
02041   MRI->clearKillFlags(RHS.reg);
02042 
02043   if (EndPoints.empty())
02044     return true;
02045 
02046   // Recompute the parts of the live range we had to remove because of
02047   // CR_Replace conflicts.
02048   DEBUG(dbgs() << "\t\trestoring liveness to " << EndPoints.size()
02049                << " points: " << LHS << '\n');
02050   LIS->extendToIndices(LHS, EndPoints);
02051   return true;
02052 }
02053 
02054 /// joinIntervals - Attempt to join these two intervals.  On failure, this
02055 /// returns false.
02056 bool RegisterCoalescer::joinIntervals(CoalescerPair &CP) {
02057   return CP.isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
02058 }
02059 
02060 namespace {
02061 // Information concerning MBB coalescing priority.
02062 struct MBBPriorityInfo {
02063   MachineBasicBlock *MBB;
02064   unsigned Depth;
02065   bool IsSplit;
02066 
02067   MBBPriorityInfo(MachineBasicBlock *mbb, unsigned depth, bool issplit)
02068     : MBB(mbb), Depth(depth), IsSplit(issplit) {}
02069 };
02070 }
02071 
02072 // C-style comparator that sorts first based on the loop depth of the basic
02073 // block (the unsigned), and then on the MBB number.
02074 //
02075 // EnableGlobalCopies assumes that the primary sort key is loop depth.
02076 static int compareMBBPriority(const MBBPriorityInfo *LHS,
02077                               const MBBPriorityInfo *RHS) {
02078   // Deeper loops first
02079   if (LHS->Depth != RHS->Depth)
02080     return LHS->Depth > RHS->Depth ? -1 : 1;
02081 
02082   // Try to unsplit critical edges next.
02083   if (LHS->IsSplit != RHS->IsSplit)
02084     return LHS->IsSplit ? -1 : 1;
02085 
02086   // Prefer blocks that are more connected in the CFG. This takes care of
02087   // the most difficult copies first while intervals are short.
02088   unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size();
02089   unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size();
02090   if (cl != cr)
02091     return cl > cr ? -1 : 1;
02092 
02093   // As a last resort, sort by block number.
02094   return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1;
02095 }
02096 
02097 /// \returns true if the given copy uses or defines a local live range.
02098 static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS) {
02099   if (!Copy->isCopy())
02100     return false;
02101 
02102   if (Copy->getOperand(1).isUndef())
02103     return false;
02104 
02105   unsigned SrcReg = Copy->getOperand(1).getReg();
02106   unsigned DstReg = Copy->getOperand(0).getReg();
02107   if (TargetRegisterInfo::isPhysicalRegister(SrcReg)
02108       || TargetRegisterInfo::isPhysicalRegister(DstReg))
02109     return false;
02110 
02111   return LIS->intervalIsInOneMBB(LIS->getInterval(SrcReg))
02112     || LIS->intervalIsInOneMBB(LIS->getInterval(DstReg));
02113 }
02114 
02115 // Try joining WorkList copies starting from index From.
02116 // Null out any successful joins.
02117 bool RegisterCoalescer::
02118 copyCoalesceWorkList(MutableArrayRef<MachineInstr*> CurrList) {
02119   bool Progress = false;
02120   for (unsigned i = 0, e = CurrList.size(); i != e; ++i) {
02121     if (!CurrList[i])
02122       continue;
02123     // Skip instruction pointers that have already been erased, for example by
02124     // dead code elimination.
02125     if (ErasedInstrs.erase(CurrList[i])) {
02126       CurrList[i] = nullptr;
02127       continue;
02128     }
02129     bool Again = false;
02130     bool Success = joinCopy(CurrList[i], Again);
02131     Progress |= Success;
02132     if (Success || !Again)
02133       CurrList[i] = nullptr;
02134   }
02135   return Progress;
02136 }
02137 
02138 void
02139 RegisterCoalescer::copyCoalesceInMBB(MachineBasicBlock *MBB) {
02140   DEBUG(dbgs() << MBB->getName() << ":\n");
02141 
02142   // Collect all copy-like instructions in MBB. Don't start coalescing anything
02143   // yet, it might invalidate the iterator.
02144   const unsigned PrevSize = WorkList.size();
02145   if (JoinGlobalCopies) {
02146     // Coalesce copies bottom-up to coalesce local defs before local uses. They
02147     // are not inherently easier to resolve, but slightly preferable until we
02148     // have local live range splitting. In particular this is required by
02149     // cmp+jmp macro fusion.
02150     for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
02151          MII != E; ++MII) {
02152       if (!MII->isCopyLike())
02153         continue;
02154       if (isLocalCopy(&(*MII), LIS))
02155         LocalWorkList.push_back(&(*MII));
02156       else
02157         WorkList.push_back(&(*MII));
02158     }
02159   }
02160   else {
02161      for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
02162           MII != E; ++MII)
02163        if (MII->isCopyLike())
02164          WorkList.push_back(MII);
02165   }
02166   // Try coalescing the collected copies immediately, and remove the nulls.
02167   // This prevents the WorkList from getting too large since most copies are
02168   // joinable on the first attempt.
02169   MutableArrayRef<MachineInstr*>
02170     CurrList(WorkList.begin() + PrevSize, WorkList.end());
02171   if (copyCoalesceWorkList(CurrList))
02172     WorkList.erase(std::remove(WorkList.begin() + PrevSize, WorkList.end(),
02173                                (MachineInstr*)nullptr), WorkList.end());
02174 }
02175 
02176 void RegisterCoalescer::coalesceLocals() {
02177   copyCoalesceWorkList(LocalWorkList);
02178   for (unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) {
02179     if (LocalWorkList[j])
02180       WorkList.push_back(LocalWorkList[j]);
02181   }
02182   LocalWorkList.clear();
02183 }
02184 
02185 void RegisterCoalescer::joinAllIntervals() {
02186   DEBUG(dbgs() << "********** JOINING INTERVALS ***********\n");
02187   assert(WorkList.empty() && LocalWorkList.empty() && "Old data still around.");
02188 
02189   std::vector<MBBPriorityInfo> MBBs;
02190   MBBs.reserve(MF->size());
02191   for (MachineFunction::iterator I = MF->begin(), E = MF->end();I != E;++I){
02192     MachineBasicBlock *MBB = I;
02193     MBBs.push_back(MBBPriorityInfo(MBB, Loops->getLoopDepth(MBB),
02194                                    JoinSplitEdges && isSplitEdge(MBB)));
02195   }
02196   array_pod_sort(MBBs.begin(), MBBs.end(), compareMBBPriority);
02197 
02198   // Coalesce intervals in MBB priority order.
02199   unsigned CurrDepth = UINT_MAX;
02200   for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
02201     // Try coalescing the collected local copies for deeper loops.
02202     if (JoinGlobalCopies && MBBs[i].Depth < CurrDepth) {
02203       coalesceLocals();
02204       CurrDepth = MBBs[i].Depth;
02205     }
02206     copyCoalesceInMBB(MBBs[i].MBB);
02207   }
02208   coalesceLocals();
02209 
02210   // Joining intervals can allow other intervals to be joined.  Iteratively join
02211   // until we make no progress.
02212   while (copyCoalesceWorkList(WorkList))
02213     /* empty */ ;
02214 }
02215 
02216 void RegisterCoalescer::releaseMemory() {
02217   ErasedInstrs.clear();
02218   WorkList.clear();
02219   DeadDefs.clear();
02220   InflateRegs.clear();
02221 }
02222 
02223 bool RegisterCoalescer::runOnMachineFunction(MachineFunction &fn) {
02224   MF = &fn;
02225   MRI = &fn.getRegInfo();
02226   TM = &fn.getTarget();
02227   TRI = TM->getSubtargetImpl()->getRegisterInfo();
02228   TII = TM->getSubtargetImpl()->getInstrInfo();
02229   LIS = &getAnalysis<LiveIntervals>();
02230   AA = &getAnalysis<AliasAnalysis>();
02231   Loops = &getAnalysis<MachineLoopInfo>();
02232 
02233   const TargetSubtargetInfo &ST = TM->getSubtarget<TargetSubtargetInfo>();
02234   if (EnableGlobalCopies == cl::BOU_UNSET)
02235     JoinGlobalCopies = ST.useMachineScheduler();
02236   else
02237     JoinGlobalCopies = (EnableGlobalCopies == cl::BOU_TRUE);
02238 
02239   // The MachineScheduler does not currently require JoinSplitEdges. This will
02240   // either be enabled unconditionally or replaced by a more general live range
02241   // splitting optimization.
02242   JoinSplitEdges = EnableJoinSplits;
02243 
02244   DEBUG(dbgs() << "********** SIMPLE REGISTER COALESCING **********\n"
02245                << "********** Function: " << MF->getName() << '\n');
02246 
02247   if (VerifyCoalescing)
02248     MF->verify(this, "Before register coalescing");
02249 
02250   RegClassInfo.runOnMachineFunction(fn);
02251 
02252   // Join (coalesce) intervals if requested.
02253   if (EnableJoining)
02254     joinAllIntervals();
02255 
02256   // After deleting a lot of copies, register classes may be less constrained.
02257   // Removing sub-register operands may allow GR32_ABCD -> GR32 and DPR_VFP2 ->
02258   // DPR inflation.
02259   array_pod_sort(InflateRegs.begin(), InflateRegs.end());
02260   InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
02261                     InflateRegs.end());
02262   DEBUG(dbgs() << "Trying to inflate " << InflateRegs.size() << " regs.\n");
02263   for (unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
02264     unsigned Reg = InflateRegs[i];
02265     if (MRI->reg_nodbg_empty(Reg))
02266       continue;
02267     if (MRI->recomputeRegClass(Reg, *TM)) {
02268       DEBUG(dbgs() << PrintReg(Reg) << " inflated to "
02269                    << MRI->getRegClass(Reg)->getName() << '\n');
02270       ++NumInflated;
02271     }
02272   }
02273 
02274   DEBUG(dump());
02275   if (VerifyCoalescing)
02276     MF->verify(this, "After register coalescing");
02277   return true;
02278 }
02279 
02280 /// print - Implement the dump method.
02281 void RegisterCoalescer::print(raw_ostream &O, const Module* m) const {
02282    LIS->print(O, m);
02283 }