blob: b18d1ef3b5b488ec2856952fb807f7ecce1bcaa3 [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"
Chris Lattner84bc5422007-12-31 04:13:23 +000036#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000037#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000038#include "llvm/Target/TargetInstrInfo.h"
39#include "llvm/Target/TargetMachine.h"
Owen Anderson95dad832008-10-07 20:22:28 +000040#include "llvm/Target/TargetOptions.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000041#include "llvm/Support/Compiler.h"
Evan Cheng875357d2008-03-13 06:37:55 +000042#include "llvm/Support/Debug.h"
Evan Cheng7543e582008-06-18 07:49:14 +000043#include "llvm/ADT/BitVector.h"
44#include "llvm/ADT/DenseMap.h"
Dan Gohmand68a0762009-01-05 17:59:02 +000045#include "llvm/ADT/SmallSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000046#include "llvm/ADT/Statistic.h"
47#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000048using namespace llvm;
49
Chris Lattnercd3245a2006-12-19 22:41:21 +000050STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
51STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
Evan Chengd498c8f2009-01-25 03:53:59 +000052STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
Chris Lattnercd3245a2006-12-19 22:41:21 +000053STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
Evan Cheng875357d2008-03-13 06:37:55 +000054STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
Evan Cheng7543e582008-06-18 07:49:14 +000055STATISTIC(NumReMats, "Number of instructions re-materialized");
Evan Cheng28c7ce32009-02-21 03:14:25 +000056STATISTIC(NumDeletes, "Number of dead instructions deleted");
Evan Cheng875357d2008-03-13 06:37:55 +000057
58namespace {
Bill Wendling637980e2008-05-10 00:12:52 +000059 class VISIBILITY_HIDDEN TwoAddressInstructionPass
60 : public MachineFunctionPass {
Evan Cheng875357d2008-03-13 06:37:55 +000061 const TargetInstrInfo *TII;
62 const TargetRegisterInfo *TRI;
63 MachineRegisterInfo *MRI;
64 LiveVariables *LV;
65
Evan Cheng870b8072009-03-01 02:03:43 +000066 // DistanceMap - Keep track the distance of a MI from the start of the
67 // current basic block.
68 DenseMap<MachineInstr*, unsigned> DistanceMap;
69
70 // SrcRegMap - A map from virtual registers to physical registers which
71 // are likely targets to be coalesced to due to copies from physical
72 // registers to virtual registers. e.g. v1024 = move r0.
73 DenseMap<unsigned, unsigned> SrcRegMap;
74
75 // DstRegMap - A map from virtual registers to physical registers which
76 // are likely targets to be coalesced to due to copies to physical
77 // registers from virtual registers. e.g. r1 = move v1024.
78 DenseMap<unsigned, unsigned> DstRegMap;
79
Bill Wendling637980e2008-05-10 00:12:52 +000080 bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
81 unsigned Reg,
82 MachineBasicBlock::iterator OldPos);
Evan Cheng7543e582008-06-18 07:49:14 +000083
Evan Cheng7543e582008-06-18 07:49:14 +000084 bool isProfitableToReMat(unsigned Reg, const TargetRegisterClass *RC,
Evan Cheng601ca4b2008-06-25 01:16:38 +000085 MachineInstr *MI, MachineInstr *DefMI,
Evan Cheng870b8072009-03-01 02:03:43 +000086 MachineBasicBlock *MBB, unsigned Loc);
Evan Cheng81913712009-01-23 23:27:33 +000087
Evan Chengd498c8f2009-01-25 03:53:59 +000088 bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
Evan Chengd498c8f2009-01-25 03:53:59 +000089 unsigned &LastDef);
90
Evan Chenge9ccb3a2009-04-28 02:12:36 +000091 MachineInstr *FindLastUseInMBB(unsigned Reg, MachineBasicBlock *MBB,
92 unsigned Dist);
93
Evan Chengd498c8f2009-01-25 03:53:59 +000094 bool isProfitableToCommute(unsigned regB, unsigned regC,
95 MachineInstr *MI, MachineBasicBlock *MBB,
Evan Cheng870b8072009-03-01 02:03:43 +000096 unsigned Dist);
Evan Chengd498c8f2009-01-25 03:53:59 +000097
Evan Cheng81913712009-01-23 23:27:33 +000098 bool CommuteInstruction(MachineBasicBlock::iterator &mi,
99 MachineFunction::iterator &mbbi,
Evan Cheng870b8072009-03-01 02:03:43 +0000100 unsigned RegB, unsigned RegC, unsigned Dist);
101
Evan Chenge6f350d2009-03-30 21:34:07 +0000102 bool isProfitableToConv3Addr(unsigned RegA);
103
104 bool ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
105 MachineBasicBlock::iterator &nmi,
106 MachineFunction::iterator &mbbi,
107 unsigned RegB, unsigned Dist);
108
Evan Cheng870b8072009-03-01 02:03:43 +0000109 void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
110 SmallPtrSet<MachineInstr*, 8> &Processed);
Evan Cheng875357d2008-03-13 06:37:55 +0000111 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000112 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +0000113 TwoAddressInstructionPass() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000114
Bill Wendling637980e2008-05-10 00:12:52 +0000115 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +0000116 AU.setPreservesCFG();
Bill Wendling637980e2008-05-10 00:12:52 +0000117 AU.addPreserved<LiveVariables>();
118 AU.addPreservedID(MachineLoopInfoID);
119 AU.addPreservedID(MachineDominatorsID);
Owen Anderson95dad832008-10-07 20:22:28 +0000120 if (StrongPHIElim)
121 AU.addPreservedID(StrongPHIEliminationID);
122 else
123 AU.addPreservedID(PHIEliminationID);
Bill Wendling637980e2008-05-10 00:12:52 +0000124 MachineFunctionPass::getAnalysisUsage(AU);
125 }
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000126
Bill Wendling637980e2008-05-10 00:12:52 +0000127 /// runOnMachineFunction - Pass entry point.
Misha Brukman75fa4e42004-07-22 15:26:23 +0000128 bool runOnMachineFunction(MachineFunction&);
129 };
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000130}
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000131
Dan Gohman844731a2008-05-13 00:00:25 +0000132char TwoAddressInstructionPass::ID = 0;
133static RegisterPass<TwoAddressInstructionPass>
134X("twoaddressinstruction", "Two-Address instruction pass");
135
Dan Gohman6ddba2b2008-05-13 02:05:11 +0000136const PassInfo *const llvm::TwoAddressInstructionPassID = &X;
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000137
Evan Cheng875357d2008-03-13 06:37:55 +0000138/// Sink3AddrInstruction - A two-address instruction has been converted to a
139/// three-address instruction to avoid clobbering a register. Try to sink it
Bill Wendling637980e2008-05-10 00:12:52 +0000140/// past the instruction that would kill the above mentioned register to reduce
141/// register pressure.
Evan Cheng875357d2008-03-13 06:37:55 +0000142bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
143 MachineInstr *MI, unsigned SavedReg,
144 MachineBasicBlock::iterator OldPos) {
145 // Check if it's safe to move this instruction.
146 bool SeenStore = true; // Be conservative.
147 if (!MI->isSafeToMove(TII, SeenStore))
148 return false;
149
150 unsigned DefReg = 0;
151 SmallSet<unsigned, 4> UseRegs;
Bill Wendling637980e2008-05-10 00:12:52 +0000152
Evan Cheng875357d2008-03-13 06:37:55 +0000153 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
154 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000155 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000156 continue;
157 unsigned MOReg = MO.getReg();
158 if (!MOReg)
159 continue;
160 if (MO.isUse() && MOReg != SavedReg)
161 UseRegs.insert(MO.getReg());
162 if (!MO.isDef())
163 continue;
164 if (MO.isImplicit())
165 // Don't try to move it if it implicitly defines a register.
166 return false;
167 if (DefReg)
168 // For now, don't move any instructions that define multiple registers.
169 return false;
170 DefReg = MO.getReg();
171 }
172
173 // Find the instruction that kills SavedReg.
174 MachineInstr *KillMI = NULL;
175 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SavedReg),
176 UE = MRI->use_end(); UI != UE; ++UI) {
177 MachineOperand &UseMO = UI.getOperand();
178 if (!UseMO.isKill())
179 continue;
180 KillMI = UseMO.getParent();
181 break;
182 }
Bill Wendling637980e2008-05-10 00:12:52 +0000183
Dan Gohman97121ba2009-04-08 00:15:30 +0000184 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI)
Evan Cheng875357d2008-03-13 06:37:55 +0000185 return false;
186
Bill Wendling637980e2008-05-10 00:12:52 +0000187 // If any of the definitions are used by another instruction between the
188 // position and the kill use, then it's not safe to sink it.
189 //
190 // FIXME: This can be sped up if there is an easy way to query whether an
Evan Cheng7543e582008-06-18 07:49:14 +0000191 // instruction is before or after another instruction. Then we can use
Bill Wendling637980e2008-05-10 00:12:52 +0000192 // MachineRegisterInfo def / use instead.
Evan Cheng875357d2008-03-13 06:37:55 +0000193 MachineOperand *KillMO = NULL;
194 MachineBasicBlock::iterator KillPos = KillMI;
195 ++KillPos;
Bill Wendling637980e2008-05-10 00:12:52 +0000196
Evan Cheng7543e582008-06-18 07:49:14 +0000197 unsigned NumVisited = 0;
Evan Cheng875357d2008-03-13 06:37:55 +0000198 for (MachineBasicBlock::iterator I = next(OldPos); I != KillPos; ++I) {
199 MachineInstr *OtherMI = I;
Evan Cheng7543e582008-06-18 07:49:14 +0000200 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
201 return false;
202 ++NumVisited;
Evan Cheng875357d2008-03-13 06:37:55 +0000203 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
204 MachineOperand &MO = OtherMI->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 (DefReg == MOReg)
211 return false;
Bill Wendling637980e2008-05-10 00:12:52 +0000212
Evan Cheng875357d2008-03-13 06:37:55 +0000213 if (MO.isKill()) {
214 if (OtherMI == KillMI && MOReg == SavedReg)
Evan Cheng7543e582008-06-18 07:49:14 +0000215 // Save the operand that kills the register. We want to unset the kill
216 // marker if we can sink MI past it.
Evan Cheng875357d2008-03-13 06:37:55 +0000217 KillMO = &MO;
218 else if (UseRegs.count(MOReg))
219 // One of the uses is killed before the destination.
220 return false;
221 }
222 }
223 }
224
Evan Cheng875357d2008-03-13 06:37:55 +0000225 // Update kill and LV information.
226 KillMO->setIsKill(false);
227 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
228 KillMO->setIsKill(true);
Owen Anderson802af112008-07-02 21:28:58 +0000229
Evan Cheng9f1c8312008-07-03 09:09:37 +0000230 if (LV)
231 LV->replaceKillInstruction(SavedReg, KillMI, MI);
Evan Cheng875357d2008-03-13 06:37:55 +0000232
233 // Move instruction to its destination.
234 MBB->remove(MI);
235 MBB->insert(KillPos, MI);
236
237 ++Num3AddrSunk;
238 return true;
239}
240
Evan Cheng7543e582008-06-18 07:49:14 +0000241/// isTwoAddrUse - Return true if the specified MI is using the specified
242/// register as a two-address operand.
243static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
244 const TargetInstrDesc &TID = UseMI->getDesc();
245 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
246 MachineOperand &MO = UseMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000247 if (MO.isReg() && MO.getReg() == Reg &&
Evan Chenga24752f2009-03-19 20:30:06 +0000248 (MO.isDef() || UseMI->isRegTiedToDefOperand(i)))
Evan Cheng7543e582008-06-18 07:49:14 +0000249 // Earlier use is a two-address one.
250 return true;
251 }
252 return false;
253}
254
255/// isProfitableToReMat - Return true if the heuristics determines it is likely
256/// to be profitable to re-materialize the definition of Reg rather than copy
257/// the register.
258bool
259TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
Evan Cheng870b8072009-03-01 02:03:43 +0000260 const TargetRegisterClass *RC,
261 MachineInstr *MI, MachineInstr *DefMI,
262 MachineBasicBlock *MBB, unsigned Loc) {
Evan Cheng7543e582008-06-18 07:49:14 +0000263 bool OtherUse = false;
264 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
265 UE = MRI->use_end(); UI != UE; ++UI) {
266 MachineOperand &UseMO = UI.getOperand();
Evan Cheng7543e582008-06-18 07:49:14 +0000267 MachineInstr *UseMI = UseMO.getParent();
Evan Cheng601ca4b2008-06-25 01:16:38 +0000268 MachineBasicBlock *UseMBB = UseMI->getParent();
269 if (UseMBB == MBB) {
270 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
271 if (DI != DistanceMap.end() && DI->second == Loc)
272 continue; // Current use.
273 OtherUse = true;
274 // There is at least one other use in the MBB that will clobber the
275 // register.
276 if (isTwoAddrUse(UseMI, Reg))
277 return true;
278 }
Evan Cheng7543e582008-06-18 07:49:14 +0000279 }
Evan Cheng601ca4b2008-06-25 01:16:38 +0000280
281 // If other uses in MBB are not two-address uses, then don't remat.
282 if (OtherUse)
283 return false;
284
285 // No other uses in the same block, remat if it's defined in the same
286 // block so it does not unnecessarily extend the live range.
287 return MBB == DefMI->getParent();
Evan Cheng7543e582008-06-18 07:49:14 +0000288}
289
Evan Chengd498c8f2009-01-25 03:53:59 +0000290/// NoUseAfterLastDef - Return true if there are no intervening uses between the
291/// last instruction in the MBB that defines the specified register and the
292/// two-address instruction which is being processed. It also returns the last
293/// def location by reference
294bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
Evan Cheng870b8072009-03-01 02:03:43 +0000295 MachineBasicBlock *MBB, unsigned Dist,
296 unsigned &LastDef) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000297 LastDef = 0;
298 unsigned LastUse = Dist;
299 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
300 E = MRI->reg_end(); I != E; ++I) {
301 MachineOperand &MO = I.getOperand();
302 MachineInstr *MI = MO.getParent();
303 if (MI->getParent() != MBB)
304 continue;
305 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
306 if (DI == DistanceMap.end())
307 continue;
308 if (MO.isUse() && DI->second < LastUse)
309 LastUse = DI->second;
310 if (MO.isDef() && DI->second > LastDef)
311 LastDef = DI->second;
312 }
313
314 return !(LastUse > LastDef && LastUse < Dist);
315}
316
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000317MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg,
318 MachineBasicBlock *MBB,
319 unsigned Dist) {
Lang Hamesa7c9dea2009-05-14 04:26:30 +0000320 unsigned LastUseDist = 0;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000321 MachineInstr *LastUse = 0;
322 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
323 E = MRI->reg_end(); I != E; ++I) {
324 MachineOperand &MO = I.getOperand();
325 MachineInstr *MI = MO.getParent();
326 if (MI->getParent() != MBB)
327 continue;
328 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
329 if (DI == DistanceMap.end())
330 continue;
Lang Hamesa7c9dea2009-05-14 04:26:30 +0000331 if (DI->second >= Dist)
332 continue;
333
334 if (MO.isUse() && DI->second > LastUseDist) {
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000335 LastUse = DI->first;
336 LastUseDist = DI->second;
337 }
338 }
339 return LastUse;
340}
341
Evan Cheng870b8072009-03-01 02:03:43 +0000342/// isCopyToReg - Return true if the specified MI is a copy instruction or
343/// a extract_subreg instruction. It also returns the source and destination
344/// registers and whether they are physical registers by reference.
345static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
346 unsigned &SrcReg, unsigned &DstReg,
347 bool &IsSrcPhys, bool &IsDstPhys) {
348 SrcReg = 0;
349 DstReg = 0;
350 unsigned SrcSubIdx, DstSubIdx;
351 if (!TII->isMoveInstr(MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
352 if (MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
353 DstReg = MI.getOperand(0).getReg();
354 SrcReg = MI.getOperand(1).getReg();
355 } else if (MI.getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
356 DstReg = MI.getOperand(0).getReg();
357 SrcReg = MI.getOperand(2).getReg();
Dan Gohman97121ba2009-04-08 00:15:30 +0000358 } else if (MI.getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
359 DstReg = MI.getOperand(0).getReg();
360 SrcReg = MI.getOperand(2).getReg();
Evan Cheng870b8072009-03-01 02:03:43 +0000361 }
362 }
363
364 if (DstReg) {
365 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
366 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
367 return true;
368 }
369 return false;
370}
371
Dan Gohman97121ba2009-04-08 00:15:30 +0000372/// isKilled - Test if the given register value, which is used by the given
373/// instruction, is killed by the given instruction. This looks through
374/// coalescable copies to see if the original value is potentially not killed.
375///
376/// For example, in this code:
377///
378/// %reg1034 = copy %reg1024
379/// %reg1035 = copy %reg1025<kill>
380/// %reg1036 = add %reg1034<kill>, %reg1035<kill>
381///
382/// %reg1034 is not considered to be killed, since it is copied from a
383/// register which is not killed. Treating it as not killed lets the
384/// normal heuristics commute the (two-address) add, which lets
385/// coalescing eliminate the extra copy.
386///
387static bool isKilled(MachineInstr &MI, unsigned Reg,
388 const MachineRegisterInfo *MRI,
389 const TargetInstrInfo *TII) {
390 MachineInstr *DefMI = &MI;
391 for (;;) {
392 if (!DefMI->killsRegister(Reg))
393 return false;
394 if (TargetRegisterInfo::isPhysicalRegister(Reg))
395 return true;
396 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
397 // If there are multiple defs, we can't do a simple analysis, so just
398 // go with what the kill flag says.
399 if (next(Begin) != MRI->def_end())
400 return true;
401 DefMI = &*Begin;
402 bool IsSrcPhys, IsDstPhys;
403 unsigned SrcReg, DstReg;
404 // If the def is something other than a copy, then it isn't going to
405 // be coalesced, so follow the kill flag.
406 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
407 return true;
408 Reg = SrcReg;
409 }
410}
411
Evan Cheng870b8072009-03-01 02:03:43 +0000412/// isTwoAddrUse - Return true if the specified MI uses the specified register
413/// as a two-address use. If so, return the destination register by reference.
414static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
415 const TargetInstrDesc &TID = MI.getDesc();
Evan Chenge6f350d2009-03-30 21:34:07 +0000416 unsigned NumOps = (MI.getOpcode() == TargetInstrInfo::INLINEASM)
417 ? MI.getNumOperands() : TID.getNumOperands();
418 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng870b8072009-03-01 02:03:43 +0000419 const MachineOperand &MO = MI.getOperand(i);
420 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
421 continue;
Evan Chenga24752f2009-03-19 20:30:06 +0000422 unsigned ti;
423 if (MI.isRegTiedToDefOperand(i, &ti)) {
Evan Cheng870b8072009-03-01 02:03:43 +0000424 DstReg = MI.getOperand(ti).getReg();
425 return true;
426 }
427 }
428 return false;
429}
430
431/// findOnlyInterestingUse - Given a register, if has a single in-basic block
432/// use, return the use instruction if it's a copy or a two-address use.
433static
434MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
435 MachineRegisterInfo *MRI,
436 const TargetInstrInfo *TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000437 bool &IsCopy,
Evan Cheng870b8072009-03-01 02:03:43 +0000438 unsigned &DstReg, bool &IsDstPhys) {
439 MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg);
440 if (UI == MRI->use_end())
441 return 0;
442 MachineInstr &UseMI = *UI;
443 if (++UI != MRI->use_end())
444 // More than one use.
445 return 0;
446 if (UseMI.getParent() != MBB)
447 return 0;
448 unsigned SrcReg;
449 bool IsSrcPhys;
Evan Cheng87d696a2009-04-14 00:32:25 +0000450 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
451 IsCopy = true;
Evan Cheng870b8072009-03-01 02:03:43 +0000452 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000453 }
Evan Cheng870b8072009-03-01 02:03:43 +0000454 IsDstPhys = false;
Evan Cheng87d696a2009-04-14 00:32:25 +0000455 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
456 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng870b8072009-03-01 02:03:43 +0000457 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000458 }
Evan Cheng870b8072009-03-01 02:03:43 +0000459 return 0;
460}
461
462/// getMappedReg - Return the physical register the specified virtual register
463/// might be mapped to.
464static unsigned
465getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
466 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
467 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
468 if (SI == RegMap.end())
469 return 0;
470 Reg = SI->second;
471 }
472 if (TargetRegisterInfo::isPhysicalRegister(Reg))
473 return Reg;
474 return 0;
475}
476
477/// regsAreCompatible - Return true if the two registers are equal or aliased.
478///
479static bool
480regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
481 if (RegA == RegB)
482 return true;
483 if (!RegA || !RegB)
484 return false;
485 return TRI->regsOverlap(RegA, RegB);
486}
487
488
Evan Chengd498c8f2009-01-25 03:53:59 +0000489/// isProfitableToReMat - Return true if it's potentially profitable to commute
490/// the two-address instruction that's being processed.
491bool
492TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC,
Evan Cheng870b8072009-03-01 02:03:43 +0000493 MachineInstr *MI, MachineBasicBlock *MBB,
494 unsigned Dist) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000495 // Determine if it's profitable to commute this two address instruction. In
496 // general, we want no uses between this instruction and the definition of
497 // the two-address register.
498 // e.g.
499 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
500 // %reg1029<def> = MOV8rr %reg1028
501 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
502 // insert => %reg1030<def> = MOV8rr %reg1028
503 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
504 // In this case, it might not be possible to coalesce the second MOV8rr
505 // instruction if the first one is coalesced. So it would be profitable to
506 // commute it:
507 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
508 // %reg1029<def> = MOV8rr %reg1028
509 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
510 // insert => %reg1030<def> = MOV8rr %reg1029
511 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
512
513 if (!MI->killsRegister(regC))
514 return false;
515
516 // Ok, we have something like:
517 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
518 // let's see if it's worth commuting it.
519
Evan Cheng870b8072009-03-01 02:03:43 +0000520 // Look for situations like this:
521 // %reg1024<def> = MOV r1
522 // %reg1025<def> = MOV r0
523 // %reg1026<def> = ADD %reg1024, %reg1025
524 // r0 = MOV %reg1026
525 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
526 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
527 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
528 unsigned ToRegB = getMappedReg(regB, DstRegMap);
529 unsigned ToRegC = getMappedReg(regC, DstRegMap);
530 if (!regsAreCompatible(FromRegB, ToRegB, TRI) &&
531 (regsAreCompatible(FromRegB, ToRegC, TRI) ||
532 regsAreCompatible(FromRegC, ToRegB, TRI)))
533 return true;
534
Evan Chengd498c8f2009-01-25 03:53:59 +0000535 // If there is a use of regC between its last def (could be livein) and this
536 // instruction, then bail.
537 unsigned LastDefC = 0;
Evan Cheng870b8072009-03-01 02:03:43 +0000538 if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
Evan Chengd498c8f2009-01-25 03:53:59 +0000539 return false;
540
541 // If there is a use of regB between its last def (could be livein) and this
542 // instruction, then go ahead and make this transformation.
543 unsigned LastDefB = 0;
Evan Cheng870b8072009-03-01 02:03:43 +0000544 if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
Evan Chengd498c8f2009-01-25 03:53:59 +0000545 return true;
546
547 // Since there are no intervening uses for both registers, then commute
548 // if the def of regC is closer. Its live interval is shorter.
549 return LastDefB && LastDefC && LastDefC > LastDefB;
550}
551
Evan Cheng81913712009-01-23 23:27:33 +0000552/// CommuteInstruction - Commute a two-address instruction and update the basic
553/// block, distance map, and live variables if needed. Return true if it is
554/// successful.
555bool
556TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
Evan Cheng870b8072009-03-01 02:03:43 +0000557 MachineFunction::iterator &mbbi,
558 unsigned RegB, unsigned RegC, unsigned Dist) {
Evan Cheng81913712009-01-23 23:27:33 +0000559 MachineInstr *MI = mi;
560 DOUT << "2addr: COMMUTING : " << *MI;
561 MachineInstr *NewMI = TII->commuteInstruction(MI);
562
563 if (NewMI == 0) {
564 DOUT << "2addr: COMMUTING FAILED!\n";
565 return false;
566 }
567
568 DOUT << "2addr: COMMUTED TO: " << *NewMI;
569 // If the instruction changed to commute it, update livevar.
570 if (NewMI != MI) {
571 if (LV)
572 // Update live variables
573 LV->replaceKillInstruction(RegC, MI, NewMI);
574
575 mbbi->insert(mi, NewMI); // Insert the new inst
576 mbbi->erase(mi); // Nuke the old inst.
577 mi = NewMI;
578 DistanceMap.insert(std::make_pair(NewMI, Dist));
579 }
Evan Cheng870b8072009-03-01 02:03:43 +0000580
581 // Update source register map.
582 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
583 if (FromRegC) {
584 unsigned RegA = MI->getOperand(0).getReg();
585 SrcRegMap[RegA] = FromRegC;
586 }
587
Evan Cheng81913712009-01-23 23:27:33 +0000588 return true;
589}
590
Evan Chenge6f350d2009-03-30 21:34:07 +0000591/// isProfitableToConv3Addr - Return true if it is profitable to convert the
592/// given 2-address instruction to a 3-address one.
593bool
594TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA) {
595 // Look for situations like this:
596 // %reg1024<def> = MOV r1
597 // %reg1025<def> = MOV r0
598 // %reg1026<def> = ADD %reg1024, %reg1025
599 // r2 = MOV %reg1026
600 // Turn ADD into a 3-address instruction to avoid a copy.
601 unsigned FromRegA = getMappedReg(RegA, SrcRegMap);
602 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
603 return (FromRegA && ToRegA && !regsAreCompatible(FromRegA, ToRegA, TRI));
604}
605
606/// ConvertInstTo3Addr - Convert the specified two-address instruction into a
607/// three address one. Return true if this transformation was successful.
608bool
609TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
610 MachineBasicBlock::iterator &nmi,
611 MachineFunction::iterator &mbbi,
612 unsigned RegB, unsigned Dist) {
613 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
614 if (NewMI) {
615 DOUT << "2addr: CONVERTING 2-ADDR: " << *mi;
616 DOUT << "2addr: TO 3-ADDR: " << *NewMI;
617 bool Sunk = false;
618
619 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
620 // FIXME: Temporary workaround. If the new instruction doesn't
621 // uses RegB, convertToThreeAddress must have created more
622 // then one instruction.
623 Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
624
625 mbbi->erase(mi); // Nuke the old inst.
626
627 if (!Sunk) {
628 DistanceMap.insert(std::make_pair(NewMI, Dist));
629 mi = NewMI;
630 nmi = next(mi);
631 }
632 return true;
633 }
634
635 return false;
636}
637
Evan Cheng870b8072009-03-01 02:03:43 +0000638/// ProcessCopy - If the specified instruction is not yet processed, process it
639/// if it's a copy. For a copy instruction, we find the physical registers the
640/// source and destination registers might be mapped to. These are kept in
641/// point-to maps used to determine future optimizations. e.g.
642/// v1024 = mov r0
643/// v1025 = mov r1
644/// v1026 = add v1024, v1025
645/// r1 = mov r1026
646/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
647/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
648/// potentially joined with r1 on the output side. It's worthwhile to commute
649/// 'add' to eliminate a copy.
650void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
651 MachineBasicBlock *MBB,
652 SmallPtrSet<MachineInstr*, 8> &Processed) {
653 if (Processed.count(MI))
654 return;
655
656 bool IsSrcPhys, IsDstPhys;
657 unsigned SrcReg, DstReg;
658 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
659 return;
660
661 if (IsDstPhys && !IsSrcPhys)
662 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
663 else if (!IsDstPhys && IsSrcPhys) {
Evan Cheng3005ed62009-04-13 20:04:24 +0000664 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
665 if (!isNew)
666 assert(SrcRegMap[DstReg] == SrcReg &&
667 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000668
669 SmallVector<unsigned, 4> VirtRegPairs;
Evan Cheng87d696a2009-04-14 00:32:25 +0000670 bool IsCopy = false;
Evan Cheng870b8072009-03-01 02:03:43 +0000671 unsigned NewReg = 0;
672 while (MachineInstr *UseMI = findOnlyInterestingUse(DstReg, MBB, MRI,TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000673 IsCopy, NewReg, IsDstPhys)) {
674 if (IsCopy) {
675 if (!Processed.insert(UseMI))
Evan Cheng870b8072009-03-01 02:03:43 +0000676 break;
677 }
678
679 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
680 if (DI != DistanceMap.end())
681 // Earlier in the same MBB.Reached via a back edge.
682 break;
683
684 if (IsDstPhys) {
685 VirtRegPairs.push_back(NewReg);
686 break;
687 }
688 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, DstReg)).second;
Evan Cheng3005ed62009-04-13 20:04:24 +0000689 if (!isNew)
Evan Cheng87d696a2009-04-14 00:32:25 +0000690 assert(SrcRegMap[NewReg] == DstReg &&
691 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000692 VirtRegPairs.push_back(NewReg);
693 DstReg = NewReg;
694 }
695
696 if (!VirtRegPairs.empty()) {
697 unsigned ToReg = VirtRegPairs.back();
698 VirtRegPairs.pop_back();
699 while (!VirtRegPairs.empty()) {
700 unsigned FromReg = VirtRegPairs.back();
701 VirtRegPairs.pop_back();
702 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
Evan Cheng3005ed62009-04-13 20:04:24 +0000703 if (!isNew)
704 assert(DstRegMap[FromReg] == ToReg &&
705 "Can't map to two dst physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000706 ToReg = FromReg;
707 }
708 }
709 }
710
711 Processed.insert(MI);
712}
713
Evan Cheng28c7ce32009-02-21 03:14:25 +0000714/// isSafeToDelete - If the specified instruction does not produce any side
715/// effects and all of its defs are dead, then it's safe to delete.
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000716static bool isSafeToDelete(MachineInstr *MI, unsigned Reg,
717 const TargetInstrInfo *TII,
718 SmallVector<unsigned, 4> &Kills) {
Evan Cheng28c7ce32009-02-21 03:14:25 +0000719 const TargetInstrDesc &TID = MI->getDesc();
720 if (TID.mayStore() || TID.isCall())
721 return false;
722 if (TID.isTerminator() || TID.hasUnmodeledSideEffects())
723 return false;
724
725 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
726 MachineOperand &MO = MI->getOperand(i);
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000727 if (!MO.isReg())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000728 continue;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000729 if (MO.isDef() && !MO.isDead())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000730 return false;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000731 if (MO.isUse() && MO.getReg() != Reg && MO.isKill())
732 Kills.push_back(MO.getReg());
Evan Cheng28c7ce32009-02-21 03:14:25 +0000733 }
734
735 return true;
736}
737
Bill Wendling637980e2008-05-10 00:12:52 +0000738/// runOnMachineFunction - Reduce two-address instructions to two operands.
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000739///
Chris Lattner163c1e72004-01-31 21:14:04 +0000740bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
Bill Wendlinga09362e2006-11-28 22:48:48 +0000741 DOUT << "Machine Function\n";
Misha Brukman75fa4e42004-07-22 15:26:23 +0000742 const TargetMachine &TM = MF.getTarget();
Evan Cheng875357d2008-03-13 06:37:55 +0000743 MRI = &MF.getRegInfo();
744 TII = TM.getInstrInfo();
745 TRI = TM.getRegisterInfo();
Duncan Sands1465d612009-01-28 13:14:17 +0000746 LV = getAnalysisIfAvailable<LiveVariables>();
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000747
Misha Brukman75fa4e42004-07-22 15:26:23 +0000748 bool MadeChange = false;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000749
Bill Wendlinga09362e2006-11-28 22:48:48 +0000750 DOUT << "********** REWRITING TWO-ADDR INSTRS **********\n";
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000751 DEBUG(errs() << "********** Function: "
752 << MF.getFunction()->getName() << '\n');
Alkis Evlogimenos3a9986f2004-02-18 00:35:06 +0000753
Evan Cheng7543e582008-06-18 07:49:14 +0000754 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
755 BitVector ReMatRegs;
756 ReMatRegs.resize(MRI->getLastVirtReg()+1);
757
Evan Cheng870b8072009-03-01 02:03:43 +0000758 SmallPtrSet<MachineInstr*, 8> Processed;
Misha Brukman75fa4e42004-07-22 15:26:23 +0000759 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
760 mbbi != mbbe; ++mbbi) {
Evan Cheng7543e582008-06-18 07:49:14 +0000761 unsigned Dist = 0;
762 DistanceMap.clear();
Evan Cheng870b8072009-03-01 02:03:43 +0000763 SrcRegMap.clear();
764 DstRegMap.clear();
765 Processed.clear();
Misha Brukman75fa4e42004-07-22 15:26:23 +0000766 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
Evan Cheng7a963fa2008-03-27 01:27:25 +0000767 mi != me; ) {
768 MachineBasicBlock::iterator nmi = next(mi);
Chris Lattner749c6f62008-01-07 07:27:27 +0000769 const TargetInstrDesc &TID = mi->getDesc();
Evan Cheng360c2dd2006-11-01 23:06:55 +0000770 bool FirstTied = true;
Bill Wendling637980e2008-05-10 00:12:52 +0000771
Evan Cheng7543e582008-06-18 07:49:14 +0000772 DistanceMap.insert(std::make_pair(mi, ++Dist));
Evan Cheng870b8072009-03-01 02:03:43 +0000773
774 ProcessCopy(&*mi, &*mbbi, Processed);
775
Evan Chengfb112882009-03-23 08:01:15 +0000776 unsigned NumOps = (mi->getOpcode() == TargetInstrInfo::INLINEASM)
777 ? mi->getNumOperands() : TID.getNumOperands();
778 for (unsigned si = 0; si < NumOps; ++si) {
Evan Chenga24752f2009-03-19 20:30:06 +0000779 unsigned ti = 0;
780 if (!mi->isRegTiedToDefOperand(si, &ti))
Evan Cheng360c2dd2006-11-01 23:06:55 +0000781 continue;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000782
Evan Cheng360c2dd2006-11-01 23:06:55 +0000783 if (FirstTied) {
784 ++NumTwoAddressInstrs;
Bill Wendlingbcd24982006-12-07 20:28:15 +0000785 DOUT << '\t'; DEBUG(mi->print(*cerr.stream(), &TM));
Evan Cheng360c2dd2006-11-01 23:06:55 +0000786 }
Bill Wendling637980e2008-05-10 00:12:52 +0000787
Evan Cheng360c2dd2006-11-01 23:06:55 +0000788 FirstTied = false;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000789
Dan Gohmand735b802008-10-03 15:45:36 +0000790 assert(mi->getOperand(si).isReg() && mi->getOperand(si).getReg() &&
Evan Cheng360c2dd2006-11-01 23:06:55 +0000791 mi->getOperand(si).isUse() && "two address instruction invalid");
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000792
Bill Wendling637980e2008-05-10 00:12:52 +0000793 // If the two operands are the same we just remove the use
Evan Cheng360c2dd2006-11-01 23:06:55 +0000794 // and mark the def as def&use, otherwise we have to insert a copy.
795 if (mi->getOperand(ti).getReg() != mi->getOperand(si).getReg()) {
Bill Wendling637980e2008-05-10 00:12:52 +0000796 // Rewrite:
Evan Cheng360c2dd2006-11-01 23:06:55 +0000797 // a = b op c
798 // to:
799 // a = b
800 // a = a op c
801 unsigned regA = mi->getOperand(ti).getReg();
802 unsigned regB = mi->getOperand(si).getReg();
Evan Cheng37844532009-07-16 09:20:10 +0000803 unsigned regASubIdx = mi->getOperand(ti).getSubReg();
Evan Cheng360c2dd2006-11-01 23:06:55 +0000804
Evan Chengfb112882009-03-23 08:01:15 +0000805 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
Evan Cheng360c2dd2006-11-01 23:06:55 +0000806 "cannot update physical register live information");
Chris Lattner6b507672004-01-31 21:21:43 +0000807
Chris Lattner1e313632004-07-21 23:17:57 +0000808#ifndef NDEBUG
Evan Cheng360c2dd2006-11-01 23:06:55 +0000809 // First, verify that we don't have a use of a in the instruction (a =
810 // b + a for example) because our transformation will not work. This
811 // should never occur because we are in SSA form.
812 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
Evan Chenga24752f2009-03-19 20:30:06 +0000813 assert(i == ti ||
Dan Gohmand735b802008-10-03 15:45:36 +0000814 !mi->getOperand(i).isReg() ||
Evan Cheng360c2dd2006-11-01 23:06:55 +0000815 mi->getOperand(i).getReg() != regA);
Chris Lattner1e313632004-07-21 23:17:57 +0000816#endif
Alkis Evlogimenos14be6402004-02-04 22:17:40 +0000817
Evan Cheng360c2dd2006-11-01 23:06:55 +0000818 // If this instruction is not the killing user of B, see if we can
819 // rearrange the code to make it so. Making it the killing user will
820 // allow us to coalesce A and B together, eliminating the copy we are
821 // about to insert.
Dan Gohman97121ba2009-04-08 00:15:30 +0000822 if (!isKilled(*mi, regB, MRI, TII)) {
Evan Cheng28c7ce32009-02-21 03:14:25 +0000823 // If regA is dead and the instruction can be deleted, just delete
824 // it so it doesn't clobber regB.
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000825 SmallVector<unsigned, 4> Kills;
826 if (mi->getOperand(ti).isDead() &&
827 isSafeToDelete(mi, regB, TII, Kills)) {
828 SmallVector<std::pair<std::pair<unsigned, bool>
829 ,MachineInstr*>, 4> NewKills;
830 bool ReallySafe = true;
831 // If this instruction kills some virtual registers, we need
832 // update the kill information. If it's not possible to do so,
833 // then bail out.
834 while (!Kills.empty()) {
835 unsigned Kill = Kills.back();
836 Kills.pop_back();
837 if (TargetRegisterInfo::isPhysicalRegister(Kill)) {
838 ReallySafe = false;
839 break;
840 }
841 MachineInstr *LastKill = FindLastUseInMBB(Kill, &*mbbi, Dist);
842 if (LastKill) {
843 bool isModRef = LastKill->modifiesRegister(Kill);
844 NewKills.push_back(std::make_pair(std::make_pair(Kill,isModRef),
845 LastKill));
846 } else {
847 ReallySafe = false;
848 break;
849 }
850 }
851
852 if (ReallySafe) {
853 if (LV) {
854 while (!NewKills.empty()) {
855 MachineInstr *NewKill = NewKills.back().second;
856 unsigned Kill = NewKills.back().first.first;
857 bool isDead = NewKills.back().first.second;
858 NewKills.pop_back();
859 if (LV->removeVirtualRegisterKilled(Kill, mi)) {
860 if (isDead)
861 LV->addVirtualRegisterDead(Kill, NewKill);
862 else
863 LV->addVirtualRegisterKilled(Kill, NewKill);
864 }
865 }
866 }
Lang Hames60dc7342009-05-13 04:18:47 +0000867
868 // We're really going to nuke the old inst. If regB was marked
869 // as a kill we need to update its Kills list.
870 if (mi->getOperand(si).isKill())
871 LV->removeVirtualRegisterKilled(regB, mi);
872
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000873 mbbi->erase(mi); // Nuke the old inst.
874 mi = nmi;
875 ++NumDeletes;
876 break; // Done with this instruction.
877 }
Evan Cheng28c7ce32009-02-21 03:14:25 +0000878 }
879
Evan Cheng360c2dd2006-11-01 23:06:55 +0000880 // If this instruction is commutative, check to see if C dies. If
881 // so, swap the B and C operands. This makes the live ranges of A
882 // and C joinable.
883 // FIXME: This code also works for A := B op C instructions.
Evan Cheng33d04742009-07-20 21:16:08 +0000884 unsigned SrcOp1, SrcOp2;
885 if (TID.isCommutable() && mi->getNumOperands() >= 3 &&
886 TII->findCommutedOpIndices(mi, SrcOp1, SrcOp2)) {
887 unsigned regC = 0;
888 if (si == SrcOp1)
889 regC = mi->getOperand(SrcOp2).getReg();
890 else if (si == SrcOp2)
891 regC = mi->getOperand(SrcOp1).getReg();
Dan Gohman97121ba2009-04-08 00:15:30 +0000892 if (isKilled(*mi, regC, MRI, TII)) {
Evan Cheng870b8072009-03-01 02:03:43 +0000893 if (CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
Evan Cheng360c2dd2006-11-01 23:06:55 +0000894 ++NumCommuted;
895 regB = regC;
896 goto InstructionRearranged;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000897 }
Chris Lattnerc71d6942005-01-19 07:08:42 +0000898 }
Chris Lattnercfa0f2e2005-01-02 02:34:12 +0000899 }
Evan Cheng360c2dd2006-11-01 23:06:55 +0000900
901 // If this instruction is potentially convertible to a true
902 // three-address instruction,
Chris Lattner749c6f62008-01-07 07:27:27 +0000903 if (TID.isConvertibleTo3Addr()) {
Evan Cheng360c2dd2006-11-01 23:06:55 +0000904 // FIXME: This assumes there are no more operands which are tied
905 // to another register.
906#ifndef NDEBUG
Bill Wendling637980e2008-05-10 00:12:52 +0000907 for (unsigned i = si + 1, e = TID.getNumOperands(); i < e; ++i)
Chris Lattner749c6f62008-01-07 07:27:27 +0000908 assert(TID.getOperandConstraint(i, TOI::TIED_TO) == -1);
Evan Cheng360c2dd2006-11-01 23:06:55 +0000909#endif
910
Evan Chenge6f350d2009-03-30 21:34:07 +0000911 if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) {
Evan Cheng360c2dd2006-11-01 23:06:55 +0000912 ++NumConvertedTo3Addr;
Bill Wendling637980e2008-05-10 00:12:52 +0000913 break; // Done with this instruction.
Evan Cheng360c2dd2006-11-01 23:06:55 +0000914 }
Evan Chengb9d5e7c2007-10-20 04:01:47 +0000915 }
Chris Lattnercfa0f2e2005-01-02 02:34:12 +0000916 }
Evan Cheng360c2dd2006-11-01 23:06:55 +0000917
Evan Chengd498c8f2009-01-25 03:53:59 +0000918 // If it's profitable to commute the instruction, do so.
Evan Chengebfc1772009-07-11 00:04:23 +0000919 unsigned SrcOp1, SrcOp2;
920 if (TID.isCommutable() && mi->getNumOperands() >= 3 &&
921 TII->findCommutedOpIndices(mi, SrcOp1, SrcOp2)) {
922 unsigned regC = 0;
923 if (si == SrcOp1)
924 regC = mi->getOperand(SrcOp2).getReg();
925 else if (si == SrcOp2)
926 regC = mi->getOperand(SrcOp1).getReg();
927
928 if (regC && isProfitableToCommute(regB, regC, mi, mbbi, Dist))
Evan Cheng870b8072009-03-01 02:03:43 +0000929 if (CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000930 ++NumAggrCommuted;
931 ++NumCommuted;
932 regB = regC;
Evan Chenge6f350d2009-03-30 21:34:07 +0000933 goto InstructionRearranged;
Evan Chengd498c8f2009-01-25 03:53:59 +0000934 }
935 }
936
Evan Chenge6f350d2009-03-30 21:34:07 +0000937 // If it's profitable to convert the 2-address instruction to a
938 // 3-address one, do so.
939 if (TID.isConvertibleTo3Addr() && isProfitableToConv3Addr(regA)) {
940 if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) {
941 ++NumConvertedTo3Addr;
942 break; // Done with this instruction.
943 }
944 }
945
Evan Cheng360c2dd2006-11-01 23:06:55 +0000946 InstructionRearranged:
Evan Chengfb112882009-03-23 08:01:15 +0000947 const TargetRegisterClass* rc = MRI->getRegClass(regB);
Evan Cheng7543e582008-06-18 07:49:14 +0000948 MachineInstr *DefMI = MRI->getVRegDef(regB);
949 // If it's safe and profitable, remat the definition instead of
950 // copying it.
Evan Cheng601ca4b2008-06-25 01:16:38 +0000951 if (DefMI &&
Evan Cheng8763c1c2008-08-27 20:58:54 +0000952 DefMI->getDesc().isAsCheapAsAMove() &&
Evan Chengdf3b9932008-08-27 20:33:50 +0000953 DefMI->isSafeToReMat(TII, regB) &&
Evan Cheng870b8072009-03-01 02:03:43 +0000954 isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){
Evan Cheng7543e582008-06-18 07:49:14 +0000955 DEBUG(cerr << "2addr: REMATTING : " << *DefMI << "\n");
Evan Cheng37844532009-07-16 09:20:10 +0000956 TII->reMaterialize(*mbbi, mi, regA, regASubIdx, DefMI);
Evan Cheng7543e582008-06-18 07:49:14 +0000957 ReMatRegs.set(regB);
958 ++NumReMats;
Bill Wendling48f7f232008-05-26 05:18:34 +0000959 } else {
Dan Gohman6ed0e202009-04-13 15:16:56 +0000960 bool Emitted = TII->copyRegToReg(*mbbi, mi, regA, regB, rc, rc);
Mike Stump1e8f0722009-05-08 22:53:06 +0000961 (void)Emitted;
Dan Gohman6ed0e202009-04-13 15:16:56 +0000962 assert(Emitted && "Unable to issue a copy instruction!\n");
Bill Wendling48f7f232008-05-26 05:18:34 +0000963 }
Evan Cheng360c2dd2006-11-01 23:06:55 +0000964
Evan Chengd498c8f2009-01-25 03:53:59 +0000965 MachineBasicBlock::iterator prevMI = prior(mi);
966 // Update DistanceMap.
967 DistanceMap.insert(std::make_pair(prevMI, Dist));
968 DistanceMap[mi] = ++Dist;
Evan Cheng360c2dd2006-11-01 23:06:55 +0000969
Bill Wendling637980e2008-05-10 00:12:52 +0000970 // Update live variables for regB.
Owen Anderson802af112008-07-02 21:28:58 +0000971 if (LV) {
Evan Cheng9f1c8312008-07-03 09:09:37 +0000972 if (LV->removeVirtualRegisterKilled(regB, mi))
Evan Chengd498c8f2009-01-25 03:53:59 +0000973 LV->addVirtualRegisterKilled(regB, prevMI);
Evan Cheng360c2dd2006-11-01 23:06:55 +0000974
Evan Cheng9f1c8312008-07-03 09:09:37 +0000975 if (LV->removeVirtualRegisterDead(regB, mi))
Evan Chengd498c8f2009-01-25 03:53:59 +0000976 LV->addVirtualRegisterDead(regB, prevMI);
Owen Anderson802af112008-07-02 21:28:58 +0000977 }
Dan Gohman2d9716f2008-11-12 17:15:19 +0000978
Evan Chengd498c8f2009-01-25 03:53:59 +0000979 DOUT << "\t\tprepend:\t"; DEBUG(prevMI->print(*cerr.stream(), &TM));
Owen Anderson802af112008-07-02 21:28:58 +0000980
Bill Wendling637980e2008-05-10 00:12:52 +0000981 // Replace all occurences of regB with regA.
Evan Cheng360c2dd2006-11-01 23:06:55 +0000982 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
Dan Gohmand735b802008-10-03 15:45:36 +0000983 if (mi->getOperand(i).isReg() &&
Evan Cheng360c2dd2006-11-01 23:06:55 +0000984 mi->getOperand(i).getReg() == regB)
985 mi->getOperand(i).setReg(regA);
986 }
Chris Lattnercfa0f2e2005-01-02 02:34:12 +0000987 }
Alkis Evlogimenos14be6402004-02-04 22:17:40 +0000988
Evan Cheng360c2dd2006-11-01 23:06:55 +0000989 assert(mi->getOperand(ti).isDef() && mi->getOperand(si).isUse());
990 mi->getOperand(ti).setReg(mi->getOperand(si).getReg());
991 MadeChange = true;
Alkis Evlogimenos14be6402004-02-04 22:17:40 +0000992
Bill Wendlingbcd24982006-12-07 20:28:15 +0000993 DOUT << "\t\trewrite to:\t"; DEBUG(mi->print(*cerr.stream(), &TM));
Misha Brukman75fa4e42004-07-22 15:26:23 +0000994 }
Bill Wendling637980e2008-05-10 00:12:52 +0000995
Evan Cheng7a963fa2008-03-27 01:27:25 +0000996 mi = nmi;
Misha Brukman75fa4e42004-07-22 15:26:23 +0000997 }
998 }
999
Evan Cheng601ca4b2008-06-25 01:16:38 +00001000 // Some remat'ed instructions are dead.
1001 int VReg = ReMatRegs.find_first();
1002 while (VReg != -1) {
1003 if (MRI->use_empty(VReg)) {
1004 MachineInstr *DefMI = MRI->getVRegDef(VReg);
1005 DefMI->eraseFromParent();
Bill Wendlinga16157a2008-05-26 05:49:49 +00001006 }
Evan Cheng601ca4b2008-06-25 01:16:38 +00001007 VReg = ReMatRegs.find_next(VReg);
Bill Wendling48f7f232008-05-26 05:18:34 +00001008 }
1009
Misha Brukman75fa4e42004-07-22 15:26:23 +00001010 return MadeChange;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001011}