blob: a0c1a4f70b33582573fcd035f31366a79b8e1bcf [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
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/STLExtras.h"
Michael Kupersteine36d7712016-08-11 17:38:33 +000032#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/ADT/Statistic.h"
34#include "llvm/Analysis/AliasAnalysis.h"
Jakob Stoklund Olesen24bc5142012-08-03 22:58:34 +000035#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Alkis Evlogimenos725021c2003-12-18 13:06:04 +000036#include "llvm/CodeGen/LiveVariables.h"
Alkis Evlogimenos725021c2003-12-18 13:06:04 +000037#include "llvm/CodeGen/MachineFunctionPass.h"
38#include "llvm/CodeGen/MachineInstr.h"
Bob Wilsona55b8872010-06-15 05:56:31 +000039#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattnera10fff52007-12-31 04:13:23 +000040#include "llvm/CodeGen/MachineRegisterInfo.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000041#include "llvm/CodeGen/Passes.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/Function.h"
Evan Cheng30f44ad2011-11-14 19:48:55 +000043#include "llvm/MC/MCInstrItineraries.h"
Andrew Trick608a6982013-04-24 15:54:39 +000044#include "llvm/Support/CommandLine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000045#include "llvm/Support/Debug.h"
46#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000047#include "llvm/Support/raw_ostream.h"
Alkis Evlogimenos725021c2003-12-18 13:06:04 +000048#include "llvm/Target/TargetInstrInfo.h"
49#include "llvm/Target/TargetMachine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000050#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000051#include "llvm/Target/TargetSubtargetInfo.h"
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +000052
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
Sanjay Patelb53791e2015-12-01 19:32:35 +000086 // Keep track the distance of a MI from the start of the current basic block.
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +000087 DenseMap<MachineInstr*, unsigned> DistanceMap;
Evan Chengc2f95b52009-03-01 02:03:43 +000088
Jakob Stoklund Olesend788e322012-10-26 22:06:00 +000089 // Set of already processed instructions in the current block.
90 SmallPtrSet<MachineInstr*, 8> Processed;
91
Sanjay Patelb53791e2015-12-01 19:32:35 +000092 // A map from virtual registers to physical registers which are likely targets
93 // to be coalesced to due to copies from physical registers to virtual
94 // registers. e.g. v1024 = move r0.
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +000095 DenseMap<unsigned, unsigned> SrcRegMap;
Evan Chengc2f95b52009-03-01 02:03:43 +000096
Sanjay Patelb53791e2015-12-01 19:32:35 +000097 // A map from virtual registers to physical registers which are likely targets
98 // to be coalesced to due to copies to physical registers from virtual
99 // registers. e.g. r1 = move v1024.
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000100 DenseMap<unsigned, unsigned> DstRegMap;
Evan Chengc2f95b52009-03-01 02:03:43 +0000101
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000102 bool sink3AddrInstruction(MachineInstr *MI, unsigned Reg,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000103 MachineBasicBlock::iterator OldPos);
Evan Chengc5618eb2008-06-18 07:49:14 +0000104
Eric Christopher28919132015-03-03 22:03:03 +0000105 bool isRevCopyChain(unsigned FromReg, unsigned ToReg, int Maxlen);
106
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000107 bool noUseAfterLastDef(unsigned Reg, unsigned Dist, unsigned &LastDef);
Evan Chengabda6652009-01-25 03:53:59 +0000108
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000109 bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000110 MachineInstr *MI, unsigned Dist);
Evan Chengabda6652009-01-25 03:53:59 +0000111
Craig Topper76007942016-09-11 22:10:42 +0000112 bool commuteInstruction(MachineInstr *MI, unsigned DstIdx,
Andrew Kaylor16c4da02015-09-28 20:33:22 +0000113 unsigned RegBIdx, unsigned RegCIdx, unsigned Dist);
Evan Chengc2f95b52009-03-01 02:03:43 +0000114
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000115 bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
Evan Cheng09f5be82009-03-30 21:34:07 +0000116
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000117 bool convertInstTo3Addr(MachineBasicBlock::iterator &mi,
118 MachineBasicBlock::iterator &nmi,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000119 unsigned RegA, unsigned RegB, unsigned Dist);
Evan Cheng09f5be82009-03-30 21:34:07 +0000120
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000121 bool isDefTooClose(unsigned Reg, unsigned Dist, MachineInstr *MI);
Evan Cheng30f44ad2011-11-14 19:48:55 +0000122
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000123 bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000124 MachineBasicBlock::iterator &nmi,
125 unsigned Reg);
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000126 bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000127 MachineBasicBlock::iterator &nmi,
128 unsigned Reg);
129
130 bool tryInstructionTransform(MachineBasicBlock::iterator &mi,
Evan Cheng30f44ad2011-11-14 19:48:55 +0000131 MachineBasicBlock::iterator &nmi,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000132 unsigned SrcIdx, unsigned DstIdx,
Cameron Zwarichf05c0cb2013-02-24 00:27:26 +0000133 unsigned Dist, bool shouldOnlyCommute);
Evan Cheng30f44ad2011-11-14 19:48:55 +0000134
Andrew Kaylor16c4da02015-09-28 20:33:22 +0000135 bool tryInstructionCommute(MachineInstr *MI,
136 unsigned DstOpIdx,
137 unsigned BaseOpIdx,
138 bool BaseOpKilled,
139 unsigned Dist);
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000140 void scanUses(unsigned DstReg);
Evan Cheng15fed7a2011-03-02 01:08:17 +0000141
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000142 void processCopy(MachineInstr *MI);
Bob Wilson5c7d9ca2009-09-03 20:58:42 +0000143
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000144 typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList;
145 typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap;
146 bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
147 void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +0000148 void eliminateRegSequence(MachineBasicBlock::iterator&);
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +0000149
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000150public:
151 static char ID; // Pass identification, replacement for typeid
152 TwoAddressInstructionPass() : MachineFunctionPass(ID) {
153 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
154 }
Evan Cheng1e4f5522010-05-17 23:24:12 +0000155
Craig Topper4584cd52014-03-07 09:26:03 +0000156 void getAnalysisUsage(AnalysisUsage &AU) const override {
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000157 AU.setPreservesCFG();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000158 AU.addRequired<AAResultsWrapperPass>();
Matthias Braunf84547c2016-04-28 23:42:51 +0000159 AU.addUsedIfAvailable<LiveVariables>();
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000160 AU.addPreserved<LiveVariables>();
161 AU.addPreserved<SlotIndexes>();
162 AU.addPreserved<LiveIntervals>();
163 AU.addPreservedID(MachineLoopInfoID);
164 AU.addPreservedID(MachineDominatorsID);
165 MachineFunctionPass::getAnalysisUsage(AU);
166 }
Devang Patel09f162c2007-05-01 21:15:47 +0000167
Sanjay Patelb53791e2015-12-01 19:32:35 +0000168 /// Pass entry point.
Craig Topper4584cd52014-03-07 09:26:03 +0000169 bool runOnMachineFunction(MachineFunction&) override;
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000170};
171} // end anonymous namespace
Alkis Evlogimenos725021c2003-12-18 13:06:04 +0000172
Dan Gohmand78c4002008-05-13 00:00:25 +0000173char TwoAddressInstructionPass::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000174INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
175 "Two-Address instruction pass", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000176INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000177INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000178 "Two-Address instruction pass", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000179
Owen Andersona7aed182010-08-06 18:33:48 +0000180char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
Alkis Evlogimenos71390902003-12-18 22:40:24 +0000181
Cameron Zwarich35c30502013-02-23 04:49:20 +0000182static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg, LiveIntervals *LIS);
183
Sanjay Patelb53791e2015-12-01 19:32:35 +0000184/// A two-address instruction has been converted to a three-address instruction
185/// to avoid clobbering a register. Try to sink it past the instruction that
186/// would kill the above mentioned register to reduce register pressure.
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000187bool TwoAddressInstructionPass::
188sink3AddrInstruction(MachineInstr *MI, unsigned SavedReg,
189 MachineBasicBlock::iterator OldPos) {
Eli Friedman8a15a5a2011-09-23 22:41:57 +0000190 // FIXME: Shouldn't we be trying to do this before we three-addressify the
191 // instruction? After this transformation is done, we no longer need
192 // the instruction to be in three-address form.
193
Evan Cheng5c26bde2008-03-13 06:37:55 +0000194 // Check if it's safe to move this instruction.
195 bool SeenStore = true; // Be conservative.
Matthias Braun07066cc2015-05-19 21:22:20 +0000196 if (!MI->isSafeToMove(AA, SeenStore))
Evan Cheng5c26bde2008-03-13 06:37:55 +0000197 return false;
198
199 unsigned DefReg = 0;
200 SmallSet<unsigned, 4> UseRegs;
Bill Wendling19e3c852008-05-10 00:12:52 +0000201
Craig Topperda5168b2015-10-08 06:06:42 +0000202 for (const MachineOperand &MO : MI->operands()) {
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000203 if (!MO.isReg())
Evan Cheng5c26bde2008-03-13 06:37:55 +0000204 continue;
205 unsigned MOReg = MO.getReg();
206 if (!MOReg)
207 continue;
208 if (MO.isUse() && MOReg != SavedReg)
209 UseRegs.insert(MO.getReg());
210 if (!MO.isDef())
211 continue;
212 if (MO.isImplicit())
213 // Don't try to move it if it implicitly defines a register.
214 return false;
215 if (DefReg)
216 // For now, don't move any instructions that define multiple registers.
217 return false;
218 DefReg = MO.getReg();
219 }
220
221 // Find the instruction that kills SavedReg.
Craig Topperc0196b12014-04-14 00:51:57 +0000222 MachineInstr *KillMI = nullptr;
Cameron Zwarich35c30502013-02-23 04:49:20 +0000223 if (LIS) {
224 LiveInterval &LI = LIS->getInterval(SavedReg);
225 assert(LI.end() != LI.begin() &&
226 "Reg should not have empty live interval.");
227
228 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
229 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
230 if (I != LI.end() && I->start < MBBEndIdx)
231 return false;
232
233 --I;
234 KillMI = LIS->getInstructionFromIndex(I->end);
235 }
236 if (!KillMI) {
Craig Topperda5168b2015-10-08 06:06:42 +0000237 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SavedReg)) {
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 ||
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +0000249 MachineBasicBlock::iterator(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;
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +0000263 for (MachineInstr &OtherMI : llvm::make_range(std::next(OldPos), KillPos)) {
Dale Johannesen12565de2010-02-11 18:22:31 +0000264 // DBG_VALUE cannot be counted against the limit.
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +0000265 if (OtherMI.isDebugValue())
Dale Johannesen12565de2010-02-11 18:22:31 +0000266 continue;
Evan Chengc5618eb2008-06-18 07:49:14 +0000267 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
268 return false;
269 ++NumVisited;
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +0000270 for (unsigned i = 0, e = OtherMI.getNumOperands(); i != e; ++i) {
271 MachineOperand &MO = OtherMI.getOperand(i);
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000272 if (!MO.isReg())
Evan Cheng5c26bde2008-03-13 06:37:55 +0000273 continue;
274 unsigned MOReg = MO.getReg();
275 if (!MOReg)
276 continue;
277 if (DefReg == MOReg)
278 return false;
Bill Wendling19e3c852008-05-10 00:12:52 +0000279
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +0000280 if (MO.isKill() || (LIS && isPlainlyKilled(&OtherMI, MOReg, LIS))) {
281 if (&OtherMI == KillMI && MOReg == SavedReg)
Evan Chengc5618eb2008-06-18 07:49:14 +0000282 // Save the operand that kills the register. We want to unset the kill
283 // marker if we can sink MI past it.
Evan Cheng5c26bde2008-03-13 06:37:55 +0000284 KillMO = &MO;
285 else if (UseRegs.count(MOReg))
286 // One of the uses is killed before the destination.
287 return false;
288 }
289 }
290 }
Jakob Stoklund Olesen420798c2012-08-09 22:08:26 +0000291 assert(KillMO && "Didn't find kill");
Evan Cheng5c26bde2008-03-13 06:37:55 +0000292
Cameron Zwarich35c30502013-02-23 04:49:20 +0000293 if (!LIS) {
294 // Update kill and LV information.
295 KillMO->setIsKill(false);
296 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
297 KillMO->setIsKill(true);
Andrew Trick808a7a62012-02-03 05:12:30 +0000298
Cameron Zwarich35c30502013-02-23 04:49:20 +0000299 if (LV)
Duncan P. N. Exon Smithd26fdc82016-07-01 01:51:32 +0000300 LV->replaceKillInstruction(SavedReg, *KillMI, *MI);
Cameron Zwarich35c30502013-02-23 04:49:20 +0000301 }
Evan Cheng5c26bde2008-03-13 06:37:55 +0000302
303 // Move instruction to its destination.
304 MBB->remove(MI);
305 MBB->insert(KillPos, MI);
306
Jakob Stoklund Olesen24bc5142012-08-03 22:58:34 +0000307 if (LIS)
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +0000308 LIS->handleMove(*MI);
Jakob Stoklund Olesen24bc5142012-08-03 22:58:34 +0000309
Evan Cheng5c26bde2008-03-13 06:37:55 +0000310 ++Num3AddrSunk;
311 return true;
312}
313
Sanjay Patelb53791e2015-12-01 19:32:35 +0000314/// Return the MachineInstr* if it is the single def of the Reg in current BB.
Eric Christopher28919132015-03-03 22:03:03 +0000315static MachineInstr *getSingleDef(unsigned Reg, MachineBasicBlock *BB,
316 const MachineRegisterInfo *MRI) {
317 MachineInstr *Ret = nullptr;
318 for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
319 if (DefMI.getParent() != BB || DefMI.isDebugValue())
320 continue;
321 if (!Ret)
322 Ret = &DefMI;
323 else if (Ret != &DefMI)
324 return nullptr;
325 }
326 return Ret;
327}
328
329/// Check if there is a reversed copy chain from FromReg to ToReg:
330/// %Tmp1 = copy %Tmp2;
331/// %FromReg = copy %Tmp1;
332/// %ToReg = add %FromReg ...
333/// %Tmp2 = copy %ToReg;
334/// MaxLen specifies the maximum length of the copy chain the func
335/// can walk through.
336bool TwoAddressInstructionPass::isRevCopyChain(unsigned FromReg, unsigned ToReg,
337 int Maxlen) {
338 unsigned TmpReg = FromReg;
339 for (int i = 0; i < Maxlen; i++) {
340 MachineInstr *Def = getSingleDef(TmpReg, MBB, MRI);
341 if (!Def || !Def->isCopy())
342 return false;
343
344 TmpReg = Def->getOperand(1).getReg();
345
346 if (TmpReg == ToReg)
347 return true;
348 }
349 return false;
350}
351
Sanjay Patelb53791e2015-12-01 19:32:35 +0000352/// Return true if there are no intervening uses between the last instruction
353/// in the MBB that defines the specified register and the two-address
354/// instruction which is being processed. It also returns the last def location
355/// by reference.
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000356bool TwoAddressInstructionPass::noUseAfterLastDef(unsigned Reg, unsigned Dist,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000357 unsigned &LastDef) {
Evan Chengabda6652009-01-25 03:53:59 +0000358 LastDef = 0;
359 unsigned LastUse = Dist;
Owen Andersonb36376e2014-03-17 19:36:09 +0000360 for (MachineOperand &MO : MRI->reg_operands(Reg)) {
Evan Chengabda6652009-01-25 03:53:59 +0000361 MachineInstr *MI = MO.getParent();
Chris Lattnerb06015a2010-02-09 19:54:29 +0000362 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesenc3adf442010-02-09 02:01:46 +0000363 continue;
Evan Chengabda6652009-01-25 03:53:59 +0000364 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
365 if (DI == DistanceMap.end())
366 continue;
367 if (MO.isUse() && DI->second < LastUse)
368 LastUse = DI->second;
369 if (MO.isDef() && DI->second > LastDef)
370 LastDef = DI->second;
371 }
372
373 return !(LastUse > LastDef && LastUse < Dist);
374}
375
Sanjay Patelb53791e2015-12-01 19:32:35 +0000376/// Return true if the specified MI is a copy instruction or an extract_subreg
377/// instruction. It also returns the source and destination registers and
378/// whether they are physical registers by reference.
Evan Chengc2f95b52009-03-01 02:03:43 +0000379static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
380 unsigned &SrcReg, unsigned &DstReg,
381 bool &IsSrcPhys, bool &IsDstPhys) {
382 SrcReg = 0;
383 DstReg = 0;
Jakob Stoklund Olesen37c42a32010-07-16 04:45:42 +0000384 if (MI.isCopy()) {
385 DstReg = MI.getOperand(0).getReg();
386 SrcReg = MI.getOperand(1).getReg();
387 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
388 DstReg = MI.getOperand(0).getReg();
389 SrcReg = MI.getOperand(2).getReg();
390 } else
391 return false;
Evan Chengc2f95b52009-03-01 02:03:43 +0000392
Jakob Stoklund Olesen37c42a32010-07-16 04:45:42 +0000393 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
394 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
395 return true;
Evan Chengc2f95b52009-03-01 02:03:43 +0000396}
397
Sanjay Patelb53791e2015-12-01 19:32:35 +0000398/// Test if the given register value, which is used by the
399/// given instruction, is killed by the given instruction.
Cameron Zwarichc8964782013-02-21 07:02:28 +0000400static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg,
401 LiveIntervals *LIS) {
402 if (LIS && TargetRegisterInfo::isVirtualRegister(Reg) &&
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000403 !LIS->isNotInMIMap(*MI)) {
Cameron Zwarichc8964782013-02-21 07:02:28 +0000404 // FIXME: Sometimes tryInstructionTransform() will add instructions and
405 // test whether they can be folded before keeping them. In this case it
406 // sets a kill before recursively calling tryInstructionTransform() again.
407 // If there is no interval available, we assume that this instruction is
408 // one of those. A kill flag is manually inserted on the operand so the
409 // check below will handle it.
410 LiveInterval &LI = LIS->getInterval(Reg);
411 // This is to match the kill flag version where undefs don't have kill
412 // flags.
413 if (!LI.hasAtLeastOneValue())
414 return false;
415
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000416 SlotIndex useIdx = LIS->getInstructionIndex(*MI);
Cameron Zwarichc8964782013-02-21 07:02:28 +0000417 LiveInterval::const_iterator I = LI.find(useIdx);
418 assert(I != LI.end() && "Reg must be live-in to use.");
Cameron Zwarich4e80d9e2013-02-23 04:49:22 +0000419 return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx);
Cameron Zwarichc8964782013-02-21 07:02:28 +0000420 }
421
422 return MI->killsRegister(Reg);
423}
424
Sanjay Patelb53791e2015-12-01 19:32:35 +0000425/// Test if the given register value, which is used by the given
Dan Gohmanad3e5492009-04-08 00:15:30 +0000426/// instruction, is killed by the given instruction. This looks through
427/// coalescable copies to see if the original value is potentially not killed.
428///
429/// For example, in this code:
430///
431/// %reg1034 = copy %reg1024
432/// %reg1035 = copy %reg1025<kill>
433/// %reg1036 = add %reg1034<kill>, %reg1035<kill>
434///
435/// %reg1034 is not considered to be killed, since it is copied from a
436/// register which is not killed. Treating it as not killed lets the
437/// normal heuristics commute the (two-address) add, which lets
438/// coalescing eliminate the extra copy.
439///
Cameron Zwarich384026b2013-02-21 22:58:42 +0000440/// If allowFalsePositives is true then likely kills are treated as kills even
441/// if it can't be proven that they are kills.
Dan Gohmanad3e5492009-04-08 00:15:30 +0000442static bool isKilled(MachineInstr &MI, unsigned Reg,
443 const MachineRegisterInfo *MRI,
Cameron Zwarich94b204b2013-02-21 04:33:02 +0000444 const TargetInstrInfo *TII,
Cameron Zwarich384026b2013-02-21 22:58:42 +0000445 LiveIntervals *LIS,
446 bool allowFalsePositives) {
Dan Gohmanad3e5492009-04-08 00:15:30 +0000447 MachineInstr *DefMI = &MI;
448 for (;;) {
Cameron Zwarich384026b2013-02-21 22:58:42 +0000449 // All uses of physical registers are likely to be kills.
450 if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
451 (allowFalsePositives || MRI->hasOneUse(Reg)))
452 return true;
Cameron Zwarichc8964782013-02-21 07:02:28 +0000453 if (!isPlainlyKilled(DefMI, Reg, LIS))
Dan Gohmanad3e5492009-04-08 00:15:30 +0000454 return false;
455 if (TargetRegisterInfo::isPhysicalRegister(Reg))
456 return true;
457 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
458 // If there are multiple defs, we can't do a simple analysis, so just
459 // go with what the kill flag says.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000460 if (std::next(Begin) != MRI->def_end())
Dan Gohmanad3e5492009-04-08 00:15:30 +0000461 return true;
Owen Anderson16c6bf42014-03-13 23:12:04 +0000462 DefMI = Begin->getParent();
Dan Gohmanad3e5492009-04-08 00:15:30 +0000463 bool IsSrcPhys, IsDstPhys;
464 unsigned SrcReg, DstReg;
465 // If the def is something other than a copy, then it isn't going to
466 // be coalesced, so follow the kill flag.
467 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
468 return true;
469 Reg = SrcReg;
470 }
471}
472
Sanjay Patelb53791e2015-12-01 19:32:35 +0000473/// Return true if the specified MI uses the specified register as a two-address
474/// use. If so, return the destination register by reference.
Evan Chengc2f95b52009-03-01 02:03:43 +0000475static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
Evan Chengf85a76f2013-05-02 02:07:32 +0000476 for (unsigned i = 0, NumOps = MI.getNumOperands(); i != NumOps; ++i) {
Evan Chengc2f95b52009-03-01 02:03:43 +0000477 const MachineOperand &MO = MI.getOperand(i);
478 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
479 continue;
Evan Cheng1361cbb2009-03-19 20:30:06 +0000480 unsigned ti;
481 if (MI.isRegTiedToDefOperand(i, &ti)) {
Evan Chengc2f95b52009-03-01 02:03:43 +0000482 DstReg = MI.getOperand(ti).getReg();
483 return true;
484 }
485 }
486 return false;
487}
488
Sanjay Patelb53791e2015-12-01 19:32:35 +0000489/// Given a register, if has a single in-basic block use, return the use
490/// instruction if it's a copy or a two-address use.
Evan Chengc2f95b52009-03-01 02:03:43 +0000491static
492MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
493 MachineRegisterInfo *MRI,
494 const TargetInstrInfo *TII,
Evan Cheng97871832009-04-14 00:32:25 +0000495 bool &IsCopy,
Evan Chengc2f95b52009-03-01 02:03:43 +0000496 unsigned &DstReg, bool &IsDstPhys) {
Evan Chengf94d6832010-03-03 21:18:38 +0000497 if (!MRI->hasOneNonDBGUse(Reg))
498 // None or more than one use.
Craig Topperc0196b12014-04-14 00:51:57 +0000499 return nullptr;
Owen Anderson16c6bf42014-03-13 23:12:04 +0000500 MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(Reg);
Evan Chengc2f95b52009-03-01 02:03:43 +0000501 if (UseMI.getParent() != MBB)
Craig Topperc0196b12014-04-14 00:51:57 +0000502 return nullptr;
Evan Chengc2f95b52009-03-01 02:03:43 +0000503 unsigned SrcReg;
504 bool IsSrcPhys;
Evan Cheng97871832009-04-14 00:32:25 +0000505 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
506 IsCopy = true;
Evan Chengc2f95b52009-03-01 02:03:43 +0000507 return &UseMI;
Evan Cheng97871832009-04-14 00:32:25 +0000508 }
Evan Chengc2f95b52009-03-01 02:03:43 +0000509 IsDstPhys = false;
Evan Cheng97871832009-04-14 00:32:25 +0000510 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
511 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Chengc2f95b52009-03-01 02:03:43 +0000512 return &UseMI;
Evan Cheng97871832009-04-14 00:32:25 +0000513 }
Craig Topperc0196b12014-04-14 00:51:57 +0000514 return nullptr;
Evan Chengc2f95b52009-03-01 02:03:43 +0000515}
516
Sanjay Patelb53791e2015-12-01 19:32:35 +0000517/// Return the physical register the specified virtual register might be mapped
518/// to.
Evan Chengc2f95b52009-03-01 02:03:43 +0000519static unsigned
520getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
521 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
522 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
523 if (SI == RegMap.end())
524 return 0;
525 Reg = SI->second;
526 }
527 if (TargetRegisterInfo::isPhysicalRegister(Reg))
528 return Reg;
529 return 0;
530}
531
Sanjay Patelb53791e2015-12-01 19:32:35 +0000532/// Return true if the two registers are equal or aliased.
Evan Chengc2f95b52009-03-01 02:03:43 +0000533static bool
534regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
535 if (RegA == RegB)
536 return true;
537 if (!RegA || !RegB)
538 return false;
539 return TRI->regsOverlap(RegA, RegB);
540}
541
Michael Kupersteine36d7712016-08-11 17:38:33 +0000542// Returns true if Reg is equal or aliased to at least one register in Set.
543static bool regOverlapsSet(const SmallVectorImpl<unsigned> &Set, unsigned Reg,
544 const TargetRegisterInfo *TRI) {
545 for (unsigned R : Set)
546 if (TRI->regsOverlap(R, Reg))
547 return true;
548
549 return false;
550}
551
Sanjay Patelb53791e2015-12-01 19:32:35 +0000552/// Return true if it's potentially profitable to commute the two-address
553/// instruction that's being processed.
Evan Chengabda6652009-01-25 03:53:59 +0000554bool
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000555TwoAddressInstructionPass::
556isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
557 MachineInstr *MI, unsigned Dist) {
Evan Cheng822ddde2011-11-16 18:44:48 +0000558 if (OptLevel == CodeGenOpt::None)
559 return false;
560
Evan Chengabda6652009-01-25 03:53:59 +0000561 // Determine if it's profitable to commute this two address instruction. In
562 // general, we want no uses between this instruction and the definition of
563 // the two-address register.
564 // e.g.
565 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
566 // %reg1029<def> = MOV8rr %reg1028
567 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
568 // insert => %reg1030<def> = MOV8rr %reg1028
569 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
570 // In this case, it might not be possible to coalesce the second MOV8rr
571 // instruction if the first one is coalesced. So it would be profitable to
572 // commute it:
573 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
574 // %reg1029<def> = MOV8rr %reg1028
575 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
576 // insert => %reg1030<def> = MOV8rr %reg1029
Andrew Trick808a7a62012-02-03 05:12:30 +0000577 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
Evan Chengabda6652009-01-25 03:53:59 +0000578
Cameron Zwarich9e722ae2013-02-21 07:02:30 +0000579 if (!isPlainlyKilled(MI, regC, LIS))
Evan Chengabda6652009-01-25 03:53:59 +0000580 return false;
581
582 // Ok, we have something like:
583 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
584 // let's see if it's worth commuting it.
585
Evan Chengc2f95b52009-03-01 02:03:43 +0000586 // Look for situations like this:
587 // %reg1024<def> = MOV r1
588 // %reg1025<def> = MOV r0
589 // %reg1026<def> = ADD %reg1024, %reg1025
590 // r0 = MOV %reg1026
591 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
Evan Chengb64e7b72012-05-03 01:45:13 +0000592 unsigned ToRegA = getMappedReg(regA, DstRegMap);
593 if (ToRegA) {
594 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
595 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
Craig Topper12f0d9e2014-11-05 06:43:02 +0000596 bool CompB = FromRegB && regsAreCompatible(FromRegB, ToRegA, TRI);
597 bool CompC = FromRegC && regsAreCompatible(FromRegC, ToRegA, TRI);
598
599 // Compute if any of the following are true:
600 // -RegB is not tied to a register and RegC is compatible with RegA.
601 // -RegB is tied to the wrong physical register, but RegC is.
602 // -RegB is tied to the wrong physical register, and RegC isn't tied.
603 if ((!FromRegB && CompC) || (FromRegB && !CompB && (!FromRegC || CompC)))
604 return true;
605 // Don't compute if any of the following are true:
606 // -RegC is not tied to a register and RegB is compatible with RegA.
607 // -RegC is tied to the wrong physical register, but RegB is.
608 // -RegC is tied to the wrong physical register, and RegB isn't tied.
609 if ((!FromRegC && CompB) || (FromRegC && !CompC && (!FromRegB || CompB)))
610 return false;
Evan Chengb64e7b72012-05-03 01:45:13 +0000611 }
Evan Chengc2f95b52009-03-01 02:03:43 +0000612
Evan Chengabda6652009-01-25 03:53:59 +0000613 // If there is a use of regC between its last def (could be livein) and this
614 // instruction, then bail.
615 unsigned LastDefC = 0;
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000616 if (!noUseAfterLastDef(regC, Dist, LastDefC))
Evan Chengabda6652009-01-25 03:53:59 +0000617 return false;
618
619 // If there is a use of regB between its last def (could be livein) and this
620 // instruction, then go ahead and make this transformation.
621 unsigned LastDefB = 0;
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000622 if (!noUseAfterLastDef(regB, Dist, LastDefB))
Evan Chengabda6652009-01-25 03:53:59 +0000623 return true;
624
Eric Christopher28919132015-03-03 22:03:03 +0000625 // Look for situation like this:
626 // %reg101 = MOV %reg100
627 // %reg102 = ...
628 // %reg103 = ADD %reg102, %reg101
629 // ... = %reg103 ...
630 // %reg100 = MOV %reg103
631 // If there is a reversed copy chain from reg101 to reg103, commute the ADD
632 // to eliminate an otherwise unavoidable copy.
633 // FIXME:
634 // We can extend the logic further: If an pair of operands in an insn has
635 // been merged, the insn could be regarded as a virtual copy, and the virtual
636 // copy could also be used to construct a copy chain.
637 // To more generally minimize register copies, ideally the logic of two addr
638 // instruction pass should be integrated with register allocation pass where
639 // interference graph is available.
640 if (isRevCopyChain(regC, regA, 3))
641 return true;
642
643 if (isRevCopyChain(regB, regA, 3))
644 return false;
645
Evan Chengabda6652009-01-25 03:53:59 +0000646 // Since there are no intervening uses for both registers, then commute
647 // if the def of regC is closer. Its live interval is shorter.
648 return LastDefB && LastDefC && LastDefC > LastDefB;
649}
650
Sanjay Patelb53791e2015-12-01 19:32:35 +0000651/// Commute a two-address instruction and update the basic block, distance map,
652/// and live variables if needed. Return true if it is successful.
Andrew Kaylor16c4da02015-09-28 20:33:22 +0000653bool TwoAddressInstructionPass::commuteInstruction(MachineInstr *MI,
Craig Topper76007942016-09-11 22:10:42 +0000654 unsigned DstIdx,
Andrew Kaylor16c4da02015-09-28 20:33:22 +0000655 unsigned RegBIdx,
656 unsigned RegCIdx,
657 unsigned Dist) {
658 unsigned RegC = MI->getOperand(RegCIdx).getReg();
David Greeneac9f8192010-01-05 01:24:21 +0000659 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000660 MachineInstr *NewMI = TII->commuteInstruction(*MI, false, RegBIdx, RegCIdx);
Evan Cheng6d897062009-01-23 23:27:33 +0000661
Craig Topperc0196b12014-04-14 00:51:57 +0000662 if (NewMI == nullptr) {
David Greeneac9f8192010-01-05 01:24:21 +0000663 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
Evan Cheng6d897062009-01-23 23:27:33 +0000664 return false;
665 }
666
David Greeneac9f8192010-01-05 01:24:21 +0000667 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
Cameron Zwariche6907bc2013-02-23 23:13:28 +0000668 assert(NewMI == MI &&
669 "TargetInstrInfo::commuteInstruction() should not return a new "
670 "instruction unless it was requested.");
Evan Chengc2f95b52009-03-01 02:03:43 +0000671
672 // Update source register map.
673 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
674 if (FromRegC) {
Craig Topper76007942016-09-11 22:10:42 +0000675 unsigned RegA = MI->getOperand(DstIdx).getReg();
Evan Chengc2f95b52009-03-01 02:03:43 +0000676 SrcRegMap[RegA] = FromRegC;
677 }
678
Evan Cheng6d897062009-01-23 23:27:33 +0000679 return true;
680}
681
Sanjay Patelb53791e2015-12-01 19:32:35 +0000682/// Return true if it is profitable to convert the given 2-address instruction
683/// to a 3-address one.
Evan Cheng09f5be82009-03-30 21:34:07 +0000684bool
Evan Cheng15fed7a2011-03-02 01:08:17 +0000685TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
Evan Cheng09f5be82009-03-30 21:34:07 +0000686 // Look for situations like this:
687 // %reg1024<def> = MOV r1
688 // %reg1025<def> = MOV r0
689 // %reg1026<def> = ADD %reg1024, %reg1025
690 // r2 = MOV %reg1026
691 // Turn ADD into a 3-address instruction to avoid a copy.
Evan Cheng15fed7a2011-03-02 01:08:17 +0000692 unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
693 if (!FromRegB)
694 return false;
Evan Cheng09f5be82009-03-30 21:34:07 +0000695 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
Evan Cheng15fed7a2011-03-02 01:08:17 +0000696 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
Evan Cheng09f5be82009-03-30 21:34:07 +0000697}
698
Sanjay Patelb53791e2015-12-01 19:32:35 +0000699/// Convert the specified two-address instruction into a three address one.
700/// Return true if this transformation was successful.
Evan Cheng09f5be82009-03-30 21:34:07 +0000701bool
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000702TwoAddressInstructionPass::convertInstTo3Addr(MachineBasicBlock::iterator &mi,
Evan Cheng09f5be82009-03-30 21:34:07 +0000703 MachineBasicBlock::iterator &nmi,
Evan Chengd4fcc052011-02-10 02:20:55 +0000704 unsigned RegA, unsigned RegB,
705 unsigned Dist) {
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000706 // FIXME: Why does convertToThreeAddress() need an iterator reference?
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000707 MachineFunction::iterator MFI = MBB->getIterator();
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000708 MachineInstr *NewMI = TII->convertToThreeAddress(MFI, *mi, LV);
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000709 assert(MBB->getIterator() == MFI &&
710 "convertToThreeAddress changed iterator reference");
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000711 if (!NewMI)
712 return false;
Evan Cheng09f5be82009-03-30 21:34:07 +0000713
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000714 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
715 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
716 bool Sunk = false;
Jakob Stoklund Olesen24bc5142012-08-03 22:58:34 +0000717
Cameron Zwarich2ad3ca32013-02-20 22:10:02 +0000718 if (LIS)
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000719 LIS->ReplaceMachineInstrInMaps(*mi, *NewMI);
Evan Cheng09f5be82009-03-30 21:34:07 +0000720
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000721 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
722 // FIXME: Temporary workaround. If the new instruction doesn't
723 // uses RegB, convertToThreeAddress must have created more
724 // then one instruction.
725 Sunk = sink3AddrInstruction(NewMI, RegB, mi);
Evan Cheng09f5be82009-03-30 21:34:07 +0000726
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000727 MBB->erase(mi); // Nuke the old inst.
Evan Chengd4fcc052011-02-10 02:20:55 +0000728
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000729 if (!Sunk) {
730 DistanceMap.insert(std::make_pair(NewMI, Dist));
731 mi = NewMI;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000732 nmi = std::next(mi);
Evan Cheng09f5be82009-03-30 21:34:07 +0000733 }
734
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000735 // Update source and destination register maps.
736 SrcRegMap.erase(RegA);
737 DstRegMap.erase(RegB);
738 return true;
Evan Cheng09f5be82009-03-30 21:34:07 +0000739}
740
Sanjay Patelb53791e2015-12-01 19:32:35 +0000741/// Scan forward recursively for only uses, update maps if the use is a copy or
742/// a two-address instruction.
Evan Cheng15fed7a2011-03-02 01:08:17 +0000743void
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000744TwoAddressInstructionPass::scanUses(unsigned DstReg) {
Evan Cheng15fed7a2011-03-02 01:08:17 +0000745 SmallVector<unsigned, 4> VirtRegPairs;
746 bool IsDstPhys;
747 bool IsCopy = false;
748 unsigned NewReg = 0;
749 unsigned Reg = DstReg;
750 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
751 NewReg, IsDstPhys)) {
David Blaikie70573dc2014-11-19 07:49:26 +0000752 if (IsCopy && !Processed.insert(UseMI).second)
Evan Cheng15fed7a2011-03-02 01:08:17 +0000753 break;
754
755 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
756 if (DI != DistanceMap.end())
757 // Earlier in the same MBB.Reached via a back edge.
758 break;
759
760 if (IsDstPhys) {
761 VirtRegPairs.push_back(NewReg);
762 break;
763 }
764 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
765 if (!isNew)
766 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
767 VirtRegPairs.push_back(NewReg);
768 Reg = NewReg;
769 }
770
771 if (!VirtRegPairs.empty()) {
772 unsigned ToReg = VirtRegPairs.back();
773 VirtRegPairs.pop_back();
774 while (!VirtRegPairs.empty()) {
775 unsigned FromReg = VirtRegPairs.back();
776 VirtRegPairs.pop_back();
777 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
778 if (!isNew)
779 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
780 ToReg = FromReg;
781 }
782 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
783 if (!isNew)
784 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
785 }
786}
787
Sanjay Patelb53791e2015-12-01 19:32:35 +0000788/// If the specified instruction is not yet processed, process it if it's a
789/// copy. For a copy instruction, we find the physical registers the
Evan Chengc2f95b52009-03-01 02:03:43 +0000790/// source and destination registers might be mapped to. These are kept in
791/// point-to maps used to determine future optimizations. e.g.
792/// v1024 = mov r0
793/// v1025 = mov r1
794/// v1026 = add v1024, v1025
795/// r1 = mov r1026
796/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
797/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
798/// potentially joined with r1 on the output side. It's worthwhile to commute
799/// 'add' to eliminate a copy.
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000800void TwoAddressInstructionPass::processCopy(MachineInstr *MI) {
Evan Chengc2f95b52009-03-01 02:03:43 +0000801 if (Processed.count(MI))
802 return;
803
804 bool IsSrcPhys, IsDstPhys;
805 unsigned SrcReg, DstReg;
806 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
807 return;
808
809 if (IsDstPhys && !IsSrcPhys)
810 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
811 else if (!IsDstPhys && IsSrcPhys) {
Evan Chengf0843802009-04-13 20:04:24 +0000812 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
813 if (!isNew)
814 assert(SrcRegMap[DstReg] == SrcReg &&
815 "Can't map to two src physical registers!");
Evan Chengc2f95b52009-03-01 02:03:43 +0000816
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000817 scanUses(DstReg);
Evan Chengc2f95b52009-03-01 02:03:43 +0000818 }
819
820 Processed.insert(MI);
821}
822
Sanjay Patelb53791e2015-12-01 19:32:35 +0000823/// If there is one more local instruction that reads 'Reg' and it kills 'Reg,
824/// consider moving the instruction below the kill instruction in order to
825/// eliminate the need for the copy.
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000826bool TwoAddressInstructionPass::
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000827rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000828 MachineBasicBlock::iterator &nmi,
829 unsigned Reg) {
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000830 // Bail immediately if we don't have LV or LIS available. We use them to find
831 // kills efficiently.
832 if (!LV && !LIS)
Chandler Carruthdb5536f2012-07-15 03:29:46 +0000833 return false;
834
Evan Cheng30f44ad2011-11-14 19:48:55 +0000835 MachineInstr *MI = &*mi;
Andrew Trick808a7a62012-02-03 05:12:30 +0000836 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
Evan Cheng30f44ad2011-11-14 19:48:55 +0000837 if (DI == DistanceMap.end())
838 // Must be created from unfolded load. Don't waste time trying this.
839 return false;
840
Craig Topperc0196b12014-04-14 00:51:57 +0000841 MachineInstr *KillMI = nullptr;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000842 if (LIS) {
843 LiveInterval &LI = LIS->getInterval(Reg);
844 assert(LI.end() != LI.begin() &&
845 "Reg should not have empty live interval.");
846
847 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
848 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
849 if (I != LI.end() && I->start < MBBEndIdx)
850 return false;
851
852 --I;
853 KillMI = LIS->getInstructionFromIndex(I->end);
854 } else {
855 KillMI = LV->getVarInfo(Reg).findKill(MBB);
856 }
Chandler Carruthdb5536f2012-07-15 03:29:46 +0000857 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng30f44ad2011-11-14 19:48:55 +0000858 // Don't mess with copies, they may be coalesced later.
859 return false;
860
Evan Cheng7f8e5632011-12-07 07:15:52 +0000861 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
862 KillMI->isBranch() || KillMI->isTerminator())
Evan Cheng30f44ad2011-11-14 19:48:55 +0000863 // Don't move pass calls, etc.
864 return false;
865
866 unsigned DstReg;
867 if (isTwoAddrUse(*KillMI, Reg, DstReg))
868 return false;
869
Evan Cheng7098c4e2011-11-15 06:26:51 +0000870 bool SeenStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +0000871 if (!MI->isSafeToMove(AA, SeenStore))
Evan Cheng30f44ad2011-11-14 19:48:55 +0000872 return false;
873
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000874 if (TII->getInstrLatency(InstrItins, *MI) > 1)
Evan Cheng30f44ad2011-11-14 19:48:55 +0000875 // FIXME: Needs more sophisticated heuristics.
876 return false;
877
Michael Kupersteine36d7712016-08-11 17:38:33 +0000878 SmallVector<unsigned, 2> Uses;
879 SmallVector<unsigned, 2> Kills;
880 SmallVector<unsigned, 2> Defs;
Sanjay Patel0b2a9492015-12-01 19:57:43 +0000881 for (const MachineOperand &MO : MI->operands()) {
Evan Cheng30f44ad2011-11-14 19:48:55 +0000882 if (!MO.isReg())
883 continue;
884 unsigned MOReg = MO.getReg();
885 if (!MOReg)
886 continue;
887 if (MO.isDef())
Michael Kupersteine36d7712016-08-11 17:38:33 +0000888 Defs.push_back(MOReg);
Evan Chengb8c55a52011-11-16 03:47:42 +0000889 else {
Michael Kupersteine36d7712016-08-11 17:38:33 +0000890 Uses.push_back(MOReg);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000891 if (MOReg != Reg && (MO.isKill() ||
892 (LIS && isPlainlyKilled(MI, MOReg, LIS))))
Michael Kupersteine36d7712016-08-11 17:38:33 +0000893 Kills.push_back(MOReg);
Evan Chengb8c55a52011-11-16 03:47:42 +0000894 }
Evan Cheng30f44ad2011-11-14 19:48:55 +0000895 }
896
897 // Move the copies connected to MI down as well.
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000898 MachineBasicBlock::iterator Begin = MI;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000899 MachineBasicBlock::iterator AfterMI = std::next(Begin);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000900
901 MachineBasicBlock::iterator End = AfterMI;
Michael Kupersteine36d7712016-08-11 17:38:33 +0000902 while (End->isCopy() &&
903 regOverlapsSet(Defs, End->getOperand(1).getReg(), TRI)) {
904 Defs.push_back(End->getOperand(0).getReg());
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000905 ++End;
Evan Cheng30f44ad2011-11-14 19:48:55 +0000906 }
907
908 // Check if the reschedule will not break depedencies.
909 unsigned NumVisited = 0;
910 MachineBasicBlock::iterator KillPos = KillMI;
911 ++KillPos;
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +0000912 for (MachineInstr &OtherMI : llvm::make_range(End, KillPos)) {
Evan Cheng30f44ad2011-11-14 19:48:55 +0000913 // DBG_VALUE cannot be counted against the limit.
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +0000914 if (OtherMI.isDebugValue())
Evan Cheng30f44ad2011-11-14 19:48:55 +0000915 continue;
916 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
917 return false;
918 ++NumVisited;
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +0000919 if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
920 OtherMI.isBranch() || OtherMI.isTerminator())
Evan Cheng30f44ad2011-11-14 19:48:55 +0000921 // Don't move pass calls, etc.
922 return false;
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +0000923 for (const MachineOperand &MO : OtherMI.operands()) {
Evan Cheng30f44ad2011-11-14 19:48:55 +0000924 if (!MO.isReg())
925 continue;
926 unsigned MOReg = MO.getReg();
927 if (!MOReg)
928 continue;
929 if (MO.isDef()) {
Michael Kupersteine36d7712016-08-11 17:38:33 +0000930 if (regOverlapsSet(Uses, MOReg, TRI))
Evan Cheng30f44ad2011-11-14 19:48:55 +0000931 // Physical register use would be clobbered.
932 return false;
Michael Kupersteine36d7712016-08-11 17:38:33 +0000933 if (!MO.isDead() && regOverlapsSet(Defs, MOReg, TRI))
Evan Cheng30f44ad2011-11-14 19:48:55 +0000934 // May clobber a physical register def.
935 // FIXME: This may be too conservative. It's ok if the instruction
936 // is sunken completely below the use.
937 return false;
938 } else {
Michael Kupersteine36d7712016-08-11 17:38:33 +0000939 if (regOverlapsSet(Defs, MOReg, TRI))
Evan Cheng30f44ad2011-11-14 19:48:55 +0000940 return false;
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +0000941 bool isKill =
942 MO.isKill() || (LIS && isPlainlyKilled(&OtherMI, MOReg, LIS));
Michael Kupersteine36d7712016-08-11 17:38:33 +0000943 if (MOReg != Reg && ((isKill && regOverlapsSet(Uses, MOReg, TRI)) ||
944 regOverlapsSet(Kills, MOReg, TRI)))
Evan Cheng30f44ad2011-11-14 19:48:55 +0000945 // Don't want to extend other live ranges and update kills.
946 return false;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000947 if (MOReg == Reg && !isKill)
Chandler Carruthdb5536f2012-07-15 03:29:46 +0000948 // We can't schedule across a use of the register in question.
949 return false;
950 // Ensure that if this is register in question, its the kill we expect.
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +0000951 assert((MOReg != Reg || &OtherMI == KillMI) &&
Chandler Carruthdb5536f2012-07-15 03:29:46 +0000952 "Found multiple kills of a register in a basic block");
Evan Cheng30f44ad2011-11-14 19:48:55 +0000953 }
954 }
955 }
956
957 // Move debug info as well.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000958 while (Begin != MBB->begin() && std::prev(Begin)->isDebugValue())
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000959 --Begin;
960
961 nmi = End;
962 MachineBasicBlock::iterator InsertPos = KillPos;
963 if (LIS) {
964 // We have to move the copies first so that the MBB is still well-formed
965 // when calling handleMove().
966 for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) {
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +0000967 auto CopyMI = MBBI++;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000968 MBB->splice(InsertPos, MBB, CopyMI);
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +0000969 LIS->handleMove(*CopyMI);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000970 InsertPos = CopyMI;
971 }
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000972 End = std::next(MachineBasicBlock::iterator(MI));
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000973 }
Evan Cheng30f44ad2011-11-14 19:48:55 +0000974
975 // Copies following MI may have been moved as well.
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000976 MBB->splice(InsertPos, MBB, Begin, End);
Evan Cheng30f44ad2011-11-14 19:48:55 +0000977 DistanceMap.erase(DI);
978
Chandler Carruthdb5536f2012-07-15 03:29:46 +0000979 // Update live variables
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000980 if (LIS) {
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +0000981 LIS->handleMove(*MI);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000982 } else {
Duncan P. N. Exon Smithd26fdc82016-07-01 01:51:32 +0000983 LV->removeVirtualRegisterKilled(Reg, *KillMI);
984 LV->addVirtualRegisterKilled(Reg, *MI);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000985 }
Evan Cheng30f44ad2011-11-14 19:48:55 +0000986
Jakob Stoklund Olesen0ef03112012-07-17 17:57:23 +0000987 DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
Evan Cheng30f44ad2011-11-14 19:48:55 +0000988 return true;
989}
990
Sanjay Patelb53791e2015-12-01 19:32:35 +0000991/// Return true if the re-scheduling will put the given instruction too close
992/// to the defs of its register dependencies.
Evan Cheng30f44ad2011-11-14 19:48:55 +0000993bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000994 MachineInstr *MI) {
Owen Andersonb36376e2014-03-17 19:36:09 +0000995 for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
996 if (DefMI.getParent() != MBB || DefMI.isCopy() || DefMI.isCopyLike())
Evan Cheng30f44ad2011-11-14 19:48:55 +0000997 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +0000998 if (&DefMI == MI)
Evan Cheng30f44ad2011-11-14 19:48:55 +0000999 return true; // MI is defining something KillMI uses
Owen Andersonb36376e2014-03-17 19:36:09 +00001000 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(&DefMI);
Evan Cheng30f44ad2011-11-14 19:48:55 +00001001 if (DDI == DistanceMap.end())
1002 return true; // Below MI
1003 unsigned DefDist = DDI->second;
1004 assert(Dist > DefDist && "Visited def already?");
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001005 if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist))
Evan Cheng30f44ad2011-11-14 19:48:55 +00001006 return true;
1007 }
1008 return false;
1009}
1010
Sanjay Patelb53791e2015-12-01 19:32:35 +00001011/// If there is one more local instruction that reads 'Reg' and it kills 'Reg,
1012/// consider moving the kill instruction above the current two-address
1013/// instruction in order to eliminate the need for the copy.
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +00001014bool TwoAddressInstructionPass::
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001015rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +00001016 MachineBasicBlock::iterator &nmi,
1017 unsigned Reg) {
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001018 // Bail immediately if we don't have LV or LIS available. We use them to find
1019 // kills efficiently.
1020 if (!LV && !LIS)
Chandler Carruthdb5536f2012-07-15 03:29:46 +00001021 return false;
1022
Evan Cheng30f44ad2011-11-14 19:48:55 +00001023 MachineInstr *MI = &*mi;
1024 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
1025 if (DI == DistanceMap.end())
1026 // Must be created from unfolded load. Don't waste time trying this.
1027 return false;
1028
Craig Topperc0196b12014-04-14 00:51:57 +00001029 MachineInstr *KillMI = nullptr;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001030 if (LIS) {
1031 LiveInterval &LI = LIS->getInterval(Reg);
1032 assert(LI.end() != LI.begin() &&
1033 "Reg should not have empty live interval.");
1034
1035 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
1036 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
1037 if (I != LI.end() && I->start < MBBEndIdx)
1038 return false;
1039
1040 --I;
1041 KillMI = LIS->getInstructionFromIndex(I->end);
1042 } else {
1043 KillMI = LV->getVarInfo(Reg).findKill(MBB);
1044 }
Chandler Carruthdb5536f2012-07-15 03:29:46 +00001045 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng30f44ad2011-11-14 19:48:55 +00001046 // Don't mess with copies, they may be coalesced later.
1047 return false;
1048
1049 unsigned DstReg;
1050 if (isTwoAddrUse(*KillMI, Reg, DstReg))
1051 return false;
1052
Evan Cheng7098c4e2011-11-15 06:26:51 +00001053 bool SeenStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +00001054 if (!KillMI->isSafeToMove(AA, SeenStore))
Evan Cheng30f44ad2011-11-14 19:48:55 +00001055 return false;
1056
1057 SmallSet<unsigned, 2> Uses;
1058 SmallSet<unsigned, 2> Kills;
1059 SmallSet<unsigned, 2> Defs;
1060 SmallSet<unsigned, 2> LiveDefs;
Sanjay Patel0b2a9492015-12-01 19:57:43 +00001061 for (const MachineOperand &MO : KillMI->operands()) {
Evan Cheng30f44ad2011-11-14 19:48:55 +00001062 if (!MO.isReg())
1063 continue;
1064 unsigned MOReg = MO.getReg();
1065 if (MO.isUse()) {
1066 if (!MOReg)
1067 continue;
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001068 if (isDefTooClose(MOReg, DI->second, MI))
Evan Cheng30f44ad2011-11-14 19:48:55 +00001069 return false;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001070 bool isKill = MO.isKill() || (LIS && isPlainlyKilled(KillMI, MOReg, LIS));
1071 if (MOReg == Reg && !isKill)
Chandler Carruthdb5536f2012-07-15 03:29:46 +00001072 return false;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001073 Uses.insert(MOReg);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001074 if (isKill && MOReg != Reg)
Evan Cheng30f44ad2011-11-14 19:48:55 +00001075 Kills.insert(MOReg);
1076 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1077 Defs.insert(MOReg);
1078 if (!MO.isDead())
1079 LiveDefs.insert(MOReg);
1080 }
1081 }
1082
1083 // Check if the reschedule will not break depedencies.
1084 unsigned NumVisited = 0;
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001085 for (MachineInstr &OtherMI :
1086 llvm::make_range(mi, MachineBasicBlock::iterator(KillMI))) {
Evan Cheng30f44ad2011-11-14 19:48:55 +00001087 // DBG_VALUE cannot be counted against the limit.
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001088 if (OtherMI.isDebugValue())
Evan Cheng30f44ad2011-11-14 19:48:55 +00001089 continue;
1090 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
1091 return false;
1092 ++NumVisited;
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001093 if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
1094 OtherMI.isBranch() || OtherMI.isTerminator())
Evan Cheng30f44ad2011-11-14 19:48:55 +00001095 // Don't move pass calls, etc.
1096 return false;
Evan Cheng9ddd69a2011-11-16 03:05:12 +00001097 SmallVector<unsigned, 2> OtherDefs;
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001098 for (const MachineOperand &MO : OtherMI.operands()) {
Evan Cheng30f44ad2011-11-14 19:48:55 +00001099 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;
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +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) {
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +00001148 LIS->handleMove(*KillMI);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001149 } else {
Duncan P. N. Exon Smithd26fdc82016-07-01 01:51:32 +00001150 LV->removeVirtualRegisterKilled(Reg, *KillMI);
1151 LV->addVirtualRegisterKilled(Reg, *MI);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001152 }
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
Andrew Kaylor16c4da02015-09-28 20:33:22 +00001158/// Tries to commute the operand 'BaseOpIdx' and some other operand in the
1159/// given machine instruction to improve opportunities for coalescing and
1160/// elimination of a register to register copy.
1161///
1162/// 'DstOpIdx' specifies the index of MI def operand.
1163/// 'BaseOpKilled' specifies if the register associated with 'BaseOpIdx'
1164/// operand is killed by the given instruction.
1165/// The 'Dist' arguments provides the distance of MI from the start of the
1166/// current basic block and it is used to determine if it is profitable
1167/// to commute operands in the instruction.
1168///
1169/// Returns true if the transformation happened. Otherwise, returns false.
1170bool TwoAddressInstructionPass::tryInstructionCommute(MachineInstr *MI,
1171 unsigned DstOpIdx,
1172 unsigned BaseOpIdx,
1173 bool BaseOpKilled,
1174 unsigned Dist) {
Craig Topper1f81dee2016-09-11 06:00:15 +00001175 if (!MI->isCommutable())
1176 return false;
1177
Andrew Kaylor16c4da02015-09-28 20:33:22 +00001178 unsigned DstOpReg = MI->getOperand(DstOpIdx).getReg();
1179 unsigned BaseOpReg = MI->getOperand(BaseOpIdx).getReg();
1180 unsigned OpsNum = MI->getDesc().getNumOperands();
1181 unsigned OtherOpIdx = MI->getDesc().getNumDefs();
1182 for (; OtherOpIdx < OpsNum; OtherOpIdx++) {
1183 // The call of findCommutedOpIndices below only checks if BaseOpIdx
Sanjay Patel96824de2015-12-01 19:19:18 +00001184 // and OtherOpIdx are commutable, it does not really search for
Andrew Kaylor16c4da02015-09-28 20:33:22 +00001185 // other commutable operands and does not change the values of passed
1186 // variables.
Craig Topper1f81dee2016-09-11 06:00:15 +00001187 if (OtherOpIdx == BaseOpIdx || !MI->getOperand(OtherOpIdx).isReg() ||
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001188 !TII->findCommutedOpIndices(*MI, BaseOpIdx, OtherOpIdx))
Andrew Kaylor16c4da02015-09-28 20:33:22 +00001189 continue;
1190
1191 unsigned OtherOpReg = MI->getOperand(OtherOpIdx).getReg();
1192 bool AggressiveCommute = false;
1193
1194 // If OtherOp dies but BaseOp does not, swap the OtherOp and BaseOp
1195 // operands. This makes the live ranges of DstOp and OtherOp joinable.
1196 bool DoCommute =
1197 !BaseOpKilled && isKilled(*MI, OtherOpReg, MRI, TII, LIS, false);
1198
1199 if (!DoCommute &&
1200 isProfitableToCommute(DstOpReg, BaseOpReg, OtherOpReg, MI, Dist)) {
1201 DoCommute = true;
1202 AggressiveCommute = true;
1203 }
1204
1205 // If it's profitable to commute, try to do so.
Craig Topper76007942016-09-11 22:10:42 +00001206 if (DoCommute && commuteInstruction(MI, DstOpIdx, BaseOpIdx, OtherOpIdx,
1207 Dist)) {
Andrew Kaylor16c4da02015-09-28 20:33:22 +00001208 ++NumCommuted;
1209 if (AggressiveCommute)
1210 ++NumAggrCommuted;
1211 return true;
1212 }
1213 }
1214 return false;
1215}
1216
Sanjay Patelb53791e2015-12-01 19:32:35 +00001217/// For the case where an instruction has a single pair of tied register
1218/// operands, attempt some transformations that may either eliminate the tied
1219/// operands or improve the opportunities for coalescing away the register copy.
1220/// Returns true if no copy needs to be inserted to untie mi's operands
1221/// (either because they were untied, or because mi was rescheduled, and will
1222/// be visited again later). If the shouldOnlyCommute flag is true, only
1223/// instruction commutation is attempted.
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001224bool TwoAddressInstructionPass::
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +00001225tryInstructionTransform(MachineBasicBlock::iterator &mi,
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001226 MachineBasicBlock::iterator &nmi,
Cameron Zwarichf05c0cb2013-02-24 00:27:26 +00001227 unsigned SrcIdx, unsigned DstIdx,
1228 unsigned Dist, bool shouldOnlyCommute) {
Evan Cheng822ddde2011-11-16 18:44:48 +00001229 if (OptLevel == CodeGenOpt::None)
1230 return false;
1231
Evan Cheng30f44ad2011-11-14 19:48:55 +00001232 MachineInstr &MI = *mi;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001233 unsigned regA = MI.getOperand(DstIdx).getReg();
1234 unsigned regB = MI.getOperand(SrcIdx).getReg();
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001235
1236 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1237 "cannot make instruction into two-address form");
Cameron Zwarich384026b2013-02-21 22:58:42 +00001238 bool regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001239
Evan Chengb64e7b72012-05-03 01:45:13 +00001240 if (TargetRegisterInfo::isVirtualRegister(regA))
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001241 scanUses(regA);
Evan Chengb64e7b72012-05-03 01:45:13 +00001242
Andrew Kaylor16c4da02015-09-28 20:33:22 +00001243 bool Commuted = tryInstructionCommute(&MI, DstIdx, SrcIdx, regBKilled, Dist);
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001244
Quentin Colombet9729fb32015-07-01 23:12:13 +00001245 // If the instruction is convertible to 3 Addr, instead
1246 // of returning try 3 Addr transformation aggresively and
1247 // use this variable to check later. Because it might be better.
1248 // For example, we can just use `leal (%rsi,%rdi), %eax` and `ret`
1249 // instead of the following code.
NAKAMURA Takumi84965032015-09-22 11:14:12 +00001250 // addl %esi, %edi
1251 // movl %edi, %eax
Quentin Colombet9729fb32015-07-01 23:12:13 +00001252 // ret
Andrew Kaylor16c4da02015-09-28 20:33:22 +00001253 if (Commuted && !MI.isConvertibleTo3Addr())
1254 return false;
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001255
Cameron Zwarichf05c0cb2013-02-24 00:27:26 +00001256 if (shouldOnlyCommute)
1257 return false;
1258
Evan Cheng30f44ad2011-11-14 19:48:55 +00001259 // If there is one more use of regB later in the same MBB, consider
1260 // re-schedule this MI below it.
Quentin Colombet40dd5102015-07-06 20:12:54 +00001261 if (!Commuted && EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) {
Evan Cheng30f44ad2011-11-14 19:48:55 +00001262 ++NumReSchedDowns;
Lang Hames3ad11ff2012-04-09 20:17:30 +00001263 return true;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001264 }
1265
Craig Topper2c4068f2015-10-06 05:39:59 +00001266 // If we commuted, regB may have changed so we should re-sample it to avoid
1267 // confusing the three address conversion below.
1268 if (Commuted) {
1269 regB = MI.getOperand(SrcIdx).getReg();
1270 regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
1271 }
1272
Evan Cheng7f8e5632011-12-07 07:15:52 +00001273 if (MI.isConvertibleTo3Addr()) {
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001274 // This instruction is potentially convertible to a true
1275 // three-address instruction. Check if it is profitable.
Evan Cheng15fed7a2011-03-02 01:08:17 +00001276 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001277 // Try to convert it.
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001278 if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001279 ++NumConvertedTo3Addr;
1280 return true; // Done with this instruction.
1281 }
1282 }
1283 }
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001284
Quentin Colombet9729fb32015-07-01 23:12:13 +00001285 // Return if it is commuted but 3 addr conversion is failed.
Quentin Colombet40dd5102015-07-06 20:12:54 +00001286 if (Commuted)
Quentin Colombet9729fb32015-07-01 23:12:13 +00001287 return false;
1288
Evan Cheng30f44ad2011-11-14 19:48:55 +00001289 // If there is one more use of regB later in the same MBB, consider
1290 // re-schedule it before this MI if it's legal.
Andrew Trick608a6982013-04-24 15:54:39 +00001291 if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) {
Evan Cheng30f44ad2011-11-14 19:48:55 +00001292 ++NumReSchedUps;
Lang Hames3ad11ff2012-04-09 20:17:30 +00001293 return true;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001294 }
1295
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001296 // If this is an instruction with a load folded into it, try unfolding
1297 // the load, e.g. avoid this:
1298 // movq %rdx, %rcx
1299 // addq (%rax), %rcx
1300 // in favor of this:
1301 // movq (%rax), %rcx
1302 // addq %rdx, %rcx
1303 // because it's preferable to schedule a load than a register copy.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001304 if (MI.mayLoad() && !regBKilled) {
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001305 // Determine if a load can be unfolded.
1306 unsigned LoadRegIndex;
1307 unsigned NewOpc =
Evan Cheng30f44ad2011-11-14 19:48:55 +00001308 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001309 /*UnfoldLoad=*/true,
1310 /*UnfoldStore=*/false,
1311 &LoadRegIndex);
1312 if (NewOpc != 0) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00001313 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1314 if (UnfoldMCID.getNumDefs() == 1) {
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001315 // Unfold the load.
Evan Cheng30f44ad2011-11-14 19:48:55 +00001316 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001317 const TargetRegisterClass *RC =
Andrew Trick32aea352012-05-03 01:14:37 +00001318 TRI->getAllocatableClass(
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001319 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001320 unsigned Reg = MRI->createVirtualRegister(RC);
1321 SmallVector<MachineInstr *, 2> NewMIs;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001322 if (!TII->unfoldMemoryOperand(*MF, MI, Reg,
1323 /*UnfoldLoad=*/true,
1324 /*UnfoldStore=*/false, NewMIs)) {
Evan Cheng0ce84482010-07-02 20:36:18 +00001325 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1326 return false;
1327 }
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001328 assert(NewMIs.size() == 2 &&
1329 "Unfolded a load into multiple instructions!");
1330 // The load was previously folded, so this is the only use.
1331 NewMIs[1]->addRegisterKilled(Reg, TRI);
1332
1333 // Tentatively insert the instructions into the block so that they
1334 // look "normal" to the transformation logic.
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001335 MBB->insert(mi, NewMIs[0]);
1336 MBB->insert(mi, NewMIs[1]);
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001337
1338 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1339 << "2addr: NEW INST: " << *NewMIs[1]);
1340
1341 // Transform the instruction, now that it no longer has a load.
1342 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1343 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1344 MachineBasicBlock::iterator NewMI = NewMIs[1];
Cameron Zwarich6868f382013-02-24 00:27:29 +00001345 bool TransformResult =
Cameron Zwarichf05c0cb2013-02-24 00:27:26 +00001346 tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true);
Cameron Zwarich1b4c64c2013-02-24 01:26:05 +00001347 (void)TransformResult;
Cameron Zwarich6868f382013-02-24 00:27:29 +00001348 assert(!TransformResult &&
1349 "tryInstructionTransform() should return false.");
1350 if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001351 // Success, or at least we made an improvement. Keep the unfolded
1352 // instructions and discard the original.
1353 if (LV) {
Evan Cheng30f44ad2011-11-14 19:48:55 +00001354 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1355 MachineOperand &MO = MI.getOperand(i);
Andrew Trick808a7a62012-02-03 05:12:30 +00001356 if (MO.isReg() &&
Dan Gohman851e4782010-06-22 00:32:04 +00001357 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1358 if (MO.isUse()) {
Dan Gohman2370e2f2010-06-22 02:07:21 +00001359 if (MO.isKill()) {
1360 if (NewMIs[0]->killsRegister(MO.getReg()))
Duncan P. N. Exon Smithd26fdc82016-07-01 01:51:32 +00001361 LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[0]);
Dan Gohman2370e2f2010-06-22 02:07:21 +00001362 else {
1363 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1364 "Kill missing after load unfold!");
Duncan P. N. Exon Smithd26fdc82016-07-01 01:51:32 +00001365 LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[1]);
Dan Gohman2370e2f2010-06-22 02:07:21 +00001366 }
1367 }
Duncan P. N. Exon Smithd26fdc82016-07-01 01:51:32 +00001368 } else if (LV->removeVirtualRegisterDead(MO.getReg(), MI)) {
Dan Gohman2370e2f2010-06-22 02:07:21 +00001369 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
Duncan P. N. Exon Smithd26fdc82016-07-01 01:51:32 +00001370 LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[1]);
Dan Gohman2370e2f2010-06-22 02:07:21 +00001371 else {
1372 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1373 "Dead flag missing after load unfold!");
Duncan P. N. Exon Smithd26fdc82016-07-01 01:51:32 +00001374 LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[0]);
Dan Gohman2370e2f2010-06-22 02:07:21 +00001375 }
1376 }
Dan Gohman851e4782010-06-22 00:32:04 +00001377 }
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001378 }
Duncan P. N. Exon Smithd26fdc82016-07-01 01:51:32 +00001379 LV->addVirtualRegisterKilled(Reg, *NewMIs[1]);
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001380 }
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001381
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001382 SmallVector<unsigned, 4> OrigRegs;
1383 if (LIS) {
Craig Topperda5168b2015-10-08 06:06:42 +00001384 for (const MachineOperand &MO : MI.operands()) {
1385 if (MO.isReg())
1386 OrigRegs.push_back(MO.getReg());
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001387 }
1388 }
1389
Evan Cheng30f44ad2011-11-14 19:48:55 +00001390 MI.eraseFromParent();
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001391
1392 // Update LiveIntervals.
Cameron Zwarichcaad7e12013-02-20 22:10:00 +00001393 if (LIS) {
1394 MachineBasicBlock::iterator Begin(NewMIs[0]);
1395 MachineBasicBlock::iterator End(NewMIs[1]);
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001396 LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs);
Cameron Zwarichcaad7e12013-02-20 22:10:00 +00001397 }
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001398
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001399 mi = NewMIs[1];
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001400 } else {
1401 // Transforming didn't eliminate the tie and didn't lead to an
1402 // improvement. Clean up the unfolded instructions and keep the
1403 // original.
1404 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1405 NewMIs[0]->eraseFromParent();
1406 NewMIs[1]->eraseFromParent();
1407 }
1408 }
1409 }
1410 }
1411
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001412 return false;
1413}
1414
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001415// Collect tied operands of MI that need to be handled.
1416// Rewrite trivial cases immediately.
1417// Return true if any tied operands where found, including the trivial ones.
1418bool TwoAddressInstructionPass::
1419collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
1420 const MCInstrDesc &MCID = MI->getDesc();
1421 bool AnyOps = false;
Jakob Stoklund Olesenade363e2012-09-04 22:59:30 +00001422 unsigned NumOps = MI->getNumOperands();
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001423
1424 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1425 unsigned DstIdx = 0;
1426 if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1427 continue;
1428 AnyOps = true;
Jakob Stoklund Olesenfbf45dc2012-08-07 22:47:06 +00001429 MachineOperand &SrcMO = MI->getOperand(SrcIdx);
1430 MachineOperand &DstMO = MI->getOperand(DstIdx);
1431 unsigned SrcReg = SrcMO.getReg();
1432 unsigned DstReg = DstMO.getReg();
1433 // Tied constraint already satisfied?
1434 if (SrcReg == DstReg)
1435 continue;
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001436
Jakob Stoklund Olesenfbf45dc2012-08-07 22:47:06 +00001437 assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001438
1439 // Deal with <undef> uses immediately - simply rewrite the src operand.
Andrew Tricke3398282013-12-17 04:50:45 +00001440 if (SrcMO.isUndef() && !DstMO.getSubReg()) {
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001441 // Constrain the DstReg register class if required.
1442 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1443 if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
1444 TRI, *MF))
1445 MRI->constrainRegClass(DstReg, RC);
Jakob Stoklund Olesenfbf45dc2012-08-07 22:47:06 +00001446 SrcMO.setReg(DstReg);
Andrew Tricke3398282013-12-17 04:50:45 +00001447 SrcMO.setSubReg(0);
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001448 DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
1449 continue;
1450 }
Jakob Stoklund Olesenfbf45dc2012-08-07 22:47:06 +00001451 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001452 }
1453 return AnyOps;
1454}
1455
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001456// Process a list of tied MI operands that all use the same source register.
1457// The tied pairs are of the form (SrcIdx, DstIdx).
1458void
1459TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
1460 TiedPairList &TiedPairs,
1461 unsigned &Dist) {
1462 bool IsEarlyClobber = false;
Cameron Zwarich2991feb2013-02-20 06:46:46 +00001463 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1464 const MachineOperand &DstMO = MI->getOperand(TiedPairs[tpi].second);
1465 IsEarlyClobber |= DstMO.isEarlyClobber();
1466 }
1467
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001468 bool RemovedKillFlag = false;
1469 bool AllUsesCopied = true;
1470 unsigned LastCopiedReg = 0;
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001471 SlotIndex LastCopyIdx;
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001472 unsigned RegB = 0;
Andrew Tricke3398282013-12-17 04:50:45 +00001473 unsigned SubRegB = 0;
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001474 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1475 unsigned SrcIdx = TiedPairs[tpi].first;
1476 unsigned DstIdx = TiedPairs[tpi].second;
1477
1478 const MachineOperand &DstMO = MI->getOperand(DstIdx);
1479 unsigned RegA = DstMO.getReg();
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001480
1481 // Grab RegB from the instruction because it may have changed if the
1482 // instruction was commuted.
1483 RegB = MI->getOperand(SrcIdx).getReg();
Andrew Tricke3398282013-12-17 04:50:45 +00001484 SubRegB = MI->getOperand(SrcIdx).getSubReg();
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001485
1486 if (RegA == RegB) {
1487 // The register is tied to multiple destinations (or else we would
1488 // not have continued this far), but this use of the register
1489 // already matches the tied destination. Leave it.
1490 AllUsesCopied = false;
1491 continue;
1492 }
1493 LastCopiedReg = RegA;
1494
1495 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1496 "cannot make instruction into two-address form");
1497
1498#ifndef NDEBUG
1499 // First, verify that we don't have a use of "a" in the instruction
1500 // (a = b + a for example) because our transformation will not
1501 // work. This should never occur because we are in SSA form.
1502 for (unsigned i = 0; i != MI->getNumOperands(); ++i)
1503 assert(i == DstIdx ||
1504 !MI->getOperand(i).isReg() ||
1505 MI->getOperand(i).getReg() != RegA);
1506#endif
1507
1508 // Emit a copy.
Andrew Tricke3398282013-12-17 04:50:45 +00001509 MachineInstrBuilder MIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1510 TII->get(TargetOpcode::COPY), RegA);
1511 // If this operand is folding a truncation, the truncation now moves to the
1512 // copy so that the register classes remain valid for the operands.
1513 MIB.addReg(RegB, 0, SubRegB);
1514 const TargetRegisterClass *RC = MRI->getRegClass(RegB);
1515 if (SubRegB) {
1516 if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1517 assert(TRI->getMatchingSuperRegClass(RC, MRI->getRegClass(RegA),
1518 SubRegB) &&
1519 "tied subregister must be a truncation");
1520 // The superreg class will not be used to constrain the subreg class.
Craig Topperc0196b12014-04-14 00:51:57 +00001521 RC = nullptr;
Andrew Tricke3398282013-12-17 04:50:45 +00001522 }
1523 else {
1524 assert(TRI->getMatchingSuperReg(RegA, SubRegB, MRI->getRegClass(RegB))
1525 && "tied subregister must be a truncation");
1526 }
1527 }
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001528
1529 // Update DistanceMap.
1530 MachineBasicBlock::iterator PrevMI = MI;
1531 --PrevMI;
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001532 DistanceMap.insert(std::make_pair(&*PrevMI, Dist));
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001533 DistanceMap[MI] = ++Dist;
1534
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001535 if (LIS) {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001536 LastCopyIdx = LIS->InsertMachineInstrInMaps(*PrevMI).getRegSlot();
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001537
1538 if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1539 LiveInterval &LI = LIS->getInterval(RegA);
1540 VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1541 SlotIndex endIdx =
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001542 LIS->getInstructionIndex(*MI).getRegSlot(IsEarlyClobber);
Matthias Braun13ddb7c2013-10-10 21:28:43 +00001543 LI.addSegment(LiveInterval::Segment(LastCopyIdx, endIdx, VNI));
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001544 }
1545 }
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001546
Andrew Tricke3398282013-12-17 04:50:45 +00001547 DEBUG(dbgs() << "\t\tprepend:\t" << *MIB);
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001548
1549 MachineOperand &MO = MI->getOperand(SrcIdx);
1550 assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
1551 "inconsistent operand info for 2-reg pass");
1552 if (MO.isKill()) {
1553 MO.setIsKill(false);
1554 RemovedKillFlag = true;
1555 }
1556
1557 // Make sure regA is a legal regclass for the SrcIdx operand.
1558 if (TargetRegisterInfo::isVirtualRegister(RegA) &&
1559 TargetRegisterInfo::isVirtualRegister(RegB))
Andrew Tricke3398282013-12-17 04:50:45 +00001560 MRI->constrainRegClass(RegA, RC);
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001561 MO.setReg(RegA);
Andrew Tricke3398282013-12-17 04:50:45 +00001562 // The getMatchingSuper asserts guarantee that the register class projected
1563 // by SubRegB is compatible with RegA with no subregister. So regardless of
1564 // whether the dest oper writes a subreg, the source oper should not.
1565 MO.setSubReg(0);
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001566
1567 // Propagate SrcRegMap.
1568 SrcRegMap[RegA] = RegB;
1569 }
1570
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001571 if (AllUsesCopied) {
1572 if (!IsEarlyClobber) {
1573 // Replace other (un-tied) uses of regB with LastCopiedReg.
Sanjay Patel0b2a9492015-12-01 19:57:43 +00001574 for (MachineOperand &MO : MI->operands()) {
Matt Arsenaultf403df32016-08-26 06:31:32 +00001575 if (MO.isReg() && MO.getReg() == RegB &&
Andrew Tricke3398282013-12-17 04:50:45 +00001576 MO.isUse()) {
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001577 if (MO.isKill()) {
1578 MO.setIsKill(false);
1579 RemovedKillFlag = true;
1580 }
1581 MO.setReg(LastCopiedReg);
Matt Arsenaultf403df32016-08-26 06:31:32 +00001582 MO.setSubReg(MO.getSubReg());
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001583 }
1584 }
1585 }
1586
1587 // Update live variables for regB.
Duncan P. N. Exon Smithd26fdc82016-07-01 01:51:32 +00001588 if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(*MI)) {
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001589 MachineBasicBlock::iterator PrevMI = MI;
1590 --PrevMI;
Duncan P. N. Exon Smithd26fdc82016-07-01 01:51:32 +00001591 LV->addVirtualRegisterKilled(RegB, *PrevMI);
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001592 }
1593
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001594 // Update LiveIntervals.
1595 if (LIS) {
1596 LiveInterval &LI = LIS->getInterval(RegB);
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001597 SlotIndex MIIdx = LIS->getInstructionIndex(*MI);
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001598 LiveInterval::const_iterator I = LI.find(MIIdx);
1599 assert(I != LI.end() && "RegB must be live-in to use.");
1600
1601 SlotIndex UseIdx = MIIdx.getRegSlot(IsEarlyClobber);
1602 if (I->end == UseIdx)
Matthias Braun13ddb7c2013-10-10 21:28:43 +00001603 LI.removeSegment(LastCopyIdx, UseIdx);
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001604 }
1605
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001606 } else if (RemovedKillFlag) {
1607 // Some tied uses of regB matched their destination registers, so
1608 // regB is still used in this instruction, but a kill flag was
1609 // removed from a different tied use of regB, so now we need to add
1610 // a kill flag to one of the remaining uses of regB.
Sanjay Patel0b2a9492015-12-01 19:57:43 +00001611 for (MachineOperand &MO : MI->operands()) {
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001612 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1613 MO.setIsKill(true);
1614 break;
1615 }
1616 }
1617 }
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001618}
1619
Sanjay Patelb53791e2015-12-01 19:32:35 +00001620/// Reduce two-address instructions to two operands.
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001621bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
1622 MF = &Func;
1623 const TargetMachine &TM = MF->getTarget();
1624 MRI = &MF->getRegInfo();
Eric Christopher33726202015-01-27 08:48:42 +00001625 TII = MF->getSubtarget().getInstrInfo();
1626 TRI = MF->getSubtarget().getRegisterInfo();
1627 InstrItins = MF->getSubtarget().getInstrItineraryData();
Duncan Sands5a913d62009-01-28 13:14:17 +00001628 LV = getAnalysisIfAvailable<LiveVariables>();
Jakob Stoklund Olesen24bc5142012-08-03 22:58:34 +00001629 LIS = getAnalysisIfAvailable<LiveIntervals>();
Chandler Carruth7b560d42015-09-09 17:55:00 +00001630 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Evan Cheng822ddde2011-11-16 18:44:48 +00001631 OptLevel = TM.getOptLevel();
Alkis Evlogimenos725021c2003-12-18 13:06:04 +00001632
Misha Brukman6dd644e2004-07-22 15:26:23 +00001633 bool MadeChange = false;
Alkis Evlogimenos725021c2003-12-18 13:06:04 +00001634
David Greeneac9f8192010-01-05 01:24:21 +00001635 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
Andrew Trick808a7a62012-02-03 05:12:30 +00001636 DEBUG(dbgs() << "********** Function: "
Craig Toppera538d832012-08-22 06:07:19 +00001637 << MF->getName() << '\n');
Alkis Evlogimenos26583db2004-02-18 00:35:06 +00001638
Jakob Stoklund Olesen9760f042011-07-29 22:51:22 +00001639 // This pass takes the function out of SSA form.
1640 MRI->leaveSSA();
1641
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001642 TiedOperandMap TiedOperands;
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001643 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
1644 MBBI != MBBE; ++MBBI) {
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +00001645 MBB = &*MBBI;
Evan Chengc5618eb2008-06-18 07:49:14 +00001646 unsigned Dist = 0;
1647 DistanceMap.clear();
Evan Chengc2f95b52009-03-01 02:03:43 +00001648 SrcRegMap.clear();
1649 DstRegMap.clear();
1650 Processed.clear();
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001651 for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
Evan Cheng58324102008-03-27 01:27:25 +00001652 mi != me; ) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001653 MachineBasicBlock::iterator nmi = std::next(mi);
Dale Johannesen8bba1602010-02-10 21:47:48 +00001654 if (mi->isDebugValue()) {
1655 mi = nmi;
1656 continue;
1657 }
Evan Cheng77be42a2010-03-23 20:36:12 +00001658
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001659 // Expand REG_SEQUENCE instructions. This will position mi at the first
1660 // expanded instruction.
Evan Cheng4b6abd82010-05-05 18:45:40 +00001661 if (mi->isRegSequence())
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001662 eliminateRegSequence(mi);
Evan Cheng4b6abd82010-05-05 18:45:40 +00001663
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001664 DistanceMap.insert(std::make_pair(&*mi, ++Dist));
Evan Chengc2f95b52009-03-01 02:03:43 +00001665
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001666 processCopy(&*mi);
Evan Chengc2f95b52009-03-01 02:03:43 +00001667
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001668 // First scan through all the tied register uses in this instruction
1669 // and record a list of pairs of tied operands for each register.
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001670 if (!collectTiedOperands(&*mi, TiedOperands)) {
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001671 mi = nmi;
1672 continue;
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001673 }
Alkis Evlogimenos725021c2003-12-18 13:06:04 +00001674
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001675 ++NumTwoAddressInstrs;
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001676 MadeChange = true;
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001677 DEBUG(dbgs() << '\t' << *mi);
1678
Chandler Carruth985454e2012-07-18 18:58:22 +00001679 // If the instruction has a single pair of tied operands, try some
1680 // transformations that may either eliminate the tied operands or
1681 // improve the opportunities for coalescing away the register copy.
1682 if (TiedOperands.size() == 1) {
Craig Topperb94011f2013-07-14 04:42:23 +00001683 SmallVectorImpl<std::pair<unsigned, unsigned> > &TiedPairs
Chandler Carruth985454e2012-07-18 18:58:22 +00001684 = TiedOperands.begin()->second;
1685 if (TiedPairs.size() == 1) {
1686 unsigned SrcIdx = TiedPairs[0].first;
1687 unsigned DstIdx = TiedPairs[0].second;
1688 unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
1689 unsigned DstReg = mi->getOperand(DstIdx).getReg();
1690 if (SrcReg != DstReg &&
Cameron Zwarichf05c0cb2013-02-24 00:27:26 +00001691 tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) {
NAKAMURA Takumi84965032015-09-22 11:14:12 +00001692 // The tied operands have been eliminated or shifted further down
1693 // the block to ease elimination. Continue processing with 'nmi'.
Chandler Carruth985454e2012-07-18 18:58:22 +00001694 TiedOperands.clear();
1695 mi = nmi;
1696 continue;
1697 }
1698 }
1699 }
1700
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001701 // Now iterate over the information collected above.
Craig Topperda5168b2015-10-08 06:06:42 +00001702 for (auto &TO : TiedOperands) {
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001703 processTiedPairs(&*mi, TO.second, Dist);
David Greeneac9f8192010-01-05 01:24:21 +00001704 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
Jakob Stoklund Olesen6b556f82012-06-25 03:27:12 +00001705 }
Bill Wendling19e3c852008-05-10 00:12:52 +00001706
Jakob Stoklund Olesen6b556f82012-06-25 03:27:12 +00001707 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1708 if (mi->isInsertSubreg()) {
1709 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1710 // To %reg:subidx = COPY %subreg
1711 unsigned SubIdx = mi->getOperand(3).getImm();
1712 mi->RemoveOperand(3);
1713 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1714 mi->getOperand(0).setSubReg(SubIdx);
1715 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1716 mi->RemoveOperand(1);
1717 mi->setDesc(TII->get(TargetOpcode::COPY));
1718 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
Jakob Stoklund Olesen70ee3ec2010-07-06 23:26:25 +00001719 }
1720
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001721 // Clear TiedOperands here instead of at the top of the loop
1722 // since most instructions do not have tied operands.
1723 TiedOperands.clear();
Evan Cheng58324102008-03-27 01:27:25 +00001724 mi = nmi;
Misha Brukman6dd644e2004-07-22 15:26:23 +00001725 }
1726 }
1727
Cameron Zwarich36735812013-02-20 06:46:34 +00001728 if (LIS)
1729 MF->verify(this, "After two-address instruction pass");
1730
Misha Brukman6dd644e2004-07-22 15:26:23 +00001731 return MadeChange;
Alkis Evlogimenos725021c2003-12-18 13:06:04 +00001732}
Evan Cheng4b6abd82010-05-05 18:45:40 +00001733
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001734/// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process.
Evan Cheng4b6abd82010-05-05 18:45:40 +00001735///
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001736/// The instruction is turned into a sequence of sub-register copies:
1737///
1738/// %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1
1739///
1740/// Becomes:
1741///
1742/// %dst:ssub0<def,undef> = COPY %v1
1743/// %dst:ssub1<def> = COPY %v2
1744///
1745void TwoAddressInstructionPass::
1746eliminateRegSequence(MachineBasicBlock::iterator &MBBI) {
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001747 MachineInstr &MI = *MBBI;
1748 unsigned DstReg = MI.getOperand(0).getReg();
1749 if (MI.getOperand(0).getSubReg() ||
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001750 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001751 !(MI.getNumOperands() & 1)) {
1752 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << MI);
Craig Topperc0196b12014-04-14 00:51:57 +00001753 llvm_unreachable(nullptr);
Evan Cheng4b6abd82010-05-05 18:45:40 +00001754 }
1755
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001756 SmallVector<unsigned, 4> OrigRegs;
1757 if (LIS) {
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001758 OrigRegs.push_back(MI.getOperand(0).getReg());
1759 for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2)
1760 OrigRegs.push_back(MI.getOperand(i).getReg());
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001761 }
1762
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001763 bool DefEmitted = false;
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001764 for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2) {
1765 MachineOperand &UseMO = MI.getOperand(i);
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001766 unsigned SrcReg = UseMO.getReg();
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001767 unsigned SubIdx = MI.getOperand(i+1).getImm();
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001768 // Nothing needs to be inserted for <undef> operands.
1769 if (UseMO.isUndef())
1770 continue;
1771
1772 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1773 // might insert a COPY that uses SrcReg after is was killed.
1774 bool isKill = UseMO.isKill();
1775 if (isKill)
1776 for (unsigned j = i + 2; j < e; j += 2)
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001777 if (MI.getOperand(j).getReg() == SrcReg) {
1778 MI.getOperand(j).setIsKill();
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001779 UseMO.setIsKill(false);
1780 isKill = false;
1781 break;
1782 }
1783
1784 // Insert the sub-register copy.
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001785 MachineInstr *CopyMI = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001786 TII->get(TargetOpcode::COPY))
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001787 .addReg(DstReg, RegState::Define, SubIdx)
Diana Picus116bbab2017-01-13 09:58:52 +00001788 .add(UseMO);
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001789
1790 // The first def needs an <undef> flag because there is no live register
1791 // before it.
1792 if (!DefEmitted) {
1793 CopyMI->getOperand(0).setIsUndef(true);
1794 // Return an iterator pointing to the first inserted instr.
1795 MBBI = CopyMI;
1796 }
1797 DefEmitted = true;
1798
1799 // Update LiveVariables' kill info.
1800 if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001801 LV->replaceKillInstruction(SrcReg, MI, *CopyMI);
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001802
1803 DEBUG(dbgs() << "Inserted: " << *CopyMI);
1804 }
1805
David Blaikie9db062e2013-02-20 07:39:20 +00001806 MachineBasicBlock::iterator EndMBBI =
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001807 std::next(MachineBasicBlock::iterator(MI));
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001808
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001809 if (!DefEmitted) {
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001810 DEBUG(dbgs() << "Turned: " << MI << " into an IMPLICIT_DEF");
1811 MI.setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1812 for (int j = MI.getNumOperands() - 1, ee = 0; j > ee; --j)
1813 MI.RemoveOperand(j);
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001814 } else {
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001815 DEBUG(dbgs() << "Eliminated: " << MI);
1816 MI.eraseFromParent();
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001817 }
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001818
1819 // Udpate LiveIntervals.
Cameron Zwarichcaad7e12013-02-20 22:10:00 +00001820 if (LIS)
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001821 LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs);
Evan Cheng4b6abd82010-05-05 18:45:40 +00001822}