blob: d71e0673d7fb4e7b1f2ffeca7ffade13bf4da365 [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"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000033#include "llvm/CodeGen/LiveVariables.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000034#include "llvm/CodeGen/MachineFunctionPass.h"
35#include "llvm/CodeGen/MachineInstr.h"
Bob Wilson852a7e32010-06-15 05:56:31 +000036#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000037#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohmana70dca12009-10-09 23:27:56 +000038#include "llvm/Analysis/AliasAnalysis.h"
Evan Cheng2a4410d2011-11-14 19:48:55 +000039#include "llvm/MC/MCInstrItineraries.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000040#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000041#include "llvm/Target/TargetInstrInfo.h"
42#include "llvm/Target/TargetMachine.h"
Owen Anderson95dad832008-10-07 20:22:28 +000043#include "llvm/Target/TargetOptions.h"
Evan Cheng875357d2008-03-13 06:37:55 +000044#include "llvm/Support/Debug.h"
Evan Cheng3d720fb2010-05-05 18:45:40 +000045#include "llvm/Support/ErrorHandling.h"
Evan Cheng7543e582008-06-18 07:49:14 +000046#include "llvm/ADT/BitVector.h"
47#include "llvm/ADT/DenseMap.h"
Dan Gohmand68a0762009-01-05 17:59:02 +000048#include "llvm/ADT/SmallSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000049#include "llvm/ADT/Statistic.h"
50#include "llvm/ADT/STLExtras.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 Cheng28c7ce32009-02-21 03:14:25 +000058STATISTIC(NumDeletes, "Number of dead instructions deleted");
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 {
Evan Cheng875357d2008-03-13 06:37:55 +000064 const TargetInstrInfo *TII;
65 const TargetRegisterInfo *TRI;
Evan Cheng2a4410d2011-11-14 19:48:55 +000066 const InstrItineraryData *InstrItins;
Evan Cheng875357d2008-03-13 06:37:55 +000067 MachineRegisterInfo *MRI;
68 LiveVariables *LV;
Dan Gohmana70dca12009-10-09 23:27:56 +000069 AliasAnalysis *AA;
Evan Chengc3aa7c52011-11-16 18:44:48 +000070 CodeGenOpt::Level OptLevel;
Evan Cheng875357d2008-03-13 06:37:55 +000071
Evan Cheng870b8072009-03-01 02:03:43 +000072 // DistanceMap - Keep track the distance of a MI from the start of the
73 // current basic block.
74 DenseMap<MachineInstr*, unsigned> DistanceMap;
75
76 // SrcRegMap - A map from virtual registers to physical registers which
77 // are likely targets to be coalesced to due to copies from physical
78 // registers to virtual registers. e.g. v1024 = move r0.
79 DenseMap<unsigned, unsigned> SrcRegMap;
80
81 // DstRegMap - A map from virtual registers to physical registers which
82 // are likely targets to be coalesced to due to copies to physical
83 // registers from virtual registers. e.g. r1 = move v1024.
84 DenseMap<unsigned, unsigned> DstRegMap;
85
Evan Cheng3d720fb2010-05-05 18:45:40 +000086 /// RegSequences - Keep track the list of REG_SEQUENCE instructions seen
87 /// during the initial walk of the machine function.
88 SmallVector<MachineInstr*, 16> RegSequences;
89
Bill Wendling637980e2008-05-10 00:12:52 +000090 bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
91 unsigned Reg,
92 MachineBasicBlock::iterator OldPos);
Evan Cheng7543e582008-06-18 07:49:14 +000093
Evan Chengd498c8f2009-01-25 03:53:59 +000094 bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
Evan Chengd498c8f2009-01-25 03:53:59 +000095 unsigned &LastDef);
96
Evan Chenge9ccb3a2009-04-28 02:12:36 +000097 MachineInstr *FindLastUseInMBB(unsigned Reg, MachineBasicBlock *MBB,
98 unsigned Dist);
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
Bob Wilson326f4382009-09-01 22:51:08 +0000115 typedef std::pair<std::pair<unsigned, bool>, MachineInstr*> NewKill;
116 bool canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
117 SmallVector<NewKill, 4> &NewKills,
118 MachineBasicBlock *MBB, unsigned Dist);
119 bool DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
120 MachineBasicBlock::iterator &nmi,
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000121 MachineFunction::iterator &mbbi, unsigned Dist);
Bob Wilson326f4382009-09-01 22:51:08 +0000122
Evan Cheng2a4410d2011-11-14 19:48:55 +0000123 bool isDefTooClose(unsigned Reg, unsigned Dist,
124 MachineInstr *MI, MachineBasicBlock *MBB);
125
126 bool RescheduleMIBelowKill(MachineBasicBlock *MBB,
127 MachineBasicBlock::iterator &mi,
128 MachineBasicBlock::iterator &nmi,
129 unsigned Reg);
130 bool RescheduleKillAboveMI(MachineBasicBlock *MBB,
131 MachineBasicBlock::iterator &mi,
132 MachineBasicBlock::iterator &nmi,
133 unsigned Reg);
134
Bob Wilsoncc80df92009-09-03 20:58:42 +0000135 bool TryInstructionTransform(MachineBasicBlock::iterator &mi,
136 MachineBasicBlock::iterator &nmi,
137 MachineFunction::iterator &mbbi,
138 unsigned SrcIdx, unsigned DstIdx,
Evan Chengf06e6c22011-03-02 01:08:17 +0000139 unsigned Dist,
140 SmallPtrSet<MachineInstr*, 8> &Processed);
141
142 void ScanUses(unsigned DstReg, MachineBasicBlock *MBB,
143 SmallPtrSet<MachineInstr*, 8> &Processed);
Bob Wilsoncc80df92009-09-03 20:58:42 +0000144
Evan Cheng870b8072009-03-01 02:03:43 +0000145 void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
146 SmallPtrSet<MachineInstr*, 8> &Processed);
Evan Cheng3a3cce52009-08-07 00:28:58 +0000147
Evan Cheng53c779b2010-05-17 20:57:12 +0000148 void CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs, unsigned DstReg);
149
Evan Cheng3d720fb2010-05-05 18:45:40 +0000150 /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
151 /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
152 /// sub-register references of the register defined by REG_SEQUENCE.
153 bool EliminateRegSequences();
Evan Chengc6dcce32010-05-17 23:24:12 +0000154
Evan Cheng875357d2008-03-13 06:37:55 +0000155 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000156 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +0000157 TwoAddressInstructionPass() : MachineFunctionPass(ID) {
158 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
159 }
Devang Patel794fd752007-05-01 21:15:47 +0000160
Bill Wendling637980e2008-05-10 00:12:52 +0000161 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +0000162 AU.setPreservesCFG();
Dan Gohmana70dca12009-10-09 23:27:56 +0000163 AU.addRequired<AliasAnalysis>();
Bill Wendling637980e2008-05-10 00:12:52 +0000164 AU.addPreserved<LiveVariables>();
165 AU.addPreservedID(MachineLoopInfoID);
166 AU.addPreservedID(MachineDominatorsID);
Bill Wendling637980e2008-05-10 00:12:52 +0000167 MachineFunctionPass::getAnalysisUsage(AU);
168 }
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000169
Bill Wendling637980e2008-05-10 00:12:52 +0000170 /// runOnMachineFunction - Pass entry point.
Misha Brukman75fa4e42004-07-22 15:26:23 +0000171 bool runOnMachineFunction(MachineFunction&);
172 };
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000173}
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000174
Dan Gohman844731a2008-05-13 00:00:25 +0000175char TwoAddressInstructionPass::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000176INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
177 "Two-Address instruction pass", false, false)
178INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
179INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
Owen Andersonce665bd2010-10-07 22:25:06 +0000180 "Two-Address instruction pass", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000181
Owen Anderson90c579d2010-08-06 18:33:48 +0000182char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000183
Evan Cheng875357d2008-03-13 06:37:55 +0000184/// Sink3AddrInstruction - A two-address instruction has been converted to a
185/// three-address instruction to avoid clobbering a register. Try to sink it
Bill Wendling637980e2008-05-10 00:12:52 +0000186/// past the instruction that would kill the above mentioned register to reduce
187/// register pressure.
Evan Cheng875357d2008-03-13 06:37:55 +0000188bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
189 MachineInstr *MI, unsigned SavedReg,
190 MachineBasicBlock::iterator OldPos) {
Eli Friedmanbde81d52011-09-23 22:41:57 +0000191 // FIXME: Shouldn't we be trying to do this before we three-addressify the
192 // instruction? After this transformation is done, we no longer need
193 // the instruction to be in three-address form.
194
Evan Cheng875357d2008-03-13 06:37:55 +0000195 // Check if it's safe to move this instruction.
196 bool SeenStore = true; // Be conservative.
Evan Chengac1abde2010-03-02 19:03:01 +0000197 if (!MI->isSafeToMove(TII, AA, SeenStore))
Evan Cheng875357d2008-03-13 06:37:55 +0000198 return false;
199
200 unsigned DefReg = 0;
201 SmallSet<unsigned, 4> UseRegs;
Bill Wendling637980e2008-05-10 00:12:52 +0000202
Evan Cheng875357d2008-03-13 06:37:55 +0000203 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
204 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000205 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000206 continue;
207 unsigned MOReg = MO.getReg();
208 if (!MOReg)
209 continue;
210 if (MO.isUse() && MOReg != SavedReg)
211 UseRegs.insert(MO.getReg());
212 if (!MO.isDef())
213 continue;
214 if (MO.isImplicit())
215 // Don't try to move it if it implicitly defines a register.
216 return false;
217 if (DefReg)
218 // For now, don't move any instructions that define multiple registers.
219 return false;
220 DefReg = MO.getReg();
221 }
222
223 // Find the instruction that kills SavedReg.
224 MachineInstr *KillMI = NULL;
Evan Chengf1250ee2010-03-23 20:36:12 +0000225 for (MachineRegisterInfo::use_nodbg_iterator
226 UI = MRI->use_nodbg_begin(SavedReg),
227 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
Evan Cheng875357d2008-03-13 06:37:55 +0000228 MachineOperand &UseMO = UI.getOperand();
229 if (!UseMO.isKill())
230 continue;
231 KillMI = UseMO.getParent();
232 break;
233 }
Bill Wendling637980e2008-05-10 00:12:52 +0000234
Eli Friedmanbde81d52011-09-23 22:41:57 +0000235 // If we find the instruction that kills SavedReg, and it is in an
236 // appropriate location, we can try to sink the current instruction
237 // past it.
238 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000239 KillMI->isTerminator())
Evan Cheng875357d2008-03-13 06:37:55 +0000240 return false;
241
Bill Wendling637980e2008-05-10 00:12:52 +0000242 // If any of the definitions are used by another instruction between the
243 // position and the kill use, then it's not safe to sink it.
Andrew Trick8247e0d2012-02-03 05:12:30 +0000244 //
Bill Wendling637980e2008-05-10 00:12:52 +0000245 // FIXME: This can be sped up if there is an easy way to query whether an
Evan Cheng7543e582008-06-18 07:49:14 +0000246 // instruction is before or after another instruction. Then we can use
Bill Wendling637980e2008-05-10 00:12:52 +0000247 // MachineRegisterInfo def / use instead.
Evan Cheng875357d2008-03-13 06:37:55 +0000248 MachineOperand *KillMO = NULL;
249 MachineBasicBlock::iterator KillPos = KillMI;
250 ++KillPos;
Bill Wendling637980e2008-05-10 00:12:52 +0000251
Evan Cheng7543e582008-06-18 07:49:14 +0000252 unsigned NumVisited = 0;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000253 for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
Evan Cheng875357d2008-03-13 06:37:55 +0000254 MachineInstr *OtherMI = I;
Dale Johannesen3bfef032010-02-11 18:22:31 +0000255 // DBG_VALUE cannot be counted against the limit.
256 if (OtherMI->isDebugValue())
257 continue;
Evan Cheng7543e582008-06-18 07:49:14 +0000258 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
259 return false;
260 ++NumVisited;
Evan Cheng875357d2008-03-13 06:37:55 +0000261 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
262 MachineOperand &MO = OtherMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000263 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000264 continue;
265 unsigned MOReg = MO.getReg();
266 if (!MOReg)
267 continue;
268 if (DefReg == MOReg)
269 return false;
Bill Wendling637980e2008-05-10 00:12:52 +0000270
Evan Cheng875357d2008-03-13 06:37:55 +0000271 if (MO.isKill()) {
272 if (OtherMI == KillMI && MOReg == SavedReg)
Evan Cheng7543e582008-06-18 07:49:14 +0000273 // Save the operand that kills the register. We want to unset the kill
274 // marker if we can sink MI past it.
Evan Cheng875357d2008-03-13 06:37:55 +0000275 KillMO = &MO;
276 else if (UseRegs.count(MOReg))
277 // One of the uses is killed before the destination.
278 return false;
279 }
280 }
281 }
282
Evan Cheng875357d2008-03-13 06:37:55 +0000283 // 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
Evan Cheng9f1c8312008-07-03 09:09:37 +0000288 if (LV)
289 LV->replaceKillInstruction(SavedReg, KillMI, MI);
Evan Cheng875357d2008-03-13 06:37:55 +0000290
291 // Move instruction to its destination.
292 MBB->remove(MI);
293 MBB->insert(KillPos, MI);
294
295 ++Num3AddrSunk;
296 return true;
297}
298
Evan Chengd498c8f2009-01-25 03:53:59 +0000299/// NoUseAfterLastDef - Return true if there are no intervening uses between the
300/// last instruction in the MBB that defines the specified register and the
301/// two-address instruction which is being processed. It also returns the last
302/// def location by reference
303bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
Evan Cheng870b8072009-03-01 02:03:43 +0000304 MachineBasicBlock *MBB, unsigned Dist,
305 unsigned &LastDef) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000306 LastDef = 0;
307 unsigned LastUse = Dist;
308 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
309 E = MRI->reg_end(); I != E; ++I) {
310 MachineOperand &MO = I.getOperand();
311 MachineInstr *MI = MO.getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000312 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesend94998f2010-02-09 02:01:46 +0000313 continue;
Evan Chengd498c8f2009-01-25 03:53:59 +0000314 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
315 if (DI == DistanceMap.end())
316 continue;
317 if (MO.isUse() && DI->second < LastUse)
318 LastUse = DI->second;
319 if (MO.isDef() && DI->second > LastDef)
320 LastDef = DI->second;
321 }
322
323 return !(LastUse > LastDef && LastUse < Dist);
324}
325
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000326MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg,
327 MachineBasicBlock *MBB,
328 unsigned Dist) {
Lang Hamesa7c9dea2009-05-14 04:26:30 +0000329 unsigned LastUseDist = 0;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000330 MachineInstr *LastUse = 0;
331 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
332 E = MRI->reg_end(); I != E; ++I) {
333 MachineOperand &MO = I.getOperand();
334 MachineInstr *MI = MO.getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000335 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesend94998f2010-02-09 02:01:46 +0000336 continue;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000337 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
338 if (DI == DistanceMap.end())
339 continue;
Lang Hamesa7c9dea2009-05-14 04:26:30 +0000340 if (DI->second >= Dist)
341 continue;
342
343 if (MO.isUse() && DI->second > LastUseDist) {
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000344 LastUse = DI->first;
345 LastUseDist = DI->second;
346 }
347 }
348 return LastUse;
349}
350
Evan Cheng870b8072009-03-01 02:03:43 +0000351/// isCopyToReg - Return true if the specified MI is a copy instruction or
352/// a extract_subreg instruction. It also returns the source and destination
353/// registers and whether they are physical registers by reference.
354static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
355 unsigned &SrcReg, unsigned &DstReg,
356 bool &IsSrcPhys, bool &IsDstPhys) {
357 SrcReg = 0;
358 DstReg = 0;
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000359 if (MI.isCopy()) {
360 DstReg = MI.getOperand(0).getReg();
361 SrcReg = MI.getOperand(1).getReg();
362 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
363 DstReg = MI.getOperand(0).getReg();
364 SrcReg = MI.getOperand(2).getReg();
365 } else
366 return false;
Evan Cheng870b8072009-03-01 02:03:43 +0000367
Jakob Stoklund Olesen04c528a2010-07-16 04:45:42 +0000368 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
369 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
370 return true;
Evan Cheng870b8072009-03-01 02:03:43 +0000371}
372
Dan Gohman97121ba2009-04-08 00:15:30 +0000373/// isKilled - Test if the given register value, which is used by the given
374/// instruction, is killed by the given instruction. This looks through
375/// coalescable copies to see if the original value is potentially not killed.
376///
377/// For example, in this code:
378///
379/// %reg1034 = copy %reg1024
380/// %reg1035 = copy %reg1025<kill>
381/// %reg1036 = add %reg1034<kill>, %reg1035<kill>
382///
383/// %reg1034 is not considered to be killed, since it is copied from a
384/// register which is not killed. Treating it as not killed lets the
385/// normal heuristics commute the (two-address) add, which lets
386/// coalescing eliminate the extra copy.
387///
388static bool isKilled(MachineInstr &MI, unsigned Reg,
389 const MachineRegisterInfo *MRI,
390 const TargetInstrInfo *TII) {
391 MachineInstr *DefMI = &MI;
392 for (;;) {
393 if (!DefMI->killsRegister(Reg))
394 return false;
395 if (TargetRegisterInfo::isPhysicalRegister(Reg))
396 return true;
397 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
398 // If there are multiple defs, we can't do a simple analysis, so just
399 // go with what the kill flag says.
Chris Lattner7896c9f2009-12-03 00:50:42 +0000400 if (llvm::next(Begin) != MRI->def_end())
Dan Gohman97121ba2009-04-08 00:15:30 +0000401 return true;
402 DefMI = &*Begin;
403 bool IsSrcPhys, IsDstPhys;
404 unsigned SrcReg, DstReg;
405 // If the def is something other than a copy, then it isn't going to
406 // be coalesced, so follow the kill flag.
407 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
408 return true;
409 Reg = SrcReg;
410 }
411}
412
Evan Cheng870b8072009-03-01 02:03:43 +0000413/// isTwoAddrUse - Return true if the specified MI uses the specified register
414/// as a two-address use. If so, return the destination register by reference.
415static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
Evan Chenge837dea2011-06-28 19:10:37 +0000416 const MCInstrDesc &MCID = MI.getDesc();
417 unsigned NumOps = MI.isInlineAsm()
418 ? MI.getNumOperands() : MCID.getNumOperands();
Evan Chenge6f350d2009-03-30 21:34:07 +0000419 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng870b8072009-03-01 02:03:43 +0000420 const MachineOperand &MO = MI.getOperand(i);
421 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
422 continue;
Evan Chenga24752f2009-03-19 20:30:06 +0000423 unsigned ti;
424 if (MI.isRegTiedToDefOperand(i, &ti)) {
Evan Cheng870b8072009-03-01 02:03:43 +0000425 DstReg = MI.getOperand(ti).getReg();
426 return true;
427 }
428 }
429 return false;
430}
431
432/// findOnlyInterestingUse - Given a register, if has a single in-basic block
433/// use, return the use instruction if it's a copy or a two-address use.
434static
435MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
436 MachineRegisterInfo *MRI,
437 const TargetInstrInfo *TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000438 bool &IsCopy,
Evan Cheng870b8072009-03-01 02:03:43 +0000439 unsigned &DstReg, bool &IsDstPhys) {
Evan Cheng1423c702010-03-03 21:18:38 +0000440 if (!MRI->hasOneNonDBGUse(Reg))
441 // None or more than one use.
Evan Cheng870b8072009-03-01 02:03:43 +0000442 return 0;
Evan Cheng1423c702010-03-03 21:18:38 +0000443 MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg);
Evan Cheng870b8072009-03-01 02:03:43 +0000444 if (UseMI.getParent() != MBB)
445 return 0;
446 unsigned SrcReg;
447 bool IsSrcPhys;
Evan Cheng87d696a2009-04-14 00:32:25 +0000448 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
449 IsCopy = true;
Evan Cheng870b8072009-03-01 02:03:43 +0000450 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000451 }
Evan Cheng870b8072009-03-01 02:03:43 +0000452 IsDstPhys = false;
Evan Cheng87d696a2009-04-14 00:32:25 +0000453 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
454 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng870b8072009-03-01 02:03:43 +0000455 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000456 }
Evan Cheng870b8072009-03-01 02:03:43 +0000457 return 0;
458}
459
460/// getMappedReg - Return the physical register the specified virtual register
461/// might be mapped to.
462static unsigned
463getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
464 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
465 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
466 if (SI == RegMap.end())
467 return 0;
468 Reg = SI->second;
469 }
470 if (TargetRegisterInfo::isPhysicalRegister(Reg))
471 return Reg;
472 return 0;
473}
474
475/// regsAreCompatible - Return true if the two registers are equal or aliased.
476///
477static bool
478regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
479 if (RegA == RegB)
480 return true;
481 if (!RegA || !RegB)
482 return false;
483 return TRI->regsOverlap(RegA, RegB);
484}
485
486
Manman Rend68e8cd2012-07-25 18:28:13 +0000487/// isProfitableToCommute - Return true if it's potentially profitable to commute
Evan Chengd498c8f2009-01-25 03:53:59 +0000488/// the two-address instruction that's being processed.
489bool
Evan Chengd99d68b2012-05-03 01:45:13 +0000490TwoAddressInstructionPass::isProfitableToCommute(unsigned regA, unsigned regB,
491 unsigned regC,
Evan Cheng870b8072009-03-01 02:03:43 +0000492 MachineInstr *MI, MachineBasicBlock *MBB,
493 unsigned Dist) {
Evan Chengc3aa7c52011-11-16 18:44:48 +0000494 if (OptLevel == CodeGenOpt::None)
495 return false;
496
Evan Chengd498c8f2009-01-25 03:53:59 +0000497 // Determine if it's profitable to commute this two address instruction. In
498 // general, we want no uses between this instruction and the definition of
499 // the two-address register.
500 // e.g.
501 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
502 // %reg1029<def> = MOV8rr %reg1028
503 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
504 // insert => %reg1030<def> = MOV8rr %reg1028
505 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
506 // In this case, it might not be possible to coalesce the second MOV8rr
507 // instruction if the first one is coalesced. So it would be profitable to
508 // commute it:
509 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
510 // %reg1029<def> = MOV8rr %reg1028
511 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
512 // insert => %reg1030<def> = MOV8rr %reg1029
Andrew Trick8247e0d2012-02-03 05:12:30 +0000513 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
Evan Chengd498c8f2009-01-25 03:53:59 +0000514
515 if (!MI->killsRegister(regC))
516 return false;
517
518 // Ok, we have something like:
519 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
520 // let's see if it's worth commuting it.
521
Evan Cheng870b8072009-03-01 02:03:43 +0000522 // Look for situations like this:
523 // %reg1024<def> = MOV r1
524 // %reg1025<def> = MOV r0
525 // %reg1026<def> = ADD %reg1024, %reg1025
526 // r0 = MOV %reg1026
527 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
Evan Chengd99d68b2012-05-03 01:45:13 +0000528 unsigned ToRegA = getMappedReg(regA, DstRegMap);
529 if (ToRegA) {
530 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
531 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
532 bool BComp = !FromRegB || regsAreCompatible(FromRegB, ToRegA, TRI);
533 bool CComp = !FromRegC || regsAreCompatible(FromRegC, ToRegA, TRI);
534 if (BComp != CComp)
535 return !BComp && CComp;
536 }
Evan Cheng870b8072009-03-01 02:03:43 +0000537
Evan Chengd498c8f2009-01-25 03:53:59 +0000538 // If there is a use of regC between its last def (could be livein) and this
539 // instruction, then bail.
540 unsigned LastDefC = 0;
Evan Cheng870b8072009-03-01 02:03:43 +0000541 if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
Evan Chengd498c8f2009-01-25 03:53:59 +0000542 return false;
543
544 // If there is a use of regB between its last def (could be livein) and this
545 // instruction, then go ahead and make this transformation.
546 unsigned LastDefB = 0;
Evan Cheng870b8072009-03-01 02:03:43 +0000547 if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
Evan Chengd498c8f2009-01-25 03:53:59 +0000548 return true;
549
550 // Since there are no intervening uses for both registers, then commute
551 // if the def of regC is closer. Its live interval is shorter.
552 return LastDefB && LastDefC && LastDefC > LastDefB;
553}
554
Evan Cheng81913712009-01-23 23:27:33 +0000555/// CommuteInstruction - Commute a two-address instruction and update the basic
556/// block, distance map, and live variables if needed. Return true if it is
557/// successful.
558bool
559TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
Evan Cheng870b8072009-03-01 02:03:43 +0000560 MachineFunction::iterator &mbbi,
561 unsigned RegB, unsigned RegC, unsigned Dist) {
Evan Cheng81913712009-01-23 23:27:33 +0000562 MachineInstr *MI = mi;
David Greeneeb00b182010-01-05 01:24:21 +0000563 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
Evan Cheng81913712009-01-23 23:27:33 +0000564 MachineInstr *NewMI = TII->commuteInstruction(MI);
565
566 if (NewMI == 0) {
David Greeneeb00b182010-01-05 01:24:21 +0000567 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
Evan Cheng81913712009-01-23 23:27:33 +0000568 return false;
569 }
570
David Greeneeb00b182010-01-05 01:24:21 +0000571 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
Evan Cheng81913712009-01-23 23:27:33 +0000572 // If the instruction changed to commute it, update livevar.
573 if (NewMI != MI) {
574 if (LV)
575 // Update live variables
576 LV->replaceKillInstruction(RegC, MI, NewMI);
577
578 mbbi->insert(mi, NewMI); // Insert the new inst
579 mbbi->erase(mi); // Nuke the old inst.
580 mi = NewMI;
581 DistanceMap.insert(std::make_pair(NewMI, Dist));
582 }
Evan Cheng870b8072009-03-01 02:03:43 +0000583
584 // Update source register map.
585 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
586 if (FromRegC) {
587 unsigned RegA = MI->getOperand(0).getReg();
588 SrcRegMap[RegA] = FromRegC;
589 }
590
Evan Cheng81913712009-01-23 23:27:33 +0000591 return true;
592}
593
Evan Chenge6f350d2009-03-30 21:34:07 +0000594/// isProfitableToConv3Addr - Return true if it is profitable to convert the
595/// given 2-address instruction to a 3-address one.
596bool
Evan Chengf06e6c22011-03-02 01:08:17 +0000597TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
Evan Chenge6f350d2009-03-30 21:34:07 +0000598 // Look for situations like this:
599 // %reg1024<def> = MOV r1
600 // %reg1025<def> = MOV r0
601 // %reg1026<def> = ADD %reg1024, %reg1025
602 // r2 = MOV %reg1026
603 // Turn ADD into a 3-address instruction to avoid a copy.
Evan Chengf06e6c22011-03-02 01:08:17 +0000604 unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
605 if (!FromRegB)
606 return false;
Evan Chenge6f350d2009-03-30 21:34:07 +0000607 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
Evan Chengf06e6c22011-03-02 01:08:17 +0000608 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
Evan Chenge6f350d2009-03-30 21:34:07 +0000609}
610
611/// ConvertInstTo3Addr - Convert the specified two-address instruction into a
612/// three address one. Return true if this transformation was successful.
613bool
614TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
615 MachineBasicBlock::iterator &nmi,
616 MachineFunction::iterator &mbbi,
Evan Cheng4d96c632011-02-10 02:20:55 +0000617 unsigned RegA, unsigned RegB,
618 unsigned Dist) {
Evan Chenge6f350d2009-03-30 21:34:07 +0000619 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
620 if (NewMI) {
David Greeneeb00b182010-01-05 01:24:21 +0000621 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
622 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
Evan Chenge6f350d2009-03-30 21:34:07 +0000623 bool Sunk = false;
624
625 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
626 // FIXME: Temporary workaround. If the new instruction doesn't
627 // uses RegB, convertToThreeAddress must have created more
628 // then one instruction.
629 Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
630
631 mbbi->erase(mi); // Nuke the old inst.
632
633 if (!Sunk) {
634 DistanceMap.insert(std::make_pair(NewMI, Dist));
635 mi = NewMI;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000636 nmi = llvm::next(mi);
Evan Chenge6f350d2009-03-30 21:34:07 +0000637 }
Evan Cheng4d96c632011-02-10 02:20:55 +0000638
639 // Update source and destination register maps.
640 SrcRegMap.erase(RegA);
641 DstRegMap.erase(RegB);
Evan Chenge6f350d2009-03-30 21:34:07 +0000642 return true;
643 }
644
645 return false;
646}
647
Evan Chengf06e6c22011-03-02 01:08:17 +0000648/// ScanUses - Scan forward recursively for only uses, update maps if the use
649/// is a copy or a two-address instruction.
650void
651TwoAddressInstructionPass::ScanUses(unsigned DstReg, MachineBasicBlock *MBB,
652 SmallPtrSet<MachineInstr*, 8> &Processed) {
653 SmallVector<unsigned, 4> VirtRegPairs;
654 bool IsDstPhys;
655 bool IsCopy = false;
656 unsigned NewReg = 0;
657 unsigned Reg = DstReg;
658 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
659 NewReg, IsDstPhys)) {
660 if (IsCopy && !Processed.insert(UseMI))
661 break;
662
663 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
664 if (DI != DistanceMap.end())
665 // Earlier in the same MBB.Reached via a back edge.
666 break;
667
668 if (IsDstPhys) {
669 VirtRegPairs.push_back(NewReg);
670 break;
671 }
672 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
673 if (!isNew)
674 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
675 VirtRegPairs.push_back(NewReg);
676 Reg = NewReg;
677 }
678
679 if (!VirtRegPairs.empty()) {
680 unsigned ToReg = VirtRegPairs.back();
681 VirtRegPairs.pop_back();
682 while (!VirtRegPairs.empty()) {
683 unsigned FromReg = VirtRegPairs.back();
684 VirtRegPairs.pop_back();
685 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
686 if (!isNew)
687 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
688 ToReg = FromReg;
689 }
690 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
691 if (!isNew)
692 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
693 }
694}
695
Evan Cheng870b8072009-03-01 02:03:43 +0000696/// ProcessCopy - If the specified instruction is not yet processed, process it
697/// if it's a copy. For a copy instruction, we find the physical registers the
698/// source and destination registers might be mapped to. These are kept in
699/// point-to maps used to determine future optimizations. e.g.
700/// v1024 = mov r0
701/// v1025 = mov r1
702/// v1026 = add v1024, v1025
703/// r1 = mov r1026
704/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
705/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
706/// potentially joined with r1 on the output side. It's worthwhile to commute
707/// 'add' to eliminate a copy.
708void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
709 MachineBasicBlock *MBB,
710 SmallPtrSet<MachineInstr*, 8> &Processed) {
711 if (Processed.count(MI))
712 return;
713
714 bool IsSrcPhys, IsDstPhys;
715 unsigned SrcReg, DstReg;
716 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
717 return;
718
719 if (IsDstPhys && !IsSrcPhys)
720 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
721 else if (!IsDstPhys && IsSrcPhys) {
Evan Cheng3005ed62009-04-13 20:04:24 +0000722 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
723 if (!isNew)
724 assert(SrcRegMap[DstReg] == SrcReg &&
725 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000726
Evan Chengf06e6c22011-03-02 01:08:17 +0000727 ScanUses(DstReg, MBB, Processed);
Evan Cheng870b8072009-03-01 02:03:43 +0000728 }
729
730 Processed.insert(MI);
Evan Chengf06e6c22011-03-02 01:08:17 +0000731 return;
Evan Cheng870b8072009-03-01 02:03:43 +0000732}
733
Evan Cheng28c7ce32009-02-21 03:14:25 +0000734/// isSafeToDelete - If the specified instruction does not produce any side
735/// effects and all of its defs are dead, then it's safe to delete.
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000736static bool isSafeToDelete(MachineInstr *MI,
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000737 const TargetInstrInfo *TII,
738 SmallVector<unsigned, 4> &Kills) {
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000739 if (MI->mayStore() || MI->isCall())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000740 return false;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000741 if (MI->isTerminator() || MI->hasUnmodeledSideEffects())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000742 return false;
743
744 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
745 MachineOperand &MO = MI->getOperand(i);
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000746 if (!MO.isReg())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000747 continue;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000748 if (MO.isDef() && !MO.isDead())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000749 return false;
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000750 if (MO.isUse() && MO.isKill())
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000751 Kills.push_back(MO.getReg());
Evan Cheng28c7ce32009-02-21 03:14:25 +0000752 }
Evan Cheng28c7ce32009-02-21 03:14:25 +0000753 return true;
754}
755
Bob Wilson326f4382009-09-01 22:51:08 +0000756/// canUpdateDeletedKills - Check if all the registers listed in Kills are
757/// killed by instructions in MBB preceding the current instruction at
758/// position Dist. If so, return true and record information about the
759/// preceding kills in NewKills.
760bool TwoAddressInstructionPass::
761canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
762 SmallVector<NewKill, 4> &NewKills,
763 MachineBasicBlock *MBB, unsigned Dist) {
764 while (!Kills.empty()) {
765 unsigned Kill = Kills.back();
766 Kills.pop_back();
767 if (TargetRegisterInfo::isPhysicalRegister(Kill))
768 return false;
769
770 MachineInstr *LastKill = FindLastUseInMBB(Kill, MBB, Dist);
771 if (!LastKill)
772 return false;
773
Evan Cheng1015ba72010-05-21 20:53:24 +0000774 bool isModRef = LastKill->definesRegister(Kill);
Bob Wilson326f4382009-09-01 22:51:08 +0000775 NewKills.push_back(std::make_pair(std::make_pair(Kill, isModRef),
776 LastKill));
777 }
778 return true;
779}
780
781/// DeleteUnusedInstr - If an instruction with a tied register operand can
782/// be safely deleted, just delete it.
783bool
784TwoAddressInstructionPass::DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
785 MachineBasicBlock::iterator &nmi,
786 MachineFunction::iterator &mbbi,
Bob Wilson326f4382009-09-01 22:51:08 +0000787 unsigned Dist) {
788 // Check if the instruction has no side effects and if all its defs are dead.
789 SmallVector<unsigned, 4> Kills;
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000790 if (!isSafeToDelete(mi, TII, Kills))
Bob Wilson326f4382009-09-01 22:51:08 +0000791 return false;
792
793 // If this instruction kills some virtual registers, we need to
794 // update the kill information. If it's not possible to do so,
795 // then bail out.
796 SmallVector<NewKill, 4> NewKills;
797 if (!canUpdateDeletedKills(Kills, NewKills, &*mbbi, Dist))
798 return false;
799
800 if (LV) {
801 while (!NewKills.empty()) {
802 MachineInstr *NewKill = NewKills.back().second;
803 unsigned Kill = NewKills.back().first.first;
804 bool isDead = NewKills.back().first.second;
805 NewKills.pop_back();
806 if (LV->removeVirtualRegisterKilled(Kill, mi)) {
807 if (isDead)
808 LV->addVirtualRegisterDead(Kill, NewKill);
809 else
810 LV->addVirtualRegisterKilled(Kill, NewKill);
811 }
812 }
Bob Wilson326f4382009-09-01 22:51:08 +0000813 }
814
815 mbbi->erase(mi); // Nuke the old inst.
816 mi = nmi;
817 return true;
818}
819
Evan Cheng2a4410d2011-11-14 19:48:55 +0000820/// RescheduleMIBelowKill - If there is one more local instruction that reads
821/// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
822/// instruction in order to eliminate the need for the copy.
823bool
824TwoAddressInstructionPass::RescheduleMIBelowKill(MachineBasicBlock *MBB,
825 MachineBasicBlock::iterator &mi,
826 MachineBasicBlock::iterator &nmi,
827 unsigned Reg) {
Chandler Carruth7d532c82012-07-15 03:29:46 +0000828 // Bail immediately if we don't have LV available. We use it to find kills
829 // efficiently.
830 if (!LV)
831 return false;
832
Evan Cheng2a4410d2011-11-14 19:48:55 +0000833 MachineInstr *MI = &*mi;
Andrew Trick8247e0d2012-02-03 05:12:30 +0000834 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000835 if (DI == DistanceMap.end())
836 // Must be created from unfolded load. Don't waste time trying this.
837 return false;
838
Chandler Carruth7d532c82012-07-15 03:29:46 +0000839 MachineInstr *KillMI = LV->getVarInfo(Reg).findKill(MBB);
840 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000841 // Don't mess with copies, they may be coalesced later.
842 return false;
843
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000844 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
845 KillMI->isBranch() || KillMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000846 // Don't move pass calls, etc.
847 return false;
848
849 unsigned DstReg;
850 if (isTwoAddrUse(*KillMI, Reg, DstReg))
851 return false;
852
Evan Chengf1784182011-11-15 06:26:51 +0000853 bool SeenStore = true;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000854 if (!MI->isSafeToMove(TII, AA, SeenStore))
855 return false;
856
857 if (TII->getInstrLatency(InstrItins, MI) > 1)
858 // FIXME: Needs more sophisticated heuristics.
859 return false;
860
861 SmallSet<unsigned, 2> Uses;
Evan Cheng9bad88a2011-11-16 03:47:42 +0000862 SmallSet<unsigned, 2> Kills;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000863 SmallSet<unsigned, 2> Defs;
864 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
865 const MachineOperand &MO = MI->getOperand(i);
866 if (!MO.isReg())
867 continue;
868 unsigned MOReg = MO.getReg();
869 if (!MOReg)
870 continue;
871 if (MO.isDef())
872 Defs.insert(MOReg);
Evan Cheng9bad88a2011-11-16 03:47:42 +0000873 else {
Evan Cheng2a4410d2011-11-14 19:48:55 +0000874 Uses.insert(MOReg);
Evan Cheng9bad88a2011-11-16 03:47:42 +0000875 if (MO.isKill() && MOReg != Reg)
876 Kills.insert(MOReg);
877 }
Evan Cheng2a4410d2011-11-14 19:48:55 +0000878 }
879
880 // Move the copies connected to MI down as well.
881 MachineBasicBlock::iterator From = MI;
882 MachineBasicBlock::iterator To = llvm::next(From);
883 while (To->isCopy() && Defs.count(To->getOperand(1).getReg())) {
884 Defs.insert(To->getOperand(0).getReg());
885 ++To;
886 }
887
888 // Check if the reschedule will not break depedencies.
889 unsigned NumVisited = 0;
890 MachineBasicBlock::iterator KillPos = KillMI;
891 ++KillPos;
892 for (MachineBasicBlock::iterator I = To; I != KillPos; ++I) {
893 MachineInstr *OtherMI = I;
894 // DBG_VALUE cannot be counted against the limit.
895 if (OtherMI->isDebugValue())
896 continue;
897 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
898 return false;
899 ++NumVisited;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000900 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
901 OtherMI->isBranch() || OtherMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000902 // Don't move pass calls, etc.
903 return false;
904 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
905 const MachineOperand &MO = OtherMI->getOperand(i);
906 if (!MO.isReg())
907 continue;
908 unsigned MOReg = MO.getReg();
909 if (!MOReg)
910 continue;
911 if (MO.isDef()) {
912 if (Uses.count(MOReg))
913 // Physical register use would be clobbered.
914 return false;
915 if (!MO.isDead() && Defs.count(MOReg))
916 // May clobber a physical register def.
917 // FIXME: This may be too conservative. It's ok if the instruction
918 // is sunken completely below the use.
919 return false;
920 } else {
921 if (Defs.count(MOReg))
922 return false;
Evan Cheng9bad88a2011-11-16 03:47:42 +0000923 if (MOReg != Reg &&
924 ((MO.isKill() && Uses.count(MOReg)) || Kills.count(MOReg)))
Evan Cheng2a4410d2011-11-14 19:48:55 +0000925 // Don't want to extend other live ranges and update kills.
926 return false;
Chandler Carruth7d532c82012-07-15 03:29:46 +0000927 if (MOReg == Reg && !MO.isKill())
928 // We can't schedule across a use of the register in question.
929 return false;
930 // Ensure that if this is register in question, its the kill we expect.
931 assert((MOReg != Reg || OtherMI == KillMI) &&
932 "Found multiple kills of a register in a basic block");
Evan Cheng2a4410d2011-11-14 19:48:55 +0000933 }
934 }
935 }
936
937 // Move debug info as well.
Evan Cheng8aee7d82011-11-14 21:11:15 +0000938 while (From != MBB->begin() && llvm::prior(From)->isDebugValue())
939 --From;
Evan Cheng2a4410d2011-11-14 19:48:55 +0000940
941 // Copies following MI may have been moved as well.
942 nmi = To;
943 MBB->splice(KillPos, MBB, From, To);
944 DistanceMap.erase(DI);
945
Chandler Carruth7d532c82012-07-15 03:29:46 +0000946 // Update live variables
947 LV->removeVirtualRegisterKilled(Reg, KillMI);
948 LV->addVirtualRegisterKilled(Reg, MI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000949
Jakob Stoklund Olesena532bce2012-07-17 17:57:23 +0000950 DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
Evan Cheng2a4410d2011-11-14 19:48:55 +0000951 return true;
952}
953
954/// isDefTooClose - Return true if the re-scheduling will put the given
955/// instruction too close to the defs of its register dependencies.
956bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
957 MachineInstr *MI,
958 MachineBasicBlock *MBB) {
959 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(Reg),
960 DE = MRI->def_end(); DI != DE; ++DI) {
961 MachineInstr *DefMI = &*DI;
962 if (DefMI->getParent() != MBB || DefMI->isCopy() || DefMI->isCopyLike())
963 continue;
964 if (DefMI == MI)
965 return true; // MI is defining something KillMI uses
966 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(DefMI);
967 if (DDI == DistanceMap.end())
968 return true; // Below MI
969 unsigned DefDist = DDI->second;
970 assert(Dist > DefDist && "Visited def already?");
Andrew Trickb7e02892012-06-05 21:11:27 +0000971 if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist))
Evan Cheng2a4410d2011-11-14 19:48:55 +0000972 return true;
973 }
974 return false;
975}
976
977/// RescheduleKillAboveMI - If there is one more local instruction that reads
978/// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
979/// current two-address instruction in order to eliminate the need for the
980/// copy.
981bool
982TwoAddressInstructionPass::RescheduleKillAboveMI(MachineBasicBlock *MBB,
983 MachineBasicBlock::iterator &mi,
984 MachineBasicBlock::iterator &nmi,
985 unsigned Reg) {
Chandler Carruth7d532c82012-07-15 03:29:46 +0000986 // Bail immediately if we don't have LV available. We use it to find kills
987 // efficiently.
988 if (!LV)
989 return false;
990
Evan Cheng2a4410d2011-11-14 19:48:55 +0000991 MachineInstr *MI = &*mi;
992 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
993 if (DI == DistanceMap.end())
994 // Must be created from unfolded load. Don't waste time trying this.
995 return false;
996
Chandler Carruth7d532c82012-07-15 03:29:46 +0000997 MachineInstr *KillMI = LV->getVarInfo(Reg).findKill(MBB);
998 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
Evan Cheng2a4410d2011-11-14 19:48:55 +0000999 // Don't mess with copies, they may be coalesced later.
1000 return false;
1001
1002 unsigned DstReg;
1003 if (isTwoAddrUse(*KillMI, Reg, DstReg))
1004 return false;
1005
Evan Chengf1784182011-11-15 06:26:51 +00001006 bool SeenStore = true;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001007 if (!KillMI->isSafeToMove(TII, AA, SeenStore))
1008 return false;
1009
1010 SmallSet<unsigned, 2> Uses;
1011 SmallSet<unsigned, 2> Kills;
1012 SmallSet<unsigned, 2> Defs;
1013 SmallSet<unsigned, 2> LiveDefs;
1014 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
1015 const MachineOperand &MO = KillMI->getOperand(i);
1016 if (!MO.isReg())
1017 continue;
1018 unsigned MOReg = MO.getReg();
1019 if (MO.isUse()) {
1020 if (!MOReg)
1021 continue;
1022 if (isDefTooClose(MOReg, DI->second, MI, MBB))
1023 return false;
Chandler Carruth7d532c82012-07-15 03:29:46 +00001024 if (MOReg == Reg && !MO.isKill())
1025 return false;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001026 Uses.insert(MOReg);
1027 if (MO.isKill() && MOReg != Reg)
1028 Kills.insert(MOReg);
1029 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1030 Defs.insert(MOReg);
1031 if (!MO.isDead())
1032 LiveDefs.insert(MOReg);
1033 }
1034 }
1035
1036 // Check if the reschedule will not break depedencies.
1037 unsigned NumVisited = 0;
1038 MachineBasicBlock::iterator KillPos = KillMI;
1039 for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
1040 MachineInstr *OtherMI = I;
1041 // DBG_VALUE cannot be counted against the limit.
1042 if (OtherMI->isDebugValue())
1043 continue;
1044 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
1045 return false;
1046 ++NumVisited;
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001047 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
1048 OtherMI->isBranch() || OtherMI->isTerminator())
Evan Cheng2a4410d2011-11-14 19:48:55 +00001049 // Don't move pass calls, etc.
1050 return false;
Evan Chengae7db7a2011-11-16 03:05:12 +00001051 SmallVector<unsigned, 2> OtherDefs;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001052 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
1053 const MachineOperand &MO = OtherMI->getOperand(i);
1054 if (!MO.isReg())
1055 continue;
1056 unsigned MOReg = MO.getReg();
1057 if (!MOReg)
1058 continue;
1059 if (MO.isUse()) {
1060 if (Defs.count(MOReg))
1061 // Moving KillMI can clobber the physical register if the def has
1062 // not been seen.
1063 return false;
1064 if (Kills.count(MOReg))
1065 // Don't want to extend other live ranges and update kills.
1066 return false;
Chandler Carruth7d532c82012-07-15 03:29:46 +00001067 if (OtherMI != MI && MOReg == Reg && !MO.isKill())
1068 // We can't schedule across a use of the register in question.
1069 return false;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001070 } else {
Evan Chengae7db7a2011-11-16 03:05:12 +00001071 OtherDefs.push_back(MOReg);
Evan Cheng2a4410d2011-11-14 19:48:55 +00001072 }
1073 }
Evan Chengae7db7a2011-11-16 03:05:12 +00001074
1075 for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
1076 unsigned MOReg = OtherDefs[i];
1077 if (Uses.count(MOReg))
1078 return false;
1079 if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1080 LiveDefs.count(MOReg))
1081 return false;
1082 // Physical register def is seen.
1083 Defs.erase(MOReg);
1084 }
Evan Cheng2a4410d2011-11-14 19:48:55 +00001085 }
1086
1087 // Move the old kill above MI, don't forget to move debug info as well.
1088 MachineBasicBlock::iterator InsertPos = mi;
Evan Cheng8aee7d82011-11-14 21:11:15 +00001089 while (InsertPos != MBB->begin() && llvm::prior(InsertPos)->isDebugValue())
1090 --InsertPos;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001091 MachineBasicBlock::iterator From = KillMI;
1092 MachineBasicBlock::iterator To = llvm::next(From);
1093 while (llvm::prior(From)->isDebugValue())
1094 --From;
1095 MBB->splice(InsertPos, MBB, From, To);
1096
Evan Cheng2bee6a82011-11-16 03:33:08 +00001097 nmi = llvm::prior(InsertPos); // Backtrack so we process the moved instr.
Evan Cheng2a4410d2011-11-14 19:48:55 +00001098 DistanceMap.erase(DI);
1099
Chandler Carruth7d532c82012-07-15 03:29:46 +00001100 // Update live variables
1101 LV->removeVirtualRegisterKilled(Reg, KillMI);
1102 LV->addVirtualRegisterKilled(Reg, MI);
1103
Jakob Stoklund Olesena532bce2012-07-17 17:57:23 +00001104 DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
Evan Cheng2a4410d2011-11-14 19:48:55 +00001105 return true;
1106}
1107
Bob Wilsoncc80df92009-09-03 20:58:42 +00001108/// TryInstructionTransform - For the case where an instruction has a single
1109/// pair of tied register operands, attempt some transformations that may
1110/// either eliminate the tied operands or improve the opportunities for
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001111/// coalescing away the register copy. Returns true if no copy needs to be
1112/// inserted to untie mi's operands (either because they were untied, or
1113/// because mi was rescheduled, and will be visited again later).
Bob Wilsoncc80df92009-09-03 20:58:42 +00001114bool TwoAddressInstructionPass::
1115TryInstructionTransform(MachineBasicBlock::iterator &mi,
1116 MachineBasicBlock::iterator &nmi,
1117 MachineFunction::iterator &mbbi,
Evan Chengf06e6c22011-03-02 01:08:17 +00001118 unsigned SrcIdx, unsigned DstIdx, unsigned Dist,
1119 SmallPtrSet<MachineInstr*, 8> &Processed) {
Evan Chengc3aa7c52011-11-16 18:44:48 +00001120 if (OptLevel == CodeGenOpt::None)
1121 return false;
1122
Evan Cheng2a4410d2011-11-14 19:48:55 +00001123 MachineInstr &MI = *mi;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001124 unsigned regA = MI.getOperand(DstIdx).getReg();
1125 unsigned regB = MI.getOperand(SrcIdx).getReg();
Bob Wilsoncc80df92009-09-03 20:58:42 +00001126
1127 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1128 "cannot make instruction into two-address form");
1129
1130 // If regA is dead and the instruction can be deleted, just delete
1131 // it so it doesn't clobber regB.
Evan Cheng2a4410d2011-11-14 19:48:55 +00001132 bool regBKilled = isKilled(MI, regB, MRI, TII);
1133 if (!regBKilled && MI.getOperand(DstIdx).isDead() &&
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +00001134 DeleteUnusedInstr(mi, nmi, mbbi, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001135 ++NumDeletes;
Jakob Stoklund Olesena532bce2012-07-17 17:57:23 +00001136 DEBUG(dbgs() << "\tdeleted unused instruction.\n");
1137 return true; // Done with this instruction."
Bob Wilsoncc80df92009-09-03 20:58:42 +00001138 }
1139
Evan Chengd99d68b2012-05-03 01:45:13 +00001140 if (TargetRegisterInfo::isVirtualRegister(regA))
1141 ScanUses(regA, &*mbbi, Processed);
1142
Bob Wilsoncc80df92009-09-03 20:58:42 +00001143 // Check if it is profitable to commute the operands.
1144 unsigned SrcOp1, SrcOp2;
1145 unsigned regC = 0;
1146 unsigned regCIdx = ~0U;
1147 bool TryCommute = false;
1148 bool AggressiveCommute = false;
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001149 if (MI.isCommutable() && MI.getNumOperands() >= 3 &&
Evan Cheng2a4410d2011-11-14 19:48:55 +00001150 TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001151 if (SrcIdx == SrcOp1)
1152 regCIdx = SrcOp2;
1153 else if (SrcIdx == SrcOp2)
1154 regCIdx = SrcOp1;
1155
1156 if (regCIdx != ~0U) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001157 regC = MI.getOperand(regCIdx).getReg();
1158 if (!regBKilled && isKilled(MI, regC, MRI, TII))
Bob Wilsoncc80df92009-09-03 20:58:42 +00001159 // If C dies but B does not, swap the B and C operands.
1160 // This makes the live ranges of A and C joinable.
1161 TryCommute = true;
Evan Chengd99d68b2012-05-03 01:45:13 +00001162 else if (isProfitableToCommute(regA, regB, regC, &MI, mbbi, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001163 TryCommute = true;
1164 AggressiveCommute = true;
1165 }
1166 }
1167 }
1168
1169 // If it's profitable to commute, try to do so.
1170 if (TryCommute && CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
1171 ++NumCommuted;
1172 if (AggressiveCommute)
1173 ++NumAggrCommuted;
1174 return false;
1175 }
1176
Evan Cheng2a4410d2011-11-14 19:48:55 +00001177 // If there is one more use of regB later in the same MBB, consider
1178 // re-schedule this MI below it.
1179 if (RescheduleMIBelowKill(mbbi, mi, nmi, regB)) {
1180 ++NumReSchedDowns;
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001181 return true;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001182 }
1183
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001184 if (MI.isConvertibleTo3Addr()) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001185 // This instruction is potentially convertible to a true
1186 // three-address instruction. Check if it is profitable.
Evan Chengf06e6c22011-03-02 01:08:17 +00001187 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001188 // Try to convert it.
Evan Cheng4d96c632011-02-10 02:20:55 +00001189 if (ConvertInstTo3Addr(mi, nmi, mbbi, regA, regB, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001190 ++NumConvertedTo3Addr;
1191 return true; // Done with this instruction.
1192 }
1193 }
1194 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001195
Evan Cheng2a4410d2011-11-14 19:48:55 +00001196 // If there is one more use of regB later in the same MBB, consider
1197 // re-schedule it before this MI if it's legal.
1198 if (RescheduleKillAboveMI(mbbi, mi, nmi, regB)) {
1199 ++NumReSchedUps;
Lang Hamesf31ceaf2012-04-09 20:17:30 +00001200 return true;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001201 }
1202
Dan Gohman584fedf2010-06-21 22:17:20 +00001203 // If this is an instruction with a load folded into it, try unfolding
1204 // the load, e.g. avoid this:
1205 // movq %rdx, %rcx
1206 // addq (%rax), %rcx
1207 // in favor of this:
1208 // movq (%rax), %rcx
1209 // addq %rdx, %rcx
1210 // because it's preferable to schedule a load than a register copy.
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001211 if (MI.mayLoad() && !regBKilled) {
Dan Gohman584fedf2010-06-21 22:17:20 +00001212 // Determine if a load can be unfolded.
1213 unsigned LoadRegIndex;
1214 unsigned NewOpc =
Evan Cheng2a4410d2011-11-14 19:48:55 +00001215 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
Dan Gohman584fedf2010-06-21 22:17:20 +00001216 /*UnfoldLoad=*/true,
1217 /*UnfoldStore=*/false,
1218 &LoadRegIndex);
1219 if (NewOpc != 0) {
Evan Chenge837dea2011-06-28 19:10:37 +00001220 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1221 if (UnfoldMCID.getNumDefs() == 1) {
Dan Gohman584fedf2010-06-21 22:17:20 +00001222 MachineFunction &MF = *mbbi->getParent();
1223
1224 // Unfold the load.
Evan Cheng2a4410d2011-11-14 19:48:55 +00001225 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
Dan Gohman584fedf2010-06-21 22:17:20 +00001226 const TargetRegisterClass *RC =
Andrew Trickf12f6df2012-05-03 01:14:37 +00001227 TRI->getAllocatableClass(
Jakob Stoklund Olesen397fc482012-05-07 22:10:26 +00001228 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, MF));
Dan Gohman584fedf2010-06-21 22:17:20 +00001229 unsigned Reg = MRI->createVirtualRegister(RC);
1230 SmallVector<MachineInstr *, 2> NewMIs;
Evan Cheng2a4410d2011-11-14 19:48:55 +00001231 if (!TII->unfoldMemoryOperand(MF, &MI, Reg,
Evan Cheng98ec91e2010-07-02 20:36:18 +00001232 /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
1233 NewMIs)) {
1234 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1235 return false;
1236 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001237 assert(NewMIs.size() == 2 &&
1238 "Unfolded a load into multiple instructions!");
1239 // The load was previously folded, so this is the only use.
1240 NewMIs[1]->addRegisterKilled(Reg, TRI);
1241
1242 // Tentatively insert the instructions into the block so that they
1243 // look "normal" to the transformation logic.
1244 mbbi->insert(mi, NewMIs[0]);
1245 mbbi->insert(mi, NewMIs[1]);
1246
1247 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1248 << "2addr: NEW INST: " << *NewMIs[1]);
1249
1250 // Transform the instruction, now that it no longer has a load.
1251 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1252 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1253 MachineBasicBlock::iterator NewMI = NewMIs[1];
1254 bool TransformSuccess =
1255 TryInstructionTransform(NewMI, mi, mbbi,
Evan Chengf06e6c22011-03-02 01:08:17 +00001256 NewSrcIdx, NewDstIdx, Dist, Processed);
Dan Gohman584fedf2010-06-21 22:17:20 +00001257 if (TransformSuccess ||
1258 NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1259 // Success, or at least we made an improvement. Keep the unfolded
1260 // instructions and discard the original.
1261 if (LV) {
Evan Cheng2a4410d2011-11-14 19:48:55 +00001262 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1263 MachineOperand &MO = MI.getOperand(i);
Andrew Trick8247e0d2012-02-03 05:12:30 +00001264 if (MO.isReg() &&
Dan Gohman7aa7bc72010-06-22 00:32:04 +00001265 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1266 if (MO.isUse()) {
Dan Gohmancc1ca982010-06-22 02:07:21 +00001267 if (MO.isKill()) {
1268 if (NewMIs[0]->killsRegister(MO.getReg()))
Evan Cheng2a4410d2011-11-14 19:48:55 +00001269 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
Dan Gohmancc1ca982010-06-22 02:07:21 +00001270 else {
1271 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1272 "Kill missing after load unfold!");
Evan Cheng2a4410d2011-11-14 19:48:55 +00001273 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
Dan Gohmancc1ca982010-06-22 02:07:21 +00001274 }
1275 }
Evan Cheng2a4410d2011-11-14 19:48:55 +00001276 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
Dan Gohmancc1ca982010-06-22 02:07:21 +00001277 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1278 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
1279 else {
1280 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1281 "Dead flag missing after load unfold!");
1282 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
1283 }
1284 }
Dan Gohman7aa7bc72010-06-22 00:32:04 +00001285 }
Dan Gohman584fedf2010-06-21 22:17:20 +00001286 }
1287 LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
1288 }
Evan Cheng2a4410d2011-11-14 19:48:55 +00001289 MI.eraseFromParent();
Dan Gohman584fedf2010-06-21 22:17:20 +00001290 mi = NewMIs[1];
1291 if (TransformSuccess)
1292 return true;
1293 } else {
1294 // Transforming didn't eliminate the tie and didn't lead to an
1295 // improvement. Clean up the unfolded instructions and keep the
1296 // original.
1297 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1298 NewMIs[0]->eraseFromParent();
1299 NewMIs[1]->eraseFromParent();
1300 }
1301 }
1302 }
1303 }
1304
Bob Wilsoncc80df92009-09-03 20:58:42 +00001305 return false;
1306}
1307
Bill Wendling637980e2008-05-10 00:12:52 +00001308/// runOnMachineFunction - Reduce two-address instructions to two operands.
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001309///
Chris Lattner163c1e72004-01-31 21:14:04 +00001310bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
Misha Brukman75fa4e42004-07-22 15:26:23 +00001311 const TargetMachine &TM = MF.getTarget();
Evan Cheng875357d2008-03-13 06:37:55 +00001312 MRI = &MF.getRegInfo();
1313 TII = TM.getInstrInfo();
1314 TRI = TM.getRegisterInfo();
Evan Cheng2a4410d2011-11-14 19:48:55 +00001315 InstrItins = TM.getInstrItineraryData();
Duncan Sands1465d612009-01-28 13:14:17 +00001316 LV = getAnalysisIfAvailable<LiveVariables>();
Dan Gohmana70dca12009-10-09 23:27:56 +00001317 AA = &getAnalysis<AliasAnalysis>();
Evan Chengc3aa7c52011-11-16 18:44:48 +00001318 OptLevel = TM.getOptLevel();
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001319
Misha Brukman75fa4e42004-07-22 15:26:23 +00001320 bool MadeChange = false;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001321
David Greeneeb00b182010-01-05 01:24:21 +00001322 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
Andrew Trick8247e0d2012-02-03 05:12:30 +00001323 DEBUG(dbgs() << "********** Function: "
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001324 << MF.getFunction()->getName() << '\n');
Alkis Evlogimenos3a9986f2004-02-18 00:35:06 +00001325
Jakob Stoklund Olesen73e7dce2011-07-29 22:51:22 +00001326 // This pass takes the function out of SSA form.
1327 MRI->leaveSSA();
1328
Evan Cheng7543e582008-06-18 07:49:14 +00001329 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
Jakob Stoklund Olesen00f93fc2011-01-09 03:45:44 +00001330 BitVector ReMatRegs(MRI->getNumVirtRegs());
Evan Cheng7543e582008-06-18 07:49:14 +00001331
Bob Wilsoncc80df92009-09-03 20:58:42 +00001332 typedef DenseMap<unsigned, SmallVector<std::pair<unsigned, unsigned>, 4> >
1333 TiedOperandMap;
1334 TiedOperandMap TiedOperands(4);
1335
Evan Cheng870b8072009-03-01 02:03:43 +00001336 SmallPtrSet<MachineInstr*, 8> Processed;
Misha Brukman75fa4e42004-07-22 15:26:23 +00001337 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
1338 mbbi != mbbe; ++mbbi) {
Evan Cheng7543e582008-06-18 07:49:14 +00001339 unsigned Dist = 0;
1340 DistanceMap.clear();
Evan Cheng870b8072009-03-01 02:03:43 +00001341 SrcRegMap.clear();
1342 DstRegMap.clear();
1343 Processed.clear();
Misha Brukman75fa4e42004-07-22 15:26:23 +00001344 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001345 mi != me; ) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001346 MachineBasicBlock::iterator nmi = llvm::next(mi);
Dale Johannesenb8ff9342010-02-10 21:47:48 +00001347 if (mi->isDebugValue()) {
1348 mi = nmi;
1349 continue;
1350 }
Evan Chengf1250ee2010-03-23 20:36:12 +00001351
Evan Cheng3d720fb2010-05-05 18:45:40 +00001352 // Remember REG_SEQUENCE instructions, we'll deal with them later.
1353 if (mi->isRegSequence())
1354 RegSequences.push_back(&*mi);
1355
Evan Chenge837dea2011-06-28 19:10:37 +00001356 const MCInstrDesc &MCID = mi->getDesc();
Evan Cheng360c2dd2006-11-01 23:06:55 +00001357 bool FirstTied = true;
Bill Wendling637980e2008-05-10 00:12:52 +00001358
Evan Cheng7543e582008-06-18 07:49:14 +00001359 DistanceMap.insert(std::make_pair(mi, ++Dist));
Evan Cheng870b8072009-03-01 02:03:43 +00001360
1361 ProcessCopy(&*mi, &*mbbi, Processed);
1362
Bob Wilsoncc80df92009-09-03 20:58:42 +00001363 // First scan through all the tied register uses in this instruction
1364 // and record a list of pairs of tied operands for each register.
Chris Lattner518bb532010-02-09 19:54:29 +00001365 unsigned NumOps = mi->isInlineAsm()
Evan Chenge837dea2011-06-28 19:10:37 +00001366 ? mi->getNumOperands() : MCID.getNumOperands();
Bob Wilsoncc80df92009-09-03 20:58:42 +00001367 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1368 unsigned DstIdx = 0;
1369 if (!mi->isRegTiedToDefOperand(SrcIdx, &DstIdx))
Evan Cheng360c2dd2006-11-01 23:06:55 +00001370 continue;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001371
Evan Cheng360c2dd2006-11-01 23:06:55 +00001372 if (FirstTied) {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001373 FirstTied = false;
Evan Cheng360c2dd2006-11-01 23:06:55 +00001374 ++NumTwoAddressInstrs;
David Greeneeb00b182010-01-05 01:24:21 +00001375 DEBUG(dbgs() << '\t' << *mi);
Evan Cheng360c2dd2006-11-01 23:06:55 +00001376 }
Bill Wendling637980e2008-05-10 00:12:52 +00001377
Bob Wilsoncc80df92009-09-03 20:58:42 +00001378 assert(mi->getOperand(SrcIdx).isReg() &&
1379 mi->getOperand(SrcIdx).getReg() &&
1380 mi->getOperand(SrcIdx).isUse() &&
1381 "two address instruction invalid");
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001382
Bob Wilsoncc80df92009-09-03 20:58:42 +00001383 unsigned regB = mi->getOperand(SrcIdx).getReg();
Jakob Stoklund Olesen351c8812012-06-25 03:27:12 +00001384
1385 // Deal with <undef> uses immediately - simply rewrite the src operand.
1386 if (mi->getOperand(SrcIdx).isUndef()) {
1387 unsigned DstReg = mi->getOperand(DstIdx).getReg();
1388 // Constrain the DstReg register class if required.
1389 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1390 if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
1391 TRI, MF))
1392 MRI->constrainRegClass(DstReg, RC);
1393 mi->getOperand(SrcIdx).setReg(DstReg);
1394 DEBUG(dbgs() << "\t\trewrite undef:\t" << *mi);
1395 continue;
1396 }
Benjamin Kramer4e39f8f2011-06-18 13:53:47 +00001397 TiedOperands[regB].push_back(std::make_pair(SrcIdx, DstIdx));
Bob Wilsoncc80df92009-09-03 20:58:42 +00001398 }
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001399
Chandler Carruth32d75be2012-07-18 18:58:22 +00001400 // If the instruction has a single pair of tied operands, try some
1401 // transformations that may either eliminate the tied operands or
1402 // improve the opportunities for coalescing away the register copy.
1403 if (TiedOperands.size() == 1) {
1404 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs
1405 = TiedOperands.begin()->second;
1406 if (TiedPairs.size() == 1) {
1407 unsigned SrcIdx = TiedPairs[0].first;
1408 unsigned DstIdx = TiedPairs[0].second;
1409 unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
1410 unsigned DstReg = mi->getOperand(DstIdx).getReg();
1411 if (SrcReg != DstReg &&
1412 TryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist,
1413 Processed)) {
1414 // The tied operands have been eliminated or shifted further down the
1415 // block to ease elimination. Continue processing with 'nmi'.
1416 TiedOperands.clear();
1417 mi = nmi;
1418 continue;
1419 }
1420 }
1421 }
1422
Bob Wilsoncc80df92009-09-03 20:58:42 +00001423 // Now iterate over the information collected above.
1424 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1425 OE = TiedOperands.end(); OI != OE; ++OI) {
1426 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs = OI->second;
Evan Cheng360c2dd2006-11-01 23:06:55 +00001427
Cameron Zwarichaaa5f142011-06-07 23:54:00 +00001428 bool IsEarlyClobber = false;
Bob Wilsoncc80df92009-09-03 20:58:42 +00001429 bool RemovedKillFlag = false;
1430 bool AllUsesCopied = true;
1431 unsigned LastCopiedReg = 0;
1432 unsigned regB = OI->first;
1433 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1434 unsigned SrcIdx = TiedPairs[tpi].first;
1435 unsigned DstIdx = TiedPairs[tpi].second;
Cameron Zwarichaaa5f142011-06-07 23:54:00 +00001436
1437 const MachineOperand &DstMO = mi->getOperand(DstIdx);
1438 unsigned regA = DstMO.getReg();
1439 IsEarlyClobber |= DstMO.isEarlyClobber();
1440
Bob Wilsoncc80df92009-09-03 20:58:42 +00001441 // Grab regB from the instruction because it may have changed if the
1442 // instruction was commuted.
1443 regB = mi->getOperand(SrcIdx).getReg();
1444
1445 if (regA == regB) {
1446 // The register is tied to multiple destinations (or else we would
1447 // not have continued this far), but this use of the register
1448 // already matches the tied destination. Leave it.
1449 AllUsesCopied = false;
1450 continue;
1451 }
1452 LastCopiedReg = regA;
1453
1454 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1455 "cannot make instruction into two-address form");
Chris Lattner6b507672004-01-31 21:21:43 +00001456
Chris Lattner1e313632004-07-21 23:17:57 +00001457#ifndef NDEBUG
Bob Wilsoncc80df92009-09-03 20:58:42 +00001458 // First, verify that we don't have a use of "a" in the instruction
1459 // (a = b + a for example) because our transformation will not
1460 // work. This should never occur because we are in SSA form.
1461 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
1462 assert(i == DstIdx ||
1463 !mi->getOperand(i).isReg() ||
1464 mi->getOperand(i).getReg() != regA);
Chris Lattner1e313632004-07-21 23:17:57 +00001465#endif
Alkis Evlogimenos14be6402004-02-04 22:17:40 +00001466
Manman Rend68e8cd2012-07-25 18:28:13 +00001467 // Emit a copy.
1468 BuildMI(*mbbi, mi, mi->getDebugLoc(), TII->get(TargetOpcode::COPY),
1469 regA).addReg(regB);
Bob Wilsoncc80df92009-09-03 20:58:42 +00001470
Bob Wilsoncc80df92009-09-03 20:58:42 +00001471 // Update DistanceMap.
Evan Chengad753642012-05-18 01:33:51 +00001472 MachineBasicBlock::iterator prevMI = prior(mi);
Bob Wilsoncc80df92009-09-03 20:58:42 +00001473 DistanceMap.insert(std::make_pair(prevMI, Dist));
1474 DistanceMap[mi] = ++Dist;
1475
David Greeneeb00b182010-01-05 01:24:21 +00001476 DEBUG(dbgs() << "\t\tprepend:\t" << *prevMI);
Bob Wilsoncc80df92009-09-03 20:58:42 +00001477
1478 MachineOperand &MO = mi->getOperand(SrcIdx);
1479 assert(MO.isReg() && MO.getReg() == regB && MO.isUse() &&
1480 "inconsistent operand info for 2-reg pass");
1481 if (MO.isKill()) {
1482 MO.setIsKill(false);
1483 RemovedKillFlag = true;
1484 }
Jakob Stoklund Olesen8e869292012-05-20 06:38:32 +00001485
1486 // Make sure regA is a legal regclass for the SrcIdx operand.
1487 if (TargetRegisterInfo::isVirtualRegister(regA) &&
1488 TargetRegisterInfo::isVirtualRegister(regB))
1489 MRI->constrainRegClass(regA, MRI->getRegClass(regB));
1490
Bob Wilsoncc80df92009-09-03 20:58:42 +00001491 MO.setReg(regA);
Evan Chengad753642012-05-18 01:33:51 +00001492
Manman Rend68e8cd2012-07-25 18:28:13 +00001493 // Propagate SrcRegMap.
1494 SrcRegMap[regA] = regB;
Bob Wilsoncc80df92009-09-03 20:58:42 +00001495 }
1496
1497 if (AllUsesCopied) {
Cameron Zwarichaaa5f142011-06-07 23:54:00 +00001498 if (!IsEarlyClobber) {
1499 // Replace other (un-tied) uses of regB with LastCopiedReg.
1500 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1501 MachineOperand &MO = mi->getOperand(i);
1502 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1503 if (MO.isKill()) {
1504 MO.setIsKill(false);
1505 RemovedKillFlag = true;
1506 }
1507 MO.setReg(LastCopiedReg);
Bob Wilsoncc80df92009-09-03 20:58:42 +00001508 }
Bob Wilsoncc80df92009-09-03 20:58:42 +00001509 }
1510 }
1511
1512 // Update live variables for regB.
1513 if (RemovedKillFlag && LV && LV->getVarInfo(regB).removeKill(mi))
1514 LV->addVirtualRegisterKilled(regB, prior(mi));
1515
1516 } else if (RemovedKillFlag) {
1517 // Some tied uses of regB matched their destination registers, so
1518 // regB is still used in this instruction, but a kill flag was
1519 // removed from a different tied use of regB, so now we need to add
1520 // a kill flag to one of the remaining uses of regB.
1521 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1522 MachineOperand &MO = mi->getOperand(i);
1523 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1524 MO.setIsKill(true);
1525 break;
Bob Wilson71124f62009-09-01 04:18:40 +00001526 }
1527 }
Bob Wilson43449792009-08-31 21:54:55 +00001528 }
Evan Cheng68fc2da2010-06-09 19:26:01 +00001529
Chandler Carruth32d75be2012-07-18 18:58:22 +00001530 // We didn't change anything if there was a single tied pair, and that
1531 // pair didn't require copies.
1532 if (AllUsesCopied || TiedPairs.size() > 1) {
1533 MadeChange = true;
Evan Cheng68fc2da2010-06-09 19:26:01 +00001534
Chandler Carruth32d75be2012-07-18 18:58:22 +00001535 // Schedule the source copy / remat inserted to form two-address
1536 // instruction. FIXME: Does it matter the distance map may not be
1537 // accurate after it's scheduled?
1538 TII->scheduleTwoAddrSource(prior(mi), mi, *TRI);
1539 }
Bob Wilson43449792009-08-31 21:54:55 +00001540
David Greeneeb00b182010-01-05 01:24:21 +00001541 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
Jakob Stoklund Olesen351c8812012-06-25 03:27:12 +00001542 }
Bill Wendling637980e2008-05-10 00:12:52 +00001543
Jakob Stoklund Olesen351c8812012-06-25 03:27:12 +00001544 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1545 if (mi->isInsertSubreg()) {
1546 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1547 // To %reg:subidx = COPY %subreg
1548 unsigned SubIdx = mi->getOperand(3).getImm();
1549 mi->RemoveOperand(3);
1550 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1551 mi->getOperand(0).setSubReg(SubIdx);
1552 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1553 mi->RemoveOperand(1);
1554 mi->setDesc(TII->get(TargetOpcode::COPY));
1555 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
Jakob Stoklund Olesened2185e2010-07-06 23:26:25 +00001556 }
1557
Bob Wilsoncc80df92009-09-03 20:58:42 +00001558 // Clear TiedOperands here instead of at the top of the loop
1559 // since most instructions do not have tied operands.
1560 TiedOperands.clear();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001561 mi = nmi;
Misha Brukman75fa4e42004-07-22 15:26:23 +00001562 }
1563 }
1564
Evan Cheng601ca4b2008-06-25 01:16:38 +00001565 // Some remat'ed instructions are dead.
Jakob Stoklund Olesen00f93fc2011-01-09 03:45:44 +00001566 for (int i = ReMatRegs.find_first(); i != -1; i = ReMatRegs.find_next(i)) {
1567 unsigned VReg = TargetRegisterInfo::index2VirtReg(i);
Evan Chengf1250ee2010-03-23 20:36:12 +00001568 if (MRI->use_nodbg_empty(VReg)) {
Evan Cheng601ca4b2008-06-25 01:16:38 +00001569 MachineInstr *DefMI = MRI->getVRegDef(VReg);
1570 DefMI->eraseFromParent();
Bill Wendlinga16157a2008-05-26 05:49:49 +00001571 }
Bill Wendling48f7f232008-05-26 05:18:34 +00001572 }
1573
Evan Cheng3d720fb2010-05-05 18:45:40 +00001574 // Eliminate REG_SEQUENCE instructions. Their whole purpose was to preseve
1575 // SSA form. It's now safe to de-SSA.
1576 MadeChange |= EliminateRegSequences();
1577
Misha Brukman75fa4e42004-07-22 15:26:23 +00001578 return MadeChange;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001579}
Evan Cheng3d720fb2010-05-05 18:45:40 +00001580
1581static void UpdateRegSequenceSrcs(unsigned SrcReg,
Evan Cheng53c779b2010-05-17 20:57:12 +00001582 unsigned DstReg, unsigned SubIdx,
Jakob Stoklund Olesen5a0d4fc2010-05-29 00:14:14 +00001583 MachineRegisterInfo *MRI,
1584 const TargetRegisterInfo &TRI) {
Evan Cheng3d720fb2010-05-05 18:45:40 +00001585 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg),
Evan Cheng3ae56bc2010-05-12 01:27:49 +00001586 RE = MRI->reg_end(); RI != RE; ) {
Evan Cheng3d720fb2010-05-05 18:45:40 +00001587 MachineOperand &MO = RI.getOperand();
1588 ++RI;
Jakob Stoklund Olesen5a0d4fc2010-05-29 00:14:14 +00001589 MO.substVirtReg(DstReg, SubIdx, TRI);
Evan Cheng53c779b2010-05-17 20:57:12 +00001590 }
1591}
1592
Jakob Stoklund Olesend36f5af2012-01-24 23:28:42 +00001593// Find the first def of Reg, assuming they are all in the same basic block.
1594static MachineInstr *findFirstDef(unsigned Reg, MachineRegisterInfo *MRI) {
1595 SmallPtrSet<MachineInstr*, 8> Defs;
1596 MachineInstr *First = 0;
1597 for (MachineRegisterInfo::def_iterator RI = MRI->def_begin(Reg);
1598 MachineInstr *MI = RI.skipInstruction(); Defs.insert(MI))
1599 First = MI;
1600 if (!First)
1601 return 0;
1602
1603 MachineBasicBlock *MBB = First->getParent();
1604 MachineBasicBlock::iterator A = First, B = First;
1605 bool Moving;
1606 do {
1607 Moving = false;
1608 if (A != MBB->begin()) {
1609 Moving = true;
1610 --A;
1611 if (Defs.erase(A)) First = A;
1612 }
1613 if (B != MBB->end()) {
1614 Defs.erase(B);
1615 ++B;
1616 Moving = true;
1617 }
1618 } while (Moving && !Defs.empty());
1619 assert(Defs.empty() && "Instructions outside basic block!");
1620 return First;
1621}
1622
Evan Cheng53c779b2010-05-17 20:57:12 +00001623/// CoalesceExtSubRegs - If a number of sources of the REG_SEQUENCE are
1624/// EXTRACT_SUBREG from the same register and to the same virtual register
1625/// with different sub-register indices, attempt to combine the
1626/// EXTRACT_SUBREGs and pre-coalesce them. e.g.
1627/// %reg1026<def> = VLDMQ %reg1025<kill>, 260, pred:14, pred:%reg0
1628/// %reg1029:6<def> = EXTRACT_SUBREG %reg1026, 6
1629/// %reg1029:5<def> = EXTRACT_SUBREG %reg1026<kill>, 5
1630/// Since D subregs 5, 6 can combine to a Q register, we can coalesce
1631/// reg1026 to reg1029.
1632void
1633TwoAddressInstructionPass::CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs,
1634 unsigned DstReg) {
1635 SmallSet<unsigned, 4> Seen;
1636 for (unsigned i = 0, e = Srcs.size(); i != e; ++i) {
1637 unsigned SrcReg = Srcs[i];
1638 if (!Seen.insert(SrcReg))
1639 continue;
1640
Bob Wilson26bf8f92010-06-03 23:53:58 +00001641 // Check that the instructions are all in the same basic block.
Manman Ren5f917cd2012-07-02 18:55:36 +00001642 MachineInstr *SrcDefMI = MRI->getUniqueVRegDef(SrcReg);
1643 MachineInstr *DstDefMI = MRI->getUniqueVRegDef(DstReg);
1644 if (!SrcDefMI || !DstDefMI ||
1645 SrcDefMI->getParent() != DstDefMI->getParent())
Bob Wilson26bf8f92010-06-03 23:53:58 +00001646 continue;
1647
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +00001648 // If there are no other uses than copies which feed into
Evan Cheng53c779b2010-05-17 20:57:12 +00001649 // the reg_sequence, then we might be able to coalesce them.
1650 bool CanCoalesce = true;
Bob Wilson4ffd22d2010-06-15 17:27:54 +00001651 SmallVector<unsigned, 4> SrcSubIndices, DstSubIndices;
Evan Cheng53c779b2010-05-17 20:57:12 +00001652 for (MachineRegisterInfo::use_nodbg_iterator
1653 UI = MRI->use_nodbg_begin(SrcReg),
1654 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
1655 MachineInstr *UseMI = &*UI;
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +00001656 if (!UseMI->isCopy() || UseMI->getOperand(0).getReg() != DstReg) {
Evan Cheng53c779b2010-05-17 20:57:12 +00001657 CanCoalesce = false;
1658 break;
1659 }
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +00001660 SrcSubIndices.push_back(UseMI->getOperand(1).getSubReg());
Bob Wilson4ffd22d2010-06-15 17:27:54 +00001661 DstSubIndices.push_back(UseMI->getOperand(0).getSubReg());
Evan Cheng53c779b2010-05-17 20:57:12 +00001662 }
1663
Bob Wilson4ffd22d2010-06-15 17:27:54 +00001664 if (!CanCoalesce || SrcSubIndices.size() < 2)
Evan Cheng53c779b2010-05-17 20:57:12 +00001665 continue;
1666
Bob Wilson4ffd22d2010-06-15 17:27:54 +00001667 // Check that the source subregisters can be combined.
1668 std::sort(SrcSubIndices.begin(), SrcSubIndices.end());
Bob Wilson852a7e32010-06-15 05:56:31 +00001669 unsigned NewSrcSubIdx = 0;
Bob Wilson4ffd22d2010-06-15 17:27:54 +00001670 if (!TRI->canCombineSubRegIndices(MRI->getRegClass(SrcReg), SrcSubIndices,
Bob Wilson852a7e32010-06-15 05:56:31 +00001671 NewSrcSubIdx))
Bob Wilson26bf8f92010-06-03 23:53:58 +00001672 continue;
1673
Bob Wilson4ffd22d2010-06-15 17:27:54 +00001674 // Check that the destination subregisters can also be combined.
1675 std::sort(DstSubIndices.begin(), DstSubIndices.end());
1676 unsigned NewDstSubIdx = 0;
1677 if (!TRI->canCombineSubRegIndices(MRI->getRegClass(DstReg), DstSubIndices,
1678 NewDstSubIdx))
1679 continue;
1680
1681 // If neither source nor destination can be combined to the full register,
1682 // just give up. This could be improved if it ever matters.
1683 if (NewSrcSubIdx != 0 && NewDstSubIdx != 0)
1684 continue;
1685
Bob Wilson852a7e32010-06-15 05:56:31 +00001686 // Now that we know that all the uses are extract_subregs and that those
1687 // subregs can somehow be combined, scan all the extract_subregs again to
1688 // make sure the subregs are in the right order and can be composed.
Bob Wilson852a7e32010-06-15 05:56:31 +00001689 MachineInstr *SomeMI = 0;
1690 CanCoalesce = true;
1691 for (MachineRegisterInfo::use_nodbg_iterator
1692 UI = MRI->use_nodbg_begin(SrcReg),
1693 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
1694 MachineInstr *UseMI = &*UI;
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +00001695 assert(UseMI->isCopy());
Bob Wilson852a7e32010-06-15 05:56:31 +00001696 unsigned DstSubIdx = UseMI->getOperand(0).getSubReg();
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +00001697 unsigned SrcSubIdx = UseMI->getOperand(1).getSubReg();
Bob Wilson852a7e32010-06-15 05:56:31 +00001698 assert(DstSubIdx != 0 && "missing subreg from RegSequence elimination");
Bob Wilson4ffd22d2010-06-15 17:27:54 +00001699 if ((NewDstSubIdx == 0 &&
1700 TRI->composeSubRegIndices(NewSrcSubIdx, DstSubIdx) != SrcSubIdx) ||
1701 (NewSrcSubIdx == 0 &&
1702 TRI->composeSubRegIndices(NewDstSubIdx, SrcSubIdx) != DstSubIdx)) {
Bob Wilson852a7e32010-06-15 05:56:31 +00001703 CanCoalesce = false;
1704 break;
Evan Cheng53c779b2010-05-17 20:57:12 +00001705 }
Jakob Stoklund Olesendefe12d2012-01-24 04:44:01 +00001706 // Keep track of one of the uses. Preferably the first one which has a
1707 // <def,undef> flag.
1708 if (!SomeMI || UseMI->getOperand(0).isUndef())
1709 SomeMI = UseMI;
Bob Wilson852a7e32010-06-15 05:56:31 +00001710 }
1711 if (!CanCoalesce)
1712 continue;
1713
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +00001714 // Insert a copy to replace the original.
Jakob Stoklund Olesen5c00e072010-07-08 16:40:15 +00001715 MachineInstr *CopyMI = BuildMI(*SomeMI->getParent(), SomeMI,
1716 SomeMI->getDebugLoc(),
1717 TII->get(TargetOpcode::COPY))
Jakob Stoklund Olesendefe12d2012-01-24 04:44:01 +00001718 .addReg(DstReg, RegState::Define |
1719 getUndefRegState(SomeMI->getOperand(0).isUndef()),
1720 NewDstSubIdx)
Jakob Stoklund Olesen5c00e072010-07-08 16:40:15 +00001721 .addReg(SrcReg, 0, NewSrcSubIdx);
Bob Wilson852a7e32010-06-15 05:56:31 +00001722
1723 // Remove all the old extract instructions.
1724 for (MachineRegisterInfo::use_nodbg_iterator
1725 UI = MRI->use_nodbg_begin(SrcReg),
1726 UE = MRI->use_nodbg_end(); UI != UE; ) {
1727 MachineInstr *UseMI = &*UI;
1728 ++UI;
1729 if (UseMI == CopyMI)
1730 continue;
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +00001731 assert(UseMI->isCopy());
Bob Wilson852a7e32010-06-15 05:56:31 +00001732 // Move any kills to the new copy or extract instruction.
1733 if (UseMI->getOperand(1).isKill()) {
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +00001734 CopyMI->getOperand(1).setIsKill();
Bob Wilson852a7e32010-06-15 05:56:31 +00001735 if (LV)
1736 // Update live variables
1737 LV->replaceKillInstruction(SrcReg, UseMI, &*CopyMI);
1738 }
1739 UseMI->eraseFromParent();
1740 }
Evan Cheng3d720fb2010-05-05 18:45:40 +00001741 }
1742}
1743
Evan Chengc6dcce32010-05-17 23:24:12 +00001744static bool HasOtherRegSequenceUses(unsigned Reg, MachineInstr *RegSeq,
1745 MachineRegisterInfo *MRI) {
1746 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
1747 UE = MRI->use_end(); UI != UE; ++UI) {
1748 MachineInstr *UseMI = &*UI;
1749 if (UseMI != RegSeq && UseMI->isRegSequence())
1750 return true;
1751 }
1752 return false;
1753}
1754
Evan Cheng3d720fb2010-05-05 18:45:40 +00001755/// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
1756/// of the de-ssa process. This replaces sources of REG_SEQUENCE as
1757/// sub-register references of the register defined by REG_SEQUENCE. e.g.
1758///
1759/// %reg1029<def>, %reg1030<def> = VLD1q16 %reg1024<kill>, ...
1760/// %reg1031<def> = REG_SEQUENCE %reg1029<kill>, 5, %reg1030<kill>, 6
1761/// =>
1762/// %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
1763bool TwoAddressInstructionPass::EliminateRegSequences() {
1764 if (RegSequences.empty())
1765 return false;
1766
1767 for (unsigned i = 0, e = RegSequences.size(); i != e; ++i) {
1768 MachineInstr *MI = RegSequences[i];
1769 unsigned DstReg = MI->getOperand(0).getReg();
1770 if (MI->getOperand(0).getSubReg() ||
1771 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1772 !(MI->getNumOperands() & 1)) {
1773 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1774 llvm_unreachable(0);
1775 }
Evan Cheng0bcccac2010-05-11 00:04:31 +00001776
Evan Cheng44bfdd32010-05-17 22:09:49 +00001777 bool IsImpDef = true;
Evan Chengb990a2f2010-05-14 23:21:14 +00001778 SmallVector<unsigned, 4> RealSrcs;
Evan Cheng0bcccac2010-05-11 00:04:31 +00001779 SmallSet<unsigned, 4> Seen;
Evan Cheng3d720fb2010-05-05 18:45:40 +00001780 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
Jakob Stoklund Olesen351c8812012-06-25 03:27:12 +00001781 // Nothing needs to be inserted for <undef> operands.
1782 if (MI->getOperand(i).isUndef()) {
1783 MI->getOperand(i).setReg(0);
1784 continue;
1785 }
Evan Cheng3d720fb2010-05-05 18:45:40 +00001786 unsigned SrcReg = MI->getOperand(i).getReg();
Pete Cooperef74ca62012-04-04 21:03:25 +00001787 unsigned SrcSubIdx = MI->getOperand(i).getSubReg();
Bob Wilson495de3b2010-12-17 01:21:12 +00001788 unsigned SubIdx = MI->getOperand(i+1).getImm();
Pete Coopercd7f02b2012-01-18 04:16:16 +00001789 // DefMI of NULL means the value does not have a vreg in this block
1790 // i.e., its a physical register or a subreg.
1791 // In either case we force a copy to be generated.
1792 MachineInstr *DefMI = NULL;
1793 if (!MI->getOperand(i).getSubReg() &&
1794 !TargetRegisterInfo::isPhysicalRegister(SrcReg)) {
Manman Ren5f917cd2012-07-02 18:55:36 +00001795 DefMI = MRI->getUniqueVRegDef(SrcReg);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001796 }
Evan Cheng0bcccac2010-05-11 00:04:31 +00001797
Pete Coopercd7f02b2012-01-18 04:16:16 +00001798 if (DefMI && DefMI->isImplicitDef()) {
Evan Chengb990a2f2010-05-14 23:21:14 +00001799 DefMI->eraseFromParent();
1800 continue;
1801 }
Evan Cheng44bfdd32010-05-17 22:09:49 +00001802 IsImpDef = false;
Evan Chengb990a2f2010-05-14 23:21:14 +00001803
Jakob Stoklund Olesen0bc25f42010-07-08 16:40:22 +00001804 // Remember COPY sources. These might be candidate for coalescing.
Pete Coopercd7f02b2012-01-18 04:16:16 +00001805 if (DefMI && DefMI->isCopy() && DefMI->getOperand(1).getSubReg())
Evan Chengb990a2f2010-05-14 23:21:14 +00001806 RealSrcs.push_back(DefMI->getOperand(1).getReg());
1807
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001808 bool isKill = MI->getOperand(i).isKill();
Pete Coopercd7f02b2012-01-18 04:16:16 +00001809 if (!DefMI || !Seen.insert(SrcReg) ||
1810 MI->getParent() != DefMI->getParent() ||
Bob Wilson495de3b2010-12-17 01:21:12 +00001811 !isKill || HasOtherRegSequenceUses(SrcReg, MI, MRI) ||
1812 !TRI->getMatchingSuperRegClass(MRI->getRegClass(DstReg),
1813 MRI->getRegClass(SrcReg), SubIdx)) {
Evan Cheng054dbb82010-05-13 00:00:35 +00001814 // REG_SEQUENCE cannot have duplicated operands, add a copy.
Jakob Stoklund Olesen34373522010-05-19 20:08:00 +00001815 // Also add an copy if the source is live-in the block. We don't want
Evan Cheng054dbb82010-05-13 00:00:35 +00001816 // to end up with a partial-redef of a livein, e.g.
1817 // BB0:
1818 // reg1051:10<def> =
1819 // ...
1820 // BB1:
1821 // ... = reg1051:10
1822 // BB2:
1823 // reg1051:9<def> =
1824 // LiveIntervalAnalysis won't like it.
Jakob Stoklund Olesen34373522010-05-19 20:08:00 +00001825 //
1826 // If the REG_SEQUENCE doesn't kill its source, keeping live variables
1827 // correctly up to date becomes very difficult. Insert a copy.
Jakob Stoklund Olesene4b9c4f2010-08-09 20:19:16 +00001828
1829 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1830 // might insert a COPY that uses SrcReg after is was killed.
1831 if (isKill)
1832 for (unsigned j = i + 2; j < e; j += 2)
1833 if (MI->getOperand(j).getReg() == SrcReg) {
1834 MI->getOperand(j).setIsKill();
1835 isKill = false;
1836 break;
1837 }
1838
Evan Cheng054dbb82010-05-13 00:00:35 +00001839 MachineBasicBlock::iterator InsertLoc = MI;
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001840 MachineInstr *CopyMI = BuildMI(*MI->getParent(), InsertLoc,
1841 MI->getDebugLoc(), TII->get(TargetOpcode::COPY))
Bob Wilson495de3b2010-12-17 01:21:12 +00001842 .addReg(DstReg, RegState::Define, SubIdx)
Pete Cooperef74ca62012-04-04 21:03:25 +00001843 .addReg(SrcReg, getKillRegState(isKill), SrcSubIdx);
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001844 MI->getOperand(i).setReg(0);
Pete Coopercd7f02b2012-01-18 04:16:16 +00001845 if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001846 LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1847 DEBUG(dbgs() << "Inserted: " << *CopyMI);
Evan Cheng0bcccac2010-05-11 00:04:31 +00001848 }
1849 }
1850
1851 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1852 unsigned SrcReg = MI->getOperand(i).getReg();
Jakob Stoklund Olesen1e1098c2010-07-10 22:42:59 +00001853 if (!SrcReg) continue;
Evan Cheng53c779b2010-05-17 20:57:12 +00001854 unsigned SubIdx = MI->getOperand(i+1).getImm();
Jakob Stoklund Olesen5a0d4fc2010-05-29 00:14:14 +00001855 UpdateRegSequenceSrcs(SrcReg, DstReg, SubIdx, MRI, *TRI);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001856 }
1857
Jakob Stoklund Olesend36f5af2012-01-24 23:28:42 +00001858 // Set <def,undef> flags on the first DstReg def in the basic block.
1859 // It marks the beginning of the live range. All the other defs are
1860 // read-modify-write.
1861 if (MachineInstr *Def = findFirstDef(DstReg, MRI)) {
1862 for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
1863 MachineOperand &MO = Def->getOperand(i);
1864 if (MO.isReg() && MO.isDef() && MO.getReg() == DstReg)
1865 MO.setIsUndef();
1866 }
1867 // Make sure there is a full non-subreg imp-def operand on the
1868 // instruction. This shouldn't be necessary, but it seems that at least
1869 // RAFast requires it.
1870 Def->addRegisterDefined(DstReg, TRI);
1871 DEBUG(dbgs() << "First def: " << *Def);
1872 }
1873
Evan Cheng44bfdd32010-05-17 22:09:49 +00001874 if (IsImpDef) {
1875 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1876 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1877 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
Andrew Trick8247e0d2012-02-03 05:12:30 +00001878 MI->RemoveOperand(j);
Evan Cheng44bfdd32010-05-17 22:09:49 +00001879 } else {
1880 DEBUG(dbgs() << "Eliminated: " << *MI);
1881 MI->eraseFromParent();
1882 }
Evan Chengb990a2f2010-05-14 23:21:14 +00001883
Jakob Stoklund Olesenfe181f42010-06-18 23:10:20 +00001884 // Try coalescing some EXTRACT_SUBREG instructions. This can create
1885 // INSERT_SUBREG instructions that must have <undef> flags added by
1886 // LiveIntervalAnalysis, so only run it when LiveVariables is available.
1887 if (LV)
1888 CoalesceExtSubRegs(RealSrcs, DstReg);
Evan Cheng3d720fb2010-05-05 18:45:40 +00001889 }
1890
Evan Chengfc6e6a92010-05-10 21:24:55 +00001891 RegSequences.clear();
Evan Cheng3d720fb2010-05-05 18:45:40 +00001892 return true;
1893}