blob: e6dfe104c82f859b236be14a857cbfeb5fb76994 [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
30#define DEBUG_TYPE "twoaddrinstr"
Chris Lattnerbd91c1c2004-01-31 21:07:15 +000031#include "llvm/CodeGen/Passes.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000032#include "llvm/ADT/BitVector.h"
33#include "llvm/ADT/DenseMap.h"
34#include "llvm/ADT/STLExtras.h"
35#include "llvm/ADT/SmallSet.h"
36#include "llvm/ADT/Statistic.h"
37#include "llvm/Analysis/AliasAnalysis.h"
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +000038#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000039#include "llvm/CodeGen/LiveVariables.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000040#include "llvm/CodeGen/MachineFunctionPass.h"
41#include "llvm/CodeGen/MachineInstr.h"
Bob Wilson852a7e32010-06-15 05:56:31 +000042#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000043#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000044#include "llvm/IR/Function.h"
Evan Cheng2a4410d2011-11-14 19:48:55 +000045#include "llvm/MC/MCInstrItineraries.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
Chris Lattnercd3245a2006-12-19 22:41:21 +000053STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
54STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
Evan Chengd498c8f2009-01-25 03:53:59 +000055STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
Chris Lattnercd3245a2006-12-19 22:41:21 +000056STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
Evan Cheng875357d2008-03-13 06:37:55 +000057STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
Evan Cheng2a4410d2011-11-14 19:48:55 +000058STATISTIC(NumReSchedUps, "Number of instructions re-scheduled up");
59STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down");
Evan Cheng875357d2008-03-13 06:37:55 +000060
61namespace {
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000062class TwoAddressInstructionPass : public MachineFunctionPass {
63 MachineFunction *MF;
64 const TargetInstrInfo *TII;
65 const TargetRegisterInfo *TRI;
66 const InstrItineraryData *InstrItins;
67 MachineRegisterInfo *MRI;
68 LiveVariables *LV;
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000069 LiveIntervals *LIS;
70 AliasAnalysis *AA;
71 CodeGenOpt::Level OptLevel;
Evan Cheng875357d2008-03-13 06:37:55 +000072
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +000073 // The current basic block being processed.
74 MachineBasicBlock *MBB;
75
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000076 // DistanceMap - Keep track the distance of a MI from the start of the
77 // current basic block.
78 DenseMap<MachineInstr*, unsigned> DistanceMap;
Evan Cheng870b8072009-03-01 02:03:43 +000079
Jakob Stoklund Olesen002ef572012-10-26 22:06:00 +000080 // Set of already processed instructions in the current block.
81 SmallPtrSet<MachineInstr*, 8> Processed;
82
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000083 // SrcRegMap - A map from virtual registers to physical registers which are
84 // likely targets to be coalesced to due to copies from physical registers to
85 // virtual registers. e.g. v1024 = move r0.
86 DenseMap<unsigned, unsigned> SrcRegMap;
Evan Cheng870b8072009-03-01 02:03:43 +000087
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000088 // DstRegMap - A map from virtual registers to physical registers which are
89 // likely targets to be coalesced to due to copies to physical registers from
90 // virtual registers. e.g. r1 = move v1024.
91 DenseMap<unsigned, unsigned> DstRegMap;
Evan Cheng870b8072009-03-01 02:03:43 +000092
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +000093 bool sink3AddrInstruction(MachineInstr *MI, unsigned Reg,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000094 MachineBasicBlock::iterator OldPos);
Evan Cheng7543e582008-06-18 07:49:14 +000095
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +000096 bool noUseAfterLastDef(unsigned Reg, unsigned Dist, unsigned &LastDef);
Evan Chengd498c8f2009-01-25 03:53:59 +000097
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +000098 bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +000099 MachineInstr *MI, unsigned Dist);
Evan Chengd498c8f2009-01-25 03:53:59 +0000100
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000101 bool commuteInstruction(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000102 unsigned RegB, unsigned RegC, unsigned Dist);
Evan Cheng870b8072009-03-01 02:03:43 +0000103
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000104 bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
Evan Chenge6f350d2009-03-30 21:34:07 +0000105
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000106 bool convertInstTo3Addr(MachineBasicBlock::iterator &mi,
107 MachineBasicBlock::iterator &nmi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000108 unsigned RegA, unsigned RegB, unsigned Dist);
Evan Chenge6f350d2009-03-30 21:34:07 +0000109
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000110 bool isDefTooClose(unsigned Reg, unsigned Dist, MachineInstr *MI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000111
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000112 bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000113 MachineBasicBlock::iterator &nmi,
114 unsigned Reg);
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000115 bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000116 MachineBasicBlock::iterator &nmi,
117 unsigned Reg);
118
119 bool tryInstructionTransform(MachineBasicBlock::iterator &mi,
Evan Cheng2a4410d2011-11-14 19:48:55 +0000120 MachineBasicBlock::iterator &nmi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000121 unsigned SrcIdx, unsigned DstIdx,
Cameron Zwarichc5a63492013-02-24 00:27:26 +0000122 unsigned Dist, bool shouldOnlyCommute);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000123
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000124 void scanUses(unsigned DstReg);
Evan Chengf06e6c22011-03-02 01:08:17 +0000125
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000126 void processCopy(MachineInstr *MI);
Bob Wilsoncc80df92009-09-03 20:58:42 +0000127
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000128 typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList;
129 typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap;
130 bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
131 void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +0000132 void eliminateRegSequence(MachineBasicBlock::iterator&);
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +0000133
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000134public:
135 static char ID; // Pass identification, replacement for typeid
136 TwoAddressInstructionPass() : MachineFunctionPass(ID) {
137 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
138 }
Evan Chengc6dcce32010-05-17 23:24:12 +0000139
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000140 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
141 AU.setPreservesCFG();
142 AU.addRequired<AliasAnalysis>();
143 AU.addPreserved<LiveVariables>();
144 AU.addPreserved<SlotIndexes>();
145 AU.addPreserved<LiveIntervals>();
146 AU.addPreservedID(MachineLoopInfoID);
147 AU.addPreservedID(MachineDominatorsID);
148 MachineFunctionPass::getAnalysisUsage(AU);
149 }
Devang Patel794fd752007-05-01 21:15:47 +0000150
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000151 /// runOnMachineFunction - Pass entry point.
152 bool runOnMachineFunction(MachineFunction&);
153};
154} // end anonymous namespace
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000155
Dan Gohman844731a2008-05-13 00:00:25 +0000156char TwoAddressInstructionPass::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000157INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
158 "Two-Address instruction pass", false, false)
159INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
160INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
Owen Andersonce665bd2010-10-07 22:25:06 +0000161 "Two-Address instruction pass", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000162
Owen Anderson90c579d2010-08-06 18:33:48 +0000163char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000164
Cameron Zwarich4c579422013-02-23 04:49:20 +0000165static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg, LiveIntervals *LIS);
166
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000167/// sink3AddrInstruction - A two-address instruction has been converted to a
Evan Cheng875357d2008-03-13 06:37:55 +0000168/// three-address instruction to avoid clobbering a register. Try to sink it
Bill Wendling637980e2008-05-10 00:12:52 +0000169/// past the instruction that would kill the above mentioned register to reduce
170/// register pressure.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000171bool TwoAddressInstructionPass::
172sink3AddrInstruction(MachineInstr *MI, unsigned SavedReg,
173 MachineBasicBlock::iterator OldPos) {
Eli Friedmanbde81d52011-09-23 22:41:57 +0000174 // FIXME: Shouldn't we be trying to do this before we three-addressify the
175 // instruction? After this transformation is done, we no longer need
176 // the instruction to be in three-address form.
177
Evan Cheng875357d2008-03-13 06:37:55 +0000178 // Check if it's safe to move this instruction.
179 bool SeenStore = true; // Be conservative.
Evan Chengac1abde2010-03-02 19:03:01 +0000180 if (!MI->isSafeToMove(TII, AA, SeenStore))
Evan Cheng875357d2008-03-13 06:37:55 +0000181 return false;
182
183 unsigned DefReg = 0;
184 SmallSet<unsigned, 4> UseRegs;
Bill Wendling637980e2008-05-10 00:12:52 +0000185
Evan Cheng875357d2008-03-13 06:37:55 +0000186 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
187 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000188 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000189 continue;
190 unsigned MOReg = MO.getReg();
191 if (!MOReg)
192 continue;
193 if (MO.isUse() && MOReg != SavedReg)
194 UseRegs.insert(MO.getReg());
195 if (!MO.isDef())
196 continue;
197 if (MO.isImplicit())
198 // Don't try to move it if it implicitly defines a register.
199 return false;
200 if (DefReg)
201 // For now, don't move any instructions that define multiple registers.
202 return false;
203 DefReg = MO.getReg();
204 }
205
206 // Find the instruction that kills SavedReg.
207 MachineInstr *KillMI = NULL;
Cameron Zwarich4c579422013-02-23 04:49:20 +0000208 if (LIS) {
209 LiveInterval &LI = LIS->getInterval(SavedReg);
210 assert(LI.end() != LI.begin() &&
211 "Reg should not have empty live interval.");
212
213 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
214 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
215 if (I != LI.end() && I->start < MBBEndIdx)
216 return false;
217
218 --I;
219 KillMI = LIS->getInstructionFromIndex(I->end);
220 }
221 if (!KillMI) {
222 for (MachineRegisterInfo::use_nodbg_iterator
223 UI = MRI->use_nodbg_begin(SavedReg),
224 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
225 MachineOperand &UseMO = UI.getOperand();
226 if (!UseMO.isKill())
227 continue;
228 KillMI = UseMO.getParent();
229 break;
230 }
Evan Cheng875357d2008-03-13 06:37:55 +0000231 }
Bill Wendling637980e2008-05-10 00:12:52 +0000232
Eli Friedmanbde81d52011-09-23 22:41:57 +0000233 // If we find the instruction that kills SavedReg, and it is in an
234 // appropriate location, we can try to sink the current instruction
235 // past it.
236 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
Jakob Stoklund Olesen988069e2012-08-09 22:08:26 +0000237 KillMI == OldPos || KillMI->isTerminator())
Evan Cheng875357d2008-03-13 06:37:55 +0000238 return false;
239
Bill Wendling637980e2008-05-10 00:12:52 +0000240 // If any of the definitions are used by another instruction between the
241 // position and the kill use, then it's not safe to sink it.
Andrew Trick8247e0d2012-02-03 05:12:30 +0000242 //
Bill Wendling637980e2008-05-10 00:12:52 +0000243 // FIXME: This can be sped up if there is an easy way to query whether an
Evan Cheng7543e582008-06-18 07:49:14 +0000244 // instruction is before or after another instruction. Then we can use
Bill Wendling637980e2008-05-10 00:12:52 +0000245 // MachineRegisterInfo def / use instead.
Evan Cheng875357d2008-03-13 06:37:55 +0000246 MachineOperand *KillMO = NULL;
247 MachineBasicBlock::iterator KillPos = KillMI;
248 ++KillPos;
Bill Wendling637980e2008-05-10 00:12:52 +0000249
Evan Cheng7543e582008-06-18 07:49:14 +0000250 unsigned NumVisited = 0;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000251 for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
Evan Cheng875357d2008-03-13 06:37:55 +0000252 MachineInstr *OtherMI = I;
Dale Johannesen3bfef032010-02-11 18:22:31 +0000253 // DBG_VALUE cannot be counted against the limit.
254 if (OtherMI->isDebugValue())
255 continue;
Evan Cheng7543e582008-06-18 07:49:14 +0000256 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
257 return false;
258 ++NumVisited;
Evan Cheng875357d2008-03-13 06:37:55 +0000259 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
260 MachineOperand &MO = OtherMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000261 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000262 continue;
263 unsigned MOReg = MO.getReg();
264 if (!MOReg)
265 continue;
266 if (DefReg == MOReg)
267 return false;
Bill Wendling637980e2008-05-10 00:12:52 +0000268
Cameron Zwarich4c579422013-02-23 04:49:20 +0000269 if (MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))) {
Evan Cheng875357d2008-03-13 06:37:55 +0000270 if (OtherMI == KillMI && MOReg == SavedReg)
Evan Cheng7543e582008-06-18 07:49:14 +0000271 // Save the operand that kills the register. We want to unset the kill
272 // marker if we can sink MI past it.
Evan Cheng875357d2008-03-13 06:37:55 +0000273 KillMO = &MO;
274 else if (UseRegs.count(MOReg))
275 // One of the uses is killed before the destination.
276 return false;
277 }
278 }
279 }
Jakob Stoklund Olesen988069e2012-08-09 22:08:26 +0000280 assert(KillMO && "Didn't find kill");
Evan Cheng875357d2008-03-13 06:37:55 +0000281
Cameron Zwarich4c579422013-02-23 04:49:20 +0000282 if (!LIS) {
283 // Update kill and LV information.
284 KillMO->setIsKill(false);
285 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
286 KillMO->setIsKill(true);
Andrew Trick8247e0d2012-02-03 05:12:30 +0000287
Cameron Zwarich4c579422013-02-23 04:49:20 +0000288 if (LV)
289 LV->replaceKillInstruction(SavedReg, KillMI, MI);
290 }
Evan Cheng875357d2008-03-13 06:37:55 +0000291
292 // Move instruction to its destination.
293 MBB->remove(MI);
294 MBB->insert(KillPos, MI);
295
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000296 if (LIS)
297 LIS->handleMove(MI);
298
Evan Cheng875357d2008-03-13 06:37:55 +0000299 ++Num3AddrSunk;
300 return true;
301}
302
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000303/// noUseAfterLastDef - Return true if there are no intervening uses between the
Evan Chengd498c8f2009-01-25 03:53:59 +0000304/// last instruction in the MBB that defines the specified register and the
305/// two-address instruction which is being processed. It also returns the last
306/// def location by reference
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000307bool TwoAddressInstructionPass::noUseAfterLastDef(unsigned Reg, unsigned Dist,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000308 unsigned &LastDef) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000309 LastDef = 0;
310 unsigned LastUse = Dist;
311 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
312 E = MRI->reg_end(); I != E; ++I) {
313 MachineOperand &MO = I.getOperand();
314 MachineInstr *MI = MO.getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000315 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesend94998f2010-02-09 02:01:46 +0000316 continue;
Evan Chengd498c8f2009-01-25 03:53:59 +0000317 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
318 if (DI == DistanceMap.end())
319 continue;
320 if (MO.isUse() && DI->second < LastUse)
321 LastUse = DI->second;
322 if (MO.isDef() && DI->second > LastDef)
323 LastDef = DI->second;
324 }
325
326 return !(LastUse > LastDef && LastUse < Dist);
327}
328
Evan Cheng870b8072009-03-01 02:03:43 +0000329/// isCopyToReg - Return true if the specified MI is a copy instruction or
330/// a extract_subreg instruction. It also returns the source and destination
331/// registers and whether they are physical registers by reference.
332static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
333 unsigned &SrcReg, unsigned &DstReg,
334 bool &IsSrcPhys, bool &IsDstPhys) {
335 SrcReg = 0;
336 DstReg = 0;
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000337 if (MI.isCopy()) {
338 DstReg = MI.getOperand(0).getReg();
339 SrcReg = MI.getOperand(1).getReg();
340 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
341 DstReg = MI.getOperand(0).getReg();
342 SrcReg = MI.getOperand(2).getReg();
343 } else
344 return false;
Evan Cheng870b8072009-03-01 02:03:43 +0000345
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000346 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
347 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
348 return true;
Evan Cheng870b8072009-03-01 02:03:43 +0000349}
350
Cameron Zwarich3a9805f2013-02-21 07:02:28 +0000351/// isPLainlyKilled - Test if the given register value, which is used by the
352// given instruction, is killed by the given instruction.
353static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg,
354 LiveIntervals *LIS) {
355 if (LIS && TargetRegisterInfo::isVirtualRegister(Reg) &&
356 !LIS->isNotInMIMap(MI)) {
357 // FIXME: Sometimes tryInstructionTransform() will add instructions and
358 // test whether they can be folded before keeping them. In this case it
359 // sets a kill before recursively calling tryInstructionTransform() again.
360 // If there is no interval available, we assume that this instruction is
361 // one of those. A kill flag is manually inserted on the operand so the
362 // check below will handle it.
363 LiveInterval &LI = LIS->getInterval(Reg);
364 // This is to match the kill flag version where undefs don't have kill
365 // flags.
366 if (!LI.hasAtLeastOneValue())
367 return false;
368
369 SlotIndex useIdx = LIS->getInstructionIndex(MI);
370 LiveInterval::const_iterator I = LI.find(useIdx);
371 assert(I != LI.end() && "Reg must be live-in to use.");
Cameron Zwarichb4bd0222013-02-23 04:49:22 +0000372 return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx);
Cameron Zwarich3a9805f2013-02-21 07:02:28 +0000373 }
374
375 return MI->killsRegister(Reg);
376}
377
Dan Gohman97121ba2009-04-08 00:15:30 +0000378/// isKilled - Test if the given register value, which is used by the given
379/// instruction, is killed by the given instruction. This looks through
380/// coalescable copies to see if the original value is potentially not killed.
381///
382/// For example, in this code:
383///
384/// %reg1034 = copy %reg1024
385/// %reg1035 = copy %reg1025<kill>
386/// %reg1036 = add %reg1034<kill>, %reg1035<kill>
387///
388/// %reg1034 is not considered to be killed, since it is copied from a
389/// register which is not killed. Treating it as not killed lets the
390/// normal heuristics commute the (two-address) add, which lets
391/// coalescing eliminate the extra copy.
392///
Cameron Zwaricha931a122013-02-21 22:58:42 +0000393/// If allowFalsePositives is true then likely kills are treated as kills even
394/// if it can't be proven that they are kills.
Dan Gohman97121ba2009-04-08 00:15:30 +0000395static bool isKilled(MachineInstr &MI, unsigned Reg,
396 const MachineRegisterInfo *MRI,
Cameron Zwarich214df422013-02-21 04:33:02 +0000397 const TargetInstrInfo *TII,
Cameron Zwaricha931a122013-02-21 22:58:42 +0000398 LiveIntervals *LIS,
399 bool allowFalsePositives) {
Dan Gohman97121ba2009-04-08 00:15:30 +0000400 MachineInstr *DefMI = &MI;
401 for (;;) {
Cameron Zwaricha931a122013-02-21 22:58:42 +0000402 // All uses of physical registers are likely to be kills.
403 if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
404 (allowFalsePositives || MRI->hasOneUse(Reg)))
405 return true;
Cameron Zwarich3a9805f2013-02-21 07:02:28 +0000406 if (!isPlainlyKilled(DefMI, Reg, LIS))
Dan Gohman97121ba2009-04-08 00:15:30 +0000407 return false;
408 if (TargetRegisterInfo::isPhysicalRegister(Reg))
409 return true;
410 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
411 // If there are multiple defs, we can't do a simple analysis, so just
412 // go with what the kill flag says.
Chris Lattner7896c9f2009-12-03 00:50:42 +0000413 if (llvm::next(Begin) != MRI->def_end())
Dan Gohman97121ba2009-04-08 00:15:30 +0000414 return true;
415 DefMI = &*Begin;
416 bool IsSrcPhys, IsDstPhys;
417 unsigned SrcReg, DstReg;
418 // If the def is something other than a copy, then it isn't going to
419 // be coalesced, so follow the kill flag.
420 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
421 return true;
422 Reg = SrcReg;
423 }
424}
425
Evan Cheng870b8072009-03-01 02:03:43 +0000426/// isTwoAddrUse - Return true if the specified MI uses the specified register
427/// as a two-address use. If so, return the destination register by reference.
428static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
Evan Chenge837dea2011-06-28 19:10:37 +0000429 const MCInstrDesc &MCID = MI.getDesc();
430 unsigned NumOps = MI.isInlineAsm()
431 ? MI.getNumOperands() : MCID.getNumOperands();
Evan Chenge6f350d2009-03-30 21:34:07 +0000432 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng870b8072009-03-01 02:03:43 +0000433 const MachineOperand &MO = MI.getOperand(i);
434 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
435 continue;
Evan Chenga24752f2009-03-19 20:30:06 +0000436 unsigned ti;
437 if (MI.isRegTiedToDefOperand(i, &ti)) {
Evan Cheng870b8072009-03-01 02:03:43 +0000438 DstReg = MI.getOperand(ti).getReg();
439 return true;
440 }
441 }
442 return false;
443}
444
445/// findOnlyInterestingUse - Given a register, if has a single in-basic block
446/// use, return the use instruction if it's a copy or a two-address use.
447static
448MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
449 MachineRegisterInfo *MRI,
450 const TargetInstrInfo *TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000451 bool &IsCopy,
Evan Cheng870b8072009-03-01 02:03:43 +0000452 unsigned &DstReg, bool &IsDstPhys) {
Evan Cheng1423c702010-03-03 21:18:38 +0000453 if (!MRI->hasOneNonDBGUse(Reg))
454 // None or more than one use.
Evan Cheng870b8072009-03-01 02:03:43 +0000455 return 0;
Evan Cheng1423c702010-03-03 21:18:38 +0000456 MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg);
Evan Cheng870b8072009-03-01 02:03:43 +0000457 if (UseMI.getParent() != MBB)
458 return 0;
459 unsigned SrcReg;
460 bool IsSrcPhys;
Evan Cheng87d696a2009-04-14 00:32:25 +0000461 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
462 IsCopy = true;
Evan Cheng870b8072009-03-01 02:03:43 +0000463 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000464 }
Evan Cheng870b8072009-03-01 02:03:43 +0000465 IsDstPhys = false;
Evan Cheng87d696a2009-04-14 00:32:25 +0000466 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
467 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng870b8072009-03-01 02:03:43 +0000468 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000469 }
Evan Cheng870b8072009-03-01 02:03:43 +0000470 return 0;
471}
472
473/// getMappedReg - Return the physical register the specified virtual register
474/// might be mapped to.
475static unsigned
476getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
477 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
478 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
479 if (SI == RegMap.end())
480 return 0;
481 Reg = SI->second;
482 }
483 if (TargetRegisterInfo::isPhysicalRegister(Reg))
484 return Reg;
485 return 0;
486}
487
488/// regsAreCompatible - Return true if the two registers are equal or aliased.
489///
490static bool
491regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
492 if (RegA == RegB)
493 return true;
494 if (!RegA || !RegB)
495 return false;
496 return TRI->regsOverlap(RegA, RegB);
497}
498
499
Manman Rend68e8cd2012-07-25 18:28:13 +0000500/// isProfitableToCommute - Return true if it's potentially profitable to commute
Evan Chengd498c8f2009-01-25 03:53:59 +0000501/// the two-address instruction that's being processed.
502bool
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000503TwoAddressInstructionPass::
504isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
505 MachineInstr *MI, unsigned Dist) {
Evan Chengc3aa7c52011-11-16 18:44:48 +0000506 if (OptLevel == CodeGenOpt::None)
507 return false;
508
Evan Chengd498c8f2009-01-25 03:53:59 +0000509 // Determine if it's profitable to commute this two address instruction. In
510 // general, we want no uses between this instruction and the definition of
511 // the two-address register.
512 // e.g.
513 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
514 // %reg1029<def> = MOV8rr %reg1028
515 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
516 // insert => %reg1030<def> = MOV8rr %reg1028
517 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
518 // In this case, it might not be possible to coalesce the second MOV8rr
519 // instruction if the first one is coalesced. So it would be profitable to
520 // commute it:
521 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
522 // %reg1029<def> = MOV8rr %reg1028
523 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
524 // insert => %reg1030<def> = MOV8rr %reg1029
Andrew Trick8247e0d2012-02-03 05:12:30 +0000525 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
Evan Chengd498c8f2009-01-25 03:53:59 +0000526
Cameron Zwarich17cec5a2013-02-21 07:02:30 +0000527 if (!isPlainlyKilled(MI, regC, LIS))
Evan Chengd498c8f2009-01-25 03:53:59 +0000528 return false;
529
530 // Ok, we have something like:
531 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
532 // let's see if it's worth commuting it.
533
Evan Cheng870b8072009-03-01 02:03:43 +0000534 // Look for situations like this:
535 // %reg1024<def> = MOV r1
536 // %reg1025<def> = MOV r0
537 // %reg1026<def> = ADD %reg1024, %reg1025
538 // r0 = MOV %reg1026
539 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
Evan Chengd99d68b2012-05-03 01:45:13 +0000540 unsigned ToRegA = getMappedReg(regA, DstRegMap);
541 if (ToRegA) {
542 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
543 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
544 bool BComp = !FromRegB || regsAreCompatible(FromRegB, ToRegA, TRI);
545 bool CComp = !FromRegC || regsAreCompatible(FromRegC, ToRegA, TRI);
546 if (BComp != CComp)
547 return !BComp && CComp;
548 }
Evan Cheng870b8072009-03-01 02:03:43 +0000549
Evan Chengd498c8f2009-01-25 03:53:59 +0000550 // If there is a use of regC between its last def (could be livein) and this
551 // instruction, then bail.
552 unsigned LastDefC = 0;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000553 if (!noUseAfterLastDef(regC, Dist, LastDefC))
Evan Chengd498c8f2009-01-25 03:53:59 +0000554 return false;
555
556 // If there is a use of regB between its last def (could be livein) and this
557 // instruction, then go ahead and make this transformation.
558 unsigned LastDefB = 0;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000559 if (!noUseAfterLastDef(regB, Dist, LastDefB))
Evan Chengd498c8f2009-01-25 03:53:59 +0000560 return true;
561
562 // Since there are no intervening uses for both registers, then commute
563 // if the def of regC is closer. Its live interval is shorter.
564 return LastDefB && LastDefC && LastDefC > LastDefB;
565}
566
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000567/// commuteInstruction - Commute a two-address instruction and update the basic
Evan Cheng81913712009-01-23 23:27:33 +0000568/// block, distance map, and live variables if needed. Return true if it is
569/// successful.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000570bool TwoAddressInstructionPass::
571commuteInstruction(MachineBasicBlock::iterator &mi,
572 unsigned RegB, unsigned RegC, unsigned Dist) {
Evan Cheng81913712009-01-23 23:27:33 +0000573 MachineInstr *MI = mi;
David Greeneeb00b182010-01-05 01:24:21 +0000574 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
Evan Cheng81913712009-01-23 23:27:33 +0000575 MachineInstr *NewMI = TII->commuteInstruction(MI);
576
577 if (NewMI == 0) {
David Greeneeb00b182010-01-05 01:24:21 +0000578 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
Evan Cheng81913712009-01-23 23:27:33 +0000579 return false;
580 }
581
David Greeneeb00b182010-01-05 01:24:21 +0000582 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
Cameron Zwarich1ea93c72013-02-23 23:13:28 +0000583 assert(NewMI == MI &&
584 "TargetInstrInfo::commuteInstruction() should not return a new "
585 "instruction unless it was requested.");
Evan Cheng870b8072009-03-01 02:03:43 +0000586
587 // Update source register map.
588 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
589 if (FromRegC) {
590 unsigned RegA = MI->getOperand(0).getReg();
591 SrcRegMap[RegA] = FromRegC;
592 }
593
Evan Cheng81913712009-01-23 23:27:33 +0000594 return true;
595}
596
Evan Chenge6f350d2009-03-30 21:34:07 +0000597/// isProfitableToConv3Addr - Return true if it is profitable to convert the
598/// given 2-address instruction to a 3-address one.
599bool
Evan Chengf06e6c22011-03-02 01:08:17 +0000600TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
Evan Chenge6f350d2009-03-30 21:34:07 +0000601 // Look for situations like this:
602 // %reg1024<def> = MOV r1
603 // %reg1025<def> = MOV r0
604 // %reg1026<def> = ADD %reg1024, %reg1025
605 // r2 = MOV %reg1026
606 // Turn ADD into a 3-address instruction to avoid a copy.
Evan Chengf06e6c22011-03-02 01:08:17 +0000607 unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
608 if (!FromRegB)
609 return false;
Evan Chenge6f350d2009-03-30 21:34:07 +0000610 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
Evan Chengf06e6c22011-03-02 01:08:17 +0000611 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
Evan Chenge6f350d2009-03-30 21:34:07 +0000612}
613
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000614/// convertInstTo3Addr - Convert the specified two-address instruction into a
Evan Chenge6f350d2009-03-30 21:34:07 +0000615/// three address one. Return true if this transformation was successful.
616bool
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000617TwoAddressInstructionPass::convertInstTo3Addr(MachineBasicBlock::iterator &mi,
Evan Chenge6f350d2009-03-30 21:34:07 +0000618 MachineBasicBlock::iterator &nmi,
Evan Cheng4d96c632011-02-10 02:20:55 +0000619 unsigned RegA, unsigned RegB,
620 unsigned Dist) {
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000621 // FIXME: Why does convertToThreeAddress() need an iterator reference?
622 MachineFunction::iterator MFI = MBB;
623 MachineInstr *NewMI = TII->convertToThreeAddress(MFI, mi, LV);
624 assert(MBB == MFI && "convertToThreeAddress changed iterator reference");
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000625 if (!NewMI)
626 return false;
Evan Chenge6f350d2009-03-30 21:34:07 +0000627
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000628 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
629 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
630 bool Sunk = false;
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000631
Cameron Zwarich61892882013-02-20 22:10:02 +0000632 if (LIS)
633 LIS->ReplaceMachineInstrInMaps(mi, NewMI);
Evan Chenge6f350d2009-03-30 21:34:07 +0000634
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000635 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
636 // FIXME: Temporary workaround. If the new instruction doesn't
637 // uses RegB, convertToThreeAddress must have created more
638 // then one instruction.
639 Sunk = sink3AddrInstruction(NewMI, RegB, mi);
Evan Chenge6f350d2009-03-30 21:34:07 +0000640
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000641 MBB->erase(mi); // Nuke the old inst.
Evan Cheng4d96c632011-02-10 02:20:55 +0000642
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000643 if (!Sunk) {
644 DistanceMap.insert(std::make_pair(NewMI, Dist));
645 mi = NewMI;
646 nmi = llvm::next(mi);
Evan Chenge6f350d2009-03-30 21:34:07 +0000647 }
648
Jakob Stoklund Olesen96e6da42012-10-26 23:05:13 +0000649 // Update source and destination register maps.
650 SrcRegMap.erase(RegA);
651 DstRegMap.erase(RegB);
652 return true;
Evan Chenge6f350d2009-03-30 21:34:07 +0000653}
654
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000655/// scanUses - Scan forward recursively for only uses, update maps if the use
Evan Chengf06e6c22011-03-02 01:08:17 +0000656/// is a copy or a two-address instruction.
657void
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000658TwoAddressInstructionPass::scanUses(unsigned DstReg) {
Evan Chengf06e6c22011-03-02 01:08:17 +0000659 SmallVector<unsigned, 4> VirtRegPairs;
660 bool IsDstPhys;
661 bool IsCopy = false;
662 unsigned NewReg = 0;
663 unsigned Reg = DstReg;
664 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
665 NewReg, IsDstPhys)) {
666 if (IsCopy && !Processed.insert(UseMI))
667 break;
668
669 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
670 if (DI != DistanceMap.end())
671 // Earlier in the same MBB.Reached via a back edge.
672 break;
673
674 if (IsDstPhys) {
675 VirtRegPairs.push_back(NewReg);
676 break;
677 }
678 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
679 if (!isNew)
680 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
681 VirtRegPairs.push_back(NewReg);
682 Reg = NewReg;
683 }
684
685 if (!VirtRegPairs.empty()) {
686 unsigned ToReg = VirtRegPairs.back();
687 VirtRegPairs.pop_back();
688 while (!VirtRegPairs.empty()) {
689 unsigned FromReg = VirtRegPairs.back();
690 VirtRegPairs.pop_back();
691 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
692 if (!isNew)
693 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
694 ToReg = FromReg;
695 }
696 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
697 if (!isNew)
698 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
699 }
700}
701
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000702/// processCopy - If the specified instruction is not yet processed, process it
Evan Cheng870b8072009-03-01 02:03:43 +0000703/// if it's a copy. For a copy instruction, we find the physical registers the
704/// source and destination registers might be mapped to. These are kept in
705/// point-to maps used to determine future optimizations. e.g.
706/// v1024 = mov r0
707/// v1025 = mov r1
708/// v1026 = add v1024, v1025
709/// r1 = mov r1026
710/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
711/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
712/// potentially joined with r1 on the output side. It's worthwhile to commute
713/// 'add' to eliminate a copy.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000714void TwoAddressInstructionPass::processCopy(MachineInstr *MI) {
Evan Cheng870b8072009-03-01 02:03:43 +0000715 if (Processed.count(MI))
716 return;
717
718 bool IsSrcPhys, IsDstPhys;
719 unsigned SrcReg, DstReg;
720 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
721 return;
722
723 if (IsDstPhys && !IsSrcPhys)
724 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
725 else if (!IsDstPhys && IsSrcPhys) {
Evan Cheng3005ed62009-04-13 20:04:24 +0000726 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
727 if (!isNew)
728 assert(SrcRegMap[DstReg] == SrcReg &&
729 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000730
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000731 scanUses(DstReg);
Evan Cheng870b8072009-03-01 02:03:43 +0000732 }
733
734 Processed.insert(MI);
Evan Chengf06e6c22011-03-02 01:08:17 +0000735 return;
Evan Cheng870b8072009-03-01 02:03:43 +0000736}
737
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000738/// rescheduleMIBelowKill - If there is one more local instruction that reads
Evan Cheng2a4410d2011-11-14 19:48:55 +0000739/// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
740/// instruction in order to eliminate the need for the copy.
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000741bool TwoAddressInstructionPass::
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000742rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000743 MachineBasicBlock::iterator &nmi,
744 unsigned Reg) {
Cameron Zwarich80885e52013-02-23 04:49:13 +0000745 // Bail immediately if we don't have LV or LIS available. We use them to find
746 // kills efficiently.
747 if (!LV && !LIS)
Chandler Carruth7d532c82012-07-15 03:29:46 +0000748 return false;
749
Evan Cheng2a4410d2011-11-14 19:48:55 +0000750 MachineInstr *MI = &*mi;
Andrew Trick8247e0d2012-02-03 05:12:30 +0000751 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000752 if (DI == DistanceMap.end())
753 // Must be created from unfolded load. Don't waste time trying this.
754 return false;
755
Cameron Zwarich80885e52013-02-23 04:49:13 +0000756 MachineInstr *KillMI = 0;
757 if (LIS) {
758 LiveInterval &LI = LIS->getInterval(Reg);
759 assert(LI.end() != LI.begin() &&
760 "Reg should not have empty live interval.");
761
762 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
763 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
764 if (I != LI.end() && I->start < MBBEndIdx)
765 return false;
766
767 --I;
768 KillMI = LIS->getInstructionFromIndex(I->end);
769 } else {
770 KillMI = LV->getVarInfo(Reg).findKill(MBB);
771 }
Chandler Carruth7d532c82012-07-15 03:29:46 +0000772 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000773 // Don't mess with copies, they may be coalesced later.
774 return false;
775
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000776 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
777 KillMI->isBranch() || KillMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000778 // Don't move pass calls, etc.
779 return false;
780
781 unsigned DstReg;
782 if (isTwoAddrUse(*KillMI, Reg, DstReg))
783 return false;
784
Evan Chengf1784182011-11-15 06:26:51 +0000785 bool SeenStore = true;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000786 if (!MI->isSafeToMove(TII, AA, SeenStore))
787 return false;
788
789 if (TII->getInstrLatency(InstrItins, MI) > 1)
790 // FIXME: Needs more sophisticated heuristics.
791 return false;
792
793 SmallSet<unsigned, 2> Uses;
Evan Cheng9bad88a2011-11-16 03:47:42 +0000794 SmallSet<unsigned, 2> Kills;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000795 SmallSet<unsigned, 2> Defs;
796 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
797 const MachineOperand &MO = MI->getOperand(i);
798 if (!MO.isReg())
799 continue;
800 unsigned MOReg = MO.getReg();
801 if (!MOReg)
802 continue;
803 if (MO.isDef())
804 Defs.insert(MOReg);
Evan Cheng9bad88a2011-11-16 03:47:42 +0000805 else {
Evan Cheng2a4410d2011-11-14 19:48:55 +0000806 Uses.insert(MOReg);
Cameron Zwarich80885e52013-02-23 04:49:13 +0000807 if (MOReg != Reg && (MO.isKill() ||
808 (LIS && isPlainlyKilled(MI, MOReg, LIS))))
Evan Cheng9bad88a2011-11-16 03:47:42 +0000809 Kills.insert(MOReg);
810 }
Evan Cheng2a4410d2011-11-14 19:48:55 +0000811 }
812
813 // Move the copies connected to MI down as well.
Cameron Zwarich80885e52013-02-23 04:49:13 +0000814 MachineBasicBlock::iterator Begin = MI;
815 MachineBasicBlock::iterator AfterMI = llvm::next(Begin);
816
817 MachineBasicBlock::iterator End = AfterMI;
818 while (End->isCopy() && Defs.count(End->getOperand(1).getReg())) {
819 Defs.insert(End->getOperand(0).getReg());
820 ++End;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000821 }
822
823 // Check if the reschedule will not break depedencies.
824 unsigned NumVisited = 0;
825 MachineBasicBlock::iterator KillPos = KillMI;
826 ++KillPos;
Cameron Zwarich80885e52013-02-23 04:49:13 +0000827 for (MachineBasicBlock::iterator I = End; I != KillPos; ++I) {
Evan Cheng2a4410d2011-11-14 19:48:55 +0000828 MachineInstr *OtherMI = I;
829 // DBG_VALUE cannot be counted against the limit.
830 if (OtherMI->isDebugValue())
831 continue;
832 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
833 return false;
834 ++NumVisited;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000835 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
836 OtherMI->isBranch() || OtherMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000837 // Don't move pass calls, etc.
838 return false;
839 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
840 const MachineOperand &MO = OtherMI->getOperand(i);
841 if (!MO.isReg())
842 continue;
843 unsigned MOReg = MO.getReg();
844 if (!MOReg)
845 continue;
846 if (MO.isDef()) {
847 if (Uses.count(MOReg))
848 // Physical register use would be clobbered.
849 return false;
850 if (!MO.isDead() && Defs.count(MOReg))
851 // May clobber a physical register def.
852 // FIXME: This may be too conservative. It's ok if the instruction
853 // is sunken completely below the use.
854 return false;
855 } else {
856 if (Defs.count(MOReg))
857 return false;
Cameron Zwarich80885e52013-02-23 04:49:13 +0000858 bool isKill = MO.isKill() ||
859 (LIS && isPlainlyKilled(OtherMI, MOReg, LIS));
Evan Cheng9bad88a2011-11-16 03:47:42 +0000860 if (MOReg != Reg &&
Cameron Zwarich80885e52013-02-23 04:49:13 +0000861 ((isKill && Uses.count(MOReg)) || Kills.count(MOReg)))
Evan Cheng2a4410d2011-11-14 19:48:55 +0000862 // Don't want to extend other live ranges and update kills.
863 return false;
Cameron Zwarich80885e52013-02-23 04:49:13 +0000864 if (MOReg == Reg && !isKill)
Chandler Carruth7d532c82012-07-15 03:29:46 +0000865 // We can't schedule across a use of the register in question.
866 return false;
867 // Ensure that if this is register in question, its the kill we expect.
868 assert((MOReg != Reg || OtherMI == KillMI) &&
869 "Found multiple kills of a register in a basic block");
Evan Cheng2a4410d2011-11-14 19:48:55 +0000870 }
871 }
872 }
873
874 // Move debug info as well.
Cameron Zwarich80885e52013-02-23 04:49:13 +0000875 while (Begin != MBB->begin() && llvm::prior(Begin)->isDebugValue())
876 --Begin;
877
878 nmi = End;
879 MachineBasicBlock::iterator InsertPos = KillPos;
880 if (LIS) {
881 // We have to move the copies first so that the MBB is still well-formed
882 // when calling handleMove().
883 for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) {
884 MachineInstr *CopyMI = MBBI;
885 ++MBBI;
886 MBB->splice(InsertPos, MBB, CopyMI);
887 LIS->handleMove(CopyMI);
888 InsertPos = CopyMI;
889 }
890 End = llvm::next(MachineBasicBlock::iterator(MI));
891 }
Evan Cheng2a4410d2011-11-14 19:48:55 +0000892
893 // Copies following MI may have been moved as well.
Cameron Zwarich80885e52013-02-23 04:49:13 +0000894 MBB->splice(InsertPos, MBB, Begin, End);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000895 DistanceMap.erase(DI);
896
Chandler Carruth7d532c82012-07-15 03:29:46 +0000897 // Update live variables
Cameron Zwarich80885e52013-02-23 04:49:13 +0000898 if (LIS) {
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000899 LIS->handleMove(MI);
Cameron Zwarich80885e52013-02-23 04:49:13 +0000900 } else {
901 LV->removeVirtualRegisterKilled(Reg, KillMI);
902 LV->addVirtualRegisterKilled(Reg, MI);
903 }
Evan Cheng2a4410d2011-11-14 19:48:55 +0000904
Jakob Stoklund Olesena532bce2012-07-17 17:57:23 +0000905 DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000906 return true;
907}
908
909/// isDefTooClose - Return true if the re-scheduling will put the given
910/// instruction too close to the defs of its register dependencies.
911bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000912 MachineInstr *MI) {
Evan Cheng2a4410d2011-11-14 19:48:55 +0000913 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(Reg),
914 DE = MRI->def_end(); DI != DE; ++DI) {
915 MachineInstr *DefMI = &*DI;
916 if (DefMI->getParent() != MBB || DefMI->isCopy() || DefMI->isCopyLike())
917 continue;
918 if (DefMI == MI)
919 return true; // MI is defining something KillMI uses
920 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(DefMI);
921 if (DDI == DistanceMap.end())
922 return true; // Below MI
923 unsigned DefDist = DDI->second;
924 assert(Dist > DefDist && "Visited def already?");
Andrew Trickb7e02892012-06-05 21:11:27 +0000925 if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist))
Evan Cheng2a4410d2011-11-14 19:48:55 +0000926 return true;
927 }
928 return false;
929}
930
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000931/// rescheduleKillAboveMI - If there is one more local instruction that reads
Evan Cheng2a4410d2011-11-14 19:48:55 +0000932/// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
933/// current two-address instruction in order to eliminate the need for the
934/// copy.
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000935bool TwoAddressInstructionPass::
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000936rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +0000937 MachineBasicBlock::iterator &nmi,
938 unsigned Reg) {
Cameron Zwarich80885e52013-02-23 04:49:13 +0000939 // Bail immediately if we don't have LV or LIS available. We use them to find
940 // kills efficiently.
941 if (!LV && !LIS)
Chandler Carruth7d532c82012-07-15 03:29:46 +0000942 return false;
943
Evan Cheng2a4410d2011-11-14 19:48:55 +0000944 MachineInstr *MI = &*mi;
945 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
946 if (DI == DistanceMap.end())
947 // Must be created from unfolded load. Don't waste time trying this.
948 return false;
949
Cameron Zwarich80885e52013-02-23 04:49:13 +0000950 MachineInstr *KillMI = 0;
951 if (LIS) {
952 LiveInterval &LI = LIS->getInterval(Reg);
953 assert(LI.end() != LI.begin() &&
954 "Reg should not have empty live interval.");
955
956 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
957 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
958 if (I != LI.end() && I->start < MBBEndIdx)
959 return false;
960
961 --I;
962 KillMI = LIS->getInstructionFromIndex(I->end);
963 } else {
964 KillMI = LV->getVarInfo(Reg).findKill(MBB);
965 }
Chandler Carruth7d532c82012-07-15 03:29:46 +0000966 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000967 // Don't mess with copies, they may be coalesced later.
968 return false;
969
970 unsigned DstReg;
971 if (isTwoAddrUse(*KillMI, Reg, DstReg))
972 return false;
973
Evan Chengf1784182011-11-15 06:26:51 +0000974 bool SeenStore = true;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000975 if (!KillMI->isSafeToMove(TII, AA, SeenStore))
976 return false;
977
978 SmallSet<unsigned, 2> Uses;
979 SmallSet<unsigned, 2> Kills;
980 SmallSet<unsigned, 2> Defs;
981 SmallSet<unsigned, 2> LiveDefs;
982 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
983 const MachineOperand &MO = KillMI->getOperand(i);
984 if (!MO.isReg())
985 continue;
986 unsigned MOReg = MO.getReg();
987 if (MO.isUse()) {
988 if (!MOReg)
989 continue;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +0000990 if (isDefTooClose(MOReg, DI->second, MI))
Evan Cheng2a4410d2011-11-14 19:48:55 +0000991 return false;
Cameron Zwarich80885e52013-02-23 04:49:13 +0000992 bool isKill = MO.isKill() || (LIS && isPlainlyKilled(KillMI, MOReg, LIS));
993 if (MOReg == Reg && !isKill)
Chandler Carruth7d532c82012-07-15 03:29:46 +0000994 return false;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000995 Uses.insert(MOReg);
Cameron Zwarich80885e52013-02-23 04:49:13 +0000996 if (isKill && MOReg != Reg)
Evan Cheng2a4410d2011-11-14 19:48:55 +0000997 Kills.insert(MOReg);
998 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
999 Defs.insert(MOReg);
1000 if (!MO.isDead())
1001 LiveDefs.insert(MOReg);
1002 }
1003 }
1004
1005 // Check if the reschedule will not break depedencies.
1006 unsigned NumVisited = 0;
1007 MachineBasicBlock::iterator KillPos = KillMI;
1008 for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
1009 MachineInstr *OtherMI = I;
1010 // DBG_VALUE cannot be counted against the limit.
1011 if (OtherMI->isDebugValue())
1012 continue;
1013 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
1014 return false;
1015 ++NumVisited;
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001016 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
1017 OtherMI->isBranch() || OtherMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +00001018 // Don't move pass calls, etc.
1019 return false;
Evan Chengae7db7a2011-11-16 03:05:12 +00001020 SmallVector<unsigned, 2> OtherDefs;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001021 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
1022 const MachineOperand &MO = OtherMI->getOperand(i);
1023 if (!MO.isReg())
1024 continue;
1025 unsigned MOReg = MO.getReg();
1026 if (!MOReg)
1027 continue;
1028 if (MO.isUse()) {
1029 if (Defs.count(MOReg))
1030 // Moving KillMI can clobber the physical register if the def has
1031 // not been seen.
1032 return false;
1033 if (Kills.count(MOReg))
1034 // Don't want to extend other live ranges and update kills.
1035 return false;
Cameron Zwarich80885e52013-02-23 04:49:13 +00001036 if (OtherMI != MI && MOReg == Reg &&
1037 !(MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))))
Chandler Carruth7d532c82012-07-15 03:29:46 +00001038 // We can't schedule across a use of the register in question.
1039 return false;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001040 } else {
Evan Chengae7db7a2011-11-16 03:05:12 +00001041 OtherDefs.push_back(MOReg);
Evan Cheng2a4410d2011-11-14 19:48:55 +00001042 }
1043 }
Evan Chengae7db7a2011-11-16 03:05:12 +00001044
1045 for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
1046 unsigned MOReg = OtherDefs[i];
1047 if (Uses.count(MOReg))
1048 return false;
1049 if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1050 LiveDefs.count(MOReg))
1051 return false;
1052 // Physical register def is seen.
1053 Defs.erase(MOReg);
1054 }
Evan Cheng2a4410d2011-11-14 19:48:55 +00001055 }
1056
1057 // Move the old kill above MI, don't forget to move debug info as well.
1058 MachineBasicBlock::iterator InsertPos = mi;
Evan Cheng8aee7d82011-11-14 21:11:15 +00001059 while (InsertPos != MBB->begin() && llvm::prior(InsertPos)->isDebugValue())
1060 --InsertPos;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001061 MachineBasicBlock::iterator From = KillMI;
1062 MachineBasicBlock::iterator To = llvm::next(From);
1063 while (llvm::prior(From)->isDebugValue())
1064 --From;
1065 MBB->splice(InsertPos, MBB, From, To);
1066
Evan Cheng2bee6a82011-11-16 03:33:08 +00001067 nmi = llvm::prior(InsertPos); // Backtrack so we process the moved instr.
Evan Cheng2a4410d2011-11-14 19:48:55 +00001068 DistanceMap.erase(DI);
1069
Chandler Carruth7d532c82012-07-15 03:29:46 +00001070 // Update live variables
Cameron Zwarich80885e52013-02-23 04:49:13 +00001071 if (LIS) {
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +00001072 LIS->handleMove(KillMI);
Cameron Zwarich80885e52013-02-23 04:49:13 +00001073 } else {
1074 LV->removeVirtualRegisterKilled(Reg, KillMI);
1075 LV->addVirtualRegisterKilled(Reg, MI);
1076 }
Chandler Carruth7d532c82012-07-15 03:29:46 +00001077
Jakob Stoklund Olesena532bce2012-07-17 17:57:23 +00001078 DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
Evan Cheng2a4410d2011-11-14 19:48:55 +00001079 return true;
1080}
1081
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001082/// tryInstructionTransform - For the case where an instruction has a single
Bob Wilsoncc80df92009-09-03 20:58:42 +00001083/// pair of tied register operands, attempt some transformations that may
1084/// either eliminate the tied operands or improve the opportunities for
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001085/// coalescing away the register copy. Returns true if no copy needs to be
1086/// inserted to untie mi's operands (either because they were untied, or
Cameron Zwarichc5a63492013-02-24 00:27:26 +00001087/// because mi was rescheduled, and will be visited again later). If the
1088/// shouldOnlyCommute flag is true, only instruction commutation is attempted.
Bob Wilsoncc80df92009-09-03 20:58:42 +00001089bool TwoAddressInstructionPass::
Jakob Stoklund Olesen6db89362012-10-26 21:12:49 +00001090tryInstructionTransform(MachineBasicBlock::iterator &mi,
Bob Wilsoncc80df92009-09-03 20:58:42 +00001091 MachineBasicBlock::iterator &nmi,
Cameron Zwarichc5a63492013-02-24 00:27:26 +00001092 unsigned SrcIdx, unsigned DstIdx,
1093 unsigned Dist, bool shouldOnlyCommute) {
Evan Chengc3aa7c52011-11-16 18:44:48 +00001094 if (OptLevel == CodeGenOpt::None)
1095 return false;
1096
Evan Cheng2a4410d2011-11-14 19:48:55 +00001097 MachineInstr &MI = *mi;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001098 unsigned regA = MI.getOperand(DstIdx).getReg();
1099 unsigned regB = MI.getOperand(SrcIdx).getReg();
Bob Wilsoncc80df92009-09-03 20:58:42 +00001100
1101 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1102 "cannot make instruction into two-address form");
Cameron Zwaricha931a122013-02-21 22:58:42 +00001103 bool regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
Bob Wilsoncc80df92009-09-03 20:58:42 +00001104
Evan Chengd99d68b2012-05-03 01:45:13 +00001105 if (TargetRegisterInfo::isVirtualRegister(regA))
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001106 scanUses(regA);
Evan Chengd99d68b2012-05-03 01:45:13 +00001107
Bob Wilsoncc80df92009-09-03 20:58:42 +00001108 // Check if it is profitable to commute the operands.
1109 unsigned SrcOp1, SrcOp2;
1110 unsigned regC = 0;
1111 unsigned regCIdx = ~0U;
1112 bool TryCommute = false;
1113 bool AggressiveCommute = false;
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001114 if (MI.isCommutable() && MI.getNumOperands() >= 3 &&
Evan Cheng2a4410d2011-11-14 19:48:55 +00001115 TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001116 if (SrcIdx == SrcOp1)
1117 regCIdx = SrcOp2;
1118 else if (SrcIdx == SrcOp2)
1119 regCIdx = SrcOp1;
1120
1121 if (regCIdx != ~0U) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001122 regC = MI.getOperand(regCIdx).getReg();
Cameron Zwaricha931a122013-02-21 22:58:42 +00001123 if (!regBKilled && isKilled(MI, regC, MRI, TII, LIS, false))
Bob Wilsoncc80df92009-09-03 20:58:42 +00001124 // If C dies but B does not, swap the B and C operands.
1125 // This makes the live ranges of A and C joinable.
1126 TryCommute = true;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001127 else if (isProfitableToCommute(regA, regB, regC, &MI, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001128 TryCommute = true;
1129 AggressiveCommute = true;
1130 }
1131 }
1132 }
1133
1134 // If it's profitable to commute, try to do so.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001135 if (TryCommute && commuteInstruction(mi, regB, regC, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001136 ++NumCommuted;
1137 if (AggressiveCommute)
1138 ++NumAggrCommuted;
1139 return false;
1140 }
1141
Cameron Zwarichc5a63492013-02-24 00:27:26 +00001142 if (shouldOnlyCommute)
1143 return false;
1144
Evan Cheng2a4410d2011-11-14 19:48:55 +00001145 // If there is one more use of regB later in the same MBB, consider
1146 // re-schedule this MI below it.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001147 if (rescheduleMIBelowKill(mi, nmi, regB)) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001148 ++NumReSchedDowns;
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001149 return true;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001150 }
1151
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001152 if (MI.isConvertibleTo3Addr()) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001153 // This instruction is potentially convertible to a true
1154 // three-address instruction. Check if it is profitable.
Evan Chengf06e6c22011-03-02 01:08:17 +00001155 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001156 // Try to convert it.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001157 if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001158 ++NumConvertedTo3Addr;
1159 return true; // Done with this instruction.
1160 }
1161 }
1162 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001163
Evan Cheng2a4410d2011-11-14 19:48:55 +00001164 // If there is one more use of regB later in the same MBB, consider
1165 // re-schedule it before this MI if it's legal.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001166 if (rescheduleKillAboveMI(mi, nmi, regB)) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001167 ++NumReSchedUps;
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001168 return true;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001169 }
1170
Dan Gohman584fedf2010-06-21 22:17:20 +00001171 // If this is an instruction with a load folded into it, try unfolding
1172 // the load, e.g. avoid this:
1173 // movq %rdx, %rcx
1174 // addq (%rax), %rcx
1175 // in favor of this:
1176 // movq (%rax), %rcx
1177 // addq %rdx, %rcx
1178 // because it's preferable to schedule a load than a register copy.
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001179 if (MI.mayLoad() && !regBKilled) {
Dan Gohman584fedf2010-06-21 22:17:20 +00001180 // Determine if a load can be unfolded.
1181 unsigned LoadRegIndex;
1182 unsigned NewOpc =
Evan Cheng2a4410d2011-11-14 19:48:55 +00001183 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
Dan Gohman584fedf2010-06-21 22:17:20 +00001184 /*UnfoldLoad=*/true,
1185 /*UnfoldStore=*/false,
1186 &LoadRegIndex);
1187 if (NewOpc != 0) {
Evan Chenge837dea2011-06-28 19:10:37 +00001188 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1189 if (UnfoldMCID.getNumDefs() == 1) {
Dan Gohman584fedf2010-06-21 22:17:20 +00001190 // Unfold the load.
Evan Cheng2a4410d2011-11-14 19:48:55 +00001191 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
Dan Gohman584fedf2010-06-21 22:17:20 +00001192 const TargetRegisterClass *RC =
Andrew Trickf12f6df2012-05-03 01:14:37 +00001193 TRI->getAllocatableClass(
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001194 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
Dan Gohman584fedf2010-06-21 22:17:20 +00001195 unsigned Reg = MRI->createVirtualRegister(RC);
1196 SmallVector<MachineInstr *, 2> NewMIs;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001197 if (!TII->unfoldMemoryOperand(*MF, &MI, Reg,
Evan Cheng98ec91e2010-07-02 20:36:18 +00001198 /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
1199 NewMIs)) {
1200 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1201 return false;
1202 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001203 assert(NewMIs.size() == 2 &&
1204 "Unfolded a load into multiple instructions!");
1205 // The load was previously folded, so this is the only use.
1206 NewMIs[1]->addRegisterKilled(Reg, TRI);
1207
1208 // Tentatively insert the instructions into the block so that they
1209 // look "normal" to the transformation logic.
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001210 MBB->insert(mi, NewMIs[0]);
1211 MBB->insert(mi, NewMIs[1]);
Dan Gohman584fedf2010-06-21 22:17:20 +00001212
1213 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1214 << "2addr: NEW INST: " << *NewMIs[1]);
1215
1216 // Transform the instruction, now that it no longer has a load.
1217 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1218 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1219 MachineBasicBlock::iterator NewMI = NewMIs[1];
Cameron Zwaricheb1b7252013-02-24 00:27:29 +00001220 bool TransformResult =
Cameron Zwarichc5a63492013-02-24 00:27:26 +00001221 tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true);
Cameron Zwarichcc6137e2013-02-24 01:26:05 +00001222 (void)TransformResult;
Cameron Zwaricheb1b7252013-02-24 00:27:29 +00001223 assert(!TransformResult &&
1224 "tryInstructionTransform() should return false.");
1225 if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
Dan Gohman584fedf2010-06-21 22:17:20 +00001226 // Success, or at least we made an improvement. Keep the unfolded
1227 // instructions and discard the original.
1228 if (LV) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001229 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1230 MachineOperand &MO = MI.getOperand(i);
Andrew Trick8247e0d2012-02-03 05:12:30 +00001231 if (MO.isReg() &&
Dan Gohman7aa7bc72010-06-22 00:32:04 +00001232 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1233 if (MO.isUse()) {
Dan Gohmancc1ca982010-06-22 02:07:21 +00001234 if (MO.isKill()) {
1235 if (NewMIs[0]->killsRegister(MO.getReg()))
Evan Cheng2a4410d2011-11-14 19:48:55 +00001236 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
Dan Gohmancc1ca982010-06-22 02:07:21 +00001237 else {
1238 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1239 "Kill missing after load unfold!");
Evan Cheng2a4410d2011-11-14 19:48:55 +00001240 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
Dan Gohmancc1ca982010-06-22 02:07:21 +00001241 }
1242 }
Evan Cheng2a4410d2011-11-14 19:48:55 +00001243 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
Dan Gohmancc1ca982010-06-22 02:07:21 +00001244 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1245 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
1246 else {
1247 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1248 "Dead flag missing after load unfold!");
1249 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
1250 }
1251 }
Dan Gohman7aa7bc72010-06-22 00:32:04 +00001252 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001253 }
1254 LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
1255 }
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001256
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001257 SmallVector<unsigned, 4> OrigRegs;
1258 if (LIS) {
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001259 for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(),
1260 MOE = MI.operands_end(); MOI != MOE; ++MOI) {
1261 if (MOI->isReg())
1262 OrigRegs.push_back(MOI->getReg());
1263 }
1264 }
1265
Evan Cheng2a4410d2011-11-14 19:48:55 +00001266 MI.eraseFromParent();
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001267
1268 // Update LiveIntervals.
Cameron Zwarichc5b61352013-02-20 22:10:00 +00001269 if (LIS) {
1270 MachineBasicBlock::iterator Begin(NewMIs[0]);
1271 MachineBasicBlock::iterator End(NewMIs[1]);
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001272 LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs);
Cameron Zwarichc5b61352013-02-20 22:10:00 +00001273 }
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001274
Dan Gohman584fedf2010-06-21 22:17:20 +00001275 mi = NewMIs[1];
Dan Gohman584fedf2010-06-21 22:17:20 +00001276 } else {
1277 // Transforming didn't eliminate the tie and didn't lead to an
1278 // improvement. Clean up the unfolded instructions and keep the
1279 // original.
1280 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1281 NewMIs[0]->eraseFromParent();
1282 NewMIs[1]->eraseFromParent();
1283 }
1284 }
1285 }
1286 }
1287
Bob Wilsoncc80df92009-09-03 20:58:42 +00001288 return false;
1289}
1290
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001291// Collect tied operands of MI that need to be handled.
1292// Rewrite trivial cases immediately.
1293// Return true if any tied operands where found, including the trivial ones.
1294bool TwoAddressInstructionPass::
1295collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
1296 const MCInstrDesc &MCID = MI->getDesc();
1297 bool AnyOps = false;
Jakob Stoklund Olesenf363ebd2012-09-04 22:59:30 +00001298 unsigned NumOps = MI->getNumOperands();
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001299
1300 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1301 unsigned DstIdx = 0;
1302 if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1303 continue;
1304 AnyOps = true;
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001305 MachineOperand &SrcMO = MI->getOperand(SrcIdx);
1306 MachineOperand &DstMO = MI->getOperand(DstIdx);
1307 unsigned SrcReg = SrcMO.getReg();
1308 unsigned DstReg = DstMO.getReg();
1309 // Tied constraint already satisfied?
1310 if (SrcReg == DstReg)
1311 continue;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001312
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001313 assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001314
1315 // Deal with <undef> uses immediately - simply rewrite the src operand.
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001316 if (SrcMO.isUndef()) {
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001317 // Constrain the DstReg register class if required.
1318 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1319 if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
1320 TRI, *MF))
1321 MRI->constrainRegClass(DstReg, RC);
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001322 SrcMO.setReg(DstReg);
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001323 DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
1324 continue;
1325 }
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001326 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001327 }
1328 return AnyOps;
1329}
1330
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001331// Process a list of tied MI operands that all use the same source register.
1332// The tied pairs are of the form (SrcIdx, DstIdx).
1333void
1334TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
1335 TiedPairList &TiedPairs,
1336 unsigned &Dist) {
1337 bool IsEarlyClobber = false;
Cameron Zwarich6cf93d72013-02-20 06:46:46 +00001338 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1339 const MachineOperand &DstMO = MI->getOperand(TiedPairs[tpi].second);
1340 IsEarlyClobber |= DstMO.isEarlyClobber();
1341 }
1342
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001343 bool RemovedKillFlag = false;
1344 bool AllUsesCopied = true;
1345 unsigned LastCopiedReg = 0;
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001346 SlotIndex LastCopyIdx;
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001347 unsigned RegB = 0;
1348 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1349 unsigned SrcIdx = TiedPairs[tpi].first;
1350 unsigned DstIdx = TiedPairs[tpi].second;
1351
1352 const MachineOperand &DstMO = MI->getOperand(DstIdx);
1353 unsigned RegA = DstMO.getReg();
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001354
1355 // Grab RegB from the instruction because it may have changed if the
1356 // instruction was commuted.
1357 RegB = MI->getOperand(SrcIdx).getReg();
1358
1359 if (RegA == RegB) {
1360 // The register is tied to multiple destinations (or else we would
1361 // not have continued this far), but this use of the register
1362 // already matches the tied destination. Leave it.
1363 AllUsesCopied = false;
1364 continue;
1365 }
1366 LastCopiedReg = RegA;
1367
1368 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1369 "cannot make instruction into two-address form");
1370
1371#ifndef NDEBUG
1372 // First, verify that we don't have a use of "a" in the instruction
1373 // (a = b + a for example) because our transformation will not
1374 // work. This should never occur because we are in SSA form.
1375 for (unsigned i = 0; i != MI->getNumOperands(); ++i)
1376 assert(i == DstIdx ||
1377 !MI->getOperand(i).isReg() ||
1378 MI->getOperand(i).getReg() != RegA);
1379#endif
1380
1381 // Emit a copy.
1382 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1383 TII->get(TargetOpcode::COPY), RegA).addReg(RegB);
1384
1385 // Update DistanceMap.
1386 MachineBasicBlock::iterator PrevMI = MI;
1387 --PrevMI;
1388 DistanceMap.insert(std::make_pair(PrevMI, Dist));
1389 DistanceMap[MI] = ++Dist;
1390
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001391 if (LIS) {
1392 LastCopyIdx = LIS->InsertMachineInstrInMaps(PrevMI).getRegSlot();
1393
1394 if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1395 LiveInterval &LI = LIS->getInterval(RegA);
1396 VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1397 SlotIndex endIdx =
1398 LIS->getInstructionIndex(MI).getRegSlot(IsEarlyClobber);
1399 LI.addRange(LiveRange(LastCopyIdx, endIdx, VNI));
1400 }
1401 }
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001402
1403 DEBUG(dbgs() << "\t\tprepend:\t" << *PrevMI);
1404
1405 MachineOperand &MO = MI->getOperand(SrcIdx);
1406 assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
1407 "inconsistent operand info for 2-reg pass");
1408 if (MO.isKill()) {
1409 MO.setIsKill(false);
1410 RemovedKillFlag = true;
1411 }
1412
1413 // Make sure regA is a legal regclass for the SrcIdx operand.
1414 if (TargetRegisterInfo::isVirtualRegister(RegA) &&
1415 TargetRegisterInfo::isVirtualRegister(RegB))
1416 MRI->constrainRegClass(RegA, MRI->getRegClass(RegB));
1417
1418 MO.setReg(RegA);
1419
1420 // Propagate SrcRegMap.
1421 SrcRegMap[RegA] = RegB;
1422 }
1423
1424
1425 if (AllUsesCopied) {
1426 if (!IsEarlyClobber) {
1427 // Replace other (un-tied) uses of regB with LastCopiedReg.
1428 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1429 MachineOperand &MO = MI->getOperand(i);
1430 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1431 if (MO.isKill()) {
1432 MO.setIsKill(false);
1433 RemovedKillFlag = true;
1434 }
1435 MO.setReg(LastCopiedReg);
1436 }
1437 }
1438 }
1439
1440 // Update live variables for regB.
1441 if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(MI)) {
1442 MachineBasicBlock::iterator PrevMI = MI;
1443 --PrevMI;
1444 LV->addVirtualRegisterKilled(RegB, PrevMI);
1445 }
1446
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001447 // Update LiveIntervals.
1448 if (LIS) {
1449 LiveInterval &LI = LIS->getInterval(RegB);
1450 SlotIndex MIIdx = LIS->getInstructionIndex(MI);
1451 LiveInterval::const_iterator I = LI.find(MIIdx);
1452 assert(I != LI.end() && "RegB must be live-in to use.");
1453
1454 SlotIndex UseIdx = MIIdx.getRegSlot(IsEarlyClobber);
1455 if (I->end == UseIdx)
1456 LI.removeRange(LastCopyIdx, UseIdx);
1457 }
1458
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001459 } else if (RemovedKillFlag) {
1460 // Some tied uses of regB matched their destination registers, so
1461 // regB is still used in this instruction, but a kill flag was
1462 // removed from a different tied use of regB, so now we need to add
1463 // a kill flag to one of the remaining uses of regB.
1464 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1465 MachineOperand &MO = MI->getOperand(i);
1466 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1467 MO.setIsKill(true);
1468 break;
1469 }
1470 }
1471 }
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001472}
1473
Bill Wendling637980e2008-05-10 00:12:52 +00001474/// runOnMachineFunction - Reduce two-address instructions to two operands.
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001475///
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001476bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
1477 MF = &Func;
1478 const TargetMachine &TM = MF->getTarget();
1479 MRI = &MF->getRegInfo();
Evan Cheng875357d2008-03-13 06:37:55 +00001480 TII = TM.getInstrInfo();
1481 TRI = TM.getRegisterInfo();
Evan Cheng2a4410d2011-11-14 19:48:55 +00001482 InstrItins = TM.getInstrItineraryData();
Duncan Sands1465d612009-01-28 13:14:17 +00001483 LV = getAnalysisIfAvailable<LiveVariables>();
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +00001484 LIS = getAnalysisIfAvailable<LiveIntervals>();
Dan Gohmana70dca12009-10-09 23:27:56 +00001485 AA = &getAnalysis<AliasAnalysis>();
Evan Chengc3aa7c52011-11-16 18:44:48 +00001486 OptLevel = TM.getOptLevel();
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001487
Misha Brukman75fa4e42004-07-22 15:26:23 +00001488 bool MadeChange = false;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001489
David Greeneeb00b182010-01-05 01:24:21 +00001490 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
Andrew Trick8247e0d2012-02-03 05:12:30 +00001491 DEBUG(dbgs() << "********** Function: "
Craig Topper96601ca2012-08-22 06:07:19 +00001492 << MF->getName() << '\n');
Alkis Evlogimenos3a9986f2004-02-18 00:35:06 +00001493
Jakob Stoklund Olesen73e7dce2011-07-29 22:51:22 +00001494 // This pass takes the function out of SSA form.
1495 MRI->leaveSSA();
1496
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001497 TiedOperandMap TiedOperands;
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001498 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
1499 MBBI != MBBE; ++MBBI) {
1500 MBB = MBBI;
Evan Cheng7543e582008-06-18 07:49:14 +00001501 unsigned Dist = 0;
1502 DistanceMap.clear();
Evan Cheng870b8072009-03-01 02:03:43 +00001503 SrcRegMap.clear();
1504 DstRegMap.clear();
1505 Processed.clear();
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001506 for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001507 mi != me; ) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001508 MachineBasicBlock::iterator nmi = llvm::next(mi);
Dale Johannesenb8ff9342010-02-10 21:47:48 +00001509 if (mi->isDebugValue()) {
1510 mi = nmi;
1511 continue;
1512 }
Evan Chengf1250ee2010-03-23 20:36:12 +00001513
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001514 // Expand REG_SEQUENCE instructions. This will position mi at the first
1515 // expanded instruction.
Evan Cheng3d720fb2010-05-05 18:45:40 +00001516 if (mi->isRegSequence())
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001517 eliminateRegSequence(mi);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001518
Evan Cheng7543e582008-06-18 07:49:14 +00001519 DistanceMap.insert(std::make_pair(mi, ++Dist));
Evan Cheng870b8072009-03-01 02:03:43 +00001520
Jakob Stoklund Olesen0de4fd22012-10-26 23:05:10 +00001521 processCopy(&*mi);
Evan Cheng870b8072009-03-01 02:03:43 +00001522
Bob Wilsoncc80df92009-09-03 20:58:42 +00001523 // First scan through all the tied register uses in this instruction
1524 // and record a list of pairs of tied operands for each register.
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001525 if (!collectTiedOperands(mi, TiedOperands)) {
1526 mi = nmi;
1527 continue;
Bob Wilsoncc80df92009-09-03 20:58:42 +00001528 }
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001529
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001530 ++NumTwoAddressInstrs;
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001531 MadeChange = true;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001532 DEBUG(dbgs() << '\t' << *mi);
1533
Chandler Carruth32d75be2012-07-18 18:58:22 +00001534 // If the instruction has a single pair of tied operands, try some
1535 // transformations that may either eliminate the tied operands or
1536 // improve the opportunities for coalescing away the register copy.
1537 if (TiedOperands.size() == 1) {
1538 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs
1539 = TiedOperands.begin()->second;
1540 if (TiedPairs.size() == 1) {
1541 unsigned SrcIdx = TiedPairs[0].first;
1542 unsigned DstIdx = TiedPairs[0].second;
1543 unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
1544 unsigned DstReg = mi->getOperand(DstIdx).getReg();
1545 if (SrcReg != DstReg &&
Cameron Zwarichc5a63492013-02-24 00:27:26 +00001546 tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) {
Chandler Carruth32d75be2012-07-18 18:58:22 +00001547 // The tied operands have been eliminated or shifted further down the
1548 // block to ease elimination. Continue processing with 'nmi'.
1549 TiedOperands.clear();
1550 mi = nmi;
1551 continue;
1552 }
1553 }
1554 }
1555
Bob Wilsoncc80df92009-09-03 20:58:42 +00001556 // Now iterate over the information collected above.
1557 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1558 OE = TiedOperands.end(); OI != OE; ++OI) {
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001559 processTiedPairs(mi, OI->second, Dist);
David Greeneeb00b182010-01-05 01:24:21 +00001560 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
Jakob Stoklund Olesen351c8812012-06-25 03:27:12 +00001561 }
Bill Wendling637980e2008-05-10 00:12:52 +00001562
Jakob Stoklund Olesen351c8812012-06-25 03:27:12 +00001563 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1564 if (mi->isInsertSubreg()) {
1565 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1566 // To %reg:subidx = COPY %subreg
1567 unsigned SubIdx = mi->getOperand(3).getImm();
1568 mi->RemoveOperand(3);
1569 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1570 mi->getOperand(0).setSubReg(SubIdx);
1571 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1572 mi->RemoveOperand(1);
1573 mi->setDesc(TII->get(TargetOpcode::COPY));
1574 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
Jakob Stoklund Olesened2185e2010-07-06 23:26:25 +00001575 }
1576
Bob Wilsoncc80df92009-09-03 20:58:42 +00001577 // Clear TiedOperands here instead of at the top of the loop
1578 // since most instructions do not have tied operands.
1579 TiedOperands.clear();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001580 mi = nmi;
Misha Brukman75fa4e42004-07-22 15:26:23 +00001581 }
1582 }
1583
Cameron Zwarich767e0432013-02-20 06:46:34 +00001584 if (LIS)
1585 MF->verify(this, "After two-address instruction pass");
1586
Misha Brukman75fa4e42004-07-22 15:26:23 +00001587 return MadeChange;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001588}
Evan Cheng3d720fb2010-05-05 18:45:40 +00001589
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001590/// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process.
Evan Cheng3d720fb2010-05-05 18:45:40 +00001591///
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001592/// The instruction is turned into a sequence of sub-register copies:
1593///
1594/// %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1
1595///
1596/// Becomes:
1597///
1598/// %dst:ssub0<def,undef> = COPY %v1
1599/// %dst:ssub1<def> = COPY %v2
1600///
1601void TwoAddressInstructionPass::
1602eliminateRegSequence(MachineBasicBlock::iterator &MBBI) {
1603 MachineInstr *MI = MBBI;
1604 unsigned DstReg = MI->getOperand(0).getReg();
1605 if (MI->getOperand(0).getSubReg() ||
1606 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1607 !(MI->getNumOperands() & 1)) {
1608 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1609 llvm_unreachable(0);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001610 }
1611
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001612 SmallVector<unsigned, 4> OrigRegs;
1613 if (LIS) {
1614 OrigRegs.push_back(MI->getOperand(0).getReg());
1615 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2)
1616 OrigRegs.push_back(MI->getOperand(i).getReg());
1617 }
1618
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001619 bool DefEmitted = false;
1620 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1621 MachineOperand &UseMO = MI->getOperand(i);
1622 unsigned SrcReg = UseMO.getReg();
1623 unsigned SubIdx = MI->getOperand(i+1).getImm();
1624 // Nothing needs to be inserted for <undef> operands.
1625 if (UseMO.isUndef())
1626 continue;
1627
1628 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1629 // might insert a COPY that uses SrcReg after is was killed.
1630 bool isKill = UseMO.isKill();
1631 if (isKill)
1632 for (unsigned j = i + 2; j < e; j += 2)
1633 if (MI->getOperand(j).getReg() == SrcReg) {
1634 MI->getOperand(j).setIsKill();
1635 UseMO.setIsKill(false);
1636 isKill = false;
1637 break;
1638 }
1639
1640 // Insert the sub-register copy.
1641 MachineInstr *CopyMI = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1642 TII->get(TargetOpcode::COPY))
1643 .addReg(DstReg, RegState::Define, SubIdx)
1644 .addOperand(UseMO);
1645
1646 // The first def needs an <undef> flag because there is no live register
1647 // before it.
1648 if (!DefEmitted) {
1649 CopyMI->getOperand(0).setIsUndef(true);
1650 // Return an iterator pointing to the first inserted instr.
1651 MBBI = CopyMI;
1652 }
1653 DefEmitted = true;
1654
1655 // Update LiveVariables' kill info.
1656 if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
1657 LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1658
1659 DEBUG(dbgs() << "Inserted: " << *CopyMI);
1660 }
1661
David Blaikiefdf45172013-02-20 07:39:20 +00001662 MachineBasicBlock::iterator EndMBBI =
1663 llvm::next(MachineBasicBlock::iterator(MI));
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001664
Jakob Stoklund Olesen8c3dccd2012-12-01 01:06:44 +00001665 if (!DefEmitted) {
1666 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1667 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1668 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
1669 MI->RemoveOperand(j);
1670 } else {
1671 DEBUG(dbgs() << "Eliminated: " << *MI);
1672 MI->eraseFromParent();
1673 }
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001674
1675 // Udpate LiveIntervals.
Cameron Zwarichc5b61352013-02-20 22:10:00 +00001676 if (LIS)
Cameron Zwarich9030fc22013-02-20 06:46:48 +00001677 LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001678}