blob: 0a6a0d745496a0e5bf99f08da22687a63faa604c [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 Gohmana70dca12009-10-09 23:27:56 +000037#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000038#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000039#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetMachine.h"
Owen Anderson95dad832008-10-07 20:22:28 +000041#include "llvm/Target/TargetOptions.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 {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000059 class TwoAddressInstructionPass : public MachineFunctionPass {
Evan Cheng875357d2008-03-13 06:37:55 +000060 const TargetInstrInfo *TII;
61 const TargetRegisterInfo *TRI;
62 MachineRegisterInfo *MRI;
63 LiveVariables *LV;
Dan Gohmana70dca12009-10-09 23:27:56 +000064 AliasAnalysis *AA;
Evan Cheng875357d2008-03-13 06:37:55 +000065
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
Bob Wilson326f4382009-09-01 22:51:08 +0000109 typedef std::pair<std::pair<unsigned, bool>, MachineInstr*> NewKill;
110 bool canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
111 SmallVector<NewKill, 4> &NewKills,
112 MachineBasicBlock *MBB, unsigned Dist);
113 bool DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
114 MachineBasicBlock::iterator &nmi,
115 MachineFunction::iterator &mbbi,
116 unsigned regB, unsigned regBIdx, unsigned Dist);
117
Bob Wilsoncc80df92009-09-03 20:58:42 +0000118 bool TryInstructionTransform(MachineBasicBlock::iterator &mi,
119 MachineBasicBlock::iterator &nmi,
120 MachineFunction::iterator &mbbi,
121 unsigned SrcIdx, unsigned DstIdx,
122 unsigned Dist);
123
Evan Cheng870b8072009-03-01 02:03:43 +0000124 void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
125 SmallPtrSet<MachineInstr*, 8> &Processed);
Evan Cheng3a3cce52009-08-07 00:28:58 +0000126
Evan Cheng875357d2008-03-13 06:37:55 +0000127 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000128 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +0000129 TwoAddressInstructionPass() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000130
Bill Wendling637980e2008-05-10 00:12:52 +0000131 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +0000132 AU.setPreservesCFG();
Dan Gohmana70dca12009-10-09 23:27:56 +0000133 AU.addRequired<AliasAnalysis>();
Bill Wendling637980e2008-05-10 00:12:52 +0000134 AU.addPreserved<LiveVariables>();
135 AU.addPreservedID(MachineLoopInfoID);
136 AU.addPreservedID(MachineDominatorsID);
Owen Anderson95dad832008-10-07 20:22:28 +0000137 if (StrongPHIElim)
138 AU.addPreservedID(StrongPHIEliminationID);
139 else
140 AU.addPreservedID(PHIEliminationID);
Bill Wendling637980e2008-05-10 00:12:52 +0000141 MachineFunctionPass::getAnalysisUsage(AU);
142 }
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000143
Bill Wendling637980e2008-05-10 00:12:52 +0000144 /// runOnMachineFunction - Pass entry point.
Misha Brukman75fa4e42004-07-22 15:26:23 +0000145 bool runOnMachineFunction(MachineFunction&);
146 };
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000147}
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000148
Dan Gohman844731a2008-05-13 00:00:25 +0000149char TwoAddressInstructionPass::ID = 0;
150static RegisterPass<TwoAddressInstructionPass>
151X("twoaddressinstruction", "Two-Address instruction pass");
152
Dan Gohman6ddba2b2008-05-13 02:05:11 +0000153const PassInfo *const llvm::TwoAddressInstructionPassID = &X;
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000154
Evan Cheng875357d2008-03-13 06:37:55 +0000155/// Sink3AddrInstruction - A two-address instruction has been converted to a
156/// three-address instruction to avoid clobbering a register. Try to sink it
Bill Wendling637980e2008-05-10 00:12:52 +0000157/// past the instruction that would kill the above mentioned register to reduce
158/// register pressure.
Evan Cheng875357d2008-03-13 06:37:55 +0000159bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
160 MachineInstr *MI, unsigned SavedReg,
161 MachineBasicBlock::iterator OldPos) {
162 // Check if it's safe to move this instruction.
163 bool SeenStore = true; // Be conservative.
Dan Gohmana70dca12009-10-09 23:27:56 +0000164 if (!MI->isSafeToMove(TII, SeenStore, AA))
Evan Cheng875357d2008-03-13 06:37:55 +0000165 return false;
166
167 unsigned DefReg = 0;
168 SmallSet<unsigned, 4> UseRegs;
Bill Wendling637980e2008-05-10 00:12:52 +0000169
Evan Cheng875357d2008-03-13 06:37:55 +0000170 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
171 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000172 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000173 continue;
174 unsigned MOReg = MO.getReg();
175 if (!MOReg)
176 continue;
177 if (MO.isUse() && MOReg != SavedReg)
178 UseRegs.insert(MO.getReg());
179 if (!MO.isDef())
180 continue;
181 if (MO.isImplicit())
182 // Don't try to move it if it implicitly defines a register.
183 return false;
184 if (DefReg)
185 // For now, don't move any instructions that define multiple registers.
186 return false;
187 DefReg = MO.getReg();
188 }
189
190 // Find the instruction that kills SavedReg.
191 MachineInstr *KillMI = NULL;
192 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SavedReg),
193 UE = MRI->use_end(); UI != UE; ++UI) {
194 MachineOperand &UseMO = UI.getOperand();
195 if (!UseMO.isKill())
196 continue;
197 KillMI = UseMO.getParent();
198 break;
199 }
Bill Wendling637980e2008-05-10 00:12:52 +0000200
Dan Gohman97121ba2009-04-08 00:15:30 +0000201 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI)
Evan Cheng875357d2008-03-13 06:37:55 +0000202 return false;
203
Bill Wendling637980e2008-05-10 00:12:52 +0000204 // If any of the definitions are used by another instruction between the
205 // position and the kill use, then it's not safe to sink it.
206 //
207 // FIXME: This can be sped up if there is an easy way to query whether an
Evan Cheng7543e582008-06-18 07:49:14 +0000208 // instruction is before or after another instruction. Then we can use
Bill Wendling637980e2008-05-10 00:12:52 +0000209 // MachineRegisterInfo def / use instead.
Evan Cheng875357d2008-03-13 06:37:55 +0000210 MachineOperand *KillMO = NULL;
211 MachineBasicBlock::iterator KillPos = KillMI;
212 ++KillPos;
Bill Wendling637980e2008-05-10 00:12:52 +0000213
Evan Cheng7543e582008-06-18 07:49:14 +0000214 unsigned NumVisited = 0;
Evan Cheng875357d2008-03-13 06:37:55 +0000215 for (MachineBasicBlock::iterator I = next(OldPos); I != KillPos; ++I) {
216 MachineInstr *OtherMI = I;
Evan Cheng7543e582008-06-18 07:49:14 +0000217 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
218 return false;
219 ++NumVisited;
Evan Cheng875357d2008-03-13 06:37:55 +0000220 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
221 MachineOperand &MO = OtherMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000222 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000223 continue;
224 unsigned MOReg = MO.getReg();
225 if (!MOReg)
226 continue;
227 if (DefReg == MOReg)
228 return false;
Bill Wendling637980e2008-05-10 00:12:52 +0000229
Evan Cheng875357d2008-03-13 06:37:55 +0000230 if (MO.isKill()) {
231 if (OtherMI == KillMI && MOReg == SavedReg)
Evan Cheng7543e582008-06-18 07:49:14 +0000232 // Save the operand that kills the register. We want to unset the kill
233 // marker if we can sink MI past it.
Evan Cheng875357d2008-03-13 06:37:55 +0000234 KillMO = &MO;
235 else if (UseRegs.count(MOReg))
236 // One of the uses is killed before the destination.
237 return false;
238 }
239 }
240 }
241
Evan Cheng875357d2008-03-13 06:37:55 +0000242 // Update kill and LV information.
243 KillMO->setIsKill(false);
244 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
245 KillMO->setIsKill(true);
Owen Anderson802af112008-07-02 21:28:58 +0000246
Evan Cheng9f1c8312008-07-03 09:09:37 +0000247 if (LV)
248 LV->replaceKillInstruction(SavedReg, KillMI, MI);
Evan Cheng875357d2008-03-13 06:37:55 +0000249
250 // Move instruction to its destination.
251 MBB->remove(MI);
252 MBB->insert(KillPos, MI);
253
254 ++Num3AddrSunk;
255 return true;
256}
257
Evan Cheng7543e582008-06-18 07:49:14 +0000258/// isTwoAddrUse - Return true if the specified MI is using the specified
259/// register as a two-address operand.
260static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
261 const TargetInstrDesc &TID = UseMI->getDesc();
262 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
263 MachineOperand &MO = UseMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000264 if (MO.isReg() && MO.getReg() == Reg &&
Evan Chenga24752f2009-03-19 20:30:06 +0000265 (MO.isDef() || UseMI->isRegTiedToDefOperand(i)))
Evan Cheng7543e582008-06-18 07:49:14 +0000266 // Earlier use is a two-address one.
267 return true;
268 }
269 return false;
270}
271
272/// isProfitableToReMat - Return true if the heuristics determines it is likely
273/// to be profitable to re-materialize the definition of Reg rather than copy
274/// the register.
275bool
276TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
Evan Cheng870b8072009-03-01 02:03:43 +0000277 const TargetRegisterClass *RC,
278 MachineInstr *MI, MachineInstr *DefMI,
279 MachineBasicBlock *MBB, unsigned Loc) {
Evan Cheng7543e582008-06-18 07:49:14 +0000280 bool OtherUse = false;
281 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
282 UE = MRI->use_end(); UI != UE; ++UI) {
283 MachineOperand &UseMO = UI.getOperand();
Evan Cheng7543e582008-06-18 07:49:14 +0000284 MachineInstr *UseMI = UseMO.getParent();
Evan Cheng601ca4b2008-06-25 01:16:38 +0000285 MachineBasicBlock *UseMBB = UseMI->getParent();
286 if (UseMBB == MBB) {
287 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
288 if (DI != DistanceMap.end() && DI->second == Loc)
289 continue; // Current use.
290 OtherUse = true;
291 // There is at least one other use in the MBB that will clobber the
292 // register.
293 if (isTwoAddrUse(UseMI, Reg))
294 return true;
295 }
Evan Cheng7543e582008-06-18 07:49:14 +0000296 }
Evan Cheng601ca4b2008-06-25 01:16:38 +0000297
298 // If other uses in MBB are not two-address uses, then don't remat.
299 if (OtherUse)
300 return false;
301
302 // No other uses in the same block, remat if it's defined in the same
303 // block so it does not unnecessarily extend the live range.
304 return MBB == DefMI->getParent();
Evan Cheng7543e582008-06-18 07:49:14 +0000305}
306
Evan Chengd498c8f2009-01-25 03:53:59 +0000307/// NoUseAfterLastDef - Return true if there are no intervening uses between the
308/// last instruction in the MBB that defines the specified register and the
309/// two-address instruction which is being processed. It also returns the last
310/// def location by reference
311bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
Evan Cheng870b8072009-03-01 02:03:43 +0000312 MachineBasicBlock *MBB, unsigned Dist,
313 unsigned &LastDef) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000314 LastDef = 0;
315 unsigned LastUse = Dist;
316 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
317 E = MRI->reg_end(); I != E; ++I) {
318 MachineOperand &MO = I.getOperand();
319 MachineInstr *MI = MO.getParent();
320 if (MI->getParent() != MBB)
321 continue;
322 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
323 if (DI == DistanceMap.end())
324 continue;
325 if (MO.isUse() && DI->second < LastUse)
326 LastUse = DI->second;
327 if (MO.isDef() && DI->second > LastDef)
328 LastDef = DI->second;
329 }
330
331 return !(LastUse > LastDef && LastUse < Dist);
332}
333
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000334MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg,
335 MachineBasicBlock *MBB,
336 unsigned Dist) {
Lang Hamesa7c9dea2009-05-14 04:26:30 +0000337 unsigned LastUseDist = 0;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000338 MachineInstr *LastUse = 0;
339 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
340 E = MRI->reg_end(); I != E; ++I) {
341 MachineOperand &MO = I.getOperand();
342 MachineInstr *MI = MO.getParent();
343 if (MI->getParent() != MBB)
344 continue;
345 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
346 if (DI == DistanceMap.end())
347 continue;
Lang Hamesa7c9dea2009-05-14 04:26:30 +0000348 if (DI->second >= Dist)
349 continue;
350
351 if (MO.isUse() && DI->second > LastUseDist) {
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000352 LastUse = DI->first;
353 LastUseDist = DI->second;
354 }
355 }
356 return LastUse;
357}
358
Evan Cheng870b8072009-03-01 02:03:43 +0000359/// isCopyToReg - Return true if the specified MI is a copy instruction or
360/// a extract_subreg instruction. It also returns the source and destination
361/// registers and whether they are physical registers by reference.
362static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
363 unsigned &SrcReg, unsigned &DstReg,
364 bool &IsSrcPhys, bool &IsDstPhys) {
365 SrcReg = 0;
366 DstReg = 0;
367 unsigned SrcSubIdx, DstSubIdx;
368 if (!TII->isMoveInstr(MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
369 if (MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
370 DstReg = MI.getOperand(0).getReg();
371 SrcReg = MI.getOperand(1).getReg();
372 } else if (MI.getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
373 DstReg = MI.getOperand(0).getReg();
374 SrcReg = MI.getOperand(2).getReg();
Dan Gohman97121ba2009-04-08 00:15:30 +0000375 } else if (MI.getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
376 DstReg = MI.getOperand(0).getReg();
377 SrcReg = MI.getOperand(2).getReg();
Evan Cheng870b8072009-03-01 02:03:43 +0000378 }
379 }
380
381 if (DstReg) {
382 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
383 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
384 return true;
385 }
386 return false;
387}
388
Dan Gohman97121ba2009-04-08 00:15:30 +0000389/// isKilled - Test if the given register value, which is used by the given
390/// instruction, is killed by the given instruction. This looks through
391/// coalescable copies to see if the original value is potentially not killed.
392///
393/// For example, in this code:
394///
395/// %reg1034 = copy %reg1024
396/// %reg1035 = copy %reg1025<kill>
397/// %reg1036 = add %reg1034<kill>, %reg1035<kill>
398///
399/// %reg1034 is not considered to be killed, since it is copied from a
400/// register which is not killed. Treating it as not killed lets the
401/// normal heuristics commute the (two-address) add, which lets
402/// coalescing eliminate the extra copy.
403///
404static bool isKilled(MachineInstr &MI, unsigned Reg,
405 const MachineRegisterInfo *MRI,
406 const TargetInstrInfo *TII) {
407 MachineInstr *DefMI = &MI;
408 for (;;) {
409 if (!DefMI->killsRegister(Reg))
410 return false;
411 if (TargetRegisterInfo::isPhysicalRegister(Reg))
412 return true;
413 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
414 // If there are multiple defs, we can't do a simple analysis, so just
415 // go with what the kill flag says.
416 if (next(Begin) != MRI->def_end())
417 return true;
418 DefMI = &*Begin;
419 bool IsSrcPhys, IsDstPhys;
420 unsigned SrcReg, DstReg;
421 // If the def is something other than a copy, then it isn't going to
422 // be coalesced, so follow the kill flag.
423 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
424 return true;
425 Reg = SrcReg;
426 }
427}
428
Evan Cheng870b8072009-03-01 02:03:43 +0000429/// isTwoAddrUse - Return true if the specified MI uses the specified register
430/// as a two-address use. If so, return the destination register by reference.
431static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
432 const TargetInstrDesc &TID = MI.getDesc();
Evan Chenge6f350d2009-03-30 21:34:07 +0000433 unsigned NumOps = (MI.getOpcode() == TargetInstrInfo::INLINEASM)
434 ? MI.getNumOperands() : TID.getNumOperands();
435 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng870b8072009-03-01 02:03:43 +0000436 const MachineOperand &MO = MI.getOperand(i);
437 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
438 continue;
Evan Chenga24752f2009-03-19 20:30:06 +0000439 unsigned ti;
440 if (MI.isRegTiedToDefOperand(i, &ti)) {
Evan Cheng870b8072009-03-01 02:03:43 +0000441 DstReg = MI.getOperand(ti).getReg();
442 return true;
443 }
444 }
445 return false;
446}
447
448/// findOnlyInterestingUse - Given a register, if has a single in-basic block
449/// use, return the use instruction if it's a copy or a two-address use.
450static
451MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
452 MachineRegisterInfo *MRI,
453 const TargetInstrInfo *TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000454 bool &IsCopy,
Evan Cheng870b8072009-03-01 02:03:43 +0000455 unsigned &DstReg, bool &IsDstPhys) {
456 MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg);
457 if (UI == MRI->use_end())
458 return 0;
459 MachineInstr &UseMI = *UI;
460 if (++UI != MRI->use_end())
461 // More than one use.
462 return 0;
463 if (UseMI.getParent() != MBB)
464 return 0;
465 unsigned SrcReg;
466 bool IsSrcPhys;
Evan Cheng87d696a2009-04-14 00:32:25 +0000467 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
468 IsCopy = true;
Evan Cheng870b8072009-03-01 02:03:43 +0000469 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000470 }
Evan Cheng870b8072009-03-01 02:03:43 +0000471 IsDstPhys = false;
Evan Cheng87d696a2009-04-14 00:32:25 +0000472 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
473 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng870b8072009-03-01 02:03:43 +0000474 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000475 }
Evan Cheng870b8072009-03-01 02:03:43 +0000476 return 0;
477}
478
479/// getMappedReg - Return the physical register the specified virtual register
480/// might be mapped to.
481static unsigned
482getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
483 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
484 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
485 if (SI == RegMap.end())
486 return 0;
487 Reg = SI->second;
488 }
489 if (TargetRegisterInfo::isPhysicalRegister(Reg))
490 return Reg;
491 return 0;
492}
493
494/// regsAreCompatible - Return true if the two registers are equal or aliased.
495///
496static bool
497regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
498 if (RegA == RegB)
499 return true;
500 if (!RegA || !RegB)
501 return false;
502 return TRI->regsOverlap(RegA, RegB);
503}
504
505
Evan Chengd498c8f2009-01-25 03:53:59 +0000506/// isProfitableToReMat - Return true if it's potentially profitable to commute
507/// the two-address instruction that's being processed.
508bool
509TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC,
Evan Cheng870b8072009-03-01 02:03:43 +0000510 MachineInstr *MI, MachineBasicBlock *MBB,
511 unsigned Dist) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000512 // Determine if it's profitable to commute this two address instruction. In
513 // general, we want no uses between this instruction and the definition of
514 // the two-address register.
515 // e.g.
516 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
517 // %reg1029<def> = MOV8rr %reg1028
518 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
519 // insert => %reg1030<def> = MOV8rr %reg1028
520 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
521 // In this case, it might not be possible to coalesce the second MOV8rr
522 // instruction if the first one is coalesced. So it would be profitable to
523 // commute it:
524 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
525 // %reg1029<def> = MOV8rr %reg1028
526 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
527 // insert => %reg1030<def> = MOV8rr %reg1029
528 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
529
530 if (!MI->killsRegister(regC))
531 return false;
532
533 // Ok, we have something like:
534 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
535 // let's see if it's worth commuting it.
536
Evan Cheng870b8072009-03-01 02:03:43 +0000537 // Look for situations like this:
538 // %reg1024<def> = MOV r1
539 // %reg1025<def> = MOV r0
540 // %reg1026<def> = ADD %reg1024, %reg1025
541 // r0 = MOV %reg1026
542 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
543 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
544 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
545 unsigned ToRegB = getMappedReg(regB, DstRegMap);
546 unsigned ToRegC = getMappedReg(regC, DstRegMap);
547 if (!regsAreCompatible(FromRegB, ToRegB, TRI) &&
548 (regsAreCompatible(FromRegB, ToRegC, TRI) ||
549 regsAreCompatible(FromRegC, ToRegB, TRI)))
550 return true;
551
Evan Chengd498c8f2009-01-25 03:53:59 +0000552 // If there is a use of regC between its last def (could be livein) and this
553 // instruction, then bail.
554 unsigned LastDefC = 0;
Evan Cheng870b8072009-03-01 02:03:43 +0000555 if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
Evan Chengd498c8f2009-01-25 03:53:59 +0000556 return false;
557
558 // If there is a use of regB between its last def (could be livein) and this
559 // instruction, then go ahead and make this transformation.
560 unsigned LastDefB = 0;
Evan Cheng870b8072009-03-01 02:03:43 +0000561 if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
Evan Chengd498c8f2009-01-25 03:53:59 +0000562 return true;
563
564 // Since there are no intervening uses for both registers, then commute
565 // if the def of regC is closer. Its live interval is shorter.
566 return LastDefB && LastDefC && LastDefC > LastDefB;
567}
568
Evan Cheng81913712009-01-23 23:27:33 +0000569/// CommuteInstruction - Commute a two-address instruction and update the basic
570/// block, distance map, and live variables if needed. Return true if it is
571/// successful.
572bool
573TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
Evan Cheng870b8072009-03-01 02:03:43 +0000574 MachineFunction::iterator &mbbi,
575 unsigned RegB, unsigned RegC, unsigned Dist) {
Evan Cheng81913712009-01-23 23:27:33 +0000576 MachineInstr *MI = mi;
Chris Lattner6456d382009-08-23 03:20:44 +0000577 DEBUG(errs() << "2addr: COMMUTING : " << *MI);
Evan Cheng81913712009-01-23 23:27:33 +0000578 MachineInstr *NewMI = TII->commuteInstruction(MI);
579
580 if (NewMI == 0) {
Chris Lattner6456d382009-08-23 03:20:44 +0000581 DEBUG(errs() << "2addr: COMMUTING FAILED!\n");
Evan Cheng81913712009-01-23 23:27:33 +0000582 return false;
583 }
584
Chris Lattner6456d382009-08-23 03:20:44 +0000585 DEBUG(errs() << "2addr: COMMUTED TO: " << *NewMI);
Evan Cheng81913712009-01-23 23:27:33 +0000586 // If the instruction changed to commute it, update livevar.
587 if (NewMI != MI) {
588 if (LV)
589 // Update live variables
590 LV->replaceKillInstruction(RegC, MI, NewMI);
591
592 mbbi->insert(mi, NewMI); // Insert the new inst
593 mbbi->erase(mi); // Nuke the old inst.
594 mi = NewMI;
595 DistanceMap.insert(std::make_pair(NewMI, Dist));
596 }
Evan Cheng870b8072009-03-01 02:03:43 +0000597
598 // Update source register map.
599 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
600 if (FromRegC) {
601 unsigned RegA = MI->getOperand(0).getReg();
602 SrcRegMap[RegA] = FromRegC;
603 }
604
Evan Cheng81913712009-01-23 23:27:33 +0000605 return true;
606}
607
Evan Chenge6f350d2009-03-30 21:34:07 +0000608/// isProfitableToConv3Addr - Return true if it is profitable to convert the
609/// given 2-address instruction to a 3-address one.
610bool
611TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA) {
612 // Look for situations like this:
613 // %reg1024<def> = MOV r1
614 // %reg1025<def> = MOV r0
615 // %reg1026<def> = ADD %reg1024, %reg1025
616 // r2 = MOV %reg1026
617 // Turn ADD into a 3-address instruction to avoid a copy.
618 unsigned FromRegA = getMappedReg(RegA, SrcRegMap);
619 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
620 return (FromRegA && ToRegA && !regsAreCompatible(FromRegA, ToRegA, TRI));
621}
622
623/// ConvertInstTo3Addr - Convert the specified two-address instruction into a
624/// three address one. Return true if this transformation was successful.
625bool
626TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
627 MachineBasicBlock::iterator &nmi,
628 MachineFunction::iterator &mbbi,
629 unsigned RegB, unsigned Dist) {
630 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
631 if (NewMI) {
Chris Lattner6456d382009-08-23 03:20:44 +0000632 DEBUG(errs() << "2addr: CONVERTING 2-ADDR: " << *mi);
633 DEBUG(errs() << "2addr: TO 3-ADDR: " << *NewMI);
Evan Chenge6f350d2009-03-30 21:34:07 +0000634 bool Sunk = false;
635
636 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
637 // FIXME: Temporary workaround. If the new instruction doesn't
638 // uses RegB, convertToThreeAddress must have created more
639 // then one instruction.
640 Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
641
642 mbbi->erase(mi); // Nuke the old inst.
643
644 if (!Sunk) {
645 DistanceMap.insert(std::make_pair(NewMI, Dist));
646 mi = NewMI;
647 nmi = next(mi);
648 }
649 return true;
650 }
651
652 return false;
653}
654
Evan Cheng870b8072009-03-01 02:03:43 +0000655/// ProcessCopy - If the specified instruction is not yet processed, process it
656/// if it's a copy. For a copy instruction, we find the physical registers the
657/// source and destination registers might be mapped to. These are kept in
658/// point-to maps used to determine future optimizations. e.g.
659/// v1024 = mov r0
660/// v1025 = mov r1
661/// v1026 = add v1024, v1025
662/// r1 = mov r1026
663/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
664/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
665/// potentially joined with r1 on the output side. It's worthwhile to commute
666/// 'add' to eliminate a copy.
667void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
668 MachineBasicBlock *MBB,
669 SmallPtrSet<MachineInstr*, 8> &Processed) {
670 if (Processed.count(MI))
671 return;
672
673 bool IsSrcPhys, IsDstPhys;
674 unsigned SrcReg, DstReg;
675 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
676 return;
677
678 if (IsDstPhys && !IsSrcPhys)
679 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
680 else if (!IsDstPhys && IsSrcPhys) {
Evan Cheng3005ed62009-04-13 20:04:24 +0000681 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
682 if (!isNew)
683 assert(SrcRegMap[DstReg] == SrcReg &&
684 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000685
686 SmallVector<unsigned, 4> VirtRegPairs;
Evan Cheng87d696a2009-04-14 00:32:25 +0000687 bool IsCopy = false;
Evan Cheng870b8072009-03-01 02:03:43 +0000688 unsigned NewReg = 0;
689 while (MachineInstr *UseMI = findOnlyInterestingUse(DstReg, MBB, MRI,TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000690 IsCopy, NewReg, IsDstPhys)) {
691 if (IsCopy) {
692 if (!Processed.insert(UseMI))
Evan Cheng870b8072009-03-01 02:03:43 +0000693 break;
694 }
695
696 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
697 if (DI != DistanceMap.end())
698 // Earlier in the same MBB.Reached via a back edge.
699 break;
700
701 if (IsDstPhys) {
702 VirtRegPairs.push_back(NewReg);
703 break;
704 }
705 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, DstReg)).second;
Evan Cheng3005ed62009-04-13 20:04:24 +0000706 if (!isNew)
Evan Cheng87d696a2009-04-14 00:32:25 +0000707 assert(SrcRegMap[NewReg] == DstReg &&
708 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000709 VirtRegPairs.push_back(NewReg);
710 DstReg = NewReg;
711 }
712
713 if (!VirtRegPairs.empty()) {
714 unsigned ToReg = VirtRegPairs.back();
715 VirtRegPairs.pop_back();
716 while (!VirtRegPairs.empty()) {
717 unsigned FromReg = VirtRegPairs.back();
718 VirtRegPairs.pop_back();
719 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
Evan Cheng3005ed62009-04-13 20:04:24 +0000720 if (!isNew)
721 assert(DstRegMap[FromReg] == ToReg &&
722 "Can't map to two dst physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000723 ToReg = FromReg;
724 }
725 }
726 }
727
728 Processed.insert(MI);
729}
730
Evan Cheng28c7ce32009-02-21 03:14:25 +0000731/// isSafeToDelete - If the specified instruction does not produce any side
732/// effects and all of its defs are dead, then it's safe to delete.
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000733static bool isSafeToDelete(MachineInstr *MI, unsigned Reg,
734 const TargetInstrInfo *TII,
735 SmallVector<unsigned, 4> &Kills) {
Evan Cheng28c7ce32009-02-21 03:14:25 +0000736 const TargetInstrDesc &TID = MI->getDesc();
737 if (TID.mayStore() || TID.isCall())
738 return false;
739 if (TID.isTerminator() || TID.hasUnmodeledSideEffects())
740 return false;
741
742 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
743 MachineOperand &MO = MI->getOperand(i);
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000744 if (!MO.isReg())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000745 continue;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000746 if (MO.isDef() && !MO.isDead())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000747 return false;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000748 if (MO.isUse() && MO.getReg() != Reg && MO.isKill())
749 Kills.push_back(MO.getReg());
Evan Cheng28c7ce32009-02-21 03:14:25 +0000750 }
751
752 return true;
753}
754
Bob Wilson326f4382009-09-01 22:51:08 +0000755/// canUpdateDeletedKills - Check if all the registers listed in Kills are
756/// killed by instructions in MBB preceding the current instruction at
757/// position Dist. If so, return true and record information about the
758/// preceding kills in NewKills.
759bool TwoAddressInstructionPass::
760canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
761 SmallVector<NewKill, 4> &NewKills,
762 MachineBasicBlock *MBB, unsigned Dist) {
763 while (!Kills.empty()) {
764 unsigned Kill = Kills.back();
765 Kills.pop_back();
766 if (TargetRegisterInfo::isPhysicalRegister(Kill))
767 return false;
768
769 MachineInstr *LastKill = FindLastUseInMBB(Kill, MBB, Dist);
770 if (!LastKill)
771 return false;
772
773 bool isModRef = LastKill->modifiesRegister(Kill);
774 NewKills.push_back(std::make_pair(std::make_pair(Kill, isModRef),
775 LastKill));
776 }
777 return true;
778}
779
780/// DeleteUnusedInstr - If an instruction with a tied register operand can
781/// be safely deleted, just delete it.
782bool
783TwoAddressInstructionPass::DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
784 MachineBasicBlock::iterator &nmi,
785 MachineFunction::iterator &mbbi,
786 unsigned regB, unsigned regBIdx,
787 unsigned Dist) {
788 // Check if the instruction has no side effects and if all its defs are dead.
789 SmallVector<unsigned, 4> Kills;
790 if (!isSafeToDelete(mi, regB, TII, Kills))
791 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 }
813
814 // If regB was marked as a kill, update its Kills list.
815 if (mi->getOperand(regBIdx).isKill())
816 LV->removeVirtualRegisterKilled(regB, mi);
817 }
818
819 mbbi->erase(mi); // Nuke the old inst.
820 mi = nmi;
821 return true;
822}
823
Bob Wilsoncc80df92009-09-03 20:58:42 +0000824/// TryInstructionTransform - For the case where an instruction has a single
825/// pair of tied register operands, attempt some transformations that may
826/// either eliminate the tied operands or improve the opportunities for
827/// coalescing away the register copy. Returns true if the tied operands
828/// are eliminated altogether.
829bool TwoAddressInstructionPass::
830TryInstructionTransform(MachineBasicBlock::iterator &mi,
831 MachineBasicBlock::iterator &nmi,
832 MachineFunction::iterator &mbbi,
833 unsigned SrcIdx, unsigned DstIdx, unsigned Dist) {
834 const TargetInstrDesc &TID = mi->getDesc();
835 unsigned regA = mi->getOperand(DstIdx).getReg();
836 unsigned regB = mi->getOperand(SrcIdx).getReg();
837
838 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
839 "cannot make instruction into two-address form");
840
841 // If regA is dead and the instruction can be deleted, just delete
842 // it so it doesn't clobber regB.
843 bool regBKilled = isKilled(*mi, regB, MRI, TII);
844 if (!regBKilled && mi->getOperand(DstIdx).isDead() &&
845 DeleteUnusedInstr(mi, nmi, mbbi, regB, SrcIdx, Dist)) {
846 ++NumDeletes;
847 return true; // Done with this instruction.
848 }
849
850 // Check if it is profitable to commute the operands.
851 unsigned SrcOp1, SrcOp2;
852 unsigned regC = 0;
853 unsigned regCIdx = ~0U;
854 bool TryCommute = false;
855 bool AggressiveCommute = false;
856 if (TID.isCommutable() && mi->getNumOperands() >= 3 &&
857 TII->findCommutedOpIndices(mi, SrcOp1, SrcOp2)) {
858 if (SrcIdx == SrcOp1)
859 regCIdx = SrcOp2;
860 else if (SrcIdx == SrcOp2)
861 regCIdx = SrcOp1;
862
863 if (regCIdx != ~0U) {
864 regC = mi->getOperand(regCIdx).getReg();
865 if (!regBKilled && isKilled(*mi, regC, MRI, TII))
866 // If C dies but B does not, swap the B and C operands.
867 // This makes the live ranges of A and C joinable.
868 TryCommute = true;
869 else if (isProfitableToCommute(regB, regC, mi, mbbi, Dist)) {
870 TryCommute = true;
871 AggressiveCommute = true;
872 }
873 }
874 }
875
876 // If it's profitable to commute, try to do so.
877 if (TryCommute && CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
878 ++NumCommuted;
879 if (AggressiveCommute)
880 ++NumAggrCommuted;
881 return false;
882 }
883
884 if (TID.isConvertibleTo3Addr()) {
885 // This instruction is potentially convertible to a true
886 // three-address instruction. Check if it is profitable.
887 if (!regBKilled || isProfitableToConv3Addr(regA)) {
888 // Try to convert it.
889 if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) {
890 ++NumConvertedTo3Addr;
891 return true; // Done with this instruction.
892 }
893 }
894 }
895 return false;
896}
897
Bill Wendling637980e2008-05-10 00:12:52 +0000898/// runOnMachineFunction - Reduce two-address instructions to two operands.
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000899///
Chris Lattner163c1e72004-01-31 21:14:04 +0000900bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
Chris Lattner6456d382009-08-23 03:20:44 +0000901 DEBUG(errs() << "Machine Function\n");
Misha Brukman75fa4e42004-07-22 15:26:23 +0000902 const TargetMachine &TM = MF.getTarget();
Evan Cheng875357d2008-03-13 06:37:55 +0000903 MRI = &MF.getRegInfo();
904 TII = TM.getInstrInfo();
905 TRI = TM.getRegisterInfo();
Duncan Sands1465d612009-01-28 13:14:17 +0000906 LV = getAnalysisIfAvailable<LiveVariables>();
Dan Gohmana70dca12009-10-09 23:27:56 +0000907 AA = &getAnalysis<AliasAnalysis>();
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000908
Misha Brukman75fa4e42004-07-22 15:26:23 +0000909 bool MadeChange = false;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000910
Chris Lattner6456d382009-08-23 03:20:44 +0000911 DEBUG(errs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000912 DEBUG(errs() << "********** Function: "
913 << MF.getFunction()->getName() << '\n');
Alkis Evlogimenos3a9986f2004-02-18 00:35:06 +0000914
Evan Cheng7543e582008-06-18 07:49:14 +0000915 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
916 BitVector ReMatRegs;
917 ReMatRegs.resize(MRI->getLastVirtReg()+1);
918
Bob Wilsoncc80df92009-09-03 20:58:42 +0000919 typedef DenseMap<unsigned, SmallVector<std::pair<unsigned, unsigned>, 4> >
920 TiedOperandMap;
921 TiedOperandMap TiedOperands(4);
922
Evan Cheng870b8072009-03-01 02:03:43 +0000923 SmallPtrSet<MachineInstr*, 8> Processed;
Misha Brukman75fa4e42004-07-22 15:26:23 +0000924 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
925 mbbi != mbbe; ++mbbi) {
Evan Cheng7543e582008-06-18 07:49:14 +0000926 unsigned Dist = 0;
927 DistanceMap.clear();
Evan Cheng870b8072009-03-01 02:03:43 +0000928 SrcRegMap.clear();
929 DstRegMap.clear();
930 Processed.clear();
Misha Brukman75fa4e42004-07-22 15:26:23 +0000931 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
Evan Cheng7a963fa2008-03-27 01:27:25 +0000932 mi != me; ) {
933 MachineBasicBlock::iterator nmi = next(mi);
Chris Lattner749c6f62008-01-07 07:27:27 +0000934 const TargetInstrDesc &TID = mi->getDesc();
Evan Cheng360c2dd2006-11-01 23:06:55 +0000935 bool FirstTied = true;
Bill Wendling637980e2008-05-10 00:12:52 +0000936
Evan Cheng7543e582008-06-18 07:49:14 +0000937 DistanceMap.insert(std::make_pair(mi, ++Dist));
Evan Cheng870b8072009-03-01 02:03:43 +0000938
939 ProcessCopy(&*mi, &*mbbi, Processed);
940
Bob Wilsoncc80df92009-09-03 20:58:42 +0000941 // First scan through all the tied register uses in this instruction
942 // and record a list of pairs of tied operands for each register.
Evan Chengfb112882009-03-23 08:01:15 +0000943 unsigned NumOps = (mi->getOpcode() == TargetInstrInfo::INLINEASM)
944 ? mi->getNumOperands() : TID.getNumOperands();
Bob Wilsoncc80df92009-09-03 20:58:42 +0000945 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
946 unsigned DstIdx = 0;
947 if (!mi->isRegTiedToDefOperand(SrcIdx, &DstIdx))
Evan Cheng360c2dd2006-11-01 23:06:55 +0000948 continue;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000949
Evan Cheng360c2dd2006-11-01 23:06:55 +0000950 if (FirstTied) {
Bob Wilsoncc80df92009-09-03 20:58:42 +0000951 FirstTied = false;
Evan Cheng360c2dd2006-11-01 23:06:55 +0000952 ++NumTwoAddressInstrs;
Chris Lattner6456d382009-08-23 03:20:44 +0000953 DEBUG(errs() << '\t' << *mi);
Evan Cheng360c2dd2006-11-01 23:06:55 +0000954 }
Bill Wendling637980e2008-05-10 00:12:52 +0000955
Bob Wilsoncc80df92009-09-03 20:58:42 +0000956 assert(mi->getOperand(SrcIdx).isReg() &&
957 mi->getOperand(SrcIdx).getReg() &&
958 mi->getOperand(SrcIdx).isUse() &&
959 "two address instruction invalid");
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000960
Bob Wilsoncc80df92009-09-03 20:58:42 +0000961 unsigned regB = mi->getOperand(SrcIdx).getReg();
962 TiedOperandMap::iterator OI = TiedOperands.find(regB);
963 if (OI == TiedOperands.end()) {
964 SmallVector<std::pair<unsigned, unsigned>, 4> TiedPair;
965 OI = TiedOperands.insert(std::make_pair(regB, TiedPair)).first;
966 }
967 OI->second.push_back(std::make_pair(SrcIdx, DstIdx));
968 }
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000969
Bob Wilsoncc80df92009-09-03 20:58:42 +0000970 // Now iterate over the information collected above.
971 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
972 OE = TiedOperands.end(); OI != OE; ++OI) {
973 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs = OI->second;
Evan Cheng360c2dd2006-11-01 23:06:55 +0000974
Bob Wilsoncc80df92009-09-03 20:58:42 +0000975 // If the instruction has a single pair of tied operands, try some
976 // transformations that may either eliminate the tied operands or
977 // improve the opportunities for coalescing away the register copy.
978 if (TiedOperands.size() == 1 && TiedPairs.size() == 1) {
979 unsigned SrcIdx = TiedPairs[0].first;
980 unsigned DstIdx = TiedPairs[0].second;
Bob Wilson43449792009-08-31 21:54:55 +0000981
Bob Wilsoncc80df92009-09-03 20:58:42 +0000982 // If the registers are already equal, nothing needs to be done.
983 if (mi->getOperand(SrcIdx).getReg() ==
984 mi->getOperand(DstIdx).getReg())
985 break; // Done with this instruction.
986
987 if (TryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist))
988 break; // The tied operands have been eliminated.
989 }
990
991 bool RemovedKillFlag = false;
992 bool AllUsesCopied = true;
993 unsigned LastCopiedReg = 0;
994 unsigned regB = OI->first;
995 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
996 unsigned SrcIdx = TiedPairs[tpi].first;
997 unsigned DstIdx = TiedPairs[tpi].second;
998 unsigned regA = mi->getOperand(DstIdx).getReg();
999 // Grab regB from the instruction because it may have changed if the
1000 // instruction was commuted.
1001 regB = mi->getOperand(SrcIdx).getReg();
1002
1003 if (regA == regB) {
1004 // The register is tied to multiple destinations (or else we would
1005 // not have continued this far), but this use of the register
1006 // already matches the tied destination. Leave it.
1007 AllUsesCopied = false;
1008 continue;
1009 }
1010 LastCopiedReg = regA;
1011
1012 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1013 "cannot make instruction into two-address form");
Chris Lattner6b507672004-01-31 21:21:43 +00001014
Chris Lattner1e313632004-07-21 23:17:57 +00001015#ifndef NDEBUG
Bob Wilsoncc80df92009-09-03 20:58:42 +00001016 // First, verify that we don't have a use of "a" in the instruction
1017 // (a = b + a for example) because our transformation will not
1018 // work. This should never occur because we are in SSA form.
1019 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
1020 assert(i == DstIdx ||
1021 !mi->getOperand(i).isReg() ||
1022 mi->getOperand(i).getReg() != regA);
Chris Lattner1e313632004-07-21 23:17:57 +00001023#endif
Alkis Evlogimenos14be6402004-02-04 22:17:40 +00001024
Bob Wilsoncc80df92009-09-03 20:58:42 +00001025 // Emit a copy or rematerialize the definition.
1026 const TargetRegisterClass *rc = MRI->getRegClass(regB);
1027 MachineInstr *DefMI = MRI->getVRegDef(regB);
1028 // If it's safe and profitable, remat the definition instead of
1029 // copying it.
1030 if (DefMI &&
1031 DefMI->getDesc().isAsCheapAsAMove() &&
Dan Gohmana70dca12009-10-09 23:27:56 +00001032 DefMI->isSafeToReMat(TII, regB, AA) &&
Bob Wilsoncc80df92009-09-03 20:58:42 +00001033 isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){
1034 DEBUG(errs() << "2addr: REMATTING : " << *DefMI << "\n");
1035 unsigned regASubIdx = mi->getOperand(DstIdx).getSubReg();
1036 TII->reMaterialize(*mbbi, mi, regA, regASubIdx, DefMI);
1037 ReMatRegs.set(regB);
1038 ++NumReMats;
Bob Wilson71124f62009-09-01 04:18:40 +00001039 } else {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001040 bool Emitted = TII->copyRegToReg(*mbbi, mi, regA, regB, rc, rc);
1041 (void)Emitted;
1042 assert(Emitted && "Unable to issue a copy instruction!\n");
1043 }
1044
1045 MachineBasicBlock::iterator prevMI = prior(mi);
1046 // Update DistanceMap.
1047 DistanceMap.insert(std::make_pair(prevMI, Dist));
1048 DistanceMap[mi] = ++Dist;
1049
1050 DEBUG(errs() << "\t\tprepend:\t" << *prevMI);
1051
1052 MachineOperand &MO = mi->getOperand(SrcIdx);
1053 assert(MO.isReg() && MO.getReg() == regB && MO.isUse() &&
1054 "inconsistent operand info for 2-reg pass");
1055 if (MO.isKill()) {
1056 MO.setIsKill(false);
1057 RemovedKillFlag = true;
1058 }
1059 MO.setReg(regA);
1060 }
1061
1062 if (AllUsesCopied) {
1063 // Replace other (un-tied) uses of regB with LastCopiedReg.
1064 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1065 MachineOperand &MO = mi->getOperand(i);
1066 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1067 if (MO.isKill()) {
1068 MO.setIsKill(false);
1069 RemovedKillFlag = true;
1070 }
1071 MO.setReg(LastCopiedReg);
1072 }
1073 }
1074
1075 // Update live variables for regB.
1076 if (RemovedKillFlag && LV && LV->getVarInfo(regB).removeKill(mi))
1077 LV->addVirtualRegisterKilled(regB, prior(mi));
1078
1079 } else if (RemovedKillFlag) {
1080 // Some tied uses of regB matched their destination registers, so
1081 // regB is still used in this instruction, but a kill flag was
1082 // removed from a different tied use of regB, so now we need to add
1083 // a kill flag to one of the remaining uses of regB.
1084 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1085 MachineOperand &MO = mi->getOperand(i);
1086 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1087 MO.setIsKill(true);
1088 break;
Bob Wilson71124f62009-09-01 04:18:40 +00001089 }
1090 }
Bob Wilson43449792009-08-31 21:54:55 +00001091 }
Bob Wilsoncc80df92009-09-03 20:58:42 +00001092
Bob Wilson43449792009-08-31 21:54:55 +00001093 MadeChange = true;
1094
1095 DEBUG(errs() << "\t\trewrite to:\t" << *mi);
Misha Brukman75fa4e42004-07-22 15:26:23 +00001096 }
Bill Wendling637980e2008-05-10 00:12:52 +00001097
Bob Wilsoncc80df92009-09-03 20:58:42 +00001098 // Clear TiedOperands here instead of at the top of the loop
1099 // since most instructions do not have tied operands.
1100 TiedOperands.clear();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001101 mi = nmi;
Misha Brukman75fa4e42004-07-22 15:26:23 +00001102 }
1103 }
1104
Evan Cheng601ca4b2008-06-25 01:16:38 +00001105 // Some remat'ed instructions are dead.
1106 int VReg = ReMatRegs.find_first();
1107 while (VReg != -1) {
1108 if (MRI->use_empty(VReg)) {
1109 MachineInstr *DefMI = MRI->getVRegDef(VReg);
1110 DefMI->eraseFromParent();
Bill Wendlinga16157a2008-05-26 05:49:49 +00001111 }
Evan Cheng601ca4b2008-06-25 01:16:38 +00001112 VReg = ReMatRegs.find_next(VReg);
Bill Wendling48f7f232008-05-26 05:18:34 +00001113 }
1114
Misha Brukman75fa4e42004-07-22 15:26:23 +00001115 return MadeChange;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001116}