LCOV - code coverage report
Current view: top level - lib/CodeGen - TwoAddressInstructionPass.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 653 726 89.9 %
Date: 2017-09-14 15:23:50 Functions: 32 32 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===-- TwoAddressInstructionPass.cpp - Two-Address instruction pass ------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This file implements the TwoAddress instruction pass which is used
      11             : // by most register allocators. Two-Address instructions are rewritten
      12             : // from:
      13             : //
      14             : //     A = B op C
      15             : //
      16             : // to:
      17             : //
      18             : //     A = B
      19             : //     A op= C
      20             : //
      21             : // Note that if a register allocator chooses to use this pass, that it
      22             : // has to be capable of handling the non-SSA nature of these rewritten
      23             : // virtual registers.
      24             : //
      25             : // It is also worth noting that the duplicate operand of the two
      26             : // address instruction is removed.
      27             : //
      28             : //===----------------------------------------------------------------------===//
      29             : 
      30             : #include "llvm/ADT/DenseMap.h"
      31             : #include "llvm/ADT/STLExtras.h"
      32             : #include "llvm/ADT/SmallVector.h"
      33             : #include "llvm/ADT/Statistic.h"
      34             : #include "llvm/Analysis/AliasAnalysis.h"
      35             : #include "llvm/CodeGen/LiveIntervalAnalysis.h"
      36             : #include "llvm/CodeGen/LiveVariables.h"
      37             : #include "llvm/CodeGen/MachineFunctionPass.h"
      38             : #include "llvm/CodeGen/MachineInstr.h"
      39             : #include "llvm/CodeGen/MachineInstrBuilder.h"
      40             : #include "llvm/CodeGen/MachineRegisterInfo.h"
      41             : #include "llvm/CodeGen/Passes.h"
      42             : #include "llvm/IR/Function.h"
      43             : #include "llvm/MC/MCInstrItineraries.h"
      44             : #include "llvm/Support/CommandLine.h"
      45             : #include "llvm/Support/Debug.h"
      46             : #include "llvm/Support/ErrorHandling.h"
      47             : #include "llvm/Support/raw_ostream.h"
      48             : #include "llvm/Target/TargetInstrInfo.h"
      49             : #include "llvm/Target/TargetMachine.h"
      50             : #include "llvm/Target/TargetRegisterInfo.h"
      51             : #include "llvm/Target/TargetSubtargetInfo.h"
      52             : 
      53             : using namespace llvm;
      54             : 
      55             : #define DEBUG_TYPE "twoaddressinstruction"
      56             : 
      57             : STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
      58             : STATISTIC(NumCommuted        , "Number of instructions commuted to coalesce");
      59             : STATISTIC(NumAggrCommuted    , "Number of instructions aggressively commuted");
      60             : STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
      61             : STATISTIC(Num3AddrSunk,        "Number of 3-address instructions sunk");
      62             : STATISTIC(NumReSchedUps,       "Number of instructions re-scheduled up");
      63             : STATISTIC(NumReSchedDowns,     "Number of instructions re-scheduled down");
      64             : 
      65             : // Temporary flag to disable rescheduling.
      66             : static cl::opt<bool>
      67       72306 : EnableRescheduling("twoaddr-reschedule",
      68      216918 :                    cl::desc("Coalesce copies by rescheduling (default=true)"),
      69      289224 :                    cl::init(true), cl::Hidden);
      70             : 
      71             : // Limit the number of dataflow edges to traverse when evaluating the benefit
      72             : // of commuting operands.
      73       72306 : static cl::opt<unsigned> MaxDataFlowEdge(
      74      216918 :     "dataflow-edge-limit", cl::Hidden, cl::init(3),
      75      216918 :     cl::desc("Maximum number of dataflow edges to traverse when evaluating "
      76       72306 :              "the benefit of commuting operands"));
      77             : 
      78             : namespace {
      79      100926 : class TwoAddressInstructionPass : public MachineFunctionPass {
      80             :   MachineFunction *MF;
      81             :   const TargetInstrInfo *TII;
      82             :   const TargetRegisterInfo *TRI;
      83             :   const InstrItineraryData *InstrItins;
      84             :   MachineRegisterInfo *MRI;
      85             :   LiveVariables *LV;
      86             :   LiveIntervals *LIS;
      87             :   AliasAnalysis *AA;
      88             :   CodeGenOpt::Level OptLevel;
      89             : 
      90             :   // The current basic block being processed.
      91             :   MachineBasicBlock *MBB;
      92             : 
      93             :   // Keep track the distance of a MI from the start of the current basic block.
      94             :   DenseMap<MachineInstr*, unsigned> DistanceMap;
      95             : 
      96             :   // Set of already processed instructions in the current block.
      97             :   SmallPtrSet<MachineInstr*, 8> Processed;
      98             : 
      99             :   // A map from virtual registers to physical registers which are likely targets
     100             :   // to be coalesced to due to copies from physical registers to virtual
     101             :   // registers. e.g. v1024 = move r0.
     102             :   DenseMap<unsigned, unsigned> SrcRegMap;
     103             : 
     104             :   // A map from virtual registers to physical registers which are likely targets
     105             :   // to be coalesced to due to copies to physical registers from virtual
     106             :   // registers. e.g. r1 = move v1024.
     107             :   DenseMap<unsigned, unsigned> DstRegMap;
     108             : 
     109             :   bool sink3AddrInstruction(MachineInstr *MI, unsigned Reg,
     110             :                             MachineBasicBlock::iterator OldPos);
     111             : 
     112             :   bool isRevCopyChain(unsigned FromReg, unsigned ToReg, int Maxlen);
     113             : 
     114             :   bool noUseAfterLastDef(unsigned Reg, unsigned Dist, unsigned &LastDef);
     115             : 
     116             :   bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
     117             :                              MachineInstr *MI, unsigned Dist);
     118             : 
     119             :   bool commuteInstruction(MachineInstr *MI, unsigned DstIdx,
     120             :                           unsigned RegBIdx, unsigned RegCIdx, unsigned Dist);
     121             : 
     122             :   bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
     123             : 
     124             :   bool convertInstTo3Addr(MachineBasicBlock::iterator &mi,
     125             :                           MachineBasicBlock::iterator &nmi,
     126             :                           unsigned RegA, unsigned RegB, unsigned Dist);
     127             : 
     128             :   bool isDefTooClose(unsigned Reg, unsigned Dist, MachineInstr *MI);
     129             : 
     130             :   bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
     131             :                              MachineBasicBlock::iterator &nmi,
     132             :                              unsigned Reg);
     133             :   bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
     134             :                              MachineBasicBlock::iterator &nmi,
     135             :                              unsigned Reg);
     136             : 
     137             :   bool tryInstructionTransform(MachineBasicBlock::iterator &mi,
     138             :                                MachineBasicBlock::iterator &nmi,
     139             :                                unsigned SrcIdx, unsigned DstIdx,
     140             :                                unsigned Dist, bool shouldOnlyCommute);
     141             : 
     142             :   bool tryInstructionCommute(MachineInstr *MI,
     143             :                              unsigned DstOpIdx,
     144             :                              unsigned BaseOpIdx,
     145             :                              bool BaseOpKilled,
     146             :                              unsigned Dist);
     147             :   void scanUses(unsigned DstReg);
     148             : 
     149             :   void processCopy(MachineInstr *MI);
     150             : 
     151             :   typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList;
     152             :   typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap;
     153             :   bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
     154             :   void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
     155             :   void eliminateRegSequence(MachineBasicBlock::iterator&);
     156             : 
     157             : public:
     158             :   static char ID; // Pass identification, replacement for typeid
     159       84620 :   TwoAddressInstructionPass() : MachineFunctionPass(ID) {
     160       16924 :     initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
     161       16924 :   }
     162             : 
     163       16859 :   void getAnalysisUsage(AnalysisUsage &AU) const override {
     164       16859 :     AU.setPreservesCFG();
     165       16859 :     AU.addUsedIfAvailable<AAResultsWrapperPass>();
     166       16859 :     AU.addUsedIfAvailable<LiveVariables>();
     167       16859 :     AU.addPreserved<LiveVariables>();
     168       16859 :     AU.addPreserved<SlotIndexes>();
     169       16859 :     AU.addPreserved<LiveIntervals>();
     170       33718 :     AU.addPreservedID(MachineLoopInfoID);
     171       33718 :     AU.addPreservedID(MachineDominatorsID);
     172       16859 :     MachineFunctionPass::getAnalysisUsage(AU);
     173       16859 :   }
     174             : 
     175             :   /// Pass entry point.
     176             :   bool runOnMachineFunction(MachineFunction&) override;
     177             : };
     178             : } // end anonymous namespace
     179             : 
     180             : char TwoAddressInstructionPass::ID = 0;
     181       20212 : INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, DEBUG_TYPE,
     182             :                 "Two-Address instruction pass", false, false)
     183       20212 : INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
     184      201971 : INITIALIZE_PASS_END(TwoAddressInstructionPass, DEBUG_TYPE,
     185             :                 "Two-Address instruction pass", false, false)
     186             : 
     187             : char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
     188             : 
     189             : static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg, LiveIntervals *LIS);
     190             : 
     191             : /// A two-address instruction has been converted to a three-address instruction
     192             : /// to avoid clobbering a register. Try to sink it past the instruction that
     193             : /// would kill the above mentioned register to reduce register pressure.
     194        4149 : bool TwoAddressInstructionPass::
     195             : sink3AddrInstruction(MachineInstr *MI, unsigned SavedReg,
     196             :                      MachineBasicBlock::iterator OldPos) {
     197             :   // FIXME: Shouldn't we be trying to do this before we three-addressify the
     198             :   // instruction?  After this transformation is done, we no longer need
     199             :   // the instruction to be in three-address form.
     200             : 
     201             :   // Check if it's safe to move this instruction.
     202        4149 :   bool SeenStore = true; // Be conservative.
     203        4149 :   if (!MI->isSafeToMove(AA, SeenStore))
     204             :     return false;
     205             : 
     206        3781 :   unsigned DefReg = 0;
     207        7562 :   SmallSet<unsigned, 4> UseRegs;
     208             : 
     209       26395 :   for (const MachineOperand &MO : MI->operands()) {
     210       22614 :     if (!MO.isReg())
     211        7347 :       continue;
     212       15267 :     unsigned MOReg = MO.getReg();
     213       15267 :     if (!MOReg)
     214        6178 :       continue;
     215        9089 :     if (MO.isUse() && MOReg != SavedReg)
     216        1470 :       UseRegs.insert(MO.getReg());
     217        9089 :     if (!MO.isDef())
     218        5308 :       continue;
     219        3781 :     if (MO.isImplicit())
     220             :       // Don't try to move it if it implicitly defines a register.
     221             :       return false;
     222        3781 :     if (DefReg)
     223             :       // For now, don't move any instructions that define multiple registers.
     224             :       return false;
     225        3781 :     DefReg = MO.getReg();
     226             :   }
     227             : 
     228             :   // Find the instruction that kills SavedReg.
     229        3781 :   MachineInstr *KillMI = nullptr;
     230        3781 :   if (LIS) {
     231           0 :     LiveInterval &LI = LIS->getInterval(SavedReg);
     232             :     assert(LI.end() != LI.begin() &&
     233             :            "Reg should not have empty live interval.");
     234             : 
     235           0 :     SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
     236           0 :     LiveInterval::const_iterator I = LI.find(MBBEndIdx);
     237           0 :     if (I != LI.end() && I->start < MBBEndIdx)
     238             :       return false;
     239             : 
     240           0 :     --I;
     241           0 :     KillMI = LIS->getInstructionFromIndex(I->end);
     242             :   }
     243           0 :   if (!KillMI) {
     244       29753 :     for (MachineOperand &UseMO : MRI->use_nodbg_operands(SavedReg)) {
     245       21882 :       if (!UseMO.isKill())
     246             :         continue;
     247        3472 :       KillMI = UseMO.getParent();
     248        3472 :       break;
     249             :     }
     250             :   }
     251             : 
     252             :   // If we find the instruction that kills SavedReg, and it is in an
     253             :   // appropriate location, we can try to sink the current instruction
     254             :   // past it.
     255        5187 :   if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
     256        8345 :       MachineBasicBlock::iterator(KillMI) == OldPos || KillMI->isTerminator())
     257             :     return false;
     258             : 
     259             :   // If any of the definitions are used by another instruction between the
     260             :   // position and the kill use, then it's not safe to sink it.
     261             :   //
     262             :   // FIXME: This can be sped up if there is an easy way to query whether an
     263             :   // instruction is before or after another instruction. Then we can use
     264             :   // MachineRegisterInfo def / use instead.
     265        1134 :   MachineOperand *KillMO = nullptr;
     266        1134 :   MachineBasicBlock::iterator KillPos = KillMI;
     267        1134 :   ++KillPos;
     268             : 
     269        1134 :   unsigned NumVisited = 0;
     270       10723 :   for (MachineInstr &OtherMI : llvm::make_range(std::next(OldPos), KillPos)) {
     271             :     // DBG_VALUE cannot be counted against the limit.
     272        4009 :     if (OtherMI.isDebugValue())
     273         144 :       continue;
     274        3865 :     if (NumVisited > 30)  // FIXME: Arbitrary limit to reduce compile time cost.
     275         697 :       return false;
     276        3862 :     ++NumVisited;
     277       19390 :     for (unsigned i = 0, e = OtherMI.getNumOperands(); i != e; ++i) {
     278       32444 :       MachineOperand &MO = OtherMI.getOperand(i);
     279       16222 :       if (!MO.isReg())
     280       11888 :         continue;
     281       11506 :       unsigned MOReg = MO.getReg();
     282       11506 :       if (!MOReg)
     283        2456 :         continue;
     284        9050 :       if (DefReg == MOReg)
     285         694 :         return false;
     286             : 
     287        8401 :       if (MO.isKill() || (LIS && isPlainlyKilled(&OtherMI, MOReg, LIS))) {
     288        2179 :         if (&OtherMI == KillMI && MOReg == SavedReg)
     289             :           // Save the operand that kills the register. We want to unset the kill
     290             :           // marker if we can sink MI past it.
     291             :           KillMO = &MO;
     292        1695 :         else if (UseRegs.count(MOReg))
     293             :           // One of the uses is killed before the destination.
     294             :           return false;
     295             :       }
     296             :     }
     297             :   }
     298             :   assert(KillMO && "Didn't find kill");
     299             : 
     300         437 :   if (!LIS) {
     301             :     // Update kill and LV information.
     302         437 :     KillMO->setIsKill(false);
     303         874 :     KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
     304         437 :     KillMO->setIsKill(true);
     305             : 
     306         437 :     if (LV)
     307         437 :       LV->replaceKillInstruction(SavedReg, *KillMI, *MI);
     308             :   }
     309             : 
     310             :   // Move instruction to its destination.
     311         874 :   MBB->remove(MI);
     312         874 :   MBB->insert(KillPos, MI);
     313             : 
     314         437 :   if (LIS)
     315           0 :     LIS->handleMove(*MI);
     316             : 
     317             :   ++Num3AddrSunk;
     318             :   return true;
     319             : }
     320             : 
     321             : /// Return the MachineInstr* if it is the single def of the Reg in current BB.
     322       28508 : static MachineInstr *getSingleDef(unsigned Reg, MachineBasicBlock *BB,
     323             :                                   const MachineRegisterInfo *MRI) {
     324       28508 :   MachineInstr *Ret = nullptr;
     325      126550 :   for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
     326       78784 :     if (DefMI.getParent() != BB || DefMI.isDebugValue())
     327        3324 :       continue;
     328       37730 :     if (!Ret)
     329             :       Ret = &DefMI;
     330       12574 :     else if (Ret != &DefMI)
     331             :       return nullptr;
     332             :   }
     333             :   return Ret;
     334             : }
     335             : 
     336             : /// Check if there is a reversed copy chain from FromReg to ToReg:
     337             : /// %Tmp1 = copy %Tmp2;
     338             : /// %FromReg = copy %Tmp1;
     339             : /// %ToReg = add %FromReg ...
     340             : /// %Tmp2 = copy %ToReg;
     341             : /// MaxLen specifies the maximum length of the copy chain the func
     342             : /// can walk through.
     343       24195 : bool TwoAddressInstructionPass::isRevCopyChain(unsigned FromReg, unsigned ToReg,
     344             :                                                int Maxlen) {
     345       24195 :   unsigned TmpReg = FromReg;
     346       28558 :   for (int i = 0; i < Maxlen; i++) {
     347       28508 :     MachineInstr *Def = getSingleDef(TmpReg, MBB, MRI);
     348       41090 :     if (!Def || !Def->isCopy())
     349             :       return false;
     350             : 
     351        4490 :     TmpReg = Def->getOperand(1).getReg();
     352             : 
     353        4490 :     if (TmpReg == ToReg)
     354             :       return true;
     355             :   }
     356             :   return false;
     357             : }
     358             : 
     359             : /// Return true if there are no intervening uses between the last instruction
     360             : /// in the MBB that defines the specified register and the two-address
     361             : /// instruction which is being processed. It also returns the last def location
     362             : /// by reference.
     363       27531 : bool TwoAddressInstructionPass::noUseAfterLastDef(unsigned Reg, unsigned Dist,
     364             :                                                   unsigned &LastDef) {
     365       27531 :   LastDef = 0;
     366       27531 :   unsigned LastUse = Dist;
     367      148545 :   for (MachineOperand &MO : MRI->reg_operands(Reg)) {
     368       93483 :     MachineInstr *MI = MO.getParent();
     369      181567 :     if (MI->getParent() != MBB || MI->isDebugValue())
     370       11052 :       continue;
     371       87966 :     DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
     372      263898 :     if (DI == DistanceMap.end())
     373          18 :       continue;
     374       87948 :     if (MO.isUse() && DI->second < LastUse)
     375             :       LastUse = DI->second;
     376       87948 :     if (MO.isDef() && DI->second > LastDef)
     377       38171 :       LastDef = DI->second;
     378             :   }
     379             : 
     380       27531 :   return !(LastUse > LastDef && LastUse < Dist);
     381             : }
     382             : 
     383             : /// Return true if the specified MI is a copy instruction or an extract_subreg
     384             : /// instruction. It also returns the source and destination registers and
     385             : /// whether they are physical registers by reference.
     386             : static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
     387             :                         unsigned &SrcReg, unsigned &DstReg,
     388             :                         bool &IsSrcPhys, bool &IsDstPhys) {
     389     4575821 :   SrcReg = 0;
     390     4575821 :   DstReg = 0;
     391     4575821 :   if (MI.isCopy()) {
     392     1154956 :     DstReg = MI.getOperand(0).getReg();
     393     1154956 :     SrcReg = MI.getOperand(1).getReg();
     394     6679360 :   } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
     395       67523 :     DstReg = MI.getOperand(0).getReg();
     396       67523 :     SrcReg = MI.getOperand(2).getReg();
     397             :   } else
     398             :     return false;
     399             : 
     400     2444958 :   IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
     401     2444958 :   IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
     402             :   return true;
     403             : }
     404             : 
     405             : /// Test if the given register value, which is used by the
     406             : /// given instruction, is killed by the given instruction.
     407      265313 : static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg,
     408             :                             LiveIntervals *LIS) {
     409      265313 :   if (LIS && TargetRegisterInfo::isVirtualRegister(Reg) &&
     410           0 :       !LIS->isNotInMIMap(*MI)) {
     411             :     // FIXME: Sometimes tryInstructionTransform() will add instructions and
     412             :     // test whether they can be folded before keeping them. In this case it
     413             :     // sets a kill before recursively calling tryInstructionTransform() again.
     414             :     // If there is no interval available, we assume that this instruction is
     415             :     // one of those. A kill flag is manually inserted on the operand so the
     416             :     // check below will handle it.
     417           0 :     LiveInterval &LI = LIS->getInterval(Reg);
     418             :     // This is to match the kill flag version where undefs don't have kill
     419             :     // flags.
     420           0 :     if (!LI.hasAtLeastOneValue())
     421             :       return false;
     422             : 
     423           0 :     SlotIndex useIdx = LIS->getInstructionIndex(*MI);
     424           0 :     LiveInterval::const_iterator I = LI.find(useIdx);
     425             :     assert(I != LI.end() && "Reg must be live-in to use.");
     426           0 :     return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx);
     427             :   }
     428             : 
     429      265313 :   return MI->killsRegister(Reg);
     430             : }
     431             : 
     432             : /// Test if the given register value, which is used by the given
     433             : /// instruction, is killed by the given instruction. This looks through
     434             : /// coalescable copies to see if the original value is potentially not killed.
     435             : ///
     436             : /// For example, in this code:
     437             : ///
     438             : ///   %reg1034 = copy %reg1024
     439             : ///   %reg1035 = copy %reg1025<kill>
     440             : ///   %reg1036 = add %reg1034<kill>, %reg1035<kill>
     441             : ///
     442             : /// %reg1034 is not considered to be killed, since it is copied from a
     443             : /// register which is not killed. Treating it as not killed lets the
     444             : /// normal heuristics commute the (two-address) add, which lets
     445             : /// coalescing eliminate the extra copy.
     446             : ///
     447             : /// If allowFalsePositives is true then likely kills are treated as kills even
     448             : /// if it can't be proven that they are kills.
     449      219974 : static bool isKilled(MachineInstr &MI, unsigned Reg,
     450             :                      const MachineRegisterInfo *MRI,
     451             :                      const TargetInstrInfo *TII,
     452             :                      LiveIntervals *LIS,
     453             :                      bool allowFalsePositives) {
     454      219974 :   MachineInstr *DefMI = &MI;
     455             :   for (;;) {
     456             :     // All uses of physical registers are likely to be kills.
     457      261932 :     if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
     458         356 :         (allowFalsePositives || MRI->hasOneUse(Reg)))
     459      219974 :       return true;
     460      237660 :     if (!isPlainlyKilled(DefMI, Reg, LIS))
     461             :       return false;
     462      203554 :     if (TargetRegisterInfo::isPhysicalRegister(Reg))
     463             :       return true;
     464      203326 :     MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
     465             :     // If there are multiple defs, we can't do a simple analysis, so just
     466             :     // go with what the kill flag says.
     467      406652 :     if (std::next(Begin) != MRI->def_end())
     468             :       return true;
     469      162921 :     DefMI = Begin->getParent();
     470             :     bool IsSrcPhys, IsDstPhys;
     471             :     unsigned SrcReg,  DstReg;
     472             :     // If the def is something other than a copy, then it isn't going to
     473             :     // be coalesced, so follow the kill flag.
     474      325842 :     if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
     475             :       return true;
     476       41958 :     Reg = SrcReg;
     477       41958 :   }
     478             : }
     479             : 
     480             : /// Return true if the specified MI uses the specified register as a two-address
     481             : /// use. If so, return the destination register by reference.
     482      439099 : static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
     483     2134797 :   for (unsigned i = 0, NumOps = MI.getNumOperands(); i != NumOps; ++i) {
     484     3631084 :     const MachineOperand &MO = MI.getOperand(i);
     485     3209109 :     if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
     486     1369543 :       continue;
     487             :     unsigned ti;
     488      445999 :     if (MI.isRegTiedToDefOperand(i, &ti)) {
     489      239688 :       DstReg = MI.getOperand(ti).getReg();
     490      119844 :       return true;
     491             :     }
     492             :   }
     493             :   return false;
     494             : }
     495             : 
     496             : /// Given a register, if has a single in-basic block use, return the use
     497             : /// instruction if it's a copy or a two-address use.
     498             : static
     499      696177 : MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
     500             :                                      MachineRegisterInfo *MRI,
     501             :                                      const TargetInstrInfo *TII,
     502             :                                      bool &IsCopy,
     503             :                                      unsigned &DstReg, bool &IsDstPhys) {
     504      696177 :   if (!MRI->hasOneNonDBGUse(Reg))
     505             :     // None or more than one use.
     506             :     return nullptr;
     507     1173604 :   MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(Reg);
     508      586802 :   if (UseMI.getParent() != MBB)
     509             :     return nullptr;
     510             :   unsigned SrcReg;
     511             :   bool IsSrcPhys;
     512     1112436 :   if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
     513      149058 :     IsCopy = true;
     514             :     return &UseMI;
     515             :   }
     516      407160 :   IsDstPhys = false;
     517      407160 :   if (isTwoAddrUse(UseMI, Reg, DstReg)) {
     518      205438 :     IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
     519             :     return &UseMI;
     520             :   }
     521             :   return nullptr;
     522             : }
     523             : 
     524             : /// Return the physical register the specified virtual register might be mapped
     525             : /// to.
     526             : static unsigned
     527       71526 : getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
     528      332289 :   while (TargetRegisterInfo::isVirtualRegister(Reg))  {
     529      109192 :     DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
     530      218384 :     if (SI == RegMap.end())
     531       46113 :       return 0;
     532       63079 :     Reg = SI->second;
     533             :   }
     534       25413 :   if (TargetRegisterInfo::isPhysicalRegister(Reg))
     535       25413 :     return Reg;
     536             :   return 0;
     537             : }
     538             : 
     539             : /// Return true if the two registers are equal or aliased.
     540             : static bool
     541             : regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
     542       11280 :   if (RegA == RegB)
     543             :     return true;
     544             :   if (!RegA || !RegB)
     545             :     return false;
     546        5537 :   return TRI->regsOverlap(RegA, RegB);
     547             : }
     548             : 
     549             : // Returns true if Reg is equal or aliased to at least one register in Set.
     550             : static bool regOverlapsSet(const SmallVectorImpl<unsigned> &Set, unsigned Reg,
     551             :                            const TargetRegisterInfo *TRI) {
     552      212428 :   for (unsigned R : Set)
     553       65360 :     if (TRI->regsOverlap(R, Reg))
     554             :       return true;
     555             : 
     556             :   return false;
     557             : }
     558             : 
     559             : /// Return true if it's potentially profitable to commute the two-address
     560             : /// instruction that's being processed.
     561             : bool
     562       27653 : TwoAddressInstructionPass::
     563             : isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
     564             :                       MachineInstr *MI, unsigned Dist) {
     565       27653 :   if (OptLevel == CodeGenOpt::None)
     566             :     return false;
     567             : 
     568             :   // Determine if it's profitable to commute this two address instruction. In
     569             :   // general, we want no uses between this instruction and the definition of
     570             :   // the two-address register.
     571             :   // e.g.
     572             :   // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
     573             :   // %reg1029<def> = MOV8rr %reg1028
     574             :   // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
     575             :   // insert => %reg1030<def> = MOV8rr %reg1028
     576             :   // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
     577             :   // In this case, it might not be possible to coalesce the second MOV8rr
     578             :   // instruction if the first one is coalesced. So it would be profitable to
     579             :   // commute it:
     580             :   // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
     581             :   // %reg1029<def> = MOV8rr %reg1028
     582             :   // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
     583             :   // insert => %reg1030<def> = MOV8rr %reg1029
     584             :   // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
     585             : 
     586       27653 :   if (!isPlainlyKilled(MI, regC, LIS))
     587             :     return false;
     588             : 
     589             :   // Ok, we have something like:
     590             :   // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
     591             :   // let's see if it's worth commuting it.
     592             : 
     593             :   // Look for situations like this:
     594             :   // %reg1024<def> = MOV r1
     595             :   // %reg1025<def> = MOV r0
     596             :   // %reg1026<def> = ADD %reg1024, %reg1025
     597             :   // r0            = MOV %reg1026
     598             :   // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
     599       19300 :   unsigned ToRegA = getMappedReg(regA, DstRegMap);
     600       19300 :   if (ToRegA) {
     601        8349 :     unsigned FromRegB = getMappedReg(regB, SrcRegMap);
     602        8349 :     unsigned FromRegC = getMappedReg(regC, SrcRegMap);
     603       10290 :     bool CompB = FromRegB && regsAreCompatible(FromRegB, ToRegA, TRI);
     604       11201 :     bool CompC = FromRegC && regsAreCompatible(FromRegC, ToRegA, TRI);
     605             : 
     606             :     // Compute if any of the following are true:
     607             :     // -RegB is not tied to a register and RegC is compatible with RegA.
     608             :     // -RegB is tied to the wrong physical register, but RegC is.
     609             :     // -RegB is tied to the wrong physical register, and RegC isn't tied.
     610        8349 :     if ((!FromRegB && CompC) || (FromRegB && !CompB && (!FromRegC || CompC)))
     611             :       return true;
     612             :     // Don't compute if any of the following are true:
     613             :     // -RegC is not tied to a register and RegB is compatible with RegA.
     614             :     // -RegC is tied to the wrong physical register, but RegB is.
     615             :     // -RegC is tied to the wrong physical register, and RegB isn't tied.
     616        6907 :     if ((!FromRegC && CompB) || (FromRegC && !CompC && (!FromRegB || CompB)))
     617             :       return false;
     618             :   }
     619             : 
     620             :   // If there is a use of regC between its last def (could be livein) and this
     621             :   // instruction, then bail.
     622       14741 :   unsigned LastDefC = 0;
     623       14741 :   if (!noUseAfterLastDef(regC, Dist, LastDefC))
     624             :     return false;
     625             : 
     626             :   // If there is a use of regB between its last def (could be livein) and this
     627             :   // instruction, then go ahead and make this transformation.
     628       12790 :   unsigned LastDefB = 0;
     629       12790 :   if (!noUseAfterLastDef(regB, Dist, LastDefB))
     630             :     return true;
     631             : 
     632             :   // Look for situation like this:
     633             :   // %reg101 = MOV %reg100
     634             :   // %reg102 = ...
     635             :   // %reg103 = ADD %reg102, %reg101
     636             :   // ... = %reg103 ...
     637             :   // %reg100 = MOV %reg103
     638             :   // If there is a reversed copy chain from reg101 to reg103, commute the ADD
     639             :   // to eliminate an otherwise unavoidable copy.
     640             :   // FIXME:
     641             :   // We can extend the logic further: If an pair of operands in an insn has
     642             :   // been merged, the insn could be regarded as a virtual copy, and the virtual
     643             :   // copy could also be used to construct a copy chain.
     644             :   // To more generally minimize register copies, ideally the logic of two addr
     645             :   // instruction pass should be integrated with register allocation pass where
     646             :   // interference graph is available.
     647       12111 :   if (isRevCopyChain(regC, regA, MaxDataFlowEdge))
     648             :     return true;
     649             : 
     650       12084 :   if (isRevCopyChain(regB, regA, MaxDataFlowEdge))
     651             :     return false;
     652             : 
     653             :   // Since there are no intervening uses for both registers, then commute
     654             :   // if the def of regC is closer. Its live interval is shorter.
     655       11984 :   return LastDefB && LastDefC && LastDefC > LastDefB;
     656             : }
     657             : 
     658             : /// Commute a two-address instruction and update the basic block, distance map,
     659             : /// and live variables if needed. Return true if it is successful.
     660       10864 : bool TwoAddressInstructionPass::commuteInstruction(MachineInstr *MI,
     661             :                                                    unsigned DstIdx,
     662             :                                                    unsigned RegBIdx,
     663             :                                                    unsigned RegCIdx,
     664             :                                                    unsigned Dist) {
     665       21728 :   unsigned RegC = MI->getOperand(RegCIdx).getReg();
     666             :   DEBUG(dbgs() << "2addr: COMMUTING  : " << *MI);
     667       10864 :   MachineInstr *NewMI = TII->commuteInstruction(*MI, false, RegBIdx, RegCIdx);
     668             : 
     669       10864 :   if (NewMI == nullptr) {
     670             :     DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
     671             :     return false;
     672             :   }
     673             : 
     674             :   DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
     675             :   assert(NewMI == MI &&
     676             :          "TargetInstrInfo::commuteInstruction() should not return a new "
     677             :          "instruction unless it was requested.");
     678             : 
     679             :   // Update source register map.
     680       10859 :   unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
     681       10859 :   if (FromRegC) {
     682        5888 :     unsigned RegA = MI->getOperand(DstIdx).getReg();
     683        5888 :     SrcRegMap[RegA] = FromRegC;
     684             :   }
     685             : 
     686             :   return true;
     687             : }
     688             : 
     689             : /// Return true if it is profitable to convert the given 2-address instruction
     690             : /// to a 3-address one.
     691             : bool
     692       21829 : TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
     693             :   // Look for situations like this:
     694             :   // %reg1024<def> = MOV r1
     695             :   // %reg1025<def> = MOV r0
     696             :   // %reg1026<def> = ADD %reg1024, %reg1025
     697             :   // r2            = MOV %reg1026
     698             :   // Turn ADD into a 3-address instruction to avoid a copy.
     699       21829 :   unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
     700       21829 :   if (!FromRegB)
     701             :     return false;
     702        2840 :   unsigned ToRegA = getMappedReg(RegA, DstRegMap);
     703        3584 :   return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
     704             : }
     705             : 
     706             : /// Convert the specified two-address instruction into a three address one.
     707             : /// Return true if this transformation was successful.
     708             : bool
     709        6664 : TwoAddressInstructionPass::convertInstTo3Addr(MachineBasicBlock::iterator &mi,
     710             :                                               MachineBasicBlock::iterator &nmi,
     711             :                                               unsigned RegA, unsigned RegB,
     712             :                                               unsigned Dist) {
     713             :   // FIXME: Why does convertToThreeAddress() need an iterator reference?
     714       13328 :   MachineFunction::iterator MFI = MBB->getIterator();
     715       13328 :   MachineInstr *NewMI = TII->convertToThreeAddress(MFI, *mi, LV);
     716             :   assert(MBB->getIterator() == MFI &&
     717             :          "convertToThreeAddress changed iterator reference");
     718        6664 :   if (!NewMI)
     719             :     return false;
     720             : 
     721             :   DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
     722             :   DEBUG(dbgs() << "2addr:         TO 3-ADDR: " << *NewMI);
     723        5001 :   bool Sunk = false;
     724             : 
     725        5001 :   if (LIS)
     726           0 :     LIS->ReplaceMachineInstrInMaps(*mi, *NewMI);
     727             : 
     728        9150 :   if (NewMI->findRegisterUseOperand(RegB, false, TRI))
     729             :     // FIXME: Temporary workaround. If the new instruction doesn't
     730             :     // uses RegB, convertToThreeAddress must have created more
     731             :     // then one instruction.
     732        4149 :     Sunk = sink3AddrInstruction(NewMI, RegB, mi);
     733             : 
     734        5001 :   MBB->erase(mi); // Nuke the old inst.
     735             : 
     736        5001 :   if (!Sunk) {
     737       13692 :     DistanceMap.insert(std::make_pair(NewMI, Dist));
     738        9128 :     mi = NewMI;
     739        4564 :     nmi = std::next(mi);
     740             :   }
     741             : 
     742             :   // Update source and destination register maps.
     743        5001 :   SrcRegMap.erase(RegA);
     744        5001 :   DstRegMap.erase(RegB);
     745        5001 :   return true;
     746             : }
     747             : 
     748             : /// Scan forward recursively for only uses, update maps if the use is a copy or
     749             : /// a two-address instruction.
     750             : void
     751      511269 : TwoAddressInstructionPass::scanUses(unsigned DstReg) {
     752     1022538 :   SmallVector<unsigned, 4> VirtRegPairs;
     753             :   bool IsDstPhys;
     754      511269 :   bool IsCopy = false;
     755      511269 :   unsigned NewReg = 0;
     756      511269 :   unsigned Reg = DstReg;
     757      696177 :   while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
     758      696177 :                                                       NewReg, IsDstPhys)) {
     759      251777 :     if (IsCopy && !Processed.insert(UseMI).second)
     760             :       break;
     761             : 
     762      228289 :     DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
     763      684867 :     if (DI != DistanceMap.end())
     764             :       // Earlier in the same MBB.Reached via a back edge.
     765             :       break;
     766             : 
     767      228289 :     if (IsDstPhys) {
     768       43381 :       VirtRegPairs.push_back(NewReg);
     769       43381 :       break;
     770             :     }
     771      554724 :     bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
     772             :     if (!isNew)
     773             :       assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
     774      184908 :     VirtRegPairs.push_back(NewReg);
     775      184908 :     Reg = NewReg;
     776             :   }
     777             : 
     778      511269 :   if (!VirtRegPairs.empty()) {
     779      249896 :     unsigned ToReg = VirtRegPairs.back();
     780             :     VirtRegPairs.pop_back();
     781      331630 :     while (!VirtRegPairs.empty()) {
     782      206682 :       unsigned FromReg = VirtRegPairs.back();
     783      103341 :       VirtRegPairs.pop_back();
     784      310023 :       bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
     785             :       if (!isNew)
     786             :         assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
     787      103341 :       ToReg = FromReg;
     788             :     }
     789      374844 :     bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
     790             :     if (!isNew)
     791             :       assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
     792             :   }
     793      511269 : }
     794             : 
     795             : /// If the specified instruction is not yet processed, process it if it's a
     796             : /// copy. For a copy instruction, we find the physical registers the
     797             : /// source and destination registers might be mapped to. These are kept in
     798             : /// point-to maps used to determine future optimizations. e.g.
     799             : /// v1024 = mov r0
     800             : /// v1025 = mov r1
     801             : /// v1026 = add v1024, v1025
     802             : /// r1    = mov r1026
     803             : /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
     804             : /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
     805             : /// potentially joined with r1 on the output side. It's worthwhile to commute
     806             : /// 'add' to eliminate a copy.
     807     3985447 : void TwoAddressInstructionPass::processCopy(MachineInstr *MI) {
     808     3985447 :   if (Processed.count(MI))
     809             :     return;
     810             : 
     811             :   bool IsSrcPhys, IsDstPhys;
     812             :   unsigned SrcReg, DstReg;
     813     7713364 :   if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
     814             :     return;
     815             : 
     816     1031463 :   if (IsDstPhys && !IsSrcPhys)
     817     1319157 :     DstRegMap.insert(std::make_pair(SrcReg, DstReg));
     818      591744 :   else if (!IsDstPhys && IsSrcPhys) {
     819      898641 :     bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
     820             :     if (!isNew)
     821             :       assert(SrcRegMap[DstReg] == SrcReg &&
     822             :              "Can't map to two src physical registers!");
     823             : 
     824      299547 :     scanUses(DstReg);
     825             :   }
     826             : 
     827     1031463 :   Processed.insert(MI);
     828             : }
     829             : 
     830             : /// If there is one more local instruction that reads 'Reg' and it kills 'Reg,
     831             : /// consider moving the instruction below the kill instruction in order to
     832             : /// eliminate the need for the copy.
     833      200755 : bool TwoAddressInstructionPass::
     834             : rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
     835             :                       MachineBasicBlock::iterator &nmi,
     836             :                       unsigned Reg) {
     837             :   // Bail immediately if we don't have LV or LIS available. We use them to find
     838             :   // kills efficiently.
     839      200755 :   if (!LV && !LIS)
     840             :     return false;
     841             : 
     842      200732 :   MachineInstr *MI = &*mi;
     843      200732 :   DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
     844      602196 :   if (DI == DistanceMap.end())
     845             :     // Must be created from unfolded load. Don't waste time trying this.
     846             :     return false;
     847             : 
     848      200732 :   MachineInstr *KillMI = nullptr;
     849      200732 :   if (LIS) {
     850           0 :     LiveInterval &LI = LIS->getInterval(Reg);
     851             :     assert(LI.end() != LI.begin() &&
     852             :            "Reg should not have empty live interval.");
     853             : 
     854           0 :     SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
     855           0 :     LiveInterval::const_iterator I = LI.find(MBBEndIdx);
     856           0 :     if (I != LI.end() && I->start < MBBEndIdx)
     857             :       return false;
     858             : 
     859           0 :     --I;
     860           0 :     KillMI = LIS->getInstructionFromIndex(I->end);
     861             :   } else {
     862      200732 :     KillMI = LV->getVarInfo(Reg).findKill(MBB);
     863             :   }
     864      236841 :   if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
     865             :     // Don't mess with copies, they may be coalesced later.
     866             :     return false;
     867             : 
     868       50649 :   if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
     869       50649 :       KillMI->isBranch() || KillMI->isTerminator())
     870             :     // Don't move pass calls, etc.
     871             :     return false;
     872             : 
     873             :   unsigned DstReg;
     874       16881 :   if (isTwoAddrUse(*KillMI, Reg, DstReg))
     875             :     return false;
     876             : 
     877        8162 :   bool SeenStore = true;
     878        8162 :   if (!MI->isSafeToMove(AA, SeenStore))
     879             :     return false;
     880             : 
     881        7778 :   if (TII->getInstrLatency(InstrItins, *MI) > 1)
     882             :     // FIXME: Needs more sophisticated heuristics.
     883             :     return false;
     884             : 
     885        7758 :   SmallVector<unsigned, 2> Uses;
     886       15516 :   SmallVector<unsigned, 2> Kills;
     887       15516 :   SmallVector<unsigned, 2> Defs;
     888       36984 :   for (const MachineOperand &MO : MI->operands()) {
     889       29226 :     if (!MO.isReg())
     890       11305 :       continue;
     891       23618 :     unsigned MOReg = MO.getReg();
     892       23618 :     if (!MOReg)
     893          89 :       continue;
     894       23529 :     if (MO.isDef())
     895       13376 :       Defs.push_back(MOReg);
     896             :     else {
     897       10153 :       Uses.push_back(MOReg);
     898       14226 :       if (MOReg != Reg && (MO.isKill() ||
     899        1770 :                            (LIS && isPlainlyKilled(MI, MOReg, LIS))))
     900         533 :         Kills.push_back(MOReg);
     901             :     }
     902             :   }
     903             : 
     904             :   // Move the copies connected to MI down as well.
     905        7758 :   MachineBasicBlock::iterator Begin = MI;
     906        7758 :   MachineBasicBlock::iterator AfterMI = std::next(Begin);
     907             : 
     908        7758 :   MachineBasicBlock::iterator End = AfterMI;
     909       16278 :   while (End->isCopy() &&
     910        1014 :          regOverlapsSet(Defs, End->getOperand(1).getReg(), TRI)) {
     911         212 :     Defs.push_back(End->getOperand(0).getReg());
     912             :     ++End;
     913             :   }
     914             : 
     915             :   // Check if the reschedule will not break dependencies.
     916        7758 :   unsigned NumVisited = 0;
     917        7758 :   MachineBasicBlock::iterator KillPos = KillMI;
     918        7758 :   ++KillPos;
     919       34317 :   for (MachineInstr &OtherMI : llvm::make_range(End, KillPos)) {
     920             :     // DBG_VALUE cannot be counted against the limit.
     921       12989 :     if (OtherMI.isDebugValue())
     922          81 :       continue;
     923       12908 :     if (NumVisited > 10)  // FIXME: Arbitrary limit to reduce compile time cost.
     924        7177 :       return false;
     925       12693 :     ++NumVisited;
     926       38016 :     if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
     927       37987 :         OtherMI.isBranch() || OtherMI.isTerminator())
     928             :       // Don't move pass calls, etc.
     929             :       return false;
     930       42798 :     for (const MachineOperand &MO : OtherMI.operands()) {
     931       37067 :       if (!MO.isReg())
     932        5926 :         continue;
     933       31141 :       unsigned MOReg = MO.getReg();
     934       31141 :       if (!MOReg)
     935        2919 :         continue;
     936       28222 :       if (MO.isDef()) {
     937       26334 :         if (regOverlapsSet(Uses, MOReg, TRI))
     938             :           // Physical register use would be clobbered.
     939             :           return false;
     940       24419 :         if (!MO.isDead() && regOverlapsSet(Defs, MOReg, TRI))
     941             :           // May clobber a physical register def.
     942             :           // FIXME: This may be too conservative. It's ok if the instruction
     943             :           // is sunken completely below the use.
     944             :           return false;
     945             :       } else {
     946       30110 :         if (regOverlapsSet(Defs, MOReg, TRI))
     947             :           return false;
     948             :         bool isKill =
     949        9542 :             MO.isKill() || (LIS && isPlainlyKilled(&OtherMI, MOReg, LIS));
     950       20881 :         if (MOReg != Reg && ((isKill && regOverlapsSet(Uses, MOReg, TRI)) ||
     951       15220 :                              regOverlapsSet(Kills, MOReg, TRI)))
     952             :           // Don't want to extend other live ranges and update kills.
     953             :           return false;
     954        8967 :         if (MOReg == Reg && !isKill)
     955             :           // We can't schedule across a use of the register in question.
     956             :           return false;
     957             :         // Ensure that if this is register in question, its the kill we expect.
     958             :         assert((MOReg != Reg || &OtherMI == KillMI) &&
     959             :                "Found multiple kills of a register in a basic block");
     960             :       }
     961             :     }
     962             :   }
     963             : 
     964             :   // Move debug info as well.
     965        3660 :   while (Begin != MBB->begin() && std::prev(Begin)->isDebugValue())
     966             :     --Begin;
     967             : 
     968         581 :   nmi = End;
     969         581 :   MachineBasicBlock::iterator InsertPos = KillPos;
     970         581 :   if (LIS) {
     971             :     // We have to move the copies first so that the MBB is still well-formed
     972             :     // when calling handleMove().
     973           0 :     for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) {
     974           0 :       auto CopyMI = MBBI++;
     975           0 :       MBB->splice(InsertPos, MBB, CopyMI);
     976           0 :       LIS->handleMove(*CopyMI);
     977           0 :       InsertPos = CopyMI;
     978             :     }
     979           0 :     End = std::next(MachineBasicBlock::iterator(MI));
     980             :   }
     981             : 
     982             :   // Copies following MI may have been moved as well.
     983        1162 :   MBB->splice(InsertPos, MBB, Begin, End);
     984        1162 :   DistanceMap.erase(DI);
     985             : 
     986             :   // Update live variables
     987         581 :   if (LIS) {
     988           0 :     LIS->handleMove(*MI);
     989             :   } else {
     990         581 :     LV->removeVirtualRegisterKilled(Reg, *KillMI);
     991         581 :     LV->addVirtualRegisterKilled(Reg, *MI);
     992             :   }
     993             : 
     994             :   DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
     995             :   return true;
     996             : }
     997             : 
     998             : /// Return true if the re-scheduling will put the given instruction too close
     999             : /// to the defs of its register dependencies.
    1000       10557 : bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
    1001             :                                               MachineInstr *MI) {
    1002       53379 :   for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
    1003       28574 :     if (DefMI.getParent() != MBB || DefMI.isCopy() || DefMI.isCopyLike())
    1004        9160 :       continue;
    1005        2428 :     if (&DefMI == MI)
    1006        1468 :       return true; // MI is defining something KillMI uses
    1007        2093 :     DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(&DefMI);
    1008        6279 :     if (DDI == DistanceMap.end())
    1009             :       return true;  // Below MI
    1010         969 :     unsigned DefDist = DDI->second;
    1011             :     assert(Dist > DefDist && "Visited def already?");
    1012         969 :     if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist))
    1013             :       return true;
    1014             :   }
    1015             :   return false;
    1016             : }
    1017             : 
    1018             : /// If there is one more local instruction that reads 'Reg' and it kills 'Reg,
    1019             : /// consider moving the kill instruction above the current two-address
    1020             : /// instruction in order to eliminate the need for the copy.
    1021      195255 : bool TwoAddressInstructionPass::
    1022             : rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
    1023             :                       MachineBasicBlock::iterator &nmi,
    1024             :                       unsigned Reg) {
    1025             :   // Bail immediately if we don't have LV or LIS available. We use them to find
    1026             :   // kills efficiently.
    1027      195255 :   if (!LV && !LIS)
    1028             :     return false;
    1029             : 
    1030      195239 :   MachineInstr *MI = &*mi;
    1031      195239 :   DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
    1032      585717 :   if (DI == DistanceMap.end())
    1033             :     // Must be created from unfolded load. Don't waste time trying this.
    1034             :     return false;
    1035             : 
    1036      195239 :   MachineInstr *KillMI = nullptr;
    1037      195239 :   if (LIS) {
    1038           0 :     LiveInterval &LI = LIS->getInterval(Reg);
    1039             :     assert(LI.end() != LI.begin() &&
    1040             :            "Reg should not have empty live interval.");
    1041             : 
    1042           0 :     SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
    1043           0 :     LiveInterval::const_iterator I = LI.find(MBBEndIdx);
    1044           0 :     if (I != LI.end() && I->start < MBBEndIdx)
    1045             :       return false;
    1046             : 
    1047           0 :     --I;
    1048           0 :     KillMI = LIS->getInstructionFromIndex(I->end);
    1049             :   } else {
    1050      195239 :     KillMI = LV->getVarInfo(Reg).findKill(MBB);
    1051             :   }
    1052      227232 :   if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
    1053             :     // Don't mess with copies, they may be coalesced later.
    1054             :     return false;
    1055             : 
    1056             :   unsigned DstReg;
    1057       15058 :   if (isTwoAddrUse(*KillMI, Reg, DstReg))
    1058             :     return false;
    1059             : 
    1060        6652 :   bool SeenStore = true;
    1061        6652 :   if (!KillMI->isSafeToMove(AA, SeenStore))
    1062             :     return false;
    1063             : 
    1064       12340 :   SmallSet<unsigned, 2> Uses;
    1065       12340 :   SmallSet<unsigned, 2> Kills;
    1066       12340 :   SmallSet<unsigned, 2> Defs;
    1067       12340 :   SmallSet<unsigned, 2> LiveDefs;
    1068       15068 :   for (const MachineOperand &MO : KillMI->operands()) {
    1069       13792 :     if (!MO.isReg())
    1070         814 :       continue;
    1071       13410 :     unsigned MOReg = MO.getReg();
    1072       13410 :     if (MO.isUse()) {
    1073       10607 :       if (!MOReg)
    1074          50 :         continue;
    1075       10557 :       if (isDefTooClose(MOReg, DI->second, MI))
    1076        4894 :         return false;
    1077        9089 :       bool isKill = MO.isKill() || (LIS && isPlainlyKilled(KillMI, MOReg, LIS));
    1078        9089 :       if (MOReg == Reg && !isKill)
    1079             :         return false;
    1080        5663 :       Uses.insert(MOReg);
    1081        5663 :       if (isKill && MOReg != Reg)
    1082         683 :         Kills.insert(MOReg);
    1083        5606 :     } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
    1084         342 :       Defs.insert(MOReg);
    1085         342 :       if (!MO.isDead())
    1086         237 :         LiveDefs.insert(MOReg);
    1087             :     }
    1088             :   }
    1089             : 
    1090             :   // Check if the reschedule will not break depedencies.
    1091        1276 :   unsigned NumVisited = 0;
    1092             :   for (MachineInstr &OtherMI :
    1093       16416 :        llvm::make_range(mi, MachineBasicBlock::iterator(KillMI))) {
    1094             :     // DBG_VALUE cannot be counted against the limit.
    1095        6853 :     if (OtherMI.isDebugValue())
    1096           4 :       continue;
    1097        6849 :     if (NumVisited > 10)  // FIXME: Arbitrary limit to reduce compile time cost.
    1098        1118 :       return false;
    1099        6477 :     ++NumVisited;
    1100       19394 :     if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
    1101       19363 :         OtherMI.isBranch() || OtherMI.isTerminator())
    1102             :       // Don't move pass calls, etc.
    1103             :       return false;
    1104       12174 :     SmallVector<unsigned, 2> OtherDefs;
    1105       30439 :     for (const MachineOperand &MO : OtherMI.operands()) {
    1106       24620 :       if (!MO.isReg())
    1107       14922 :         continue;
    1108       18824 :       unsigned MOReg = MO.getReg();
    1109       18824 :       if (!MOReg)
    1110        3330 :         continue;
    1111       15494 :       if (MO.isUse()) {
    1112        8752 :         if (Defs.count(MOReg))
    1113             :           // Moving KillMI can clobber the physical register if the def has
    1114             :           // not been seen.
    1115         624 :           return false;
    1116        8746 :         if (Kills.count(MOReg))
    1117             :           // Don't want to extend other live ranges and update kills.
    1118             :           return false;
    1119        8716 :         if (&OtherMI != MI && MOReg == Reg &&
    1120         588 :             !(MO.isKill() || (LIS && isPlainlyKilled(&OtherMI, MOReg, LIS))))
    1121             :           // We can't schedule across a use of the register in question.
    1122             :           return false;
    1123             :       } else {
    1124        6742 :         OtherDefs.push_back(MOReg);
    1125             :       }
    1126             :     }
    1127             : 
    1128       17652 :     for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
    1129       12204 :       unsigned MOReg = OtherDefs[i];
    1130        6102 :       if (Uses.count(MOReg))
    1131          88 :         return false;
    1132       13450 :       if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
    1133        1292 :           LiveDefs.count(MOReg))
    1134             :         return false;
    1135             :       // Physical register def is seen.
    1136        6014 :       Defs.erase(MOReg);
    1137             :     }
    1138             :   }
    1139             : 
    1140             :   // Move the old kill above MI, don't forget to move debug info as well.
    1141         158 :   MachineBasicBlock::iterator InsertPos = mi;
    1142         954 :   while (InsertPos != MBB->begin() && std::prev(InsertPos)->isDebugValue())
    1143             :     --InsertPos;
    1144         158 :   MachineBasicBlock::iterator From = KillMI;
    1145         158 :   MachineBasicBlock::iterator To = std::next(From);
    1146         474 :   while (std::prev(From)->isDebugValue())
    1147             :     --From;
    1148         316 :   MBB->splice(InsertPos, MBB, From, To);
    1149             : 
    1150         158 :   nmi = std::prev(InsertPos); // Backtrack so we process the moved instr.
    1151         316 :   DistanceMap.erase(DI);
    1152             : 
    1153             :   // Update live variables
    1154         158 :   if (LIS) {
    1155           0 :     LIS->handleMove(*KillMI);
    1156             :   } else {
    1157         158 :     LV->removeVirtualRegisterKilled(Reg, *KillMI);
    1158         158 :     LV->addVirtualRegisterKilled(Reg, *MI);
    1159             :   }
    1160             : 
    1161             :   DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
    1162             :   return true;
    1163             : }
    1164             : 
    1165             : /// Tries to commute the operand 'BaseOpIdx' and some other operand in the
    1166             : /// given machine instruction to improve opportunities for coalescing and
    1167             : /// elimination of a register to register copy.
    1168             : ///
    1169             : /// 'DstOpIdx' specifies the index of MI def operand.
    1170             : /// 'BaseOpKilled' specifies if the register associated with 'BaseOpIdx'
    1171             : /// operand is killed by the given instruction.
    1172             : /// The 'Dist' arguments provides the distance of MI from the start of the
    1173             : /// current basic block and it is used to determine if it is profitable
    1174             : /// to commute operands in the instruction.
    1175             : ///
    1176             : /// Returns true if the transformation happened. Otherwise, returns false.
    1177      211741 : bool TwoAddressInstructionPass::tryInstructionCommute(MachineInstr *MI,
    1178             :                                                       unsigned DstOpIdx,
    1179             :                                                       unsigned BaseOpIdx,
    1180             :                                                       bool BaseOpKilled,
    1181             :                                                       unsigned Dist) {
    1182      211741 :   if (!MI->isCommutable())
    1183             :     return false;
    1184             : 
    1185       66234 :   unsigned DstOpReg = MI->getOperand(DstOpIdx).getReg();
    1186       66234 :   unsigned BaseOpReg = MI->getOperand(BaseOpIdx).getReg();
    1187       66234 :   unsigned OpsNum = MI->getDesc().getNumOperands();
    1188       66234 :   unsigned OtherOpIdx = MI->getDesc().getNumDefs();
    1189      156391 :   for (; OtherOpIdx < OpsNum; OtherOpIdx++) {
    1190             :     // The call of findCommutedOpIndices below only checks if BaseOpIdx
    1191             :     // and OtherOpIdx are commutable, it does not really search for
    1192             :     // other commutable operands and does not change the values of passed
    1193             :     // variables.
    1194      188213 :     if (OtherOpIdx == BaseOpIdx || !MI->getOperand(OtherOpIdx).isReg() ||
    1195       36703 :         !TII->findCommutedOpIndices(*MI, BaseOpIdx, OtherOpIdx))
    1196       41584 :       continue;
    1197             : 
    1198       61824 :     unsigned OtherOpReg = MI->getOperand(OtherOpIdx).getReg();
    1199       30912 :     bool AggressiveCommute = false;
    1200             : 
    1201             :     // If OtherOp dies but BaseOp does not, swap the OtherOp and BaseOp
    1202             :     // operands. This makes the live ranges of DstOp and OtherOp joinable.
    1203             :     bool DoCommute =
    1204       30912 :         !BaseOpKilled && isKilled(*MI, OtherOpReg, MRI, TII, LIS, false);
    1205             : 
    1206       27653 :     if (!DoCommute &&
    1207       27653 :         isProfitableToCommute(DstOpReg, BaseOpReg, OtherOpReg, MI, Dist)) {
    1208             :       DoCommute = true;
    1209             :       AggressiveCommute = true;
    1210             :     }
    1211             : 
    1212             :     // If it's profitable to commute, try to do so.
    1213       23307 :     if (DoCommute && commuteInstruction(MI, DstOpIdx, BaseOpIdx, OtherOpIdx,
    1214             :                                         Dist)) {
    1215             :       ++NumCommuted;
    1216             :       if (AggressiveCommute)
    1217             :         ++NumAggrCommuted;
    1218             :       return true;
    1219             :     }
    1220             :   }
    1221             :   return false;
    1222             : }
    1223             : 
    1224             : /// For the case where an instruction has a single pair of tied register
    1225             : /// operands, attempt some transformations that may either eliminate the tied
    1226             : /// operands or improve the opportunities for coalescing away the register copy.
    1227             : /// Returns true if no copy needs to be inserted to untie mi's operands
    1228             : /// (either because they were untied, or because mi was rescheduled, and will
    1229             : /// be visited again later). If the shouldOnlyCommute flag is true, only
    1230             : /// instruction commutation is attempted.
    1231      214347 : bool TwoAddressInstructionPass::
    1232             : tryInstructionTransform(MachineBasicBlock::iterator &mi,
    1233             :                         MachineBasicBlock::iterator &nmi,
    1234             :                         unsigned SrcIdx, unsigned DstIdx,
    1235             :                         unsigned Dist, bool shouldOnlyCommute) {
    1236      214347 :   if (OptLevel == CodeGenOpt::None)
    1237             :     return false;
    1238             : 
    1239      211741 :   MachineInstr &MI = *mi;
    1240      423482 :   unsigned regA = MI.getOperand(DstIdx).getReg();
    1241      423482 :   unsigned regB = MI.getOperand(SrcIdx).getReg();
    1242             : 
    1243             :   assert(TargetRegisterInfo::isVirtualRegister(regB) &&
    1244             :          "cannot make instruction into two-address form");
    1245      211741 :   bool regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
    1246             : 
    1247      211741 :   if (TargetRegisterInfo::isVirtualRegister(regA))
    1248      211722 :     scanUses(regA);
    1249             : 
    1250      211741 :   bool Commuted = tryInstructionCommute(&MI, DstIdx, SrcIdx, regBKilled, Dist);
    1251             : 
    1252             :   // If the instruction is convertible to 3 Addr, instead
    1253             :   // of returning try 3 Addr transformation aggresively and
    1254             :   // use this variable to check later. Because it might be better.
    1255             :   // For example, we can just use `leal (%rsi,%rdi), %eax` and `ret`
    1256             :   // instead of the following code.
    1257             :   //   addl     %esi, %edi
    1258             :   //   movl     %edi, %eax
    1259             :   //   ret
    1260      222600 :   if (Commuted && !MI.isConvertibleTo3Addr())
    1261             :     return false;
    1262             : 
    1263      202535 :   if (shouldOnlyCommute)
    1264             :     return false;
    1265             : 
    1266             :   // If there is one more use of regB later in the same MBB, consider
    1267             :   // re-schedule this MI below it.
    1268      403028 :   if (!Commuted && EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) {
    1269             :     ++NumReSchedDowns;
    1270             :     return true;
    1271             :   }
    1272             : 
    1273             :   // If we commuted, regB may have changed so we should re-sample it to avoid
    1274             :   // confusing the three address conversion below.
    1275      201692 :   if (Commuted) {
    1276        3036 :     regB = MI.getOperand(SrcIdx).getReg();
    1277        1518 :     regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
    1278             :   }
    1279             : 
    1280      201692 :   if (MI.isConvertibleTo3Addr()) {
    1281             :     // This instruction is potentially convertible to a true
    1282             :     // three-address instruction.  Check if it is profitable.
    1283       27754 :     if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
    1284             :       // Try to convert it.
    1285        6664 :       if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
    1286             :         ++NumConvertedTo3Addr;
    1287             :         return true; // Done with this instruction.
    1288             :       }
    1289             :     }
    1290             :   }
    1291             : 
    1292             :   // Return if it is commuted but 3 addr conversion is failed.
    1293      196691 :   if (Commuted)
    1294             :     return false;
    1295             : 
    1296             :   // If there is one more use of regB later in the same MBB, consider
    1297             :   // re-schedule it before this MI if it's legal.
    1298      195255 :   if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) {
    1299             :     ++NumReSchedUps;
    1300             :     return true;
    1301             :   }
    1302             : 
    1303             :   // If this is an instruction with a load folded into it, try unfolding
    1304             :   // the load, e.g. avoid this:
    1305             :   //   movq %rdx, %rcx
    1306             :   //   addq (%rax), %rcx
    1307             :   // in favor of this:
    1308             :   //   movq (%rax), %rcx
    1309             :   //   addq %rdx, %rcx
    1310             :   // because it's preferable to schedule a load than a register copy.
    1311      195097 :   if (MI.mayLoad() && !regBKilled) {
    1312             :     // Determine if a load can be unfolded.
    1313             :     unsigned LoadRegIndex;
    1314             :     unsigned NewOpc =
    1315        2492 :       TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
    1316             :                                       /*UnfoldLoad=*/true,
    1317             :                                       /*UnfoldStore=*/false,
    1318        4984 :                                       &LoadRegIndex);
    1319        2492 :     if (NewOpc != 0) {
    1320        3988 :       const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
    1321        1994 :       if (UnfoldMCID.getNumDefs() == 1) {
    1322             :         // Unfold the load.
    1323             :         DEBUG(dbgs() << "2addr:   UNFOLDING: " << MI);
    1324             :         const TargetRegisterClass *RC =
    1325        3988 :           TRI->getAllocatableClass(
    1326        3988 :             TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
    1327        1994 :         unsigned Reg = MRI->createVirtualRegister(RC);
    1328        3988 :         SmallVector<MachineInstr *, 2> NewMIs;
    1329        3988 :         if (!TII->unfoldMemoryOperand(*MF, MI, Reg,
    1330             :                                       /*UnfoldLoad=*/true,
    1331        1994 :                                       /*UnfoldStore=*/false, NewMIs)) {
    1332             :           DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
    1333           0 :           return false;
    1334             :         }
    1335             :         assert(NewMIs.size() == 2 &&
    1336             :                "Unfolded a load into multiple instructions!");
    1337             :         // The load was previously folded, so this is the only use.
    1338        1994 :         NewMIs[1]->addRegisterKilled(Reg, TRI);
    1339             : 
    1340             :         // Tentatively insert the instructions into the block so that they
    1341             :         // look "normal" to the transformation logic.
    1342        5982 :         MBB->insert(mi, NewMIs[0]);
    1343        5982 :         MBB->insert(mi, NewMIs[1]);
    1344             : 
    1345             :         DEBUG(dbgs() << "2addr:    NEW LOAD: " << *NewMIs[0]
    1346             :                      << "2addr:    NEW INST: " << *NewMIs[1]);
    1347             : 
    1348             :         // Transform the instruction, now that it no longer has a load.
    1349        1994 :         unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
    1350        1994 :         unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
    1351        3988 :         MachineBasicBlock::iterator NewMI = NewMIs[1];
    1352             :         bool TransformResult =
    1353        1994 :           tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true);
    1354             :         (void)TransformResult;
    1355             :         assert(!TransformResult &&
    1356             :                "tryInstructionTransform() should return false.");
    1357        5982 :         if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
    1358             :           // Success, or at least we made an improvement. Keep the unfolded
    1359             :           // instructions and discard the original.
    1360        1868 :           if (LV) {
    1361       15185 :             for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
    1362       26644 :               MachineOperand &MO = MI.getOperand(i);
    1363       22804 :               if (MO.isReg() &&
    1364       18964 :                   TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
    1365        4785 :                 if (MO.isUse()) {
    1366        2922 :                   if (MO.isKill()) {
    1367         160 :                     if (NewMIs[0]->killsRegister(MO.getReg()))
    1368         126 :                       LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[0]);
    1369             :                     else {
    1370             :                       assert(NewMIs[1]->killsRegister(MO.getReg()) &&
    1371             :                              "Kill missing after load unfold!");
    1372          34 :                       LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[1]);
    1373             :                     }
    1374             :                   }
    1375        1863 :                 } else if (LV->removeVirtualRegisterDead(MO.getReg(), MI)) {
    1376           0 :                   if (NewMIs[1]->registerDefIsDead(MO.getReg()))
    1377           0 :                     LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[1]);
    1378             :                   else {
    1379             :                     assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
    1380             :                            "Dead flag missing after load unfold!");
    1381           0 :                     LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[0]);
    1382             :                   }
    1383             :                 }
    1384             :               }
    1385             :             }
    1386        3726 :             LV->addVirtualRegisterKilled(Reg, *NewMIs[1]);
    1387             :           }
    1388             : 
    1389        3736 :           SmallVector<unsigned, 4> OrigRegs;
    1390        1868 :           if (LIS) {
    1391           0 :             for (const MachineOperand &MO : MI.operands()) {
    1392           0 :               if (MO.isReg())
    1393           0 :                 OrigRegs.push_back(MO.getReg());
    1394             :             }
    1395             :           }
    1396             : 
    1397        1868 :           MI.eraseFromParent();
    1398             : 
    1399             :           // Update LiveIntervals.
    1400        1868 :           if (LIS) {
    1401           0 :             MachineBasicBlock::iterator Begin(NewMIs[0]);
    1402           0 :             MachineBasicBlock::iterator End(NewMIs[1]);
    1403           0 :             LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs);
    1404             :           }
    1405             : 
    1406        3736 :           mi = NewMIs[1];
    1407             :         } else {
    1408             :           // Transforming didn't eliminate the tie and didn't lead to an
    1409             :           // improvement. Clean up the unfolded instructions and keep the
    1410             :           // original.
    1411             :           DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
    1412         126 :           NewMIs[0]->eraseFromParent();
    1413         126 :           NewMIs[1]->eraseFromParent();
    1414             :         }
    1415             :       }
    1416             :     }
    1417             :   }
    1418             : 
    1419             :   return false;
    1420             : }
    1421             : 
    1422             : // Collect tied operands of MI that need to be handled.
    1423             : // Rewrite trivial cases immediately.
    1424             : // Return true if any tied operands where found, including the trivial ones.
    1425     3985447 : bool TwoAddressInstructionPass::
    1426             : collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
    1427     3985447 :   const MCInstrDesc &MCID = MI->getDesc();
    1428     3985447 :   bool AnyOps = false;
    1429     3985447 :   unsigned NumOps = MI->getNumOperands();
    1430             : 
    1431    19524942 :   for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
    1432    15539495 :     unsigned DstIdx = 0;
    1433    15539495 :     if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
    1434    30633577 :       continue;
    1435      231464 :     AnyOps = true;
    1436      462928 :     MachineOperand &SrcMO = MI->getOperand(SrcIdx);
    1437      462928 :     MachineOperand &DstMO = MI->getOperand(DstIdx);
    1438      231464 :     unsigned SrcReg = SrcMO.getReg();
    1439      231464 :     unsigned DstReg = DstMO.getReg();
    1440             :     // Tied constraint already satisfied?
    1441      231464 :     if (SrcReg == DstReg)
    1442          47 :       continue;
    1443             : 
    1444             :     assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
    1445             : 
    1446             :     // Deal with <undef> uses immediately - simply rewrite the src operand.
    1447      248885 :     if (SrcMO.isUndef() && !DstMO.getSubReg()) {
    1448             :       // Constrain the DstReg register class if required.
    1449       17468 :       if (TargetRegisterInfo::isVirtualRegister(DstReg))
    1450       52404 :         if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
    1451       34936 :                                                              TRI, *MF))
    1452         987 :           MRI->constrainRegClass(DstReg, RC);
    1453       17468 :       SrcMO.setReg(DstReg);
    1454       17468 :       SrcMO.setSubReg(0);
    1455             :       DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
    1456       17468 :       continue;
    1457             :     }
    1458      427898 :     TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
    1459             :   }
    1460     3985447 :   return AnyOps;
    1461             : }
    1462             : 
    1463             : // Process a list of tied MI operands that all use the same source register.
    1464             : // The tied pairs are of the form (SrcIdx, DstIdx).
    1465             : void
    1466      208173 : TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
    1467             :                                             TiedPairList &TiedPairs,
    1468             :                                             unsigned &Dist) {
    1469      208173 :   bool IsEarlyClobber = false;
    1470      624555 :   for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
    1471      624627 :     const MachineOperand &DstMO = MI->getOperand(TiedPairs[tpi].second);
    1472      208209 :     IsEarlyClobber |= DstMO.isEarlyClobber();
    1473             :   }
    1474             : 
    1475             :   bool RemovedKillFlag = false;
    1476             :   bool AllUsesCopied = true;
    1477             :   unsigned LastCopiedReg = 0;
    1478             :   SlotIndex LastCopyIdx;
    1479             :   unsigned RegB = 0;
    1480             :   unsigned SubRegB = 0;
    1481      624591 :   for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
    1482      416418 :     unsigned SrcIdx = TiedPairs[tpi].first;
    1483      416418 :     unsigned DstIdx = TiedPairs[tpi].second;
    1484             : 
    1485      416418 :     const MachineOperand &DstMO = MI->getOperand(DstIdx);
    1486      208209 :     unsigned RegA = DstMO.getReg();
    1487             : 
    1488             :     // Grab RegB from the instruction because it may have changed if the
    1489             :     // instruction was commuted.
    1490      416418 :     RegB = MI->getOperand(SrcIdx).getReg();
    1491      416418 :     SubRegB = MI->getOperand(SrcIdx).getSubReg();
    1492             : 
    1493      208209 :     if (RegA == RegB) {
    1494             :       // The register is tied to multiple destinations (or else we would
    1495             :       // not have continued this far), but this use of the register
    1496             :       // already matches the tied destination.  Leave it.
    1497           0 :       AllUsesCopied = false;
    1498           0 :       continue;
    1499             :     }
    1500      208209 :     LastCopiedReg = RegA;
    1501             : 
    1502             :     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
    1503             :            "cannot make instruction into two-address form");
    1504             : 
    1505             : #ifndef NDEBUG
    1506             :     // First, verify that we don't have a use of "a" in the instruction
    1507             :     // (a = b + a for example) because our transformation will not
    1508             :     // work. This should never occur because we are in SSA form.
    1509             :     for (unsigned i = 0; i != MI->getNumOperands(); ++i)
    1510             :       assert(i == DstIdx ||
    1511             :              !MI->getOperand(i).isReg() ||
    1512             :              MI->getOperand(i).getReg() != RegA);
    1513             : #endif
    1514             : 
    1515             :     // Emit a copy.
    1516      208209 :     MachineInstrBuilder MIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
    1517      832836 :                                       TII->get(TargetOpcode::COPY), RegA);
    1518             :     // If this operand is folding a truncation, the truncation now moves to the
    1519             :     // copy so that the register classes remain valid for the operands.
    1520      208209 :     MIB.addReg(RegB, 0, SubRegB);
    1521      416418 :     const TargetRegisterClass *RC = MRI->getRegClass(RegB);
    1522      208209 :     if (SubRegB) {
    1523           0 :       if (TargetRegisterInfo::isVirtualRegister(RegA)) {
    1524             :         assert(TRI->getMatchingSuperRegClass(RC, MRI->getRegClass(RegA),
    1525             :                                              SubRegB) &&
    1526             :                "tied subregister must be a truncation");
    1527             :         // The superreg class will not be used to constrain the subreg class.
    1528           0 :         RC = nullptr;
    1529             :       }
    1530             :       else {
    1531             :         assert(TRI->getMatchingSuperReg(RegA, SubRegB, MRI->getRegClass(RegB))
    1532             :                && "tied subregister must be a truncation");
    1533             :       }
    1534             :     }
    1535             : 
    1536             :     // Update DistanceMap.
    1537      416418 :     MachineBasicBlock::iterator PrevMI = MI;
    1538      208209 :     --PrevMI;
    1539      832836 :     DistanceMap.insert(std::make_pair(&*PrevMI, Dist));
    1540      416418 :     DistanceMap[MI] = ++Dist;
    1541             : 
    1542      208209 :     if (LIS) {
    1543           0 :       LastCopyIdx = LIS->InsertMachineInstrInMaps(*PrevMI).getRegSlot();
    1544             : 
    1545           0 :       if (TargetRegisterInfo::isVirtualRegister(RegA)) {
    1546           0 :         LiveInterval &LI = LIS->getInterval(RegA);
    1547           0 :         VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
    1548             :         SlotIndex endIdx =
    1549           0 :             LIS->getInstructionIndex(*MI).getRegSlot(IsEarlyClobber);
    1550           0 :         LI.addSegment(LiveInterval::Segment(LastCopyIdx, endIdx, VNI));
    1551             :       }
    1552             :     }
    1553             : 
    1554             :     DEBUG(dbgs() << "\t\tprepend:\t" << *MIB);
    1555             : 
    1556      416418 :     MachineOperand &MO = MI->getOperand(SrcIdx);
    1557             :     assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
    1558             :            "inconsistent operand info for 2-reg pass");
    1559      208209 :     if (MO.isKill()) {
    1560      185690 :       MO.setIsKill(false);
    1561      185690 :       RemovedKillFlag = true;
    1562             :     }
    1563             : 
    1564             :     // Make sure regA is a legal regclass for the SrcIdx operand.
    1565      624573 :     if (TargetRegisterInfo::isVirtualRegister(RegA) &&
    1566      208155 :         TargetRegisterInfo::isVirtualRegister(RegB))
    1567      208155 :       MRI->constrainRegClass(RegA, RC);
    1568      208209 :     MO.setReg(RegA);
    1569             :     // The getMatchingSuper asserts guarantee that the register class projected
    1570             :     // by SubRegB is compatible with RegA with no subregister. So regardless of
    1571             :     // whether the dest oper writes a subreg, the source oper should not.
    1572      208209 :     MO.setSubReg(0);
    1573             : 
    1574             :     // Propagate SrcRegMap.
    1575      416418 :     SrcRegMap[RegA] = RegB;
    1576             :   }
    1577             : 
    1578      208173 :   if (AllUsesCopied) {
    1579      208173 :     if (!IsEarlyClobber) {
    1580             :       // Replace other (un-tied) uses of regB with LastCopiedReg.
    1581     1201650 :       for (MachineOperand &MO : MI->operands()) {
    1582      792337 :         if (MO.isReg() && MO.getReg() == RegB &&
    1583        2515 :             MO.isUse()) {
    1584        2515 :           if (MO.isKill()) {
    1585          96 :             MO.setIsKill(false);
    1586          96 :             RemovedKillFlag = true;
    1587             :           }
    1588        2515 :           MO.setReg(LastCopiedReg);
    1589        2515 :           MO.setSubReg(MO.getSubReg());
    1590             :         }
    1591             :       }
    1592             :     }
    1593             : 
    1594             :     // Update live variables for regB.
    1595      208173 :     if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(*MI)) {
    1596      371248 :       MachineBasicBlock::iterator PrevMI = MI;
    1597      185624 :       --PrevMI;
    1598      371248 :       LV->addVirtualRegisterKilled(RegB, *PrevMI);
    1599             :     }
    1600             : 
    1601             :     // Update LiveIntervals.
    1602      208173 :     if (LIS) {
    1603           0 :       LiveInterval &LI = LIS->getInterval(RegB);
    1604           0 :       SlotIndex MIIdx = LIS->getInstructionIndex(*MI);
    1605           0 :       LiveInterval::const_iterator I = LI.find(MIIdx);
    1606             :       assert(I != LI.end() && "RegB must be live-in to use.");
    1607             : 
    1608           0 :       SlotIndex UseIdx = MIIdx.getRegSlot(IsEarlyClobber);
    1609           0 :       if (I->end == UseIdx)
    1610           0 :         LI.removeSegment(LastCopyIdx, UseIdx);
    1611             :     }
    1612             : 
    1613           0 :   } else if (RemovedKillFlag) {
    1614             :     // Some tied uses of regB matched their destination registers, so
    1615             :     // regB is still used in this instruction, but a kill flag was
    1616             :     // removed from a different tied use of regB, so now we need to add
    1617             :     // a kill flag to one of the remaining uses of regB.
    1618           0 :     for (MachineOperand &MO : MI->operands()) {
    1619           0 :       if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
    1620             :         MO.setIsKill(true);
    1621             :         break;
    1622             :       }
    1623             :     }
    1624             :   }
    1625      208173 : }
    1626             : 
    1627             : /// Reduce two-address instructions to two operands.
    1628      142751 : bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
    1629      142751 :   MF = &Func;
    1630      142751 :   const TargetMachine &TM = MF->getTarget();
    1631      142751 :   MRI = &MF->getRegInfo();
    1632      142751 :   TII = MF->getSubtarget().getInstrInfo();
    1633      142751 :   TRI = MF->getSubtarget().getRegisterInfo();
    1634      142751 :   InstrItins = MF->getSubtarget().getInstrItineraryData();
    1635      142751 :   LV = getAnalysisIfAvailable<LiveVariables>();
    1636      142751 :   LIS = getAnalysisIfAvailable<LiveIntervals>();
    1637      142751 :   if (auto *AAPass = getAnalysisIfAvailable<AAResultsWrapperPass>())
    1638      136412 :     AA = &AAPass->getAAResults();
    1639             :   else
    1640        6339 :     AA = nullptr;
    1641      142751 :   OptLevel = TM.getOptLevel();
    1642             : 
    1643      142751 :   bool MadeChange = false;
    1644             : 
    1645             :   DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
    1646             :   DEBUG(dbgs() << "********** Function: "
    1647             :         << MF->getName() << '\n');
    1648             : 
    1649             :   // This pass takes the function out of SSA form.
    1650      285502 :   MRI->leaveSSA();
    1651             : 
    1652      285502 :   TiedOperandMap TiedOperands;
    1653      428253 :   for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
    1654      436291 :        MBBI != MBBE; ++MBBI) {
    1655      293540 :     MBB = &*MBBI;
    1656      293540 :     unsigned Dist = 0;
    1657      293540 :     DistanceMap.clear();
    1658      293540 :     SrcRegMap.clear();
    1659      293540 :     DstRegMap.clear();
    1660      293540 :     Processed.clear();
    1661      880620 :     for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
    1662     4297055 :          mi != me; ) {
    1663     4003515 :       MachineBasicBlock::iterator nmi = std::next(mi);
    1664     8025098 :       if (mi->isDebugValue()) {
    1665       18068 :         mi = nmi;
    1666     3796802 :         continue;
    1667             :       }
    1668             : 
    1669             :       // Expand REG_SEQUENCE instructions. This will position mi at the first
    1670             :       // expanded instruction.
    1671     3985447 :       if (mi->isRegSequence())
    1672       42661 :         eliminateRegSequence(mi);
    1673             : 
    1674    15941788 :       DistanceMap.insert(std::make_pair(&*mi, ++Dist));
    1675             : 
    1676     3985447 :       processCopy(&*mi);
    1677             : 
    1678             :       // First scan through all the tied register uses in this instruction
    1679             :       // and record a list of pairs of tied operands for each register.
    1680     7740373 :       if (!collectTiedOperands(&*mi, TiedOperands)) {
    1681     3754926 :         mi = nmi;
    1682     3754926 :         continue;
    1683             :       }
    1684             : 
    1685      230521 :       ++NumTwoAddressInstrs;
    1686      230521 :       MadeChange = true;
    1687             :       DEBUG(dbgs() << '\t' << *mi);
    1688             : 
    1689             :       // If the instruction has a single pair of tied operands, try some
    1690             :       // transformations that may either eliminate the tied operands or
    1691             :       // improve the opportunities for coalescing away the register copy.
    1692      230521 :       if (TiedOperands.size() == 1) {
    1693             :         SmallVectorImpl<std::pair<unsigned, unsigned> > &TiedPairs
    1694      212371 :           = TiedOperands.begin()->second;
    1695      424742 :         if (TiedPairs.size() == 1) {
    1696      424706 :           unsigned SrcIdx = TiedPairs[0].first;
    1697      424706 :           unsigned DstIdx = TiedPairs[0].second;
    1698      424706 :           unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
    1699      424706 :           unsigned DstReg = mi->getOperand(DstIdx).getReg();
    1700      430446 :           if (SrcReg != DstReg &&
    1701      212353 :               tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) {
    1702             :             // The tied operands have been eliminated or shifted further down
    1703             :             // the block to ease elimination. Continue processing with 'nmi'.
    1704        5740 :             TiedOperands.clear();
    1705        5740 :             mi = nmi;
    1706        5740 :             continue;
    1707             :           }
    1708             :         }
    1709             :       }
    1710             : 
    1711             :       // Now iterate over the information collected above.
    1712      882516 :       for (auto &TO : TiedOperands) {
    1713      416346 :         processTiedPairs(&*mi, TO.second, Dist);
    1714             :         DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
    1715             :       }
    1716             : 
    1717             :       // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
    1718      449562 :       if (mi->isInsertSubreg()) {
    1719             :         // From %reg = INSERT_SUBREG %reg, %subreg, subidx
    1720             :         // To   %reg:subidx = COPY %subreg
    1721       38564 :         unsigned SubIdx = mi->getOperand(3).getImm();
    1722       38564 :         mi->RemoveOperand(3);
    1723             :         assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
    1724       77128 :         mi->getOperand(0).setSubReg(SubIdx);
    1725      154256 :         mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
    1726       38564 :         mi->RemoveOperand(1);
    1727       77128 :         mi->setDesc(TII->get(TargetOpcode::COPY));
    1728             :         DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
    1729             :       }
    1730             : 
    1731             :       // Clear TiedOperands here instead of at the top of the loop
    1732             :       // since most instructions do not have tied operands.
    1733      224781 :       TiedOperands.clear();
    1734      224781 :       mi = nmi;
    1735             :     }
    1736             :   }
    1737             : 
    1738      142751 :   if (LIS)
    1739           0 :     MF->verify(this, "After two-address instruction pass");
    1740             : 
    1741      142751 :   return MadeChange;
    1742             : }
    1743             : 
    1744             : /// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process.
    1745             : ///
    1746             : /// The instruction is turned into a sequence of sub-register copies:
    1747             : ///
    1748             : ///   %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1
    1749             : ///
    1750             : /// Becomes:
    1751             : ///
    1752             : ///   %dst:ssub0<def,undef> = COPY %v1
    1753             : ///   %dst:ssub1<def> = COPY %v2
    1754             : ///
    1755       42661 : void TwoAddressInstructionPass::
    1756             : eliminateRegSequence(MachineBasicBlock::iterator &MBBI) {
    1757       42661 :   MachineInstr &MI = *MBBI;
    1758       42661 :   unsigned DstReg = MI.getOperand(0).getReg();
    1759      127983 :   if (MI.getOperand(0).getSubReg() ||
    1760      127983 :       TargetRegisterInfo::isPhysicalRegister(DstReg) ||
    1761       42661 :       !(MI.getNumOperands() & 1)) {
    1762             :     DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << MI);
    1763           0 :     llvm_unreachable(nullptr);
    1764             :   }
    1765             : 
    1766       85322 :   SmallVector<unsigned, 4> OrigRegs;
    1767       42661 :   if (LIS) {
    1768           0 :     OrigRegs.push_back(MI.getOperand(0).getReg());
    1769           0 :     for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2)
    1770           0 :       OrigRegs.push_back(MI.getOperand(i).getReg());
    1771             :   }
    1772             : 
    1773       42661 :   bool DefEmitted = false;
    1774      169936 :   for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2) {
    1775      254550 :     MachineOperand &UseMO = MI.getOperand(i);
    1776      127275 :     unsigned SrcReg = UseMO.getReg();
    1777      254550 :     unsigned SubIdx = MI.getOperand(i+1).getImm();
    1778             :     // Nothing needs to be inserted for <undef> operands.
    1779      127275 :     if (UseMO.isUndef())
    1780        3522 :       continue;
    1781             : 
    1782             :     // Defer any kill flag to the last operand using SrcReg. Otherwise, we
    1783             :     // might insert a COPY that uses SrcReg after is was killed.
    1784      123753 :     bool isKill = UseMO.isKill();
    1785      123753 :     if (isKill)
    1786      231563 :       for (unsigned j = i + 2; j < e; j += 2)
    1787      262046 :         if (MI.getOperand(j).getReg() == SrcReg) {
    1788       12538 :           MI.getOperand(j).setIsKill();
    1789        6269 :           UseMO.setIsKill(false);
    1790        6269 :           isKill = false;
    1791        6269 :           break;
    1792             :         }
    1793             : 
    1794             :     // Insert the sub-register copy.
    1795      247506 :     MachineInstr *CopyMI = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
    1796      371259 :                                    TII->get(TargetOpcode::COPY))
    1797      123753 :                                .addReg(DstReg, RegState::Define, SubIdx)
    1798      123753 :                                .add(UseMO);
    1799             : 
    1800             :     // The first def needs an <undef> flag because there is no live register
    1801             :     // before it.
    1802      123753 :     if (!DefEmitted) {
    1803       85322 :       CopyMI->getOperand(0).setIsUndef(true);
    1804             :       // Return an iterator pointing to the first inserted instr.
    1805       42661 :       MBBI = CopyMI;
    1806             :     }
    1807      123753 :     DefEmitted = true;
    1808             : 
    1809             :     // Update LiveVariables' kill info.
    1810      224220 :     if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
    1811      100467 :       LV->replaceKillInstruction(SrcReg, MI, *CopyMI);
    1812             : 
    1813             :     DEBUG(dbgs() << "Inserted: " << *CopyMI);
    1814             :   }
    1815             : 
    1816             :   MachineBasicBlock::iterator EndMBBI =
    1817       85322 :       std::next(MachineBasicBlock::iterator(MI));
    1818             : 
    1819       42661 :   if (!DefEmitted) {
    1820             :     DEBUG(dbgs() << "Turned: " << MI << " into an IMPLICIT_DEF");
    1821           0 :     MI.setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
    1822           0 :     for (int j = MI.getNumOperands() - 1, ee = 0; j > ee; --j)
    1823           0 :       MI.RemoveOperand(j);
    1824             :   } else {
    1825             :     DEBUG(dbgs() << "Eliminated: " << MI);
    1826       42661 :     MI.eraseFromParent();
    1827             :   }
    1828             : 
    1829             :   // Udpate LiveIntervals.
    1830       42661 :   if (LIS)
    1831           0 :     LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs);
    1832      259579 : }

Generated by: LCOV version 1.13