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/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/Analysis/AliasAnalysis.h"
39 #include "llvm/MC/MCInstrItineraries.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/ADT/BitVector.h"
47 #include "llvm/ADT/DenseMap.h"
48 #include "llvm/ADT/SmallSet.h"
49 #include "llvm/ADT/Statistic.h"
50 #include "llvm/ADT/STLExtras.h"
53 STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
54 STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
55 STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
56 STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
57 STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
58 STATISTIC(NumReMats, "Number of instructions re-materialized");
59 STATISTIC(NumDeletes, "Number of dead instructions deleted");
60 STATISTIC(NumReSchedUps, "Number of instructions re-scheduled up");
61 STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down");
64 class TwoAddressInstructionPass : public MachineFunctionPass {
65 const TargetInstrInfo *TII;
66 const TargetRegisterInfo *TRI;
67 const InstrItineraryData *InstrItins;
68 MachineRegisterInfo *MRI;
72 // DistanceMap - Keep track the distance of a MI from the start of the
73 // current basic block.
74 DenseMap<MachineInstr*, unsigned> DistanceMap;
76 // SrcRegMap - A map from virtual registers to physical registers which
77 // are likely targets to be coalesced to due to copies from physical
78 // registers to virtual registers. e.g. v1024 = move r0.
79 DenseMap<unsigned, unsigned> SrcRegMap;
81 // DstRegMap - A map from virtual registers to physical registers which
82 // are likely targets to be coalesced to due to copies to physical
83 // registers from virtual registers. e.g. r1 = move v1024.
84 DenseMap<unsigned, unsigned> DstRegMap;
86 /// RegSequences - Keep track the list of REG_SEQUENCE instructions seen
87 /// during the initial walk of the machine function.
88 SmallVector<MachineInstr*, 16> RegSequences;
90 bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
92 MachineBasicBlock::iterator OldPos);
94 bool isProfitableToReMat(unsigned Reg, const TargetRegisterClass *RC,
95 MachineInstr *MI, MachineInstr *DefMI,
96 MachineBasicBlock *MBB, unsigned Loc);
98 bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
101 MachineInstr *FindLastUseInMBB(unsigned Reg, MachineBasicBlock *MBB,
104 bool isProfitableToCommute(unsigned regB, unsigned regC,
105 MachineInstr *MI, MachineBasicBlock *MBB,
108 bool CommuteInstruction(MachineBasicBlock::iterator &mi,
109 MachineFunction::iterator &mbbi,
110 unsigned RegB, unsigned RegC, unsigned Dist);
112 bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
114 bool ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
115 MachineBasicBlock::iterator &nmi,
116 MachineFunction::iterator &mbbi,
117 unsigned RegA, unsigned RegB, unsigned Dist);
119 typedef std::pair<std::pair<unsigned, bool>, MachineInstr*> NewKill;
120 bool canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
121 SmallVector<NewKill, 4> &NewKills,
122 MachineBasicBlock *MBB, unsigned Dist);
123 bool DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
124 MachineBasicBlock::iterator &nmi,
125 MachineFunction::iterator &mbbi, unsigned Dist);
127 bool isDefTooClose(unsigned Reg, unsigned Dist,
128 MachineInstr *MI, MachineBasicBlock *MBB);
130 bool RescheduleMIBelowKill(MachineBasicBlock *MBB,
131 MachineBasicBlock::iterator &mi,
132 MachineBasicBlock::iterator &nmi,
134 bool RescheduleKillAboveMI(MachineBasicBlock *MBB,
135 MachineBasicBlock::iterator &mi,
136 MachineBasicBlock::iterator &nmi,
139 bool TryInstructionTransform(MachineBasicBlock::iterator &mi,
140 MachineBasicBlock::iterator &nmi,
141 MachineFunction::iterator &mbbi,
142 unsigned SrcIdx, unsigned DstIdx,
144 SmallPtrSet<MachineInstr*, 8> &Processed);
146 void ScanUses(unsigned DstReg, MachineBasicBlock *MBB,
147 SmallPtrSet<MachineInstr*, 8> &Processed);
149 void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
150 SmallPtrSet<MachineInstr*, 8> &Processed);
152 void CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs, unsigned DstReg);
154 /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
155 /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
156 /// sub-register references of the register defined by REG_SEQUENCE.
157 bool EliminateRegSequences();
160 static char ID; // Pass identification, replacement for typeid
161 TwoAddressInstructionPass() : MachineFunctionPass(ID) {
162 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
165 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
166 AU.setPreservesCFG();
167 AU.addRequired<AliasAnalysis>();
168 AU.addPreserved<LiveVariables>();
169 AU.addPreservedID(MachineLoopInfoID);
170 AU.addPreservedID(MachineDominatorsID);
171 AU.addPreservedID(PHIEliminationID);
172 MachineFunctionPass::getAnalysisUsage(AU);
175 /// runOnMachineFunction - Pass entry point.
176 bool runOnMachineFunction(MachineFunction&);
180 char TwoAddressInstructionPass::ID = 0;
181 INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
182 "Two-Address instruction pass", false, false)
183 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
184 INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
185 "Two-Address instruction pass", false, false)
187 char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
189 /// Sink3AddrInstruction - A two-address instruction has been converted to a
190 /// three-address instruction to avoid clobbering a register. Try to sink it
191 /// past the instruction that would kill the above mentioned register to reduce
192 /// register pressure.
193 bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
194 MachineInstr *MI, unsigned SavedReg,
195 MachineBasicBlock::iterator OldPos) {
196 // FIXME: Shouldn't we be trying to do this before we three-addressify the
197 // instruction? After this transformation is done, we no longer need
198 // the instruction to be in three-address form.
200 // Check if it's safe to move this instruction.
201 bool SeenStore = true; // Be conservative.
202 if (!MI->isSafeToMove(TII, AA, SeenStore))
206 SmallSet<unsigned, 4> UseRegs;
208 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
209 const MachineOperand &MO = MI->getOperand(i);
212 unsigned MOReg = MO.getReg();
215 if (MO.isUse() && MOReg != SavedReg)
216 UseRegs.insert(MO.getReg());
220 // Don't try to move it if it implicitly defines a register.
223 // For now, don't move any instructions that define multiple registers.
225 DefReg = MO.getReg();
228 // Find the instruction that kills SavedReg.
229 MachineInstr *KillMI = NULL;
230 for (MachineRegisterInfo::use_nodbg_iterator
231 UI = MRI->use_nodbg_begin(SavedReg),
232 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
233 MachineOperand &UseMO = UI.getOperand();
236 KillMI = UseMO.getParent();
240 // If we find the instruction that kills SavedReg, and it is in an
241 // appropriate location, we can try to sink the current instruction
243 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
244 KillMI->getDesc().isTerminator())
247 // If any of the definitions are used by another instruction between the
248 // position and the kill use, then it's not safe to sink it.
250 // FIXME: This can be sped up if there is an easy way to query whether an
251 // instruction is before or after another instruction. Then we can use
252 // MachineRegisterInfo def / use instead.
253 MachineOperand *KillMO = NULL;
254 MachineBasicBlock::iterator KillPos = KillMI;
257 unsigned NumVisited = 0;
258 for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
259 MachineInstr *OtherMI = I;
260 // DBG_VALUE cannot be counted against the limit.
261 if (OtherMI->isDebugValue())
263 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
266 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
267 MachineOperand &MO = OtherMI->getOperand(i);
270 unsigned MOReg = MO.getReg();
277 if (OtherMI == KillMI && MOReg == SavedReg)
278 // Save the operand that kills the register. We want to unset the kill
279 // marker if we can sink MI past it.
281 else if (UseRegs.count(MOReg))
282 // One of the uses is killed before the destination.
288 // Update kill and LV information.
289 KillMO->setIsKill(false);
290 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
291 KillMO->setIsKill(true);
294 LV->replaceKillInstruction(SavedReg, KillMI, MI);
296 // Move instruction to its destination.
298 MBB->insert(KillPos, MI);
304 /// isTwoAddrUse - Return true if the specified MI is using the specified
305 /// register as a two-address operand.
306 static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
307 const MCInstrDesc &MCID = UseMI->getDesc();
308 for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
309 MachineOperand &MO = UseMI->getOperand(i);
310 if (MO.isReg() && MO.getReg() == Reg &&
311 (MO.isDef() || UseMI->isRegTiedToDefOperand(i)))
312 // Earlier use is a two-address one.
318 /// isProfitableToReMat - Return true if the heuristics determines it is likely
319 /// to be profitable to re-materialize the definition of Reg rather than copy
322 TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
323 const TargetRegisterClass *RC,
324 MachineInstr *MI, MachineInstr *DefMI,
325 MachineBasicBlock *MBB, unsigned Loc) {
326 bool OtherUse = false;
327 for (MachineRegisterInfo::use_nodbg_iterator UI = MRI->use_nodbg_begin(Reg),
328 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
329 MachineOperand &UseMO = UI.getOperand();
330 MachineInstr *UseMI = UseMO.getParent();
331 MachineBasicBlock *UseMBB = UseMI->getParent();
333 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
334 if (DI != DistanceMap.end() && DI->second == Loc)
335 continue; // Current use.
337 // There is at least one other use in the MBB that will clobber the
339 if (isTwoAddrUse(UseMI, Reg))
344 // If other uses in MBB are not two-address uses, then don't remat.
348 // No other uses in the same block, remat if it's defined in the same
349 // block so it does not unnecessarily extend the live range.
350 return MBB == DefMI->getParent();
353 /// NoUseAfterLastDef - Return true if there are no intervening uses between the
354 /// last instruction in the MBB that defines the specified register and the
355 /// two-address instruction which is being processed. It also returns the last
356 /// def location by reference
357 bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
358 MachineBasicBlock *MBB, unsigned Dist,
361 unsigned LastUse = Dist;
362 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
363 E = MRI->reg_end(); I != E; ++I) {
364 MachineOperand &MO = I.getOperand();
365 MachineInstr *MI = MO.getParent();
366 if (MI->getParent() != MBB || MI->isDebugValue())
368 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
369 if (DI == DistanceMap.end())
371 if (MO.isUse() && DI->second < LastUse)
372 LastUse = DI->second;
373 if (MO.isDef() && DI->second > LastDef)
374 LastDef = DI->second;
377 return !(LastUse > LastDef && LastUse < Dist);
380 MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg,
381 MachineBasicBlock *MBB,
383 unsigned LastUseDist = 0;
384 MachineInstr *LastUse = 0;
385 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
386 E = MRI->reg_end(); I != E; ++I) {
387 MachineOperand &MO = I.getOperand();
388 MachineInstr *MI = MO.getParent();
389 if (MI->getParent() != MBB || MI->isDebugValue())
391 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
392 if (DI == DistanceMap.end())
394 if (DI->second >= Dist)
397 if (MO.isUse() && DI->second > LastUseDist) {
399 LastUseDist = DI->second;
405 /// isCopyToReg - Return true if the specified MI is a copy instruction or
406 /// a extract_subreg instruction. It also returns the source and destination
407 /// registers and whether they are physical registers by reference.
408 static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
409 unsigned &SrcReg, unsigned &DstReg,
410 bool &IsSrcPhys, bool &IsDstPhys) {
414 DstReg = MI.getOperand(0).getReg();
415 SrcReg = MI.getOperand(1).getReg();
416 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
417 DstReg = MI.getOperand(0).getReg();
418 SrcReg = MI.getOperand(2).getReg();
422 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
423 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
427 /// isKilled - Test if the given register value, which is used by the given
428 /// instruction, is killed by the given instruction. This looks through
429 /// coalescable copies to see if the original value is potentially not killed.
431 /// For example, in this code:
433 /// %reg1034 = copy %reg1024
434 /// %reg1035 = copy %reg1025<kill>
435 /// %reg1036 = add %reg1034<kill>, %reg1035<kill>
437 /// %reg1034 is not considered to be killed, since it is copied from a
438 /// register which is not killed. Treating it as not killed lets the
439 /// normal heuristics commute the (two-address) add, which lets
440 /// coalescing eliminate the extra copy.
442 static bool isKilled(MachineInstr &MI, unsigned Reg,
443 const MachineRegisterInfo *MRI,
444 const TargetInstrInfo *TII) {
445 MachineInstr *DefMI = &MI;
447 if (!DefMI->killsRegister(Reg))
449 if (TargetRegisterInfo::isPhysicalRegister(Reg))
451 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
452 // If there are multiple defs, we can't do a simple analysis, so just
453 // go with what the kill flag says.
454 if (llvm::next(Begin) != MRI->def_end())
457 bool IsSrcPhys, IsDstPhys;
458 unsigned SrcReg, DstReg;
459 // If the def is something other than a copy, then it isn't going to
460 // be coalesced, so follow the kill flag.
461 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
467 /// isTwoAddrUse - Return true if the specified MI uses the specified register
468 /// as a two-address use. If so, return the destination register by reference.
469 static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
470 const MCInstrDesc &MCID = MI.getDesc();
471 unsigned NumOps = MI.isInlineAsm()
472 ? MI.getNumOperands() : MCID.getNumOperands();
473 for (unsigned i = 0; i != NumOps; ++i) {
474 const MachineOperand &MO = MI.getOperand(i);
475 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
478 if (MI.isRegTiedToDefOperand(i, &ti)) {
479 DstReg = MI.getOperand(ti).getReg();
486 /// findLocalKill - Look for an instruction below MI in the MBB that kills the
487 /// specified register. Returns null if there are any other Reg use between the
490 MachineInstr *findLocalKill(unsigned Reg, MachineBasicBlock *MBB,
491 MachineInstr *MI, MachineRegisterInfo *MRI,
492 DenseMap<MachineInstr*, unsigned> &DistanceMap) {
493 MachineInstr *KillMI = 0;
494 for (MachineRegisterInfo::use_nodbg_iterator
495 UI = MRI->use_nodbg_begin(Reg),
496 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
497 MachineInstr *UseMI = &*UI;
498 if (UseMI == MI || UseMI->getParent() != MBB)
500 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
501 if (DI != DistanceMap.end())
503 if (!UI.getOperand().isKill())
505 assert(!KillMI && "More than one local kills?");
512 /// findOnlyInterestingUse - Given a register, if has a single in-basic block
513 /// use, return the use instruction if it's a copy or a two-address use.
515 MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
516 MachineRegisterInfo *MRI,
517 const TargetInstrInfo *TII,
519 unsigned &DstReg, bool &IsDstPhys) {
520 if (!MRI->hasOneNonDBGUse(Reg))
521 // None or more than one use.
523 MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg);
524 if (UseMI.getParent() != MBB)
528 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
533 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
534 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
540 /// getMappedReg - Return the physical register the specified virtual register
541 /// might be mapped to.
543 getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
544 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
545 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
546 if (SI == RegMap.end())
550 if (TargetRegisterInfo::isPhysicalRegister(Reg))
555 /// regsAreCompatible - Return true if the two registers are equal or aliased.
558 regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
563 return TRI->regsOverlap(RegA, RegB);
567 /// isProfitableToReMat - Return true if it's potentially profitable to commute
568 /// the two-address instruction that's being processed.
570 TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC,
571 MachineInstr *MI, MachineBasicBlock *MBB,
573 // Determine if it's profitable to commute this two address instruction. In
574 // general, we want no uses between this instruction and the definition of
575 // the two-address register.
577 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
578 // %reg1029<def> = MOV8rr %reg1028
579 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
580 // insert => %reg1030<def> = MOV8rr %reg1028
581 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
582 // In this case, it might not be possible to coalesce the second MOV8rr
583 // instruction if the first one is coalesced. So it would be profitable to
585 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
586 // %reg1029<def> = MOV8rr %reg1028
587 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
588 // insert => %reg1030<def> = MOV8rr %reg1029
589 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
591 if (!MI->killsRegister(regC))
594 // Ok, we have something like:
595 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
596 // let's see if it's worth commuting it.
598 // Look for situations like this:
599 // %reg1024<def> = MOV r1
600 // %reg1025<def> = MOV r0
601 // %reg1026<def> = ADD %reg1024, %reg1025
603 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
604 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
605 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
606 unsigned ToRegB = getMappedReg(regB, DstRegMap);
607 unsigned ToRegC = getMappedReg(regC, DstRegMap);
608 if ((FromRegB && ToRegB && !regsAreCompatible(FromRegB, ToRegB, TRI)) &&
609 ((!FromRegC && !ToRegC) ||
610 regsAreCompatible(FromRegB, ToRegC, TRI) ||
611 regsAreCompatible(FromRegC, ToRegB, TRI)))
614 // If there is a use of regC between its last def (could be livein) and this
615 // instruction, then bail.
616 unsigned LastDefC = 0;
617 if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
620 // If there is a use of regB between its last def (could be livein) and this
621 // instruction, then go ahead and make this transformation.
622 unsigned LastDefB = 0;
623 if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
626 // Since there are no intervening uses for both registers, then commute
627 // if the def of regC is closer. Its live interval is shorter.
628 return LastDefB && LastDefC && LastDefC > LastDefB;
631 /// CommuteInstruction - Commute a two-address instruction and update the basic
632 /// block, distance map, and live variables if needed. Return true if it is
635 TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
636 MachineFunction::iterator &mbbi,
637 unsigned RegB, unsigned RegC, unsigned Dist) {
638 MachineInstr *MI = mi;
639 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
640 MachineInstr *NewMI = TII->commuteInstruction(MI);
643 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
647 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
648 // If the instruction changed to commute it, update livevar.
651 // Update live variables
652 LV->replaceKillInstruction(RegC, MI, NewMI);
654 mbbi->insert(mi, NewMI); // Insert the new inst
655 mbbi->erase(mi); // Nuke the old inst.
657 DistanceMap.insert(std::make_pair(NewMI, Dist));
660 // Update source register map.
661 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
663 unsigned RegA = MI->getOperand(0).getReg();
664 SrcRegMap[RegA] = FromRegC;
670 /// isProfitableToConv3Addr - Return true if it is profitable to convert the
671 /// given 2-address instruction to a 3-address one.
673 TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
674 // Look for situations like this:
675 // %reg1024<def> = MOV r1
676 // %reg1025<def> = MOV r0
677 // %reg1026<def> = ADD %reg1024, %reg1025
679 // Turn ADD into a 3-address instruction to avoid a copy.
680 unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
683 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
684 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
687 /// ConvertInstTo3Addr - Convert the specified two-address instruction into a
688 /// three address one. Return true if this transformation was successful.
690 TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
691 MachineBasicBlock::iterator &nmi,
692 MachineFunction::iterator &mbbi,
693 unsigned RegA, unsigned RegB,
695 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
697 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
698 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
701 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
702 // FIXME: Temporary workaround. If the new instruction doesn't
703 // uses RegB, convertToThreeAddress must have created more
704 // then one instruction.
705 Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
707 mbbi->erase(mi); // Nuke the old inst.
710 DistanceMap.insert(std::make_pair(NewMI, Dist));
712 nmi = llvm::next(mi);
715 // Update source and destination register maps.
716 SrcRegMap.erase(RegA);
717 DstRegMap.erase(RegB);
724 /// ScanUses - Scan forward recursively for only uses, update maps if the use
725 /// is a copy or a two-address instruction.
727 TwoAddressInstructionPass::ScanUses(unsigned DstReg, MachineBasicBlock *MBB,
728 SmallPtrSet<MachineInstr*, 8> &Processed) {
729 SmallVector<unsigned, 4> VirtRegPairs;
733 unsigned Reg = DstReg;
734 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
735 NewReg, IsDstPhys)) {
736 if (IsCopy && !Processed.insert(UseMI))
739 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
740 if (DI != DistanceMap.end())
741 // Earlier in the same MBB.Reached via a back edge.
745 VirtRegPairs.push_back(NewReg);
748 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
750 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
751 VirtRegPairs.push_back(NewReg);
755 if (!VirtRegPairs.empty()) {
756 unsigned ToReg = VirtRegPairs.back();
757 VirtRegPairs.pop_back();
758 while (!VirtRegPairs.empty()) {
759 unsigned FromReg = VirtRegPairs.back();
760 VirtRegPairs.pop_back();
761 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
763 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
766 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
768 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
772 /// ProcessCopy - If the specified instruction is not yet processed, process it
773 /// if it's a copy. For a copy instruction, we find the physical registers the
774 /// source and destination registers might be mapped to. These are kept in
775 /// point-to maps used to determine future optimizations. e.g.
778 /// v1026 = add v1024, v1025
780 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
781 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
782 /// potentially joined with r1 on the output side. It's worthwhile to commute
783 /// 'add' to eliminate a copy.
784 void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
785 MachineBasicBlock *MBB,
786 SmallPtrSet<MachineInstr*, 8> &Processed) {
787 if (Processed.count(MI))
790 bool IsSrcPhys, IsDstPhys;
791 unsigned SrcReg, DstReg;
792 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
795 if (IsDstPhys && !IsSrcPhys)
796 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
797 else if (!IsDstPhys && IsSrcPhys) {
798 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
800 assert(SrcRegMap[DstReg] == SrcReg &&
801 "Can't map to two src physical registers!");
803 ScanUses(DstReg, MBB, Processed);
806 Processed.insert(MI);
810 /// isSafeToDelete - If the specified instruction does not produce any side
811 /// effects and all of its defs are dead, then it's safe to delete.
812 static bool isSafeToDelete(MachineInstr *MI,
813 const TargetInstrInfo *TII,
814 SmallVector<unsigned, 4> &Kills) {
815 const MCInstrDesc &MCID = MI->getDesc();
816 if (MCID.mayStore() || MCID.isCall())
818 if (MCID.isTerminator() || MI->hasUnmodeledSideEffects())
821 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
822 MachineOperand &MO = MI->getOperand(i);
825 if (MO.isDef() && !MO.isDead())
827 if (MO.isUse() && MO.isKill())
828 Kills.push_back(MO.getReg());
833 /// canUpdateDeletedKills - Check if all the registers listed in Kills are
834 /// killed by instructions in MBB preceding the current instruction at
835 /// position Dist. If so, return true and record information about the
836 /// preceding kills in NewKills.
837 bool TwoAddressInstructionPass::
838 canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
839 SmallVector<NewKill, 4> &NewKills,
840 MachineBasicBlock *MBB, unsigned Dist) {
841 while (!Kills.empty()) {
842 unsigned Kill = Kills.back();
844 if (TargetRegisterInfo::isPhysicalRegister(Kill))
847 MachineInstr *LastKill = FindLastUseInMBB(Kill, MBB, Dist);
851 bool isModRef = LastKill->definesRegister(Kill);
852 NewKills.push_back(std::make_pair(std::make_pair(Kill, isModRef),
858 /// DeleteUnusedInstr - If an instruction with a tied register operand can
859 /// be safely deleted, just delete it.
861 TwoAddressInstructionPass::DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
862 MachineBasicBlock::iterator &nmi,
863 MachineFunction::iterator &mbbi,
865 // Check if the instruction has no side effects and if all its defs are dead.
866 SmallVector<unsigned, 4> Kills;
867 if (!isSafeToDelete(mi, TII, Kills))
870 // If this instruction kills some virtual registers, we need to
871 // update the kill information. If it's not possible to do so,
873 SmallVector<NewKill, 4> NewKills;
874 if (!canUpdateDeletedKills(Kills, NewKills, &*mbbi, Dist))
878 while (!NewKills.empty()) {
879 MachineInstr *NewKill = NewKills.back().second;
880 unsigned Kill = NewKills.back().first.first;
881 bool isDead = NewKills.back().first.second;
883 if (LV->removeVirtualRegisterKilled(Kill, mi)) {
885 LV->addVirtualRegisterDead(Kill, NewKill);
887 LV->addVirtualRegisterKilled(Kill, NewKill);
892 mbbi->erase(mi); // Nuke the old inst.
897 /// RescheduleMIBelowKill - If there is one more local instruction that reads
898 /// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
899 /// instruction in order to eliminate the need for the copy.
901 TwoAddressInstructionPass::RescheduleMIBelowKill(MachineBasicBlock *MBB,
902 MachineBasicBlock::iterator &mi,
903 MachineBasicBlock::iterator &nmi,
905 MachineInstr *MI = &*mi;
906 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
907 if (DI == DistanceMap.end())
908 // Must be created from unfolded load. Don't waste time trying this.
911 MachineInstr *KillMI = findLocalKill(Reg, MBB, mi, MRI, DistanceMap);
912 if (!KillMI || KillMI->isCopy() || KillMI->isCopyLike())
913 // Don't mess with copies, they may be coalesced later.
916 const MCInstrDesc &MCID = KillMI->getDesc();
917 if (MCID.hasUnmodeledSideEffects() || MCID.isCall() || MCID.isBranch() ||
919 // Don't move pass calls, etc.
923 if (isTwoAddrUse(*KillMI, Reg, DstReg))
926 bool SeenStore = true;
927 if (!MI->isSafeToMove(TII, AA, SeenStore))
930 if (TII->getInstrLatency(InstrItins, MI) > 1)
931 // FIXME: Needs more sophisticated heuristics.
934 SmallSet<unsigned, 2> Uses;
935 SmallSet<unsigned, 2> Kills;
936 SmallSet<unsigned, 2> Defs;
937 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
938 const MachineOperand &MO = MI->getOperand(i);
941 unsigned MOReg = MO.getReg();
948 if (MO.isKill() && MOReg != Reg)
953 // Move the copies connected to MI down as well.
954 MachineBasicBlock::iterator From = MI;
955 MachineBasicBlock::iterator To = llvm::next(From);
956 while (To->isCopy() && Defs.count(To->getOperand(1).getReg())) {
957 Defs.insert(To->getOperand(0).getReg());
961 // Check if the reschedule will not break depedencies.
962 unsigned NumVisited = 0;
963 MachineBasicBlock::iterator KillPos = KillMI;
965 for (MachineBasicBlock::iterator I = To; I != KillPos; ++I) {
966 MachineInstr *OtherMI = I;
967 // DBG_VALUE cannot be counted against the limit.
968 if (OtherMI->isDebugValue())
970 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
973 const MCInstrDesc &OMCID = OtherMI->getDesc();
974 if (OMCID.hasUnmodeledSideEffects() || OMCID.isCall() || OMCID.isBranch() ||
975 OMCID.isTerminator())
976 // Don't move pass calls, etc.
978 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
979 const MachineOperand &MO = OtherMI->getOperand(i);
982 unsigned MOReg = MO.getReg();
986 if (Uses.count(MOReg))
987 // Physical register use would be clobbered.
989 if (!MO.isDead() && Defs.count(MOReg))
990 // May clobber a physical register def.
991 // FIXME: This may be too conservative. It's ok if the instruction
992 // is sunken completely below the use.
995 if (Defs.count(MOReg))
998 ((MO.isKill() && Uses.count(MOReg)) || Kills.count(MOReg)))
999 // Don't want to extend other live ranges and update kills.
1005 // Move debug info as well.
1006 while (From != MBB->begin() && llvm::prior(From)->isDebugValue())
1009 // Copies following MI may have been moved as well.
1011 MBB->splice(KillPos, MBB, From, To);
1012 DistanceMap.erase(DI);
1015 // Update live variables
1016 LV->removeVirtualRegisterKilled(Reg, KillMI);
1017 LV->addVirtualRegisterKilled(Reg, MI);
1019 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
1020 MachineOperand &MO = KillMI->getOperand(i);
1021 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
1023 MO.setIsKill(false);
1025 MI->addRegisterKilled(Reg, 0);
1031 /// isDefTooClose - Return true if the re-scheduling will put the given
1032 /// instruction too close to the defs of its register dependencies.
1033 bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
1035 MachineBasicBlock *MBB) {
1036 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(Reg),
1037 DE = MRI->def_end(); DI != DE; ++DI) {
1038 MachineInstr *DefMI = &*DI;
1039 if (DefMI->getParent() != MBB || DefMI->isCopy() || DefMI->isCopyLike())
1042 return true; // MI is defining something KillMI uses
1043 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(DefMI);
1044 if (DDI == DistanceMap.end())
1045 return true; // Below MI
1046 unsigned DefDist = DDI->second;
1047 assert(Dist > DefDist && "Visited def already?");
1048 if (TII->getInstrLatency(InstrItins, DefMI) > (int)(Dist - DefDist))
1054 /// RescheduleKillAboveMI - If there is one more local instruction that reads
1055 /// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
1056 /// current two-address instruction in order to eliminate the need for the
1059 TwoAddressInstructionPass::RescheduleKillAboveMI(MachineBasicBlock *MBB,
1060 MachineBasicBlock::iterator &mi,
1061 MachineBasicBlock::iterator &nmi,
1063 MachineInstr *MI = &*mi;
1064 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
1065 if (DI == DistanceMap.end())
1066 // Must be created from unfolded load. Don't waste time trying this.
1069 MachineInstr *KillMI = findLocalKill(Reg, MBB, mi, MRI, DistanceMap);
1070 if (!KillMI || KillMI->isCopy() || KillMI->isCopyLike())
1071 // Don't mess with copies, they may be coalesced later.
1075 if (isTwoAddrUse(*KillMI, Reg, DstReg))
1078 bool SeenStore = true;
1079 if (!KillMI->isSafeToMove(TII, AA, SeenStore))
1082 SmallSet<unsigned, 2> Uses;
1083 SmallSet<unsigned, 2> Kills;
1084 SmallSet<unsigned, 2> Defs;
1085 SmallSet<unsigned, 2> LiveDefs;
1086 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
1087 const MachineOperand &MO = KillMI->getOperand(i);
1090 unsigned MOReg = MO.getReg();
1094 if (isDefTooClose(MOReg, DI->second, MI, MBB))
1097 if (MO.isKill() && MOReg != Reg)
1098 Kills.insert(MOReg);
1099 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1102 LiveDefs.insert(MOReg);
1106 // Check if the reschedule will not break depedencies.
1107 unsigned NumVisited = 0;
1108 MachineBasicBlock::iterator KillPos = KillMI;
1109 for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
1110 MachineInstr *OtherMI = I;
1111 // DBG_VALUE cannot be counted against the limit.
1112 if (OtherMI->isDebugValue())
1114 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
1117 const MCInstrDesc &MCID = OtherMI->getDesc();
1118 if (MCID.hasUnmodeledSideEffects() || MCID.isCall() || MCID.isBranch() ||
1119 MCID.isTerminator())
1120 // Don't move pass calls, etc.
1122 SmallVector<unsigned, 2> OtherDefs;
1123 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
1124 const MachineOperand &MO = OtherMI->getOperand(i);
1127 unsigned MOReg = MO.getReg();
1131 if (Defs.count(MOReg))
1132 // Moving KillMI can clobber the physical register if the def has
1135 if (Kills.count(MOReg))
1136 // Don't want to extend other live ranges and update kills.
1139 OtherDefs.push_back(MOReg);
1143 for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
1144 unsigned MOReg = OtherDefs[i];
1145 if (Uses.count(MOReg))
1147 if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1148 LiveDefs.count(MOReg))
1150 // Physical register def is seen.
1155 // Move the old kill above MI, don't forget to move debug info as well.
1156 MachineBasicBlock::iterator InsertPos = mi;
1157 while (InsertPos != MBB->begin() && llvm::prior(InsertPos)->isDebugValue())
1159 MachineBasicBlock::iterator From = KillMI;
1160 MachineBasicBlock::iterator To = llvm::next(From);
1161 while (llvm::prior(From)->isDebugValue())
1163 MBB->splice(InsertPos, MBB, From, To);
1165 nmi = llvm::prior(InsertPos); // Backtrack so we process the moved instr.
1166 DistanceMap.erase(DI);
1169 // Update live variables
1170 LV->removeVirtualRegisterKilled(Reg, KillMI);
1171 LV->addVirtualRegisterKilled(Reg, MI);
1173 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
1174 MachineOperand &MO = KillMI->getOperand(i);
1175 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
1177 MO.setIsKill(false);
1179 MI->addRegisterKilled(Reg, 0);
1184 /// TryInstructionTransform - For the case where an instruction has a single
1185 /// pair of tied register operands, attempt some transformations that may
1186 /// either eliminate the tied operands or improve the opportunities for
1187 /// coalescing away the register copy. Returns true if the tied operands
1188 /// are eliminated altogether.
1189 bool TwoAddressInstructionPass::
1190 TryInstructionTransform(MachineBasicBlock::iterator &mi,
1191 MachineBasicBlock::iterator &nmi,
1192 MachineFunction::iterator &mbbi,
1193 unsigned SrcIdx, unsigned DstIdx, unsigned Dist,
1194 SmallPtrSet<MachineInstr*, 8> &Processed) {
1195 MachineInstr &MI = *mi;
1196 const MCInstrDesc &MCID = MI.getDesc();
1197 unsigned regA = MI.getOperand(DstIdx).getReg();
1198 unsigned regB = MI.getOperand(SrcIdx).getReg();
1200 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1201 "cannot make instruction into two-address form");
1203 // If regA is dead and the instruction can be deleted, just delete
1204 // it so it doesn't clobber regB.
1205 bool regBKilled = isKilled(MI, regB, MRI, TII);
1206 if (!regBKilled && MI.getOperand(DstIdx).isDead() &&
1207 DeleteUnusedInstr(mi, nmi, mbbi, Dist)) {
1209 return true; // Done with this instruction.
1212 // Check if it is profitable to commute the operands.
1213 unsigned SrcOp1, SrcOp2;
1215 unsigned regCIdx = ~0U;
1216 bool TryCommute = false;
1217 bool AggressiveCommute = false;
1218 if (MCID.isCommutable() && MI.getNumOperands() >= 3 &&
1219 TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
1220 if (SrcIdx == SrcOp1)
1222 else if (SrcIdx == SrcOp2)
1225 if (regCIdx != ~0U) {
1226 regC = MI.getOperand(regCIdx).getReg();
1227 if (!regBKilled && isKilled(MI, regC, MRI, TII))
1228 // If C dies but B does not, swap the B and C operands.
1229 // This makes the live ranges of A and C joinable.
1231 else if (isProfitableToCommute(regB, regC, &MI, mbbi, Dist)) {
1233 AggressiveCommute = true;
1238 // If it's profitable to commute, try to do so.
1239 if (TryCommute && CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
1241 if (AggressiveCommute)
1246 // If there is one more use of regB later in the same MBB, consider
1247 // re-schedule this MI below it.
1248 if (RescheduleMIBelowKill(mbbi, mi, nmi, regB)) {
1253 if (TargetRegisterInfo::isVirtualRegister(regA))
1254 ScanUses(regA, &*mbbi, Processed);
1256 if (MCID.isConvertibleTo3Addr()) {
1257 // This instruction is potentially convertible to a true
1258 // three-address instruction. Check if it is profitable.
1259 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
1260 // Try to convert it.
1261 if (ConvertInstTo3Addr(mi, nmi, mbbi, regA, regB, Dist)) {
1262 ++NumConvertedTo3Addr;
1263 return true; // Done with this instruction.
1268 // If there is one more use of regB later in the same MBB, consider
1269 // re-schedule it before this MI if it's legal.
1270 if (RescheduleKillAboveMI(mbbi, mi, nmi, regB)) {
1275 // If this is an instruction with a load folded into it, try unfolding
1276 // the load, e.g. avoid this:
1278 // addq (%rax), %rcx
1279 // in favor of this:
1280 // movq (%rax), %rcx
1282 // because it's preferable to schedule a load than a register copy.
1283 if (MCID.mayLoad() && !regBKilled) {
1284 // Determine if a load can be unfolded.
1285 unsigned LoadRegIndex;
1287 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1288 /*UnfoldLoad=*/true,
1289 /*UnfoldStore=*/false,
1292 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1293 if (UnfoldMCID.getNumDefs() == 1) {
1294 MachineFunction &MF = *mbbi->getParent();
1297 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
1298 const TargetRegisterClass *RC =
1299 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI);
1300 unsigned Reg = MRI->createVirtualRegister(RC);
1301 SmallVector<MachineInstr *, 2> NewMIs;
1302 if (!TII->unfoldMemoryOperand(MF, &MI, Reg,
1303 /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
1305 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1308 assert(NewMIs.size() == 2 &&
1309 "Unfolded a load into multiple instructions!");
1310 // The load was previously folded, so this is the only use.
1311 NewMIs[1]->addRegisterKilled(Reg, TRI);
1313 // Tentatively insert the instructions into the block so that they
1314 // look "normal" to the transformation logic.
1315 mbbi->insert(mi, NewMIs[0]);
1316 mbbi->insert(mi, NewMIs[1]);
1318 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1319 << "2addr: NEW INST: " << *NewMIs[1]);
1321 // Transform the instruction, now that it no longer has a load.
1322 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1323 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1324 MachineBasicBlock::iterator NewMI = NewMIs[1];
1325 bool TransformSuccess =
1326 TryInstructionTransform(NewMI, mi, mbbi,
1327 NewSrcIdx, NewDstIdx, Dist, Processed);
1328 if (TransformSuccess ||
1329 NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1330 // Success, or at least we made an improvement. Keep the unfolded
1331 // instructions and discard the original.
1333 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1334 MachineOperand &MO = MI.getOperand(i);
1336 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1339 if (NewMIs[0]->killsRegister(MO.getReg()))
1340 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
1342 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1343 "Kill missing after load unfold!");
1344 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
1347 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
1348 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1349 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
1351 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1352 "Dead flag missing after load unfold!");
1353 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
1358 LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
1360 MI.eraseFromParent();
1362 if (TransformSuccess)
1365 // Transforming didn't eliminate the tie and didn't lead to an
1366 // improvement. Clean up the unfolded instructions and keep the
1368 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1369 NewMIs[0]->eraseFromParent();
1370 NewMIs[1]->eraseFromParent();
1379 /// runOnMachineFunction - Reduce two-address instructions to two operands.
1381 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
1382 DEBUG(dbgs() << "Machine Function\n");
1383 const TargetMachine &TM = MF.getTarget();
1384 MRI = &MF.getRegInfo();
1385 TII = TM.getInstrInfo();
1386 TRI = TM.getRegisterInfo();
1387 InstrItins = TM.getInstrItineraryData();
1388 LV = getAnalysisIfAvailable<LiveVariables>();
1389 AA = &getAnalysis<AliasAnalysis>();
1391 bool MadeChange = false;
1393 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
1394 DEBUG(dbgs() << "********** Function: "
1395 << MF.getFunction()->getName() << '\n');
1397 // This pass takes the function out of SSA form.
1400 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
1401 BitVector ReMatRegs(MRI->getNumVirtRegs());
1403 typedef DenseMap<unsigned, SmallVector<std::pair<unsigned, unsigned>, 4> >
1405 TiedOperandMap TiedOperands(4);
1407 SmallPtrSet<MachineInstr*, 8> Processed;
1408 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
1409 mbbi != mbbe; ++mbbi) {
1411 DistanceMap.clear();
1415 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
1417 MachineBasicBlock::iterator nmi = llvm::next(mi);
1418 if (mi->isDebugValue()) {
1423 // Remember REG_SEQUENCE instructions, we'll deal with them later.
1424 if (mi->isRegSequence())
1425 RegSequences.push_back(&*mi);
1427 const MCInstrDesc &MCID = mi->getDesc();
1428 bool FirstTied = true;
1430 DistanceMap.insert(std::make_pair(mi, ++Dist));
1432 ProcessCopy(&*mi, &*mbbi, Processed);
1434 // First scan through all the tied register uses in this instruction
1435 // and record a list of pairs of tied operands for each register.
1436 unsigned NumOps = mi->isInlineAsm()
1437 ? mi->getNumOperands() : MCID.getNumOperands();
1438 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1439 unsigned DstIdx = 0;
1440 if (!mi->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1445 ++NumTwoAddressInstrs;
1446 DEBUG(dbgs() << '\t' << *mi);
1449 assert(mi->getOperand(SrcIdx).isReg() &&
1450 mi->getOperand(SrcIdx).getReg() &&
1451 mi->getOperand(SrcIdx).isUse() &&
1452 "two address instruction invalid");
1454 unsigned regB = mi->getOperand(SrcIdx).getReg();
1455 TiedOperands[regB].push_back(std::make_pair(SrcIdx, DstIdx));
1458 // Now iterate over the information collected above.
1459 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1460 OE = TiedOperands.end(); OI != OE; ++OI) {
1461 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs = OI->second;
1463 // If the instruction has a single pair of tied operands, try some
1464 // transformations that may either eliminate the tied operands or
1465 // improve the opportunities for coalescing away the register copy.
1466 if (TiedOperands.size() == 1 && TiedPairs.size() == 1) {
1467 unsigned SrcIdx = TiedPairs[0].first;
1468 unsigned DstIdx = TiedPairs[0].second;
1470 // If the registers are already equal, nothing needs to be done.
1471 if (mi->getOperand(SrcIdx).getReg() ==
1472 mi->getOperand(DstIdx).getReg())
1473 break; // Done with this instruction.
1475 if (TryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist,
1477 break; // The tied operands have been eliminated.
1480 bool IsEarlyClobber = false;
1481 bool RemovedKillFlag = false;
1482 bool AllUsesCopied = true;
1483 unsigned LastCopiedReg = 0;
1484 unsigned regB = OI->first;
1485 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1486 unsigned SrcIdx = TiedPairs[tpi].first;
1487 unsigned DstIdx = TiedPairs[tpi].second;
1489 const MachineOperand &DstMO = mi->getOperand(DstIdx);
1490 unsigned regA = DstMO.getReg();
1491 IsEarlyClobber |= DstMO.isEarlyClobber();
1493 // Grab regB from the instruction because it may have changed if the
1494 // instruction was commuted.
1495 regB = mi->getOperand(SrcIdx).getReg();
1498 // The register is tied to multiple destinations (or else we would
1499 // not have continued this far), but this use of the register
1500 // already matches the tied destination. Leave it.
1501 AllUsesCopied = false;
1504 LastCopiedReg = regA;
1506 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1507 "cannot make instruction into two-address form");
1510 // First, verify that we don't have a use of "a" in the instruction
1511 // (a = b + a for example) because our transformation will not
1512 // work. This should never occur because we are in SSA form.
1513 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
1514 assert(i == DstIdx ||
1515 !mi->getOperand(i).isReg() ||
1516 mi->getOperand(i).getReg() != regA);
1519 // Emit a copy or rematerialize the definition.
1520 const TargetRegisterClass *rc = MRI->getRegClass(regB);
1521 MachineInstr *DefMI = MRI->getVRegDef(regB);
1522 // If it's safe and profitable, remat the definition instead of
1525 DefMI->getDesc().isAsCheapAsAMove() &&
1526 DefMI->isSafeToReMat(TII, AA, regB) &&
1527 isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){
1528 DEBUG(dbgs() << "2addr: REMATTING : " << *DefMI << "\n");
1529 unsigned regASubIdx = mi->getOperand(DstIdx).getSubReg();
1530 TII->reMaterialize(*mbbi, mi, regA, regASubIdx, DefMI, *TRI);
1531 ReMatRegs.set(TargetRegisterInfo::virtReg2Index(regB));
1534 BuildMI(*mbbi, mi, mi->getDebugLoc(), TII->get(TargetOpcode::COPY),
1538 MachineBasicBlock::iterator prevMI = prior(mi);
1539 // Update DistanceMap.
1540 DistanceMap.insert(std::make_pair(prevMI, Dist));
1541 DistanceMap[mi] = ++Dist;
1543 DEBUG(dbgs() << "\t\tprepend:\t" << *prevMI);
1545 MachineOperand &MO = mi->getOperand(SrcIdx);
1546 assert(MO.isReg() && MO.getReg() == regB && MO.isUse() &&
1547 "inconsistent operand info for 2-reg pass");
1549 MO.setIsKill(false);
1550 RemovedKillFlag = true;
1555 if (AllUsesCopied) {
1556 if (!IsEarlyClobber) {
1557 // Replace other (un-tied) uses of regB with LastCopiedReg.
1558 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1559 MachineOperand &MO = mi->getOperand(i);
1560 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1562 MO.setIsKill(false);
1563 RemovedKillFlag = true;
1565 MO.setReg(LastCopiedReg);
1570 // Update live variables for regB.
1571 if (RemovedKillFlag && LV && LV->getVarInfo(regB).removeKill(mi))
1572 LV->addVirtualRegisterKilled(regB, prior(mi));
1574 } else if (RemovedKillFlag) {
1575 // Some tied uses of regB matched their destination registers, so
1576 // regB is still used in this instruction, but a kill flag was
1577 // removed from a different tied use of regB, so now we need to add
1578 // a kill flag to one of the remaining uses of regB.
1579 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1580 MachineOperand &MO = mi->getOperand(i);
1581 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1588 // Schedule the source copy / remat inserted to form two-address
1589 // instruction. FIXME: Does it matter the distance map may not be
1590 // accurate after it's scheduled?
1591 TII->scheduleTwoAddrSource(prior(mi), mi, *TRI);
1595 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1598 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1599 if (mi->isInsertSubreg()) {
1600 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1601 // To %reg:subidx = COPY %subreg
1602 unsigned SubIdx = mi->getOperand(3).getImm();
1603 mi->RemoveOperand(3);
1604 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1605 mi->getOperand(0).setSubReg(SubIdx);
1606 mi->RemoveOperand(1);
1607 mi->setDesc(TII->get(TargetOpcode::COPY));
1608 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
1611 // Clear TiedOperands here instead of at the top of the loop
1612 // since most instructions do not have tied operands.
1613 TiedOperands.clear();
1618 // Some remat'ed instructions are dead.
1619 for (int i = ReMatRegs.find_first(); i != -1; i = ReMatRegs.find_next(i)) {
1620 unsigned VReg = TargetRegisterInfo::index2VirtReg(i);
1621 if (MRI->use_nodbg_empty(VReg)) {
1622 MachineInstr *DefMI = MRI->getVRegDef(VReg);
1623 DefMI->eraseFromParent();
1627 // Eliminate REG_SEQUENCE instructions. Their whole purpose was to preseve
1628 // SSA form. It's now safe to de-SSA.
1629 MadeChange |= EliminateRegSequences();
1634 static void UpdateRegSequenceSrcs(unsigned SrcReg,
1635 unsigned DstReg, unsigned SubIdx,
1636 MachineRegisterInfo *MRI,
1637 const TargetRegisterInfo &TRI) {
1638 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg),
1639 RE = MRI->reg_end(); RI != RE; ) {
1640 MachineOperand &MO = RI.getOperand();
1642 MO.substVirtReg(DstReg, SubIdx, TRI);
1646 /// CoalesceExtSubRegs - If a number of sources of the REG_SEQUENCE are
1647 /// EXTRACT_SUBREG from the same register and to the same virtual register
1648 /// with different sub-register indices, attempt to combine the
1649 /// EXTRACT_SUBREGs and pre-coalesce them. e.g.
1650 /// %reg1026<def> = VLDMQ %reg1025<kill>, 260, pred:14, pred:%reg0
1651 /// %reg1029:6<def> = EXTRACT_SUBREG %reg1026, 6
1652 /// %reg1029:5<def> = EXTRACT_SUBREG %reg1026<kill>, 5
1653 /// Since D subregs 5, 6 can combine to a Q register, we can coalesce
1654 /// reg1026 to reg1029.
1656 TwoAddressInstructionPass::CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs,
1658 SmallSet<unsigned, 4> Seen;
1659 for (unsigned i = 0, e = Srcs.size(); i != e; ++i) {
1660 unsigned SrcReg = Srcs[i];
1661 if (!Seen.insert(SrcReg))
1664 // Check that the instructions are all in the same basic block.
1665 MachineInstr *SrcDefMI = MRI->getVRegDef(SrcReg);
1666 MachineInstr *DstDefMI = MRI->getVRegDef(DstReg);
1667 if (SrcDefMI->getParent() != DstDefMI->getParent())
1670 // If there are no other uses than copies which feed into
1671 // the reg_sequence, then we might be able to coalesce them.
1672 bool CanCoalesce = true;
1673 SmallVector<unsigned, 4> SrcSubIndices, DstSubIndices;
1674 for (MachineRegisterInfo::use_nodbg_iterator
1675 UI = MRI->use_nodbg_begin(SrcReg),
1676 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
1677 MachineInstr *UseMI = &*UI;
1678 if (!UseMI->isCopy() || UseMI->getOperand(0).getReg() != DstReg) {
1679 CanCoalesce = false;
1682 SrcSubIndices.push_back(UseMI->getOperand(1).getSubReg());
1683 DstSubIndices.push_back(UseMI->getOperand(0).getSubReg());
1686 if (!CanCoalesce || SrcSubIndices.size() < 2)
1689 // Check that the source subregisters can be combined.
1690 std::sort(SrcSubIndices.begin(), SrcSubIndices.end());
1691 unsigned NewSrcSubIdx = 0;
1692 if (!TRI->canCombineSubRegIndices(MRI->getRegClass(SrcReg), SrcSubIndices,
1696 // Check that the destination subregisters can also be combined.
1697 std::sort(DstSubIndices.begin(), DstSubIndices.end());
1698 unsigned NewDstSubIdx = 0;
1699 if (!TRI->canCombineSubRegIndices(MRI->getRegClass(DstReg), DstSubIndices,
1703 // If neither source nor destination can be combined to the full register,
1704 // just give up. This could be improved if it ever matters.
1705 if (NewSrcSubIdx != 0 && NewDstSubIdx != 0)
1708 // Now that we know that all the uses are extract_subregs and that those
1709 // subregs can somehow be combined, scan all the extract_subregs again to
1710 // make sure the subregs are in the right order and can be composed.
1711 MachineInstr *SomeMI = 0;
1713 for (MachineRegisterInfo::use_nodbg_iterator
1714 UI = MRI->use_nodbg_begin(SrcReg),
1715 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
1716 MachineInstr *UseMI = &*UI;
1717 assert(UseMI->isCopy());
1718 unsigned DstSubIdx = UseMI->getOperand(0).getSubReg();
1719 unsigned SrcSubIdx = UseMI->getOperand(1).getSubReg();
1720 assert(DstSubIdx != 0 && "missing subreg from RegSequence elimination");
1721 if ((NewDstSubIdx == 0 &&
1722 TRI->composeSubRegIndices(NewSrcSubIdx, DstSubIdx) != SrcSubIdx) ||
1723 (NewSrcSubIdx == 0 &&
1724 TRI->composeSubRegIndices(NewDstSubIdx, SrcSubIdx) != DstSubIdx)) {
1725 CanCoalesce = false;
1728 // Keep track of one of the uses.
1734 // Insert a copy to replace the original.
1735 MachineInstr *CopyMI = BuildMI(*SomeMI->getParent(), SomeMI,
1736 SomeMI->getDebugLoc(),
1737 TII->get(TargetOpcode::COPY))
1738 .addReg(DstReg, RegState::Define, NewDstSubIdx)
1739 .addReg(SrcReg, 0, NewSrcSubIdx);
1741 // Remove all the old extract instructions.
1742 for (MachineRegisterInfo::use_nodbg_iterator
1743 UI = MRI->use_nodbg_begin(SrcReg),
1744 UE = MRI->use_nodbg_end(); UI != UE; ) {
1745 MachineInstr *UseMI = &*UI;
1747 if (UseMI == CopyMI)
1749 assert(UseMI->isCopy());
1750 // Move any kills to the new copy or extract instruction.
1751 if (UseMI->getOperand(1).isKill()) {
1752 CopyMI->getOperand(1).setIsKill();
1754 // Update live variables
1755 LV->replaceKillInstruction(SrcReg, UseMI, &*CopyMI);
1757 UseMI->eraseFromParent();
1762 static bool HasOtherRegSequenceUses(unsigned Reg, MachineInstr *RegSeq,
1763 MachineRegisterInfo *MRI) {
1764 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
1765 UE = MRI->use_end(); UI != UE; ++UI) {
1766 MachineInstr *UseMI = &*UI;
1767 if (UseMI != RegSeq && UseMI->isRegSequence())
1773 /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
1774 /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
1775 /// sub-register references of the register defined by REG_SEQUENCE. e.g.
1777 /// %reg1029<def>, %reg1030<def> = VLD1q16 %reg1024<kill>, ...
1778 /// %reg1031<def> = REG_SEQUENCE %reg1029<kill>, 5, %reg1030<kill>, 6
1780 /// %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
1781 bool TwoAddressInstructionPass::EliminateRegSequences() {
1782 if (RegSequences.empty())
1785 for (unsigned i = 0, e = RegSequences.size(); i != e; ++i) {
1786 MachineInstr *MI = RegSequences[i];
1787 unsigned DstReg = MI->getOperand(0).getReg();
1788 if (MI->getOperand(0).getSubReg() ||
1789 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1790 !(MI->getNumOperands() & 1)) {
1791 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1792 llvm_unreachable(0);
1795 bool IsImpDef = true;
1796 SmallVector<unsigned, 4> RealSrcs;
1797 SmallSet<unsigned, 4> Seen;
1798 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1799 unsigned SrcReg = MI->getOperand(i).getReg();
1800 unsigned SubIdx = MI->getOperand(i+1).getImm();
1801 if (MI->getOperand(i).getSubReg() ||
1802 TargetRegisterInfo::isPhysicalRegister(SrcReg)) {
1803 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1804 llvm_unreachable(0);
1807 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
1808 if (DefMI->isImplicitDef()) {
1809 DefMI->eraseFromParent();
1814 // Remember COPY sources. These might be candidate for coalescing.
1815 if (DefMI->isCopy() && DefMI->getOperand(1).getSubReg())
1816 RealSrcs.push_back(DefMI->getOperand(1).getReg());
1818 bool isKill = MI->getOperand(i).isKill();
1819 if (!Seen.insert(SrcReg) || MI->getParent() != DefMI->getParent() ||
1820 !isKill || HasOtherRegSequenceUses(SrcReg, MI, MRI) ||
1821 !TRI->getMatchingSuperRegClass(MRI->getRegClass(DstReg),
1822 MRI->getRegClass(SrcReg), SubIdx)) {
1823 // REG_SEQUENCE cannot have duplicated operands, add a copy.
1824 // Also add an copy if the source is live-in the block. We don't want
1825 // to end up with a partial-redef of a livein, e.g.
1827 // reg1051:10<def> =
1833 // LiveIntervalAnalysis won't like it.
1835 // If the REG_SEQUENCE doesn't kill its source, keeping live variables
1836 // correctly up to date becomes very difficult. Insert a copy.
1838 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1839 // might insert a COPY that uses SrcReg after is was killed.
1841 for (unsigned j = i + 2; j < e; j += 2)
1842 if (MI->getOperand(j).getReg() == SrcReg) {
1843 MI->getOperand(j).setIsKill();
1848 MachineBasicBlock::iterator InsertLoc = MI;
1849 MachineInstr *CopyMI = BuildMI(*MI->getParent(), InsertLoc,
1850 MI->getDebugLoc(), TII->get(TargetOpcode::COPY))
1851 .addReg(DstReg, RegState::Define, SubIdx)
1852 .addReg(SrcReg, getKillRegState(isKill));
1853 MI->getOperand(i).setReg(0);
1855 LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1856 DEBUG(dbgs() << "Inserted: " << *CopyMI);
1860 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1861 unsigned SrcReg = MI->getOperand(i).getReg();
1862 if (!SrcReg) continue;
1863 unsigned SubIdx = MI->getOperand(i+1).getImm();
1864 UpdateRegSequenceSrcs(SrcReg, DstReg, SubIdx, MRI, *TRI);
1868 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1869 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1870 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
1871 MI->RemoveOperand(j);
1873 DEBUG(dbgs() << "Eliminated: " << *MI);
1874 MI->eraseFromParent();
1877 // Try coalescing some EXTRACT_SUBREG instructions. This can create
1878 // INSERT_SUBREG instructions that must have <undef> flags added by
1879 // LiveIntervalAnalysis, so only run it when LiveVariables is available.
1881 CoalesceExtSubRegs(RealSrcs, DstReg);
1884 RegSequences.clear();