blob: f42d47bebda77922bb54ce4ecd3f45915be74e32 [file] [log] [blame]
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001//===-- TwoAddressInstructionPass.cpp - Two-Address instruction pass ------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Evlogimenos71499de2003-12-18 13:06:04 +00007//
8//===----------------------------------------------------------------------===//
9//
Alkis Evlogimenos50c047d2004-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 Evlogimenos14be6402004-02-04 22:17:40 +000019// A op= C
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000020//
Alkis Evlogimenos14be6402004-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 Lattnerbd91c1c2004-01-31 21:07:15 +000027//
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000028//===----------------------------------------------------------------------===//
29
Chris Lattnerbd91c1c2004-01-31 21:07:15 +000030#include "llvm/CodeGen/Passes.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000031#include "llvm/ADT/BitVector.h"
32#include "llvm/ADT/DenseMap.h"
33#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/SmallSet.h"
35#include "llvm/ADT/Statistic.h"
36#include "llvm/Analysis/AliasAnalysis.h"
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +000037#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000038#include "llvm/CodeGen/LiveVariables.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000039#include "llvm/CodeGen/MachineFunctionPass.h"
40#include "llvm/CodeGen/MachineInstr.h"
Bob Wilson852a7e32010-06-15 05:56:31 +000041#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000042#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000043#include "llvm/IR/Function.h"
Evan Cheng2a4410d2011-11-14 19:48:55 +000044#include "llvm/MC/MCInstrItineraries.h"
Andrew Tricke2326ad2013-04-24 15:54:39 +000045#include "llvm/Support/CommandLine.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000046#include "llvm/Support/Debug.h"
47#include "llvm/Support/ErrorHandling.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000048#include "llvm/Target/TargetInstrInfo.h"
49#include "llvm/Target/TargetMachine.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000050#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000051using namespace llvm;
52
Stephen Hinesdce4a402014-05-29 02:49:00 -070053#define DEBUG_TYPE "twoaddrinstr"
54
Chris Lattnercd3245a2006-12-19 22:41:21 +000055STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
56STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
Evan Chengd498c8f2009-01-25 03:53:59 +000057STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
Chris Lattnercd3245a2006-12-19 22:41:21 +000058STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
Evan Cheng875357d2008-03-13 06:37:55 +000059STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
Evan Cheng2a4410d2011-11-14 19:48:55 +000060STATISTIC(NumReSchedUps, "Number of instructions re-scheduled up");
61STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down");
Evan Cheng875357d2008-03-13 06:37:55 +000062
Andrew Tricke2326ad2013-04-24 15:54:39 +000063// Temporary flag to disable rescheduling.
64static cl::opt<bool>
65EnableRescheduling("twoaddr-reschedule",
Evan Chengd4201b62013-05-02 02:07:32 +000066 cl::desc("Coalesce copies by rescheduling (default=true)"),
67 cl::init(true), cl::Hidden);
Andrew Tricke2326ad2013-04-24 15:54:39 +000068
Evan Cheng875357d2008-03-13 06:37:55 +000069namespace {
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000070class TwoAddressInstructionPass : public MachineFunctionPass {
71 MachineFunction *MF;
72 const TargetInstrInfo *TII;
73 const TargetRegisterInfo *TRI;
74 const InstrItineraryData *InstrItins;
75 MachineRegisterInfo *MRI;
76 LiveVariables *LV;
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000077 LiveIntervals *LIS;
78 AliasAnalysis *AA;
79 CodeGenOpt::Level OptLevel;
Evan Cheng875357d2008-03-13 06:37:55 +000080
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +000081 // The current basic block being processed.
82 MachineBasicBlock *MBB;
83
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000084 // DistanceMap - Keep track the distance of a MI from the start of the
85 // current basic block.
86 DenseMap<MachineInstr*, unsigned> DistanceMap;
Evan Cheng870b8072009-03-01 02:03:43 +000087
Jakob Stoklund Olesen002ef572012-10-26 22:06:00 +000088 // Set of already processed instructions in the current block.
89 SmallPtrSet<MachineInstr*, 8> Processed;
90
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000091 // SrcRegMap - A map from virtual registers to physical registers which are
92 // likely targets to be coalesced to due to copies from physical registers to
93 // virtual registers. e.g. v1024 = move r0.
94 DenseMap<unsigned, unsigned> SrcRegMap;
Evan Cheng870b8072009-03-01 02:03:43 +000095
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000096 // DstRegMap - A map from virtual registers to physical registers which are
97 // likely targets to be coalesced to due to copies to physical registers from
98 // virtual registers. e.g. r1 = move v1024.
99 DenseMap<unsigned, unsigned> DstRegMap;
Evan Cheng870b8072009-03-01 02:03:43 +0000100
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000101 bool sink3AddrInstruction(MachineInstr *MI, unsigned Reg,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000102 MachineBasicBlock::iterator OldPos);
Evan Cheng7543e582008-06-18 07:49:14 +0000103
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000104 bool noUseAfterLastDef(unsigned Reg, unsigned Dist, unsigned &LastDef);
Evan Chengd498c8f2009-01-25 03:53:59 +0000105
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000106 bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000107 MachineInstr *MI, unsigned Dist);
Evan Chengd498c8f2009-01-25 03:53:59 +0000108
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000109 bool commuteInstruction(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000110 unsigned RegB, unsigned RegC, unsigned Dist);
Evan Cheng870b8072009-03-01 02:03:43 +0000111
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000112 bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
Evan Chenge6f350d2009-03-30 21:34:07 +0000113
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000114 bool convertInstTo3Addr(MachineBasicBlock::iterator &mi,
115 MachineBasicBlock::iterator &nmi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000116 unsigned RegA, unsigned RegB, unsigned Dist);
Evan Chenge6f350d2009-03-30 21:34:07 +0000117
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000118 bool isDefTooClose(unsigned Reg, unsigned Dist, MachineInstr *MI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000119
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000120 bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000121 MachineBasicBlock::iterator &nmi,
122 unsigned Reg);
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000123 bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000124 MachineBasicBlock::iterator &nmi,
125 unsigned Reg);
126
127 bool tryInstructionTransform(MachineBasicBlock::iterator &mi,
Evan Cheng2a4410d2011-11-14 19:48:55 +0000128 MachineBasicBlock::iterator &nmi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000129 unsigned SrcIdx, unsigned DstIdx,
Cameron Zwarichc5a63492013-02-24 00:27:26 +0000130 unsigned Dist, bool shouldOnlyCommute);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000131
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000132 void scanUses(unsigned DstReg);
Evan Chengf06e6c22011-03-02 01:08:17 +0000133
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000134 void processCopy(MachineInstr *MI);
Bob Wilsoncc80df92009-09-03 20:58:42 +0000135
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000136 typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList;
137 typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap;
138 bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
139 void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +0000140 void eliminateRegSequence(MachineBasicBlock::iterator&);
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +0000141
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000142public:
143 static char ID; // Pass identification, replacement for typeid
144 TwoAddressInstructionPass() : MachineFunctionPass(ID) {
145 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
146 }
Evan Chengc6dcce32010-05-17 23:24:12 +0000147
Stephen Hines36b56882014-04-23 16:57:46 -0700148 void getAnalysisUsage(AnalysisUsage &AU) const override {
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000149 AU.setPreservesCFG();
150 AU.addRequired<AliasAnalysis>();
151 AU.addPreserved<LiveVariables>();
152 AU.addPreserved<SlotIndexes>();
153 AU.addPreserved<LiveIntervals>();
154 AU.addPreservedID(MachineLoopInfoID);
155 AU.addPreservedID(MachineDominatorsID);
156 MachineFunctionPass::getAnalysisUsage(AU);
157 }
Devang Patel794fd752007-05-01 21:15:47 +0000158
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000159 /// runOnMachineFunction - Pass entry point.
Stephen Hines36b56882014-04-23 16:57:46 -0700160 bool runOnMachineFunction(MachineFunction&) override;
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000161};
162} // end anonymous namespace
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000163
Dan Gohman844731a2008-05-13 00:00:25 +0000164char TwoAddressInstructionPass::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000165INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
166 "Two-Address instruction pass", false, false)
167INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
168INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
Owen Andersonce665bd2010-10-07 22:25:06 +0000169 "Two-Address instruction pass", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000170
Owen Anderson90c579d2010-08-06 18:33:48 +0000171char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000172
Cameron Zwarich4c579422013-02-23 04:49:20 +0000173static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg, LiveIntervals *LIS);
174
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000175/// sink3AddrInstruction - A two-address instruction has been converted to a
Evan Cheng875357d2008-03-13 06:37:55 +0000176/// three-address instruction to avoid clobbering a register. Try to sink it
Bill Wendling637980e2008-05-10 00:12:52 +0000177/// past the instruction that would kill the above mentioned register to reduce
178/// register pressure.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000179bool TwoAddressInstructionPass::
180sink3AddrInstruction(MachineInstr *MI, unsigned SavedReg,
181 MachineBasicBlock::iterator OldPos) {
Eli Friedmanbde81d52011-09-23 22:41:57 +0000182 // FIXME: Shouldn't we be trying to do this before we three-addressify the
183 // instruction? After this transformation is done, we no longer need
184 // the instruction to be in three-address form.
185
Evan Cheng875357d2008-03-13 06:37:55 +0000186 // Check if it's safe to move this instruction.
187 bool SeenStore = true; // Be conservative.
Evan Chengac1abde2010-03-02 19:03:01 +0000188 if (!MI->isSafeToMove(TII, AA, SeenStore))
Evan Cheng875357d2008-03-13 06:37:55 +0000189 return false;
190
191 unsigned DefReg = 0;
192 SmallSet<unsigned, 4> UseRegs;
Bill Wendling637980e2008-05-10 00:12:52 +0000193
Evan Cheng875357d2008-03-13 06:37:55 +0000194 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
195 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000196 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000197 continue;
198 unsigned MOReg = MO.getReg();
199 if (!MOReg)
200 continue;
201 if (MO.isUse() && MOReg != SavedReg)
202 UseRegs.insert(MO.getReg());
203 if (!MO.isDef())
204 continue;
205 if (MO.isImplicit())
206 // Don't try to move it if it implicitly defines a register.
207 return false;
208 if (DefReg)
209 // For now, don't move any instructions that define multiple registers.
210 return false;
211 DefReg = MO.getReg();
212 }
213
214 // Find the instruction that kills SavedReg.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700215 MachineInstr *KillMI = nullptr;
Cameron Zwarich4c579422013-02-23 04:49:20 +0000216 if (LIS) {
217 LiveInterval &LI = LIS->getInterval(SavedReg);
218 assert(LI.end() != LI.begin() &&
219 "Reg should not have empty live interval.");
220
221 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
222 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
223 if (I != LI.end() && I->start < MBBEndIdx)
224 return false;
225
226 --I;
227 KillMI = LIS->getInstructionFromIndex(I->end);
228 }
229 if (!KillMI) {
230 for (MachineRegisterInfo::use_nodbg_iterator
231 UI = MRI->use_nodbg_begin(SavedReg),
232 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
Stephen Hines36b56882014-04-23 16:57:46 -0700233 MachineOperand &UseMO = *UI;
Cameron Zwarich4c579422013-02-23 04:49:20 +0000234 if (!UseMO.isKill())
235 continue;
236 KillMI = UseMO.getParent();
237 break;
238 }
Evan Cheng875357d2008-03-13 06:37:55 +0000239 }
Bill Wendling637980e2008-05-10 00:12:52 +0000240
Eli Friedmanbde81d52011-09-23 22:41:57 +0000241 // If we find the instruction that kills SavedReg, and it is in an
242 // appropriate location, we can try to sink the current instruction
243 // past it.
244 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
Jakob Stoklund Olesen988069e2012-08-09 22:08:26 +0000245 KillMI == OldPos || KillMI->isTerminator())
Evan Cheng875357d2008-03-13 06:37:55 +0000246 return false;
247
Bill Wendling637980e2008-05-10 00:12:52 +0000248 // If any of the definitions are used by another instruction between the
249 // position and the kill use, then it's not safe to sink it.
Andrew Trick8247e0d2012-02-03 05:12:30 +0000250 //
Bill Wendling637980e2008-05-10 00:12:52 +0000251 // FIXME: This can be sped up if there is an easy way to query whether an
Evan Cheng7543e582008-06-18 07:49:14 +0000252 // instruction is before or after another instruction. Then we can use
Bill Wendling637980e2008-05-10 00:12:52 +0000253 // MachineRegisterInfo def / use instead.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700254 MachineOperand *KillMO = nullptr;
Evan Cheng875357d2008-03-13 06:37:55 +0000255 MachineBasicBlock::iterator KillPos = KillMI;
256 ++KillPos;
Bill Wendling637980e2008-05-10 00:12:52 +0000257
Evan Cheng7543e582008-06-18 07:49:14 +0000258 unsigned NumVisited = 0;
Stephen Hines36b56882014-04-23 16:57:46 -0700259 for (MachineBasicBlock::iterator I = std::next(OldPos); I != KillPos; ++I) {
Evan Cheng875357d2008-03-13 06:37:55 +0000260 MachineInstr *OtherMI = I;
Dale Johannesen3bfef032010-02-11 18:22:31 +0000261 // DBG_VALUE cannot be counted against the limit.
262 if (OtherMI->isDebugValue())
263 continue;
Evan Cheng7543e582008-06-18 07:49:14 +0000264 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
265 return false;
266 ++NumVisited;
Evan Cheng875357d2008-03-13 06:37:55 +0000267 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
268 MachineOperand &MO = OtherMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000269 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000270 continue;
271 unsigned MOReg = MO.getReg();
272 if (!MOReg)
273 continue;
274 if (DefReg == MOReg)
275 return false;
Bill Wendling637980e2008-05-10 00:12:52 +0000276
Cameron Zwarich4c579422013-02-23 04:49:20 +0000277 if (MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))) {
Evan Cheng875357d2008-03-13 06:37:55 +0000278 if (OtherMI == KillMI && MOReg == SavedReg)
Evan Cheng7543e582008-06-18 07:49:14 +0000279 // Save the operand that kills the register. We want to unset the kill
280 // marker if we can sink MI past it.
Evan Cheng875357d2008-03-13 06:37:55 +0000281 KillMO = &MO;
282 else if (UseRegs.count(MOReg))
283 // One of the uses is killed before the destination.
284 return false;
285 }
286 }
287 }
Jakob Stoklund Olesen988069e2012-08-09 22:08:26 +0000288 assert(KillMO && "Didn't find kill");
Evan Cheng875357d2008-03-13 06:37:55 +0000289
Cameron Zwarich4c579422013-02-23 04:49:20 +0000290 if (!LIS) {
291 // Update kill and LV information.
292 KillMO->setIsKill(false);
293 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
294 KillMO->setIsKill(true);
Andrew Trick8247e0d2012-02-03 05:12:30 +0000295
Cameron Zwarich4c579422013-02-23 04:49:20 +0000296 if (LV)
297 LV->replaceKillInstruction(SavedReg, KillMI, MI);
298 }
Evan Cheng875357d2008-03-13 06:37:55 +0000299
300 // Move instruction to its destination.
301 MBB->remove(MI);
302 MBB->insert(KillPos, MI);
303
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000304 if (LIS)
305 LIS->handleMove(MI);
306
Evan Cheng875357d2008-03-13 06:37:55 +0000307 ++Num3AddrSunk;
308 return true;
309}
310
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000311/// noUseAfterLastDef - Return true if there are no intervening uses between the
Evan Chengd498c8f2009-01-25 03:53:59 +0000312/// last instruction in the MBB that defines the specified register and the
313/// two-address instruction which is being processed. It also returns the last
314/// def location by reference
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000315bool TwoAddressInstructionPass::noUseAfterLastDef(unsigned Reg, unsigned Dist,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000316 unsigned &LastDef) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000317 LastDef = 0;
318 unsigned LastUse = Dist;
Stephen Hines36b56882014-04-23 16:57:46 -0700319 for (MachineOperand &MO : MRI->reg_operands(Reg)) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000320 MachineInstr *MI = MO.getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000321 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesend94998f2010-02-09 02:01:46 +0000322 continue;
Evan Chengd498c8f2009-01-25 03:53:59 +0000323 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
324 if (DI == DistanceMap.end())
325 continue;
326 if (MO.isUse() && DI->second < LastUse)
327 LastUse = DI->second;
328 if (MO.isDef() && DI->second > LastDef)
329 LastDef = DI->second;
330 }
331
332 return !(LastUse > LastDef && LastUse < Dist);
333}
334
Evan Cheng870b8072009-03-01 02:03:43 +0000335/// isCopyToReg - Return true if the specified MI is a copy instruction or
336/// a extract_subreg instruction. It also returns the source and destination
337/// registers and whether they are physical registers by reference.
338static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
339 unsigned &SrcReg, unsigned &DstReg,
340 bool &IsSrcPhys, bool &IsDstPhys) {
341 SrcReg = 0;
342 DstReg = 0;
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000343 if (MI.isCopy()) {
344 DstReg = MI.getOperand(0).getReg();
345 SrcReg = MI.getOperand(1).getReg();
346 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
347 DstReg = MI.getOperand(0).getReg();
348 SrcReg = MI.getOperand(2).getReg();
349 } else
350 return false;
Evan Cheng870b8072009-03-01 02:03:43 +0000351
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000352 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
353 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
354 return true;
Evan Cheng870b8072009-03-01 02:03:43 +0000355}
356
Cameron Zwarich3a9805f2013-02-21 07:02:28 +0000357/// isPLainlyKilled - Test if the given register value, which is used by the
358// given instruction, is killed by the given instruction.
359static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg,
360 LiveIntervals *LIS) {
361 if (LIS && TargetRegisterInfo::isVirtualRegister(Reg) &&
362 !LIS->isNotInMIMap(MI)) {
363 // FIXME: Sometimes tryInstructionTransform() will add instructions and
364 // test whether they can be folded before keeping them. In this case it
365 // sets a kill before recursively calling tryInstructionTransform() again.
366 // If there is no interval available, we assume that this instruction is
367 // one of those. A kill flag is manually inserted on the operand so the
368 // check below will handle it.
369 LiveInterval &LI = LIS->getInterval(Reg);
370 // This is to match the kill flag version where undefs don't have kill
371 // flags.
372 if (!LI.hasAtLeastOneValue())
373 return false;
374
375 SlotIndex useIdx = LIS->getInstructionIndex(MI);
376 LiveInterval::const_iterator I = LI.find(useIdx);
377 assert(I != LI.end() && "Reg must be live-in to use.");
Cameron Zwarichb4bd0222013-02-23 04:49:22 +0000378 return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx);
Cameron Zwarich3a9805f2013-02-21 07:02:28 +0000379 }
380
381 return MI->killsRegister(Reg);
382}
383
Dan Gohman97121ba2009-04-08 00:15:30 +0000384/// isKilled - Test if the given register value, which is used by the given
385/// instruction, is killed by the given instruction. This looks through
386/// coalescable copies to see if the original value is potentially not killed.
387///
388/// For example, in this code:
389///
390/// %reg1034 = copy %reg1024
391/// %reg1035 = copy %reg1025<kill>
392/// %reg1036 = add %reg1034<kill>, %reg1035<kill>
393///
394/// %reg1034 is not considered to be killed, since it is copied from a
395/// register which is not killed. Treating it as not killed lets the
396/// normal heuristics commute the (two-address) add, which lets
397/// coalescing eliminate the extra copy.
398///
Cameron Zwaricha931a122013-02-21 22:58:42 +0000399/// If allowFalsePositives is true then likely kills are treated as kills even
400/// if it can't be proven that they are kills.
Dan Gohman97121ba2009-04-08 00:15:30 +0000401static bool isKilled(MachineInstr &MI, unsigned Reg,
402 const MachineRegisterInfo *MRI,
Cameron Zwarich214df422013-02-21 04:33:02 +0000403 const TargetInstrInfo *TII,
Cameron Zwaricha931a122013-02-21 22:58:42 +0000404 LiveIntervals *LIS,
405 bool allowFalsePositives) {
Dan Gohman97121ba2009-04-08 00:15:30 +0000406 MachineInstr *DefMI = &MI;
407 for (;;) {
Cameron Zwaricha931a122013-02-21 22:58:42 +0000408 // All uses of physical registers are likely to be kills.
409 if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
410 (allowFalsePositives || MRI->hasOneUse(Reg)))
411 return true;
Cameron Zwarich3a9805f2013-02-21 07:02:28 +0000412 if (!isPlainlyKilled(DefMI, Reg, LIS))
Dan Gohman97121ba2009-04-08 00:15:30 +0000413 return false;
414 if (TargetRegisterInfo::isPhysicalRegister(Reg))
415 return true;
416 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
417 // If there are multiple defs, we can't do a simple analysis, so just
418 // go with what the kill flag says.
Stephen Hines36b56882014-04-23 16:57:46 -0700419 if (std::next(Begin) != MRI->def_end())
Dan Gohman97121ba2009-04-08 00:15:30 +0000420 return true;
Stephen Hines36b56882014-04-23 16:57:46 -0700421 DefMI = Begin->getParent();
Dan Gohman97121ba2009-04-08 00:15:30 +0000422 bool IsSrcPhys, IsDstPhys;
423 unsigned SrcReg, DstReg;
424 // If the def is something other than a copy, then it isn't going to
425 // be coalesced, so follow the kill flag.
426 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
427 return true;
428 Reg = SrcReg;
429 }
430}
431
Evan Cheng870b8072009-03-01 02:03:43 +0000432/// isTwoAddrUse - Return true if the specified MI uses the specified register
433/// as a two-address use. If so, return the destination register by reference.
434static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
Evan Chengd4201b62013-05-02 02:07:32 +0000435 for (unsigned i = 0, NumOps = MI.getNumOperands(); i != NumOps; ++i) {
Evan Cheng870b8072009-03-01 02:03:43 +0000436 const MachineOperand &MO = MI.getOperand(i);
437 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
438 continue;
Evan Chenga24752f2009-03-19 20:30:06 +0000439 unsigned ti;
440 if (MI.isRegTiedToDefOperand(i, &ti)) {
Evan Cheng870b8072009-03-01 02:03:43 +0000441 DstReg = MI.getOperand(ti).getReg();
442 return true;
443 }
444 }
445 return false;
446}
447
448/// findOnlyInterestingUse - Given a register, if has a single in-basic block
449/// use, return the use instruction if it's a copy or a two-address use.
450static
451MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
452 MachineRegisterInfo *MRI,
453 const TargetInstrInfo *TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000454 bool &IsCopy,
Evan Cheng870b8072009-03-01 02:03:43 +0000455 unsigned &DstReg, bool &IsDstPhys) {
Evan Cheng1423c702010-03-03 21:18:38 +0000456 if (!MRI->hasOneNonDBGUse(Reg))
457 // None or more than one use.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700458 return nullptr;
Stephen Hines36b56882014-04-23 16:57:46 -0700459 MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(Reg);
Evan Cheng870b8072009-03-01 02:03:43 +0000460 if (UseMI.getParent() != MBB)
Stephen Hinesdce4a402014-05-29 02:49:00 -0700461 return nullptr;
Evan Cheng870b8072009-03-01 02:03:43 +0000462 unsigned SrcReg;
463 bool IsSrcPhys;
Evan Cheng87d696a2009-04-14 00:32:25 +0000464 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
465 IsCopy = true;
Evan Cheng870b8072009-03-01 02:03:43 +0000466 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000467 }
Evan Cheng870b8072009-03-01 02:03:43 +0000468 IsDstPhys = false;
Evan Cheng87d696a2009-04-14 00:32:25 +0000469 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
470 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng870b8072009-03-01 02:03:43 +0000471 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000472 }
Stephen Hinesdce4a402014-05-29 02:49:00 -0700473 return nullptr;
Evan Cheng870b8072009-03-01 02:03:43 +0000474}
475
476/// getMappedReg - Return the physical register the specified virtual register
477/// might be mapped to.
478static unsigned
479getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
480 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
481 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
482 if (SI == RegMap.end())
483 return 0;
484 Reg = SI->second;
485 }
486 if (TargetRegisterInfo::isPhysicalRegister(Reg))
487 return Reg;
488 return 0;
489}
490
491/// regsAreCompatible - Return true if the two registers are equal or aliased.
492///
493static bool
494regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
495 if (RegA == RegB)
496 return true;
497 if (!RegA || !RegB)
498 return false;
499 return TRI->regsOverlap(RegA, RegB);
500}
501
502
Manman Rend68e8cd2012-07-25 18:28:13 +0000503/// isProfitableToCommute - Return true if it's potentially profitable to commute
Evan Chengd498c8f2009-01-25 03:53:59 +0000504/// the two-address instruction that's being processed.
505bool
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000506TwoAddressInstructionPass::
507isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
508 MachineInstr *MI, unsigned Dist) {
Evan Chengc3aa7c52011-11-16 18:44:48 +0000509 if (OptLevel == CodeGenOpt::None)
510 return false;
511
Evan Chengd498c8f2009-01-25 03:53:59 +0000512 // Determine if it's profitable to commute this two address instruction. In
513 // general, we want no uses between this instruction and the definition of
514 // the two-address register.
515 // e.g.
516 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
517 // %reg1029<def> = MOV8rr %reg1028
518 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
519 // insert => %reg1030<def> = MOV8rr %reg1028
520 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
521 // In this case, it might not be possible to coalesce the second MOV8rr
522 // instruction if the first one is coalesced. So it would be profitable to
523 // commute it:
524 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
525 // %reg1029<def> = MOV8rr %reg1028
526 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
527 // insert => %reg1030<def> = MOV8rr %reg1029
Andrew Trick8247e0d2012-02-03 05:12:30 +0000528 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
Evan Chengd498c8f2009-01-25 03:53:59 +0000529
Cameron Zwarich17cec5a2013-02-21 07:02:30 +0000530 if (!isPlainlyKilled(MI, regC, LIS))
Evan Chengd498c8f2009-01-25 03:53:59 +0000531 return false;
532
533 // Ok, we have something like:
534 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
535 // let's see if it's worth commuting it.
536
Evan Cheng870b8072009-03-01 02:03:43 +0000537 // Look for situations like this:
538 // %reg1024<def> = MOV r1
539 // %reg1025<def> = MOV r0
540 // %reg1026<def> = ADD %reg1024, %reg1025
541 // r0 = MOV %reg1026
542 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
Evan Chengd99d68b2012-05-03 01:45:13 +0000543 unsigned ToRegA = getMappedReg(regA, DstRegMap);
544 if (ToRegA) {
545 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
546 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
547 bool BComp = !FromRegB || regsAreCompatible(FromRegB, ToRegA, TRI);
548 bool CComp = !FromRegC || regsAreCompatible(FromRegC, ToRegA, TRI);
549 if (BComp != CComp)
550 return !BComp && CComp;
551 }
Evan Cheng870b8072009-03-01 02:03:43 +0000552
Evan Chengd498c8f2009-01-25 03:53:59 +0000553 // If there is a use of regC between its last def (could be livein) and this
554 // instruction, then bail.
555 unsigned LastDefC = 0;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000556 if (!noUseAfterLastDef(regC, Dist, LastDefC))
Evan Chengd498c8f2009-01-25 03:53:59 +0000557 return false;
558
559 // If there is a use of regB between its last def (could be livein) and this
560 // instruction, then go ahead and make this transformation.
561 unsigned LastDefB = 0;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000562 if (!noUseAfterLastDef(regB, Dist, LastDefB))
Evan Chengd498c8f2009-01-25 03:53:59 +0000563 return true;
564
565 // Since there are no intervening uses for both registers, then commute
566 // if the def of regC is closer. Its live interval is shorter.
567 return LastDefB && LastDefC && LastDefC > LastDefB;
568}
569
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000570/// commuteInstruction - Commute a two-address instruction and update the basic
Evan Cheng81913712009-01-23 23:27:33 +0000571/// block, distance map, and live variables if needed. Return true if it is
572/// successful.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000573bool TwoAddressInstructionPass::
574commuteInstruction(MachineBasicBlock::iterator &mi,
575 unsigned RegB, unsigned RegC, unsigned Dist) {
Evan Cheng81913712009-01-23 23:27:33 +0000576 MachineInstr *MI = mi;
David Greeneeb00b182010-01-05 01:24:21 +0000577 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
Evan Cheng81913712009-01-23 23:27:33 +0000578 MachineInstr *NewMI = TII->commuteInstruction(MI);
579
Stephen Hinesdce4a402014-05-29 02:49:00 -0700580 if (NewMI == nullptr) {
David Greeneeb00b182010-01-05 01:24:21 +0000581 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
Evan Cheng81913712009-01-23 23:27:33 +0000582 return false;
583 }
584
David Greeneeb00b182010-01-05 01:24:21 +0000585 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
Cameron Zwarich1ea93c72013-02-23 23:13:28 +0000586 assert(NewMI == MI &&
587 "TargetInstrInfo::commuteInstruction() should not return a new "
588 "instruction unless it was requested.");
Evan Cheng870b8072009-03-01 02:03:43 +0000589
590 // Update source register map.
591 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
592 if (FromRegC) {
593 unsigned RegA = MI->getOperand(0).getReg();
594 SrcRegMap[RegA] = FromRegC;
595 }
596
Evan Cheng81913712009-01-23 23:27:33 +0000597 return true;
598}
599
Evan Chenge6f350d2009-03-30 21:34:07 +0000600/// isProfitableToConv3Addr - Return true if it is profitable to convert the
601/// given 2-address instruction to a 3-address one.
602bool
Evan Chengf06e6c22011-03-02 01:08:17 +0000603TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
Evan Chenge6f350d2009-03-30 21:34:07 +0000604 // Look for situations like this:
605 // %reg1024<def> = MOV r1
606 // %reg1025<def> = MOV r0
607 // %reg1026<def> = ADD %reg1024, %reg1025
608 // r2 = MOV %reg1026
609 // Turn ADD into a 3-address instruction to avoid a copy.
Evan Chengf06e6c22011-03-02 01:08:17 +0000610 unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
611 if (!FromRegB)
612 return false;
Evan Chenge6f350d2009-03-30 21:34:07 +0000613 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
Evan Chengf06e6c22011-03-02 01:08:17 +0000614 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
Evan Chenge6f350d2009-03-30 21:34:07 +0000615}
616
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000617/// convertInstTo3Addr - Convert the specified two-address instruction into a
Evan Chenge6f350d2009-03-30 21:34:07 +0000618/// three address one. Return true if this transformation was successful.
619bool
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000620TwoAddressInstructionPass::convertInstTo3Addr(MachineBasicBlock::iterator &mi,
Evan Chenge6f350d2009-03-30 21:34:07 +0000621 MachineBasicBlock::iterator &nmi,
Evan Cheng4d96c632011-02-10 02:20:55 +0000622 unsigned RegA, unsigned RegB,
623 unsigned Dist) {
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000624 // FIXME: Why does convertToThreeAddress() need an iterator reference?
625 MachineFunction::iterator MFI = MBB;
626 MachineInstr *NewMI = TII->convertToThreeAddress(MFI, mi, LV);
627 assert(MBB == MFI && "convertToThreeAddress changed iterator reference");
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000628 if (!NewMI)
629 return false;
Evan Chenge6f350d2009-03-30 21:34:07 +0000630
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000631 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
632 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
633 bool Sunk = false;
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000634
Cameron Zwarich61892882013-02-20 22:10:02 +0000635 if (LIS)
636 LIS->ReplaceMachineInstrInMaps(mi, NewMI);
Evan Chenge6f350d2009-03-30 21:34:07 +0000637
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000638 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
639 // FIXME: Temporary workaround. If the new instruction doesn't
640 // uses RegB, convertToThreeAddress must have created more
641 // then one instruction.
642 Sunk = sink3AddrInstruction(NewMI, RegB, mi);
Evan Chenge6f350d2009-03-30 21:34:07 +0000643
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000644 MBB->erase(mi); // Nuke the old inst.
Evan Cheng4d96c632011-02-10 02:20:55 +0000645
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000646 if (!Sunk) {
647 DistanceMap.insert(std::make_pair(NewMI, Dist));
648 mi = NewMI;
Stephen Hines36b56882014-04-23 16:57:46 -0700649 nmi = std::next(mi);
Evan Chenge6f350d2009-03-30 21:34:07 +0000650 }
651
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000652 // Update source and destination register maps.
653 SrcRegMap.erase(RegA);
654 DstRegMap.erase(RegB);
655 return true;
Evan Chenge6f350d2009-03-30 21:34:07 +0000656}
657
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000658/// scanUses - Scan forward recursively for only uses, update maps if the use
Evan Chengf06e6c22011-03-02 01:08:17 +0000659/// is a copy or a two-address instruction.
660void
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000661TwoAddressInstructionPass::scanUses(unsigned DstReg) {
Evan Chengf06e6c22011-03-02 01:08:17 +0000662 SmallVector<unsigned, 4> VirtRegPairs;
663 bool IsDstPhys;
664 bool IsCopy = false;
665 unsigned NewReg = 0;
666 unsigned Reg = DstReg;
667 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
668 NewReg, IsDstPhys)) {
669 if (IsCopy && !Processed.insert(UseMI))
670 break;
671
672 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
673 if (DI != DistanceMap.end())
674 // Earlier in the same MBB.Reached via a back edge.
675 break;
676
677 if (IsDstPhys) {
678 VirtRegPairs.push_back(NewReg);
679 break;
680 }
681 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
682 if (!isNew)
683 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
684 VirtRegPairs.push_back(NewReg);
685 Reg = NewReg;
686 }
687
688 if (!VirtRegPairs.empty()) {
689 unsigned ToReg = VirtRegPairs.back();
690 VirtRegPairs.pop_back();
691 while (!VirtRegPairs.empty()) {
692 unsigned FromReg = VirtRegPairs.back();
693 VirtRegPairs.pop_back();
694 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
695 if (!isNew)
696 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
697 ToReg = FromReg;
698 }
699 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
700 if (!isNew)
701 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
702 }
703}
704
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000705/// processCopy - If the specified instruction is not yet processed, process it
Evan Cheng870b8072009-03-01 02:03:43 +0000706/// if it's a copy. For a copy instruction, we find the physical registers the
707/// source and destination registers might be mapped to. These are kept in
708/// point-to maps used to determine future optimizations. e.g.
709/// v1024 = mov r0
710/// v1025 = mov r1
711/// v1026 = add v1024, v1025
712/// r1 = mov r1026
713/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
714/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
715/// potentially joined with r1 on the output side. It's worthwhile to commute
716/// 'add' to eliminate a copy.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000717void TwoAddressInstructionPass::processCopy(MachineInstr *MI) {
Evan Cheng870b8072009-03-01 02:03:43 +0000718 if (Processed.count(MI))
719 return;
720
721 bool IsSrcPhys, IsDstPhys;
722 unsigned SrcReg, DstReg;
723 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
724 return;
725
726 if (IsDstPhys && !IsSrcPhys)
727 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
728 else if (!IsDstPhys && IsSrcPhys) {
Evan Cheng3005ed62009-04-13 20:04:24 +0000729 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
730 if (!isNew)
731 assert(SrcRegMap[DstReg] == SrcReg &&
732 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000733
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000734 scanUses(DstReg);
Evan Cheng870b8072009-03-01 02:03:43 +0000735 }
736
737 Processed.insert(MI);
Evan Chengf06e6c22011-03-02 01:08:17 +0000738 return;
Evan Cheng870b8072009-03-01 02:03:43 +0000739}
740
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000741/// rescheduleMIBelowKill - If there is one more local instruction that reads
Evan Cheng2a4410d2011-11-14 19:48:55 +0000742/// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
743/// instruction in order to eliminate the need for the copy.
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000744bool TwoAddressInstructionPass::
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000745rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000746 MachineBasicBlock::iterator &nmi,
747 unsigned Reg) {
Cameron Zwarich80885e52013-02-23 04:49:13 +0000748 // Bail immediately if we don't have LV or LIS available. We use them to find
749 // kills efficiently.
750 if (!LV && !LIS)
Chandler Carruth7d532c82012-07-15 03:29:46 +0000751 return false;
752
Evan Cheng2a4410d2011-11-14 19:48:55 +0000753 MachineInstr *MI = &*mi;
Andrew Trick8247e0d2012-02-03 05:12:30 +0000754 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000755 if (DI == DistanceMap.end())
756 // Must be created from unfolded load. Don't waste time trying this.
757 return false;
758
Stephen Hinesdce4a402014-05-29 02:49:00 -0700759 MachineInstr *KillMI = nullptr;
Cameron Zwarich80885e52013-02-23 04:49:13 +0000760 if (LIS) {
761 LiveInterval &LI = LIS->getInterval(Reg);
762 assert(LI.end() != LI.begin() &&
763 "Reg should not have empty live interval.");
764
765 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
766 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
767 if (I != LI.end() && I->start < MBBEndIdx)
768 return false;
769
770 --I;
771 KillMI = LIS->getInstructionFromIndex(I->end);
772 } else {
773 KillMI = LV->getVarInfo(Reg).findKill(MBB);
774 }
Chandler Carruth7d532c82012-07-15 03:29:46 +0000775 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000776 // Don't mess with copies, they may be coalesced later.
777 return false;
778
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000779 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
780 KillMI->isBranch() || KillMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000781 // Don't move pass calls, etc.
782 return false;
783
784 unsigned DstReg;
785 if (isTwoAddrUse(*KillMI, Reg, DstReg))
786 return false;
787
Evan Chengf1784182011-11-15 06:26:51 +0000788 bool SeenStore = true;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000789 if (!MI->isSafeToMove(TII, AA, SeenStore))
790 return false;
791
792 if (TII->getInstrLatency(InstrItins, MI) > 1)
793 // FIXME: Needs more sophisticated heuristics.
794 return false;
795
796 SmallSet<unsigned, 2> Uses;
Evan Cheng9bad88a2011-11-16 03:47:42 +0000797 SmallSet<unsigned, 2> Kills;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000798 SmallSet<unsigned, 2> Defs;
799 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
800 const MachineOperand &MO = MI->getOperand(i);
801 if (!MO.isReg())
802 continue;
803 unsigned MOReg = MO.getReg();
804 if (!MOReg)
805 continue;
806 if (MO.isDef())
807 Defs.insert(MOReg);
Evan Cheng9bad88a2011-11-16 03:47:42 +0000808 else {
Evan Cheng2a4410d2011-11-14 19:48:55 +0000809 Uses.insert(MOReg);
Cameron Zwarich80885e52013-02-23 04:49:13 +0000810 if (MOReg != Reg && (MO.isKill() ||
811 (LIS && isPlainlyKilled(MI, MOReg, LIS))))
Evan Cheng9bad88a2011-11-16 03:47:42 +0000812 Kills.insert(MOReg);
813 }
Evan Cheng2a4410d2011-11-14 19:48:55 +0000814 }
815
816 // Move the copies connected to MI down as well.
Cameron Zwarich80885e52013-02-23 04:49:13 +0000817 MachineBasicBlock::iterator Begin = MI;
Stephen Hines36b56882014-04-23 16:57:46 -0700818 MachineBasicBlock::iterator AfterMI = std::next(Begin);
Cameron Zwarich80885e52013-02-23 04:49:13 +0000819
820 MachineBasicBlock::iterator End = AfterMI;
821 while (End->isCopy() && Defs.count(End->getOperand(1).getReg())) {
822 Defs.insert(End->getOperand(0).getReg());
823 ++End;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000824 }
825
826 // Check if the reschedule will not break depedencies.
827 unsigned NumVisited = 0;
828 MachineBasicBlock::iterator KillPos = KillMI;
829 ++KillPos;
Cameron Zwarich80885e52013-02-23 04:49:13 +0000830 for (MachineBasicBlock::iterator I = End; I != KillPos; ++I) {
Evan Cheng2a4410d2011-11-14 19:48:55 +0000831 MachineInstr *OtherMI = I;
832 // DBG_VALUE cannot be counted against the limit.
833 if (OtherMI->isDebugValue())
834 continue;
835 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
836 return false;
837 ++NumVisited;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000838 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
839 OtherMI->isBranch() || OtherMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000840 // Don't move pass calls, etc.
841 return false;
842 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
843 const MachineOperand &MO = OtherMI->getOperand(i);
844 if (!MO.isReg())
845 continue;
846 unsigned MOReg = MO.getReg();
847 if (!MOReg)
848 continue;
849 if (MO.isDef()) {
850 if (Uses.count(MOReg))
851 // Physical register use would be clobbered.
852 return false;
853 if (!MO.isDead() && Defs.count(MOReg))
854 // May clobber a physical register def.
855 // FIXME: This may be too conservative. It's ok if the instruction
856 // is sunken completely below the use.
857 return false;
858 } else {
859 if (Defs.count(MOReg))
860 return false;
Cameron Zwarich80885e52013-02-23 04:49:13 +0000861 bool isKill = MO.isKill() ||
862 (LIS && isPlainlyKilled(OtherMI, MOReg, LIS));
Evan Cheng9bad88a2011-11-16 03:47:42 +0000863 if (MOReg != Reg &&
Cameron Zwarich80885e52013-02-23 04:49:13 +0000864 ((isKill && Uses.count(MOReg)) || Kills.count(MOReg)))
Evan Cheng2a4410d2011-11-14 19:48:55 +0000865 // Don't want to extend other live ranges and update kills.
866 return false;
Cameron Zwarich80885e52013-02-23 04:49:13 +0000867 if (MOReg == Reg && !isKill)
Chandler Carruth7d532c82012-07-15 03:29:46 +0000868 // We can't schedule across a use of the register in question.
869 return false;
870 // Ensure that if this is register in question, its the kill we expect.
871 assert((MOReg != Reg || OtherMI == KillMI) &&
872 "Found multiple kills of a register in a basic block");
Evan Cheng2a4410d2011-11-14 19:48:55 +0000873 }
874 }
875 }
876
877 // Move debug info as well.
Stephen Hines36b56882014-04-23 16:57:46 -0700878 while (Begin != MBB->begin() && std::prev(Begin)->isDebugValue())
Cameron Zwarich80885e52013-02-23 04:49:13 +0000879 --Begin;
880
881 nmi = End;
882 MachineBasicBlock::iterator InsertPos = KillPos;
883 if (LIS) {
884 // We have to move the copies first so that the MBB is still well-formed
885 // when calling handleMove().
886 for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) {
887 MachineInstr *CopyMI = MBBI;
888 ++MBBI;
889 MBB->splice(InsertPos, MBB, CopyMI);
890 LIS->handleMove(CopyMI);
891 InsertPos = CopyMI;
892 }
Stephen Hines36b56882014-04-23 16:57:46 -0700893 End = std::next(MachineBasicBlock::iterator(MI));
Cameron Zwarich80885e52013-02-23 04:49:13 +0000894 }
Evan Cheng2a4410d2011-11-14 19:48:55 +0000895
896 // Copies following MI may have been moved as well.
Cameron Zwarich80885e52013-02-23 04:49:13 +0000897 MBB->splice(InsertPos, MBB, Begin, End);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000898 DistanceMap.erase(DI);
899
Chandler Carruth7d532c82012-07-15 03:29:46 +0000900 // Update live variables
Cameron Zwarich80885e52013-02-23 04:49:13 +0000901 if (LIS) {
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000902 LIS->handleMove(MI);
Cameron Zwarich80885e52013-02-23 04:49:13 +0000903 } else {
904 LV->removeVirtualRegisterKilled(Reg, KillMI);
905 LV->addVirtualRegisterKilled(Reg, MI);
906 }
Evan Cheng2a4410d2011-11-14 19:48:55 +0000907
Jakob Stoklund Olesena532bce2012-07-17 17:57:23 +0000908 DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000909 return true;
910}
911
912/// isDefTooClose - Return true if the re-scheduling will put the given
913/// instruction too close to the defs of its register dependencies.
914bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000915 MachineInstr *MI) {
Stephen Hines36b56882014-04-23 16:57:46 -0700916 for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
917 if (DefMI.getParent() != MBB || DefMI.isCopy() || DefMI.isCopyLike())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000918 continue;
Stephen Hines36b56882014-04-23 16:57:46 -0700919 if (&DefMI == MI)
Evan Cheng2a4410d2011-11-14 19:48:55 +0000920 return true; // MI is defining something KillMI uses
Stephen Hines36b56882014-04-23 16:57:46 -0700921 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(&DefMI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000922 if (DDI == DistanceMap.end())
923 return true; // Below MI
924 unsigned DefDist = DDI->second;
925 assert(Dist > DefDist && "Visited def already?");
Stephen Hines36b56882014-04-23 16:57:46 -0700926 if (TII->getInstrLatency(InstrItins, &DefMI) > (Dist - DefDist))
Evan Cheng2a4410d2011-11-14 19:48:55 +0000927 return true;
928 }
929 return false;
930}
931
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000932/// rescheduleKillAboveMI - If there is one more local instruction that reads
Evan Cheng2a4410d2011-11-14 19:48:55 +0000933/// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
934/// current two-address instruction in order to eliminate the need for the
935/// copy.
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000936bool TwoAddressInstructionPass::
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000937rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000938 MachineBasicBlock::iterator &nmi,
939 unsigned Reg) {
Cameron Zwarich80885e52013-02-23 04:49:13 +0000940 // Bail immediately if we don't have LV or LIS available. We use them to find
941 // kills efficiently.
942 if (!LV && !LIS)
Chandler Carruth7d532c82012-07-15 03:29:46 +0000943 return false;
944
Evan Cheng2a4410d2011-11-14 19:48:55 +0000945 MachineInstr *MI = &*mi;
946 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
947 if (DI == DistanceMap.end())
948 // Must be created from unfolded load. Don't waste time trying this.
949 return false;
950
Stephen Hinesdce4a402014-05-29 02:49:00 -0700951 MachineInstr *KillMI = nullptr;
Cameron Zwarich80885e52013-02-23 04:49:13 +0000952 if (LIS) {
953 LiveInterval &LI = LIS->getInterval(Reg);
954 assert(LI.end() != LI.begin() &&
955 "Reg should not have empty live interval.");
956
957 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
958 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
959 if (I != LI.end() && I->start < MBBEndIdx)
960 return false;
961
962 --I;
963 KillMI = LIS->getInstructionFromIndex(I->end);
964 } else {
965 KillMI = LV->getVarInfo(Reg).findKill(MBB);
966 }
Chandler Carruth7d532c82012-07-15 03:29:46 +0000967 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000968 // Don't mess with copies, they may be coalesced later.
969 return false;
970
971 unsigned DstReg;
972 if (isTwoAddrUse(*KillMI, Reg, DstReg))
973 return false;
974
Evan Chengf1784182011-11-15 06:26:51 +0000975 bool SeenStore = true;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000976 if (!KillMI->isSafeToMove(TII, AA, SeenStore))
977 return false;
978
979 SmallSet<unsigned, 2> Uses;
980 SmallSet<unsigned, 2> Kills;
981 SmallSet<unsigned, 2> Defs;
982 SmallSet<unsigned, 2> LiveDefs;
983 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
984 const MachineOperand &MO = KillMI->getOperand(i);
985 if (!MO.isReg())
986 continue;
987 unsigned MOReg = MO.getReg();
988 if (MO.isUse()) {
989 if (!MOReg)
990 continue;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000991 if (isDefTooClose(MOReg, DI->second, MI))
Evan Cheng2a4410d2011-11-14 19:48:55 +0000992 return false;
Cameron Zwarich80885e52013-02-23 04:49:13 +0000993 bool isKill = MO.isKill() || (LIS && isPlainlyKilled(KillMI, MOReg, LIS));
994 if (MOReg == Reg && !isKill)
Chandler Carruth7d532c82012-07-15 03:29:46 +0000995 return false;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000996 Uses.insert(MOReg);
Cameron Zwarich80885e52013-02-23 04:49:13 +0000997 if (isKill && MOReg != Reg)
Evan Cheng2a4410d2011-11-14 19:48:55 +0000998 Kills.insert(MOReg);
999 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1000 Defs.insert(MOReg);
1001 if (!MO.isDead())
1002 LiveDefs.insert(MOReg);
1003 }
1004 }
1005
1006 // Check if the reschedule will not break depedencies.
1007 unsigned NumVisited = 0;
1008 MachineBasicBlock::iterator KillPos = KillMI;
1009 for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
1010 MachineInstr *OtherMI = I;
1011 // DBG_VALUE cannot be counted against the limit.
1012 if (OtherMI->isDebugValue())
1013 continue;
1014 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
1015 return false;
1016 ++NumVisited;
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001017 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
1018 OtherMI->isBranch() || OtherMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +00001019 // Don't move pass calls, etc.
1020 return false;
Evan Chengae7db7a2011-11-16 03:05:12 +00001021 SmallVector<unsigned, 2> OtherDefs;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001022 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
1023 const MachineOperand &MO = OtherMI->getOperand(i);
1024 if (!MO.isReg())
1025 continue;
1026 unsigned MOReg = MO.getReg();
1027 if (!MOReg)
1028 continue;
1029 if (MO.isUse()) {
1030 if (Defs.count(MOReg))
1031 // Moving KillMI can clobber the physical register if the def has
1032 // not been seen.
1033 return false;
1034 if (Kills.count(MOReg))
1035 // Don't want to extend other live ranges and update kills.
1036 return false;
Cameron Zwarich80885e52013-02-23 04:49:13 +00001037 if (OtherMI != MI && MOReg == Reg &&
1038 !(MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))))
Chandler Carruth7d532c82012-07-15 03:29:46 +00001039 // We can't schedule across a use of the register in question.
1040 return false;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001041 } else {
Evan Chengae7db7a2011-11-16 03:05:12 +00001042 OtherDefs.push_back(MOReg);
Evan Cheng2a4410d2011-11-14 19:48:55 +00001043 }
1044 }
Evan Chengae7db7a2011-11-16 03:05:12 +00001045
1046 for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
1047 unsigned MOReg = OtherDefs[i];
1048 if (Uses.count(MOReg))
1049 return false;
1050 if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1051 LiveDefs.count(MOReg))
1052 return false;
1053 // Physical register def is seen.
1054 Defs.erase(MOReg);
1055 }
Evan Cheng2a4410d2011-11-14 19:48:55 +00001056 }
1057
1058 // Move the old kill above MI, don't forget to move debug info as well.
1059 MachineBasicBlock::iterator InsertPos = mi;
Stephen Hines36b56882014-04-23 16:57:46 -07001060 while (InsertPos != MBB->begin() && std::prev(InsertPos)->isDebugValue())
Evan Cheng8aee7d82011-11-14 21:11:15 +00001061 --InsertPos;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001062 MachineBasicBlock::iterator From = KillMI;
Stephen Hines36b56882014-04-23 16:57:46 -07001063 MachineBasicBlock::iterator To = std::next(From);
1064 while (std::prev(From)->isDebugValue())
Evan Cheng2a4410d2011-11-14 19:48:55 +00001065 --From;
1066 MBB->splice(InsertPos, MBB, From, To);
1067
Stephen Hines36b56882014-04-23 16:57:46 -07001068 nmi = std::prev(InsertPos); // Backtrack so we process the moved instr.
Evan Cheng2a4410d2011-11-14 19:48:55 +00001069 DistanceMap.erase(DI);
1070
Chandler Carruth7d532c82012-07-15 03:29:46 +00001071 // Update live variables
Cameron Zwarich80885e52013-02-23 04:49:13 +00001072 if (LIS) {
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +00001073 LIS->handleMove(KillMI);
Cameron Zwarich80885e52013-02-23 04:49:13 +00001074 } else {
1075 LV->removeVirtualRegisterKilled(Reg, KillMI);
1076 LV->addVirtualRegisterKilled(Reg, MI);
1077 }
Chandler Carruth7d532c82012-07-15 03:29:46 +00001078
Jakob Stoklund Olesena532bce2012-07-17 17:57:23 +00001079 DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
Evan Cheng2a4410d2011-11-14 19:48:55 +00001080 return true;
1081}
1082
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001083/// tryInstructionTransform - For the case where an instruction has a single
Bob Wilsoncc80df92009-09-03 20:58:42 +00001084/// pair of tied register operands, attempt some transformations that may
1085/// either eliminate the tied operands or improve the opportunities for
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001086/// coalescing away the register copy. Returns true if no copy needs to be
1087/// inserted to untie mi's operands (either because they were untied, or
Cameron Zwarichc5a63492013-02-24 00:27:26 +00001088/// because mi was rescheduled, and will be visited again later). If the
1089/// shouldOnlyCommute flag is true, only instruction commutation is attempted.
Bob Wilsoncc80df92009-09-03 20:58:42 +00001090bool TwoAddressInstructionPass::
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001091tryInstructionTransform(MachineBasicBlock::iterator &mi,
Bob Wilsoncc80df92009-09-03 20:58:42 +00001092 MachineBasicBlock::iterator &nmi,
Cameron Zwarichc5a63492013-02-24 00:27:26 +00001093 unsigned SrcIdx, unsigned DstIdx,
1094 unsigned Dist, bool shouldOnlyCommute) {
Evan Chengc3aa7c52011-11-16 18:44:48 +00001095 if (OptLevel == CodeGenOpt::None)
1096 return false;
1097
Evan Cheng2a4410d2011-11-14 19:48:55 +00001098 MachineInstr &MI = *mi;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001099 unsigned regA = MI.getOperand(DstIdx).getReg();
1100 unsigned regB = MI.getOperand(SrcIdx).getReg();
Bob Wilsoncc80df92009-09-03 20:58:42 +00001101
1102 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1103 "cannot make instruction into two-address form");
Cameron Zwaricha931a122013-02-21 22:58:42 +00001104 bool regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
Bob Wilsoncc80df92009-09-03 20:58:42 +00001105
Evan Chengd99d68b2012-05-03 01:45:13 +00001106 if (TargetRegisterInfo::isVirtualRegister(regA))
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001107 scanUses(regA);
Evan Chengd99d68b2012-05-03 01:45:13 +00001108
Bob Wilsoncc80df92009-09-03 20:58:42 +00001109 // Check if it is profitable to commute the operands.
1110 unsigned SrcOp1, SrcOp2;
1111 unsigned regC = 0;
1112 unsigned regCIdx = ~0U;
1113 bool TryCommute = false;
1114 bool AggressiveCommute = false;
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001115 if (MI.isCommutable() && MI.getNumOperands() >= 3 &&
Evan Cheng2a4410d2011-11-14 19:48:55 +00001116 TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001117 if (SrcIdx == SrcOp1)
1118 regCIdx = SrcOp2;
1119 else if (SrcIdx == SrcOp2)
1120 regCIdx = SrcOp1;
1121
1122 if (regCIdx != ~0U) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001123 regC = MI.getOperand(regCIdx).getReg();
Cameron Zwaricha931a122013-02-21 22:58:42 +00001124 if (!regBKilled && isKilled(MI, regC, MRI, TII, LIS, false))
Bob Wilsoncc80df92009-09-03 20:58:42 +00001125 // If C dies but B does not, swap the B and C operands.
1126 // This makes the live ranges of A and C joinable.
1127 TryCommute = true;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001128 else if (isProfitableToCommute(regA, regB, regC, &MI, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001129 TryCommute = true;
1130 AggressiveCommute = true;
1131 }
1132 }
1133 }
1134
1135 // If it's profitable to commute, try to do so.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001136 if (TryCommute && commuteInstruction(mi, regB, regC, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001137 ++NumCommuted;
1138 if (AggressiveCommute)
1139 ++NumAggrCommuted;
1140 return false;
1141 }
1142
Cameron Zwarichc5a63492013-02-24 00:27:26 +00001143 if (shouldOnlyCommute)
1144 return false;
1145
Evan Cheng2a4410d2011-11-14 19:48:55 +00001146 // If there is one more use of regB later in the same MBB, consider
1147 // re-schedule this MI below it.
Andrew Tricke2326ad2013-04-24 15:54:39 +00001148 if (EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001149 ++NumReSchedDowns;
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001150 return true;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001151 }
1152
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001153 if (MI.isConvertibleTo3Addr()) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001154 // This instruction is potentially convertible to a true
1155 // three-address instruction. Check if it is profitable.
Evan Chengf06e6c22011-03-02 01:08:17 +00001156 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001157 // Try to convert it.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001158 if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001159 ++NumConvertedTo3Addr;
1160 return true; // Done with this instruction.
1161 }
1162 }
1163 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001164
Evan Cheng2a4410d2011-11-14 19:48:55 +00001165 // If there is one more use of regB later in the same MBB, consider
1166 // re-schedule it before this MI if it's legal.
Andrew Tricke2326ad2013-04-24 15:54:39 +00001167 if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001168 ++NumReSchedUps;
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001169 return true;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001170 }
1171
Dan Gohman584fedf2010-06-21 22:17:20 +00001172 // If this is an instruction with a load folded into it, try unfolding
1173 // the load, e.g. avoid this:
1174 // movq %rdx, %rcx
1175 // addq (%rax), %rcx
1176 // in favor of this:
1177 // movq (%rax), %rcx
1178 // addq %rdx, %rcx
1179 // because it's preferable to schedule a load than a register copy.
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001180 if (MI.mayLoad() && !regBKilled) {
Dan Gohman584fedf2010-06-21 22:17:20 +00001181 // Determine if a load can be unfolded.
1182 unsigned LoadRegIndex;
1183 unsigned NewOpc =
Evan Cheng2a4410d2011-11-14 19:48:55 +00001184 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
Dan Gohman584fedf2010-06-21 22:17:20 +00001185 /*UnfoldLoad=*/true,
1186 /*UnfoldStore=*/false,
1187 &LoadRegIndex);
1188 if (NewOpc != 0) {
Evan Chenge837dea2011-06-28 19:10:37 +00001189 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1190 if (UnfoldMCID.getNumDefs() == 1) {
Dan Gohman584fedf2010-06-21 22:17:20 +00001191 // Unfold the load.
Evan Cheng2a4410d2011-11-14 19:48:55 +00001192 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
Dan Gohman584fedf2010-06-21 22:17:20 +00001193 const TargetRegisterClass *RC =
Andrew Trickf12f6df2012-05-03 01:14:37 +00001194 TRI->getAllocatableClass(
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001195 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
Dan Gohman584fedf2010-06-21 22:17:20 +00001196 unsigned Reg = MRI->createVirtualRegister(RC);
1197 SmallVector<MachineInstr *, 2> NewMIs;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001198 if (!TII->unfoldMemoryOperand(*MF, &MI, Reg,
Evan Cheng98ec91e2010-07-02 20:36:18 +00001199 /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
1200 NewMIs)) {
1201 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1202 return false;
1203 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001204 assert(NewMIs.size() == 2 &&
1205 "Unfolded a load into multiple instructions!");
1206 // The load was previously folded, so this is the only use.
1207 NewMIs[1]->addRegisterKilled(Reg, TRI);
1208
1209 // Tentatively insert the instructions into the block so that they
1210 // look "normal" to the transformation logic.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001211 MBB->insert(mi, NewMIs[0]);
1212 MBB->insert(mi, NewMIs[1]);
Dan Gohman584fedf2010-06-21 22:17:20 +00001213
1214 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1215 << "2addr: NEW INST: " << *NewMIs[1]);
1216
1217 // Transform the instruction, now that it no longer has a load.
1218 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1219 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1220 MachineBasicBlock::iterator NewMI = NewMIs[1];
Cameron Zwaricheb1b7252013-02-24 00:27:29 +00001221 bool TransformResult =
Cameron Zwarichc5a63492013-02-24 00:27:26 +00001222 tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true);
Cameron Zwarichcc6137e2013-02-24 01:26:05 +00001223 (void)TransformResult;
Cameron Zwaricheb1b7252013-02-24 00:27:29 +00001224 assert(!TransformResult &&
1225 "tryInstructionTransform() should return false.");
1226 if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
Dan Gohman584fedf2010-06-21 22:17:20 +00001227 // Success, or at least we made an improvement. Keep the unfolded
1228 // instructions and discard the original.
1229 if (LV) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001230 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1231 MachineOperand &MO = MI.getOperand(i);
Andrew Trick8247e0d2012-02-03 05:12:30 +00001232 if (MO.isReg() &&
Dan Gohman7aa7bc72010-06-22 00:32:04 +00001233 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1234 if (MO.isUse()) {
Dan Gohmancc1ca982010-06-22 02:07:21 +00001235 if (MO.isKill()) {
1236 if (NewMIs[0]->killsRegister(MO.getReg()))
Evan Cheng2a4410d2011-11-14 19:48:55 +00001237 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
Dan Gohmancc1ca982010-06-22 02:07:21 +00001238 else {
1239 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1240 "Kill missing after load unfold!");
Evan Cheng2a4410d2011-11-14 19:48:55 +00001241 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
Dan Gohmancc1ca982010-06-22 02:07:21 +00001242 }
1243 }
Evan Cheng2a4410d2011-11-14 19:48:55 +00001244 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
Dan Gohmancc1ca982010-06-22 02:07:21 +00001245 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1246 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
1247 else {
1248 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1249 "Dead flag missing after load unfold!");
1250 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
1251 }
1252 }
Dan Gohman7aa7bc72010-06-22 00:32:04 +00001253 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001254 }
1255 LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
1256 }
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001257
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001258 SmallVector<unsigned, 4> OrigRegs;
1259 if (LIS) {
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001260 for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(),
1261 MOE = MI.operands_end(); MOI != MOE; ++MOI) {
1262 if (MOI->isReg())
1263 OrigRegs.push_back(MOI->getReg());
1264 }
1265 }
1266
Evan Cheng2a4410d2011-11-14 19:48:55 +00001267 MI.eraseFromParent();
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001268
1269 // Update LiveIntervals.
Cameron Zwarichc5b61352013-02-20 22:10:00 +00001270 if (LIS) {
1271 MachineBasicBlock::iterator Begin(NewMIs[0]);
1272 MachineBasicBlock::iterator End(NewMIs[1]);
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001273 LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs);
Cameron Zwarichc5b61352013-02-20 22:10:00 +00001274 }
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001275
Dan Gohman584fedf2010-06-21 22:17:20 +00001276 mi = NewMIs[1];
Dan Gohman584fedf2010-06-21 22:17:20 +00001277 } else {
1278 // Transforming didn't eliminate the tie and didn't lead to an
1279 // improvement. Clean up the unfolded instructions and keep the
1280 // original.
1281 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1282 NewMIs[0]->eraseFromParent();
1283 NewMIs[1]->eraseFromParent();
1284 }
1285 }
1286 }
1287 }
1288
Bob Wilsoncc80df92009-09-03 20:58:42 +00001289 return false;
1290}
1291
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001292// Collect tied operands of MI that need to be handled.
1293// Rewrite trivial cases immediately.
1294// Return true if any tied operands where found, including the trivial ones.
1295bool TwoAddressInstructionPass::
1296collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
1297 const MCInstrDesc &MCID = MI->getDesc();
1298 bool AnyOps = false;
Jakob Stoklund Olesenf363ebd2012-09-04 22:59:30 +00001299 unsigned NumOps = MI->getNumOperands();
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001300
1301 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1302 unsigned DstIdx = 0;
1303 if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1304 continue;
1305 AnyOps = true;
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001306 MachineOperand &SrcMO = MI->getOperand(SrcIdx);
1307 MachineOperand &DstMO = MI->getOperand(DstIdx);
1308 unsigned SrcReg = SrcMO.getReg();
1309 unsigned DstReg = DstMO.getReg();
1310 // Tied constraint already satisfied?
1311 if (SrcReg == DstReg)
1312 continue;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001313
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001314 assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001315
1316 // Deal with <undef> uses immediately - simply rewrite the src operand.
Stephen Hines36b56882014-04-23 16:57:46 -07001317 if (SrcMO.isUndef() && !DstMO.getSubReg()) {
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001318 // Constrain the DstReg register class if required.
1319 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1320 if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
1321 TRI, *MF))
1322 MRI->constrainRegClass(DstReg, RC);
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001323 SrcMO.setReg(DstReg);
Stephen Hines36b56882014-04-23 16:57:46 -07001324 SrcMO.setSubReg(0);
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001325 DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
1326 continue;
1327 }
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001328 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001329 }
1330 return AnyOps;
1331}
1332
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001333// Process a list of tied MI operands that all use the same source register.
1334// The tied pairs are of the form (SrcIdx, DstIdx).
1335void
1336TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
1337 TiedPairList &TiedPairs,
1338 unsigned &Dist) {
1339 bool IsEarlyClobber = false;
Cameron Zwarich6cf93d72013-02-20 06:46:46 +00001340 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1341 const MachineOperand &DstMO = MI->getOperand(TiedPairs[tpi].second);
1342 IsEarlyClobber |= DstMO.isEarlyClobber();
1343 }
1344
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001345 bool RemovedKillFlag = false;
1346 bool AllUsesCopied = true;
1347 unsigned LastCopiedReg = 0;
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001348 SlotIndex LastCopyIdx;
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001349 unsigned RegB = 0;
Stephen Hines36b56882014-04-23 16:57:46 -07001350 unsigned SubRegB = 0;
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001351 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1352 unsigned SrcIdx = TiedPairs[tpi].first;
1353 unsigned DstIdx = TiedPairs[tpi].second;
1354
1355 const MachineOperand &DstMO = MI->getOperand(DstIdx);
1356 unsigned RegA = DstMO.getReg();
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001357
1358 // Grab RegB from the instruction because it may have changed if the
1359 // instruction was commuted.
1360 RegB = MI->getOperand(SrcIdx).getReg();
Stephen Hines36b56882014-04-23 16:57:46 -07001361 SubRegB = MI->getOperand(SrcIdx).getSubReg();
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001362
1363 if (RegA == RegB) {
1364 // The register is tied to multiple destinations (or else we would
1365 // not have continued this far), but this use of the register
1366 // already matches the tied destination. Leave it.
1367 AllUsesCopied = false;
1368 continue;
1369 }
1370 LastCopiedReg = RegA;
1371
1372 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1373 "cannot make instruction into two-address form");
1374
1375#ifndef NDEBUG
1376 // First, verify that we don't have a use of "a" in the instruction
1377 // (a = b + a for example) because our transformation will not
1378 // work. This should never occur because we are in SSA form.
1379 for (unsigned i = 0; i != MI->getNumOperands(); ++i)
1380 assert(i == DstIdx ||
1381 !MI->getOperand(i).isReg() ||
1382 MI->getOperand(i).getReg() != RegA);
1383#endif
1384
1385 // Emit a copy.
Stephen Hines36b56882014-04-23 16:57:46 -07001386 MachineInstrBuilder MIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1387 TII->get(TargetOpcode::COPY), RegA);
1388 // If this operand is folding a truncation, the truncation now moves to the
1389 // copy so that the register classes remain valid for the operands.
1390 MIB.addReg(RegB, 0, SubRegB);
1391 const TargetRegisterClass *RC = MRI->getRegClass(RegB);
1392 if (SubRegB) {
1393 if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1394 assert(TRI->getMatchingSuperRegClass(RC, MRI->getRegClass(RegA),
1395 SubRegB) &&
1396 "tied subregister must be a truncation");
1397 // The superreg class will not be used to constrain the subreg class.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001398 RC = nullptr;
Stephen Hines36b56882014-04-23 16:57:46 -07001399 }
1400 else {
1401 assert(TRI->getMatchingSuperReg(RegA, SubRegB, MRI->getRegClass(RegB))
1402 && "tied subregister must be a truncation");
1403 }
1404 }
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001405
1406 // Update DistanceMap.
1407 MachineBasicBlock::iterator PrevMI = MI;
1408 --PrevMI;
1409 DistanceMap.insert(std::make_pair(PrevMI, Dist));
1410 DistanceMap[MI] = ++Dist;
1411
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001412 if (LIS) {
1413 LastCopyIdx = LIS->InsertMachineInstrInMaps(PrevMI).getRegSlot();
1414
1415 if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1416 LiveInterval &LI = LIS->getInterval(RegA);
1417 VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1418 SlotIndex endIdx =
1419 LIS->getInstructionIndex(MI).getRegSlot(IsEarlyClobber);
Matthias Braun331de112013-10-10 21:28:43 +00001420 LI.addSegment(LiveInterval::Segment(LastCopyIdx, endIdx, VNI));
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001421 }
1422 }
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001423
Stephen Hines36b56882014-04-23 16:57:46 -07001424 DEBUG(dbgs() << "\t\tprepend:\t" << *MIB);
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001425
1426 MachineOperand &MO = MI->getOperand(SrcIdx);
1427 assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
1428 "inconsistent operand info for 2-reg pass");
1429 if (MO.isKill()) {
1430 MO.setIsKill(false);
1431 RemovedKillFlag = true;
1432 }
1433
1434 // Make sure regA is a legal regclass for the SrcIdx operand.
1435 if (TargetRegisterInfo::isVirtualRegister(RegA) &&
1436 TargetRegisterInfo::isVirtualRegister(RegB))
Stephen Hines36b56882014-04-23 16:57:46 -07001437 MRI->constrainRegClass(RegA, RC);
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001438 MO.setReg(RegA);
Stephen Hines36b56882014-04-23 16:57:46 -07001439 // The getMatchingSuper asserts guarantee that the register class projected
1440 // by SubRegB is compatible with RegA with no subregister. So regardless of
1441 // whether the dest oper writes a subreg, the source oper should not.
1442 MO.setSubReg(0);
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001443
1444 // Propagate SrcRegMap.
1445 SrcRegMap[RegA] = RegB;
1446 }
1447
1448
1449 if (AllUsesCopied) {
1450 if (!IsEarlyClobber) {
1451 // Replace other (un-tied) uses of regB with LastCopiedReg.
1452 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1453 MachineOperand &MO = MI->getOperand(i);
Stephen Hines36b56882014-04-23 16:57:46 -07001454 if (MO.isReg() && MO.getReg() == RegB && MO.getSubReg() == SubRegB &&
1455 MO.isUse()) {
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001456 if (MO.isKill()) {
1457 MO.setIsKill(false);
1458 RemovedKillFlag = true;
1459 }
1460 MO.setReg(LastCopiedReg);
Stephen Hines36b56882014-04-23 16:57:46 -07001461 MO.setSubReg(0);
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001462 }
1463 }
1464 }
1465
1466 // Update live variables for regB.
1467 if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(MI)) {
1468 MachineBasicBlock::iterator PrevMI = MI;
1469 --PrevMI;
1470 LV->addVirtualRegisterKilled(RegB, PrevMI);
1471 }
1472
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001473 // Update LiveIntervals.
1474 if (LIS) {
1475 LiveInterval &LI = LIS->getInterval(RegB);
1476 SlotIndex MIIdx = LIS->getInstructionIndex(MI);
1477 LiveInterval::const_iterator I = LI.find(MIIdx);
1478 assert(I != LI.end() && "RegB must be live-in to use.");
1479
1480 SlotIndex UseIdx = MIIdx.getRegSlot(IsEarlyClobber);
1481 if (I->end == UseIdx)
Matthias Braun331de112013-10-10 21:28:43 +00001482 LI.removeSegment(LastCopyIdx, UseIdx);
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001483 }
1484
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001485 } else if (RemovedKillFlag) {
1486 // Some tied uses of regB matched their destination registers, so
1487 // regB is still used in this instruction, but a kill flag was
1488 // removed from a different tied use of regB, so now we need to add
1489 // a kill flag to one of the remaining uses of regB.
1490 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1491 MachineOperand &MO = MI->getOperand(i);
1492 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1493 MO.setIsKill(true);
1494 break;
1495 }
1496 }
1497 }
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001498}
1499
Bill Wendling637980e2008-05-10 00:12:52 +00001500/// runOnMachineFunction - Reduce two-address instructions to two operands.
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001501///
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001502bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
1503 MF = &Func;
1504 const TargetMachine &TM = MF->getTarget();
1505 MRI = &MF->getRegInfo();
Evan Cheng875357d2008-03-13 06:37:55 +00001506 TII = TM.getInstrInfo();
1507 TRI = TM.getRegisterInfo();
Evan Cheng2a4410d2011-11-14 19:48:55 +00001508 InstrItins = TM.getInstrItineraryData();
Duncan Sands1465d612009-01-28 13:14:17 +00001509 LV = getAnalysisIfAvailable<LiveVariables>();
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +00001510 LIS = getAnalysisIfAvailable<LiveIntervals>();
Dan Gohmana70dca12009-10-09 23:27:56 +00001511 AA = &getAnalysis<AliasAnalysis>();
Evan Chengc3aa7c52011-11-16 18:44:48 +00001512 OptLevel = TM.getOptLevel();
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001513
Misha Brukman75fa4e42004-07-22 15:26:23 +00001514 bool MadeChange = false;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001515
David Greeneeb00b182010-01-05 01:24:21 +00001516 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
Andrew Trick8247e0d2012-02-03 05:12:30 +00001517 DEBUG(dbgs() << "********** Function: "
Craig Topper96601ca2012-08-22 06:07:19 +00001518 << MF->getName() << '\n');
Alkis Evlogimenos3a9986f2004-02-18 00:35:06 +00001519
Jakob Stoklund Olesen73e7dce2011-07-29 22:51:22 +00001520 // This pass takes the function out of SSA form.
1521 MRI->leaveSSA();
1522
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001523 TiedOperandMap TiedOperands;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001524 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
1525 MBBI != MBBE; ++MBBI) {
1526 MBB = MBBI;
Evan Cheng7543e582008-06-18 07:49:14 +00001527 unsigned Dist = 0;
1528 DistanceMap.clear();
Evan Cheng870b8072009-03-01 02:03:43 +00001529 SrcRegMap.clear();
1530 DstRegMap.clear();
1531 Processed.clear();
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001532 for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001533 mi != me; ) {
Stephen Hines36b56882014-04-23 16:57:46 -07001534 MachineBasicBlock::iterator nmi = std::next(mi);
Dale Johannesenb8ff9342010-02-10 21:47:48 +00001535 if (mi->isDebugValue()) {
1536 mi = nmi;
1537 continue;
1538 }
Evan Chengf1250ee2010-03-23 20:36:12 +00001539
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001540 // Expand REG_SEQUENCE instructions. This will position mi at the first
1541 // expanded instruction.
Evan Cheng3d720fb2010-05-05 18:45:40 +00001542 if (mi->isRegSequence())
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001543 eliminateRegSequence(mi);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001544
Evan Cheng7543e582008-06-18 07:49:14 +00001545 DistanceMap.insert(std::make_pair(mi, ++Dist));
Evan Cheng870b8072009-03-01 02:03:43 +00001546
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001547 processCopy(&*mi);
Evan Cheng870b8072009-03-01 02:03:43 +00001548
Bob Wilsoncc80df92009-09-03 20:58:42 +00001549 // First scan through all the tied register uses in this instruction
1550 // and record a list of pairs of tied operands for each register.
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001551 if (!collectTiedOperands(mi, TiedOperands)) {
1552 mi = nmi;
1553 continue;
Bob Wilsoncc80df92009-09-03 20:58:42 +00001554 }
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001555
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001556 ++NumTwoAddressInstrs;
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001557 MadeChange = true;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001558 DEBUG(dbgs() << '\t' << *mi);
1559
Chandler Carruth32d75be2012-07-18 18:58:22 +00001560 // If the instruction has a single pair of tied operands, try some
1561 // transformations that may either eliminate the tied operands or
1562 // improve the opportunities for coalescing away the register copy.
1563 if (TiedOperands.size() == 1) {
Craig Toppera0ec3f92013-07-14 04:42:23 +00001564 SmallVectorImpl<std::pair<unsigned, unsigned> > &TiedPairs
Chandler Carruth32d75be2012-07-18 18:58:22 +00001565 = TiedOperands.begin()->second;
1566 if (TiedPairs.size() == 1) {
1567 unsigned SrcIdx = TiedPairs[0].first;
1568 unsigned DstIdx = TiedPairs[0].second;
1569 unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
1570 unsigned DstReg = mi->getOperand(DstIdx).getReg();
1571 if (SrcReg != DstReg &&
Cameron Zwarichc5a63492013-02-24 00:27:26 +00001572 tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) {
Chandler Carruth32d75be2012-07-18 18:58:22 +00001573 // The tied operands have been eliminated or shifted further down the
1574 // block to ease elimination. Continue processing with 'nmi'.
1575 TiedOperands.clear();
1576 mi = nmi;
1577 continue;
1578 }
1579 }
1580 }
1581
Bob Wilsoncc80df92009-09-03 20:58:42 +00001582 // Now iterate over the information collected above.
1583 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1584 OE = TiedOperands.end(); OI != OE; ++OI) {
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001585 processTiedPairs(mi, OI->second, Dist);
David Greeneeb00b182010-01-05 01:24:21 +00001586 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
Jakob Stoklund Olesen351c8812012-06-25 03:27:12 +00001587 }
Bill Wendling637980e2008-05-10 00:12:52 +00001588
Jakob Stoklund Olesen351c8812012-06-25 03:27:12 +00001589 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1590 if (mi->isInsertSubreg()) {
1591 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1592 // To %reg:subidx = COPY %subreg
1593 unsigned SubIdx = mi->getOperand(3).getImm();
1594 mi->RemoveOperand(3);
1595 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1596 mi->getOperand(0).setSubReg(SubIdx);
1597 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1598 mi->RemoveOperand(1);
1599 mi->setDesc(TII->get(TargetOpcode::COPY));
1600 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
Jakob Stoklund Olesened2185e2010-07-06 23:26:25 +00001601 }
1602
Bob Wilsoncc80df92009-09-03 20:58:42 +00001603 // Clear TiedOperands here instead of at the top of the loop
1604 // since most instructions do not have tied operands.
1605 TiedOperands.clear();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001606 mi = nmi;
Misha Brukman75fa4e42004-07-22 15:26:23 +00001607 }
1608 }
1609
Cameron Zwarich767e0432013-02-20 06:46:34 +00001610 if (LIS)
1611 MF->verify(this, "After two-address instruction pass");
1612
Misha Brukman75fa4e42004-07-22 15:26:23 +00001613 return MadeChange;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001614}
Evan Cheng3d720fb2010-05-05 18:45:40 +00001615
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001616/// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process.
Evan Cheng3d720fb2010-05-05 18:45:40 +00001617///
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001618/// The instruction is turned into a sequence of sub-register copies:
1619///
1620/// %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1
1621///
1622/// Becomes:
1623///
1624/// %dst:ssub0<def,undef> = COPY %v1
1625/// %dst:ssub1<def> = COPY %v2
1626///
1627void TwoAddressInstructionPass::
1628eliminateRegSequence(MachineBasicBlock::iterator &MBBI) {
1629 MachineInstr *MI = MBBI;
1630 unsigned DstReg = MI->getOperand(0).getReg();
1631 if (MI->getOperand(0).getSubReg() ||
1632 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1633 !(MI->getNumOperands() & 1)) {
1634 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
Stephen Hinesdce4a402014-05-29 02:49:00 -07001635 llvm_unreachable(nullptr);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001636 }
1637
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001638 SmallVector<unsigned, 4> OrigRegs;
1639 if (LIS) {
1640 OrigRegs.push_back(MI->getOperand(0).getReg());
1641 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2)
1642 OrigRegs.push_back(MI->getOperand(i).getReg());
1643 }
1644
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001645 bool DefEmitted = false;
1646 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1647 MachineOperand &UseMO = MI->getOperand(i);
1648 unsigned SrcReg = UseMO.getReg();
1649 unsigned SubIdx = MI->getOperand(i+1).getImm();
1650 // Nothing needs to be inserted for <undef> operands.
1651 if (UseMO.isUndef())
1652 continue;
1653
1654 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1655 // might insert a COPY that uses SrcReg after is was killed.
1656 bool isKill = UseMO.isKill();
1657 if (isKill)
1658 for (unsigned j = i + 2; j < e; j += 2)
1659 if (MI->getOperand(j).getReg() == SrcReg) {
1660 MI->getOperand(j).setIsKill();
1661 UseMO.setIsKill(false);
1662 isKill = false;
1663 break;
1664 }
1665
1666 // Insert the sub-register copy.
1667 MachineInstr *CopyMI = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1668 TII->get(TargetOpcode::COPY))
1669 .addReg(DstReg, RegState::Define, SubIdx)
1670 .addOperand(UseMO);
1671
1672 // The first def needs an <undef> flag because there is no live register
1673 // before it.
1674 if (!DefEmitted) {
1675 CopyMI->getOperand(0).setIsUndef(true);
1676 // Return an iterator pointing to the first inserted instr.
1677 MBBI = CopyMI;
1678 }
1679 DefEmitted = true;
1680
1681 // Update LiveVariables' kill info.
1682 if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
1683 LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1684
1685 DEBUG(dbgs() << "Inserted: " << *CopyMI);
1686 }
1687
David Blaikiefdf45172013-02-20 07:39:20 +00001688 MachineBasicBlock::iterator EndMBBI =
Stephen Hines36b56882014-04-23 16:57:46 -07001689 std::next(MachineBasicBlock::iterator(MI));
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001690
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001691 if (!DefEmitted) {
1692 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1693 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1694 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
1695 MI->RemoveOperand(j);
1696 } else {
1697 DEBUG(dbgs() << "Eliminated: " << *MI);
1698 MI->eraseFromParent();
1699 }
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001700
1701 // Udpate LiveIntervals.
Cameron Zwarichc5b61352013-02-20 22:10:00 +00001702 if (LIS)
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001703 LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001704}