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 typedef std::pair
<std::pair
<unsigned, bool>, MachineInstr
*> NewKill
;
110 bool canUpdateDeletedKills(SmallVector
<unsigned, 4> &Kills
,
111 SmallVector
<NewKill
, 4> &NewKills
,
112 MachineBasicBlock
*MBB
, unsigned Dist
);
113 bool DeleteUnusedInstr(MachineBasicBlock::iterator
&mi
,
114 MachineBasicBlock::iterator
&nmi
,
115 MachineFunction::iterator
&mbbi
,
116 unsigned regB
, unsigned regBIdx
, unsigned Dist
);
118 bool TryInstructionTransform(MachineBasicBlock::iterator
&mi
,
119 MachineBasicBlock::iterator
&nmi
,
120 MachineFunction::iterator
&mbbi
,
121 unsigned SrcIdx
, unsigned DstIdx
,
124 void ProcessCopy(MachineInstr
*MI
, MachineBasicBlock
*MBB
,
125 SmallPtrSet
<MachineInstr
*, 8> &Processed
);
128 static char ID
; // Pass identification, replacement for typeid
129 TwoAddressInstructionPass() : MachineFunctionPass(&ID
) {}
131 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
132 AU
.setPreservesCFG();
133 AU
.addPreserved
<LiveVariables
>();
134 AU
.addPreservedID(MachineLoopInfoID
);
135 AU
.addPreservedID(MachineDominatorsID
);
137 AU
.addPreservedID(StrongPHIEliminationID
);
139 AU
.addPreservedID(PHIEliminationID
);
140 MachineFunctionPass::getAnalysisUsage(AU
);
143 /// runOnMachineFunction - Pass entry point.
144 bool runOnMachineFunction(MachineFunction
&);
148 char TwoAddressInstructionPass::ID
= 0;
149 static RegisterPass
<TwoAddressInstructionPass
>
150 X("twoaddressinstruction", "Two-Address instruction pass");
152 const PassInfo
*const llvm::TwoAddressInstructionPassID
= &X
;
154 /// Sink3AddrInstruction - A two-address instruction has been converted to a
155 /// three-address instruction to avoid clobbering a register. Try to sink it
156 /// past the instruction that would kill the above mentioned register to reduce
157 /// register pressure.
158 bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock
*MBB
,
159 MachineInstr
*MI
, unsigned SavedReg
,
160 MachineBasicBlock::iterator OldPos
) {
161 // Check if it's safe to move this instruction.
162 bool SeenStore
= true; // Be conservative.
163 if (!MI
->isSafeToMove(TII
, SeenStore
))
167 SmallSet
<unsigned, 4> UseRegs
;
169 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
!= e
; ++i
) {
170 const MachineOperand
&MO
= MI
->getOperand(i
);
173 unsigned MOReg
= MO
.getReg();
176 if (MO
.isUse() && MOReg
!= SavedReg
)
177 UseRegs
.insert(MO
.getReg());
181 // Don't try to move it if it implicitly defines a register.
184 // For now, don't move any instructions that define multiple registers.
186 DefReg
= MO
.getReg();
189 // Find the instruction that kills SavedReg.
190 MachineInstr
*KillMI
= NULL
;
191 for (MachineRegisterInfo::use_iterator UI
= MRI
->use_begin(SavedReg
),
192 UE
= MRI
->use_end(); UI
!= UE
; ++UI
) {
193 MachineOperand
&UseMO
= UI
.getOperand();
196 KillMI
= UseMO
.getParent();
200 if (!KillMI
|| KillMI
->getParent() != MBB
|| KillMI
== MI
)
203 // If any of the definitions are used by another instruction between the
204 // position and the kill use, then it's not safe to sink it.
206 // FIXME: This can be sped up if there is an easy way to query whether an
207 // instruction is before or after another instruction. Then we can use
208 // MachineRegisterInfo def / use instead.
209 MachineOperand
*KillMO
= NULL
;
210 MachineBasicBlock::iterator KillPos
= KillMI
;
213 unsigned NumVisited
= 0;
214 for (MachineBasicBlock::iterator I
= next(OldPos
); I
!= KillPos
; ++I
) {
215 MachineInstr
*OtherMI
= I
;
216 if (NumVisited
> 30) // FIXME: Arbitrary limit to reduce compile time cost.
219 for (unsigned i
= 0, e
= OtherMI
->getNumOperands(); i
!= e
; ++i
) {
220 MachineOperand
&MO
= OtherMI
->getOperand(i
);
223 unsigned MOReg
= MO
.getReg();
230 if (OtherMI
== KillMI
&& MOReg
== SavedReg
)
231 // Save the operand that kills the register. We want to unset the kill
232 // marker if we can sink MI past it.
234 else if (UseRegs
.count(MOReg
))
235 // One of the uses is killed before the destination.
241 // Update kill and LV information.
242 KillMO
->setIsKill(false);
243 KillMO
= MI
->findRegisterUseOperand(SavedReg
, false, TRI
);
244 KillMO
->setIsKill(true);
247 LV
->replaceKillInstruction(SavedReg
, KillMI
, MI
);
249 // Move instruction to its destination.
251 MBB
->insert(KillPos
, MI
);
257 /// isTwoAddrUse - Return true if the specified MI is using the specified
258 /// register as a two-address operand.
259 static bool isTwoAddrUse(MachineInstr
*UseMI
, unsigned Reg
) {
260 const TargetInstrDesc
&TID
= UseMI
->getDesc();
261 for (unsigned i
= 0, e
= TID
.getNumOperands(); i
!= e
; ++i
) {
262 MachineOperand
&MO
= UseMI
->getOperand(i
);
263 if (MO
.isReg() && MO
.getReg() == Reg
&&
264 (MO
.isDef() || UseMI
->isRegTiedToDefOperand(i
)))
265 // Earlier use is a two-address one.
271 /// isProfitableToReMat - Return true if the heuristics determines it is likely
272 /// to be profitable to re-materialize the definition of Reg rather than copy
275 TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg
,
276 const TargetRegisterClass
*RC
,
277 MachineInstr
*MI
, MachineInstr
*DefMI
,
278 MachineBasicBlock
*MBB
, unsigned Loc
) {
279 bool OtherUse
= false;
280 for (MachineRegisterInfo::use_iterator UI
= MRI
->use_begin(Reg
),
281 UE
= MRI
->use_end(); UI
!= UE
; ++UI
) {
282 MachineOperand
&UseMO
= UI
.getOperand();
283 MachineInstr
*UseMI
= UseMO
.getParent();
284 MachineBasicBlock
*UseMBB
= UseMI
->getParent();
286 DenseMap
<MachineInstr
*, unsigned>::iterator DI
= DistanceMap
.find(UseMI
);
287 if (DI
!= DistanceMap
.end() && DI
->second
== Loc
)
288 continue; // Current use.
290 // There is at least one other use in the MBB that will clobber the
292 if (isTwoAddrUse(UseMI
, Reg
))
297 // If other uses in MBB are not two-address uses, then don't remat.
301 // No other uses in the same block, remat if it's defined in the same
302 // block so it does not unnecessarily extend the live range.
303 return MBB
== DefMI
->getParent();
306 /// NoUseAfterLastDef - Return true if there are no intervening uses between the
307 /// last instruction in the MBB that defines the specified register and the
308 /// two-address instruction which is being processed. It also returns the last
309 /// def location by reference
310 bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg
,
311 MachineBasicBlock
*MBB
, unsigned Dist
,
314 unsigned LastUse
= Dist
;
315 for (MachineRegisterInfo::reg_iterator I
= MRI
->reg_begin(Reg
),
316 E
= MRI
->reg_end(); I
!= E
; ++I
) {
317 MachineOperand
&MO
= I
.getOperand();
318 MachineInstr
*MI
= MO
.getParent();
319 if (MI
->getParent() != MBB
)
321 DenseMap
<MachineInstr
*, unsigned>::iterator DI
= DistanceMap
.find(MI
);
322 if (DI
== DistanceMap
.end())
324 if (MO
.isUse() && DI
->second
< LastUse
)
325 LastUse
= DI
->second
;
326 if (MO
.isDef() && DI
->second
> LastDef
)
327 LastDef
= DI
->second
;
330 return !(LastUse
> LastDef
&& LastUse
< Dist
);
333 MachineInstr
*TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg
,
334 MachineBasicBlock
*MBB
,
336 unsigned LastUseDist
= 0;
337 MachineInstr
*LastUse
= 0;
338 for (MachineRegisterInfo::reg_iterator I
= MRI
->reg_begin(Reg
),
339 E
= MRI
->reg_end(); I
!= E
; ++I
) {
340 MachineOperand
&MO
= I
.getOperand();
341 MachineInstr
*MI
= MO
.getParent();
342 if (MI
->getParent() != MBB
)
344 DenseMap
<MachineInstr
*, unsigned>::iterator DI
= DistanceMap
.find(MI
);
345 if (DI
== DistanceMap
.end())
347 if (DI
->second
>= Dist
)
350 if (MO
.isUse() && DI
->second
> LastUseDist
) {
352 LastUseDist
= DI
->second
;
358 /// isCopyToReg - Return true if the specified MI is a copy instruction or
359 /// a extract_subreg instruction. It also returns the source and destination
360 /// registers and whether they are physical registers by reference.
361 static bool isCopyToReg(MachineInstr
&MI
, const TargetInstrInfo
*TII
,
362 unsigned &SrcReg
, unsigned &DstReg
,
363 bool &IsSrcPhys
, bool &IsDstPhys
) {
366 unsigned SrcSubIdx
, DstSubIdx
;
367 if (!TII
->isMoveInstr(MI
, SrcReg
, DstReg
, SrcSubIdx
, DstSubIdx
)) {
368 if (MI
.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG
) {
369 DstReg
= MI
.getOperand(0).getReg();
370 SrcReg
= MI
.getOperand(1).getReg();
371 } else if (MI
.getOpcode() == TargetInstrInfo::INSERT_SUBREG
) {
372 DstReg
= MI
.getOperand(0).getReg();
373 SrcReg
= MI
.getOperand(2).getReg();
374 } else if (MI
.getOpcode() == TargetInstrInfo::SUBREG_TO_REG
) {
375 DstReg
= MI
.getOperand(0).getReg();
376 SrcReg
= MI
.getOperand(2).getReg();
381 IsSrcPhys
= TargetRegisterInfo::isPhysicalRegister(SrcReg
);
382 IsDstPhys
= TargetRegisterInfo::isPhysicalRegister(DstReg
);
388 /// isKilled - Test if the given register value, which is used by the given
389 /// instruction, is killed by the given instruction. This looks through
390 /// coalescable copies to see if the original value is potentially not killed.
392 /// For example, in this code:
394 /// %reg1034 = copy %reg1024
395 /// %reg1035 = copy %reg1025<kill>
396 /// %reg1036 = add %reg1034<kill>, %reg1035<kill>
398 /// %reg1034 is not considered to be killed, since it is copied from a
399 /// register which is not killed. Treating it as not killed lets the
400 /// normal heuristics commute the (two-address) add, which lets
401 /// coalescing eliminate the extra copy.
403 static bool isKilled(MachineInstr
&MI
, unsigned Reg
,
404 const MachineRegisterInfo
*MRI
,
405 const TargetInstrInfo
*TII
) {
406 MachineInstr
*DefMI
= &MI
;
408 if (!DefMI
->killsRegister(Reg
))
410 if (TargetRegisterInfo::isPhysicalRegister(Reg
))
412 MachineRegisterInfo::def_iterator Begin
= MRI
->def_begin(Reg
);
413 // If there are multiple defs, we can't do a simple analysis, so just
414 // go with what the kill flag says.
415 if (next(Begin
) != MRI
->def_end())
418 bool IsSrcPhys
, IsDstPhys
;
419 unsigned SrcReg
, DstReg
;
420 // If the def is something other than a copy, then it isn't going to
421 // be coalesced, so follow the kill flag.
422 if (!isCopyToReg(*DefMI
, TII
, SrcReg
, DstReg
, IsSrcPhys
, IsDstPhys
))
428 /// isTwoAddrUse - Return true if the specified MI uses the specified register
429 /// as a two-address use. If so, return the destination register by reference.
430 static bool isTwoAddrUse(MachineInstr
&MI
, unsigned Reg
, unsigned &DstReg
) {
431 const TargetInstrDesc
&TID
= MI
.getDesc();
432 unsigned NumOps
= (MI
.getOpcode() == TargetInstrInfo::INLINEASM
)
433 ? MI
.getNumOperands() : TID
.getNumOperands();
434 for (unsigned i
= 0; i
!= NumOps
; ++i
) {
435 const MachineOperand
&MO
= MI
.getOperand(i
);
436 if (!MO
.isReg() || !MO
.isUse() || MO
.getReg() != Reg
)
439 if (MI
.isRegTiedToDefOperand(i
, &ti
)) {
440 DstReg
= MI
.getOperand(ti
).getReg();
447 /// findOnlyInterestingUse - Given a register, if has a single in-basic block
448 /// use, return the use instruction if it's a copy or a two-address use.
450 MachineInstr
*findOnlyInterestingUse(unsigned Reg
, MachineBasicBlock
*MBB
,
451 MachineRegisterInfo
*MRI
,
452 const TargetInstrInfo
*TII
,
454 unsigned &DstReg
, bool &IsDstPhys
) {
455 MachineRegisterInfo::use_iterator UI
= MRI
->use_begin(Reg
);
456 if (UI
== MRI
->use_end())
458 MachineInstr
&UseMI
= *UI
;
459 if (++UI
!= MRI
->use_end())
460 // More than one use.
462 if (UseMI
.getParent() != MBB
)
466 if (isCopyToReg(UseMI
, TII
, SrcReg
, DstReg
, IsSrcPhys
, IsDstPhys
)) {
471 if (isTwoAddrUse(UseMI
, Reg
, DstReg
)) {
472 IsDstPhys
= TargetRegisterInfo::isPhysicalRegister(DstReg
);
478 /// getMappedReg - Return the physical register the specified virtual register
479 /// might be mapped to.
481 getMappedReg(unsigned Reg
, DenseMap
<unsigned, unsigned> &RegMap
) {
482 while (TargetRegisterInfo::isVirtualRegister(Reg
)) {
483 DenseMap
<unsigned, unsigned>::iterator SI
= RegMap
.find(Reg
);
484 if (SI
== RegMap
.end())
488 if (TargetRegisterInfo::isPhysicalRegister(Reg
))
493 /// regsAreCompatible - Return true if the two registers are equal or aliased.
496 regsAreCompatible(unsigned RegA
, unsigned RegB
, const TargetRegisterInfo
*TRI
) {
501 return TRI
->regsOverlap(RegA
, RegB
);
505 /// isProfitableToReMat - Return true if it's potentially profitable to commute
506 /// the two-address instruction that's being processed.
508 TwoAddressInstructionPass::isProfitableToCommute(unsigned regB
, unsigned regC
,
509 MachineInstr
*MI
, MachineBasicBlock
*MBB
,
511 // Determine if it's profitable to commute this two address instruction. In
512 // general, we want no uses between this instruction and the definition of
513 // the two-address register.
515 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
516 // %reg1029<def> = MOV8rr %reg1028
517 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
518 // insert => %reg1030<def> = MOV8rr %reg1028
519 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
520 // In this case, it might not be possible to coalesce the second MOV8rr
521 // instruction if the first one is coalesced. So it would be profitable to
523 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
524 // %reg1029<def> = MOV8rr %reg1028
525 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
526 // insert => %reg1030<def> = MOV8rr %reg1029
527 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
529 if (!MI
->killsRegister(regC
))
532 // Ok, we have something like:
533 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
534 // let's see if it's worth commuting it.
536 // Look for situations like this:
537 // %reg1024<def> = MOV r1
538 // %reg1025<def> = MOV r0
539 // %reg1026<def> = ADD %reg1024, %reg1025
541 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
542 unsigned FromRegB
= getMappedReg(regB
, SrcRegMap
);
543 unsigned FromRegC
= getMappedReg(regC
, SrcRegMap
);
544 unsigned ToRegB
= getMappedReg(regB
, DstRegMap
);
545 unsigned ToRegC
= getMappedReg(regC
, DstRegMap
);
546 if (!regsAreCompatible(FromRegB
, ToRegB
, TRI
) &&
547 (regsAreCompatible(FromRegB
, ToRegC
, TRI
) ||
548 regsAreCompatible(FromRegC
, ToRegB
, TRI
)))
551 // If there is a use of regC between its last def (could be livein) and this
552 // instruction, then bail.
553 unsigned LastDefC
= 0;
554 if (!NoUseAfterLastDef(regC
, MBB
, Dist
, LastDefC
))
557 // If there is a use of regB between its last def (could be livein) and this
558 // instruction, then go ahead and make this transformation.
559 unsigned LastDefB
= 0;
560 if (!NoUseAfterLastDef(regB
, MBB
, Dist
, LastDefB
))
563 // Since there are no intervening uses for both registers, then commute
564 // if the def of regC is closer. Its live interval is shorter.
565 return LastDefB
&& LastDefC
&& LastDefC
> LastDefB
;
568 /// CommuteInstruction - Commute a two-address instruction and update the basic
569 /// block, distance map, and live variables if needed. Return true if it is
572 TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator
&mi
,
573 MachineFunction::iterator
&mbbi
,
574 unsigned RegB
, unsigned RegC
, unsigned Dist
) {
575 MachineInstr
*MI
= mi
;
576 DEBUG(errs() << "2addr: COMMUTING : " << *MI
);
577 MachineInstr
*NewMI
= TII
->commuteInstruction(MI
);
580 DEBUG(errs() << "2addr: COMMUTING FAILED!\n");
584 DEBUG(errs() << "2addr: COMMUTED TO: " << *NewMI
);
585 // If the instruction changed to commute it, update livevar.
588 // Update live variables
589 LV
->replaceKillInstruction(RegC
, MI
, NewMI
);
591 mbbi
->insert(mi
, NewMI
); // Insert the new inst
592 mbbi
->erase(mi
); // Nuke the old inst.
594 DistanceMap
.insert(std::make_pair(NewMI
, Dist
));
597 // Update source register map.
598 unsigned FromRegC
= getMappedReg(RegC
, SrcRegMap
);
600 unsigned RegA
= MI
->getOperand(0).getReg();
601 SrcRegMap
[RegA
] = FromRegC
;
607 /// isProfitableToConv3Addr - Return true if it is profitable to convert the
608 /// given 2-address instruction to a 3-address one.
610 TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA
) {
611 // Look for situations like this:
612 // %reg1024<def> = MOV r1
613 // %reg1025<def> = MOV r0
614 // %reg1026<def> = ADD %reg1024, %reg1025
616 // Turn ADD into a 3-address instruction to avoid a copy.
617 unsigned FromRegA
= getMappedReg(RegA
, SrcRegMap
);
618 unsigned ToRegA
= getMappedReg(RegA
, DstRegMap
);
619 return (FromRegA
&& ToRegA
&& !regsAreCompatible(FromRegA
, ToRegA
, TRI
));
622 /// ConvertInstTo3Addr - Convert the specified two-address instruction into a
623 /// three address one. Return true if this transformation was successful.
625 TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator
&mi
,
626 MachineBasicBlock::iterator
&nmi
,
627 MachineFunction::iterator
&mbbi
,
628 unsigned RegB
, unsigned Dist
) {
629 MachineInstr
*NewMI
= TII
->convertToThreeAddress(mbbi
, mi
, LV
);
631 DEBUG(errs() << "2addr: CONVERTING 2-ADDR: " << *mi
);
632 DEBUG(errs() << "2addr: TO 3-ADDR: " << *NewMI
);
635 if (NewMI
->findRegisterUseOperand(RegB
, false, TRI
))
636 // FIXME: Temporary workaround. If the new instruction doesn't
637 // uses RegB, convertToThreeAddress must have created more
638 // then one instruction.
639 Sunk
= Sink3AddrInstruction(mbbi
, NewMI
, RegB
, mi
);
641 mbbi
->erase(mi
); // Nuke the old inst.
644 DistanceMap
.insert(std::make_pair(NewMI
, Dist
));
654 /// ProcessCopy - If the specified instruction is not yet processed, process it
655 /// if it's a copy. For a copy instruction, we find the physical registers the
656 /// source and destination registers might be mapped to. These are kept in
657 /// point-to maps used to determine future optimizations. e.g.
660 /// v1026 = add v1024, v1025
662 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
663 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
664 /// potentially joined with r1 on the output side. It's worthwhile to commute
665 /// 'add' to eliminate a copy.
666 void TwoAddressInstructionPass::ProcessCopy(MachineInstr
*MI
,
667 MachineBasicBlock
*MBB
,
668 SmallPtrSet
<MachineInstr
*, 8> &Processed
) {
669 if (Processed
.count(MI
))
672 bool IsSrcPhys
, IsDstPhys
;
673 unsigned SrcReg
, DstReg
;
674 if (!isCopyToReg(*MI
, TII
, SrcReg
, DstReg
, IsSrcPhys
, IsDstPhys
))
677 if (IsDstPhys
&& !IsSrcPhys
)
678 DstRegMap
.insert(std::make_pair(SrcReg
, DstReg
));
679 else if (!IsDstPhys
&& IsSrcPhys
) {
680 bool isNew
= SrcRegMap
.insert(std::make_pair(DstReg
, SrcReg
)).second
;
682 assert(SrcRegMap
[DstReg
] == SrcReg
&&
683 "Can't map to two src physical registers!");
685 SmallVector
<unsigned, 4> VirtRegPairs
;
688 while (MachineInstr
*UseMI
= findOnlyInterestingUse(DstReg
, MBB
, MRI
,TII
,
689 IsCopy
, NewReg
, IsDstPhys
)) {
691 if (!Processed
.insert(UseMI
))
695 DenseMap
<MachineInstr
*, unsigned>::iterator DI
= DistanceMap
.find(UseMI
);
696 if (DI
!= DistanceMap
.end())
697 // Earlier in the same MBB.Reached via a back edge.
701 VirtRegPairs
.push_back(NewReg
);
704 bool isNew
= SrcRegMap
.insert(std::make_pair(NewReg
, DstReg
)).second
;
706 assert(SrcRegMap
[NewReg
] == DstReg
&&
707 "Can't map to two src physical registers!");
708 VirtRegPairs
.push_back(NewReg
);
712 if (!VirtRegPairs
.empty()) {
713 unsigned ToReg
= VirtRegPairs
.back();
714 VirtRegPairs
.pop_back();
715 while (!VirtRegPairs
.empty()) {
716 unsigned FromReg
= VirtRegPairs
.back();
717 VirtRegPairs
.pop_back();
718 bool isNew
= DstRegMap
.insert(std::make_pair(FromReg
, ToReg
)).second
;
720 assert(DstRegMap
[FromReg
] == ToReg
&&
721 "Can't map to two dst physical registers!");
727 Processed
.insert(MI
);
730 /// isSafeToDelete - If the specified instruction does not produce any side
731 /// effects and all of its defs are dead, then it's safe to delete.
732 static bool isSafeToDelete(MachineInstr
*MI
, unsigned Reg
,
733 const TargetInstrInfo
*TII
,
734 SmallVector
<unsigned, 4> &Kills
) {
735 const TargetInstrDesc
&TID
= MI
->getDesc();
736 if (TID
.mayStore() || TID
.isCall())
738 if (TID
.isTerminator() || TID
.hasUnmodeledSideEffects())
741 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
!= e
; ++i
) {
742 MachineOperand
&MO
= MI
->getOperand(i
);
745 if (MO
.isDef() && !MO
.isDead())
747 if (MO
.isUse() && MO
.getReg() != Reg
&& MO
.isKill())
748 Kills
.push_back(MO
.getReg());
754 /// canUpdateDeletedKills - Check if all the registers listed in Kills are
755 /// killed by instructions in MBB preceding the current instruction at
756 /// position Dist. If so, return true and record information about the
757 /// preceding kills in NewKills.
758 bool TwoAddressInstructionPass::
759 canUpdateDeletedKills(SmallVector
<unsigned, 4> &Kills
,
760 SmallVector
<NewKill
, 4> &NewKills
,
761 MachineBasicBlock
*MBB
, unsigned Dist
) {
762 while (!Kills
.empty()) {
763 unsigned Kill
= Kills
.back();
765 if (TargetRegisterInfo::isPhysicalRegister(Kill
))
768 MachineInstr
*LastKill
= FindLastUseInMBB(Kill
, MBB
, Dist
);
772 bool isModRef
= LastKill
->modifiesRegister(Kill
);
773 NewKills
.push_back(std::make_pair(std::make_pair(Kill
, isModRef
),
779 /// DeleteUnusedInstr - If an instruction with a tied register operand can
780 /// be safely deleted, just delete it.
782 TwoAddressInstructionPass::DeleteUnusedInstr(MachineBasicBlock::iterator
&mi
,
783 MachineBasicBlock::iterator
&nmi
,
784 MachineFunction::iterator
&mbbi
,
785 unsigned regB
, unsigned regBIdx
,
787 // Check if the instruction has no side effects and if all its defs are dead.
788 SmallVector
<unsigned, 4> Kills
;
789 if (!isSafeToDelete(mi
, regB
, TII
, Kills
))
792 // If this instruction kills some virtual registers, we need to
793 // update the kill information. If it's not possible to do so,
795 SmallVector
<NewKill
, 4> NewKills
;
796 if (!canUpdateDeletedKills(Kills
, NewKills
, &*mbbi
, Dist
))
800 while (!NewKills
.empty()) {
801 MachineInstr
*NewKill
= NewKills
.back().second
;
802 unsigned Kill
= NewKills
.back().first
.first
;
803 bool isDead
= NewKills
.back().first
.second
;
805 if (LV
->removeVirtualRegisterKilled(Kill
, mi
)) {
807 LV
->addVirtualRegisterDead(Kill
, NewKill
);
809 LV
->addVirtualRegisterKilled(Kill
, NewKill
);
813 // If regB was marked as a kill, update its Kills list.
814 if (mi
->getOperand(regBIdx
).isKill())
815 LV
->removeVirtualRegisterKilled(regB
, mi
);
818 mbbi
->erase(mi
); // Nuke the old inst.
823 /// TryInstructionTransform - For the case where an instruction has a single
824 /// pair of tied register operands, attempt some transformations that may
825 /// either eliminate the tied operands or improve the opportunities for
826 /// coalescing away the register copy. Returns true if the tied operands
827 /// are eliminated altogether.
828 bool TwoAddressInstructionPass::
829 TryInstructionTransform(MachineBasicBlock::iterator
&mi
,
830 MachineBasicBlock::iterator
&nmi
,
831 MachineFunction::iterator
&mbbi
,
832 unsigned SrcIdx
, unsigned DstIdx
, unsigned Dist
) {
833 const TargetInstrDesc
&TID
= mi
->getDesc();
834 unsigned regA
= mi
->getOperand(DstIdx
).getReg();
835 unsigned regB
= mi
->getOperand(SrcIdx
).getReg();
837 assert(TargetRegisterInfo::isVirtualRegister(regB
) &&
838 "cannot make instruction into two-address form");
840 // If regA is dead and the instruction can be deleted, just delete
841 // it so it doesn't clobber regB.
842 bool regBKilled
= isKilled(*mi
, regB
, MRI
, TII
);
843 if (!regBKilled
&& mi
->getOperand(DstIdx
).isDead() &&
844 DeleteUnusedInstr(mi
, nmi
, mbbi
, regB
, SrcIdx
, Dist
)) {
846 return true; // Done with this instruction.
849 // Check if it is profitable to commute the operands.
850 unsigned SrcOp1
, SrcOp2
;
852 unsigned regCIdx
= ~0U;
853 bool TryCommute
= false;
854 bool AggressiveCommute
= false;
855 if (TID
.isCommutable() && mi
->getNumOperands() >= 3 &&
856 TII
->findCommutedOpIndices(mi
, SrcOp1
, SrcOp2
)) {
857 if (SrcIdx
== SrcOp1
)
859 else if (SrcIdx
== SrcOp2
)
862 if (regCIdx
!= ~0U) {
863 regC
= mi
->getOperand(regCIdx
).getReg();
864 if (!regBKilled
&& isKilled(*mi
, regC
, MRI
, TII
))
865 // If C dies but B does not, swap the B and C operands.
866 // This makes the live ranges of A and C joinable.
868 else if (isProfitableToCommute(regB
, regC
, mi
, mbbi
, Dist
)) {
870 AggressiveCommute
= true;
875 // If it's profitable to commute, try to do so.
876 if (TryCommute
&& CommuteInstruction(mi
, mbbi
, regB
, regC
, Dist
)) {
878 if (AggressiveCommute
)
883 if (TID
.isConvertibleTo3Addr()) {
884 // This instruction is potentially convertible to a true
885 // three-address instruction. Check if it is profitable.
886 if (!regBKilled
|| isProfitableToConv3Addr(regA
)) {
887 // Try to convert it.
888 if (ConvertInstTo3Addr(mi
, nmi
, mbbi
, regB
, Dist
)) {
889 ++NumConvertedTo3Addr
;
890 return true; // Done with this instruction.
897 /// runOnMachineFunction - Reduce two-address instructions to two operands.
899 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction
&MF
) {
900 DEBUG(errs() << "Machine Function\n");
901 const TargetMachine
&TM
= MF
.getTarget();
902 MRI
= &MF
.getRegInfo();
903 TII
= TM
.getInstrInfo();
904 TRI
= TM
.getRegisterInfo();
905 LV
= getAnalysisIfAvailable
<LiveVariables
>();
907 bool MadeChange
= false;
909 DEBUG(errs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
910 DEBUG(errs() << "********** Function: "
911 << MF
.getFunction()->getName() << '\n');
913 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
915 ReMatRegs
.resize(MRI
->getLastVirtReg()+1);
917 typedef DenseMap
<unsigned, SmallVector
<std::pair
<unsigned, unsigned>, 4> >
919 TiedOperandMap
TiedOperands(4);
921 SmallPtrSet
<MachineInstr
*, 8> Processed
;
922 for (MachineFunction::iterator mbbi
= MF
.begin(), mbbe
= MF
.end();
923 mbbi
!= mbbe
; ++mbbi
) {
929 for (MachineBasicBlock::iterator mi
= mbbi
->begin(), me
= mbbi
->end();
931 MachineBasicBlock::iterator nmi
= next(mi
);
932 const TargetInstrDesc
&TID
= mi
->getDesc();
933 bool FirstTied
= true;
935 DistanceMap
.insert(std::make_pair(mi
, ++Dist
));
937 ProcessCopy(&*mi
, &*mbbi
, Processed
);
939 // First scan through all the tied register uses in this instruction
940 // and record a list of pairs of tied operands for each register.
941 unsigned NumOps
= (mi
->getOpcode() == TargetInstrInfo::INLINEASM
)
942 ? mi
->getNumOperands() : TID
.getNumOperands();
943 for (unsigned SrcIdx
= 0; SrcIdx
< NumOps
; ++SrcIdx
) {
945 if (!mi
->isRegTiedToDefOperand(SrcIdx
, &DstIdx
))
950 ++NumTwoAddressInstrs
;
951 DEBUG(errs() << '\t' << *mi
);
954 assert(mi
->getOperand(SrcIdx
).isReg() &&
955 mi
->getOperand(SrcIdx
).getReg() &&
956 mi
->getOperand(SrcIdx
).isUse() &&
957 "two address instruction invalid");
959 unsigned regB
= mi
->getOperand(SrcIdx
).getReg();
960 TiedOperandMap::iterator OI
= TiedOperands
.find(regB
);
961 if (OI
== TiedOperands
.end()) {
962 SmallVector
<std::pair
<unsigned, unsigned>, 4> TiedPair
;
963 OI
= TiedOperands
.insert(std::make_pair(regB
, TiedPair
)).first
;
965 OI
->second
.push_back(std::make_pair(SrcIdx
, DstIdx
));
968 // Now iterate over the information collected above.
969 for (TiedOperandMap::iterator OI
= TiedOperands
.begin(),
970 OE
= TiedOperands
.end(); OI
!= OE
; ++OI
) {
971 SmallVector
<std::pair
<unsigned, unsigned>, 4> &TiedPairs
= OI
->second
;
973 // If the instruction has a single pair of tied operands, try some
974 // transformations that may either eliminate the tied operands or
975 // improve the opportunities for coalescing away the register copy.
976 if (TiedOperands
.size() == 1 && TiedPairs
.size() == 1) {
977 unsigned SrcIdx
= TiedPairs
[0].first
;
978 unsigned DstIdx
= TiedPairs
[0].second
;
980 // If the registers are already equal, nothing needs to be done.
981 if (mi
->getOperand(SrcIdx
).getReg() ==
982 mi
->getOperand(DstIdx
).getReg())
983 break; // Done with this instruction.
985 if (TryInstructionTransform(mi
, nmi
, mbbi
, SrcIdx
, DstIdx
, Dist
))
986 break; // The tied operands have been eliminated.
989 bool RemovedKillFlag
= false;
990 bool AllUsesCopied
= true;
991 unsigned LastCopiedReg
= 0;
992 unsigned regB
= OI
->first
;
993 for (unsigned tpi
= 0, tpe
= TiedPairs
.size(); tpi
!= tpe
; ++tpi
) {
994 unsigned SrcIdx
= TiedPairs
[tpi
].first
;
995 unsigned DstIdx
= TiedPairs
[tpi
].second
;
996 unsigned regA
= mi
->getOperand(DstIdx
).getReg();
997 // Grab regB from the instruction because it may have changed if the
998 // instruction was commuted.
999 regB
= mi
->getOperand(SrcIdx
).getReg();
1002 // The register is tied to multiple destinations (or else we would
1003 // not have continued this far), but this use of the register
1004 // already matches the tied destination. Leave it.
1005 AllUsesCopied
= false;
1008 LastCopiedReg
= regA
;
1010 assert(TargetRegisterInfo::isVirtualRegister(regB
) &&
1011 "cannot make instruction into two-address form");
1014 // First, verify that we don't have a use of "a" in the instruction
1015 // (a = b + a for example) because our transformation will not
1016 // work. This should never occur because we are in SSA form.
1017 for (unsigned i
= 0; i
!= mi
->getNumOperands(); ++i
)
1018 assert(i
== DstIdx
||
1019 !mi
->getOperand(i
).isReg() ||
1020 mi
->getOperand(i
).getReg() != regA
);
1023 // Emit a copy or rematerialize the definition.
1024 const TargetRegisterClass
*rc
= MRI
->getRegClass(regB
);
1025 MachineInstr
*DefMI
= MRI
->getVRegDef(regB
);
1026 // If it's safe and profitable, remat the definition instead of
1029 DefMI
->getDesc().isAsCheapAsAMove() &&
1030 DefMI
->isSafeToReMat(TII
, regB
) &&
1031 isProfitableToReMat(regB
, rc
, mi
, DefMI
, mbbi
, Dist
)){
1032 DEBUG(errs() << "2addr: REMATTING : " << *DefMI
<< "\n");
1033 unsigned regASubIdx
= mi
->getOperand(DstIdx
).getSubReg();
1034 TII
->reMaterialize(*mbbi
, mi
, regA
, regASubIdx
, DefMI
);
1035 ReMatRegs
.set(regB
);
1038 bool Emitted
= TII
->copyRegToReg(*mbbi
, mi
, regA
, regB
, rc
, rc
);
1040 assert(Emitted
&& "Unable to issue a copy instruction!\n");
1043 MachineBasicBlock::iterator prevMI
= prior(mi
);
1044 // Update DistanceMap.
1045 DistanceMap
.insert(std::make_pair(prevMI
, Dist
));
1046 DistanceMap
[mi
] = ++Dist
;
1048 DEBUG(errs() << "\t\tprepend:\t" << *prevMI
);
1050 MachineOperand
&MO
= mi
->getOperand(SrcIdx
);
1051 assert(MO
.isReg() && MO
.getReg() == regB
&& MO
.isUse() &&
1052 "inconsistent operand info for 2-reg pass");
1054 MO
.setIsKill(false);
1055 RemovedKillFlag
= true;
1060 if (AllUsesCopied
) {
1061 // Replace other (un-tied) uses of regB with LastCopiedReg.
1062 for (unsigned i
= 0, e
= mi
->getNumOperands(); i
!= e
; ++i
) {
1063 MachineOperand
&MO
= mi
->getOperand(i
);
1064 if (MO
.isReg() && MO
.getReg() == regB
&& MO
.isUse()) {
1066 MO
.setIsKill(false);
1067 RemovedKillFlag
= true;
1069 MO
.setReg(LastCopiedReg
);
1073 // Update live variables for regB.
1074 if (RemovedKillFlag
&& LV
&& LV
->getVarInfo(regB
).removeKill(mi
))
1075 LV
->addVirtualRegisterKilled(regB
, prior(mi
));
1077 } else if (RemovedKillFlag
) {
1078 // Some tied uses of regB matched their destination registers, so
1079 // regB is still used in this instruction, but a kill flag was
1080 // removed from a different tied use of regB, so now we need to add
1081 // a kill flag to one of the remaining uses of regB.
1082 for (unsigned i
= 0, e
= mi
->getNumOperands(); i
!= e
; ++i
) {
1083 MachineOperand
&MO
= mi
->getOperand(i
);
1084 if (MO
.isReg() && MO
.getReg() == regB
&& MO
.isUse()) {
1093 DEBUG(errs() << "\t\trewrite to:\t" << *mi
);
1096 // Clear TiedOperands here instead of at the top of the loop
1097 // since most instructions do not have tied operands.
1098 TiedOperands
.clear();
1103 // Some remat'ed instructions are dead.
1104 int VReg
= ReMatRegs
.find_first();
1105 while (VReg
!= -1) {
1106 if (MRI
->use_empty(VReg
)) {
1107 MachineInstr
*DefMI
= MRI
->getVRegDef(VReg
);
1108 DefMI
->eraseFromParent();
1110 VReg
= ReMatRegs
.find_next(VReg
);