10b57cec5SDimitry Andric //===- TwoAddressInstructionPass.cpp - Two-Address instruction pass -------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This file implements the TwoAddress instruction pass which is used 100b57cec5SDimitry Andric // by most register allocators. Two-Address instructions are rewritten 110b57cec5SDimitry Andric // from: 120b57cec5SDimitry Andric // 130b57cec5SDimitry Andric // A = B op C 140b57cec5SDimitry Andric // 150b57cec5SDimitry Andric // to: 160b57cec5SDimitry Andric // 170b57cec5SDimitry Andric // A = B 180b57cec5SDimitry Andric // A op= C 190b57cec5SDimitry Andric // 200b57cec5SDimitry Andric // Note that if a register allocator chooses to use this pass, that it 210b57cec5SDimitry Andric // has to be capable of handling the non-SSA nature of these rewritten 220b57cec5SDimitry Andric // virtual registers. 230b57cec5SDimitry Andric // 240b57cec5SDimitry Andric // It is also worth noting that the duplicate operand of the two 250b57cec5SDimitry Andric // address instruction is removed. 260b57cec5SDimitry Andric // 270b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 280b57cec5SDimitry Andric 29*0fca6ea1SDimitry Andric #include "llvm/CodeGen/TwoAddressInstructionPass.h" 300b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h" 310b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h" 320b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h" 330b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h" 340b57cec5SDimitry Andric #include "llvm/ADT/iterator_range.h" 350b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h" 360b57cec5SDimitry Andric #include "llvm/CodeGen/LiveInterval.h" 370b57cec5SDimitry Andric #include "llvm/CodeGen/LiveIntervals.h" 380b57cec5SDimitry Andric #include "llvm/CodeGen/LiveVariables.h" 390b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h" 40*0fca6ea1SDimitry Andric #include "llvm/CodeGen/MachineDominators.h" 410b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h" 420b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h" 430b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h" 440b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h" 45*0fca6ea1SDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h" 460b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h" 470b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h" 480b57cec5SDimitry Andric #include "llvm/CodeGen/Passes.h" 490b57cec5SDimitry Andric #include "llvm/CodeGen/SlotIndexes.h" 500b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h" 510b57cec5SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h" 520b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h" 530b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h" 540b57cec5SDimitry Andric #include "llvm/MC/MCInstrDesc.h" 550b57cec5SDimitry Andric #include "llvm/Pass.h" 560b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h" 570b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h" 580b57cec5SDimitry Andric #include "llvm/Support/Debug.h" 590b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 600b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 610b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h" 620b57cec5SDimitry Andric #include <cassert> 630b57cec5SDimitry Andric #include <iterator> 640b57cec5SDimitry Andric #include <utility> 650b57cec5SDimitry Andric 660b57cec5SDimitry Andric using namespace llvm; 670b57cec5SDimitry Andric 680b57cec5SDimitry Andric #define DEBUG_TYPE "twoaddressinstruction" 690b57cec5SDimitry Andric 700b57cec5SDimitry Andric STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions"); 710b57cec5SDimitry Andric STATISTIC(NumCommuted , "Number of instructions commuted to coalesce"); 720b57cec5SDimitry Andric STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted"); 730b57cec5SDimitry Andric STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address"); 740b57cec5SDimitry Andric STATISTIC(NumReSchedUps, "Number of instructions re-scheduled up"); 750b57cec5SDimitry Andric STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down"); 760b57cec5SDimitry Andric 770b57cec5SDimitry Andric // Temporary flag to disable rescheduling. 780b57cec5SDimitry Andric static cl::opt<bool> 790b57cec5SDimitry Andric EnableRescheduling("twoaddr-reschedule", 800b57cec5SDimitry Andric cl::desc("Coalesce copies by rescheduling (default=true)"), 810b57cec5SDimitry Andric cl::init(true), cl::Hidden); 820b57cec5SDimitry Andric 830b57cec5SDimitry Andric // Limit the number of dataflow edges to traverse when evaluating the benefit 840b57cec5SDimitry Andric // of commuting operands. 850b57cec5SDimitry Andric static cl::opt<unsigned> MaxDataFlowEdge( 860b57cec5SDimitry Andric "dataflow-edge-limit", cl::Hidden, cl::init(3), 870b57cec5SDimitry Andric cl::desc("Maximum number of dataflow edges to traverse when evaluating " 880b57cec5SDimitry Andric "the benefit of commuting operands")); 890b57cec5SDimitry Andric 900b57cec5SDimitry Andric namespace { 910b57cec5SDimitry Andric 92*0fca6ea1SDimitry Andric class TwoAddressInstructionImpl { 9306c3fb27SDimitry Andric MachineFunction *MF = nullptr; 9406c3fb27SDimitry Andric const TargetInstrInfo *TII = nullptr; 9506c3fb27SDimitry Andric const TargetRegisterInfo *TRI = nullptr; 9606c3fb27SDimitry Andric const InstrItineraryData *InstrItins = nullptr; 9706c3fb27SDimitry Andric MachineRegisterInfo *MRI = nullptr; 9806c3fb27SDimitry Andric LiveVariables *LV = nullptr; 9906c3fb27SDimitry Andric LiveIntervals *LIS = nullptr; 10006c3fb27SDimitry Andric AliasAnalysis *AA = nullptr; 1015f757f3fSDimitry Andric CodeGenOptLevel OptLevel = CodeGenOptLevel::None; 1020b57cec5SDimitry Andric 1030b57cec5SDimitry Andric // The current basic block being processed. 10406c3fb27SDimitry Andric MachineBasicBlock *MBB = nullptr; 1050b57cec5SDimitry Andric 1060b57cec5SDimitry Andric // Keep track the distance of a MI from the start of the current basic block. 1070b57cec5SDimitry Andric DenseMap<MachineInstr*, unsigned> DistanceMap; 1080b57cec5SDimitry Andric 1090b57cec5SDimitry Andric // Set of already processed instructions in the current block. 1100b57cec5SDimitry Andric SmallPtrSet<MachineInstr*, 8> Processed; 1110b57cec5SDimitry Andric 1120b57cec5SDimitry Andric // A map from virtual registers to physical registers which are likely targets 1130b57cec5SDimitry Andric // to be coalesced to due to copies from physical registers to virtual 1140b57cec5SDimitry Andric // registers. e.g. v1024 = move r0. 115e8d8bef9SDimitry Andric DenseMap<Register, Register> SrcRegMap; 1160b57cec5SDimitry Andric 1170b57cec5SDimitry Andric // A map from virtual registers to physical registers which are likely targets 1180b57cec5SDimitry Andric // to be coalesced to due to copies to physical registers from virtual 1190b57cec5SDimitry Andric // registers. e.g. r1 = move v1024. 120e8d8bef9SDimitry Andric DenseMap<Register, Register> DstRegMap; 1210b57cec5SDimitry Andric 1225f757f3fSDimitry Andric MachineInstr *getSingleDef(Register Reg, MachineBasicBlock *BB) const; 123349cc55cSDimitry Andric 124e8d8bef9SDimitry Andric bool isRevCopyChain(Register FromReg, Register ToReg, int Maxlen); 1250b57cec5SDimitry Andric 126e8d8bef9SDimitry Andric bool noUseAfterLastDef(Register Reg, unsigned Dist, unsigned &LastDef); 1270b57cec5SDimitry Andric 1285f757f3fSDimitry Andric bool isCopyToReg(MachineInstr &MI, Register &SrcReg, Register &DstReg, 1295f757f3fSDimitry Andric bool &IsSrcPhys, bool &IsDstPhys) const; 1305f757f3fSDimitry Andric 1315f757f3fSDimitry Andric bool isPlainlyKilled(const MachineInstr *MI, LiveRange &LR) const; 1325f757f3fSDimitry Andric bool isPlainlyKilled(const MachineInstr *MI, Register Reg) const; 1335f757f3fSDimitry Andric bool isPlainlyKilled(const MachineOperand &MO) const; 1345f757f3fSDimitry Andric 1355f757f3fSDimitry Andric bool isKilled(MachineInstr &MI, Register Reg, bool allowFalsePositives) const; 1365f757f3fSDimitry Andric 1375f757f3fSDimitry Andric MachineInstr *findOnlyInterestingUse(Register Reg, MachineBasicBlock *MBB, 1385f757f3fSDimitry Andric bool &IsCopy, Register &DstReg, 1395f757f3fSDimitry Andric bool &IsDstPhys) const; 1405f757f3fSDimitry Andric 1415f757f3fSDimitry Andric bool regsAreCompatible(Register RegA, Register RegB) const; 1425f757f3fSDimitry Andric 1435f757f3fSDimitry Andric void removeMapRegEntry(const MachineOperand &MO, 1445f757f3fSDimitry Andric DenseMap<Register, Register> &RegMap) const; 1455f757f3fSDimitry Andric 1465f757f3fSDimitry Andric void removeClobberedSrcRegMap(MachineInstr *MI); 1475f757f3fSDimitry Andric 1485f757f3fSDimitry Andric bool regOverlapsSet(const SmallVectorImpl<Register> &Set, Register Reg) const; 1495f757f3fSDimitry Andric 150e8d8bef9SDimitry Andric bool isProfitableToCommute(Register RegA, Register RegB, Register RegC, 1510b57cec5SDimitry Andric MachineInstr *MI, unsigned Dist); 1520b57cec5SDimitry Andric 1530b57cec5SDimitry Andric bool commuteInstruction(MachineInstr *MI, unsigned DstIdx, 1540b57cec5SDimitry Andric unsigned RegBIdx, unsigned RegCIdx, unsigned Dist); 1550b57cec5SDimitry Andric 156e8d8bef9SDimitry Andric bool isProfitableToConv3Addr(Register RegA, Register RegB); 1570b57cec5SDimitry Andric 1580b57cec5SDimitry Andric bool convertInstTo3Addr(MachineBasicBlock::iterator &mi, 159e8d8bef9SDimitry Andric MachineBasicBlock::iterator &nmi, Register RegA, 160349cc55cSDimitry Andric Register RegB, unsigned &Dist); 1610b57cec5SDimitry Andric 162e8d8bef9SDimitry Andric bool isDefTooClose(Register Reg, unsigned Dist, MachineInstr *MI); 1630b57cec5SDimitry Andric 1640b57cec5SDimitry Andric bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi, 165e8d8bef9SDimitry Andric MachineBasicBlock::iterator &nmi, Register Reg); 1660b57cec5SDimitry Andric bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi, 167e8d8bef9SDimitry Andric MachineBasicBlock::iterator &nmi, Register Reg); 1680b57cec5SDimitry Andric 1690b57cec5SDimitry Andric bool tryInstructionTransform(MachineBasicBlock::iterator &mi, 1700b57cec5SDimitry Andric MachineBasicBlock::iterator &nmi, 1710b57cec5SDimitry Andric unsigned SrcIdx, unsigned DstIdx, 172349cc55cSDimitry Andric unsigned &Dist, bool shouldOnlyCommute); 1730b57cec5SDimitry Andric 1740b57cec5SDimitry Andric bool tryInstructionCommute(MachineInstr *MI, 1750b57cec5SDimitry Andric unsigned DstOpIdx, 1760b57cec5SDimitry Andric unsigned BaseOpIdx, 1770b57cec5SDimitry Andric bool BaseOpKilled, 1780b57cec5SDimitry Andric unsigned Dist); 179e8d8bef9SDimitry Andric void scanUses(Register DstReg); 1800b57cec5SDimitry Andric 1810b57cec5SDimitry Andric void processCopy(MachineInstr *MI); 1820b57cec5SDimitry Andric 1830b57cec5SDimitry Andric using TiedPairList = SmallVector<std::pair<unsigned, unsigned>, 4>; 1840b57cec5SDimitry Andric using TiedOperandMap = SmallDenseMap<unsigned, TiedPairList>; 1850b57cec5SDimitry Andric 1860b57cec5SDimitry Andric bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&); 1870b57cec5SDimitry Andric void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist); 1880b57cec5SDimitry Andric void eliminateRegSequence(MachineBasicBlock::iterator&); 18981ad6265SDimitry Andric bool processStatepoint(MachineInstr *MI, TiedOperandMap &TiedOperands); 1900b57cec5SDimitry Andric 1910b57cec5SDimitry Andric public: 192*0fca6ea1SDimitry Andric TwoAddressInstructionImpl(MachineFunction &MF, MachineFunctionPass *P); 193*0fca6ea1SDimitry Andric TwoAddressInstructionImpl(MachineFunction &MF, 194*0fca6ea1SDimitry Andric MachineFunctionAnalysisManager &MFAM); 195*0fca6ea1SDimitry Andric void setOptLevel(CodeGenOptLevel Level) { OptLevel = Level; } 196*0fca6ea1SDimitry Andric bool run(); 197*0fca6ea1SDimitry Andric }; 198*0fca6ea1SDimitry Andric 199*0fca6ea1SDimitry Andric class TwoAddressInstructionLegacyPass : public MachineFunctionPass { 200*0fca6ea1SDimitry Andric public: 2010b57cec5SDimitry Andric static char ID; // Pass identification, replacement for typeid 2020b57cec5SDimitry Andric 203*0fca6ea1SDimitry Andric TwoAddressInstructionLegacyPass() : MachineFunctionPass(ID) { 204*0fca6ea1SDimitry Andric initializeTwoAddressInstructionLegacyPassPass( 205*0fca6ea1SDimitry Andric *PassRegistry::getPassRegistry()); 206*0fca6ea1SDimitry Andric } 207*0fca6ea1SDimitry Andric 208*0fca6ea1SDimitry Andric /// Pass entry point. 209*0fca6ea1SDimitry Andric bool runOnMachineFunction(MachineFunction &MF) override { 210*0fca6ea1SDimitry Andric TwoAddressInstructionImpl Impl(MF, this); 211*0fca6ea1SDimitry Andric // Disable optimizations if requested. We cannot skip the whole pass as some 212*0fca6ea1SDimitry Andric // fixups are necessary for correctness. 213*0fca6ea1SDimitry Andric if (skipFunction(MF.getFunction())) 214*0fca6ea1SDimitry Andric Impl.setOptLevel(CodeGenOptLevel::None); 215*0fca6ea1SDimitry Andric return Impl.run(); 2160b57cec5SDimitry Andric } 2170b57cec5SDimitry Andric 2180b57cec5SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 2190b57cec5SDimitry Andric AU.setPreservesCFG(); 2200b57cec5SDimitry Andric AU.addUsedIfAvailable<AAResultsWrapperPass>(); 221*0fca6ea1SDimitry Andric AU.addUsedIfAvailable<LiveVariablesWrapperPass>(); 222*0fca6ea1SDimitry Andric AU.addPreserved<LiveVariablesWrapperPass>(); 223*0fca6ea1SDimitry Andric AU.addPreserved<SlotIndexesWrapperPass>(); 224*0fca6ea1SDimitry Andric AU.addPreserved<LiveIntervalsWrapperPass>(); 2250b57cec5SDimitry Andric AU.addPreservedID(MachineLoopInfoID); 2260b57cec5SDimitry Andric AU.addPreservedID(MachineDominatorsID); 2270b57cec5SDimitry Andric MachineFunctionPass::getAnalysisUsage(AU); 2280b57cec5SDimitry Andric } 2290b57cec5SDimitry Andric }; 2300b57cec5SDimitry Andric 2310b57cec5SDimitry Andric } // end anonymous namespace 2320b57cec5SDimitry Andric 233*0fca6ea1SDimitry Andric PreservedAnalyses 234*0fca6ea1SDimitry Andric TwoAddressInstructionPass::run(MachineFunction &MF, 235*0fca6ea1SDimitry Andric MachineFunctionAnalysisManager &MFAM) { 236*0fca6ea1SDimitry Andric // Disable optimizations if requested. We cannot skip the whole pass as some 237*0fca6ea1SDimitry Andric // fixups are necessary for correctness. 238*0fca6ea1SDimitry Andric TwoAddressInstructionImpl Impl(MF, MFAM); 239*0fca6ea1SDimitry Andric if (MF.getFunction().hasOptNone()) 240*0fca6ea1SDimitry Andric Impl.setOptLevel(CodeGenOptLevel::None); 2410b57cec5SDimitry Andric 242*0fca6ea1SDimitry Andric MFPropsModifier _(*this, MF); 243*0fca6ea1SDimitry Andric bool Changed = Impl.run(); 244*0fca6ea1SDimitry Andric if (!Changed) 245*0fca6ea1SDimitry Andric return PreservedAnalyses::all(); 246*0fca6ea1SDimitry Andric auto PA = getMachineFunctionPassPreservedAnalyses(); 247*0fca6ea1SDimitry Andric PA.preserve<LiveIntervalsAnalysis>(); 248*0fca6ea1SDimitry Andric PA.preserve<LiveVariablesAnalysis>(); 249*0fca6ea1SDimitry Andric PA.preserve<MachineDominatorTreeAnalysis>(); 250*0fca6ea1SDimitry Andric PA.preserve<MachineLoopAnalysis>(); 251*0fca6ea1SDimitry Andric PA.preserve<SlotIndexesAnalysis>(); 252*0fca6ea1SDimitry Andric PA.preserveSet<CFGAnalyses>(); 253*0fca6ea1SDimitry Andric return PA; 254*0fca6ea1SDimitry Andric } 2550b57cec5SDimitry Andric 256*0fca6ea1SDimitry Andric char TwoAddressInstructionLegacyPass::ID = 0; 257*0fca6ea1SDimitry Andric 258*0fca6ea1SDimitry Andric char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionLegacyPass::ID; 259*0fca6ea1SDimitry Andric 260*0fca6ea1SDimitry Andric INITIALIZE_PASS_BEGIN(TwoAddressInstructionLegacyPass, DEBUG_TYPE, 2610b57cec5SDimitry Andric "Two-Address instruction pass", false, false) 2620b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 263*0fca6ea1SDimitry Andric INITIALIZE_PASS_END(TwoAddressInstructionLegacyPass, DEBUG_TYPE, 2640b57cec5SDimitry Andric "Two-Address instruction pass", false, false) 2650b57cec5SDimitry Andric 266*0fca6ea1SDimitry Andric TwoAddressInstructionImpl::TwoAddressInstructionImpl( 267*0fca6ea1SDimitry Andric MachineFunction &Func, MachineFunctionAnalysisManager &MFAM) 268*0fca6ea1SDimitry Andric : MF(&Func), TII(Func.getSubtarget().getInstrInfo()), 269*0fca6ea1SDimitry Andric TRI(Func.getSubtarget().getRegisterInfo()), 270*0fca6ea1SDimitry Andric InstrItins(Func.getSubtarget().getInstrItineraryData()), 271*0fca6ea1SDimitry Andric MRI(&Func.getRegInfo()), 272*0fca6ea1SDimitry Andric LV(MFAM.getCachedResult<LiveVariablesAnalysis>(Func)), 273*0fca6ea1SDimitry Andric LIS(MFAM.getCachedResult<LiveIntervalsAnalysis>(Func)), 274*0fca6ea1SDimitry Andric OptLevel(Func.getTarget().getOptLevel()) { 275*0fca6ea1SDimitry Andric auto &FAM = MFAM.getResult<FunctionAnalysisManagerMachineFunctionProxy>(Func) 276*0fca6ea1SDimitry Andric .getManager(); 277*0fca6ea1SDimitry Andric AA = FAM.getCachedResult<AAManager>(Func.getFunction()); 278*0fca6ea1SDimitry Andric } 279*0fca6ea1SDimitry Andric 280*0fca6ea1SDimitry Andric TwoAddressInstructionImpl::TwoAddressInstructionImpl(MachineFunction &Func, 281*0fca6ea1SDimitry Andric MachineFunctionPass *P) 282*0fca6ea1SDimitry Andric : MF(&Func), TII(Func.getSubtarget().getInstrInfo()), 283*0fca6ea1SDimitry Andric TRI(Func.getSubtarget().getRegisterInfo()), 284*0fca6ea1SDimitry Andric InstrItins(Func.getSubtarget().getInstrItineraryData()), 285*0fca6ea1SDimitry Andric MRI(&Func.getRegInfo()), OptLevel(Func.getTarget().getOptLevel()) { 286*0fca6ea1SDimitry Andric auto *LVWrapper = P->getAnalysisIfAvailable<LiveVariablesWrapperPass>(); 287*0fca6ea1SDimitry Andric LV = LVWrapper ? &LVWrapper->getLV() : nullptr; 288*0fca6ea1SDimitry Andric auto *LISWrapper = P->getAnalysisIfAvailable<LiveIntervalsWrapperPass>(); 289*0fca6ea1SDimitry Andric LIS = LISWrapper ? &LISWrapper->getLIS() : nullptr; 290*0fca6ea1SDimitry Andric if (auto *AAPass = P->getAnalysisIfAvailable<AAResultsWrapperPass>()) 291*0fca6ea1SDimitry Andric AA = &AAPass->getAAResults(); 292*0fca6ea1SDimitry Andric else 293*0fca6ea1SDimitry Andric AA = nullptr; 294*0fca6ea1SDimitry Andric } 295*0fca6ea1SDimitry Andric 2960b57cec5SDimitry Andric /// Return the MachineInstr* if it is the single def of the Reg in current BB. 2975f757f3fSDimitry Andric MachineInstr * 298*0fca6ea1SDimitry Andric TwoAddressInstructionImpl::getSingleDef(Register Reg, 2995f757f3fSDimitry Andric MachineBasicBlock *BB) const { 3000b57cec5SDimitry Andric MachineInstr *Ret = nullptr; 3010b57cec5SDimitry Andric for (MachineInstr &DefMI : MRI->def_instructions(Reg)) { 3020b57cec5SDimitry Andric if (DefMI.getParent() != BB || DefMI.isDebugValue()) 3030b57cec5SDimitry Andric continue; 3040b57cec5SDimitry Andric if (!Ret) 3050b57cec5SDimitry Andric Ret = &DefMI; 3060b57cec5SDimitry Andric else if (Ret != &DefMI) 3070b57cec5SDimitry Andric return nullptr; 3080b57cec5SDimitry Andric } 3090b57cec5SDimitry Andric return Ret; 3100b57cec5SDimitry Andric } 3110b57cec5SDimitry Andric 3120b57cec5SDimitry Andric /// Check if there is a reversed copy chain from FromReg to ToReg: 3130b57cec5SDimitry Andric /// %Tmp1 = copy %Tmp2; 3140b57cec5SDimitry Andric /// %FromReg = copy %Tmp1; 3150b57cec5SDimitry Andric /// %ToReg = add %FromReg ... 3160b57cec5SDimitry Andric /// %Tmp2 = copy %ToReg; 3170b57cec5SDimitry Andric /// MaxLen specifies the maximum length of the copy chain the func 3180b57cec5SDimitry Andric /// can walk through. 319*0fca6ea1SDimitry Andric bool TwoAddressInstructionImpl::isRevCopyChain(Register FromReg, Register ToReg, 3200b57cec5SDimitry Andric int Maxlen) { 321e8d8bef9SDimitry Andric Register TmpReg = FromReg; 3220b57cec5SDimitry Andric for (int i = 0; i < Maxlen; i++) { 3235f757f3fSDimitry Andric MachineInstr *Def = getSingleDef(TmpReg, MBB); 3240b57cec5SDimitry Andric if (!Def || !Def->isCopy()) 3250b57cec5SDimitry Andric return false; 3260b57cec5SDimitry Andric 3270b57cec5SDimitry Andric TmpReg = Def->getOperand(1).getReg(); 3280b57cec5SDimitry Andric 3290b57cec5SDimitry Andric if (TmpReg == ToReg) 3300b57cec5SDimitry Andric return true; 3310b57cec5SDimitry Andric } 3320b57cec5SDimitry Andric return false; 3330b57cec5SDimitry Andric } 3340b57cec5SDimitry Andric 3350b57cec5SDimitry Andric /// Return true if there are no intervening uses between the last instruction 3360b57cec5SDimitry Andric /// in the MBB that defines the specified register and the two-address 3370b57cec5SDimitry Andric /// instruction which is being processed. It also returns the last def location 3380b57cec5SDimitry Andric /// by reference. 339*0fca6ea1SDimitry Andric bool TwoAddressInstructionImpl::noUseAfterLastDef(Register Reg, unsigned Dist, 3400b57cec5SDimitry Andric unsigned &LastDef) { 3410b57cec5SDimitry Andric LastDef = 0; 3420b57cec5SDimitry Andric unsigned LastUse = Dist; 3430b57cec5SDimitry Andric for (MachineOperand &MO : MRI->reg_operands(Reg)) { 3440b57cec5SDimitry Andric MachineInstr *MI = MO.getParent(); 3450b57cec5SDimitry Andric if (MI->getParent() != MBB || MI->isDebugValue()) 3460b57cec5SDimitry Andric continue; 3470b57cec5SDimitry Andric DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI); 3480b57cec5SDimitry Andric if (DI == DistanceMap.end()) 3490b57cec5SDimitry Andric continue; 3500b57cec5SDimitry Andric if (MO.isUse() && DI->second < LastUse) 3510b57cec5SDimitry Andric LastUse = DI->second; 3520b57cec5SDimitry Andric if (MO.isDef() && DI->second > LastDef) 3530b57cec5SDimitry Andric LastDef = DI->second; 3540b57cec5SDimitry Andric } 3550b57cec5SDimitry Andric 3560b57cec5SDimitry Andric return !(LastUse > LastDef && LastUse < Dist); 3570b57cec5SDimitry Andric } 3580b57cec5SDimitry Andric 3590b57cec5SDimitry Andric /// Return true if the specified MI is a copy instruction or an extract_subreg 3600b57cec5SDimitry Andric /// instruction. It also returns the source and destination registers and 3610b57cec5SDimitry Andric /// whether they are physical registers by reference. 362*0fca6ea1SDimitry Andric bool TwoAddressInstructionImpl::isCopyToReg(MachineInstr &MI, Register &SrcReg, 3635f757f3fSDimitry Andric Register &DstReg, bool &IsSrcPhys, 3645f757f3fSDimitry Andric bool &IsDstPhys) const { 3650b57cec5SDimitry Andric SrcReg = 0; 3660b57cec5SDimitry Andric DstReg = 0; 3670b57cec5SDimitry Andric if (MI.isCopy()) { 3680b57cec5SDimitry Andric DstReg = MI.getOperand(0).getReg(); 3690b57cec5SDimitry Andric SrcReg = MI.getOperand(1).getReg(); 3700b57cec5SDimitry Andric } else if (MI.isInsertSubreg() || MI.isSubregToReg()) { 3710b57cec5SDimitry Andric DstReg = MI.getOperand(0).getReg(); 3720b57cec5SDimitry Andric SrcReg = MI.getOperand(2).getReg(); 373e8d8bef9SDimitry Andric } else { 3740b57cec5SDimitry Andric return false; 375e8d8bef9SDimitry Andric } 3760b57cec5SDimitry Andric 377e8d8bef9SDimitry Andric IsSrcPhys = SrcReg.isPhysical(); 378e8d8bef9SDimitry Andric IsDstPhys = DstReg.isPhysical(); 3790b57cec5SDimitry Andric return true; 3800b57cec5SDimitry Andric } 3810b57cec5SDimitry Andric 382*0fca6ea1SDimitry Andric bool TwoAddressInstructionImpl::isPlainlyKilled(const MachineInstr *MI, 3835f757f3fSDimitry Andric LiveRange &LR) const { 3845f757f3fSDimitry Andric // This is to match the kill flag version where undefs don't have kill flags. 3855f757f3fSDimitry Andric if (!LR.hasAtLeastOneValue()) 3865f757f3fSDimitry Andric return false; 3875f757f3fSDimitry Andric 3885f757f3fSDimitry Andric SlotIndex useIdx = LIS->getInstructionIndex(*MI); 3895f757f3fSDimitry Andric LiveInterval::const_iterator I = LR.find(useIdx); 3905f757f3fSDimitry Andric assert(I != LR.end() && "Reg must be live-in to use."); 3915f757f3fSDimitry Andric return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx); 3925f757f3fSDimitry Andric } 3935f757f3fSDimitry Andric 3940b57cec5SDimitry Andric /// Test if the given register value, which is used by the 3950b57cec5SDimitry Andric /// given instruction, is killed by the given instruction. 396*0fca6ea1SDimitry Andric bool TwoAddressInstructionImpl::isPlainlyKilled(const MachineInstr *MI, 3975f757f3fSDimitry Andric Register Reg) const { 3980b57cec5SDimitry Andric // FIXME: Sometimes tryInstructionTransform() will add instructions and 3990b57cec5SDimitry Andric // test whether they can be folded before keeping them. In this case it 4000b57cec5SDimitry Andric // sets a kill before recursively calling tryInstructionTransform() again. 4010b57cec5SDimitry Andric // If there is no interval available, we assume that this instruction is 4020b57cec5SDimitry Andric // one of those. A kill flag is manually inserted on the operand so the 4030b57cec5SDimitry Andric // check below will handle it. 4045f757f3fSDimitry Andric if (LIS && !LIS->isNotInMIMap(*MI)) { 4055f757f3fSDimitry Andric if (Reg.isVirtual()) 4065f757f3fSDimitry Andric return isPlainlyKilled(MI, LIS->getInterval(Reg)); 4075f757f3fSDimitry Andric // Reserved registers are considered always live. 4085f757f3fSDimitry Andric if (MRI->isReserved(Reg)) 4090b57cec5SDimitry Andric return false; 4105f757f3fSDimitry Andric return all_of(TRI->regunits(Reg), [&](MCRegUnit U) { 4115f757f3fSDimitry Andric return isPlainlyKilled(MI, LIS->getRegUnit(U)); 4125f757f3fSDimitry Andric }); 4130b57cec5SDimitry Andric } 4140b57cec5SDimitry Andric 415*0fca6ea1SDimitry Andric return MI->killsRegister(Reg, /*TRI=*/nullptr); 4160b57cec5SDimitry Andric } 4170b57cec5SDimitry Andric 41806c3fb27SDimitry Andric /// Test if the register used by the given operand is killed by the operand's 41906c3fb27SDimitry Andric /// instruction. 420*0fca6ea1SDimitry Andric bool TwoAddressInstructionImpl::isPlainlyKilled( 4215f757f3fSDimitry Andric const MachineOperand &MO) const { 4225f757f3fSDimitry Andric return MO.isKill() || isPlainlyKilled(MO.getParent(), MO.getReg()); 42306c3fb27SDimitry Andric } 42406c3fb27SDimitry Andric 4250b57cec5SDimitry Andric /// Test if the given register value, which is used by the given 4260b57cec5SDimitry Andric /// instruction, is killed by the given instruction. This looks through 4270b57cec5SDimitry Andric /// coalescable copies to see if the original value is potentially not killed. 4280b57cec5SDimitry Andric /// 4290b57cec5SDimitry Andric /// For example, in this code: 4300b57cec5SDimitry Andric /// 4310b57cec5SDimitry Andric /// %reg1034 = copy %reg1024 4320b57cec5SDimitry Andric /// %reg1035 = copy killed %reg1025 4330b57cec5SDimitry Andric /// %reg1036 = add killed %reg1034, killed %reg1035 4340b57cec5SDimitry Andric /// 4350b57cec5SDimitry Andric /// %reg1034 is not considered to be killed, since it is copied from a 4360b57cec5SDimitry Andric /// register which is not killed. Treating it as not killed lets the 4370b57cec5SDimitry Andric /// normal heuristics commute the (two-address) add, which lets 4380b57cec5SDimitry Andric /// coalescing eliminate the extra copy. 4390b57cec5SDimitry Andric /// 4400b57cec5SDimitry Andric /// If allowFalsePositives is true then likely kills are treated as kills even 4410b57cec5SDimitry Andric /// if it can't be proven that they are kills. 442*0fca6ea1SDimitry Andric bool TwoAddressInstructionImpl::isKilled(MachineInstr &MI, Register Reg, 4435f757f3fSDimitry Andric bool allowFalsePositives) const { 4440b57cec5SDimitry Andric MachineInstr *DefMI = &MI; 4450b57cec5SDimitry Andric while (true) { 4460b57cec5SDimitry Andric // All uses of physical registers are likely to be kills. 447e8d8bef9SDimitry Andric if (Reg.isPhysical() && (allowFalsePositives || MRI->hasOneUse(Reg))) 4480b57cec5SDimitry Andric return true; 4495f757f3fSDimitry Andric if (!isPlainlyKilled(DefMI, Reg)) 4500b57cec5SDimitry Andric return false; 451e8d8bef9SDimitry Andric if (Reg.isPhysical()) 4520b57cec5SDimitry Andric return true; 4530b57cec5SDimitry Andric MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg); 4540b57cec5SDimitry Andric // If there are multiple defs, we can't do a simple analysis, so just 4550b57cec5SDimitry Andric // go with what the kill flag says. 4560b57cec5SDimitry Andric if (std::next(Begin) != MRI->def_end()) 4570b57cec5SDimitry Andric return true; 4580b57cec5SDimitry Andric DefMI = Begin->getParent(); 4590b57cec5SDimitry Andric bool IsSrcPhys, IsDstPhys; 460e8d8bef9SDimitry Andric Register SrcReg, DstReg; 4610b57cec5SDimitry Andric // If the def is something other than a copy, then it isn't going to 4620b57cec5SDimitry Andric // be coalesced, so follow the kill flag. 4635f757f3fSDimitry Andric if (!isCopyToReg(*DefMI, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) 4640b57cec5SDimitry Andric return true; 4650b57cec5SDimitry Andric Reg = SrcReg; 4660b57cec5SDimitry Andric } 4670b57cec5SDimitry Andric } 4680b57cec5SDimitry Andric 4690b57cec5SDimitry Andric /// Return true if the specified MI uses the specified register as a two-address 4700b57cec5SDimitry Andric /// use. If so, return the destination register by reference. 471e8d8bef9SDimitry Andric static bool isTwoAddrUse(MachineInstr &MI, Register Reg, Register &DstReg) { 4720b57cec5SDimitry Andric for (unsigned i = 0, NumOps = MI.getNumOperands(); i != NumOps; ++i) { 4730b57cec5SDimitry Andric const MachineOperand &MO = MI.getOperand(i); 4740b57cec5SDimitry Andric if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg) 4750b57cec5SDimitry Andric continue; 4760b57cec5SDimitry Andric unsigned ti; 4770b57cec5SDimitry Andric if (MI.isRegTiedToDefOperand(i, &ti)) { 4780b57cec5SDimitry Andric DstReg = MI.getOperand(ti).getReg(); 4790b57cec5SDimitry Andric return true; 4800b57cec5SDimitry Andric } 4810b57cec5SDimitry Andric } 4820b57cec5SDimitry Andric return false; 4830b57cec5SDimitry Andric } 4840b57cec5SDimitry Andric 4854824e7fdSDimitry Andric /// Given a register, if all its uses are in the same basic block, return the 4864824e7fdSDimitry Andric /// last use instruction if it's a copy or a two-address use. 487*0fca6ea1SDimitry Andric MachineInstr *TwoAddressInstructionImpl::findOnlyInterestingUse( 4885f757f3fSDimitry Andric Register Reg, MachineBasicBlock *MBB, bool &IsCopy, Register &DstReg, 4895f757f3fSDimitry Andric bool &IsDstPhys) const { 4904824e7fdSDimitry Andric MachineOperand *UseOp = nullptr; 4914824e7fdSDimitry Andric for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) { 4924824e7fdSDimitry Andric MachineInstr *MI = MO.getParent(); 4934824e7fdSDimitry Andric if (MI->getParent() != MBB) 4940b57cec5SDimitry Andric return nullptr; 4955f757f3fSDimitry Andric if (isPlainlyKilled(MI, Reg)) 4964824e7fdSDimitry Andric UseOp = &MO; 4974824e7fdSDimitry Andric } 4984824e7fdSDimitry Andric if (!UseOp) 4990b57cec5SDimitry Andric return nullptr; 5004824e7fdSDimitry Andric MachineInstr &UseMI = *UseOp->getParent(); 5014824e7fdSDimitry Andric 502e8d8bef9SDimitry Andric Register SrcReg; 5030b57cec5SDimitry Andric bool IsSrcPhys; 5045f757f3fSDimitry Andric if (isCopyToReg(UseMI, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) { 5050b57cec5SDimitry Andric IsCopy = true; 5060b57cec5SDimitry Andric return &UseMI; 5070b57cec5SDimitry Andric } 5080b57cec5SDimitry Andric IsDstPhys = false; 5090b57cec5SDimitry Andric if (isTwoAddrUse(UseMI, Reg, DstReg)) { 510e8d8bef9SDimitry Andric IsDstPhys = DstReg.isPhysical(); 5110b57cec5SDimitry Andric return &UseMI; 5120b57cec5SDimitry Andric } 513349cc55cSDimitry Andric if (UseMI.isCommutable()) { 514349cc55cSDimitry Andric unsigned Src1 = TargetInstrInfo::CommuteAnyOperandIndex; 51506c3fb27SDimitry Andric unsigned Src2 = UseOp->getOperandNo(); 516349cc55cSDimitry Andric if (TII->findCommutedOpIndices(UseMI, Src1, Src2)) { 517349cc55cSDimitry Andric MachineOperand &MO = UseMI.getOperand(Src1); 518349cc55cSDimitry Andric if (MO.isReg() && MO.isUse() && 519349cc55cSDimitry Andric isTwoAddrUse(UseMI, MO.getReg(), DstReg)) { 520349cc55cSDimitry Andric IsDstPhys = DstReg.isPhysical(); 521349cc55cSDimitry Andric return &UseMI; 522349cc55cSDimitry Andric } 523349cc55cSDimitry Andric } 524349cc55cSDimitry Andric } 5250b57cec5SDimitry Andric return nullptr; 5260b57cec5SDimitry Andric } 5270b57cec5SDimitry Andric 5280b57cec5SDimitry Andric /// Return the physical register the specified virtual register might be mapped 5290b57cec5SDimitry Andric /// to. 530e8d8bef9SDimitry Andric static MCRegister getMappedReg(Register Reg, 531e8d8bef9SDimitry Andric DenseMap<Register, Register> &RegMap) { 532e8d8bef9SDimitry Andric while (Reg.isVirtual()) { 533e8d8bef9SDimitry Andric DenseMap<Register, Register>::iterator SI = RegMap.find(Reg); 5340b57cec5SDimitry Andric if (SI == RegMap.end()) 5350b57cec5SDimitry Andric return 0; 5360b57cec5SDimitry Andric Reg = SI->second; 5370b57cec5SDimitry Andric } 538e8d8bef9SDimitry Andric if (Reg.isPhysical()) 5390b57cec5SDimitry Andric return Reg; 5400b57cec5SDimitry Andric return 0; 5410b57cec5SDimitry Andric } 5420b57cec5SDimitry Andric 5430b57cec5SDimitry Andric /// Return true if the two registers are equal or aliased. 544*0fca6ea1SDimitry Andric bool TwoAddressInstructionImpl::regsAreCompatible(Register RegA, 5455f757f3fSDimitry Andric Register RegB) const { 5460b57cec5SDimitry Andric if (RegA == RegB) 5470b57cec5SDimitry Andric return true; 5480b57cec5SDimitry Andric if (!RegA || !RegB) 5490b57cec5SDimitry Andric return false; 5500b57cec5SDimitry Andric return TRI->regsOverlap(RegA, RegB); 5510b57cec5SDimitry Andric } 5520b57cec5SDimitry Andric 553349cc55cSDimitry Andric /// From RegMap remove entries mapped to a physical register which overlaps MO. 554*0fca6ea1SDimitry Andric void TwoAddressInstructionImpl::removeMapRegEntry( 5555f757f3fSDimitry Andric const MachineOperand &MO, DenseMap<Register, Register> &RegMap) const { 556349cc55cSDimitry Andric assert( 557349cc55cSDimitry Andric (MO.isReg() || MO.isRegMask()) && 558349cc55cSDimitry Andric "removeMapRegEntry must be called with a register or regmask operand."); 559349cc55cSDimitry Andric 560349cc55cSDimitry Andric SmallVector<Register, 2> Srcs; 561349cc55cSDimitry Andric for (auto SI : RegMap) { 562349cc55cSDimitry Andric Register ToReg = SI.second; 563349cc55cSDimitry Andric if (ToReg.isVirtual()) 564349cc55cSDimitry Andric continue; 565349cc55cSDimitry Andric 566349cc55cSDimitry Andric if (MO.isReg()) { 567349cc55cSDimitry Andric Register Reg = MO.getReg(); 568349cc55cSDimitry Andric if (TRI->regsOverlap(ToReg, Reg)) 569349cc55cSDimitry Andric Srcs.push_back(SI.first); 570349cc55cSDimitry Andric } else if (MO.clobbersPhysReg(ToReg)) 571349cc55cSDimitry Andric Srcs.push_back(SI.first); 572349cc55cSDimitry Andric } 573349cc55cSDimitry Andric 574349cc55cSDimitry Andric for (auto SrcReg : Srcs) 575349cc55cSDimitry Andric RegMap.erase(SrcReg); 576349cc55cSDimitry Andric } 577349cc55cSDimitry Andric 578349cc55cSDimitry Andric /// If a physical register is clobbered, old entries mapped to it should be 579349cc55cSDimitry Andric /// deleted. For example 580349cc55cSDimitry Andric /// 581349cc55cSDimitry Andric /// %2:gr64 = COPY killed $rdx 582349cc55cSDimitry Andric /// MUL64r %3:gr64, implicit-def $rax, implicit-def $rdx 583349cc55cSDimitry Andric /// 584349cc55cSDimitry Andric /// After the MUL instruction, $rdx contains different value than in the COPY 585349cc55cSDimitry Andric /// instruction. So %2 should not map to $rdx after MUL. 586*0fca6ea1SDimitry Andric void TwoAddressInstructionImpl::removeClobberedSrcRegMap(MachineInstr *MI) { 587349cc55cSDimitry Andric if (MI->isCopy()) { 588349cc55cSDimitry Andric // If a virtual register is copied to its mapped physical register, it 589349cc55cSDimitry Andric // doesn't change the potential coalescing between them, so we don't remove 590349cc55cSDimitry Andric // entries mapped to the physical register. For example 591349cc55cSDimitry Andric // 592349cc55cSDimitry Andric // %100 = COPY $r8 593349cc55cSDimitry Andric // ... 594349cc55cSDimitry Andric // $r8 = COPY %100 595349cc55cSDimitry Andric // 596349cc55cSDimitry Andric // The first copy constructs SrcRegMap[%100] = $r8, the second copy doesn't 597349cc55cSDimitry Andric // destroy the content of $r8, and should not impact SrcRegMap. 598349cc55cSDimitry Andric Register Dst = MI->getOperand(0).getReg(); 599349cc55cSDimitry Andric if (!Dst || Dst.isVirtual()) 600349cc55cSDimitry Andric return; 601349cc55cSDimitry Andric 602349cc55cSDimitry Andric Register Src = MI->getOperand(1).getReg(); 6035f757f3fSDimitry Andric if (regsAreCompatible(Dst, getMappedReg(Src, SrcRegMap))) 604349cc55cSDimitry Andric return; 605349cc55cSDimitry Andric } 606349cc55cSDimitry Andric 6074824e7fdSDimitry Andric for (const MachineOperand &MO : MI->operands()) { 608349cc55cSDimitry Andric if (MO.isRegMask()) { 6095f757f3fSDimitry Andric removeMapRegEntry(MO, SrcRegMap); 610349cc55cSDimitry Andric continue; 611349cc55cSDimitry Andric } 612349cc55cSDimitry Andric if (!MO.isReg() || !MO.isDef()) 613349cc55cSDimitry Andric continue; 614349cc55cSDimitry Andric Register Reg = MO.getReg(); 615349cc55cSDimitry Andric if (!Reg || Reg.isVirtual()) 616349cc55cSDimitry Andric continue; 6175f757f3fSDimitry Andric removeMapRegEntry(MO, SrcRegMap); 618349cc55cSDimitry Andric } 619349cc55cSDimitry Andric } 620349cc55cSDimitry Andric 6210b57cec5SDimitry Andric // Returns true if Reg is equal or aliased to at least one register in Set. 622*0fca6ea1SDimitry Andric bool TwoAddressInstructionImpl::regOverlapsSet( 6235f757f3fSDimitry Andric const SmallVectorImpl<Register> &Set, Register Reg) const { 6240b57cec5SDimitry Andric for (unsigned R : Set) 6250b57cec5SDimitry Andric if (TRI->regsOverlap(R, Reg)) 6260b57cec5SDimitry Andric return true; 6270b57cec5SDimitry Andric 6280b57cec5SDimitry Andric return false; 6290b57cec5SDimitry Andric } 6300b57cec5SDimitry Andric 6310b57cec5SDimitry Andric /// Return true if it's potentially profitable to commute the two-address 6320b57cec5SDimitry Andric /// instruction that's being processed. 633*0fca6ea1SDimitry Andric bool TwoAddressInstructionImpl::isProfitableToCommute(Register RegA, 634e8d8bef9SDimitry Andric Register RegB, 635e8d8bef9SDimitry Andric Register RegC, 636e8d8bef9SDimitry Andric MachineInstr *MI, 637e8d8bef9SDimitry Andric unsigned Dist) { 6385f757f3fSDimitry Andric if (OptLevel == CodeGenOptLevel::None) 6390b57cec5SDimitry Andric return false; 6400b57cec5SDimitry Andric 6410b57cec5SDimitry Andric // Determine if it's profitable to commute this two address instruction. In 6420b57cec5SDimitry Andric // general, we want no uses between this instruction and the definition of 6430b57cec5SDimitry Andric // the two-address register. 6440b57cec5SDimitry Andric // e.g. 6450b57cec5SDimitry Andric // %reg1028 = EXTRACT_SUBREG killed %reg1027, 1 6460b57cec5SDimitry Andric // %reg1029 = COPY %reg1028 6470b57cec5SDimitry Andric // %reg1029 = SHR8ri %reg1029, 7, implicit dead %eflags 6480b57cec5SDimitry Andric // insert => %reg1030 = COPY %reg1028 6490b57cec5SDimitry Andric // %reg1030 = ADD8rr killed %reg1028, killed %reg1029, implicit dead %eflags 6500b57cec5SDimitry Andric // In this case, it might not be possible to coalesce the second COPY 6510b57cec5SDimitry Andric // instruction if the first one is coalesced. So it would be profitable to 6520b57cec5SDimitry Andric // commute it: 6530b57cec5SDimitry Andric // %reg1028 = EXTRACT_SUBREG killed %reg1027, 1 6540b57cec5SDimitry Andric // %reg1029 = COPY %reg1028 6550b57cec5SDimitry Andric // %reg1029 = SHR8ri %reg1029, 7, implicit dead %eflags 6560b57cec5SDimitry Andric // insert => %reg1030 = COPY %reg1029 6570b57cec5SDimitry Andric // %reg1030 = ADD8rr killed %reg1029, killed %reg1028, implicit dead %eflags 6580b57cec5SDimitry Andric 6595f757f3fSDimitry Andric if (!isPlainlyKilled(MI, RegC)) 6600b57cec5SDimitry Andric return false; 6610b57cec5SDimitry Andric 6620b57cec5SDimitry Andric // Ok, we have something like: 6630b57cec5SDimitry Andric // %reg1030 = ADD8rr killed %reg1028, killed %reg1029, implicit dead %eflags 6640b57cec5SDimitry Andric // let's see if it's worth commuting it. 6650b57cec5SDimitry Andric 6660b57cec5SDimitry Andric // Look for situations like this: 6670b57cec5SDimitry Andric // %reg1024 = MOV r1 6680b57cec5SDimitry Andric // %reg1025 = MOV r0 6690b57cec5SDimitry Andric // %reg1026 = ADD %reg1024, %reg1025 6700b57cec5SDimitry Andric // r0 = MOV %reg1026 6710b57cec5SDimitry Andric // Commute the ADD to hopefully eliminate an otherwise unavoidable copy. 672e8d8bef9SDimitry Andric MCRegister ToRegA = getMappedReg(RegA, DstRegMap); 6730b57cec5SDimitry Andric if (ToRegA) { 674e8d8bef9SDimitry Andric MCRegister FromRegB = getMappedReg(RegB, SrcRegMap); 675e8d8bef9SDimitry Andric MCRegister FromRegC = getMappedReg(RegC, SrcRegMap); 6765f757f3fSDimitry Andric bool CompB = FromRegB && regsAreCompatible(FromRegB, ToRegA); 6775f757f3fSDimitry Andric bool CompC = FromRegC && regsAreCompatible(FromRegC, ToRegA); 6780b57cec5SDimitry Andric 6790b57cec5SDimitry Andric // Compute if any of the following are true: 6800b57cec5SDimitry Andric // -RegB is not tied to a register and RegC is compatible with RegA. 6810b57cec5SDimitry Andric // -RegB is tied to the wrong physical register, but RegC is. 6820b57cec5SDimitry Andric // -RegB is tied to the wrong physical register, and RegC isn't tied. 6830b57cec5SDimitry Andric if ((!FromRegB && CompC) || (FromRegB && !CompB && (!FromRegC || CompC))) 6840b57cec5SDimitry Andric return true; 6850b57cec5SDimitry Andric // Don't compute if any of the following are true: 6860b57cec5SDimitry Andric // -RegC is not tied to a register and RegB is compatible with RegA. 6870b57cec5SDimitry Andric // -RegC is tied to the wrong physical register, but RegB is. 6880b57cec5SDimitry Andric // -RegC is tied to the wrong physical register, and RegB isn't tied. 6890b57cec5SDimitry Andric if ((!FromRegC && CompB) || (FromRegC && !CompC && (!FromRegB || CompB))) 6900b57cec5SDimitry Andric return false; 6910b57cec5SDimitry Andric } 6920b57cec5SDimitry Andric 693e8d8bef9SDimitry Andric // If there is a use of RegC between its last def (could be livein) and this 6940b57cec5SDimitry Andric // instruction, then bail. 6950b57cec5SDimitry Andric unsigned LastDefC = 0; 696e8d8bef9SDimitry Andric if (!noUseAfterLastDef(RegC, Dist, LastDefC)) 6970b57cec5SDimitry Andric return false; 6980b57cec5SDimitry Andric 699e8d8bef9SDimitry Andric // If there is a use of RegB between its last def (could be livein) and this 7000b57cec5SDimitry Andric // instruction, then go ahead and make this transformation. 7010b57cec5SDimitry Andric unsigned LastDefB = 0; 702e8d8bef9SDimitry Andric if (!noUseAfterLastDef(RegB, Dist, LastDefB)) 7030b57cec5SDimitry Andric return true; 7040b57cec5SDimitry Andric 7050b57cec5SDimitry Andric // Look for situation like this: 7060b57cec5SDimitry Andric // %reg101 = MOV %reg100 7070b57cec5SDimitry Andric // %reg102 = ... 7080b57cec5SDimitry Andric // %reg103 = ADD %reg102, %reg101 7090b57cec5SDimitry Andric // ... = %reg103 ... 7100b57cec5SDimitry Andric // %reg100 = MOV %reg103 7110b57cec5SDimitry Andric // If there is a reversed copy chain from reg101 to reg103, commute the ADD 7120b57cec5SDimitry Andric // to eliminate an otherwise unavoidable copy. 7130b57cec5SDimitry Andric // FIXME: 7140b57cec5SDimitry Andric // We can extend the logic further: If an pair of operands in an insn has 7150b57cec5SDimitry Andric // been merged, the insn could be regarded as a virtual copy, and the virtual 7160b57cec5SDimitry Andric // copy could also be used to construct a copy chain. 7170b57cec5SDimitry Andric // To more generally minimize register copies, ideally the logic of two addr 7180b57cec5SDimitry Andric // instruction pass should be integrated with register allocation pass where 7190b57cec5SDimitry Andric // interference graph is available. 720e8d8bef9SDimitry Andric if (isRevCopyChain(RegC, RegA, MaxDataFlowEdge)) 7210b57cec5SDimitry Andric return true; 7220b57cec5SDimitry Andric 723e8d8bef9SDimitry Andric if (isRevCopyChain(RegB, RegA, MaxDataFlowEdge)) 7240b57cec5SDimitry Andric return false; 7250b57cec5SDimitry Andric 726fe6060f1SDimitry Andric // Look for other target specific commute preference. 727fe6060f1SDimitry Andric bool Commute; 728fe6060f1SDimitry Andric if (TII->hasCommutePreference(*MI, Commute)) 729fe6060f1SDimitry Andric return Commute; 730fe6060f1SDimitry Andric 7310b57cec5SDimitry Andric // Since there are no intervening uses for both registers, then commute 732e8d8bef9SDimitry Andric // if the def of RegC is closer. Its live interval is shorter. 7330b57cec5SDimitry Andric return LastDefB && LastDefC && LastDefC > LastDefB; 7340b57cec5SDimitry Andric } 7350b57cec5SDimitry Andric 7360b57cec5SDimitry Andric /// Commute a two-address instruction and update the basic block, distance map, 7370b57cec5SDimitry Andric /// and live variables if needed. Return true if it is successful. 738*0fca6ea1SDimitry Andric bool TwoAddressInstructionImpl::commuteInstruction(MachineInstr *MI, 7390b57cec5SDimitry Andric unsigned DstIdx, 7400b57cec5SDimitry Andric unsigned RegBIdx, 7410b57cec5SDimitry Andric unsigned RegCIdx, 7420b57cec5SDimitry Andric unsigned Dist) { 7438bcb0991SDimitry Andric Register RegC = MI->getOperand(RegCIdx).getReg(); 7440b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: COMMUTING : " << *MI); 7450b57cec5SDimitry Andric MachineInstr *NewMI = TII->commuteInstruction(*MI, false, RegBIdx, RegCIdx); 7460b57cec5SDimitry Andric 7470b57cec5SDimitry Andric if (NewMI == nullptr) { 7480b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n"); 7490b57cec5SDimitry Andric return false; 7500b57cec5SDimitry Andric } 7510b57cec5SDimitry Andric 7520b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI); 7530b57cec5SDimitry Andric assert(NewMI == MI && 7540b57cec5SDimitry Andric "TargetInstrInfo::commuteInstruction() should not return a new " 7550b57cec5SDimitry Andric "instruction unless it was requested."); 7560b57cec5SDimitry Andric 7570b57cec5SDimitry Andric // Update source register map. 758e8d8bef9SDimitry Andric MCRegister FromRegC = getMappedReg(RegC, SrcRegMap); 7590b57cec5SDimitry Andric if (FromRegC) { 7608bcb0991SDimitry Andric Register RegA = MI->getOperand(DstIdx).getReg(); 7610b57cec5SDimitry Andric SrcRegMap[RegA] = FromRegC; 7620b57cec5SDimitry Andric } 7630b57cec5SDimitry Andric 7640b57cec5SDimitry Andric return true; 7650b57cec5SDimitry Andric } 7660b57cec5SDimitry Andric 7670b57cec5SDimitry Andric /// Return true if it is profitable to convert the given 2-address instruction 7680b57cec5SDimitry Andric /// to a 3-address one. 769*0fca6ea1SDimitry Andric bool TwoAddressInstructionImpl::isProfitableToConv3Addr(Register RegA, 770e8d8bef9SDimitry Andric Register RegB) { 7710b57cec5SDimitry Andric // Look for situations like this: 7720b57cec5SDimitry Andric // %reg1024 = MOV r1 7730b57cec5SDimitry Andric // %reg1025 = MOV r0 7740b57cec5SDimitry Andric // %reg1026 = ADD %reg1024, %reg1025 7750b57cec5SDimitry Andric // r2 = MOV %reg1026 7760b57cec5SDimitry Andric // Turn ADD into a 3-address instruction to avoid a copy. 777e8d8bef9SDimitry Andric MCRegister FromRegB = getMappedReg(RegB, SrcRegMap); 7780b57cec5SDimitry Andric if (!FromRegB) 7790b57cec5SDimitry Andric return false; 780e8d8bef9SDimitry Andric MCRegister ToRegA = getMappedReg(RegA, DstRegMap); 7815f757f3fSDimitry Andric return (ToRegA && !regsAreCompatible(FromRegB, ToRegA)); 7820b57cec5SDimitry Andric } 7830b57cec5SDimitry Andric 7840b57cec5SDimitry Andric /// Convert the specified two-address instruction into a three address one. 7850b57cec5SDimitry Andric /// Return true if this transformation was successful. 786*0fca6ea1SDimitry Andric bool TwoAddressInstructionImpl::convertInstTo3Addr( 787e8d8bef9SDimitry Andric MachineBasicBlock::iterator &mi, MachineBasicBlock::iterator &nmi, 788349cc55cSDimitry Andric Register RegA, Register RegB, unsigned &Dist) { 789349cc55cSDimitry Andric MachineInstrSpan MIS(mi, MBB); 790349cc55cSDimitry Andric MachineInstr *NewMI = TII->convertToThreeAddress(*mi, LV, LIS); 7910b57cec5SDimitry Andric if (!NewMI) 7920b57cec5SDimitry Andric return false; 7930b57cec5SDimitry Andric 7940b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi); 7950b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI); 7960b57cec5SDimitry Andric 797e8d8bef9SDimitry Andric // If the old instruction is debug value tracked, an update is required. 798e8d8bef9SDimitry Andric if (auto OldInstrNum = mi->peekDebugInstrNum()) { 799e8d8bef9SDimitry Andric assert(mi->getNumExplicitDefs() == 1); 800e8d8bef9SDimitry Andric assert(NewMI->getNumExplicitDefs() == 1); 801e8d8bef9SDimitry Andric 802e8d8bef9SDimitry Andric // Find the old and new def location. 80306c3fb27SDimitry Andric unsigned OldIdx = mi->defs().begin()->getOperandNo(); 80406c3fb27SDimitry Andric unsigned NewIdx = NewMI->defs().begin()->getOperandNo(); 805e8d8bef9SDimitry Andric 806e8d8bef9SDimitry Andric // Record that one def has been replaced by the other. 807e8d8bef9SDimitry Andric unsigned NewInstrNum = NewMI->getDebugInstrNum(); 808e8d8bef9SDimitry Andric MF->makeDebugValueSubstitution(std::make_pair(OldInstrNum, OldIdx), 809e8d8bef9SDimitry Andric std::make_pair(NewInstrNum, NewIdx)); 810e8d8bef9SDimitry Andric } 811e8d8bef9SDimitry Andric 8120b57cec5SDimitry Andric MBB->erase(mi); // Nuke the old inst. 8130b57cec5SDimitry Andric 814349cc55cSDimitry Andric for (MachineInstr &MI : MIS) 815349cc55cSDimitry Andric DistanceMap.insert(std::make_pair(&MI, Dist++)); 816349cc55cSDimitry Andric Dist--; 8170b57cec5SDimitry Andric mi = NewMI; 8180b57cec5SDimitry Andric nmi = std::next(mi); 8190b57cec5SDimitry Andric 8200b57cec5SDimitry Andric // Update source and destination register maps. 8210b57cec5SDimitry Andric SrcRegMap.erase(RegA); 8220b57cec5SDimitry Andric DstRegMap.erase(RegB); 8230b57cec5SDimitry Andric return true; 8240b57cec5SDimitry Andric } 8250b57cec5SDimitry Andric 8260b57cec5SDimitry Andric /// Scan forward recursively for only uses, update maps if the use is a copy or 8270b57cec5SDimitry Andric /// a two-address instruction. 828*0fca6ea1SDimitry Andric void TwoAddressInstructionImpl::scanUses(Register DstReg) { 829e8d8bef9SDimitry Andric SmallVector<Register, 4> VirtRegPairs; 8300b57cec5SDimitry Andric bool IsDstPhys; 8310b57cec5SDimitry Andric bool IsCopy = false; 832e8d8bef9SDimitry Andric Register NewReg; 833e8d8bef9SDimitry Andric Register Reg = DstReg; 8345f757f3fSDimitry Andric while (MachineInstr *UseMI = 8355f757f3fSDimitry Andric findOnlyInterestingUse(Reg, MBB, IsCopy, NewReg, IsDstPhys)) { 8360b57cec5SDimitry Andric if (IsCopy && !Processed.insert(UseMI).second) 8370b57cec5SDimitry Andric break; 8380b57cec5SDimitry Andric 8390b57cec5SDimitry Andric DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI); 8400b57cec5SDimitry Andric if (DI != DistanceMap.end()) 8410b57cec5SDimitry Andric // Earlier in the same MBB.Reached via a back edge. 8420b57cec5SDimitry Andric break; 8430b57cec5SDimitry Andric 8440b57cec5SDimitry Andric if (IsDstPhys) { 8450b57cec5SDimitry Andric VirtRegPairs.push_back(NewReg); 8460b57cec5SDimitry Andric break; 8470b57cec5SDimitry Andric } 848349cc55cSDimitry Andric SrcRegMap[NewReg] = Reg; 8490b57cec5SDimitry Andric VirtRegPairs.push_back(NewReg); 8500b57cec5SDimitry Andric Reg = NewReg; 8510b57cec5SDimitry Andric } 8520b57cec5SDimitry Andric 8530b57cec5SDimitry Andric if (!VirtRegPairs.empty()) { 8540b57cec5SDimitry Andric unsigned ToReg = VirtRegPairs.back(); 8550b57cec5SDimitry Andric VirtRegPairs.pop_back(); 8560b57cec5SDimitry Andric while (!VirtRegPairs.empty()) { 857349cc55cSDimitry Andric unsigned FromReg = VirtRegPairs.pop_back_val(); 8580b57cec5SDimitry Andric bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second; 8590b57cec5SDimitry Andric if (!isNew) 8600b57cec5SDimitry Andric assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!"); 8610b57cec5SDimitry Andric ToReg = FromReg; 8620b57cec5SDimitry Andric } 8630b57cec5SDimitry Andric bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second; 8640b57cec5SDimitry Andric if (!isNew) 8650b57cec5SDimitry Andric assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!"); 8660b57cec5SDimitry Andric } 8670b57cec5SDimitry Andric } 8680b57cec5SDimitry Andric 8690b57cec5SDimitry Andric /// If the specified instruction is not yet processed, process it if it's a 8700b57cec5SDimitry Andric /// copy. For a copy instruction, we find the physical registers the 8710b57cec5SDimitry Andric /// source and destination registers might be mapped to. These are kept in 8720b57cec5SDimitry Andric /// point-to maps used to determine future optimizations. e.g. 8730b57cec5SDimitry Andric /// v1024 = mov r0 8740b57cec5SDimitry Andric /// v1025 = mov r1 8750b57cec5SDimitry Andric /// v1026 = add v1024, v1025 8760b57cec5SDimitry Andric /// r1 = mov r1026 8770b57cec5SDimitry Andric /// If 'add' is a two-address instruction, v1024, v1026 are both potentially 8780b57cec5SDimitry Andric /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is 8790b57cec5SDimitry Andric /// potentially joined with r1 on the output side. It's worthwhile to commute 8800b57cec5SDimitry Andric /// 'add' to eliminate a copy. 881*0fca6ea1SDimitry Andric void TwoAddressInstructionImpl::processCopy(MachineInstr *MI) { 8820b57cec5SDimitry Andric if (Processed.count(MI)) 8830b57cec5SDimitry Andric return; 8840b57cec5SDimitry Andric 8850b57cec5SDimitry Andric bool IsSrcPhys, IsDstPhys; 886e8d8bef9SDimitry Andric Register SrcReg, DstReg; 8875f757f3fSDimitry Andric if (!isCopyToReg(*MI, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) 8880b57cec5SDimitry Andric return; 8890b57cec5SDimitry Andric 890e8d8bef9SDimitry Andric if (IsDstPhys && !IsSrcPhys) { 8910b57cec5SDimitry Andric DstRegMap.insert(std::make_pair(SrcReg, DstReg)); 892e8d8bef9SDimitry Andric } else if (!IsDstPhys && IsSrcPhys) { 8930b57cec5SDimitry Andric bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second; 8940b57cec5SDimitry Andric if (!isNew) 8950b57cec5SDimitry Andric assert(SrcRegMap[DstReg] == SrcReg && 8960b57cec5SDimitry Andric "Can't map to two src physical registers!"); 8970b57cec5SDimitry Andric 8980b57cec5SDimitry Andric scanUses(DstReg); 8990b57cec5SDimitry Andric } 9000b57cec5SDimitry Andric 9010b57cec5SDimitry Andric Processed.insert(MI); 9020b57cec5SDimitry Andric } 9030b57cec5SDimitry Andric 9040b57cec5SDimitry Andric /// If there is one more local instruction that reads 'Reg' and it kills 'Reg, 9050b57cec5SDimitry Andric /// consider moving the instruction below the kill instruction in order to 9060b57cec5SDimitry Andric /// eliminate the need for the copy. 907*0fca6ea1SDimitry Andric bool TwoAddressInstructionImpl::rescheduleMIBelowKill( 908e8d8bef9SDimitry Andric MachineBasicBlock::iterator &mi, MachineBasicBlock::iterator &nmi, 909e8d8bef9SDimitry Andric Register Reg) { 9100b57cec5SDimitry Andric // Bail immediately if we don't have LV or LIS available. We use them to find 9110b57cec5SDimitry Andric // kills efficiently. 9120b57cec5SDimitry Andric if (!LV && !LIS) 9130b57cec5SDimitry Andric return false; 9140b57cec5SDimitry Andric 9150b57cec5SDimitry Andric MachineInstr *MI = &*mi; 9160b57cec5SDimitry Andric DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI); 9170b57cec5SDimitry Andric if (DI == DistanceMap.end()) 9180b57cec5SDimitry Andric // Must be created from unfolded load. Don't waste time trying this. 9190b57cec5SDimitry Andric return false; 9200b57cec5SDimitry Andric 9210b57cec5SDimitry Andric MachineInstr *KillMI = nullptr; 9220b57cec5SDimitry Andric if (LIS) { 9230b57cec5SDimitry Andric LiveInterval &LI = LIS->getInterval(Reg); 9240b57cec5SDimitry Andric assert(LI.end() != LI.begin() && 9250b57cec5SDimitry Andric "Reg should not have empty live interval."); 9260b57cec5SDimitry Andric 9270b57cec5SDimitry Andric SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot(); 9280b57cec5SDimitry Andric LiveInterval::const_iterator I = LI.find(MBBEndIdx); 9290b57cec5SDimitry Andric if (I != LI.end() && I->start < MBBEndIdx) 9300b57cec5SDimitry Andric return false; 9310b57cec5SDimitry Andric 9320b57cec5SDimitry Andric --I; 9330b57cec5SDimitry Andric KillMI = LIS->getInstructionFromIndex(I->end); 9340b57cec5SDimitry Andric } else { 9350b57cec5SDimitry Andric KillMI = LV->getVarInfo(Reg).findKill(MBB); 9360b57cec5SDimitry Andric } 9370b57cec5SDimitry Andric if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike()) 9380b57cec5SDimitry Andric // Don't mess with copies, they may be coalesced later. 9390b57cec5SDimitry Andric return false; 9400b57cec5SDimitry Andric 9410b57cec5SDimitry Andric if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() || 9420b57cec5SDimitry Andric KillMI->isBranch() || KillMI->isTerminator()) 9430b57cec5SDimitry Andric // Don't move pass calls, etc. 9440b57cec5SDimitry Andric return false; 9450b57cec5SDimitry Andric 946e8d8bef9SDimitry Andric Register DstReg; 9470b57cec5SDimitry Andric if (isTwoAddrUse(*KillMI, Reg, DstReg)) 9480b57cec5SDimitry Andric return false; 9490b57cec5SDimitry Andric 9500b57cec5SDimitry Andric bool SeenStore = true; 9510b57cec5SDimitry Andric if (!MI->isSafeToMove(AA, SeenStore)) 9520b57cec5SDimitry Andric return false; 9530b57cec5SDimitry Andric 9540b57cec5SDimitry Andric if (TII->getInstrLatency(InstrItins, *MI) > 1) 9550b57cec5SDimitry Andric // FIXME: Needs more sophisticated heuristics. 9560b57cec5SDimitry Andric return false; 9570b57cec5SDimitry Andric 958e8d8bef9SDimitry Andric SmallVector<Register, 2> Uses; 959e8d8bef9SDimitry Andric SmallVector<Register, 2> Kills; 960e8d8bef9SDimitry Andric SmallVector<Register, 2> Defs; 9610b57cec5SDimitry Andric for (const MachineOperand &MO : MI->operands()) { 9620b57cec5SDimitry Andric if (!MO.isReg()) 9630b57cec5SDimitry Andric continue; 9648bcb0991SDimitry Andric Register MOReg = MO.getReg(); 9650b57cec5SDimitry Andric if (!MOReg) 9660b57cec5SDimitry Andric continue; 9670b57cec5SDimitry Andric if (MO.isDef()) 9680b57cec5SDimitry Andric Defs.push_back(MOReg); 9690b57cec5SDimitry Andric else { 9700b57cec5SDimitry Andric Uses.push_back(MOReg); 9715f757f3fSDimitry Andric if (MOReg != Reg && isPlainlyKilled(MO)) 9720b57cec5SDimitry Andric Kills.push_back(MOReg); 9730b57cec5SDimitry Andric } 9740b57cec5SDimitry Andric } 9750b57cec5SDimitry Andric 9760b57cec5SDimitry Andric // Move the copies connected to MI down as well. 9770b57cec5SDimitry Andric MachineBasicBlock::iterator Begin = MI; 9780b57cec5SDimitry Andric MachineBasicBlock::iterator AfterMI = std::next(Begin); 9790b57cec5SDimitry Andric MachineBasicBlock::iterator End = AfterMI; 9800b57cec5SDimitry Andric while (End != MBB->end()) { 9810b57cec5SDimitry Andric End = skipDebugInstructionsForward(End, MBB->end()); 9825f757f3fSDimitry Andric if (End->isCopy() && regOverlapsSet(Defs, End->getOperand(1).getReg())) 9830b57cec5SDimitry Andric Defs.push_back(End->getOperand(0).getReg()); 9840b57cec5SDimitry Andric else 9850b57cec5SDimitry Andric break; 9860b57cec5SDimitry Andric ++End; 9870b57cec5SDimitry Andric } 9880b57cec5SDimitry Andric 9890b57cec5SDimitry Andric // Check if the reschedule will not break dependencies. 9900b57cec5SDimitry Andric unsigned NumVisited = 0; 9910b57cec5SDimitry Andric MachineBasicBlock::iterator KillPos = KillMI; 9920b57cec5SDimitry Andric ++KillPos; 9930b57cec5SDimitry Andric for (MachineInstr &OtherMI : make_range(End, KillPos)) { 994d409305fSDimitry Andric // Debug or pseudo instructions cannot be counted against the limit. 995d409305fSDimitry Andric if (OtherMI.isDebugOrPseudoInstr()) 9960b57cec5SDimitry Andric continue; 9970b57cec5SDimitry Andric if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost. 9980b57cec5SDimitry Andric return false; 9990b57cec5SDimitry Andric ++NumVisited; 10000b57cec5SDimitry Andric if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() || 10010b57cec5SDimitry Andric OtherMI.isBranch() || OtherMI.isTerminator()) 10020b57cec5SDimitry Andric // Don't move pass calls, etc. 10030b57cec5SDimitry Andric return false; 10040b57cec5SDimitry Andric for (const MachineOperand &MO : OtherMI.operands()) { 10050b57cec5SDimitry Andric if (!MO.isReg()) 10060b57cec5SDimitry Andric continue; 10078bcb0991SDimitry Andric Register MOReg = MO.getReg(); 10080b57cec5SDimitry Andric if (!MOReg) 10090b57cec5SDimitry Andric continue; 10100b57cec5SDimitry Andric if (MO.isDef()) { 10115f757f3fSDimitry Andric if (regOverlapsSet(Uses, MOReg)) 10120b57cec5SDimitry Andric // Physical register use would be clobbered. 10130b57cec5SDimitry Andric return false; 10145f757f3fSDimitry Andric if (!MO.isDead() && regOverlapsSet(Defs, MOReg)) 10150b57cec5SDimitry Andric // May clobber a physical register def. 10160b57cec5SDimitry Andric // FIXME: This may be too conservative. It's ok if the instruction 10170b57cec5SDimitry Andric // is sunken completely below the use. 10180b57cec5SDimitry Andric return false; 10190b57cec5SDimitry Andric } else { 10205f757f3fSDimitry Andric if (regOverlapsSet(Defs, MOReg)) 10210b57cec5SDimitry Andric return false; 10225f757f3fSDimitry Andric bool isKill = isPlainlyKilled(MO); 10235f757f3fSDimitry Andric if (MOReg != Reg && ((isKill && regOverlapsSet(Uses, MOReg)) || 10245f757f3fSDimitry Andric regOverlapsSet(Kills, MOReg))) 10250b57cec5SDimitry Andric // Don't want to extend other live ranges and update kills. 10260b57cec5SDimitry Andric return false; 10270b57cec5SDimitry Andric if (MOReg == Reg && !isKill) 10280b57cec5SDimitry Andric // We can't schedule across a use of the register in question. 10290b57cec5SDimitry Andric return false; 10300b57cec5SDimitry Andric // Ensure that if this is register in question, its the kill we expect. 10310b57cec5SDimitry Andric assert((MOReg != Reg || &OtherMI == KillMI) && 10320b57cec5SDimitry Andric "Found multiple kills of a register in a basic block"); 10330b57cec5SDimitry Andric } 10340b57cec5SDimitry Andric } 10350b57cec5SDimitry Andric } 10360b57cec5SDimitry Andric 10370b57cec5SDimitry Andric // Move debug info as well. 10380b57cec5SDimitry Andric while (Begin != MBB->begin() && std::prev(Begin)->isDebugInstr()) 10390b57cec5SDimitry Andric --Begin; 10400b57cec5SDimitry Andric 10410b57cec5SDimitry Andric nmi = End; 10420b57cec5SDimitry Andric MachineBasicBlock::iterator InsertPos = KillPos; 10430b57cec5SDimitry Andric if (LIS) { 1044349cc55cSDimitry Andric // We have to move the copies (and any interleaved debug instructions) 1045349cc55cSDimitry Andric // first so that the MBB is still well-formed when calling handleMove(). 10460b57cec5SDimitry Andric for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) { 10470b57cec5SDimitry Andric auto CopyMI = MBBI++; 10480b57cec5SDimitry Andric MBB->splice(InsertPos, MBB, CopyMI); 1049349cc55cSDimitry Andric if (!CopyMI->isDebugOrPseudoInstr()) 10500b57cec5SDimitry Andric LIS->handleMove(*CopyMI); 10510b57cec5SDimitry Andric InsertPos = CopyMI; 10520b57cec5SDimitry Andric } 10530b57cec5SDimitry Andric End = std::next(MachineBasicBlock::iterator(MI)); 10540b57cec5SDimitry Andric } 10550b57cec5SDimitry Andric 10560b57cec5SDimitry Andric // Copies following MI may have been moved as well. 10570b57cec5SDimitry Andric MBB->splice(InsertPos, MBB, Begin, End); 10580b57cec5SDimitry Andric DistanceMap.erase(DI); 10590b57cec5SDimitry Andric 10600b57cec5SDimitry Andric // Update live variables 10610b57cec5SDimitry Andric if (LIS) { 10620b57cec5SDimitry Andric LIS->handleMove(*MI); 10630b57cec5SDimitry Andric } else { 10640b57cec5SDimitry Andric LV->removeVirtualRegisterKilled(Reg, *KillMI); 10650b57cec5SDimitry Andric LV->addVirtualRegisterKilled(Reg, *MI); 10660b57cec5SDimitry Andric } 10670b57cec5SDimitry Andric 10680b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI); 10690b57cec5SDimitry Andric return true; 10700b57cec5SDimitry Andric } 10710b57cec5SDimitry Andric 10720b57cec5SDimitry Andric /// Return true if the re-scheduling will put the given instruction too close 10730b57cec5SDimitry Andric /// to the defs of its register dependencies. 1074*0fca6ea1SDimitry Andric bool TwoAddressInstructionImpl::isDefTooClose(Register Reg, unsigned Dist, 10750b57cec5SDimitry Andric MachineInstr *MI) { 10760b57cec5SDimitry Andric for (MachineInstr &DefMI : MRI->def_instructions(Reg)) { 10770b57cec5SDimitry Andric if (DefMI.getParent() != MBB || DefMI.isCopy() || DefMI.isCopyLike()) 10780b57cec5SDimitry Andric continue; 10790b57cec5SDimitry Andric if (&DefMI == MI) 10800b57cec5SDimitry Andric return true; // MI is defining something KillMI uses 10810b57cec5SDimitry Andric DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(&DefMI); 10820b57cec5SDimitry Andric if (DDI == DistanceMap.end()) 10830b57cec5SDimitry Andric return true; // Below MI 10840b57cec5SDimitry Andric unsigned DefDist = DDI->second; 10850b57cec5SDimitry Andric assert(Dist > DefDist && "Visited def already?"); 10860b57cec5SDimitry Andric if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist)) 10870b57cec5SDimitry Andric return true; 10880b57cec5SDimitry Andric } 10890b57cec5SDimitry Andric return false; 10900b57cec5SDimitry Andric } 10910b57cec5SDimitry Andric 10920b57cec5SDimitry Andric /// If there is one more local instruction that reads 'Reg' and it kills 'Reg, 10930b57cec5SDimitry Andric /// consider moving the kill instruction above the current two-address 10940b57cec5SDimitry Andric /// instruction in order to eliminate the need for the copy. 1095*0fca6ea1SDimitry Andric bool TwoAddressInstructionImpl::rescheduleKillAboveMI( 1096e8d8bef9SDimitry Andric MachineBasicBlock::iterator &mi, MachineBasicBlock::iterator &nmi, 1097e8d8bef9SDimitry Andric Register Reg) { 10980b57cec5SDimitry Andric // Bail immediately if we don't have LV or LIS available. We use them to find 10990b57cec5SDimitry Andric // kills efficiently. 11000b57cec5SDimitry Andric if (!LV && !LIS) 11010b57cec5SDimitry Andric return false; 11020b57cec5SDimitry Andric 11030b57cec5SDimitry Andric MachineInstr *MI = &*mi; 11040b57cec5SDimitry Andric DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI); 11050b57cec5SDimitry Andric if (DI == DistanceMap.end()) 11060b57cec5SDimitry Andric // Must be created from unfolded load. Don't waste time trying this. 11070b57cec5SDimitry Andric return false; 11080b57cec5SDimitry Andric 11090b57cec5SDimitry Andric MachineInstr *KillMI = nullptr; 11100b57cec5SDimitry Andric if (LIS) { 11110b57cec5SDimitry Andric LiveInterval &LI = LIS->getInterval(Reg); 11120b57cec5SDimitry Andric assert(LI.end() != LI.begin() && 11130b57cec5SDimitry Andric "Reg should not have empty live interval."); 11140b57cec5SDimitry Andric 11150b57cec5SDimitry Andric SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot(); 11160b57cec5SDimitry Andric LiveInterval::const_iterator I = LI.find(MBBEndIdx); 11170b57cec5SDimitry Andric if (I != LI.end() && I->start < MBBEndIdx) 11180b57cec5SDimitry Andric return false; 11190b57cec5SDimitry Andric 11200b57cec5SDimitry Andric --I; 11210b57cec5SDimitry Andric KillMI = LIS->getInstructionFromIndex(I->end); 11220b57cec5SDimitry Andric } else { 11230b57cec5SDimitry Andric KillMI = LV->getVarInfo(Reg).findKill(MBB); 11240b57cec5SDimitry Andric } 11250b57cec5SDimitry Andric if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike()) 11260b57cec5SDimitry Andric // Don't mess with copies, they may be coalesced later. 11270b57cec5SDimitry Andric return false; 11280b57cec5SDimitry Andric 1129e8d8bef9SDimitry Andric Register DstReg; 11300b57cec5SDimitry Andric if (isTwoAddrUse(*KillMI, Reg, DstReg)) 11310b57cec5SDimitry Andric return false; 11320b57cec5SDimitry Andric 11330b57cec5SDimitry Andric bool SeenStore = true; 11340b57cec5SDimitry Andric if (!KillMI->isSafeToMove(AA, SeenStore)) 11350b57cec5SDimitry Andric return false; 11360b57cec5SDimitry Andric 1137e8d8bef9SDimitry Andric SmallVector<Register, 2> Uses; 1138e8d8bef9SDimitry Andric SmallVector<Register, 2> Kills; 1139e8d8bef9SDimitry Andric SmallVector<Register, 2> Defs; 1140e8d8bef9SDimitry Andric SmallVector<Register, 2> LiveDefs; 11410b57cec5SDimitry Andric for (const MachineOperand &MO : KillMI->operands()) { 11420b57cec5SDimitry Andric if (!MO.isReg()) 11430b57cec5SDimitry Andric continue; 11448bcb0991SDimitry Andric Register MOReg = MO.getReg(); 11450b57cec5SDimitry Andric if (MO.isUse()) { 11460b57cec5SDimitry Andric if (!MOReg) 11470b57cec5SDimitry Andric continue; 11480b57cec5SDimitry Andric if (isDefTooClose(MOReg, DI->second, MI)) 11490b57cec5SDimitry Andric return false; 11505f757f3fSDimitry Andric bool isKill = isPlainlyKilled(MO); 11510b57cec5SDimitry Andric if (MOReg == Reg && !isKill) 11520b57cec5SDimitry Andric return false; 1153e8d8bef9SDimitry Andric Uses.push_back(MOReg); 11540b57cec5SDimitry Andric if (isKill && MOReg != Reg) 1155e8d8bef9SDimitry Andric Kills.push_back(MOReg); 1156e8d8bef9SDimitry Andric } else if (MOReg.isPhysical()) { 1157e8d8bef9SDimitry Andric Defs.push_back(MOReg); 11580b57cec5SDimitry Andric if (!MO.isDead()) 1159e8d8bef9SDimitry Andric LiveDefs.push_back(MOReg); 11600b57cec5SDimitry Andric } 11610b57cec5SDimitry Andric } 11620b57cec5SDimitry Andric 11630b57cec5SDimitry Andric // Check if the reschedule will not break depedencies. 11640b57cec5SDimitry Andric unsigned NumVisited = 0; 11650b57cec5SDimitry Andric for (MachineInstr &OtherMI : 11660b57cec5SDimitry Andric make_range(mi, MachineBasicBlock::iterator(KillMI))) { 1167d409305fSDimitry Andric // Debug or pseudo instructions cannot be counted against the limit. 1168d409305fSDimitry Andric if (OtherMI.isDebugOrPseudoInstr()) 11690b57cec5SDimitry Andric continue; 11700b57cec5SDimitry Andric if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost. 11710b57cec5SDimitry Andric return false; 11720b57cec5SDimitry Andric ++NumVisited; 11730b57cec5SDimitry Andric if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() || 11740b57cec5SDimitry Andric OtherMI.isBranch() || OtherMI.isTerminator()) 11750b57cec5SDimitry Andric // Don't move pass calls, etc. 11760b57cec5SDimitry Andric return false; 1177e8d8bef9SDimitry Andric SmallVector<Register, 2> OtherDefs; 11780b57cec5SDimitry Andric for (const MachineOperand &MO : OtherMI.operands()) { 11790b57cec5SDimitry Andric if (!MO.isReg()) 11800b57cec5SDimitry Andric continue; 11818bcb0991SDimitry Andric Register MOReg = MO.getReg(); 11820b57cec5SDimitry Andric if (!MOReg) 11830b57cec5SDimitry Andric continue; 11840b57cec5SDimitry Andric if (MO.isUse()) { 11855f757f3fSDimitry Andric if (regOverlapsSet(Defs, MOReg)) 11860b57cec5SDimitry Andric // Moving KillMI can clobber the physical register if the def has 11870b57cec5SDimitry Andric // not been seen. 11880b57cec5SDimitry Andric return false; 11895f757f3fSDimitry Andric if (regOverlapsSet(Kills, MOReg)) 11900b57cec5SDimitry Andric // Don't want to extend other live ranges and update kills. 11910b57cec5SDimitry Andric return false; 11925f757f3fSDimitry Andric if (&OtherMI != MI && MOReg == Reg && !isPlainlyKilled(MO)) 11930b57cec5SDimitry Andric // We can't schedule across a use of the register in question. 11940b57cec5SDimitry Andric return false; 11950b57cec5SDimitry Andric } else { 11960b57cec5SDimitry Andric OtherDefs.push_back(MOReg); 11970b57cec5SDimitry Andric } 11980b57cec5SDimitry Andric } 11990b57cec5SDimitry Andric 1200cb14a3feSDimitry Andric for (Register MOReg : OtherDefs) { 12015f757f3fSDimitry Andric if (regOverlapsSet(Uses, MOReg)) 12020b57cec5SDimitry Andric return false; 12035f757f3fSDimitry Andric if (MOReg.isPhysical() && regOverlapsSet(LiveDefs, MOReg)) 12040b57cec5SDimitry Andric return false; 12050b57cec5SDimitry Andric // Physical register def is seen. 12065f757f3fSDimitry Andric llvm::erase(Defs, MOReg); 12070b57cec5SDimitry Andric } 12080b57cec5SDimitry Andric } 12090b57cec5SDimitry Andric 12100b57cec5SDimitry Andric // Move the old kill above MI, don't forget to move debug info as well. 12110b57cec5SDimitry Andric MachineBasicBlock::iterator InsertPos = mi; 12120b57cec5SDimitry Andric while (InsertPos != MBB->begin() && std::prev(InsertPos)->isDebugInstr()) 12130b57cec5SDimitry Andric --InsertPos; 12140b57cec5SDimitry Andric MachineBasicBlock::iterator From = KillMI; 12150b57cec5SDimitry Andric MachineBasicBlock::iterator To = std::next(From); 12160b57cec5SDimitry Andric while (std::prev(From)->isDebugInstr()) 12170b57cec5SDimitry Andric --From; 12180b57cec5SDimitry Andric MBB->splice(InsertPos, MBB, From, To); 12190b57cec5SDimitry Andric 12200b57cec5SDimitry Andric nmi = std::prev(InsertPos); // Backtrack so we process the moved instr. 12210b57cec5SDimitry Andric DistanceMap.erase(DI); 12220b57cec5SDimitry Andric 12230b57cec5SDimitry Andric // Update live variables 12240b57cec5SDimitry Andric if (LIS) { 12250b57cec5SDimitry Andric LIS->handleMove(*KillMI); 12260b57cec5SDimitry Andric } else { 12270b57cec5SDimitry Andric LV->removeVirtualRegisterKilled(Reg, *KillMI); 12280b57cec5SDimitry Andric LV->addVirtualRegisterKilled(Reg, *MI); 12290b57cec5SDimitry Andric } 12300b57cec5SDimitry Andric 12310b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\trescheduled kill: " << *KillMI); 12320b57cec5SDimitry Andric return true; 12330b57cec5SDimitry Andric } 12340b57cec5SDimitry Andric 12350b57cec5SDimitry Andric /// Tries to commute the operand 'BaseOpIdx' and some other operand in the 12360b57cec5SDimitry Andric /// given machine instruction to improve opportunities for coalescing and 12370b57cec5SDimitry Andric /// elimination of a register to register copy. 12380b57cec5SDimitry Andric /// 12390b57cec5SDimitry Andric /// 'DstOpIdx' specifies the index of MI def operand. 12400b57cec5SDimitry Andric /// 'BaseOpKilled' specifies if the register associated with 'BaseOpIdx' 12410b57cec5SDimitry Andric /// operand is killed by the given instruction. 12420b57cec5SDimitry Andric /// The 'Dist' arguments provides the distance of MI from the start of the 12430b57cec5SDimitry Andric /// current basic block and it is used to determine if it is profitable 12440b57cec5SDimitry Andric /// to commute operands in the instruction. 12450b57cec5SDimitry Andric /// 12460b57cec5SDimitry Andric /// Returns true if the transformation happened. Otherwise, returns false. 1247*0fca6ea1SDimitry Andric bool TwoAddressInstructionImpl::tryInstructionCommute(MachineInstr *MI, 12480b57cec5SDimitry Andric unsigned DstOpIdx, 12490b57cec5SDimitry Andric unsigned BaseOpIdx, 12500b57cec5SDimitry Andric bool BaseOpKilled, 12510b57cec5SDimitry Andric unsigned Dist) { 12520b57cec5SDimitry Andric if (!MI->isCommutable()) 12530b57cec5SDimitry Andric return false; 12540b57cec5SDimitry Andric 12550b57cec5SDimitry Andric bool MadeChange = false; 12568bcb0991SDimitry Andric Register DstOpReg = MI->getOperand(DstOpIdx).getReg(); 12578bcb0991SDimitry Andric Register BaseOpReg = MI->getOperand(BaseOpIdx).getReg(); 12580b57cec5SDimitry Andric unsigned OpsNum = MI->getDesc().getNumOperands(); 12590b57cec5SDimitry Andric unsigned OtherOpIdx = MI->getDesc().getNumDefs(); 12600b57cec5SDimitry Andric for (; OtherOpIdx < OpsNum; OtherOpIdx++) { 12610b57cec5SDimitry Andric // The call of findCommutedOpIndices below only checks if BaseOpIdx 12620b57cec5SDimitry Andric // and OtherOpIdx are commutable, it does not really search for 12630b57cec5SDimitry Andric // other commutable operands and does not change the values of passed 12640b57cec5SDimitry Andric // variables. 12650b57cec5SDimitry Andric if (OtherOpIdx == BaseOpIdx || !MI->getOperand(OtherOpIdx).isReg() || 12660b57cec5SDimitry Andric !TII->findCommutedOpIndices(*MI, BaseOpIdx, OtherOpIdx)) 12670b57cec5SDimitry Andric continue; 12680b57cec5SDimitry Andric 12698bcb0991SDimitry Andric Register OtherOpReg = MI->getOperand(OtherOpIdx).getReg(); 12700b57cec5SDimitry Andric bool AggressiveCommute = false; 12710b57cec5SDimitry Andric 12720b57cec5SDimitry Andric // If OtherOp dies but BaseOp does not, swap the OtherOp and BaseOp 12730b57cec5SDimitry Andric // operands. This makes the live ranges of DstOp and OtherOp joinable. 12745f757f3fSDimitry Andric bool OtherOpKilled = isKilled(*MI, OtherOpReg, false); 12750b57cec5SDimitry Andric bool DoCommute = !BaseOpKilled && OtherOpKilled; 12760b57cec5SDimitry Andric 12770b57cec5SDimitry Andric if (!DoCommute && 12780b57cec5SDimitry Andric isProfitableToCommute(DstOpReg, BaseOpReg, OtherOpReg, MI, Dist)) { 12790b57cec5SDimitry Andric DoCommute = true; 12800b57cec5SDimitry Andric AggressiveCommute = true; 12810b57cec5SDimitry Andric } 12820b57cec5SDimitry Andric 12830b57cec5SDimitry Andric // If it's profitable to commute, try to do so. 12840b57cec5SDimitry Andric if (DoCommute && commuteInstruction(MI, DstOpIdx, BaseOpIdx, OtherOpIdx, 12850b57cec5SDimitry Andric Dist)) { 12860b57cec5SDimitry Andric MadeChange = true; 12870b57cec5SDimitry Andric ++NumCommuted; 12885ffd83dbSDimitry Andric if (AggressiveCommute) 12890b57cec5SDimitry Andric ++NumAggrCommuted; 12905ffd83dbSDimitry Andric 12910b57cec5SDimitry Andric // There might be more than two commutable operands, update BaseOp and 12920b57cec5SDimitry Andric // continue scanning. 12930b57cec5SDimitry Andric // FIXME: This assumes that the new instruction's operands are in the 12940b57cec5SDimitry Andric // same positions and were simply swapped. 12950b57cec5SDimitry Andric BaseOpReg = OtherOpReg; 12960b57cec5SDimitry Andric BaseOpKilled = OtherOpKilled; 12970b57cec5SDimitry Andric // Resamples OpsNum in case the number of operands was reduced. This 12980b57cec5SDimitry Andric // happens with X86. 12990b57cec5SDimitry Andric OpsNum = MI->getDesc().getNumOperands(); 13000b57cec5SDimitry Andric } 13010b57cec5SDimitry Andric } 13020b57cec5SDimitry Andric return MadeChange; 13030b57cec5SDimitry Andric } 13040b57cec5SDimitry Andric 13050b57cec5SDimitry Andric /// For the case where an instruction has a single pair of tied register 13060b57cec5SDimitry Andric /// operands, attempt some transformations that may either eliminate the tied 13070b57cec5SDimitry Andric /// operands or improve the opportunities for coalescing away the register copy. 13080b57cec5SDimitry Andric /// Returns true if no copy needs to be inserted to untie mi's operands 13090b57cec5SDimitry Andric /// (either because they were untied, or because mi was rescheduled, and will 13100b57cec5SDimitry Andric /// be visited again later). If the shouldOnlyCommute flag is true, only 13110b57cec5SDimitry Andric /// instruction commutation is attempted. 1312*0fca6ea1SDimitry Andric bool TwoAddressInstructionImpl::tryInstructionTransform( 1313*0fca6ea1SDimitry Andric MachineBasicBlock::iterator &mi, MachineBasicBlock::iterator &nmi, 1314*0fca6ea1SDimitry Andric unsigned SrcIdx, unsigned DstIdx, unsigned &Dist, bool shouldOnlyCommute) { 13155f757f3fSDimitry Andric if (OptLevel == CodeGenOptLevel::None) 13160b57cec5SDimitry Andric return false; 13170b57cec5SDimitry Andric 13180b57cec5SDimitry Andric MachineInstr &MI = *mi; 13198bcb0991SDimitry Andric Register regA = MI.getOperand(DstIdx).getReg(); 13208bcb0991SDimitry Andric Register regB = MI.getOperand(SrcIdx).getReg(); 13210b57cec5SDimitry Andric 1322e8d8bef9SDimitry Andric assert(regB.isVirtual() && "cannot make instruction into two-address form"); 13235f757f3fSDimitry Andric bool regBKilled = isKilled(MI, regB, true); 13240b57cec5SDimitry Andric 1325e8d8bef9SDimitry Andric if (regA.isVirtual()) 13260b57cec5SDimitry Andric scanUses(regA); 13270b57cec5SDimitry Andric 13280b57cec5SDimitry Andric bool Commuted = tryInstructionCommute(&MI, DstIdx, SrcIdx, regBKilled, Dist); 13290b57cec5SDimitry Andric 13300b57cec5SDimitry Andric // If the instruction is convertible to 3 Addr, instead 1331480093f4SDimitry Andric // of returning try 3 Addr transformation aggressively and 13320b57cec5SDimitry Andric // use this variable to check later. Because it might be better. 13330b57cec5SDimitry Andric // For example, we can just use `leal (%rsi,%rdi), %eax` and `ret` 13340b57cec5SDimitry Andric // instead of the following code. 13350b57cec5SDimitry Andric // addl %esi, %edi 13360b57cec5SDimitry Andric // movl %edi, %eax 13370b57cec5SDimitry Andric // ret 13380b57cec5SDimitry Andric if (Commuted && !MI.isConvertibleTo3Addr()) 13390b57cec5SDimitry Andric return false; 13400b57cec5SDimitry Andric 13410b57cec5SDimitry Andric if (shouldOnlyCommute) 13420b57cec5SDimitry Andric return false; 13430b57cec5SDimitry Andric 13440b57cec5SDimitry Andric // If there is one more use of regB later in the same MBB, consider 13450b57cec5SDimitry Andric // re-schedule this MI below it. 13460b57cec5SDimitry Andric if (!Commuted && EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) { 13470b57cec5SDimitry Andric ++NumReSchedDowns; 13480b57cec5SDimitry Andric return true; 13490b57cec5SDimitry Andric } 13500b57cec5SDimitry Andric 13510b57cec5SDimitry Andric // If we commuted, regB may have changed so we should re-sample it to avoid 13520b57cec5SDimitry Andric // confusing the three address conversion below. 13530b57cec5SDimitry Andric if (Commuted) { 13540b57cec5SDimitry Andric regB = MI.getOperand(SrcIdx).getReg(); 13555f757f3fSDimitry Andric regBKilled = isKilled(MI, regB, true); 13560b57cec5SDimitry Andric } 13570b57cec5SDimitry Andric 13580b57cec5SDimitry Andric if (MI.isConvertibleTo3Addr()) { 13590b57cec5SDimitry Andric // This instruction is potentially convertible to a true 13600b57cec5SDimitry Andric // three-address instruction. Check if it is profitable. 13610b57cec5SDimitry Andric if (!regBKilled || isProfitableToConv3Addr(regA, regB)) { 13620b57cec5SDimitry Andric // Try to convert it. 13630b57cec5SDimitry Andric if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) { 13640b57cec5SDimitry Andric ++NumConvertedTo3Addr; 13650b57cec5SDimitry Andric return true; // Done with this instruction. 13660b57cec5SDimitry Andric } 13670b57cec5SDimitry Andric } 13680b57cec5SDimitry Andric } 13690b57cec5SDimitry Andric 13700b57cec5SDimitry Andric // Return if it is commuted but 3 addr conversion is failed. 13710b57cec5SDimitry Andric if (Commuted) 13720b57cec5SDimitry Andric return false; 13730b57cec5SDimitry Andric 13740b57cec5SDimitry Andric // If there is one more use of regB later in the same MBB, consider 13750b57cec5SDimitry Andric // re-schedule it before this MI if it's legal. 13760b57cec5SDimitry Andric if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) { 13770b57cec5SDimitry Andric ++NumReSchedUps; 13780b57cec5SDimitry Andric return true; 13790b57cec5SDimitry Andric } 13800b57cec5SDimitry Andric 13810b57cec5SDimitry Andric // If this is an instruction with a load folded into it, try unfolding 13820b57cec5SDimitry Andric // the load, e.g. avoid this: 13830b57cec5SDimitry Andric // movq %rdx, %rcx 13840b57cec5SDimitry Andric // addq (%rax), %rcx 13850b57cec5SDimitry Andric // in favor of this: 13860b57cec5SDimitry Andric // movq (%rax), %rcx 13870b57cec5SDimitry Andric // addq %rdx, %rcx 13880b57cec5SDimitry Andric // because it's preferable to schedule a load than a register copy. 13890b57cec5SDimitry Andric if (MI.mayLoad() && !regBKilled) { 13900b57cec5SDimitry Andric // Determine if a load can be unfolded. 13910b57cec5SDimitry Andric unsigned LoadRegIndex; 13920b57cec5SDimitry Andric unsigned NewOpc = 13930b57cec5SDimitry Andric TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), 13940b57cec5SDimitry Andric /*UnfoldLoad=*/true, 13950b57cec5SDimitry Andric /*UnfoldStore=*/false, 13960b57cec5SDimitry Andric &LoadRegIndex); 13970b57cec5SDimitry Andric if (NewOpc != 0) { 13980b57cec5SDimitry Andric const MCInstrDesc &UnfoldMCID = TII->get(NewOpc); 13990b57cec5SDimitry Andric if (UnfoldMCID.getNumDefs() == 1) { 14000b57cec5SDimitry Andric // Unfold the load. 14010b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: UNFOLDING: " << MI); 14020b57cec5SDimitry Andric const TargetRegisterClass *RC = 14030b57cec5SDimitry Andric TRI->getAllocatableClass( 14040b57cec5SDimitry Andric TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF)); 14058bcb0991SDimitry Andric Register Reg = MRI->createVirtualRegister(RC); 14060b57cec5SDimitry Andric SmallVector<MachineInstr *, 2> NewMIs; 14070b57cec5SDimitry Andric if (!TII->unfoldMemoryOperand(*MF, MI, Reg, 14080b57cec5SDimitry Andric /*UnfoldLoad=*/true, 14090b57cec5SDimitry Andric /*UnfoldStore=*/false, NewMIs)) { 14100b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n"); 14110b57cec5SDimitry Andric return false; 14120b57cec5SDimitry Andric } 14130b57cec5SDimitry Andric assert(NewMIs.size() == 2 && 14140b57cec5SDimitry Andric "Unfolded a load into multiple instructions!"); 14150b57cec5SDimitry Andric // The load was previously folded, so this is the only use. 14160b57cec5SDimitry Andric NewMIs[1]->addRegisterKilled(Reg, TRI); 14170b57cec5SDimitry Andric 14180b57cec5SDimitry Andric // Tentatively insert the instructions into the block so that they 14190b57cec5SDimitry Andric // look "normal" to the transformation logic. 14200b57cec5SDimitry Andric MBB->insert(mi, NewMIs[0]); 14210b57cec5SDimitry Andric MBB->insert(mi, NewMIs[1]); 1422349cc55cSDimitry Andric DistanceMap.insert(std::make_pair(NewMIs[0], Dist++)); 1423349cc55cSDimitry Andric DistanceMap.insert(std::make_pair(NewMIs[1], Dist)); 14240b57cec5SDimitry Andric 14250b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0] 14260b57cec5SDimitry Andric << "2addr: NEW INST: " << *NewMIs[1]); 14270b57cec5SDimitry Andric 14280b57cec5SDimitry Andric // Transform the instruction, now that it no longer has a load. 1429*0fca6ea1SDimitry Andric unsigned NewDstIdx = 1430*0fca6ea1SDimitry Andric NewMIs[1]->findRegisterDefOperandIdx(regA, /*TRI=*/nullptr); 1431*0fca6ea1SDimitry Andric unsigned NewSrcIdx = 1432*0fca6ea1SDimitry Andric NewMIs[1]->findRegisterUseOperandIdx(regB, /*TRI=*/nullptr); 14330b57cec5SDimitry Andric MachineBasicBlock::iterator NewMI = NewMIs[1]; 14340b57cec5SDimitry Andric bool TransformResult = 14350b57cec5SDimitry Andric tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true); 14360b57cec5SDimitry Andric (void)TransformResult; 14370b57cec5SDimitry Andric assert(!TransformResult && 14380b57cec5SDimitry Andric "tryInstructionTransform() should return false."); 14390b57cec5SDimitry Andric if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) { 14400b57cec5SDimitry Andric // Success, or at least we made an improvement. Keep the unfolded 14410b57cec5SDimitry Andric // instructions and discard the original. 14420b57cec5SDimitry Andric if (LV) { 14434824e7fdSDimitry Andric for (const MachineOperand &MO : MI.operands()) { 1444e8d8bef9SDimitry Andric if (MO.isReg() && MO.getReg().isVirtual()) { 14450b57cec5SDimitry Andric if (MO.isUse()) { 14460b57cec5SDimitry Andric if (MO.isKill()) { 1447*0fca6ea1SDimitry Andric if (NewMIs[0]->killsRegister(MO.getReg(), /*TRI=*/nullptr)) 14480b57cec5SDimitry Andric LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[0]); 14490b57cec5SDimitry Andric else { 1450*0fca6ea1SDimitry Andric assert(NewMIs[1]->killsRegister(MO.getReg(), 1451*0fca6ea1SDimitry Andric /*TRI=*/nullptr) && 14520b57cec5SDimitry Andric "Kill missing after load unfold!"); 14530b57cec5SDimitry Andric LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[1]); 14540b57cec5SDimitry Andric } 14550b57cec5SDimitry Andric } 14560b57cec5SDimitry Andric } else if (LV->removeVirtualRegisterDead(MO.getReg(), MI)) { 1457*0fca6ea1SDimitry Andric if (NewMIs[1]->registerDefIsDead(MO.getReg(), 1458*0fca6ea1SDimitry Andric /*TRI=*/nullptr)) 14590b57cec5SDimitry Andric LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[1]); 14600b57cec5SDimitry Andric else { 1461*0fca6ea1SDimitry Andric assert(NewMIs[0]->registerDefIsDead(MO.getReg(), 1462*0fca6ea1SDimitry Andric /*TRI=*/nullptr) && 14630b57cec5SDimitry Andric "Dead flag missing after load unfold!"); 14640b57cec5SDimitry Andric LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[0]); 14650b57cec5SDimitry Andric } 14660b57cec5SDimitry Andric } 14670b57cec5SDimitry Andric } 14680b57cec5SDimitry Andric } 14690b57cec5SDimitry Andric LV->addVirtualRegisterKilled(Reg, *NewMIs[1]); 14700b57cec5SDimitry Andric } 14710b57cec5SDimitry Andric 14725ffd83dbSDimitry Andric SmallVector<Register, 4> OrigRegs; 14730b57cec5SDimitry Andric if (LIS) { 14740b57cec5SDimitry Andric for (const MachineOperand &MO : MI.operands()) { 14750b57cec5SDimitry Andric if (MO.isReg()) 14760b57cec5SDimitry Andric OrigRegs.push_back(MO.getReg()); 14770b57cec5SDimitry Andric } 1478349cc55cSDimitry Andric 1479349cc55cSDimitry Andric LIS->RemoveMachineInstrFromMaps(MI); 14800b57cec5SDimitry Andric } 14810b57cec5SDimitry Andric 14820b57cec5SDimitry Andric MI.eraseFromParent(); 1483349cc55cSDimitry Andric DistanceMap.erase(&MI); 14840b57cec5SDimitry Andric 14850b57cec5SDimitry Andric // Update LiveIntervals. 14860b57cec5SDimitry Andric if (LIS) { 14870b57cec5SDimitry Andric MachineBasicBlock::iterator Begin(NewMIs[0]); 14880b57cec5SDimitry Andric MachineBasicBlock::iterator End(NewMIs[1]); 14890b57cec5SDimitry Andric LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs); 14900b57cec5SDimitry Andric } 14910b57cec5SDimitry Andric 14920b57cec5SDimitry Andric mi = NewMIs[1]; 14930b57cec5SDimitry Andric } else { 14940b57cec5SDimitry Andric // Transforming didn't eliminate the tie and didn't lead to an 14950b57cec5SDimitry Andric // improvement. Clean up the unfolded instructions and keep the 14960b57cec5SDimitry Andric // original. 14970b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n"); 14980b57cec5SDimitry Andric NewMIs[0]->eraseFromParent(); 14990b57cec5SDimitry Andric NewMIs[1]->eraseFromParent(); 1500349cc55cSDimitry Andric DistanceMap.erase(NewMIs[0]); 1501349cc55cSDimitry Andric DistanceMap.erase(NewMIs[1]); 1502349cc55cSDimitry Andric Dist--; 15030b57cec5SDimitry Andric } 15040b57cec5SDimitry Andric } 15050b57cec5SDimitry Andric } 15060b57cec5SDimitry Andric } 15070b57cec5SDimitry Andric 15080b57cec5SDimitry Andric return false; 15090b57cec5SDimitry Andric } 15100b57cec5SDimitry Andric 15110b57cec5SDimitry Andric // Collect tied operands of MI that need to be handled. 15120b57cec5SDimitry Andric // Rewrite trivial cases immediately. 15130b57cec5SDimitry Andric // Return true if any tied operands where found, including the trivial ones. 1514*0fca6ea1SDimitry Andric bool TwoAddressInstructionImpl::collectTiedOperands( 1515*0fca6ea1SDimitry Andric MachineInstr *MI, TiedOperandMap &TiedOperands) { 15160b57cec5SDimitry Andric bool AnyOps = false; 15170b57cec5SDimitry Andric unsigned NumOps = MI->getNumOperands(); 15180b57cec5SDimitry Andric 15190b57cec5SDimitry Andric for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) { 15200b57cec5SDimitry Andric unsigned DstIdx = 0; 15210b57cec5SDimitry Andric if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx)) 15220b57cec5SDimitry Andric continue; 15230b57cec5SDimitry Andric AnyOps = true; 15240b57cec5SDimitry Andric MachineOperand &SrcMO = MI->getOperand(SrcIdx); 15250b57cec5SDimitry Andric MachineOperand &DstMO = MI->getOperand(DstIdx); 15268bcb0991SDimitry Andric Register SrcReg = SrcMO.getReg(); 15278bcb0991SDimitry Andric Register DstReg = DstMO.getReg(); 15280b57cec5SDimitry Andric // Tied constraint already satisfied? 15290b57cec5SDimitry Andric if (SrcReg == DstReg) 15300b57cec5SDimitry Andric continue; 15310b57cec5SDimitry Andric 15320b57cec5SDimitry Andric assert(SrcReg && SrcMO.isUse() && "two address instruction invalid"); 15330b57cec5SDimitry Andric 15340b57cec5SDimitry Andric // Deal with undef uses immediately - simply rewrite the src operand. 15350b57cec5SDimitry Andric if (SrcMO.isUndef() && !DstMO.getSubReg()) { 15360b57cec5SDimitry Andric // Constrain the DstReg register class if required. 1537349cc55cSDimitry Andric if (DstReg.isVirtual()) { 1538349cc55cSDimitry Andric const TargetRegisterClass *RC = MRI->getRegClass(SrcReg); 15390b57cec5SDimitry Andric MRI->constrainRegClass(DstReg, RC); 1540349cc55cSDimitry Andric } 15410b57cec5SDimitry Andric SrcMO.setReg(DstReg); 15420b57cec5SDimitry Andric SrcMO.setSubReg(0); 15430b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI); 15440b57cec5SDimitry Andric continue; 15450b57cec5SDimitry Andric } 15460b57cec5SDimitry Andric TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx)); 15470b57cec5SDimitry Andric } 15480b57cec5SDimitry Andric return AnyOps; 15490b57cec5SDimitry Andric } 15500b57cec5SDimitry Andric 15510b57cec5SDimitry Andric // Process a list of tied MI operands that all use the same source register. 15520b57cec5SDimitry Andric // The tied pairs are of the form (SrcIdx, DstIdx). 1553*0fca6ea1SDimitry Andric void TwoAddressInstructionImpl::processTiedPairs(MachineInstr *MI, 15540b57cec5SDimitry Andric TiedPairList &TiedPairs, 15550b57cec5SDimitry Andric unsigned &Dist) { 1556fcaf7f86SDimitry Andric bool IsEarlyClobber = llvm::any_of(TiedPairs, [MI](auto const &TP) { 1557fe6060f1SDimitry Andric return MI->getOperand(TP.second).isEarlyClobber(); 1558fcaf7f86SDimitry Andric }); 15590b57cec5SDimitry Andric 15600b57cec5SDimitry Andric bool RemovedKillFlag = false; 15610b57cec5SDimitry Andric bool AllUsesCopied = true; 15620b57cec5SDimitry Andric unsigned LastCopiedReg = 0; 15630b57cec5SDimitry Andric SlotIndex LastCopyIdx; 1564e8d8bef9SDimitry Andric Register RegB = 0; 15650b57cec5SDimitry Andric unsigned SubRegB = 0; 1566fe6060f1SDimitry Andric for (auto &TP : TiedPairs) { 1567fe6060f1SDimitry Andric unsigned SrcIdx = TP.first; 1568fe6060f1SDimitry Andric unsigned DstIdx = TP.second; 15690b57cec5SDimitry Andric 15700b57cec5SDimitry Andric const MachineOperand &DstMO = MI->getOperand(DstIdx); 15718bcb0991SDimitry Andric Register RegA = DstMO.getReg(); 15720b57cec5SDimitry Andric 15730b57cec5SDimitry Andric // Grab RegB from the instruction because it may have changed if the 15740b57cec5SDimitry Andric // instruction was commuted. 15750b57cec5SDimitry Andric RegB = MI->getOperand(SrcIdx).getReg(); 15760b57cec5SDimitry Andric SubRegB = MI->getOperand(SrcIdx).getSubReg(); 15770b57cec5SDimitry Andric 15780b57cec5SDimitry Andric if (RegA == RegB) { 15790b57cec5SDimitry Andric // The register is tied to multiple destinations (or else we would 15800b57cec5SDimitry Andric // not have continued this far), but this use of the register 15810b57cec5SDimitry Andric // already matches the tied destination. Leave it. 15820b57cec5SDimitry Andric AllUsesCopied = false; 15830b57cec5SDimitry Andric continue; 15840b57cec5SDimitry Andric } 15850b57cec5SDimitry Andric LastCopiedReg = RegA; 15860b57cec5SDimitry Andric 1587e8d8bef9SDimitry Andric assert(RegB.isVirtual() && "cannot make instruction into two-address form"); 15880b57cec5SDimitry Andric 15890b57cec5SDimitry Andric #ifndef NDEBUG 15900b57cec5SDimitry Andric // First, verify that we don't have a use of "a" in the instruction 15910b57cec5SDimitry Andric // (a = b + a for example) because our transformation will not 15920b57cec5SDimitry Andric // work. This should never occur because we are in SSA form. 15930b57cec5SDimitry Andric for (unsigned i = 0; i != MI->getNumOperands(); ++i) 15940b57cec5SDimitry Andric assert(i == DstIdx || 15950b57cec5SDimitry Andric !MI->getOperand(i).isReg() || 15960b57cec5SDimitry Andric MI->getOperand(i).getReg() != RegA); 15970b57cec5SDimitry Andric #endif 15980b57cec5SDimitry Andric 15990b57cec5SDimitry Andric // Emit a copy. 16000b57cec5SDimitry Andric MachineInstrBuilder MIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), 16010b57cec5SDimitry Andric TII->get(TargetOpcode::COPY), RegA); 16020b57cec5SDimitry Andric // If this operand is folding a truncation, the truncation now moves to the 16030b57cec5SDimitry Andric // copy so that the register classes remain valid for the operands. 16040b57cec5SDimitry Andric MIB.addReg(RegB, 0, SubRegB); 16050b57cec5SDimitry Andric const TargetRegisterClass *RC = MRI->getRegClass(RegB); 16060b57cec5SDimitry Andric if (SubRegB) { 1607e8d8bef9SDimitry Andric if (RegA.isVirtual()) { 16080b57cec5SDimitry Andric assert(TRI->getMatchingSuperRegClass(RC, MRI->getRegClass(RegA), 16090b57cec5SDimitry Andric SubRegB) && 16100b57cec5SDimitry Andric "tied subregister must be a truncation"); 16110b57cec5SDimitry Andric // The superreg class will not be used to constrain the subreg class. 16120b57cec5SDimitry Andric RC = nullptr; 16138bcb0991SDimitry Andric } else { 16140b57cec5SDimitry Andric assert(TRI->getMatchingSuperReg(RegA, SubRegB, MRI->getRegClass(RegB)) 16150b57cec5SDimitry Andric && "tied subregister must be a truncation"); 16160b57cec5SDimitry Andric } 16170b57cec5SDimitry Andric } 16180b57cec5SDimitry Andric 16190b57cec5SDimitry Andric // Update DistanceMap. 16200b57cec5SDimitry Andric MachineBasicBlock::iterator PrevMI = MI; 16210b57cec5SDimitry Andric --PrevMI; 16220b57cec5SDimitry Andric DistanceMap.insert(std::make_pair(&*PrevMI, Dist)); 16230b57cec5SDimitry Andric DistanceMap[MI] = ++Dist; 16240b57cec5SDimitry Andric 16250b57cec5SDimitry Andric if (LIS) { 16260b57cec5SDimitry Andric LastCopyIdx = LIS->InsertMachineInstrInMaps(*PrevMI).getRegSlot(); 16270b57cec5SDimitry Andric 1628349cc55cSDimitry Andric SlotIndex endIdx = 1629349cc55cSDimitry Andric LIS->getInstructionIndex(*MI).getRegSlot(IsEarlyClobber); 1630e8d8bef9SDimitry Andric if (RegA.isVirtual()) { 16310b57cec5SDimitry Andric LiveInterval &LI = LIS->getInterval(RegA); 16320b57cec5SDimitry Andric VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator()); 1633349cc55cSDimitry Andric LI.addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI)); 1634349cc55cSDimitry Andric for (auto &S : LI.subranges()) { 1635349cc55cSDimitry Andric VNI = S.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator()); 1636349cc55cSDimitry Andric S.addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI)); 1637349cc55cSDimitry Andric } 1638349cc55cSDimitry Andric } else { 163906c3fb27SDimitry Andric for (MCRegUnit Unit : TRI->regunits(RegA)) { 164006c3fb27SDimitry Andric if (LiveRange *LR = LIS->getCachedRegUnit(Unit)) { 1641349cc55cSDimitry Andric VNInfo *VNI = 1642349cc55cSDimitry Andric LR->getNextValue(LastCopyIdx, LIS->getVNInfoAllocator()); 1643349cc55cSDimitry Andric LR->addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI)); 1644349cc55cSDimitry Andric } 1645349cc55cSDimitry Andric } 16460b57cec5SDimitry Andric } 16470b57cec5SDimitry Andric } 16480b57cec5SDimitry Andric 16490b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\t\tprepend:\t" << *MIB); 16500b57cec5SDimitry Andric 16510b57cec5SDimitry Andric MachineOperand &MO = MI->getOperand(SrcIdx); 16520b57cec5SDimitry Andric assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() && 16530b57cec5SDimitry Andric "inconsistent operand info for 2-reg pass"); 16545f757f3fSDimitry Andric if (isPlainlyKilled(MO)) { 16550b57cec5SDimitry Andric MO.setIsKill(false); 16560b57cec5SDimitry Andric RemovedKillFlag = true; 16570b57cec5SDimitry Andric } 16580b57cec5SDimitry Andric 16590b57cec5SDimitry Andric // Make sure regA is a legal regclass for the SrcIdx operand. 1660e8d8bef9SDimitry Andric if (RegA.isVirtual() && RegB.isVirtual()) 16610b57cec5SDimitry Andric MRI->constrainRegClass(RegA, RC); 16620b57cec5SDimitry Andric MO.setReg(RegA); 16630b57cec5SDimitry Andric // The getMatchingSuper asserts guarantee that the register class projected 16640b57cec5SDimitry Andric // by SubRegB is compatible with RegA with no subregister. So regardless of 16650b57cec5SDimitry Andric // whether the dest oper writes a subreg, the source oper should not. 16660b57cec5SDimitry Andric MO.setSubReg(0); 16670b57cec5SDimitry Andric } 16680b57cec5SDimitry Andric 16690b57cec5SDimitry Andric if (AllUsesCopied) { 1670349cc55cSDimitry Andric LaneBitmask RemainingUses = LaneBitmask::getNone(); 16710b57cec5SDimitry Andric // Replace other (un-tied) uses of regB with LastCopiedReg. 167206c3fb27SDimitry Andric for (MachineOperand &MO : MI->all_uses()) { 167306c3fb27SDimitry Andric if (MO.getReg() == RegB) { 1674349cc55cSDimitry Andric if (MO.getSubReg() == SubRegB && !IsEarlyClobber) { 16755f757f3fSDimitry Andric if (isPlainlyKilled(MO)) { 16760b57cec5SDimitry Andric MO.setIsKill(false); 16770b57cec5SDimitry Andric RemovedKillFlag = true; 16780b57cec5SDimitry Andric } 16790b57cec5SDimitry Andric MO.setReg(LastCopiedReg); 16800b57cec5SDimitry Andric MO.setSubReg(0); 16810b57cec5SDimitry Andric } else { 1682349cc55cSDimitry Andric RemainingUses |= TRI->getSubRegIndexLaneMask(MO.getSubReg()); 16830b57cec5SDimitry Andric } 16840b57cec5SDimitry Andric } 16850b57cec5SDimitry Andric } 16860b57cec5SDimitry Andric 16870b57cec5SDimitry Andric // Update live variables for regB. 1688349cc55cSDimitry Andric if (RemovedKillFlag && RemainingUses.none() && LV && 1689349cc55cSDimitry Andric LV->getVarInfo(RegB).removeKill(*MI)) { 16900b57cec5SDimitry Andric MachineBasicBlock::iterator PrevMI = MI; 16910b57cec5SDimitry Andric --PrevMI; 16920b57cec5SDimitry Andric LV->addVirtualRegisterKilled(RegB, *PrevMI); 16930b57cec5SDimitry Andric } 16940b57cec5SDimitry Andric 1695349cc55cSDimitry Andric if (RemovedKillFlag && RemainingUses.none()) 1696349cc55cSDimitry Andric SrcRegMap[LastCopiedReg] = RegB; 1697349cc55cSDimitry Andric 16980b57cec5SDimitry Andric // Update LiveIntervals. 16990b57cec5SDimitry Andric if (LIS) { 1700349cc55cSDimitry Andric SlotIndex UseIdx = LIS->getInstructionIndex(*MI); 1701349cc55cSDimitry Andric auto Shrink = [=](LiveRange &LR, LaneBitmask LaneMask) { 1702349cc55cSDimitry Andric LiveRange::Segment *S = LR.getSegmentContaining(LastCopyIdx); 1703349cc55cSDimitry Andric if (!S) 1704349cc55cSDimitry Andric return true; 1705349cc55cSDimitry Andric if ((LaneMask & RemainingUses).any()) 1706349cc55cSDimitry Andric return false; 1707349cc55cSDimitry Andric if (S->end.getBaseIndex() != UseIdx) 1708349cc55cSDimitry Andric return false; 1709349cc55cSDimitry Andric S->end = LastCopyIdx; 1710349cc55cSDimitry Andric return true; 1711349cc55cSDimitry Andric }; 17120b57cec5SDimitry Andric 1713349cc55cSDimitry Andric LiveInterval &LI = LIS->getInterval(RegB); 1714349cc55cSDimitry Andric bool ShrinkLI = true; 1715349cc55cSDimitry Andric for (auto &S : LI.subranges()) 1716349cc55cSDimitry Andric ShrinkLI &= Shrink(S, S.LaneMask); 1717349cc55cSDimitry Andric if (ShrinkLI) 1718349cc55cSDimitry Andric Shrink(LI, LaneBitmask::getAll()); 17190b57cec5SDimitry Andric } 17200b57cec5SDimitry Andric } else if (RemovedKillFlag) { 17210b57cec5SDimitry Andric // Some tied uses of regB matched their destination registers, so 17220b57cec5SDimitry Andric // regB is still used in this instruction, but a kill flag was 17230b57cec5SDimitry Andric // removed from a different tied use of regB, so now we need to add 17240b57cec5SDimitry Andric // a kill flag to one of the remaining uses of regB. 172506c3fb27SDimitry Andric for (MachineOperand &MO : MI->all_uses()) { 172606c3fb27SDimitry Andric if (MO.getReg() == RegB) { 17270b57cec5SDimitry Andric MO.setIsKill(true); 17280b57cec5SDimitry Andric break; 17290b57cec5SDimitry Andric } 17300b57cec5SDimitry Andric } 17310b57cec5SDimitry Andric } 17320b57cec5SDimitry Andric } 17330b57cec5SDimitry Andric 173481ad6265SDimitry Andric // For every tied operand pair this function transforms statepoint from 173581ad6265SDimitry Andric // RegA = STATEPOINT ... RegB(tied-def N) 173681ad6265SDimitry Andric // to 173781ad6265SDimitry Andric // RegB = STATEPOINT ... RegB(tied-def N) 173881ad6265SDimitry Andric // and replaces all uses of RegA with RegB. 173981ad6265SDimitry Andric // No extra COPY instruction is necessary because tied use is killed at 174081ad6265SDimitry Andric // STATEPOINT. 1741*0fca6ea1SDimitry Andric bool TwoAddressInstructionImpl::processStatepoint( 174281ad6265SDimitry Andric MachineInstr *MI, TiedOperandMap &TiedOperands) { 174381ad6265SDimitry Andric 174481ad6265SDimitry Andric bool NeedCopy = false; 174581ad6265SDimitry Andric for (auto &TO : TiedOperands) { 174681ad6265SDimitry Andric Register RegB = TO.first; 174781ad6265SDimitry Andric if (TO.second.size() != 1) { 174881ad6265SDimitry Andric NeedCopy = true; 174981ad6265SDimitry Andric continue; 175081ad6265SDimitry Andric } 175181ad6265SDimitry Andric 175281ad6265SDimitry Andric unsigned SrcIdx = TO.second[0].first; 175381ad6265SDimitry Andric unsigned DstIdx = TO.second[0].second; 175481ad6265SDimitry Andric 175581ad6265SDimitry Andric MachineOperand &DstMO = MI->getOperand(DstIdx); 175681ad6265SDimitry Andric Register RegA = DstMO.getReg(); 175781ad6265SDimitry Andric 175881ad6265SDimitry Andric assert(RegB == MI->getOperand(SrcIdx).getReg()); 175981ad6265SDimitry Andric 176081ad6265SDimitry Andric if (RegA == RegB) 176181ad6265SDimitry Andric continue; 176281ad6265SDimitry Andric 1763bdd1243dSDimitry Andric // CodeGenPrepare can sink pointer compare past statepoint, which 1764bdd1243dSDimitry Andric // breaks assumption that statepoint kills tied-use register when 1765bdd1243dSDimitry Andric // in SSA form (see note in IR/SafepointIRVerifier.cpp). Fall back 1766bdd1243dSDimitry Andric // to generic tied register handling to avoid assertion failures. 1767bdd1243dSDimitry Andric // TODO: Recompute LIS/LV information for new range here. 1768bdd1243dSDimitry Andric if (LIS) { 1769bdd1243dSDimitry Andric const auto &UseLI = LIS->getInterval(RegB); 1770bdd1243dSDimitry Andric const auto &DefLI = LIS->getInterval(RegA); 1771bdd1243dSDimitry Andric if (DefLI.overlaps(UseLI)) { 1772bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "LIS: " << printReg(RegB, TRI, 0) 1773bdd1243dSDimitry Andric << " UseLI overlaps with DefLI\n"); 1774bdd1243dSDimitry Andric NeedCopy = true; 1775bdd1243dSDimitry Andric continue; 1776bdd1243dSDimitry Andric } 1777bdd1243dSDimitry Andric } else if (LV && LV->getVarInfo(RegB).findKill(MI->getParent()) != MI) { 1778bdd1243dSDimitry Andric // Note that MachineOperand::isKill does not work here, because it 1779bdd1243dSDimitry Andric // is set only on first register use in instruction and for statepoint 1780bdd1243dSDimitry Andric // tied-use register will usually be found in preceeding deopt bundle. 1781bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "LV: " << printReg(RegB, TRI, 0) 1782bdd1243dSDimitry Andric << " not killed by statepoint\n"); 1783bdd1243dSDimitry Andric NeedCopy = true; 1784bdd1243dSDimitry Andric continue; 1785bdd1243dSDimitry Andric } 1786bdd1243dSDimitry Andric 1787bdd1243dSDimitry Andric if (!MRI->constrainRegClass(RegB, MRI->getRegClass(RegA))) { 1788bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "MRI: couldn't constrain" << printReg(RegB, TRI, 0) 1789bdd1243dSDimitry Andric << " to register class of " << printReg(RegA, TRI, 0) 1790bdd1243dSDimitry Andric << '\n'); 1791bdd1243dSDimitry Andric NeedCopy = true; 1792bdd1243dSDimitry Andric continue; 1793bdd1243dSDimitry Andric } 179481ad6265SDimitry Andric MRI->replaceRegWith(RegA, RegB); 179581ad6265SDimitry Andric 179681ad6265SDimitry Andric if (LIS) { 179781ad6265SDimitry Andric VNInfo::Allocator &A = LIS->getVNInfoAllocator(); 179881ad6265SDimitry Andric LiveInterval &LI = LIS->getInterval(RegB); 1799bdd1243dSDimitry Andric LiveInterval &Other = LIS->getInterval(RegA); 1800bdd1243dSDimitry Andric SmallVector<VNInfo *> NewVNIs; 1801bdd1243dSDimitry Andric for (const VNInfo *VNI : Other.valnos) { 1802bdd1243dSDimitry Andric assert(VNI->id == NewVNIs.size() && "assumed"); 1803bdd1243dSDimitry Andric NewVNIs.push_back(LI.createValueCopy(VNI, A)); 1804bdd1243dSDimitry Andric } 1805bdd1243dSDimitry Andric for (auto &S : Other) { 1806bdd1243dSDimitry Andric VNInfo *VNI = NewVNIs[S.valno->id]; 180781ad6265SDimitry Andric LiveRange::Segment NewSeg(S.start, S.end, VNI); 180881ad6265SDimitry Andric LI.addSegment(NewSeg); 180981ad6265SDimitry Andric } 181081ad6265SDimitry Andric LIS->removeInterval(RegA); 181181ad6265SDimitry Andric } 181281ad6265SDimitry Andric 181381ad6265SDimitry Andric if (LV) { 181481ad6265SDimitry Andric if (MI->getOperand(SrcIdx).isKill()) 181581ad6265SDimitry Andric LV->removeVirtualRegisterKilled(RegB, *MI); 181681ad6265SDimitry Andric LiveVariables::VarInfo &SrcInfo = LV->getVarInfo(RegB); 181781ad6265SDimitry Andric LiveVariables::VarInfo &DstInfo = LV->getVarInfo(RegA); 181881ad6265SDimitry Andric SrcInfo.AliveBlocks |= DstInfo.AliveBlocks; 1819bdd1243dSDimitry Andric DstInfo.AliveBlocks.clear(); 182081ad6265SDimitry Andric for (auto *KillMI : DstInfo.Kills) 182181ad6265SDimitry Andric LV->addVirtualRegisterKilled(RegB, *KillMI, false); 182281ad6265SDimitry Andric } 182381ad6265SDimitry Andric } 182481ad6265SDimitry Andric return !NeedCopy; 182581ad6265SDimitry Andric } 182681ad6265SDimitry Andric 18270b57cec5SDimitry Andric /// Reduce two-address instructions to two operands. 1828*0fca6ea1SDimitry Andric bool TwoAddressInstructionImpl::run() { 18290b57cec5SDimitry Andric bool MadeChange = false; 18300b57cec5SDimitry Andric 18310b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n"); 18320b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "********** Function: " << MF->getName() << '\n'); 18330b57cec5SDimitry Andric 18340b57cec5SDimitry Andric // This pass takes the function out of SSA form. 18350b57cec5SDimitry Andric MRI->leaveSSA(); 18360b57cec5SDimitry Andric 18375ffd83dbSDimitry Andric // This pass will rewrite the tied-def to meet the RegConstraint. 18385ffd83dbSDimitry Andric MF->getProperties() 18395ffd83dbSDimitry Andric .set(MachineFunctionProperties::Property::TiedOpsRewritten); 18405ffd83dbSDimitry Andric 18410b57cec5SDimitry Andric TiedOperandMap TiedOperands; 1842fe6060f1SDimitry Andric for (MachineBasicBlock &MBBI : *MF) { 1843fe6060f1SDimitry Andric MBB = &MBBI; 18440b57cec5SDimitry Andric unsigned Dist = 0; 18450b57cec5SDimitry Andric DistanceMap.clear(); 18460b57cec5SDimitry Andric SrcRegMap.clear(); 18470b57cec5SDimitry Andric DstRegMap.clear(); 18480b57cec5SDimitry Andric Processed.clear(); 18490b57cec5SDimitry Andric for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end(); 18500b57cec5SDimitry Andric mi != me; ) { 18510b57cec5SDimitry Andric MachineBasicBlock::iterator nmi = std::next(mi); 1852590d96feSDimitry Andric // Skip debug instructions. 1853590d96feSDimitry Andric if (mi->isDebugInstr()) { 18540b57cec5SDimitry Andric mi = nmi; 18550b57cec5SDimitry Andric continue; 18560b57cec5SDimitry Andric } 18570b57cec5SDimitry Andric 18580b57cec5SDimitry Andric // Expand REG_SEQUENCE instructions. This will position mi at the first 18590b57cec5SDimitry Andric // expanded instruction. 18600b57cec5SDimitry Andric if (mi->isRegSequence()) 18610b57cec5SDimitry Andric eliminateRegSequence(mi); 18620b57cec5SDimitry Andric 18630b57cec5SDimitry Andric DistanceMap.insert(std::make_pair(&*mi, ++Dist)); 18640b57cec5SDimitry Andric 18650b57cec5SDimitry Andric processCopy(&*mi); 18660b57cec5SDimitry Andric 18670b57cec5SDimitry Andric // First scan through all the tied register uses in this instruction 18680b57cec5SDimitry Andric // and record a list of pairs of tied operands for each register. 18690b57cec5SDimitry Andric if (!collectTiedOperands(&*mi, TiedOperands)) { 1870349cc55cSDimitry Andric removeClobberedSrcRegMap(&*mi); 18710b57cec5SDimitry Andric mi = nmi; 18720b57cec5SDimitry Andric continue; 18730b57cec5SDimitry Andric } 18740b57cec5SDimitry Andric 18750b57cec5SDimitry Andric ++NumTwoAddressInstrs; 18760b57cec5SDimitry Andric MadeChange = true; 18770b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << '\t' << *mi); 18780b57cec5SDimitry Andric 18790b57cec5SDimitry Andric // If the instruction has a single pair of tied operands, try some 18800b57cec5SDimitry Andric // transformations that may either eliminate the tied operands or 18810b57cec5SDimitry Andric // improve the opportunities for coalescing away the register copy. 18820b57cec5SDimitry Andric if (TiedOperands.size() == 1) { 18830b57cec5SDimitry Andric SmallVectorImpl<std::pair<unsigned, unsigned>> &TiedPairs 18840b57cec5SDimitry Andric = TiedOperands.begin()->second; 18850b57cec5SDimitry Andric if (TiedPairs.size() == 1) { 18860b57cec5SDimitry Andric unsigned SrcIdx = TiedPairs[0].first; 18870b57cec5SDimitry Andric unsigned DstIdx = TiedPairs[0].second; 18888bcb0991SDimitry Andric Register SrcReg = mi->getOperand(SrcIdx).getReg(); 18898bcb0991SDimitry Andric Register DstReg = mi->getOperand(DstIdx).getReg(); 18900b57cec5SDimitry Andric if (SrcReg != DstReg && 18910b57cec5SDimitry Andric tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) { 18920b57cec5SDimitry Andric // The tied operands have been eliminated or shifted further down 18930b57cec5SDimitry Andric // the block to ease elimination. Continue processing with 'nmi'. 18940b57cec5SDimitry Andric TiedOperands.clear(); 1895349cc55cSDimitry Andric removeClobberedSrcRegMap(&*mi); 18960b57cec5SDimitry Andric mi = nmi; 18970b57cec5SDimitry Andric continue; 18980b57cec5SDimitry Andric } 18990b57cec5SDimitry Andric } 19000b57cec5SDimitry Andric } 19010b57cec5SDimitry Andric 190281ad6265SDimitry Andric if (mi->getOpcode() == TargetOpcode::STATEPOINT && 190381ad6265SDimitry Andric processStatepoint(&*mi, TiedOperands)) { 190481ad6265SDimitry Andric TiedOperands.clear(); 190581ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "\t\trewrite to:\t" << *mi); 190681ad6265SDimitry Andric mi = nmi; 190781ad6265SDimitry Andric continue; 190881ad6265SDimitry Andric } 190981ad6265SDimitry Andric 19100b57cec5SDimitry Andric // Now iterate over the information collected above. 19110b57cec5SDimitry Andric for (auto &TO : TiedOperands) { 19120b57cec5SDimitry Andric processTiedPairs(&*mi, TO.second, Dist); 19130b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\t\trewrite to:\t" << *mi); 19140b57cec5SDimitry Andric } 19150b57cec5SDimitry Andric 19160b57cec5SDimitry Andric // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form. 19170b57cec5SDimitry Andric if (mi->isInsertSubreg()) { 19180b57cec5SDimitry Andric // From %reg = INSERT_SUBREG %reg, %subreg, subidx 19190b57cec5SDimitry Andric // To %reg:subidx = COPY %subreg 19200b57cec5SDimitry Andric unsigned SubIdx = mi->getOperand(3).getImm(); 192181ad6265SDimitry Andric mi->removeOperand(3); 19220b57cec5SDimitry Andric assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx"); 19230b57cec5SDimitry Andric mi->getOperand(0).setSubReg(SubIdx); 19240b57cec5SDimitry Andric mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef()); 192581ad6265SDimitry Andric mi->removeOperand(1); 19260b57cec5SDimitry Andric mi->setDesc(TII->get(TargetOpcode::COPY)); 19270b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\t\tconvert to:\t" << *mi); 1928349cc55cSDimitry Andric 1929349cc55cSDimitry Andric // Update LiveIntervals. 1930349cc55cSDimitry Andric if (LIS) { 1931349cc55cSDimitry Andric Register Reg = mi->getOperand(0).getReg(); 1932349cc55cSDimitry Andric LiveInterval &LI = LIS->getInterval(Reg); 1933349cc55cSDimitry Andric if (LI.hasSubRanges()) { 1934349cc55cSDimitry Andric // The COPY no longer defines subregs of %reg except for 1935349cc55cSDimitry Andric // %reg.subidx. 1936349cc55cSDimitry Andric LaneBitmask LaneMask = 1937349cc55cSDimitry Andric TRI->getSubRegIndexLaneMask(mi->getOperand(0).getSubReg()); 19385f757f3fSDimitry Andric SlotIndex Idx = LIS->getInstructionIndex(*mi).getRegSlot(); 1939349cc55cSDimitry Andric for (auto &S : LI.subranges()) { 1940349cc55cSDimitry Andric if ((S.LaneMask & LaneMask).none()) { 19415f757f3fSDimitry Andric LiveRange::iterator DefSeg = S.FindSegmentContaining(Idx); 19425f757f3fSDimitry Andric if (mi->getOperand(0).isUndef()) { 19435f757f3fSDimitry Andric S.removeValNo(DefSeg->valno); 19445f757f3fSDimitry Andric } else { 19455f757f3fSDimitry Andric LiveRange::iterator UseSeg = std::prev(DefSeg); 1946349cc55cSDimitry Andric S.MergeValueNumberInto(DefSeg->valno, UseSeg->valno); 1947349cc55cSDimitry Andric } 1948349cc55cSDimitry Andric } 19495f757f3fSDimitry Andric } 1950349cc55cSDimitry Andric 1951349cc55cSDimitry Andric // The COPY no longer has a use of %reg. 1952349cc55cSDimitry Andric LIS->shrinkToUses(&LI); 1953349cc55cSDimitry Andric } else { 1954349cc55cSDimitry Andric // The live interval for Reg did not have subranges but now it needs 1955349cc55cSDimitry Andric // them because we have introduced a subreg def. Recompute it. 1956349cc55cSDimitry Andric LIS->removeInterval(Reg); 1957349cc55cSDimitry Andric LIS->createAndComputeVirtRegInterval(Reg); 1958349cc55cSDimitry Andric } 1959349cc55cSDimitry Andric } 19600b57cec5SDimitry Andric } 19610b57cec5SDimitry Andric 19620b57cec5SDimitry Andric // Clear TiedOperands here instead of at the top of the loop 19630b57cec5SDimitry Andric // since most instructions do not have tied operands. 19640b57cec5SDimitry Andric TiedOperands.clear(); 1965349cc55cSDimitry Andric removeClobberedSrcRegMap(&*mi); 19660b57cec5SDimitry Andric mi = nmi; 19670b57cec5SDimitry Andric } 19680b57cec5SDimitry Andric } 19690b57cec5SDimitry Andric 19700b57cec5SDimitry Andric return MadeChange; 19710b57cec5SDimitry Andric } 19720b57cec5SDimitry Andric 19730b57cec5SDimitry Andric /// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process. 19740b57cec5SDimitry Andric /// 19750b57cec5SDimitry Andric /// The instruction is turned into a sequence of sub-register copies: 19760b57cec5SDimitry Andric /// 19770b57cec5SDimitry Andric /// %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1 19780b57cec5SDimitry Andric /// 19790b57cec5SDimitry Andric /// Becomes: 19800b57cec5SDimitry Andric /// 19810b57cec5SDimitry Andric /// undef %dst:ssub0 = COPY %v1 19820b57cec5SDimitry Andric /// %dst:ssub1 = COPY %v2 1983*0fca6ea1SDimitry Andric void TwoAddressInstructionImpl::eliminateRegSequence( 1984*0fca6ea1SDimitry Andric MachineBasicBlock::iterator &MBBI) { 19850b57cec5SDimitry Andric MachineInstr &MI = *MBBI; 19868bcb0991SDimitry Andric Register DstReg = MI.getOperand(0).getReg(); 19870b57cec5SDimitry Andric 19885ffd83dbSDimitry Andric SmallVector<Register, 4> OrigRegs; 1989*0fca6ea1SDimitry Andric VNInfo *DefVN = nullptr; 19900b57cec5SDimitry Andric if (LIS) { 19910b57cec5SDimitry Andric OrigRegs.push_back(MI.getOperand(0).getReg()); 19920b57cec5SDimitry Andric for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2) 19930b57cec5SDimitry Andric OrigRegs.push_back(MI.getOperand(i).getReg()); 1994*0fca6ea1SDimitry Andric if (LIS->hasInterval(DstReg)) { 1995*0fca6ea1SDimitry Andric DefVN = LIS->getInterval(DstReg) 1996*0fca6ea1SDimitry Andric .Query(LIS->getInstructionIndex(MI)) 1997*0fca6ea1SDimitry Andric .valueOut(); 1998*0fca6ea1SDimitry Andric } 19990b57cec5SDimitry Andric } 20000b57cec5SDimitry Andric 2001*0fca6ea1SDimitry Andric LaneBitmask UndefLanes = LaneBitmask::getNone(); 20020b57cec5SDimitry Andric bool DefEmitted = false; 20030b57cec5SDimitry Andric for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2) { 20040b57cec5SDimitry Andric MachineOperand &UseMO = MI.getOperand(i); 20058bcb0991SDimitry Andric Register SrcReg = UseMO.getReg(); 20060b57cec5SDimitry Andric unsigned SubIdx = MI.getOperand(i+1).getImm(); 20070b57cec5SDimitry Andric // Nothing needs to be inserted for undef operands. 20087a6dacacSDimitry Andric if (UseMO.isUndef()) { 2009*0fca6ea1SDimitry Andric UndefLanes |= TRI->getSubRegIndexLaneMask(SubIdx); 20100b57cec5SDimitry Andric continue; 20117a6dacacSDimitry Andric } 20120b57cec5SDimitry Andric 20130b57cec5SDimitry Andric // Defer any kill flag to the last operand using SrcReg. Otherwise, we 20140b57cec5SDimitry Andric // might insert a COPY that uses SrcReg after is was killed. 20150b57cec5SDimitry Andric bool isKill = UseMO.isKill(); 20160b57cec5SDimitry Andric if (isKill) 20170b57cec5SDimitry Andric for (unsigned j = i + 2; j < e; j += 2) 20180b57cec5SDimitry Andric if (MI.getOperand(j).getReg() == SrcReg) { 20190b57cec5SDimitry Andric MI.getOperand(j).setIsKill(); 20200b57cec5SDimitry Andric UseMO.setIsKill(false); 20210b57cec5SDimitry Andric isKill = false; 20220b57cec5SDimitry Andric break; 20230b57cec5SDimitry Andric } 20240b57cec5SDimitry Andric 20250b57cec5SDimitry Andric // Insert the sub-register copy. 20260b57cec5SDimitry Andric MachineInstr *CopyMI = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 20270b57cec5SDimitry Andric TII->get(TargetOpcode::COPY)) 20280b57cec5SDimitry Andric .addReg(DstReg, RegState::Define, SubIdx) 20290b57cec5SDimitry Andric .add(UseMO); 20300b57cec5SDimitry Andric 20310b57cec5SDimitry Andric // The first def needs an undef flag because there is no live register 20320b57cec5SDimitry Andric // before it. 20330b57cec5SDimitry Andric if (!DefEmitted) { 20340b57cec5SDimitry Andric CopyMI->getOperand(0).setIsUndef(true); 20350b57cec5SDimitry Andric // Return an iterator pointing to the first inserted instr. 20360b57cec5SDimitry Andric MBBI = CopyMI; 20370b57cec5SDimitry Andric } 20380b57cec5SDimitry Andric DefEmitted = true; 20390b57cec5SDimitry Andric 20400b57cec5SDimitry Andric // Update LiveVariables' kill info. 2041e8d8bef9SDimitry Andric if (LV && isKill && !SrcReg.isPhysical()) 20420b57cec5SDimitry Andric LV->replaceKillInstruction(SrcReg, MI, *CopyMI); 20430b57cec5SDimitry Andric 20440b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Inserted: " << *CopyMI); 20450b57cec5SDimitry Andric } 20460b57cec5SDimitry Andric 20470b57cec5SDimitry Andric MachineBasicBlock::iterator EndMBBI = 20480b57cec5SDimitry Andric std::next(MachineBasicBlock::iterator(MI)); 20490b57cec5SDimitry Andric 20500b57cec5SDimitry Andric if (!DefEmitted) { 20510b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Turned: " << MI << " into an IMPLICIT_DEF"); 20520b57cec5SDimitry Andric MI.setDesc(TII->get(TargetOpcode::IMPLICIT_DEF)); 20530b57cec5SDimitry Andric for (int j = MI.getNumOperands() - 1, ee = 0; j > ee; --j) 205481ad6265SDimitry Andric MI.removeOperand(j); 20550b57cec5SDimitry Andric } else { 20567a6dacacSDimitry Andric if (LIS) { 2057*0fca6ea1SDimitry Andric // Force live interval recomputation if we moved to a partial definition 2058*0fca6ea1SDimitry Andric // of the register. Undef flags must be propagate to uses of undefined 2059*0fca6ea1SDimitry Andric // subregister for accurate interval computation. 2060*0fca6ea1SDimitry Andric if (UndefLanes.any() && DefVN && MRI->shouldTrackSubRegLiveness(DstReg)) { 2061*0fca6ea1SDimitry Andric auto &LI = LIS->getInterval(DstReg); 2062*0fca6ea1SDimitry Andric for (MachineOperand &UseOp : MRI->use_operands(DstReg)) { 2063*0fca6ea1SDimitry Andric unsigned SubReg = UseOp.getSubReg(); 2064*0fca6ea1SDimitry Andric if (UseOp.isUndef() || !SubReg) 2065*0fca6ea1SDimitry Andric continue; 2066*0fca6ea1SDimitry Andric auto *VN = 2067*0fca6ea1SDimitry Andric LI.getVNInfoAt(LIS->getInstructionIndex(*UseOp.getParent())); 2068*0fca6ea1SDimitry Andric if (DefVN != VN) 2069*0fca6ea1SDimitry Andric continue; 2070*0fca6ea1SDimitry Andric LaneBitmask LaneMask = TRI->getSubRegIndexLaneMask(SubReg); 2071*0fca6ea1SDimitry Andric if ((UndefLanes & LaneMask).any()) 2072*0fca6ea1SDimitry Andric UseOp.setIsUndef(true); 2073*0fca6ea1SDimitry Andric } 20747a6dacacSDimitry Andric LIS->removeInterval(DstReg); 2075*0fca6ea1SDimitry Andric } 2076349cc55cSDimitry Andric LIS->RemoveMachineInstrFromMaps(MI); 20777a6dacacSDimitry Andric } 2078349cc55cSDimitry Andric 20790b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Eliminated: " << MI); 20800b57cec5SDimitry Andric MI.eraseFromParent(); 20810b57cec5SDimitry Andric } 20820b57cec5SDimitry Andric 20830b57cec5SDimitry Andric // Udpate LiveIntervals. 20840b57cec5SDimitry Andric if (LIS) 20850b57cec5SDimitry Andric LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs); 20860b57cec5SDimitry Andric } 2087