blob: 717b07ca0591c8290f217b7466d8eff594eae026 [file] [log] [blame]
Alkis Evlogimenos725021c2003-12-18 13:06:04 +00001//===-- TwoAddressInstructionPass.cpp - Two-Address instruction pass ------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Alkis Evlogimenos725021c2003-12-18 13:06:04 +00007//
8//===----------------------------------------------------------------------===//
9//
Alkis Evlogimenos5e0e6712004-01-04 23:09:24 +000010// This file implements the TwoAddress instruction pass which is used
11// by most register allocators. Two-Address instructions are rewritten
12// from:
13//
14// A = B op C
15//
16// to:
17//
18// A = B
Alkis Evlogimenos32742642004-02-04 22:17:40 +000019// A op= C
Alkis Evlogimenos725021c2003-12-18 13:06:04 +000020//
Alkis Evlogimenos32742642004-02-04 22:17:40 +000021// Note that if a register allocator chooses to use this pass, that it
22// has to be capable of handling the non-SSA nature of these rewritten
23// virtual registers.
24//
25// It is also worth noting that the duplicate operand of the two
26// address instruction is removed.
Chris Lattnerd835aa62004-01-31 21:07:15 +000027//
Alkis Evlogimenos725021c2003-12-18 13:06:04 +000028//===----------------------------------------------------------------------===//
29
Chris Lattnerd835aa62004-01-31 21:07:15 +000030#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/ADT/BitVector.h"
32#include "llvm/ADT/DenseMap.h"
33#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/SmallSet.h"
35#include "llvm/ADT/Statistic.h"
36#include "llvm/Analysis/AliasAnalysis.h"
Jakob Stoklund Olesen24bc5142012-08-03 22:58:34 +000037#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Alkis Evlogimenos725021c2003-12-18 13:06:04 +000038#include "llvm/CodeGen/LiveVariables.h"
Alkis Evlogimenos725021c2003-12-18 13:06:04 +000039#include "llvm/CodeGen/MachineFunctionPass.h"
40#include "llvm/CodeGen/MachineInstr.h"
Bob Wilsona55b8872010-06-15 05:56:31 +000041#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattnera10fff52007-12-31 04:13:23 +000042#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/Function.h"
Evan Cheng30f44ad2011-11-14 19:48:55 +000044#include "llvm/MC/MCInstrItineraries.h"
Andrew Trick608a6982013-04-24 15:54:39 +000045#include "llvm/Support/CommandLine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000046#include "llvm/Support/Debug.h"
47#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000048#include "llvm/Support/raw_ostream.h"
Alkis Evlogimenos725021c2003-12-18 13:06:04 +000049#include "llvm/Target/TargetInstrInfo.h"
50#include "llvm/Target/TargetMachine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000051#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000052#include "llvm/Target/TargetSubtargetInfo.h"
Alkis Evlogimenos725021c2003-12-18 13:06:04 +000053using namespace llvm;
54
Chandler Carruth1b9dde02014-04-22 02:02:50 +000055#define DEBUG_TYPE "twoaddrinstr"
56
Chris Lattneraee775a2006-12-19 22:41:21 +000057STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
58STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
Evan Chengabda6652009-01-25 03:53:59 +000059STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
Chris Lattneraee775a2006-12-19 22:41:21 +000060STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
Evan Cheng5c26bde2008-03-13 06:37:55 +000061STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
Evan Cheng30f44ad2011-11-14 19:48:55 +000062STATISTIC(NumReSchedUps, "Number of instructions re-scheduled up");
63STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down");
Evan Cheng5c26bde2008-03-13 06:37:55 +000064
Andrew Trick608a6982013-04-24 15:54:39 +000065// Temporary flag to disable rescheduling.
66static cl::opt<bool>
67EnableRescheduling("twoaddr-reschedule",
Evan Chengf85a76f2013-05-02 02:07:32 +000068 cl::desc("Coalesce copies by rescheduling (default=true)"),
69 cl::init(true), cl::Hidden);
Andrew Trick608a6982013-04-24 15:54:39 +000070
Evan Cheng5c26bde2008-03-13 06:37:55 +000071namespace {
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +000072class TwoAddressInstructionPass : public MachineFunctionPass {
73 MachineFunction *MF;
74 const TargetInstrInfo *TII;
75 const TargetRegisterInfo *TRI;
76 const InstrItineraryData *InstrItins;
77 MachineRegisterInfo *MRI;
78 LiveVariables *LV;
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +000079 LiveIntervals *LIS;
80 AliasAnalysis *AA;
81 CodeGenOpt::Level OptLevel;
Evan Cheng5c26bde2008-03-13 06:37:55 +000082
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +000083 // The current basic block being processed.
84 MachineBasicBlock *MBB;
85
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +000086 // DistanceMap - Keep track the distance of a MI from the start of the
87 // current basic block.
88 DenseMap<MachineInstr*, unsigned> DistanceMap;
Evan Chengc2f95b52009-03-01 02:03:43 +000089
Jakob Stoklund Olesend788e322012-10-26 22:06:00 +000090 // Set of already processed instructions in the current block.
91 SmallPtrSet<MachineInstr*, 8> Processed;
92
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +000093 // SrcRegMap - A map from virtual registers to physical registers which are
94 // likely targets to be coalesced to due to copies from physical registers to
95 // virtual registers. e.g. v1024 = move r0.
96 DenseMap<unsigned, unsigned> SrcRegMap;
Evan Chengc2f95b52009-03-01 02:03:43 +000097
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +000098 // DstRegMap - A map from virtual registers to physical registers which are
99 // likely targets to be coalesced to due to copies to physical registers from
100 // virtual registers. e.g. r1 = move v1024.
101 DenseMap<unsigned, unsigned> DstRegMap;
Evan Chengc2f95b52009-03-01 02:03:43 +0000102
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000103 bool sink3AddrInstruction(MachineInstr *MI, unsigned Reg,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000104 MachineBasicBlock::iterator OldPos);
Evan Chengc5618eb2008-06-18 07:49:14 +0000105
Eric Christopher28919132015-03-03 22:03:03 +0000106 bool isRevCopyChain(unsigned FromReg, unsigned ToReg, int Maxlen);
107
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000108 bool noUseAfterLastDef(unsigned Reg, unsigned Dist, unsigned &LastDef);
Evan Chengabda6652009-01-25 03:53:59 +0000109
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000110 bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000111 MachineInstr *MI, unsigned Dist);
Evan Chengabda6652009-01-25 03:53:59 +0000112
Andrew Kaylor16c4da02015-09-28 20:33:22 +0000113 bool commuteInstruction(MachineInstr *MI,
114 unsigned RegBIdx, unsigned RegCIdx, unsigned Dist);
Evan Chengc2f95b52009-03-01 02:03:43 +0000115
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000116 bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
Evan Cheng09f5be82009-03-30 21:34:07 +0000117
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000118 bool convertInstTo3Addr(MachineBasicBlock::iterator &mi,
119 MachineBasicBlock::iterator &nmi,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000120 unsigned RegA, unsigned RegB, unsigned Dist);
Evan Cheng09f5be82009-03-30 21:34:07 +0000121
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000122 bool isDefTooClose(unsigned Reg, unsigned Dist, MachineInstr *MI);
Evan Cheng30f44ad2011-11-14 19:48:55 +0000123
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000124 bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000125 MachineBasicBlock::iterator &nmi,
126 unsigned Reg);
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000127 bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000128 MachineBasicBlock::iterator &nmi,
129 unsigned Reg);
130
131 bool tryInstructionTransform(MachineBasicBlock::iterator &mi,
Evan Cheng30f44ad2011-11-14 19:48:55 +0000132 MachineBasicBlock::iterator &nmi,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000133 unsigned SrcIdx, unsigned DstIdx,
Cameron Zwarichf05c0cb2013-02-24 00:27:26 +0000134 unsigned Dist, bool shouldOnlyCommute);
Evan Cheng30f44ad2011-11-14 19:48:55 +0000135
Andrew Kaylor16c4da02015-09-28 20:33:22 +0000136 bool tryInstructionCommute(MachineInstr *MI,
137 unsigned DstOpIdx,
138 unsigned BaseOpIdx,
139 bool BaseOpKilled,
140 unsigned Dist);
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000141 void scanUses(unsigned DstReg);
Evan Cheng15fed7a2011-03-02 01:08:17 +0000142
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000143 void processCopy(MachineInstr *MI);
Bob Wilson5c7d9ca2009-09-03 20:58:42 +0000144
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000145 typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList;
146 typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap;
147 bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
148 void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +0000149 void eliminateRegSequence(MachineBasicBlock::iterator&);
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +0000150
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000151public:
152 static char ID; // Pass identification, replacement for typeid
153 TwoAddressInstructionPass() : MachineFunctionPass(ID) {
154 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
155 }
Evan Cheng1e4f5522010-05-17 23:24:12 +0000156
Craig Topper4584cd52014-03-07 09:26:03 +0000157 void getAnalysisUsage(AnalysisUsage &AU) const override {
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000158 AU.setPreservesCFG();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000159 AU.addRequired<AAResultsWrapperPass>();
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000160 AU.addPreserved<LiveVariables>();
161 AU.addPreserved<SlotIndexes>();
162 AU.addPreserved<LiveIntervals>();
163 AU.addPreservedID(MachineLoopInfoID);
164 AU.addPreservedID(MachineDominatorsID);
165 MachineFunctionPass::getAnalysisUsage(AU);
166 }
Devang Patel09f162c2007-05-01 21:15:47 +0000167
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000168 /// runOnMachineFunction - Pass entry point.
Craig Topper4584cd52014-03-07 09:26:03 +0000169 bool runOnMachineFunction(MachineFunction&) override;
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000170};
171} // end anonymous namespace
Alkis Evlogimenos725021c2003-12-18 13:06:04 +0000172
Dan Gohmand78c4002008-05-13 00:00:25 +0000173char TwoAddressInstructionPass::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000174INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
175 "Two-Address instruction pass", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000176INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000177INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000178 "Two-Address instruction pass", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000179
Owen Andersona7aed182010-08-06 18:33:48 +0000180char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
Alkis Evlogimenos71390902003-12-18 22:40:24 +0000181
Cameron Zwarich35c30502013-02-23 04:49:20 +0000182static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg, LiveIntervals *LIS);
183
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000184/// sink3AddrInstruction - A two-address instruction has been converted to a
Evan Cheng5c26bde2008-03-13 06:37:55 +0000185/// three-address instruction to avoid clobbering a register. Try to sink it
Bill Wendling19e3c852008-05-10 00:12:52 +0000186/// past the instruction that would kill the above mentioned register to reduce
187/// register pressure.
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000188bool TwoAddressInstructionPass::
189sink3AddrInstruction(MachineInstr *MI, unsigned SavedReg,
190 MachineBasicBlock::iterator OldPos) {
Eli Friedman8a15a5a2011-09-23 22:41:57 +0000191 // FIXME: Shouldn't we be trying to do this before we three-addressify the
192 // instruction? After this transformation is done, we no longer need
193 // the instruction to be in three-address form.
194
Evan Cheng5c26bde2008-03-13 06:37:55 +0000195 // Check if it's safe to move this instruction.
196 bool SeenStore = true; // Be conservative.
Matthias Braun07066cc2015-05-19 21:22:20 +0000197 if (!MI->isSafeToMove(AA, SeenStore))
Evan Cheng5c26bde2008-03-13 06:37:55 +0000198 return false;
199
200 unsigned DefReg = 0;
201 SmallSet<unsigned, 4> UseRegs;
Bill Wendling19e3c852008-05-10 00:12:52 +0000202
Evan Cheng5c26bde2008-03-13 06:37:55 +0000203 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
204 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000205 if (!MO.isReg())
Evan Cheng5c26bde2008-03-13 06:37:55 +0000206 continue;
207 unsigned MOReg = MO.getReg();
208 if (!MOReg)
209 continue;
210 if (MO.isUse() && MOReg != SavedReg)
211 UseRegs.insert(MO.getReg());
212 if (!MO.isDef())
213 continue;
214 if (MO.isImplicit())
215 // Don't try to move it if it implicitly defines a register.
216 return false;
217 if (DefReg)
218 // For now, don't move any instructions that define multiple registers.
219 return false;
220 DefReg = MO.getReg();
221 }
222
223 // Find the instruction that kills SavedReg.
Craig Topperc0196b12014-04-14 00:51:57 +0000224 MachineInstr *KillMI = nullptr;
Cameron Zwarich35c30502013-02-23 04:49:20 +0000225 if (LIS) {
226 LiveInterval &LI = LIS->getInterval(SavedReg);
227 assert(LI.end() != LI.begin() &&
228 "Reg should not have empty live interval.");
229
230 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
231 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
232 if (I != LI.end() && I->start < MBBEndIdx)
233 return false;
234
235 --I;
236 KillMI = LIS->getInstructionFromIndex(I->end);
237 }
238 if (!KillMI) {
239 for (MachineRegisterInfo::use_nodbg_iterator
240 UI = MRI->use_nodbg_begin(SavedReg),
241 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
Owen Anderson16c6bf42014-03-13 23:12:04 +0000242 MachineOperand &UseMO = *UI;
Cameron Zwarich35c30502013-02-23 04:49:20 +0000243 if (!UseMO.isKill())
244 continue;
245 KillMI = UseMO.getParent();
246 break;
247 }
Evan Cheng5c26bde2008-03-13 06:37:55 +0000248 }
Bill Wendling19e3c852008-05-10 00:12:52 +0000249
Eli Friedman8a15a5a2011-09-23 22:41:57 +0000250 // If we find the instruction that kills SavedReg, and it is in an
251 // appropriate location, we can try to sink the current instruction
252 // past it.
253 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
Jakob Stoklund Olesen420798c2012-08-09 22:08:26 +0000254 KillMI == OldPos || KillMI->isTerminator())
Evan Cheng5c26bde2008-03-13 06:37:55 +0000255 return false;
256
Bill Wendling19e3c852008-05-10 00:12:52 +0000257 // If any of the definitions are used by another instruction between the
258 // position and the kill use, then it's not safe to sink it.
Andrew Trick808a7a62012-02-03 05:12:30 +0000259 //
Bill Wendling19e3c852008-05-10 00:12:52 +0000260 // FIXME: This can be sped up if there is an easy way to query whether an
Evan Chengc5618eb2008-06-18 07:49:14 +0000261 // instruction is before or after another instruction. Then we can use
Bill Wendling19e3c852008-05-10 00:12:52 +0000262 // MachineRegisterInfo def / use instead.
Craig Topperc0196b12014-04-14 00:51:57 +0000263 MachineOperand *KillMO = nullptr;
Evan Cheng5c26bde2008-03-13 06:37:55 +0000264 MachineBasicBlock::iterator KillPos = KillMI;
265 ++KillPos;
Bill Wendling19e3c852008-05-10 00:12:52 +0000266
Evan Chengc5618eb2008-06-18 07:49:14 +0000267 unsigned NumVisited = 0;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000268 for (MachineBasicBlock::iterator I = std::next(OldPos); I != KillPos; ++I) {
Evan Cheng5c26bde2008-03-13 06:37:55 +0000269 MachineInstr *OtherMI = I;
Dale Johannesen12565de2010-02-11 18:22:31 +0000270 // DBG_VALUE cannot be counted against the limit.
271 if (OtherMI->isDebugValue())
272 continue;
Evan Chengc5618eb2008-06-18 07:49:14 +0000273 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
274 return false;
275 ++NumVisited;
Evan Cheng5c26bde2008-03-13 06:37:55 +0000276 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
277 MachineOperand &MO = OtherMI->getOperand(i);
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000278 if (!MO.isReg())
Evan Cheng5c26bde2008-03-13 06:37:55 +0000279 continue;
280 unsigned MOReg = MO.getReg();
281 if (!MOReg)
282 continue;
283 if (DefReg == MOReg)
284 return false;
Bill Wendling19e3c852008-05-10 00:12:52 +0000285
Cameron Zwarich35c30502013-02-23 04:49:20 +0000286 if (MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))) {
Evan Cheng5c26bde2008-03-13 06:37:55 +0000287 if (OtherMI == KillMI && MOReg == SavedReg)
Evan Chengc5618eb2008-06-18 07:49:14 +0000288 // Save the operand that kills the register. We want to unset the kill
289 // marker if we can sink MI past it.
Evan Cheng5c26bde2008-03-13 06:37:55 +0000290 KillMO = &MO;
291 else if (UseRegs.count(MOReg))
292 // One of the uses is killed before the destination.
293 return false;
294 }
295 }
296 }
Jakob Stoklund Olesen420798c2012-08-09 22:08:26 +0000297 assert(KillMO && "Didn't find kill");
Evan Cheng5c26bde2008-03-13 06:37:55 +0000298
Cameron Zwarich35c30502013-02-23 04:49:20 +0000299 if (!LIS) {
300 // Update kill and LV information.
301 KillMO->setIsKill(false);
302 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
303 KillMO->setIsKill(true);
Andrew Trick808a7a62012-02-03 05:12:30 +0000304
Cameron Zwarich35c30502013-02-23 04:49:20 +0000305 if (LV)
306 LV->replaceKillInstruction(SavedReg, KillMI, MI);
307 }
Evan Cheng5c26bde2008-03-13 06:37:55 +0000308
309 // Move instruction to its destination.
310 MBB->remove(MI);
311 MBB->insert(KillPos, MI);
312
Jakob Stoklund Olesen24bc5142012-08-03 22:58:34 +0000313 if (LIS)
314 LIS->handleMove(MI);
315
Evan Cheng5c26bde2008-03-13 06:37:55 +0000316 ++Num3AddrSunk;
317 return true;
318}
319
Eric Christopher28919132015-03-03 22:03:03 +0000320/// getSingleDef -- return the MachineInstr* if it is the single def of the Reg
321/// in current BB.
322static MachineInstr *getSingleDef(unsigned Reg, MachineBasicBlock *BB,
323 const MachineRegisterInfo *MRI) {
324 MachineInstr *Ret = nullptr;
325 for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
326 if (DefMI.getParent() != BB || DefMI.isDebugValue())
327 continue;
328 if (!Ret)
329 Ret = &DefMI;
330 else if (Ret != &DefMI)
331 return nullptr;
332 }
333 return Ret;
334}
335
336/// Check if there is a reversed copy chain from FromReg to ToReg:
337/// %Tmp1 = copy %Tmp2;
338/// %FromReg = copy %Tmp1;
339/// %ToReg = add %FromReg ...
340/// %Tmp2 = copy %ToReg;
341/// MaxLen specifies the maximum length of the copy chain the func
342/// can walk through.
343bool TwoAddressInstructionPass::isRevCopyChain(unsigned FromReg, unsigned ToReg,
344 int Maxlen) {
345 unsigned TmpReg = FromReg;
346 for (int i = 0; i < Maxlen; i++) {
347 MachineInstr *Def = getSingleDef(TmpReg, MBB, MRI);
348 if (!Def || !Def->isCopy())
349 return false;
350
351 TmpReg = Def->getOperand(1).getReg();
352
353 if (TmpReg == ToReg)
354 return true;
355 }
356 return false;
357}
358
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000359/// noUseAfterLastDef - Return true if there are no intervening uses between the
Evan Chengabda6652009-01-25 03:53:59 +0000360/// last instruction in the MBB that defines the specified register and the
361/// two-address instruction which is being processed. It also returns the last
362/// def location by reference
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000363bool TwoAddressInstructionPass::noUseAfterLastDef(unsigned Reg, unsigned Dist,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000364 unsigned &LastDef) {
Evan Chengabda6652009-01-25 03:53:59 +0000365 LastDef = 0;
366 unsigned LastUse = Dist;
Owen Andersonb36376e2014-03-17 19:36:09 +0000367 for (MachineOperand &MO : MRI->reg_operands(Reg)) {
Evan Chengabda6652009-01-25 03:53:59 +0000368 MachineInstr *MI = MO.getParent();
Chris Lattnerb06015a2010-02-09 19:54:29 +0000369 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesenc3adf442010-02-09 02:01:46 +0000370 continue;
Evan Chengabda6652009-01-25 03:53:59 +0000371 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
372 if (DI == DistanceMap.end())
373 continue;
374 if (MO.isUse() && DI->second < LastUse)
375 LastUse = DI->second;
376 if (MO.isDef() && DI->second > LastDef)
377 LastDef = DI->second;
378 }
379
380 return !(LastUse > LastDef && LastUse < Dist);
381}
382
Evan Chengc2f95b52009-03-01 02:03:43 +0000383/// isCopyToReg - Return true if the specified MI is a copy instruction or
384/// a extract_subreg instruction. It also returns the source and destination
385/// registers and whether they are physical registers by reference.
386static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
387 unsigned &SrcReg, unsigned &DstReg,
388 bool &IsSrcPhys, bool &IsDstPhys) {
389 SrcReg = 0;
390 DstReg = 0;
Jakob Stoklund Olesen37c42a32010-07-16 04:45:42 +0000391 if (MI.isCopy()) {
392 DstReg = MI.getOperand(0).getReg();
393 SrcReg = MI.getOperand(1).getReg();
394 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
395 DstReg = MI.getOperand(0).getReg();
396 SrcReg = MI.getOperand(2).getReg();
397 } else
398 return false;
Evan Chengc2f95b52009-03-01 02:03:43 +0000399
Jakob Stoklund Olesen37c42a32010-07-16 04:45:42 +0000400 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
401 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
402 return true;
Evan Chengc2f95b52009-03-01 02:03:43 +0000403}
404
Cameron Zwarichc8964782013-02-21 07:02:28 +0000405/// isPLainlyKilled - Test if the given register value, which is used by the
406// given instruction, is killed by the given instruction.
407static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg,
408 LiveIntervals *LIS) {
409 if (LIS && TargetRegisterInfo::isVirtualRegister(Reg) &&
410 !LIS->isNotInMIMap(MI)) {
411 // FIXME: Sometimes tryInstructionTransform() will add instructions and
412 // test whether they can be folded before keeping them. In this case it
413 // sets a kill before recursively calling tryInstructionTransform() again.
414 // If there is no interval available, we assume that this instruction is
415 // one of those. A kill flag is manually inserted on the operand so the
416 // check below will handle it.
417 LiveInterval &LI = LIS->getInterval(Reg);
418 // This is to match the kill flag version where undefs don't have kill
419 // flags.
420 if (!LI.hasAtLeastOneValue())
421 return false;
422
423 SlotIndex useIdx = LIS->getInstructionIndex(MI);
424 LiveInterval::const_iterator I = LI.find(useIdx);
425 assert(I != LI.end() && "Reg must be live-in to use.");
Cameron Zwarich4e80d9e2013-02-23 04:49:22 +0000426 return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx);
Cameron Zwarichc8964782013-02-21 07:02:28 +0000427 }
428
429 return MI->killsRegister(Reg);
430}
431
Dan Gohmanad3e5492009-04-08 00:15:30 +0000432/// isKilled - Test if the given register value, which is used by the given
433/// instruction, is killed by the given instruction. This looks through
434/// coalescable copies to see if the original value is potentially not killed.
435///
436/// For example, in this code:
437///
438/// %reg1034 = copy %reg1024
439/// %reg1035 = copy %reg1025<kill>
440/// %reg1036 = add %reg1034<kill>, %reg1035<kill>
441///
442/// %reg1034 is not considered to be killed, since it is copied from a
443/// register which is not killed. Treating it as not killed lets the
444/// normal heuristics commute the (two-address) add, which lets
445/// coalescing eliminate the extra copy.
446///
Cameron Zwarich384026b2013-02-21 22:58:42 +0000447/// If allowFalsePositives is true then likely kills are treated as kills even
448/// if it can't be proven that they are kills.
Dan Gohmanad3e5492009-04-08 00:15:30 +0000449static bool isKilled(MachineInstr &MI, unsigned Reg,
450 const MachineRegisterInfo *MRI,
Cameron Zwarich94b204b2013-02-21 04:33:02 +0000451 const TargetInstrInfo *TII,
Cameron Zwarich384026b2013-02-21 22:58:42 +0000452 LiveIntervals *LIS,
453 bool allowFalsePositives) {
Dan Gohmanad3e5492009-04-08 00:15:30 +0000454 MachineInstr *DefMI = &MI;
455 for (;;) {
Cameron Zwarich384026b2013-02-21 22:58:42 +0000456 // All uses of physical registers are likely to be kills.
457 if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
458 (allowFalsePositives || MRI->hasOneUse(Reg)))
459 return true;
Cameron Zwarichc8964782013-02-21 07:02:28 +0000460 if (!isPlainlyKilled(DefMI, Reg, LIS))
Dan Gohmanad3e5492009-04-08 00:15:30 +0000461 return false;
462 if (TargetRegisterInfo::isPhysicalRegister(Reg))
463 return true;
464 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
465 // If there are multiple defs, we can't do a simple analysis, so just
466 // go with what the kill flag says.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000467 if (std::next(Begin) != MRI->def_end())
Dan Gohmanad3e5492009-04-08 00:15:30 +0000468 return true;
Owen Anderson16c6bf42014-03-13 23:12:04 +0000469 DefMI = Begin->getParent();
Dan Gohmanad3e5492009-04-08 00:15:30 +0000470 bool IsSrcPhys, IsDstPhys;
471 unsigned SrcReg, DstReg;
472 // If the def is something other than a copy, then it isn't going to
473 // be coalesced, so follow the kill flag.
474 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
475 return true;
476 Reg = SrcReg;
477 }
478}
479
Evan Chengc2f95b52009-03-01 02:03:43 +0000480/// isTwoAddrUse - Return true if the specified MI uses the specified register
481/// as a two-address use. If so, return the destination register by reference.
482static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
Evan Chengf85a76f2013-05-02 02:07:32 +0000483 for (unsigned i = 0, NumOps = MI.getNumOperands(); i != NumOps; ++i) {
Evan Chengc2f95b52009-03-01 02:03:43 +0000484 const MachineOperand &MO = MI.getOperand(i);
485 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
486 continue;
Evan Cheng1361cbb2009-03-19 20:30:06 +0000487 unsigned ti;
488 if (MI.isRegTiedToDefOperand(i, &ti)) {
Evan Chengc2f95b52009-03-01 02:03:43 +0000489 DstReg = MI.getOperand(ti).getReg();
490 return true;
491 }
492 }
493 return false;
494}
495
496/// findOnlyInterestingUse - Given a register, if has a single in-basic block
497/// use, return the use instruction if it's a copy or a two-address use.
498static
499MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
500 MachineRegisterInfo *MRI,
501 const TargetInstrInfo *TII,
Evan Cheng97871832009-04-14 00:32:25 +0000502 bool &IsCopy,
Evan Chengc2f95b52009-03-01 02:03:43 +0000503 unsigned &DstReg, bool &IsDstPhys) {
Evan Chengf94d6832010-03-03 21:18:38 +0000504 if (!MRI->hasOneNonDBGUse(Reg))
505 // None or more than one use.
Craig Topperc0196b12014-04-14 00:51:57 +0000506 return nullptr;
Owen Anderson16c6bf42014-03-13 23:12:04 +0000507 MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(Reg);
Evan Chengc2f95b52009-03-01 02:03:43 +0000508 if (UseMI.getParent() != MBB)
Craig Topperc0196b12014-04-14 00:51:57 +0000509 return nullptr;
Evan Chengc2f95b52009-03-01 02:03:43 +0000510 unsigned SrcReg;
511 bool IsSrcPhys;
Evan Cheng97871832009-04-14 00:32:25 +0000512 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
513 IsCopy = true;
Evan Chengc2f95b52009-03-01 02:03:43 +0000514 return &UseMI;
Evan Cheng97871832009-04-14 00:32:25 +0000515 }
Evan Chengc2f95b52009-03-01 02:03:43 +0000516 IsDstPhys = false;
Evan Cheng97871832009-04-14 00:32:25 +0000517 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
518 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Chengc2f95b52009-03-01 02:03:43 +0000519 return &UseMI;
Evan Cheng97871832009-04-14 00:32:25 +0000520 }
Craig Topperc0196b12014-04-14 00:51:57 +0000521 return nullptr;
Evan Chengc2f95b52009-03-01 02:03:43 +0000522}
523
524/// getMappedReg - Return the physical register the specified virtual register
525/// might be mapped to.
526static unsigned
527getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
528 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
529 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
530 if (SI == RegMap.end())
531 return 0;
532 Reg = SI->second;
533 }
534 if (TargetRegisterInfo::isPhysicalRegister(Reg))
535 return Reg;
536 return 0;
537}
538
539/// regsAreCompatible - Return true if the two registers are equal or aliased.
540///
541static bool
542regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
543 if (RegA == RegB)
544 return true;
545 if (!RegA || !RegB)
546 return false;
547 return TRI->regsOverlap(RegA, RegB);
548}
549
550
Manman Rencc1dc6d2012-07-25 18:28:13 +0000551/// isProfitableToCommute - Return true if it's potentially profitable to commute
Evan Chengabda6652009-01-25 03:53:59 +0000552/// the two-address instruction that's being processed.
553bool
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000554TwoAddressInstructionPass::
555isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
556 MachineInstr *MI, unsigned Dist) {
Evan Cheng822ddde2011-11-16 18:44:48 +0000557 if (OptLevel == CodeGenOpt::None)
558 return false;
559
Evan Chengabda6652009-01-25 03:53:59 +0000560 // Determine if it's profitable to commute this two address instruction. In
561 // general, we want no uses between this instruction and the definition of
562 // the two-address register.
563 // e.g.
564 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
565 // %reg1029<def> = MOV8rr %reg1028
566 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
567 // insert => %reg1030<def> = MOV8rr %reg1028
568 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
569 // In this case, it might not be possible to coalesce the second MOV8rr
570 // instruction if the first one is coalesced. So it would be profitable to
571 // commute it:
572 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
573 // %reg1029<def> = MOV8rr %reg1028
574 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
575 // insert => %reg1030<def> = MOV8rr %reg1029
Andrew Trick808a7a62012-02-03 05:12:30 +0000576 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
Evan Chengabda6652009-01-25 03:53:59 +0000577
Cameron Zwarich9e722ae2013-02-21 07:02:30 +0000578 if (!isPlainlyKilled(MI, regC, LIS))
Evan Chengabda6652009-01-25 03:53:59 +0000579 return false;
580
581 // Ok, we have something like:
582 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
583 // let's see if it's worth commuting it.
584
Evan Chengc2f95b52009-03-01 02:03:43 +0000585 // Look for situations like this:
586 // %reg1024<def> = MOV r1
587 // %reg1025<def> = MOV r0
588 // %reg1026<def> = ADD %reg1024, %reg1025
589 // r0 = MOV %reg1026
590 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
Evan Chengb64e7b72012-05-03 01:45:13 +0000591 unsigned ToRegA = getMappedReg(regA, DstRegMap);
592 if (ToRegA) {
593 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
594 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
Craig Topper12f0d9e2014-11-05 06:43:02 +0000595 bool CompB = FromRegB && regsAreCompatible(FromRegB, ToRegA, TRI);
596 bool CompC = FromRegC && regsAreCompatible(FromRegC, ToRegA, TRI);
597
598 // Compute if any of the following are true:
599 // -RegB is not tied to a register and RegC is compatible with RegA.
600 // -RegB is tied to the wrong physical register, but RegC is.
601 // -RegB is tied to the wrong physical register, and RegC isn't tied.
602 if ((!FromRegB && CompC) || (FromRegB && !CompB && (!FromRegC || CompC)))
603 return true;
604 // Don't compute if any of the following are true:
605 // -RegC is not tied to a register and RegB is compatible with RegA.
606 // -RegC is tied to the wrong physical register, but RegB is.
607 // -RegC is tied to the wrong physical register, and RegB isn't tied.
608 if ((!FromRegC && CompB) || (FromRegC && !CompC && (!FromRegB || CompB)))
609 return false;
Evan Chengb64e7b72012-05-03 01:45:13 +0000610 }
Evan Chengc2f95b52009-03-01 02:03:43 +0000611
Evan Chengabda6652009-01-25 03:53:59 +0000612 // If there is a use of regC between its last def (could be livein) and this
613 // instruction, then bail.
614 unsigned LastDefC = 0;
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000615 if (!noUseAfterLastDef(regC, Dist, LastDefC))
Evan Chengabda6652009-01-25 03:53:59 +0000616 return false;
617
618 // If there is a use of regB between its last def (could be livein) and this
619 // instruction, then go ahead and make this transformation.
620 unsigned LastDefB = 0;
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000621 if (!noUseAfterLastDef(regB, Dist, LastDefB))
Evan Chengabda6652009-01-25 03:53:59 +0000622 return true;
623
Eric Christopher28919132015-03-03 22:03:03 +0000624 // Look for situation like this:
625 // %reg101 = MOV %reg100
626 // %reg102 = ...
627 // %reg103 = ADD %reg102, %reg101
628 // ... = %reg103 ...
629 // %reg100 = MOV %reg103
630 // If there is a reversed copy chain from reg101 to reg103, commute the ADD
631 // to eliminate an otherwise unavoidable copy.
632 // FIXME:
633 // We can extend the logic further: If an pair of operands in an insn has
634 // been merged, the insn could be regarded as a virtual copy, and the virtual
635 // copy could also be used to construct a copy chain.
636 // To more generally minimize register copies, ideally the logic of two addr
637 // instruction pass should be integrated with register allocation pass where
638 // interference graph is available.
639 if (isRevCopyChain(regC, regA, 3))
640 return true;
641
642 if (isRevCopyChain(regB, regA, 3))
643 return false;
644
Evan Chengabda6652009-01-25 03:53:59 +0000645 // Since there are no intervening uses for both registers, then commute
646 // if the def of regC is closer. Its live interval is shorter.
647 return LastDefB && LastDefC && LastDefC > LastDefB;
648}
649
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000650/// commuteInstruction - Commute a two-address instruction and update the basic
Evan Cheng6d897062009-01-23 23:27:33 +0000651/// block, distance map, and live variables if needed. Return true if it is
652/// successful.
Andrew Kaylor16c4da02015-09-28 20:33:22 +0000653bool TwoAddressInstructionPass::commuteInstruction(MachineInstr *MI,
654 unsigned RegBIdx,
655 unsigned RegCIdx,
656 unsigned Dist) {
657 unsigned RegC = MI->getOperand(RegCIdx).getReg();
David Greeneac9f8192010-01-05 01:24:21 +0000658 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
Andrew Kaylor16c4da02015-09-28 20:33:22 +0000659 MachineInstr *NewMI = TII->commuteInstruction(MI, false, RegBIdx, RegCIdx);
Evan Cheng6d897062009-01-23 23:27:33 +0000660
Craig Topperc0196b12014-04-14 00:51:57 +0000661 if (NewMI == nullptr) {
David Greeneac9f8192010-01-05 01:24:21 +0000662 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
Evan Cheng6d897062009-01-23 23:27:33 +0000663 return false;
664 }
665
David Greeneac9f8192010-01-05 01:24:21 +0000666 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
Cameron Zwariche6907bc2013-02-23 23:13:28 +0000667 assert(NewMI == MI &&
668 "TargetInstrInfo::commuteInstruction() should not return a new "
669 "instruction unless it was requested.");
Evan Chengc2f95b52009-03-01 02:03:43 +0000670
671 // Update source register map.
672 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
673 if (FromRegC) {
674 unsigned RegA = MI->getOperand(0).getReg();
675 SrcRegMap[RegA] = FromRegC;
676 }
677
Evan Cheng6d897062009-01-23 23:27:33 +0000678 return true;
679}
680
Evan Cheng09f5be82009-03-30 21:34:07 +0000681/// isProfitableToConv3Addr - Return true if it is profitable to convert the
682/// given 2-address instruction to a 3-address one.
683bool
Evan Cheng15fed7a2011-03-02 01:08:17 +0000684TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
Evan Cheng09f5be82009-03-30 21:34:07 +0000685 // Look for situations like this:
686 // %reg1024<def> = MOV r1
687 // %reg1025<def> = MOV r0
688 // %reg1026<def> = ADD %reg1024, %reg1025
689 // r2 = MOV %reg1026
690 // Turn ADD into a 3-address instruction to avoid a copy.
Evan Cheng15fed7a2011-03-02 01:08:17 +0000691 unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
692 if (!FromRegB)
693 return false;
Evan Cheng09f5be82009-03-30 21:34:07 +0000694 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
Evan Cheng15fed7a2011-03-02 01:08:17 +0000695 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
Evan Cheng09f5be82009-03-30 21:34:07 +0000696}
697
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000698/// convertInstTo3Addr - Convert the specified two-address instruction into a
Evan Cheng09f5be82009-03-30 21:34:07 +0000699/// three address one. Return true if this transformation was successful.
700bool
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000701TwoAddressInstructionPass::convertInstTo3Addr(MachineBasicBlock::iterator &mi,
Evan Cheng09f5be82009-03-30 21:34:07 +0000702 MachineBasicBlock::iterator &nmi,
Evan Chengd4fcc052011-02-10 02:20:55 +0000703 unsigned RegA, unsigned RegB,
704 unsigned Dist) {
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000705 // FIXME: Why does convertToThreeAddress() need an iterator reference?
706 MachineFunction::iterator MFI = MBB;
707 MachineInstr *NewMI = TII->convertToThreeAddress(MFI, mi, LV);
708 assert(MBB == MFI && "convertToThreeAddress changed iterator reference");
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000709 if (!NewMI)
710 return false;
Evan Cheng09f5be82009-03-30 21:34:07 +0000711
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000712 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
713 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
714 bool Sunk = false;
Jakob Stoklund Olesen24bc5142012-08-03 22:58:34 +0000715
Cameron Zwarich2ad3ca32013-02-20 22:10:02 +0000716 if (LIS)
717 LIS->ReplaceMachineInstrInMaps(mi, NewMI);
Evan Cheng09f5be82009-03-30 21:34:07 +0000718
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000719 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
720 // FIXME: Temporary workaround. If the new instruction doesn't
721 // uses RegB, convertToThreeAddress must have created more
722 // then one instruction.
723 Sunk = sink3AddrInstruction(NewMI, RegB, mi);
Evan Cheng09f5be82009-03-30 21:34:07 +0000724
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000725 MBB->erase(mi); // Nuke the old inst.
Evan Chengd4fcc052011-02-10 02:20:55 +0000726
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000727 if (!Sunk) {
728 DistanceMap.insert(std::make_pair(NewMI, Dist));
729 mi = NewMI;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000730 nmi = std::next(mi);
Evan Cheng09f5be82009-03-30 21:34:07 +0000731 }
732
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000733 // Update source and destination register maps.
734 SrcRegMap.erase(RegA);
735 DstRegMap.erase(RegB);
736 return true;
Evan Cheng09f5be82009-03-30 21:34:07 +0000737}
738
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000739/// scanUses - Scan forward recursively for only uses, update maps if the use
Evan Cheng15fed7a2011-03-02 01:08:17 +0000740/// is a copy or a two-address instruction.
741void
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000742TwoAddressInstructionPass::scanUses(unsigned DstReg) {
Evan Cheng15fed7a2011-03-02 01:08:17 +0000743 SmallVector<unsigned, 4> VirtRegPairs;
744 bool IsDstPhys;
745 bool IsCopy = false;
746 unsigned NewReg = 0;
747 unsigned Reg = DstReg;
748 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
749 NewReg, IsDstPhys)) {
David Blaikie70573dc2014-11-19 07:49:26 +0000750 if (IsCopy && !Processed.insert(UseMI).second)
Evan Cheng15fed7a2011-03-02 01:08:17 +0000751 break;
752
753 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
754 if (DI != DistanceMap.end())
755 // Earlier in the same MBB.Reached via a back edge.
756 break;
757
758 if (IsDstPhys) {
759 VirtRegPairs.push_back(NewReg);
760 break;
761 }
762 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
763 if (!isNew)
764 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
765 VirtRegPairs.push_back(NewReg);
766 Reg = NewReg;
767 }
768
769 if (!VirtRegPairs.empty()) {
770 unsigned ToReg = VirtRegPairs.back();
771 VirtRegPairs.pop_back();
772 while (!VirtRegPairs.empty()) {
773 unsigned FromReg = VirtRegPairs.back();
774 VirtRegPairs.pop_back();
775 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
776 if (!isNew)
777 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
778 ToReg = FromReg;
779 }
780 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
781 if (!isNew)
782 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
783 }
784}
785
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000786/// processCopy - If the specified instruction is not yet processed, process it
Evan Chengc2f95b52009-03-01 02:03:43 +0000787/// if it's a copy. For a copy instruction, we find the physical registers the
788/// source and destination registers might be mapped to. These are kept in
789/// point-to maps used to determine future optimizations. e.g.
790/// v1024 = mov r0
791/// v1025 = mov r1
792/// v1026 = add v1024, v1025
793/// r1 = mov r1026
794/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
795/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
796/// potentially joined with r1 on the output side. It's worthwhile to commute
797/// 'add' to eliminate a copy.
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000798void TwoAddressInstructionPass::processCopy(MachineInstr *MI) {
Evan Chengc2f95b52009-03-01 02:03:43 +0000799 if (Processed.count(MI))
800 return;
801
802 bool IsSrcPhys, IsDstPhys;
803 unsigned SrcReg, DstReg;
804 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
805 return;
806
807 if (IsDstPhys && !IsSrcPhys)
808 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
809 else if (!IsDstPhys && IsSrcPhys) {
Evan Chengf0843802009-04-13 20:04:24 +0000810 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
811 if (!isNew)
812 assert(SrcRegMap[DstReg] == SrcReg &&
813 "Can't map to two src physical registers!");
Evan Chengc2f95b52009-03-01 02:03:43 +0000814
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000815 scanUses(DstReg);
Evan Chengc2f95b52009-03-01 02:03:43 +0000816 }
817
818 Processed.insert(MI);
Evan Cheng15fed7a2011-03-02 01:08:17 +0000819 return;
Evan Chengc2f95b52009-03-01 02:03:43 +0000820}
821
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000822/// rescheduleMIBelowKill - If there is one more local instruction that reads
Evan Cheng30f44ad2011-11-14 19:48:55 +0000823/// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
824/// instruction in order to eliminate the need for the copy.
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000825bool TwoAddressInstructionPass::
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000826rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000827 MachineBasicBlock::iterator &nmi,
828 unsigned Reg) {
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000829 // Bail immediately if we don't have LV or LIS available. We use them to find
830 // kills efficiently.
831 if (!LV && !LIS)
Chandler Carruthdb5536f2012-07-15 03:29:46 +0000832 return false;
833
Evan Cheng30f44ad2011-11-14 19:48:55 +0000834 MachineInstr *MI = &*mi;
Andrew Trick808a7a62012-02-03 05:12:30 +0000835 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
Evan Cheng30f44ad2011-11-14 19:48:55 +0000836 if (DI == DistanceMap.end())
837 // Must be created from unfolded load. Don't waste time trying this.
838 return false;
839
Craig Topperc0196b12014-04-14 00:51:57 +0000840 MachineInstr *KillMI = nullptr;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000841 if (LIS) {
842 LiveInterval &LI = LIS->getInterval(Reg);
843 assert(LI.end() != LI.begin() &&
844 "Reg should not have empty live interval.");
845
846 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
847 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
848 if (I != LI.end() && I->start < MBBEndIdx)
849 return false;
850
851 --I;
852 KillMI = LIS->getInstructionFromIndex(I->end);
853 } else {
854 KillMI = LV->getVarInfo(Reg).findKill(MBB);
855 }
Chandler Carruthdb5536f2012-07-15 03:29:46 +0000856 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng30f44ad2011-11-14 19:48:55 +0000857 // Don't mess with copies, they may be coalesced later.
858 return false;
859
Evan Cheng7f8e5632011-12-07 07:15:52 +0000860 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
861 KillMI->isBranch() || KillMI->isTerminator())
Evan Cheng30f44ad2011-11-14 19:48:55 +0000862 // Don't move pass calls, etc.
863 return false;
864
865 unsigned DstReg;
866 if (isTwoAddrUse(*KillMI, Reg, DstReg))
867 return false;
868
Evan Cheng7098c4e2011-11-15 06:26:51 +0000869 bool SeenStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +0000870 if (!MI->isSafeToMove(AA, SeenStore))
Evan Cheng30f44ad2011-11-14 19:48:55 +0000871 return false;
872
873 if (TII->getInstrLatency(InstrItins, MI) > 1)
874 // FIXME: Needs more sophisticated heuristics.
875 return false;
876
877 SmallSet<unsigned, 2> Uses;
Evan Chengb8c55a52011-11-16 03:47:42 +0000878 SmallSet<unsigned, 2> Kills;
Evan Cheng30f44ad2011-11-14 19:48:55 +0000879 SmallSet<unsigned, 2> Defs;
880 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
881 const MachineOperand &MO = MI->getOperand(i);
882 if (!MO.isReg())
883 continue;
884 unsigned MOReg = MO.getReg();
885 if (!MOReg)
886 continue;
887 if (MO.isDef())
888 Defs.insert(MOReg);
Evan Chengb8c55a52011-11-16 03:47:42 +0000889 else {
Evan Cheng30f44ad2011-11-14 19:48:55 +0000890 Uses.insert(MOReg);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000891 if (MOReg != Reg && (MO.isKill() ||
892 (LIS && isPlainlyKilled(MI, MOReg, LIS))))
Evan Chengb8c55a52011-11-16 03:47:42 +0000893 Kills.insert(MOReg);
894 }
Evan Cheng30f44ad2011-11-14 19:48:55 +0000895 }
896
897 // Move the copies connected to MI down as well.
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000898 MachineBasicBlock::iterator Begin = MI;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000899 MachineBasicBlock::iterator AfterMI = std::next(Begin);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000900
901 MachineBasicBlock::iterator End = AfterMI;
902 while (End->isCopy() && Defs.count(End->getOperand(1).getReg())) {
903 Defs.insert(End->getOperand(0).getReg());
904 ++End;
Evan Cheng30f44ad2011-11-14 19:48:55 +0000905 }
906
907 // Check if the reschedule will not break depedencies.
908 unsigned NumVisited = 0;
909 MachineBasicBlock::iterator KillPos = KillMI;
910 ++KillPos;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000911 for (MachineBasicBlock::iterator I = End; I != KillPos; ++I) {
Evan Cheng30f44ad2011-11-14 19:48:55 +0000912 MachineInstr *OtherMI = I;
913 // DBG_VALUE cannot be counted against the limit.
914 if (OtherMI->isDebugValue())
915 continue;
916 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
917 return false;
918 ++NumVisited;
Evan Cheng7f8e5632011-12-07 07:15:52 +0000919 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
920 OtherMI->isBranch() || OtherMI->isTerminator())
Evan Cheng30f44ad2011-11-14 19:48:55 +0000921 // Don't move pass calls, etc.
922 return false;
923 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
924 const MachineOperand &MO = OtherMI->getOperand(i);
925 if (!MO.isReg())
926 continue;
927 unsigned MOReg = MO.getReg();
928 if (!MOReg)
929 continue;
930 if (MO.isDef()) {
931 if (Uses.count(MOReg))
932 // Physical register use would be clobbered.
933 return false;
934 if (!MO.isDead() && Defs.count(MOReg))
935 // May clobber a physical register def.
936 // FIXME: This may be too conservative. It's ok if the instruction
937 // is sunken completely below the use.
938 return false;
939 } else {
940 if (Defs.count(MOReg))
941 return false;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000942 bool isKill = MO.isKill() ||
943 (LIS && isPlainlyKilled(OtherMI, MOReg, LIS));
Evan Chengb8c55a52011-11-16 03:47:42 +0000944 if (MOReg != Reg &&
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000945 ((isKill && Uses.count(MOReg)) || Kills.count(MOReg)))
Evan Cheng30f44ad2011-11-14 19:48:55 +0000946 // Don't want to extend other live ranges and update kills.
947 return false;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000948 if (MOReg == Reg && !isKill)
Chandler Carruthdb5536f2012-07-15 03:29:46 +0000949 // We can't schedule across a use of the register in question.
950 return false;
951 // Ensure that if this is register in question, its the kill we expect.
952 assert((MOReg != Reg || OtherMI == KillMI) &&
953 "Found multiple kills of a register in a basic block");
Evan Cheng30f44ad2011-11-14 19:48:55 +0000954 }
955 }
956 }
957
958 // Move debug info as well.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000959 while (Begin != MBB->begin() && std::prev(Begin)->isDebugValue())
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000960 --Begin;
961
962 nmi = End;
963 MachineBasicBlock::iterator InsertPos = KillPos;
964 if (LIS) {
965 // We have to move the copies first so that the MBB is still well-formed
966 // when calling handleMove().
967 for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) {
968 MachineInstr *CopyMI = MBBI;
969 ++MBBI;
970 MBB->splice(InsertPos, MBB, CopyMI);
971 LIS->handleMove(CopyMI);
972 InsertPos = CopyMI;
973 }
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000974 End = std::next(MachineBasicBlock::iterator(MI));
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000975 }
Evan Cheng30f44ad2011-11-14 19:48:55 +0000976
977 // Copies following MI may have been moved as well.
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000978 MBB->splice(InsertPos, MBB, Begin, End);
Evan Cheng30f44ad2011-11-14 19:48:55 +0000979 DistanceMap.erase(DI);
980
Chandler Carruthdb5536f2012-07-15 03:29:46 +0000981 // Update live variables
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000982 if (LIS) {
Jakob Stoklund Olesen24bc5142012-08-03 22:58:34 +0000983 LIS->handleMove(MI);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000984 } else {
985 LV->removeVirtualRegisterKilled(Reg, KillMI);
986 LV->addVirtualRegisterKilled(Reg, MI);
987 }
Evan Cheng30f44ad2011-11-14 19:48:55 +0000988
Jakob Stoklund Olesen0ef03112012-07-17 17:57:23 +0000989 DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
Evan Cheng30f44ad2011-11-14 19:48:55 +0000990 return true;
991}
992
993/// isDefTooClose - Return true if the re-scheduling will put the given
994/// instruction too close to the defs of its register dependencies.
995bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000996 MachineInstr *MI) {
Owen Andersonb36376e2014-03-17 19:36:09 +0000997 for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
998 if (DefMI.getParent() != MBB || DefMI.isCopy() || DefMI.isCopyLike())
Evan Cheng30f44ad2011-11-14 19:48:55 +0000999 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001000 if (&DefMI == MI)
Evan Cheng30f44ad2011-11-14 19:48:55 +00001001 return true; // MI is defining something KillMI uses
Owen Andersonb36376e2014-03-17 19:36:09 +00001002 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(&DefMI);
Evan Cheng30f44ad2011-11-14 19:48:55 +00001003 if (DDI == DistanceMap.end())
1004 return true; // Below MI
1005 unsigned DefDist = DDI->second;
1006 assert(Dist > DefDist && "Visited def already?");
Owen Andersonb36376e2014-03-17 19:36:09 +00001007 if (TII->getInstrLatency(InstrItins, &DefMI) > (Dist - DefDist))
Evan Cheng30f44ad2011-11-14 19:48:55 +00001008 return true;
1009 }
1010 return false;
1011}
1012
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +00001013/// rescheduleKillAboveMI - If there is one more local instruction that reads
Evan Cheng30f44ad2011-11-14 19:48:55 +00001014/// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
1015/// current two-address instruction in order to eliminate the need for the
1016/// copy.
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +00001017bool TwoAddressInstructionPass::
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001018rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +00001019 MachineBasicBlock::iterator &nmi,
1020 unsigned Reg) {
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001021 // Bail immediately if we don't have LV or LIS available. We use them to find
1022 // kills efficiently.
1023 if (!LV && !LIS)
Chandler Carruthdb5536f2012-07-15 03:29:46 +00001024 return false;
1025
Evan Cheng30f44ad2011-11-14 19:48:55 +00001026 MachineInstr *MI = &*mi;
1027 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
1028 if (DI == DistanceMap.end())
1029 // Must be created from unfolded load. Don't waste time trying this.
1030 return false;
1031
Craig Topperc0196b12014-04-14 00:51:57 +00001032 MachineInstr *KillMI = nullptr;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001033 if (LIS) {
1034 LiveInterval &LI = LIS->getInterval(Reg);
1035 assert(LI.end() != LI.begin() &&
1036 "Reg should not have empty live interval.");
1037
1038 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
1039 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
1040 if (I != LI.end() && I->start < MBBEndIdx)
1041 return false;
1042
1043 --I;
1044 KillMI = LIS->getInstructionFromIndex(I->end);
1045 } else {
1046 KillMI = LV->getVarInfo(Reg).findKill(MBB);
1047 }
Chandler Carruthdb5536f2012-07-15 03:29:46 +00001048 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng30f44ad2011-11-14 19:48:55 +00001049 // Don't mess with copies, they may be coalesced later.
1050 return false;
1051
1052 unsigned DstReg;
1053 if (isTwoAddrUse(*KillMI, Reg, DstReg))
1054 return false;
1055
Evan Cheng7098c4e2011-11-15 06:26:51 +00001056 bool SeenStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +00001057 if (!KillMI->isSafeToMove(AA, SeenStore))
Evan Cheng30f44ad2011-11-14 19:48:55 +00001058 return false;
1059
1060 SmallSet<unsigned, 2> Uses;
1061 SmallSet<unsigned, 2> Kills;
1062 SmallSet<unsigned, 2> Defs;
1063 SmallSet<unsigned, 2> LiveDefs;
1064 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
1065 const MachineOperand &MO = KillMI->getOperand(i);
1066 if (!MO.isReg())
1067 continue;
1068 unsigned MOReg = MO.getReg();
1069 if (MO.isUse()) {
1070 if (!MOReg)
1071 continue;
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001072 if (isDefTooClose(MOReg, DI->second, MI))
Evan Cheng30f44ad2011-11-14 19:48:55 +00001073 return false;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001074 bool isKill = MO.isKill() || (LIS && isPlainlyKilled(KillMI, MOReg, LIS));
1075 if (MOReg == Reg && !isKill)
Chandler Carruthdb5536f2012-07-15 03:29:46 +00001076 return false;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001077 Uses.insert(MOReg);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001078 if (isKill && MOReg != Reg)
Evan Cheng30f44ad2011-11-14 19:48:55 +00001079 Kills.insert(MOReg);
1080 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1081 Defs.insert(MOReg);
1082 if (!MO.isDead())
1083 LiveDefs.insert(MOReg);
1084 }
1085 }
1086
1087 // Check if the reschedule will not break depedencies.
1088 unsigned NumVisited = 0;
1089 MachineBasicBlock::iterator KillPos = KillMI;
1090 for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
1091 MachineInstr *OtherMI = I;
1092 // DBG_VALUE cannot be counted against the limit.
1093 if (OtherMI->isDebugValue())
1094 continue;
1095 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
1096 return false;
1097 ++NumVisited;
Evan Cheng7f8e5632011-12-07 07:15:52 +00001098 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
1099 OtherMI->isBranch() || OtherMI->isTerminator())
Evan Cheng30f44ad2011-11-14 19:48:55 +00001100 // Don't move pass calls, etc.
1101 return false;
Evan Cheng9ddd69a2011-11-16 03:05:12 +00001102 SmallVector<unsigned, 2> OtherDefs;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001103 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
1104 const MachineOperand &MO = OtherMI->getOperand(i);
1105 if (!MO.isReg())
1106 continue;
1107 unsigned MOReg = MO.getReg();
1108 if (!MOReg)
1109 continue;
1110 if (MO.isUse()) {
1111 if (Defs.count(MOReg))
1112 // Moving KillMI can clobber the physical register if the def has
1113 // not been seen.
1114 return false;
1115 if (Kills.count(MOReg))
1116 // Don't want to extend other live ranges and update kills.
1117 return false;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001118 if (OtherMI != MI && MOReg == Reg &&
1119 !(MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))))
Chandler Carruthdb5536f2012-07-15 03:29:46 +00001120 // We can't schedule across a use of the register in question.
1121 return false;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001122 } else {
Evan Cheng9ddd69a2011-11-16 03:05:12 +00001123 OtherDefs.push_back(MOReg);
Evan Cheng30f44ad2011-11-14 19:48:55 +00001124 }
1125 }
Evan Cheng9ddd69a2011-11-16 03:05:12 +00001126
1127 for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
1128 unsigned MOReg = OtherDefs[i];
1129 if (Uses.count(MOReg))
1130 return false;
1131 if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1132 LiveDefs.count(MOReg))
1133 return false;
1134 // Physical register def is seen.
1135 Defs.erase(MOReg);
1136 }
Evan Cheng30f44ad2011-11-14 19:48:55 +00001137 }
1138
1139 // Move the old kill above MI, don't forget to move debug info as well.
1140 MachineBasicBlock::iterator InsertPos = mi;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001141 while (InsertPos != MBB->begin() && std::prev(InsertPos)->isDebugValue())
Evan Chengf2fc5082011-11-14 21:11:15 +00001142 --InsertPos;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001143 MachineBasicBlock::iterator From = KillMI;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001144 MachineBasicBlock::iterator To = std::next(From);
1145 while (std::prev(From)->isDebugValue())
Evan Cheng30f44ad2011-11-14 19:48:55 +00001146 --From;
1147 MBB->splice(InsertPos, MBB, From, To);
1148
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001149 nmi = std::prev(InsertPos); // Backtrack so we process the moved instr.
Evan Cheng30f44ad2011-11-14 19:48:55 +00001150 DistanceMap.erase(DI);
1151
Chandler Carruthdb5536f2012-07-15 03:29:46 +00001152 // Update live variables
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001153 if (LIS) {
Jakob Stoklund Olesen24bc5142012-08-03 22:58:34 +00001154 LIS->handleMove(KillMI);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001155 } else {
1156 LV->removeVirtualRegisterKilled(Reg, KillMI);
1157 LV->addVirtualRegisterKilled(Reg, MI);
1158 }
Chandler Carruthdb5536f2012-07-15 03:29:46 +00001159
Jakob Stoklund Olesen0ef03112012-07-17 17:57:23 +00001160 DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
Evan Cheng30f44ad2011-11-14 19:48:55 +00001161 return true;
1162}
1163
Andrew Kaylor16c4da02015-09-28 20:33:22 +00001164/// Tries to commute the operand 'BaseOpIdx' and some other operand in the
1165/// given machine instruction to improve opportunities for coalescing and
1166/// elimination of a register to register copy.
1167///
1168/// 'DstOpIdx' specifies the index of MI def operand.
1169/// 'BaseOpKilled' specifies if the register associated with 'BaseOpIdx'
1170/// operand is killed by the given instruction.
1171/// The 'Dist' arguments provides the distance of MI from the start of the
1172/// current basic block and it is used to determine if it is profitable
1173/// to commute operands in the instruction.
1174///
1175/// Returns true if the transformation happened. Otherwise, returns false.
1176bool TwoAddressInstructionPass::tryInstructionCommute(MachineInstr *MI,
1177 unsigned DstOpIdx,
1178 unsigned BaseOpIdx,
1179 bool BaseOpKilled,
1180 unsigned Dist) {
1181 unsigned DstOpReg = MI->getOperand(DstOpIdx).getReg();
1182 unsigned BaseOpReg = MI->getOperand(BaseOpIdx).getReg();
1183 unsigned OpsNum = MI->getDesc().getNumOperands();
1184 unsigned OtherOpIdx = MI->getDesc().getNumDefs();
1185 for (; OtherOpIdx < OpsNum; OtherOpIdx++) {
1186 // The call of findCommutedOpIndices below only checks if BaseOpIdx
1187 // and OtherOpIdx are commutable, it does not really searches for
1188 // other commutable operands and does not change the values of passed
1189 // variables.
1190 if (OtherOpIdx == BaseOpIdx ||
1191 !TII->findCommutedOpIndices(MI, BaseOpIdx, OtherOpIdx))
1192 continue;
1193
1194 unsigned OtherOpReg = MI->getOperand(OtherOpIdx).getReg();
1195 bool AggressiveCommute = false;
1196
1197 // If OtherOp dies but BaseOp does not, swap the OtherOp and BaseOp
1198 // operands. This makes the live ranges of DstOp and OtherOp joinable.
1199 bool DoCommute =
1200 !BaseOpKilled && isKilled(*MI, OtherOpReg, MRI, TII, LIS, false);
1201
1202 if (!DoCommute &&
1203 isProfitableToCommute(DstOpReg, BaseOpReg, OtherOpReg, MI, Dist)) {
1204 DoCommute = true;
1205 AggressiveCommute = true;
1206 }
1207
1208 // If it's profitable to commute, try to do so.
1209 if (DoCommute && commuteInstruction(MI, BaseOpIdx, OtherOpIdx, Dist)) {
1210 ++NumCommuted;
1211 if (AggressiveCommute)
1212 ++NumAggrCommuted;
1213 return true;
1214 }
1215 }
1216 return false;
1217}
1218
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +00001219/// tryInstructionTransform - For the case where an instruction has a single
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001220/// pair of tied register operands, attempt some transformations that may
1221/// either eliminate the tied operands or improve the opportunities for
Lang Hames3ad11ff2012-04-09 20:17:30 +00001222/// coalescing away the register copy. Returns true if no copy needs to be
1223/// inserted to untie mi's operands (either because they were untied, or
Cameron Zwarichf05c0cb2013-02-24 00:27:26 +00001224/// because mi was rescheduled, and will be visited again later). If the
1225/// shouldOnlyCommute flag is true, only instruction commutation is attempted.
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001226bool TwoAddressInstructionPass::
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +00001227tryInstructionTransform(MachineBasicBlock::iterator &mi,
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001228 MachineBasicBlock::iterator &nmi,
Cameron Zwarichf05c0cb2013-02-24 00:27:26 +00001229 unsigned SrcIdx, unsigned DstIdx,
1230 unsigned Dist, bool shouldOnlyCommute) {
Evan Cheng822ddde2011-11-16 18:44:48 +00001231 if (OptLevel == CodeGenOpt::None)
1232 return false;
1233
Evan Cheng30f44ad2011-11-14 19:48:55 +00001234 MachineInstr &MI = *mi;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001235 unsigned regA = MI.getOperand(DstIdx).getReg();
1236 unsigned regB = MI.getOperand(SrcIdx).getReg();
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001237
1238 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1239 "cannot make instruction into two-address form");
Cameron Zwarich384026b2013-02-21 22:58:42 +00001240 bool regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001241
Evan Chengb64e7b72012-05-03 01:45:13 +00001242 if (TargetRegisterInfo::isVirtualRegister(regA))
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001243 scanUses(regA);
Evan Chengb64e7b72012-05-03 01:45:13 +00001244
Andrew Kaylor16c4da02015-09-28 20:33:22 +00001245 bool Commuted = tryInstructionCommute(&MI, DstIdx, SrcIdx, regBKilled, Dist);
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001246
Quentin Colombet9729fb32015-07-01 23:12:13 +00001247 // If the instruction is convertible to 3 Addr, instead
1248 // of returning try 3 Addr transformation aggresively and
1249 // use this variable to check later. Because it might be better.
1250 // For example, we can just use `leal (%rsi,%rdi), %eax` and `ret`
1251 // instead of the following code.
NAKAMURA Takumi84965032015-09-22 11:14:12 +00001252 // addl %esi, %edi
1253 // movl %edi, %eax
Quentin Colombet9729fb32015-07-01 23:12:13 +00001254 // ret
Andrew Kaylor16c4da02015-09-28 20:33:22 +00001255 if (Commuted && !MI.isConvertibleTo3Addr())
1256 return false;
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001257
Cameron Zwarichf05c0cb2013-02-24 00:27:26 +00001258 if (shouldOnlyCommute)
1259 return false;
1260
Evan Cheng30f44ad2011-11-14 19:48:55 +00001261 // If there is one more use of regB later in the same MBB, consider
1262 // re-schedule this MI below it.
Quentin Colombet40dd5102015-07-06 20:12:54 +00001263 if (!Commuted && EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) {
Evan Cheng30f44ad2011-11-14 19:48:55 +00001264 ++NumReSchedDowns;
Lang Hames3ad11ff2012-04-09 20:17:30 +00001265 return true;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001266 }
1267
Evan Cheng7f8e5632011-12-07 07:15:52 +00001268 if (MI.isConvertibleTo3Addr()) {
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001269 // This instruction is potentially convertible to a true
1270 // three-address instruction. Check if it is profitable.
Evan Cheng15fed7a2011-03-02 01:08:17 +00001271 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001272 // Try to convert it.
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001273 if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001274 ++NumConvertedTo3Addr;
1275 return true; // Done with this instruction.
1276 }
1277 }
1278 }
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001279
Quentin Colombet9729fb32015-07-01 23:12:13 +00001280 // Return if it is commuted but 3 addr conversion is failed.
Quentin Colombet40dd5102015-07-06 20:12:54 +00001281 if (Commuted)
Quentin Colombet9729fb32015-07-01 23:12:13 +00001282 return false;
1283
Evan Cheng30f44ad2011-11-14 19:48:55 +00001284 // If there is one more use of regB later in the same MBB, consider
1285 // re-schedule it before this MI if it's legal.
Andrew Trick608a6982013-04-24 15:54:39 +00001286 if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) {
Evan Cheng30f44ad2011-11-14 19:48:55 +00001287 ++NumReSchedUps;
Lang Hames3ad11ff2012-04-09 20:17:30 +00001288 return true;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001289 }
1290
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001291 // If this is an instruction with a load folded into it, try unfolding
1292 // the load, e.g. avoid this:
1293 // movq %rdx, %rcx
1294 // addq (%rax), %rcx
1295 // in favor of this:
1296 // movq (%rax), %rcx
1297 // addq %rdx, %rcx
1298 // because it's preferable to schedule a load than a register copy.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001299 if (MI.mayLoad() && !regBKilled) {
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001300 // Determine if a load can be unfolded.
1301 unsigned LoadRegIndex;
1302 unsigned NewOpc =
Evan Cheng30f44ad2011-11-14 19:48:55 +00001303 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001304 /*UnfoldLoad=*/true,
1305 /*UnfoldStore=*/false,
1306 &LoadRegIndex);
1307 if (NewOpc != 0) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00001308 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1309 if (UnfoldMCID.getNumDefs() == 1) {
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001310 // Unfold the load.
Evan Cheng30f44ad2011-11-14 19:48:55 +00001311 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001312 const TargetRegisterClass *RC =
Andrew Trick32aea352012-05-03 01:14:37 +00001313 TRI->getAllocatableClass(
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001314 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001315 unsigned Reg = MRI->createVirtualRegister(RC);
1316 SmallVector<MachineInstr *, 2> NewMIs;
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001317 if (!TII->unfoldMemoryOperand(*MF, &MI, Reg,
Evan Cheng0ce84482010-07-02 20:36:18 +00001318 /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
1319 NewMIs)) {
1320 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1321 return false;
1322 }
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001323 assert(NewMIs.size() == 2 &&
1324 "Unfolded a load into multiple instructions!");
1325 // The load was previously folded, so this is the only use.
1326 NewMIs[1]->addRegisterKilled(Reg, TRI);
1327
1328 // Tentatively insert the instructions into the block so that they
1329 // look "normal" to the transformation logic.
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001330 MBB->insert(mi, NewMIs[0]);
1331 MBB->insert(mi, NewMIs[1]);
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001332
1333 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1334 << "2addr: NEW INST: " << *NewMIs[1]);
1335
1336 // Transform the instruction, now that it no longer has a load.
1337 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1338 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1339 MachineBasicBlock::iterator NewMI = NewMIs[1];
Cameron Zwarich6868f382013-02-24 00:27:29 +00001340 bool TransformResult =
Cameron Zwarichf05c0cb2013-02-24 00:27:26 +00001341 tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true);
Cameron Zwarich1b4c64c2013-02-24 01:26:05 +00001342 (void)TransformResult;
Cameron Zwarich6868f382013-02-24 00:27:29 +00001343 assert(!TransformResult &&
1344 "tryInstructionTransform() should return false.");
1345 if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001346 // Success, or at least we made an improvement. Keep the unfolded
1347 // instructions and discard the original.
1348 if (LV) {
Evan Cheng30f44ad2011-11-14 19:48:55 +00001349 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1350 MachineOperand &MO = MI.getOperand(i);
Andrew Trick808a7a62012-02-03 05:12:30 +00001351 if (MO.isReg() &&
Dan Gohman851e4782010-06-22 00:32:04 +00001352 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1353 if (MO.isUse()) {
Dan Gohman2370e2f2010-06-22 02:07:21 +00001354 if (MO.isKill()) {
1355 if (NewMIs[0]->killsRegister(MO.getReg()))
Evan Cheng30f44ad2011-11-14 19:48:55 +00001356 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
Dan Gohman2370e2f2010-06-22 02:07:21 +00001357 else {
1358 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1359 "Kill missing after load unfold!");
Evan Cheng30f44ad2011-11-14 19:48:55 +00001360 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
Dan Gohman2370e2f2010-06-22 02:07:21 +00001361 }
1362 }
Evan Cheng30f44ad2011-11-14 19:48:55 +00001363 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
Dan Gohman2370e2f2010-06-22 02:07:21 +00001364 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1365 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
1366 else {
1367 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1368 "Dead flag missing after load unfold!");
1369 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
1370 }
1371 }
Dan Gohman851e4782010-06-22 00:32:04 +00001372 }
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001373 }
1374 LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
1375 }
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001376
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001377 SmallVector<unsigned, 4> OrigRegs;
1378 if (LIS) {
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001379 for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(),
1380 MOE = MI.operands_end(); MOI != MOE; ++MOI) {
1381 if (MOI->isReg())
1382 OrigRegs.push_back(MOI->getReg());
1383 }
1384 }
1385
Evan Cheng30f44ad2011-11-14 19:48:55 +00001386 MI.eraseFromParent();
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001387
1388 // Update LiveIntervals.
Cameron Zwarichcaad7e12013-02-20 22:10:00 +00001389 if (LIS) {
1390 MachineBasicBlock::iterator Begin(NewMIs[0]);
1391 MachineBasicBlock::iterator End(NewMIs[1]);
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001392 LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs);
Cameron Zwarichcaad7e12013-02-20 22:10:00 +00001393 }
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001394
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001395 mi = NewMIs[1];
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001396 } else {
1397 // Transforming didn't eliminate the tie and didn't lead to an
1398 // improvement. Clean up the unfolded instructions and keep the
1399 // original.
1400 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1401 NewMIs[0]->eraseFromParent();
1402 NewMIs[1]->eraseFromParent();
1403 }
1404 }
1405 }
1406 }
1407
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001408 return false;
1409}
1410
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001411// Collect tied operands of MI that need to be handled.
1412// Rewrite trivial cases immediately.
1413// Return true if any tied operands where found, including the trivial ones.
1414bool TwoAddressInstructionPass::
1415collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
1416 const MCInstrDesc &MCID = MI->getDesc();
1417 bool AnyOps = false;
Jakob Stoklund Olesenade363e2012-09-04 22:59:30 +00001418 unsigned NumOps = MI->getNumOperands();
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001419
1420 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1421 unsigned DstIdx = 0;
1422 if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1423 continue;
1424 AnyOps = true;
Jakob Stoklund Olesenfbf45dc2012-08-07 22:47:06 +00001425 MachineOperand &SrcMO = MI->getOperand(SrcIdx);
1426 MachineOperand &DstMO = MI->getOperand(DstIdx);
1427 unsigned SrcReg = SrcMO.getReg();
1428 unsigned DstReg = DstMO.getReg();
1429 // Tied constraint already satisfied?
1430 if (SrcReg == DstReg)
1431 continue;
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001432
Jakob Stoklund Olesenfbf45dc2012-08-07 22:47:06 +00001433 assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001434
1435 // Deal with <undef> uses immediately - simply rewrite the src operand.
Andrew Tricke3398282013-12-17 04:50:45 +00001436 if (SrcMO.isUndef() && !DstMO.getSubReg()) {
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001437 // Constrain the DstReg register class if required.
1438 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1439 if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
1440 TRI, *MF))
1441 MRI->constrainRegClass(DstReg, RC);
Jakob Stoklund Olesenfbf45dc2012-08-07 22:47:06 +00001442 SrcMO.setReg(DstReg);
Andrew Tricke3398282013-12-17 04:50:45 +00001443 SrcMO.setSubReg(0);
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001444 DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
1445 continue;
1446 }
Jakob Stoklund Olesenfbf45dc2012-08-07 22:47:06 +00001447 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001448 }
1449 return AnyOps;
1450}
1451
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001452// Process a list of tied MI operands that all use the same source register.
1453// The tied pairs are of the form (SrcIdx, DstIdx).
1454void
1455TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
1456 TiedPairList &TiedPairs,
1457 unsigned &Dist) {
1458 bool IsEarlyClobber = false;
Cameron Zwarich2991feb2013-02-20 06:46:46 +00001459 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1460 const MachineOperand &DstMO = MI->getOperand(TiedPairs[tpi].second);
1461 IsEarlyClobber |= DstMO.isEarlyClobber();
1462 }
1463
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001464 bool RemovedKillFlag = false;
1465 bool AllUsesCopied = true;
1466 unsigned LastCopiedReg = 0;
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001467 SlotIndex LastCopyIdx;
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001468 unsigned RegB = 0;
Andrew Tricke3398282013-12-17 04:50:45 +00001469 unsigned SubRegB = 0;
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001470 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1471 unsigned SrcIdx = TiedPairs[tpi].first;
1472 unsigned DstIdx = TiedPairs[tpi].second;
1473
1474 const MachineOperand &DstMO = MI->getOperand(DstIdx);
1475 unsigned RegA = DstMO.getReg();
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001476
1477 // Grab RegB from the instruction because it may have changed if the
1478 // instruction was commuted.
1479 RegB = MI->getOperand(SrcIdx).getReg();
Andrew Tricke3398282013-12-17 04:50:45 +00001480 SubRegB = MI->getOperand(SrcIdx).getSubReg();
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001481
1482 if (RegA == RegB) {
1483 // The register is tied to multiple destinations (or else we would
1484 // not have continued this far), but this use of the register
1485 // already matches the tied destination. Leave it.
1486 AllUsesCopied = false;
1487 continue;
1488 }
1489 LastCopiedReg = RegA;
1490
1491 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1492 "cannot make instruction into two-address form");
1493
1494#ifndef NDEBUG
1495 // First, verify that we don't have a use of "a" in the instruction
1496 // (a = b + a for example) because our transformation will not
1497 // work. This should never occur because we are in SSA form.
1498 for (unsigned i = 0; i != MI->getNumOperands(); ++i)
1499 assert(i == DstIdx ||
1500 !MI->getOperand(i).isReg() ||
1501 MI->getOperand(i).getReg() != RegA);
1502#endif
1503
1504 // Emit a copy.
Andrew Tricke3398282013-12-17 04:50:45 +00001505 MachineInstrBuilder MIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1506 TII->get(TargetOpcode::COPY), RegA);
1507 // If this operand is folding a truncation, the truncation now moves to the
1508 // copy so that the register classes remain valid for the operands.
1509 MIB.addReg(RegB, 0, SubRegB);
1510 const TargetRegisterClass *RC = MRI->getRegClass(RegB);
1511 if (SubRegB) {
1512 if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1513 assert(TRI->getMatchingSuperRegClass(RC, MRI->getRegClass(RegA),
1514 SubRegB) &&
1515 "tied subregister must be a truncation");
1516 // The superreg class will not be used to constrain the subreg class.
Craig Topperc0196b12014-04-14 00:51:57 +00001517 RC = nullptr;
Andrew Tricke3398282013-12-17 04:50:45 +00001518 }
1519 else {
1520 assert(TRI->getMatchingSuperReg(RegA, SubRegB, MRI->getRegClass(RegB))
1521 && "tied subregister must be a truncation");
1522 }
1523 }
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001524
1525 // Update DistanceMap.
1526 MachineBasicBlock::iterator PrevMI = MI;
1527 --PrevMI;
1528 DistanceMap.insert(std::make_pair(PrevMI, Dist));
1529 DistanceMap[MI] = ++Dist;
1530
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001531 if (LIS) {
1532 LastCopyIdx = LIS->InsertMachineInstrInMaps(PrevMI).getRegSlot();
1533
1534 if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1535 LiveInterval &LI = LIS->getInterval(RegA);
1536 VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1537 SlotIndex endIdx =
1538 LIS->getInstructionIndex(MI).getRegSlot(IsEarlyClobber);
Matthias Braun13ddb7c2013-10-10 21:28:43 +00001539 LI.addSegment(LiveInterval::Segment(LastCopyIdx, endIdx, VNI));
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001540 }
1541 }
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001542
Andrew Tricke3398282013-12-17 04:50:45 +00001543 DEBUG(dbgs() << "\t\tprepend:\t" << *MIB);
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001544
1545 MachineOperand &MO = MI->getOperand(SrcIdx);
1546 assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
1547 "inconsistent operand info for 2-reg pass");
1548 if (MO.isKill()) {
1549 MO.setIsKill(false);
1550 RemovedKillFlag = true;
1551 }
1552
1553 // Make sure regA is a legal regclass for the SrcIdx operand.
1554 if (TargetRegisterInfo::isVirtualRegister(RegA) &&
1555 TargetRegisterInfo::isVirtualRegister(RegB))
Andrew Tricke3398282013-12-17 04:50:45 +00001556 MRI->constrainRegClass(RegA, RC);
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001557 MO.setReg(RegA);
Andrew Tricke3398282013-12-17 04:50:45 +00001558 // The getMatchingSuper asserts guarantee that the register class projected
1559 // by SubRegB is compatible with RegA with no subregister. So regardless of
1560 // whether the dest oper writes a subreg, the source oper should not.
1561 MO.setSubReg(0);
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001562
1563 // Propagate SrcRegMap.
1564 SrcRegMap[RegA] = RegB;
1565 }
1566
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001567 if (AllUsesCopied) {
1568 if (!IsEarlyClobber) {
1569 // Replace other (un-tied) uses of regB with LastCopiedReg.
1570 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1571 MachineOperand &MO = MI->getOperand(i);
Andrew Tricke3398282013-12-17 04:50:45 +00001572 if (MO.isReg() && MO.getReg() == RegB && MO.getSubReg() == SubRegB &&
1573 MO.isUse()) {
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001574 if (MO.isKill()) {
1575 MO.setIsKill(false);
1576 RemovedKillFlag = true;
1577 }
1578 MO.setReg(LastCopiedReg);
Andrew Tricke3398282013-12-17 04:50:45 +00001579 MO.setSubReg(0);
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001580 }
1581 }
1582 }
1583
1584 // Update live variables for regB.
1585 if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(MI)) {
1586 MachineBasicBlock::iterator PrevMI = MI;
1587 --PrevMI;
1588 LV->addVirtualRegisterKilled(RegB, PrevMI);
1589 }
1590
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001591 // Update LiveIntervals.
1592 if (LIS) {
1593 LiveInterval &LI = LIS->getInterval(RegB);
1594 SlotIndex MIIdx = LIS->getInstructionIndex(MI);
1595 LiveInterval::const_iterator I = LI.find(MIIdx);
1596 assert(I != LI.end() && "RegB must be live-in to use.");
1597
1598 SlotIndex UseIdx = MIIdx.getRegSlot(IsEarlyClobber);
1599 if (I->end == UseIdx)
Matthias Braun13ddb7c2013-10-10 21:28:43 +00001600 LI.removeSegment(LastCopyIdx, UseIdx);
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001601 }
1602
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001603 } else if (RemovedKillFlag) {
1604 // Some tied uses of regB matched their destination registers, so
1605 // regB is still used in this instruction, but a kill flag was
1606 // removed from a different tied use of regB, so now we need to add
1607 // a kill flag to one of the remaining uses of regB.
1608 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1609 MachineOperand &MO = MI->getOperand(i);
1610 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1611 MO.setIsKill(true);
1612 break;
1613 }
1614 }
1615 }
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001616}
1617
Bill Wendling19e3c852008-05-10 00:12:52 +00001618/// runOnMachineFunction - Reduce two-address instructions to two operands.
Alkis Evlogimenos725021c2003-12-18 13:06:04 +00001619///
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001620bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
1621 MF = &Func;
1622 const TargetMachine &TM = MF->getTarget();
1623 MRI = &MF->getRegInfo();
Eric Christopher33726202015-01-27 08:48:42 +00001624 TII = MF->getSubtarget().getInstrInfo();
1625 TRI = MF->getSubtarget().getRegisterInfo();
1626 InstrItins = MF->getSubtarget().getInstrItineraryData();
Duncan Sands5a913d62009-01-28 13:14:17 +00001627 LV = getAnalysisIfAvailable<LiveVariables>();
Jakob Stoklund Olesen24bc5142012-08-03 22:58:34 +00001628 LIS = getAnalysisIfAvailable<LiveIntervals>();
Chandler Carruth7b560d42015-09-09 17:55:00 +00001629 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Evan Cheng822ddde2011-11-16 18:44:48 +00001630 OptLevel = TM.getOptLevel();
Alkis Evlogimenos725021c2003-12-18 13:06:04 +00001631
Misha Brukman6dd644e2004-07-22 15:26:23 +00001632 bool MadeChange = false;
Alkis Evlogimenos725021c2003-12-18 13:06:04 +00001633
David Greeneac9f8192010-01-05 01:24:21 +00001634 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
Andrew Trick808a7a62012-02-03 05:12:30 +00001635 DEBUG(dbgs() << "********** Function: "
Craig Toppera538d832012-08-22 06:07:19 +00001636 << MF->getName() << '\n');
Alkis Evlogimenos26583db2004-02-18 00:35:06 +00001637
Jakob Stoklund Olesen9760f042011-07-29 22:51:22 +00001638 // This pass takes the function out of SSA form.
1639 MRI->leaveSSA();
1640
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001641 TiedOperandMap TiedOperands;
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001642 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
1643 MBBI != MBBE; ++MBBI) {
1644 MBB = MBBI;
Evan Chengc5618eb2008-06-18 07:49:14 +00001645 unsigned Dist = 0;
1646 DistanceMap.clear();
Evan Chengc2f95b52009-03-01 02:03:43 +00001647 SrcRegMap.clear();
1648 DstRegMap.clear();
1649 Processed.clear();
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001650 for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
Evan Cheng58324102008-03-27 01:27:25 +00001651 mi != me; ) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001652 MachineBasicBlock::iterator nmi = std::next(mi);
Dale Johannesen8bba1602010-02-10 21:47:48 +00001653 if (mi->isDebugValue()) {
1654 mi = nmi;
1655 continue;
1656 }
Evan Cheng77be42a2010-03-23 20:36:12 +00001657
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001658 // Expand REG_SEQUENCE instructions. This will position mi at the first
1659 // expanded instruction.
Evan Cheng4b6abd82010-05-05 18:45:40 +00001660 if (mi->isRegSequence())
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001661 eliminateRegSequence(mi);
Evan Cheng4b6abd82010-05-05 18:45:40 +00001662
Evan Chengc5618eb2008-06-18 07:49:14 +00001663 DistanceMap.insert(std::make_pair(mi, ++Dist));
Evan Chengc2f95b52009-03-01 02:03:43 +00001664
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001665 processCopy(&*mi);
Evan Chengc2f95b52009-03-01 02:03:43 +00001666
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001667 // First scan through all the tied register uses in this instruction
1668 // and record a list of pairs of tied operands for each register.
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001669 if (!collectTiedOperands(mi, TiedOperands)) {
1670 mi = nmi;
1671 continue;
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001672 }
Alkis Evlogimenos725021c2003-12-18 13:06:04 +00001673
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001674 ++NumTwoAddressInstrs;
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001675 MadeChange = true;
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001676 DEBUG(dbgs() << '\t' << *mi);
1677
Chandler Carruth985454e2012-07-18 18:58:22 +00001678 // If the instruction has a single pair of tied operands, try some
1679 // transformations that may either eliminate the tied operands or
1680 // improve the opportunities for coalescing away the register copy.
1681 if (TiedOperands.size() == 1) {
Craig Topperb94011f2013-07-14 04:42:23 +00001682 SmallVectorImpl<std::pair<unsigned, unsigned> > &TiedPairs
Chandler Carruth985454e2012-07-18 18:58:22 +00001683 = TiedOperands.begin()->second;
1684 if (TiedPairs.size() == 1) {
1685 unsigned SrcIdx = TiedPairs[0].first;
1686 unsigned DstIdx = TiedPairs[0].second;
1687 unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
1688 unsigned DstReg = mi->getOperand(DstIdx).getReg();
1689 if (SrcReg != DstReg &&
Cameron Zwarichf05c0cb2013-02-24 00:27:26 +00001690 tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) {
NAKAMURA Takumi84965032015-09-22 11:14:12 +00001691 // The tied operands have been eliminated or shifted further down
1692 // the block to ease elimination. Continue processing with 'nmi'.
Chandler Carruth985454e2012-07-18 18:58:22 +00001693 TiedOperands.clear();
1694 mi = nmi;
1695 continue;
1696 }
1697 }
1698 }
1699
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001700 // Now iterate over the information collected above.
1701 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1702 OE = TiedOperands.end(); OI != OE; ++OI) {
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001703 processTiedPairs(mi, OI->second, Dist);
David Greeneac9f8192010-01-05 01:24:21 +00001704 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
Jakob Stoklund Olesen6b556f82012-06-25 03:27:12 +00001705 }
Bill Wendling19e3c852008-05-10 00:12:52 +00001706
Jakob Stoklund Olesen6b556f82012-06-25 03:27:12 +00001707 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1708 if (mi->isInsertSubreg()) {
1709 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1710 // To %reg:subidx = COPY %subreg
1711 unsigned SubIdx = mi->getOperand(3).getImm();
1712 mi->RemoveOperand(3);
1713 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1714 mi->getOperand(0).setSubReg(SubIdx);
1715 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1716 mi->RemoveOperand(1);
1717 mi->setDesc(TII->get(TargetOpcode::COPY));
1718 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
Jakob Stoklund Olesen70ee3ec2010-07-06 23:26:25 +00001719 }
1720
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001721 // Clear TiedOperands here instead of at the top of the loop
1722 // since most instructions do not have tied operands.
1723 TiedOperands.clear();
Evan Cheng58324102008-03-27 01:27:25 +00001724 mi = nmi;
Misha Brukman6dd644e2004-07-22 15:26:23 +00001725 }
1726 }
1727
Cameron Zwarich36735812013-02-20 06:46:34 +00001728 if (LIS)
1729 MF->verify(this, "After two-address instruction pass");
1730
Misha Brukman6dd644e2004-07-22 15:26:23 +00001731 return MadeChange;
Alkis Evlogimenos725021c2003-12-18 13:06:04 +00001732}
Evan Cheng4b6abd82010-05-05 18:45:40 +00001733
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001734/// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process.
Evan Cheng4b6abd82010-05-05 18:45:40 +00001735///
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001736/// The instruction is turned into a sequence of sub-register copies:
1737///
1738/// %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1
1739///
1740/// Becomes:
1741///
1742/// %dst:ssub0<def,undef> = COPY %v1
1743/// %dst:ssub1<def> = COPY %v2
1744///
1745void TwoAddressInstructionPass::
1746eliminateRegSequence(MachineBasicBlock::iterator &MBBI) {
1747 MachineInstr *MI = MBBI;
1748 unsigned DstReg = MI->getOperand(0).getReg();
1749 if (MI->getOperand(0).getSubReg() ||
1750 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1751 !(MI->getNumOperands() & 1)) {
1752 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
Craig Topperc0196b12014-04-14 00:51:57 +00001753 llvm_unreachable(nullptr);
Evan Cheng4b6abd82010-05-05 18:45:40 +00001754 }
1755
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001756 SmallVector<unsigned, 4> OrigRegs;
1757 if (LIS) {
1758 OrigRegs.push_back(MI->getOperand(0).getReg());
1759 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2)
1760 OrigRegs.push_back(MI->getOperand(i).getReg());
1761 }
1762
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001763 bool DefEmitted = false;
1764 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1765 MachineOperand &UseMO = MI->getOperand(i);
1766 unsigned SrcReg = UseMO.getReg();
1767 unsigned SubIdx = MI->getOperand(i+1).getImm();
1768 // Nothing needs to be inserted for <undef> operands.
1769 if (UseMO.isUndef())
1770 continue;
1771
1772 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1773 // might insert a COPY that uses SrcReg after is was killed.
1774 bool isKill = UseMO.isKill();
1775 if (isKill)
1776 for (unsigned j = i + 2; j < e; j += 2)
1777 if (MI->getOperand(j).getReg() == SrcReg) {
1778 MI->getOperand(j).setIsKill();
1779 UseMO.setIsKill(false);
1780 isKill = false;
1781 break;
1782 }
1783
1784 // Insert the sub-register copy.
1785 MachineInstr *CopyMI = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1786 TII->get(TargetOpcode::COPY))
1787 .addReg(DstReg, RegState::Define, SubIdx)
1788 .addOperand(UseMO);
1789
1790 // The first def needs an <undef> flag because there is no live register
1791 // before it.
1792 if (!DefEmitted) {
1793 CopyMI->getOperand(0).setIsUndef(true);
1794 // Return an iterator pointing to the first inserted instr.
1795 MBBI = CopyMI;
1796 }
1797 DefEmitted = true;
1798
1799 // Update LiveVariables' kill info.
1800 if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
1801 LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1802
1803 DEBUG(dbgs() << "Inserted: " << *CopyMI);
1804 }
1805
David Blaikie9db062e2013-02-20 07:39:20 +00001806 MachineBasicBlock::iterator EndMBBI =
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001807 std::next(MachineBasicBlock::iterator(MI));
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001808
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001809 if (!DefEmitted) {
1810 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1811 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1812 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
1813 MI->RemoveOperand(j);
1814 } else {
1815 DEBUG(dbgs() << "Eliminated: " << *MI);
1816 MI->eraseFromParent();
1817 }
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001818
1819 // Udpate LiveIntervals.
Cameron Zwarichcaad7e12013-02-20 22:10:00 +00001820 if (LIS)
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001821 LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs);
Evan Cheng4b6abd82010-05-05 18:45:40 +00001822}