blob: 6bcf7087a7aaa5e9d2e11ec7d1ea29f4aeabe936 [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"
Chris Lattner1e313632004-07-21 23:17:57 +000032#include "llvm/Function.h"
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +000033#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000034#include "llvm/CodeGen/LiveVariables.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000035#include "llvm/CodeGen/MachineFunctionPass.h"
36#include "llvm/CodeGen/MachineInstr.h"
Bob Wilson852a7e32010-06-15 05:56:31 +000037#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000038#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohmana70dca12009-10-09 23:27:56 +000039#include "llvm/Analysis/AliasAnalysis.h"
Evan Cheng2a4410d2011-11-14 19:48:55 +000040#include "llvm/MC/MCInstrItineraries.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000041#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000042#include "llvm/Target/TargetInstrInfo.h"
43#include "llvm/Target/TargetMachine.h"
Owen Anderson95dad832008-10-07 20:22:28 +000044#include "llvm/Target/TargetOptions.h"
Evan Cheng875357d2008-03-13 06:37:55 +000045#include "llvm/Support/Debug.h"
Evan Cheng3d720fb2010-05-05 18:45:40 +000046#include "llvm/Support/ErrorHandling.h"
Evan Cheng7543e582008-06-18 07:49:14 +000047#include "llvm/ADT/BitVector.h"
48#include "llvm/ADT/DenseMap.h"
Dan Gohmand68a0762009-01-05 17:59:02 +000049#include "llvm/ADT/SmallSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000050#include "llvm/ADT/Statistic.h"
51#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000052using namespace llvm;
53
Chris Lattnercd3245a2006-12-19 22:41:21 +000054STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
55STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
Evan Chengd498c8f2009-01-25 03:53:59 +000056STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
Chris Lattnercd3245a2006-12-19 22:41:21 +000057STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
Evan Cheng875357d2008-03-13 06:37:55 +000058STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
Evan Cheng2a4410d2011-11-14 19:48:55 +000059STATISTIC(NumReSchedUps, "Number of instructions re-scheduled up");
60STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down");
Evan Cheng875357d2008-03-13 06:37:55 +000061
62namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000063 class TwoAddressInstructionPass : public MachineFunctionPass {
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +000064 MachineFunction *MF;
Evan Cheng875357d2008-03-13 06:37:55 +000065 const TargetInstrInfo *TII;
66 const TargetRegisterInfo *TRI;
Evan Cheng2a4410d2011-11-14 19:48:55 +000067 const InstrItineraryData *InstrItins;
Evan Cheng875357d2008-03-13 06:37:55 +000068 MachineRegisterInfo *MRI;
69 LiveVariables *LV;
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +000070 SlotIndexes *Indexes;
71 LiveIntervals *LIS;
Dan Gohmana70dca12009-10-09 23:27:56 +000072 AliasAnalysis *AA;
Evan Chengc3aa7c52011-11-16 18:44:48 +000073 CodeGenOpt::Level OptLevel;
Evan Cheng875357d2008-03-13 06:37:55 +000074
Evan Cheng870b8072009-03-01 02:03:43 +000075 // DistanceMap - Keep track the distance of a MI from the start of the
76 // current basic block.
77 DenseMap<MachineInstr*, unsigned> DistanceMap;
78
79 // SrcRegMap - A map from virtual registers to physical registers which
80 // are likely targets to be coalesced to due to copies from physical
81 // registers to virtual registers. e.g. v1024 = move r0.
82 DenseMap<unsigned, unsigned> SrcRegMap;
83
84 // DstRegMap - A map from virtual registers to physical registers which
85 // are likely targets to be coalesced to due to copies to physical
86 // registers from virtual registers. e.g. r1 = move v1024.
87 DenseMap<unsigned, unsigned> DstRegMap;
88
Evan Cheng3d720fb2010-05-05 18:45:40 +000089 /// RegSequences - Keep track the list of REG_SEQUENCE instructions seen
90 /// during the initial walk of the machine function.
91 SmallVector<MachineInstr*, 16> RegSequences;
92
Bill Wendling637980e2008-05-10 00:12:52 +000093 bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
94 unsigned Reg,
95 MachineBasicBlock::iterator OldPos);
Evan Cheng7543e582008-06-18 07:49:14 +000096
Evan Chengd498c8f2009-01-25 03:53:59 +000097 bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
Evan Chengd498c8f2009-01-25 03:53:59 +000098 unsigned &LastDef);
99
Evan Chengd99d68b2012-05-03 01:45:13 +0000100 bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
Evan Chengd498c8f2009-01-25 03:53:59 +0000101 MachineInstr *MI, MachineBasicBlock *MBB,
Evan Cheng870b8072009-03-01 02:03:43 +0000102 unsigned Dist);
Evan Chengd498c8f2009-01-25 03:53:59 +0000103
Evan Cheng81913712009-01-23 23:27:33 +0000104 bool CommuteInstruction(MachineBasicBlock::iterator &mi,
105 MachineFunction::iterator &mbbi,
Evan Cheng870b8072009-03-01 02:03:43 +0000106 unsigned RegB, unsigned RegC, unsigned Dist);
107
Evan Chengf06e6c22011-03-02 01:08:17 +0000108 bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
Evan Chenge6f350d2009-03-30 21:34:07 +0000109
110 bool ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
111 MachineBasicBlock::iterator &nmi,
112 MachineFunction::iterator &mbbi,
Evan Cheng4d96c632011-02-10 02:20:55 +0000113 unsigned RegA, unsigned RegB, unsigned Dist);
Evan Chenge6f350d2009-03-30 21:34:07 +0000114
Evan Cheng2a4410d2011-11-14 19:48:55 +0000115 bool isDefTooClose(unsigned Reg, unsigned Dist,
116 MachineInstr *MI, MachineBasicBlock *MBB);
117
118 bool RescheduleMIBelowKill(MachineBasicBlock *MBB,
119 MachineBasicBlock::iterator &mi,
120 MachineBasicBlock::iterator &nmi,
121 unsigned Reg);
122 bool RescheduleKillAboveMI(MachineBasicBlock *MBB,
123 MachineBasicBlock::iterator &mi,
124 MachineBasicBlock::iterator &nmi,
125 unsigned Reg);
126
Bob Wilsoncc80df92009-09-03 20:58:42 +0000127 bool TryInstructionTransform(MachineBasicBlock::iterator &mi,
128 MachineBasicBlock::iterator &nmi,
129 MachineFunction::iterator &mbbi,
130 unsigned SrcIdx, unsigned DstIdx,
Evan Chengf06e6c22011-03-02 01:08:17 +0000131 unsigned Dist,
132 SmallPtrSet<MachineInstr*, 8> &Processed);
133
134 void ScanUses(unsigned DstReg, MachineBasicBlock *MBB,
135 SmallPtrSet<MachineInstr*, 8> &Processed);
Bob Wilsoncc80df92009-09-03 20:58:42 +0000136
Evan Cheng870b8072009-03-01 02:03:43 +0000137 void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
138 SmallPtrSet<MachineInstr*, 8> &Processed);
Evan Cheng3a3cce52009-08-07 00:28:58 +0000139
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +0000140 typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList;
141 typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +0000142 bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +0000143 void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +0000144
Evan Cheng3d720fb2010-05-05 18:45:40 +0000145 /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
146 /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
147 /// sub-register references of the register defined by REG_SEQUENCE.
148 bool EliminateRegSequences();
Evan Chengc6dcce32010-05-17 23:24:12 +0000149
Evan Cheng875357d2008-03-13 06:37:55 +0000150 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000151 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +0000152 TwoAddressInstructionPass() : MachineFunctionPass(ID) {
153 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
154 }
Devang Patel794fd752007-05-01 21:15:47 +0000155
Bill Wendling637980e2008-05-10 00:12:52 +0000156 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +0000157 AU.setPreservesCFG();
Dan Gohmana70dca12009-10-09 23:27:56 +0000158 AU.addRequired<AliasAnalysis>();
Bill Wendling637980e2008-05-10 00:12:52 +0000159 AU.addPreserved<LiveVariables>();
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000160 AU.addPreserved<SlotIndexes>();
161 AU.addPreserved<LiveIntervals>();
Bill Wendling637980e2008-05-10 00:12:52 +0000162 AU.addPreservedID(MachineLoopInfoID);
163 AU.addPreservedID(MachineDominatorsID);
Bill Wendling637980e2008-05-10 00:12:52 +0000164 MachineFunctionPass::getAnalysisUsage(AU);
165 }
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000166
Bill Wendling637980e2008-05-10 00:12:52 +0000167 /// runOnMachineFunction - Pass entry point.
Misha Brukman75fa4e42004-07-22 15:26:23 +0000168 bool runOnMachineFunction(MachineFunction&);
169 };
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000170}
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000171
Dan Gohman844731a2008-05-13 00:00:25 +0000172char TwoAddressInstructionPass::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000173INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
174 "Two-Address instruction pass", false, false)
175INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
176INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
Owen Andersonce665bd2010-10-07 22:25:06 +0000177 "Two-Address instruction pass", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000178
Owen Anderson90c579d2010-08-06 18:33:48 +0000179char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000180
Evan Cheng875357d2008-03-13 06:37:55 +0000181/// Sink3AddrInstruction - A two-address instruction has been converted to a
182/// three-address instruction to avoid clobbering a register. Try to sink it
Bill Wendling637980e2008-05-10 00:12:52 +0000183/// past the instruction that would kill the above mentioned register to reduce
184/// register pressure.
Evan Cheng875357d2008-03-13 06:37:55 +0000185bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
186 MachineInstr *MI, unsigned SavedReg,
187 MachineBasicBlock::iterator OldPos) {
Eli Friedmanbde81d52011-09-23 22:41:57 +0000188 // FIXME: Shouldn't we be trying to do this before we three-addressify the
189 // instruction? After this transformation is done, we no longer need
190 // the instruction to be in three-address form.
191
Evan Cheng875357d2008-03-13 06:37:55 +0000192 // Check if it's safe to move this instruction.
193 bool SeenStore = true; // Be conservative.
Evan Chengac1abde2010-03-02 19:03:01 +0000194 if (!MI->isSafeToMove(TII, AA, SeenStore))
Evan Cheng875357d2008-03-13 06:37:55 +0000195 return false;
196
197 unsigned DefReg = 0;
198 SmallSet<unsigned, 4> UseRegs;
Bill Wendling637980e2008-05-10 00:12:52 +0000199
Evan Cheng875357d2008-03-13 06:37:55 +0000200 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
201 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000202 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000203 continue;
204 unsigned MOReg = MO.getReg();
205 if (!MOReg)
206 continue;
207 if (MO.isUse() && MOReg != SavedReg)
208 UseRegs.insert(MO.getReg());
209 if (!MO.isDef())
210 continue;
211 if (MO.isImplicit())
212 // Don't try to move it if it implicitly defines a register.
213 return false;
214 if (DefReg)
215 // For now, don't move any instructions that define multiple registers.
216 return false;
217 DefReg = MO.getReg();
218 }
219
220 // Find the instruction that kills SavedReg.
221 MachineInstr *KillMI = NULL;
Evan Chengf1250ee2010-03-23 20:36:12 +0000222 for (MachineRegisterInfo::use_nodbg_iterator
223 UI = MRI->use_nodbg_begin(SavedReg),
224 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
Evan Cheng875357d2008-03-13 06:37:55 +0000225 MachineOperand &UseMO = UI.getOperand();
226 if (!UseMO.isKill())
227 continue;
228 KillMI = UseMO.getParent();
229 break;
230 }
Bill Wendling637980e2008-05-10 00:12:52 +0000231
Eli Friedmanbde81d52011-09-23 22:41:57 +0000232 // If we find the instruction that kills SavedReg, and it is in an
233 // appropriate location, we can try to sink the current instruction
234 // past it.
235 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
Jakob Stoklund Olesen988069e2012-08-09 22:08:26 +0000236 KillMI == OldPos || KillMI->isTerminator())
Evan Cheng875357d2008-03-13 06:37:55 +0000237 return false;
238
Bill Wendling637980e2008-05-10 00:12:52 +0000239 // If any of the definitions are used by another instruction between the
240 // position and the kill use, then it's not safe to sink it.
Andrew Trick8247e0d2012-02-03 05:12:30 +0000241 //
Bill Wendling637980e2008-05-10 00:12:52 +0000242 // FIXME: This can be sped up if there is an easy way to query whether an
Evan Cheng7543e582008-06-18 07:49:14 +0000243 // instruction is before or after another instruction. Then we can use
Bill Wendling637980e2008-05-10 00:12:52 +0000244 // MachineRegisterInfo def / use instead.
Evan Cheng875357d2008-03-13 06:37:55 +0000245 MachineOperand *KillMO = NULL;
246 MachineBasicBlock::iterator KillPos = KillMI;
247 ++KillPos;
Bill Wendling637980e2008-05-10 00:12:52 +0000248
Evan Cheng7543e582008-06-18 07:49:14 +0000249 unsigned NumVisited = 0;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000250 for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
Evan Cheng875357d2008-03-13 06:37:55 +0000251 MachineInstr *OtherMI = I;
Dale Johannesen3bfef032010-02-11 18:22:31 +0000252 // DBG_VALUE cannot be counted against the limit.
253 if (OtherMI->isDebugValue())
254 continue;
Evan Cheng7543e582008-06-18 07:49:14 +0000255 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
256 return false;
257 ++NumVisited;
Evan Cheng875357d2008-03-13 06:37:55 +0000258 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
259 MachineOperand &MO = OtherMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000260 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000261 continue;
262 unsigned MOReg = MO.getReg();
263 if (!MOReg)
264 continue;
265 if (DefReg == MOReg)
266 return false;
Bill Wendling637980e2008-05-10 00:12:52 +0000267
Evan Cheng875357d2008-03-13 06:37:55 +0000268 if (MO.isKill()) {
269 if (OtherMI == KillMI && MOReg == SavedReg)
Evan Cheng7543e582008-06-18 07:49:14 +0000270 // Save the operand that kills the register. We want to unset the kill
271 // marker if we can sink MI past it.
Evan Cheng875357d2008-03-13 06:37:55 +0000272 KillMO = &MO;
273 else if (UseRegs.count(MOReg))
274 // One of the uses is killed before the destination.
275 return false;
276 }
277 }
278 }
Jakob Stoklund Olesen988069e2012-08-09 22:08:26 +0000279 assert(KillMO && "Didn't find kill");
Evan Cheng875357d2008-03-13 06:37:55 +0000280
Evan Cheng875357d2008-03-13 06:37:55 +0000281 // Update kill and LV information.
282 KillMO->setIsKill(false);
283 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
284 KillMO->setIsKill(true);
Andrew Trick8247e0d2012-02-03 05:12:30 +0000285
Evan Cheng9f1c8312008-07-03 09:09:37 +0000286 if (LV)
287 LV->replaceKillInstruction(SavedReg, KillMI, MI);
Evan Cheng875357d2008-03-13 06:37:55 +0000288
289 // Move instruction to its destination.
290 MBB->remove(MI);
291 MBB->insert(KillPos, MI);
292
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000293 if (LIS)
294 LIS->handleMove(MI);
295
Evan Cheng875357d2008-03-13 06:37:55 +0000296 ++Num3AddrSunk;
297 return true;
298}
299
Evan Chengd498c8f2009-01-25 03:53:59 +0000300/// NoUseAfterLastDef - Return true if there are no intervening uses between the
301/// last instruction in the MBB that defines the specified register and the
302/// two-address instruction which is being processed. It also returns the last
303/// def location by reference
304bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
Evan Cheng870b8072009-03-01 02:03:43 +0000305 MachineBasicBlock *MBB, unsigned Dist,
306 unsigned &LastDef) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000307 LastDef = 0;
308 unsigned LastUse = Dist;
309 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
310 E = MRI->reg_end(); I != E; ++I) {
311 MachineOperand &MO = I.getOperand();
312 MachineInstr *MI = MO.getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000313 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesend94998f2010-02-09 02:01:46 +0000314 continue;
Evan Chengd498c8f2009-01-25 03:53:59 +0000315 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
316 if (DI == DistanceMap.end())
317 continue;
318 if (MO.isUse() && DI->second < LastUse)
319 LastUse = DI->second;
320 if (MO.isDef() && DI->second > LastDef)
321 LastDef = DI->second;
322 }
323
324 return !(LastUse > LastDef && LastUse < Dist);
325}
326
Evan Cheng870b8072009-03-01 02:03:43 +0000327/// isCopyToReg - Return true if the specified MI is a copy instruction or
328/// a extract_subreg instruction. It also returns the source and destination
329/// registers and whether they are physical registers by reference.
330static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
331 unsigned &SrcReg, unsigned &DstReg,
332 bool &IsSrcPhys, bool &IsDstPhys) {
333 SrcReg = 0;
334 DstReg = 0;
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000335 if (MI.isCopy()) {
336 DstReg = MI.getOperand(0).getReg();
337 SrcReg = MI.getOperand(1).getReg();
338 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
339 DstReg = MI.getOperand(0).getReg();
340 SrcReg = MI.getOperand(2).getReg();
341 } else
342 return false;
Evan Cheng870b8072009-03-01 02:03:43 +0000343
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000344 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
345 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
346 return true;
Evan Cheng870b8072009-03-01 02:03:43 +0000347}
348
Dan Gohman97121ba2009-04-08 00:15:30 +0000349/// isKilled - Test if the given register value, which is used by the given
350/// instruction, is killed by the given instruction. This looks through
351/// coalescable copies to see if the original value is potentially not killed.
352///
353/// For example, in this code:
354///
355/// %reg1034 = copy %reg1024
356/// %reg1035 = copy %reg1025<kill>
357/// %reg1036 = add %reg1034<kill>, %reg1035<kill>
358///
359/// %reg1034 is not considered to be killed, since it is copied from a
360/// register which is not killed. Treating it as not killed lets the
361/// normal heuristics commute the (two-address) add, which lets
362/// coalescing eliminate the extra copy.
363///
364static bool isKilled(MachineInstr &MI, unsigned Reg,
365 const MachineRegisterInfo *MRI,
366 const TargetInstrInfo *TII) {
367 MachineInstr *DefMI = &MI;
368 for (;;) {
369 if (!DefMI->killsRegister(Reg))
370 return false;
371 if (TargetRegisterInfo::isPhysicalRegister(Reg))
372 return true;
373 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
374 // If there are multiple defs, we can't do a simple analysis, so just
375 // go with what the kill flag says.
Chris Lattner7896c9f2009-12-03 00:50:42 +0000376 if (llvm::next(Begin) != MRI->def_end())
Dan Gohman97121ba2009-04-08 00:15:30 +0000377 return true;
378 DefMI = &*Begin;
379 bool IsSrcPhys, IsDstPhys;
380 unsigned SrcReg, DstReg;
381 // If the def is something other than a copy, then it isn't going to
382 // be coalesced, so follow the kill flag.
383 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
384 return true;
385 Reg = SrcReg;
386 }
387}
388
Evan Cheng870b8072009-03-01 02:03:43 +0000389/// isTwoAddrUse - Return true if the specified MI uses the specified register
390/// as a two-address use. If so, return the destination register by reference.
391static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
Evan Chenge837dea2011-06-28 19:10:37 +0000392 const MCInstrDesc &MCID = MI.getDesc();
393 unsigned NumOps = MI.isInlineAsm()
394 ? MI.getNumOperands() : MCID.getNumOperands();
Evan Chenge6f350d2009-03-30 21:34:07 +0000395 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng870b8072009-03-01 02:03:43 +0000396 const MachineOperand &MO = MI.getOperand(i);
397 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
398 continue;
Evan Chenga24752f2009-03-19 20:30:06 +0000399 unsigned ti;
400 if (MI.isRegTiedToDefOperand(i, &ti)) {
Evan Cheng870b8072009-03-01 02:03:43 +0000401 DstReg = MI.getOperand(ti).getReg();
402 return true;
403 }
404 }
405 return false;
406}
407
408/// findOnlyInterestingUse - Given a register, if has a single in-basic block
409/// use, return the use instruction if it's a copy or a two-address use.
410static
411MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
412 MachineRegisterInfo *MRI,
413 const TargetInstrInfo *TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000414 bool &IsCopy,
Evan Cheng870b8072009-03-01 02:03:43 +0000415 unsigned &DstReg, bool &IsDstPhys) {
Evan Cheng1423c702010-03-03 21:18:38 +0000416 if (!MRI->hasOneNonDBGUse(Reg))
417 // None or more than one use.
Evan Cheng870b8072009-03-01 02:03:43 +0000418 return 0;
Evan Cheng1423c702010-03-03 21:18:38 +0000419 MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg);
Evan Cheng870b8072009-03-01 02:03:43 +0000420 if (UseMI.getParent() != MBB)
421 return 0;
422 unsigned SrcReg;
423 bool IsSrcPhys;
Evan Cheng87d696a2009-04-14 00:32:25 +0000424 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
425 IsCopy = true;
Evan Cheng870b8072009-03-01 02:03:43 +0000426 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000427 }
Evan Cheng870b8072009-03-01 02:03:43 +0000428 IsDstPhys = false;
Evan Cheng87d696a2009-04-14 00:32:25 +0000429 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
430 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng870b8072009-03-01 02:03:43 +0000431 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000432 }
Evan Cheng870b8072009-03-01 02:03:43 +0000433 return 0;
434}
435
436/// getMappedReg - Return the physical register the specified virtual register
437/// might be mapped to.
438static unsigned
439getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
440 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
441 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
442 if (SI == RegMap.end())
443 return 0;
444 Reg = SI->second;
445 }
446 if (TargetRegisterInfo::isPhysicalRegister(Reg))
447 return Reg;
448 return 0;
449}
450
451/// regsAreCompatible - Return true if the two registers are equal or aliased.
452///
453static bool
454regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
455 if (RegA == RegB)
456 return true;
457 if (!RegA || !RegB)
458 return false;
459 return TRI->regsOverlap(RegA, RegB);
460}
461
462
Manman Rend68e8cd2012-07-25 18:28:13 +0000463/// isProfitableToCommute - Return true if it's potentially profitable to commute
Evan Chengd498c8f2009-01-25 03:53:59 +0000464/// the two-address instruction that's being processed.
465bool
Evan Chengd99d68b2012-05-03 01:45:13 +0000466TwoAddressInstructionPass::isProfitableToCommute(unsigned regA, unsigned regB,
467 unsigned regC,
Evan Cheng870b8072009-03-01 02:03:43 +0000468 MachineInstr *MI, MachineBasicBlock *MBB,
469 unsigned Dist) {
Evan Chengc3aa7c52011-11-16 18:44:48 +0000470 if (OptLevel == CodeGenOpt::None)
471 return false;
472
Evan Chengd498c8f2009-01-25 03:53:59 +0000473 // Determine if it's profitable to commute this two address instruction. In
474 // general, we want no uses between this instruction and the definition of
475 // the two-address register.
476 // e.g.
477 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
478 // %reg1029<def> = MOV8rr %reg1028
479 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
480 // insert => %reg1030<def> = MOV8rr %reg1028
481 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
482 // In this case, it might not be possible to coalesce the second MOV8rr
483 // instruction if the first one is coalesced. So it would be profitable to
484 // commute it:
485 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
486 // %reg1029<def> = MOV8rr %reg1028
487 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
488 // insert => %reg1030<def> = MOV8rr %reg1029
Andrew Trick8247e0d2012-02-03 05:12:30 +0000489 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
Evan Chengd498c8f2009-01-25 03:53:59 +0000490
491 if (!MI->killsRegister(regC))
492 return false;
493
494 // Ok, we have something like:
495 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
496 // let's see if it's worth commuting it.
497
Evan Cheng870b8072009-03-01 02:03:43 +0000498 // Look for situations like this:
499 // %reg1024<def> = MOV r1
500 // %reg1025<def> = MOV r0
501 // %reg1026<def> = ADD %reg1024, %reg1025
502 // r0 = MOV %reg1026
503 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
Evan Chengd99d68b2012-05-03 01:45:13 +0000504 unsigned ToRegA = getMappedReg(regA, DstRegMap);
505 if (ToRegA) {
506 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
507 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
508 bool BComp = !FromRegB || regsAreCompatible(FromRegB, ToRegA, TRI);
509 bool CComp = !FromRegC || regsAreCompatible(FromRegC, ToRegA, TRI);
510 if (BComp != CComp)
511 return !BComp && CComp;
512 }
Evan Cheng870b8072009-03-01 02:03:43 +0000513
Evan Chengd498c8f2009-01-25 03:53:59 +0000514 // If there is a use of regC between its last def (could be livein) and this
515 // instruction, then bail.
516 unsigned LastDefC = 0;
Evan Cheng870b8072009-03-01 02:03:43 +0000517 if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
Evan Chengd498c8f2009-01-25 03:53:59 +0000518 return false;
519
520 // If there is a use of regB between its last def (could be livein) and this
521 // instruction, then go ahead and make this transformation.
522 unsigned LastDefB = 0;
Evan Cheng870b8072009-03-01 02:03:43 +0000523 if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
Evan Chengd498c8f2009-01-25 03:53:59 +0000524 return true;
525
526 // Since there are no intervening uses for both registers, then commute
527 // if the def of regC is closer. Its live interval is shorter.
528 return LastDefB && LastDefC && LastDefC > LastDefB;
529}
530
Evan Cheng81913712009-01-23 23:27:33 +0000531/// CommuteInstruction - Commute a two-address instruction and update the basic
532/// block, distance map, and live variables if needed. Return true if it is
533/// successful.
534bool
535TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
Evan Cheng870b8072009-03-01 02:03:43 +0000536 MachineFunction::iterator &mbbi,
537 unsigned RegB, unsigned RegC, unsigned Dist) {
Evan Cheng81913712009-01-23 23:27:33 +0000538 MachineInstr *MI = mi;
David Greeneeb00b182010-01-05 01:24:21 +0000539 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
Evan Cheng81913712009-01-23 23:27:33 +0000540 MachineInstr *NewMI = TII->commuteInstruction(MI);
541
542 if (NewMI == 0) {
David Greeneeb00b182010-01-05 01:24:21 +0000543 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
Evan Cheng81913712009-01-23 23:27:33 +0000544 return false;
545 }
546
David Greeneeb00b182010-01-05 01:24:21 +0000547 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
Evan Cheng81913712009-01-23 23:27:33 +0000548 // If the instruction changed to commute it, update livevar.
549 if (NewMI != MI) {
550 if (LV)
551 // Update live variables
552 LV->replaceKillInstruction(RegC, MI, NewMI);
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000553 if (Indexes)
554 Indexes->replaceMachineInstrInMaps(MI, NewMI);
Evan Cheng81913712009-01-23 23:27:33 +0000555
556 mbbi->insert(mi, NewMI); // Insert the new inst
557 mbbi->erase(mi); // Nuke the old inst.
558 mi = NewMI;
559 DistanceMap.insert(std::make_pair(NewMI, Dist));
560 }
Evan Cheng870b8072009-03-01 02:03:43 +0000561
562 // Update source register map.
563 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
564 if (FromRegC) {
565 unsigned RegA = MI->getOperand(0).getReg();
566 SrcRegMap[RegA] = FromRegC;
567 }
568
Evan Cheng81913712009-01-23 23:27:33 +0000569 return true;
570}
571
Evan Chenge6f350d2009-03-30 21:34:07 +0000572/// isProfitableToConv3Addr - Return true if it is profitable to convert the
573/// given 2-address instruction to a 3-address one.
574bool
Evan Chengf06e6c22011-03-02 01:08:17 +0000575TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
Evan Chenge6f350d2009-03-30 21:34:07 +0000576 // Look for situations like this:
577 // %reg1024<def> = MOV r1
578 // %reg1025<def> = MOV r0
579 // %reg1026<def> = ADD %reg1024, %reg1025
580 // r2 = MOV %reg1026
581 // Turn ADD into a 3-address instruction to avoid a copy.
Evan Chengf06e6c22011-03-02 01:08:17 +0000582 unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
583 if (!FromRegB)
584 return false;
Evan Chenge6f350d2009-03-30 21:34:07 +0000585 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
Evan Chengf06e6c22011-03-02 01:08:17 +0000586 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
Evan Chenge6f350d2009-03-30 21:34:07 +0000587}
588
589/// ConvertInstTo3Addr - Convert the specified two-address instruction into a
590/// three address one. Return true if this transformation was successful.
591bool
592TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
593 MachineBasicBlock::iterator &nmi,
594 MachineFunction::iterator &mbbi,
Evan Cheng4d96c632011-02-10 02:20:55 +0000595 unsigned RegA, unsigned RegB,
596 unsigned Dist) {
Evan Chenge6f350d2009-03-30 21:34:07 +0000597 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
598 if (NewMI) {
David Greeneeb00b182010-01-05 01:24:21 +0000599 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
600 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
Evan Chenge6f350d2009-03-30 21:34:07 +0000601 bool Sunk = false;
602
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000603 if (Indexes)
604 Indexes->replaceMachineInstrInMaps(mi, NewMI);
605
Evan Chenge6f350d2009-03-30 21:34:07 +0000606 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
607 // FIXME: Temporary workaround. If the new instruction doesn't
608 // uses RegB, convertToThreeAddress must have created more
609 // then one instruction.
610 Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
611
612 mbbi->erase(mi); // Nuke the old inst.
613
614 if (!Sunk) {
615 DistanceMap.insert(std::make_pair(NewMI, Dist));
616 mi = NewMI;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000617 nmi = llvm::next(mi);
Evan Chenge6f350d2009-03-30 21:34:07 +0000618 }
Evan Cheng4d96c632011-02-10 02:20:55 +0000619
620 // Update source and destination register maps.
621 SrcRegMap.erase(RegA);
622 DstRegMap.erase(RegB);
Evan Chenge6f350d2009-03-30 21:34:07 +0000623 return true;
624 }
625
626 return false;
627}
628
Evan Chengf06e6c22011-03-02 01:08:17 +0000629/// ScanUses - Scan forward recursively for only uses, update maps if the use
630/// is a copy or a two-address instruction.
631void
632TwoAddressInstructionPass::ScanUses(unsigned DstReg, MachineBasicBlock *MBB,
633 SmallPtrSet<MachineInstr*, 8> &Processed) {
634 SmallVector<unsigned, 4> VirtRegPairs;
635 bool IsDstPhys;
636 bool IsCopy = false;
637 unsigned NewReg = 0;
638 unsigned Reg = DstReg;
639 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
640 NewReg, IsDstPhys)) {
641 if (IsCopy && !Processed.insert(UseMI))
642 break;
643
644 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
645 if (DI != DistanceMap.end())
646 // Earlier in the same MBB.Reached via a back edge.
647 break;
648
649 if (IsDstPhys) {
650 VirtRegPairs.push_back(NewReg);
651 break;
652 }
653 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
654 if (!isNew)
655 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
656 VirtRegPairs.push_back(NewReg);
657 Reg = NewReg;
658 }
659
660 if (!VirtRegPairs.empty()) {
661 unsigned ToReg = VirtRegPairs.back();
662 VirtRegPairs.pop_back();
663 while (!VirtRegPairs.empty()) {
664 unsigned FromReg = VirtRegPairs.back();
665 VirtRegPairs.pop_back();
666 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
667 if (!isNew)
668 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
669 ToReg = FromReg;
670 }
671 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
672 if (!isNew)
673 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
674 }
675}
676
Evan Cheng870b8072009-03-01 02:03:43 +0000677/// ProcessCopy - If the specified instruction is not yet processed, process it
678/// if it's a copy. For a copy instruction, we find the physical registers the
679/// source and destination registers might be mapped to. These are kept in
680/// point-to maps used to determine future optimizations. e.g.
681/// v1024 = mov r0
682/// v1025 = mov r1
683/// v1026 = add v1024, v1025
684/// r1 = mov r1026
685/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
686/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
687/// potentially joined with r1 on the output side. It's worthwhile to commute
688/// 'add' to eliminate a copy.
689void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
690 MachineBasicBlock *MBB,
691 SmallPtrSet<MachineInstr*, 8> &Processed) {
692 if (Processed.count(MI))
693 return;
694
695 bool IsSrcPhys, IsDstPhys;
696 unsigned SrcReg, DstReg;
697 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
698 return;
699
700 if (IsDstPhys && !IsSrcPhys)
701 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
702 else if (!IsDstPhys && IsSrcPhys) {
Evan Cheng3005ed62009-04-13 20:04:24 +0000703 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
704 if (!isNew)
705 assert(SrcRegMap[DstReg] == SrcReg &&
706 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000707
Evan Chengf06e6c22011-03-02 01:08:17 +0000708 ScanUses(DstReg, MBB, Processed);
Evan Cheng870b8072009-03-01 02:03:43 +0000709 }
710
711 Processed.insert(MI);
Evan Chengf06e6c22011-03-02 01:08:17 +0000712 return;
Evan Cheng870b8072009-03-01 02:03:43 +0000713}
714
Evan Cheng2a4410d2011-11-14 19:48:55 +0000715/// RescheduleMIBelowKill - If there is one more local instruction that reads
716/// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
717/// instruction in order to eliminate the need for the copy.
718bool
719TwoAddressInstructionPass::RescheduleMIBelowKill(MachineBasicBlock *MBB,
720 MachineBasicBlock::iterator &mi,
721 MachineBasicBlock::iterator &nmi,
722 unsigned Reg) {
Chandler Carruth7d532c82012-07-15 03:29:46 +0000723 // Bail immediately if we don't have LV available. We use it to find kills
724 // efficiently.
725 if (!LV)
726 return false;
727
Evan Cheng2a4410d2011-11-14 19:48:55 +0000728 MachineInstr *MI = &*mi;
Andrew Trick8247e0d2012-02-03 05:12:30 +0000729 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000730 if (DI == DistanceMap.end())
731 // Must be created from unfolded load. Don't waste time trying this.
732 return false;
733
Chandler Carruth7d532c82012-07-15 03:29:46 +0000734 MachineInstr *KillMI = LV->getVarInfo(Reg).findKill(MBB);
735 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000736 // Don't mess with copies, they may be coalesced later.
737 return false;
738
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000739 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
740 KillMI->isBranch() || KillMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000741 // Don't move pass calls, etc.
742 return false;
743
744 unsigned DstReg;
745 if (isTwoAddrUse(*KillMI, Reg, DstReg))
746 return false;
747
Evan Chengf1784182011-11-15 06:26:51 +0000748 bool SeenStore = true;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000749 if (!MI->isSafeToMove(TII, AA, SeenStore))
750 return false;
751
752 if (TII->getInstrLatency(InstrItins, MI) > 1)
753 // FIXME: Needs more sophisticated heuristics.
754 return false;
755
756 SmallSet<unsigned, 2> Uses;
Evan Cheng9bad88a2011-11-16 03:47:42 +0000757 SmallSet<unsigned, 2> Kills;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000758 SmallSet<unsigned, 2> Defs;
759 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
760 const MachineOperand &MO = MI->getOperand(i);
761 if (!MO.isReg())
762 continue;
763 unsigned MOReg = MO.getReg();
764 if (!MOReg)
765 continue;
766 if (MO.isDef())
767 Defs.insert(MOReg);
Evan Cheng9bad88a2011-11-16 03:47:42 +0000768 else {
Evan Cheng2a4410d2011-11-14 19:48:55 +0000769 Uses.insert(MOReg);
Evan Cheng9bad88a2011-11-16 03:47:42 +0000770 if (MO.isKill() && MOReg != Reg)
771 Kills.insert(MOReg);
772 }
Evan Cheng2a4410d2011-11-14 19:48:55 +0000773 }
774
775 // Move the copies connected to MI down as well.
776 MachineBasicBlock::iterator From = MI;
777 MachineBasicBlock::iterator To = llvm::next(From);
778 while (To->isCopy() && Defs.count(To->getOperand(1).getReg())) {
779 Defs.insert(To->getOperand(0).getReg());
780 ++To;
781 }
782
783 // Check if the reschedule will not break depedencies.
784 unsigned NumVisited = 0;
785 MachineBasicBlock::iterator KillPos = KillMI;
786 ++KillPos;
787 for (MachineBasicBlock::iterator I = To; I != KillPos; ++I) {
788 MachineInstr *OtherMI = I;
789 // DBG_VALUE cannot be counted against the limit.
790 if (OtherMI->isDebugValue())
791 continue;
792 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
793 return false;
794 ++NumVisited;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000795 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
796 OtherMI->isBranch() || OtherMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000797 // Don't move pass calls, etc.
798 return false;
799 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
800 const MachineOperand &MO = OtherMI->getOperand(i);
801 if (!MO.isReg())
802 continue;
803 unsigned MOReg = MO.getReg();
804 if (!MOReg)
805 continue;
806 if (MO.isDef()) {
807 if (Uses.count(MOReg))
808 // Physical register use would be clobbered.
809 return false;
810 if (!MO.isDead() && Defs.count(MOReg))
811 // May clobber a physical register def.
812 // FIXME: This may be too conservative. It's ok if the instruction
813 // is sunken completely below the use.
814 return false;
815 } else {
816 if (Defs.count(MOReg))
817 return false;
Evan Cheng9bad88a2011-11-16 03:47:42 +0000818 if (MOReg != Reg &&
819 ((MO.isKill() && Uses.count(MOReg)) || Kills.count(MOReg)))
Evan Cheng2a4410d2011-11-14 19:48:55 +0000820 // Don't want to extend other live ranges and update kills.
821 return false;
Chandler Carruth7d532c82012-07-15 03:29:46 +0000822 if (MOReg == Reg && !MO.isKill())
823 // We can't schedule across a use of the register in question.
824 return false;
825 // Ensure that if this is register in question, its the kill we expect.
826 assert((MOReg != Reg || OtherMI == KillMI) &&
827 "Found multiple kills of a register in a basic block");
Evan Cheng2a4410d2011-11-14 19:48:55 +0000828 }
829 }
830 }
831
832 // Move debug info as well.
Evan Cheng8aee7d82011-11-14 21:11:15 +0000833 while (From != MBB->begin() && llvm::prior(From)->isDebugValue())
834 --From;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000835
836 // Copies following MI may have been moved as well.
837 nmi = To;
838 MBB->splice(KillPos, MBB, From, To);
839 DistanceMap.erase(DI);
840
Chandler Carruth7d532c82012-07-15 03:29:46 +0000841 // Update live variables
842 LV->removeVirtualRegisterKilled(Reg, KillMI);
843 LV->addVirtualRegisterKilled(Reg, MI);
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +0000844 if (LIS)
845 LIS->handleMove(MI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000846
Jakob Stoklund Olesena532bce2012-07-17 17:57:23 +0000847 DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000848 return true;
849}
850
851/// isDefTooClose - Return true if the re-scheduling will put the given
852/// instruction too close to the defs of its register dependencies.
853bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
854 MachineInstr *MI,
855 MachineBasicBlock *MBB) {
856 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(Reg),
857 DE = MRI->def_end(); DI != DE; ++DI) {
858 MachineInstr *DefMI = &*DI;
859 if (DefMI->getParent() != MBB || DefMI->isCopy() || DefMI->isCopyLike())
860 continue;
861 if (DefMI == MI)
862 return true; // MI is defining something KillMI uses
863 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(DefMI);
864 if (DDI == DistanceMap.end())
865 return true; // Below MI
866 unsigned DefDist = DDI->second;
867 assert(Dist > DefDist && "Visited def already?");
Andrew Trickb7e02892012-06-05 21:11:27 +0000868 if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist))
Evan Cheng2a4410d2011-11-14 19:48:55 +0000869 return true;
870 }
871 return false;
872}
873
874/// RescheduleKillAboveMI - If there is one more local instruction that reads
875/// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
876/// current two-address instruction in order to eliminate the need for the
877/// copy.
878bool
879TwoAddressInstructionPass::RescheduleKillAboveMI(MachineBasicBlock *MBB,
880 MachineBasicBlock::iterator &mi,
881 MachineBasicBlock::iterator &nmi,
882 unsigned Reg) {
Chandler Carruth7d532c82012-07-15 03:29:46 +0000883 // Bail immediately if we don't have LV available. We use it to find kills
884 // efficiently.
885 if (!LV)
886 return false;
887
Evan Cheng2a4410d2011-11-14 19:48:55 +0000888 MachineInstr *MI = &*mi;
889 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
890 if (DI == DistanceMap.end())
891 // Must be created from unfolded load. Don't waste time trying this.
892 return false;
893
Chandler Carruth7d532c82012-07-15 03:29:46 +0000894 MachineInstr *KillMI = LV->getVarInfo(Reg).findKill(MBB);
895 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000896 // Don't mess with copies, they may be coalesced later.
897 return false;
898
899 unsigned DstReg;
900 if (isTwoAddrUse(*KillMI, Reg, DstReg))
901 return false;
902
Evan Chengf1784182011-11-15 06:26:51 +0000903 bool SeenStore = true;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000904 if (!KillMI->isSafeToMove(TII, AA, SeenStore))
905 return false;
906
907 SmallSet<unsigned, 2> Uses;
908 SmallSet<unsigned, 2> Kills;
909 SmallSet<unsigned, 2> Defs;
910 SmallSet<unsigned, 2> LiveDefs;
911 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
912 const MachineOperand &MO = KillMI->getOperand(i);
913 if (!MO.isReg())
914 continue;
915 unsigned MOReg = MO.getReg();
916 if (MO.isUse()) {
917 if (!MOReg)
918 continue;
919 if (isDefTooClose(MOReg, DI->second, MI, MBB))
920 return false;
Chandler Carruth7d532c82012-07-15 03:29:46 +0000921 if (MOReg == Reg && !MO.isKill())
922 return false;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000923 Uses.insert(MOReg);
924 if (MO.isKill() && MOReg != Reg)
925 Kills.insert(MOReg);
926 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
927 Defs.insert(MOReg);
928 if (!MO.isDead())
929 LiveDefs.insert(MOReg);
930 }
931 }
932
933 // Check if the reschedule will not break depedencies.
934 unsigned NumVisited = 0;
935 MachineBasicBlock::iterator KillPos = KillMI;
936 for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
937 MachineInstr *OtherMI = I;
938 // DBG_VALUE cannot be counted against the limit.
939 if (OtherMI->isDebugValue())
940 continue;
941 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
942 return false;
943 ++NumVisited;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000944 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
945 OtherMI->isBranch() || OtherMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000946 // Don't move pass calls, etc.
947 return false;
Evan Chengae7db7a2011-11-16 03:05:12 +0000948 SmallVector<unsigned, 2> OtherDefs;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000949 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
950 const MachineOperand &MO = OtherMI->getOperand(i);
951 if (!MO.isReg())
952 continue;
953 unsigned MOReg = MO.getReg();
954 if (!MOReg)
955 continue;
956 if (MO.isUse()) {
957 if (Defs.count(MOReg))
958 // Moving KillMI can clobber the physical register if the def has
959 // not been seen.
960 return false;
961 if (Kills.count(MOReg))
962 // Don't want to extend other live ranges and update kills.
963 return false;
Chandler Carruth7d532c82012-07-15 03:29:46 +0000964 if (OtherMI != MI && MOReg == Reg && !MO.isKill())
965 // We can't schedule across a use of the register in question.
966 return false;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000967 } else {
Evan Chengae7db7a2011-11-16 03:05:12 +0000968 OtherDefs.push_back(MOReg);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000969 }
970 }
Evan Chengae7db7a2011-11-16 03:05:12 +0000971
972 for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
973 unsigned MOReg = OtherDefs[i];
974 if (Uses.count(MOReg))
975 return false;
976 if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
977 LiveDefs.count(MOReg))
978 return false;
979 // Physical register def is seen.
980 Defs.erase(MOReg);
981 }
Evan Cheng2a4410d2011-11-14 19:48:55 +0000982 }
983
984 // Move the old kill above MI, don't forget to move debug info as well.
985 MachineBasicBlock::iterator InsertPos = mi;
Evan Cheng8aee7d82011-11-14 21:11:15 +0000986 while (InsertPos != MBB->begin() && llvm::prior(InsertPos)->isDebugValue())
987 --InsertPos;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000988 MachineBasicBlock::iterator From = KillMI;
989 MachineBasicBlock::iterator To = llvm::next(From);
990 while (llvm::prior(From)->isDebugValue())
991 --From;
992 MBB->splice(InsertPos, MBB, From, To);
993
Evan Cheng2bee6a82011-11-16 03:33:08 +0000994 nmi = llvm::prior(InsertPos); // Backtrack so we process the moved instr.
Evan Cheng2a4410d2011-11-14 19:48:55 +0000995 DistanceMap.erase(DI);
996
Chandler Carruth7d532c82012-07-15 03:29:46 +0000997 // Update live variables
998 LV->removeVirtualRegisterKilled(Reg, KillMI);
999 LV->addVirtualRegisterKilled(Reg, MI);
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +00001000 if (LIS)
1001 LIS->handleMove(KillMI);
Chandler Carruth7d532c82012-07-15 03:29:46 +00001002
Jakob Stoklund Olesena532bce2012-07-17 17:57:23 +00001003 DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
Evan Cheng2a4410d2011-11-14 19:48:55 +00001004 return true;
1005}
1006
Bob Wilsoncc80df92009-09-03 20:58:42 +00001007/// TryInstructionTransform - For the case where an instruction has a single
1008/// pair of tied register operands, attempt some transformations that may
1009/// either eliminate the tied operands or improve the opportunities for
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001010/// coalescing away the register copy. Returns true if no copy needs to be
1011/// inserted to untie mi's operands (either because they were untied, or
1012/// because mi was rescheduled, and will be visited again later).
Bob Wilsoncc80df92009-09-03 20:58:42 +00001013bool TwoAddressInstructionPass::
1014TryInstructionTransform(MachineBasicBlock::iterator &mi,
1015 MachineBasicBlock::iterator &nmi,
1016 MachineFunction::iterator &mbbi,
Evan Chengf06e6c22011-03-02 01:08:17 +00001017 unsigned SrcIdx, unsigned DstIdx, unsigned Dist,
1018 SmallPtrSet<MachineInstr*, 8> &Processed) {
Evan Chengc3aa7c52011-11-16 18:44:48 +00001019 if (OptLevel == CodeGenOpt::None)
1020 return false;
1021
Evan Cheng2a4410d2011-11-14 19:48:55 +00001022 MachineInstr &MI = *mi;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001023 unsigned regA = MI.getOperand(DstIdx).getReg();
1024 unsigned regB = MI.getOperand(SrcIdx).getReg();
Bob Wilsoncc80df92009-09-03 20:58:42 +00001025
1026 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1027 "cannot make instruction into two-address form");
Evan Cheng2a4410d2011-11-14 19:48:55 +00001028 bool regBKilled = isKilled(MI, regB, MRI, TII);
Bob Wilsoncc80df92009-09-03 20:58:42 +00001029
Evan Chengd99d68b2012-05-03 01:45:13 +00001030 if (TargetRegisterInfo::isVirtualRegister(regA))
1031 ScanUses(regA, &*mbbi, Processed);
1032
Bob Wilsoncc80df92009-09-03 20:58:42 +00001033 // Check if it is profitable to commute the operands.
1034 unsigned SrcOp1, SrcOp2;
1035 unsigned regC = 0;
1036 unsigned regCIdx = ~0U;
1037 bool TryCommute = false;
1038 bool AggressiveCommute = false;
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001039 if (MI.isCommutable() && MI.getNumOperands() >= 3 &&
Evan Cheng2a4410d2011-11-14 19:48:55 +00001040 TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001041 if (SrcIdx == SrcOp1)
1042 regCIdx = SrcOp2;
1043 else if (SrcIdx == SrcOp2)
1044 regCIdx = SrcOp1;
1045
1046 if (regCIdx != ~0U) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001047 regC = MI.getOperand(regCIdx).getReg();
1048 if (!regBKilled && isKilled(MI, regC, MRI, TII))
Bob Wilsoncc80df92009-09-03 20:58:42 +00001049 // If C dies but B does not, swap the B and C operands.
1050 // This makes the live ranges of A and C joinable.
1051 TryCommute = true;
Evan Chengd99d68b2012-05-03 01:45:13 +00001052 else if (isProfitableToCommute(regA, regB, regC, &MI, mbbi, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001053 TryCommute = true;
1054 AggressiveCommute = true;
1055 }
1056 }
1057 }
1058
1059 // If it's profitable to commute, try to do so.
1060 if (TryCommute && CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
1061 ++NumCommuted;
1062 if (AggressiveCommute)
1063 ++NumAggrCommuted;
1064 return false;
1065 }
1066
Evan Cheng2a4410d2011-11-14 19:48:55 +00001067 // If there is one more use of regB later in the same MBB, consider
1068 // re-schedule this MI below it.
1069 if (RescheduleMIBelowKill(mbbi, mi, nmi, regB)) {
1070 ++NumReSchedDowns;
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001071 return true;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001072 }
1073
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001074 if (MI.isConvertibleTo3Addr()) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001075 // This instruction is potentially convertible to a true
1076 // three-address instruction. Check if it is profitable.
Evan Chengf06e6c22011-03-02 01:08:17 +00001077 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001078 // Try to convert it.
Evan Cheng4d96c632011-02-10 02:20:55 +00001079 if (ConvertInstTo3Addr(mi, nmi, mbbi, regA, regB, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001080 ++NumConvertedTo3Addr;
1081 return true; // Done with this instruction.
1082 }
1083 }
1084 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001085
Evan Cheng2a4410d2011-11-14 19:48:55 +00001086 // If there is one more use of regB later in the same MBB, consider
1087 // re-schedule it before this MI if it's legal.
1088 if (RescheduleKillAboveMI(mbbi, mi, nmi, regB)) {
1089 ++NumReSchedUps;
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001090 return true;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001091 }
1092
Dan Gohman584fedf2010-06-21 22:17:20 +00001093 // If this is an instruction with a load folded into it, try unfolding
1094 // the load, e.g. avoid this:
1095 // movq %rdx, %rcx
1096 // addq (%rax), %rcx
1097 // in favor of this:
1098 // movq (%rax), %rcx
1099 // addq %rdx, %rcx
1100 // because it's preferable to schedule a load than a register copy.
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001101 if (MI.mayLoad() && !regBKilled) {
Dan Gohman584fedf2010-06-21 22:17:20 +00001102 // Determine if a load can be unfolded.
1103 unsigned LoadRegIndex;
1104 unsigned NewOpc =
Evan Cheng2a4410d2011-11-14 19:48:55 +00001105 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
Dan Gohman584fedf2010-06-21 22:17:20 +00001106 /*UnfoldLoad=*/true,
1107 /*UnfoldStore=*/false,
1108 &LoadRegIndex);
1109 if (NewOpc != 0) {
Evan Chenge837dea2011-06-28 19:10:37 +00001110 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1111 if (UnfoldMCID.getNumDefs() == 1) {
Dan Gohman584fedf2010-06-21 22:17:20 +00001112 // Unfold the load.
Evan Cheng2a4410d2011-11-14 19:48:55 +00001113 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
Dan Gohman584fedf2010-06-21 22:17:20 +00001114 const TargetRegisterClass *RC =
Andrew Trickf12f6df2012-05-03 01:14:37 +00001115 TRI->getAllocatableClass(
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001116 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
Dan Gohman584fedf2010-06-21 22:17:20 +00001117 unsigned Reg = MRI->createVirtualRegister(RC);
1118 SmallVector<MachineInstr *, 2> NewMIs;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001119 if (!TII->unfoldMemoryOperand(*MF, &MI, Reg,
Evan Cheng98ec91e2010-07-02 20:36:18 +00001120 /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
1121 NewMIs)) {
1122 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1123 return false;
1124 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001125 assert(NewMIs.size() == 2 &&
1126 "Unfolded a load into multiple instructions!");
1127 // The load was previously folded, so this is the only use.
1128 NewMIs[1]->addRegisterKilled(Reg, TRI);
1129
1130 // Tentatively insert the instructions into the block so that they
1131 // look "normal" to the transformation logic.
1132 mbbi->insert(mi, NewMIs[0]);
1133 mbbi->insert(mi, NewMIs[1]);
1134
1135 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1136 << "2addr: NEW INST: " << *NewMIs[1]);
1137
1138 // Transform the instruction, now that it no longer has a load.
1139 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1140 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1141 MachineBasicBlock::iterator NewMI = NewMIs[1];
1142 bool TransformSuccess =
1143 TryInstructionTransform(NewMI, mi, mbbi,
Evan Chengf06e6c22011-03-02 01:08:17 +00001144 NewSrcIdx, NewDstIdx, Dist, Processed);
Dan Gohman584fedf2010-06-21 22:17:20 +00001145 if (TransformSuccess ||
1146 NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1147 // Success, or at least we made an improvement. Keep the unfolded
1148 // instructions and discard the original.
1149 if (LV) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001150 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1151 MachineOperand &MO = MI.getOperand(i);
Andrew Trick8247e0d2012-02-03 05:12:30 +00001152 if (MO.isReg() &&
Dan Gohman7aa7bc72010-06-22 00:32:04 +00001153 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1154 if (MO.isUse()) {
Dan Gohmancc1ca982010-06-22 02:07:21 +00001155 if (MO.isKill()) {
1156 if (NewMIs[0]->killsRegister(MO.getReg()))
Evan Cheng2a4410d2011-11-14 19:48:55 +00001157 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
Dan Gohmancc1ca982010-06-22 02:07:21 +00001158 else {
1159 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1160 "Kill missing after load unfold!");
Evan Cheng2a4410d2011-11-14 19:48:55 +00001161 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
Dan Gohmancc1ca982010-06-22 02:07:21 +00001162 }
1163 }
Evan Cheng2a4410d2011-11-14 19:48:55 +00001164 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
Dan Gohmancc1ca982010-06-22 02:07:21 +00001165 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1166 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
1167 else {
1168 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1169 "Dead flag missing after load unfold!");
1170 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
1171 }
1172 }
Dan Gohman7aa7bc72010-06-22 00:32:04 +00001173 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001174 }
1175 LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
1176 }
Evan Cheng2a4410d2011-11-14 19:48:55 +00001177 MI.eraseFromParent();
Dan Gohman584fedf2010-06-21 22:17:20 +00001178 mi = NewMIs[1];
1179 if (TransformSuccess)
1180 return true;
1181 } else {
1182 // Transforming didn't eliminate the tie and didn't lead to an
1183 // improvement. Clean up the unfolded instructions and keep the
1184 // original.
1185 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1186 NewMIs[0]->eraseFromParent();
1187 NewMIs[1]->eraseFromParent();
1188 }
1189 }
1190 }
1191 }
1192
Bob Wilsoncc80df92009-09-03 20:58:42 +00001193 return false;
1194}
1195
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001196// Collect tied operands of MI that need to be handled.
1197// Rewrite trivial cases immediately.
1198// Return true if any tied operands where found, including the trivial ones.
1199bool TwoAddressInstructionPass::
1200collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
1201 const MCInstrDesc &MCID = MI->getDesc();
1202 bool AnyOps = false;
Jakob Stoklund Olesenf363ebd2012-09-04 22:59:30 +00001203 unsigned NumOps = MI->getNumOperands();
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001204
1205 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1206 unsigned DstIdx = 0;
1207 if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1208 continue;
1209 AnyOps = true;
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001210 MachineOperand &SrcMO = MI->getOperand(SrcIdx);
1211 MachineOperand &DstMO = MI->getOperand(DstIdx);
1212 unsigned SrcReg = SrcMO.getReg();
1213 unsigned DstReg = DstMO.getReg();
1214 // Tied constraint already satisfied?
1215 if (SrcReg == DstReg)
1216 continue;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001217
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001218 assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001219
1220 // Deal with <undef> uses immediately - simply rewrite the src operand.
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001221 if (SrcMO.isUndef()) {
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001222 // Constrain the DstReg register class if required.
1223 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1224 if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
1225 TRI, *MF))
1226 MRI->constrainRegClass(DstReg, RC);
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001227 SrcMO.setReg(DstReg);
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001228 DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
1229 continue;
1230 }
Jakob Stoklund Olesen8c5c0732012-08-07 22:47:06 +00001231 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001232 }
1233 return AnyOps;
1234}
1235
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001236// Process a list of tied MI operands that all use the same source register.
1237// The tied pairs are of the form (SrcIdx, DstIdx).
1238void
1239TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
1240 TiedPairList &TiedPairs,
1241 unsigned &Dist) {
1242 bool IsEarlyClobber = false;
1243 bool RemovedKillFlag = false;
1244 bool AllUsesCopied = true;
1245 unsigned LastCopiedReg = 0;
1246 unsigned RegB = 0;
1247 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1248 unsigned SrcIdx = TiedPairs[tpi].first;
1249 unsigned DstIdx = TiedPairs[tpi].second;
1250
1251 const MachineOperand &DstMO = MI->getOperand(DstIdx);
1252 unsigned RegA = DstMO.getReg();
1253 IsEarlyClobber |= DstMO.isEarlyClobber();
1254
1255 // Grab RegB from the instruction because it may have changed if the
1256 // instruction was commuted.
1257 RegB = MI->getOperand(SrcIdx).getReg();
1258
1259 if (RegA == RegB) {
1260 // The register is tied to multiple destinations (or else we would
1261 // not have continued this far), but this use of the register
1262 // already matches the tied destination. Leave it.
1263 AllUsesCopied = false;
1264 continue;
1265 }
1266 LastCopiedReg = RegA;
1267
1268 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1269 "cannot make instruction into two-address form");
1270
1271#ifndef NDEBUG
1272 // First, verify that we don't have a use of "a" in the instruction
1273 // (a = b + a for example) because our transformation will not
1274 // work. This should never occur because we are in SSA form.
1275 for (unsigned i = 0; i != MI->getNumOperands(); ++i)
1276 assert(i == DstIdx ||
1277 !MI->getOperand(i).isReg() ||
1278 MI->getOperand(i).getReg() != RegA);
1279#endif
1280
1281 // Emit a copy.
1282 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1283 TII->get(TargetOpcode::COPY), RegA).addReg(RegB);
1284
1285 // Update DistanceMap.
1286 MachineBasicBlock::iterator PrevMI = MI;
1287 --PrevMI;
1288 DistanceMap.insert(std::make_pair(PrevMI, Dist));
1289 DistanceMap[MI] = ++Dist;
1290
1291 SlotIndex CopyIdx;
1292 if (Indexes)
1293 CopyIdx = Indexes->insertMachineInstrInMaps(PrevMI).getRegSlot();
1294
1295 DEBUG(dbgs() << "\t\tprepend:\t" << *PrevMI);
1296
1297 MachineOperand &MO = MI->getOperand(SrcIdx);
1298 assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
1299 "inconsistent operand info for 2-reg pass");
1300 if (MO.isKill()) {
1301 MO.setIsKill(false);
1302 RemovedKillFlag = true;
1303 }
1304
1305 // Make sure regA is a legal regclass for the SrcIdx operand.
1306 if (TargetRegisterInfo::isVirtualRegister(RegA) &&
1307 TargetRegisterInfo::isVirtualRegister(RegB))
1308 MRI->constrainRegClass(RegA, MRI->getRegClass(RegB));
1309
1310 MO.setReg(RegA);
1311
1312 // Propagate SrcRegMap.
1313 SrcRegMap[RegA] = RegB;
1314 }
1315
1316
1317 if (AllUsesCopied) {
1318 if (!IsEarlyClobber) {
1319 // Replace other (un-tied) uses of regB with LastCopiedReg.
1320 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1321 MachineOperand &MO = MI->getOperand(i);
1322 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1323 if (MO.isKill()) {
1324 MO.setIsKill(false);
1325 RemovedKillFlag = true;
1326 }
1327 MO.setReg(LastCopiedReg);
1328 }
1329 }
1330 }
1331
1332 // Update live variables for regB.
1333 if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(MI)) {
1334 MachineBasicBlock::iterator PrevMI = MI;
1335 --PrevMI;
1336 LV->addVirtualRegisterKilled(RegB, PrevMI);
1337 }
1338
1339 } else if (RemovedKillFlag) {
1340 // Some tied uses of regB matched their destination registers, so
1341 // regB is still used in this instruction, but a kill flag was
1342 // removed from a different tied use of regB, so now we need to add
1343 // a kill flag to one of the remaining uses of regB.
1344 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1345 MachineOperand &MO = MI->getOperand(i);
1346 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1347 MO.setIsKill(true);
1348 break;
1349 }
1350 }
1351 }
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001352}
1353
Bill Wendling637980e2008-05-10 00:12:52 +00001354/// runOnMachineFunction - Reduce two-address instructions to two operands.
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001355///
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001356bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
1357 MF = &Func;
1358 const TargetMachine &TM = MF->getTarget();
1359 MRI = &MF->getRegInfo();
Evan Cheng875357d2008-03-13 06:37:55 +00001360 TII = TM.getInstrInfo();
1361 TRI = TM.getRegisterInfo();
Evan Cheng2a4410d2011-11-14 19:48:55 +00001362 InstrItins = TM.getInstrItineraryData();
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +00001363 Indexes = getAnalysisIfAvailable<SlotIndexes>();
Duncan Sands1465d612009-01-28 13:14:17 +00001364 LV = getAnalysisIfAvailable<LiveVariables>();
Jakob Stoklund Olesen5bfdedf2012-08-03 22:58:34 +00001365 LIS = getAnalysisIfAvailable<LiveIntervals>();
Dan Gohmana70dca12009-10-09 23:27:56 +00001366 AA = &getAnalysis<AliasAnalysis>();
Evan Chengc3aa7c52011-11-16 18:44:48 +00001367 OptLevel = TM.getOptLevel();
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001368
Misha Brukman75fa4e42004-07-22 15:26:23 +00001369 bool MadeChange = false;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001370
David Greeneeb00b182010-01-05 01:24:21 +00001371 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
Andrew Trick8247e0d2012-02-03 05:12:30 +00001372 DEBUG(dbgs() << "********** Function: "
Craig Topper96601ca2012-08-22 06:07:19 +00001373 << MF->getName() << '\n');
Alkis Evlogimenos3a9986f2004-02-18 00:35:06 +00001374
Jakob Stoklund Olesen73e7dce2011-07-29 22:51:22 +00001375 // This pass takes the function out of SSA form.
1376 MRI->leaveSSA();
1377
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001378 TiedOperandMap TiedOperands;
Bob Wilsoncc80df92009-09-03 20:58:42 +00001379
Evan Cheng870b8072009-03-01 02:03:43 +00001380 SmallPtrSet<MachineInstr*, 8> Processed;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001381 for (MachineFunction::iterator mbbi = MF->begin(), mbbe = MF->end();
Misha Brukman75fa4e42004-07-22 15:26:23 +00001382 mbbi != mbbe; ++mbbi) {
Evan Cheng7543e582008-06-18 07:49:14 +00001383 unsigned Dist = 0;
1384 DistanceMap.clear();
Evan Cheng870b8072009-03-01 02:03:43 +00001385 SrcRegMap.clear();
1386 DstRegMap.clear();
1387 Processed.clear();
Misha Brukman75fa4e42004-07-22 15:26:23 +00001388 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001389 mi != me; ) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001390 MachineBasicBlock::iterator nmi = llvm::next(mi);
Dale Johannesenb8ff9342010-02-10 21:47:48 +00001391 if (mi->isDebugValue()) {
1392 mi = nmi;
1393 continue;
1394 }
Evan Chengf1250ee2010-03-23 20:36:12 +00001395
Evan Cheng3d720fb2010-05-05 18:45:40 +00001396 // Remember REG_SEQUENCE instructions, we'll deal with them later.
1397 if (mi->isRegSequence())
1398 RegSequences.push_back(&*mi);
1399
Evan Cheng7543e582008-06-18 07:49:14 +00001400 DistanceMap.insert(std::make_pair(mi, ++Dist));
Evan Cheng870b8072009-03-01 02:03:43 +00001401
1402 ProcessCopy(&*mi, &*mbbi, Processed);
1403
Bob Wilsoncc80df92009-09-03 20:58:42 +00001404 // First scan through all the tied register uses in this instruction
1405 // and record a list of pairs of tied operands for each register.
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001406 if (!collectTiedOperands(mi, TiedOperands)) {
1407 mi = nmi;
1408 continue;
Bob Wilsoncc80df92009-09-03 20:58:42 +00001409 }
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001410
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001411 ++NumTwoAddressInstrs;
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001412 MadeChange = true;
Jakob Stoklund Olesen6ac80662012-08-03 23:25:45 +00001413 DEBUG(dbgs() << '\t' << *mi);
1414
Chandler Carruth32d75be2012-07-18 18:58:22 +00001415 // If the instruction has a single pair of tied operands, try some
1416 // transformations that may either eliminate the tied operands or
1417 // improve the opportunities for coalescing away the register copy.
1418 if (TiedOperands.size() == 1) {
1419 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs
1420 = TiedOperands.begin()->second;
1421 if (TiedPairs.size() == 1) {
1422 unsigned SrcIdx = TiedPairs[0].first;
1423 unsigned DstIdx = TiedPairs[0].second;
1424 unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
1425 unsigned DstReg = mi->getOperand(DstIdx).getReg();
1426 if (SrcReg != DstReg &&
1427 TryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist,
1428 Processed)) {
1429 // The tied operands have been eliminated or shifted further down the
1430 // block to ease elimination. Continue processing with 'nmi'.
1431 TiedOperands.clear();
1432 mi = nmi;
1433 continue;
1434 }
1435 }
1436 }
1437
Bob Wilsoncc80df92009-09-03 20:58:42 +00001438 // Now iterate over the information collected above.
1439 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1440 OE = TiedOperands.end(); OI != OE; ++OI) {
Jakob Stoklund Olesenae52fad2012-08-03 23:57:58 +00001441 processTiedPairs(mi, OI->second, Dist);
David Greeneeb00b182010-01-05 01:24:21 +00001442 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
Jakob Stoklund Olesen351c8812012-06-25 03:27:12 +00001443 }
Bill Wendling637980e2008-05-10 00:12:52 +00001444
Jakob Stoklund Olesen351c8812012-06-25 03:27:12 +00001445 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1446 if (mi->isInsertSubreg()) {
1447 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1448 // To %reg:subidx = COPY %subreg
1449 unsigned SubIdx = mi->getOperand(3).getImm();
1450 mi->RemoveOperand(3);
1451 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1452 mi->getOperand(0).setSubReg(SubIdx);
1453 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1454 mi->RemoveOperand(1);
1455 mi->setDesc(TII->get(TargetOpcode::COPY));
1456 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
Jakob Stoklund Olesened2185e2010-07-06 23:26:25 +00001457 }
1458
Bob Wilsoncc80df92009-09-03 20:58:42 +00001459 // Clear TiedOperands here instead of at the top of the loop
1460 // since most instructions do not have tied operands.
1461 TiedOperands.clear();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001462 mi = nmi;
Misha Brukman75fa4e42004-07-22 15:26:23 +00001463 }
1464 }
1465
Evan Cheng3d720fb2010-05-05 18:45:40 +00001466 // Eliminate REG_SEQUENCE instructions. Their whole purpose was to preseve
1467 // SSA form. It's now safe to de-SSA.
1468 MadeChange |= EliminateRegSequences();
1469
Misha Brukman75fa4e42004-07-22 15:26:23 +00001470 return MadeChange;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001471}
Evan Cheng3d720fb2010-05-05 18:45:40 +00001472
1473static void UpdateRegSequenceSrcs(unsigned SrcReg,
Evan Cheng53c779b2010-05-17 20:57:12 +00001474 unsigned DstReg, unsigned SubIdx,
Jakob Stoklund Olesen5a0d4fc2010-05-29 00:14:14 +00001475 MachineRegisterInfo *MRI,
1476 const TargetRegisterInfo &TRI) {
Evan Cheng3d720fb2010-05-05 18:45:40 +00001477 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg),
Evan Cheng3ae56bc2010-05-12 01:27:49 +00001478 RE = MRI->reg_end(); RI != RE; ) {
Evan Cheng3d720fb2010-05-05 18:45:40 +00001479 MachineOperand &MO = RI.getOperand();
1480 ++RI;
Jakob Stoklund Olesen5a0d4fc2010-05-29 00:14:14 +00001481 MO.substVirtReg(DstReg, SubIdx, TRI);
Evan Cheng53c779b2010-05-17 20:57:12 +00001482 }
1483}
1484
Jakob Stoklund Olesend36f5af2012-01-24 23:28:42 +00001485// Find the first def of Reg, assuming they are all in the same basic block.
1486static MachineInstr *findFirstDef(unsigned Reg, MachineRegisterInfo *MRI) {
1487 SmallPtrSet<MachineInstr*, 8> Defs;
1488 MachineInstr *First = 0;
1489 for (MachineRegisterInfo::def_iterator RI = MRI->def_begin(Reg);
1490 MachineInstr *MI = RI.skipInstruction(); Defs.insert(MI))
1491 First = MI;
1492 if (!First)
1493 return 0;
1494
1495 MachineBasicBlock *MBB = First->getParent();
1496 MachineBasicBlock::iterator A = First, B = First;
1497 bool Moving;
1498 do {
1499 Moving = false;
1500 if (A != MBB->begin()) {
1501 Moving = true;
1502 --A;
1503 if (Defs.erase(A)) First = A;
1504 }
1505 if (B != MBB->end()) {
1506 Defs.erase(B);
1507 ++B;
1508 Moving = true;
1509 }
1510 } while (Moving && !Defs.empty());
1511 assert(Defs.empty() && "Instructions outside basic block!");
1512 return First;
1513}
1514
Evan Chengc6dcce32010-05-17 23:24:12 +00001515static bool HasOtherRegSequenceUses(unsigned Reg, MachineInstr *RegSeq,
1516 MachineRegisterInfo *MRI) {
1517 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
1518 UE = MRI->use_end(); UI != UE; ++UI) {
1519 MachineInstr *UseMI = &*UI;
1520 if (UseMI != RegSeq && UseMI->isRegSequence())
1521 return true;
1522 }
1523 return false;
1524}
1525
Evan Cheng3d720fb2010-05-05 18:45:40 +00001526/// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
1527/// of the de-ssa process. This replaces sources of REG_SEQUENCE as
1528/// sub-register references of the register defined by REG_SEQUENCE. e.g.
1529///
1530/// %reg1029<def>, %reg1030<def> = VLD1q16 %reg1024<kill>, ...
1531/// %reg1031<def> = REG_SEQUENCE %reg1029<kill>, 5, %reg1030<kill>, 6
1532/// =>
1533/// %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
1534bool TwoAddressInstructionPass::EliminateRegSequences() {
1535 if (RegSequences.empty())
1536 return false;
1537
1538 for (unsigned i = 0, e = RegSequences.size(); i != e; ++i) {
1539 MachineInstr *MI = RegSequences[i];
1540 unsigned DstReg = MI->getOperand(0).getReg();
1541 if (MI->getOperand(0).getSubReg() ||
1542 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1543 !(MI->getNumOperands() & 1)) {
1544 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1545 llvm_unreachable(0);
1546 }
Evan Cheng0bcccac2010-05-11 00:04:31 +00001547
Evan Cheng44bfdd32010-05-17 22:09:49 +00001548 bool IsImpDef = true;
Evan Chengb990a2f2010-05-14 23:21:14 +00001549 SmallVector<unsigned, 4> RealSrcs;
Evan Cheng0bcccac2010-05-11 00:04:31 +00001550 SmallSet<unsigned, 4> Seen;
Evan Cheng3d720fb2010-05-05 18:45:40 +00001551 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
Jakob Stoklund Olesen351c8812012-06-25 03:27:12 +00001552 // Nothing needs to be inserted for <undef> operands.
1553 if (MI->getOperand(i).isUndef()) {
1554 MI->getOperand(i).setReg(0);
1555 continue;
1556 }
Evan Cheng3d720fb2010-05-05 18:45:40 +00001557 unsigned SrcReg = MI->getOperand(i).getReg();
Pete Cooperef74ca62012-04-04 21:03:25 +00001558 unsigned SrcSubIdx = MI->getOperand(i).getSubReg();
Bob Wilson495de3b2010-12-17 01:21:12 +00001559 unsigned SubIdx = MI->getOperand(i+1).getImm();
Pete Coopercd7f02b2012-01-18 04:16:16 +00001560 // DefMI of NULL means the value does not have a vreg in this block
1561 // i.e., its a physical register or a subreg.
1562 // In either case we force a copy to be generated.
1563 MachineInstr *DefMI = NULL;
1564 if (!MI->getOperand(i).getSubReg() &&
1565 !TargetRegisterInfo::isPhysicalRegister(SrcReg)) {
Manman Ren5f917cd2012-07-02 18:55:36 +00001566 DefMI = MRI->getUniqueVRegDef(SrcReg);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001567 }
Evan Cheng0bcccac2010-05-11 00:04:31 +00001568
Pete Coopercd7f02b2012-01-18 04:16:16 +00001569 if (DefMI && DefMI->isImplicitDef()) {
Evan Chengb990a2f2010-05-14 23:21:14 +00001570 DefMI->eraseFromParent();
1571 continue;
1572 }
Evan Cheng44bfdd32010-05-17 22:09:49 +00001573 IsImpDef = false;
Evan Chengb990a2f2010-05-14 23:21:14 +00001574
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +00001575 // Remember COPY sources. These might be candidate for coalescing.
Pete Coopercd7f02b2012-01-18 04:16:16 +00001576 if (DefMI && DefMI->isCopy() && DefMI->getOperand(1).getSubReg())
Evan Chengb990a2f2010-05-14 23:21:14 +00001577 RealSrcs.push_back(DefMI->getOperand(1).getReg());
1578
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001579 bool isKill = MI->getOperand(i).isKill();
Pete Coopercd7f02b2012-01-18 04:16:16 +00001580 if (!DefMI || !Seen.insert(SrcReg) ||
1581 MI->getParent() != DefMI->getParent() ||
Bob Wilson495de3b2010-12-17 01:21:12 +00001582 !isKill || HasOtherRegSequenceUses(SrcReg, MI, MRI) ||
1583 !TRI->getMatchingSuperRegClass(MRI->getRegClass(DstReg),
1584 MRI->getRegClass(SrcReg), SubIdx)) {
Evan Cheng054dbb82010-05-13 00:00:35 +00001585 // REG_SEQUENCE cannot have duplicated operands, add a copy.
Jakob Stoklund Olesen34373522010-05-19 20:08:00 +00001586 // Also add an copy if the source is live-in the block. We don't want
Evan Cheng054dbb82010-05-13 00:00:35 +00001587 // to end up with a partial-redef of a livein, e.g.
1588 // BB0:
1589 // reg1051:10<def> =
1590 // ...
1591 // BB1:
1592 // ... = reg1051:10
1593 // BB2:
1594 // reg1051:9<def> =
1595 // LiveIntervalAnalysis won't like it.
Jakob Stoklund Olesen34373522010-05-19 20:08:00 +00001596 //
1597 // If the REG_SEQUENCE doesn't kill its source, keeping live variables
1598 // correctly up to date becomes very difficult. Insert a copy.
Jakob Stoklund Olesene4b9c4f2010-08-09 20:19:16 +00001599
1600 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1601 // might insert a COPY that uses SrcReg after is was killed.
1602 if (isKill)
1603 for (unsigned j = i + 2; j < e; j += 2)
1604 if (MI->getOperand(j).getReg() == SrcReg) {
1605 MI->getOperand(j).setIsKill();
1606 isKill = false;
1607 break;
1608 }
1609
Evan Cheng054dbb82010-05-13 00:00:35 +00001610 MachineBasicBlock::iterator InsertLoc = MI;
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001611 MachineInstr *CopyMI = BuildMI(*MI->getParent(), InsertLoc,
1612 MI->getDebugLoc(), TII->get(TargetOpcode::COPY))
Bob Wilson495de3b2010-12-17 01:21:12 +00001613 .addReg(DstReg, RegState::Define, SubIdx)
Pete Cooperef74ca62012-04-04 21:03:25 +00001614 .addReg(SrcReg, getKillRegState(isKill), SrcSubIdx);
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001615 MI->getOperand(i).setReg(0);
Pete Coopercd7f02b2012-01-18 04:16:16 +00001616 if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001617 LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1618 DEBUG(dbgs() << "Inserted: " << *CopyMI);
Evan Cheng0bcccac2010-05-11 00:04:31 +00001619 }
1620 }
1621
1622 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1623 unsigned SrcReg = MI->getOperand(i).getReg();
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001624 if (!SrcReg) continue;
Evan Cheng53c779b2010-05-17 20:57:12 +00001625 unsigned SubIdx = MI->getOperand(i+1).getImm();
Jakob Stoklund Olesen5a0d4fc2010-05-29 00:14:14 +00001626 UpdateRegSequenceSrcs(SrcReg, DstReg, SubIdx, MRI, *TRI);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001627 }
1628
Jakob Stoklund Olesend36f5af2012-01-24 23:28:42 +00001629 // Set <def,undef> flags on the first DstReg def in the basic block.
1630 // It marks the beginning of the live range. All the other defs are
1631 // read-modify-write.
1632 if (MachineInstr *Def = findFirstDef(DstReg, MRI)) {
1633 for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
1634 MachineOperand &MO = Def->getOperand(i);
1635 if (MO.isReg() && MO.isDef() && MO.getReg() == DstReg)
1636 MO.setIsUndef();
1637 }
Jakob Stoklund Olesend36f5af2012-01-24 23:28:42 +00001638 DEBUG(dbgs() << "First def: " << *Def);
1639 }
1640
Evan Cheng44bfdd32010-05-17 22:09:49 +00001641 if (IsImpDef) {
1642 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1643 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1644 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
Andrew Trick8247e0d2012-02-03 05:12:30 +00001645 MI->RemoveOperand(j);
Evan Cheng44bfdd32010-05-17 22:09:49 +00001646 } else {
1647 DEBUG(dbgs() << "Eliminated: " << *MI);
1648 MI->eraseFromParent();
1649 }
Evan Cheng3d720fb2010-05-05 18:45:40 +00001650 }
1651
Evan Chengfc6e6a92010-05-10 21:24:55 +00001652 RegSequences.clear();
Evan Cheng3d720fb2010-05-05 18:45:40 +00001653 return true;
1654}