blob: 1e30821dc741b6da596c16afdcb9cd195afafbeb [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
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000113 bool commuteInstruction(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000114 unsigned RegB, unsigned RegC, 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
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000136 void scanUses(unsigned DstReg);
Evan Cheng15fed7a2011-03-02 01:08:17 +0000137
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000138 void processCopy(MachineInstr *MI);
Bob Wilson5c7d9ca2009-09-03 20:58:42 +0000139
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000140 typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList;
141 typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap;
142 bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
143 void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +0000144 void eliminateRegSequence(MachineBasicBlock::iterator&);
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +0000145
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000146public:
147 static char ID; // Pass identification, replacement for typeid
148 TwoAddressInstructionPass() : MachineFunctionPass(ID) {
149 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
150 }
Evan Cheng1e4f5522010-05-17 23:24:12 +0000151
Craig Topper4584cd52014-03-07 09:26:03 +0000152 void getAnalysisUsage(AnalysisUsage &AU) const override {
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000153 AU.setPreservesCFG();
154 AU.addRequired<AliasAnalysis>();
155 AU.addPreserved<LiveVariables>();
156 AU.addPreserved<SlotIndexes>();
157 AU.addPreserved<LiveIntervals>();
158 AU.addPreservedID(MachineLoopInfoID);
159 AU.addPreservedID(MachineDominatorsID);
160 MachineFunctionPass::getAnalysisUsage(AU);
161 }
Devang Patel09f162c2007-05-01 21:15:47 +0000162
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000163 /// runOnMachineFunction - Pass entry point.
Craig Topper4584cd52014-03-07 09:26:03 +0000164 bool runOnMachineFunction(MachineFunction&) override;
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000165};
166} // end anonymous namespace
Alkis Evlogimenos725021c2003-12-18 13:06:04 +0000167
Dan Gohmand78c4002008-05-13 00:00:25 +0000168char TwoAddressInstructionPass::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000169INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
170 "Two-Address instruction pass", false, false)
171INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
172INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000173 "Two-Address instruction pass", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000174
Owen Andersona7aed182010-08-06 18:33:48 +0000175char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
Alkis Evlogimenos71390902003-12-18 22:40:24 +0000176
Cameron Zwarich35c30502013-02-23 04:49:20 +0000177static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg, LiveIntervals *LIS);
178
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000179/// sink3AddrInstruction - A two-address instruction has been converted to a
Evan Cheng5c26bde2008-03-13 06:37:55 +0000180/// three-address instruction to avoid clobbering a register. Try to sink it
Bill Wendling19e3c852008-05-10 00:12:52 +0000181/// past the instruction that would kill the above mentioned register to reduce
182/// register pressure.
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000183bool TwoAddressInstructionPass::
184sink3AddrInstruction(MachineInstr *MI, unsigned SavedReg,
185 MachineBasicBlock::iterator OldPos) {
Eli Friedman8a15a5a2011-09-23 22:41:57 +0000186 // FIXME: Shouldn't we be trying to do this before we three-addressify the
187 // instruction? After this transformation is done, we no longer need
188 // the instruction to be in three-address form.
189
Evan Cheng5c26bde2008-03-13 06:37:55 +0000190 // Check if it's safe to move this instruction.
191 bool SeenStore = true; // Be conservative.
Matthias Braun07066cc2015-05-19 21:22:20 +0000192 if (!MI->isSafeToMove(AA, SeenStore))
Evan Cheng5c26bde2008-03-13 06:37:55 +0000193 return false;
194
195 unsigned DefReg = 0;
196 SmallSet<unsigned, 4> UseRegs;
Bill Wendling19e3c852008-05-10 00:12:52 +0000197
Evan Cheng5c26bde2008-03-13 06:37:55 +0000198 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
199 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000200 if (!MO.isReg())
Evan Cheng5c26bde2008-03-13 06:37:55 +0000201 continue;
202 unsigned MOReg = MO.getReg();
203 if (!MOReg)
204 continue;
205 if (MO.isUse() && MOReg != SavedReg)
206 UseRegs.insert(MO.getReg());
207 if (!MO.isDef())
208 continue;
209 if (MO.isImplicit())
210 // Don't try to move it if it implicitly defines a register.
211 return false;
212 if (DefReg)
213 // For now, don't move any instructions that define multiple registers.
214 return false;
215 DefReg = MO.getReg();
216 }
217
218 // Find the instruction that kills SavedReg.
Craig Topperc0196b12014-04-14 00:51:57 +0000219 MachineInstr *KillMI = nullptr;
Cameron Zwarich35c30502013-02-23 04:49:20 +0000220 if (LIS) {
221 LiveInterval &LI = LIS->getInterval(SavedReg);
222 assert(LI.end() != LI.begin() &&
223 "Reg should not have empty live interval.");
224
225 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
226 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
227 if (I != LI.end() && I->start < MBBEndIdx)
228 return false;
229
230 --I;
231 KillMI = LIS->getInstructionFromIndex(I->end);
232 }
233 if (!KillMI) {
234 for (MachineRegisterInfo::use_nodbg_iterator
235 UI = MRI->use_nodbg_begin(SavedReg),
236 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
Owen Anderson16c6bf42014-03-13 23:12:04 +0000237 MachineOperand &UseMO = *UI;
Cameron Zwarich35c30502013-02-23 04:49:20 +0000238 if (!UseMO.isKill())
239 continue;
240 KillMI = UseMO.getParent();
241 break;
242 }
Evan Cheng5c26bde2008-03-13 06:37:55 +0000243 }
Bill Wendling19e3c852008-05-10 00:12:52 +0000244
Eli Friedman8a15a5a2011-09-23 22:41:57 +0000245 // If we find the instruction that kills SavedReg, and it is in an
246 // appropriate location, we can try to sink the current instruction
247 // past it.
248 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
Jakob Stoklund Olesen420798c2012-08-09 22:08:26 +0000249 KillMI == OldPos || KillMI->isTerminator())
Evan Cheng5c26bde2008-03-13 06:37:55 +0000250 return false;
251
Bill Wendling19e3c852008-05-10 00:12:52 +0000252 // If any of the definitions are used by another instruction between the
253 // position and the kill use, then it's not safe to sink it.
Andrew Trick808a7a62012-02-03 05:12:30 +0000254 //
Bill Wendling19e3c852008-05-10 00:12:52 +0000255 // FIXME: This can be sped up if there is an easy way to query whether an
Evan Chengc5618eb2008-06-18 07:49:14 +0000256 // instruction is before or after another instruction. Then we can use
Bill Wendling19e3c852008-05-10 00:12:52 +0000257 // MachineRegisterInfo def / use instead.
Craig Topperc0196b12014-04-14 00:51:57 +0000258 MachineOperand *KillMO = nullptr;
Evan Cheng5c26bde2008-03-13 06:37:55 +0000259 MachineBasicBlock::iterator KillPos = KillMI;
260 ++KillPos;
Bill Wendling19e3c852008-05-10 00:12:52 +0000261
Evan Chengc5618eb2008-06-18 07:49:14 +0000262 unsigned NumVisited = 0;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000263 for (MachineBasicBlock::iterator I = std::next(OldPos); I != KillPos; ++I) {
Evan Cheng5c26bde2008-03-13 06:37:55 +0000264 MachineInstr *OtherMI = I;
Dale Johannesen12565de2010-02-11 18:22:31 +0000265 // DBG_VALUE cannot be counted against the limit.
266 if (OtherMI->isDebugValue())
267 continue;
Evan Chengc5618eb2008-06-18 07:49:14 +0000268 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
269 return false;
270 ++NumVisited;
Evan Cheng5c26bde2008-03-13 06:37:55 +0000271 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
272 MachineOperand &MO = OtherMI->getOperand(i);
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000273 if (!MO.isReg())
Evan Cheng5c26bde2008-03-13 06:37:55 +0000274 continue;
275 unsigned MOReg = MO.getReg();
276 if (!MOReg)
277 continue;
278 if (DefReg == MOReg)
279 return false;
Bill Wendling19e3c852008-05-10 00:12:52 +0000280
Cameron Zwarich35c30502013-02-23 04:49:20 +0000281 if (MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))) {
Evan Cheng5c26bde2008-03-13 06:37:55 +0000282 if (OtherMI == KillMI && MOReg == SavedReg)
Evan Chengc5618eb2008-06-18 07:49:14 +0000283 // Save the operand that kills the register. We want to unset the kill
284 // marker if we can sink MI past it.
Evan Cheng5c26bde2008-03-13 06:37:55 +0000285 KillMO = &MO;
286 else if (UseRegs.count(MOReg))
287 // One of the uses is killed before the destination.
288 return false;
289 }
290 }
291 }
Jakob Stoklund Olesen420798c2012-08-09 22:08:26 +0000292 assert(KillMO && "Didn't find kill");
Evan Cheng5c26bde2008-03-13 06:37:55 +0000293
Cameron Zwarich35c30502013-02-23 04:49:20 +0000294 if (!LIS) {
295 // Update kill and LV information.
296 KillMO->setIsKill(false);
297 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
298 KillMO->setIsKill(true);
Andrew Trick808a7a62012-02-03 05:12:30 +0000299
Cameron Zwarich35c30502013-02-23 04:49:20 +0000300 if (LV)
301 LV->replaceKillInstruction(SavedReg, KillMI, MI);
302 }
Evan Cheng5c26bde2008-03-13 06:37:55 +0000303
304 // Move instruction to its destination.
305 MBB->remove(MI);
306 MBB->insert(KillPos, MI);
307
Jakob Stoklund Olesen24bc5142012-08-03 22:58:34 +0000308 if (LIS)
309 LIS->handleMove(MI);
310
Evan Cheng5c26bde2008-03-13 06:37:55 +0000311 ++Num3AddrSunk;
312 return true;
313}
314
Eric Christopher28919132015-03-03 22:03:03 +0000315/// getSingleDef -- return the MachineInstr* if it is the single def of the Reg
316/// in current BB.
317static MachineInstr *getSingleDef(unsigned Reg, MachineBasicBlock *BB,
318 const MachineRegisterInfo *MRI) {
319 MachineInstr *Ret = nullptr;
320 for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
321 if (DefMI.getParent() != BB || DefMI.isDebugValue())
322 continue;
323 if (!Ret)
324 Ret = &DefMI;
325 else if (Ret != &DefMI)
326 return nullptr;
327 }
328 return Ret;
329}
330
331/// Check if there is a reversed copy chain from FromReg to ToReg:
332/// %Tmp1 = copy %Tmp2;
333/// %FromReg = copy %Tmp1;
334/// %ToReg = add %FromReg ...
335/// %Tmp2 = copy %ToReg;
336/// MaxLen specifies the maximum length of the copy chain the func
337/// can walk through.
338bool TwoAddressInstructionPass::isRevCopyChain(unsigned FromReg, unsigned ToReg,
339 int Maxlen) {
340 unsigned TmpReg = FromReg;
341 for (int i = 0; i < Maxlen; i++) {
342 MachineInstr *Def = getSingleDef(TmpReg, MBB, MRI);
343 if (!Def || !Def->isCopy())
344 return false;
345
346 TmpReg = Def->getOperand(1).getReg();
347
348 if (TmpReg == ToReg)
349 return true;
350 }
351 return false;
352}
353
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000354/// noUseAfterLastDef - Return true if there are no intervening uses between the
Evan Chengabda6652009-01-25 03:53:59 +0000355/// last instruction in the MBB that defines the specified register and the
356/// two-address instruction which is being processed. It also returns the last
357/// def location by reference
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000358bool TwoAddressInstructionPass::noUseAfterLastDef(unsigned Reg, unsigned Dist,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000359 unsigned &LastDef) {
Evan Chengabda6652009-01-25 03:53:59 +0000360 LastDef = 0;
361 unsigned LastUse = Dist;
Owen Andersonb36376e2014-03-17 19:36:09 +0000362 for (MachineOperand &MO : MRI->reg_operands(Reg)) {
Evan Chengabda6652009-01-25 03:53:59 +0000363 MachineInstr *MI = MO.getParent();
Chris Lattnerb06015a2010-02-09 19:54:29 +0000364 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesenc3adf442010-02-09 02:01:46 +0000365 continue;
Evan Chengabda6652009-01-25 03:53:59 +0000366 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
367 if (DI == DistanceMap.end())
368 continue;
369 if (MO.isUse() && DI->second < LastUse)
370 LastUse = DI->second;
371 if (MO.isDef() && DI->second > LastDef)
372 LastDef = DI->second;
373 }
374
375 return !(LastUse > LastDef && LastUse < Dist);
376}
377
Evan Chengc2f95b52009-03-01 02:03:43 +0000378/// isCopyToReg - Return true if the specified MI is a copy instruction or
379/// a extract_subreg instruction. It also returns the source and destination
380/// registers and whether they are physical registers by reference.
381static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
382 unsigned &SrcReg, unsigned &DstReg,
383 bool &IsSrcPhys, bool &IsDstPhys) {
384 SrcReg = 0;
385 DstReg = 0;
Jakob Stoklund Olesen37c42a32010-07-16 04:45:42 +0000386 if (MI.isCopy()) {
387 DstReg = MI.getOperand(0).getReg();
388 SrcReg = MI.getOperand(1).getReg();
389 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
390 DstReg = MI.getOperand(0).getReg();
391 SrcReg = MI.getOperand(2).getReg();
392 } else
393 return false;
Evan Chengc2f95b52009-03-01 02:03:43 +0000394
Jakob Stoklund Olesen37c42a32010-07-16 04:45:42 +0000395 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
396 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
397 return true;
Evan Chengc2f95b52009-03-01 02:03:43 +0000398}
399
Cameron Zwarichc8964782013-02-21 07:02:28 +0000400/// isPLainlyKilled - Test if the given register value, which is used by the
401// given instruction, is killed by the given instruction.
402static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg,
403 LiveIntervals *LIS) {
404 if (LIS && TargetRegisterInfo::isVirtualRegister(Reg) &&
405 !LIS->isNotInMIMap(MI)) {
406 // FIXME: Sometimes tryInstructionTransform() will add instructions and
407 // test whether they can be folded before keeping them. In this case it
408 // sets a kill before recursively calling tryInstructionTransform() again.
409 // If there is no interval available, we assume that this instruction is
410 // one of those. A kill flag is manually inserted on the operand so the
411 // check below will handle it.
412 LiveInterval &LI = LIS->getInterval(Reg);
413 // This is to match the kill flag version where undefs don't have kill
414 // flags.
415 if (!LI.hasAtLeastOneValue())
416 return false;
417
418 SlotIndex useIdx = LIS->getInstructionIndex(MI);
419 LiveInterval::const_iterator I = LI.find(useIdx);
420 assert(I != LI.end() && "Reg must be live-in to use.");
Cameron Zwarich4e80d9e2013-02-23 04:49:22 +0000421 return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx);
Cameron Zwarichc8964782013-02-21 07:02:28 +0000422 }
423
424 return MI->killsRegister(Reg);
425}
426
Dan Gohmanad3e5492009-04-08 00:15:30 +0000427/// isKilled - Test if the given register value, which is used by the given
428/// instruction, is killed by the given instruction. This looks through
429/// coalescable copies to see if the original value is potentially not killed.
430///
431/// For example, in this code:
432///
433/// %reg1034 = copy %reg1024
434/// %reg1035 = copy %reg1025<kill>
435/// %reg1036 = add %reg1034<kill>, %reg1035<kill>
436///
437/// %reg1034 is not considered to be killed, since it is copied from a
438/// register which is not killed. Treating it as not killed lets the
439/// normal heuristics commute the (two-address) add, which lets
440/// coalescing eliminate the extra copy.
441///
Cameron Zwarich384026b2013-02-21 22:58:42 +0000442/// If allowFalsePositives is true then likely kills are treated as kills even
443/// if it can't be proven that they are kills.
Dan Gohmanad3e5492009-04-08 00:15:30 +0000444static bool isKilled(MachineInstr &MI, unsigned Reg,
445 const MachineRegisterInfo *MRI,
Cameron Zwarich94b204b2013-02-21 04:33:02 +0000446 const TargetInstrInfo *TII,
Cameron Zwarich384026b2013-02-21 22:58:42 +0000447 LiveIntervals *LIS,
448 bool allowFalsePositives) {
Dan Gohmanad3e5492009-04-08 00:15:30 +0000449 MachineInstr *DefMI = &MI;
450 for (;;) {
Cameron Zwarich384026b2013-02-21 22:58:42 +0000451 // All uses of physical registers are likely to be kills.
452 if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
453 (allowFalsePositives || MRI->hasOneUse(Reg)))
454 return true;
Cameron Zwarichc8964782013-02-21 07:02:28 +0000455 if (!isPlainlyKilled(DefMI, Reg, LIS))
Dan Gohmanad3e5492009-04-08 00:15:30 +0000456 return false;
457 if (TargetRegisterInfo::isPhysicalRegister(Reg))
458 return true;
459 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
460 // If there are multiple defs, we can't do a simple analysis, so just
461 // go with what the kill flag says.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000462 if (std::next(Begin) != MRI->def_end())
Dan Gohmanad3e5492009-04-08 00:15:30 +0000463 return true;
Owen Anderson16c6bf42014-03-13 23:12:04 +0000464 DefMI = Begin->getParent();
Dan Gohmanad3e5492009-04-08 00:15:30 +0000465 bool IsSrcPhys, IsDstPhys;
466 unsigned SrcReg, DstReg;
467 // If the def is something other than a copy, then it isn't going to
468 // be coalesced, so follow the kill flag.
469 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
470 return true;
471 Reg = SrcReg;
472 }
473}
474
Evan Chengc2f95b52009-03-01 02:03:43 +0000475/// isTwoAddrUse - Return true if the specified MI uses the specified register
476/// as a two-address use. If so, return the destination register by reference.
477static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
Evan Chengf85a76f2013-05-02 02:07:32 +0000478 for (unsigned i = 0, NumOps = MI.getNumOperands(); i != NumOps; ++i) {
Evan Chengc2f95b52009-03-01 02:03:43 +0000479 const MachineOperand &MO = MI.getOperand(i);
480 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
481 continue;
Evan Cheng1361cbb2009-03-19 20:30:06 +0000482 unsigned ti;
483 if (MI.isRegTiedToDefOperand(i, &ti)) {
Evan Chengc2f95b52009-03-01 02:03:43 +0000484 DstReg = MI.getOperand(ti).getReg();
485 return true;
486 }
487 }
488 return false;
489}
490
491/// findOnlyInterestingUse - Given a register, if has a single in-basic block
492/// use, return the use instruction if it's a copy or a two-address use.
493static
494MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
495 MachineRegisterInfo *MRI,
496 const TargetInstrInfo *TII,
Evan Cheng97871832009-04-14 00:32:25 +0000497 bool &IsCopy,
Evan Chengc2f95b52009-03-01 02:03:43 +0000498 unsigned &DstReg, bool &IsDstPhys) {
Evan Chengf94d6832010-03-03 21:18:38 +0000499 if (!MRI->hasOneNonDBGUse(Reg))
500 // None or more than one use.
Craig Topperc0196b12014-04-14 00:51:57 +0000501 return nullptr;
Owen Anderson16c6bf42014-03-13 23:12:04 +0000502 MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(Reg);
Evan Chengc2f95b52009-03-01 02:03:43 +0000503 if (UseMI.getParent() != MBB)
Craig Topperc0196b12014-04-14 00:51:57 +0000504 return nullptr;
Evan Chengc2f95b52009-03-01 02:03:43 +0000505 unsigned SrcReg;
506 bool IsSrcPhys;
Evan Cheng97871832009-04-14 00:32:25 +0000507 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
508 IsCopy = true;
Evan Chengc2f95b52009-03-01 02:03:43 +0000509 return &UseMI;
Evan Cheng97871832009-04-14 00:32:25 +0000510 }
Evan Chengc2f95b52009-03-01 02:03:43 +0000511 IsDstPhys = false;
Evan Cheng97871832009-04-14 00:32:25 +0000512 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
513 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Chengc2f95b52009-03-01 02:03:43 +0000514 return &UseMI;
Evan Cheng97871832009-04-14 00:32:25 +0000515 }
Craig Topperc0196b12014-04-14 00:51:57 +0000516 return nullptr;
Evan Chengc2f95b52009-03-01 02:03:43 +0000517}
518
519/// getMappedReg - Return the physical register the specified virtual register
520/// might be mapped to.
521static unsigned
522getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
523 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
524 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
525 if (SI == RegMap.end())
526 return 0;
527 Reg = SI->second;
528 }
529 if (TargetRegisterInfo::isPhysicalRegister(Reg))
530 return Reg;
531 return 0;
532}
533
534/// regsAreCompatible - Return true if the two registers are equal or aliased.
535///
536static bool
537regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
538 if (RegA == RegB)
539 return true;
540 if (!RegA || !RegB)
541 return false;
542 return TRI->regsOverlap(RegA, RegB);
543}
544
545
Manman Rencc1dc6d2012-07-25 18:28:13 +0000546/// isProfitableToCommute - Return true if it's potentially profitable to commute
Evan Chengabda6652009-01-25 03:53:59 +0000547/// the two-address instruction that's being processed.
548bool
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000549TwoAddressInstructionPass::
550isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
551 MachineInstr *MI, unsigned Dist) {
Evan Cheng822ddde2011-11-16 18:44:48 +0000552 if (OptLevel == CodeGenOpt::None)
553 return false;
554
Evan Chengabda6652009-01-25 03:53:59 +0000555 // Determine if it's profitable to commute this two address instruction. In
556 // general, we want no uses between this instruction and the definition of
557 // the two-address register.
558 // e.g.
559 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
560 // %reg1029<def> = MOV8rr %reg1028
561 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
562 // insert => %reg1030<def> = MOV8rr %reg1028
563 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
564 // In this case, it might not be possible to coalesce the second MOV8rr
565 // instruction if the first one is coalesced. So it would be profitable to
566 // commute it:
567 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
568 // %reg1029<def> = MOV8rr %reg1028
569 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
570 // insert => %reg1030<def> = MOV8rr %reg1029
Andrew Trick808a7a62012-02-03 05:12:30 +0000571 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
Evan Chengabda6652009-01-25 03:53:59 +0000572
Cameron Zwarich9e722ae2013-02-21 07:02:30 +0000573 if (!isPlainlyKilled(MI, regC, LIS))
Evan Chengabda6652009-01-25 03:53:59 +0000574 return false;
575
576 // Ok, we have something like:
577 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
578 // let's see if it's worth commuting it.
579
Evan Chengc2f95b52009-03-01 02:03:43 +0000580 // Look for situations like this:
581 // %reg1024<def> = MOV r1
582 // %reg1025<def> = MOV r0
583 // %reg1026<def> = ADD %reg1024, %reg1025
584 // r0 = MOV %reg1026
585 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
Evan Chengb64e7b72012-05-03 01:45:13 +0000586 unsigned ToRegA = getMappedReg(regA, DstRegMap);
587 if (ToRegA) {
588 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
589 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
Craig Topper12f0d9e2014-11-05 06:43:02 +0000590 bool CompB = FromRegB && regsAreCompatible(FromRegB, ToRegA, TRI);
591 bool CompC = FromRegC && regsAreCompatible(FromRegC, ToRegA, TRI);
592
593 // Compute if any of the following are true:
594 // -RegB is not tied to a register and RegC is compatible with RegA.
595 // -RegB is tied to the wrong physical register, but RegC is.
596 // -RegB is tied to the wrong physical register, and RegC isn't tied.
597 if ((!FromRegB && CompC) || (FromRegB && !CompB && (!FromRegC || CompC)))
598 return true;
599 // Don't compute if any of the following are true:
600 // -RegC is not tied to a register and RegB is compatible with RegA.
601 // -RegC is tied to the wrong physical register, but RegB is.
602 // -RegC is tied to the wrong physical register, and RegB isn't tied.
603 if ((!FromRegC && CompB) || (FromRegC && !CompC && (!FromRegB || CompB)))
604 return false;
Evan Chengb64e7b72012-05-03 01:45:13 +0000605 }
Evan Chengc2f95b52009-03-01 02:03:43 +0000606
Evan Chengabda6652009-01-25 03:53:59 +0000607 // If there is a use of regC between its last def (could be livein) and this
608 // instruction, then bail.
609 unsigned LastDefC = 0;
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000610 if (!noUseAfterLastDef(regC, Dist, LastDefC))
Evan Chengabda6652009-01-25 03:53:59 +0000611 return false;
612
613 // If there is a use of regB between its last def (could be livein) and this
614 // instruction, then go ahead and make this transformation.
615 unsigned LastDefB = 0;
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000616 if (!noUseAfterLastDef(regB, Dist, LastDefB))
Evan Chengabda6652009-01-25 03:53:59 +0000617 return true;
618
Eric Christopher28919132015-03-03 22:03:03 +0000619 // Look for situation like this:
620 // %reg101 = MOV %reg100
621 // %reg102 = ...
622 // %reg103 = ADD %reg102, %reg101
623 // ... = %reg103 ...
624 // %reg100 = MOV %reg103
625 // If there is a reversed copy chain from reg101 to reg103, commute the ADD
626 // to eliminate an otherwise unavoidable copy.
627 // FIXME:
628 // We can extend the logic further: If an pair of operands in an insn has
629 // been merged, the insn could be regarded as a virtual copy, and the virtual
630 // copy could also be used to construct a copy chain.
631 // To more generally minimize register copies, ideally the logic of two addr
632 // instruction pass should be integrated with register allocation pass where
633 // interference graph is available.
634 if (isRevCopyChain(regC, regA, 3))
635 return true;
636
637 if (isRevCopyChain(regB, regA, 3))
638 return false;
639
Evan Chengabda6652009-01-25 03:53:59 +0000640 // Since there are no intervening uses for both registers, then commute
641 // if the def of regC is closer. Its live interval is shorter.
642 return LastDefB && LastDefC && LastDefC > LastDefB;
643}
644
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000645/// commuteInstruction - Commute a two-address instruction and update the basic
Evan Cheng6d897062009-01-23 23:27:33 +0000646/// block, distance map, and live variables if needed. Return true if it is
647/// successful.
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000648bool TwoAddressInstructionPass::
649commuteInstruction(MachineBasicBlock::iterator &mi,
650 unsigned RegB, unsigned RegC, unsigned Dist) {
Evan Cheng6d897062009-01-23 23:27:33 +0000651 MachineInstr *MI = mi;
David Greeneac9f8192010-01-05 01:24:21 +0000652 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
Evan Cheng6d897062009-01-23 23:27:33 +0000653 MachineInstr *NewMI = TII->commuteInstruction(MI);
654
Craig Topperc0196b12014-04-14 00:51:57 +0000655 if (NewMI == nullptr) {
David Greeneac9f8192010-01-05 01:24:21 +0000656 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
Evan Cheng6d897062009-01-23 23:27:33 +0000657 return false;
658 }
659
David Greeneac9f8192010-01-05 01:24:21 +0000660 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
Cameron Zwariche6907bc2013-02-23 23:13:28 +0000661 assert(NewMI == MI &&
662 "TargetInstrInfo::commuteInstruction() should not return a new "
663 "instruction unless it was requested.");
Evan Chengc2f95b52009-03-01 02:03:43 +0000664
665 // Update source register map.
666 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
667 if (FromRegC) {
668 unsigned RegA = MI->getOperand(0).getReg();
669 SrcRegMap[RegA] = FromRegC;
670 }
671
Evan Cheng6d897062009-01-23 23:27:33 +0000672 return true;
673}
674
Evan Cheng09f5be82009-03-30 21:34:07 +0000675/// isProfitableToConv3Addr - Return true if it is profitable to convert the
676/// given 2-address instruction to a 3-address one.
677bool
Evan Cheng15fed7a2011-03-02 01:08:17 +0000678TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
Evan Cheng09f5be82009-03-30 21:34:07 +0000679 // Look for situations like this:
680 // %reg1024<def> = MOV r1
681 // %reg1025<def> = MOV r0
682 // %reg1026<def> = ADD %reg1024, %reg1025
683 // r2 = MOV %reg1026
684 // Turn ADD into a 3-address instruction to avoid a copy.
Evan Cheng15fed7a2011-03-02 01:08:17 +0000685 unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
686 if (!FromRegB)
687 return false;
Evan Cheng09f5be82009-03-30 21:34:07 +0000688 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
Evan Cheng15fed7a2011-03-02 01:08:17 +0000689 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
Evan Cheng09f5be82009-03-30 21:34:07 +0000690}
691
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000692/// convertInstTo3Addr - Convert the specified two-address instruction into a
Evan Cheng09f5be82009-03-30 21:34:07 +0000693/// three address one. Return true if this transformation was successful.
694bool
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000695TwoAddressInstructionPass::convertInstTo3Addr(MachineBasicBlock::iterator &mi,
Evan Cheng09f5be82009-03-30 21:34:07 +0000696 MachineBasicBlock::iterator &nmi,
Evan Chengd4fcc052011-02-10 02:20:55 +0000697 unsigned RegA, unsigned RegB,
698 unsigned Dist) {
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000699 // FIXME: Why does convertToThreeAddress() need an iterator reference?
700 MachineFunction::iterator MFI = MBB;
701 MachineInstr *NewMI = TII->convertToThreeAddress(MFI, mi, LV);
702 assert(MBB == MFI && "convertToThreeAddress changed iterator reference");
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000703 if (!NewMI)
704 return false;
Evan Cheng09f5be82009-03-30 21:34:07 +0000705
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000706 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
707 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
708 bool Sunk = false;
Jakob Stoklund Olesen24bc5142012-08-03 22:58:34 +0000709
Cameron Zwarich2ad3ca32013-02-20 22:10:02 +0000710 if (LIS)
711 LIS->ReplaceMachineInstrInMaps(mi, NewMI);
Evan Cheng09f5be82009-03-30 21:34:07 +0000712
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000713 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
714 // FIXME: Temporary workaround. If the new instruction doesn't
715 // uses RegB, convertToThreeAddress must have created more
716 // then one instruction.
717 Sunk = sink3AddrInstruction(NewMI, RegB, mi);
Evan Cheng09f5be82009-03-30 21:34:07 +0000718
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000719 MBB->erase(mi); // Nuke the old inst.
Evan Chengd4fcc052011-02-10 02:20:55 +0000720
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000721 if (!Sunk) {
722 DistanceMap.insert(std::make_pair(NewMI, Dist));
723 mi = NewMI;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000724 nmi = std::next(mi);
Evan Cheng09f5be82009-03-30 21:34:07 +0000725 }
726
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000727 // Update source and destination register maps.
728 SrcRegMap.erase(RegA);
729 DstRegMap.erase(RegB);
730 return true;
Evan Cheng09f5be82009-03-30 21:34:07 +0000731}
732
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000733/// scanUses - Scan forward recursively for only uses, update maps if the use
Evan Cheng15fed7a2011-03-02 01:08:17 +0000734/// is a copy or a two-address instruction.
735void
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000736TwoAddressInstructionPass::scanUses(unsigned DstReg) {
Evan Cheng15fed7a2011-03-02 01:08:17 +0000737 SmallVector<unsigned, 4> VirtRegPairs;
738 bool IsDstPhys;
739 bool IsCopy = false;
740 unsigned NewReg = 0;
741 unsigned Reg = DstReg;
742 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
743 NewReg, IsDstPhys)) {
David Blaikie70573dc2014-11-19 07:49:26 +0000744 if (IsCopy && !Processed.insert(UseMI).second)
Evan Cheng15fed7a2011-03-02 01:08:17 +0000745 break;
746
747 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
748 if (DI != DistanceMap.end())
749 // Earlier in the same MBB.Reached via a back edge.
750 break;
751
752 if (IsDstPhys) {
753 VirtRegPairs.push_back(NewReg);
754 break;
755 }
756 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
757 if (!isNew)
758 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
759 VirtRegPairs.push_back(NewReg);
760 Reg = NewReg;
761 }
762
763 if (!VirtRegPairs.empty()) {
764 unsigned ToReg = VirtRegPairs.back();
765 VirtRegPairs.pop_back();
766 while (!VirtRegPairs.empty()) {
767 unsigned FromReg = VirtRegPairs.back();
768 VirtRegPairs.pop_back();
769 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
770 if (!isNew)
771 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
772 ToReg = FromReg;
773 }
774 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
775 if (!isNew)
776 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
777 }
778}
779
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000780/// processCopy - If the specified instruction is not yet processed, process it
Evan Chengc2f95b52009-03-01 02:03:43 +0000781/// if it's a copy. For a copy instruction, we find the physical registers the
782/// source and destination registers might be mapped to. These are kept in
783/// point-to maps used to determine future optimizations. e.g.
784/// v1024 = mov r0
785/// v1025 = mov r1
786/// v1026 = add v1024, v1025
787/// r1 = mov r1026
788/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
789/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
790/// potentially joined with r1 on the output side. It's worthwhile to commute
791/// 'add' to eliminate a copy.
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000792void TwoAddressInstructionPass::processCopy(MachineInstr *MI) {
Evan Chengc2f95b52009-03-01 02:03:43 +0000793 if (Processed.count(MI))
794 return;
795
796 bool IsSrcPhys, IsDstPhys;
797 unsigned SrcReg, DstReg;
798 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
799 return;
800
801 if (IsDstPhys && !IsSrcPhys)
802 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
803 else if (!IsDstPhys && IsSrcPhys) {
Evan Chengf0843802009-04-13 20:04:24 +0000804 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
805 if (!isNew)
806 assert(SrcRegMap[DstReg] == SrcReg &&
807 "Can't map to two src physical registers!");
Evan Chengc2f95b52009-03-01 02:03:43 +0000808
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000809 scanUses(DstReg);
Evan Chengc2f95b52009-03-01 02:03:43 +0000810 }
811
812 Processed.insert(MI);
Evan Cheng15fed7a2011-03-02 01:08:17 +0000813 return;
Evan Chengc2f95b52009-03-01 02:03:43 +0000814}
815
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000816/// rescheduleMIBelowKill - If there is one more local instruction that reads
Evan Cheng30f44ad2011-11-14 19:48:55 +0000817/// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
818/// instruction in order to eliminate the need for the copy.
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000819bool TwoAddressInstructionPass::
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000820rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000821 MachineBasicBlock::iterator &nmi,
822 unsigned Reg) {
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000823 // Bail immediately if we don't have LV or LIS available. We use them to find
824 // kills efficiently.
825 if (!LV && !LIS)
Chandler Carruthdb5536f2012-07-15 03:29:46 +0000826 return false;
827
Evan Cheng30f44ad2011-11-14 19:48:55 +0000828 MachineInstr *MI = &*mi;
Andrew Trick808a7a62012-02-03 05:12:30 +0000829 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
Evan Cheng30f44ad2011-11-14 19:48:55 +0000830 if (DI == DistanceMap.end())
831 // Must be created from unfolded load. Don't waste time trying this.
832 return false;
833
Craig Topperc0196b12014-04-14 00:51:57 +0000834 MachineInstr *KillMI = nullptr;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000835 if (LIS) {
836 LiveInterval &LI = LIS->getInterval(Reg);
837 assert(LI.end() != LI.begin() &&
838 "Reg should not have empty live interval.");
839
840 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
841 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
842 if (I != LI.end() && I->start < MBBEndIdx)
843 return false;
844
845 --I;
846 KillMI = LIS->getInstructionFromIndex(I->end);
847 } else {
848 KillMI = LV->getVarInfo(Reg).findKill(MBB);
849 }
Chandler Carruthdb5536f2012-07-15 03:29:46 +0000850 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng30f44ad2011-11-14 19:48:55 +0000851 // Don't mess with copies, they may be coalesced later.
852 return false;
853
Evan Cheng7f8e5632011-12-07 07:15:52 +0000854 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
855 KillMI->isBranch() || KillMI->isTerminator())
Evan Cheng30f44ad2011-11-14 19:48:55 +0000856 // Don't move pass calls, etc.
857 return false;
858
859 unsigned DstReg;
860 if (isTwoAddrUse(*KillMI, Reg, DstReg))
861 return false;
862
Evan Cheng7098c4e2011-11-15 06:26:51 +0000863 bool SeenStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +0000864 if (!MI->isSafeToMove(AA, SeenStore))
Evan Cheng30f44ad2011-11-14 19:48:55 +0000865 return false;
866
867 if (TII->getInstrLatency(InstrItins, MI) > 1)
868 // FIXME: Needs more sophisticated heuristics.
869 return false;
870
871 SmallSet<unsigned, 2> Uses;
Evan Chengb8c55a52011-11-16 03:47:42 +0000872 SmallSet<unsigned, 2> Kills;
Evan Cheng30f44ad2011-11-14 19:48:55 +0000873 SmallSet<unsigned, 2> Defs;
874 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
875 const MachineOperand &MO = MI->getOperand(i);
876 if (!MO.isReg())
877 continue;
878 unsigned MOReg = MO.getReg();
879 if (!MOReg)
880 continue;
881 if (MO.isDef())
882 Defs.insert(MOReg);
Evan Chengb8c55a52011-11-16 03:47:42 +0000883 else {
Evan Cheng30f44ad2011-11-14 19:48:55 +0000884 Uses.insert(MOReg);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000885 if (MOReg != Reg && (MO.isKill() ||
886 (LIS && isPlainlyKilled(MI, MOReg, LIS))))
Evan Chengb8c55a52011-11-16 03:47:42 +0000887 Kills.insert(MOReg);
888 }
Evan Cheng30f44ad2011-11-14 19:48:55 +0000889 }
890
891 // Move the copies connected to MI down as well.
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000892 MachineBasicBlock::iterator Begin = MI;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000893 MachineBasicBlock::iterator AfterMI = std::next(Begin);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000894
895 MachineBasicBlock::iterator End = AfterMI;
896 while (End->isCopy() && Defs.count(End->getOperand(1).getReg())) {
897 Defs.insert(End->getOperand(0).getReg());
898 ++End;
Evan Cheng30f44ad2011-11-14 19:48:55 +0000899 }
900
901 // Check if the reschedule will not break depedencies.
902 unsigned NumVisited = 0;
903 MachineBasicBlock::iterator KillPos = KillMI;
904 ++KillPos;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000905 for (MachineBasicBlock::iterator I = End; I != KillPos; ++I) {
Evan Cheng30f44ad2011-11-14 19:48:55 +0000906 MachineInstr *OtherMI = I;
907 // DBG_VALUE cannot be counted against the limit.
908 if (OtherMI->isDebugValue())
909 continue;
910 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
911 return false;
912 ++NumVisited;
Evan Cheng7f8e5632011-12-07 07:15:52 +0000913 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
914 OtherMI->isBranch() || OtherMI->isTerminator())
Evan Cheng30f44ad2011-11-14 19:48:55 +0000915 // Don't move pass calls, etc.
916 return false;
917 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
918 const MachineOperand &MO = OtherMI->getOperand(i);
919 if (!MO.isReg())
920 continue;
921 unsigned MOReg = MO.getReg();
922 if (!MOReg)
923 continue;
924 if (MO.isDef()) {
925 if (Uses.count(MOReg))
926 // Physical register use would be clobbered.
927 return false;
928 if (!MO.isDead() && Defs.count(MOReg))
929 // May clobber a physical register def.
930 // FIXME: This may be too conservative. It's ok if the instruction
931 // is sunken completely below the use.
932 return false;
933 } else {
934 if (Defs.count(MOReg))
935 return false;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000936 bool isKill = MO.isKill() ||
937 (LIS && isPlainlyKilled(OtherMI, MOReg, LIS));
Evan Chengb8c55a52011-11-16 03:47:42 +0000938 if (MOReg != Reg &&
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000939 ((isKill && Uses.count(MOReg)) || Kills.count(MOReg)))
Evan Cheng30f44ad2011-11-14 19:48:55 +0000940 // Don't want to extend other live ranges and update kills.
941 return false;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000942 if (MOReg == Reg && !isKill)
Chandler Carruthdb5536f2012-07-15 03:29:46 +0000943 // We can't schedule across a use of the register in question.
944 return false;
945 // Ensure that if this is register in question, its the kill we expect.
946 assert((MOReg != Reg || OtherMI == KillMI) &&
947 "Found multiple kills of a register in a basic block");
Evan Cheng30f44ad2011-11-14 19:48:55 +0000948 }
949 }
950 }
951
952 // Move debug info as well.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000953 while (Begin != MBB->begin() && std::prev(Begin)->isDebugValue())
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000954 --Begin;
955
956 nmi = End;
957 MachineBasicBlock::iterator InsertPos = KillPos;
958 if (LIS) {
959 // We have to move the copies first so that the MBB is still well-formed
960 // when calling handleMove().
961 for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) {
962 MachineInstr *CopyMI = MBBI;
963 ++MBBI;
964 MBB->splice(InsertPos, MBB, CopyMI);
965 LIS->handleMove(CopyMI);
966 InsertPos = CopyMI;
967 }
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000968 End = std::next(MachineBasicBlock::iterator(MI));
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000969 }
Evan Cheng30f44ad2011-11-14 19:48:55 +0000970
971 // Copies following MI may have been moved as well.
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000972 MBB->splice(InsertPos, MBB, Begin, End);
Evan Cheng30f44ad2011-11-14 19:48:55 +0000973 DistanceMap.erase(DI);
974
Chandler Carruthdb5536f2012-07-15 03:29:46 +0000975 // Update live variables
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000976 if (LIS) {
Jakob Stoklund Olesen24bc5142012-08-03 22:58:34 +0000977 LIS->handleMove(MI);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000978 } else {
979 LV->removeVirtualRegisterKilled(Reg, KillMI);
980 LV->addVirtualRegisterKilled(Reg, MI);
981 }
Evan Cheng30f44ad2011-11-14 19:48:55 +0000982
Jakob Stoklund Olesen0ef03112012-07-17 17:57:23 +0000983 DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
Evan Cheng30f44ad2011-11-14 19:48:55 +0000984 return true;
985}
986
987/// isDefTooClose - Return true if the re-scheduling will put the given
988/// instruction too close to the defs of its register dependencies.
989bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000990 MachineInstr *MI) {
Owen Andersonb36376e2014-03-17 19:36:09 +0000991 for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
992 if (DefMI.getParent() != MBB || DefMI.isCopy() || DefMI.isCopyLike())
Evan Cheng30f44ad2011-11-14 19:48:55 +0000993 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +0000994 if (&DefMI == MI)
Evan Cheng30f44ad2011-11-14 19:48:55 +0000995 return true; // MI is defining something KillMI uses
Owen Andersonb36376e2014-03-17 19:36:09 +0000996 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(&DefMI);
Evan Cheng30f44ad2011-11-14 19:48:55 +0000997 if (DDI == DistanceMap.end())
998 return true; // Below MI
999 unsigned DefDist = DDI->second;
1000 assert(Dist > DefDist && "Visited def already?");
Owen Andersonb36376e2014-03-17 19:36:09 +00001001 if (TII->getInstrLatency(InstrItins, &DefMI) > (Dist - DefDist))
Evan Cheng30f44ad2011-11-14 19:48:55 +00001002 return true;
1003 }
1004 return false;
1005}
1006
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +00001007/// rescheduleKillAboveMI - If there is one more local instruction that reads
Evan Cheng30f44ad2011-11-14 19:48:55 +00001008/// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
1009/// current two-address instruction in order to eliminate the need for the
1010/// copy.
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +00001011bool TwoAddressInstructionPass::
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001012rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +00001013 MachineBasicBlock::iterator &nmi,
1014 unsigned Reg) {
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001015 // Bail immediately if we don't have LV or LIS available. We use them to find
1016 // kills efficiently.
1017 if (!LV && !LIS)
Chandler Carruthdb5536f2012-07-15 03:29:46 +00001018 return false;
1019
Evan Cheng30f44ad2011-11-14 19:48:55 +00001020 MachineInstr *MI = &*mi;
1021 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
1022 if (DI == DistanceMap.end())
1023 // Must be created from unfolded load. Don't waste time trying this.
1024 return false;
1025
Craig Topperc0196b12014-04-14 00:51:57 +00001026 MachineInstr *KillMI = nullptr;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001027 if (LIS) {
1028 LiveInterval &LI = LIS->getInterval(Reg);
1029 assert(LI.end() != LI.begin() &&
1030 "Reg should not have empty live interval.");
1031
1032 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
1033 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
1034 if (I != LI.end() && I->start < MBBEndIdx)
1035 return false;
1036
1037 --I;
1038 KillMI = LIS->getInstructionFromIndex(I->end);
1039 } else {
1040 KillMI = LV->getVarInfo(Reg).findKill(MBB);
1041 }
Chandler Carruthdb5536f2012-07-15 03:29:46 +00001042 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng30f44ad2011-11-14 19:48:55 +00001043 // Don't mess with copies, they may be coalesced later.
1044 return false;
1045
1046 unsigned DstReg;
1047 if (isTwoAddrUse(*KillMI, Reg, DstReg))
1048 return false;
1049
Evan Cheng7098c4e2011-11-15 06:26:51 +00001050 bool SeenStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +00001051 if (!KillMI->isSafeToMove(AA, SeenStore))
Evan Cheng30f44ad2011-11-14 19:48:55 +00001052 return false;
1053
1054 SmallSet<unsigned, 2> Uses;
1055 SmallSet<unsigned, 2> Kills;
1056 SmallSet<unsigned, 2> Defs;
1057 SmallSet<unsigned, 2> LiveDefs;
1058 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
1059 const MachineOperand &MO = KillMI->getOperand(i);
1060 if (!MO.isReg())
1061 continue;
1062 unsigned MOReg = MO.getReg();
1063 if (MO.isUse()) {
1064 if (!MOReg)
1065 continue;
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001066 if (isDefTooClose(MOReg, DI->second, MI))
Evan Cheng30f44ad2011-11-14 19:48:55 +00001067 return false;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001068 bool isKill = MO.isKill() || (LIS && isPlainlyKilled(KillMI, MOReg, LIS));
1069 if (MOReg == Reg && !isKill)
Chandler Carruthdb5536f2012-07-15 03:29:46 +00001070 return false;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001071 Uses.insert(MOReg);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001072 if (isKill && MOReg != Reg)
Evan Cheng30f44ad2011-11-14 19:48:55 +00001073 Kills.insert(MOReg);
1074 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1075 Defs.insert(MOReg);
1076 if (!MO.isDead())
1077 LiveDefs.insert(MOReg);
1078 }
1079 }
1080
1081 // Check if the reschedule will not break depedencies.
1082 unsigned NumVisited = 0;
1083 MachineBasicBlock::iterator KillPos = KillMI;
1084 for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
1085 MachineInstr *OtherMI = I;
1086 // DBG_VALUE cannot be counted against the limit.
1087 if (OtherMI->isDebugValue())
1088 continue;
1089 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
1090 return false;
1091 ++NumVisited;
Evan Cheng7f8e5632011-12-07 07:15:52 +00001092 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
1093 OtherMI->isBranch() || OtherMI->isTerminator())
Evan Cheng30f44ad2011-11-14 19:48:55 +00001094 // Don't move pass calls, etc.
1095 return false;
Evan Cheng9ddd69a2011-11-16 03:05:12 +00001096 SmallVector<unsigned, 2> OtherDefs;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001097 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
1098 const MachineOperand &MO = OtherMI->getOperand(i);
1099 if (!MO.isReg())
1100 continue;
1101 unsigned MOReg = MO.getReg();
1102 if (!MOReg)
1103 continue;
1104 if (MO.isUse()) {
1105 if (Defs.count(MOReg))
1106 // Moving KillMI can clobber the physical register if the def has
1107 // not been seen.
1108 return false;
1109 if (Kills.count(MOReg))
1110 // Don't want to extend other live ranges and update kills.
1111 return false;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001112 if (OtherMI != MI && MOReg == Reg &&
1113 !(MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))))
Chandler Carruthdb5536f2012-07-15 03:29:46 +00001114 // We can't schedule across a use of the register in question.
1115 return false;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001116 } else {
Evan Cheng9ddd69a2011-11-16 03:05:12 +00001117 OtherDefs.push_back(MOReg);
Evan Cheng30f44ad2011-11-14 19:48:55 +00001118 }
1119 }
Evan Cheng9ddd69a2011-11-16 03:05:12 +00001120
1121 for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
1122 unsigned MOReg = OtherDefs[i];
1123 if (Uses.count(MOReg))
1124 return false;
1125 if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1126 LiveDefs.count(MOReg))
1127 return false;
1128 // Physical register def is seen.
1129 Defs.erase(MOReg);
1130 }
Evan Cheng30f44ad2011-11-14 19:48:55 +00001131 }
1132
1133 // Move the old kill above MI, don't forget to move debug info as well.
1134 MachineBasicBlock::iterator InsertPos = mi;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001135 while (InsertPos != MBB->begin() && std::prev(InsertPos)->isDebugValue())
Evan Chengf2fc5082011-11-14 21:11:15 +00001136 --InsertPos;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001137 MachineBasicBlock::iterator From = KillMI;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001138 MachineBasicBlock::iterator To = std::next(From);
1139 while (std::prev(From)->isDebugValue())
Evan Cheng30f44ad2011-11-14 19:48:55 +00001140 --From;
1141 MBB->splice(InsertPos, MBB, From, To);
1142
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001143 nmi = std::prev(InsertPos); // Backtrack so we process the moved instr.
Evan Cheng30f44ad2011-11-14 19:48:55 +00001144 DistanceMap.erase(DI);
1145
Chandler Carruthdb5536f2012-07-15 03:29:46 +00001146 // Update live variables
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001147 if (LIS) {
Jakob Stoklund Olesen24bc5142012-08-03 22:58:34 +00001148 LIS->handleMove(KillMI);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001149 } else {
1150 LV->removeVirtualRegisterKilled(Reg, KillMI);
1151 LV->addVirtualRegisterKilled(Reg, MI);
1152 }
Chandler Carruthdb5536f2012-07-15 03:29:46 +00001153
Jakob Stoklund Olesen0ef03112012-07-17 17:57:23 +00001154 DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
Evan Cheng30f44ad2011-11-14 19:48:55 +00001155 return true;
1156}
1157
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +00001158/// tryInstructionTransform - For the case where an instruction has a single
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001159/// pair of tied register operands, attempt some transformations that may
1160/// either eliminate the tied operands or improve the opportunities for
Lang Hames3ad11ff2012-04-09 20:17:30 +00001161/// coalescing away the register copy. Returns true if no copy needs to be
1162/// inserted to untie mi's operands (either because they were untied, or
Cameron Zwarichf05c0cb2013-02-24 00:27:26 +00001163/// because mi was rescheduled, and will be visited again later). If the
1164/// shouldOnlyCommute flag is true, only instruction commutation is attempted.
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001165bool TwoAddressInstructionPass::
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +00001166tryInstructionTransform(MachineBasicBlock::iterator &mi,
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001167 MachineBasicBlock::iterator &nmi,
Cameron Zwarichf05c0cb2013-02-24 00:27:26 +00001168 unsigned SrcIdx, unsigned DstIdx,
1169 unsigned Dist, bool shouldOnlyCommute) {
Evan Cheng822ddde2011-11-16 18:44:48 +00001170 if (OptLevel == CodeGenOpt::None)
1171 return false;
1172
Evan Cheng30f44ad2011-11-14 19:48:55 +00001173 MachineInstr &MI = *mi;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001174 unsigned regA = MI.getOperand(DstIdx).getReg();
1175 unsigned regB = MI.getOperand(SrcIdx).getReg();
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001176
1177 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1178 "cannot make instruction into two-address form");
Cameron Zwarich384026b2013-02-21 22:58:42 +00001179 bool regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001180
Evan Chengb64e7b72012-05-03 01:45:13 +00001181 if (TargetRegisterInfo::isVirtualRegister(regA))
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001182 scanUses(regA);
Evan Chengb64e7b72012-05-03 01:45:13 +00001183
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001184 // Check if it is profitable to commute the operands.
1185 unsigned SrcOp1, SrcOp2;
1186 unsigned regC = 0;
1187 unsigned regCIdx = ~0U;
1188 bool TryCommute = false;
1189 bool AggressiveCommute = false;
Evan Cheng7f8e5632011-12-07 07:15:52 +00001190 if (MI.isCommutable() && MI.getNumOperands() >= 3 &&
Evan Cheng30f44ad2011-11-14 19:48:55 +00001191 TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001192 if (SrcIdx == SrcOp1)
1193 regCIdx = SrcOp2;
1194 else if (SrcIdx == SrcOp2)
1195 regCIdx = SrcOp1;
1196
1197 if (regCIdx != ~0U) {
Evan Cheng30f44ad2011-11-14 19:48:55 +00001198 regC = MI.getOperand(regCIdx).getReg();
Cameron Zwarich384026b2013-02-21 22:58:42 +00001199 if (!regBKilled && isKilled(MI, regC, MRI, TII, LIS, false))
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001200 // If C dies but B does not, swap the B and C operands.
1201 // This makes the live ranges of A and C joinable.
1202 TryCommute = true;
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001203 else if (isProfitableToCommute(regA, regB, regC, &MI, Dist)) {
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001204 TryCommute = true;
1205 AggressiveCommute = true;
1206 }
1207 }
1208 }
1209
Quentin Colombet9729fb32015-07-01 23:12:13 +00001210 // If the instruction is convertible to 3 Addr, instead
1211 // of returning try 3 Addr transformation aggresively and
1212 // use this variable to check later. Because it might be better.
1213 // For example, we can just use `leal (%rsi,%rdi), %eax` and `ret`
1214 // instead of the following code.
1215 // addl %esi, %edi
1216 // movl %edi, %eax
1217 // ret
Quentin Colombet40dd5102015-07-06 20:12:54 +00001218 bool Commuted = false;
Quentin Colombet9729fb32015-07-01 23:12:13 +00001219
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001220 // If it's profitable to commute, try to do so.
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001221 if (TryCommute && commuteInstruction(mi, regB, regC, Dist)) {
Quentin Colombet40dd5102015-07-06 20:12:54 +00001222 Commuted = true;
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001223 ++NumCommuted;
1224 if (AggressiveCommute)
1225 ++NumAggrCommuted;
Quentin Colombet9729fb32015-07-01 23:12:13 +00001226 if (!MI.isConvertibleTo3Addr())
1227 return false;
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001228 }
1229
Cameron Zwarichf05c0cb2013-02-24 00:27:26 +00001230 if (shouldOnlyCommute)
1231 return false;
1232
Evan Cheng30f44ad2011-11-14 19:48:55 +00001233 // If there is one more use of regB later in the same MBB, consider
1234 // re-schedule this MI below it.
Quentin Colombet40dd5102015-07-06 20:12:54 +00001235 if (!Commuted && EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) {
Evan Cheng30f44ad2011-11-14 19:48:55 +00001236 ++NumReSchedDowns;
Lang Hames3ad11ff2012-04-09 20:17:30 +00001237 return true;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001238 }
1239
Evan Cheng7f8e5632011-12-07 07:15:52 +00001240 if (MI.isConvertibleTo3Addr()) {
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001241 // This instruction is potentially convertible to a true
1242 // three-address instruction. Check if it is profitable.
Evan Cheng15fed7a2011-03-02 01:08:17 +00001243 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001244 // Try to convert it.
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001245 if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001246 ++NumConvertedTo3Addr;
1247 return true; // Done with this instruction.
1248 }
1249 }
1250 }
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001251
Quentin Colombet9729fb32015-07-01 23:12:13 +00001252 // Return if it is commuted but 3 addr conversion is failed.
Quentin Colombet40dd5102015-07-06 20:12:54 +00001253 if (Commuted)
Quentin Colombet9729fb32015-07-01 23:12:13 +00001254 return false;
1255
Evan Cheng30f44ad2011-11-14 19:48:55 +00001256 // If there is one more use of regB later in the same MBB, consider
1257 // re-schedule it before this MI if it's legal.
Andrew Trick608a6982013-04-24 15:54:39 +00001258 if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) {
Evan Cheng30f44ad2011-11-14 19:48:55 +00001259 ++NumReSchedUps;
Lang Hames3ad11ff2012-04-09 20:17:30 +00001260 return true;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001261 }
1262
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001263 // If this is an instruction with a load folded into it, try unfolding
1264 // the load, e.g. avoid this:
1265 // movq %rdx, %rcx
1266 // addq (%rax), %rcx
1267 // in favor of this:
1268 // movq (%rax), %rcx
1269 // addq %rdx, %rcx
1270 // because it's preferable to schedule a load than a register copy.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001271 if (MI.mayLoad() && !regBKilled) {
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001272 // Determine if a load can be unfolded.
1273 unsigned LoadRegIndex;
1274 unsigned NewOpc =
Evan Cheng30f44ad2011-11-14 19:48:55 +00001275 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001276 /*UnfoldLoad=*/true,
1277 /*UnfoldStore=*/false,
1278 &LoadRegIndex);
1279 if (NewOpc != 0) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00001280 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1281 if (UnfoldMCID.getNumDefs() == 1) {
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001282 // Unfold the load.
Evan Cheng30f44ad2011-11-14 19:48:55 +00001283 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001284 const TargetRegisterClass *RC =
Andrew Trick32aea352012-05-03 01:14:37 +00001285 TRI->getAllocatableClass(
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001286 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001287 unsigned Reg = MRI->createVirtualRegister(RC);
1288 SmallVector<MachineInstr *, 2> NewMIs;
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001289 if (!TII->unfoldMemoryOperand(*MF, &MI, Reg,
Evan Cheng0ce84482010-07-02 20:36:18 +00001290 /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
1291 NewMIs)) {
1292 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1293 return false;
1294 }
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001295 assert(NewMIs.size() == 2 &&
1296 "Unfolded a load into multiple instructions!");
1297 // The load was previously folded, so this is the only use.
1298 NewMIs[1]->addRegisterKilled(Reg, TRI);
1299
1300 // Tentatively insert the instructions into the block so that they
1301 // look "normal" to the transformation logic.
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001302 MBB->insert(mi, NewMIs[0]);
1303 MBB->insert(mi, NewMIs[1]);
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001304
1305 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1306 << "2addr: NEW INST: " << *NewMIs[1]);
1307
1308 // Transform the instruction, now that it no longer has a load.
1309 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1310 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1311 MachineBasicBlock::iterator NewMI = NewMIs[1];
Cameron Zwarich6868f382013-02-24 00:27:29 +00001312 bool TransformResult =
Cameron Zwarichf05c0cb2013-02-24 00:27:26 +00001313 tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true);
Cameron Zwarich1b4c64c2013-02-24 01:26:05 +00001314 (void)TransformResult;
Cameron Zwarich6868f382013-02-24 00:27:29 +00001315 assert(!TransformResult &&
1316 "tryInstructionTransform() should return false.");
1317 if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001318 // Success, or at least we made an improvement. Keep the unfolded
1319 // instructions and discard the original.
1320 if (LV) {
Evan Cheng30f44ad2011-11-14 19:48:55 +00001321 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1322 MachineOperand &MO = MI.getOperand(i);
Andrew Trick808a7a62012-02-03 05:12:30 +00001323 if (MO.isReg() &&
Dan Gohman851e4782010-06-22 00:32:04 +00001324 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1325 if (MO.isUse()) {
Dan Gohman2370e2f2010-06-22 02:07:21 +00001326 if (MO.isKill()) {
1327 if (NewMIs[0]->killsRegister(MO.getReg()))
Evan Cheng30f44ad2011-11-14 19:48:55 +00001328 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
Dan Gohman2370e2f2010-06-22 02:07:21 +00001329 else {
1330 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1331 "Kill missing after load unfold!");
Evan Cheng30f44ad2011-11-14 19:48:55 +00001332 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
Dan Gohman2370e2f2010-06-22 02:07:21 +00001333 }
1334 }
Evan Cheng30f44ad2011-11-14 19:48:55 +00001335 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
Dan Gohman2370e2f2010-06-22 02:07:21 +00001336 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1337 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
1338 else {
1339 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1340 "Dead flag missing after load unfold!");
1341 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
1342 }
1343 }
Dan Gohman851e4782010-06-22 00:32:04 +00001344 }
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001345 }
1346 LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
1347 }
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001348
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001349 SmallVector<unsigned, 4> OrigRegs;
1350 if (LIS) {
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001351 for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(),
1352 MOE = MI.operands_end(); MOI != MOE; ++MOI) {
1353 if (MOI->isReg())
1354 OrigRegs.push_back(MOI->getReg());
1355 }
1356 }
1357
Evan Cheng30f44ad2011-11-14 19:48:55 +00001358 MI.eraseFromParent();
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001359
1360 // Update LiveIntervals.
Cameron Zwarichcaad7e12013-02-20 22:10:00 +00001361 if (LIS) {
1362 MachineBasicBlock::iterator Begin(NewMIs[0]);
1363 MachineBasicBlock::iterator End(NewMIs[1]);
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001364 LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs);
Cameron Zwarichcaad7e12013-02-20 22:10:00 +00001365 }
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001366
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001367 mi = NewMIs[1];
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001368 } else {
1369 // Transforming didn't eliminate the tie and didn't lead to an
1370 // improvement. Clean up the unfolded instructions and keep the
1371 // original.
1372 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1373 NewMIs[0]->eraseFromParent();
1374 NewMIs[1]->eraseFromParent();
1375 }
1376 }
1377 }
1378 }
1379
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001380 return false;
1381}
1382
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001383// Collect tied operands of MI that need to be handled.
1384// Rewrite trivial cases immediately.
1385// Return true if any tied operands where found, including the trivial ones.
1386bool TwoAddressInstructionPass::
1387collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
1388 const MCInstrDesc &MCID = MI->getDesc();
1389 bool AnyOps = false;
Jakob Stoklund Olesenade363e2012-09-04 22:59:30 +00001390 unsigned NumOps = MI->getNumOperands();
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001391
1392 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1393 unsigned DstIdx = 0;
1394 if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1395 continue;
1396 AnyOps = true;
Jakob Stoklund Olesenfbf45dc2012-08-07 22:47:06 +00001397 MachineOperand &SrcMO = MI->getOperand(SrcIdx);
1398 MachineOperand &DstMO = MI->getOperand(DstIdx);
1399 unsigned SrcReg = SrcMO.getReg();
1400 unsigned DstReg = DstMO.getReg();
1401 // Tied constraint already satisfied?
1402 if (SrcReg == DstReg)
1403 continue;
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001404
Jakob Stoklund Olesenfbf45dc2012-08-07 22:47:06 +00001405 assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001406
1407 // Deal with <undef> uses immediately - simply rewrite the src operand.
Andrew Tricke3398282013-12-17 04:50:45 +00001408 if (SrcMO.isUndef() && !DstMO.getSubReg()) {
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001409 // Constrain the DstReg register class if required.
1410 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1411 if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
1412 TRI, *MF))
1413 MRI->constrainRegClass(DstReg, RC);
Jakob Stoklund Olesenfbf45dc2012-08-07 22:47:06 +00001414 SrcMO.setReg(DstReg);
Andrew Tricke3398282013-12-17 04:50:45 +00001415 SrcMO.setSubReg(0);
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001416 DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
1417 continue;
1418 }
Jakob Stoklund Olesenfbf45dc2012-08-07 22:47:06 +00001419 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001420 }
1421 return AnyOps;
1422}
1423
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001424// Process a list of tied MI operands that all use the same source register.
1425// The tied pairs are of the form (SrcIdx, DstIdx).
1426void
1427TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
1428 TiedPairList &TiedPairs,
1429 unsigned &Dist) {
1430 bool IsEarlyClobber = false;
Cameron Zwarich2991feb2013-02-20 06:46:46 +00001431 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1432 const MachineOperand &DstMO = MI->getOperand(TiedPairs[tpi].second);
1433 IsEarlyClobber |= DstMO.isEarlyClobber();
1434 }
1435
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001436 bool RemovedKillFlag = false;
1437 bool AllUsesCopied = true;
1438 unsigned LastCopiedReg = 0;
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001439 SlotIndex LastCopyIdx;
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001440 unsigned RegB = 0;
Andrew Tricke3398282013-12-17 04:50:45 +00001441 unsigned SubRegB = 0;
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001442 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1443 unsigned SrcIdx = TiedPairs[tpi].first;
1444 unsigned DstIdx = TiedPairs[tpi].second;
1445
1446 const MachineOperand &DstMO = MI->getOperand(DstIdx);
1447 unsigned RegA = DstMO.getReg();
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001448
1449 // Grab RegB from the instruction because it may have changed if the
1450 // instruction was commuted.
1451 RegB = MI->getOperand(SrcIdx).getReg();
Andrew Tricke3398282013-12-17 04:50:45 +00001452 SubRegB = MI->getOperand(SrcIdx).getSubReg();
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001453
1454 if (RegA == RegB) {
1455 // The register is tied to multiple destinations (or else we would
1456 // not have continued this far), but this use of the register
1457 // already matches the tied destination. Leave it.
1458 AllUsesCopied = false;
1459 continue;
1460 }
1461 LastCopiedReg = RegA;
1462
1463 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1464 "cannot make instruction into two-address form");
1465
1466#ifndef NDEBUG
1467 // First, verify that we don't have a use of "a" in the instruction
1468 // (a = b + a for example) because our transformation will not
1469 // work. This should never occur because we are in SSA form.
1470 for (unsigned i = 0; i != MI->getNumOperands(); ++i)
1471 assert(i == DstIdx ||
1472 !MI->getOperand(i).isReg() ||
1473 MI->getOperand(i).getReg() != RegA);
1474#endif
1475
1476 // Emit a copy.
Andrew Tricke3398282013-12-17 04:50:45 +00001477 MachineInstrBuilder MIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1478 TII->get(TargetOpcode::COPY), RegA);
1479 // If this operand is folding a truncation, the truncation now moves to the
1480 // copy so that the register classes remain valid for the operands.
1481 MIB.addReg(RegB, 0, SubRegB);
1482 const TargetRegisterClass *RC = MRI->getRegClass(RegB);
1483 if (SubRegB) {
1484 if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1485 assert(TRI->getMatchingSuperRegClass(RC, MRI->getRegClass(RegA),
1486 SubRegB) &&
1487 "tied subregister must be a truncation");
1488 // The superreg class will not be used to constrain the subreg class.
Craig Topperc0196b12014-04-14 00:51:57 +00001489 RC = nullptr;
Andrew Tricke3398282013-12-17 04:50:45 +00001490 }
1491 else {
1492 assert(TRI->getMatchingSuperReg(RegA, SubRegB, MRI->getRegClass(RegB))
1493 && "tied subregister must be a truncation");
1494 }
1495 }
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001496
1497 // Update DistanceMap.
1498 MachineBasicBlock::iterator PrevMI = MI;
1499 --PrevMI;
1500 DistanceMap.insert(std::make_pair(PrevMI, Dist));
1501 DistanceMap[MI] = ++Dist;
1502
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001503 if (LIS) {
1504 LastCopyIdx = LIS->InsertMachineInstrInMaps(PrevMI).getRegSlot();
1505
1506 if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1507 LiveInterval &LI = LIS->getInterval(RegA);
1508 VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1509 SlotIndex endIdx =
1510 LIS->getInstructionIndex(MI).getRegSlot(IsEarlyClobber);
Matthias Braun13ddb7c2013-10-10 21:28:43 +00001511 LI.addSegment(LiveInterval::Segment(LastCopyIdx, endIdx, VNI));
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001512 }
1513 }
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001514
Andrew Tricke3398282013-12-17 04:50:45 +00001515 DEBUG(dbgs() << "\t\tprepend:\t" << *MIB);
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001516
1517 MachineOperand &MO = MI->getOperand(SrcIdx);
1518 assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
1519 "inconsistent operand info for 2-reg pass");
1520 if (MO.isKill()) {
1521 MO.setIsKill(false);
1522 RemovedKillFlag = true;
1523 }
1524
1525 // Make sure regA is a legal regclass for the SrcIdx operand.
1526 if (TargetRegisterInfo::isVirtualRegister(RegA) &&
1527 TargetRegisterInfo::isVirtualRegister(RegB))
Andrew Tricke3398282013-12-17 04:50:45 +00001528 MRI->constrainRegClass(RegA, RC);
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001529 MO.setReg(RegA);
Andrew Tricke3398282013-12-17 04:50:45 +00001530 // The getMatchingSuper asserts guarantee that the register class projected
1531 // by SubRegB is compatible with RegA with no subregister. So regardless of
1532 // whether the dest oper writes a subreg, the source oper should not.
1533 MO.setSubReg(0);
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001534
1535 // Propagate SrcRegMap.
1536 SrcRegMap[RegA] = RegB;
1537 }
1538
1539
1540 if (AllUsesCopied) {
1541 if (!IsEarlyClobber) {
1542 // Replace other (un-tied) uses of regB with LastCopiedReg.
1543 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1544 MachineOperand &MO = MI->getOperand(i);
Andrew Tricke3398282013-12-17 04:50:45 +00001545 if (MO.isReg() && MO.getReg() == RegB && MO.getSubReg() == SubRegB &&
1546 MO.isUse()) {
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001547 if (MO.isKill()) {
1548 MO.setIsKill(false);
1549 RemovedKillFlag = true;
1550 }
1551 MO.setReg(LastCopiedReg);
Andrew Tricke3398282013-12-17 04:50:45 +00001552 MO.setSubReg(0);
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001553 }
1554 }
1555 }
1556
1557 // Update live variables for regB.
1558 if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(MI)) {
1559 MachineBasicBlock::iterator PrevMI = MI;
1560 --PrevMI;
1561 LV->addVirtualRegisterKilled(RegB, PrevMI);
1562 }
1563
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001564 // Update LiveIntervals.
1565 if (LIS) {
1566 LiveInterval &LI = LIS->getInterval(RegB);
1567 SlotIndex MIIdx = LIS->getInstructionIndex(MI);
1568 LiveInterval::const_iterator I = LI.find(MIIdx);
1569 assert(I != LI.end() && "RegB must be live-in to use.");
1570
1571 SlotIndex UseIdx = MIIdx.getRegSlot(IsEarlyClobber);
1572 if (I->end == UseIdx)
Matthias Braun13ddb7c2013-10-10 21:28:43 +00001573 LI.removeSegment(LastCopyIdx, UseIdx);
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001574 }
1575
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001576 } else if (RemovedKillFlag) {
1577 // Some tied uses of regB matched their destination registers, so
1578 // regB is still used in this instruction, but a kill flag was
1579 // removed from a different tied use of regB, so now we need to add
1580 // a kill flag to one of the remaining uses of regB.
1581 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1582 MachineOperand &MO = MI->getOperand(i);
1583 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1584 MO.setIsKill(true);
1585 break;
1586 }
1587 }
1588 }
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001589}
1590
Bill Wendling19e3c852008-05-10 00:12:52 +00001591/// runOnMachineFunction - Reduce two-address instructions to two operands.
Alkis Evlogimenos725021c2003-12-18 13:06:04 +00001592///
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001593bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
1594 MF = &Func;
1595 const TargetMachine &TM = MF->getTarget();
1596 MRI = &MF->getRegInfo();
Eric Christopher33726202015-01-27 08:48:42 +00001597 TII = MF->getSubtarget().getInstrInfo();
1598 TRI = MF->getSubtarget().getRegisterInfo();
1599 InstrItins = MF->getSubtarget().getInstrItineraryData();
Duncan Sands5a913d62009-01-28 13:14:17 +00001600 LV = getAnalysisIfAvailable<LiveVariables>();
Jakob Stoklund Olesen24bc5142012-08-03 22:58:34 +00001601 LIS = getAnalysisIfAvailable<LiveIntervals>();
Dan Gohman87b02d52009-10-09 23:27:56 +00001602 AA = &getAnalysis<AliasAnalysis>();
Evan Cheng822ddde2011-11-16 18:44:48 +00001603 OptLevel = TM.getOptLevel();
Alkis Evlogimenos725021c2003-12-18 13:06:04 +00001604
Misha Brukman6dd644e2004-07-22 15:26:23 +00001605 bool MadeChange = false;
Alkis Evlogimenos725021c2003-12-18 13:06:04 +00001606
David Greeneac9f8192010-01-05 01:24:21 +00001607 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
Andrew Trick808a7a62012-02-03 05:12:30 +00001608 DEBUG(dbgs() << "********** Function: "
Craig Toppera538d832012-08-22 06:07:19 +00001609 << MF->getName() << '\n');
Alkis Evlogimenos26583db2004-02-18 00:35:06 +00001610
Jakob Stoklund Olesen9760f042011-07-29 22:51:22 +00001611 // This pass takes the function out of SSA form.
1612 MRI->leaveSSA();
1613
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001614 TiedOperandMap TiedOperands;
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001615 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
1616 MBBI != MBBE; ++MBBI) {
1617 MBB = MBBI;
Evan Chengc5618eb2008-06-18 07:49:14 +00001618 unsigned Dist = 0;
1619 DistanceMap.clear();
Evan Chengc2f95b52009-03-01 02:03:43 +00001620 SrcRegMap.clear();
1621 DstRegMap.clear();
1622 Processed.clear();
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001623 for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
Evan Cheng58324102008-03-27 01:27:25 +00001624 mi != me; ) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001625 MachineBasicBlock::iterator nmi = std::next(mi);
Dale Johannesen8bba1602010-02-10 21:47:48 +00001626 if (mi->isDebugValue()) {
1627 mi = nmi;
1628 continue;
1629 }
Evan Cheng77be42a2010-03-23 20:36:12 +00001630
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001631 // Expand REG_SEQUENCE instructions. This will position mi at the first
1632 // expanded instruction.
Evan Cheng4b6abd82010-05-05 18:45:40 +00001633 if (mi->isRegSequence())
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001634 eliminateRegSequence(mi);
Evan Cheng4b6abd82010-05-05 18:45:40 +00001635
Evan Chengc5618eb2008-06-18 07:49:14 +00001636 DistanceMap.insert(std::make_pair(mi, ++Dist));
Evan Chengc2f95b52009-03-01 02:03:43 +00001637
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001638 processCopy(&*mi);
Evan Chengc2f95b52009-03-01 02:03:43 +00001639
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001640 // First scan through all the tied register uses in this instruction
1641 // and record a list of pairs of tied operands for each register.
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001642 if (!collectTiedOperands(mi, TiedOperands)) {
1643 mi = nmi;
1644 continue;
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001645 }
Alkis Evlogimenos725021c2003-12-18 13:06:04 +00001646
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001647 ++NumTwoAddressInstrs;
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001648 MadeChange = true;
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001649 DEBUG(dbgs() << '\t' << *mi);
1650
Chandler Carruth985454e2012-07-18 18:58:22 +00001651 // If the instruction has a single pair of tied operands, try some
1652 // transformations that may either eliminate the tied operands or
1653 // improve the opportunities for coalescing away the register copy.
1654 if (TiedOperands.size() == 1) {
Craig Topperb94011f2013-07-14 04:42:23 +00001655 SmallVectorImpl<std::pair<unsigned, unsigned> > &TiedPairs
Chandler Carruth985454e2012-07-18 18:58:22 +00001656 = TiedOperands.begin()->second;
1657 if (TiedPairs.size() == 1) {
1658 unsigned SrcIdx = TiedPairs[0].first;
1659 unsigned DstIdx = TiedPairs[0].second;
1660 unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
1661 unsigned DstReg = mi->getOperand(DstIdx).getReg();
1662 if (SrcReg != DstReg &&
Cameron Zwarichf05c0cb2013-02-24 00:27:26 +00001663 tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) {
Chandler Carruth985454e2012-07-18 18:58:22 +00001664 // The tied operands have been eliminated or shifted further down the
1665 // block to ease elimination. Continue processing with 'nmi'.
1666 TiedOperands.clear();
1667 mi = nmi;
1668 continue;
1669 }
1670 }
1671 }
1672
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001673 // Now iterate over the information collected above.
1674 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1675 OE = TiedOperands.end(); OI != OE; ++OI) {
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001676 processTiedPairs(mi, OI->second, Dist);
David Greeneac9f8192010-01-05 01:24:21 +00001677 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
Jakob Stoklund Olesen6b556f82012-06-25 03:27:12 +00001678 }
Bill Wendling19e3c852008-05-10 00:12:52 +00001679
Jakob Stoklund Olesen6b556f82012-06-25 03:27:12 +00001680 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1681 if (mi->isInsertSubreg()) {
1682 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1683 // To %reg:subidx = COPY %subreg
1684 unsigned SubIdx = mi->getOperand(3).getImm();
1685 mi->RemoveOperand(3);
1686 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1687 mi->getOperand(0).setSubReg(SubIdx);
1688 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1689 mi->RemoveOperand(1);
1690 mi->setDesc(TII->get(TargetOpcode::COPY));
1691 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
Jakob Stoklund Olesen70ee3ec2010-07-06 23:26:25 +00001692 }
1693
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001694 // Clear TiedOperands here instead of at the top of the loop
1695 // since most instructions do not have tied operands.
1696 TiedOperands.clear();
Evan Cheng58324102008-03-27 01:27:25 +00001697 mi = nmi;
Misha Brukman6dd644e2004-07-22 15:26:23 +00001698 }
1699 }
1700
Cameron Zwarich36735812013-02-20 06:46:34 +00001701 if (LIS)
1702 MF->verify(this, "After two-address instruction pass");
1703
Misha Brukman6dd644e2004-07-22 15:26:23 +00001704 return MadeChange;
Alkis Evlogimenos725021c2003-12-18 13:06:04 +00001705}
Evan Cheng4b6abd82010-05-05 18:45:40 +00001706
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001707/// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process.
Evan Cheng4b6abd82010-05-05 18:45:40 +00001708///
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001709/// The instruction is turned into a sequence of sub-register copies:
1710///
1711/// %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1
1712///
1713/// Becomes:
1714///
1715/// %dst:ssub0<def,undef> = COPY %v1
1716/// %dst:ssub1<def> = COPY %v2
1717///
1718void TwoAddressInstructionPass::
1719eliminateRegSequence(MachineBasicBlock::iterator &MBBI) {
1720 MachineInstr *MI = MBBI;
1721 unsigned DstReg = MI->getOperand(0).getReg();
1722 if (MI->getOperand(0).getSubReg() ||
1723 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1724 !(MI->getNumOperands() & 1)) {
1725 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
Craig Topperc0196b12014-04-14 00:51:57 +00001726 llvm_unreachable(nullptr);
Evan Cheng4b6abd82010-05-05 18:45:40 +00001727 }
1728
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001729 SmallVector<unsigned, 4> OrigRegs;
1730 if (LIS) {
1731 OrigRegs.push_back(MI->getOperand(0).getReg());
1732 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2)
1733 OrigRegs.push_back(MI->getOperand(i).getReg());
1734 }
1735
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001736 bool DefEmitted = false;
1737 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1738 MachineOperand &UseMO = MI->getOperand(i);
1739 unsigned SrcReg = UseMO.getReg();
1740 unsigned SubIdx = MI->getOperand(i+1).getImm();
1741 // Nothing needs to be inserted for <undef> operands.
1742 if (UseMO.isUndef())
1743 continue;
1744
1745 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1746 // might insert a COPY that uses SrcReg after is was killed.
1747 bool isKill = UseMO.isKill();
1748 if (isKill)
1749 for (unsigned j = i + 2; j < e; j += 2)
1750 if (MI->getOperand(j).getReg() == SrcReg) {
1751 MI->getOperand(j).setIsKill();
1752 UseMO.setIsKill(false);
1753 isKill = false;
1754 break;
1755 }
1756
1757 // Insert the sub-register copy.
1758 MachineInstr *CopyMI = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1759 TII->get(TargetOpcode::COPY))
1760 .addReg(DstReg, RegState::Define, SubIdx)
1761 .addOperand(UseMO);
1762
1763 // The first def needs an <undef> flag because there is no live register
1764 // before it.
1765 if (!DefEmitted) {
1766 CopyMI->getOperand(0).setIsUndef(true);
1767 // Return an iterator pointing to the first inserted instr.
1768 MBBI = CopyMI;
1769 }
1770 DefEmitted = true;
1771
1772 // Update LiveVariables' kill info.
1773 if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
1774 LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1775
1776 DEBUG(dbgs() << "Inserted: " << *CopyMI);
1777 }
1778
David Blaikie9db062e2013-02-20 07:39:20 +00001779 MachineBasicBlock::iterator EndMBBI =
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001780 std::next(MachineBasicBlock::iterator(MI));
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001781
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001782 if (!DefEmitted) {
1783 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1784 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1785 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
1786 MI->RemoveOperand(j);
1787 } else {
1788 DEBUG(dbgs() << "Eliminated: " << *MI);
1789 MI->eraseFromParent();
1790 }
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001791
1792 // Udpate LiveIntervals.
Cameron Zwarichcaad7e12013-02-20 22:10:00 +00001793 if (LIS)
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001794 LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs);
Evan Cheng4b6abd82010-05-05 18:45:40 +00001795}