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