blob: efd40b209e9f7e72ae325608546d7f9b2e996569 [file] [log] [blame]
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +00001//===- TwoAddressInstructionPass.cpp - Two-Address instruction pass -------===//
Alkis Evlogimenos725021c2003-12-18 13:06:04 +00002//
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"
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +000031#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/SmallSet.h"
Michael Kupersteine36d7712016-08-11 17:38:33 +000033#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/ADT/Statistic.h"
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +000035#include "llvm/ADT/iterator_range.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +000037#include "llvm/CodeGen/LiveInterval.h"
Jakob Stoklund Olesen24bc5142012-08-03 22:58:34 +000038#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Alkis Evlogimenos725021c2003-12-18 13:06:04 +000039#include "llvm/CodeGen/LiveVariables.h"
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +000040#include "llvm/CodeGen/MachineBasicBlock.h"
41#include "llvm/CodeGen/MachineFunction.h"
Alkis Evlogimenos725021c2003-12-18 13:06:04 +000042#include "llvm/CodeGen/MachineFunctionPass.h"
43#include "llvm/CodeGen/MachineInstr.h"
Bob Wilsona55b8872010-06-15 05:56:31 +000044#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +000045#include "llvm/CodeGen/MachineOperand.h"
Chris Lattnera10fff52007-12-31 04:13:23 +000046#include "llvm/CodeGen/MachineRegisterInfo.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000047#include "llvm/CodeGen/Passes.h"
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +000048#include "llvm/CodeGen/SlotIndexes.h"
49#include "llvm/MC/MCInstrDesc.h"
Evan Cheng30f44ad2011-11-14 19:48:55 +000050#include "llvm/MC/MCInstrItineraries.h"
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +000051#include "llvm/Pass.h"
52#include "llvm/Support/CodeGen.h"
Andrew Trick608a6982013-04-24 15:54:39 +000053#include "llvm/Support/CommandLine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000054#include "llvm/Support/Debug.h"
55#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000056#include "llvm/Support/raw_ostream.h"
Alkis Evlogimenos725021c2003-12-18 13:06:04 +000057#include "llvm/Target/TargetInstrInfo.h"
58#include "llvm/Target/TargetMachine.h"
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +000059#include "llvm/Target/TargetOpcodes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000060#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000061#include "llvm/Target/TargetSubtargetInfo.h"
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +000062#include <cassert>
63#include <iterator>
64#include <utility>
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +000065
Alkis Evlogimenos725021c2003-12-18 13:06:04 +000066using namespace llvm;
67
Matthias Braun1527baa2017-05-25 21:26:32 +000068#define DEBUG_TYPE "twoaddressinstruction"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000069
Chris Lattneraee775a2006-12-19 22:41:21 +000070STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
71STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
Evan Chengabda6652009-01-25 03:53:59 +000072STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
Chris Lattneraee775a2006-12-19 22:41:21 +000073STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
Evan Cheng5c26bde2008-03-13 06:37:55 +000074STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
Evan Cheng30f44ad2011-11-14 19:48:55 +000075STATISTIC(NumReSchedUps, "Number of instructions re-scheduled up");
76STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down");
Evan Cheng5c26bde2008-03-13 06:37:55 +000077
Andrew Trick608a6982013-04-24 15:54:39 +000078// Temporary flag to disable rescheduling.
79static cl::opt<bool>
80EnableRescheduling("twoaddr-reschedule",
Evan Chengf85a76f2013-05-02 02:07:32 +000081 cl::desc("Coalesce copies by rescheduling (default=true)"),
82 cl::init(true), cl::Hidden);
Andrew Trick608a6982013-04-24 15:54:39 +000083
Taewook Oh0e35ea32017-06-29 23:11:24 +000084// Limit the number of dataflow edges to traverse when evaluating the benefit
85// of commuting operands.
86static cl::opt<unsigned> MaxDataFlowEdge(
87 "dataflow-edge-limit", cl::Hidden, cl::init(3),
88 cl::desc("Maximum number of dataflow edges to traverse when evaluating "
89 "the benefit of commuting operands"));
90
Evan Cheng5c26bde2008-03-13 06:37:55 +000091namespace {
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +000092
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +000093class TwoAddressInstructionPass : public MachineFunctionPass {
94 MachineFunction *MF;
95 const TargetInstrInfo *TII;
96 const TargetRegisterInfo *TRI;
97 const InstrItineraryData *InstrItins;
98 MachineRegisterInfo *MRI;
99 LiveVariables *LV;
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000100 LiveIntervals *LIS;
101 AliasAnalysis *AA;
102 CodeGenOpt::Level OptLevel;
Evan Cheng5c26bde2008-03-13 06:37:55 +0000103
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000104 // The current basic block being processed.
105 MachineBasicBlock *MBB;
106
Sanjay Patelb53791e2015-12-01 19:32:35 +0000107 // Keep track the distance of a MI from the start of the current basic block.
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000108 DenseMap<MachineInstr*, unsigned> DistanceMap;
Evan Chengc2f95b52009-03-01 02:03:43 +0000109
Jakob Stoklund Olesend788e322012-10-26 22:06:00 +0000110 // Set of already processed instructions in the current block.
111 SmallPtrSet<MachineInstr*, 8> Processed;
112
Sanjay Patelb53791e2015-12-01 19:32:35 +0000113 // A map from virtual registers to physical registers which are likely targets
114 // to be coalesced to due to copies from physical registers to virtual
115 // registers. e.g. v1024 = move r0.
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000116 DenseMap<unsigned, unsigned> SrcRegMap;
Evan Chengc2f95b52009-03-01 02:03:43 +0000117
Sanjay Patelb53791e2015-12-01 19:32:35 +0000118 // A map from virtual registers to physical registers which are likely targets
119 // to be coalesced to due to copies to physical registers from virtual
120 // registers. e.g. r1 = move v1024.
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000121 DenseMap<unsigned, unsigned> DstRegMap;
Evan Chengc2f95b52009-03-01 02:03:43 +0000122
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000123 bool sink3AddrInstruction(MachineInstr *MI, unsigned Reg,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000124 MachineBasicBlock::iterator OldPos);
Evan Chengc5618eb2008-06-18 07:49:14 +0000125
Eric Christopher28919132015-03-03 22:03:03 +0000126 bool isRevCopyChain(unsigned FromReg, unsigned ToReg, int Maxlen);
127
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000128 bool noUseAfterLastDef(unsigned Reg, unsigned Dist, unsigned &LastDef);
Evan Chengabda6652009-01-25 03:53:59 +0000129
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000130 bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000131 MachineInstr *MI, unsigned Dist);
Evan Chengabda6652009-01-25 03:53:59 +0000132
Craig Topper76007942016-09-11 22:10:42 +0000133 bool commuteInstruction(MachineInstr *MI, unsigned DstIdx,
Andrew Kaylor16c4da02015-09-28 20:33:22 +0000134 unsigned RegBIdx, unsigned RegCIdx, unsigned Dist);
Evan Chengc2f95b52009-03-01 02:03:43 +0000135
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000136 bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
Evan Cheng09f5be82009-03-30 21:34:07 +0000137
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000138 bool convertInstTo3Addr(MachineBasicBlock::iterator &mi,
139 MachineBasicBlock::iterator &nmi,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000140 unsigned RegA, unsigned RegB, unsigned Dist);
Evan Cheng09f5be82009-03-30 21:34:07 +0000141
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000142 bool isDefTooClose(unsigned Reg, unsigned Dist, MachineInstr *MI);
Evan Cheng30f44ad2011-11-14 19:48:55 +0000143
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000144 bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000145 MachineBasicBlock::iterator &nmi,
146 unsigned Reg);
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000147 bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000148 MachineBasicBlock::iterator &nmi,
149 unsigned Reg);
150
151 bool tryInstructionTransform(MachineBasicBlock::iterator &mi,
Evan Cheng30f44ad2011-11-14 19:48:55 +0000152 MachineBasicBlock::iterator &nmi,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000153 unsigned SrcIdx, unsigned DstIdx,
Cameron Zwarichf05c0cb2013-02-24 00:27:26 +0000154 unsigned Dist, bool shouldOnlyCommute);
Evan Cheng30f44ad2011-11-14 19:48:55 +0000155
Andrew Kaylor16c4da02015-09-28 20:33:22 +0000156 bool tryInstructionCommute(MachineInstr *MI,
157 unsigned DstOpIdx,
158 unsigned BaseOpIdx,
159 bool BaseOpKilled,
160 unsigned Dist);
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000161 void scanUses(unsigned DstReg);
Evan Cheng15fed7a2011-03-02 01:08:17 +0000162
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000163 void processCopy(MachineInstr *MI);
Bob Wilson5c7d9ca2009-09-03 20:58:42 +0000164
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +0000165 using TiedPairList = SmallVector<std::pair<unsigned, unsigned>, 4>;
166 using TiedOperandMap = SmallDenseMap<unsigned, TiedPairList>;
167
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000168 bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
169 void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +0000170 void eliminateRegSequence(MachineBasicBlock::iterator&);
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +0000171
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000172public:
173 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +0000174
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000175 TwoAddressInstructionPass() : MachineFunctionPass(ID) {
176 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
177 }
Evan Cheng1e4f5522010-05-17 23:24:12 +0000178
Craig Topper4584cd52014-03-07 09:26:03 +0000179 void getAnalysisUsage(AnalysisUsage &AU) const override {
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000180 AU.setPreservesCFG();
Ahmed Bougachaa09ff592017-05-10 00:56:00 +0000181 AU.addUsedIfAvailable<AAResultsWrapperPass>();
Matthias Braunf84547c2016-04-28 23:42:51 +0000182 AU.addUsedIfAvailable<LiveVariables>();
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000183 AU.addPreserved<LiveVariables>();
184 AU.addPreserved<SlotIndexes>();
185 AU.addPreserved<LiveIntervals>();
186 AU.addPreservedID(MachineLoopInfoID);
187 AU.addPreservedID(MachineDominatorsID);
188 MachineFunctionPass::getAnalysisUsage(AU);
189 }
Devang Patel09f162c2007-05-01 21:15:47 +0000190
Sanjay Patelb53791e2015-12-01 19:32:35 +0000191 /// Pass entry point.
Craig Topper4584cd52014-03-07 09:26:03 +0000192 bool runOnMachineFunction(MachineFunction&) override;
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000193};
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +0000194
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000195} // end anonymous namespace
Alkis Evlogimenos725021c2003-12-18 13:06:04 +0000196
Dan Gohmand78c4002008-05-13 00:00:25 +0000197char TwoAddressInstructionPass::ID = 0;
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +0000198
199char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
200
Matthias Braun1527baa2017-05-25 21:26:32 +0000201INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, DEBUG_TYPE,
Owen Anderson8ac477f2010-10-12 19:48:12 +0000202 "Two-Address instruction pass", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000203INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000204INITIALIZE_PASS_END(TwoAddressInstructionPass, DEBUG_TYPE,
Owen Andersondf7a4f22010-10-07 22:25:06 +0000205 "Two-Address instruction pass", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000206
Cameron Zwarich35c30502013-02-23 04:49:20 +0000207static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg, LiveIntervals *LIS);
208
Sanjay Patelb53791e2015-12-01 19:32:35 +0000209/// A two-address instruction has been converted to a three-address instruction
210/// to avoid clobbering a register. Try to sink it past the instruction that
211/// would kill the above mentioned register to reduce register pressure.
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000212bool TwoAddressInstructionPass::
213sink3AddrInstruction(MachineInstr *MI, unsigned SavedReg,
214 MachineBasicBlock::iterator OldPos) {
Eli Friedman8a15a5a2011-09-23 22:41:57 +0000215 // FIXME: Shouldn't we be trying to do this before we three-addressify the
216 // instruction? After this transformation is done, we no longer need
217 // the instruction to be in three-address form.
218
Evan Cheng5c26bde2008-03-13 06:37:55 +0000219 // Check if it's safe to move this instruction.
220 bool SeenStore = true; // Be conservative.
Matthias Braun07066cc2015-05-19 21:22:20 +0000221 if (!MI->isSafeToMove(AA, SeenStore))
Evan Cheng5c26bde2008-03-13 06:37:55 +0000222 return false;
223
224 unsigned DefReg = 0;
225 SmallSet<unsigned, 4> UseRegs;
Bill Wendling19e3c852008-05-10 00:12:52 +0000226
Craig Topperda5168b2015-10-08 06:06:42 +0000227 for (const MachineOperand &MO : MI->operands()) {
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000228 if (!MO.isReg())
Evan Cheng5c26bde2008-03-13 06:37:55 +0000229 continue;
230 unsigned MOReg = MO.getReg();
231 if (!MOReg)
232 continue;
233 if (MO.isUse() && MOReg != SavedReg)
234 UseRegs.insert(MO.getReg());
235 if (!MO.isDef())
236 continue;
237 if (MO.isImplicit())
238 // Don't try to move it if it implicitly defines a register.
239 return false;
240 if (DefReg)
241 // For now, don't move any instructions that define multiple registers.
242 return false;
243 DefReg = MO.getReg();
244 }
245
246 // Find the instruction that kills SavedReg.
Craig Topperc0196b12014-04-14 00:51:57 +0000247 MachineInstr *KillMI = nullptr;
Cameron Zwarich35c30502013-02-23 04:49:20 +0000248 if (LIS) {
249 LiveInterval &LI = LIS->getInterval(SavedReg);
250 assert(LI.end() != LI.begin() &&
251 "Reg should not have empty live interval.");
252
253 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
254 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
255 if (I != LI.end() && I->start < MBBEndIdx)
256 return false;
257
258 --I;
259 KillMI = LIS->getInstructionFromIndex(I->end);
260 }
261 if (!KillMI) {
Craig Topperda5168b2015-10-08 06:06:42 +0000262 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SavedReg)) {
Cameron Zwarich35c30502013-02-23 04:49:20 +0000263 if (!UseMO.isKill())
264 continue;
265 KillMI = UseMO.getParent();
266 break;
267 }
Evan Cheng5c26bde2008-03-13 06:37:55 +0000268 }
Bill Wendling19e3c852008-05-10 00:12:52 +0000269
Eli Friedman8a15a5a2011-09-23 22:41:57 +0000270 // If we find the instruction that kills SavedReg, and it is in an
271 // appropriate location, we can try to sink the current instruction
272 // past it.
273 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +0000274 MachineBasicBlock::iterator(KillMI) == OldPos || KillMI->isTerminator())
Evan Cheng5c26bde2008-03-13 06:37:55 +0000275 return false;
276
Bill Wendling19e3c852008-05-10 00:12:52 +0000277 // If any of the definitions are used by another instruction between the
278 // position and the kill use, then it's not safe to sink it.
Andrew Trick808a7a62012-02-03 05:12:30 +0000279 //
Bill Wendling19e3c852008-05-10 00:12:52 +0000280 // FIXME: This can be sped up if there is an easy way to query whether an
Evan Chengc5618eb2008-06-18 07:49:14 +0000281 // instruction is before or after another instruction. Then we can use
Bill Wendling19e3c852008-05-10 00:12:52 +0000282 // MachineRegisterInfo def / use instead.
Craig Topperc0196b12014-04-14 00:51:57 +0000283 MachineOperand *KillMO = nullptr;
Evan Cheng5c26bde2008-03-13 06:37:55 +0000284 MachineBasicBlock::iterator KillPos = KillMI;
285 ++KillPos;
Bill Wendling19e3c852008-05-10 00:12:52 +0000286
Evan Chengc5618eb2008-06-18 07:49:14 +0000287 unsigned NumVisited = 0;
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +0000288 for (MachineInstr &OtherMI : make_range(std::next(OldPos), KillPos)) {
Dale Johannesen12565de2010-02-11 18:22:31 +0000289 // DBG_VALUE cannot be counted against the limit.
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +0000290 if (OtherMI.isDebugValue())
Dale Johannesen12565de2010-02-11 18:22:31 +0000291 continue;
Evan Chengc5618eb2008-06-18 07:49:14 +0000292 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
293 return false;
294 ++NumVisited;
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +0000295 for (unsigned i = 0, e = OtherMI.getNumOperands(); i != e; ++i) {
296 MachineOperand &MO = OtherMI.getOperand(i);
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000297 if (!MO.isReg())
Evan Cheng5c26bde2008-03-13 06:37:55 +0000298 continue;
299 unsigned MOReg = MO.getReg();
300 if (!MOReg)
301 continue;
302 if (DefReg == MOReg)
303 return false;
Bill Wendling19e3c852008-05-10 00:12:52 +0000304
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +0000305 if (MO.isKill() || (LIS && isPlainlyKilled(&OtherMI, MOReg, LIS))) {
306 if (&OtherMI == KillMI && MOReg == SavedReg)
Evan Chengc5618eb2008-06-18 07:49:14 +0000307 // Save the operand that kills the register. We want to unset the kill
308 // marker if we can sink MI past it.
Evan Cheng5c26bde2008-03-13 06:37:55 +0000309 KillMO = &MO;
310 else if (UseRegs.count(MOReg))
311 // One of the uses is killed before the destination.
312 return false;
313 }
314 }
315 }
Jakob Stoklund Olesen420798c2012-08-09 22:08:26 +0000316 assert(KillMO && "Didn't find kill");
Evan Cheng5c26bde2008-03-13 06:37:55 +0000317
Cameron Zwarich35c30502013-02-23 04:49:20 +0000318 if (!LIS) {
319 // Update kill and LV information.
320 KillMO->setIsKill(false);
321 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
322 KillMO->setIsKill(true);
Andrew Trick808a7a62012-02-03 05:12:30 +0000323
Cameron Zwarich35c30502013-02-23 04:49:20 +0000324 if (LV)
Duncan P. N. Exon Smithd26fdc82016-07-01 01:51:32 +0000325 LV->replaceKillInstruction(SavedReg, *KillMI, *MI);
Cameron Zwarich35c30502013-02-23 04:49:20 +0000326 }
Evan Cheng5c26bde2008-03-13 06:37:55 +0000327
328 // Move instruction to its destination.
329 MBB->remove(MI);
330 MBB->insert(KillPos, MI);
331
Jakob Stoklund Olesen24bc5142012-08-03 22:58:34 +0000332 if (LIS)
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +0000333 LIS->handleMove(*MI);
Jakob Stoklund Olesen24bc5142012-08-03 22:58:34 +0000334
Evan Cheng5c26bde2008-03-13 06:37:55 +0000335 ++Num3AddrSunk;
336 return true;
337}
338
Sanjay Patelb53791e2015-12-01 19:32:35 +0000339/// Return the MachineInstr* if it is the single def of the Reg in current BB.
Eric Christopher28919132015-03-03 22:03:03 +0000340static MachineInstr *getSingleDef(unsigned Reg, MachineBasicBlock *BB,
341 const MachineRegisterInfo *MRI) {
342 MachineInstr *Ret = nullptr;
343 for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
344 if (DefMI.getParent() != BB || DefMI.isDebugValue())
345 continue;
346 if (!Ret)
347 Ret = &DefMI;
348 else if (Ret != &DefMI)
349 return nullptr;
350 }
351 return Ret;
352}
353
354/// Check if there is a reversed copy chain from FromReg to ToReg:
355/// %Tmp1 = copy %Tmp2;
356/// %FromReg = copy %Tmp1;
357/// %ToReg = add %FromReg ...
358/// %Tmp2 = copy %ToReg;
359/// MaxLen specifies the maximum length of the copy chain the func
360/// can walk through.
361bool TwoAddressInstructionPass::isRevCopyChain(unsigned FromReg, unsigned ToReg,
362 int Maxlen) {
363 unsigned TmpReg = FromReg;
364 for (int i = 0; i < Maxlen; i++) {
365 MachineInstr *Def = getSingleDef(TmpReg, MBB, MRI);
366 if (!Def || !Def->isCopy())
367 return false;
368
369 TmpReg = Def->getOperand(1).getReg();
370
371 if (TmpReg == ToReg)
372 return true;
373 }
374 return false;
375}
376
Sanjay Patelb53791e2015-12-01 19:32:35 +0000377/// Return true if there are no intervening uses between the last instruction
378/// in the MBB that defines the specified register and the two-address
379/// instruction which is being processed. It also returns the last def location
380/// by reference.
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000381bool TwoAddressInstructionPass::noUseAfterLastDef(unsigned Reg, unsigned Dist,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000382 unsigned &LastDef) {
Evan Chengabda6652009-01-25 03:53:59 +0000383 LastDef = 0;
384 unsigned LastUse = Dist;
Owen Andersonb36376e2014-03-17 19:36:09 +0000385 for (MachineOperand &MO : MRI->reg_operands(Reg)) {
Evan Chengabda6652009-01-25 03:53:59 +0000386 MachineInstr *MI = MO.getParent();
Chris Lattnerb06015a2010-02-09 19:54:29 +0000387 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesenc3adf442010-02-09 02:01:46 +0000388 continue;
Evan Chengabda6652009-01-25 03:53:59 +0000389 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
390 if (DI == DistanceMap.end())
391 continue;
392 if (MO.isUse() && DI->second < LastUse)
393 LastUse = DI->second;
394 if (MO.isDef() && DI->second > LastDef)
395 LastDef = DI->second;
396 }
397
398 return !(LastUse > LastDef && LastUse < Dist);
399}
400
Sanjay Patelb53791e2015-12-01 19:32:35 +0000401/// Return true if the specified MI is a copy instruction or an extract_subreg
402/// instruction. It also returns the source and destination registers and
403/// whether they are physical registers by reference.
Evan Chengc2f95b52009-03-01 02:03:43 +0000404static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
405 unsigned &SrcReg, unsigned &DstReg,
406 bool &IsSrcPhys, bool &IsDstPhys) {
407 SrcReg = 0;
408 DstReg = 0;
Jakob Stoklund Olesen37c42a32010-07-16 04:45:42 +0000409 if (MI.isCopy()) {
410 DstReg = MI.getOperand(0).getReg();
411 SrcReg = MI.getOperand(1).getReg();
412 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
413 DstReg = MI.getOperand(0).getReg();
414 SrcReg = MI.getOperand(2).getReg();
415 } else
416 return false;
Evan Chengc2f95b52009-03-01 02:03:43 +0000417
Jakob Stoklund Olesen37c42a32010-07-16 04:45:42 +0000418 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
419 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
420 return true;
Evan Chengc2f95b52009-03-01 02:03:43 +0000421}
422
Sanjay Patelb53791e2015-12-01 19:32:35 +0000423/// Test if the given register value, which is used by the
424/// given instruction, is killed by the given instruction.
Cameron Zwarichc8964782013-02-21 07:02:28 +0000425static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg,
426 LiveIntervals *LIS) {
427 if (LIS && TargetRegisterInfo::isVirtualRegister(Reg) &&
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000428 !LIS->isNotInMIMap(*MI)) {
Cameron Zwarichc8964782013-02-21 07:02:28 +0000429 // FIXME: Sometimes tryInstructionTransform() will add instructions and
430 // test whether they can be folded before keeping them. In this case it
431 // sets a kill before recursively calling tryInstructionTransform() again.
432 // If there is no interval available, we assume that this instruction is
433 // one of those. A kill flag is manually inserted on the operand so the
434 // check below will handle it.
435 LiveInterval &LI = LIS->getInterval(Reg);
436 // This is to match the kill flag version where undefs don't have kill
437 // flags.
438 if (!LI.hasAtLeastOneValue())
439 return false;
440
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000441 SlotIndex useIdx = LIS->getInstructionIndex(*MI);
Cameron Zwarichc8964782013-02-21 07:02:28 +0000442 LiveInterval::const_iterator I = LI.find(useIdx);
443 assert(I != LI.end() && "Reg must be live-in to use.");
Cameron Zwarich4e80d9e2013-02-23 04:49:22 +0000444 return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx);
Cameron Zwarichc8964782013-02-21 07:02:28 +0000445 }
446
447 return MI->killsRegister(Reg);
448}
449
Sanjay Patelb53791e2015-12-01 19:32:35 +0000450/// Test if the given register value, which is used by the given
Dan Gohmanad3e5492009-04-08 00:15:30 +0000451/// instruction, is killed by the given instruction. This looks through
452/// coalescable copies to see if the original value is potentially not killed.
453///
454/// For example, in this code:
455///
456/// %reg1034 = copy %reg1024
457/// %reg1035 = copy %reg1025<kill>
458/// %reg1036 = add %reg1034<kill>, %reg1035<kill>
459///
460/// %reg1034 is not considered to be killed, since it is copied from a
461/// register which is not killed. Treating it as not killed lets the
462/// normal heuristics commute the (two-address) add, which lets
463/// coalescing eliminate the extra copy.
464///
Cameron Zwarich384026b2013-02-21 22:58:42 +0000465/// If allowFalsePositives is true then likely kills are treated as kills even
466/// if it can't be proven that they are kills.
Dan Gohmanad3e5492009-04-08 00:15:30 +0000467static bool isKilled(MachineInstr &MI, unsigned Reg,
468 const MachineRegisterInfo *MRI,
Cameron Zwarich94b204b2013-02-21 04:33:02 +0000469 const TargetInstrInfo *TII,
Cameron Zwarich384026b2013-02-21 22:58:42 +0000470 LiveIntervals *LIS,
471 bool allowFalsePositives) {
Dan Gohmanad3e5492009-04-08 00:15:30 +0000472 MachineInstr *DefMI = &MI;
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +0000473 while (true) {
Cameron Zwarich384026b2013-02-21 22:58:42 +0000474 // All uses of physical registers are likely to be kills.
475 if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
476 (allowFalsePositives || MRI->hasOneUse(Reg)))
477 return true;
Cameron Zwarichc8964782013-02-21 07:02:28 +0000478 if (!isPlainlyKilled(DefMI, Reg, LIS))
Dan Gohmanad3e5492009-04-08 00:15:30 +0000479 return false;
480 if (TargetRegisterInfo::isPhysicalRegister(Reg))
481 return true;
482 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
483 // If there are multiple defs, we can't do a simple analysis, so just
484 // go with what the kill flag says.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000485 if (std::next(Begin) != MRI->def_end())
Dan Gohmanad3e5492009-04-08 00:15:30 +0000486 return true;
Owen Anderson16c6bf42014-03-13 23:12:04 +0000487 DefMI = Begin->getParent();
Dan Gohmanad3e5492009-04-08 00:15:30 +0000488 bool IsSrcPhys, IsDstPhys;
489 unsigned SrcReg, DstReg;
490 // If the def is something other than a copy, then it isn't going to
491 // be coalesced, so follow the kill flag.
492 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
493 return true;
494 Reg = SrcReg;
495 }
496}
497
Sanjay Patelb53791e2015-12-01 19:32:35 +0000498/// Return true if the specified MI uses the specified register as a two-address
499/// use. If so, return the destination register by reference.
Evan Chengc2f95b52009-03-01 02:03:43 +0000500static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
Evan Chengf85a76f2013-05-02 02:07:32 +0000501 for (unsigned i = 0, NumOps = MI.getNumOperands(); i != NumOps; ++i) {
Evan Chengc2f95b52009-03-01 02:03:43 +0000502 const MachineOperand &MO = MI.getOperand(i);
503 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
504 continue;
Evan Cheng1361cbb2009-03-19 20:30:06 +0000505 unsigned ti;
506 if (MI.isRegTiedToDefOperand(i, &ti)) {
Evan Chengc2f95b52009-03-01 02:03:43 +0000507 DstReg = MI.getOperand(ti).getReg();
508 return true;
509 }
510 }
511 return false;
512}
513
Sanjay Patelb53791e2015-12-01 19:32:35 +0000514/// Given a register, if has a single in-basic block use, return the use
515/// instruction if it's a copy or a two-address use.
Evan Chengc2f95b52009-03-01 02:03:43 +0000516static
517MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
518 MachineRegisterInfo *MRI,
519 const TargetInstrInfo *TII,
Evan Cheng97871832009-04-14 00:32:25 +0000520 bool &IsCopy,
Evan Chengc2f95b52009-03-01 02:03:43 +0000521 unsigned &DstReg, bool &IsDstPhys) {
Evan Chengf94d6832010-03-03 21:18:38 +0000522 if (!MRI->hasOneNonDBGUse(Reg))
523 // None or more than one use.
Craig Topperc0196b12014-04-14 00:51:57 +0000524 return nullptr;
Owen Anderson16c6bf42014-03-13 23:12:04 +0000525 MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(Reg);
Evan Chengc2f95b52009-03-01 02:03:43 +0000526 if (UseMI.getParent() != MBB)
Craig Topperc0196b12014-04-14 00:51:57 +0000527 return nullptr;
Evan Chengc2f95b52009-03-01 02:03:43 +0000528 unsigned SrcReg;
529 bool IsSrcPhys;
Evan Cheng97871832009-04-14 00:32:25 +0000530 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
531 IsCopy = true;
Evan Chengc2f95b52009-03-01 02:03:43 +0000532 return &UseMI;
Evan Cheng97871832009-04-14 00:32:25 +0000533 }
Evan Chengc2f95b52009-03-01 02:03:43 +0000534 IsDstPhys = false;
Evan Cheng97871832009-04-14 00:32:25 +0000535 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
536 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Chengc2f95b52009-03-01 02:03:43 +0000537 return &UseMI;
Evan Cheng97871832009-04-14 00:32:25 +0000538 }
Craig Topperc0196b12014-04-14 00:51:57 +0000539 return nullptr;
Evan Chengc2f95b52009-03-01 02:03:43 +0000540}
541
Sanjay Patelb53791e2015-12-01 19:32:35 +0000542/// Return the physical register the specified virtual register might be mapped
543/// to.
Evan Chengc2f95b52009-03-01 02:03:43 +0000544static unsigned
545getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
546 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
547 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
548 if (SI == RegMap.end())
549 return 0;
550 Reg = SI->second;
551 }
552 if (TargetRegisterInfo::isPhysicalRegister(Reg))
553 return Reg;
554 return 0;
555}
556
Sanjay Patelb53791e2015-12-01 19:32:35 +0000557/// Return true if the two registers are equal or aliased.
Evan Chengc2f95b52009-03-01 02:03:43 +0000558static bool
559regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
560 if (RegA == RegB)
561 return true;
562 if (!RegA || !RegB)
563 return false;
564 return TRI->regsOverlap(RegA, RegB);
565}
566
Michael Kupersteine36d7712016-08-11 17:38:33 +0000567// Returns true if Reg is equal or aliased to at least one register in Set.
568static bool regOverlapsSet(const SmallVectorImpl<unsigned> &Set, unsigned Reg,
569 const TargetRegisterInfo *TRI) {
570 for (unsigned R : Set)
571 if (TRI->regsOverlap(R, Reg))
572 return true;
573
574 return false;
575}
576
Sanjay Patelb53791e2015-12-01 19:32:35 +0000577/// Return true if it's potentially profitable to commute the two-address
578/// instruction that's being processed.
Evan Chengabda6652009-01-25 03:53:59 +0000579bool
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000580TwoAddressInstructionPass::
581isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
582 MachineInstr *MI, unsigned Dist) {
Evan Cheng822ddde2011-11-16 18:44:48 +0000583 if (OptLevel == CodeGenOpt::None)
584 return false;
585
Evan Chengabda6652009-01-25 03:53:59 +0000586 // Determine if it's profitable to commute this two address instruction. In
587 // general, we want no uses between this instruction and the definition of
588 // the two-address register.
589 // e.g.
590 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
591 // %reg1029<def> = MOV8rr %reg1028
592 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
593 // insert => %reg1030<def> = MOV8rr %reg1028
594 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
595 // In this case, it might not be possible to coalesce the second MOV8rr
596 // instruction if the first one is coalesced. So it would be profitable to
597 // commute it:
598 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
599 // %reg1029<def> = MOV8rr %reg1028
600 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
601 // insert => %reg1030<def> = MOV8rr %reg1029
Andrew Trick808a7a62012-02-03 05:12:30 +0000602 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
Evan Chengabda6652009-01-25 03:53:59 +0000603
Cameron Zwarich9e722ae2013-02-21 07:02:30 +0000604 if (!isPlainlyKilled(MI, regC, LIS))
Evan Chengabda6652009-01-25 03:53:59 +0000605 return false;
606
607 // Ok, we have something like:
608 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
609 // let's see if it's worth commuting it.
610
Evan Chengc2f95b52009-03-01 02:03:43 +0000611 // Look for situations like this:
612 // %reg1024<def> = MOV r1
613 // %reg1025<def> = MOV r0
614 // %reg1026<def> = ADD %reg1024, %reg1025
615 // r0 = MOV %reg1026
616 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
Evan Chengb64e7b72012-05-03 01:45:13 +0000617 unsigned ToRegA = getMappedReg(regA, DstRegMap);
618 if (ToRegA) {
619 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
620 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
Craig Topper12f0d9e2014-11-05 06:43:02 +0000621 bool CompB = FromRegB && regsAreCompatible(FromRegB, ToRegA, TRI);
622 bool CompC = FromRegC && regsAreCompatible(FromRegC, ToRegA, TRI);
623
624 // Compute if any of the following are true:
625 // -RegB is not tied to a register and RegC is compatible with RegA.
626 // -RegB is tied to the wrong physical register, but RegC is.
627 // -RegB is tied to the wrong physical register, and RegC isn't tied.
628 if ((!FromRegB && CompC) || (FromRegB && !CompB && (!FromRegC || CompC)))
629 return true;
630 // Don't compute if any of the following are true:
631 // -RegC is not tied to a register and RegB is compatible with RegA.
632 // -RegC is tied to the wrong physical register, but RegB is.
633 // -RegC is tied to the wrong physical register, and RegB isn't tied.
634 if ((!FromRegC && CompB) || (FromRegC && !CompC && (!FromRegB || CompB)))
635 return false;
Evan Chengb64e7b72012-05-03 01:45:13 +0000636 }
Evan Chengc2f95b52009-03-01 02:03:43 +0000637
Evan Chengabda6652009-01-25 03:53:59 +0000638 // If there is a use of regC between its last def (could be livein) and this
639 // instruction, then bail.
640 unsigned LastDefC = 0;
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000641 if (!noUseAfterLastDef(regC, Dist, LastDefC))
Evan Chengabda6652009-01-25 03:53:59 +0000642 return false;
643
644 // If there is a use of regB between its last def (could be livein) and this
645 // instruction, then go ahead and make this transformation.
646 unsigned LastDefB = 0;
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000647 if (!noUseAfterLastDef(regB, Dist, LastDefB))
Evan Chengabda6652009-01-25 03:53:59 +0000648 return true;
649
Eric Christopher28919132015-03-03 22:03:03 +0000650 // Look for situation like this:
651 // %reg101 = MOV %reg100
652 // %reg102 = ...
653 // %reg103 = ADD %reg102, %reg101
654 // ... = %reg103 ...
655 // %reg100 = MOV %reg103
656 // If there is a reversed copy chain from reg101 to reg103, commute the ADD
657 // to eliminate an otherwise unavoidable copy.
658 // FIXME:
659 // We can extend the logic further: If an pair of operands in an insn has
660 // been merged, the insn could be regarded as a virtual copy, and the virtual
661 // copy could also be used to construct a copy chain.
662 // To more generally minimize register copies, ideally the logic of two addr
663 // instruction pass should be integrated with register allocation pass where
664 // interference graph is available.
Taewook Oh0e35ea32017-06-29 23:11:24 +0000665 if (isRevCopyChain(regC, regA, MaxDataFlowEdge))
Eric Christopher28919132015-03-03 22:03:03 +0000666 return true;
667
Taewook Oh0e35ea32017-06-29 23:11:24 +0000668 if (isRevCopyChain(regB, regA, MaxDataFlowEdge))
Eric Christopher28919132015-03-03 22:03:03 +0000669 return false;
670
Evan Chengabda6652009-01-25 03:53:59 +0000671 // Since there are no intervening uses for both registers, then commute
672 // if the def of regC is closer. Its live interval is shorter.
673 return LastDefB && LastDefC && LastDefC > LastDefB;
674}
675
Sanjay Patelb53791e2015-12-01 19:32:35 +0000676/// Commute a two-address instruction and update the basic block, distance map,
677/// and live variables if needed. Return true if it is successful.
Andrew Kaylor16c4da02015-09-28 20:33:22 +0000678bool TwoAddressInstructionPass::commuteInstruction(MachineInstr *MI,
Craig Topper76007942016-09-11 22:10:42 +0000679 unsigned DstIdx,
Andrew Kaylor16c4da02015-09-28 20:33:22 +0000680 unsigned RegBIdx,
681 unsigned RegCIdx,
682 unsigned Dist) {
683 unsigned RegC = MI->getOperand(RegCIdx).getReg();
David Greeneac9f8192010-01-05 01:24:21 +0000684 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000685 MachineInstr *NewMI = TII->commuteInstruction(*MI, false, RegBIdx, RegCIdx);
Evan Cheng6d897062009-01-23 23:27:33 +0000686
Craig Topperc0196b12014-04-14 00:51:57 +0000687 if (NewMI == nullptr) {
David Greeneac9f8192010-01-05 01:24:21 +0000688 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
Evan Cheng6d897062009-01-23 23:27:33 +0000689 return false;
690 }
691
David Greeneac9f8192010-01-05 01:24:21 +0000692 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
Cameron Zwariche6907bc2013-02-23 23:13:28 +0000693 assert(NewMI == MI &&
694 "TargetInstrInfo::commuteInstruction() should not return a new "
695 "instruction unless it was requested.");
Evan Chengc2f95b52009-03-01 02:03:43 +0000696
697 // Update source register map.
698 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
699 if (FromRegC) {
Craig Topper76007942016-09-11 22:10:42 +0000700 unsigned RegA = MI->getOperand(DstIdx).getReg();
Evan Chengc2f95b52009-03-01 02:03:43 +0000701 SrcRegMap[RegA] = FromRegC;
702 }
703
Evan Cheng6d897062009-01-23 23:27:33 +0000704 return true;
705}
706
Sanjay Patelb53791e2015-12-01 19:32:35 +0000707/// Return true if it is profitable to convert the given 2-address instruction
708/// to a 3-address one.
Evan Cheng09f5be82009-03-30 21:34:07 +0000709bool
Evan Cheng15fed7a2011-03-02 01:08:17 +0000710TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
Evan Cheng09f5be82009-03-30 21:34:07 +0000711 // Look for situations like this:
712 // %reg1024<def> = MOV r1
713 // %reg1025<def> = MOV r0
714 // %reg1026<def> = ADD %reg1024, %reg1025
715 // r2 = MOV %reg1026
716 // Turn ADD into a 3-address instruction to avoid a copy.
Evan Cheng15fed7a2011-03-02 01:08:17 +0000717 unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
718 if (!FromRegB)
719 return false;
Evan Cheng09f5be82009-03-30 21:34:07 +0000720 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
Evan Cheng15fed7a2011-03-02 01:08:17 +0000721 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
Evan Cheng09f5be82009-03-30 21:34:07 +0000722}
723
Sanjay Patelb53791e2015-12-01 19:32:35 +0000724/// Convert the specified two-address instruction into a three address one.
725/// Return true if this transformation was successful.
Evan Cheng09f5be82009-03-30 21:34:07 +0000726bool
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000727TwoAddressInstructionPass::convertInstTo3Addr(MachineBasicBlock::iterator &mi,
Evan Cheng09f5be82009-03-30 21:34:07 +0000728 MachineBasicBlock::iterator &nmi,
Evan Chengd4fcc052011-02-10 02:20:55 +0000729 unsigned RegA, unsigned RegB,
730 unsigned Dist) {
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000731 // FIXME: Why does convertToThreeAddress() need an iterator reference?
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000732 MachineFunction::iterator MFI = MBB->getIterator();
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000733 MachineInstr *NewMI = TII->convertToThreeAddress(MFI, *mi, LV);
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000734 assert(MBB->getIterator() == MFI &&
735 "convertToThreeAddress changed iterator reference");
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000736 if (!NewMI)
737 return false;
Evan Cheng09f5be82009-03-30 21:34:07 +0000738
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000739 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
740 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
741 bool Sunk = false;
Jakob Stoklund Olesen24bc5142012-08-03 22:58:34 +0000742
Cameron Zwarich2ad3ca32013-02-20 22:10:02 +0000743 if (LIS)
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +0000744 LIS->ReplaceMachineInstrInMaps(*mi, *NewMI);
Evan Cheng09f5be82009-03-30 21:34:07 +0000745
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000746 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
747 // FIXME: Temporary workaround. If the new instruction doesn't
748 // uses RegB, convertToThreeAddress must have created more
749 // then one instruction.
750 Sunk = sink3AddrInstruction(NewMI, RegB, mi);
Evan Cheng09f5be82009-03-30 21:34:07 +0000751
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000752 MBB->erase(mi); // Nuke the old inst.
Evan Chengd4fcc052011-02-10 02:20:55 +0000753
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000754 if (!Sunk) {
755 DistanceMap.insert(std::make_pair(NewMI, Dist));
756 mi = NewMI;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000757 nmi = std::next(mi);
Evan Cheng09f5be82009-03-30 21:34:07 +0000758 }
759
Jakob Stoklund Olesen1dfe4fc2012-10-26 23:05:13 +0000760 // Update source and destination register maps.
761 SrcRegMap.erase(RegA);
762 DstRegMap.erase(RegB);
763 return true;
Evan Cheng09f5be82009-03-30 21:34:07 +0000764}
765
Sanjay Patelb53791e2015-12-01 19:32:35 +0000766/// Scan forward recursively for only uses, update maps if the use is a copy or
767/// a two-address instruction.
Evan Cheng15fed7a2011-03-02 01:08:17 +0000768void
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000769TwoAddressInstructionPass::scanUses(unsigned DstReg) {
Evan Cheng15fed7a2011-03-02 01:08:17 +0000770 SmallVector<unsigned, 4> VirtRegPairs;
771 bool IsDstPhys;
772 bool IsCopy = false;
773 unsigned NewReg = 0;
774 unsigned Reg = DstReg;
775 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
776 NewReg, IsDstPhys)) {
David Blaikie70573dc2014-11-19 07:49:26 +0000777 if (IsCopy && !Processed.insert(UseMI).second)
Evan Cheng15fed7a2011-03-02 01:08:17 +0000778 break;
779
780 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
781 if (DI != DistanceMap.end())
782 // Earlier in the same MBB.Reached via a back edge.
783 break;
784
785 if (IsDstPhys) {
786 VirtRegPairs.push_back(NewReg);
787 break;
788 }
789 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
790 if (!isNew)
791 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
792 VirtRegPairs.push_back(NewReg);
793 Reg = NewReg;
794 }
795
796 if (!VirtRegPairs.empty()) {
797 unsigned ToReg = VirtRegPairs.back();
798 VirtRegPairs.pop_back();
799 while (!VirtRegPairs.empty()) {
800 unsigned FromReg = VirtRegPairs.back();
801 VirtRegPairs.pop_back();
802 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
803 if (!isNew)
804 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
805 ToReg = FromReg;
806 }
807 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
808 if (!isNew)
809 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
810 }
811}
812
Sanjay Patelb53791e2015-12-01 19:32:35 +0000813/// If the specified instruction is not yet processed, process it if it's a
814/// copy. For a copy instruction, we find the physical registers the
Evan Chengc2f95b52009-03-01 02:03:43 +0000815/// source and destination registers might be mapped to. These are kept in
816/// point-to maps used to determine future optimizations. e.g.
817/// v1024 = mov r0
818/// v1025 = mov r1
819/// v1026 = add v1024, v1025
820/// r1 = mov r1026
821/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
822/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
823/// potentially joined with r1 on the output side. It's worthwhile to commute
824/// 'add' to eliminate a copy.
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000825void TwoAddressInstructionPass::processCopy(MachineInstr *MI) {
Evan Chengc2f95b52009-03-01 02:03:43 +0000826 if (Processed.count(MI))
827 return;
828
829 bool IsSrcPhys, IsDstPhys;
830 unsigned SrcReg, DstReg;
831 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
832 return;
833
834 if (IsDstPhys && !IsSrcPhys)
835 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
836 else if (!IsDstPhys && IsSrcPhys) {
Evan Chengf0843802009-04-13 20:04:24 +0000837 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
838 if (!isNew)
839 assert(SrcRegMap[DstReg] == SrcReg &&
840 "Can't map to two src physical registers!");
Evan Chengc2f95b52009-03-01 02:03:43 +0000841
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000842 scanUses(DstReg);
Evan Chengc2f95b52009-03-01 02:03:43 +0000843 }
844
845 Processed.insert(MI);
846}
847
Sanjay Patelb53791e2015-12-01 19:32:35 +0000848/// If there is one more local instruction that reads 'Reg' and it kills 'Reg,
849/// consider moving the instruction below the kill instruction in order to
850/// eliminate the need for the copy.
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000851bool TwoAddressInstructionPass::
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +0000852rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +0000853 MachineBasicBlock::iterator &nmi,
854 unsigned Reg) {
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000855 // Bail immediately if we don't have LV or LIS available. We use them to find
856 // kills efficiently.
857 if (!LV && !LIS)
Chandler Carruthdb5536f2012-07-15 03:29:46 +0000858 return false;
859
Evan Cheng30f44ad2011-11-14 19:48:55 +0000860 MachineInstr *MI = &*mi;
Andrew Trick808a7a62012-02-03 05:12:30 +0000861 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
Evan Cheng30f44ad2011-11-14 19:48:55 +0000862 if (DI == DistanceMap.end())
863 // Must be created from unfolded load. Don't waste time trying this.
864 return false;
865
Craig Topperc0196b12014-04-14 00:51:57 +0000866 MachineInstr *KillMI = nullptr;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000867 if (LIS) {
868 LiveInterval &LI = LIS->getInterval(Reg);
869 assert(LI.end() != LI.begin() &&
870 "Reg should not have empty live interval.");
871
872 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
873 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
874 if (I != LI.end() && I->start < MBBEndIdx)
875 return false;
876
877 --I;
878 KillMI = LIS->getInstructionFromIndex(I->end);
879 } else {
880 KillMI = LV->getVarInfo(Reg).findKill(MBB);
881 }
Chandler Carruthdb5536f2012-07-15 03:29:46 +0000882 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng30f44ad2011-11-14 19:48:55 +0000883 // Don't mess with copies, they may be coalesced later.
884 return false;
885
Evan Cheng7f8e5632011-12-07 07:15:52 +0000886 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
887 KillMI->isBranch() || KillMI->isTerminator())
Evan Cheng30f44ad2011-11-14 19:48:55 +0000888 // Don't move pass calls, etc.
889 return false;
890
891 unsigned DstReg;
892 if (isTwoAddrUse(*KillMI, Reg, DstReg))
893 return false;
894
Evan Cheng7098c4e2011-11-15 06:26:51 +0000895 bool SeenStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +0000896 if (!MI->isSafeToMove(AA, SeenStore))
Evan Cheng30f44ad2011-11-14 19:48:55 +0000897 return false;
898
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000899 if (TII->getInstrLatency(InstrItins, *MI) > 1)
Evan Cheng30f44ad2011-11-14 19:48:55 +0000900 // FIXME: Needs more sophisticated heuristics.
901 return false;
902
Michael Kupersteine36d7712016-08-11 17:38:33 +0000903 SmallVector<unsigned, 2> Uses;
904 SmallVector<unsigned, 2> Kills;
905 SmallVector<unsigned, 2> Defs;
Sanjay Patel0b2a9492015-12-01 19:57:43 +0000906 for (const MachineOperand &MO : MI->operands()) {
Evan Cheng30f44ad2011-11-14 19:48:55 +0000907 if (!MO.isReg())
908 continue;
909 unsigned MOReg = MO.getReg();
910 if (!MOReg)
911 continue;
912 if (MO.isDef())
Michael Kupersteine36d7712016-08-11 17:38:33 +0000913 Defs.push_back(MOReg);
Evan Chengb8c55a52011-11-16 03:47:42 +0000914 else {
Michael Kupersteine36d7712016-08-11 17:38:33 +0000915 Uses.push_back(MOReg);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000916 if (MOReg != Reg && (MO.isKill() ||
917 (LIS && isPlainlyKilled(MI, MOReg, LIS))))
Michael Kupersteine36d7712016-08-11 17:38:33 +0000918 Kills.push_back(MOReg);
Evan Chengb8c55a52011-11-16 03:47:42 +0000919 }
Evan Cheng30f44ad2011-11-14 19:48:55 +0000920 }
921
922 // Move the copies connected to MI down as well.
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000923 MachineBasicBlock::iterator Begin = MI;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000924 MachineBasicBlock::iterator AfterMI = std::next(Begin);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000925 MachineBasicBlock::iterator End = AfterMI;
Michael Kupersteine36d7712016-08-11 17:38:33 +0000926 while (End->isCopy() &&
927 regOverlapsSet(Defs, End->getOperand(1).getReg(), TRI)) {
928 Defs.push_back(End->getOperand(0).getReg());
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000929 ++End;
Evan Cheng30f44ad2011-11-14 19:48:55 +0000930 }
931
Craig Topperaa741ab2017-02-04 01:58:10 +0000932 // Check if the reschedule will not break dependencies.
Evan Cheng30f44ad2011-11-14 19:48:55 +0000933 unsigned NumVisited = 0;
934 MachineBasicBlock::iterator KillPos = KillMI;
935 ++KillPos;
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +0000936 for (MachineInstr &OtherMI : make_range(End, KillPos)) {
Evan Cheng30f44ad2011-11-14 19:48:55 +0000937 // DBG_VALUE cannot be counted against the limit.
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +0000938 if (OtherMI.isDebugValue())
Evan Cheng30f44ad2011-11-14 19:48:55 +0000939 continue;
940 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
941 return false;
942 ++NumVisited;
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +0000943 if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
944 OtherMI.isBranch() || OtherMI.isTerminator())
Evan Cheng30f44ad2011-11-14 19:48:55 +0000945 // Don't move pass calls, etc.
946 return false;
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +0000947 for (const MachineOperand &MO : OtherMI.operands()) {
Evan Cheng30f44ad2011-11-14 19:48:55 +0000948 if (!MO.isReg())
949 continue;
950 unsigned MOReg = MO.getReg();
951 if (!MOReg)
952 continue;
953 if (MO.isDef()) {
Michael Kupersteine36d7712016-08-11 17:38:33 +0000954 if (regOverlapsSet(Uses, MOReg, TRI))
Evan Cheng30f44ad2011-11-14 19:48:55 +0000955 // Physical register use would be clobbered.
956 return false;
Michael Kupersteine36d7712016-08-11 17:38:33 +0000957 if (!MO.isDead() && regOverlapsSet(Defs, MOReg, TRI))
Evan Cheng30f44ad2011-11-14 19:48:55 +0000958 // May clobber a physical register def.
959 // FIXME: This may be too conservative. It's ok if the instruction
960 // is sunken completely below the use.
961 return false;
962 } else {
Michael Kupersteine36d7712016-08-11 17:38:33 +0000963 if (regOverlapsSet(Defs, MOReg, TRI))
Evan Cheng30f44ad2011-11-14 19:48:55 +0000964 return false;
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +0000965 bool isKill =
966 MO.isKill() || (LIS && isPlainlyKilled(&OtherMI, MOReg, LIS));
Michael Kupersteine36d7712016-08-11 17:38:33 +0000967 if (MOReg != Reg && ((isKill && regOverlapsSet(Uses, MOReg, TRI)) ||
968 regOverlapsSet(Kills, MOReg, TRI)))
Evan Cheng30f44ad2011-11-14 19:48:55 +0000969 // Don't want to extend other live ranges and update kills.
970 return false;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000971 if (MOReg == Reg && !isKill)
Chandler Carruthdb5536f2012-07-15 03:29:46 +0000972 // We can't schedule across a use of the register in question.
973 return false;
974 // Ensure that if this is register in question, its the kill we expect.
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +0000975 assert((MOReg != Reg || &OtherMI == KillMI) &&
Chandler Carruthdb5536f2012-07-15 03:29:46 +0000976 "Found multiple kills of a register in a basic block");
Evan Cheng30f44ad2011-11-14 19:48:55 +0000977 }
978 }
979 }
980
981 // Move debug info as well.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000982 while (Begin != MBB->begin() && std::prev(Begin)->isDebugValue())
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000983 --Begin;
984
985 nmi = End;
986 MachineBasicBlock::iterator InsertPos = KillPos;
987 if (LIS) {
988 // We have to move the copies first so that the MBB is still well-formed
989 // when calling handleMove().
990 for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) {
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +0000991 auto CopyMI = MBBI++;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000992 MBB->splice(InsertPos, MBB, CopyMI);
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +0000993 LIS->handleMove(*CopyMI);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000994 InsertPos = CopyMI;
995 }
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000996 End = std::next(MachineBasicBlock::iterator(MI));
Cameron Zwarich7d13fb42013-02-23 04:49:13 +0000997 }
Evan Cheng30f44ad2011-11-14 19:48:55 +0000998
999 // Copies following MI may have been moved as well.
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001000 MBB->splice(InsertPos, MBB, Begin, End);
Evan Cheng30f44ad2011-11-14 19:48:55 +00001001 DistanceMap.erase(DI);
1002
Chandler Carruthdb5536f2012-07-15 03:29:46 +00001003 // Update live variables
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001004 if (LIS) {
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +00001005 LIS->handleMove(*MI);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001006 } else {
Duncan P. N. Exon Smithd26fdc82016-07-01 01:51:32 +00001007 LV->removeVirtualRegisterKilled(Reg, *KillMI);
1008 LV->addVirtualRegisterKilled(Reg, *MI);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001009 }
Evan Cheng30f44ad2011-11-14 19:48:55 +00001010
Jakob Stoklund Olesen0ef03112012-07-17 17:57:23 +00001011 DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
Evan Cheng30f44ad2011-11-14 19:48:55 +00001012 return true;
1013}
1014
Sanjay Patelb53791e2015-12-01 19:32:35 +00001015/// Return true if the re-scheduling will put the given instruction too close
1016/// to the defs of its register dependencies.
Evan Cheng30f44ad2011-11-14 19:48:55 +00001017bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001018 MachineInstr *MI) {
Owen Andersonb36376e2014-03-17 19:36:09 +00001019 for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
1020 if (DefMI.getParent() != MBB || DefMI.isCopy() || DefMI.isCopyLike())
Evan Cheng30f44ad2011-11-14 19:48:55 +00001021 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001022 if (&DefMI == MI)
Evan Cheng30f44ad2011-11-14 19:48:55 +00001023 return true; // MI is defining something KillMI uses
Owen Andersonb36376e2014-03-17 19:36:09 +00001024 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(&DefMI);
Evan Cheng30f44ad2011-11-14 19:48:55 +00001025 if (DDI == DistanceMap.end())
1026 return true; // Below MI
1027 unsigned DefDist = DDI->second;
1028 assert(Dist > DefDist && "Visited def already?");
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001029 if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist))
Evan Cheng30f44ad2011-11-14 19:48:55 +00001030 return true;
1031 }
1032 return false;
1033}
1034
Sanjay Patelb53791e2015-12-01 19:32:35 +00001035/// If there is one more local instruction that reads 'Reg' and it kills 'Reg,
1036/// consider moving the kill instruction above the current two-address
1037/// instruction in order to eliminate the need for the copy.
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +00001038bool TwoAddressInstructionPass::
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001039rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +00001040 MachineBasicBlock::iterator &nmi,
1041 unsigned Reg) {
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001042 // Bail immediately if we don't have LV or LIS available. We use them to find
1043 // kills efficiently.
1044 if (!LV && !LIS)
Chandler Carruthdb5536f2012-07-15 03:29:46 +00001045 return false;
1046
Evan Cheng30f44ad2011-11-14 19:48:55 +00001047 MachineInstr *MI = &*mi;
1048 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
1049 if (DI == DistanceMap.end())
1050 // Must be created from unfolded load. Don't waste time trying this.
1051 return false;
1052
Craig Topperc0196b12014-04-14 00:51:57 +00001053 MachineInstr *KillMI = nullptr;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001054 if (LIS) {
1055 LiveInterval &LI = LIS->getInterval(Reg);
1056 assert(LI.end() != LI.begin() &&
1057 "Reg should not have empty live interval.");
1058
1059 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
1060 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
1061 if (I != LI.end() && I->start < MBBEndIdx)
1062 return false;
1063
1064 --I;
1065 KillMI = LIS->getInstructionFromIndex(I->end);
1066 } else {
1067 KillMI = LV->getVarInfo(Reg).findKill(MBB);
1068 }
Chandler Carruthdb5536f2012-07-15 03:29:46 +00001069 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng30f44ad2011-11-14 19:48:55 +00001070 // Don't mess with copies, they may be coalesced later.
1071 return false;
1072
1073 unsigned DstReg;
1074 if (isTwoAddrUse(*KillMI, Reg, DstReg))
1075 return false;
1076
Evan Cheng7098c4e2011-11-15 06:26:51 +00001077 bool SeenStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +00001078 if (!KillMI->isSafeToMove(AA, SeenStore))
Evan Cheng30f44ad2011-11-14 19:48:55 +00001079 return false;
1080
1081 SmallSet<unsigned, 2> Uses;
1082 SmallSet<unsigned, 2> Kills;
1083 SmallSet<unsigned, 2> Defs;
1084 SmallSet<unsigned, 2> LiveDefs;
Sanjay Patel0b2a9492015-12-01 19:57:43 +00001085 for (const MachineOperand &MO : KillMI->operands()) {
Evan Cheng30f44ad2011-11-14 19:48:55 +00001086 if (!MO.isReg())
1087 continue;
1088 unsigned MOReg = MO.getReg();
1089 if (MO.isUse()) {
1090 if (!MOReg)
1091 continue;
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001092 if (isDefTooClose(MOReg, DI->second, MI))
Evan Cheng30f44ad2011-11-14 19:48:55 +00001093 return false;
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001094 bool isKill = MO.isKill() || (LIS && isPlainlyKilled(KillMI, MOReg, LIS));
1095 if (MOReg == Reg && !isKill)
Chandler Carruthdb5536f2012-07-15 03:29:46 +00001096 return false;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001097 Uses.insert(MOReg);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001098 if (isKill && MOReg != Reg)
Evan Cheng30f44ad2011-11-14 19:48:55 +00001099 Kills.insert(MOReg);
1100 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1101 Defs.insert(MOReg);
1102 if (!MO.isDead())
1103 LiveDefs.insert(MOReg);
1104 }
1105 }
1106
1107 // Check if the reschedule will not break depedencies.
1108 unsigned NumVisited = 0;
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001109 for (MachineInstr &OtherMI :
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +00001110 make_range(mi, MachineBasicBlock::iterator(KillMI))) {
Evan Cheng30f44ad2011-11-14 19:48:55 +00001111 // DBG_VALUE cannot be counted against the limit.
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001112 if (OtherMI.isDebugValue())
Evan Cheng30f44ad2011-11-14 19:48:55 +00001113 continue;
1114 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
1115 return false;
1116 ++NumVisited;
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001117 if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
1118 OtherMI.isBranch() || OtherMI.isTerminator())
Evan Cheng30f44ad2011-11-14 19:48:55 +00001119 // Don't move pass calls, etc.
1120 return false;
Evan Cheng9ddd69a2011-11-16 03:05:12 +00001121 SmallVector<unsigned, 2> OtherDefs;
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001122 for (const MachineOperand &MO : OtherMI.operands()) {
Evan Cheng30f44ad2011-11-14 19:48:55 +00001123 if (!MO.isReg())
1124 continue;
1125 unsigned MOReg = MO.getReg();
1126 if (!MOReg)
1127 continue;
1128 if (MO.isUse()) {
1129 if (Defs.count(MOReg))
1130 // Moving KillMI can clobber the physical register if the def has
1131 // not been seen.
1132 return false;
1133 if (Kills.count(MOReg))
1134 // Don't want to extend other live ranges and update kills.
1135 return false;
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001136 if (&OtherMI != MI && MOReg == Reg &&
1137 !(MO.isKill() || (LIS && isPlainlyKilled(&OtherMI, MOReg, LIS))))
Chandler Carruthdb5536f2012-07-15 03:29:46 +00001138 // We can't schedule across a use of the register in question.
1139 return false;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001140 } else {
Evan Cheng9ddd69a2011-11-16 03:05:12 +00001141 OtherDefs.push_back(MOReg);
Evan Cheng30f44ad2011-11-14 19:48:55 +00001142 }
1143 }
Evan Cheng9ddd69a2011-11-16 03:05:12 +00001144
1145 for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
1146 unsigned MOReg = OtherDefs[i];
1147 if (Uses.count(MOReg))
1148 return false;
1149 if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1150 LiveDefs.count(MOReg))
1151 return false;
1152 // Physical register def is seen.
1153 Defs.erase(MOReg);
1154 }
Evan Cheng30f44ad2011-11-14 19:48:55 +00001155 }
1156
1157 // Move the old kill above MI, don't forget to move debug info as well.
1158 MachineBasicBlock::iterator InsertPos = mi;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001159 while (InsertPos != MBB->begin() && std::prev(InsertPos)->isDebugValue())
Evan Chengf2fc5082011-11-14 21:11:15 +00001160 --InsertPos;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001161 MachineBasicBlock::iterator From = KillMI;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001162 MachineBasicBlock::iterator To = std::next(From);
1163 while (std::prev(From)->isDebugValue())
Evan Cheng30f44ad2011-11-14 19:48:55 +00001164 --From;
1165 MBB->splice(InsertPos, MBB, From, To);
1166
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001167 nmi = std::prev(InsertPos); // Backtrack so we process the moved instr.
Evan Cheng30f44ad2011-11-14 19:48:55 +00001168 DistanceMap.erase(DI);
1169
Chandler Carruthdb5536f2012-07-15 03:29:46 +00001170 // Update live variables
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001171 if (LIS) {
Duncan P. N. Exon Smithbe8f8c42016-02-27 20:14:29 +00001172 LIS->handleMove(*KillMI);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001173 } else {
Duncan P. N. Exon Smithd26fdc82016-07-01 01:51:32 +00001174 LV->removeVirtualRegisterKilled(Reg, *KillMI);
1175 LV->addVirtualRegisterKilled(Reg, *MI);
Cameron Zwarich7d13fb42013-02-23 04:49:13 +00001176 }
Chandler Carruthdb5536f2012-07-15 03:29:46 +00001177
Jakob Stoklund Olesen0ef03112012-07-17 17:57:23 +00001178 DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
Evan Cheng30f44ad2011-11-14 19:48:55 +00001179 return true;
1180}
1181
Andrew Kaylor16c4da02015-09-28 20:33:22 +00001182/// Tries to commute the operand 'BaseOpIdx' and some other operand in the
1183/// given machine instruction to improve opportunities for coalescing and
1184/// elimination of a register to register copy.
1185///
1186/// 'DstOpIdx' specifies the index of MI def operand.
1187/// 'BaseOpKilled' specifies if the register associated with 'BaseOpIdx'
1188/// operand is killed by the given instruction.
1189/// The 'Dist' arguments provides the distance of MI from the start of the
1190/// current basic block and it is used to determine if it is profitable
1191/// to commute operands in the instruction.
1192///
1193/// Returns true if the transformation happened. Otherwise, returns false.
1194bool TwoAddressInstructionPass::tryInstructionCommute(MachineInstr *MI,
1195 unsigned DstOpIdx,
1196 unsigned BaseOpIdx,
1197 bool BaseOpKilled,
1198 unsigned Dist) {
Craig Topper1f81dee2016-09-11 06:00:15 +00001199 if (!MI->isCommutable())
1200 return false;
1201
Andrew Kaylor16c4da02015-09-28 20:33:22 +00001202 unsigned DstOpReg = MI->getOperand(DstOpIdx).getReg();
1203 unsigned BaseOpReg = MI->getOperand(BaseOpIdx).getReg();
1204 unsigned OpsNum = MI->getDesc().getNumOperands();
1205 unsigned OtherOpIdx = MI->getDesc().getNumDefs();
1206 for (; OtherOpIdx < OpsNum; OtherOpIdx++) {
1207 // The call of findCommutedOpIndices below only checks if BaseOpIdx
Sanjay Patel96824de2015-12-01 19:19:18 +00001208 // and OtherOpIdx are commutable, it does not really search for
Andrew Kaylor16c4da02015-09-28 20:33:22 +00001209 // other commutable operands and does not change the values of passed
1210 // variables.
Craig Topper1f81dee2016-09-11 06:00:15 +00001211 if (OtherOpIdx == BaseOpIdx || !MI->getOperand(OtherOpIdx).isReg() ||
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001212 !TII->findCommutedOpIndices(*MI, BaseOpIdx, OtherOpIdx))
Andrew Kaylor16c4da02015-09-28 20:33:22 +00001213 continue;
1214
1215 unsigned OtherOpReg = MI->getOperand(OtherOpIdx).getReg();
1216 bool AggressiveCommute = false;
1217
1218 // If OtherOp dies but BaseOp does not, swap the OtherOp and BaseOp
1219 // operands. This makes the live ranges of DstOp and OtherOp joinable.
1220 bool DoCommute =
1221 !BaseOpKilled && isKilled(*MI, OtherOpReg, MRI, TII, LIS, false);
1222
1223 if (!DoCommute &&
1224 isProfitableToCommute(DstOpReg, BaseOpReg, OtherOpReg, MI, Dist)) {
1225 DoCommute = true;
1226 AggressiveCommute = true;
1227 }
1228
1229 // If it's profitable to commute, try to do so.
Craig Topper76007942016-09-11 22:10:42 +00001230 if (DoCommute && commuteInstruction(MI, DstOpIdx, BaseOpIdx, OtherOpIdx,
1231 Dist)) {
Andrew Kaylor16c4da02015-09-28 20:33:22 +00001232 ++NumCommuted;
1233 if (AggressiveCommute)
1234 ++NumAggrCommuted;
1235 return true;
1236 }
1237 }
1238 return false;
1239}
1240
Sanjay Patelb53791e2015-12-01 19:32:35 +00001241/// For the case where an instruction has a single pair of tied register
1242/// operands, attempt some transformations that may either eliminate the tied
1243/// operands or improve the opportunities for coalescing away the register copy.
1244/// Returns true if no copy needs to be inserted to untie mi's operands
1245/// (either because they were untied, or because mi was rescheduled, and will
1246/// be visited again later). If the shouldOnlyCommute flag is true, only
1247/// instruction commutation is attempted.
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001248bool TwoAddressInstructionPass::
Jakob Stoklund Olesen112a44d2012-10-26 21:12:49 +00001249tryInstructionTransform(MachineBasicBlock::iterator &mi,
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001250 MachineBasicBlock::iterator &nmi,
Cameron Zwarichf05c0cb2013-02-24 00:27:26 +00001251 unsigned SrcIdx, unsigned DstIdx,
1252 unsigned Dist, bool shouldOnlyCommute) {
Evan Cheng822ddde2011-11-16 18:44:48 +00001253 if (OptLevel == CodeGenOpt::None)
1254 return false;
1255
Evan Cheng30f44ad2011-11-14 19:48:55 +00001256 MachineInstr &MI = *mi;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001257 unsigned regA = MI.getOperand(DstIdx).getReg();
1258 unsigned regB = MI.getOperand(SrcIdx).getReg();
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001259
1260 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1261 "cannot make instruction into two-address form");
Cameron Zwarich384026b2013-02-21 22:58:42 +00001262 bool regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001263
Evan Chengb64e7b72012-05-03 01:45:13 +00001264 if (TargetRegisterInfo::isVirtualRegister(regA))
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001265 scanUses(regA);
Evan Chengb64e7b72012-05-03 01:45:13 +00001266
Andrew Kaylor16c4da02015-09-28 20:33:22 +00001267 bool Commuted = tryInstructionCommute(&MI, DstIdx, SrcIdx, regBKilled, Dist);
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001268
Quentin Colombet9729fb32015-07-01 23:12:13 +00001269 // If the instruction is convertible to 3 Addr, instead
1270 // of returning try 3 Addr transformation aggresively and
1271 // use this variable to check later. Because it might be better.
1272 // For example, we can just use `leal (%rsi,%rdi), %eax` and `ret`
1273 // instead of the following code.
NAKAMURA Takumi84965032015-09-22 11:14:12 +00001274 // addl %esi, %edi
1275 // movl %edi, %eax
Quentin Colombet9729fb32015-07-01 23:12:13 +00001276 // ret
Andrew Kaylor16c4da02015-09-28 20:33:22 +00001277 if (Commuted && !MI.isConvertibleTo3Addr())
1278 return false;
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001279
Cameron Zwarichf05c0cb2013-02-24 00:27:26 +00001280 if (shouldOnlyCommute)
1281 return false;
1282
Evan Cheng30f44ad2011-11-14 19:48:55 +00001283 // If there is one more use of regB later in the same MBB, consider
1284 // re-schedule this MI below it.
Quentin Colombet40dd5102015-07-06 20:12:54 +00001285 if (!Commuted && EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) {
Evan Cheng30f44ad2011-11-14 19:48:55 +00001286 ++NumReSchedDowns;
Lang Hames3ad11ff2012-04-09 20:17:30 +00001287 return true;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001288 }
1289
Craig Topper2c4068f2015-10-06 05:39:59 +00001290 // If we commuted, regB may have changed so we should re-sample it to avoid
1291 // confusing the three address conversion below.
1292 if (Commuted) {
1293 regB = MI.getOperand(SrcIdx).getReg();
1294 regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
1295 }
1296
Evan Cheng7f8e5632011-12-07 07:15:52 +00001297 if (MI.isConvertibleTo3Addr()) {
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001298 // This instruction is potentially convertible to a true
1299 // three-address instruction. Check if it is profitable.
Evan Cheng15fed7a2011-03-02 01:08:17 +00001300 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001301 // Try to convert it.
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001302 if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001303 ++NumConvertedTo3Addr;
1304 return true; // Done with this instruction.
1305 }
1306 }
1307 }
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001308
Quentin Colombet9729fb32015-07-01 23:12:13 +00001309 // Return if it is commuted but 3 addr conversion is failed.
Quentin Colombet40dd5102015-07-06 20:12:54 +00001310 if (Commuted)
Quentin Colombet9729fb32015-07-01 23:12:13 +00001311 return false;
1312
Evan Cheng30f44ad2011-11-14 19:48:55 +00001313 // If there is one more use of regB later in the same MBB, consider
1314 // re-schedule it before this MI if it's legal.
Andrew Trick608a6982013-04-24 15:54:39 +00001315 if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) {
Evan Cheng30f44ad2011-11-14 19:48:55 +00001316 ++NumReSchedUps;
Lang Hames3ad11ff2012-04-09 20:17:30 +00001317 return true;
Evan Cheng30f44ad2011-11-14 19:48:55 +00001318 }
1319
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001320 // If this is an instruction with a load folded into it, try unfolding
1321 // the load, e.g. avoid this:
1322 // movq %rdx, %rcx
1323 // addq (%rax), %rcx
1324 // in favor of this:
1325 // movq (%rax), %rcx
1326 // addq %rdx, %rcx
1327 // because it's preferable to schedule a load than a register copy.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001328 if (MI.mayLoad() && !regBKilled) {
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001329 // Determine if a load can be unfolded.
1330 unsigned LoadRegIndex;
1331 unsigned NewOpc =
Evan Cheng30f44ad2011-11-14 19:48:55 +00001332 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001333 /*UnfoldLoad=*/true,
1334 /*UnfoldStore=*/false,
1335 &LoadRegIndex);
1336 if (NewOpc != 0) {
Evan Cheng6cc775f2011-06-28 19:10:37 +00001337 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1338 if (UnfoldMCID.getNumDefs() == 1) {
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001339 // Unfold the load.
Evan Cheng30f44ad2011-11-14 19:48:55 +00001340 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001341 const TargetRegisterClass *RC =
Andrew Trick32aea352012-05-03 01:14:37 +00001342 TRI->getAllocatableClass(
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001343 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001344 unsigned Reg = MRI->createVirtualRegister(RC);
1345 SmallVector<MachineInstr *, 2> NewMIs;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001346 if (!TII->unfoldMemoryOperand(*MF, MI, Reg,
1347 /*UnfoldLoad=*/true,
1348 /*UnfoldStore=*/false, NewMIs)) {
Evan Cheng0ce84482010-07-02 20:36:18 +00001349 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1350 return false;
1351 }
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001352 assert(NewMIs.size() == 2 &&
1353 "Unfolded a load into multiple instructions!");
1354 // The load was previously folded, so this is the only use.
1355 NewMIs[1]->addRegisterKilled(Reg, TRI);
1356
1357 // Tentatively insert the instructions into the block so that they
1358 // look "normal" to the transformation logic.
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001359 MBB->insert(mi, NewMIs[0]);
1360 MBB->insert(mi, NewMIs[1]);
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001361
1362 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1363 << "2addr: NEW INST: " << *NewMIs[1]);
1364
1365 // Transform the instruction, now that it no longer has a load.
1366 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1367 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1368 MachineBasicBlock::iterator NewMI = NewMIs[1];
Cameron Zwarich6868f382013-02-24 00:27:29 +00001369 bool TransformResult =
Cameron Zwarichf05c0cb2013-02-24 00:27:26 +00001370 tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true);
Cameron Zwarich1b4c64c2013-02-24 01:26:05 +00001371 (void)TransformResult;
Cameron Zwarich6868f382013-02-24 00:27:29 +00001372 assert(!TransformResult &&
1373 "tryInstructionTransform() should return false.");
1374 if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001375 // Success, or at least we made an improvement. Keep the unfolded
1376 // instructions and discard the original.
1377 if (LV) {
Evan Cheng30f44ad2011-11-14 19:48:55 +00001378 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1379 MachineOperand &MO = MI.getOperand(i);
Andrew Trick808a7a62012-02-03 05:12:30 +00001380 if (MO.isReg() &&
Dan Gohman851e4782010-06-22 00:32:04 +00001381 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1382 if (MO.isUse()) {
Dan Gohman2370e2f2010-06-22 02:07:21 +00001383 if (MO.isKill()) {
1384 if (NewMIs[0]->killsRegister(MO.getReg()))
Duncan P. N. Exon Smithd26fdc82016-07-01 01:51:32 +00001385 LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[0]);
Dan Gohman2370e2f2010-06-22 02:07:21 +00001386 else {
1387 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1388 "Kill missing after load unfold!");
Duncan P. N. Exon Smithd26fdc82016-07-01 01:51:32 +00001389 LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[1]);
Dan Gohman2370e2f2010-06-22 02:07:21 +00001390 }
1391 }
Duncan P. N. Exon Smithd26fdc82016-07-01 01:51:32 +00001392 } else if (LV->removeVirtualRegisterDead(MO.getReg(), MI)) {
Dan Gohman2370e2f2010-06-22 02:07:21 +00001393 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
Duncan P. N. Exon Smithd26fdc82016-07-01 01:51:32 +00001394 LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[1]);
Dan Gohman2370e2f2010-06-22 02:07:21 +00001395 else {
1396 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1397 "Dead flag missing after load unfold!");
Duncan P. N. Exon Smithd26fdc82016-07-01 01:51:32 +00001398 LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[0]);
Dan Gohman2370e2f2010-06-22 02:07:21 +00001399 }
1400 }
Dan Gohman851e4782010-06-22 00:32:04 +00001401 }
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001402 }
Duncan P. N. Exon Smithd26fdc82016-07-01 01:51:32 +00001403 LV->addVirtualRegisterKilled(Reg, *NewMIs[1]);
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001404 }
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001405
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001406 SmallVector<unsigned, 4> OrigRegs;
1407 if (LIS) {
Craig Topperda5168b2015-10-08 06:06:42 +00001408 for (const MachineOperand &MO : MI.operands()) {
1409 if (MO.isReg())
1410 OrigRegs.push_back(MO.getReg());
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001411 }
1412 }
1413
Evan Cheng30f44ad2011-11-14 19:48:55 +00001414 MI.eraseFromParent();
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001415
1416 // Update LiveIntervals.
Cameron Zwarichcaad7e12013-02-20 22:10:00 +00001417 if (LIS) {
1418 MachineBasicBlock::iterator Begin(NewMIs[0]);
1419 MachineBasicBlock::iterator End(NewMIs[1]);
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001420 LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs);
Cameron Zwarichcaad7e12013-02-20 22:10:00 +00001421 }
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001422
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001423 mi = NewMIs[1];
Dan Gohman3c1b3c62010-06-21 22:17:20 +00001424 } else {
1425 // Transforming didn't eliminate the tie and didn't lead to an
1426 // improvement. Clean up the unfolded instructions and keep the
1427 // original.
1428 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1429 NewMIs[0]->eraseFromParent();
1430 NewMIs[1]->eraseFromParent();
1431 }
1432 }
1433 }
1434 }
1435
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001436 return false;
1437}
1438
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001439// Collect tied operands of MI that need to be handled.
1440// Rewrite trivial cases immediately.
1441// Return true if any tied operands where found, including the trivial ones.
1442bool TwoAddressInstructionPass::
1443collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
1444 const MCInstrDesc &MCID = MI->getDesc();
1445 bool AnyOps = false;
Jakob Stoklund Olesenade363e2012-09-04 22:59:30 +00001446 unsigned NumOps = MI->getNumOperands();
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001447
1448 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1449 unsigned DstIdx = 0;
1450 if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1451 continue;
1452 AnyOps = true;
Jakob Stoklund Olesenfbf45dc2012-08-07 22:47:06 +00001453 MachineOperand &SrcMO = MI->getOperand(SrcIdx);
1454 MachineOperand &DstMO = MI->getOperand(DstIdx);
1455 unsigned SrcReg = SrcMO.getReg();
1456 unsigned DstReg = DstMO.getReg();
1457 // Tied constraint already satisfied?
1458 if (SrcReg == DstReg)
1459 continue;
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001460
Jakob Stoklund Olesenfbf45dc2012-08-07 22:47:06 +00001461 assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001462
1463 // Deal with <undef> uses immediately - simply rewrite the src operand.
Andrew Tricke3398282013-12-17 04:50:45 +00001464 if (SrcMO.isUndef() && !DstMO.getSubReg()) {
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001465 // Constrain the DstReg register class if required.
1466 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1467 if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
1468 TRI, *MF))
1469 MRI->constrainRegClass(DstReg, RC);
Jakob Stoklund Olesenfbf45dc2012-08-07 22:47:06 +00001470 SrcMO.setReg(DstReg);
Andrew Tricke3398282013-12-17 04:50:45 +00001471 SrcMO.setSubReg(0);
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001472 DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
1473 continue;
1474 }
Jakob Stoklund Olesenfbf45dc2012-08-07 22:47:06 +00001475 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001476 }
1477 return AnyOps;
1478}
1479
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001480// Process a list of tied MI operands that all use the same source register.
1481// The tied pairs are of the form (SrcIdx, DstIdx).
1482void
1483TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
1484 TiedPairList &TiedPairs,
1485 unsigned &Dist) {
1486 bool IsEarlyClobber = false;
Cameron Zwarich2991feb2013-02-20 06:46:46 +00001487 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1488 const MachineOperand &DstMO = MI->getOperand(TiedPairs[tpi].second);
1489 IsEarlyClobber |= DstMO.isEarlyClobber();
1490 }
1491
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001492 bool RemovedKillFlag = false;
1493 bool AllUsesCopied = true;
1494 unsigned LastCopiedReg = 0;
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001495 SlotIndex LastCopyIdx;
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001496 unsigned RegB = 0;
Andrew Tricke3398282013-12-17 04:50:45 +00001497 unsigned SubRegB = 0;
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001498 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1499 unsigned SrcIdx = TiedPairs[tpi].first;
1500 unsigned DstIdx = TiedPairs[tpi].second;
1501
1502 const MachineOperand &DstMO = MI->getOperand(DstIdx);
1503 unsigned RegA = DstMO.getReg();
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001504
1505 // Grab RegB from the instruction because it may have changed if the
1506 // instruction was commuted.
1507 RegB = MI->getOperand(SrcIdx).getReg();
Andrew Tricke3398282013-12-17 04:50:45 +00001508 SubRegB = MI->getOperand(SrcIdx).getSubReg();
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001509
1510 if (RegA == RegB) {
1511 // The register is tied to multiple destinations (or else we would
1512 // not have continued this far), but this use of the register
1513 // already matches the tied destination. Leave it.
1514 AllUsesCopied = false;
1515 continue;
1516 }
1517 LastCopiedReg = RegA;
1518
1519 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1520 "cannot make instruction into two-address form");
1521
1522#ifndef NDEBUG
1523 // First, verify that we don't have a use of "a" in the instruction
1524 // (a = b + a for example) because our transformation will not
1525 // work. This should never occur because we are in SSA form.
1526 for (unsigned i = 0; i != MI->getNumOperands(); ++i)
1527 assert(i == DstIdx ||
1528 !MI->getOperand(i).isReg() ||
1529 MI->getOperand(i).getReg() != RegA);
1530#endif
1531
1532 // Emit a copy.
Andrew Tricke3398282013-12-17 04:50:45 +00001533 MachineInstrBuilder MIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1534 TII->get(TargetOpcode::COPY), RegA);
1535 // If this operand is folding a truncation, the truncation now moves to the
1536 // copy so that the register classes remain valid for the operands.
1537 MIB.addReg(RegB, 0, SubRegB);
1538 const TargetRegisterClass *RC = MRI->getRegClass(RegB);
1539 if (SubRegB) {
1540 if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1541 assert(TRI->getMatchingSuperRegClass(RC, MRI->getRegClass(RegA),
1542 SubRegB) &&
1543 "tied subregister must be a truncation");
1544 // The superreg class will not be used to constrain the subreg class.
Craig Topperc0196b12014-04-14 00:51:57 +00001545 RC = nullptr;
Andrew Tricke3398282013-12-17 04:50:45 +00001546 }
1547 else {
1548 assert(TRI->getMatchingSuperReg(RegA, SubRegB, MRI->getRegClass(RegB))
1549 && "tied subregister must be a truncation");
1550 }
1551 }
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001552
1553 // Update DistanceMap.
1554 MachineBasicBlock::iterator PrevMI = MI;
1555 --PrevMI;
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001556 DistanceMap.insert(std::make_pair(&*PrevMI, Dist));
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001557 DistanceMap[MI] = ++Dist;
1558
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001559 if (LIS) {
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001560 LastCopyIdx = LIS->InsertMachineInstrInMaps(*PrevMI).getRegSlot();
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001561
1562 if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1563 LiveInterval &LI = LIS->getInterval(RegA);
1564 VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1565 SlotIndex endIdx =
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001566 LIS->getInstructionIndex(*MI).getRegSlot(IsEarlyClobber);
Matthias Braun13ddb7c2013-10-10 21:28:43 +00001567 LI.addSegment(LiveInterval::Segment(LastCopyIdx, endIdx, VNI));
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001568 }
1569 }
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001570
Andrew Tricke3398282013-12-17 04:50:45 +00001571 DEBUG(dbgs() << "\t\tprepend:\t" << *MIB);
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001572
1573 MachineOperand &MO = MI->getOperand(SrcIdx);
1574 assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
1575 "inconsistent operand info for 2-reg pass");
1576 if (MO.isKill()) {
1577 MO.setIsKill(false);
1578 RemovedKillFlag = true;
1579 }
1580
1581 // Make sure regA is a legal regclass for the SrcIdx operand.
1582 if (TargetRegisterInfo::isVirtualRegister(RegA) &&
1583 TargetRegisterInfo::isVirtualRegister(RegB))
Andrew Tricke3398282013-12-17 04:50:45 +00001584 MRI->constrainRegClass(RegA, RC);
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001585 MO.setReg(RegA);
Andrew Tricke3398282013-12-17 04:50:45 +00001586 // The getMatchingSuper asserts guarantee that the register class projected
1587 // by SubRegB is compatible with RegA with no subregister. So regardless of
1588 // whether the dest oper writes a subreg, the source oper should not.
1589 MO.setSubReg(0);
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001590
1591 // Propagate SrcRegMap.
1592 SrcRegMap[RegA] = RegB;
1593 }
1594
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001595 if (AllUsesCopied) {
1596 if (!IsEarlyClobber) {
1597 // Replace other (un-tied) uses of regB with LastCopiedReg.
Sanjay Patel0b2a9492015-12-01 19:57:43 +00001598 for (MachineOperand &MO : MI->operands()) {
Matt Arsenaultf403df32016-08-26 06:31:32 +00001599 if (MO.isReg() && MO.getReg() == RegB &&
Andrew Tricke3398282013-12-17 04:50:45 +00001600 MO.isUse()) {
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001601 if (MO.isKill()) {
1602 MO.setIsKill(false);
1603 RemovedKillFlag = true;
1604 }
1605 MO.setReg(LastCopiedReg);
Matt Arsenaultf403df32016-08-26 06:31:32 +00001606 MO.setSubReg(MO.getSubReg());
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001607 }
1608 }
1609 }
1610
1611 // Update live variables for regB.
Duncan P. N. Exon Smithd26fdc82016-07-01 01:51:32 +00001612 if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(*MI)) {
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001613 MachineBasicBlock::iterator PrevMI = MI;
1614 --PrevMI;
Duncan P. N. Exon Smithd26fdc82016-07-01 01:51:32 +00001615 LV->addVirtualRegisterKilled(RegB, *PrevMI);
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001616 }
1617
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001618 // Update LiveIntervals.
1619 if (LIS) {
1620 LiveInterval &LI = LIS->getInterval(RegB);
Duncan P. N. Exon Smith3ac9cc62016-02-27 06:40:41 +00001621 SlotIndex MIIdx = LIS->getInstructionIndex(*MI);
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001622 LiveInterval::const_iterator I = LI.find(MIIdx);
1623 assert(I != LI.end() && "RegB must be live-in to use.");
1624
1625 SlotIndex UseIdx = MIIdx.getRegSlot(IsEarlyClobber);
1626 if (I->end == UseIdx)
Matthias Braun13ddb7c2013-10-10 21:28:43 +00001627 LI.removeSegment(LastCopyIdx, UseIdx);
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001628 }
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001629 } else if (RemovedKillFlag) {
1630 // Some tied uses of regB matched their destination registers, so
1631 // regB is still used in this instruction, but a kill flag was
1632 // removed from a different tied use of regB, so now we need to add
1633 // a kill flag to one of the remaining uses of regB.
Sanjay Patel0b2a9492015-12-01 19:57:43 +00001634 for (MachineOperand &MO : MI->operands()) {
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001635 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1636 MO.setIsKill(true);
1637 break;
1638 }
1639 }
1640 }
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001641}
1642
Sanjay Patelb53791e2015-12-01 19:32:35 +00001643/// Reduce two-address instructions to two operands.
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001644bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
1645 MF = &Func;
1646 const TargetMachine &TM = MF->getTarget();
1647 MRI = &MF->getRegInfo();
Eric Christopher33726202015-01-27 08:48:42 +00001648 TII = MF->getSubtarget().getInstrInfo();
1649 TRI = MF->getSubtarget().getRegisterInfo();
1650 InstrItins = MF->getSubtarget().getInstrItineraryData();
Duncan Sands5a913d62009-01-28 13:14:17 +00001651 LV = getAnalysisIfAvailable<LiveVariables>();
Jakob Stoklund Olesen24bc5142012-08-03 22:58:34 +00001652 LIS = getAnalysisIfAvailable<LiveIntervals>();
Ahmed Bougachaa09ff592017-05-10 00:56:00 +00001653 if (auto *AAPass = getAnalysisIfAvailable<AAResultsWrapperPass>())
1654 AA = &AAPass->getAAResults();
1655 else
1656 AA = nullptr;
Evan Cheng822ddde2011-11-16 18:44:48 +00001657 OptLevel = TM.getOptLevel();
Alkis Evlogimenos725021c2003-12-18 13:06:04 +00001658
Misha Brukman6dd644e2004-07-22 15:26:23 +00001659 bool MadeChange = false;
Alkis Evlogimenos725021c2003-12-18 13:06:04 +00001660
David Greeneac9f8192010-01-05 01:24:21 +00001661 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
Andrew Trick808a7a62012-02-03 05:12:30 +00001662 DEBUG(dbgs() << "********** Function: "
Craig Toppera538d832012-08-22 06:07:19 +00001663 << MF->getName() << '\n');
Alkis Evlogimenos26583db2004-02-18 00:35:06 +00001664
Jakob Stoklund Olesen9760f042011-07-29 22:51:22 +00001665 // This pass takes the function out of SSA form.
1666 MRI->leaveSSA();
1667
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001668 TiedOperandMap TiedOperands;
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001669 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
1670 MBBI != MBBE; ++MBBI) {
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +00001671 MBB = &*MBBI;
Evan Chengc5618eb2008-06-18 07:49:14 +00001672 unsigned Dist = 0;
1673 DistanceMap.clear();
Evan Chengc2f95b52009-03-01 02:03:43 +00001674 SrcRegMap.clear();
1675 DstRegMap.clear();
1676 Processed.clear();
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001677 for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
Evan Cheng58324102008-03-27 01:27:25 +00001678 mi != me; ) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001679 MachineBasicBlock::iterator nmi = std::next(mi);
Dale Johannesen8bba1602010-02-10 21:47:48 +00001680 if (mi->isDebugValue()) {
1681 mi = nmi;
1682 continue;
1683 }
Evan Cheng77be42a2010-03-23 20:36:12 +00001684
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001685 // Expand REG_SEQUENCE instructions. This will position mi at the first
1686 // expanded instruction.
Evan Cheng4b6abd82010-05-05 18:45:40 +00001687 if (mi->isRegSequence())
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001688 eliminateRegSequence(mi);
Evan Cheng4b6abd82010-05-05 18:45:40 +00001689
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001690 DistanceMap.insert(std::make_pair(&*mi, ++Dist));
Evan Chengc2f95b52009-03-01 02:03:43 +00001691
Jakob Stoklund Olesen7fa17d42012-10-26 23:05:10 +00001692 processCopy(&*mi);
Evan Chengc2f95b52009-03-01 02:03:43 +00001693
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001694 // First scan through all the tied register uses in this instruction
1695 // and record a list of pairs of tied operands for each register.
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001696 if (!collectTiedOperands(&*mi, TiedOperands)) {
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001697 mi = nmi;
1698 continue;
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001699 }
Alkis Evlogimenos725021c2003-12-18 13:06:04 +00001700
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001701 ++NumTwoAddressInstrs;
Jakob Stoklund Olesena0c72ec2012-08-03 23:57:58 +00001702 MadeChange = true;
Jakob Stoklund Olesen1162a152012-08-03 23:25:45 +00001703 DEBUG(dbgs() << '\t' << *mi);
1704
Chandler Carruth985454e2012-07-18 18:58:22 +00001705 // If the instruction has a single pair of tied operands, try some
1706 // transformations that may either eliminate the tied operands or
1707 // improve the opportunities for coalescing away the register copy.
1708 if (TiedOperands.size() == 1) {
Eugene Zelenko4f81cdd2017-09-29 21:55:49 +00001709 SmallVectorImpl<std::pair<unsigned, unsigned>> &TiedPairs
Chandler Carruth985454e2012-07-18 18:58:22 +00001710 = TiedOperands.begin()->second;
1711 if (TiedPairs.size() == 1) {
1712 unsigned SrcIdx = TiedPairs[0].first;
1713 unsigned DstIdx = TiedPairs[0].second;
1714 unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
1715 unsigned DstReg = mi->getOperand(DstIdx).getReg();
1716 if (SrcReg != DstReg &&
Cameron Zwarichf05c0cb2013-02-24 00:27:26 +00001717 tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) {
NAKAMURA Takumi84965032015-09-22 11:14:12 +00001718 // The tied operands have been eliminated or shifted further down
1719 // the block to ease elimination. Continue processing with 'nmi'.
Chandler Carruth985454e2012-07-18 18:58:22 +00001720 TiedOperands.clear();
1721 mi = nmi;
1722 continue;
1723 }
1724 }
1725 }
1726
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001727 // Now iterate over the information collected above.
Craig Topperda5168b2015-10-08 06:06:42 +00001728 for (auto &TO : TiedOperands) {
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001729 processTiedPairs(&*mi, TO.second, Dist);
David Greeneac9f8192010-01-05 01:24:21 +00001730 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
Jakob Stoklund Olesen6b556f82012-06-25 03:27:12 +00001731 }
Bill Wendling19e3c852008-05-10 00:12:52 +00001732
Jakob Stoklund Olesen6b556f82012-06-25 03:27:12 +00001733 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1734 if (mi->isInsertSubreg()) {
1735 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1736 // To %reg:subidx = COPY %subreg
1737 unsigned SubIdx = mi->getOperand(3).getImm();
1738 mi->RemoveOperand(3);
1739 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1740 mi->getOperand(0).setSubReg(SubIdx);
1741 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1742 mi->RemoveOperand(1);
1743 mi->setDesc(TII->get(TargetOpcode::COPY));
1744 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
Jakob Stoklund Olesen70ee3ec2010-07-06 23:26:25 +00001745 }
1746
Bob Wilson5c7d9ca2009-09-03 20:58:42 +00001747 // Clear TiedOperands here instead of at the top of the loop
1748 // since most instructions do not have tied operands.
1749 TiedOperands.clear();
Evan Cheng58324102008-03-27 01:27:25 +00001750 mi = nmi;
Misha Brukman6dd644e2004-07-22 15:26:23 +00001751 }
1752 }
1753
Cameron Zwarich36735812013-02-20 06:46:34 +00001754 if (LIS)
1755 MF->verify(this, "After two-address instruction pass");
1756
Misha Brukman6dd644e2004-07-22 15:26:23 +00001757 return MadeChange;
Alkis Evlogimenos725021c2003-12-18 13:06:04 +00001758}
Evan Cheng4b6abd82010-05-05 18:45:40 +00001759
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001760/// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process.
Evan Cheng4b6abd82010-05-05 18:45:40 +00001761///
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001762/// The instruction is turned into a sequence of sub-register copies:
1763///
1764/// %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1
1765///
1766/// Becomes:
1767///
1768/// %dst:ssub0<def,undef> = COPY %v1
1769/// %dst:ssub1<def> = COPY %v2
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001770void TwoAddressInstructionPass::
1771eliminateRegSequence(MachineBasicBlock::iterator &MBBI) {
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001772 MachineInstr &MI = *MBBI;
1773 unsigned DstReg = MI.getOperand(0).getReg();
1774 if (MI.getOperand(0).getSubReg() ||
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001775 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001776 !(MI.getNumOperands() & 1)) {
1777 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << MI);
Craig Topperc0196b12014-04-14 00:51:57 +00001778 llvm_unreachable(nullptr);
Evan Cheng4b6abd82010-05-05 18:45:40 +00001779 }
1780
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001781 SmallVector<unsigned, 4> OrigRegs;
1782 if (LIS) {
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001783 OrigRegs.push_back(MI.getOperand(0).getReg());
1784 for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2)
1785 OrigRegs.push_back(MI.getOperand(i).getReg());
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001786 }
1787
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001788 bool DefEmitted = false;
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001789 for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2) {
1790 MachineOperand &UseMO = MI.getOperand(i);
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001791 unsigned SrcReg = UseMO.getReg();
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001792 unsigned SubIdx = MI.getOperand(i+1).getImm();
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001793 // Nothing needs to be inserted for <undef> operands.
1794 if (UseMO.isUndef())
1795 continue;
1796
1797 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1798 // might insert a COPY that uses SrcReg after is was killed.
1799 bool isKill = UseMO.isKill();
1800 if (isKill)
1801 for (unsigned j = i + 2; j < e; j += 2)
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001802 if (MI.getOperand(j).getReg() == SrcReg) {
1803 MI.getOperand(j).setIsKill();
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001804 UseMO.setIsKill(false);
1805 isKill = false;
1806 break;
1807 }
1808
1809 // Insert the sub-register copy.
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001810 MachineInstr *CopyMI = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001811 TII->get(TargetOpcode::COPY))
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001812 .addReg(DstReg, RegState::Define, SubIdx)
Diana Picus116bbab2017-01-13 09:58:52 +00001813 .add(UseMO);
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001814
1815 // The first def needs an <undef> flag because there is no live register
1816 // before it.
1817 if (!DefEmitted) {
1818 CopyMI->getOperand(0).setIsUndef(true);
1819 // Return an iterator pointing to the first inserted instr.
1820 MBBI = CopyMI;
1821 }
1822 DefEmitted = true;
1823
1824 // Update LiveVariables' kill info.
1825 if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001826 LV->replaceKillInstruction(SrcReg, MI, *CopyMI);
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001827
1828 DEBUG(dbgs() << "Inserted: " << *CopyMI);
1829 }
1830
David Blaikie9db062e2013-02-20 07:39:20 +00001831 MachineBasicBlock::iterator EndMBBI =
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001832 std::next(MachineBasicBlock::iterator(MI));
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001833
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001834 if (!DefEmitted) {
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001835 DEBUG(dbgs() << "Turned: " << MI << " into an IMPLICIT_DEF");
1836 MI.setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1837 for (int j = MI.getNumOperands() - 1, ee = 0; j > ee; --j)
1838 MI.RemoveOperand(j);
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001839 } else {
Duncan P. N. Exon Smith50d307682016-07-08 17:43:08 +00001840 DEBUG(dbgs() << "Eliminated: " << MI);
1841 MI.eraseFromParent();
Jakob Stoklund Olesenda2b6b32012-12-01 01:06:44 +00001842 }
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001843
1844 // Udpate LiveIntervals.
Cameron Zwarichcaad7e12013-02-20 22:10:00 +00001845 if (LIS)
Cameron Zwarich8e60d4d2013-02-20 06:46:48 +00001846 LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs);
Evan Cheng4b6abd82010-05-05 18:45:40 +00001847}