1 //===-- TwoAddressInstructionPass.cpp - Two-Address instruction pass ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the TwoAddress instruction pass which is used
11 // by most register allocators. Two-Address instructions are rewritten
21 // 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
25 // It is also worth noting that the duplicate operand of the two
26 // address instruction is removed.
28 //===----------------------------------------------------------------------===//
30 #define DEBUG_TYPE "twoaddrinstr"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/Function.h"
33 #include "llvm/CodeGen/LiveVariables.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineInstr.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Support/Compiler.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/DenseMap.h"
44 #include "llvm/ADT/SmallPtrSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/STLExtras.h"
49 STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
50 STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
51 STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
52 STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
53 STATISTIC(NumReMats, "Number of instructions re-materialized");
56 class VISIBILITY_HIDDEN TwoAddressInstructionPass
57 : public MachineFunctionPass {
58 const TargetInstrInfo *TII;
59 const TargetRegisterInfo *TRI;
60 MachineRegisterInfo *MRI;
63 bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
65 MachineBasicBlock::iterator OldPos);
67 bool isSafeToReMat(unsigned DstReg, MachineInstr *MI);
68 bool isProfitableToReMat(unsigned Reg, const TargetRegisterClass *RC,
69 MachineInstr *MI, MachineInstr *DefMI,
70 MachineBasicBlock *MBB, unsigned Loc,
71 DenseMap<MachineInstr*, unsigned> &DistanceMap);
73 static char ID; // Pass identification, replacement for typeid
74 TwoAddressInstructionPass() : MachineFunctionPass((intptr_t)&ID) {}
76 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
77 AU.addPreserved<LiveVariables>();
78 AU.addPreservedID(MachineLoopInfoID);
79 AU.addPreservedID(MachineDominatorsID);
80 AU.addPreservedID(PHIEliminationID);
81 MachineFunctionPass::getAnalysisUsage(AU);
84 /// runOnMachineFunction - Pass entry point.
85 bool runOnMachineFunction(MachineFunction&);
89 char TwoAddressInstructionPass::ID = 0;
90 static RegisterPass<TwoAddressInstructionPass>
91 X("twoaddressinstruction", "Two-Address instruction pass");
93 const PassInfo *const llvm::TwoAddressInstructionPassID = &X;
95 /// Sink3AddrInstruction - A two-address instruction has been converted to a
96 /// three-address instruction to avoid clobbering a register. Try to sink it
97 /// past the instruction that would kill the above mentioned register to reduce
98 /// register pressure.
99 bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
100 MachineInstr *MI, unsigned SavedReg,
101 MachineBasicBlock::iterator OldPos) {
102 // Check if it's safe to move this instruction.
103 bool SeenStore = true; // Be conservative.
104 if (!MI->isSafeToMove(TII, SeenStore))
108 SmallSet<unsigned, 4> UseRegs;
110 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
111 const MachineOperand &MO = MI->getOperand(i);
112 if (!MO.isRegister())
114 unsigned MOReg = MO.getReg();
117 if (MO.isUse() && MOReg != SavedReg)
118 UseRegs.insert(MO.getReg());
122 // Don't try to move it if it implicitly defines a register.
125 // For now, don't move any instructions that define multiple registers.
127 DefReg = MO.getReg();
130 // Find the instruction that kills SavedReg.
131 MachineInstr *KillMI = NULL;
132 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SavedReg),
133 UE = MRI->use_end(); UI != UE; ++UI) {
134 MachineOperand &UseMO = UI.getOperand();
137 KillMI = UseMO.getParent();
141 if (!KillMI || KillMI->getParent() != MBB)
144 // If any of the definitions are used by another instruction between the
145 // position and the kill use, then it's not safe to sink it.
147 // FIXME: This can be sped up if there is an easy way to query whether an
148 // instruction is before or after another instruction. Then we can use
149 // MachineRegisterInfo def / use instead.
150 MachineOperand *KillMO = NULL;
151 MachineBasicBlock::iterator KillPos = KillMI;
154 unsigned NumVisited = 0;
155 for (MachineBasicBlock::iterator I = next(OldPos); I != KillPos; ++I) {
156 MachineInstr *OtherMI = I;
157 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
160 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
161 MachineOperand &MO = OtherMI->getOperand(i);
162 if (!MO.isRegister())
164 unsigned MOReg = MO.getReg();
171 if (OtherMI == KillMI && MOReg == SavedReg)
172 // Save the operand that kills the register. We want to unset the kill
173 // marker if we can sink MI past it.
175 else if (UseRegs.count(MOReg))
176 // One of the uses is killed before the destination.
182 // Update kill and LV information.
183 KillMO->setIsKill(false);
184 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
185 KillMO->setIsKill(true);
188 LV->replaceKillInstruction(SavedReg, KillMI, MI);
190 // Move instruction to its destination.
192 MBB->insert(KillPos, MI);
198 /// isSafeToReMat - Return true if it's safe to rematerialize the specified
199 /// instruction which defined the specified register instead of copying it.
201 TwoAddressInstructionPass::isSafeToReMat(unsigned DstReg, MachineInstr *MI) {
202 const TargetInstrDesc &TID = MI->getDesc();
203 if (!TID.isAsCheapAsAMove())
205 bool SawStore = false;
206 if (!MI->isSafeToMove(TII, SawStore))
208 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
209 MachineOperand &MO = MI->getOperand(i);
210 if (!MO.isRegister())
212 // FIXME: For now, do not remat any instruction with register operands.
213 // Later on, we can loosen the restriction is the register operands have
214 // not been modified between the def and use. Note, this is different from
215 // MachineSink because the code in no longer in two-address form (at least
219 else if (!MO.isDead() && MO.getReg() != DstReg)
225 /// isTwoAddrUse - Return true if the specified MI is using the specified
226 /// register as a two-address operand.
227 static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
228 const TargetInstrDesc &TID = UseMI->getDesc();
229 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
230 MachineOperand &MO = UseMI->getOperand(i);
231 if (MO.isRegister() && MO.getReg() == Reg &&
232 (MO.isDef() || TID.getOperandConstraint(i, TOI::TIED_TO) != -1))
233 // Earlier use is a two-address one.
239 /// isProfitableToReMat - Return true if the heuristics determines it is likely
240 /// to be profitable to re-materialize the definition of Reg rather than copy
243 TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
244 const TargetRegisterClass *RC,
245 MachineInstr *MI, MachineInstr *DefMI,
246 MachineBasicBlock *MBB, unsigned Loc,
247 DenseMap<MachineInstr*, unsigned> &DistanceMap){
248 bool OtherUse = false;
249 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
250 UE = MRI->use_end(); UI != UE; ++UI) {
251 MachineOperand &UseMO = UI.getOperand();
254 MachineInstr *UseMI = UseMO.getParent();
255 MachineBasicBlock *UseMBB = UseMI->getParent();
257 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
258 if (DI != DistanceMap.end() && DI->second == Loc)
259 continue; // Current use.
261 // There is at least one other use in the MBB that will clobber the
263 if (isTwoAddrUse(UseMI, Reg))
268 // If other uses in MBB are not two-address uses, then don't remat.
272 // No other uses in the same block, remat if it's defined in the same
273 // block so it does not unnecessarily extend the live range.
274 return MBB == DefMI->getParent();
277 /// runOnMachineFunction - Reduce two-address instructions to two operands.
279 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
280 DOUT << "Machine Function\n";
281 const TargetMachine &TM = MF.getTarget();
282 MRI = &MF.getRegInfo();
283 TII = TM.getInstrInfo();
284 TRI = TM.getRegisterInfo();
285 LV = getAnalysisToUpdate<LiveVariables>();
287 bool MadeChange = false;
289 DOUT << "********** REWRITING TWO-ADDR INSTRS **********\n";
290 DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
292 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
294 ReMatRegs.resize(MRI->getLastVirtReg()+1);
296 // DistanceMap - Keep track the distance of a MI from the start of the
297 // current basic block.
298 DenseMap<MachineInstr*, unsigned> DistanceMap;
300 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
301 mbbi != mbbe; ++mbbi) {
304 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
306 MachineBasicBlock::iterator nmi = next(mi);
307 const TargetInstrDesc &TID = mi->getDesc();
308 bool FirstTied = true;
310 DistanceMap.insert(std::make_pair(mi, ++Dist));
311 for (unsigned si = 1, e = TID.getNumOperands(); si < e; ++si) {
312 int ti = TID.getOperandConstraint(si, TOI::TIED_TO);
317 ++NumTwoAddressInstrs;
318 DOUT << '\t'; DEBUG(mi->print(*cerr.stream(), &TM));
323 assert(mi->getOperand(si).isRegister() && mi->getOperand(si).getReg() &&
324 mi->getOperand(si).isUse() && "two address instruction invalid");
326 // If the two operands are the same we just remove the use
327 // and mark the def as def&use, otherwise we have to insert a copy.
328 if (mi->getOperand(ti).getReg() != mi->getOperand(si).getReg()) {
334 unsigned regA = mi->getOperand(ti).getReg();
335 unsigned regB = mi->getOperand(si).getReg();
337 assert(TargetRegisterInfo::isVirtualRegister(regA) &&
338 TargetRegisterInfo::isVirtualRegister(regB) &&
339 "cannot update physical register live information");
342 // First, verify that we don't have a use of a in the instruction (a =
343 // b + a for example) because our transformation will not work. This
344 // should never occur because we are in SSA form.
345 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
346 assert((int)i == ti ||
347 !mi->getOperand(i).isRegister() ||
348 mi->getOperand(i).getReg() != regA);
351 // If this instruction is not the killing user of B, see if we can
352 // rearrange the code to make it so. Making it the killing user will
353 // allow us to coalesce A and B together, eliminating the copy we are
355 if (!mi->killsRegister(regB)) {
356 // If this instruction is commutative, check to see if C dies. If
357 // so, swap the B and C operands. This makes the live ranges of A
359 // FIXME: This code also works for A := B op C instructions.
360 if (TID.isCommutable() && mi->getNumOperands() >= 3) {
361 assert(mi->getOperand(3-si).isRegister() &&
362 "Not a proper commutative instruction!");
363 unsigned regC = mi->getOperand(3-si).getReg();
365 if (mi->killsRegister(regC)) {
366 DOUT << "2addr: COMMUTING : " << *mi;
367 MachineInstr *NewMI = TII->commuteInstruction(mi);
370 DOUT << "2addr: COMMUTING FAILED!\n";
372 DOUT << "2addr: COMMUTED TO: " << *NewMI;
373 // If the instruction changed to commute it, update livevar.
376 // Update live variables
377 LV->replaceKillInstruction(regC, mi, NewMI);
379 mbbi->insert(mi, NewMI); // Insert the new inst
380 mbbi->erase(mi); // Nuke the old inst.
382 DistanceMap.insert(std::make_pair(NewMI, Dist));
387 goto InstructionRearranged;
392 // If this instruction is potentially convertible to a true
393 // three-address instruction,
394 if (TID.isConvertibleTo3Addr()) {
395 // FIXME: This assumes there are no more operands which are tied
396 // to another register.
398 for (unsigned i = si + 1, e = TID.getNumOperands(); i < e; ++i)
399 assert(TID.getOperandConstraint(i, TOI::TIED_TO) == -1);
402 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
404 DOUT << "2addr: CONVERTING 2-ADDR: " << *mi;
405 DOUT << "2addr: TO 3-ADDR: " << *NewMI;
408 if (NewMI->findRegisterUseOperand(regB, false, TRI))
409 // FIXME: Temporary workaround. If the new instruction doesn't
410 // uses regB, convertToThreeAddress must have created more
411 // then one instruction.
412 Sunk = Sink3AddrInstruction(mbbi, NewMI, regB, mi);
414 mbbi->erase(mi); // Nuke the old inst.
417 DistanceMap.insert(std::make_pair(NewMI, Dist));
422 ++NumConvertedTo3Addr;
423 break; // Done with this instruction.
428 InstructionRearranged:
429 const TargetRegisterClass* rc = MRI->getRegClass(regA);
430 MachineInstr *DefMI = MRI->getVRegDef(regB);
431 // If it's safe and profitable, remat the definition instead of
434 isSafeToReMat(regB, DefMI) &&
435 isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist,DistanceMap)){
436 DEBUG(cerr << "2addr: REMATTING : " << *DefMI << "\n");
437 TII->reMaterialize(*mbbi, mi, regA, DefMI);
441 TII->copyRegToReg(*mbbi, mi, regA, regB, rc, rc);
444 MachineBasicBlock::iterator prevMi = prior(mi);
445 DOUT << "\t\tprepend:\t"; DEBUG(prevMi->print(*cerr.stream(), &TM));
447 // Update live variables for regB.
449 LiveVariables::VarInfo& varInfoB = LV->getVarInfo(regB);
451 // regB is used in this BB.
452 varInfoB.UsedBlocks[mbbi->getNumber()] = true;
454 if (LV->removeVirtualRegisterKilled(regB, mi))
455 LV->addVirtualRegisterKilled(regB, prevMi);
457 if (LV->removeVirtualRegisterDead(regB, mi))
458 LV->addVirtualRegisterDead(regB, prevMi);
461 // Replace all occurences of regB with regA.
462 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
463 if (mi->getOperand(i).isRegister() &&
464 mi->getOperand(i).getReg() == regB)
465 mi->getOperand(i).setReg(regA);
469 assert(mi->getOperand(ti).isDef() && mi->getOperand(si).isUse());
470 mi->getOperand(ti).setReg(mi->getOperand(si).getReg());
473 DOUT << "\t\trewrite to:\t"; DEBUG(mi->print(*cerr.stream(), &TM));
480 // Some remat'ed instructions are dead.
481 int VReg = ReMatRegs.find_first();
483 if (MRI->use_empty(VReg)) {
484 MachineInstr *DefMI = MRI->getVRegDef(VReg);
485 DefMI->eraseFromParent();
487 VReg = ReMatRegs.find_next(VReg);