12cab237bSDimitry Andric //===- TwoAddressInstructionPass.cpp - Two-Address instruction pass -------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This file implements the TwoAddress instruction pass which is used
11f22ef01cSRoman Divacky // by most register allocators. Two-Address instructions are rewritten
12f22ef01cSRoman Divacky // from:
13f22ef01cSRoman Divacky //
14f22ef01cSRoman Divacky //     A = B op C
15f22ef01cSRoman Divacky //
16f22ef01cSRoman Divacky // to:
17f22ef01cSRoman Divacky //
18f22ef01cSRoman Divacky //     A = B
19f22ef01cSRoman Divacky //     A op= C
20f22ef01cSRoman Divacky //
21f22ef01cSRoman Divacky // Note that if a register allocator chooses to use this pass, that it
22f22ef01cSRoman Divacky // has to be capable of handling the non-SSA nature of these rewritten
23f22ef01cSRoman Divacky // virtual registers.
24f22ef01cSRoman Divacky //
25f22ef01cSRoman Divacky // It is also worth noting that the duplicate operand of the two
26f22ef01cSRoman Divacky // address instruction is removed.
27f22ef01cSRoman Divacky //
28f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
29f22ef01cSRoman Divacky 
30139f7f9bSDimitry Andric #include "llvm/ADT/DenseMap.h"
312cab237bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
322cab237bSDimitry Andric #include "llvm/ADT/SmallSet.h"
336c4bc1bdSDimitry Andric #include "llvm/ADT/SmallVector.h"
34139f7f9bSDimitry Andric #include "llvm/ADT/Statistic.h"
352cab237bSDimitry Andric #include "llvm/ADT/iterator_range.h"
36139f7f9bSDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
372cab237bSDimitry Andric #include "llvm/CodeGen/LiveInterval.h"
382cab237bSDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
39f22ef01cSRoman Divacky #include "llvm/CodeGen/LiveVariables.h"
402cab237bSDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
412cab237bSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
42f22ef01cSRoman Divacky #include "llvm/CodeGen/MachineFunctionPass.h"
43f22ef01cSRoman Divacky #include "llvm/CodeGen/MachineInstr.h"
44ffd1746dSEd Schouten #include "llvm/CodeGen/MachineInstrBuilder.h"
452cab237bSDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
46f22ef01cSRoman Divacky #include "llvm/CodeGen/MachineRegisterInfo.h"
473ca95b02SDimitry Andric #include "llvm/CodeGen/Passes.h"
482cab237bSDimitry Andric #include "llvm/CodeGen/SlotIndexes.h"
492cab237bSDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
502cab237bSDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
512cab237bSDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
522cab237bSDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
532cab237bSDimitry Andric #include "llvm/MC/MCInstrDesc.h"
54dff0c46cSDimitry Andric #include "llvm/MC/MCInstrItineraries.h"
552cab237bSDimitry Andric #include "llvm/Pass.h"
562cab237bSDimitry Andric #include "llvm/Support/CodeGen.h"
57284c1978SDimitry Andric #include "llvm/Support/CommandLine.h"
58f22ef01cSRoman Divacky #include "llvm/Support/Debug.h"
59f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h"
60ff0cc061SDimitry Andric #include "llvm/Support/raw_ostream.h"
61139f7f9bSDimitry Andric #include "llvm/Target/TargetMachine.h"
622cab237bSDimitry Andric #include <cassert>
632cab237bSDimitry Andric #include <iterator>
642cab237bSDimitry Andric #include <utility>
653ca95b02SDimitry Andric 
66f22ef01cSRoman Divacky using namespace llvm;
67f22ef01cSRoman Divacky 
68302affcbSDimitry Andric #define DEBUG_TYPE "twoaddressinstruction"
6991bc56edSDimitry Andric 
70f22ef01cSRoman Divacky STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
71f22ef01cSRoman Divacky STATISTIC(NumCommuted        , "Number of instructions commuted to coalesce");
72f22ef01cSRoman Divacky STATISTIC(NumAggrCommuted    , "Number of instructions aggressively commuted");
73f22ef01cSRoman Divacky STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
74f22ef01cSRoman Divacky STATISTIC(Num3AddrSunk,        "Number of 3-address instructions sunk");
75dff0c46cSDimitry Andric STATISTIC(NumReSchedUps,       "Number of instructions re-scheduled up");
76dff0c46cSDimitry Andric STATISTIC(NumReSchedDowns,     "Number of instructions re-scheduled down");
77f22ef01cSRoman Divacky 
78284c1978SDimitry Andric // Temporary flag to disable rescheduling.
79284c1978SDimitry Andric static cl::opt<bool>
80284c1978SDimitry Andric EnableRescheduling("twoaddr-reschedule",
81284c1978SDimitry Andric                    cl::desc("Coalesce copies by rescheduling (default=true)"),
82284c1978SDimitry Andric                    cl::init(true), cl::Hidden);
83284c1978SDimitry Andric 
84a580b014SDimitry Andric // Limit the number of dataflow edges to traverse when evaluating the benefit
85a580b014SDimitry Andric // of commuting operands.
86a580b014SDimitry Andric static cl::opt<unsigned> MaxDataFlowEdge(
87a580b014SDimitry Andric     "dataflow-edge-limit", cl::Hidden, cl::init(3),
88a580b014SDimitry Andric     cl::desc("Maximum number of dataflow edges to traverse when evaluating "
89a580b014SDimitry Andric              "the benefit of commuting operands"));
90a580b014SDimitry Andric 
91f22ef01cSRoman Divacky namespace {
922cab237bSDimitry Andric 
93f22ef01cSRoman Divacky class TwoAddressInstructionPass : public MachineFunctionPass {
947ae0e2c9SDimitry Andric   MachineFunction *MF;
95f22ef01cSRoman Divacky   const TargetInstrInfo *TII;
96f22ef01cSRoman Divacky   const TargetRegisterInfo *TRI;
97dff0c46cSDimitry Andric   const InstrItineraryData *InstrItins;
98f22ef01cSRoman Divacky   MachineRegisterInfo *MRI;
99f22ef01cSRoman Divacky   LiveVariables *LV;
1007ae0e2c9SDimitry Andric   LiveIntervals *LIS;
101f22ef01cSRoman Divacky   AliasAnalysis *AA;
102dff0c46cSDimitry Andric   CodeGenOpt::Level OptLevel;
103f22ef01cSRoman Divacky 
1043861d79fSDimitry Andric   // The current basic block being processed.
1053861d79fSDimitry Andric   MachineBasicBlock *MBB;
1063861d79fSDimitry Andric 
1077d523365SDimitry Andric   // Keep track the distance of a MI from the start of the current basic block.
108f22ef01cSRoman Divacky   DenseMap<MachineInstr*, unsigned> DistanceMap;
109f22ef01cSRoman Divacky 
1103861d79fSDimitry Andric   // Set of already processed instructions in the current block.
1113861d79fSDimitry Andric   SmallPtrSet<MachineInstr*, 8> Processed;
1123861d79fSDimitry Andric 
1132cab237bSDimitry Andric   // Set of instructions converted to three-address by target and then sunk
1142cab237bSDimitry Andric   // down current basic block.
1152cab237bSDimitry Andric   SmallPtrSet<MachineInstr*, 8> SunkInstrs;
1162cab237bSDimitry Andric 
1177d523365SDimitry Andric   // A map from virtual registers to physical registers which are likely targets
1187d523365SDimitry Andric   // to be coalesced to due to copies from physical registers to virtual
1197d523365SDimitry Andric   // registers. e.g. v1024 = move r0.
120f22ef01cSRoman Divacky   DenseMap<unsigned, unsigned> SrcRegMap;
121f22ef01cSRoman Divacky 
1227d523365SDimitry Andric   // A map from virtual registers to physical registers which are likely targets
1237d523365SDimitry Andric   // to be coalesced to due to copies to physical registers from virtual
1247d523365SDimitry Andric   // registers. e.g. r1 = move v1024.
125f22ef01cSRoman Divacky   DenseMap<unsigned, unsigned> DstRegMap;
126f22ef01cSRoman Divacky 
1273861d79fSDimitry Andric   bool sink3AddrInstruction(MachineInstr *MI, unsigned Reg,
128f22ef01cSRoman Divacky                             MachineBasicBlock::iterator OldPos);
129f22ef01cSRoman Divacky 
130ff0cc061SDimitry Andric   bool isRevCopyChain(unsigned FromReg, unsigned ToReg, int Maxlen);
131ff0cc061SDimitry Andric 
1323861d79fSDimitry Andric   bool noUseAfterLastDef(unsigned Reg, unsigned Dist, unsigned &LastDef);
133f22ef01cSRoman Divacky 
1347ae0e2c9SDimitry Andric   bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
1353861d79fSDimitry Andric                              MachineInstr *MI, unsigned Dist);
136f22ef01cSRoman Divacky 
137d88c1a5aSDimitry Andric   bool commuteInstruction(MachineInstr *MI, unsigned DstIdx,
1387d523365SDimitry Andric                           unsigned RegBIdx, unsigned RegCIdx, unsigned Dist);
139f22ef01cSRoman Divacky 
1403b0f4066SDimitry Andric   bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
141f22ef01cSRoman Divacky 
1423861d79fSDimitry Andric   bool convertInstTo3Addr(MachineBasicBlock::iterator &mi,
143f22ef01cSRoman Divacky                           MachineBasicBlock::iterator &nmi,
1442754fe60SDimitry Andric                           unsigned RegA, unsigned RegB, unsigned Dist);
145f22ef01cSRoman Divacky 
1463861d79fSDimitry Andric   bool isDefTooClose(unsigned Reg, unsigned Dist, MachineInstr *MI);
147dff0c46cSDimitry Andric 
1483861d79fSDimitry Andric   bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
149dff0c46cSDimitry Andric                              MachineBasicBlock::iterator &nmi,
150dff0c46cSDimitry Andric                              unsigned Reg);
1513861d79fSDimitry Andric   bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
152dff0c46cSDimitry Andric                              MachineBasicBlock::iterator &nmi,
153dff0c46cSDimitry Andric                              unsigned Reg);
154dff0c46cSDimitry Andric 
1553861d79fSDimitry Andric   bool tryInstructionTransform(MachineBasicBlock::iterator &mi,
156f22ef01cSRoman Divacky                                MachineBasicBlock::iterator &nmi,
157f22ef01cSRoman Divacky                                unsigned SrcIdx, unsigned DstIdx,
158139f7f9bSDimitry Andric                                unsigned Dist, bool shouldOnlyCommute);
1593b0f4066SDimitry Andric 
1607d523365SDimitry Andric   bool tryInstructionCommute(MachineInstr *MI,
1617d523365SDimitry Andric                              unsigned DstOpIdx,
1627d523365SDimitry Andric                              unsigned BaseOpIdx,
1637d523365SDimitry Andric                              bool BaseOpKilled,
1647d523365SDimitry Andric                              unsigned Dist);
1653861d79fSDimitry Andric   void scanUses(unsigned DstReg);
166f22ef01cSRoman Divacky 
1673861d79fSDimitry Andric   void processCopy(MachineInstr *MI);
168f22ef01cSRoman Divacky 
1692cab237bSDimitry Andric   using TiedPairList = SmallVector<std::pair<unsigned, unsigned>, 4>;
1702cab237bSDimitry Andric   using TiedOperandMap = SmallDenseMap<unsigned, TiedPairList>;
1712cab237bSDimitry Andric 
1727ae0e2c9SDimitry Andric   bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
1737ae0e2c9SDimitry Andric   void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
174139f7f9bSDimitry Andric   void eliminateRegSequence(MachineBasicBlock::iterator&);
175f22ef01cSRoman Divacky 
176f22ef01cSRoman Divacky public:
177f22ef01cSRoman Divacky   static char ID; // Pass identification, replacement for typeid
1782cab237bSDimitry Andric 
TwoAddressInstructionPass()1792754fe60SDimitry Andric   TwoAddressInstructionPass() : MachineFunctionPass(ID) {
1802754fe60SDimitry Andric     initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
1812754fe60SDimitry Andric   }
182f22ef01cSRoman Divacky 
getAnalysisUsage(AnalysisUsage & AU) const18391bc56edSDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
184f22ef01cSRoman Divacky     AU.setPreservesCFG();
1855517e702SDimitry Andric     AU.addUsedIfAvailable<AAResultsWrapperPass>();
1863ca95b02SDimitry Andric     AU.addUsedIfAvailable<LiveVariables>();
187f22ef01cSRoman Divacky     AU.addPreserved<LiveVariables>();
1887ae0e2c9SDimitry Andric     AU.addPreserved<SlotIndexes>();
1897ae0e2c9SDimitry Andric     AU.addPreserved<LiveIntervals>();
190f22ef01cSRoman Divacky     AU.addPreservedID(MachineLoopInfoID);
191f22ef01cSRoman Divacky     AU.addPreservedID(MachineDominatorsID);
192f22ef01cSRoman Divacky     MachineFunctionPass::getAnalysisUsage(AU);
193f22ef01cSRoman Divacky   }
194f22ef01cSRoman Divacky 
1957d523365SDimitry Andric   /// Pass entry point.
19691bc56edSDimitry Andric   bool runOnMachineFunction(MachineFunction&) override;
197f22ef01cSRoman Divacky };
1982cab237bSDimitry Andric 
1993861d79fSDimitry Andric } // end anonymous namespace
200f22ef01cSRoman Divacky 
201f22ef01cSRoman Divacky char TwoAddressInstructionPass::ID = 0;
2022cab237bSDimitry Andric 
2032cab237bSDimitry Andric char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
2042cab237bSDimitry Andric 
205302affcbSDimitry Andric INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, DEBUG_TYPE,
2062754fe60SDimitry Andric                 "Two-Address instruction pass", false, false)
2077d523365SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
208302affcbSDimitry Andric INITIALIZE_PASS_END(TwoAddressInstructionPass, DEBUG_TYPE,
2092754fe60SDimitry Andric                 "Two-Address instruction pass", false, false)
210f22ef01cSRoman Divacky 
211139f7f9bSDimitry Andric static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg, LiveIntervals *LIS);
212139f7f9bSDimitry Andric 
2137d523365SDimitry Andric /// A two-address instruction has been converted to a three-address instruction
2147d523365SDimitry Andric /// to avoid clobbering a register. Try to sink it past the instruction that
2157d523365SDimitry Andric /// would kill the above mentioned register to reduce register pressure.
2163861d79fSDimitry Andric bool TwoAddressInstructionPass::
sink3AddrInstruction(MachineInstr * MI,unsigned SavedReg,MachineBasicBlock::iterator OldPos)2173861d79fSDimitry Andric sink3AddrInstruction(MachineInstr *MI, unsigned SavedReg,
218f22ef01cSRoman Divacky                      MachineBasicBlock::iterator OldPos) {
2196122f3e6SDimitry Andric   // FIXME: Shouldn't we be trying to do this before we three-addressify the
2206122f3e6SDimitry Andric   // instruction?  After this transformation is done, we no longer need
2216122f3e6SDimitry Andric   // the instruction to be in three-address form.
2226122f3e6SDimitry Andric 
223f22ef01cSRoman Divacky   // Check if it's safe to move this instruction.
224f22ef01cSRoman Divacky   bool SeenStore = true; // Be conservative.
225ff0cc061SDimitry Andric   if (!MI->isSafeToMove(AA, SeenStore))
226f22ef01cSRoman Divacky     return false;
227f22ef01cSRoman Divacky 
228f22ef01cSRoman Divacky   unsigned DefReg = 0;
229f22ef01cSRoman Divacky   SmallSet<unsigned, 4> UseRegs;
230f22ef01cSRoman Divacky 
2317d523365SDimitry Andric   for (const MachineOperand &MO : MI->operands()) {
232f22ef01cSRoman Divacky     if (!MO.isReg())
233f22ef01cSRoman Divacky       continue;
234f22ef01cSRoman Divacky     unsigned MOReg = MO.getReg();
235f22ef01cSRoman Divacky     if (!MOReg)
236f22ef01cSRoman Divacky       continue;
237f22ef01cSRoman Divacky     if (MO.isUse() && MOReg != SavedReg)
238f22ef01cSRoman Divacky       UseRegs.insert(MO.getReg());
239f22ef01cSRoman Divacky     if (!MO.isDef())
240f22ef01cSRoman Divacky       continue;
241f22ef01cSRoman Divacky     if (MO.isImplicit())
242f22ef01cSRoman Divacky       // Don't try to move it if it implicitly defines a register.
243f22ef01cSRoman Divacky       return false;
244f22ef01cSRoman Divacky     if (DefReg)
245f22ef01cSRoman Divacky       // For now, don't move any instructions that define multiple registers.
246f22ef01cSRoman Divacky       return false;
247f22ef01cSRoman Divacky     DefReg = MO.getReg();
248f22ef01cSRoman Divacky   }
249f22ef01cSRoman Divacky 
250f22ef01cSRoman Divacky   // Find the instruction that kills SavedReg.
25191bc56edSDimitry Andric   MachineInstr *KillMI = nullptr;
252139f7f9bSDimitry Andric   if (LIS) {
253139f7f9bSDimitry Andric     LiveInterval &LI = LIS->getInterval(SavedReg);
254139f7f9bSDimitry Andric     assert(LI.end() != LI.begin() &&
255139f7f9bSDimitry Andric            "Reg should not have empty live interval.");
256139f7f9bSDimitry Andric 
257139f7f9bSDimitry Andric     SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
258139f7f9bSDimitry Andric     LiveInterval::const_iterator I = LI.find(MBBEndIdx);
259139f7f9bSDimitry Andric     if (I != LI.end() && I->start < MBBEndIdx)
260139f7f9bSDimitry Andric       return false;
261139f7f9bSDimitry Andric 
262139f7f9bSDimitry Andric     --I;
263139f7f9bSDimitry Andric     KillMI = LIS->getInstructionFromIndex(I->end);
264139f7f9bSDimitry Andric   }
265139f7f9bSDimitry Andric   if (!KillMI) {
2667d523365SDimitry Andric     for (MachineOperand &UseMO : MRI->use_nodbg_operands(SavedReg)) {
267f22ef01cSRoman Divacky       if (!UseMO.isKill())
268f22ef01cSRoman Divacky         continue;
269f22ef01cSRoman Divacky       KillMI = UseMO.getParent();
270f22ef01cSRoman Divacky       break;
271f22ef01cSRoman Divacky     }
272139f7f9bSDimitry Andric   }
273f22ef01cSRoman Divacky 
2746122f3e6SDimitry Andric   // If we find the instruction that kills SavedReg, and it is in an
2756122f3e6SDimitry Andric   // appropriate location, we can try to sink the current instruction
2766122f3e6SDimitry Andric   // past it.
2776122f3e6SDimitry Andric   if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
2783ca95b02SDimitry Andric       MachineBasicBlock::iterator(KillMI) == OldPos || KillMI->isTerminator())
279f22ef01cSRoman Divacky     return false;
280f22ef01cSRoman Divacky 
281f22ef01cSRoman Divacky   // If any of the definitions are used by another instruction between the
282f22ef01cSRoman Divacky   // position and the kill use, then it's not safe to sink it.
283f22ef01cSRoman Divacky   //
284f22ef01cSRoman Divacky   // FIXME: This can be sped up if there is an easy way to query whether an
285f22ef01cSRoman Divacky   // instruction is before or after another instruction. Then we can use
286f22ef01cSRoman Divacky   // MachineRegisterInfo def / use instead.
28791bc56edSDimitry Andric   MachineOperand *KillMO = nullptr;
288f22ef01cSRoman Divacky   MachineBasicBlock::iterator KillPos = KillMI;
289f22ef01cSRoman Divacky   ++KillPos;
290f22ef01cSRoman Divacky 
291f22ef01cSRoman Divacky   unsigned NumVisited = 0;
2922cab237bSDimitry Andric   for (MachineInstr &OtherMI : make_range(std::next(OldPos), KillPos)) {
2934ba319b5SDimitry Andric     // Debug instructions cannot be counted against the limit.
2944ba319b5SDimitry Andric     if (OtherMI.isDebugInstr())
295f22ef01cSRoman Divacky       continue;
296f22ef01cSRoman Divacky     if (NumVisited > 30)  // FIXME: Arbitrary limit to reduce compile time cost.
297f22ef01cSRoman Divacky       return false;
298f22ef01cSRoman Divacky     ++NumVisited;
2993ca95b02SDimitry Andric     for (unsigned i = 0, e = OtherMI.getNumOperands(); i != e; ++i) {
3003ca95b02SDimitry Andric       MachineOperand &MO = OtherMI.getOperand(i);
301f22ef01cSRoman Divacky       if (!MO.isReg())
302f22ef01cSRoman Divacky         continue;
303f22ef01cSRoman Divacky       unsigned MOReg = MO.getReg();
304f22ef01cSRoman Divacky       if (!MOReg)
305f22ef01cSRoman Divacky         continue;
306f22ef01cSRoman Divacky       if (DefReg == MOReg)
307f22ef01cSRoman Divacky         return false;
308f22ef01cSRoman Divacky 
3093ca95b02SDimitry Andric       if (MO.isKill() || (LIS && isPlainlyKilled(&OtherMI, MOReg, LIS))) {
3103ca95b02SDimitry Andric         if (&OtherMI == KillMI && MOReg == SavedReg)
311f22ef01cSRoman Divacky           // Save the operand that kills the register. We want to unset the kill
312f22ef01cSRoman Divacky           // marker if we can sink MI past it.
313f22ef01cSRoman Divacky           KillMO = &MO;
314f22ef01cSRoman Divacky         else if (UseRegs.count(MOReg))
315f22ef01cSRoman Divacky           // One of the uses is killed before the destination.
316f22ef01cSRoman Divacky           return false;
317f22ef01cSRoman Divacky       }
318f22ef01cSRoman Divacky     }
319f22ef01cSRoman Divacky   }
3207ae0e2c9SDimitry Andric   assert(KillMO && "Didn't find kill");
321f22ef01cSRoman Divacky 
322139f7f9bSDimitry Andric   if (!LIS) {
323f22ef01cSRoman Divacky     // Update kill and LV information.
324f22ef01cSRoman Divacky     KillMO->setIsKill(false);
325f22ef01cSRoman Divacky     KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
326f22ef01cSRoman Divacky     KillMO->setIsKill(true);
327f22ef01cSRoman Divacky 
328f22ef01cSRoman Divacky     if (LV)
3293ca95b02SDimitry Andric       LV->replaceKillInstruction(SavedReg, *KillMI, *MI);
330139f7f9bSDimitry Andric   }
331f22ef01cSRoman Divacky 
332f22ef01cSRoman Divacky   // Move instruction to its destination.
333f22ef01cSRoman Divacky   MBB->remove(MI);
334f22ef01cSRoman Divacky   MBB->insert(KillPos, MI);
335f22ef01cSRoman Divacky 
3367ae0e2c9SDimitry Andric   if (LIS)
3373ca95b02SDimitry Andric     LIS->handleMove(*MI);
3387ae0e2c9SDimitry Andric 
339f22ef01cSRoman Divacky   ++Num3AddrSunk;
340f22ef01cSRoman Divacky   return true;
341f22ef01cSRoman Divacky }
342f22ef01cSRoman Divacky 
3437d523365SDimitry Andric /// Return the MachineInstr* if it is the single def of the Reg in current BB.
getSingleDef(unsigned Reg,MachineBasicBlock * BB,const MachineRegisterInfo * MRI)344ff0cc061SDimitry Andric static MachineInstr *getSingleDef(unsigned Reg, MachineBasicBlock *BB,
345ff0cc061SDimitry Andric                                   const MachineRegisterInfo *MRI) {
346ff0cc061SDimitry Andric   MachineInstr *Ret = nullptr;
347ff0cc061SDimitry Andric   for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
348ff0cc061SDimitry Andric     if (DefMI.getParent() != BB || DefMI.isDebugValue())
349ff0cc061SDimitry Andric       continue;
350ff0cc061SDimitry Andric     if (!Ret)
351ff0cc061SDimitry Andric       Ret = &DefMI;
352ff0cc061SDimitry Andric     else if (Ret != &DefMI)
353ff0cc061SDimitry Andric       return nullptr;
354ff0cc061SDimitry Andric   }
355ff0cc061SDimitry Andric   return Ret;
356ff0cc061SDimitry Andric }
357ff0cc061SDimitry Andric 
358ff0cc061SDimitry Andric /// Check if there is a reversed copy chain from FromReg to ToReg:
359ff0cc061SDimitry Andric /// %Tmp1 = copy %Tmp2;
360ff0cc061SDimitry Andric /// %FromReg = copy %Tmp1;
361ff0cc061SDimitry Andric /// %ToReg = add %FromReg ...
362ff0cc061SDimitry Andric /// %Tmp2 = copy %ToReg;
363ff0cc061SDimitry Andric /// MaxLen specifies the maximum length of the copy chain the func
364ff0cc061SDimitry Andric /// can walk through.
isRevCopyChain(unsigned FromReg,unsigned ToReg,int Maxlen)365ff0cc061SDimitry Andric bool TwoAddressInstructionPass::isRevCopyChain(unsigned FromReg, unsigned ToReg,
366ff0cc061SDimitry Andric                                                int Maxlen) {
367ff0cc061SDimitry Andric   unsigned TmpReg = FromReg;
368ff0cc061SDimitry Andric   for (int i = 0; i < Maxlen; i++) {
369ff0cc061SDimitry Andric     MachineInstr *Def = getSingleDef(TmpReg, MBB, MRI);
370ff0cc061SDimitry Andric     if (!Def || !Def->isCopy())
371ff0cc061SDimitry Andric       return false;
372ff0cc061SDimitry Andric 
373ff0cc061SDimitry Andric     TmpReg = Def->getOperand(1).getReg();
374ff0cc061SDimitry Andric 
375ff0cc061SDimitry Andric     if (TmpReg == ToReg)
376ff0cc061SDimitry Andric       return true;
377ff0cc061SDimitry Andric   }
378ff0cc061SDimitry Andric   return false;
379ff0cc061SDimitry Andric }
380ff0cc061SDimitry Andric 
3817d523365SDimitry Andric /// Return true if there are no intervening uses between the last instruction
3827d523365SDimitry Andric /// in the MBB that defines the specified register and the two-address
3837d523365SDimitry Andric /// instruction which is being processed. It also returns the last def location
3847d523365SDimitry Andric /// by reference.
noUseAfterLastDef(unsigned Reg,unsigned Dist,unsigned & LastDef)3853861d79fSDimitry Andric bool TwoAddressInstructionPass::noUseAfterLastDef(unsigned Reg, unsigned Dist,
386f22ef01cSRoman Divacky                                                   unsigned &LastDef) {
387f22ef01cSRoman Divacky   LastDef = 0;
388f22ef01cSRoman Divacky   unsigned LastUse = Dist;
38991bc56edSDimitry Andric   for (MachineOperand &MO : MRI->reg_operands(Reg)) {
390f22ef01cSRoman Divacky     MachineInstr *MI = MO.getParent();
391f22ef01cSRoman Divacky     if (MI->getParent() != MBB || MI->isDebugValue())
392f22ef01cSRoman Divacky       continue;
393f22ef01cSRoman Divacky     DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
394f22ef01cSRoman Divacky     if (DI == DistanceMap.end())
395f22ef01cSRoman Divacky       continue;
396f22ef01cSRoman Divacky     if (MO.isUse() && DI->second < LastUse)
397f22ef01cSRoman Divacky       LastUse = DI->second;
398f22ef01cSRoman Divacky     if (MO.isDef() && DI->second > LastDef)
399f22ef01cSRoman Divacky       LastDef = DI->second;
400f22ef01cSRoman Divacky   }
401f22ef01cSRoman Divacky 
402f22ef01cSRoman Divacky   return !(LastUse > LastDef && LastUse < Dist);
403f22ef01cSRoman Divacky }
404f22ef01cSRoman Divacky 
4057d523365SDimitry Andric /// Return true if the specified MI is a copy instruction or an extract_subreg
4067d523365SDimitry Andric /// instruction. It also returns the source and destination registers and
4077d523365SDimitry Andric /// whether they are physical registers by reference.
isCopyToReg(MachineInstr & MI,const TargetInstrInfo * TII,unsigned & SrcReg,unsigned & DstReg,bool & IsSrcPhys,bool & IsDstPhys)408f22ef01cSRoman Divacky static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
409f22ef01cSRoman Divacky                         unsigned &SrcReg, unsigned &DstReg,
410f22ef01cSRoman Divacky                         bool &IsSrcPhys, bool &IsDstPhys) {
411f22ef01cSRoman Divacky   SrcReg = 0;
412f22ef01cSRoman Divacky   DstReg = 0;
413ffd1746dSEd Schouten   if (MI.isCopy()) {
414f22ef01cSRoman Divacky     DstReg = MI.getOperand(0).getReg();
415f22ef01cSRoman Divacky     SrcReg = MI.getOperand(1).getReg();
416e580952dSDimitry Andric   } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
417f22ef01cSRoman Divacky     DstReg = MI.getOperand(0).getReg();
418f22ef01cSRoman Divacky     SrcReg = MI.getOperand(2).getReg();
419e580952dSDimitry Andric   } else
420e580952dSDimitry Andric     return false;
421f22ef01cSRoman Divacky 
422f22ef01cSRoman Divacky   IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
423f22ef01cSRoman Divacky   IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
424f22ef01cSRoman Divacky   return true;
425f22ef01cSRoman Divacky }
426f22ef01cSRoman Divacky 
4277d523365SDimitry Andric /// Test if the given register value, which is used by the
4287d523365SDimitry Andric /// given instruction, is killed by the given instruction.
isPlainlyKilled(MachineInstr * MI,unsigned Reg,LiveIntervals * LIS)429139f7f9bSDimitry Andric static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg,
430139f7f9bSDimitry Andric                             LiveIntervals *LIS) {
431139f7f9bSDimitry Andric   if (LIS && TargetRegisterInfo::isVirtualRegister(Reg) &&
4323ca95b02SDimitry Andric       !LIS->isNotInMIMap(*MI)) {
433139f7f9bSDimitry Andric     // FIXME: Sometimes tryInstructionTransform() will add instructions and
434139f7f9bSDimitry Andric     // test whether they can be folded before keeping them. In this case it
435139f7f9bSDimitry Andric     // sets a kill before recursively calling tryInstructionTransform() again.
436139f7f9bSDimitry Andric     // If there is no interval available, we assume that this instruction is
437139f7f9bSDimitry Andric     // one of those. A kill flag is manually inserted on the operand so the
438139f7f9bSDimitry Andric     // check below will handle it.
439139f7f9bSDimitry Andric     LiveInterval &LI = LIS->getInterval(Reg);
440139f7f9bSDimitry Andric     // This is to match the kill flag version where undefs don't have kill
441139f7f9bSDimitry Andric     // flags.
442139f7f9bSDimitry Andric     if (!LI.hasAtLeastOneValue())
443139f7f9bSDimitry Andric       return false;
444139f7f9bSDimitry Andric 
4453ca95b02SDimitry Andric     SlotIndex useIdx = LIS->getInstructionIndex(*MI);
446139f7f9bSDimitry Andric     LiveInterval::const_iterator I = LI.find(useIdx);
447139f7f9bSDimitry Andric     assert(I != LI.end() && "Reg must be live-in to use.");
448139f7f9bSDimitry Andric     return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx);
449139f7f9bSDimitry Andric   }
450139f7f9bSDimitry Andric 
451139f7f9bSDimitry Andric   return MI->killsRegister(Reg);
452139f7f9bSDimitry Andric }
453139f7f9bSDimitry Andric 
4547d523365SDimitry Andric /// Test if the given register value, which is used by the given
455f22ef01cSRoman Divacky /// instruction, is killed by the given instruction. This looks through
456f22ef01cSRoman Divacky /// coalescable copies to see if the original value is potentially not killed.
457f22ef01cSRoman Divacky ///
458f22ef01cSRoman Divacky /// For example, in this code:
459f22ef01cSRoman Divacky ///
460f22ef01cSRoman Divacky ///   %reg1034 = copy %reg1024
4612cab237bSDimitry Andric ///   %reg1035 = copy killed %reg1025
4622cab237bSDimitry Andric ///   %reg1036 = add killed %reg1034, killed %reg1035
463f22ef01cSRoman Divacky ///
464f22ef01cSRoman Divacky /// %reg1034 is not considered to be killed, since it is copied from a
465f22ef01cSRoman Divacky /// register which is not killed. Treating it as not killed lets the
466f22ef01cSRoman Divacky /// normal heuristics commute the (two-address) add, which lets
467f22ef01cSRoman Divacky /// coalescing eliminate the extra copy.
468f22ef01cSRoman Divacky ///
469139f7f9bSDimitry Andric /// If allowFalsePositives is true then likely kills are treated as kills even
470139f7f9bSDimitry Andric /// if it can't be proven that they are kills.
isKilled(MachineInstr & MI,unsigned Reg,const MachineRegisterInfo * MRI,const TargetInstrInfo * TII,LiveIntervals * LIS,bool allowFalsePositives)471f22ef01cSRoman Divacky static bool isKilled(MachineInstr &MI, unsigned Reg,
472f22ef01cSRoman Divacky                      const MachineRegisterInfo *MRI,
473139f7f9bSDimitry Andric                      const TargetInstrInfo *TII,
474139f7f9bSDimitry Andric                      LiveIntervals *LIS,
475139f7f9bSDimitry Andric                      bool allowFalsePositives) {
476f22ef01cSRoman Divacky   MachineInstr *DefMI = &MI;
4772cab237bSDimitry Andric   while (true) {
478139f7f9bSDimitry Andric     // All uses of physical registers are likely to be kills.
479139f7f9bSDimitry Andric     if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
480139f7f9bSDimitry Andric         (allowFalsePositives || MRI->hasOneUse(Reg)))
481139f7f9bSDimitry Andric       return true;
482139f7f9bSDimitry Andric     if (!isPlainlyKilled(DefMI, Reg, LIS))
483f22ef01cSRoman Divacky       return false;
484f22ef01cSRoman Divacky     if (TargetRegisterInfo::isPhysicalRegister(Reg))
485f22ef01cSRoman Divacky       return true;
486f22ef01cSRoman Divacky     MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
487f22ef01cSRoman Divacky     // If there are multiple defs, we can't do a simple analysis, so just
488f22ef01cSRoman Divacky     // go with what the kill flag says.
48991bc56edSDimitry Andric     if (std::next(Begin) != MRI->def_end())
490f22ef01cSRoman Divacky       return true;
49191bc56edSDimitry Andric     DefMI = Begin->getParent();
492f22ef01cSRoman Divacky     bool IsSrcPhys, IsDstPhys;
493f22ef01cSRoman Divacky     unsigned SrcReg,  DstReg;
494f22ef01cSRoman Divacky     // If the def is something other than a copy, then it isn't going to
495f22ef01cSRoman Divacky     // be coalesced, so follow the kill flag.
496f22ef01cSRoman Divacky     if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
497f22ef01cSRoman Divacky       return true;
498f22ef01cSRoman Divacky     Reg = SrcReg;
499f22ef01cSRoman Divacky   }
500f22ef01cSRoman Divacky }
501f22ef01cSRoman Divacky 
5027d523365SDimitry Andric /// Return true if the specified MI uses the specified register as a two-address
5037d523365SDimitry Andric /// use. If so, return the destination register by reference.
isTwoAddrUse(MachineInstr & MI,unsigned Reg,unsigned & DstReg)504f22ef01cSRoman Divacky static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
505284c1978SDimitry Andric   for (unsigned i = 0, NumOps = MI.getNumOperands(); i != NumOps; ++i) {
506f22ef01cSRoman Divacky     const MachineOperand &MO = MI.getOperand(i);
507f22ef01cSRoman Divacky     if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
508f22ef01cSRoman Divacky       continue;
509f22ef01cSRoman Divacky     unsigned ti;
510f22ef01cSRoman Divacky     if (MI.isRegTiedToDefOperand(i, &ti)) {
511f22ef01cSRoman Divacky       DstReg = MI.getOperand(ti).getReg();
512f22ef01cSRoman Divacky       return true;
513f22ef01cSRoman Divacky     }
514f22ef01cSRoman Divacky   }
515f22ef01cSRoman Divacky   return false;
516f22ef01cSRoman Divacky }
517f22ef01cSRoman Divacky 
5187d523365SDimitry Andric /// Given a register, if has a single in-basic block use, return the use
5197d523365SDimitry Andric /// instruction if it's a copy or a two-address use.
520f22ef01cSRoman Divacky static
findOnlyInterestingUse(unsigned Reg,MachineBasicBlock * MBB,MachineRegisterInfo * MRI,const TargetInstrInfo * TII,bool & IsCopy,unsigned & DstReg,bool & IsDstPhys)521f22ef01cSRoman Divacky MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
522f22ef01cSRoman Divacky                                      MachineRegisterInfo *MRI,
523f22ef01cSRoman Divacky                                      const TargetInstrInfo *TII,
524f22ef01cSRoman Divacky                                      bool &IsCopy,
525f22ef01cSRoman Divacky                                      unsigned &DstReg, bool &IsDstPhys) {
526f22ef01cSRoman Divacky   if (!MRI->hasOneNonDBGUse(Reg))
527f22ef01cSRoman Divacky     // None or more than one use.
52891bc56edSDimitry Andric     return nullptr;
52991bc56edSDimitry Andric   MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(Reg);
530f22ef01cSRoman Divacky   if (UseMI.getParent() != MBB)
53191bc56edSDimitry Andric     return nullptr;
532f22ef01cSRoman Divacky   unsigned SrcReg;
533f22ef01cSRoman Divacky   bool IsSrcPhys;
534f22ef01cSRoman Divacky   if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
535f22ef01cSRoman Divacky     IsCopy = true;
536f22ef01cSRoman Divacky     return &UseMI;
537f22ef01cSRoman Divacky   }
538f22ef01cSRoman Divacky   IsDstPhys = false;
539f22ef01cSRoman Divacky   if (isTwoAddrUse(UseMI, Reg, DstReg)) {
540f22ef01cSRoman Divacky     IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
541f22ef01cSRoman Divacky     return &UseMI;
542f22ef01cSRoman Divacky   }
54391bc56edSDimitry Andric   return nullptr;
544f22ef01cSRoman Divacky }
545f22ef01cSRoman Divacky 
5467d523365SDimitry Andric /// Return the physical register the specified virtual register might be mapped
5477d523365SDimitry Andric /// to.
548f22ef01cSRoman Divacky static unsigned
getMappedReg(unsigned Reg,DenseMap<unsigned,unsigned> & RegMap)549f22ef01cSRoman Divacky getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
550f22ef01cSRoman Divacky   while (TargetRegisterInfo::isVirtualRegister(Reg))  {
551f22ef01cSRoman Divacky     DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
552f22ef01cSRoman Divacky     if (SI == RegMap.end())
553f22ef01cSRoman Divacky       return 0;
554f22ef01cSRoman Divacky     Reg = SI->second;
555f22ef01cSRoman Divacky   }
556f22ef01cSRoman Divacky   if (TargetRegisterInfo::isPhysicalRegister(Reg))
557f22ef01cSRoman Divacky     return Reg;
558f22ef01cSRoman Divacky   return 0;
559f22ef01cSRoman Divacky }
560f22ef01cSRoman Divacky 
5617d523365SDimitry Andric /// Return true if the two registers are equal or aliased.
562f22ef01cSRoman Divacky static bool
regsAreCompatible(unsigned RegA,unsigned RegB,const TargetRegisterInfo * TRI)563f22ef01cSRoman Divacky regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
564f22ef01cSRoman Divacky   if (RegA == RegB)
565f22ef01cSRoman Divacky     return true;
566f22ef01cSRoman Divacky   if (!RegA || !RegB)
567f22ef01cSRoman Divacky     return false;
568f22ef01cSRoman Divacky   return TRI->regsOverlap(RegA, RegB);
569f22ef01cSRoman Divacky }
570f22ef01cSRoman Divacky 
5716c4bc1bdSDimitry Andric // Returns true if Reg is equal or aliased to at least one register in Set.
regOverlapsSet(const SmallVectorImpl<unsigned> & Set,unsigned Reg,const TargetRegisterInfo * TRI)5726c4bc1bdSDimitry Andric static bool regOverlapsSet(const SmallVectorImpl<unsigned> &Set, unsigned Reg,
5736c4bc1bdSDimitry Andric                            const TargetRegisterInfo *TRI) {
5746c4bc1bdSDimitry Andric   for (unsigned R : Set)
5756c4bc1bdSDimitry Andric     if (TRI->regsOverlap(R, Reg))
5766c4bc1bdSDimitry Andric       return true;
5776c4bc1bdSDimitry Andric 
5786c4bc1bdSDimitry Andric   return false;
5796c4bc1bdSDimitry Andric }
5806c4bc1bdSDimitry Andric 
5817d523365SDimitry Andric /// Return true if it's potentially profitable to commute the two-address
5827d523365SDimitry Andric /// instruction that's being processed.
583f22ef01cSRoman Divacky bool
5843861d79fSDimitry Andric TwoAddressInstructionPass::
isProfitableToCommute(unsigned regA,unsigned regB,unsigned regC,MachineInstr * MI,unsigned Dist)5853861d79fSDimitry Andric isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
5863861d79fSDimitry Andric                       MachineInstr *MI, unsigned Dist) {
587dff0c46cSDimitry Andric   if (OptLevel == CodeGenOpt::None)
588dff0c46cSDimitry Andric     return false;
589dff0c46cSDimitry Andric 
590f22ef01cSRoman Divacky   // Determine if it's profitable to commute this two address instruction. In
591f22ef01cSRoman Divacky   // general, we want no uses between this instruction and the definition of
592f22ef01cSRoman Divacky   // the two-address register.
593f22ef01cSRoman Divacky   // e.g.
5942cab237bSDimitry Andric   // %reg1028 = EXTRACT_SUBREG killed %reg1027, 1
595*b5893f02SDimitry Andric   // %reg1029 = COPY %reg1028
5962cab237bSDimitry Andric   // %reg1029 = SHR8ri %reg1029, 7, implicit dead %eflags
597*b5893f02SDimitry Andric   // insert => %reg1030 = COPY %reg1028
5982cab237bSDimitry Andric   // %reg1030 = ADD8rr killed %reg1028, killed %reg1029, implicit dead %eflags
599*b5893f02SDimitry Andric   // In this case, it might not be possible to coalesce the second COPY
600f22ef01cSRoman Divacky   // instruction if the first one is coalesced. So it would be profitable to
601f22ef01cSRoman Divacky   // commute it:
6022cab237bSDimitry Andric   // %reg1028 = EXTRACT_SUBREG killed %reg1027, 1
603*b5893f02SDimitry Andric   // %reg1029 = COPY %reg1028
6042cab237bSDimitry Andric   // %reg1029 = SHR8ri %reg1029, 7, implicit dead %eflags
605*b5893f02SDimitry Andric   // insert => %reg1030 = COPY %reg1029
6062cab237bSDimitry Andric   // %reg1030 = ADD8rr killed %reg1029, killed %reg1028, implicit dead %eflags
607f22ef01cSRoman Divacky 
608139f7f9bSDimitry Andric   if (!isPlainlyKilled(MI, regC, LIS))
609f22ef01cSRoman Divacky     return false;
610f22ef01cSRoman Divacky 
611f22ef01cSRoman Divacky   // Ok, we have something like:
6122cab237bSDimitry Andric   // %reg1030 = ADD8rr killed %reg1028, killed %reg1029, implicit dead %eflags
613f22ef01cSRoman Divacky   // let's see if it's worth commuting it.
614f22ef01cSRoman Divacky 
615f22ef01cSRoman Divacky   // Look for situations like this:
6162cab237bSDimitry Andric   // %reg1024 = MOV r1
6172cab237bSDimitry Andric   // %reg1025 = MOV r0
6182cab237bSDimitry Andric   // %reg1026 = ADD %reg1024, %reg1025
619f22ef01cSRoman Divacky   // r0            = MOV %reg1026
620f22ef01cSRoman Divacky   // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
6217ae0e2c9SDimitry Andric   unsigned ToRegA = getMappedReg(regA, DstRegMap);
6227ae0e2c9SDimitry Andric   if (ToRegA) {
623f22ef01cSRoman Divacky     unsigned FromRegB = getMappedReg(regB, SrcRegMap);
624f22ef01cSRoman Divacky     unsigned FromRegC = getMappedReg(regC, SrcRegMap);
62539d628a0SDimitry Andric     bool CompB = FromRegB && regsAreCompatible(FromRegB, ToRegA, TRI);
62639d628a0SDimitry Andric     bool CompC = FromRegC && regsAreCompatible(FromRegC, ToRegA, TRI);
62739d628a0SDimitry Andric 
62839d628a0SDimitry Andric     // Compute if any of the following are true:
62939d628a0SDimitry Andric     // -RegB is not tied to a register and RegC is compatible with RegA.
63039d628a0SDimitry Andric     // -RegB is tied to the wrong physical register, but RegC is.
63139d628a0SDimitry Andric     // -RegB is tied to the wrong physical register, and RegC isn't tied.
63239d628a0SDimitry Andric     if ((!FromRegB && CompC) || (FromRegB && !CompB && (!FromRegC || CompC)))
63339d628a0SDimitry Andric       return true;
63439d628a0SDimitry Andric     // Don't compute if any of the following are true:
63539d628a0SDimitry Andric     // -RegC is not tied to a register and RegB is compatible with RegA.
63639d628a0SDimitry Andric     // -RegC is tied to the wrong physical register, but RegB is.
63739d628a0SDimitry Andric     // -RegC is tied to the wrong physical register, and RegB isn't tied.
63839d628a0SDimitry Andric     if ((!FromRegC && CompB) || (FromRegC && !CompC && (!FromRegB || CompB)))
63939d628a0SDimitry Andric       return false;
6407ae0e2c9SDimitry Andric   }
641f22ef01cSRoman Divacky 
642f22ef01cSRoman Divacky   // If there is a use of regC between its last def (could be livein) and this
643f22ef01cSRoman Divacky   // instruction, then bail.
644f22ef01cSRoman Divacky   unsigned LastDefC = 0;
6453861d79fSDimitry Andric   if (!noUseAfterLastDef(regC, Dist, LastDefC))
646f22ef01cSRoman Divacky     return false;
647f22ef01cSRoman Divacky 
648f22ef01cSRoman Divacky   // If there is a use of regB between its last def (could be livein) and this
649f22ef01cSRoman Divacky   // instruction, then go ahead and make this transformation.
650f22ef01cSRoman Divacky   unsigned LastDefB = 0;
6513861d79fSDimitry Andric   if (!noUseAfterLastDef(regB, Dist, LastDefB))
652f22ef01cSRoman Divacky     return true;
653f22ef01cSRoman Divacky 
654ff0cc061SDimitry Andric   // Look for situation like this:
655ff0cc061SDimitry Andric   // %reg101 = MOV %reg100
656ff0cc061SDimitry Andric   // %reg102 = ...
657ff0cc061SDimitry Andric   // %reg103 = ADD %reg102, %reg101
658ff0cc061SDimitry Andric   // ... = %reg103 ...
659ff0cc061SDimitry Andric   // %reg100 = MOV %reg103
660ff0cc061SDimitry Andric   // If there is a reversed copy chain from reg101 to reg103, commute the ADD
661ff0cc061SDimitry Andric   // to eliminate an otherwise unavoidable copy.
662ff0cc061SDimitry Andric   // FIXME:
663ff0cc061SDimitry Andric   // We can extend the logic further: If an pair of operands in an insn has
664ff0cc061SDimitry Andric   // been merged, the insn could be regarded as a virtual copy, and the virtual
665ff0cc061SDimitry Andric   // copy could also be used to construct a copy chain.
666ff0cc061SDimitry Andric   // To more generally minimize register copies, ideally the logic of two addr
667ff0cc061SDimitry Andric   // instruction pass should be integrated with register allocation pass where
668ff0cc061SDimitry Andric   // interference graph is available.
669a580b014SDimitry Andric   if (isRevCopyChain(regC, regA, MaxDataFlowEdge))
670ff0cc061SDimitry Andric     return true;
671ff0cc061SDimitry Andric 
672a580b014SDimitry Andric   if (isRevCopyChain(regB, regA, MaxDataFlowEdge))
673ff0cc061SDimitry Andric     return false;
674ff0cc061SDimitry Andric 
675f22ef01cSRoman Divacky   // Since there are no intervening uses for both registers, then commute
676f22ef01cSRoman Divacky   // if the def of regC is closer. Its live interval is shorter.
677f22ef01cSRoman Divacky   return LastDefB && LastDefC && LastDefC > LastDefB;
678f22ef01cSRoman Divacky }
679f22ef01cSRoman Divacky 
6807d523365SDimitry Andric /// Commute a two-address instruction and update the basic block, distance map,
6817d523365SDimitry Andric /// and live variables if needed. Return true if it is successful.
commuteInstruction(MachineInstr * MI,unsigned DstIdx,unsigned RegBIdx,unsigned RegCIdx,unsigned Dist)6827d523365SDimitry Andric bool TwoAddressInstructionPass::commuteInstruction(MachineInstr *MI,
683d88c1a5aSDimitry Andric                                                    unsigned DstIdx,
6847d523365SDimitry Andric                                                    unsigned RegBIdx,
6857d523365SDimitry Andric                                                    unsigned RegCIdx,
6867d523365SDimitry Andric                                                    unsigned Dist) {
6877d523365SDimitry Andric   unsigned RegC = MI->getOperand(RegCIdx).getReg();
6884ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "2addr: COMMUTING  : " << *MI);
6893ca95b02SDimitry Andric   MachineInstr *NewMI = TII->commuteInstruction(*MI, false, RegBIdx, RegCIdx);
690f22ef01cSRoman Divacky 
69191bc56edSDimitry Andric   if (NewMI == nullptr) {
6924ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
693f22ef01cSRoman Divacky     return false;
694f22ef01cSRoman Divacky   }
695f22ef01cSRoman Divacky 
6964ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
697139f7f9bSDimitry Andric   assert(NewMI == MI &&
698139f7f9bSDimitry Andric          "TargetInstrInfo::commuteInstruction() should not return a new "
699139f7f9bSDimitry Andric          "instruction unless it was requested.");
700f22ef01cSRoman Divacky 
701f22ef01cSRoman Divacky   // Update source register map.
702f22ef01cSRoman Divacky   unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
703f22ef01cSRoman Divacky   if (FromRegC) {
704d88c1a5aSDimitry Andric     unsigned RegA = MI->getOperand(DstIdx).getReg();
705f22ef01cSRoman Divacky     SrcRegMap[RegA] = FromRegC;
706f22ef01cSRoman Divacky   }
707f22ef01cSRoman Divacky 
708f22ef01cSRoman Divacky   return true;
709f22ef01cSRoman Divacky }
710f22ef01cSRoman Divacky 
7117d523365SDimitry Andric /// Return true if it is profitable to convert the given 2-address instruction
7127d523365SDimitry Andric /// to a 3-address one.
713f22ef01cSRoman Divacky bool
isProfitableToConv3Addr(unsigned RegA,unsigned RegB)7143b0f4066SDimitry Andric TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
715f22ef01cSRoman Divacky   // Look for situations like this:
7162cab237bSDimitry Andric   // %reg1024 = MOV r1
7172cab237bSDimitry Andric   // %reg1025 = MOV r0
7182cab237bSDimitry Andric   // %reg1026 = ADD %reg1024, %reg1025
719f22ef01cSRoman Divacky   // r2            = MOV %reg1026
720f22ef01cSRoman Divacky   // Turn ADD into a 3-address instruction to avoid a copy.
7213b0f4066SDimitry Andric   unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
7223b0f4066SDimitry Andric   if (!FromRegB)
7233b0f4066SDimitry Andric     return false;
724f22ef01cSRoman Divacky   unsigned ToRegA = getMappedReg(RegA, DstRegMap);
7253b0f4066SDimitry Andric   return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
726f22ef01cSRoman Divacky }
727f22ef01cSRoman Divacky 
7287d523365SDimitry Andric /// Convert the specified two-address instruction into a three address one.
7297d523365SDimitry Andric /// Return true if this transformation was successful.
730f22ef01cSRoman Divacky bool
convertInstTo3Addr(MachineBasicBlock::iterator & mi,MachineBasicBlock::iterator & nmi,unsigned RegA,unsigned RegB,unsigned Dist)7313861d79fSDimitry Andric TwoAddressInstructionPass::convertInstTo3Addr(MachineBasicBlock::iterator &mi,
732f22ef01cSRoman Divacky                                               MachineBasicBlock::iterator &nmi,
7332754fe60SDimitry Andric                                               unsigned RegA, unsigned RegB,
7342754fe60SDimitry Andric                                               unsigned Dist) {
7353861d79fSDimitry Andric   // FIXME: Why does convertToThreeAddress() need an iterator reference?
7367d523365SDimitry Andric   MachineFunction::iterator MFI = MBB->getIterator();
7373ca95b02SDimitry Andric   MachineInstr *NewMI = TII->convertToThreeAddress(MFI, *mi, LV);
7387d523365SDimitry Andric   assert(MBB->getIterator() == MFI &&
7397d523365SDimitry Andric          "convertToThreeAddress changed iterator reference");
7403861d79fSDimitry Andric   if (!NewMI)
7413861d79fSDimitry Andric     return false;
7423861d79fSDimitry Andric 
7434ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
7444ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "2addr:         TO 3-ADDR: " << *NewMI);
745f22ef01cSRoman Divacky   bool Sunk = false;
746f22ef01cSRoman Divacky 
747139f7f9bSDimitry Andric   if (LIS)
7483ca95b02SDimitry Andric     LIS->ReplaceMachineInstrInMaps(*mi, *NewMI);
7497ae0e2c9SDimitry Andric 
750f22ef01cSRoman Divacky   if (NewMI->findRegisterUseOperand(RegB, false, TRI))
751f22ef01cSRoman Divacky     // FIXME: Temporary workaround. If the new instruction doesn't
752f22ef01cSRoman Divacky     // uses RegB, convertToThreeAddress must have created more
753f22ef01cSRoman Divacky     // then one instruction.
7543861d79fSDimitry Andric     Sunk = sink3AddrInstruction(NewMI, RegB, mi);
755f22ef01cSRoman Divacky 
7563861d79fSDimitry Andric   MBB->erase(mi); // Nuke the old inst.
757f22ef01cSRoman Divacky 
758f22ef01cSRoman Divacky   if (!Sunk) {
759f22ef01cSRoman Divacky     DistanceMap.insert(std::make_pair(NewMI, Dist));
760f22ef01cSRoman Divacky     mi = NewMI;
76191bc56edSDimitry Andric     nmi = std::next(mi);
762f22ef01cSRoman Divacky   }
7632cab237bSDimitry Andric   else
7642cab237bSDimitry Andric     SunkInstrs.insert(NewMI);
7652754fe60SDimitry Andric 
7662754fe60SDimitry Andric   // Update source and destination register maps.
7672754fe60SDimitry Andric   SrcRegMap.erase(RegA);
7682754fe60SDimitry Andric   DstRegMap.erase(RegB);
769f22ef01cSRoman Divacky   return true;
770f22ef01cSRoman Divacky }
771f22ef01cSRoman Divacky 
7727d523365SDimitry Andric /// Scan forward recursively for only uses, update maps if the use is a copy or
7737d523365SDimitry Andric /// a two-address instruction.
7743b0f4066SDimitry Andric void
scanUses(unsigned DstReg)7753861d79fSDimitry Andric TwoAddressInstructionPass::scanUses(unsigned DstReg) {
7763b0f4066SDimitry Andric   SmallVector<unsigned, 4> VirtRegPairs;
7773b0f4066SDimitry Andric   bool IsDstPhys;
7783b0f4066SDimitry Andric   bool IsCopy = false;
7793b0f4066SDimitry Andric   unsigned NewReg = 0;
7803b0f4066SDimitry Andric   unsigned Reg = DstReg;
7813b0f4066SDimitry Andric   while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
7823b0f4066SDimitry Andric                                                       NewReg, IsDstPhys)) {
78339d628a0SDimitry Andric     if (IsCopy && !Processed.insert(UseMI).second)
7843b0f4066SDimitry Andric       break;
7853b0f4066SDimitry Andric 
7863b0f4066SDimitry Andric     DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
7873b0f4066SDimitry Andric     if (DI != DistanceMap.end())
7883b0f4066SDimitry Andric       // Earlier in the same MBB.Reached via a back edge.
7893b0f4066SDimitry Andric       break;
7903b0f4066SDimitry Andric 
7913b0f4066SDimitry Andric     if (IsDstPhys) {
7923b0f4066SDimitry Andric       VirtRegPairs.push_back(NewReg);
7933b0f4066SDimitry Andric       break;
7943b0f4066SDimitry Andric     }
7953b0f4066SDimitry Andric     bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
7963b0f4066SDimitry Andric     if (!isNew)
7973b0f4066SDimitry Andric       assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
7983b0f4066SDimitry Andric     VirtRegPairs.push_back(NewReg);
7993b0f4066SDimitry Andric     Reg = NewReg;
8003b0f4066SDimitry Andric   }
8013b0f4066SDimitry Andric 
8023b0f4066SDimitry Andric   if (!VirtRegPairs.empty()) {
8033b0f4066SDimitry Andric     unsigned ToReg = VirtRegPairs.back();
8043b0f4066SDimitry Andric     VirtRegPairs.pop_back();
8053b0f4066SDimitry Andric     while (!VirtRegPairs.empty()) {
8063b0f4066SDimitry Andric       unsigned FromReg = VirtRegPairs.back();
8073b0f4066SDimitry Andric       VirtRegPairs.pop_back();
8083b0f4066SDimitry Andric       bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
8093b0f4066SDimitry Andric       if (!isNew)
8103b0f4066SDimitry Andric         assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
8113b0f4066SDimitry Andric       ToReg = FromReg;
8123b0f4066SDimitry Andric     }
8133b0f4066SDimitry Andric     bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
8143b0f4066SDimitry Andric     if (!isNew)
8153b0f4066SDimitry Andric       assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
8163b0f4066SDimitry Andric   }
8173b0f4066SDimitry Andric }
8183b0f4066SDimitry Andric 
8197d523365SDimitry Andric /// If the specified instruction is not yet processed, process it if it's a
8207d523365SDimitry Andric /// copy. For a copy instruction, we find the physical registers the
821f22ef01cSRoman Divacky /// source and destination registers might be mapped to. These are kept in
822f22ef01cSRoman Divacky /// point-to maps used to determine future optimizations. e.g.
823f22ef01cSRoman Divacky /// v1024 = mov r0
824f22ef01cSRoman Divacky /// v1025 = mov r1
825f22ef01cSRoman Divacky /// v1026 = add v1024, v1025
826f22ef01cSRoman Divacky /// r1    = mov r1026
827f22ef01cSRoman Divacky /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
828f22ef01cSRoman Divacky /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
829f22ef01cSRoman Divacky /// potentially joined with r1 on the output side. It's worthwhile to commute
830f22ef01cSRoman Divacky /// 'add' to eliminate a copy.
processCopy(MachineInstr * MI)8313861d79fSDimitry Andric void TwoAddressInstructionPass::processCopy(MachineInstr *MI) {
832f22ef01cSRoman Divacky   if (Processed.count(MI))
833f22ef01cSRoman Divacky     return;
834f22ef01cSRoman Divacky 
835f22ef01cSRoman Divacky   bool IsSrcPhys, IsDstPhys;
836f22ef01cSRoman Divacky   unsigned SrcReg, DstReg;
837f22ef01cSRoman Divacky   if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
838f22ef01cSRoman Divacky     return;
839f22ef01cSRoman Divacky 
840f22ef01cSRoman Divacky   if (IsDstPhys && !IsSrcPhys)
841f22ef01cSRoman Divacky     DstRegMap.insert(std::make_pair(SrcReg, DstReg));
842f22ef01cSRoman Divacky   else if (!IsDstPhys && IsSrcPhys) {
843f22ef01cSRoman Divacky     bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
844f22ef01cSRoman Divacky     if (!isNew)
845f22ef01cSRoman Divacky       assert(SrcRegMap[DstReg] == SrcReg &&
846f22ef01cSRoman Divacky              "Can't map to two src physical registers!");
847f22ef01cSRoman Divacky 
8483861d79fSDimitry Andric     scanUses(DstReg);
849f22ef01cSRoman Divacky   }
850f22ef01cSRoman Divacky 
851f22ef01cSRoman Divacky   Processed.insert(MI);
852f22ef01cSRoman Divacky }
853f22ef01cSRoman Divacky 
8547d523365SDimitry Andric /// If there is one more local instruction that reads 'Reg' and it kills 'Reg,
8557d523365SDimitry Andric /// consider moving the instruction below the kill instruction in order to
8567d523365SDimitry Andric /// eliminate the need for the copy.
8573861d79fSDimitry Andric bool TwoAddressInstructionPass::
rescheduleMIBelowKill(MachineBasicBlock::iterator & mi,MachineBasicBlock::iterator & nmi,unsigned Reg)8583861d79fSDimitry Andric rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
859dff0c46cSDimitry Andric                       MachineBasicBlock::iterator &nmi,
860dff0c46cSDimitry Andric                       unsigned Reg) {
861139f7f9bSDimitry Andric   // Bail immediately if we don't have LV or LIS available. We use them to find
862139f7f9bSDimitry Andric   // kills efficiently.
863139f7f9bSDimitry Andric   if (!LV && !LIS)
8647ae0e2c9SDimitry Andric     return false;
8657ae0e2c9SDimitry Andric 
866dff0c46cSDimitry Andric   MachineInstr *MI = &*mi;
867dff0c46cSDimitry Andric   DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
868dff0c46cSDimitry Andric   if (DI == DistanceMap.end())
869dff0c46cSDimitry Andric     // Must be created from unfolded load. Don't waste time trying this.
870dff0c46cSDimitry Andric     return false;
871dff0c46cSDimitry Andric 
87291bc56edSDimitry Andric   MachineInstr *KillMI = nullptr;
873139f7f9bSDimitry Andric   if (LIS) {
874139f7f9bSDimitry Andric     LiveInterval &LI = LIS->getInterval(Reg);
875139f7f9bSDimitry Andric     assert(LI.end() != LI.begin() &&
876139f7f9bSDimitry Andric            "Reg should not have empty live interval.");
877139f7f9bSDimitry Andric 
878139f7f9bSDimitry Andric     SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
879139f7f9bSDimitry Andric     LiveInterval::const_iterator I = LI.find(MBBEndIdx);
880139f7f9bSDimitry Andric     if (I != LI.end() && I->start < MBBEndIdx)
881139f7f9bSDimitry Andric       return false;
882139f7f9bSDimitry Andric 
883139f7f9bSDimitry Andric     --I;
884139f7f9bSDimitry Andric     KillMI = LIS->getInstructionFromIndex(I->end);
885139f7f9bSDimitry Andric   } else {
886139f7f9bSDimitry Andric     KillMI = LV->getVarInfo(Reg).findKill(MBB);
887139f7f9bSDimitry Andric   }
8887ae0e2c9SDimitry Andric   if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
889dff0c46cSDimitry Andric     // Don't mess with copies, they may be coalesced later.
890dff0c46cSDimitry Andric     return false;
891dff0c46cSDimitry Andric 
892dff0c46cSDimitry Andric   if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
893dff0c46cSDimitry Andric       KillMI->isBranch() || KillMI->isTerminator())
894dff0c46cSDimitry Andric     // Don't move pass calls, etc.
895dff0c46cSDimitry Andric     return false;
896dff0c46cSDimitry Andric 
897dff0c46cSDimitry Andric   unsigned DstReg;
898dff0c46cSDimitry Andric   if (isTwoAddrUse(*KillMI, Reg, DstReg))
899dff0c46cSDimitry Andric     return false;
900dff0c46cSDimitry Andric 
901dff0c46cSDimitry Andric   bool SeenStore = true;
902ff0cc061SDimitry Andric   if (!MI->isSafeToMove(AA, SeenStore))
903dff0c46cSDimitry Andric     return false;
904dff0c46cSDimitry Andric 
9053ca95b02SDimitry Andric   if (TII->getInstrLatency(InstrItins, *MI) > 1)
906dff0c46cSDimitry Andric     // FIXME: Needs more sophisticated heuristics.
907dff0c46cSDimitry Andric     return false;
908dff0c46cSDimitry Andric 
9096c4bc1bdSDimitry Andric   SmallVector<unsigned, 2> Uses;
9106c4bc1bdSDimitry Andric   SmallVector<unsigned, 2> Kills;
9116c4bc1bdSDimitry Andric   SmallVector<unsigned, 2> Defs;
9127d523365SDimitry Andric   for (const MachineOperand &MO : MI->operands()) {
913dff0c46cSDimitry Andric     if (!MO.isReg())
914dff0c46cSDimitry Andric       continue;
915dff0c46cSDimitry Andric     unsigned MOReg = MO.getReg();
916dff0c46cSDimitry Andric     if (!MOReg)
917dff0c46cSDimitry Andric       continue;
918dff0c46cSDimitry Andric     if (MO.isDef())
9196c4bc1bdSDimitry Andric       Defs.push_back(MOReg);
920dff0c46cSDimitry Andric     else {
9216c4bc1bdSDimitry Andric       Uses.push_back(MOReg);
922139f7f9bSDimitry Andric       if (MOReg != Reg && (MO.isKill() ||
923139f7f9bSDimitry Andric                            (LIS && isPlainlyKilled(MI, MOReg, LIS))))
9246c4bc1bdSDimitry Andric         Kills.push_back(MOReg);
925dff0c46cSDimitry Andric     }
926dff0c46cSDimitry Andric   }
927dff0c46cSDimitry Andric 
928dff0c46cSDimitry Andric   // Move the copies connected to MI down as well.
929139f7f9bSDimitry Andric   MachineBasicBlock::iterator Begin = MI;
93091bc56edSDimitry Andric   MachineBasicBlock::iterator AfterMI = std::next(Begin);
931139f7f9bSDimitry Andric   MachineBasicBlock::iterator End = AfterMI;
932*b5893f02SDimitry Andric   while (End != MBB->end()) {
933*b5893f02SDimitry Andric     End = skipDebugInstructionsForward(End, MBB->end());
934*b5893f02SDimitry Andric     if (End->isCopy() && regOverlapsSet(Defs, End->getOperand(1).getReg(), TRI))
9356c4bc1bdSDimitry Andric       Defs.push_back(End->getOperand(0).getReg());
936*b5893f02SDimitry Andric     else
937*b5893f02SDimitry Andric       break;
938139f7f9bSDimitry Andric     ++End;
939dff0c46cSDimitry Andric   }
940dff0c46cSDimitry Andric 
9417a7e6055SDimitry Andric   // Check if the reschedule will not break dependencies.
942dff0c46cSDimitry Andric   unsigned NumVisited = 0;
943dff0c46cSDimitry Andric   MachineBasicBlock::iterator KillPos = KillMI;
944dff0c46cSDimitry Andric   ++KillPos;
9452cab237bSDimitry Andric   for (MachineInstr &OtherMI : make_range(End, KillPos)) {
9464ba319b5SDimitry Andric     // Debug instructions cannot be counted against the limit.
9474ba319b5SDimitry Andric     if (OtherMI.isDebugInstr())
948dff0c46cSDimitry Andric       continue;
949dff0c46cSDimitry Andric     if (NumVisited > 10)  // FIXME: Arbitrary limit to reduce compile time cost.
950dff0c46cSDimitry Andric       return false;
951dff0c46cSDimitry Andric     ++NumVisited;
9523ca95b02SDimitry Andric     if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
9533ca95b02SDimitry Andric         OtherMI.isBranch() || OtherMI.isTerminator())
954dff0c46cSDimitry Andric       // Don't move pass calls, etc.
955dff0c46cSDimitry Andric       return false;
9563ca95b02SDimitry Andric     for (const MachineOperand &MO : OtherMI.operands()) {
957dff0c46cSDimitry Andric       if (!MO.isReg())
958dff0c46cSDimitry Andric         continue;
959dff0c46cSDimitry Andric       unsigned MOReg = MO.getReg();
960dff0c46cSDimitry Andric       if (!MOReg)
961dff0c46cSDimitry Andric         continue;
962dff0c46cSDimitry Andric       if (MO.isDef()) {
9636c4bc1bdSDimitry Andric         if (regOverlapsSet(Uses, MOReg, TRI))
964dff0c46cSDimitry Andric           // Physical register use would be clobbered.
965dff0c46cSDimitry Andric           return false;
9666c4bc1bdSDimitry Andric         if (!MO.isDead() && regOverlapsSet(Defs, MOReg, TRI))
967dff0c46cSDimitry Andric           // May clobber a physical register def.
968dff0c46cSDimitry Andric           // FIXME: This may be too conservative. It's ok if the instruction
969dff0c46cSDimitry Andric           // is sunken completely below the use.
970dff0c46cSDimitry Andric           return false;
971dff0c46cSDimitry Andric       } else {
9726c4bc1bdSDimitry Andric         if (regOverlapsSet(Defs, MOReg, TRI))
973dff0c46cSDimitry Andric           return false;
9743ca95b02SDimitry Andric         bool isKill =
9753ca95b02SDimitry Andric             MO.isKill() || (LIS && isPlainlyKilled(&OtherMI, MOReg, LIS));
9766c4bc1bdSDimitry Andric         if (MOReg != Reg && ((isKill && regOverlapsSet(Uses, MOReg, TRI)) ||
9776c4bc1bdSDimitry Andric                              regOverlapsSet(Kills, MOReg, TRI)))
978dff0c46cSDimitry Andric           // Don't want to extend other live ranges and update kills.
979dff0c46cSDimitry Andric           return false;
980139f7f9bSDimitry Andric         if (MOReg == Reg && !isKill)
9817ae0e2c9SDimitry Andric           // We can't schedule across a use of the register in question.
9827ae0e2c9SDimitry Andric           return false;
9837ae0e2c9SDimitry Andric         // Ensure that if this is register in question, its the kill we expect.
9843ca95b02SDimitry Andric         assert((MOReg != Reg || &OtherMI == KillMI) &&
9857ae0e2c9SDimitry Andric                "Found multiple kills of a register in a basic block");
986dff0c46cSDimitry Andric       }
987dff0c46cSDimitry Andric     }
988dff0c46cSDimitry Andric   }
989dff0c46cSDimitry Andric 
990dff0c46cSDimitry Andric   // Move debug info as well.
9914ba319b5SDimitry Andric   while (Begin != MBB->begin() && std::prev(Begin)->isDebugInstr())
992139f7f9bSDimitry Andric     --Begin;
993139f7f9bSDimitry Andric 
994139f7f9bSDimitry Andric   nmi = End;
995139f7f9bSDimitry Andric   MachineBasicBlock::iterator InsertPos = KillPos;
996139f7f9bSDimitry Andric   if (LIS) {
997139f7f9bSDimitry Andric     // We have to move the copies first so that the MBB is still well-formed
998139f7f9bSDimitry Andric     // when calling handleMove().
999139f7f9bSDimitry Andric     for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) {
10003ca95b02SDimitry Andric       auto CopyMI = MBBI++;
1001139f7f9bSDimitry Andric       MBB->splice(InsertPos, MBB, CopyMI);
10023ca95b02SDimitry Andric       LIS->handleMove(*CopyMI);
1003139f7f9bSDimitry Andric       InsertPos = CopyMI;
1004139f7f9bSDimitry Andric     }
100591bc56edSDimitry Andric     End = std::next(MachineBasicBlock::iterator(MI));
1006139f7f9bSDimitry Andric   }
1007dff0c46cSDimitry Andric 
1008dff0c46cSDimitry Andric   // Copies following MI may have been moved as well.
1009139f7f9bSDimitry Andric   MBB->splice(InsertPos, MBB, Begin, End);
1010dff0c46cSDimitry Andric   DistanceMap.erase(DI);
1011dff0c46cSDimitry Andric 
1012dff0c46cSDimitry Andric   // Update live variables
1013139f7f9bSDimitry Andric   if (LIS) {
10143ca95b02SDimitry Andric     LIS->handleMove(*MI);
1015139f7f9bSDimitry Andric   } else {
10163ca95b02SDimitry Andric     LV->removeVirtualRegisterKilled(Reg, *KillMI);
10173ca95b02SDimitry Andric     LV->addVirtualRegisterKilled(Reg, *MI);
1018139f7f9bSDimitry Andric   }
1019dff0c46cSDimitry Andric 
10204ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
1021dff0c46cSDimitry Andric   return true;
1022dff0c46cSDimitry Andric }
1023dff0c46cSDimitry Andric 
10247d523365SDimitry Andric /// Return true if the re-scheduling will put the given instruction too close
10257d523365SDimitry Andric /// to the defs of its register dependencies.
isDefTooClose(unsigned Reg,unsigned Dist,MachineInstr * MI)1026dff0c46cSDimitry Andric bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
10273861d79fSDimitry Andric                                               MachineInstr *MI) {
102891bc56edSDimitry Andric   for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
102991bc56edSDimitry Andric     if (DefMI.getParent() != MBB || DefMI.isCopy() || DefMI.isCopyLike())
1030dff0c46cSDimitry Andric       continue;
103191bc56edSDimitry Andric     if (&DefMI == MI)
1032dff0c46cSDimitry Andric       return true; // MI is defining something KillMI uses
103391bc56edSDimitry Andric     DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(&DefMI);
1034dff0c46cSDimitry Andric     if (DDI == DistanceMap.end())
1035dff0c46cSDimitry Andric       return true;  // Below MI
1036dff0c46cSDimitry Andric     unsigned DefDist = DDI->second;
1037dff0c46cSDimitry Andric     assert(Dist > DefDist && "Visited def already?");
10383ca95b02SDimitry Andric     if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist))
1039dff0c46cSDimitry Andric       return true;
1040dff0c46cSDimitry Andric   }
1041dff0c46cSDimitry Andric   return false;
1042dff0c46cSDimitry Andric }
1043dff0c46cSDimitry Andric 
10447d523365SDimitry Andric /// If there is one more local instruction that reads 'Reg' and it kills 'Reg,
10457d523365SDimitry Andric /// consider moving the kill instruction above the current two-address
10467d523365SDimitry Andric /// instruction in order to eliminate the need for the copy.
10473861d79fSDimitry Andric bool TwoAddressInstructionPass::
rescheduleKillAboveMI(MachineBasicBlock::iterator & mi,MachineBasicBlock::iterator & nmi,unsigned Reg)10483861d79fSDimitry Andric rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
1049dff0c46cSDimitry Andric                       MachineBasicBlock::iterator &nmi,
1050dff0c46cSDimitry Andric                       unsigned Reg) {
1051139f7f9bSDimitry Andric   // Bail immediately if we don't have LV or LIS available. We use them to find
1052139f7f9bSDimitry Andric   // kills efficiently.
1053139f7f9bSDimitry Andric   if (!LV && !LIS)
10547ae0e2c9SDimitry Andric     return false;
10557ae0e2c9SDimitry Andric 
1056dff0c46cSDimitry Andric   MachineInstr *MI = &*mi;
1057dff0c46cSDimitry Andric   DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
1058dff0c46cSDimitry Andric   if (DI == DistanceMap.end())
1059dff0c46cSDimitry Andric     // Must be created from unfolded load. Don't waste time trying this.
1060dff0c46cSDimitry Andric     return false;
1061dff0c46cSDimitry Andric 
106291bc56edSDimitry Andric   MachineInstr *KillMI = nullptr;
1063139f7f9bSDimitry Andric   if (LIS) {
1064139f7f9bSDimitry Andric     LiveInterval &LI = LIS->getInterval(Reg);
1065139f7f9bSDimitry Andric     assert(LI.end() != LI.begin() &&
1066139f7f9bSDimitry Andric            "Reg should not have empty live interval.");
1067139f7f9bSDimitry Andric 
1068139f7f9bSDimitry Andric     SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
1069139f7f9bSDimitry Andric     LiveInterval::const_iterator I = LI.find(MBBEndIdx);
1070139f7f9bSDimitry Andric     if (I != LI.end() && I->start < MBBEndIdx)
1071139f7f9bSDimitry Andric       return false;
1072139f7f9bSDimitry Andric 
1073139f7f9bSDimitry Andric     --I;
1074139f7f9bSDimitry Andric     KillMI = LIS->getInstructionFromIndex(I->end);
1075139f7f9bSDimitry Andric   } else {
1076139f7f9bSDimitry Andric     KillMI = LV->getVarInfo(Reg).findKill(MBB);
1077139f7f9bSDimitry Andric   }
10787ae0e2c9SDimitry Andric   if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
1079dff0c46cSDimitry Andric     // Don't mess with copies, they may be coalesced later.
1080dff0c46cSDimitry Andric     return false;
1081dff0c46cSDimitry Andric 
1082dff0c46cSDimitry Andric   unsigned DstReg;
1083dff0c46cSDimitry Andric   if (isTwoAddrUse(*KillMI, Reg, DstReg))
1084dff0c46cSDimitry Andric     return false;
1085dff0c46cSDimitry Andric 
1086dff0c46cSDimitry Andric   bool SeenStore = true;
1087ff0cc061SDimitry Andric   if (!KillMI->isSafeToMove(AA, SeenStore))
1088dff0c46cSDimitry Andric     return false;
1089dff0c46cSDimitry Andric 
1090dff0c46cSDimitry Andric   SmallSet<unsigned, 2> Uses;
1091dff0c46cSDimitry Andric   SmallSet<unsigned, 2> Kills;
1092dff0c46cSDimitry Andric   SmallSet<unsigned, 2> Defs;
1093dff0c46cSDimitry Andric   SmallSet<unsigned, 2> LiveDefs;
10947d523365SDimitry Andric   for (const MachineOperand &MO : KillMI->operands()) {
1095dff0c46cSDimitry Andric     if (!MO.isReg())
1096dff0c46cSDimitry Andric       continue;
1097dff0c46cSDimitry Andric     unsigned MOReg = MO.getReg();
1098dff0c46cSDimitry Andric     if (MO.isUse()) {
1099dff0c46cSDimitry Andric       if (!MOReg)
1100dff0c46cSDimitry Andric         continue;
11013861d79fSDimitry Andric       if (isDefTooClose(MOReg, DI->second, MI))
1102dff0c46cSDimitry Andric         return false;
1103139f7f9bSDimitry Andric       bool isKill = MO.isKill() || (LIS && isPlainlyKilled(KillMI, MOReg, LIS));
1104139f7f9bSDimitry Andric       if (MOReg == Reg && !isKill)
11057ae0e2c9SDimitry Andric         return false;
1106dff0c46cSDimitry Andric       Uses.insert(MOReg);
1107139f7f9bSDimitry Andric       if (isKill && MOReg != Reg)
1108dff0c46cSDimitry Andric         Kills.insert(MOReg);
1109dff0c46cSDimitry Andric     } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1110dff0c46cSDimitry Andric       Defs.insert(MOReg);
1111dff0c46cSDimitry Andric       if (!MO.isDead())
1112dff0c46cSDimitry Andric         LiveDefs.insert(MOReg);
1113dff0c46cSDimitry Andric     }
1114dff0c46cSDimitry Andric   }
1115dff0c46cSDimitry Andric 
1116dff0c46cSDimitry Andric   // Check if the reschedule will not break depedencies.
1117dff0c46cSDimitry Andric   unsigned NumVisited = 0;
11183ca95b02SDimitry Andric   for (MachineInstr &OtherMI :
11192cab237bSDimitry Andric        make_range(mi, MachineBasicBlock::iterator(KillMI))) {
11204ba319b5SDimitry Andric     // Debug instructions cannot be counted against the limit.
11214ba319b5SDimitry Andric     if (OtherMI.isDebugInstr())
1122dff0c46cSDimitry Andric       continue;
1123dff0c46cSDimitry Andric     if (NumVisited > 10)  // FIXME: Arbitrary limit to reduce compile time cost.
1124dff0c46cSDimitry Andric       return false;
1125dff0c46cSDimitry Andric     ++NumVisited;
11263ca95b02SDimitry Andric     if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
11273ca95b02SDimitry Andric         OtherMI.isBranch() || OtherMI.isTerminator())
1128dff0c46cSDimitry Andric       // Don't move pass calls, etc.
1129dff0c46cSDimitry Andric       return false;
1130dff0c46cSDimitry Andric     SmallVector<unsigned, 2> OtherDefs;
11313ca95b02SDimitry Andric     for (const MachineOperand &MO : OtherMI.operands()) {
1132dff0c46cSDimitry Andric       if (!MO.isReg())
1133dff0c46cSDimitry Andric         continue;
1134dff0c46cSDimitry Andric       unsigned MOReg = MO.getReg();
1135dff0c46cSDimitry Andric       if (!MOReg)
1136dff0c46cSDimitry Andric         continue;
1137dff0c46cSDimitry Andric       if (MO.isUse()) {
1138dff0c46cSDimitry Andric         if (Defs.count(MOReg))
1139dff0c46cSDimitry Andric           // Moving KillMI can clobber the physical register if the def has
1140dff0c46cSDimitry Andric           // not been seen.
1141dff0c46cSDimitry Andric           return false;
1142dff0c46cSDimitry Andric         if (Kills.count(MOReg))
1143dff0c46cSDimitry Andric           // Don't want to extend other live ranges and update kills.
1144dff0c46cSDimitry Andric           return false;
11453ca95b02SDimitry Andric         if (&OtherMI != MI && MOReg == Reg &&
11463ca95b02SDimitry Andric             !(MO.isKill() || (LIS && isPlainlyKilled(&OtherMI, MOReg, LIS))))
11477ae0e2c9SDimitry Andric           // We can't schedule across a use of the register in question.
11487ae0e2c9SDimitry Andric           return false;
1149dff0c46cSDimitry Andric       } else {
1150dff0c46cSDimitry Andric         OtherDefs.push_back(MOReg);
1151dff0c46cSDimitry Andric       }
1152dff0c46cSDimitry Andric     }
1153dff0c46cSDimitry Andric 
1154dff0c46cSDimitry Andric     for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
1155dff0c46cSDimitry Andric       unsigned MOReg = OtherDefs[i];
1156dff0c46cSDimitry Andric       if (Uses.count(MOReg))
1157dff0c46cSDimitry Andric         return false;
1158dff0c46cSDimitry Andric       if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1159dff0c46cSDimitry Andric           LiveDefs.count(MOReg))
1160dff0c46cSDimitry Andric         return false;
1161dff0c46cSDimitry Andric       // Physical register def is seen.
1162dff0c46cSDimitry Andric       Defs.erase(MOReg);
1163dff0c46cSDimitry Andric     }
1164dff0c46cSDimitry Andric   }
1165dff0c46cSDimitry Andric 
1166dff0c46cSDimitry Andric   // Move the old kill above MI, don't forget to move debug info as well.
1167dff0c46cSDimitry Andric   MachineBasicBlock::iterator InsertPos = mi;
11684ba319b5SDimitry Andric   while (InsertPos != MBB->begin() && std::prev(InsertPos)->isDebugInstr())
1169dff0c46cSDimitry Andric     --InsertPos;
1170dff0c46cSDimitry Andric   MachineBasicBlock::iterator From = KillMI;
117191bc56edSDimitry Andric   MachineBasicBlock::iterator To = std::next(From);
11724ba319b5SDimitry Andric   while (std::prev(From)->isDebugInstr())
1173dff0c46cSDimitry Andric     --From;
1174dff0c46cSDimitry Andric   MBB->splice(InsertPos, MBB, From, To);
1175dff0c46cSDimitry Andric 
117691bc56edSDimitry Andric   nmi = std::prev(InsertPos); // Backtrack so we process the moved instr.
1177dff0c46cSDimitry Andric   DistanceMap.erase(DI);
1178dff0c46cSDimitry Andric 
1179dff0c46cSDimitry Andric   // Update live variables
1180139f7f9bSDimitry Andric   if (LIS) {
11813ca95b02SDimitry Andric     LIS->handleMove(*KillMI);
1182139f7f9bSDimitry Andric   } else {
11833ca95b02SDimitry Andric     LV->removeVirtualRegisterKilled(Reg, *KillMI);
11843ca95b02SDimitry Andric     LV->addVirtualRegisterKilled(Reg, *MI);
1185139f7f9bSDimitry Andric   }
11867ae0e2c9SDimitry Andric 
11874ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
1188dff0c46cSDimitry Andric   return true;
1189dff0c46cSDimitry Andric }
1190dff0c46cSDimitry Andric 
11917d523365SDimitry Andric /// Tries to commute the operand 'BaseOpIdx' and some other operand in the
11927d523365SDimitry Andric /// given machine instruction to improve opportunities for coalescing and
11937d523365SDimitry Andric /// elimination of a register to register copy.
11947d523365SDimitry Andric ///
11957d523365SDimitry Andric /// 'DstOpIdx' specifies the index of MI def operand.
11967d523365SDimitry Andric /// 'BaseOpKilled' specifies if the register associated with 'BaseOpIdx'
11977d523365SDimitry Andric /// operand is killed by the given instruction.
11987d523365SDimitry Andric /// The 'Dist' arguments provides the distance of MI from the start of the
11997d523365SDimitry Andric /// current basic block and it is used to determine if it is profitable
12007d523365SDimitry Andric /// to commute operands in the instruction.
12017d523365SDimitry Andric ///
12027d523365SDimitry Andric /// Returns true if the transformation happened. Otherwise, returns false.
tryInstructionCommute(MachineInstr * MI,unsigned DstOpIdx,unsigned BaseOpIdx,bool BaseOpKilled,unsigned Dist)12037d523365SDimitry Andric bool TwoAddressInstructionPass::tryInstructionCommute(MachineInstr *MI,
12047d523365SDimitry Andric                                                       unsigned DstOpIdx,
12057d523365SDimitry Andric                                                       unsigned BaseOpIdx,
12067d523365SDimitry Andric                                                       bool BaseOpKilled,
12077d523365SDimitry Andric                                                       unsigned Dist) {
1208d88c1a5aSDimitry Andric   if (!MI->isCommutable())
1209d88c1a5aSDimitry Andric     return false;
1210d88c1a5aSDimitry Andric 
12114ba319b5SDimitry Andric   bool MadeChange = false;
12127d523365SDimitry Andric   unsigned DstOpReg = MI->getOperand(DstOpIdx).getReg();
12137d523365SDimitry Andric   unsigned BaseOpReg = MI->getOperand(BaseOpIdx).getReg();
12147d523365SDimitry Andric   unsigned OpsNum = MI->getDesc().getNumOperands();
12157d523365SDimitry Andric   unsigned OtherOpIdx = MI->getDesc().getNumDefs();
12167d523365SDimitry Andric   for (; OtherOpIdx < OpsNum; OtherOpIdx++) {
12177d523365SDimitry Andric     // The call of findCommutedOpIndices below only checks if BaseOpIdx
12187d523365SDimitry Andric     // and OtherOpIdx are commutable, it does not really search for
12197d523365SDimitry Andric     // other commutable operands and does not change the values of passed
12207d523365SDimitry Andric     // variables.
1221d88c1a5aSDimitry Andric     if (OtherOpIdx == BaseOpIdx || !MI->getOperand(OtherOpIdx).isReg() ||
12223ca95b02SDimitry Andric         !TII->findCommutedOpIndices(*MI, BaseOpIdx, OtherOpIdx))
12237d523365SDimitry Andric       continue;
12247d523365SDimitry Andric 
12257d523365SDimitry Andric     unsigned OtherOpReg = MI->getOperand(OtherOpIdx).getReg();
12267d523365SDimitry Andric     bool AggressiveCommute = false;
12277d523365SDimitry Andric 
12287d523365SDimitry Andric     // If OtherOp dies but BaseOp does not, swap the OtherOp and BaseOp
12297d523365SDimitry Andric     // operands. This makes the live ranges of DstOp and OtherOp joinable.
12304ba319b5SDimitry Andric     bool OtherOpKilled = isKilled(*MI, OtherOpReg, MRI, TII, LIS, false);
12314ba319b5SDimitry Andric     bool DoCommute = !BaseOpKilled && OtherOpKilled;
12327d523365SDimitry Andric 
12337d523365SDimitry Andric     if (!DoCommute &&
12347d523365SDimitry Andric         isProfitableToCommute(DstOpReg, BaseOpReg, OtherOpReg, MI, Dist)) {
12357d523365SDimitry Andric       DoCommute = true;
12367d523365SDimitry Andric       AggressiveCommute = true;
12377d523365SDimitry Andric     }
12387d523365SDimitry Andric 
12397d523365SDimitry Andric     // If it's profitable to commute, try to do so.
1240d88c1a5aSDimitry Andric     if (DoCommute && commuteInstruction(MI, DstOpIdx, BaseOpIdx, OtherOpIdx,
1241d88c1a5aSDimitry Andric                                         Dist)) {
12424ba319b5SDimitry Andric       MadeChange = true;
12437d523365SDimitry Andric       ++NumCommuted;
12444ba319b5SDimitry Andric       if (AggressiveCommute) {
12457d523365SDimitry Andric         ++NumAggrCommuted;
12464ba319b5SDimitry Andric         // There might be more than two commutable operands, update BaseOp and
12474ba319b5SDimitry Andric         // continue scanning.
12484ba319b5SDimitry Andric         BaseOpReg = OtherOpReg;
12494ba319b5SDimitry Andric         BaseOpKilled = OtherOpKilled;
12504ba319b5SDimitry Andric         continue;
12514ba319b5SDimitry Andric       }
12524ba319b5SDimitry Andric       // If this was a commute based on kill, we won't do better continuing.
12534ba319b5SDimitry Andric       return MadeChange;
12547d523365SDimitry Andric     }
12557d523365SDimitry Andric   }
12564ba319b5SDimitry Andric   return MadeChange;
12577d523365SDimitry Andric }
12587d523365SDimitry Andric 
12597d523365SDimitry Andric /// For the case where an instruction has a single pair of tied register
12607d523365SDimitry Andric /// operands, attempt some transformations that may either eliminate the tied
12617d523365SDimitry Andric /// operands or improve the opportunities for coalescing away the register copy.
12627d523365SDimitry Andric /// Returns true if no copy needs to be inserted to untie mi's operands
12637d523365SDimitry Andric /// (either because they were untied, or because mi was rescheduled, and will
12647d523365SDimitry Andric /// be visited again later). If the shouldOnlyCommute flag is true, only
12657d523365SDimitry Andric /// instruction commutation is attempted.
1266f22ef01cSRoman Divacky bool TwoAddressInstructionPass::
tryInstructionTransform(MachineBasicBlock::iterator & mi,MachineBasicBlock::iterator & nmi,unsigned SrcIdx,unsigned DstIdx,unsigned Dist,bool shouldOnlyCommute)12673861d79fSDimitry Andric tryInstructionTransform(MachineBasicBlock::iterator &mi,
1268f22ef01cSRoman Divacky                         MachineBasicBlock::iterator &nmi,
1269139f7f9bSDimitry Andric                         unsigned SrcIdx, unsigned DstIdx,
1270139f7f9bSDimitry Andric                         unsigned Dist, bool shouldOnlyCommute) {
1271dff0c46cSDimitry Andric   if (OptLevel == CodeGenOpt::None)
1272dff0c46cSDimitry Andric     return false;
1273dff0c46cSDimitry Andric 
1274dff0c46cSDimitry Andric   MachineInstr &MI = *mi;
1275dff0c46cSDimitry Andric   unsigned regA = MI.getOperand(DstIdx).getReg();
1276dff0c46cSDimitry Andric   unsigned regB = MI.getOperand(SrcIdx).getReg();
1277f22ef01cSRoman Divacky 
1278f22ef01cSRoman Divacky   assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1279f22ef01cSRoman Divacky          "cannot make instruction into two-address form");
1280139f7f9bSDimitry Andric   bool regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
12817ae0e2c9SDimitry Andric 
12827ae0e2c9SDimitry Andric   if (TargetRegisterInfo::isVirtualRegister(regA))
12833861d79fSDimitry Andric     scanUses(regA);
1284f22ef01cSRoman Divacky 
12857d523365SDimitry Andric   bool Commuted = tryInstructionCommute(&MI, DstIdx, SrcIdx, regBKilled, Dist);
1286f22ef01cSRoman Divacky 
12873dac3a9bSDimitry Andric   // If the instruction is convertible to 3 Addr, instead
12883dac3a9bSDimitry Andric   // of returning try 3 Addr transformation aggresively and
12893dac3a9bSDimitry Andric   // use this variable to check later. Because it might be better.
12903dac3a9bSDimitry Andric   // For example, we can just use `leal (%rsi,%rdi), %eax` and `ret`
12913dac3a9bSDimitry Andric   // instead of the following code.
12923dac3a9bSDimitry Andric   //   addl     %esi, %edi
12933dac3a9bSDimitry Andric   //   movl     %edi, %eax
12943dac3a9bSDimitry Andric   //   ret
12957d523365SDimitry Andric   if (Commuted && !MI.isConvertibleTo3Addr())
1296f22ef01cSRoman Divacky     return false;
1297f22ef01cSRoman Divacky 
1298139f7f9bSDimitry Andric   if (shouldOnlyCommute)
1299139f7f9bSDimitry Andric     return false;
1300139f7f9bSDimitry Andric 
1301dff0c46cSDimitry Andric   // If there is one more use of regB later in the same MBB, consider
1302dff0c46cSDimitry Andric   // re-schedule this MI below it.
1303875ed548SDimitry Andric   if (!Commuted && EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) {
1304dff0c46cSDimitry Andric     ++NumReSchedDowns;
1305dff0c46cSDimitry Andric     return true;
1306dff0c46cSDimitry Andric   }
1307dff0c46cSDimitry Andric 
13087d523365SDimitry Andric   // If we commuted, regB may have changed so we should re-sample it to avoid
13097d523365SDimitry Andric   // confusing the three address conversion below.
13107d523365SDimitry Andric   if (Commuted) {
13117d523365SDimitry Andric     regB = MI.getOperand(SrcIdx).getReg();
13127d523365SDimitry Andric     regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
13137d523365SDimitry Andric   }
13147d523365SDimitry Andric 
1315dff0c46cSDimitry Andric   if (MI.isConvertibleTo3Addr()) {
1316f22ef01cSRoman Divacky     // This instruction is potentially convertible to a true
1317f22ef01cSRoman Divacky     // three-address instruction.  Check if it is profitable.
13183b0f4066SDimitry Andric     if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
1319f22ef01cSRoman Divacky       // Try to convert it.
13203861d79fSDimitry Andric       if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
1321f22ef01cSRoman Divacky         ++NumConvertedTo3Addr;
1322f22ef01cSRoman Divacky         return true; // Done with this instruction.
1323f22ef01cSRoman Divacky       }
1324f22ef01cSRoman Divacky     }
1325f22ef01cSRoman Divacky   }
1326ffd1746dSEd Schouten 
13273dac3a9bSDimitry Andric   // Return if it is commuted but 3 addr conversion is failed.
1328875ed548SDimitry Andric   if (Commuted)
13293dac3a9bSDimitry Andric     return false;
13303dac3a9bSDimitry Andric 
1331dff0c46cSDimitry Andric   // If there is one more use of regB later in the same MBB, consider
1332dff0c46cSDimitry Andric   // re-schedule it before this MI if it's legal.
1333284c1978SDimitry Andric   if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) {
1334dff0c46cSDimitry Andric     ++NumReSchedUps;
1335dff0c46cSDimitry Andric     return true;
1336dff0c46cSDimitry Andric   }
1337dff0c46cSDimitry Andric 
1338ffd1746dSEd Schouten   // If this is an instruction with a load folded into it, try unfolding
1339ffd1746dSEd Schouten   // the load, e.g. avoid this:
1340ffd1746dSEd Schouten   //   movq %rdx, %rcx
1341ffd1746dSEd Schouten   //   addq (%rax), %rcx
1342ffd1746dSEd Schouten   // in favor of this:
1343ffd1746dSEd Schouten   //   movq (%rax), %rcx
1344ffd1746dSEd Schouten   //   addq %rdx, %rcx
1345ffd1746dSEd Schouten   // because it's preferable to schedule a load than a register copy.
1346dff0c46cSDimitry Andric   if (MI.mayLoad() && !regBKilled) {
1347ffd1746dSEd Schouten     // Determine if a load can be unfolded.
1348ffd1746dSEd Schouten     unsigned LoadRegIndex;
1349ffd1746dSEd Schouten     unsigned NewOpc =
1350dff0c46cSDimitry Andric       TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1351ffd1746dSEd Schouten                                       /*UnfoldLoad=*/true,
1352ffd1746dSEd Schouten                                       /*UnfoldStore=*/false,
1353ffd1746dSEd Schouten                                       &LoadRegIndex);
1354ffd1746dSEd Schouten     if (NewOpc != 0) {
135517a519f9SDimitry Andric       const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
135617a519f9SDimitry Andric       if (UnfoldMCID.getNumDefs() == 1) {
1357ffd1746dSEd Schouten         // Unfold the load.
13584ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "2addr:   UNFOLDING: " << MI);
1359ffd1746dSEd Schouten         const TargetRegisterClass *RC =
13607ae0e2c9SDimitry Andric           TRI->getAllocatableClass(
13617ae0e2c9SDimitry Andric             TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
1362ffd1746dSEd Schouten         unsigned Reg = MRI->createVirtualRegister(RC);
1363ffd1746dSEd Schouten         SmallVector<MachineInstr *, 2> NewMIs;
13643ca95b02SDimitry Andric         if (!TII->unfoldMemoryOperand(*MF, MI, Reg,
13653ca95b02SDimitry Andric                                       /*UnfoldLoad=*/true,
13663ca95b02SDimitry Andric                                       /*UnfoldStore=*/false, NewMIs)) {
13674ba319b5SDimitry Andric           LLVM_DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1368ffd1746dSEd Schouten           return false;
1369ffd1746dSEd Schouten         }
1370ffd1746dSEd Schouten         assert(NewMIs.size() == 2 &&
1371ffd1746dSEd Schouten                "Unfolded a load into multiple instructions!");
1372ffd1746dSEd Schouten         // The load was previously folded, so this is the only use.
1373ffd1746dSEd Schouten         NewMIs[1]->addRegisterKilled(Reg, TRI);
1374ffd1746dSEd Schouten 
1375ffd1746dSEd Schouten         // Tentatively insert the instructions into the block so that they
1376ffd1746dSEd Schouten         // look "normal" to the transformation logic.
13773861d79fSDimitry Andric         MBB->insert(mi, NewMIs[0]);
13783861d79fSDimitry Andric         MBB->insert(mi, NewMIs[1]);
1379ffd1746dSEd Schouten 
13804ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "2addr:    NEW LOAD: " << *NewMIs[0]
1381ffd1746dSEd Schouten                           << "2addr:    NEW INST: " << *NewMIs[1]);
1382ffd1746dSEd Schouten 
1383ffd1746dSEd Schouten         // Transform the instruction, now that it no longer has a load.
1384ffd1746dSEd Schouten         unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1385ffd1746dSEd Schouten         unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1386ffd1746dSEd Schouten         MachineBasicBlock::iterator NewMI = NewMIs[1];
1387139f7f9bSDimitry Andric         bool TransformResult =
1388139f7f9bSDimitry Andric           tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true);
1389139f7f9bSDimitry Andric         (void)TransformResult;
1390139f7f9bSDimitry Andric         assert(!TransformResult &&
1391139f7f9bSDimitry Andric                "tryInstructionTransform() should return false.");
1392139f7f9bSDimitry Andric         if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1393ffd1746dSEd Schouten           // Success, or at least we made an improvement. Keep the unfolded
1394ffd1746dSEd Schouten           // instructions and discard the original.
1395ffd1746dSEd Schouten           if (LV) {
1396dff0c46cSDimitry Andric             for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1397dff0c46cSDimitry Andric               MachineOperand &MO = MI.getOperand(i);
13982754fe60SDimitry Andric               if (MO.isReg() &&
1399ffd1746dSEd Schouten                   TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1400ffd1746dSEd Schouten                 if (MO.isUse()) {
1401ffd1746dSEd Schouten                   if (MO.isKill()) {
1402ffd1746dSEd Schouten                     if (NewMIs[0]->killsRegister(MO.getReg()))
14033ca95b02SDimitry Andric                       LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[0]);
1404ffd1746dSEd Schouten                     else {
1405ffd1746dSEd Schouten                       assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1406ffd1746dSEd Schouten                              "Kill missing after load unfold!");
14073ca95b02SDimitry Andric                       LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[1]);
1408ffd1746dSEd Schouten                     }
1409ffd1746dSEd Schouten                   }
14103ca95b02SDimitry Andric                 } else if (LV->removeVirtualRegisterDead(MO.getReg(), MI)) {
1411ffd1746dSEd Schouten                   if (NewMIs[1]->registerDefIsDead(MO.getReg()))
14123ca95b02SDimitry Andric                     LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[1]);
1413ffd1746dSEd Schouten                   else {
1414ffd1746dSEd Schouten                     assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1415ffd1746dSEd Schouten                            "Dead flag missing after load unfold!");
14163ca95b02SDimitry Andric                     LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[0]);
1417ffd1746dSEd Schouten                   }
1418ffd1746dSEd Schouten                 }
1419ffd1746dSEd Schouten               }
1420ffd1746dSEd Schouten             }
14213ca95b02SDimitry Andric             LV->addVirtualRegisterKilled(Reg, *NewMIs[1]);
1422ffd1746dSEd Schouten           }
1423139f7f9bSDimitry Andric 
1424139f7f9bSDimitry Andric           SmallVector<unsigned, 4> OrigRegs;
1425139f7f9bSDimitry Andric           if (LIS) {
14267d523365SDimitry Andric             for (const MachineOperand &MO : MI.operands()) {
14277d523365SDimitry Andric               if (MO.isReg())
14287d523365SDimitry Andric                 OrigRegs.push_back(MO.getReg());
1429139f7f9bSDimitry Andric             }
1430139f7f9bSDimitry Andric           }
1431139f7f9bSDimitry Andric 
1432dff0c46cSDimitry Andric           MI.eraseFromParent();
1433139f7f9bSDimitry Andric 
1434139f7f9bSDimitry Andric           // Update LiveIntervals.
1435139f7f9bSDimitry Andric           if (LIS) {
1436139f7f9bSDimitry Andric             MachineBasicBlock::iterator Begin(NewMIs[0]);
1437139f7f9bSDimitry Andric             MachineBasicBlock::iterator End(NewMIs[1]);
1438139f7f9bSDimitry Andric             LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs);
1439139f7f9bSDimitry Andric           }
1440139f7f9bSDimitry Andric 
1441ffd1746dSEd Schouten           mi = NewMIs[1];
1442ffd1746dSEd Schouten         } else {
1443ffd1746dSEd Schouten           // Transforming didn't eliminate the tie and didn't lead to an
1444ffd1746dSEd Schouten           // improvement. Clean up the unfolded instructions and keep the
1445ffd1746dSEd Schouten           // original.
14464ba319b5SDimitry Andric           LLVM_DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1447ffd1746dSEd Schouten           NewMIs[0]->eraseFromParent();
1448ffd1746dSEd Schouten           NewMIs[1]->eraseFromParent();
1449ffd1746dSEd Schouten         }
1450ffd1746dSEd Schouten       }
1451ffd1746dSEd Schouten     }
1452ffd1746dSEd Schouten   }
1453ffd1746dSEd Schouten 
1454f22ef01cSRoman Divacky   return false;
1455f22ef01cSRoman Divacky }
1456f22ef01cSRoman Divacky 
14577ae0e2c9SDimitry Andric // Collect tied operands of MI that need to be handled.
14587ae0e2c9SDimitry Andric // Rewrite trivial cases immediately.
14597ae0e2c9SDimitry Andric // Return true if any tied operands where found, including the trivial ones.
14607ae0e2c9SDimitry Andric bool TwoAddressInstructionPass::
collectTiedOperands(MachineInstr * MI,TiedOperandMap & TiedOperands)14617ae0e2c9SDimitry Andric collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
14627ae0e2c9SDimitry Andric   const MCInstrDesc &MCID = MI->getDesc();
14637ae0e2c9SDimitry Andric   bool AnyOps = false;
14643861d79fSDimitry Andric   unsigned NumOps = MI->getNumOperands();
14657ae0e2c9SDimitry Andric 
14667ae0e2c9SDimitry Andric   for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
14677ae0e2c9SDimitry Andric     unsigned DstIdx = 0;
14687ae0e2c9SDimitry Andric     if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
14697ae0e2c9SDimitry Andric       continue;
14707ae0e2c9SDimitry Andric     AnyOps = true;
14717ae0e2c9SDimitry Andric     MachineOperand &SrcMO = MI->getOperand(SrcIdx);
14727ae0e2c9SDimitry Andric     MachineOperand &DstMO = MI->getOperand(DstIdx);
14737ae0e2c9SDimitry Andric     unsigned SrcReg = SrcMO.getReg();
14747ae0e2c9SDimitry Andric     unsigned DstReg = DstMO.getReg();
14757ae0e2c9SDimitry Andric     // Tied constraint already satisfied?
14767ae0e2c9SDimitry Andric     if (SrcReg == DstReg)
14777ae0e2c9SDimitry Andric       continue;
14787ae0e2c9SDimitry Andric 
14797ae0e2c9SDimitry Andric     assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
14807ae0e2c9SDimitry Andric 
14812cab237bSDimitry Andric     // Deal with undef uses immediately - simply rewrite the src operand.
148291bc56edSDimitry Andric     if (SrcMO.isUndef() && !DstMO.getSubReg()) {
14837ae0e2c9SDimitry Andric       // Constrain the DstReg register class if required.
14847ae0e2c9SDimitry Andric       if (TargetRegisterInfo::isVirtualRegister(DstReg))
14857ae0e2c9SDimitry Andric         if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
14867ae0e2c9SDimitry Andric                                                              TRI, *MF))
14877ae0e2c9SDimitry Andric           MRI->constrainRegClass(DstReg, RC);
14887ae0e2c9SDimitry Andric       SrcMO.setReg(DstReg);
148991bc56edSDimitry Andric       SrcMO.setSubReg(0);
14904ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
14917ae0e2c9SDimitry Andric       continue;
14927ae0e2c9SDimitry Andric     }
14937ae0e2c9SDimitry Andric     TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
14947ae0e2c9SDimitry Andric   }
14957ae0e2c9SDimitry Andric   return AnyOps;
14967ae0e2c9SDimitry Andric }
14977ae0e2c9SDimitry Andric 
14987ae0e2c9SDimitry Andric // Process a list of tied MI operands that all use the same source register.
14997ae0e2c9SDimitry Andric // The tied pairs are of the form (SrcIdx, DstIdx).
15007ae0e2c9SDimitry Andric void
processTiedPairs(MachineInstr * MI,TiedPairList & TiedPairs,unsigned & Dist)15017ae0e2c9SDimitry Andric TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
15027ae0e2c9SDimitry Andric                                             TiedPairList &TiedPairs,
15037ae0e2c9SDimitry Andric                                             unsigned &Dist) {
15047ae0e2c9SDimitry Andric   bool IsEarlyClobber = false;
1505139f7f9bSDimitry Andric   for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1506139f7f9bSDimitry Andric     const MachineOperand &DstMO = MI->getOperand(TiedPairs[tpi].second);
1507139f7f9bSDimitry Andric     IsEarlyClobber |= DstMO.isEarlyClobber();
1508139f7f9bSDimitry Andric   }
1509139f7f9bSDimitry Andric 
15107ae0e2c9SDimitry Andric   bool RemovedKillFlag = false;
15117ae0e2c9SDimitry Andric   bool AllUsesCopied = true;
15127ae0e2c9SDimitry Andric   unsigned LastCopiedReg = 0;
1513139f7f9bSDimitry Andric   SlotIndex LastCopyIdx;
15147ae0e2c9SDimitry Andric   unsigned RegB = 0;
151591bc56edSDimitry Andric   unsigned SubRegB = 0;
15167ae0e2c9SDimitry Andric   for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
15177ae0e2c9SDimitry Andric     unsigned SrcIdx = TiedPairs[tpi].first;
15187ae0e2c9SDimitry Andric     unsigned DstIdx = TiedPairs[tpi].second;
15197ae0e2c9SDimitry Andric 
15207ae0e2c9SDimitry Andric     const MachineOperand &DstMO = MI->getOperand(DstIdx);
15217ae0e2c9SDimitry Andric     unsigned RegA = DstMO.getReg();
15227ae0e2c9SDimitry Andric 
15237ae0e2c9SDimitry Andric     // Grab RegB from the instruction because it may have changed if the
15247ae0e2c9SDimitry Andric     // instruction was commuted.
15257ae0e2c9SDimitry Andric     RegB = MI->getOperand(SrcIdx).getReg();
152691bc56edSDimitry Andric     SubRegB = MI->getOperand(SrcIdx).getSubReg();
15277ae0e2c9SDimitry Andric 
15287ae0e2c9SDimitry Andric     if (RegA == RegB) {
15297ae0e2c9SDimitry Andric       // The register is tied to multiple destinations (or else we would
15307ae0e2c9SDimitry Andric       // not have continued this far), but this use of the register
15317ae0e2c9SDimitry Andric       // already matches the tied destination.  Leave it.
15327ae0e2c9SDimitry Andric       AllUsesCopied = false;
15337ae0e2c9SDimitry Andric       continue;
15347ae0e2c9SDimitry Andric     }
15357ae0e2c9SDimitry Andric     LastCopiedReg = RegA;
15367ae0e2c9SDimitry Andric 
15377ae0e2c9SDimitry Andric     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
15387ae0e2c9SDimitry Andric            "cannot make instruction into two-address form");
15397ae0e2c9SDimitry Andric 
15407ae0e2c9SDimitry Andric #ifndef NDEBUG
15417ae0e2c9SDimitry Andric     // First, verify that we don't have a use of "a" in the instruction
15427ae0e2c9SDimitry Andric     // (a = b + a for example) because our transformation will not
15437ae0e2c9SDimitry Andric     // work. This should never occur because we are in SSA form.
15447ae0e2c9SDimitry Andric     for (unsigned i = 0; i != MI->getNumOperands(); ++i)
15457ae0e2c9SDimitry Andric       assert(i == DstIdx ||
15467ae0e2c9SDimitry Andric              !MI->getOperand(i).isReg() ||
15477ae0e2c9SDimitry Andric              MI->getOperand(i).getReg() != RegA);
15487ae0e2c9SDimitry Andric #endif
15497ae0e2c9SDimitry Andric 
15507ae0e2c9SDimitry Andric     // Emit a copy.
155191bc56edSDimitry Andric     MachineInstrBuilder MIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
155291bc56edSDimitry Andric                                       TII->get(TargetOpcode::COPY), RegA);
155391bc56edSDimitry Andric     // If this operand is folding a truncation, the truncation now moves to the
155491bc56edSDimitry Andric     // copy so that the register classes remain valid for the operands.
155591bc56edSDimitry Andric     MIB.addReg(RegB, 0, SubRegB);
155691bc56edSDimitry Andric     const TargetRegisterClass *RC = MRI->getRegClass(RegB);
155791bc56edSDimitry Andric     if (SubRegB) {
155891bc56edSDimitry Andric       if (TargetRegisterInfo::isVirtualRegister(RegA)) {
155991bc56edSDimitry Andric         assert(TRI->getMatchingSuperRegClass(RC, MRI->getRegClass(RegA),
156091bc56edSDimitry Andric                                              SubRegB) &&
156191bc56edSDimitry Andric                "tied subregister must be a truncation");
156291bc56edSDimitry Andric         // The superreg class will not be used to constrain the subreg class.
156391bc56edSDimitry Andric         RC = nullptr;
156491bc56edSDimitry Andric       }
156591bc56edSDimitry Andric       else {
156691bc56edSDimitry Andric         assert(TRI->getMatchingSuperReg(RegA, SubRegB, MRI->getRegClass(RegB))
156791bc56edSDimitry Andric                && "tied subregister must be a truncation");
156891bc56edSDimitry Andric       }
156991bc56edSDimitry Andric     }
15707ae0e2c9SDimitry Andric 
15717ae0e2c9SDimitry Andric     // Update DistanceMap.
15727ae0e2c9SDimitry Andric     MachineBasicBlock::iterator PrevMI = MI;
15737ae0e2c9SDimitry Andric     --PrevMI;
15743ca95b02SDimitry Andric     DistanceMap.insert(std::make_pair(&*PrevMI, Dist));
15757ae0e2c9SDimitry Andric     DistanceMap[MI] = ++Dist;
15767ae0e2c9SDimitry Andric 
1577139f7f9bSDimitry Andric     if (LIS) {
15783ca95b02SDimitry Andric       LastCopyIdx = LIS->InsertMachineInstrInMaps(*PrevMI).getRegSlot();
1579139f7f9bSDimitry Andric 
1580139f7f9bSDimitry Andric       if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1581139f7f9bSDimitry Andric         LiveInterval &LI = LIS->getInterval(RegA);
1582139f7f9bSDimitry Andric         VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1583139f7f9bSDimitry Andric         SlotIndex endIdx =
15843ca95b02SDimitry Andric             LIS->getInstructionIndex(*MI).getRegSlot(IsEarlyClobber);
1585f785676fSDimitry Andric         LI.addSegment(LiveInterval::Segment(LastCopyIdx, endIdx, VNI));
1586139f7f9bSDimitry Andric       }
1587139f7f9bSDimitry Andric     }
15887ae0e2c9SDimitry Andric 
15894ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "\t\tprepend:\t" << *MIB);
15907ae0e2c9SDimitry Andric 
15917ae0e2c9SDimitry Andric     MachineOperand &MO = MI->getOperand(SrcIdx);
15927ae0e2c9SDimitry Andric     assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
15937ae0e2c9SDimitry Andric            "inconsistent operand info for 2-reg pass");
15947ae0e2c9SDimitry Andric     if (MO.isKill()) {
15957ae0e2c9SDimitry Andric       MO.setIsKill(false);
15967ae0e2c9SDimitry Andric       RemovedKillFlag = true;
15977ae0e2c9SDimitry Andric     }
15987ae0e2c9SDimitry Andric 
15997ae0e2c9SDimitry Andric     // Make sure regA is a legal regclass for the SrcIdx operand.
16007ae0e2c9SDimitry Andric     if (TargetRegisterInfo::isVirtualRegister(RegA) &&
16017ae0e2c9SDimitry Andric         TargetRegisterInfo::isVirtualRegister(RegB))
160291bc56edSDimitry Andric       MRI->constrainRegClass(RegA, RC);
16037ae0e2c9SDimitry Andric     MO.setReg(RegA);
160491bc56edSDimitry Andric     // The getMatchingSuper asserts guarantee that the register class projected
160591bc56edSDimitry Andric     // by SubRegB is compatible with RegA with no subregister. So regardless of
160691bc56edSDimitry Andric     // whether the dest oper writes a subreg, the source oper should not.
160791bc56edSDimitry Andric     MO.setSubReg(0);
16087ae0e2c9SDimitry Andric 
16097ae0e2c9SDimitry Andric     // Propagate SrcRegMap.
16107ae0e2c9SDimitry Andric     SrcRegMap[RegA] = RegB;
16117ae0e2c9SDimitry Andric   }
16127ae0e2c9SDimitry Andric 
16137ae0e2c9SDimitry Andric   if (AllUsesCopied) {
1614*b5893f02SDimitry Andric     bool ReplacedAllUntiedUses = true;
16157ae0e2c9SDimitry Andric     if (!IsEarlyClobber) {
16167ae0e2c9SDimitry Andric       // Replace other (un-tied) uses of regB with LastCopiedReg.
16177d523365SDimitry Andric       for (MachineOperand &MO : MI->operands()) {
1618*b5893f02SDimitry Andric         if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1619*b5893f02SDimitry Andric           if (MO.getSubReg() == SubRegB) {
16207ae0e2c9SDimitry Andric             if (MO.isKill()) {
16217ae0e2c9SDimitry Andric               MO.setIsKill(false);
16227ae0e2c9SDimitry Andric               RemovedKillFlag = true;
16237ae0e2c9SDimitry Andric             }
16247ae0e2c9SDimitry Andric             MO.setReg(LastCopiedReg);
1625*b5893f02SDimitry Andric             MO.setSubReg(0);
1626*b5893f02SDimitry Andric           } else {
1627*b5893f02SDimitry Andric             ReplacedAllUntiedUses = false;
1628*b5893f02SDimitry Andric           }
16297ae0e2c9SDimitry Andric         }
16307ae0e2c9SDimitry Andric       }
16317ae0e2c9SDimitry Andric     }
16327ae0e2c9SDimitry Andric 
16337ae0e2c9SDimitry Andric     // Update live variables for regB.
1634*b5893f02SDimitry Andric     if (RemovedKillFlag && ReplacedAllUntiedUses &&
1635*b5893f02SDimitry Andric         LV && LV->getVarInfo(RegB).removeKill(*MI)) {
16367ae0e2c9SDimitry Andric       MachineBasicBlock::iterator PrevMI = MI;
16377ae0e2c9SDimitry Andric       --PrevMI;
16383ca95b02SDimitry Andric       LV->addVirtualRegisterKilled(RegB, *PrevMI);
16397ae0e2c9SDimitry Andric     }
16407ae0e2c9SDimitry Andric 
1641139f7f9bSDimitry Andric     // Update LiveIntervals.
1642139f7f9bSDimitry Andric     if (LIS) {
1643139f7f9bSDimitry Andric       LiveInterval &LI = LIS->getInterval(RegB);
16443ca95b02SDimitry Andric       SlotIndex MIIdx = LIS->getInstructionIndex(*MI);
1645139f7f9bSDimitry Andric       LiveInterval::const_iterator I = LI.find(MIIdx);
1646139f7f9bSDimitry Andric       assert(I != LI.end() && "RegB must be live-in to use.");
1647139f7f9bSDimitry Andric 
1648139f7f9bSDimitry Andric       SlotIndex UseIdx = MIIdx.getRegSlot(IsEarlyClobber);
1649139f7f9bSDimitry Andric       if (I->end == UseIdx)
1650f785676fSDimitry Andric         LI.removeSegment(LastCopyIdx, UseIdx);
1651139f7f9bSDimitry Andric     }
16527ae0e2c9SDimitry Andric   } else if (RemovedKillFlag) {
16537ae0e2c9SDimitry Andric     // Some tied uses of regB matched their destination registers, so
16547ae0e2c9SDimitry Andric     // regB is still used in this instruction, but a kill flag was
16557ae0e2c9SDimitry Andric     // removed from a different tied use of regB, so now we need to add
16567ae0e2c9SDimitry Andric     // a kill flag to one of the remaining uses of regB.
16577d523365SDimitry Andric     for (MachineOperand &MO : MI->operands()) {
16587ae0e2c9SDimitry Andric       if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
16597ae0e2c9SDimitry Andric         MO.setIsKill(true);
16607ae0e2c9SDimitry Andric         break;
16617ae0e2c9SDimitry Andric       }
16627ae0e2c9SDimitry Andric     }
16637ae0e2c9SDimitry Andric   }
16647ae0e2c9SDimitry Andric }
16657ae0e2c9SDimitry Andric 
16667d523365SDimitry Andric /// Reduce two-address instructions to two operands.
runOnMachineFunction(MachineFunction & Func)16677ae0e2c9SDimitry Andric bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
16687ae0e2c9SDimitry Andric   MF = &Func;
16697ae0e2c9SDimitry Andric   const TargetMachine &TM = MF->getTarget();
16707ae0e2c9SDimitry Andric   MRI = &MF->getRegInfo();
1671ff0cc061SDimitry Andric   TII = MF->getSubtarget().getInstrInfo();
1672ff0cc061SDimitry Andric   TRI = MF->getSubtarget().getRegisterInfo();
1673ff0cc061SDimitry Andric   InstrItins = MF->getSubtarget().getInstrItineraryData();
1674f22ef01cSRoman Divacky   LV = getAnalysisIfAvailable<LiveVariables>();
16757ae0e2c9SDimitry Andric   LIS = getAnalysisIfAvailable<LiveIntervals>();
16765517e702SDimitry Andric   if (auto *AAPass = getAnalysisIfAvailable<AAResultsWrapperPass>())
16775517e702SDimitry Andric     AA = &AAPass->getAAResults();
16785517e702SDimitry Andric   else
16795517e702SDimitry Andric     AA = nullptr;
1680dff0c46cSDimitry Andric   OptLevel = TM.getOptLevel();
16812cab237bSDimitry Andric   // Disable optimizations if requested. We cannot skip the whole pass as some
16822cab237bSDimitry Andric   // fixups are necessary for correctness.
16832cab237bSDimitry Andric   if (skipFunction(Func.getFunction()))
16842cab237bSDimitry Andric     OptLevel = CodeGenOpt::None;
1685f22ef01cSRoman Divacky 
1686f22ef01cSRoman Divacky   bool MadeChange = false;
1687f22ef01cSRoman Divacky 
16884ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
16894ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "********** Function: " << MF->getName() << '\n');
1690f22ef01cSRoman Divacky 
16916122f3e6SDimitry Andric   // This pass takes the function out of SSA form.
16926122f3e6SDimitry Andric   MRI->leaveSSA();
16936122f3e6SDimitry Andric 
16947ae0e2c9SDimitry Andric   TiedOperandMap TiedOperands;
16953861d79fSDimitry Andric   for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
16963861d79fSDimitry Andric        MBBI != MBBE; ++MBBI) {
16977d523365SDimitry Andric     MBB = &*MBBI;
1698f22ef01cSRoman Divacky     unsigned Dist = 0;
1699f22ef01cSRoman Divacky     DistanceMap.clear();
1700f22ef01cSRoman Divacky     SrcRegMap.clear();
1701f22ef01cSRoman Divacky     DstRegMap.clear();
1702f22ef01cSRoman Divacky     Processed.clear();
17032cab237bSDimitry Andric     SunkInstrs.clear();
17043861d79fSDimitry Andric     for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
1705f22ef01cSRoman Divacky          mi != me; ) {
170691bc56edSDimitry Andric       MachineBasicBlock::iterator nmi = std::next(mi);
17072cab237bSDimitry Andric       // Don't revisit an instruction previously converted by target. It may
17082cab237bSDimitry Andric       // contain undef register operands (%noreg), which are not handled.
17094ba319b5SDimitry Andric       if (mi->isDebugInstr() || SunkInstrs.count(&*mi)) {
1710f22ef01cSRoman Divacky         mi = nmi;
1711f22ef01cSRoman Divacky         continue;
1712f22ef01cSRoman Divacky       }
1713f22ef01cSRoman Divacky 
1714139f7f9bSDimitry Andric       // Expand REG_SEQUENCE instructions. This will position mi at the first
1715139f7f9bSDimitry Andric       // expanded instruction.
1716f22ef01cSRoman Divacky       if (mi->isRegSequence())
1717139f7f9bSDimitry Andric         eliminateRegSequence(mi);
1718f22ef01cSRoman Divacky 
17193ca95b02SDimitry Andric       DistanceMap.insert(std::make_pair(&*mi, ++Dist));
1720f22ef01cSRoman Divacky 
17213861d79fSDimitry Andric       processCopy(&*mi);
1722f22ef01cSRoman Divacky 
1723f22ef01cSRoman Divacky       // First scan through all the tied register uses in this instruction
1724f22ef01cSRoman Divacky       // and record a list of pairs of tied operands for each register.
17253ca95b02SDimitry Andric       if (!collectTiedOperands(&*mi, TiedOperands)) {
17267ae0e2c9SDimitry Andric         mi = nmi;
1727f22ef01cSRoman Divacky         continue;
1728f22ef01cSRoman Divacky       }
1729f22ef01cSRoman Divacky 
17307ae0e2c9SDimitry Andric       ++NumTwoAddressInstrs;
17317ae0e2c9SDimitry Andric       MadeChange = true;
17324ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << '\t' << *mi);
1733f22ef01cSRoman Divacky 
17347ae0e2c9SDimitry Andric       // If the instruction has a single pair of tied operands, try some
17357ae0e2c9SDimitry Andric       // transformations that may either eliminate the tied operands or
17367ae0e2c9SDimitry Andric       // improve the opportunities for coalescing away the register copy.
17377ae0e2c9SDimitry Andric       if (TiedOperands.size() == 1) {
1738f785676fSDimitry Andric         SmallVectorImpl<std::pair<unsigned, unsigned>> &TiedPairs
17397ae0e2c9SDimitry Andric           = TiedOperands.begin()->second;
17407ae0e2c9SDimitry Andric         if (TiedPairs.size() == 1) {
17417ae0e2c9SDimitry Andric           unsigned SrcIdx = TiedPairs[0].first;
17427ae0e2c9SDimitry Andric           unsigned DstIdx = TiedPairs[0].second;
17437ae0e2c9SDimitry Andric           unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
17447ae0e2c9SDimitry Andric           unsigned DstReg = mi->getOperand(DstIdx).getReg();
17457ae0e2c9SDimitry Andric           if (SrcReg != DstReg &&
1746139f7f9bSDimitry Andric               tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) {
17477d523365SDimitry Andric             // The tied operands have been eliminated or shifted further down
17487d523365SDimitry Andric             // the block to ease elimination. Continue processing with 'nmi'.
17497ae0e2c9SDimitry Andric             TiedOperands.clear();
17507ae0e2c9SDimitry Andric             mi = nmi;
17517ae0e2c9SDimitry Andric             continue;
17527ae0e2c9SDimitry Andric           }
17537ae0e2c9SDimitry Andric         }
1754f22ef01cSRoman Divacky       }
1755f22ef01cSRoman Divacky 
1756f22ef01cSRoman Divacky       // Now iterate over the information collected above.
17577d523365SDimitry Andric       for (auto &TO : TiedOperands) {
17583ca95b02SDimitry Andric         processTiedPairs(&*mi, TO.second, Dist);
17594ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
17607ae0e2c9SDimitry Andric       }
1761f22ef01cSRoman Divacky 
1762ffd1746dSEd Schouten       // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1763ffd1746dSEd Schouten       if (mi->isInsertSubreg()) {
1764ffd1746dSEd Schouten         // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1765ffd1746dSEd Schouten         // To   %reg:subidx = COPY %subreg
1766ffd1746dSEd Schouten         unsigned SubIdx = mi->getOperand(3).getImm();
1767ffd1746dSEd Schouten         mi->RemoveOperand(3);
1768ffd1746dSEd Schouten         assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1769ffd1746dSEd Schouten         mi->getOperand(0).setSubReg(SubIdx);
17707ae0e2c9SDimitry Andric         mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1771ffd1746dSEd Schouten         mi->RemoveOperand(1);
1772ffd1746dSEd Schouten         mi->setDesc(TII->get(TargetOpcode::COPY));
17734ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
1774ffd1746dSEd Schouten       }
1775ffd1746dSEd Schouten 
1776f22ef01cSRoman Divacky       // Clear TiedOperands here instead of at the top of the loop
1777f22ef01cSRoman Divacky       // since most instructions do not have tied operands.
1778f22ef01cSRoman Divacky       TiedOperands.clear();
1779f22ef01cSRoman Divacky       mi = nmi;
1780f22ef01cSRoman Divacky     }
1781f22ef01cSRoman Divacky   }
1782f22ef01cSRoman Divacky 
1783139f7f9bSDimitry Andric   if (LIS)
1784139f7f9bSDimitry Andric     MF->verify(this, "After two-address instruction pass");
1785f22ef01cSRoman Divacky 
1786f22ef01cSRoman Divacky   return MadeChange;
1787f22ef01cSRoman Divacky }
1788f22ef01cSRoman Divacky 
1789139f7f9bSDimitry Andric /// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process.
1790f22ef01cSRoman Divacky ///
1791139f7f9bSDimitry Andric /// The instruction is turned into a sequence of sub-register copies:
1792139f7f9bSDimitry Andric ///
1793139f7f9bSDimitry Andric ///   %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1
1794139f7f9bSDimitry Andric ///
1795139f7f9bSDimitry Andric /// Becomes:
1796139f7f9bSDimitry Andric ///
17972cab237bSDimitry Andric ///   undef %dst:ssub0 = COPY %v1
17982cab237bSDimitry Andric ///   %dst:ssub1 = COPY %v2
1799139f7f9bSDimitry Andric void TwoAddressInstructionPass::
eliminateRegSequence(MachineBasicBlock::iterator & MBBI)1800139f7f9bSDimitry Andric eliminateRegSequence(MachineBasicBlock::iterator &MBBI) {
18013ca95b02SDimitry Andric   MachineInstr &MI = *MBBI;
18023ca95b02SDimitry Andric   unsigned DstReg = MI.getOperand(0).getReg();
18033ca95b02SDimitry Andric   if (MI.getOperand(0).getSubReg() ||
1804f22ef01cSRoman Divacky       TargetRegisterInfo::isPhysicalRegister(DstReg) ||
18053ca95b02SDimitry Andric       !(MI.getNumOperands() & 1)) {
18064ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << MI);
180791bc56edSDimitry Andric     llvm_unreachable(nullptr);
1808f22ef01cSRoman Divacky   }
1809f22ef01cSRoman Divacky 
1810139f7f9bSDimitry Andric   SmallVector<unsigned, 4> OrigRegs;
1811139f7f9bSDimitry Andric   if (LIS) {
18123ca95b02SDimitry Andric     OrigRegs.push_back(MI.getOperand(0).getReg());
18133ca95b02SDimitry Andric     for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2)
18143ca95b02SDimitry Andric       OrigRegs.push_back(MI.getOperand(i).getReg());
1815139f7f9bSDimitry Andric   }
1816139f7f9bSDimitry Andric 
1817139f7f9bSDimitry Andric   bool DefEmitted = false;
18183ca95b02SDimitry Andric   for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2) {
18193ca95b02SDimitry Andric     MachineOperand &UseMO = MI.getOperand(i);
1820139f7f9bSDimitry Andric     unsigned SrcReg = UseMO.getReg();
18213ca95b02SDimitry Andric     unsigned SubIdx = MI.getOperand(i+1).getImm();
18222cab237bSDimitry Andric     // Nothing needs to be inserted for undef operands.
1823139f7f9bSDimitry Andric     if (UseMO.isUndef())
1824f22ef01cSRoman Divacky       continue;
1825e580952dSDimitry Andric 
1826e580952dSDimitry Andric     // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1827e580952dSDimitry Andric     // might insert a COPY that uses SrcReg after is was killed.
1828139f7f9bSDimitry Andric     bool isKill = UseMO.isKill();
1829e580952dSDimitry Andric     if (isKill)
1830e580952dSDimitry Andric       for (unsigned j = i + 2; j < e; j += 2)
18313ca95b02SDimitry Andric         if (MI.getOperand(j).getReg() == SrcReg) {
18323ca95b02SDimitry Andric           MI.getOperand(j).setIsKill();
1833139f7f9bSDimitry Andric           UseMO.setIsKill(false);
1834e580952dSDimitry Andric           isKill = false;
1835e580952dSDimitry Andric           break;
1836e580952dSDimitry Andric         }
1837e580952dSDimitry Andric 
1838139f7f9bSDimitry Andric     // Insert the sub-register copy.
18393ca95b02SDimitry Andric     MachineInstr *CopyMI = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1840139f7f9bSDimitry Andric                                    TII->get(TargetOpcode::COPY))
18412754fe60SDimitry Andric                                .addReg(DstReg, RegState::Define, SubIdx)
18427a7e6055SDimitry Andric                                .add(UseMO);
1843139f7f9bSDimitry Andric 
18442cab237bSDimitry Andric     // The first def needs an undef flag because there is no live register
1845139f7f9bSDimitry Andric     // before it.
1846139f7f9bSDimitry Andric     if (!DefEmitted) {
1847139f7f9bSDimitry Andric       CopyMI->getOperand(0).setIsUndef(true);
1848139f7f9bSDimitry Andric       // Return an iterator pointing to the first inserted instr.
1849139f7f9bSDimitry Andric       MBBI = CopyMI;
1850139f7f9bSDimitry Andric     }
1851139f7f9bSDimitry Andric     DefEmitted = true;
1852139f7f9bSDimitry Andric 
1853139f7f9bSDimitry Andric     // Update LiveVariables' kill info.
1854dff0c46cSDimitry Andric     if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
18553ca95b02SDimitry Andric       LV->replaceKillInstruction(SrcReg, MI, *CopyMI);
1856139f7f9bSDimitry Andric 
18574ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Inserted: " << *CopyMI);
1858f22ef01cSRoman Divacky   }
1859f22ef01cSRoman Divacky 
1860139f7f9bSDimitry Andric   MachineBasicBlock::iterator EndMBBI =
186191bc56edSDimitry Andric       std::next(MachineBasicBlock::iterator(MI));
1862f22ef01cSRoman Divacky 
1863139f7f9bSDimitry Andric   if (!DefEmitted) {
18644ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Turned: " << MI << " into an IMPLICIT_DEF");
18653ca95b02SDimitry Andric     MI.setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
18663ca95b02SDimitry Andric     for (int j = MI.getNumOperands() - 1, ee = 0; j > ee; --j)
18673ca95b02SDimitry Andric       MI.RemoveOperand(j);
1868f22ef01cSRoman Divacky   } else {
18694ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "Eliminated: " << MI);
18703ca95b02SDimitry Andric     MI.eraseFromParent();
1871f22ef01cSRoman Divacky   }
1872f22ef01cSRoman Divacky 
1873139f7f9bSDimitry Andric   // Udpate LiveIntervals.
1874139f7f9bSDimitry Andric   if (LIS)
1875139f7f9bSDimitry Andric     LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs);
1876f22ef01cSRoman Divacky }
1877