blob: 0ba38433c220bc0289785ef2d1c5643683fd545b [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,
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000115 MachineFunction::iterator &mbbi, unsigned Dist);
Bob Wilson326f4382009-09-01 22:51:08 +0000116
Bob Wilsoncc80df92009-09-03 20:58:42 +0000117 bool TryInstructionTransform(MachineBasicBlock::iterator &mi,
118 MachineBasicBlock::iterator &nmi,
119 MachineFunction::iterator &mbbi,
120 unsigned SrcIdx, unsigned DstIdx,
121 unsigned Dist);
122
Evan Cheng870b8072009-03-01 02:03:43 +0000123 void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
124 SmallPtrSet<MachineInstr*, 8> &Processed);
Evan Cheng3a3cce52009-08-07 00:28:58 +0000125
Evan Cheng875357d2008-03-13 06:37:55 +0000126 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000127 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +0000128 TwoAddressInstructionPass() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000129
Bill Wendling637980e2008-05-10 00:12:52 +0000130 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +0000131 AU.setPreservesCFG();
Dan Gohmana70dca12009-10-09 23:27:56 +0000132 AU.addRequired<AliasAnalysis>();
Bill Wendling637980e2008-05-10 00:12:52 +0000133 AU.addPreserved<LiveVariables>();
134 AU.addPreservedID(MachineLoopInfoID);
135 AU.addPreservedID(MachineDominatorsID);
Owen Anderson95dad832008-10-07 20:22:28 +0000136 if (StrongPHIElim)
137 AU.addPreservedID(StrongPHIEliminationID);
138 else
139 AU.addPreservedID(PHIEliminationID);
Bill Wendling637980e2008-05-10 00:12:52 +0000140 MachineFunctionPass::getAnalysisUsage(AU);
141 }
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000142
Bill Wendling637980e2008-05-10 00:12:52 +0000143 /// runOnMachineFunction - Pass entry point.
Misha Brukman75fa4e42004-07-22 15:26:23 +0000144 bool runOnMachineFunction(MachineFunction&);
145 };
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000146}
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000147
Dan Gohman844731a2008-05-13 00:00:25 +0000148char TwoAddressInstructionPass::ID = 0;
149static RegisterPass<TwoAddressInstructionPass>
150X("twoaddressinstruction", "Two-Address instruction pass");
151
Dan Gohman6ddba2b2008-05-13 02:05:11 +0000152const PassInfo *const llvm::TwoAddressInstructionPassID = &X;
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000153
Evan Cheng875357d2008-03-13 06:37:55 +0000154/// Sink3AddrInstruction - A two-address instruction has been converted to a
155/// three-address instruction to avoid clobbering a register. Try to sink it
Bill Wendling637980e2008-05-10 00:12:52 +0000156/// past the instruction that would kill the above mentioned register to reduce
157/// register pressure.
Evan Cheng875357d2008-03-13 06:37:55 +0000158bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
159 MachineInstr *MI, unsigned SavedReg,
160 MachineBasicBlock::iterator OldPos) {
161 // Check if it's safe to move this instruction.
162 bool SeenStore = true; // Be conservative.
Evan Chengac1abde2010-03-02 19:03:01 +0000163 if (!MI->isSafeToMove(TII, AA, SeenStore))
Evan Cheng875357d2008-03-13 06:37:55 +0000164 return false;
165
166 unsigned DefReg = 0;
167 SmallSet<unsigned, 4> UseRegs;
Bill Wendling637980e2008-05-10 00:12:52 +0000168
Evan Cheng875357d2008-03-13 06:37:55 +0000169 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
170 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000171 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000172 continue;
173 unsigned MOReg = MO.getReg();
174 if (!MOReg)
175 continue;
176 if (MO.isUse() && MOReg != SavedReg)
177 UseRegs.insert(MO.getReg());
178 if (!MO.isDef())
179 continue;
180 if (MO.isImplicit())
181 // Don't try to move it if it implicitly defines a register.
182 return false;
183 if (DefReg)
184 // For now, don't move any instructions that define multiple registers.
185 return false;
186 DefReg = MO.getReg();
187 }
188
189 // Find the instruction that kills SavedReg.
190 MachineInstr *KillMI = NULL;
191 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SavedReg),
192 UE = MRI->use_end(); UI != UE; ++UI) {
193 MachineOperand &UseMO = UI.getOperand();
194 if (!UseMO.isKill())
195 continue;
196 KillMI = UseMO.getParent();
197 break;
198 }
Bill Wendling637980e2008-05-10 00:12:52 +0000199
Dan Gohman97121ba2009-04-08 00:15:30 +0000200 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI)
Evan Cheng875357d2008-03-13 06:37:55 +0000201 return false;
202
Bill Wendling637980e2008-05-10 00:12:52 +0000203 // If any of the definitions are used by another instruction between the
204 // position and the kill use, then it's not safe to sink it.
205 //
206 // FIXME: This can be sped up if there is an easy way to query whether an
Evan Cheng7543e582008-06-18 07:49:14 +0000207 // instruction is before or after another instruction. Then we can use
Bill Wendling637980e2008-05-10 00:12:52 +0000208 // MachineRegisterInfo def / use instead.
Evan Cheng875357d2008-03-13 06:37:55 +0000209 MachineOperand *KillMO = NULL;
210 MachineBasicBlock::iterator KillPos = KillMI;
211 ++KillPos;
Bill Wendling637980e2008-05-10 00:12:52 +0000212
Evan Cheng7543e582008-06-18 07:49:14 +0000213 unsigned NumVisited = 0;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000214 for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
Evan Cheng875357d2008-03-13 06:37:55 +0000215 MachineInstr *OtherMI = I;
Dale Johannesen3bfef032010-02-11 18:22:31 +0000216 // DBG_VALUE cannot be counted against the limit.
217 if (OtherMI->isDebugValue())
218 continue;
Evan Cheng7543e582008-06-18 07:49:14 +0000219 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
220 return false;
221 ++NumVisited;
Evan Cheng875357d2008-03-13 06:37:55 +0000222 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
223 MachineOperand &MO = OtherMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000224 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000225 continue;
226 unsigned MOReg = MO.getReg();
227 if (!MOReg)
228 continue;
229 if (DefReg == MOReg)
230 return false;
Bill Wendling637980e2008-05-10 00:12:52 +0000231
Evan Cheng875357d2008-03-13 06:37:55 +0000232 if (MO.isKill()) {
233 if (OtherMI == KillMI && MOReg == SavedReg)
Evan Cheng7543e582008-06-18 07:49:14 +0000234 // Save the operand that kills the register. We want to unset the kill
235 // marker if we can sink MI past it.
Evan Cheng875357d2008-03-13 06:37:55 +0000236 KillMO = &MO;
237 else if (UseRegs.count(MOReg))
238 // One of the uses is killed before the destination.
239 return false;
240 }
241 }
242 }
243
Evan Cheng875357d2008-03-13 06:37:55 +0000244 // Update kill and LV information.
245 KillMO->setIsKill(false);
246 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
247 KillMO->setIsKill(true);
Owen Anderson802af112008-07-02 21:28:58 +0000248
Evan Cheng9f1c8312008-07-03 09:09:37 +0000249 if (LV)
250 LV->replaceKillInstruction(SavedReg, KillMI, MI);
Evan Cheng875357d2008-03-13 06:37:55 +0000251
252 // Move instruction to its destination.
253 MBB->remove(MI);
254 MBB->insert(KillPos, MI);
255
256 ++Num3AddrSunk;
257 return true;
258}
259
Evan Cheng7543e582008-06-18 07:49:14 +0000260/// isTwoAddrUse - Return true if the specified MI is using the specified
261/// register as a two-address operand.
262static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
263 const TargetInstrDesc &TID = UseMI->getDesc();
264 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
265 MachineOperand &MO = UseMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000266 if (MO.isReg() && MO.getReg() == Reg &&
Evan Chenga24752f2009-03-19 20:30:06 +0000267 (MO.isDef() || UseMI->isRegTiedToDefOperand(i)))
Evan Cheng7543e582008-06-18 07:49:14 +0000268 // Earlier use is a two-address one.
269 return true;
270 }
271 return false;
272}
273
274/// isProfitableToReMat - Return true if the heuristics determines it is likely
275/// to be profitable to re-materialize the definition of Reg rather than copy
276/// the register.
277bool
278TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
Evan Cheng870b8072009-03-01 02:03:43 +0000279 const TargetRegisterClass *RC,
280 MachineInstr *MI, MachineInstr *DefMI,
281 MachineBasicBlock *MBB, unsigned Loc) {
Evan Cheng7543e582008-06-18 07:49:14 +0000282 bool OtherUse = false;
283 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
284 UE = MRI->use_end(); UI != UE; ++UI) {
285 MachineOperand &UseMO = UI.getOperand();
Evan Cheng7543e582008-06-18 07:49:14 +0000286 MachineInstr *UseMI = UseMO.getParent();
Evan Cheng601ca4b2008-06-25 01:16:38 +0000287 MachineBasicBlock *UseMBB = UseMI->getParent();
288 if (UseMBB == MBB) {
289 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
290 if (DI != DistanceMap.end() && DI->second == Loc)
291 continue; // Current use.
292 OtherUse = true;
293 // There is at least one other use in the MBB that will clobber the
294 // register.
295 if (isTwoAddrUse(UseMI, Reg))
296 return true;
297 }
Evan Cheng7543e582008-06-18 07:49:14 +0000298 }
Evan Cheng601ca4b2008-06-25 01:16:38 +0000299
300 // If other uses in MBB are not two-address uses, then don't remat.
301 if (OtherUse)
302 return false;
303
304 // No other uses in the same block, remat if it's defined in the same
305 // block so it does not unnecessarily extend the live range.
306 return MBB == DefMI->getParent();
Evan Cheng7543e582008-06-18 07:49:14 +0000307}
308
Evan Chengd498c8f2009-01-25 03:53:59 +0000309/// NoUseAfterLastDef - Return true if there are no intervening uses between the
310/// last instruction in the MBB that defines the specified register and the
311/// two-address instruction which is being processed. It also returns the last
312/// def location by reference
313bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
Evan Cheng870b8072009-03-01 02:03:43 +0000314 MachineBasicBlock *MBB, unsigned Dist,
315 unsigned &LastDef) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000316 LastDef = 0;
317 unsigned LastUse = Dist;
318 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
319 E = MRI->reg_end(); I != E; ++I) {
320 MachineOperand &MO = I.getOperand();
321 MachineInstr *MI = MO.getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000322 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesend94998f2010-02-09 02:01:46 +0000323 continue;
Evan Chengd498c8f2009-01-25 03:53:59 +0000324 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
325 if (DI == DistanceMap.end())
326 continue;
327 if (MO.isUse() && DI->second < LastUse)
328 LastUse = DI->second;
329 if (MO.isDef() && DI->second > LastDef)
330 LastDef = DI->second;
331 }
332
333 return !(LastUse > LastDef && LastUse < Dist);
334}
335
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000336MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg,
337 MachineBasicBlock *MBB,
338 unsigned Dist) {
Lang Hamesa7c9dea2009-05-14 04:26:30 +0000339 unsigned LastUseDist = 0;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000340 MachineInstr *LastUse = 0;
341 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
342 E = MRI->reg_end(); I != E; ++I) {
343 MachineOperand &MO = I.getOperand();
344 MachineInstr *MI = MO.getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000345 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesend94998f2010-02-09 02:01:46 +0000346 continue;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000347 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
348 if (DI == DistanceMap.end())
349 continue;
Lang Hamesa7c9dea2009-05-14 04:26:30 +0000350 if (DI->second >= Dist)
351 continue;
352
353 if (MO.isUse() && DI->second > LastUseDist) {
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000354 LastUse = DI->first;
355 LastUseDist = DI->second;
356 }
357 }
358 return LastUse;
359}
360
Evan Cheng870b8072009-03-01 02:03:43 +0000361/// isCopyToReg - Return true if the specified MI is a copy instruction or
362/// a extract_subreg instruction. It also returns the source and destination
363/// registers and whether they are physical registers by reference.
364static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
365 unsigned &SrcReg, unsigned &DstReg,
366 bool &IsSrcPhys, bool &IsDstPhys) {
367 SrcReg = 0;
368 DstReg = 0;
369 unsigned SrcSubIdx, DstSubIdx;
370 if (!TII->isMoveInstr(MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
Chris Lattner518bb532010-02-09 19:54:29 +0000371 if (MI.isExtractSubreg()) {
Evan Cheng870b8072009-03-01 02:03:43 +0000372 DstReg = MI.getOperand(0).getReg();
373 SrcReg = MI.getOperand(1).getReg();
Chris Lattner518bb532010-02-09 19:54:29 +0000374 } else if (MI.isInsertSubreg()) {
Evan Cheng870b8072009-03-01 02:03:43 +0000375 DstReg = MI.getOperand(0).getReg();
376 SrcReg = MI.getOperand(2).getReg();
Chris Lattner518bb532010-02-09 19:54:29 +0000377 } else if (MI.isSubregToReg()) {
Dan Gohman97121ba2009-04-08 00:15:30 +0000378 DstReg = MI.getOperand(0).getReg();
379 SrcReg = MI.getOperand(2).getReg();
Evan Cheng870b8072009-03-01 02:03:43 +0000380 }
381 }
382
383 if (DstReg) {
384 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
385 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
386 return true;
387 }
388 return false;
389}
390
Dan Gohman97121ba2009-04-08 00:15:30 +0000391/// isKilled - Test if the given register value, which is used by the given
392/// instruction, is killed by the given instruction. This looks through
393/// coalescable copies to see if the original value is potentially not killed.
394///
395/// For example, in this code:
396///
397/// %reg1034 = copy %reg1024
398/// %reg1035 = copy %reg1025<kill>
399/// %reg1036 = add %reg1034<kill>, %reg1035<kill>
400///
401/// %reg1034 is not considered to be killed, since it is copied from a
402/// register which is not killed. Treating it as not killed lets the
403/// normal heuristics commute the (two-address) add, which lets
404/// coalescing eliminate the extra copy.
405///
406static bool isKilled(MachineInstr &MI, unsigned Reg,
407 const MachineRegisterInfo *MRI,
408 const TargetInstrInfo *TII) {
409 MachineInstr *DefMI = &MI;
410 for (;;) {
411 if (!DefMI->killsRegister(Reg))
412 return false;
413 if (TargetRegisterInfo::isPhysicalRegister(Reg))
414 return true;
415 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
416 // If there are multiple defs, we can't do a simple analysis, so just
417 // go with what the kill flag says.
Chris Lattner7896c9f2009-12-03 00:50:42 +0000418 if (llvm::next(Begin) != MRI->def_end())
Dan Gohman97121ba2009-04-08 00:15:30 +0000419 return true;
420 DefMI = &*Begin;
421 bool IsSrcPhys, IsDstPhys;
422 unsigned SrcReg, DstReg;
423 // If the def is something other than a copy, then it isn't going to
424 // be coalesced, so follow the kill flag.
425 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
426 return true;
427 Reg = SrcReg;
428 }
429}
430
Evan Cheng870b8072009-03-01 02:03:43 +0000431/// isTwoAddrUse - Return true if the specified MI uses the specified register
432/// as a two-address use. If so, return the destination register by reference.
433static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
434 const TargetInstrDesc &TID = MI.getDesc();
Chris Lattner518bb532010-02-09 19:54:29 +0000435 unsigned NumOps = MI.isInlineAsm() ? MI.getNumOperands():TID.getNumOperands();
Evan Chenge6f350d2009-03-30 21:34:07 +0000436 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng870b8072009-03-01 02:03:43 +0000437 const MachineOperand &MO = MI.getOperand(i);
438 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
439 continue;
Evan Chenga24752f2009-03-19 20:30:06 +0000440 unsigned ti;
441 if (MI.isRegTiedToDefOperand(i, &ti)) {
Evan Cheng870b8072009-03-01 02:03:43 +0000442 DstReg = MI.getOperand(ti).getReg();
443 return true;
444 }
445 }
446 return false;
447}
448
449/// findOnlyInterestingUse - Given a register, if has a single in-basic block
450/// use, return the use instruction if it's a copy or a two-address use.
451static
452MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
453 MachineRegisterInfo *MRI,
454 const TargetInstrInfo *TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000455 bool &IsCopy,
Evan Cheng870b8072009-03-01 02:03:43 +0000456 unsigned &DstReg, bool &IsDstPhys) {
Dale Johannesenb8ff9342010-02-10 21:47:48 +0000457 MachineRegisterInfo::use_nodbg_iterator UI = MRI->use_nodbg_begin(Reg);
458 if (UI == MRI->use_nodbg_end())
Evan Cheng870b8072009-03-01 02:03:43 +0000459 return 0;
460 MachineInstr &UseMI = *UI;
Dale Johannesenb8ff9342010-02-10 21:47:48 +0000461 if (++UI != MRI->use_nodbg_end())
Evan Cheng870b8072009-03-01 02:03:43 +0000462 // More than one use.
463 return 0;
464 if (UseMI.getParent() != MBB)
465 return 0;
466 unsigned SrcReg;
467 bool IsSrcPhys;
Evan Cheng87d696a2009-04-14 00:32:25 +0000468 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
469 IsCopy = true;
Evan Cheng870b8072009-03-01 02:03:43 +0000470 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000471 }
Evan Cheng870b8072009-03-01 02:03:43 +0000472 IsDstPhys = false;
Evan Cheng87d696a2009-04-14 00:32:25 +0000473 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
474 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng870b8072009-03-01 02:03:43 +0000475 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000476 }
Evan Cheng870b8072009-03-01 02:03:43 +0000477 return 0;
478}
479
480/// getMappedReg - Return the physical register the specified virtual register
481/// might be mapped to.
482static unsigned
483getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
484 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
485 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
486 if (SI == RegMap.end())
487 return 0;
488 Reg = SI->second;
489 }
490 if (TargetRegisterInfo::isPhysicalRegister(Reg))
491 return Reg;
492 return 0;
493}
494
495/// regsAreCompatible - Return true if the two registers are equal or aliased.
496///
497static bool
498regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
499 if (RegA == RegB)
500 return true;
501 if (!RegA || !RegB)
502 return false;
503 return TRI->regsOverlap(RegA, RegB);
504}
505
506
Evan Chengd498c8f2009-01-25 03:53:59 +0000507/// isProfitableToReMat - Return true if it's potentially profitable to commute
508/// the two-address instruction that's being processed.
509bool
510TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC,
Evan Cheng870b8072009-03-01 02:03:43 +0000511 MachineInstr *MI, MachineBasicBlock *MBB,
512 unsigned Dist) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000513 // Determine if it's profitable to commute this two address instruction. In
514 // general, we want no uses between this instruction and the definition of
515 // the two-address register.
516 // e.g.
517 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
518 // %reg1029<def> = MOV8rr %reg1028
519 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
520 // insert => %reg1030<def> = MOV8rr %reg1028
521 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
522 // In this case, it might not be possible to coalesce the second MOV8rr
523 // instruction if the first one is coalesced. So it would be profitable to
524 // commute it:
525 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
526 // %reg1029<def> = MOV8rr %reg1028
527 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
528 // insert => %reg1030<def> = MOV8rr %reg1029
529 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
530
531 if (!MI->killsRegister(regC))
532 return false;
533
534 // Ok, we have something like:
535 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
536 // let's see if it's worth commuting it.
537
Evan Cheng870b8072009-03-01 02:03:43 +0000538 // Look for situations like this:
539 // %reg1024<def> = MOV r1
540 // %reg1025<def> = MOV r0
541 // %reg1026<def> = ADD %reg1024, %reg1025
542 // r0 = MOV %reg1026
543 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
544 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
545 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
546 unsigned ToRegB = getMappedReg(regB, DstRegMap);
547 unsigned ToRegC = getMappedReg(regC, DstRegMap);
548 if (!regsAreCompatible(FromRegB, ToRegB, TRI) &&
549 (regsAreCompatible(FromRegB, ToRegC, TRI) ||
550 regsAreCompatible(FromRegC, ToRegB, TRI)))
551 return true;
552
Evan Chengd498c8f2009-01-25 03:53:59 +0000553 // If there is a use of regC between its last def (could be livein) and this
554 // instruction, then bail.
555 unsigned LastDefC = 0;
Evan Cheng870b8072009-03-01 02:03:43 +0000556 if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
Evan Chengd498c8f2009-01-25 03:53:59 +0000557 return false;
558
559 // If there is a use of regB between its last def (could be livein) and this
560 // instruction, then go ahead and make this transformation.
561 unsigned LastDefB = 0;
Evan Cheng870b8072009-03-01 02:03:43 +0000562 if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
Evan Chengd498c8f2009-01-25 03:53:59 +0000563 return true;
564
565 // Since there are no intervening uses for both registers, then commute
566 // if the def of regC is closer. Its live interval is shorter.
567 return LastDefB && LastDefC && LastDefC > LastDefB;
568}
569
Evan Cheng81913712009-01-23 23:27:33 +0000570/// CommuteInstruction - Commute a two-address instruction and update the basic
571/// block, distance map, and live variables if needed. Return true if it is
572/// successful.
573bool
574TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
Evan Cheng870b8072009-03-01 02:03:43 +0000575 MachineFunction::iterator &mbbi,
576 unsigned RegB, unsigned RegC, unsigned Dist) {
Evan Cheng81913712009-01-23 23:27:33 +0000577 MachineInstr *MI = mi;
David Greeneeb00b182010-01-05 01:24:21 +0000578 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
Evan Cheng81913712009-01-23 23:27:33 +0000579 MachineInstr *NewMI = TII->commuteInstruction(MI);
580
581 if (NewMI == 0) {
David Greeneeb00b182010-01-05 01:24:21 +0000582 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
Evan Cheng81913712009-01-23 23:27:33 +0000583 return false;
584 }
585
David Greeneeb00b182010-01-05 01:24:21 +0000586 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
Evan Cheng81913712009-01-23 23:27:33 +0000587 // If the instruction changed to commute it, update livevar.
588 if (NewMI != MI) {
589 if (LV)
590 // Update live variables
591 LV->replaceKillInstruction(RegC, MI, NewMI);
592
593 mbbi->insert(mi, NewMI); // Insert the new inst
594 mbbi->erase(mi); // Nuke the old inst.
595 mi = NewMI;
596 DistanceMap.insert(std::make_pair(NewMI, Dist));
597 }
Evan Cheng870b8072009-03-01 02:03:43 +0000598
599 // Update source register map.
600 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
601 if (FromRegC) {
602 unsigned RegA = MI->getOperand(0).getReg();
603 SrcRegMap[RegA] = FromRegC;
604 }
605
Evan Cheng81913712009-01-23 23:27:33 +0000606 return true;
607}
608
Evan Chenge6f350d2009-03-30 21:34:07 +0000609/// isProfitableToConv3Addr - Return true if it is profitable to convert the
610/// given 2-address instruction to a 3-address one.
611bool
612TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA) {
613 // Look for situations like this:
614 // %reg1024<def> = MOV r1
615 // %reg1025<def> = MOV r0
616 // %reg1026<def> = ADD %reg1024, %reg1025
617 // r2 = MOV %reg1026
618 // Turn ADD into a 3-address instruction to avoid a copy.
619 unsigned FromRegA = getMappedReg(RegA, SrcRegMap);
620 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
621 return (FromRegA && ToRegA && !regsAreCompatible(FromRegA, ToRegA, TRI));
622}
623
624/// ConvertInstTo3Addr - Convert the specified two-address instruction into a
625/// three address one. Return true if this transformation was successful.
626bool
627TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
628 MachineBasicBlock::iterator &nmi,
629 MachineFunction::iterator &mbbi,
630 unsigned RegB, unsigned Dist) {
631 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
632 if (NewMI) {
David Greeneeb00b182010-01-05 01:24:21 +0000633 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
634 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
Evan Chenge6f350d2009-03-30 21:34:07 +0000635 bool Sunk = false;
636
637 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
638 // FIXME: Temporary workaround. If the new instruction doesn't
639 // uses RegB, convertToThreeAddress must have created more
640 // then one instruction.
641 Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
642
643 mbbi->erase(mi); // Nuke the old inst.
644
645 if (!Sunk) {
646 DistanceMap.insert(std::make_pair(NewMI, Dist));
647 mi = NewMI;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000648 nmi = llvm::next(mi);
Evan Chenge6f350d2009-03-30 21:34:07 +0000649 }
650 return true;
651 }
652
653 return false;
654}
655
Evan Cheng870b8072009-03-01 02:03:43 +0000656/// ProcessCopy - If the specified instruction is not yet processed, process it
657/// if it's a copy. For a copy instruction, we find the physical registers the
658/// source and destination registers might be mapped to. These are kept in
659/// point-to maps used to determine future optimizations. e.g.
660/// v1024 = mov r0
661/// v1025 = mov r1
662/// v1026 = add v1024, v1025
663/// r1 = mov r1026
664/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
665/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
666/// potentially joined with r1 on the output side. It's worthwhile to commute
667/// 'add' to eliminate a copy.
668void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
669 MachineBasicBlock *MBB,
670 SmallPtrSet<MachineInstr*, 8> &Processed) {
671 if (Processed.count(MI))
672 return;
673
674 bool IsSrcPhys, IsDstPhys;
675 unsigned SrcReg, DstReg;
676 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
677 return;
678
679 if (IsDstPhys && !IsSrcPhys)
680 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
681 else if (!IsDstPhys && IsSrcPhys) {
Evan Cheng3005ed62009-04-13 20:04:24 +0000682 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
683 if (!isNew)
684 assert(SrcRegMap[DstReg] == SrcReg &&
685 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000686
687 SmallVector<unsigned, 4> VirtRegPairs;
Evan Cheng87d696a2009-04-14 00:32:25 +0000688 bool IsCopy = false;
Evan Cheng870b8072009-03-01 02:03:43 +0000689 unsigned NewReg = 0;
690 while (MachineInstr *UseMI = findOnlyInterestingUse(DstReg, MBB, MRI,TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000691 IsCopy, NewReg, IsDstPhys)) {
692 if (IsCopy) {
693 if (!Processed.insert(UseMI))
Evan Cheng870b8072009-03-01 02:03:43 +0000694 break;
695 }
696
697 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
698 if (DI != DistanceMap.end())
699 // Earlier in the same MBB.Reached via a back edge.
700 break;
701
702 if (IsDstPhys) {
703 VirtRegPairs.push_back(NewReg);
704 break;
705 }
706 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, DstReg)).second;
Evan Cheng3005ed62009-04-13 20:04:24 +0000707 if (!isNew)
Evan Cheng87d696a2009-04-14 00:32:25 +0000708 assert(SrcRegMap[NewReg] == DstReg &&
709 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000710 VirtRegPairs.push_back(NewReg);
711 DstReg = NewReg;
712 }
713
714 if (!VirtRegPairs.empty()) {
715 unsigned ToReg = VirtRegPairs.back();
716 VirtRegPairs.pop_back();
717 while (!VirtRegPairs.empty()) {
718 unsigned FromReg = VirtRegPairs.back();
719 VirtRegPairs.pop_back();
720 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
Evan Cheng3005ed62009-04-13 20:04:24 +0000721 if (!isNew)
722 assert(DstRegMap[FromReg] == ToReg &&
723 "Can't map to two dst physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000724 ToReg = FromReg;
725 }
726 }
727 }
728
729 Processed.insert(MI);
730}
731
Evan Cheng28c7ce32009-02-21 03:14:25 +0000732/// isSafeToDelete - If the specified instruction does not produce any side
733/// effects and all of its defs are dead, then it's safe to delete.
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000734static bool isSafeToDelete(MachineInstr *MI,
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000735 const TargetInstrInfo *TII,
736 SmallVector<unsigned, 4> &Kills) {
Evan Cheng28c7ce32009-02-21 03:14:25 +0000737 const TargetInstrDesc &TID = MI->getDesc();
738 if (TID.mayStore() || TID.isCall())
739 return false;
740 if (TID.isTerminator() || TID.hasUnmodeledSideEffects())
741 return false;
742
743 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
744 MachineOperand &MO = MI->getOperand(i);
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000745 if (!MO.isReg())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000746 continue;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000747 if (MO.isDef() && !MO.isDead())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000748 return false;
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000749 if (MO.isUse() && MO.isKill())
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000750 Kills.push_back(MO.getReg());
Evan Cheng28c7ce32009-02-21 03:14:25 +0000751 }
Evan Cheng28c7ce32009-02-21 03:14:25 +0000752 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,
Bob Wilson326f4382009-09-01 22:51:08 +0000786 unsigned Dist) {
787 // Check if the instruction has no side effects and if all its defs are dead.
788 SmallVector<unsigned, 4> Kills;
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000789 if (!isSafeToDelete(mi, TII, Kills))
Bob Wilson326f4382009-09-01 22:51:08 +0000790 return false;
791
792 // If this instruction kills some virtual registers, we need to
793 // update the kill information. If it's not possible to do so,
794 // then bail out.
795 SmallVector<NewKill, 4> NewKills;
796 if (!canUpdateDeletedKills(Kills, NewKills, &*mbbi, Dist))
797 return false;
798
799 if (LV) {
800 while (!NewKills.empty()) {
801 MachineInstr *NewKill = NewKills.back().second;
802 unsigned Kill = NewKills.back().first.first;
803 bool isDead = NewKills.back().first.second;
804 NewKills.pop_back();
805 if (LV->removeVirtualRegisterKilled(Kill, mi)) {
806 if (isDead)
807 LV->addVirtualRegisterDead(Kill, NewKill);
808 else
809 LV->addVirtualRegisterKilled(Kill, NewKill);
810 }
811 }
Bob Wilson326f4382009-09-01 22:51:08 +0000812 }
813
814 mbbi->erase(mi); // Nuke the old inst.
815 mi = nmi;
816 return true;
817}
818
Bob Wilsoncc80df92009-09-03 20:58:42 +0000819/// TryInstructionTransform - For the case where an instruction has a single
820/// pair of tied register operands, attempt some transformations that may
821/// either eliminate the tied operands or improve the opportunities for
822/// coalescing away the register copy. Returns true if the tied operands
823/// are eliminated altogether.
824bool TwoAddressInstructionPass::
825TryInstructionTransform(MachineBasicBlock::iterator &mi,
826 MachineBasicBlock::iterator &nmi,
827 MachineFunction::iterator &mbbi,
828 unsigned SrcIdx, unsigned DstIdx, unsigned Dist) {
829 const TargetInstrDesc &TID = mi->getDesc();
830 unsigned regA = mi->getOperand(DstIdx).getReg();
831 unsigned regB = mi->getOperand(SrcIdx).getReg();
832
833 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
834 "cannot make instruction into two-address form");
835
836 // If regA is dead and the instruction can be deleted, just delete
837 // it so it doesn't clobber regB.
838 bool regBKilled = isKilled(*mi, regB, MRI, TII);
839 if (!regBKilled && mi->getOperand(DstIdx).isDead() &&
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000840 DeleteUnusedInstr(mi, nmi, mbbi, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +0000841 ++NumDeletes;
842 return true; // Done with this instruction.
843 }
844
845 // Check if it is profitable to commute the operands.
846 unsigned SrcOp1, SrcOp2;
847 unsigned regC = 0;
848 unsigned regCIdx = ~0U;
849 bool TryCommute = false;
850 bool AggressiveCommute = false;
851 if (TID.isCommutable() && mi->getNumOperands() >= 3 &&
852 TII->findCommutedOpIndices(mi, SrcOp1, SrcOp2)) {
853 if (SrcIdx == SrcOp1)
854 regCIdx = SrcOp2;
855 else if (SrcIdx == SrcOp2)
856 regCIdx = SrcOp1;
857
858 if (regCIdx != ~0U) {
859 regC = mi->getOperand(regCIdx).getReg();
860 if (!regBKilled && isKilled(*mi, regC, MRI, TII))
861 // If C dies but B does not, swap the B and C operands.
862 // This makes the live ranges of A and C joinable.
863 TryCommute = true;
864 else if (isProfitableToCommute(regB, regC, mi, mbbi, Dist)) {
865 TryCommute = true;
866 AggressiveCommute = true;
867 }
868 }
869 }
870
871 // If it's profitable to commute, try to do so.
872 if (TryCommute && CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
873 ++NumCommuted;
874 if (AggressiveCommute)
875 ++NumAggrCommuted;
876 return false;
877 }
878
879 if (TID.isConvertibleTo3Addr()) {
880 // This instruction is potentially convertible to a true
881 // three-address instruction. Check if it is profitable.
882 if (!regBKilled || isProfitableToConv3Addr(regA)) {
883 // Try to convert it.
884 if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) {
885 ++NumConvertedTo3Addr;
886 return true; // Done with this instruction.
887 }
888 }
889 }
890 return false;
891}
892
Bill Wendling637980e2008-05-10 00:12:52 +0000893/// runOnMachineFunction - Reduce two-address instructions to two operands.
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000894///
Chris Lattner163c1e72004-01-31 21:14:04 +0000895bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
David Greeneeb00b182010-01-05 01:24:21 +0000896 DEBUG(dbgs() << "Machine Function\n");
Misha Brukman75fa4e42004-07-22 15:26:23 +0000897 const TargetMachine &TM = MF.getTarget();
Evan Cheng875357d2008-03-13 06:37:55 +0000898 MRI = &MF.getRegInfo();
899 TII = TM.getInstrInfo();
900 TRI = TM.getRegisterInfo();
Duncan Sands1465d612009-01-28 13:14:17 +0000901 LV = getAnalysisIfAvailable<LiveVariables>();
Dan Gohmana70dca12009-10-09 23:27:56 +0000902 AA = &getAnalysis<AliasAnalysis>();
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000903
Misha Brukman75fa4e42004-07-22 15:26:23 +0000904 bool MadeChange = false;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000905
David Greeneeb00b182010-01-05 01:24:21 +0000906 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
907 DEBUG(dbgs() << "********** Function: "
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000908 << MF.getFunction()->getName() << '\n');
Alkis Evlogimenos3a9986f2004-02-18 00:35:06 +0000909
Evan Cheng7543e582008-06-18 07:49:14 +0000910 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
911 BitVector ReMatRegs;
912 ReMatRegs.resize(MRI->getLastVirtReg()+1);
913
Bob Wilsoncc80df92009-09-03 20:58:42 +0000914 typedef DenseMap<unsigned, SmallVector<std::pair<unsigned, unsigned>, 4> >
915 TiedOperandMap;
916 TiedOperandMap TiedOperands(4);
917
Evan Cheng870b8072009-03-01 02:03:43 +0000918 SmallPtrSet<MachineInstr*, 8> Processed;
Misha Brukman75fa4e42004-07-22 15:26:23 +0000919 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
920 mbbi != mbbe; ++mbbi) {
Evan Cheng7543e582008-06-18 07:49:14 +0000921 unsigned Dist = 0;
922 DistanceMap.clear();
Evan Cheng870b8072009-03-01 02:03:43 +0000923 SrcRegMap.clear();
924 DstRegMap.clear();
925 Processed.clear();
Misha Brukman75fa4e42004-07-22 15:26:23 +0000926 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
Evan Cheng7a963fa2008-03-27 01:27:25 +0000927 mi != me; ) {
Chris Lattner7896c9f2009-12-03 00:50:42 +0000928 MachineBasicBlock::iterator nmi = llvm::next(mi);
Dale Johannesenb8ff9342010-02-10 21:47:48 +0000929 if (mi->isDebugValue()) {
930 mi = nmi;
931 continue;
932 }
Chris Lattner749c6f62008-01-07 07:27:27 +0000933 const TargetInstrDesc &TID = mi->getDesc();
Evan Cheng360c2dd2006-11-01 23:06:55 +0000934 bool FirstTied = true;
Bill Wendling637980e2008-05-10 00:12:52 +0000935
Evan Cheng7543e582008-06-18 07:49:14 +0000936 DistanceMap.insert(std::make_pair(mi, ++Dist));
Evan Cheng870b8072009-03-01 02:03:43 +0000937
938 ProcessCopy(&*mi, &*mbbi, Processed);
939
Bob Wilsoncc80df92009-09-03 20:58:42 +0000940 // First scan through all the tied register uses in this instruction
941 // and record a list of pairs of tied operands for each register.
Chris Lattner518bb532010-02-09 19:54:29 +0000942 unsigned NumOps = mi->isInlineAsm()
Evan Chengfb112882009-03-23 08:01:15 +0000943 ? mi->getNumOperands() : TID.getNumOperands();
Bob Wilsoncc80df92009-09-03 20:58:42 +0000944 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
945 unsigned DstIdx = 0;
946 if (!mi->isRegTiedToDefOperand(SrcIdx, &DstIdx))
Evan Cheng360c2dd2006-11-01 23:06:55 +0000947 continue;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000948
Evan Cheng360c2dd2006-11-01 23:06:55 +0000949 if (FirstTied) {
Bob Wilsoncc80df92009-09-03 20:58:42 +0000950 FirstTied = false;
Evan Cheng360c2dd2006-11-01 23:06:55 +0000951 ++NumTwoAddressInstrs;
David Greeneeb00b182010-01-05 01:24:21 +0000952 DEBUG(dbgs() << '\t' << *mi);
Evan Cheng360c2dd2006-11-01 23:06:55 +0000953 }
Bill Wendling637980e2008-05-10 00:12:52 +0000954
Bob Wilsoncc80df92009-09-03 20:58:42 +0000955 assert(mi->getOperand(SrcIdx).isReg() &&
956 mi->getOperand(SrcIdx).getReg() &&
957 mi->getOperand(SrcIdx).isUse() &&
958 "two address instruction invalid");
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000959
Bob Wilsoncc80df92009-09-03 20:58:42 +0000960 unsigned regB = mi->getOperand(SrcIdx).getReg();
961 TiedOperandMap::iterator OI = TiedOperands.find(regB);
962 if (OI == TiedOperands.end()) {
963 SmallVector<std::pair<unsigned, unsigned>, 4> TiedPair;
964 OI = TiedOperands.insert(std::make_pair(regB, TiedPair)).first;
965 }
966 OI->second.push_back(std::make_pair(SrcIdx, DstIdx));
967 }
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000968
Bob Wilsoncc80df92009-09-03 20:58:42 +0000969 // Now iterate over the information collected above.
970 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
971 OE = TiedOperands.end(); OI != OE; ++OI) {
972 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs = OI->second;
Evan Cheng360c2dd2006-11-01 23:06:55 +0000973
Bob Wilsoncc80df92009-09-03 20:58:42 +0000974 // If the instruction has a single pair of tied operands, try some
975 // transformations that may either eliminate the tied operands or
976 // improve the opportunities for coalescing away the register copy.
977 if (TiedOperands.size() == 1 && TiedPairs.size() == 1) {
978 unsigned SrcIdx = TiedPairs[0].first;
979 unsigned DstIdx = TiedPairs[0].second;
Bob Wilson43449792009-08-31 21:54:55 +0000980
Bob Wilsoncc80df92009-09-03 20:58:42 +0000981 // If the registers are already equal, nothing needs to be done.
982 if (mi->getOperand(SrcIdx).getReg() ==
983 mi->getOperand(DstIdx).getReg())
984 break; // Done with this instruction.
985
986 if (TryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist))
987 break; // The tied operands have been eliminated.
988 }
989
990 bool RemovedKillFlag = false;
991 bool AllUsesCopied = true;
992 unsigned LastCopiedReg = 0;
993 unsigned regB = OI->first;
994 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
995 unsigned SrcIdx = TiedPairs[tpi].first;
996 unsigned DstIdx = TiedPairs[tpi].second;
997 unsigned regA = mi->getOperand(DstIdx).getReg();
998 // Grab regB from the instruction because it may have changed if the
999 // instruction was commuted.
1000 regB = mi->getOperand(SrcIdx).getReg();
1001
1002 if (regA == regB) {
1003 // The register is tied to multiple destinations (or else we would
1004 // not have continued this far), but this use of the register
1005 // already matches the tied destination. Leave it.
1006 AllUsesCopied = false;
1007 continue;
1008 }
1009 LastCopiedReg = regA;
1010
1011 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1012 "cannot make instruction into two-address form");
Chris Lattner6b507672004-01-31 21:21:43 +00001013
Chris Lattner1e313632004-07-21 23:17:57 +00001014#ifndef NDEBUG
Bob Wilsoncc80df92009-09-03 20:58:42 +00001015 // First, verify that we don't have a use of "a" in the instruction
1016 // (a = b + a for example) because our transformation will not
1017 // work. This should never occur because we are in SSA form.
1018 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
1019 assert(i == DstIdx ||
1020 !mi->getOperand(i).isReg() ||
1021 mi->getOperand(i).getReg() != regA);
Chris Lattner1e313632004-07-21 23:17:57 +00001022#endif
Alkis Evlogimenos14be6402004-02-04 22:17:40 +00001023
Bob Wilsoncc80df92009-09-03 20:58:42 +00001024 // Emit a copy or rematerialize the definition.
1025 const TargetRegisterClass *rc = MRI->getRegClass(regB);
1026 MachineInstr *DefMI = MRI->getVRegDef(regB);
1027 // If it's safe and profitable, remat the definition instead of
1028 // copying it.
1029 if (DefMI &&
1030 DefMI->getDesc().isAsCheapAsAMove() &&
Evan Chengac1abde2010-03-02 19:03:01 +00001031 DefMI->isSafeToReMat(TII, AA, regB) &&
Bob Wilsoncc80df92009-09-03 20:58:42 +00001032 isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){
David Greeneeb00b182010-01-05 01:24:21 +00001033 DEBUG(dbgs() << "2addr: REMATTING : " << *DefMI << "\n");
Bob Wilsoncc80df92009-09-03 20:58:42 +00001034 unsigned regASubIdx = mi->getOperand(DstIdx).getSubReg();
Evan Chengd57cdd52009-11-14 02:55:43 +00001035 TII->reMaterialize(*mbbi, mi, regA, regASubIdx, DefMI, TRI);
Bob Wilsoncc80df92009-09-03 20:58:42 +00001036 ReMatRegs.set(regB);
1037 ++NumReMats;
Bob Wilson71124f62009-09-01 04:18:40 +00001038 } else {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001039 bool Emitted = TII->copyRegToReg(*mbbi, mi, regA, regB, rc, rc);
1040 (void)Emitted;
1041 assert(Emitted && "Unable to issue a copy instruction!\n");
1042 }
1043
1044 MachineBasicBlock::iterator prevMI = prior(mi);
1045 // Update DistanceMap.
1046 DistanceMap.insert(std::make_pair(prevMI, Dist));
1047 DistanceMap[mi] = ++Dist;
1048
David Greeneeb00b182010-01-05 01:24:21 +00001049 DEBUG(dbgs() << "\t\tprepend:\t" << *prevMI);
Bob Wilsoncc80df92009-09-03 20:58:42 +00001050
1051 MachineOperand &MO = mi->getOperand(SrcIdx);
1052 assert(MO.isReg() && MO.getReg() == regB && MO.isUse() &&
1053 "inconsistent operand info for 2-reg pass");
1054 if (MO.isKill()) {
1055 MO.setIsKill(false);
1056 RemovedKillFlag = true;
1057 }
1058 MO.setReg(regA);
1059 }
1060
1061 if (AllUsesCopied) {
1062 // Replace other (un-tied) uses of regB with LastCopiedReg.
1063 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1064 MachineOperand &MO = mi->getOperand(i);
1065 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1066 if (MO.isKill()) {
1067 MO.setIsKill(false);
1068 RemovedKillFlag = true;
1069 }
1070 MO.setReg(LastCopiedReg);
1071 }
1072 }
1073
1074 // Update live variables for regB.
1075 if (RemovedKillFlag && LV && LV->getVarInfo(regB).removeKill(mi))
1076 LV->addVirtualRegisterKilled(regB, prior(mi));
1077
1078 } else if (RemovedKillFlag) {
1079 // Some tied uses of regB matched their destination registers, so
1080 // regB is still used in this instruction, but a kill flag was
1081 // removed from a different tied use of regB, so now we need to add
1082 // a kill flag to one of the remaining uses of regB.
1083 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1084 MachineOperand &MO = mi->getOperand(i);
1085 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1086 MO.setIsKill(true);
1087 break;
Bob Wilson71124f62009-09-01 04:18:40 +00001088 }
1089 }
Bob Wilson43449792009-08-31 21:54:55 +00001090 }
Bob Wilsoncc80df92009-09-03 20:58:42 +00001091
Bob Wilson43449792009-08-31 21:54:55 +00001092 MadeChange = true;
1093
David Greeneeb00b182010-01-05 01:24:21 +00001094 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
Misha Brukman75fa4e42004-07-22 15:26:23 +00001095 }
Bill Wendling637980e2008-05-10 00:12:52 +00001096
Bob Wilsoncc80df92009-09-03 20:58:42 +00001097 // Clear TiedOperands here instead of at the top of the loop
1098 // since most instructions do not have tied operands.
1099 TiedOperands.clear();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001100 mi = nmi;
Misha Brukman75fa4e42004-07-22 15:26:23 +00001101 }
1102 }
1103
Evan Cheng601ca4b2008-06-25 01:16:38 +00001104 // Some remat'ed instructions are dead.
1105 int VReg = ReMatRegs.find_first();
1106 while (VReg != -1) {
1107 if (MRI->use_empty(VReg)) {
1108 MachineInstr *DefMI = MRI->getVRegDef(VReg);
1109 DefMI->eraseFromParent();
Bill Wendlinga16157a2008-05-26 05:49:49 +00001110 }
Evan Cheng601ca4b2008-06-25 01:16:38 +00001111 VReg = ReMatRegs.find_next(VReg);
Bill Wendling48f7f232008-05-26 05:18:34 +00001112 }
1113
Misha Brukman75fa4e42004-07-22 15:26:23 +00001114 return MadeChange;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001115}