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/Target/TargetOptions.h"
41 #include "llvm/Support/Compiler.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/DenseMap.h"
45 #include "llvm/ADT/SmallSet.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/ADT/STLExtras.h"
50 STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
51 STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
52 STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
53 STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
54 STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
55 STATISTIC(NumReMats, "Number of instructions re-materialized");
58 class VISIBILITY_HIDDEN TwoAddressInstructionPass
59 : public MachineFunctionPass {
60 const TargetInstrInfo *TII;
61 const TargetRegisterInfo *TRI;
62 MachineRegisterInfo *MRI;
65 bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
67 MachineBasicBlock::iterator OldPos);
69 bool isProfitableToReMat(unsigned Reg, const TargetRegisterClass *RC,
70 MachineInstr *MI, MachineInstr *DefMI,
71 MachineBasicBlock *MBB, unsigned Loc,
72 DenseMap<MachineInstr*, unsigned> &DistanceMap);
74 bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
75 DenseMap<MachineInstr*, unsigned> &DistanceMap,
78 bool isProfitableToCommute(unsigned regB, unsigned regC,
79 MachineInstr *MI, MachineBasicBlock *MBB,
81 DenseMap<MachineInstr*, unsigned> &DistanceMap);
83 bool CommuteInstruction(MachineBasicBlock::iterator &mi,
84 MachineFunction::iterator &mbbi,
85 unsigned RegC, unsigned Dist,
86 DenseMap<MachineInstr*, unsigned> &DistanceMap);
88 static char ID; // Pass identification, replacement for typeid
89 TwoAddressInstructionPass() : MachineFunctionPass(&ID) {}
91 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
92 AU.addPreserved<LiveVariables>();
93 AU.addPreservedID(MachineLoopInfoID);
94 AU.addPreservedID(MachineDominatorsID);
96 AU.addPreservedID(StrongPHIEliminationID);
98 AU.addPreservedID(PHIEliminationID);
99 MachineFunctionPass::getAnalysisUsage(AU);
102 /// runOnMachineFunction - Pass entry point.
103 bool runOnMachineFunction(MachineFunction&);
107 char TwoAddressInstructionPass::ID = 0;
108 static RegisterPass<TwoAddressInstructionPass>
109 X("twoaddressinstruction", "Two-Address instruction pass");
111 const PassInfo *const llvm::TwoAddressInstructionPassID = &X;
113 /// Sink3AddrInstruction - A two-address instruction has been converted to a
114 /// three-address instruction to avoid clobbering a register. Try to sink it
115 /// past the instruction that would kill the above mentioned register to reduce
116 /// register pressure.
117 bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
118 MachineInstr *MI, unsigned SavedReg,
119 MachineBasicBlock::iterator OldPos) {
120 // Check if it's safe to move this instruction.
121 bool SeenStore = true; // Be conservative.
122 if (!MI->isSafeToMove(TII, SeenStore))
126 SmallSet<unsigned, 4> UseRegs;
128 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
129 const MachineOperand &MO = MI->getOperand(i);
132 unsigned MOReg = MO.getReg();
135 if (MO.isUse() && MOReg != SavedReg)
136 UseRegs.insert(MO.getReg());
140 // Don't try to move it if it implicitly defines a register.
143 // For now, don't move any instructions that define multiple registers.
145 DefReg = MO.getReg();
148 // Find the instruction that kills SavedReg.
149 MachineInstr *KillMI = NULL;
150 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SavedReg),
151 UE = MRI->use_end(); UI != UE; ++UI) {
152 MachineOperand &UseMO = UI.getOperand();
155 KillMI = UseMO.getParent();
159 if (!KillMI || KillMI->getParent() != MBB)
162 // If any of the definitions are used by another instruction between the
163 // position and the kill use, then it's not safe to sink it.
165 // FIXME: This can be sped up if there is an easy way to query whether an
166 // instruction is before or after another instruction. Then we can use
167 // MachineRegisterInfo def / use instead.
168 MachineOperand *KillMO = NULL;
169 MachineBasicBlock::iterator KillPos = KillMI;
172 unsigned NumVisited = 0;
173 for (MachineBasicBlock::iterator I = next(OldPos); I != KillPos; ++I) {
174 MachineInstr *OtherMI = I;
175 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
178 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
179 MachineOperand &MO = OtherMI->getOperand(i);
182 unsigned MOReg = MO.getReg();
189 if (OtherMI == KillMI && MOReg == SavedReg)
190 // Save the operand that kills the register. We want to unset the kill
191 // marker if we can sink MI past it.
193 else if (UseRegs.count(MOReg))
194 // One of the uses is killed before the destination.
200 // Update kill and LV information.
201 KillMO->setIsKill(false);
202 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
203 KillMO->setIsKill(true);
206 LV->replaceKillInstruction(SavedReg, KillMI, MI);
208 // Move instruction to its destination.
210 MBB->insert(KillPos, MI);
216 /// isTwoAddrUse - Return true if the specified MI is using the specified
217 /// register as a two-address operand.
218 static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
219 const TargetInstrDesc &TID = UseMI->getDesc();
220 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
221 MachineOperand &MO = UseMI->getOperand(i);
222 if (MO.isReg() && MO.getReg() == Reg &&
223 (MO.isDef() || TID.getOperandConstraint(i, TOI::TIED_TO) != -1))
224 // Earlier use is a two-address one.
230 /// isProfitableToReMat - Return true if the heuristics determines it is likely
231 /// to be profitable to re-materialize the definition of Reg rather than copy
234 TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
235 const TargetRegisterClass *RC,
236 MachineInstr *MI, MachineInstr *DefMI,
237 MachineBasicBlock *MBB, unsigned Loc,
238 DenseMap<MachineInstr*, unsigned> &DistanceMap){
239 bool OtherUse = false;
240 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
241 UE = MRI->use_end(); UI != UE; ++UI) {
242 MachineOperand &UseMO = UI.getOperand();
243 MachineInstr *UseMI = UseMO.getParent();
244 MachineBasicBlock *UseMBB = UseMI->getParent();
246 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
247 if (DI != DistanceMap.end() && DI->second == Loc)
248 continue; // Current use.
250 // There is at least one other use in the MBB that will clobber the
252 if (isTwoAddrUse(UseMI, Reg))
257 // If other uses in MBB are not two-address uses, then don't remat.
261 // No other uses in the same block, remat if it's defined in the same
262 // block so it does not unnecessarily extend the live range.
263 return MBB == DefMI->getParent();
266 /// NoUseAfterLastDef - Return true if there are no intervening uses between the
267 /// last instruction in the MBB that defines the specified register and the
268 /// two-address instruction which is being processed. It also returns the last
269 /// def location by reference
270 bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
271 MachineBasicBlock *MBB, unsigned Dist,
272 DenseMap<MachineInstr*, unsigned> &DistanceMap,
275 unsigned LastUse = Dist;
276 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
277 E = MRI->reg_end(); I != E; ++I) {
278 MachineOperand &MO = I.getOperand();
279 MachineInstr *MI = MO.getParent();
280 if (MI->getParent() != MBB)
282 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
283 if (DI == DistanceMap.end())
285 if (MO.isUse() && DI->second < LastUse)
286 LastUse = DI->second;
287 if (MO.isDef() && DI->second > LastDef)
288 LastDef = DI->second;
291 return !(LastUse > LastDef && LastUse < Dist);
294 /// isProfitableToReMat - Return true if it's potentially profitable to commute
295 /// the two-address instruction that's being processed.
297 TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC,
298 MachineInstr *MI, MachineBasicBlock *MBB,
299 unsigned Dist, DenseMap<MachineInstr*, unsigned> &DistanceMap) {
300 // Determine if it's profitable to commute this two address instruction. In
301 // general, we want no uses between this instruction and the definition of
302 // the two-address register.
304 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
305 // %reg1029<def> = MOV8rr %reg1028
306 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
307 // insert => %reg1030<def> = MOV8rr %reg1028
308 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
309 // In this case, it might not be possible to coalesce the second MOV8rr
310 // instruction if the first one is coalesced. So it would be profitable to
312 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
313 // %reg1029<def> = MOV8rr %reg1028
314 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
315 // insert => %reg1030<def> = MOV8rr %reg1029
316 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
318 if (!MI->killsRegister(regC))
321 // Ok, we have something like:
322 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
323 // let's see if it's worth commuting it.
325 // If there is a use of regC between its last def (could be livein) and this
326 // instruction, then bail.
327 unsigned LastDefC = 0;
328 if (!NoUseAfterLastDef(regC, MBB, Dist, DistanceMap, LastDefC))
331 // If there is a use of regB between its last def (could be livein) and this
332 // instruction, then go ahead and make this transformation.
333 unsigned LastDefB = 0;
334 if (!NoUseAfterLastDef(regB, MBB, Dist, DistanceMap, LastDefB))
337 // Since there are no intervening uses for both registers, then commute
338 // if the def of regC is closer. Its live interval is shorter.
339 return LastDefB && LastDefC && LastDefC > LastDefB;
342 /// CommuteInstruction - Commute a two-address instruction and update the basic
343 /// block, distance map, and live variables if needed. Return true if it is
346 TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
347 MachineFunction::iterator &mbbi,
348 unsigned RegC, unsigned Dist,
349 DenseMap<MachineInstr*, unsigned> &DistanceMap) {
350 MachineInstr *MI = mi;
351 DOUT << "2addr: COMMUTING : " << *MI;
352 MachineInstr *NewMI = TII->commuteInstruction(MI);
355 DOUT << "2addr: COMMUTING FAILED!\n";
359 DOUT << "2addr: COMMUTED TO: " << *NewMI;
360 // If the instruction changed to commute it, update livevar.
363 // Update live variables
364 LV->replaceKillInstruction(RegC, MI, NewMI);
366 mbbi->insert(mi, NewMI); // Insert the new inst
367 mbbi->erase(mi); // Nuke the old inst.
369 DistanceMap.insert(std::make_pair(NewMI, Dist));
374 /// runOnMachineFunction - Reduce two-address instructions to two operands.
376 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
377 DOUT << "Machine Function\n";
378 const TargetMachine &TM = MF.getTarget();
379 MRI = &MF.getRegInfo();
380 TII = TM.getInstrInfo();
381 TRI = TM.getRegisterInfo();
382 LV = getAnalysisIfAvailable<LiveVariables>();
384 bool MadeChange = false;
386 DOUT << "********** REWRITING TWO-ADDR INSTRS **********\n";
387 DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
389 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
391 ReMatRegs.resize(MRI->getLastVirtReg()+1);
393 // DistanceMap - Keep track the distance of a MI from the start of the
394 // current basic block.
395 DenseMap<MachineInstr*, unsigned> DistanceMap;
397 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
398 mbbi != mbbe; ++mbbi) {
401 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
403 MachineBasicBlock::iterator nmi = next(mi);
404 const TargetInstrDesc &TID = mi->getDesc();
405 bool FirstTied = true;
407 DistanceMap.insert(std::make_pair(mi, ++Dist));
408 for (unsigned si = 1, e = TID.getNumOperands(); si < e; ++si) {
409 int ti = TID.getOperandConstraint(si, TOI::TIED_TO);
414 ++NumTwoAddressInstrs;
415 DOUT << '\t'; DEBUG(mi->print(*cerr.stream(), &TM));
420 assert(mi->getOperand(si).isReg() && mi->getOperand(si).getReg() &&
421 mi->getOperand(si).isUse() && "two address instruction invalid");
423 // If the two operands are the same we just remove the use
424 // and mark the def as def&use, otherwise we have to insert a copy.
425 if (mi->getOperand(ti).getReg() != mi->getOperand(si).getReg()) {
431 unsigned regA = mi->getOperand(ti).getReg();
432 unsigned regB = mi->getOperand(si).getReg();
434 assert(TargetRegisterInfo::isVirtualRegister(regA) &&
435 TargetRegisterInfo::isVirtualRegister(regB) &&
436 "cannot update physical register live information");
439 // First, verify that we don't have a use of a in the instruction (a =
440 // b + a for example) because our transformation will not work. This
441 // should never occur because we are in SSA form.
442 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
443 assert((int)i == ti ||
444 !mi->getOperand(i).isReg() ||
445 mi->getOperand(i).getReg() != regA);
448 // If this instruction is not the killing user of B, see if we can
449 // rearrange the code to make it so. Making it the killing user will
450 // allow us to coalesce A and B together, eliminating the copy we are
452 if (!mi->killsRegister(regB)) {
453 // If this instruction is commutative, check to see if C dies. If
454 // so, swap the B and C operands. This makes the live ranges of A
456 // FIXME: This code also works for A := B op C instructions.
457 if (TID.isCommutable() && mi->getNumOperands() >= 3) {
458 assert(mi->getOperand(3-si).isReg() &&
459 "Not a proper commutative instruction!");
460 unsigned regC = mi->getOperand(3-si).getReg();
461 if (mi->killsRegister(regC)) {
462 if (CommuteInstruction(mi, mbbi, regC, Dist, DistanceMap)) {
465 goto InstructionRearranged;
470 // If this instruction is potentially convertible to a true
471 // three-address instruction,
472 if (TID.isConvertibleTo3Addr()) {
473 // FIXME: This assumes there are no more operands which are tied
474 // to another register.
476 for (unsigned i = si + 1, e = TID.getNumOperands(); i < e; ++i)
477 assert(TID.getOperandConstraint(i, TOI::TIED_TO) == -1);
480 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
482 DOUT << "2addr: CONVERTING 2-ADDR: " << *mi;
483 DOUT << "2addr: TO 3-ADDR: " << *NewMI;
486 if (NewMI->findRegisterUseOperand(regB, false, TRI))
487 // FIXME: Temporary workaround. If the new instruction doesn't
488 // uses regB, convertToThreeAddress must have created more
489 // then one instruction.
490 Sunk = Sink3AddrInstruction(mbbi, NewMI, regB, mi);
492 mbbi->erase(mi); // Nuke the old inst.
495 DistanceMap.insert(std::make_pair(NewMI, Dist));
500 ++NumConvertedTo3Addr;
501 break; // Done with this instruction.
506 // If it's profitable to commute the instruction, do so.
507 if (TID.isCommutable() && mi->getNumOperands() >= 3) {
508 unsigned regC = mi->getOperand(3-si).getReg();
509 if (isProfitableToCommute(regB, regC, mi, mbbi, Dist, DistanceMap))
510 if (CommuteInstruction(mi, mbbi, regC, Dist, DistanceMap)) {
517 InstructionRearranged:
518 const TargetRegisterClass* rc = MRI->getRegClass(regA);
519 MachineInstr *DefMI = MRI->getVRegDef(regB);
520 // If it's safe and profitable, remat the definition instead of
523 DefMI->getDesc().isAsCheapAsAMove() &&
524 DefMI->isSafeToReMat(TII, regB) &&
525 isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist,DistanceMap)){
526 DEBUG(cerr << "2addr: REMATTING : " << *DefMI << "\n");
527 TII->reMaterialize(*mbbi, mi, regA, DefMI);
531 TII->copyRegToReg(*mbbi, mi, regA, regB, rc, rc);
534 MachineBasicBlock::iterator prevMI = prior(mi);
535 // Update DistanceMap.
536 DistanceMap.insert(std::make_pair(prevMI, Dist));
537 DistanceMap[mi] = ++Dist;
539 // Update live variables for regB.
541 LiveVariables::VarInfo& varInfoB = LV->getVarInfo(regB);
543 // regB is used in this BB.
544 varInfoB.UsedBlocks[mbbi->getNumber()] = true;
546 if (LV->removeVirtualRegisterKilled(regB, mi))
547 LV->addVirtualRegisterKilled(regB, prevMI);
549 if (LV->removeVirtualRegisterDead(regB, mi))
550 LV->addVirtualRegisterDead(regB, prevMI);
553 DOUT << "\t\tprepend:\t"; DEBUG(prevMI->print(*cerr.stream(), &TM));
555 // Replace all occurences of regB with regA.
556 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
557 if (mi->getOperand(i).isReg() &&
558 mi->getOperand(i).getReg() == regB)
559 mi->getOperand(i).setReg(regA);
563 assert(mi->getOperand(ti).isDef() && mi->getOperand(si).isUse());
564 mi->getOperand(ti).setReg(mi->getOperand(si).getReg());
567 DOUT << "\t\trewrite to:\t"; DEBUG(mi->print(*cerr.stream(), &TM));
574 // Some remat'ed instructions are dead.
575 int VReg = ReMatRegs.find_first();
577 if (MRI->use_empty(VReg)) {
578 MachineInstr *DefMI = MRI->getVRegDef(VReg);
579 DefMI->eraseFromParent();
581 VReg = ReMatRegs.find_next(VReg);