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");
56 STATISTIC(NumDeletes, "Number of dead instructions deleted");
59 class VISIBILITY_HIDDEN TwoAddressInstructionPass
60 : public MachineFunctionPass {
61 const TargetInstrInfo *TII;
62 const TargetRegisterInfo *TRI;
63 MachineRegisterInfo *MRI;
66 // DistanceMap - Keep track the distance of a MI from the start of the
67 // current basic block.
68 DenseMap<MachineInstr*, unsigned> DistanceMap;
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;
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;
80 bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
82 MachineBasicBlock::iterator OldPos);
84 bool isProfitableToReMat(unsigned Reg, const TargetRegisterClass *RC,
85 MachineInstr *MI, MachineInstr *DefMI,
86 MachineBasicBlock *MBB, unsigned Loc);
88 bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
91 MachineInstr *FindLastUseInMBB(unsigned Reg, MachineBasicBlock *MBB,
94 bool isProfitableToCommute(unsigned regB, unsigned regC,
95 MachineInstr *MI, MachineBasicBlock *MBB,
98 bool CommuteInstruction(MachineBasicBlock::iterator &mi,
99 MachineFunction::iterator &mbbi,
100 unsigned RegB, unsigned RegC, unsigned Dist);
102 bool isProfitableToConv3Addr(unsigned RegA);
104 bool ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
105 MachineBasicBlock::iterator &nmi,
106 MachineFunction::iterator &mbbi,
107 unsigned RegB, unsigned Dist);
109 void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
110 SmallPtrSet<MachineInstr*, 8> &Processed);
112 static char ID; // Pass identification, replacement for typeid
113 TwoAddressInstructionPass() : MachineFunctionPass(&ID) {}
115 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
116 AU.addPreserved<LiveVariables>();
117 AU.addPreservedID(MachineLoopInfoID);
118 AU.addPreservedID(MachineDominatorsID);
120 AU.addPreservedID(StrongPHIEliminationID);
122 AU.addPreservedID(PHIEliminationID);
123 MachineFunctionPass::getAnalysisUsage(AU);
126 /// runOnMachineFunction - Pass entry point.
127 bool runOnMachineFunction(MachineFunction&);
131 char TwoAddressInstructionPass::ID = 0;
132 static RegisterPass<TwoAddressInstructionPass>
133 X("twoaddressinstruction", "Two-Address instruction pass");
135 const PassInfo *const llvm::TwoAddressInstructionPassID = &X;
137 /// Sink3AddrInstruction - A two-address instruction has been converted to a
138 /// three-address instruction to avoid clobbering a register. Try to sink it
139 /// past the instruction that would kill the above mentioned register to reduce
140 /// register pressure.
141 bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
142 MachineInstr *MI, unsigned SavedReg,
143 MachineBasicBlock::iterator OldPos) {
144 // Check if it's safe to move this instruction.
145 bool SeenStore = true; // Be conservative.
146 if (!MI->isSafeToMove(TII, SeenStore))
150 SmallSet<unsigned, 4> UseRegs;
152 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
153 const MachineOperand &MO = MI->getOperand(i);
156 unsigned MOReg = MO.getReg();
159 if (MO.isUse() && MOReg != SavedReg)
160 UseRegs.insert(MO.getReg());
164 // Don't try to move it if it implicitly defines a register.
167 // For now, don't move any instructions that define multiple registers.
169 DefReg = MO.getReg();
172 // Find the instruction that kills SavedReg.
173 MachineInstr *KillMI = NULL;
174 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SavedReg),
175 UE = MRI->use_end(); UI != UE; ++UI) {
176 MachineOperand &UseMO = UI.getOperand();
179 KillMI = UseMO.getParent();
183 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI)
186 // If any of the definitions are used by another instruction between the
187 // position and the kill use, then it's not safe to sink it.
189 // FIXME: This can be sped up if there is an easy way to query whether an
190 // instruction is before or after another instruction. Then we can use
191 // MachineRegisterInfo def / use instead.
192 MachineOperand *KillMO = NULL;
193 MachineBasicBlock::iterator KillPos = KillMI;
196 unsigned NumVisited = 0;
197 for (MachineBasicBlock::iterator I = next(OldPos); I != KillPos; ++I) {
198 MachineInstr *OtherMI = I;
199 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
202 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
203 MachineOperand &MO = OtherMI->getOperand(i);
206 unsigned MOReg = MO.getReg();
213 if (OtherMI == KillMI && MOReg == SavedReg)
214 // Save the operand that kills the register. We want to unset the kill
215 // marker if we can sink MI past it.
217 else if (UseRegs.count(MOReg))
218 // One of the uses is killed before the destination.
224 // Update kill and LV information.
225 KillMO->setIsKill(false);
226 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
227 KillMO->setIsKill(true);
230 LV->replaceKillInstruction(SavedReg, KillMI, MI);
232 // Move instruction to its destination.
234 MBB->insert(KillPos, MI);
240 /// isTwoAddrUse - Return true if the specified MI is using the specified
241 /// register as a two-address operand.
242 static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
243 const TargetInstrDesc &TID = UseMI->getDesc();
244 for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
245 MachineOperand &MO = UseMI->getOperand(i);
246 if (MO.isReg() && MO.getReg() == Reg &&
247 (MO.isDef() || UseMI->isRegTiedToDefOperand(i)))
248 // Earlier use is a two-address one.
254 /// isProfitableToReMat - Return true if the heuristics determines it is likely
255 /// to be profitable to re-materialize the definition of Reg rather than copy
258 TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
259 const TargetRegisterClass *RC,
260 MachineInstr *MI, MachineInstr *DefMI,
261 MachineBasicBlock *MBB, unsigned Loc) {
262 bool OtherUse = false;
263 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
264 UE = MRI->use_end(); UI != UE; ++UI) {
265 MachineOperand &UseMO = UI.getOperand();
266 MachineInstr *UseMI = UseMO.getParent();
267 MachineBasicBlock *UseMBB = UseMI->getParent();
269 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
270 if (DI != DistanceMap.end() && DI->second == Loc)
271 continue; // Current use.
273 // There is at least one other use in the MBB that will clobber the
275 if (isTwoAddrUse(UseMI, Reg))
280 // If other uses in MBB are not two-address uses, then don't remat.
284 // No other uses in the same block, remat if it's defined in the same
285 // block so it does not unnecessarily extend the live range.
286 return MBB == DefMI->getParent();
289 /// NoUseAfterLastDef - Return true if there are no intervening uses between the
290 /// last instruction in the MBB that defines the specified register and the
291 /// two-address instruction which is being processed. It also returns the last
292 /// def location by reference
293 bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
294 MachineBasicBlock *MBB, unsigned Dist,
297 unsigned LastUse = Dist;
298 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
299 E = MRI->reg_end(); I != E; ++I) {
300 MachineOperand &MO = I.getOperand();
301 MachineInstr *MI = MO.getParent();
302 if (MI->getParent() != MBB)
304 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
305 if (DI == DistanceMap.end())
307 if (MO.isUse() && DI->second < LastUse)
308 LastUse = DI->second;
309 if (MO.isDef() && DI->second > LastDef)
310 LastDef = DI->second;
313 return !(LastUse > LastDef && LastUse < Dist);
316 MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg,
317 MachineBasicBlock *MBB,
319 unsigned LastUseDist = Dist;
320 MachineInstr *LastUse = 0;
321 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
322 E = MRI->reg_end(); I != E; ++I) {
323 MachineOperand &MO = I.getOperand();
324 MachineInstr *MI = MO.getParent();
325 if (MI->getParent() != MBB)
327 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
328 if (DI == DistanceMap.end())
330 if (MO.isUse() && DI->second < LastUseDist) {
332 LastUseDist = DI->second;
338 /// isCopyToReg - Return true if the specified MI is a copy instruction or
339 /// a extract_subreg instruction. It also returns the source and destination
340 /// registers and whether they are physical registers by reference.
341 static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
342 unsigned &SrcReg, unsigned &DstReg,
343 bool &IsSrcPhys, bool &IsDstPhys) {
346 unsigned SrcSubIdx, DstSubIdx;
347 if (!TII->isMoveInstr(MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
348 if (MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
349 DstReg = MI.getOperand(0).getReg();
350 SrcReg = MI.getOperand(1).getReg();
351 } else if (MI.getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
352 DstReg = MI.getOperand(0).getReg();
353 SrcReg = MI.getOperand(2).getReg();
354 } else if (MI.getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
355 DstReg = MI.getOperand(0).getReg();
356 SrcReg = MI.getOperand(2).getReg();
361 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
362 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
368 /// isKilled - Test if the given register value, which is used by the given
369 /// instruction, is killed by the given instruction. This looks through
370 /// coalescable copies to see if the original value is potentially not killed.
372 /// For example, in this code:
374 /// %reg1034 = copy %reg1024
375 /// %reg1035 = copy %reg1025<kill>
376 /// %reg1036 = add %reg1034<kill>, %reg1035<kill>
378 /// %reg1034 is not considered to be killed, since it is copied from a
379 /// register which is not killed. Treating it as not killed lets the
380 /// normal heuristics commute the (two-address) add, which lets
381 /// coalescing eliminate the extra copy.
383 static bool isKilled(MachineInstr &MI, unsigned Reg,
384 const MachineRegisterInfo *MRI,
385 const TargetInstrInfo *TII) {
386 MachineInstr *DefMI = &MI;
388 if (!DefMI->killsRegister(Reg))
390 if (TargetRegisterInfo::isPhysicalRegister(Reg))
392 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
393 // If there are multiple defs, we can't do a simple analysis, so just
394 // go with what the kill flag says.
395 if (next(Begin) != MRI->def_end())
398 bool IsSrcPhys, IsDstPhys;
399 unsigned SrcReg, DstReg;
400 // If the def is something other than a copy, then it isn't going to
401 // be coalesced, so follow the kill flag.
402 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
408 /// isTwoAddrUse - Return true if the specified MI uses the specified register
409 /// as a two-address use. If so, return the destination register by reference.
410 static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
411 const TargetInstrDesc &TID = MI.getDesc();
412 unsigned NumOps = (MI.getOpcode() == TargetInstrInfo::INLINEASM)
413 ? MI.getNumOperands() : TID.getNumOperands();
414 for (unsigned i = 0; i != NumOps; ++i) {
415 const MachineOperand &MO = MI.getOperand(i);
416 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
419 if (MI.isRegTiedToDefOperand(i, &ti)) {
420 DstReg = MI.getOperand(ti).getReg();
427 /// findOnlyInterestingUse - Given a register, if has a single in-basic block
428 /// use, return the use instruction if it's a copy or a two-address use.
430 MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
431 MachineRegisterInfo *MRI,
432 const TargetInstrInfo *TII,
434 unsigned &DstReg, bool &IsDstPhys) {
435 MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg);
436 if (UI == MRI->use_end())
438 MachineInstr &UseMI = *UI;
439 if (++UI != MRI->use_end())
440 // More than one use.
442 if (UseMI.getParent() != MBB)
446 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
451 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
452 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
458 /// getMappedReg - Return the physical register the specified virtual register
459 /// might be mapped to.
461 getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
462 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
463 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
464 if (SI == RegMap.end())
468 if (TargetRegisterInfo::isPhysicalRegister(Reg))
473 /// regsAreCompatible - Return true if the two registers are equal or aliased.
476 regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
481 return TRI->regsOverlap(RegA, RegB);
485 /// isProfitableToReMat - Return true if it's potentially profitable to commute
486 /// the two-address instruction that's being processed.
488 TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC,
489 MachineInstr *MI, MachineBasicBlock *MBB,
491 // Determine if it's profitable to commute this two address instruction. In
492 // general, we want no uses between this instruction and the definition of
493 // the two-address register.
495 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
496 // %reg1029<def> = MOV8rr %reg1028
497 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
498 // insert => %reg1030<def> = MOV8rr %reg1028
499 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
500 // In this case, it might not be possible to coalesce the second MOV8rr
501 // instruction if the first one is coalesced. So it would be profitable to
503 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
504 // %reg1029<def> = MOV8rr %reg1028
505 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
506 // insert => %reg1030<def> = MOV8rr %reg1029
507 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
509 if (!MI->killsRegister(regC))
512 // Ok, we have something like:
513 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
514 // let's see if it's worth commuting it.
516 // Look for situations like this:
517 // %reg1024<def> = MOV r1
518 // %reg1025<def> = MOV r0
519 // %reg1026<def> = ADD %reg1024, %reg1025
521 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
522 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
523 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
524 unsigned ToRegB = getMappedReg(regB, DstRegMap);
525 unsigned ToRegC = getMappedReg(regC, DstRegMap);
526 if (!regsAreCompatible(FromRegB, ToRegB, TRI) &&
527 (regsAreCompatible(FromRegB, ToRegC, TRI) ||
528 regsAreCompatible(FromRegC, ToRegB, TRI)))
531 // If there is a use of regC between its last def (could be livein) and this
532 // instruction, then bail.
533 unsigned LastDefC = 0;
534 if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
537 // If there is a use of regB between its last def (could be livein) and this
538 // instruction, then go ahead and make this transformation.
539 unsigned LastDefB = 0;
540 if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
543 // Since there are no intervening uses for both registers, then commute
544 // if the def of regC is closer. Its live interval is shorter.
545 return LastDefB && LastDefC && LastDefC > LastDefB;
548 /// CommuteInstruction - Commute a two-address instruction and update the basic
549 /// block, distance map, and live variables if needed. Return true if it is
552 TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
553 MachineFunction::iterator &mbbi,
554 unsigned RegB, unsigned RegC, unsigned Dist) {
555 MachineInstr *MI = mi;
556 DOUT << "2addr: COMMUTING : " << *MI;
557 MachineInstr *NewMI = TII->commuteInstruction(MI);
560 DOUT << "2addr: COMMUTING FAILED!\n";
564 DOUT << "2addr: COMMUTED TO: " << *NewMI;
565 // If the instruction changed to commute it, update livevar.
568 // Update live variables
569 LV->replaceKillInstruction(RegC, MI, NewMI);
571 mbbi->insert(mi, NewMI); // Insert the new inst
572 mbbi->erase(mi); // Nuke the old inst.
574 DistanceMap.insert(std::make_pair(NewMI, Dist));
577 // Update source register map.
578 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
580 unsigned RegA = MI->getOperand(0).getReg();
581 SrcRegMap[RegA] = FromRegC;
587 /// isProfitableToConv3Addr - Return true if it is profitable to convert the
588 /// given 2-address instruction to a 3-address one.
590 TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA) {
591 // Look for situations like this:
592 // %reg1024<def> = MOV r1
593 // %reg1025<def> = MOV r0
594 // %reg1026<def> = ADD %reg1024, %reg1025
596 // Turn ADD into a 3-address instruction to avoid a copy.
597 unsigned FromRegA = getMappedReg(RegA, SrcRegMap);
598 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
599 return (FromRegA && ToRegA && !regsAreCompatible(FromRegA, ToRegA, TRI));
602 /// ConvertInstTo3Addr - Convert the specified two-address instruction into a
603 /// three address one. Return true if this transformation was successful.
605 TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
606 MachineBasicBlock::iterator &nmi,
607 MachineFunction::iterator &mbbi,
608 unsigned RegB, unsigned Dist) {
609 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
611 DOUT << "2addr: CONVERTING 2-ADDR: " << *mi;
612 DOUT << "2addr: TO 3-ADDR: " << *NewMI;
615 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
616 // FIXME: Temporary workaround. If the new instruction doesn't
617 // uses RegB, convertToThreeAddress must have created more
618 // then one instruction.
619 Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
621 mbbi->erase(mi); // Nuke the old inst.
624 DistanceMap.insert(std::make_pair(NewMI, Dist));
634 /// ProcessCopy - If the specified instruction is not yet processed, process it
635 /// if it's a copy. For a copy instruction, we find the physical registers the
636 /// source and destination registers might be mapped to. These are kept in
637 /// point-to maps used to determine future optimizations. e.g.
640 /// v1026 = add v1024, v1025
642 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
643 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
644 /// potentially joined with r1 on the output side. It's worthwhile to commute
645 /// 'add' to eliminate a copy.
646 void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
647 MachineBasicBlock *MBB,
648 SmallPtrSet<MachineInstr*, 8> &Processed) {
649 if (Processed.count(MI))
652 bool IsSrcPhys, IsDstPhys;
653 unsigned SrcReg, DstReg;
654 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
657 if (IsDstPhys && !IsSrcPhys)
658 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
659 else if (!IsDstPhys && IsSrcPhys) {
660 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
662 assert(SrcRegMap[DstReg] == SrcReg &&
663 "Can't map to two src physical registers!");
665 SmallVector<unsigned, 4> VirtRegPairs;
668 while (MachineInstr *UseMI = findOnlyInterestingUse(DstReg, MBB, MRI,TII,
669 IsCopy, NewReg, IsDstPhys)) {
671 if (!Processed.insert(UseMI))
675 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
676 if (DI != DistanceMap.end())
677 // Earlier in the same MBB.Reached via a back edge.
681 VirtRegPairs.push_back(NewReg);
684 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, DstReg)).second;
686 assert(SrcRegMap[NewReg] == DstReg &&
687 "Can't map to two src physical registers!");
688 VirtRegPairs.push_back(NewReg);
692 if (!VirtRegPairs.empty()) {
693 unsigned ToReg = VirtRegPairs.back();
694 VirtRegPairs.pop_back();
695 while (!VirtRegPairs.empty()) {
696 unsigned FromReg = VirtRegPairs.back();
697 VirtRegPairs.pop_back();
698 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
700 assert(DstRegMap[FromReg] == ToReg &&
701 "Can't map to two dst physical registers!");
707 Processed.insert(MI);
710 /// isSafeToDelete - If the specified instruction does not produce any side
711 /// effects and all of its defs are dead, then it's safe to delete.
712 static bool isSafeToDelete(MachineInstr *MI, unsigned Reg,
713 const TargetInstrInfo *TII,
714 SmallVector<unsigned, 4> &Kills) {
715 const TargetInstrDesc &TID = MI->getDesc();
716 if (TID.mayStore() || TID.isCall())
718 if (TID.isTerminator() || TID.hasUnmodeledSideEffects())
721 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
722 MachineOperand &MO = MI->getOperand(i);
725 if (MO.isDef() && !MO.isDead())
727 if (MO.isUse() && MO.getReg() != Reg && MO.isKill())
728 Kills.push_back(MO.getReg());
734 /// runOnMachineFunction - Reduce two-address instructions to two operands.
736 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
737 DOUT << "Machine Function\n";
738 const TargetMachine &TM = MF.getTarget();
739 MRI = &MF.getRegInfo();
740 TII = TM.getInstrInfo();
741 TRI = TM.getRegisterInfo();
742 LV = getAnalysisIfAvailable<LiveVariables>();
744 bool MadeChange = false;
746 DOUT << "********** REWRITING TWO-ADDR INSTRS **********\n";
747 DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
749 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
751 ReMatRegs.resize(MRI->getLastVirtReg()+1);
753 SmallPtrSet<MachineInstr*, 8> Processed;
754 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
755 mbbi != mbbe; ++mbbi) {
761 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
763 MachineBasicBlock::iterator nmi = next(mi);
764 const TargetInstrDesc &TID = mi->getDesc();
765 bool FirstTied = true;
767 DistanceMap.insert(std::make_pair(mi, ++Dist));
769 ProcessCopy(&*mi, &*mbbi, Processed);
771 unsigned NumOps = (mi->getOpcode() == TargetInstrInfo::INLINEASM)
772 ? mi->getNumOperands() : TID.getNumOperands();
773 for (unsigned si = 0; si < NumOps; ++si) {
775 if (!mi->isRegTiedToDefOperand(si, &ti))
779 ++NumTwoAddressInstrs;
780 DOUT << '\t'; DEBUG(mi->print(*cerr.stream(), &TM));
785 assert(mi->getOperand(si).isReg() && mi->getOperand(si).getReg() &&
786 mi->getOperand(si).isUse() && "two address instruction invalid");
788 // If the two operands are the same we just remove the use
789 // and mark the def as def&use, otherwise we have to insert a copy.
790 if (mi->getOperand(ti).getReg() != mi->getOperand(si).getReg()) {
796 unsigned regA = mi->getOperand(ti).getReg();
797 unsigned regB = mi->getOperand(si).getReg();
799 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
800 "cannot update physical register live information");
803 // First, verify that we don't have a use of a in the instruction (a =
804 // b + a for example) because our transformation will not work. This
805 // should never occur because we are in SSA form.
806 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
808 !mi->getOperand(i).isReg() ||
809 mi->getOperand(i).getReg() != regA);
812 // If this instruction is not the killing user of B, see if we can
813 // rearrange the code to make it so. Making it the killing user will
814 // allow us to coalesce A and B together, eliminating the copy we are
816 if (!isKilled(*mi, regB, MRI, TII)) {
817 // If regA is dead and the instruction can be deleted, just delete
818 // it so it doesn't clobber regB.
819 SmallVector<unsigned, 4> Kills;
820 if (mi->getOperand(ti).isDead() &&
821 isSafeToDelete(mi, regB, TII, Kills)) {
822 SmallVector<std::pair<std::pair<unsigned, bool>
823 ,MachineInstr*>, 4> NewKills;
824 bool ReallySafe = true;
825 // If this instruction kills some virtual registers, we need
826 // update the kill information. If it's not possible to do so,
828 while (!Kills.empty()) {
829 unsigned Kill = Kills.back();
831 if (TargetRegisterInfo::isPhysicalRegister(Kill)) {
835 MachineInstr *LastKill = FindLastUseInMBB(Kill, &*mbbi, Dist);
837 bool isModRef = LastKill->modifiesRegister(Kill);
838 NewKills.push_back(std::make_pair(std::make_pair(Kill,isModRef),
848 while (!NewKills.empty()) {
849 MachineInstr *NewKill = NewKills.back().second;
850 unsigned Kill = NewKills.back().first.first;
851 bool isDead = NewKills.back().first.second;
853 if (LV->removeVirtualRegisterKilled(Kill, mi)) {
855 LV->addVirtualRegisterDead(Kill, NewKill);
857 LV->addVirtualRegisterKilled(Kill, NewKill);
862 // We're really going to nuke the old inst. If regB was marked
863 // as a kill we need to update its Kills list.
864 if (mi->getOperand(si).isKill())
865 LV->removeVirtualRegisterKilled(regB, mi);
867 mbbi->erase(mi); // Nuke the old inst.
870 break; // Done with this instruction.
874 // If this instruction is commutative, check to see if C dies. If
875 // so, swap the B and C operands. This makes the live ranges of A
877 // FIXME: This code also works for A := B op C instructions.
878 if (TID.isCommutable() && mi->getNumOperands() >= 3) {
879 assert(mi->getOperand(3-si).isReg() &&
880 "Not a proper commutative instruction!");
881 unsigned regC = mi->getOperand(3-si).getReg();
882 if (isKilled(*mi, regC, MRI, TII)) {
883 if (CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
886 goto InstructionRearranged;
891 // If this instruction is potentially convertible to a true
892 // three-address instruction,
893 if (TID.isConvertibleTo3Addr()) {
894 // FIXME: This assumes there are no more operands which are tied
895 // to another register.
897 for (unsigned i = si + 1, e = TID.getNumOperands(); i < e; ++i)
898 assert(TID.getOperandConstraint(i, TOI::TIED_TO) == -1);
901 if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) {
902 ++NumConvertedTo3Addr;
903 break; // Done with this instruction.
908 // If it's profitable to commute the instruction, do so.
909 if (TID.isCommutable() && mi->getNumOperands() >= 3) {
910 unsigned regC = mi->getOperand(3-si).getReg();
911 if (isProfitableToCommute(regB, regC, mi, mbbi, Dist))
912 if (CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
916 goto InstructionRearranged;
920 // If it's profitable to convert the 2-address instruction to a
921 // 3-address one, do so.
922 if (TID.isConvertibleTo3Addr() && isProfitableToConv3Addr(regA)) {
923 if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) {
924 ++NumConvertedTo3Addr;
925 break; // Done with this instruction.
929 InstructionRearranged:
930 const TargetRegisterClass* rc = MRI->getRegClass(regB);
931 MachineInstr *DefMI = MRI->getVRegDef(regB);
932 // If it's safe and profitable, remat the definition instead of
935 DefMI->getDesc().isAsCheapAsAMove() &&
936 DefMI->isSafeToReMat(TII, regB) &&
937 isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){
938 DEBUG(cerr << "2addr: REMATTING : " << *DefMI << "\n");
939 TII->reMaterialize(*mbbi, mi, regA, DefMI);
943 bool Emitted = TII->copyRegToReg(*mbbi, mi, regA, regB, rc, rc);
945 assert(Emitted && "Unable to issue a copy instruction!\n");
948 MachineBasicBlock::iterator prevMI = prior(mi);
949 // Update DistanceMap.
950 DistanceMap.insert(std::make_pair(prevMI, Dist));
951 DistanceMap[mi] = ++Dist;
953 // Update live variables for regB.
955 LiveVariables::VarInfo& varInfoB = LV->getVarInfo(regB);
957 // regB is used in this BB.
958 varInfoB.UsedBlocks[mbbi->getNumber()] = true;
960 if (LV->removeVirtualRegisterKilled(regB, mi))
961 LV->addVirtualRegisterKilled(regB, prevMI);
963 if (LV->removeVirtualRegisterDead(regB, mi))
964 LV->addVirtualRegisterDead(regB, prevMI);
967 DOUT << "\t\tprepend:\t"; DEBUG(prevMI->print(*cerr.stream(), &TM));
969 // Replace all occurences of regB with regA.
970 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
971 if (mi->getOperand(i).isReg() &&
972 mi->getOperand(i).getReg() == regB)
973 mi->getOperand(i).setReg(regA);
977 assert(mi->getOperand(ti).isDef() && mi->getOperand(si).isUse());
978 mi->getOperand(ti).setReg(mi->getOperand(si).getReg());
981 DOUT << "\t\trewrite to:\t"; DEBUG(mi->print(*cerr.stream(), &TM));
988 // Some remat'ed instructions are dead.
989 int VReg = ReMatRegs.find_first();
991 if (MRI->use_empty(VReg)) {
992 MachineInstr *DefMI = MRI->getVRegDef(VReg);
993 DefMI->eraseFromParent();
995 VReg = ReMatRegs.find_next(VReg);