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 290b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h" 300b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h" 310b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h" 320b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h" 330b57cec5SDimitry Andric #include "llvm/ADT/iterator_range.h" 340b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h" 350b57cec5SDimitry Andric #include "llvm/CodeGen/LiveInterval.h" 360b57cec5SDimitry Andric #include "llvm/CodeGen/LiveIntervals.h" 370b57cec5SDimitry Andric #include "llvm/CodeGen/LiveVariables.h" 380b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h" 390b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h" 400b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h" 410b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h" 420b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h" 430b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h" 440b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h" 450b57cec5SDimitry Andric #include "llvm/CodeGen/Passes.h" 460b57cec5SDimitry Andric #include "llvm/CodeGen/SlotIndexes.h" 470b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h" 480b57cec5SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h" 490b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h" 500b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h" 510b57cec5SDimitry Andric #include "llvm/MC/MCInstrDesc.h" 520b57cec5SDimitry Andric #include "llvm/Pass.h" 530b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h" 540b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h" 550b57cec5SDimitry Andric #include "llvm/Support/Debug.h" 560b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 570b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 580b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h" 590b57cec5SDimitry Andric #include <cassert> 600b57cec5SDimitry Andric #include <iterator> 610b57cec5SDimitry Andric #include <utility> 620b57cec5SDimitry Andric 630b57cec5SDimitry Andric using namespace llvm; 640b57cec5SDimitry Andric 650b57cec5SDimitry Andric #define DEBUG_TYPE "twoaddressinstruction" 660b57cec5SDimitry Andric 670b57cec5SDimitry Andric STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions"); 680b57cec5SDimitry Andric STATISTIC(NumCommuted , "Number of instructions commuted to coalesce"); 690b57cec5SDimitry Andric STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted"); 700b57cec5SDimitry Andric STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address"); 710b57cec5SDimitry Andric STATISTIC(NumReSchedUps, "Number of instructions re-scheduled up"); 720b57cec5SDimitry Andric STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down"); 730b57cec5SDimitry Andric 740b57cec5SDimitry Andric // Temporary flag to disable rescheduling. 750b57cec5SDimitry Andric static cl::opt<bool> 760b57cec5SDimitry Andric EnableRescheduling("twoaddr-reschedule", 770b57cec5SDimitry Andric cl::desc("Coalesce copies by rescheduling (default=true)"), 780b57cec5SDimitry Andric cl::init(true), cl::Hidden); 790b57cec5SDimitry Andric 800b57cec5SDimitry Andric // Limit the number of dataflow edges to traverse when evaluating the benefit 810b57cec5SDimitry Andric // of commuting operands. 820b57cec5SDimitry Andric static cl::opt<unsigned> MaxDataFlowEdge( 830b57cec5SDimitry Andric "dataflow-edge-limit", cl::Hidden, cl::init(3), 840b57cec5SDimitry Andric cl::desc("Maximum number of dataflow edges to traverse when evaluating " 850b57cec5SDimitry Andric "the benefit of commuting operands")); 860b57cec5SDimitry Andric 870b57cec5SDimitry Andric namespace { 880b57cec5SDimitry Andric 890b57cec5SDimitry Andric class TwoAddressInstructionPass : public MachineFunctionPass { 90*06c3fb27SDimitry Andric MachineFunction *MF = nullptr; 91*06c3fb27SDimitry Andric const TargetInstrInfo *TII = nullptr; 92*06c3fb27SDimitry Andric const TargetRegisterInfo *TRI = nullptr; 93*06c3fb27SDimitry Andric const InstrItineraryData *InstrItins = nullptr; 94*06c3fb27SDimitry Andric MachineRegisterInfo *MRI = nullptr; 95*06c3fb27SDimitry Andric LiveVariables *LV = nullptr; 96*06c3fb27SDimitry Andric LiveIntervals *LIS = nullptr; 97*06c3fb27SDimitry Andric AliasAnalysis *AA = nullptr; 98*06c3fb27SDimitry Andric CodeGenOpt::Level OptLevel = CodeGenOpt::None; 990b57cec5SDimitry Andric 1000b57cec5SDimitry Andric // The current basic block being processed. 101*06c3fb27SDimitry Andric MachineBasicBlock *MBB = nullptr; 1020b57cec5SDimitry Andric 1030b57cec5SDimitry Andric // Keep track the distance of a MI from the start of the current basic block. 1040b57cec5SDimitry Andric DenseMap<MachineInstr*, unsigned> DistanceMap; 1050b57cec5SDimitry Andric 1060b57cec5SDimitry Andric // Set of already processed instructions in the current block. 1070b57cec5SDimitry Andric SmallPtrSet<MachineInstr*, 8> Processed; 1080b57cec5SDimitry Andric 1090b57cec5SDimitry Andric // A map from virtual registers to physical registers which are likely targets 1100b57cec5SDimitry Andric // to be coalesced to due to copies from physical registers to virtual 1110b57cec5SDimitry Andric // registers. e.g. v1024 = move r0. 112e8d8bef9SDimitry Andric DenseMap<Register, Register> SrcRegMap; 1130b57cec5SDimitry Andric 1140b57cec5SDimitry Andric // A map from virtual registers to physical registers which are likely targets 1150b57cec5SDimitry Andric // to be coalesced to due to copies to physical registers from virtual 1160b57cec5SDimitry Andric // registers. e.g. r1 = move v1024. 117e8d8bef9SDimitry Andric DenseMap<Register, Register> DstRegMap; 1180b57cec5SDimitry Andric 119349cc55cSDimitry Andric void removeClobberedSrcRegMap(MachineInstr *MI); 120349cc55cSDimitry Andric 121e8d8bef9SDimitry Andric bool isRevCopyChain(Register FromReg, Register ToReg, int Maxlen); 1220b57cec5SDimitry Andric 123e8d8bef9SDimitry Andric bool noUseAfterLastDef(Register Reg, unsigned Dist, unsigned &LastDef); 1240b57cec5SDimitry Andric 125e8d8bef9SDimitry Andric bool isProfitableToCommute(Register RegA, Register RegB, Register RegC, 1260b57cec5SDimitry Andric MachineInstr *MI, unsigned Dist); 1270b57cec5SDimitry Andric 1280b57cec5SDimitry Andric bool commuteInstruction(MachineInstr *MI, unsigned DstIdx, 1290b57cec5SDimitry Andric unsigned RegBIdx, unsigned RegCIdx, unsigned Dist); 1300b57cec5SDimitry Andric 131e8d8bef9SDimitry Andric bool isProfitableToConv3Addr(Register RegA, Register RegB); 1320b57cec5SDimitry Andric 1330b57cec5SDimitry Andric bool convertInstTo3Addr(MachineBasicBlock::iterator &mi, 134e8d8bef9SDimitry Andric MachineBasicBlock::iterator &nmi, Register RegA, 135349cc55cSDimitry Andric Register RegB, unsigned &Dist); 1360b57cec5SDimitry Andric 137e8d8bef9SDimitry Andric bool isDefTooClose(Register Reg, unsigned Dist, MachineInstr *MI); 1380b57cec5SDimitry Andric 1390b57cec5SDimitry Andric bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi, 140e8d8bef9SDimitry Andric MachineBasicBlock::iterator &nmi, Register Reg); 1410b57cec5SDimitry Andric bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi, 142e8d8bef9SDimitry Andric MachineBasicBlock::iterator &nmi, Register Reg); 1430b57cec5SDimitry Andric 1440b57cec5SDimitry Andric bool tryInstructionTransform(MachineBasicBlock::iterator &mi, 1450b57cec5SDimitry Andric MachineBasicBlock::iterator &nmi, 1460b57cec5SDimitry Andric unsigned SrcIdx, unsigned DstIdx, 147349cc55cSDimitry Andric unsigned &Dist, bool shouldOnlyCommute); 1480b57cec5SDimitry Andric 1490b57cec5SDimitry Andric bool tryInstructionCommute(MachineInstr *MI, 1500b57cec5SDimitry Andric unsigned DstOpIdx, 1510b57cec5SDimitry Andric unsigned BaseOpIdx, 1520b57cec5SDimitry Andric bool BaseOpKilled, 1530b57cec5SDimitry Andric unsigned Dist); 154e8d8bef9SDimitry Andric void scanUses(Register DstReg); 1550b57cec5SDimitry Andric 1560b57cec5SDimitry Andric void processCopy(MachineInstr *MI); 1570b57cec5SDimitry Andric 1580b57cec5SDimitry Andric using TiedPairList = SmallVector<std::pair<unsigned, unsigned>, 4>; 1590b57cec5SDimitry Andric using TiedOperandMap = SmallDenseMap<unsigned, TiedPairList>; 1600b57cec5SDimitry Andric 1610b57cec5SDimitry Andric bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&); 1620b57cec5SDimitry Andric void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist); 1630b57cec5SDimitry Andric void eliminateRegSequence(MachineBasicBlock::iterator&); 16481ad6265SDimitry Andric bool processStatepoint(MachineInstr *MI, TiedOperandMap &TiedOperands); 1650b57cec5SDimitry Andric 1660b57cec5SDimitry Andric public: 1670b57cec5SDimitry Andric static char ID; // Pass identification, replacement for typeid 1680b57cec5SDimitry Andric 1690b57cec5SDimitry Andric TwoAddressInstructionPass() : MachineFunctionPass(ID) { 1700b57cec5SDimitry Andric initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry()); 1710b57cec5SDimitry Andric } 1720b57cec5SDimitry Andric 1730b57cec5SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 1740b57cec5SDimitry Andric AU.setPreservesCFG(); 1750b57cec5SDimitry Andric AU.addUsedIfAvailable<AAResultsWrapperPass>(); 1760b57cec5SDimitry Andric AU.addUsedIfAvailable<LiveVariables>(); 1770b57cec5SDimitry Andric AU.addPreserved<LiveVariables>(); 1780b57cec5SDimitry Andric AU.addPreserved<SlotIndexes>(); 1790b57cec5SDimitry Andric AU.addPreserved<LiveIntervals>(); 1800b57cec5SDimitry Andric AU.addPreservedID(MachineLoopInfoID); 1810b57cec5SDimitry Andric AU.addPreservedID(MachineDominatorsID); 1820b57cec5SDimitry Andric MachineFunctionPass::getAnalysisUsage(AU); 1830b57cec5SDimitry Andric } 1840b57cec5SDimitry Andric 1850b57cec5SDimitry Andric /// Pass entry point. 1860b57cec5SDimitry Andric bool runOnMachineFunction(MachineFunction&) override; 1870b57cec5SDimitry Andric }; 1880b57cec5SDimitry Andric 1890b57cec5SDimitry Andric } // end anonymous namespace 1900b57cec5SDimitry Andric 1910b57cec5SDimitry Andric char TwoAddressInstructionPass::ID = 0; 1920b57cec5SDimitry Andric 1930b57cec5SDimitry Andric char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID; 1940b57cec5SDimitry Andric 1950b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, DEBUG_TYPE, 1960b57cec5SDimitry Andric "Two-Address instruction pass", false, false) 1970b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 1980b57cec5SDimitry Andric INITIALIZE_PASS_END(TwoAddressInstructionPass, DEBUG_TYPE, 1990b57cec5SDimitry Andric "Two-Address instruction pass", false, false) 2000b57cec5SDimitry Andric 2010b57cec5SDimitry Andric /// Return the MachineInstr* if it is the single def of the Reg in current BB. 202e8d8bef9SDimitry Andric static MachineInstr *getSingleDef(Register Reg, MachineBasicBlock *BB, 2030b57cec5SDimitry Andric const MachineRegisterInfo *MRI) { 2040b57cec5SDimitry Andric MachineInstr *Ret = nullptr; 2050b57cec5SDimitry Andric for (MachineInstr &DefMI : MRI->def_instructions(Reg)) { 2060b57cec5SDimitry Andric if (DefMI.getParent() != BB || DefMI.isDebugValue()) 2070b57cec5SDimitry Andric continue; 2080b57cec5SDimitry Andric if (!Ret) 2090b57cec5SDimitry Andric Ret = &DefMI; 2100b57cec5SDimitry Andric else if (Ret != &DefMI) 2110b57cec5SDimitry Andric return nullptr; 2120b57cec5SDimitry Andric } 2130b57cec5SDimitry Andric return Ret; 2140b57cec5SDimitry Andric } 2150b57cec5SDimitry Andric 2160b57cec5SDimitry Andric /// Check if there is a reversed copy chain from FromReg to ToReg: 2170b57cec5SDimitry Andric /// %Tmp1 = copy %Tmp2; 2180b57cec5SDimitry Andric /// %FromReg = copy %Tmp1; 2190b57cec5SDimitry Andric /// %ToReg = add %FromReg ... 2200b57cec5SDimitry Andric /// %Tmp2 = copy %ToReg; 2210b57cec5SDimitry Andric /// MaxLen specifies the maximum length of the copy chain the func 2220b57cec5SDimitry Andric /// can walk through. 223e8d8bef9SDimitry Andric bool TwoAddressInstructionPass::isRevCopyChain(Register FromReg, Register ToReg, 2240b57cec5SDimitry Andric int Maxlen) { 225e8d8bef9SDimitry Andric Register TmpReg = FromReg; 2260b57cec5SDimitry Andric for (int i = 0; i < Maxlen; i++) { 2270b57cec5SDimitry Andric MachineInstr *Def = getSingleDef(TmpReg, MBB, MRI); 2280b57cec5SDimitry Andric if (!Def || !Def->isCopy()) 2290b57cec5SDimitry Andric return false; 2300b57cec5SDimitry Andric 2310b57cec5SDimitry Andric TmpReg = Def->getOperand(1).getReg(); 2320b57cec5SDimitry Andric 2330b57cec5SDimitry Andric if (TmpReg == ToReg) 2340b57cec5SDimitry Andric return true; 2350b57cec5SDimitry Andric } 2360b57cec5SDimitry Andric return false; 2370b57cec5SDimitry Andric } 2380b57cec5SDimitry Andric 2390b57cec5SDimitry Andric /// Return true if there are no intervening uses between the last instruction 2400b57cec5SDimitry Andric /// in the MBB that defines the specified register and the two-address 2410b57cec5SDimitry Andric /// instruction which is being processed. It also returns the last def location 2420b57cec5SDimitry Andric /// by reference. 243e8d8bef9SDimitry Andric bool TwoAddressInstructionPass::noUseAfterLastDef(Register Reg, unsigned Dist, 2440b57cec5SDimitry Andric unsigned &LastDef) { 2450b57cec5SDimitry Andric LastDef = 0; 2460b57cec5SDimitry Andric unsigned LastUse = Dist; 2470b57cec5SDimitry Andric for (MachineOperand &MO : MRI->reg_operands(Reg)) { 2480b57cec5SDimitry Andric MachineInstr *MI = MO.getParent(); 2490b57cec5SDimitry Andric if (MI->getParent() != MBB || MI->isDebugValue()) 2500b57cec5SDimitry Andric continue; 2510b57cec5SDimitry Andric DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI); 2520b57cec5SDimitry Andric if (DI == DistanceMap.end()) 2530b57cec5SDimitry Andric continue; 2540b57cec5SDimitry Andric if (MO.isUse() && DI->second < LastUse) 2550b57cec5SDimitry Andric LastUse = DI->second; 2560b57cec5SDimitry Andric if (MO.isDef() && DI->second > LastDef) 2570b57cec5SDimitry Andric LastDef = DI->second; 2580b57cec5SDimitry Andric } 2590b57cec5SDimitry Andric 2600b57cec5SDimitry Andric return !(LastUse > LastDef && LastUse < Dist); 2610b57cec5SDimitry Andric } 2620b57cec5SDimitry Andric 2630b57cec5SDimitry Andric /// Return true if the specified MI is a copy instruction or an extract_subreg 2640b57cec5SDimitry Andric /// instruction. It also returns the source and destination registers and 2650b57cec5SDimitry Andric /// whether they are physical registers by reference. 2660b57cec5SDimitry Andric static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII, 267e8d8bef9SDimitry Andric Register &SrcReg, Register &DstReg, bool &IsSrcPhys, 268e8d8bef9SDimitry Andric bool &IsDstPhys) { 2690b57cec5SDimitry Andric SrcReg = 0; 2700b57cec5SDimitry Andric DstReg = 0; 2710b57cec5SDimitry Andric if (MI.isCopy()) { 2720b57cec5SDimitry Andric DstReg = MI.getOperand(0).getReg(); 2730b57cec5SDimitry Andric SrcReg = MI.getOperand(1).getReg(); 2740b57cec5SDimitry Andric } else if (MI.isInsertSubreg() || MI.isSubregToReg()) { 2750b57cec5SDimitry Andric DstReg = MI.getOperand(0).getReg(); 2760b57cec5SDimitry Andric SrcReg = MI.getOperand(2).getReg(); 277e8d8bef9SDimitry Andric } else { 2780b57cec5SDimitry Andric return false; 279e8d8bef9SDimitry Andric } 2800b57cec5SDimitry Andric 281e8d8bef9SDimitry Andric IsSrcPhys = SrcReg.isPhysical(); 282e8d8bef9SDimitry Andric IsDstPhys = DstReg.isPhysical(); 2830b57cec5SDimitry Andric return true; 2840b57cec5SDimitry Andric } 2850b57cec5SDimitry Andric 2860b57cec5SDimitry Andric /// Test if the given register value, which is used by the 2870b57cec5SDimitry Andric /// given instruction, is killed by the given instruction. 288*06c3fb27SDimitry Andric static bool isPlainlyKilled(const MachineInstr *MI, Register Reg, 2890b57cec5SDimitry Andric LiveIntervals *LIS) { 290e8d8bef9SDimitry Andric if (LIS && Reg.isVirtual() && !LIS->isNotInMIMap(*MI)) { 2910b57cec5SDimitry Andric // FIXME: Sometimes tryInstructionTransform() will add instructions and 2920b57cec5SDimitry Andric // test whether they can be folded before keeping them. In this case it 2930b57cec5SDimitry Andric // sets a kill before recursively calling tryInstructionTransform() again. 2940b57cec5SDimitry Andric // If there is no interval available, we assume that this instruction is 2950b57cec5SDimitry Andric // one of those. A kill flag is manually inserted on the operand so the 2960b57cec5SDimitry Andric // check below will handle it. 2970b57cec5SDimitry Andric LiveInterval &LI = LIS->getInterval(Reg); 2980b57cec5SDimitry Andric // This is to match the kill flag version where undefs don't have kill 2990b57cec5SDimitry Andric // flags. 3000b57cec5SDimitry Andric if (!LI.hasAtLeastOneValue()) 3010b57cec5SDimitry Andric return false; 3020b57cec5SDimitry Andric 3030b57cec5SDimitry Andric SlotIndex useIdx = LIS->getInstructionIndex(*MI); 3040b57cec5SDimitry Andric LiveInterval::const_iterator I = LI.find(useIdx); 3050b57cec5SDimitry Andric assert(I != LI.end() && "Reg must be live-in to use."); 3060b57cec5SDimitry Andric return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx); 3070b57cec5SDimitry Andric } 3080b57cec5SDimitry Andric 3090b57cec5SDimitry Andric return MI->killsRegister(Reg); 3100b57cec5SDimitry Andric } 3110b57cec5SDimitry Andric 312*06c3fb27SDimitry Andric /// Test if the register used by the given operand is killed by the operand's 313*06c3fb27SDimitry Andric /// instruction. 314*06c3fb27SDimitry Andric static bool isPlainlyKilled(const MachineOperand &MO, LiveIntervals *LIS) { 315*06c3fb27SDimitry Andric return MO.isKill() || isPlainlyKilled(MO.getParent(), MO.getReg(), LIS); 316*06c3fb27SDimitry Andric } 317*06c3fb27SDimitry Andric 3180b57cec5SDimitry Andric /// Test if the given register value, which is used by the given 3190b57cec5SDimitry Andric /// instruction, is killed by the given instruction. This looks through 3200b57cec5SDimitry Andric /// coalescable copies to see if the original value is potentially not killed. 3210b57cec5SDimitry Andric /// 3220b57cec5SDimitry Andric /// For example, in this code: 3230b57cec5SDimitry Andric /// 3240b57cec5SDimitry Andric /// %reg1034 = copy %reg1024 3250b57cec5SDimitry Andric /// %reg1035 = copy killed %reg1025 3260b57cec5SDimitry Andric /// %reg1036 = add killed %reg1034, killed %reg1035 3270b57cec5SDimitry Andric /// 3280b57cec5SDimitry Andric /// %reg1034 is not considered to be killed, since it is copied from a 3290b57cec5SDimitry Andric /// register which is not killed. Treating it as not killed lets the 3300b57cec5SDimitry Andric /// normal heuristics commute the (two-address) add, which lets 3310b57cec5SDimitry Andric /// coalescing eliminate the extra copy. 3320b57cec5SDimitry Andric /// 3330b57cec5SDimitry Andric /// If allowFalsePositives is true then likely kills are treated as kills even 3340b57cec5SDimitry Andric /// if it can't be proven that they are kills. 335e8d8bef9SDimitry Andric static bool isKilled(MachineInstr &MI, Register Reg, 336e8d8bef9SDimitry Andric const MachineRegisterInfo *MRI, const TargetInstrInfo *TII, 337e8d8bef9SDimitry Andric LiveIntervals *LIS, bool allowFalsePositives) { 3380b57cec5SDimitry Andric MachineInstr *DefMI = &MI; 3390b57cec5SDimitry Andric while (true) { 3400b57cec5SDimitry Andric // All uses of physical registers are likely to be kills. 341e8d8bef9SDimitry Andric if (Reg.isPhysical() && (allowFalsePositives || MRI->hasOneUse(Reg))) 3420b57cec5SDimitry Andric return true; 3430b57cec5SDimitry Andric if (!isPlainlyKilled(DefMI, Reg, LIS)) 3440b57cec5SDimitry Andric return false; 345e8d8bef9SDimitry Andric if (Reg.isPhysical()) 3460b57cec5SDimitry Andric return true; 3470b57cec5SDimitry Andric MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg); 3480b57cec5SDimitry Andric // If there are multiple defs, we can't do a simple analysis, so just 3490b57cec5SDimitry Andric // go with what the kill flag says. 3500b57cec5SDimitry Andric if (std::next(Begin) != MRI->def_end()) 3510b57cec5SDimitry Andric return true; 3520b57cec5SDimitry Andric DefMI = Begin->getParent(); 3530b57cec5SDimitry Andric bool IsSrcPhys, IsDstPhys; 354e8d8bef9SDimitry Andric Register SrcReg, DstReg; 3550b57cec5SDimitry Andric // If the def is something other than a copy, then it isn't going to 3560b57cec5SDimitry Andric // be coalesced, so follow the kill flag. 3570b57cec5SDimitry Andric if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) 3580b57cec5SDimitry Andric return true; 3590b57cec5SDimitry Andric Reg = SrcReg; 3600b57cec5SDimitry Andric } 3610b57cec5SDimitry Andric } 3620b57cec5SDimitry Andric 3630b57cec5SDimitry Andric /// Return true if the specified MI uses the specified register as a two-address 3640b57cec5SDimitry Andric /// use. If so, return the destination register by reference. 365e8d8bef9SDimitry Andric static bool isTwoAddrUse(MachineInstr &MI, Register Reg, Register &DstReg) { 3660b57cec5SDimitry Andric for (unsigned i = 0, NumOps = MI.getNumOperands(); i != NumOps; ++i) { 3670b57cec5SDimitry Andric const MachineOperand &MO = MI.getOperand(i); 3680b57cec5SDimitry Andric if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg) 3690b57cec5SDimitry Andric continue; 3700b57cec5SDimitry Andric unsigned ti; 3710b57cec5SDimitry Andric if (MI.isRegTiedToDefOperand(i, &ti)) { 3720b57cec5SDimitry Andric DstReg = MI.getOperand(ti).getReg(); 3730b57cec5SDimitry Andric return true; 3740b57cec5SDimitry Andric } 3750b57cec5SDimitry Andric } 3760b57cec5SDimitry Andric return false; 3770b57cec5SDimitry Andric } 3780b57cec5SDimitry Andric 3794824e7fdSDimitry Andric /// Given a register, if all its uses are in the same basic block, return the 3804824e7fdSDimitry Andric /// last use instruction if it's a copy or a two-address use. 381e8d8bef9SDimitry Andric static MachineInstr * 382e8d8bef9SDimitry Andric findOnlyInterestingUse(Register Reg, MachineBasicBlock *MBB, 383e8d8bef9SDimitry Andric MachineRegisterInfo *MRI, const TargetInstrInfo *TII, 3844824e7fdSDimitry Andric bool &IsCopy, Register &DstReg, bool &IsDstPhys, 3854824e7fdSDimitry Andric LiveIntervals *LIS) { 3864824e7fdSDimitry Andric MachineOperand *UseOp = nullptr; 3874824e7fdSDimitry Andric for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) { 3884824e7fdSDimitry Andric MachineInstr *MI = MO.getParent(); 3894824e7fdSDimitry Andric if (MI->getParent() != MBB) 3900b57cec5SDimitry Andric return nullptr; 3914824e7fdSDimitry Andric if (isPlainlyKilled(MI, Reg, LIS)) 3924824e7fdSDimitry Andric UseOp = &MO; 3934824e7fdSDimitry Andric } 3944824e7fdSDimitry Andric if (!UseOp) 3950b57cec5SDimitry Andric return nullptr; 3964824e7fdSDimitry Andric MachineInstr &UseMI = *UseOp->getParent(); 3974824e7fdSDimitry Andric 398e8d8bef9SDimitry Andric Register SrcReg; 3990b57cec5SDimitry Andric bool IsSrcPhys; 4000b57cec5SDimitry Andric if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) { 4010b57cec5SDimitry Andric IsCopy = true; 4020b57cec5SDimitry Andric return &UseMI; 4030b57cec5SDimitry Andric } 4040b57cec5SDimitry Andric IsDstPhys = false; 4050b57cec5SDimitry Andric if (isTwoAddrUse(UseMI, Reg, DstReg)) { 406e8d8bef9SDimitry Andric IsDstPhys = DstReg.isPhysical(); 4070b57cec5SDimitry Andric return &UseMI; 4080b57cec5SDimitry Andric } 409349cc55cSDimitry Andric if (UseMI.isCommutable()) { 410349cc55cSDimitry Andric unsigned Src1 = TargetInstrInfo::CommuteAnyOperandIndex; 411*06c3fb27SDimitry Andric unsigned Src2 = UseOp->getOperandNo(); 412349cc55cSDimitry Andric if (TII->findCommutedOpIndices(UseMI, Src1, Src2)) { 413349cc55cSDimitry Andric MachineOperand &MO = UseMI.getOperand(Src1); 414349cc55cSDimitry Andric if (MO.isReg() && MO.isUse() && 415349cc55cSDimitry Andric isTwoAddrUse(UseMI, MO.getReg(), DstReg)) { 416349cc55cSDimitry Andric IsDstPhys = DstReg.isPhysical(); 417349cc55cSDimitry Andric return &UseMI; 418349cc55cSDimitry Andric } 419349cc55cSDimitry Andric } 420349cc55cSDimitry Andric } 4210b57cec5SDimitry Andric return nullptr; 4220b57cec5SDimitry Andric } 4230b57cec5SDimitry Andric 4240b57cec5SDimitry Andric /// Return the physical register the specified virtual register might be mapped 4250b57cec5SDimitry Andric /// to. 426e8d8bef9SDimitry Andric static MCRegister getMappedReg(Register Reg, 427e8d8bef9SDimitry Andric DenseMap<Register, Register> &RegMap) { 428e8d8bef9SDimitry Andric while (Reg.isVirtual()) { 429e8d8bef9SDimitry Andric DenseMap<Register, Register>::iterator SI = RegMap.find(Reg); 4300b57cec5SDimitry Andric if (SI == RegMap.end()) 4310b57cec5SDimitry Andric return 0; 4320b57cec5SDimitry Andric Reg = SI->second; 4330b57cec5SDimitry Andric } 434e8d8bef9SDimitry Andric if (Reg.isPhysical()) 4350b57cec5SDimitry Andric return Reg; 4360b57cec5SDimitry Andric return 0; 4370b57cec5SDimitry Andric } 4380b57cec5SDimitry Andric 4390b57cec5SDimitry Andric /// Return true if the two registers are equal or aliased. 440e8d8bef9SDimitry Andric static bool regsAreCompatible(Register RegA, Register RegB, 441e8d8bef9SDimitry Andric const TargetRegisterInfo *TRI) { 4420b57cec5SDimitry Andric if (RegA == RegB) 4430b57cec5SDimitry Andric return true; 4440b57cec5SDimitry Andric if (!RegA || !RegB) 4450b57cec5SDimitry Andric return false; 4460b57cec5SDimitry Andric return TRI->regsOverlap(RegA, RegB); 4470b57cec5SDimitry Andric } 4480b57cec5SDimitry Andric 449349cc55cSDimitry Andric /// From RegMap remove entries mapped to a physical register which overlaps MO. 450349cc55cSDimitry Andric static void removeMapRegEntry(const MachineOperand &MO, 451349cc55cSDimitry Andric DenseMap<Register, Register> &RegMap, 452349cc55cSDimitry Andric const TargetRegisterInfo *TRI) { 453349cc55cSDimitry Andric assert( 454349cc55cSDimitry Andric (MO.isReg() || MO.isRegMask()) && 455349cc55cSDimitry Andric "removeMapRegEntry must be called with a register or regmask operand."); 456349cc55cSDimitry Andric 457349cc55cSDimitry Andric SmallVector<Register, 2> Srcs; 458349cc55cSDimitry Andric for (auto SI : RegMap) { 459349cc55cSDimitry Andric Register ToReg = SI.second; 460349cc55cSDimitry Andric if (ToReg.isVirtual()) 461349cc55cSDimitry Andric continue; 462349cc55cSDimitry Andric 463349cc55cSDimitry Andric if (MO.isReg()) { 464349cc55cSDimitry Andric Register Reg = MO.getReg(); 465349cc55cSDimitry Andric if (TRI->regsOverlap(ToReg, Reg)) 466349cc55cSDimitry Andric Srcs.push_back(SI.first); 467349cc55cSDimitry Andric } else if (MO.clobbersPhysReg(ToReg)) 468349cc55cSDimitry Andric Srcs.push_back(SI.first); 469349cc55cSDimitry Andric } 470349cc55cSDimitry Andric 471349cc55cSDimitry Andric for (auto SrcReg : Srcs) 472349cc55cSDimitry Andric RegMap.erase(SrcReg); 473349cc55cSDimitry Andric } 474349cc55cSDimitry Andric 475349cc55cSDimitry Andric /// If a physical register is clobbered, old entries mapped to it should be 476349cc55cSDimitry Andric /// deleted. For example 477349cc55cSDimitry Andric /// 478349cc55cSDimitry Andric /// %2:gr64 = COPY killed $rdx 479349cc55cSDimitry Andric /// MUL64r %3:gr64, implicit-def $rax, implicit-def $rdx 480349cc55cSDimitry Andric /// 481349cc55cSDimitry Andric /// After the MUL instruction, $rdx contains different value than in the COPY 482349cc55cSDimitry Andric /// instruction. So %2 should not map to $rdx after MUL. 483349cc55cSDimitry Andric void TwoAddressInstructionPass::removeClobberedSrcRegMap(MachineInstr *MI) { 484349cc55cSDimitry Andric if (MI->isCopy()) { 485349cc55cSDimitry Andric // If a virtual register is copied to its mapped physical register, it 486349cc55cSDimitry Andric // doesn't change the potential coalescing between them, so we don't remove 487349cc55cSDimitry Andric // entries mapped to the physical register. For example 488349cc55cSDimitry Andric // 489349cc55cSDimitry Andric // %100 = COPY $r8 490349cc55cSDimitry Andric // ... 491349cc55cSDimitry Andric // $r8 = COPY %100 492349cc55cSDimitry Andric // 493349cc55cSDimitry Andric // The first copy constructs SrcRegMap[%100] = $r8, the second copy doesn't 494349cc55cSDimitry Andric // destroy the content of $r8, and should not impact SrcRegMap. 495349cc55cSDimitry Andric Register Dst = MI->getOperand(0).getReg(); 496349cc55cSDimitry Andric if (!Dst || Dst.isVirtual()) 497349cc55cSDimitry Andric return; 498349cc55cSDimitry Andric 499349cc55cSDimitry Andric Register Src = MI->getOperand(1).getReg(); 500349cc55cSDimitry Andric if (regsAreCompatible(Dst, getMappedReg(Src, SrcRegMap), TRI)) 501349cc55cSDimitry Andric return; 502349cc55cSDimitry Andric } 503349cc55cSDimitry Andric 5044824e7fdSDimitry Andric for (const MachineOperand &MO : MI->operands()) { 505349cc55cSDimitry Andric if (MO.isRegMask()) { 506349cc55cSDimitry Andric removeMapRegEntry(MO, SrcRegMap, TRI); 507349cc55cSDimitry Andric continue; 508349cc55cSDimitry Andric } 509349cc55cSDimitry Andric if (!MO.isReg() || !MO.isDef()) 510349cc55cSDimitry Andric continue; 511349cc55cSDimitry Andric Register Reg = MO.getReg(); 512349cc55cSDimitry Andric if (!Reg || Reg.isVirtual()) 513349cc55cSDimitry Andric continue; 514349cc55cSDimitry Andric removeMapRegEntry(MO, SrcRegMap, TRI); 515349cc55cSDimitry Andric } 516349cc55cSDimitry Andric } 517349cc55cSDimitry Andric 5180b57cec5SDimitry Andric // Returns true if Reg is equal or aliased to at least one register in Set. 519e8d8bef9SDimitry Andric static bool regOverlapsSet(const SmallVectorImpl<Register> &Set, Register Reg, 5200b57cec5SDimitry Andric const TargetRegisterInfo *TRI) { 5210b57cec5SDimitry Andric for (unsigned R : Set) 5220b57cec5SDimitry Andric if (TRI->regsOverlap(R, Reg)) 5230b57cec5SDimitry Andric return true; 5240b57cec5SDimitry Andric 5250b57cec5SDimitry Andric return false; 5260b57cec5SDimitry Andric } 5270b57cec5SDimitry Andric 5280b57cec5SDimitry Andric /// Return true if it's potentially profitable to commute the two-address 5290b57cec5SDimitry Andric /// instruction that's being processed. 530e8d8bef9SDimitry Andric bool TwoAddressInstructionPass::isProfitableToCommute(Register RegA, 531e8d8bef9SDimitry Andric Register RegB, 532e8d8bef9SDimitry Andric Register RegC, 533e8d8bef9SDimitry Andric MachineInstr *MI, 534e8d8bef9SDimitry Andric unsigned Dist) { 5350b57cec5SDimitry Andric if (OptLevel == CodeGenOpt::None) 5360b57cec5SDimitry Andric return false; 5370b57cec5SDimitry Andric 5380b57cec5SDimitry Andric // Determine if it's profitable to commute this two address instruction. In 5390b57cec5SDimitry Andric // general, we want no uses between this instruction and the definition of 5400b57cec5SDimitry Andric // the two-address register. 5410b57cec5SDimitry Andric // e.g. 5420b57cec5SDimitry Andric // %reg1028 = EXTRACT_SUBREG killed %reg1027, 1 5430b57cec5SDimitry Andric // %reg1029 = COPY %reg1028 5440b57cec5SDimitry Andric // %reg1029 = SHR8ri %reg1029, 7, implicit dead %eflags 5450b57cec5SDimitry Andric // insert => %reg1030 = COPY %reg1028 5460b57cec5SDimitry Andric // %reg1030 = ADD8rr killed %reg1028, killed %reg1029, implicit dead %eflags 5470b57cec5SDimitry Andric // In this case, it might not be possible to coalesce the second COPY 5480b57cec5SDimitry Andric // instruction if the first one is coalesced. So it would be profitable to 5490b57cec5SDimitry Andric // commute it: 5500b57cec5SDimitry Andric // %reg1028 = EXTRACT_SUBREG killed %reg1027, 1 5510b57cec5SDimitry Andric // %reg1029 = COPY %reg1028 5520b57cec5SDimitry Andric // %reg1029 = SHR8ri %reg1029, 7, implicit dead %eflags 5530b57cec5SDimitry Andric // insert => %reg1030 = COPY %reg1029 5540b57cec5SDimitry Andric // %reg1030 = ADD8rr killed %reg1029, killed %reg1028, implicit dead %eflags 5550b57cec5SDimitry Andric 556e8d8bef9SDimitry Andric if (!isPlainlyKilled(MI, RegC, LIS)) 5570b57cec5SDimitry Andric return false; 5580b57cec5SDimitry Andric 5590b57cec5SDimitry Andric // Ok, we have something like: 5600b57cec5SDimitry Andric // %reg1030 = ADD8rr killed %reg1028, killed %reg1029, implicit dead %eflags 5610b57cec5SDimitry Andric // let's see if it's worth commuting it. 5620b57cec5SDimitry Andric 5630b57cec5SDimitry Andric // Look for situations like this: 5640b57cec5SDimitry Andric // %reg1024 = MOV r1 5650b57cec5SDimitry Andric // %reg1025 = MOV r0 5660b57cec5SDimitry Andric // %reg1026 = ADD %reg1024, %reg1025 5670b57cec5SDimitry Andric // r0 = MOV %reg1026 5680b57cec5SDimitry Andric // Commute the ADD to hopefully eliminate an otherwise unavoidable copy. 569e8d8bef9SDimitry Andric MCRegister ToRegA = getMappedReg(RegA, DstRegMap); 5700b57cec5SDimitry Andric if (ToRegA) { 571e8d8bef9SDimitry Andric MCRegister FromRegB = getMappedReg(RegB, SrcRegMap); 572e8d8bef9SDimitry Andric MCRegister FromRegC = getMappedReg(RegC, SrcRegMap); 5730b57cec5SDimitry Andric bool CompB = FromRegB && regsAreCompatible(FromRegB, ToRegA, TRI); 5740b57cec5SDimitry Andric bool CompC = FromRegC && regsAreCompatible(FromRegC, ToRegA, TRI); 5750b57cec5SDimitry Andric 5760b57cec5SDimitry Andric // Compute if any of the following are true: 5770b57cec5SDimitry Andric // -RegB is not tied to a register and RegC is compatible with RegA. 5780b57cec5SDimitry Andric // -RegB is tied to the wrong physical register, but RegC is. 5790b57cec5SDimitry Andric // -RegB is tied to the wrong physical register, and RegC isn't tied. 5800b57cec5SDimitry Andric if ((!FromRegB && CompC) || (FromRegB && !CompB && (!FromRegC || CompC))) 5810b57cec5SDimitry Andric return true; 5820b57cec5SDimitry Andric // Don't compute if any of the following are true: 5830b57cec5SDimitry Andric // -RegC is not tied to a register and RegB is compatible with RegA. 5840b57cec5SDimitry Andric // -RegC is tied to the wrong physical register, but RegB is. 5850b57cec5SDimitry Andric // -RegC is tied to the wrong physical register, and RegB isn't tied. 5860b57cec5SDimitry Andric if ((!FromRegC && CompB) || (FromRegC && !CompC && (!FromRegB || CompB))) 5870b57cec5SDimitry Andric return false; 5880b57cec5SDimitry Andric } 5890b57cec5SDimitry Andric 590e8d8bef9SDimitry Andric // If there is a use of RegC between its last def (could be livein) and this 5910b57cec5SDimitry Andric // instruction, then bail. 5920b57cec5SDimitry Andric unsigned LastDefC = 0; 593e8d8bef9SDimitry Andric if (!noUseAfterLastDef(RegC, Dist, LastDefC)) 5940b57cec5SDimitry Andric return false; 5950b57cec5SDimitry Andric 596e8d8bef9SDimitry Andric // If there is a use of RegB between its last def (could be livein) and this 5970b57cec5SDimitry Andric // instruction, then go ahead and make this transformation. 5980b57cec5SDimitry Andric unsigned LastDefB = 0; 599e8d8bef9SDimitry Andric if (!noUseAfterLastDef(RegB, Dist, LastDefB)) 6000b57cec5SDimitry Andric return true; 6010b57cec5SDimitry Andric 6020b57cec5SDimitry Andric // Look for situation like this: 6030b57cec5SDimitry Andric // %reg101 = MOV %reg100 6040b57cec5SDimitry Andric // %reg102 = ... 6050b57cec5SDimitry Andric // %reg103 = ADD %reg102, %reg101 6060b57cec5SDimitry Andric // ... = %reg103 ... 6070b57cec5SDimitry Andric // %reg100 = MOV %reg103 6080b57cec5SDimitry Andric // If there is a reversed copy chain from reg101 to reg103, commute the ADD 6090b57cec5SDimitry Andric // to eliminate an otherwise unavoidable copy. 6100b57cec5SDimitry Andric // FIXME: 6110b57cec5SDimitry Andric // We can extend the logic further: If an pair of operands in an insn has 6120b57cec5SDimitry Andric // been merged, the insn could be regarded as a virtual copy, and the virtual 6130b57cec5SDimitry Andric // copy could also be used to construct a copy chain. 6140b57cec5SDimitry Andric // To more generally minimize register copies, ideally the logic of two addr 6150b57cec5SDimitry Andric // instruction pass should be integrated with register allocation pass where 6160b57cec5SDimitry Andric // interference graph is available. 617e8d8bef9SDimitry Andric if (isRevCopyChain(RegC, RegA, MaxDataFlowEdge)) 6180b57cec5SDimitry Andric return true; 6190b57cec5SDimitry Andric 620e8d8bef9SDimitry Andric if (isRevCopyChain(RegB, RegA, MaxDataFlowEdge)) 6210b57cec5SDimitry Andric return false; 6220b57cec5SDimitry Andric 623fe6060f1SDimitry Andric // Look for other target specific commute preference. 624fe6060f1SDimitry Andric bool Commute; 625fe6060f1SDimitry Andric if (TII->hasCommutePreference(*MI, Commute)) 626fe6060f1SDimitry Andric return Commute; 627fe6060f1SDimitry Andric 6280b57cec5SDimitry Andric // Since there are no intervening uses for both registers, then commute 629e8d8bef9SDimitry Andric // if the def of RegC is closer. Its live interval is shorter. 6300b57cec5SDimitry Andric return LastDefB && LastDefC && LastDefC > LastDefB; 6310b57cec5SDimitry Andric } 6320b57cec5SDimitry Andric 6330b57cec5SDimitry Andric /// Commute a two-address instruction and update the basic block, distance map, 6340b57cec5SDimitry Andric /// and live variables if needed. Return true if it is successful. 6350b57cec5SDimitry Andric bool TwoAddressInstructionPass::commuteInstruction(MachineInstr *MI, 6360b57cec5SDimitry Andric unsigned DstIdx, 6370b57cec5SDimitry Andric unsigned RegBIdx, 6380b57cec5SDimitry Andric unsigned RegCIdx, 6390b57cec5SDimitry Andric unsigned Dist) { 6408bcb0991SDimitry Andric Register RegC = MI->getOperand(RegCIdx).getReg(); 6410b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: COMMUTING : " << *MI); 6420b57cec5SDimitry Andric MachineInstr *NewMI = TII->commuteInstruction(*MI, false, RegBIdx, RegCIdx); 6430b57cec5SDimitry Andric 6440b57cec5SDimitry Andric if (NewMI == nullptr) { 6450b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n"); 6460b57cec5SDimitry Andric return false; 6470b57cec5SDimitry Andric } 6480b57cec5SDimitry Andric 6490b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI); 6500b57cec5SDimitry Andric assert(NewMI == MI && 6510b57cec5SDimitry Andric "TargetInstrInfo::commuteInstruction() should not return a new " 6520b57cec5SDimitry Andric "instruction unless it was requested."); 6530b57cec5SDimitry Andric 6540b57cec5SDimitry Andric // Update source register map. 655e8d8bef9SDimitry Andric MCRegister FromRegC = getMappedReg(RegC, SrcRegMap); 6560b57cec5SDimitry Andric if (FromRegC) { 6578bcb0991SDimitry Andric Register RegA = MI->getOperand(DstIdx).getReg(); 6580b57cec5SDimitry Andric SrcRegMap[RegA] = FromRegC; 6590b57cec5SDimitry Andric } 6600b57cec5SDimitry Andric 6610b57cec5SDimitry Andric return true; 6620b57cec5SDimitry Andric } 6630b57cec5SDimitry Andric 6640b57cec5SDimitry Andric /// Return true if it is profitable to convert the given 2-address instruction 6650b57cec5SDimitry Andric /// to a 3-address one. 666e8d8bef9SDimitry Andric bool TwoAddressInstructionPass::isProfitableToConv3Addr(Register RegA, 667e8d8bef9SDimitry Andric Register RegB) { 6680b57cec5SDimitry Andric // Look for situations like this: 6690b57cec5SDimitry Andric // %reg1024 = MOV r1 6700b57cec5SDimitry Andric // %reg1025 = MOV r0 6710b57cec5SDimitry Andric // %reg1026 = ADD %reg1024, %reg1025 6720b57cec5SDimitry Andric // r2 = MOV %reg1026 6730b57cec5SDimitry Andric // Turn ADD into a 3-address instruction to avoid a copy. 674e8d8bef9SDimitry Andric MCRegister FromRegB = getMappedReg(RegB, SrcRegMap); 6750b57cec5SDimitry Andric if (!FromRegB) 6760b57cec5SDimitry Andric return false; 677e8d8bef9SDimitry Andric MCRegister ToRegA = getMappedReg(RegA, DstRegMap); 6780b57cec5SDimitry Andric return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI)); 6790b57cec5SDimitry Andric } 6800b57cec5SDimitry Andric 6810b57cec5SDimitry Andric /// Convert the specified two-address instruction into a three address one. 6820b57cec5SDimitry Andric /// Return true if this transformation was successful. 683e8d8bef9SDimitry Andric bool TwoAddressInstructionPass::convertInstTo3Addr( 684e8d8bef9SDimitry Andric MachineBasicBlock::iterator &mi, MachineBasicBlock::iterator &nmi, 685349cc55cSDimitry Andric Register RegA, Register RegB, unsigned &Dist) { 686349cc55cSDimitry Andric MachineInstrSpan MIS(mi, MBB); 687349cc55cSDimitry Andric MachineInstr *NewMI = TII->convertToThreeAddress(*mi, LV, LIS); 6880b57cec5SDimitry Andric if (!NewMI) 6890b57cec5SDimitry Andric return false; 6900b57cec5SDimitry Andric 6910b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi); 6920b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI); 6930b57cec5SDimitry Andric 694e8d8bef9SDimitry Andric // If the old instruction is debug value tracked, an update is required. 695e8d8bef9SDimitry Andric if (auto OldInstrNum = mi->peekDebugInstrNum()) { 696e8d8bef9SDimitry Andric assert(mi->getNumExplicitDefs() == 1); 697e8d8bef9SDimitry Andric assert(NewMI->getNumExplicitDefs() == 1); 698e8d8bef9SDimitry Andric 699e8d8bef9SDimitry Andric // Find the old and new def location. 700*06c3fb27SDimitry Andric unsigned OldIdx = mi->defs().begin()->getOperandNo(); 701*06c3fb27SDimitry Andric unsigned NewIdx = NewMI->defs().begin()->getOperandNo(); 702e8d8bef9SDimitry Andric 703e8d8bef9SDimitry Andric // Record that one def has been replaced by the other. 704e8d8bef9SDimitry Andric unsigned NewInstrNum = NewMI->getDebugInstrNum(); 705e8d8bef9SDimitry Andric MF->makeDebugValueSubstitution(std::make_pair(OldInstrNum, OldIdx), 706e8d8bef9SDimitry Andric std::make_pair(NewInstrNum, NewIdx)); 707e8d8bef9SDimitry Andric } 708e8d8bef9SDimitry Andric 7090b57cec5SDimitry Andric MBB->erase(mi); // Nuke the old inst. 7100b57cec5SDimitry Andric 711349cc55cSDimitry Andric for (MachineInstr &MI : MIS) 712349cc55cSDimitry Andric DistanceMap.insert(std::make_pair(&MI, Dist++)); 713349cc55cSDimitry Andric Dist--; 7140b57cec5SDimitry Andric mi = NewMI; 7150b57cec5SDimitry Andric nmi = std::next(mi); 7160b57cec5SDimitry Andric 7170b57cec5SDimitry Andric // Update source and destination register maps. 7180b57cec5SDimitry Andric SrcRegMap.erase(RegA); 7190b57cec5SDimitry Andric DstRegMap.erase(RegB); 7200b57cec5SDimitry Andric return true; 7210b57cec5SDimitry Andric } 7220b57cec5SDimitry Andric 7230b57cec5SDimitry Andric /// Scan forward recursively for only uses, update maps if the use is a copy or 7240b57cec5SDimitry Andric /// a two-address instruction. 725e8d8bef9SDimitry Andric void TwoAddressInstructionPass::scanUses(Register DstReg) { 726e8d8bef9SDimitry Andric SmallVector<Register, 4> VirtRegPairs; 7270b57cec5SDimitry Andric bool IsDstPhys; 7280b57cec5SDimitry Andric bool IsCopy = false; 729e8d8bef9SDimitry Andric Register NewReg; 730e8d8bef9SDimitry Andric Register Reg = DstReg; 7310b57cec5SDimitry Andric while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy, 7324824e7fdSDimitry Andric NewReg, IsDstPhys, LIS)) { 7330b57cec5SDimitry Andric if (IsCopy && !Processed.insert(UseMI).second) 7340b57cec5SDimitry Andric break; 7350b57cec5SDimitry Andric 7360b57cec5SDimitry Andric DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI); 7370b57cec5SDimitry Andric if (DI != DistanceMap.end()) 7380b57cec5SDimitry Andric // Earlier in the same MBB.Reached via a back edge. 7390b57cec5SDimitry Andric break; 7400b57cec5SDimitry Andric 7410b57cec5SDimitry Andric if (IsDstPhys) { 7420b57cec5SDimitry Andric VirtRegPairs.push_back(NewReg); 7430b57cec5SDimitry Andric break; 7440b57cec5SDimitry Andric } 745349cc55cSDimitry Andric SrcRegMap[NewReg] = Reg; 7460b57cec5SDimitry Andric VirtRegPairs.push_back(NewReg); 7470b57cec5SDimitry Andric Reg = NewReg; 7480b57cec5SDimitry Andric } 7490b57cec5SDimitry Andric 7500b57cec5SDimitry Andric if (!VirtRegPairs.empty()) { 7510b57cec5SDimitry Andric unsigned ToReg = VirtRegPairs.back(); 7520b57cec5SDimitry Andric VirtRegPairs.pop_back(); 7530b57cec5SDimitry Andric while (!VirtRegPairs.empty()) { 754349cc55cSDimitry Andric unsigned FromReg = VirtRegPairs.pop_back_val(); 7550b57cec5SDimitry Andric bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second; 7560b57cec5SDimitry Andric if (!isNew) 7570b57cec5SDimitry Andric assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!"); 7580b57cec5SDimitry Andric ToReg = FromReg; 7590b57cec5SDimitry Andric } 7600b57cec5SDimitry Andric bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second; 7610b57cec5SDimitry Andric if (!isNew) 7620b57cec5SDimitry Andric assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!"); 7630b57cec5SDimitry Andric } 7640b57cec5SDimitry Andric } 7650b57cec5SDimitry Andric 7660b57cec5SDimitry Andric /// If the specified instruction is not yet processed, process it if it's a 7670b57cec5SDimitry Andric /// copy. For a copy instruction, we find the physical registers the 7680b57cec5SDimitry Andric /// source and destination registers might be mapped to. These are kept in 7690b57cec5SDimitry Andric /// point-to maps used to determine future optimizations. e.g. 7700b57cec5SDimitry Andric /// v1024 = mov r0 7710b57cec5SDimitry Andric /// v1025 = mov r1 7720b57cec5SDimitry Andric /// v1026 = add v1024, v1025 7730b57cec5SDimitry Andric /// r1 = mov r1026 7740b57cec5SDimitry Andric /// If 'add' is a two-address instruction, v1024, v1026 are both potentially 7750b57cec5SDimitry Andric /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is 7760b57cec5SDimitry Andric /// potentially joined with r1 on the output side. It's worthwhile to commute 7770b57cec5SDimitry Andric /// 'add' to eliminate a copy. 7780b57cec5SDimitry Andric void TwoAddressInstructionPass::processCopy(MachineInstr *MI) { 7790b57cec5SDimitry Andric if (Processed.count(MI)) 7800b57cec5SDimitry Andric return; 7810b57cec5SDimitry Andric 7820b57cec5SDimitry Andric bool IsSrcPhys, IsDstPhys; 783e8d8bef9SDimitry Andric Register SrcReg, DstReg; 7840b57cec5SDimitry Andric if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) 7850b57cec5SDimitry Andric return; 7860b57cec5SDimitry Andric 787e8d8bef9SDimitry Andric if (IsDstPhys && !IsSrcPhys) { 7880b57cec5SDimitry Andric DstRegMap.insert(std::make_pair(SrcReg, DstReg)); 789e8d8bef9SDimitry Andric } else if (!IsDstPhys && IsSrcPhys) { 7900b57cec5SDimitry Andric bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second; 7910b57cec5SDimitry Andric if (!isNew) 7920b57cec5SDimitry Andric assert(SrcRegMap[DstReg] == SrcReg && 7930b57cec5SDimitry Andric "Can't map to two src physical registers!"); 7940b57cec5SDimitry Andric 7950b57cec5SDimitry Andric scanUses(DstReg); 7960b57cec5SDimitry Andric } 7970b57cec5SDimitry Andric 7980b57cec5SDimitry Andric Processed.insert(MI); 7990b57cec5SDimitry Andric } 8000b57cec5SDimitry Andric 8010b57cec5SDimitry Andric /// If there is one more local instruction that reads 'Reg' and it kills 'Reg, 8020b57cec5SDimitry Andric /// consider moving the instruction below the kill instruction in order to 8030b57cec5SDimitry Andric /// eliminate the need for the copy. 804e8d8bef9SDimitry Andric bool TwoAddressInstructionPass::rescheduleMIBelowKill( 805e8d8bef9SDimitry Andric MachineBasicBlock::iterator &mi, MachineBasicBlock::iterator &nmi, 806e8d8bef9SDimitry Andric Register Reg) { 8070b57cec5SDimitry Andric // Bail immediately if we don't have LV or LIS available. We use them to find 8080b57cec5SDimitry Andric // kills efficiently. 8090b57cec5SDimitry Andric if (!LV && !LIS) 8100b57cec5SDimitry Andric return false; 8110b57cec5SDimitry Andric 8120b57cec5SDimitry Andric MachineInstr *MI = &*mi; 8130b57cec5SDimitry Andric DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI); 8140b57cec5SDimitry Andric if (DI == DistanceMap.end()) 8150b57cec5SDimitry Andric // Must be created from unfolded load. Don't waste time trying this. 8160b57cec5SDimitry Andric return false; 8170b57cec5SDimitry Andric 8180b57cec5SDimitry Andric MachineInstr *KillMI = nullptr; 8190b57cec5SDimitry Andric if (LIS) { 8200b57cec5SDimitry Andric LiveInterval &LI = LIS->getInterval(Reg); 8210b57cec5SDimitry Andric assert(LI.end() != LI.begin() && 8220b57cec5SDimitry Andric "Reg should not have empty live interval."); 8230b57cec5SDimitry Andric 8240b57cec5SDimitry Andric SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot(); 8250b57cec5SDimitry Andric LiveInterval::const_iterator I = LI.find(MBBEndIdx); 8260b57cec5SDimitry Andric if (I != LI.end() && I->start < MBBEndIdx) 8270b57cec5SDimitry Andric return false; 8280b57cec5SDimitry Andric 8290b57cec5SDimitry Andric --I; 8300b57cec5SDimitry Andric KillMI = LIS->getInstructionFromIndex(I->end); 8310b57cec5SDimitry Andric } else { 8320b57cec5SDimitry Andric KillMI = LV->getVarInfo(Reg).findKill(MBB); 8330b57cec5SDimitry Andric } 8340b57cec5SDimitry Andric if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike()) 8350b57cec5SDimitry Andric // Don't mess with copies, they may be coalesced later. 8360b57cec5SDimitry Andric return false; 8370b57cec5SDimitry Andric 8380b57cec5SDimitry Andric if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() || 8390b57cec5SDimitry Andric KillMI->isBranch() || KillMI->isTerminator()) 8400b57cec5SDimitry Andric // Don't move pass calls, etc. 8410b57cec5SDimitry Andric return false; 8420b57cec5SDimitry Andric 843e8d8bef9SDimitry Andric Register DstReg; 8440b57cec5SDimitry Andric if (isTwoAddrUse(*KillMI, Reg, DstReg)) 8450b57cec5SDimitry Andric return false; 8460b57cec5SDimitry Andric 8470b57cec5SDimitry Andric bool SeenStore = true; 8480b57cec5SDimitry Andric if (!MI->isSafeToMove(AA, SeenStore)) 8490b57cec5SDimitry Andric return false; 8500b57cec5SDimitry Andric 8510b57cec5SDimitry Andric if (TII->getInstrLatency(InstrItins, *MI) > 1) 8520b57cec5SDimitry Andric // FIXME: Needs more sophisticated heuristics. 8530b57cec5SDimitry Andric return false; 8540b57cec5SDimitry Andric 855e8d8bef9SDimitry Andric SmallVector<Register, 2> Uses; 856e8d8bef9SDimitry Andric SmallVector<Register, 2> Kills; 857e8d8bef9SDimitry Andric SmallVector<Register, 2> Defs; 8580b57cec5SDimitry Andric for (const MachineOperand &MO : MI->operands()) { 8590b57cec5SDimitry Andric if (!MO.isReg()) 8600b57cec5SDimitry Andric continue; 8618bcb0991SDimitry Andric Register MOReg = MO.getReg(); 8620b57cec5SDimitry Andric if (!MOReg) 8630b57cec5SDimitry Andric continue; 8640b57cec5SDimitry Andric if (MO.isDef()) 8650b57cec5SDimitry Andric Defs.push_back(MOReg); 8660b57cec5SDimitry Andric else { 8670b57cec5SDimitry Andric Uses.push_back(MOReg); 868*06c3fb27SDimitry Andric if (MOReg != Reg && isPlainlyKilled(MO, LIS)) 8690b57cec5SDimitry Andric Kills.push_back(MOReg); 8700b57cec5SDimitry Andric } 8710b57cec5SDimitry Andric } 8720b57cec5SDimitry Andric 8730b57cec5SDimitry Andric // Move the copies connected to MI down as well. 8740b57cec5SDimitry Andric MachineBasicBlock::iterator Begin = MI; 8750b57cec5SDimitry Andric MachineBasicBlock::iterator AfterMI = std::next(Begin); 8760b57cec5SDimitry Andric MachineBasicBlock::iterator End = AfterMI; 8770b57cec5SDimitry Andric while (End != MBB->end()) { 8780b57cec5SDimitry Andric End = skipDebugInstructionsForward(End, MBB->end()); 8790b57cec5SDimitry Andric if (End->isCopy() && regOverlapsSet(Defs, End->getOperand(1).getReg(), TRI)) 8800b57cec5SDimitry Andric Defs.push_back(End->getOperand(0).getReg()); 8810b57cec5SDimitry Andric else 8820b57cec5SDimitry Andric break; 8830b57cec5SDimitry Andric ++End; 8840b57cec5SDimitry Andric } 8850b57cec5SDimitry Andric 8860b57cec5SDimitry Andric // Check if the reschedule will not break dependencies. 8870b57cec5SDimitry Andric unsigned NumVisited = 0; 8880b57cec5SDimitry Andric MachineBasicBlock::iterator KillPos = KillMI; 8890b57cec5SDimitry Andric ++KillPos; 8900b57cec5SDimitry Andric for (MachineInstr &OtherMI : make_range(End, KillPos)) { 891d409305fSDimitry Andric // Debug or pseudo instructions cannot be counted against the limit. 892d409305fSDimitry Andric if (OtherMI.isDebugOrPseudoInstr()) 8930b57cec5SDimitry Andric continue; 8940b57cec5SDimitry Andric if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost. 8950b57cec5SDimitry Andric return false; 8960b57cec5SDimitry Andric ++NumVisited; 8970b57cec5SDimitry Andric if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() || 8980b57cec5SDimitry Andric OtherMI.isBranch() || OtherMI.isTerminator()) 8990b57cec5SDimitry Andric // Don't move pass calls, etc. 9000b57cec5SDimitry Andric return false; 9010b57cec5SDimitry Andric for (const MachineOperand &MO : OtherMI.operands()) { 9020b57cec5SDimitry Andric if (!MO.isReg()) 9030b57cec5SDimitry Andric continue; 9048bcb0991SDimitry Andric Register MOReg = MO.getReg(); 9050b57cec5SDimitry Andric if (!MOReg) 9060b57cec5SDimitry Andric continue; 9070b57cec5SDimitry Andric if (MO.isDef()) { 9080b57cec5SDimitry Andric if (regOverlapsSet(Uses, MOReg, TRI)) 9090b57cec5SDimitry Andric // Physical register use would be clobbered. 9100b57cec5SDimitry Andric return false; 9110b57cec5SDimitry Andric if (!MO.isDead() && regOverlapsSet(Defs, MOReg, TRI)) 9120b57cec5SDimitry Andric // May clobber a physical register def. 9130b57cec5SDimitry Andric // FIXME: This may be too conservative. It's ok if the instruction 9140b57cec5SDimitry Andric // is sunken completely below the use. 9150b57cec5SDimitry Andric return false; 9160b57cec5SDimitry Andric } else { 9170b57cec5SDimitry Andric if (regOverlapsSet(Defs, MOReg, TRI)) 9180b57cec5SDimitry Andric return false; 919*06c3fb27SDimitry Andric bool isKill = isPlainlyKilled(MO, LIS); 9200b57cec5SDimitry Andric if (MOReg != Reg && ((isKill && regOverlapsSet(Uses, MOReg, TRI)) || 9210b57cec5SDimitry Andric regOverlapsSet(Kills, MOReg, TRI))) 9220b57cec5SDimitry Andric // Don't want to extend other live ranges and update kills. 9230b57cec5SDimitry Andric return false; 9240b57cec5SDimitry Andric if (MOReg == Reg && !isKill) 9250b57cec5SDimitry Andric // We can't schedule across a use of the register in question. 9260b57cec5SDimitry Andric return false; 9270b57cec5SDimitry Andric // Ensure that if this is register in question, its the kill we expect. 9280b57cec5SDimitry Andric assert((MOReg != Reg || &OtherMI == KillMI) && 9290b57cec5SDimitry Andric "Found multiple kills of a register in a basic block"); 9300b57cec5SDimitry Andric } 9310b57cec5SDimitry Andric } 9320b57cec5SDimitry Andric } 9330b57cec5SDimitry Andric 9340b57cec5SDimitry Andric // Move debug info as well. 9350b57cec5SDimitry Andric while (Begin != MBB->begin() && std::prev(Begin)->isDebugInstr()) 9360b57cec5SDimitry Andric --Begin; 9370b57cec5SDimitry Andric 9380b57cec5SDimitry Andric nmi = End; 9390b57cec5SDimitry Andric MachineBasicBlock::iterator InsertPos = KillPos; 9400b57cec5SDimitry Andric if (LIS) { 941349cc55cSDimitry Andric // We have to move the copies (and any interleaved debug instructions) 942349cc55cSDimitry Andric // first so that the MBB is still well-formed when calling handleMove(). 9430b57cec5SDimitry Andric for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) { 9440b57cec5SDimitry Andric auto CopyMI = MBBI++; 9450b57cec5SDimitry Andric MBB->splice(InsertPos, MBB, CopyMI); 946349cc55cSDimitry Andric if (!CopyMI->isDebugOrPseudoInstr()) 9470b57cec5SDimitry Andric LIS->handleMove(*CopyMI); 9480b57cec5SDimitry Andric InsertPos = CopyMI; 9490b57cec5SDimitry Andric } 9500b57cec5SDimitry Andric End = std::next(MachineBasicBlock::iterator(MI)); 9510b57cec5SDimitry Andric } 9520b57cec5SDimitry Andric 9530b57cec5SDimitry Andric // Copies following MI may have been moved as well. 9540b57cec5SDimitry Andric MBB->splice(InsertPos, MBB, Begin, End); 9550b57cec5SDimitry Andric DistanceMap.erase(DI); 9560b57cec5SDimitry Andric 9570b57cec5SDimitry Andric // Update live variables 9580b57cec5SDimitry Andric if (LIS) { 9590b57cec5SDimitry Andric LIS->handleMove(*MI); 9600b57cec5SDimitry Andric } else { 9610b57cec5SDimitry Andric LV->removeVirtualRegisterKilled(Reg, *KillMI); 9620b57cec5SDimitry Andric LV->addVirtualRegisterKilled(Reg, *MI); 9630b57cec5SDimitry Andric } 9640b57cec5SDimitry Andric 9650b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI); 9660b57cec5SDimitry Andric return true; 9670b57cec5SDimitry Andric } 9680b57cec5SDimitry Andric 9690b57cec5SDimitry Andric /// Return true if the re-scheduling will put the given instruction too close 9700b57cec5SDimitry Andric /// to the defs of its register dependencies. 971e8d8bef9SDimitry Andric bool TwoAddressInstructionPass::isDefTooClose(Register Reg, unsigned Dist, 9720b57cec5SDimitry Andric MachineInstr *MI) { 9730b57cec5SDimitry Andric for (MachineInstr &DefMI : MRI->def_instructions(Reg)) { 9740b57cec5SDimitry Andric if (DefMI.getParent() != MBB || DefMI.isCopy() || DefMI.isCopyLike()) 9750b57cec5SDimitry Andric continue; 9760b57cec5SDimitry Andric if (&DefMI == MI) 9770b57cec5SDimitry Andric return true; // MI is defining something KillMI uses 9780b57cec5SDimitry Andric DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(&DefMI); 9790b57cec5SDimitry Andric if (DDI == DistanceMap.end()) 9800b57cec5SDimitry Andric return true; // Below MI 9810b57cec5SDimitry Andric unsigned DefDist = DDI->second; 9820b57cec5SDimitry Andric assert(Dist > DefDist && "Visited def already?"); 9830b57cec5SDimitry Andric if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist)) 9840b57cec5SDimitry Andric return true; 9850b57cec5SDimitry Andric } 9860b57cec5SDimitry Andric return false; 9870b57cec5SDimitry Andric } 9880b57cec5SDimitry Andric 9890b57cec5SDimitry Andric /// If there is one more local instruction that reads 'Reg' and it kills 'Reg, 9900b57cec5SDimitry Andric /// consider moving the kill instruction above the current two-address 9910b57cec5SDimitry Andric /// instruction in order to eliminate the need for the copy. 992e8d8bef9SDimitry Andric bool TwoAddressInstructionPass::rescheduleKillAboveMI( 993e8d8bef9SDimitry Andric MachineBasicBlock::iterator &mi, MachineBasicBlock::iterator &nmi, 994e8d8bef9SDimitry Andric Register Reg) { 9950b57cec5SDimitry Andric // Bail immediately if we don't have LV or LIS available. We use them to find 9960b57cec5SDimitry Andric // kills efficiently. 9970b57cec5SDimitry Andric if (!LV && !LIS) 9980b57cec5SDimitry Andric return false; 9990b57cec5SDimitry Andric 10000b57cec5SDimitry Andric MachineInstr *MI = &*mi; 10010b57cec5SDimitry Andric DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI); 10020b57cec5SDimitry Andric if (DI == DistanceMap.end()) 10030b57cec5SDimitry Andric // Must be created from unfolded load. Don't waste time trying this. 10040b57cec5SDimitry Andric return false; 10050b57cec5SDimitry Andric 10060b57cec5SDimitry Andric MachineInstr *KillMI = nullptr; 10070b57cec5SDimitry Andric if (LIS) { 10080b57cec5SDimitry Andric LiveInterval &LI = LIS->getInterval(Reg); 10090b57cec5SDimitry Andric assert(LI.end() != LI.begin() && 10100b57cec5SDimitry Andric "Reg should not have empty live interval."); 10110b57cec5SDimitry Andric 10120b57cec5SDimitry Andric SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot(); 10130b57cec5SDimitry Andric LiveInterval::const_iterator I = LI.find(MBBEndIdx); 10140b57cec5SDimitry Andric if (I != LI.end() && I->start < MBBEndIdx) 10150b57cec5SDimitry Andric return false; 10160b57cec5SDimitry Andric 10170b57cec5SDimitry Andric --I; 10180b57cec5SDimitry Andric KillMI = LIS->getInstructionFromIndex(I->end); 10190b57cec5SDimitry Andric } else { 10200b57cec5SDimitry Andric KillMI = LV->getVarInfo(Reg).findKill(MBB); 10210b57cec5SDimitry Andric } 10220b57cec5SDimitry Andric if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike()) 10230b57cec5SDimitry Andric // Don't mess with copies, they may be coalesced later. 10240b57cec5SDimitry Andric return false; 10250b57cec5SDimitry Andric 1026e8d8bef9SDimitry Andric Register DstReg; 10270b57cec5SDimitry Andric if (isTwoAddrUse(*KillMI, Reg, DstReg)) 10280b57cec5SDimitry Andric return false; 10290b57cec5SDimitry Andric 10300b57cec5SDimitry Andric bool SeenStore = true; 10310b57cec5SDimitry Andric if (!KillMI->isSafeToMove(AA, SeenStore)) 10320b57cec5SDimitry Andric return false; 10330b57cec5SDimitry Andric 1034e8d8bef9SDimitry Andric SmallVector<Register, 2> Uses; 1035e8d8bef9SDimitry Andric SmallVector<Register, 2> Kills; 1036e8d8bef9SDimitry Andric SmallVector<Register, 2> Defs; 1037e8d8bef9SDimitry Andric SmallVector<Register, 2> LiveDefs; 10380b57cec5SDimitry Andric for (const MachineOperand &MO : KillMI->operands()) { 10390b57cec5SDimitry Andric if (!MO.isReg()) 10400b57cec5SDimitry Andric continue; 10418bcb0991SDimitry Andric Register MOReg = MO.getReg(); 10420b57cec5SDimitry Andric if (MO.isUse()) { 10430b57cec5SDimitry Andric if (!MOReg) 10440b57cec5SDimitry Andric continue; 10450b57cec5SDimitry Andric if (isDefTooClose(MOReg, DI->second, MI)) 10460b57cec5SDimitry Andric return false; 1047*06c3fb27SDimitry Andric bool isKill = isPlainlyKilled(MO, LIS); 10480b57cec5SDimitry Andric if (MOReg == Reg && !isKill) 10490b57cec5SDimitry Andric return false; 1050e8d8bef9SDimitry Andric Uses.push_back(MOReg); 10510b57cec5SDimitry Andric if (isKill && MOReg != Reg) 1052e8d8bef9SDimitry Andric Kills.push_back(MOReg); 1053e8d8bef9SDimitry Andric } else if (MOReg.isPhysical()) { 1054e8d8bef9SDimitry Andric Defs.push_back(MOReg); 10550b57cec5SDimitry Andric if (!MO.isDead()) 1056e8d8bef9SDimitry Andric LiveDefs.push_back(MOReg); 10570b57cec5SDimitry Andric } 10580b57cec5SDimitry Andric } 10590b57cec5SDimitry Andric 10600b57cec5SDimitry Andric // Check if the reschedule will not break depedencies. 10610b57cec5SDimitry Andric unsigned NumVisited = 0; 10620b57cec5SDimitry Andric for (MachineInstr &OtherMI : 10630b57cec5SDimitry Andric make_range(mi, MachineBasicBlock::iterator(KillMI))) { 1064d409305fSDimitry Andric // Debug or pseudo instructions cannot be counted against the limit. 1065d409305fSDimitry Andric if (OtherMI.isDebugOrPseudoInstr()) 10660b57cec5SDimitry Andric continue; 10670b57cec5SDimitry Andric if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost. 10680b57cec5SDimitry Andric return false; 10690b57cec5SDimitry Andric ++NumVisited; 10700b57cec5SDimitry Andric if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() || 10710b57cec5SDimitry Andric OtherMI.isBranch() || OtherMI.isTerminator()) 10720b57cec5SDimitry Andric // Don't move pass calls, etc. 10730b57cec5SDimitry Andric return false; 1074e8d8bef9SDimitry Andric SmallVector<Register, 2> OtherDefs; 10750b57cec5SDimitry Andric for (const MachineOperand &MO : OtherMI.operands()) { 10760b57cec5SDimitry Andric if (!MO.isReg()) 10770b57cec5SDimitry Andric continue; 10788bcb0991SDimitry Andric Register MOReg = MO.getReg(); 10790b57cec5SDimitry Andric if (!MOReg) 10800b57cec5SDimitry Andric continue; 10810b57cec5SDimitry Andric if (MO.isUse()) { 1082e8d8bef9SDimitry Andric if (regOverlapsSet(Defs, MOReg, TRI)) 10830b57cec5SDimitry Andric // Moving KillMI can clobber the physical register if the def has 10840b57cec5SDimitry Andric // not been seen. 10850b57cec5SDimitry Andric return false; 1086e8d8bef9SDimitry Andric if (regOverlapsSet(Kills, MOReg, TRI)) 10870b57cec5SDimitry Andric // Don't want to extend other live ranges and update kills. 10880b57cec5SDimitry Andric return false; 1089*06c3fb27SDimitry Andric if (&OtherMI != MI && MOReg == Reg && !isPlainlyKilled(MO, LIS)) 10900b57cec5SDimitry Andric // We can't schedule across a use of the register in question. 10910b57cec5SDimitry Andric return false; 10920b57cec5SDimitry Andric } else { 10930b57cec5SDimitry Andric OtherDefs.push_back(MOReg); 10940b57cec5SDimitry Andric } 10950b57cec5SDimitry Andric } 10960b57cec5SDimitry Andric 10970b57cec5SDimitry Andric for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) { 1098e8d8bef9SDimitry Andric Register MOReg = OtherDefs[i]; 1099e8d8bef9SDimitry Andric if (regOverlapsSet(Uses, MOReg, TRI)) 11000b57cec5SDimitry Andric return false; 1101e8d8bef9SDimitry Andric if (MOReg.isPhysical() && regOverlapsSet(LiveDefs, MOReg, TRI)) 11020b57cec5SDimitry Andric return false; 11030b57cec5SDimitry Andric // Physical register def is seen. 1104e8d8bef9SDimitry Andric llvm::erase_value(Defs, MOReg); 11050b57cec5SDimitry Andric } 11060b57cec5SDimitry Andric } 11070b57cec5SDimitry Andric 11080b57cec5SDimitry Andric // Move the old kill above MI, don't forget to move debug info as well. 11090b57cec5SDimitry Andric MachineBasicBlock::iterator InsertPos = mi; 11100b57cec5SDimitry Andric while (InsertPos != MBB->begin() && std::prev(InsertPos)->isDebugInstr()) 11110b57cec5SDimitry Andric --InsertPos; 11120b57cec5SDimitry Andric MachineBasicBlock::iterator From = KillMI; 11130b57cec5SDimitry Andric MachineBasicBlock::iterator To = std::next(From); 11140b57cec5SDimitry Andric while (std::prev(From)->isDebugInstr()) 11150b57cec5SDimitry Andric --From; 11160b57cec5SDimitry Andric MBB->splice(InsertPos, MBB, From, To); 11170b57cec5SDimitry Andric 11180b57cec5SDimitry Andric nmi = std::prev(InsertPos); // Backtrack so we process the moved instr. 11190b57cec5SDimitry Andric DistanceMap.erase(DI); 11200b57cec5SDimitry Andric 11210b57cec5SDimitry Andric // Update live variables 11220b57cec5SDimitry Andric if (LIS) { 11230b57cec5SDimitry Andric LIS->handleMove(*KillMI); 11240b57cec5SDimitry Andric } else { 11250b57cec5SDimitry Andric LV->removeVirtualRegisterKilled(Reg, *KillMI); 11260b57cec5SDimitry Andric LV->addVirtualRegisterKilled(Reg, *MI); 11270b57cec5SDimitry Andric } 11280b57cec5SDimitry Andric 11290b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\trescheduled kill: " << *KillMI); 11300b57cec5SDimitry Andric return true; 11310b57cec5SDimitry Andric } 11320b57cec5SDimitry Andric 11330b57cec5SDimitry Andric /// Tries to commute the operand 'BaseOpIdx' and some other operand in the 11340b57cec5SDimitry Andric /// given machine instruction to improve opportunities for coalescing and 11350b57cec5SDimitry Andric /// elimination of a register to register copy. 11360b57cec5SDimitry Andric /// 11370b57cec5SDimitry Andric /// 'DstOpIdx' specifies the index of MI def operand. 11380b57cec5SDimitry Andric /// 'BaseOpKilled' specifies if the register associated with 'BaseOpIdx' 11390b57cec5SDimitry Andric /// operand is killed by the given instruction. 11400b57cec5SDimitry Andric /// The 'Dist' arguments provides the distance of MI from the start of the 11410b57cec5SDimitry Andric /// current basic block and it is used to determine if it is profitable 11420b57cec5SDimitry Andric /// to commute operands in the instruction. 11430b57cec5SDimitry Andric /// 11440b57cec5SDimitry Andric /// Returns true if the transformation happened. Otherwise, returns false. 11450b57cec5SDimitry Andric bool TwoAddressInstructionPass::tryInstructionCommute(MachineInstr *MI, 11460b57cec5SDimitry Andric unsigned DstOpIdx, 11470b57cec5SDimitry Andric unsigned BaseOpIdx, 11480b57cec5SDimitry Andric bool BaseOpKilled, 11490b57cec5SDimitry Andric unsigned Dist) { 11500b57cec5SDimitry Andric if (!MI->isCommutable()) 11510b57cec5SDimitry Andric return false; 11520b57cec5SDimitry Andric 11530b57cec5SDimitry Andric bool MadeChange = false; 11548bcb0991SDimitry Andric Register DstOpReg = MI->getOperand(DstOpIdx).getReg(); 11558bcb0991SDimitry Andric Register BaseOpReg = MI->getOperand(BaseOpIdx).getReg(); 11560b57cec5SDimitry Andric unsigned OpsNum = MI->getDesc().getNumOperands(); 11570b57cec5SDimitry Andric unsigned OtherOpIdx = MI->getDesc().getNumDefs(); 11580b57cec5SDimitry Andric for (; OtherOpIdx < OpsNum; OtherOpIdx++) { 11590b57cec5SDimitry Andric // The call of findCommutedOpIndices below only checks if BaseOpIdx 11600b57cec5SDimitry Andric // and OtherOpIdx are commutable, it does not really search for 11610b57cec5SDimitry Andric // other commutable operands and does not change the values of passed 11620b57cec5SDimitry Andric // variables. 11630b57cec5SDimitry Andric if (OtherOpIdx == BaseOpIdx || !MI->getOperand(OtherOpIdx).isReg() || 11640b57cec5SDimitry Andric !TII->findCommutedOpIndices(*MI, BaseOpIdx, OtherOpIdx)) 11650b57cec5SDimitry Andric continue; 11660b57cec5SDimitry Andric 11678bcb0991SDimitry Andric Register OtherOpReg = MI->getOperand(OtherOpIdx).getReg(); 11680b57cec5SDimitry Andric bool AggressiveCommute = false; 11690b57cec5SDimitry Andric 11700b57cec5SDimitry Andric // If OtherOp dies but BaseOp does not, swap the OtherOp and BaseOp 11710b57cec5SDimitry Andric // operands. This makes the live ranges of DstOp and OtherOp joinable. 11720b57cec5SDimitry Andric bool OtherOpKilled = isKilled(*MI, OtherOpReg, MRI, TII, LIS, false); 11730b57cec5SDimitry Andric bool DoCommute = !BaseOpKilled && OtherOpKilled; 11740b57cec5SDimitry Andric 11750b57cec5SDimitry Andric if (!DoCommute && 11760b57cec5SDimitry Andric isProfitableToCommute(DstOpReg, BaseOpReg, OtherOpReg, MI, Dist)) { 11770b57cec5SDimitry Andric DoCommute = true; 11780b57cec5SDimitry Andric AggressiveCommute = true; 11790b57cec5SDimitry Andric } 11800b57cec5SDimitry Andric 11810b57cec5SDimitry Andric // If it's profitable to commute, try to do so. 11820b57cec5SDimitry Andric if (DoCommute && commuteInstruction(MI, DstOpIdx, BaseOpIdx, OtherOpIdx, 11830b57cec5SDimitry Andric Dist)) { 11840b57cec5SDimitry Andric MadeChange = true; 11850b57cec5SDimitry Andric ++NumCommuted; 11865ffd83dbSDimitry Andric if (AggressiveCommute) 11870b57cec5SDimitry Andric ++NumAggrCommuted; 11885ffd83dbSDimitry Andric 11890b57cec5SDimitry Andric // There might be more than two commutable operands, update BaseOp and 11900b57cec5SDimitry Andric // continue scanning. 11910b57cec5SDimitry Andric // FIXME: This assumes that the new instruction's operands are in the 11920b57cec5SDimitry Andric // same positions and were simply swapped. 11930b57cec5SDimitry Andric BaseOpReg = OtherOpReg; 11940b57cec5SDimitry Andric BaseOpKilled = OtherOpKilled; 11950b57cec5SDimitry Andric // Resamples OpsNum in case the number of operands was reduced. This 11960b57cec5SDimitry Andric // happens with X86. 11970b57cec5SDimitry Andric OpsNum = MI->getDesc().getNumOperands(); 11980b57cec5SDimitry Andric } 11990b57cec5SDimitry Andric } 12000b57cec5SDimitry Andric return MadeChange; 12010b57cec5SDimitry Andric } 12020b57cec5SDimitry Andric 12030b57cec5SDimitry Andric /// For the case where an instruction has a single pair of tied register 12040b57cec5SDimitry Andric /// operands, attempt some transformations that may either eliminate the tied 12050b57cec5SDimitry Andric /// operands or improve the opportunities for coalescing away the register copy. 12060b57cec5SDimitry Andric /// Returns true if no copy needs to be inserted to untie mi's operands 12070b57cec5SDimitry Andric /// (either because they were untied, or because mi was rescheduled, and will 12080b57cec5SDimitry Andric /// be visited again later). If the shouldOnlyCommute flag is true, only 12090b57cec5SDimitry Andric /// instruction commutation is attempted. 12100b57cec5SDimitry Andric bool TwoAddressInstructionPass:: 12110b57cec5SDimitry Andric tryInstructionTransform(MachineBasicBlock::iterator &mi, 12120b57cec5SDimitry Andric MachineBasicBlock::iterator &nmi, 12130b57cec5SDimitry Andric unsigned SrcIdx, unsigned DstIdx, 1214349cc55cSDimitry Andric unsigned &Dist, bool shouldOnlyCommute) { 12150b57cec5SDimitry Andric if (OptLevel == CodeGenOpt::None) 12160b57cec5SDimitry Andric return false; 12170b57cec5SDimitry Andric 12180b57cec5SDimitry Andric MachineInstr &MI = *mi; 12198bcb0991SDimitry Andric Register regA = MI.getOperand(DstIdx).getReg(); 12208bcb0991SDimitry Andric Register regB = MI.getOperand(SrcIdx).getReg(); 12210b57cec5SDimitry Andric 1222e8d8bef9SDimitry Andric assert(regB.isVirtual() && "cannot make instruction into two-address form"); 12230b57cec5SDimitry Andric bool regBKilled = isKilled(MI, regB, MRI, TII, LIS, true); 12240b57cec5SDimitry Andric 1225e8d8bef9SDimitry Andric if (regA.isVirtual()) 12260b57cec5SDimitry Andric scanUses(regA); 12270b57cec5SDimitry Andric 12280b57cec5SDimitry Andric bool Commuted = tryInstructionCommute(&MI, DstIdx, SrcIdx, regBKilled, Dist); 12290b57cec5SDimitry Andric 12300b57cec5SDimitry Andric // If the instruction is convertible to 3 Addr, instead 1231480093f4SDimitry Andric // of returning try 3 Addr transformation aggressively and 12320b57cec5SDimitry Andric // use this variable to check later. Because it might be better. 12330b57cec5SDimitry Andric // For example, we can just use `leal (%rsi,%rdi), %eax` and `ret` 12340b57cec5SDimitry Andric // instead of the following code. 12350b57cec5SDimitry Andric // addl %esi, %edi 12360b57cec5SDimitry Andric // movl %edi, %eax 12370b57cec5SDimitry Andric // ret 12380b57cec5SDimitry Andric if (Commuted && !MI.isConvertibleTo3Addr()) 12390b57cec5SDimitry Andric return false; 12400b57cec5SDimitry Andric 12410b57cec5SDimitry Andric if (shouldOnlyCommute) 12420b57cec5SDimitry Andric return false; 12430b57cec5SDimitry Andric 12440b57cec5SDimitry Andric // If there is one more use of regB later in the same MBB, consider 12450b57cec5SDimitry Andric // re-schedule this MI below it. 12460b57cec5SDimitry Andric if (!Commuted && EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) { 12470b57cec5SDimitry Andric ++NumReSchedDowns; 12480b57cec5SDimitry Andric return true; 12490b57cec5SDimitry Andric } 12500b57cec5SDimitry Andric 12510b57cec5SDimitry Andric // If we commuted, regB may have changed so we should re-sample it to avoid 12520b57cec5SDimitry Andric // confusing the three address conversion below. 12530b57cec5SDimitry Andric if (Commuted) { 12540b57cec5SDimitry Andric regB = MI.getOperand(SrcIdx).getReg(); 12550b57cec5SDimitry Andric regBKilled = isKilled(MI, regB, MRI, TII, LIS, true); 12560b57cec5SDimitry Andric } 12570b57cec5SDimitry Andric 12580b57cec5SDimitry Andric if (MI.isConvertibleTo3Addr()) { 12590b57cec5SDimitry Andric // This instruction is potentially convertible to a true 12600b57cec5SDimitry Andric // three-address instruction. Check if it is profitable. 12610b57cec5SDimitry Andric if (!regBKilled || isProfitableToConv3Addr(regA, regB)) { 12620b57cec5SDimitry Andric // Try to convert it. 12630b57cec5SDimitry Andric if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) { 12640b57cec5SDimitry Andric ++NumConvertedTo3Addr; 12650b57cec5SDimitry Andric return true; // Done with this instruction. 12660b57cec5SDimitry Andric } 12670b57cec5SDimitry Andric } 12680b57cec5SDimitry Andric } 12690b57cec5SDimitry Andric 12700b57cec5SDimitry Andric // Return if it is commuted but 3 addr conversion is failed. 12710b57cec5SDimitry Andric if (Commuted) 12720b57cec5SDimitry Andric return false; 12730b57cec5SDimitry Andric 12740b57cec5SDimitry Andric // If there is one more use of regB later in the same MBB, consider 12750b57cec5SDimitry Andric // re-schedule it before this MI if it's legal. 12760b57cec5SDimitry Andric if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) { 12770b57cec5SDimitry Andric ++NumReSchedUps; 12780b57cec5SDimitry Andric return true; 12790b57cec5SDimitry Andric } 12800b57cec5SDimitry Andric 12810b57cec5SDimitry Andric // If this is an instruction with a load folded into it, try unfolding 12820b57cec5SDimitry Andric // the load, e.g. avoid this: 12830b57cec5SDimitry Andric // movq %rdx, %rcx 12840b57cec5SDimitry Andric // addq (%rax), %rcx 12850b57cec5SDimitry Andric // in favor of this: 12860b57cec5SDimitry Andric // movq (%rax), %rcx 12870b57cec5SDimitry Andric // addq %rdx, %rcx 12880b57cec5SDimitry Andric // because it's preferable to schedule a load than a register copy. 12890b57cec5SDimitry Andric if (MI.mayLoad() && !regBKilled) { 12900b57cec5SDimitry Andric // Determine if a load can be unfolded. 12910b57cec5SDimitry Andric unsigned LoadRegIndex; 12920b57cec5SDimitry Andric unsigned NewOpc = 12930b57cec5SDimitry Andric TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), 12940b57cec5SDimitry Andric /*UnfoldLoad=*/true, 12950b57cec5SDimitry Andric /*UnfoldStore=*/false, 12960b57cec5SDimitry Andric &LoadRegIndex); 12970b57cec5SDimitry Andric if (NewOpc != 0) { 12980b57cec5SDimitry Andric const MCInstrDesc &UnfoldMCID = TII->get(NewOpc); 12990b57cec5SDimitry Andric if (UnfoldMCID.getNumDefs() == 1) { 13000b57cec5SDimitry Andric // Unfold the load. 13010b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: UNFOLDING: " << MI); 13020b57cec5SDimitry Andric const TargetRegisterClass *RC = 13030b57cec5SDimitry Andric TRI->getAllocatableClass( 13040b57cec5SDimitry Andric TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF)); 13058bcb0991SDimitry Andric Register Reg = MRI->createVirtualRegister(RC); 13060b57cec5SDimitry Andric SmallVector<MachineInstr *, 2> NewMIs; 13070b57cec5SDimitry Andric if (!TII->unfoldMemoryOperand(*MF, MI, Reg, 13080b57cec5SDimitry Andric /*UnfoldLoad=*/true, 13090b57cec5SDimitry Andric /*UnfoldStore=*/false, NewMIs)) { 13100b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n"); 13110b57cec5SDimitry Andric return false; 13120b57cec5SDimitry Andric } 13130b57cec5SDimitry Andric assert(NewMIs.size() == 2 && 13140b57cec5SDimitry Andric "Unfolded a load into multiple instructions!"); 13150b57cec5SDimitry Andric // The load was previously folded, so this is the only use. 13160b57cec5SDimitry Andric NewMIs[1]->addRegisterKilled(Reg, TRI); 13170b57cec5SDimitry Andric 13180b57cec5SDimitry Andric // Tentatively insert the instructions into the block so that they 13190b57cec5SDimitry Andric // look "normal" to the transformation logic. 13200b57cec5SDimitry Andric MBB->insert(mi, NewMIs[0]); 13210b57cec5SDimitry Andric MBB->insert(mi, NewMIs[1]); 1322349cc55cSDimitry Andric DistanceMap.insert(std::make_pair(NewMIs[0], Dist++)); 1323349cc55cSDimitry Andric DistanceMap.insert(std::make_pair(NewMIs[1], Dist)); 13240b57cec5SDimitry Andric 13250b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0] 13260b57cec5SDimitry Andric << "2addr: NEW INST: " << *NewMIs[1]); 13270b57cec5SDimitry Andric 13280b57cec5SDimitry Andric // Transform the instruction, now that it no longer has a load. 13290b57cec5SDimitry Andric unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA); 13300b57cec5SDimitry Andric unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB); 13310b57cec5SDimitry Andric MachineBasicBlock::iterator NewMI = NewMIs[1]; 13320b57cec5SDimitry Andric bool TransformResult = 13330b57cec5SDimitry Andric tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true); 13340b57cec5SDimitry Andric (void)TransformResult; 13350b57cec5SDimitry Andric assert(!TransformResult && 13360b57cec5SDimitry Andric "tryInstructionTransform() should return false."); 13370b57cec5SDimitry Andric if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) { 13380b57cec5SDimitry Andric // Success, or at least we made an improvement. Keep the unfolded 13390b57cec5SDimitry Andric // instructions and discard the original. 13400b57cec5SDimitry Andric if (LV) { 13414824e7fdSDimitry Andric for (const MachineOperand &MO : MI.operands()) { 1342e8d8bef9SDimitry Andric if (MO.isReg() && MO.getReg().isVirtual()) { 13430b57cec5SDimitry Andric if (MO.isUse()) { 13440b57cec5SDimitry Andric if (MO.isKill()) { 13450b57cec5SDimitry Andric if (NewMIs[0]->killsRegister(MO.getReg())) 13460b57cec5SDimitry Andric LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[0]); 13470b57cec5SDimitry Andric else { 13480b57cec5SDimitry Andric assert(NewMIs[1]->killsRegister(MO.getReg()) && 13490b57cec5SDimitry Andric "Kill missing after load unfold!"); 13500b57cec5SDimitry Andric LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[1]); 13510b57cec5SDimitry Andric } 13520b57cec5SDimitry Andric } 13530b57cec5SDimitry Andric } else if (LV->removeVirtualRegisterDead(MO.getReg(), MI)) { 13540b57cec5SDimitry Andric if (NewMIs[1]->registerDefIsDead(MO.getReg())) 13550b57cec5SDimitry Andric LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[1]); 13560b57cec5SDimitry Andric else { 13570b57cec5SDimitry Andric assert(NewMIs[0]->registerDefIsDead(MO.getReg()) && 13580b57cec5SDimitry Andric "Dead flag missing after load unfold!"); 13590b57cec5SDimitry Andric LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[0]); 13600b57cec5SDimitry Andric } 13610b57cec5SDimitry Andric } 13620b57cec5SDimitry Andric } 13630b57cec5SDimitry Andric } 13640b57cec5SDimitry Andric LV->addVirtualRegisterKilled(Reg, *NewMIs[1]); 13650b57cec5SDimitry Andric } 13660b57cec5SDimitry Andric 13675ffd83dbSDimitry Andric SmallVector<Register, 4> OrigRegs; 13680b57cec5SDimitry Andric if (LIS) { 13690b57cec5SDimitry Andric for (const MachineOperand &MO : MI.operands()) { 13700b57cec5SDimitry Andric if (MO.isReg()) 13710b57cec5SDimitry Andric OrigRegs.push_back(MO.getReg()); 13720b57cec5SDimitry Andric } 1373349cc55cSDimitry Andric 1374349cc55cSDimitry Andric LIS->RemoveMachineInstrFromMaps(MI); 13750b57cec5SDimitry Andric } 13760b57cec5SDimitry Andric 13770b57cec5SDimitry Andric MI.eraseFromParent(); 1378349cc55cSDimitry Andric DistanceMap.erase(&MI); 13790b57cec5SDimitry Andric 13800b57cec5SDimitry Andric // Update LiveIntervals. 13810b57cec5SDimitry Andric if (LIS) { 13820b57cec5SDimitry Andric MachineBasicBlock::iterator Begin(NewMIs[0]); 13830b57cec5SDimitry Andric MachineBasicBlock::iterator End(NewMIs[1]); 13840b57cec5SDimitry Andric LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs); 13850b57cec5SDimitry Andric } 13860b57cec5SDimitry Andric 13870b57cec5SDimitry Andric mi = NewMIs[1]; 13880b57cec5SDimitry Andric } else { 13890b57cec5SDimitry Andric // Transforming didn't eliminate the tie and didn't lead to an 13900b57cec5SDimitry Andric // improvement. Clean up the unfolded instructions and keep the 13910b57cec5SDimitry Andric // original. 13920b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n"); 13930b57cec5SDimitry Andric NewMIs[0]->eraseFromParent(); 13940b57cec5SDimitry Andric NewMIs[1]->eraseFromParent(); 1395349cc55cSDimitry Andric DistanceMap.erase(NewMIs[0]); 1396349cc55cSDimitry Andric DistanceMap.erase(NewMIs[1]); 1397349cc55cSDimitry Andric Dist--; 13980b57cec5SDimitry Andric } 13990b57cec5SDimitry Andric } 14000b57cec5SDimitry Andric } 14010b57cec5SDimitry Andric } 14020b57cec5SDimitry Andric 14030b57cec5SDimitry Andric return false; 14040b57cec5SDimitry Andric } 14050b57cec5SDimitry Andric 14060b57cec5SDimitry Andric // Collect tied operands of MI that need to be handled. 14070b57cec5SDimitry Andric // Rewrite trivial cases immediately. 14080b57cec5SDimitry Andric // Return true if any tied operands where found, including the trivial ones. 14090b57cec5SDimitry Andric bool TwoAddressInstructionPass:: 14100b57cec5SDimitry Andric collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) { 14110b57cec5SDimitry Andric bool AnyOps = false; 14120b57cec5SDimitry Andric unsigned NumOps = MI->getNumOperands(); 14130b57cec5SDimitry Andric 14140b57cec5SDimitry Andric for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) { 14150b57cec5SDimitry Andric unsigned DstIdx = 0; 14160b57cec5SDimitry Andric if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx)) 14170b57cec5SDimitry Andric continue; 14180b57cec5SDimitry Andric AnyOps = true; 14190b57cec5SDimitry Andric MachineOperand &SrcMO = MI->getOperand(SrcIdx); 14200b57cec5SDimitry Andric MachineOperand &DstMO = MI->getOperand(DstIdx); 14218bcb0991SDimitry Andric Register SrcReg = SrcMO.getReg(); 14228bcb0991SDimitry Andric Register DstReg = DstMO.getReg(); 14230b57cec5SDimitry Andric // Tied constraint already satisfied? 14240b57cec5SDimitry Andric if (SrcReg == DstReg) 14250b57cec5SDimitry Andric continue; 14260b57cec5SDimitry Andric 14270b57cec5SDimitry Andric assert(SrcReg && SrcMO.isUse() && "two address instruction invalid"); 14280b57cec5SDimitry Andric 14290b57cec5SDimitry Andric // Deal with undef uses immediately - simply rewrite the src operand. 14300b57cec5SDimitry Andric if (SrcMO.isUndef() && !DstMO.getSubReg()) { 14310b57cec5SDimitry Andric // Constrain the DstReg register class if required. 1432349cc55cSDimitry Andric if (DstReg.isVirtual()) { 1433349cc55cSDimitry Andric const TargetRegisterClass *RC = MRI->getRegClass(SrcReg); 14340b57cec5SDimitry Andric MRI->constrainRegClass(DstReg, RC); 1435349cc55cSDimitry Andric } 14360b57cec5SDimitry Andric SrcMO.setReg(DstReg); 14370b57cec5SDimitry Andric SrcMO.setSubReg(0); 14380b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI); 14390b57cec5SDimitry Andric continue; 14400b57cec5SDimitry Andric } 14410b57cec5SDimitry Andric TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx)); 14420b57cec5SDimitry Andric } 14430b57cec5SDimitry Andric return AnyOps; 14440b57cec5SDimitry Andric } 14450b57cec5SDimitry Andric 14460b57cec5SDimitry Andric // Process a list of tied MI operands that all use the same source register. 14470b57cec5SDimitry Andric // The tied pairs are of the form (SrcIdx, DstIdx). 14480b57cec5SDimitry Andric void 14490b57cec5SDimitry Andric TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI, 14500b57cec5SDimitry Andric TiedPairList &TiedPairs, 14510b57cec5SDimitry Andric unsigned &Dist) { 1452fcaf7f86SDimitry Andric bool IsEarlyClobber = llvm::any_of(TiedPairs, [MI](auto const &TP) { 1453fe6060f1SDimitry Andric return MI->getOperand(TP.second).isEarlyClobber(); 1454fcaf7f86SDimitry Andric }); 14550b57cec5SDimitry Andric 14560b57cec5SDimitry Andric bool RemovedKillFlag = false; 14570b57cec5SDimitry Andric bool AllUsesCopied = true; 14580b57cec5SDimitry Andric unsigned LastCopiedReg = 0; 14590b57cec5SDimitry Andric SlotIndex LastCopyIdx; 1460e8d8bef9SDimitry Andric Register RegB = 0; 14610b57cec5SDimitry Andric unsigned SubRegB = 0; 1462fe6060f1SDimitry Andric for (auto &TP : TiedPairs) { 1463fe6060f1SDimitry Andric unsigned SrcIdx = TP.first; 1464fe6060f1SDimitry Andric unsigned DstIdx = TP.second; 14650b57cec5SDimitry Andric 14660b57cec5SDimitry Andric const MachineOperand &DstMO = MI->getOperand(DstIdx); 14678bcb0991SDimitry Andric Register RegA = DstMO.getReg(); 14680b57cec5SDimitry Andric 14690b57cec5SDimitry Andric // Grab RegB from the instruction because it may have changed if the 14700b57cec5SDimitry Andric // instruction was commuted. 14710b57cec5SDimitry Andric RegB = MI->getOperand(SrcIdx).getReg(); 14720b57cec5SDimitry Andric SubRegB = MI->getOperand(SrcIdx).getSubReg(); 14730b57cec5SDimitry Andric 14740b57cec5SDimitry Andric if (RegA == RegB) { 14750b57cec5SDimitry Andric // The register is tied to multiple destinations (or else we would 14760b57cec5SDimitry Andric // not have continued this far), but this use of the register 14770b57cec5SDimitry Andric // already matches the tied destination. Leave it. 14780b57cec5SDimitry Andric AllUsesCopied = false; 14790b57cec5SDimitry Andric continue; 14800b57cec5SDimitry Andric } 14810b57cec5SDimitry Andric LastCopiedReg = RegA; 14820b57cec5SDimitry Andric 1483e8d8bef9SDimitry Andric assert(RegB.isVirtual() && "cannot make instruction into two-address form"); 14840b57cec5SDimitry Andric 14850b57cec5SDimitry Andric #ifndef NDEBUG 14860b57cec5SDimitry Andric // First, verify that we don't have a use of "a" in the instruction 14870b57cec5SDimitry Andric // (a = b + a for example) because our transformation will not 14880b57cec5SDimitry Andric // work. This should never occur because we are in SSA form. 14890b57cec5SDimitry Andric for (unsigned i = 0; i != MI->getNumOperands(); ++i) 14900b57cec5SDimitry Andric assert(i == DstIdx || 14910b57cec5SDimitry Andric !MI->getOperand(i).isReg() || 14920b57cec5SDimitry Andric MI->getOperand(i).getReg() != RegA); 14930b57cec5SDimitry Andric #endif 14940b57cec5SDimitry Andric 14950b57cec5SDimitry Andric // Emit a copy. 14960b57cec5SDimitry Andric MachineInstrBuilder MIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), 14970b57cec5SDimitry Andric TII->get(TargetOpcode::COPY), RegA); 14980b57cec5SDimitry Andric // If this operand is folding a truncation, the truncation now moves to the 14990b57cec5SDimitry Andric // copy so that the register classes remain valid for the operands. 15000b57cec5SDimitry Andric MIB.addReg(RegB, 0, SubRegB); 15010b57cec5SDimitry Andric const TargetRegisterClass *RC = MRI->getRegClass(RegB); 15020b57cec5SDimitry Andric if (SubRegB) { 1503e8d8bef9SDimitry Andric if (RegA.isVirtual()) { 15040b57cec5SDimitry Andric assert(TRI->getMatchingSuperRegClass(RC, MRI->getRegClass(RegA), 15050b57cec5SDimitry Andric SubRegB) && 15060b57cec5SDimitry Andric "tied subregister must be a truncation"); 15070b57cec5SDimitry Andric // The superreg class will not be used to constrain the subreg class. 15080b57cec5SDimitry Andric RC = nullptr; 15098bcb0991SDimitry Andric } else { 15100b57cec5SDimitry Andric assert(TRI->getMatchingSuperReg(RegA, SubRegB, MRI->getRegClass(RegB)) 15110b57cec5SDimitry Andric && "tied subregister must be a truncation"); 15120b57cec5SDimitry Andric } 15130b57cec5SDimitry Andric } 15140b57cec5SDimitry Andric 15150b57cec5SDimitry Andric // Update DistanceMap. 15160b57cec5SDimitry Andric MachineBasicBlock::iterator PrevMI = MI; 15170b57cec5SDimitry Andric --PrevMI; 15180b57cec5SDimitry Andric DistanceMap.insert(std::make_pair(&*PrevMI, Dist)); 15190b57cec5SDimitry Andric DistanceMap[MI] = ++Dist; 15200b57cec5SDimitry Andric 15210b57cec5SDimitry Andric if (LIS) { 15220b57cec5SDimitry Andric LastCopyIdx = LIS->InsertMachineInstrInMaps(*PrevMI).getRegSlot(); 15230b57cec5SDimitry Andric 1524349cc55cSDimitry Andric SlotIndex endIdx = 1525349cc55cSDimitry Andric LIS->getInstructionIndex(*MI).getRegSlot(IsEarlyClobber); 1526e8d8bef9SDimitry Andric if (RegA.isVirtual()) { 15270b57cec5SDimitry Andric LiveInterval &LI = LIS->getInterval(RegA); 15280b57cec5SDimitry Andric VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator()); 1529349cc55cSDimitry Andric LI.addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI)); 1530349cc55cSDimitry Andric for (auto &S : LI.subranges()) { 1531349cc55cSDimitry Andric VNI = S.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator()); 1532349cc55cSDimitry Andric S.addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI)); 1533349cc55cSDimitry Andric } 1534349cc55cSDimitry Andric } else { 1535*06c3fb27SDimitry Andric for (MCRegUnit Unit : TRI->regunits(RegA)) { 1536*06c3fb27SDimitry Andric if (LiveRange *LR = LIS->getCachedRegUnit(Unit)) { 1537349cc55cSDimitry Andric VNInfo *VNI = 1538349cc55cSDimitry Andric LR->getNextValue(LastCopyIdx, LIS->getVNInfoAllocator()); 1539349cc55cSDimitry Andric LR->addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI)); 1540349cc55cSDimitry Andric } 1541349cc55cSDimitry Andric } 15420b57cec5SDimitry Andric } 15430b57cec5SDimitry Andric } 15440b57cec5SDimitry Andric 15450b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\t\tprepend:\t" << *MIB); 15460b57cec5SDimitry Andric 15470b57cec5SDimitry Andric MachineOperand &MO = MI->getOperand(SrcIdx); 15480b57cec5SDimitry Andric assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() && 15490b57cec5SDimitry Andric "inconsistent operand info for 2-reg pass"); 15500b57cec5SDimitry Andric if (MO.isKill()) { 15510b57cec5SDimitry Andric MO.setIsKill(false); 15520b57cec5SDimitry Andric RemovedKillFlag = true; 15530b57cec5SDimitry Andric } 15540b57cec5SDimitry Andric 15550b57cec5SDimitry Andric // Make sure regA is a legal regclass for the SrcIdx operand. 1556e8d8bef9SDimitry Andric if (RegA.isVirtual() && RegB.isVirtual()) 15570b57cec5SDimitry Andric MRI->constrainRegClass(RegA, RC); 15580b57cec5SDimitry Andric MO.setReg(RegA); 15590b57cec5SDimitry Andric // The getMatchingSuper asserts guarantee that the register class projected 15600b57cec5SDimitry Andric // by SubRegB is compatible with RegA with no subregister. So regardless of 15610b57cec5SDimitry Andric // whether the dest oper writes a subreg, the source oper should not. 15620b57cec5SDimitry Andric MO.setSubReg(0); 15630b57cec5SDimitry Andric } 15640b57cec5SDimitry Andric 15650b57cec5SDimitry Andric if (AllUsesCopied) { 1566349cc55cSDimitry Andric LaneBitmask RemainingUses = LaneBitmask::getNone(); 15670b57cec5SDimitry Andric // Replace other (un-tied) uses of regB with LastCopiedReg. 1568*06c3fb27SDimitry Andric for (MachineOperand &MO : MI->all_uses()) { 1569*06c3fb27SDimitry Andric if (MO.getReg() == RegB) { 1570349cc55cSDimitry Andric if (MO.getSubReg() == SubRegB && !IsEarlyClobber) { 15710b57cec5SDimitry Andric if (MO.isKill()) { 15720b57cec5SDimitry Andric MO.setIsKill(false); 15730b57cec5SDimitry Andric RemovedKillFlag = true; 15740b57cec5SDimitry Andric } 15750b57cec5SDimitry Andric MO.setReg(LastCopiedReg); 15760b57cec5SDimitry Andric MO.setSubReg(0); 15770b57cec5SDimitry Andric } else { 1578349cc55cSDimitry Andric RemainingUses |= TRI->getSubRegIndexLaneMask(MO.getSubReg()); 15790b57cec5SDimitry Andric } 15800b57cec5SDimitry Andric } 15810b57cec5SDimitry Andric } 15820b57cec5SDimitry Andric 15830b57cec5SDimitry Andric // Update live variables for regB. 1584349cc55cSDimitry Andric if (RemovedKillFlag && RemainingUses.none() && LV && 1585349cc55cSDimitry Andric LV->getVarInfo(RegB).removeKill(*MI)) { 15860b57cec5SDimitry Andric MachineBasicBlock::iterator PrevMI = MI; 15870b57cec5SDimitry Andric --PrevMI; 15880b57cec5SDimitry Andric LV->addVirtualRegisterKilled(RegB, *PrevMI); 15890b57cec5SDimitry Andric } 15900b57cec5SDimitry Andric 1591349cc55cSDimitry Andric if (RemovedKillFlag && RemainingUses.none()) 1592349cc55cSDimitry Andric SrcRegMap[LastCopiedReg] = RegB; 1593349cc55cSDimitry Andric 15940b57cec5SDimitry Andric // Update LiveIntervals. 15950b57cec5SDimitry Andric if (LIS) { 1596349cc55cSDimitry Andric SlotIndex UseIdx = LIS->getInstructionIndex(*MI); 1597349cc55cSDimitry Andric auto Shrink = [=](LiveRange &LR, LaneBitmask LaneMask) { 1598349cc55cSDimitry Andric LiveRange::Segment *S = LR.getSegmentContaining(LastCopyIdx); 1599349cc55cSDimitry Andric if (!S) 1600349cc55cSDimitry Andric return true; 1601349cc55cSDimitry Andric if ((LaneMask & RemainingUses).any()) 1602349cc55cSDimitry Andric return false; 1603349cc55cSDimitry Andric if (S->end.getBaseIndex() != UseIdx) 1604349cc55cSDimitry Andric return false; 1605349cc55cSDimitry Andric S->end = LastCopyIdx; 1606349cc55cSDimitry Andric return true; 1607349cc55cSDimitry Andric }; 16080b57cec5SDimitry Andric 1609349cc55cSDimitry Andric LiveInterval &LI = LIS->getInterval(RegB); 1610349cc55cSDimitry Andric bool ShrinkLI = true; 1611349cc55cSDimitry Andric for (auto &S : LI.subranges()) 1612349cc55cSDimitry Andric ShrinkLI &= Shrink(S, S.LaneMask); 1613349cc55cSDimitry Andric if (ShrinkLI) 1614349cc55cSDimitry Andric Shrink(LI, LaneBitmask::getAll()); 16150b57cec5SDimitry Andric } 16160b57cec5SDimitry Andric } else if (RemovedKillFlag) { 16170b57cec5SDimitry Andric // Some tied uses of regB matched their destination registers, so 16180b57cec5SDimitry Andric // regB is still used in this instruction, but a kill flag was 16190b57cec5SDimitry Andric // removed from a different tied use of regB, so now we need to add 16200b57cec5SDimitry Andric // a kill flag to one of the remaining uses of regB. 1621*06c3fb27SDimitry Andric for (MachineOperand &MO : MI->all_uses()) { 1622*06c3fb27SDimitry Andric if (MO.getReg() == RegB) { 16230b57cec5SDimitry Andric MO.setIsKill(true); 16240b57cec5SDimitry Andric break; 16250b57cec5SDimitry Andric } 16260b57cec5SDimitry Andric } 16270b57cec5SDimitry Andric } 16280b57cec5SDimitry Andric } 16290b57cec5SDimitry Andric 163081ad6265SDimitry Andric // For every tied operand pair this function transforms statepoint from 163181ad6265SDimitry Andric // RegA = STATEPOINT ... RegB(tied-def N) 163281ad6265SDimitry Andric // to 163381ad6265SDimitry Andric // RegB = STATEPOINT ... RegB(tied-def N) 163481ad6265SDimitry Andric // and replaces all uses of RegA with RegB. 163581ad6265SDimitry Andric // No extra COPY instruction is necessary because tied use is killed at 163681ad6265SDimitry Andric // STATEPOINT. 163781ad6265SDimitry Andric bool TwoAddressInstructionPass::processStatepoint( 163881ad6265SDimitry Andric MachineInstr *MI, TiedOperandMap &TiedOperands) { 163981ad6265SDimitry Andric 164081ad6265SDimitry Andric bool NeedCopy = false; 164181ad6265SDimitry Andric for (auto &TO : TiedOperands) { 164281ad6265SDimitry Andric Register RegB = TO.first; 164381ad6265SDimitry Andric if (TO.second.size() != 1) { 164481ad6265SDimitry Andric NeedCopy = true; 164581ad6265SDimitry Andric continue; 164681ad6265SDimitry Andric } 164781ad6265SDimitry Andric 164881ad6265SDimitry Andric unsigned SrcIdx = TO.second[0].first; 164981ad6265SDimitry Andric unsigned DstIdx = TO.second[0].second; 165081ad6265SDimitry Andric 165181ad6265SDimitry Andric MachineOperand &DstMO = MI->getOperand(DstIdx); 165281ad6265SDimitry Andric Register RegA = DstMO.getReg(); 165381ad6265SDimitry Andric 165481ad6265SDimitry Andric assert(RegB == MI->getOperand(SrcIdx).getReg()); 165581ad6265SDimitry Andric 165681ad6265SDimitry Andric if (RegA == RegB) 165781ad6265SDimitry Andric continue; 165881ad6265SDimitry Andric 1659bdd1243dSDimitry Andric // CodeGenPrepare can sink pointer compare past statepoint, which 1660bdd1243dSDimitry Andric // breaks assumption that statepoint kills tied-use register when 1661bdd1243dSDimitry Andric // in SSA form (see note in IR/SafepointIRVerifier.cpp). Fall back 1662bdd1243dSDimitry Andric // to generic tied register handling to avoid assertion failures. 1663bdd1243dSDimitry Andric // TODO: Recompute LIS/LV information for new range here. 1664bdd1243dSDimitry Andric if (LIS) { 1665bdd1243dSDimitry Andric const auto &UseLI = LIS->getInterval(RegB); 1666bdd1243dSDimitry Andric const auto &DefLI = LIS->getInterval(RegA); 1667bdd1243dSDimitry Andric if (DefLI.overlaps(UseLI)) { 1668bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "LIS: " << printReg(RegB, TRI, 0) 1669bdd1243dSDimitry Andric << " UseLI overlaps with DefLI\n"); 1670bdd1243dSDimitry Andric NeedCopy = true; 1671bdd1243dSDimitry Andric continue; 1672bdd1243dSDimitry Andric } 1673bdd1243dSDimitry Andric } else if (LV && LV->getVarInfo(RegB).findKill(MI->getParent()) != MI) { 1674bdd1243dSDimitry Andric // Note that MachineOperand::isKill does not work here, because it 1675bdd1243dSDimitry Andric // is set only on first register use in instruction and for statepoint 1676bdd1243dSDimitry Andric // tied-use register will usually be found in preceeding deopt bundle. 1677bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "LV: " << printReg(RegB, TRI, 0) 1678bdd1243dSDimitry Andric << " not killed by statepoint\n"); 1679bdd1243dSDimitry Andric NeedCopy = true; 1680bdd1243dSDimitry Andric continue; 1681bdd1243dSDimitry Andric } 1682bdd1243dSDimitry Andric 1683bdd1243dSDimitry Andric if (!MRI->constrainRegClass(RegB, MRI->getRegClass(RegA))) { 1684bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "MRI: couldn't constrain" << printReg(RegB, TRI, 0) 1685bdd1243dSDimitry Andric << " to register class of " << printReg(RegA, TRI, 0) 1686bdd1243dSDimitry Andric << '\n'); 1687bdd1243dSDimitry Andric NeedCopy = true; 1688bdd1243dSDimitry Andric continue; 1689bdd1243dSDimitry Andric } 169081ad6265SDimitry Andric MRI->replaceRegWith(RegA, RegB); 169181ad6265SDimitry Andric 169281ad6265SDimitry Andric if (LIS) { 169381ad6265SDimitry Andric VNInfo::Allocator &A = LIS->getVNInfoAllocator(); 169481ad6265SDimitry Andric LiveInterval &LI = LIS->getInterval(RegB); 1695bdd1243dSDimitry Andric LiveInterval &Other = LIS->getInterval(RegA); 1696bdd1243dSDimitry Andric SmallVector<VNInfo *> NewVNIs; 1697bdd1243dSDimitry Andric for (const VNInfo *VNI : Other.valnos) { 1698bdd1243dSDimitry Andric assert(VNI->id == NewVNIs.size() && "assumed"); 1699bdd1243dSDimitry Andric NewVNIs.push_back(LI.createValueCopy(VNI, A)); 1700bdd1243dSDimitry Andric } 1701bdd1243dSDimitry Andric for (auto &S : Other) { 1702bdd1243dSDimitry Andric VNInfo *VNI = NewVNIs[S.valno->id]; 170381ad6265SDimitry Andric LiveRange::Segment NewSeg(S.start, S.end, VNI); 170481ad6265SDimitry Andric LI.addSegment(NewSeg); 170581ad6265SDimitry Andric } 170681ad6265SDimitry Andric LIS->removeInterval(RegA); 170781ad6265SDimitry Andric } 170881ad6265SDimitry Andric 170981ad6265SDimitry Andric if (LV) { 171081ad6265SDimitry Andric if (MI->getOperand(SrcIdx).isKill()) 171181ad6265SDimitry Andric LV->removeVirtualRegisterKilled(RegB, *MI); 171281ad6265SDimitry Andric LiveVariables::VarInfo &SrcInfo = LV->getVarInfo(RegB); 171381ad6265SDimitry Andric LiveVariables::VarInfo &DstInfo = LV->getVarInfo(RegA); 171481ad6265SDimitry Andric SrcInfo.AliveBlocks |= DstInfo.AliveBlocks; 1715bdd1243dSDimitry Andric DstInfo.AliveBlocks.clear(); 171681ad6265SDimitry Andric for (auto *KillMI : DstInfo.Kills) 171781ad6265SDimitry Andric LV->addVirtualRegisterKilled(RegB, *KillMI, false); 171881ad6265SDimitry Andric } 171981ad6265SDimitry Andric } 172081ad6265SDimitry Andric return !NeedCopy; 172181ad6265SDimitry Andric } 172281ad6265SDimitry Andric 17230b57cec5SDimitry Andric /// Reduce two-address instructions to two operands. 17240b57cec5SDimitry Andric bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) { 17250b57cec5SDimitry Andric MF = &Func; 17260b57cec5SDimitry Andric const TargetMachine &TM = MF->getTarget(); 17270b57cec5SDimitry Andric MRI = &MF->getRegInfo(); 17280b57cec5SDimitry Andric TII = MF->getSubtarget().getInstrInfo(); 17290b57cec5SDimitry Andric TRI = MF->getSubtarget().getRegisterInfo(); 17300b57cec5SDimitry Andric InstrItins = MF->getSubtarget().getInstrItineraryData(); 17310b57cec5SDimitry Andric LV = getAnalysisIfAvailable<LiveVariables>(); 17320b57cec5SDimitry Andric LIS = getAnalysisIfAvailable<LiveIntervals>(); 17330b57cec5SDimitry Andric if (auto *AAPass = getAnalysisIfAvailable<AAResultsWrapperPass>()) 17340b57cec5SDimitry Andric AA = &AAPass->getAAResults(); 17350b57cec5SDimitry Andric else 17360b57cec5SDimitry Andric AA = nullptr; 17370b57cec5SDimitry Andric OptLevel = TM.getOptLevel(); 17380b57cec5SDimitry Andric // Disable optimizations if requested. We cannot skip the whole pass as some 17390b57cec5SDimitry Andric // fixups are necessary for correctness. 17400b57cec5SDimitry Andric if (skipFunction(Func.getFunction())) 17410b57cec5SDimitry Andric OptLevel = CodeGenOpt::None; 17420b57cec5SDimitry Andric 17430b57cec5SDimitry Andric bool MadeChange = false; 17440b57cec5SDimitry Andric 17450b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n"); 17460b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "********** Function: " << MF->getName() << '\n'); 17470b57cec5SDimitry Andric 17480b57cec5SDimitry Andric // This pass takes the function out of SSA form. 17490b57cec5SDimitry Andric MRI->leaveSSA(); 17500b57cec5SDimitry Andric 17515ffd83dbSDimitry Andric // This pass will rewrite the tied-def to meet the RegConstraint. 17525ffd83dbSDimitry Andric MF->getProperties() 17535ffd83dbSDimitry Andric .set(MachineFunctionProperties::Property::TiedOpsRewritten); 17545ffd83dbSDimitry Andric 17550b57cec5SDimitry Andric TiedOperandMap TiedOperands; 1756fe6060f1SDimitry Andric for (MachineBasicBlock &MBBI : *MF) { 1757fe6060f1SDimitry Andric MBB = &MBBI; 17580b57cec5SDimitry Andric unsigned Dist = 0; 17590b57cec5SDimitry Andric DistanceMap.clear(); 17600b57cec5SDimitry Andric SrcRegMap.clear(); 17610b57cec5SDimitry Andric DstRegMap.clear(); 17620b57cec5SDimitry Andric Processed.clear(); 17630b57cec5SDimitry Andric for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end(); 17640b57cec5SDimitry Andric mi != me; ) { 17650b57cec5SDimitry Andric MachineBasicBlock::iterator nmi = std::next(mi); 1766590d96feSDimitry Andric // Skip debug instructions. 1767590d96feSDimitry Andric if (mi->isDebugInstr()) { 17680b57cec5SDimitry Andric mi = nmi; 17690b57cec5SDimitry Andric continue; 17700b57cec5SDimitry Andric } 17710b57cec5SDimitry Andric 17720b57cec5SDimitry Andric // Expand REG_SEQUENCE instructions. This will position mi at the first 17730b57cec5SDimitry Andric // expanded instruction. 17740b57cec5SDimitry Andric if (mi->isRegSequence()) 17750b57cec5SDimitry Andric eliminateRegSequence(mi); 17760b57cec5SDimitry Andric 17770b57cec5SDimitry Andric DistanceMap.insert(std::make_pair(&*mi, ++Dist)); 17780b57cec5SDimitry Andric 17790b57cec5SDimitry Andric processCopy(&*mi); 17800b57cec5SDimitry Andric 17810b57cec5SDimitry Andric // First scan through all the tied register uses in this instruction 17820b57cec5SDimitry Andric // and record a list of pairs of tied operands for each register. 17830b57cec5SDimitry Andric if (!collectTiedOperands(&*mi, TiedOperands)) { 1784349cc55cSDimitry Andric removeClobberedSrcRegMap(&*mi); 17850b57cec5SDimitry Andric mi = nmi; 17860b57cec5SDimitry Andric continue; 17870b57cec5SDimitry Andric } 17880b57cec5SDimitry Andric 17890b57cec5SDimitry Andric ++NumTwoAddressInstrs; 17900b57cec5SDimitry Andric MadeChange = true; 17910b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << '\t' << *mi); 17920b57cec5SDimitry Andric 17930b57cec5SDimitry Andric // If the instruction has a single pair of tied operands, try some 17940b57cec5SDimitry Andric // transformations that may either eliminate the tied operands or 17950b57cec5SDimitry Andric // improve the opportunities for coalescing away the register copy. 17960b57cec5SDimitry Andric if (TiedOperands.size() == 1) { 17970b57cec5SDimitry Andric SmallVectorImpl<std::pair<unsigned, unsigned>> &TiedPairs 17980b57cec5SDimitry Andric = TiedOperands.begin()->second; 17990b57cec5SDimitry Andric if (TiedPairs.size() == 1) { 18000b57cec5SDimitry Andric unsigned SrcIdx = TiedPairs[0].first; 18010b57cec5SDimitry Andric unsigned DstIdx = TiedPairs[0].second; 18028bcb0991SDimitry Andric Register SrcReg = mi->getOperand(SrcIdx).getReg(); 18038bcb0991SDimitry Andric Register DstReg = mi->getOperand(DstIdx).getReg(); 18040b57cec5SDimitry Andric if (SrcReg != DstReg && 18050b57cec5SDimitry Andric tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) { 18060b57cec5SDimitry Andric // The tied operands have been eliminated or shifted further down 18070b57cec5SDimitry Andric // the block to ease elimination. Continue processing with 'nmi'. 18080b57cec5SDimitry Andric TiedOperands.clear(); 1809349cc55cSDimitry Andric removeClobberedSrcRegMap(&*mi); 18100b57cec5SDimitry Andric mi = nmi; 18110b57cec5SDimitry Andric continue; 18120b57cec5SDimitry Andric } 18130b57cec5SDimitry Andric } 18140b57cec5SDimitry Andric } 18150b57cec5SDimitry Andric 181681ad6265SDimitry Andric if (mi->getOpcode() == TargetOpcode::STATEPOINT && 181781ad6265SDimitry Andric processStatepoint(&*mi, TiedOperands)) { 181881ad6265SDimitry Andric TiedOperands.clear(); 181981ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "\t\trewrite to:\t" << *mi); 182081ad6265SDimitry Andric mi = nmi; 182181ad6265SDimitry Andric continue; 182281ad6265SDimitry Andric } 182381ad6265SDimitry Andric 18240b57cec5SDimitry Andric // Now iterate over the information collected above. 18250b57cec5SDimitry Andric for (auto &TO : TiedOperands) { 18260b57cec5SDimitry Andric processTiedPairs(&*mi, TO.second, Dist); 18270b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\t\trewrite to:\t" << *mi); 18280b57cec5SDimitry Andric } 18290b57cec5SDimitry Andric 18300b57cec5SDimitry Andric // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form. 18310b57cec5SDimitry Andric if (mi->isInsertSubreg()) { 18320b57cec5SDimitry Andric // From %reg = INSERT_SUBREG %reg, %subreg, subidx 18330b57cec5SDimitry Andric // To %reg:subidx = COPY %subreg 18340b57cec5SDimitry Andric unsigned SubIdx = mi->getOperand(3).getImm(); 183581ad6265SDimitry Andric mi->removeOperand(3); 18360b57cec5SDimitry Andric assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx"); 18370b57cec5SDimitry Andric mi->getOperand(0).setSubReg(SubIdx); 18380b57cec5SDimitry Andric mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef()); 183981ad6265SDimitry Andric mi->removeOperand(1); 18400b57cec5SDimitry Andric mi->setDesc(TII->get(TargetOpcode::COPY)); 18410b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "\t\tconvert to:\t" << *mi); 1842349cc55cSDimitry Andric 1843349cc55cSDimitry Andric // Update LiveIntervals. 1844349cc55cSDimitry Andric if (LIS) { 1845349cc55cSDimitry Andric Register Reg = mi->getOperand(0).getReg(); 1846349cc55cSDimitry Andric LiveInterval &LI = LIS->getInterval(Reg); 1847349cc55cSDimitry Andric if (LI.hasSubRanges()) { 1848349cc55cSDimitry Andric // The COPY no longer defines subregs of %reg except for 1849349cc55cSDimitry Andric // %reg.subidx. 1850349cc55cSDimitry Andric LaneBitmask LaneMask = 1851349cc55cSDimitry Andric TRI->getSubRegIndexLaneMask(mi->getOperand(0).getSubReg()); 1852349cc55cSDimitry Andric SlotIndex Idx = LIS->getInstructionIndex(*mi); 1853349cc55cSDimitry Andric for (auto &S : LI.subranges()) { 1854349cc55cSDimitry Andric if ((S.LaneMask & LaneMask).none()) { 1855349cc55cSDimitry Andric LiveRange::iterator UseSeg = S.FindSegmentContaining(Idx); 1856349cc55cSDimitry Andric LiveRange::iterator DefSeg = std::next(UseSeg); 1857349cc55cSDimitry Andric S.MergeValueNumberInto(DefSeg->valno, UseSeg->valno); 1858349cc55cSDimitry Andric } 1859349cc55cSDimitry Andric } 1860349cc55cSDimitry Andric 1861349cc55cSDimitry Andric // The COPY no longer has a use of %reg. 1862349cc55cSDimitry Andric LIS->shrinkToUses(&LI); 1863349cc55cSDimitry Andric } else { 1864349cc55cSDimitry Andric // The live interval for Reg did not have subranges but now it needs 1865349cc55cSDimitry Andric // them because we have introduced a subreg def. Recompute it. 1866349cc55cSDimitry Andric LIS->removeInterval(Reg); 1867349cc55cSDimitry Andric LIS->createAndComputeVirtRegInterval(Reg); 1868349cc55cSDimitry Andric } 1869349cc55cSDimitry Andric } 18700b57cec5SDimitry Andric } 18710b57cec5SDimitry Andric 18720b57cec5SDimitry Andric // Clear TiedOperands here instead of at the top of the loop 18730b57cec5SDimitry Andric // since most instructions do not have tied operands. 18740b57cec5SDimitry Andric TiedOperands.clear(); 1875349cc55cSDimitry Andric removeClobberedSrcRegMap(&*mi); 18760b57cec5SDimitry Andric mi = nmi; 18770b57cec5SDimitry Andric } 18780b57cec5SDimitry Andric } 18790b57cec5SDimitry Andric 18800b57cec5SDimitry Andric return MadeChange; 18810b57cec5SDimitry Andric } 18820b57cec5SDimitry Andric 18830b57cec5SDimitry Andric /// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process. 18840b57cec5SDimitry Andric /// 18850b57cec5SDimitry Andric /// The instruction is turned into a sequence of sub-register copies: 18860b57cec5SDimitry Andric /// 18870b57cec5SDimitry Andric /// %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1 18880b57cec5SDimitry Andric /// 18890b57cec5SDimitry Andric /// Becomes: 18900b57cec5SDimitry Andric /// 18910b57cec5SDimitry Andric /// undef %dst:ssub0 = COPY %v1 18920b57cec5SDimitry Andric /// %dst:ssub1 = COPY %v2 18930b57cec5SDimitry Andric void TwoAddressInstructionPass:: 18940b57cec5SDimitry Andric eliminateRegSequence(MachineBasicBlock::iterator &MBBI) { 18950b57cec5SDimitry Andric MachineInstr &MI = *MBBI; 18968bcb0991SDimitry Andric Register DstReg = MI.getOperand(0).getReg(); 18970b57cec5SDimitry Andric 18985ffd83dbSDimitry Andric SmallVector<Register, 4> OrigRegs; 18990b57cec5SDimitry Andric if (LIS) { 19000b57cec5SDimitry Andric OrigRegs.push_back(MI.getOperand(0).getReg()); 19010b57cec5SDimitry Andric for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2) 19020b57cec5SDimitry Andric OrigRegs.push_back(MI.getOperand(i).getReg()); 19030b57cec5SDimitry Andric } 19040b57cec5SDimitry Andric 19050b57cec5SDimitry Andric bool DefEmitted = false; 19060b57cec5SDimitry Andric for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2) { 19070b57cec5SDimitry Andric MachineOperand &UseMO = MI.getOperand(i); 19088bcb0991SDimitry Andric Register SrcReg = UseMO.getReg(); 19090b57cec5SDimitry Andric unsigned SubIdx = MI.getOperand(i+1).getImm(); 19100b57cec5SDimitry Andric // Nothing needs to be inserted for undef operands. 19110b57cec5SDimitry Andric if (UseMO.isUndef()) 19120b57cec5SDimitry Andric continue; 19130b57cec5SDimitry Andric 19140b57cec5SDimitry Andric // Defer any kill flag to the last operand using SrcReg. Otherwise, we 19150b57cec5SDimitry Andric // might insert a COPY that uses SrcReg after is was killed. 19160b57cec5SDimitry Andric bool isKill = UseMO.isKill(); 19170b57cec5SDimitry Andric if (isKill) 19180b57cec5SDimitry Andric for (unsigned j = i + 2; j < e; j += 2) 19190b57cec5SDimitry Andric if (MI.getOperand(j).getReg() == SrcReg) { 19200b57cec5SDimitry Andric MI.getOperand(j).setIsKill(); 19210b57cec5SDimitry Andric UseMO.setIsKill(false); 19220b57cec5SDimitry Andric isKill = false; 19230b57cec5SDimitry Andric break; 19240b57cec5SDimitry Andric } 19250b57cec5SDimitry Andric 19260b57cec5SDimitry Andric // Insert the sub-register copy. 19270b57cec5SDimitry Andric MachineInstr *CopyMI = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 19280b57cec5SDimitry Andric TII->get(TargetOpcode::COPY)) 19290b57cec5SDimitry Andric .addReg(DstReg, RegState::Define, SubIdx) 19300b57cec5SDimitry Andric .add(UseMO); 19310b57cec5SDimitry Andric 19320b57cec5SDimitry Andric // The first def needs an undef flag because there is no live register 19330b57cec5SDimitry Andric // before it. 19340b57cec5SDimitry Andric if (!DefEmitted) { 19350b57cec5SDimitry Andric CopyMI->getOperand(0).setIsUndef(true); 19360b57cec5SDimitry Andric // Return an iterator pointing to the first inserted instr. 19370b57cec5SDimitry Andric MBBI = CopyMI; 19380b57cec5SDimitry Andric } 19390b57cec5SDimitry Andric DefEmitted = true; 19400b57cec5SDimitry Andric 19410b57cec5SDimitry Andric // Update LiveVariables' kill info. 1942e8d8bef9SDimitry Andric if (LV && isKill && !SrcReg.isPhysical()) 19430b57cec5SDimitry Andric LV->replaceKillInstruction(SrcReg, MI, *CopyMI); 19440b57cec5SDimitry Andric 19450b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Inserted: " << *CopyMI); 19460b57cec5SDimitry Andric } 19470b57cec5SDimitry Andric 19480b57cec5SDimitry Andric MachineBasicBlock::iterator EndMBBI = 19490b57cec5SDimitry Andric std::next(MachineBasicBlock::iterator(MI)); 19500b57cec5SDimitry Andric 19510b57cec5SDimitry Andric if (!DefEmitted) { 19520b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Turned: " << MI << " into an IMPLICIT_DEF"); 19530b57cec5SDimitry Andric MI.setDesc(TII->get(TargetOpcode::IMPLICIT_DEF)); 19540b57cec5SDimitry Andric for (int j = MI.getNumOperands() - 1, ee = 0; j > ee; --j) 195581ad6265SDimitry Andric MI.removeOperand(j); 19560b57cec5SDimitry Andric } else { 1957349cc55cSDimitry Andric if (LIS) 1958349cc55cSDimitry Andric LIS->RemoveMachineInstrFromMaps(MI); 1959349cc55cSDimitry Andric 19600b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Eliminated: " << MI); 19610b57cec5SDimitry Andric MI.eraseFromParent(); 19620b57cec5SDimitry Andric } 19630b57cec5SDimitry Andric 19640b57cec5SDimitry Andric // Udpate LiveIntervals. 19650b57cec5SDimitry Andric if (LIS) 19660b57cec5SDimitry Andric LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs); 19670b57cec5SDimitry Andric } 1968