blob: 2b04104520812a8a7a34a2a6834a45acf21fa1e2 [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 Cheng3d720fb2010-05-05 18:45:40 +000043#include "llvm/Support/ErrorHandling.h"
Evan Cheng7543e582008-06-18 07:49:14 +000044#include "llvm/ADT/BitVector.h"
45#include "llvm/ADT/DenseMap.h"
Dan Gohmand68a0762009-01-05 17:59:02 +000046#include "llvm/ADT/SmallSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000047#include "llvm/ADT/Statistic.h"
48#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos71499de2003-12-18 13:06:04 +000049using namespace llvm;
50
Chris Lattnercd3245a2006-12-19 22:41:21 +000051STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
52STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
Evan Chengd498c8f2009-01-25 03:53:59 +000053STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
Chris Lattnercd3245a2006-12-19 22:41:21 +000054STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
Evan Cheng875357d2008-03-13 06:37:55 +000055STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
Evan Cheng7543e582008-06-18 07:49:14 +000056STATISTIC(NumReMats, "Number of instructions re-materialized");
Evan Cheng28c7ce32009-02-21 03:14:25 +000057STATISTIC(NumDeletes, "Number of dead instructions deleted");
Evan Cheng875357d2008-03-13 06:37:55 +000058
59namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000060 class TwoAddressInstructionPass : public MachineFunctionPass {
Evan Cheng875357d2008-03-13 06:37:55 +000061 const TargetInstrInfo *TII;
62 const TargetRegisterInfo *TRI;
63 MachineRegisterInfo *MRI;
64 LiveVariables *LV;
Dan Gohmana70dca12009-10-09 23:27:56 +000065 AliasAnalysis *AA;
Evan Cheng875357d2008-03-13 06:37:55 +000066
Evan Cheng870b8072009-03-01 02:03:43 +000067 // DistanceMap - Keep track the distance of a MI from the start of the
68 // current basic block.
69 DenseMap<MachineInstr*, unsigned> DistanceMap;
70
71 // SrcRegMap - A map from virtual registers to physical registers which
72 // are likely targets to be coalesced to due to copies from physical
73 // registers to virtual registers. e.g. v1024 = move r0.
74 DenseMap<unsigned, unsigned> SrcRegMap;
75
76 // DstRegMap - A map from virtual registers to physical registers which
77 // are likely targets to be coalesced to due to copies to physical
78 // registers from virtual registers. e.g. r1 = move v1024.
79 DenseMap<unsigned, unsigned> DstRegMap;
80
Evan Cheng3d720fb2010-05-05 18:45:40 +000081 /// RegSequences - Keep track the list of REG_SEQUENCE instructions seen
82 /// during the initial walk of the machine function.
83 SmallVector<MachineInstr*, 16> RegSequences;
84
Bill Wendling637980e2008-05-10 00:12:52 +000085 bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
86 unsigned Reg,
87 MachineBasicBlock::iterator OldPos);
Evan Cheng7543e582008-06-18 07:49:14 +000088
Evan Cheng7543e582008-06-18 07:49:14 +000089 bool isProfitableToReMat(unsigned Reg, const TargetRegisterClass *RC,
Evan Cheng601ca4b2008-06-25 01:16:38 +000090 MachineInstr *MI, MachineInstr *DefMI,
Evan Cheng870b8072009-03-01 02:03:43 +000091 MachineBasicBlock *MBB, unsigned Loc);
Evan Cheng81913712009-01-23 23:27:33 +000092
Evan Chengd498c8f2009-01-25 03:53:59 +000093 bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
Evan Chengd498c8f2009-01-25 03:53:59 +000094 unsigned &LastDef);
95
Evan Chenge9ccb3a2009-04-28 02:12:36 +000096 MachineInstr *FindLastUseInMBB(unsigned Reg, MachineBasicBlock *MBB,
97 unsigned Dist);
98
Evan Chengd498c8f2009-01-25 03:53:59 +000099 bool isProfitableToCommute(unsigned regB, unsigned regC,
100 MachineInstr *MI, MachineBasicBlock *MBB,
Evan Cheng870b8072009-03-01 02:03:43 +0000101 unsigned Dist);
Evan Chengd498c8f2009-01-25 03:53:59 +0000102
Evan Cheng81913712009-01-23 23:27:33 +0000103 bool CommuteInstruction(MachineBasicBlock::iterator &mi,
104 MachineFunction::iterator &mbbi,
Evan Cheng870b8072009-03-01 02:03:43 +0000105 unsigned RegB, unsigned RegC, unsigned Dist);
106
Evan Chenge6f350d2009-03-30 21:34:07 +0000107 bool isProfitableToConv3Addr(unsigned RegA);
108
109 bool ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
110 MachineBasicBlock::iterator &nmi,
111 MachineFunction::iterator &mbbi,
112 unsigned RegB, unsigned Dist);
113
Bob Wilson326f4382009-09-01 22:51:08 +0000114 typedef std::pair<std::pair<unsigned, bool>, MachineInstr*> NewKill;
115 bool canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
116 SmallVector<NewKill, 4> &NewKills,
117 MachineBasicBlock *MBB, unsigned Dist);
118 bool DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
119 MachineBasicBlock::iterator &nmi,
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000120 MachineFunction::iterator &mbbi, unsigned Dist);
Bob Wilson326f4382009-09-01 22:51:08 +0000121
Bob Wilsoncc80df92009-09-03 20:58:42 +0000122 bool TryInstructionTransform(MachineBasicBlock::iterator &mi,
123 MachineBasicBlock::iterator &nmi,
124 MachineFunction::iterator &mbbi,
125 unsigned SrcIdx, unsigned DstIdx,
126 unsigned Dist);
127
Evan Cheng870b8072009-03-01 02:03:43 +0000128 void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
129 SmallPtrSet<MachineInstr*, 8> &Processed);
Evan Cheng3a3cce52009-08-07 00:28:58 +0000130
Evan Cheng3d720fb2010-05-05 18:45:40 +0000131 /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
132 /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
133 /// sub-register references of the register defined by REG_SEQUENCE.
134 bool EliminateRegSequences();
Evan Cheng875357d2008-03-13 06:37:55 +0000135 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000136 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +0000137 TwoAddressInstructionPass() : MachineFunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +0000138
Bill Wendling637980e2008-05-10 00:12:52 +0000139 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +0000140 AU.setPreservesCFG();
Dan Gohmana70dca12009-10-09 23:27:56 +0000141 AU.addRequired<AliasAnalysis>();
Bill Wendling637980e2008-05-10 00:12:52 +0000142 AU.addPreserved<LiveVariables>();
143 AU.addPreservedID(MachineLoopInfoID);
144 AU.addPreservedID(MachineDominatorsID);
Owen Anderson95dad832008-10-07 20:22:28 +0000145 if (StrongPHIElim)
146 AU.addPreservedID(StrongPHIEliminationID);
147 else
148 AU.addPreservedID(PHIEliminationID);
Bill Wendling637980e2008-05-10 00:12:52 +0000149 MachineFunctionPass::getAnalysisUsage(AU);
150 }
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000151
Bill Wendling637980e2008-05-10 00:12:52 +0000152 /// runOnMachineFunction - Pass entry point.
Misha Brukman75fa4e42004-07-22 15:26:23 +0000153 bool runOnMachineFunction(MachineFunction&);
154 };
Chris Lattnerd74ea2b2006-05-24 17:04:05 +0000155}
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000156
Dan Gohman844731a2008-05-13 00:00:25 +0000157char TwoAddressInstructionPass::ID = 0;
158static RegisterPass<TwoAddressInstructionPass>
159X("twoaddressinstruction", "Two-Address instruction pass");
160
Dan Gohman6ddba2b2008-05-13 02:05:11 +0000161const PassInfo *const llvm::TwoAddressInstructionPassID = &X;
Alkis Evlogimenos4c080862003-12-18 22:40:24 +0000162
Evan Cheng875357d2008-03-13 06:37:55 +0000163/// Sink3AddrInstruction - A two-address instruction has been converted to a
164/// three-address instruction to avoid clobbering a register. Try to sink it
Bill Wendling637980e2008-05-10 00:12:52 +0000165/// past the instruction that would kill the above mentioned register to reduce
166/// register pressure.
Evan Cheng875357d2008-03-13 06:37:55 +0000167bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
168 MachineInstr *MI, unsigned SavedReg,
169 MachineBasicBlock::iterator OldPos) {
170 // Check if it's safe to move this instruction.
171 bool SeenStore = true; // Be conservative.
Evan Chengac1abde2010-03-02 19:03:01 +0000172 if (!MI->isSafeToMove(TII, AA, SeenStore))
Evan Cheng875357d2008-03-13 06:37:55 +0000173 return false;
174
175 unsigned DefReg = 0;
176 SmallSet<unsigned, 4> UseRegs;
Bill Wendling637980e2008-05-10 00:12:52 +0000177
Evan Cheng875357d2008-03-13 06:37:55 +0000178 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
179 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000180 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000181 continue;
182 unsigned MOReg = MO.getReg();
183 if (!MOReg)
184 continue;
185 if (MO.isUse() && MOReg != SavedReg)
186 UseRegs.insert(MO.getReg());
187 if (!MO.isDef())
188 continue;
189 if (MO.isImplicit())
190 // Don't try to move it if it implicitly defines a register.
191 return false;
192 if (DefReg)
193 // For now, don't move any instructions that define multiple registers.
194 return false;
195 DefReg = MO.getReg();
196 }
197
198 // Find the instruction that kills SavedReg.
199 MachineInstr *KillMI = NULL;
Evan Chengf1250ee2010-03-23 20:36:12 +0000200 for (MachineRegisterInfo::use_nodbg_iterator
201 UI = MRI->use_nodbg_begin(SavedReg),
202 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
Evan Cheng875357d2008-03-13 06:37:55 +0000203 MachineOperand &UseMO = UI.getOperand();
204 if (!UseMO.isKill())
205 continue;
206 KillMI = UseMO.getParent();
207 break;
208 }
Bill Wendling637980e2008-05-10 00:12:52 +0000209
Dan Gohman97121ba2009-04-08 00:15:30 +0000210 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI)
Evan Cheng875357d2008-03-13 06:37:55 +0000211 return false;
212
Bill Wendling637980e2008-05-10 00:12:52 +0000213 // If any of the definitions are used by another instruction between the
214 // position and the kill use, then it's not safe to sink it.
215 //
216 // FIXME: This can be sped up if there is an easy way to query whether an
Evan Cheng7543e582008-06-18 07:49:14 +0000217 // instruction is before or after another instruction. Then we can use
Bill Wendling637980e2008-05-10 00:12:52 +0000218 // MachineRegisterInfo def / use instead.
Evan Cheng875357d2008-03-13 06:37:55 +0000219 MachineOperand *KillMO = NULL;
220 MachineBasicBlock::iterator KillPos = KillMI;
221 ++KillPos;
Bill Wendling637980e2008-05-10 00:12:52 +0000222
Evan Cheng7543e582008-06-18 07:49:14 +0000223 unsigned NumVisited = 0;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000224 for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
Evan Cheng875357d2008-03-13 06:37:55 +0000225 MachineInstr *OtherMI = I;
Dale Johannesen3bfef032010-02-11 18:22:31 +0000226 // DBG_VALUE cannot be counted against the limit.
227 if (OtherMI->isDebugValue())
228 continue;
Evan Cheng7543e582008-06-18 07:49:14 +0000229 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
230 return false;
231 ++NumVisited;
Evan Cheng875357d2008-03-13 06:37:55 +0000232 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
233 MachineOperand &MO = OtherMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000234 if (!MO.isReg())
Evan Cheng875357d2008-03-13 06:37:55 +0000235 continue;
236 unsigned MOReg = MO.getReg();
237 if (!MOReg)
238 continue;
239 if (DefReg == MOReg)
240 return false;
Bill Wendling637980e2008-05-10 00:12:52 +0000241
Evan Cheng875357d2008-03-13 06:37:55 +0000242 if (MO.isKill()) {
243 if (OtherMI == KillMI && MOReg == SavedReg)
Evan Cheng7543e582008-06-18 07:49:14 +0000244 // Save the operand that kills the register. We want to unset the kill
245 // marker if we can sink MI past it.
Evan Cheng875357d2008-03-13 06:37:55 +0000246 KillMO = &MO;
247 else if (UseRegs.count(MOReg))
248 // One of the uses is killed before the destination.
249 return false;
250 }
251 }
252 }
253
Evan Cheng875357d2008-03-13 06:37:55 +0000254 // Update kill and LV information.
255 KillMO->setIsKill(false);
256 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
257 KillMO->setIsKill(true);
Owen Anderson802af112008-07-02 21:28:58 +0000258
Evan Cheng9f1c8312008-07-03 09:09:37 +0000259 if (LV)
260 LV->replaceKillInstruction(SavedReg, KillMI, MI);
Evan Cheng875357d2008-03-13 06:37:55 +0000261
262 // Move instruction to its destination.
263 MBB->remove(MI);
264 MBB->insert(KillPos, MI);
265
266 ++Num3AddrSunk;
267 return true;
268}
269
Evan Cheng7543e582008-06-18 07:49:14 +0000270/// isTwoAddrUse - Return true if the specified MI is using the specified
271/// register as a two-address operand.
272static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
273 const TargetInstrDesc &TID = UseMI->getDesc();
274 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
275 MachineOperand &MO = UseMI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000276 if (MO.isReg() && MO.getReg() == Reg &&
Evan Chenga24752f2009-03-19 20:30:06 +0000277 (MO.isDef() || UseMI->isRegTiedToDefOperand(i)))
Evan Cheng7543e582008-06-18 07:49:14 +0000278 // Earlier use is a two-address one.
279 return true;
280 }
281 return false;
282}
283
284/// isProfitableToReMat - Return true if the heuristics determines it is likely
285/// to be profitable to re-materialize the definition of Reg rather than copy
286/// the register.
287bool
288TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
Evan Cheng870b8072009-03-01 02:03:43 +0000289 const TargetRegisterClass *RC,
290 MachineInstr *MI, MachineInstr *DefMI,
291 MachineBasicBlock *MBB, unsigned Loc) {
Evan Cheng7543e582008-06-18 07:49:14 +0000292 bool OtherUse = false;
Evan Chengf1250ee2010-03-23 20:36:12 +0000293 for (MachineRegisterInfo::use_nodbg_iterator UI = MRI->use_nodbg_begin(Reg),
294 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
Evan Cheng7543e582008-06-18 07:49:14 +0000295 MachineOperand &UseMO = UI.getOperand();
Evan Cheng7543e582008-06-18 07:49:14 +0000296 MachineInstr *UseMI = UseMO.getParent();
Evan Cheng601ca4b2008-06-25 01:16:38 +0000297 MachineBasicBlock *UseMBB = UseMI->getParent();
298 if (UseMBB == MBB) {
299 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
300 if (DI != DistanceMap.end() && DI->second == Loc)
301 continue; // Current use.
302 OtherUse = true;
303 // There is at least one other use in the MBB that will clobber the
304 // register.
305 if (isTwoAddrUse(UseMI, Reg))
306 return true;
307 }
Evan Cheng7543e582008-06-18 07:49:14 +0000308 }
Evan Cheng601ca4b2008-06-25 01:16:38 +0000309
310 // If other uses in MBB are not two-address uses, then don't remat.
311 if (OtherUse)
312 return false;
313
314 // No other uses in the same block, remat if it's defined in the same
315 // block so it does not unnecessarily extend the live range.
316 return MBB == DefMI->getParent();
Evan Cheng7543e582008-06-18 07:49:14 +0000317}
318
Evan Chengd498c8f2009-01-25 03:53:59 +0000319/// NoUseAfterLastDef - Return true if there are no intervening uses between the
320/// last instruction in the MBB that defines the specified register and the
321/// two-address instruction which is being processed. It also returns the last
322/// def location by reference
323bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
Evan Cheng870b8072009-03-01 02:03:43 +0000324 MachineBasicBlock *MBB, unsigned Dist,
325 unsigned &LastDef) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000326 LastDef = 0;
327 unsigned LastUse = Dist;
328 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
329 E = MRI->reg_end(); I != E; ++I) {
330 MachineOperand &MO = I.getOperand();
331 MachineInstr *MI = MO.getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000332 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesend94998f2010-02-09 02:01:46 +0000333 continue;
Evan Chengd498c8f2009-01-25 03:53:59 +0000334 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
335 if (DI == DistanceMap.end())
336 continue;
337 if (MO.isUse() && DI->second < LastUse)
338 LastUse = DI->second;
339 if (MO.isDef() && DI->second > LastDef)
340 LastDef = DI->second;
341 }
342
343 return !(LastUse > LastDef && LastUse < Dist);
344}
345
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000346MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg,
347 MachineBasicBlock *MBB,
348 unsigned Dist) {
Lang Hamesa7c9dea2009-05-14 04:26:30 +0000349 unsigned LastUseDist = 0;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000350 MachineInstr *LastUse = 0;
351 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
352 E = MRI->reg_end(); I != E; ++I) {
353 MachineOperand &MO = I.getOperand();
354 MachineInstr *MI = MO.getParent();
Chris Lattner518bb532010-02-09 19:54:29 +0000355 if (MI->getParent() != MBB || MI->isDebugValue())
Dale Johannesend94998f2010-02-09 02:01:46 +0000356 continue;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000357 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
358 if (DI == DistanceMap.end())
359 continue;
Lang Hamesa7c9dea2009-05-14 04:26:30 +0000360 if (DI->second >= Dist)
361 continue;
362
363 if (MO.isUse() && DI->second > LastUseDist) {
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000364 LastUse = DI->first;
365 LastUseDist = DI->second;
366 }
367 }
368 return LastUse;
369}
370
Evan Cheng870b8072009-03-01 02:03:43 +0000371/// isCopyToReg - Return true if the specified MI is a copy instruction or
372/// a extract_subreg instruction. It also returns the source and destination
373/// registers and whether they are physical registers by reference.
374static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
375 unsigned &SrcReg, unsigned &DstReg,
376 bool &IsSrcPhys, bool &IsDstPhys) {
377 SrcReg = 0;
378 DstReg = 0;
379 unsigned SrcSubIdx, DstSubIdx;
380 if (!TII->isMoveInstr(MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
Chris Lattner518bb532010-02-09 19:54:29 +0000381 if (MI.isExtractSubreg()) {
Evan Cheng870b8072009-03-01 02:03:43 +0000382 DstReg = MI.getOperand(0).getReg();
383 SrcReg = MI.getOperand(1).getReg();
Chris Lattner518bb532010-02-09 19:54:29 +0000384 } else if (MI.isInsertSubreg()) {
Evan Cheng870b8072009-03-01 02:03:43 +0000385 DstReg = MI.getOperand(0).getReg();
386 SrcReg = MI.getOperand(2).getReg();
Chris Lattner518bb532010-02-09 19:54:29 +0000387 } else if (MI.isSubregToReg()) {
Dan Gohman97121ba2009-04-08 00:15:30 +0000388 DstReg = MI.getOperand(0).getReg();
389 SrcReg = MI.getOperand(2).getReg();
Evan Cheng870b8072009-03-01 02:03:43 +0000390 }
391 }
392
393 if (DstReg) {
394 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
395 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
396 return true;
397 }
398 return false;
399}
400
Dan Gohman97121ba2009-04-08 00:15:30 +0000401/// isKilled - Test if the given register value, which is used by the given
402/// instruction, is killed by the given instruction. This looks through
403/// coalescable copies to see if the original value is potentially not killed.
404///
405/// For example, in this code:
406///
407/// %reg1034 = copy %reg1024
408/// %reg1035 = copy %reg1025<kill>
409/// %reg1036 = add %reg1034<kill>, %reg1035<kill>
410///
411/// %reg1034 is not considered to be killed, since it is copied from a
412/// register which is not killed. Treating it as not killed lets the
413/// normal heuristics commute the (two-address) add, which lets
414/// coalescing eliminate the extra copy.
415///
416static bool isKilled(MachineInstr &MI, unsigned Reg,
417 const MachineRegisterInfo *MRI,
418 const TargetInstrInfo *TII) {
419 MachineInstr *DefMI = &MI;
420 for (;;) {
421 if (!DefMI->killsRegister(Reg))
422 return false;
423 if (TargetRegisterInfo::isPhysicalRegister(Reg))
424 return true;
425 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
426 // If there are multiple defs, we can't do a simple analysis, so just
427 // go with what the kill flag says.
Chris Lattner7896c9f2009-12-03 00:50:42 +0000428 if (llvm::next(Begin) != MRI->def_end())
Dan Gohman97121ba2009-04-08 00:15:30 +0000429 return true;
430 DefMI = &*Begin;
431 bool IsSrcPhys, IsDstPhys;
432 unsigned SrcReg, DstReg;
433 // If the def is something other than a copy, then it isn't going to
434 // be coalesced, so follow the kill flag.
435 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
436 return true;
437 Reg = SrcReg;
438 }
439}
440
Evan Cheng870b8072009-03-01 02:03:43 +0000441/// isTwoAddrUse - Return true if the specified MI uses the specified register
442/// as a two-address use. If so, return the destination register by reference.
443static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
444 const TargetInstrDesc &TID = MI.getDesc();
Chris Lattner518bb532010-02-09 19:54:29 +0000445 unsigned NumOps = MI.isInlineAsm() ? MI.getNumOperands():TID.getNumOperands();
Evan Chenge6f350d2009-03-30 21:34:07 +0000446 for (unsigned i = 0; i != NumOps; ++i) {
Evan Cheng870b8072009-03-01 02:03:43 +0000447 const MachineOperand &MO = MI.getOperand(i);
448 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
449 continue;
Evan Chenga24752f2009-03-19 20:30:06 +0000450 unsigned ti;
451 if (MI.isRegTiedToDefOperand(i, &ti)) {
Evan Cheng870b8072009-03-01 02:03:43 +0000452 DstReg = MI.getOperand(ti).getReg();
453 return true;
454 }
455 }
456 return false;
457}
458
459/// findOnlyInterestingUse - Given a register, if has a single in-basic block
460/// use, return the use instruction if it's a copy or a two-address use.
461static
462MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
463 MachineRegisterInfo *MRI,
464 const TargetInstrInfo *TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000465 bool &IsCopy,
Evan Cheng870b8072009-03-01 02:03:43 +0000466 unsigned &DstReg, bool &IsDstPhys) {
Evan Cheng1423c702010-03-03 21:18:38 +0000467 if (!MRI->hasOneNonDBGUse(Reg))
468 // None or more than one use.
Evan Cheng870b8072009-03-01 02:03:43 +0000469 return 0;
Evan Cheng1423c702010-03-03 21:18:38 +0000470 MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg);
Evan Cheng870b8072009-03-01 02:03:43 +0000471 if (UseMI.getParent() != MBB)
472 return 0;
473 unsigned SrcReg;
474 bool IsSrcPhys;
Evan Cheng87d696a2009-04-14 00:32:25 +0000475 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
476 IsCopy = true;
Evan Cheng870b8072009-03-01 02:03:43 +0000477 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000478 }
Evan Cheng870b8072009-03-01 02:03:43 +0000479 IsDstPhys = false;
Evan Cheng87d696a2009-04-14 00:32:25 +0000480 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
481 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng870b8072009-03-01 02:03:43 +0000482 return &UseMI;
Evan Cheng87d696a2009-04-14 00:32:25 +0000483 }
Evan Cheng870b8072009-03-01 02:03:43 +0000484 return 0;
485}
486
487/// getMappedReg - Return the physical register the specified virtual register
488/// might be mapped to.
489static unsigned
490getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
491 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
492 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
493 if (SI == RegMap.end())
494 return 0;
495 Reg = SI->second;
496 }
497 if (TargetRegisterInfo::isPhysicalRegister(Reg))
498 return Reg;
499 return 0;
500}
501
502/// regsAreCompatible - Return true if the two registers are equal or aliased.
503///
504static bool
505regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
506 if (RegA == RegB)
507 return true;
508 if (!RegA || !RegB)
509 return false;
510 return TRI->regsOverlap(RegA, RegB);
511}
512
513
Evan Chengd498c8f2009-01-25 03:53:59 +0000514/// isProfitableToReMat - Return true if it's potentially profitable to commute
515/// the two-address instruction that's being processed.
516bool
517TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC,
Evan Cheng870b8072009-03-01 02:03:43 +0000518 MachineInstr *MI, MachineBasicBlock *MBB,
519 unsigned Dist) {
Evan Chengd498c8f2009-01-25 03:53:59 +0000520 // Determine if it's profitable to commute this two address instruction. In
521 // general, we want no uses between this instruction and the definition of
522 // the two-address register.
523 // e.g.
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 %reg1028
528 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
529 // In this case, it might not be possible to coalesce the second MOV8rr
530 // instruction if the first one is coalesced. So it would be profitable to
531 // commute it:
532 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
533 // %reg1029<def> = MOV8rr %reg1028
534 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
535 // insert => %reg1030<def> = MOV8rr %reg1029
536 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
537
538 if (!MI->killsRegister(regC))
539 return false;
540
541 // Ok, we have something like:
542 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
543 // let's see if it's worth commuting it.
544
Evan Cheng870b8072009-03-01 02:03:43 +0000545 // Look for situations like this:
546 // %reg1024<def> = MOV r1
547 // %reg1025<def> = MOV r0
548 // %reg1026<def> = ADD %reg1024, %reg1025
549 // r0 = MOV %reg1026
550 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
551 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
552 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
553 unsigned ToRegB = getMappedReg(regB, DstRegMap);
554 unsigned ToRegC = getMappedReg(regC, DstRegMap);
555 if (!regsAreCompatible(FromRegB, ToRegB, TRI) &&
556 (regsAreCompatible(FromRegB, ToRegC, TRI) ||
557 regsAreCompatible(FromRegC, ToRegB, TRI)))
558 return true;
559
Evan Chengd498c8f2009-01-25 03:53:59 +0000560 // If there is a use of regC between its last def (could be livein) and this
561 // instruction, then bail.
562 unsigned LastDefC = 0;
Evan Cheng870b8072009-03-01 02:03:43 +0000563 if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
Evan Chengd498c8f2009-01-25 03:53:59 +0000564 return false;
565
566 // If there is a use of regB between its last def (could be livein) and this
567 // instruction, then go ahead and make this transformation.
568 unsigned LastDefB = 0;
Evan Cheng870b8072009-03-01 02:03:43 +0000569 if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
Evan Chengd498c8f2009-01-25 03:53:59 +0000570 return true;
571
572 // Since there are no intervening uses for both registers, then commute
573 // if the def of regC is closer. Its live interval is shorter.
574 return LastDefB && LastDefC && LastDefC > LastDefB;
575}
576
Evan Cheng81913712009-01-23 23:27:33 +0000577/// CommuteInstruction - Commute a two-address instruction and update the basic
578/// block, distance map, and live variables if needed. Return true if it is
579/// successful.
580bool
581TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
Evan Cheng870b8072009-03-01 02:03:43 +0000582 MachineFunction::iterator &mbbi,
583 unsigned RegB, unsigned RegC, unsigned Dist) {
Evan Cheng81913712009-01-23 23:27:33 +0000584 MachineInstr *MI = mi;
David Greeneeb00b182010-01-05 01:24:21 +0000585 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
Evan Cheng81913712009-01-23 23:27:33 +0000586 MachineInstr *NewMI = TII->commuteInstruction(MI);
587
588 if (NewMI == 0) {
David Greeneeb00b182010-01-05 01:24:21 +0000589 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
Evan Cheng81913712009-01-23 23:27:33 +0000590 return false;
591 }
592
David Greeneeb00b182010-01-05 01:24:21 +0000593 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
Evan Cheng81913712009-01-23 23:27:33 +0000594 // If the instruction changed to commute it, update livevar.
595 if (NewMI != MI) {
596 if (LV)
597 // Update live variables
598 LV->replaceKillInstruction(RegC, MI, NewMI);
599
600 mbbi->insert(mi, NewMI); // Insert the new inst
601 mbbi->erase(mi); // Nuke the old inst.
602 mi = NewMI;
603 DistanceMap.insert(std::make_pair(NewMI, Dist));
604 }
Evan Cheng870b8072009-03-01 02:03:43 +0000605
606 // Update source register map.
607 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
608 if (FromRegC) {
609 unsigned RegA = MI->getOperand(0).getReg();
610 SrcRegMap[RegA] = FromRegC;
611 }
612
Evan Cheng81913712009-01-23 23:27:33 +0000613 return true;
614}
615
Evan Chenge6f350d2009-03-30 21:34:07 +0000616/// isProfitableToConv3Addr - Return true if it is profitable to convert the
617/// given 2-address instruction to a 3-address one.
618bool
619TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA) {
620 // Look for situations like this:
621 // %reg1024<def> = MOV r1
622 // %reg1025<def> = MOV r0
623 // %reg1026<def> = ADD %reg1024, %reg1025
624 // r2 = MOV %reg1026
625 // Turn ADD into a 3-address instruction to avoid a copy.
626 unsigned FromRegA = getMappedReg(RegA, SrcRegMap);
627 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
628 return (FromRegA && ToRegA && !regsAreCompatible(FromRegA, ToRegA, TRI));
629}
630
631/// ConvertInstTo3Addr - Convert the specified two-address instruction into a
632/// three address one. Return true if this transformation was successful.
633bool
634TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
635 MachineBasicBlock::iterator &nmi,
636 MachineFunction::iterator &mbbi,
637 unsigned RegB, unsigned Dist) {
638 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
639 if (NewMI) {
David Greeneeb00b182010-01-05 01:24:21 +0000640 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
641 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
Evan Chenge6f350d2009-03-30 21:34:07 +0000642 bool Sunk = false;
643
644 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
645 // FIXME: Temporary workaround. If the new instruction doesn't
646 // uses RegB, convertToThreeAddress must have created more
647 // then one instruction.
648 Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
649
650 mbbi->erase(mi); // Nuke the old inst.
651
652 if (!Sunk) {
653 DistanceMap.insert(std::make_pair(NewMI, Dist));
654 mi = NewMI;
Chris Lattner7896c9f2009-12-03 00:50:42 +0000655 nmi = llvm::next(mi);
Evan Chenge6f350d2009-03-30 21:34:07 +0000656 }
657 return true;
658 }
659
660 return false;
661}
662
Evan Cheng870b8072009-03-01 02:03:43 +0000663/// ProcessCopy - If the specified instruction is not yet processed, process it
664/// if it's a copy. For a copy instruction, we find the physical registers the
665/// source and destination registers might be mapped to. These are kept in
666/// point-to maps used to determine future optimizations. e.g.
667/// v1024 = mov r0
668/// v1025 = mov r1
669/// v1026 = add v1024, v1025
670/// r1 = mov r1026
671/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
672/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
673/// potentially joined with r1 on the output side. It's worthwhile to commute
674/// 'add' to eliminate a copy.
675void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
676 MachineBasicBlock *MBB,
677 SmallPtrSet<MachineInstr*, 8> &Processed) {
678 if (Processed.count(MI))
679 return;
680
681 bool IsSrcPhys, IsDstPhys;
682 unsigned SrcReg, DstReg;
683 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
684 return;
685
686 if (IsDstPhys && !IsSrcPhys)
687 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
688 else if (!IsDstPhys && IsSrcPhys) {
Evan Cheng3005ed62009-04-13 20:04:24 +0000689 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
690 if (!isNew)
691 assert(SrcRegMap[DstReg] == SrcReg &&
692 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000693
694 SmallVector<unsigned, 4> VirtRegPairs;
Evan Cheng87d696a2009-04-14 00:32:25 +0000695 bool IsCopy = false;
Evan Cheng870b8072009-03-01 02:03:43 +0000696 unsigned NewReg = 0;
697 while (MachineInstr *UseMI = findOnlyInterestingUse(DstReg, MBB, MRI,TII,
Evan Cheng87d696a2009-04-14 00:32:25 +0000698 IsCopy, NewReg, IsDstPhys)) {
699 if (IsCopy) {
700 if (!Processed.insert(UseMI))
Evan Cheng870b8072009-03-01 02:03:43 +0000701 break;
702 }
703
704 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
705 if (DI != DistanceMap.end())
706 // Earlier in the same MBB.Reached via a back edge.
707 break;
708
709 if (IsDstPhys) {
710 VirtRegPairs.push_back(NewReg);
711 break;
712 }
713 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, DstReg)).second;
Evan Cheng3005ed62009-04-13 20:04:24 +0000714 if (!isNew)
Evan Cheng87d696a2009-04-14 00:32:25 +0000715 assert(SrcRegMap[NewReg] == DstReg &&
716 "Can't map to two src physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000717 VirtRegPairs.push_back(NewReg);
718 DstReg = NewReg;
719 }
720
721 if (!VirtRegPairs.empty()) {
722 unsigned ToReg = VirtRegPairs.back();
723 VirtRegPairs.pop_back();
724 while (!VirtRegPairs.empty()) {
725 unsigned FromReg = VirtRegPairs.back();
726 VirtRegPairs.pop_back();
727 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
Evan Cheng3005ed62009-04-13 20:04:24 +0000728 if (!isNew)
729 assert(DstRegMap[FromReg] == ToReg &&
730 "Can't map to two dst physical registers!");
Evan Cheng870b8072009-03-01 02:03:43 +0000731 ToReg = FromReg;
732 }
733 }
734 }
735
736 Processed.insert(MI);
737}
738
Evan Cheng28c7ce32009-02-21 03:14:25 +0000739/// isSafeToDelete - If the specified instruction does not produce any side
740/// effects and all of its defs are dead, then it's safe to delete.
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000741static bool isSafeToDelete(MachineInstr *MI,
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000742 const TargetInstrInfo *TII,
743 SmallVector<unsigned, 4> &Kills) {
Evan Cheng28c7ce32009-02-21 03:14:25 +0000744 const TargetInstrDesc &TID = MI->getDesc();
745 if (TID.mayStore() || TID.isCall())
746 return false;
747 if (TID.isTerminator() || TID.hasUnmodeledSideEffects())
748 return false;
749
750 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
751 MachineOperand &MO = MI->getOperand(i);
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000752 if (!MO.isReg())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000753 continue;
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000754 if (MO.isDef() && !MO.isDead())
Evan Cheng28c7ce32009-02-21 03:14:25 +0000755 return false;
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000756 if (MO.isUse() && MO.isKill())
Evan Chenge9ccb3a2009-04-28 02:12:36 +0000757 Kills.push_back(MO.getReg());
Evan Cheng28c7ce32009-02-21 03:14:25 +0000758 }
Evan Cheng28c7ce32009-02-21 03:14:25 +0000759 return true;
760}
761
Bob Wilson326f4382009-09-01 22:51:08 +0000762/// canUpdateDeletedKills - Check if all the registers listed in Kills are
763/// killed by instructions in MBB preceding the current instruction at
764/// position Dist. If so, return true and record information about the
765/// preceding kills in NewKills.
766bool TwoAddressInstructionPass::
767canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
768 SmallVector<NewKill, 4> &NewKills,
769 MachineBasicBlock *MBB, unsigned Dist) {
770 while (!Kills.empty()) {
771 unsigned Kill = Kills.back();
772 Kills.pop_back();
773 if (TargetRegisterInfo::isPhysicalRegister(Kill))
774 return false;
775
776 MachineInstr *LastKill = FindLastUseInMBB(Kill, MBB, Dist);
777 if (!LastKill)
778 return false;
779
780 bool isModRef = LastKill->modifiesRegister(Kill);
781 NewKills.push_back(std::make_pair(std::make_pair(Kill, isModRef),
782 LastKill));
783 }
784 return true;
785}
786
787/// DeleteUnusedInstr - If an instruction with a tied register operand can
788/// be safely deleted, just delete it.
789bool
790TwoAddressInstructionPass::DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
791 MachineBasicBlock::iterator &nmi,
792 MachineFunction::iterator &mbbi,
Bob Wilson326f4382009-09-01 22:51:08 +0000793 unsigned Dist) {
794 // Check if the instruction has no side effects and if all its defs are dead.
795 SmallVector<unsigned, 4> Kills;
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000796 if (!isSafeToDelete(mi, TII, Kills))
Bob Wilson326f4382009-09-01 22:51:08 +0000797 return false;
798
799 // If this instruction kills some virtual registers, we need to
800 // update the kill information. If it's not possible to do so,
801 // then bail out.
802 SmallVector<NewKill, 4> NewKills;
803 if (!canUpdateDeletedKills(Kills, NewKills, &*mbbi, Dist))
804 return false;
805
806 if (LV) {
807 while (!NewKills.empty()) {
808 MachineInstr *NewKill = NewKills.back().second;
809 unsigned Kill = NewKills.back().first.first;
810 bool isDead = NewKills.back().first.second;
811 NewKills.pop_back();
812 if (LV->removeVirtualRegisterKilled(Kill, mi)) {
813 if (isDead)
814 LV->addVirtualRegisterDead(Kill, NewKill);
815 else
816 LV->addVirtualRegisterKilled(Kill, NewKill);
817 }
818 }
Bob Wilson326f4382009-09-01 22:51:08 +0000819 }
820
821 mbbi->erase(mi); // Nuke the old inst.
822 mi = nmi;
823 return true;
824}
825
Bob Wilsoncc80df92009-09-03 20:58:42 +0000826/// TryInstructionTransform - For the case where an instruction has a single
827/// pair of tied register operands, attempt some transformations that may
828/// either eliminate the tied operands or improve the opportunities for
829/// coalescing away the register copy. Returns true if the tied operands
830/// are eliminated altogether.
831bool TwoAddressInstructionPass::
832TryInstructionTransform(MachineBasicBlock::iterator &mi,
833 MachineBasicBlock::iterator &nmi,
834 MachineFunction::iterator &mbbi,
835 unsigned SrcIdx, unsigned DstIdx, unsigned Dist) {
836 const TargetInstrDesc &TID = mi->getDesc();
837 unsigned regA = mi->getOperand(DstIdx).getReg();
838 unsigned regB = mi->getOperand(SrcIdx).getReg();
839
840 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
841 "cannot make instruction into two-address form");
842
843 // If regA is dead and the instruction can be deleted, just delete
844 // it so it doesn't clobber regB.
845 bool regBKilled = isKilled(*mi, regB, MRI, TII);
846 if (!regBKilled && mi->getOperand(DstIdx).isDead() &&
Jakob Stoklund Olesen0b25ae12009-11-18 21:33:35 +0000847 DeleteUnusedInstr(mi, nmi, mbbi, Dist)) {
Bob Wilsoncc80df92009-09-03 20:58:42 +0000848 ++NumDeletes;
849 return true; // Done with this instruction.
850 }
851
852 // Check if it is profitable to commute the operands.
853 unsigned SrcOp1, SrcOp2;
854 unsigned regC = 0;
855 unsigned regCIdx = ~0U;
856 bool TryCommute = false;
857 bool AggressiveCommute = false;
858 if (TID.isCommutable() && mi->getNumOperands() >= 3 &&
859 TII->findCommutedOpIndices(mi, SrcOp1, SrcOp2)) {
860 if (SrcIdx == SrcOp1)
861 regCIdx = SrcOp2;
862 else if (SrcIdx == SrcOp2)
863 regCIdx = SrcOp1;
864
865 if (regCIdx != ~0U) {
866 regC = mi->getOperand(regCIdx).getReg();
867 if (!regBKilled && isKilled(*mi, regC, MRI, TII))
868 // If C dies but B does not, swap the B and C operands.
869 // This makes the live ranges of A and C joinable.
870 TryCommute = true;
871 else if (isProfitableToCommute(regB, regC, mi, mbbi, Dist)) {
872 TryCommute = true;
873 AggressiveCommute = true;
874 }
875 }
876 }
877
878 // If it's profitable to commute, try to do so.
879 if (TryCommute && CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
880 ++NumCommuted;
881 if (AggressiveCommute)
882 ++NumAggrCommuted;
883 return false;
884 }
885
886 if (TID.isConvertibleTo3Addr()) {
887 // This instruction is potentially convertible to a true
888 // three-address instruction. Check if it is profitable.
889 if (!regBKilled || isProfitableToConv3Addr(regA)) {
890 // Try to convert it.
891 if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) {
892 ++NumConvertedTo3Addr;
893 return true; // Done with this instruction.
894 }
895 }
896 }
897 return false;
898}
899
Bill Wendling637980e2008-05-10 00:12:52 +0000900/// runOnMachineFunction - Reduce two-address instructions to two operands.
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000901///
Chris Lattner163c1e72004-01-31 21:14:04 +0000902bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
David Greeneeb00b182010-01-05 01:24:21 +0000903 DEBUG(dbgs() << "Machine Function\n");
Misha Brukman75fa4e42004-07-22 15:26:23 +0000904 const TargetMachine &TM = MF.getTarget();
Evan Cheng875357d2008-03-13 06:37:55 +0000905 MRI = &MF.getRegInfo();
906 TII = TM.getInstrInfo();
907 TRI = TM.getRegisterInfo();
Duncan Sands1465d612009-01-28 13:14:17 +0000908 LV = getAnalysisIfAvailable<LiveVariables>();
Dan Gohmana70dca12009-10-09 23:27:56 +0000909 AA = &getAnalysis<AliasAnalysis>();
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000910
Misha Brukman75fa4e42004-07-22 15:26:23 +0000911 bool MadeChange = false;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000912
David Greeneeb00b182010-01-05 01:24:21 +0000913 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
914 DEBUG(dbgs() << "********** Function: "
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000915 << MF.getFunction()->getName() << '\n');
Alkis Evlogimenos3a9986f2004-02-18 00:35:06 +0000916
Evan Cheng7543e582008-06-18 07:49:14 +0000917 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
918 BitVector ReMatRegs;
919 ReMatRegs.resize(MRI->getLastVirtReg()+1);
920
Bob Wilsoncc80df92009-09-03 20:58:42 +0000921 typedef DenseMap<unsigned, SmallVector<std::pair<unsigned, unsigned>, 4> >
922 TiedOperandMap;
923 TiedOperandMap TiedOperands(4);
924
Evan Cheng870b8072009-03-01 02:03:43 +0000925 SmallPtrSet<MachineInstr*, 8> Processed;
Misha Brukman75fa4e42004-07-22 15:26:23 +0000926 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
927 mbbi != mbbe; ++mbbi) {
Evan Cheng7543e582008-06-18 07:49:14 +0000928 unsigned Dist = 0;
929 DistanceMap.clear();
Evan Cheng870b8072009-03-01 02:03:43 +0000930 SrcRegMap.clear();
931 DstRegMap.clear();
932 Processed.clear();
Misha Brukman75fa4e42004-07-22 15:26:23 +0000933 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
Evan Cheng7a963fa2008-03-27 01:27:25 +0000934 mi != me; ) {
Chris Lattner7896c9f2009-12-03 00:50:42 +0000935 MachineBasicBlock::iterator nmi = llvm::next(mi);
Dale Johannesenb8ff9342010-02-10 21:47:48 +0000936 if (mi->isDebugValue()) {
937 mi = nmi;
938 continue;
939 }
Evan Chengf1250ee2010-03-23 20:36:12 +0000940
Evan Cheng3d720fb2010-05-05 18:45:40 +0000941 // Remember REG_SEQUENCE instructions, we'll deal with them later.
942 if (mi->isRegSequence())
943 RegSequences.push_back(&*mi);
944
Chris Lattner749c6f62008-01-07 07:27:27 +0000945 const TargetInstrDesc &TID = mi->getDesc();
Evan Cheng360c2dd2006-11-01 23:06:55 +0000946 bool FirstTied = true;
Bill Wendling637980e2008-05-10 00:12:52 +0000947
Evan Cheng7543e582008-06-18 07:49:14 +0000948 DistanceMap.insert(std::make_pair(mi, ++Dist));
Evan Cheng870b8072009-03-01 02:03:43 +0000949
950 ProcessCopy(&*mi, &*mbbi, Processed);
951
Bob Wilsoncc80df92009-09-03 20:58:42 +0000952 // First scan through all the tied register uses in this instruction
953 // and record a list of pairs of tied operands for each register.
Chris Lattner518bb532010-02-09 19:54:29 +0000954 unsigned NumOps = mi->isInlineAsm()
Evan Chengfb112882009-03-23 08:01:15 +0000955 ? mi->getNumOperands() : TID.getNumOperands();
Bob Wilsoncc80df92009-09-03 20:58:42 +0000956 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
957 unsigned DstIdx = 0;
958 if (!mi->isRegTiedToDefOperand(SrcIdx, &DstIdx))
Evan Cheng360c2dd2006-11-01 23:06:55 +0000959 continue;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000960
Evan Cheng360c2dd2006-11-01 23:06:55 +0000961 if (FirstTied) {
Bob Wilsoncc80df92009-09-03 20:58:42 +0000962 FirstTied = false;
Evan Cheng360c2dd2006-11-01 23:06:55 +0000963 ++NumTwoAddressInstrs;
David Greeneeb00b182010-01-05 01:24:21 +0000964 DEBUG(dbgs() << '\t' << *mi);
Evan Cheng360c2dd2006-11-01 23:06:55 +0000965 }
Bill Wendling637980e2008-05-10 00:12:52 +0000966
Bob Wilsoncc80df92009-09-03 20:58:42 +0000967 assert(mi->getOperand(SrcIdx).isReg() &&
968 mi->getOperand(SrcIdx).getReg() &&
969 mi->getOperand(SrcIdx).isUse() &&
970 "two address instruction invalid");
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000971
Bob Wilsoncc80df92009-09-03 20:58:42 +0000972 unsigned regB = mi->getOperand(SrcIdx).getReg();
973 TiedOperandMap::iterator OI = TiedOperands.find(regB);
974 if (OI == TiedOperands.end()) {
975 SmallVector<std::pair<unsigned, unsigned>, 4> TiedPair;
976 OI = TiedOperands.insert(std::make_pair(regB, TiedPair)).first;
977 }
978 OI->second.push_back(std::make_pair(SrcIdx, DstIdx));
979 }
Alkis Evlogimenos71499de2003-12-18 13:06:04 +0000980
Bob Wilsoncc80df92009-09-03 20:58:42 +0000981 // Now iterate over the information collected above.
982 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
983 OE = TiedOperands.end(); OI != OE; ++OI) {
984 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs = OI->second;
Evan Cheng360c2dd2006-11-01 23:06:55 +0000985
Bob Wilsoncc80df92009-09-03 20:58:42 +0000986 // If the instruction has a single pair of tied operands, try some
987 // transformations that may either eliminate the tied operands or
988 // improve the opportunities for coalescing away the register copy.
989 if (TiedOperands.size() == 1 && TiedPairs.size() == 1) {
990 unsigned SrcIdx = TiedPairs[0].first;
991 unsigned DstIdx = TiedPairs[0].second;
Bob Wilson43449792009-08-31 21:54:55 +0000992
Bob Wilsoncc80df92009-09-03 20:58:42 +0000993 // If the registers are already equal, nothing needs to be done.
994 if (mi->getOperand(SrcIdx).getReg() ==
995 mi->getOperand(DstIdx).getReg())
996 break; // Done with this instruction.
997
998 if (TryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist))
999 break; // The tied operands have been eliminated.
1000 }
1001
1002 bool RemovedKillFlag = false;
1003 bool AllUsesCopied = true;
1004 unsigned LastCopiedReg = 0;
1005 unsigned regB = OI->first;
1006 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1007 unsigned SrcIdx = TiedPairs[tpi].first;
1008 unsigned DstIdx = TiedPairs[tpi].second;
1009 unsigned regA = mi->getOperand(DstIdx).getReg();
1010 // Grab regB from the instruction because it may have changed if the
1011 // instruction was commuted.
1012 regB = mi->getOperand(SrcIdx).getReg();
1013
1014 if (regA == regB) {
1015 // The register is tied to multiple destinations (or else we would
1016 // not have continued this far), but this use of the register
1017 // already matches the tied destination. Leave it.
1018 AllUsesCopied = false;
1019 continue;
1020 }
1021 LastCopiedReg = regA;
1022
1023 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1024 "cannot make instruction into two-address form");
Chris Lattner6b507672004-01-31 21:21:43 +00001025
Chris Lattner1e313632004-07-21 23:17:57 +00001026#ifndef NDEBUG
Bob Wilsoncc80df92009-09-03 20:58:42 +00001027 // First, verify that we don't have a use of "a" in the instruction
1028 // (a = b + a for example) because our transformation will not
1029 // work. This should never occur because we are in SSA form.
1030 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
1031 assert(i == DstIdx ||
1032 !mi->getOperand(i).isReg() ||
1033 mi->getOperand(i).getReg() != regA);
Chris Lattner1e313632004-07-21 23:17:57 +00001034#endif
Alkis Evlogimenos14be6402004-02-04 22:17:40 +00001035
Bob Wilsoncc80df92009-09-03 20:58:42 +00001036 // Emit a copy or rematerialize the definition.
1037 const TargetRegisterClass *rc = MRI->getRegClass(regB);
1038 MachineInstr *DefMI = MRI->getVRegDef(regB);
1039 // If it's safe and profitable, remat the definition instead of
1040 // copying it.
1041 if (DefMI &&
1042 DefMI->getDesc().isAsCheapAsAMove() &&
Evan Chengac1abde2010-03-02 19:03:01 +00001043 DefMI->isSafeToReMat(TII, AA, regB) &&
Bob Wilsoncc80df92009-09-03 20:58:42 +00001044 isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){
David Greeneeb00b182010-01-05 01:24:21 +00001045 DEBUG(dbgs() << "2addr: REMATTING : " << *DefMI << "\n");
Bob Wilsoncc80df92009-09-03 20:58:42 +00001046 unsigned regASubIdx = mi->getOperand(DstIdx).getSubReg();
Evan Chengd57cdd52009-11-14 02:55:43 +00001047 TII->reMaterialize(*mbbi, mi, regA, regASubIdx, DefMI, TRI);
Bob Wilsoncc80df92009-09-03 20:58:42 +00001048 ReMatRegs.set(regB);
1049 ++NumReMats;
Bob Wilson71124f62009-09-01 04:18:40 +00001050 } else {
Bob Wilsoncc80df92009-09-03 20:58:42 +00001051 bool Emitted = TII->copyRegToReg(*mbbi, mi, regA, regB, rc, rc);
1052 (void)Emitted;
1053 assert(Emitted && "Unable to issue a copy instruction!\n");
1054 }
1055
1056 MachineBasicBlock::iterator prevMI = prior(mi);
1057 // Update DistanceMap.
1058 DistanceMap.insert(std::make_pair(prevMI, Dist));
1059 DistanceMap[mi] = ++Dist;
1060
David Greeneeb00b182010-01-05 01:24:21 +00001061 DEBUG(dbgs() << "\t\tprepend:\t" << *prevMI);
Bob Wilsoncc80df92009-09-03 20:58:42 +00001062
1063 MachineOperand &MO = mi->getOperand(SrcIdx);
1064 assert(MO.isReg() && MO.getReg() == regB && MO.isUse() &&
1065 "inconsistent operand info for 2-reg pass");
1066 if (MO.isKill()) {
1067 MO.setIsKill(false);
1068 RemovedKillFlag = true;
1069 }
1070 MO.setReg(regA);
1071 }
1072
1073 if (AllUsesCopied) {
1074 // Replace other (un-tied) uses of regB with LastCopiedReg.
1075 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1076 MachineOperand &MO = mi->getOperand(i);
1077 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1078 if (MO.isKill()) {
1079 MO.setIsKill(false);
1080 RemovedKillFlag = true;
1081 }
1082 MO.setReg(LastCopiedReg);
1083 }
1084 }
1085
1086 // Update live variables for regB.
1087 if (RemovedKillFlag && LV && LV->getVarInfo(regB).removeKill(mi))
1088 LV->addVirtualRegisterKilled(regB, prior(mi));
1089
1090 } else if (RemovedKillFlag) {
1091 // Some tied uses of regB matched their destination registers, so
1092 // regB is still used in this instruction, but a kill flag was
1093 // removed from a different tied use of regB, so now we need to add
1094 // a kill flag to one of the remaining uses of regB.
1095 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1096 MachineOperand &MO = mi->getOperand(i);
1097 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1098 MO.setIsKill(true);
1099 break;
Bob Wilson71124f62009-09-01 04:18:40 +00001100 }
1101 }
Bob Wilson43449792009-08-31 21:54:55 +00001102 }
Bob Wilsoncc80df92009-09-03 20:58:42 +00001103
Bob Wilson43449792009-08-31 21:54:55 +00001104 MadeChange = true;
1105
David Greeneeb00b182010-01-05 01:24:21 +00001106 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
Misha Brukman75fa4e42004-07-22 15:26:23 +00001107 }
Bill Wendling637980e2008-05-10 00:12:52 +00001108
Bob Wilsoncc80df92009-09-03 20:58:42 +00001109 // Clear TiedOperands here instead of at the top of the loop
1110 // since most instructions do not have tied operands.
1111 TiedOperands.clear();
Evan Cheng7a963fa2008-03-27 01:27:25 +00001112 mi = nmi;
Misha Brukman75fa4e42004-07-22 15:26:23 +00001113 }
1114 }
1115
Evan Cheng601ca4b2008-06-25 01:16:38 +00001116 // Some remat'ed instructions are dead.
1117 int VReg = ReMatRegs.find_first();
1118 while (VReg != -1) {
Evan Chengf1250ee2010-03-23 20:36:12 +00001119 if (MRI->use_nodbg_empty(VReg)) {
Evan Cheng601ca4b2008-06-25 01:16:38 +00001120 MachineInstr *DefMI = MRI->getVRegDef(VReg);
1121 DefMI->eraseFromParent();
Bill Wendlinga16157a2008-05-26 05:49:49 +00001122 }
Evan Cheng601ca4b2008-06-25 01:16:38 +00001123 VReg = ReMatRegs.find_next(VReg);
Bill Wendling48f7f232008-05-26 05:18:34 +00001124 }
1125
Evan Cheng3d720fb2010-05-05 18:45:40 +00001126 // Eliminate REG_SEQUENCE instructions. Their whole purpose was to preseve
1127 // SSA form. It's now safe to de-SSA.
1128 MadeChange |= EliminateRegSequences();
1129
Misha Brukman75fa4e42004-07-22 15:26:23 +00001130 return MadeChange;
Alkis Evlogimenos71499de2003-12-18 13:06:04 +00001131}
Evan Cheng3d720fb2010-05-05 18:45:40 +00001132
1133static void UpdateRegSequenceSrcs(unsigned SrcReg,
1134 unsigned DstReg, unsigned SrcIdx,
1135 MachineRegisterInfo *MRI) {
1136 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg),
1137 UE = MRI->reg_end(); RI != UE; ) {
1138 MachineOperand &MO = RI.getOperand();
1139 ++RI;
1140 MO.setReg(DstReg);
1141 MO.setSubReg(SrcIdx);
1142 }
1143}
1144
1145/// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
1146/// of the de-ssa process. This replaces sources of REG_SEQUENCE as
1147/// sub-register references of the register defined by REG_SEQUENCE. e.g.
1148///
1149/// %reg1029<def>, %reg1030<def> = VLD1q16 %reg1024<kill>, ...
1150/// %reg1031<def> = REG_SEQUENCE %reg1029<kill>, 5, %reg1030<kill>, 6
1151/// =>
1152/// %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
1153bool TwoAddressInstructionPass::EliminateRegSequences() {
1154 if (RegSequences.empty())
1155 return false;
1156
1157 for (unsigned i = 0, e = RegSequences.size(); i != e; ++i) {
1158 MachineInstr *MI = RegSequences[i];
1159 unsigned DstReg = MI->getOperand(0).getReg();
1160 if (MI->getOperand(0).getSubReg() ||
1161 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1162 !(MI->getNumOperands() & 1)) {
1163 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1164 llvm_unreachable(0);
1165 }
1166 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1167 unsigned SrcReg = MI->getOperand(i).getReg();
1168 if (MI->getOperand(i).getSubReg() ||
1169 TargetRegisterInfo::isPhysicalRegister(SrcReg)) {
1170 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1171 llvm_unreachable(0);
1172 }
1173 unsigned SrcIdx = MI->getOperand(i+1).getImm();
1174 UpdateRegSequenceSrcs(SrcReg, DstReg, SrcIdx, MRI);
1175 }
1176
1177 DEBUG(dbgs() << "Eliminated: " << *MI);
1178 MI->eraseFromParent();
1179 }
1180
1181 return true;
1182}