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;
71 CodeGenOpt::Level OptLevel;
73 // DistanceMap - Keep track the distance of a MI from the start of the
74 // current basic block.
75 DenseMap<MachineInstr*, unsigned> DistanceMap;
77 // SrcRegMap - A map from virtual registers to physical registers which
78 // are likely targets to be coalesced to due to copies from physical
79 // registers to virtual registers. e.g. v1024 = move r0.
80 DenseMap<unsigned, unsigned> SrcRegMap;
82 // DstRegMap - A map from virtual registers to physical registers which
83 // are likely targets to be coalesced to due to copies to physical
84 // registers from virtual registers. e.g. r1 = move v1024.
85 DenseMap<unsigned, unsigned> DstRegMap;
87 /// RegSequences - Keep track the list of REG_SEQUENCE instructions seen
88 /// during the initial walk of the machine function.
89 SmallVector<MachineInstr*, 16> RegSequences;
91 bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
93 MachineBasicBlock::iterator OldPos);
95 bool isProfitableToReMat(unsigned Reg, const TargetRegisterClass *RC,
96 MachineInstr *MI, MachineInstr *DefMI,
97 MachineBasicBlock *MBB, unsigned Loc);
99 bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
102 MachineInstr *FindLastUseInMBB(unsigned Reg, MachineBasicBlock *MBB,
105 bool isProfitableToCommute(unsigned regB, unsigned regC,
106 MachineInstr *MI, MachineBasicBlock *MBB,
109 bool CommuteInstruction(MachineBasicBlock::iterator &mi,
110 MachineFunction::iterator &mbbi,
111 unsigned RegB, unsigned RegC, unsigned Dist);
113 bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
115 bool ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
116 MachineBasicBlock::iterator &nmi,
117 MachineFunction::iterator &mbbi,
118 unsigned RegA, unsigned RegB, unsigned Dist);
120 typedef std::pair<std::pair<unsigned, bool>, MachineInstr*> NewKill;
121 bool canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
122 SmallVector<NewKill, 4> &NewKills,
123 MachineBasicBlock *MBB, unsigned Dist);
124 bool DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
125 MachineBasicBlock::iterator &nmi,
126 MachineFunction::iterator &mbbi, unsigned Dist);
128 bool isDefTooClose(unsigned Reg, unsigned Dist,
129 MachineInstr *MI, MachineBasicBlock *MBB);
131 bool RescheduleMIBelowKill(MachineBasicBlock *MBB,
132 MachineBasicBlock::iterator &mi,
133 MachineBasicBlock::iterator &nmi,
135 bool RescheduleKillAboveMI(MachineBasicBlock *MBB,
136 MachineBasicBlock::iterator &mi,
137 MachineBasicBlock::iterator &nmi,
140 bool TryInstructionTransform(MachineBasicBlock::iterator &mi,
141 MachineBasicBlock::iterator &nmi,
142 MachineFunction::iterator &mbbi,
143 unsigned SrcIdx, unsigned DstIdx,
145 SmallPtrSet<MachineInstr*, 8> &Processed);
147 void ScanUses(unsigned DstReg, MachineBasicBlock *MBB,
148 SmallPtrSet<MachineInstr*, 8> &Processed);
150 void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
151 SmallPtrSet<MachineInstr*, 8> &Processed);
153 void CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs, unsigned DstReg);
155 /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
156 /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
157 /// sub-register references of the register defined by REG_SEQUENCE.
158 bool EliminateRegSequences();
161 static char ID; // Pass identification, replacement for typeid
162 TwoAddressInstructionPass() : MachineFunctionPass(ID) {
163 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
166 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
167 AU.setPreservesCFG();
168 AU.addRequired<AliasAnalysis>();
169 AU.addPreserved<LiveVariables>();
170 AU.addPreservedID(MachineLoopInfoID);
171 AU.addPreservedID(MachineDominatorsID);
172 AU.addPreservedID(PHIEliminationID);
173 MachineFunctionPass::getAnalysisUsage(AU);
176 /// runOnMachineFunction - Pass entry point.
177 bool runOnMachineFunction(MachineFunction&);
181 char TwoAddressInstructionPass::ID = 0;
182 INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
183 "Two-Address instruction pass", false, false)
184 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
185 INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
186 "Two-Address instruction pass", false, false)
188 char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
190 /// Sink3AddrInstruction - A two-address instruction has been converted to a
191 /// three-address instruction to avoid clobbering a register. Try to sink it
192 /// past the instruction that would kill the above mentioned register to reduce
193 /// register pressure.
194 bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
195 MachineInstr *MI, unsigned SavedReg,
196 MachineBasicBlock::iterator OldPos) {
197 // FIXME: Shouldn't we be trying to do this before we three-addressify the
198 // instruction? After this transformation is done, we no longer need
199 // the instruction to be in three-address form.
201 // Check if it's safe to move this instruction.
202 bool SeenStore = true; // Be conservative.
203 if (!MI->isSafeToMove(TII, AA, SeenStore))
207 SmallSet<unsigned, 4> UseRegs;
209 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
210 const MachineOperand &MO = MI->getOperand(i);
213 unsigned MOReg = MO.getReg();
216 if (MO.isUse() && MOReg != SavedReg)
217 UseRegs.insert(MO.getReg());
221 // Don't try to move it if it implicitly defines a register.
224 // For now, don't move any instructions that define multiple registers.
226 DefReg = MO.getReg();
229 // Find the instruction that kills SavedReg.
230 MachineInstr *KillMI = NULL;
231 for (MachineRegisterInfo::use_nodbg_iterator
232 UI = MRI->use_nodbg_begin(SavedReg),
233 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
234 MachineOperand &UseMO = UI.getOperand();
237 KillMI = UseMO.getParent();
241 // If we find the instruction that kills SavedReg, and it is in an
242 // appropriate location, we can try to sink the current instruction
244 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
245 KillMI->getDesc().isTerminator())
248 // If any of the definitions are used by another instruction between the
249 // position and the kill use, then it's not safe to sink it.
251 // FIXME: This can be sped up if there is an easy way to query whether an
252 // instruction is before or after another instruction. Then we can use
253 // MachineRegisterInfo def / use instead.
254 MachineOperand *KillMO = NULL;
255 MachineBasicBlock::iterator KillPos = KillMI;
258 unsigned NumVisited = 0;
259 for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
260 MachineInstr *OtherMI = I;
261 // DBG_VALUE cannot be counted against the limit.
262 if (OtherMI->isDebugValue())
264 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
267 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
268 MachineOperand &MO = OtherMI->getOperand(i);
271 unsigned MOReg = MO.getReg();
278 if (OtherMI == KillMI && MOReg == SavedReg)
279 // Save the operand that kills the register. We want to unset the kill
280 // marker if we can sink MI past it.
282 else if (UseRegs.count(MOReg))
283 // One of the uses is killed before the destination.
289 // Update kill and LV information.
290 KillMO->setIsKill(false);
291 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
292 KillMO->setIsKill(true);
295 LV->replaceKillInstruction(SavedReg, KillMI, MI);
297 // Move instruction to its destination.
299 MBB->insert(KillPos, MI);
305 /// isTwoAddrUse - Return true if the specified MI is using the specified
306 /// register as a two-address operand.
307 static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
308 const MCInstrDesc &MCID = UseMI->getDesc();
309 for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
310 MachineOperand &MO = UseMI->getOperand(i);
311 if (MO.isReg() && MO.getReg() == Reg &&
312 (MO.isDef() || UseMI->isRegTiedToDefOperand(i)))
313 // Earlier use is a two-address one.
319 /// isProfitableToReMat - Return true if the heuristics determines it is likely
320 /// to be profitable to re-materialize the definition of Reg rather than copy
323 TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
324 const TargetRegisterClass *RC,
325 MachineInstr *MI, MachineInstr *DefMI,
326 MachineBasicBlock *MBB, unsigned Loc) {
327 bool OtherUse = false;
328 for (MachineRegisterInfo::use_nodbg_iterator UI = MRI->use_nodbg_begin(Reg),
329 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
330 MachineOperand &UseMO = UI.getOperand();
331 MachineInstr *UseMI = UseMO.getParent();
332 MachineBasicBlock *UseMBB = UseMI->getParent();
334 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
335 if (DI != DistanceMap.end() && DI->second == Loc)
336 continue; // Current use.
338 // There is at least one other use in the MBB that will clobber the
340 if (isTwoAddrUse(UseMI, Reg))
345 // If other uses in MBB are not two-address uses, then don't remat.
349 // No other uses in the same block, remat if it's defined in the same
350 // block so it does not unnecessarily extend the live range.
351 return MBB == DefMI->getParent();
354 /// NoUseAfterLastDef - Return true if there are no intervening uses between the
355 /// last instruction in the MBB that defines the specified register and the
356 /// two-address instruction which is being processed. It also returns the last
357 /// def location by reference
358 bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
359 MachineBasicBlock *MBB, unsigned Dist,
362 unsigned LastUse = Dist;
363 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
364 E = MRI->reg_end(); I != E; ++I) {
365 MachineOperand &MO = I.getOperand();
366 MachineInstr *MI = MO.getParent();
367 if (MI->getParent() != MBB || MI->isDebugValue())
369 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
370 if (DI == DistanceMap.end())
372 if (MO.isUse() && DI->second < LastUse)
373 LastUse = DI->second;
374 if (MO.isDef() && DI->second > LastDef)
375 LastDef = DI->second;
378 return !(LastUse > LastDef && LastUse < Dist);
381 MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg,
382 MachineBasicBlock *MBB,
384 unsigned LastUseDist = 0;
385 MachineInstr *LastUse = 0;
386 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
387 E = MRI->reg_end(); I != E; ++I) {
388 MachineOperand &MO = I.getOperand();
389 MachineInstr *MI = MO.getParent();
390 if (MI->getParent() != MBB || MI->isDebugValue())
392 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
393 if (DI == DistanceMap.end())
395 if (DI->second >= Dist)
398 if (MO.isUse() && DI->second > LastUseDist) {
400 LastUseDist = DI->second;
406 /// isCopyToReg - Return true if the specified MI is a copy instruction or
407 /// a extract_subreg instruction. It also returns the source and destination
408 /// registers and whether they are physical registers by reference.
409 static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
410 unsigned &SrcReg, unsigned &DstReg,
411 bool &IsSrcPhys, bool &IsDstPhys) {
415 DstReg = MI.getOperand(0).getReg();
416 SrcReg = MI.getOperand(1).getReg();
417 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
418 DstReg = MI.getOperand(0).getReg();
419 SrcReg = MI.getOperand(2).getReg();
423 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
424 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
428 /// isKilled - Test if the given register value, which is used by the given
429 /// instruction, is killed by the given instruction. This looks through
430 /// coalescable copies to see if the original value is potentially not killed.
432 /// For example, in this code:
434 /// %reg1034 = copy %reg1024
435 /// %reg1035 = copy %reg1025<kill>
436 /// %reg1036 = add %reg1034<kill>, %reg1035<kill>
438 /// %reg1034 is not considered to be killed, since it is copied from a
439 /// register which is not killed. Treating it as not killed lets the
440 /// normal heuristics commute the (two-address) add, which lets
441 /// coalescing eliminate the extra copy.
443 static bool isKilled(MachineInstr &MI, unsigned Reg,
444 const MachineRegisterInfo *MRI,
445 const TargetInstrInfo *TII) {
446 MachineInstr *DefMI = &MI;
448 if (!DefMI->killsRegister(Reg))
450 if (TargetRegisterInfo::isPhysicalRegister(Reg))
452 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
453 // If there are multiple defs, we can't do a simple analysis, so just
454 // go with what the kill flag says.
455 if (llvm::next(Begin) != MRI->def_end())
458 bool IsSrcPhys, IsDstPhys;
459 unsigned SrcReg, DstReg;
460 // If the def is something other than a copy, then it isn't going to
461 // be coalesced, so follow the kill flag.
462 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
468 /// isTwoAddrUse - Return true if the specified MI uses the specified register
469 /// as a two-address use. If so, return the destination register by reference.
470 static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
471 const MCInstrDesc &MCID = MI.getDesc();
472 unsigned NumOps = MI.isInlineAsm()
473 ? MI.getNumOperands() : MCID.getNumOperands();
474 for (unsigned i = 0; i != NumOps; ++i) {
475 const MachineOperand &MO = MI.getOperand(i);
476 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
479 if (MI.isRegTiedToDefOperand(i, &ti)) {
480 DstReg = MI.getOperand(ti).getReg();
487 /// findLocalKill - Look for an instruction below MI in the MBB that kills the
488 /// specified register. Returns null if there are any other Reg use between the
491 MachineInstr *findLocalKill(unsigned Reg, MachineBasicBlock *MBB,
492 MachineInstr *MI, MachineRegisterInfo *MRI,
493 DenseMap<MachineInstr*, unsigned> &DistanceMap) {
494 MachineInstr *KillMI = 0;
495 for (MachineRegisterInfo::use_nodbg_iterator
496 UI = MRI->use_nodbg_begin(Reg),
497 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
498 MachineInstr *UseMI = &*UI;
499 if (UseMI == MI || UseMI->getParent() != MBB)
501 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
502 if (DI != DistanceMap.end())
504 if (!UI.getOperand().isKill())
507 return 0; // -O0 kill markers cannot be trusted?
514 /// findOnlyInterestingUse - Given a register, if has a single in-basic block
515 /// use, return the use instruction if it's a copy or a two-address use.
517 MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
518 MachineRegisterInfo *MRI,
519 const TargetInstrInfo *TII,
521 unsigned &DstReg, bool &IsDstPhys) {
522 if (!MRI->hasOneNonDBGUse(Reg))
523 // None or more than one use.
525 MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg);
526 if (UseMI.getParent() != MBB)
530 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
535 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
536 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
542 /// getMappedReg - Return the physical register the specified virtual register
543 /// might be mapped to.
545 getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
546 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
547 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
548 if (SI == RegMap.end())
552 if (TargetRegisterInfo::isPhysicalRegister(Reg))
557 /// regsAreCompatible - Return true if the two registers are equal or aliased.
560 regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
565 return TRI->regsOverlap(RegA, RegB);
569 /// isProfitableToReMat - Return true if it's potentially profitable to commute
570 /// the two-address instruction that's being processed.
572 TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC,
573 MachineInstr *MI, MachineBasicBlock *MBB,
575 if (OptLevel == CodeGenOpt::None)
578 // Determine if it's profitable to commute this two address instruction. In
579 // general, we want no uses between this instruction and the definition of
580 // the two-address register.
582 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
583 // %reg1029<def> = MOV8rr %reg1028
584 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
585 // insert => %reg1030<def> = MOV8rr %reg1028
586 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
587 // In this case, it might not be possible to coalesce the second MOV8rr
588 // instruction if the first one is coalesced. So it would be profitable to
590 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
591 // %reg1029<def> = MOV8rr %reg1028
592 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
593 // insert => %reg1030<def> = MOV8rr %reg1029
594 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
596 if (!MI->killsRegister(regC))
599 // Ok, we have something like:
600 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
601 // let's see if it's worth commuting it.
603 // Look for situations like this:
604 // %reg1024<def> = MOV r1
605 // %reg1025<def> = MOV r0
606 // %reg1026<def> = ADD %reg1024, %reg1025
608 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
609 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
610 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
611 unsigned ToRegB = getMappedReg(regB, DstRegMap);
612 unsigned ToRegC = getMappedReg(regC, DstRegMap);
613 if ((FromRegB && ToRegB && !regsAreCompatible(FromRegB, ToRegB, TRI)) &&
614 ((!FromRegC && !ToRegC) ||
615 regsAreCompatible(FromRegB, ToRegC, TRI) ||
616 regsAreCompatible(FromRegC, ToRegB, TRI)))
619 // If there is a use of regC between its last def (could be livein) and this
620 // instruction, then bail.
621 unsigned LastDefC = 0;
622 if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
625 // If there is a use of regB between its last def (could be livein) and this
626 // instruction, then go ahead and make this transformation.
627 unsigned LastDefB = 0;
628 if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
631 // Since there are no intervening uses for both registers, then commute
632 // if the def of regC is closer. Its live interval is shorter.
633 return LastDefB && LastDefC && LastDefC > LastDefB;
636 /// CommuteInstruction - Commute a two-address instruction and update the basic
637 /// block, distance map, and live variables if needed. Return true if it is
640 TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
641 MachineFunction::iterator &mbbi,
642 unsigned RegB, unsigned RegC, unsigned Dist) {
643 MachineInstr *MI = mi;
644 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
645 MachineInstr *NewMI = TII->commuteInstruction(MI);
648 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
652 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
653 // If the instruction changed to commute it, update livevar.
656 // Update live variables
657 LV->replaceKillInstruction(RegC, MI, NewMI);
659 mbbi->insert(mi, NewMI); // Insert the new inst
660 mbbi->erase(mi); // Nuke the old inst.
662 DistanceMap.insert(std::make_pair(NewMI, Dist));
665 // Update source register map.
666 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
668 unsigned RegA = MI->getOperand(0).getReg();
669 SrcRegMap[RegA] = FromRegC;
675 /// isProfitableToConv3Addr - Return true if it is profitable to convert the
676 /// given 2-address instruction to a 3-address one.
678 TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
679 // Look for situations like this:
680 // %reg1024<def> = MOV r1
681 // %reg1025<def> = MOV r0
682 // %reg1026<def> = ADD %reg1024, %reg1025
684 // Turn ADD into a 3-address instruction to avoid a copy.
685 unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
688 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
689 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
692 /// ConvertInstTo3Addr - Convert the specified two-address instruction into a
693 /// three address one. Return true if this transformation was successful.
695 TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
696 MachineBasicBlock::iterator &nmi,
697 MachineFunction::iterator &mbbi,
698 unsigned RegA, unsigned RegB,
700 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
702 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
703 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
706 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
707 // FIXME: Temporary workaround. If the new instruction doesn't
708 // uses RegB, convertToThreeAddress must have created more
709 // then one instruction.
710 Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
712 mbbi->erase(mi); // Nuke the old inst.
715 DistanceMap.insert(std::make_pair(NewMI, Dist));
717 nmi = llvm::next(mi);
720 // Update source and destination register maps.
721 SrcRegMap.erase(RegA);
722 DstRegMap.erase(RegB);
729 /// ScanUses - Scan forward recursively for only uses, update maps if the use
730 /// is a copy or a two-address instruction.
732 TwoAddressInstructionPass::ScanUses(unsigned DstReg, MachineBasicBlock *MBB,
733 SmallPtrSet<MachineInstr*, 8> &Processed) {
734 SmallVector<unsigned, 4> VirtRegPairs;
738 unsigned Reg = DstReg;
739 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
740 NewReg, IsDstPhys)) {
741 if (IsCopy && !Processed.insert(UseMI))
744 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
745 if (DI != DistanceMap.end())
746 // Earlier in the same MBB.Reached via a back edge.
750 VirtRegPairs.push_back(NewReg);
753 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
755 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
756 VirtRegPairs.push_back(NewReg);
760 if (!VirtRegPairs.empty()) {
761 unsigned ToReg = VirtRegPairs.back();
762 VirtRegPairs.pop_back();
763 while (!VirtRegPairs.empty()) {
764 unsigned FromReg = VirtRegPairs.back();
765 VirtRegPairs.pop_back();
766 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
768 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
771 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
773 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
777 /// ProcessCopy - If the specified instruction is not yet processed, process it
778 /// if it's a copy. For a copy instruction, we find the physical registers the
779 /// source and destination registers might be mapped to. These are kept in
780 /// point-to maps used to determine future optimizations. e.g.
783 /// v1026 = add v1024, v1025
785 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
786 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
787 /// potentially joined with r1 on the output side. It's worthwhile to commute
788 /// 'add' to eliminate a copy.
789 void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
790 MachineBasicBlock *MBB,
791 SmallPtrSet<MachineInstr*, 8> &Processed) {
792 if (Processed.count(MI))
795 bool IsSrcPhys, IsDstPhys;
796 unsigned SrcReg, DstReg;
797 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
800 if (IsDstPhys && !IsSrcPhys)
801 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
802 else if (!IsDstPhys && IsSrcPhys) {
803 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
805 assert(SrcRegMap[DstReg] == SrcReg &&
806 "Can't map to two src physical registers!");
808 ScanUses(DstReg, MBB, Processed);
811 Processed.insert(MI);
815 /// isSafeToDelete - If the specified instruction does not produce any side
816 /// effects and all of its defs are dead, then it's safe to delete.
817 static bool isSafeToDelete(MachineInstr *MI,
818 const TargetInstrInfo *TII,
819 SmallVector<unsigned, 4> &Kills) {
820 const MCInstrDesc &MCID = MI->getDesc();
821 if (MCID.mayStore() || MCID.isCall())
823 if (MCID.isTerminator() || MI->hasUnmodeledSideEffects())
826 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
827 MachineOperand &MO = MI->getOperand(i);
830 if (MO.isDef() && !MO.isDead())
832 if (MO.isUse() && MO.isKill())
833 Kills.push_back(MO.getReg());
838 /// canUpdateDeletedKills - Check if all the registers listed in Kills are
839 /// killed by instructions in MBB preceding the current instruction at
840 /// position Dist. If so, return true and record information about the
841 /// preceding kills in NewKills.
842 bool TwoAddressInstructionPass::
843 canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
844 SmallVector<NewKill, 4> &NewKills,
845 MachineBasicBlock *MBB, unsigned Dist) {
846 while (!Kills.empty()) {
847 unsigned Kill = Kills.back();
849 if (TargetRegisterInfo::isPhysicalRegister(Kill))
852 MachineInstr *LastKill = FindLastUseInMBB(Kill, MBB, Dist);
856 bool isModRef = LastKill->definesRegister(Kill);
857 NewKills.push_back(std::make_pair(std::make_pair(Kill, isModRef),
863 /// DeleteUnusedInstr - If an instruction with a tied register operand can
864 /// be safely deleted, just delete it.
866 TwoAddressInstructionPass::DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
867 MachineBasicBlock::iterator &nmi,
868 MachineFunction::iterator &mbbi,
870 // Check if the instruction has no side effects and if all its defs are dead.
871 SmallVector<unsigned, 4> Kills;
872 if (!isSafeToDelete(mi, TII, Kills))
875 // If this instruction kills some virtual registers, we need to
876 // update the kill information. If it's not possible to do so,
878 SmallVector<NewKill, 4> NewKills;
879 if (!canUpdateDeletedKills(Kills, NewKills, &*mbbi, Dist))
883 while (!NewKills.empty()) {
884 MachineInstr *NewKill = NewKills.back().second;
885 unsigned Kill = NewKills.back().first.first;
886 bool isDead = NewKills.back().first.second;
888 if (LV->removeVirtualRegisterKilled(Kill, mi)) {
890 LV->addVirtualRegisterDead(Kill, NewKill);
892 LV->addVirtualRegisterKilled(Kill, NewKill);
897 mbbi->erase(mi); // Nuke the old inst.
902 /// RescheduleMIBelowKill - If there is one more local instruction that reads
903 /// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
904 /// instruction in order to eliminate the need for the copy.
906 TwoAddressInstructionPass::RescheduleMIBelowKill(MachineBasicBlock *MBB,
907 MachineBasicBlock::iterator &mi,
908 MachineBasicBlock::iterator &nmi,
910 MachineInstr *MI = &*mi;
911 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
912 if (DI == DistanceMap.end())
913 // Must be created from unfolded load. Don't waste time trying this.
916 MachineInstr *KillMI = findLocalKill(Reg, MBB, mi, MRI, DistanceMap);
917 if (!KillMI || KillMI->isCopy() || KillMI->isCopyLike())
918 // Don't mess with copies, they may be coalesced later.
921 const MCInstrDesc &MCID = KillMI->getDesc();
922 if (MCID.hasUnmodeledSideEffects() || MCID.isCall() || MCID.isBranch() ||
924 // Don't move pass calls, etc.
928 if (isTwoAddrUse(*KillMI, Reg, DstReg))
931 bool SeenStore = true;
932 if (!MI->isSafeToMove(TII, AA, SeenStore))
935 if (TII->getInstrLatency(InstrItins, MI) > 1)
936 // FIXME: Needs more sophisticated heuristics.
939 SmallSet<unsigned, 2> Uses;
940 SmallSet<unsigned, 2> Kills;
941 SmallSet<unsigned, 2> Defs;
942 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
943 const MachineOperand &MO = MI->getOperand(i);
946 unsigned MOReg = MO.getReg();
953 if (MO.isKill() && MOReg != Reg)
958 // Move the copies connected to MI down as well.
959 MachineBasicBlock::iterator From = MI;
960 MachineBasicBlock::iterator To = llvm::next(From);
961 while (To->isCopy() && Defs.count(To->getOperand(1).getReg())) {
962 Defs.insert(To->getOperand(0).getReg());
966 // Check if the reschedule will not break depedencies.
967 unsigned NumVisited = 0;
968 MachineBasicBlock::iterator KillPos = KillMI;
970 for (MachineBasicBlock::iterator I = To; I != KillPos; ++I) {
971 MachineInstr *OtherMI = I;
972 // DBG_VALUE cannot be counted against the limit.
973 if (OtherMI->isDebugValue())
975 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
978 const MCInstrDesc &OMCID = OtherMI->getDesc();
979 if (OMCID.hasUnmodeledSideEffects() || OMCID.isCall() || OMCID.isBranch() ||
980 OMCID.isTerminator())
981 // Don't move pass calls, etc.
983 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
984 const MachineOperand &MO = OtherMI->getOperand(i);
987 unsigned MOReg = MO.getReg();
991 if (Uses.count(MOReg))
992 // Physical register use would be clobbered.
994 if (!MO.isDead() && Defs.count(MOReg))
995 // May clobber a physical register def.
996 // FIXME: This may be too conservative. It's ok if the instruction
997 // is sunken completely below the use.
1000 if (Defs.count(MOReg))
1003 ((MO.isKill() && Uses.count(MOReg)) || Kills.count(MOReg)))
1004 // Don't want to extend other live ranges and update kills.
1010 // Move debug info as well.
1011 while (From != MBB->begin() && llvm::prior(From)->isDebugValue())
1014 // Copies following MI may have been moved as well.
1016 MBB->splice(KillPos, MBB, From, To);
1017 DistanceMap.erase(DI);
1020 // Update live variables
1021 LV->removeVirtualRegisterKilled(Reg, KillMI);
1022 LV->addVirtualRegisterKilled(Reg, MI);
1024 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
1025 MachineOperand &MO = KillMI->getOperand(i);
1026 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
1028 MO.setIsKill(false);
1030 MI->addRegisterKilled(Reg, 0);
1036 /// isDefTooClose - Return true if the re-scheduling will put the given
1037 /// instruction too close to the defs of its register dependencies.
1038 bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
1040 MachineBasicBlock *MBB) {
1041 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(Reg),
1042 DE = MRI->def_end(); DI != DE; ++DI) {
1043 MachineInstr *DefMI = &*DI;
1044 if (DefMI->getParent() != MBB || DefMI->isCopy() || DefMI->isCopyLike())
1047 return true; // MI is defining something KillMI uses
1048 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(DefMI);
1049 if (DDI == DistanceMap.end())
1050 return true; // Below MI
1051 unsigned DefDist = DDI->second;
1052 assert(Dist > DefDist && "Visited def already?");
1053 if (TII->getInstrLatency(InstrItins, DefMI) > (int)(Dist - DefDist))
1059 /// RescheduleKillAboveMI - If there is one more local instruction that reads
1060 /// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
1061 /// current two-address instruction in order to eliminate the need for the
1064 TwoAddressInstructionPass::RescheduleKillAboveMI(MachineBasicBlock *MBB,
1065 MachineBasicBlock::iterator &mi,
1066 MachineBasicBlock::iterator &nmi,
1068 MachineInstr *MI = &*mi;
1069 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
1070 if (DI == DistanceMap.end())
1071 // Must be created from unfolded load. Don't waste time trying this.
1074 MachineInstr *KillMI = findLocalKill(Reg, MBB, mi, MRI, DistanceMap);
1075 if (!KillMI || KillMI->isCopy() || KillMI->isCopyLike())
1076 // Don't mess with copies, they may be coalesced later.
1080 if (isTwoAddrUse(*KillMI, Reg, DstReg))
1083 bool SeenStore = true;
1084 if (!KillMI->isSafeToMove(TII, AA, SeenStore))
1087 SmallSet<unsigned, 2> Uses;
1088 SmallSet<unsigned, 2> Kills;
1089 SmallSet<unsigned, 2> Defs;
1090 SmallSet<unsigned, 2> LiveDefs;
1091 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
1092 const MachineOperand &MO = KillMI->getOperand(i);
1095 unsigned MOReg = MO.getReg();
1099 if (isDefTooClose(MOReg, DI->second, MI, MBB))
1102 if (MO.isKill() && MOReg != Reg)
1103 Kills.insert(MOReg);
1104 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1107 LiveDefs.insert(MOReg);
1111 // Check if the reschedule will not break depedencies.
1112 unsigned NumVisited = 0;
1113 MachineBasicBlock::iterator KillPos = KillMI;
1114 for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
1115 MachineInstr *OtherMI = I;
1116 // DBG_VALUE cannot be counted against the limit.
1117 if (OtherMI->isDebugValue())
1119 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
1122 const MCInstrDesc &MCID = OtherMI->getDesc();
1123 if (MCID.hasUnmodeledSideEffects() || MCID.isCall() || MCID.isBranch() ||
1124 MCID.isTerminator())
1125 // Don't move pass calls, etc.
1127 SmallVector<unsigned, 2> OtherDefs;
1128 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
1129 const MachineOperand &MO = OtherMI->getOperand(i);
1132 unsigned MOReg = MO.getReg();
1136 if (Defs.count(MOReg))
1137 // Moving KillMI can clobber the physical register if the def has
1140 if (Kills.count(MOReg))
1141 // Don't want to extend other live ranges and update kills.
1144 OtherDefs.push_back(MOReg);
1148 for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
1149 unsigned MOReg = OtherDefs[i];
1150 if (Uses.count(MOReg))
1152 if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1153 LiveDefs.count(MOReg))
1155 // Physical register def is seen.
1160 // Move the old kill above MI, don't forget to move debug info as well.
1161 MachineBasicBlock::iterator InsertPos = mi;
1162 while (InsertPos != MBB->begin() && llvm::prior(InsertPos)->isDebugValue())
1164 MachineBasicBlock::iterator From = KillMI;
1165 MachineBasicBlock::iterator To = llvm::next(From);
1166 while (llvm::prior(From)->isDebugValue())
1168 MBB->splice(InsertPos, MBB, From, To);
1170 nmi = llvm::prior(InsertPos); // Backtrack so we process the moved instr.
1171 DistanceMap.erase(DI);
1174 // Update live variables
1175 LV->removeVirtualRegisterKilled(Reg, KillMI);
1176 LV->addVirtualRegisterKilled(Reg, MI);
1178 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
1179 MachineOperand &MO = KillMI->getOperand(i);
1180 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
1182 MO.setIsKill(false);
1184 MI->addRegisterKilled(Reg, 0);
1189 /// TryInstructionTransform - For the case where an instruction has a single
1190 /// pair of tied register operands, attempt some transformations that may
1191 /// either eliminate the tied operands or improve the opportunities for
1192 /// coalescing away the register copy. Returns true if the tied operands
1193 /// are eliminated altogether.
1194 bool TwoAddressInstructionPass::
1195 TryInstructionTransform(MachineBasicBlock::iterator &mi,
1196 MachineBasicBlock::iterator &nmi,
1197 MachineFunction::iterator &mbbi,
1198 unsigned SrcIdx, unsigned DstIdx, unsigned Dist,
1199 SmallPtrSet<MachineInstr*, 8> &Processed) {
1200 if (OptLevel == CodeGenOpt::None)
1203 MachineInstr &MI = *mi;
1204 const MCInstrDesc &MCID = MI.getDesc();
1205 unsigned regA = MI.getOperand(DstIdx).getReg();
1206 unsigned regB = MI.getOperand(SrcIdx).getReg();
1208 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1209 "cannot make instruction into two-address form");
1211 // If regA is dead and the instruction can be deleted, just delete
1212 // it so it doesn't clobber regB.
1213 bool regBKilled = isKilled(MI, regB, MRI, TII);
1214 if (!regBKilled && MI.getOperand(DstIdx).isDead() &&
1215 DeleteUnusedInstr(mi, nmi, mbbi, Dist)) {
1217 return true; // Done with this instruction.
1220 // Check if it is profitable to commute the operands.
1221 unsigned SrcOp1, SrcOp2;
1223 unsigned regCIdx = ~0U;
1224 bool TryCommute = false;
1225 bool AggressiveCommute = false;
1226 if (MCID.isCommutable() && MI.getNumOperands() >= 3 &&
1227 TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
1228 if (SrcIdx == SrcOp1)
1230 else if (SrcIdx == SrcOp2)
1233 if (regCIdx != ~0U) {
1234 regC = MI.getOperand(regCIdx).getReg();
1235 if (!regBKilled && isKilled(MI, regC, MRI, TII))
1236 // If C dies but B does not, swap the B and C operands.
1237 // This makes the live ranges of A and C joinable.
1239 else if (isProfitableToCommute(regB, regC, &MI, mbbi, Dist)) {
1241 AggressiveCommute = true;
1246 // If it's profitable to commute, try to do so.
1247 if (TryCommute && CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
1249 if (AggressiveCommute)
1254 // If there is one more use of regB later in the same MBB, consider
1255 // re-schedule this MI below it.
1256 if (RescheduleMIBelowKill(mbbi, mi, nmi, regB)) {
1261 if (TargetRegisterInfo::isVirtualRegister(regA))
1262 ScanUses(regA, &*mbbi, Processed);
1264 if (MCID.isConvertibleTo3Addr()) {
1265 // This instruction is potentially convertible to a true
1266 // three-address instruction. Check if it is profitable.
1267 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
1268 // Try to convert it.
1269 if (ConvertInstTo3Addr(mi, nmi, mbbi, regA, regB, Dist)) {
1270 ++NumConvertedTo3Addr;
1271 return true; // Done with this instruction.
1276 // If there is one more use of regB later in the same MBB, consider
1277 // re-schedule it before this MI if it's legal.
1278 if (RescheduleKillAboveMI(mbbi, mi, nmi, regB)) {
1283 // If this is an instruction with a load folded into it, try unfolding
1284 // the load, e.g. avoid this:
1286 // addq (%rax), %rcx
1287 // in favor of this:
1288 // movq (%rax), %rcx
1290 // because it's preferable to schedule a load than a register copy.
1291 if (MCID.mayLoad() && !regBKilled) {
1292 // Determine if a load can be unfolded.
1293 unsigned LoadRegIndex;
1295 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1296 /*UnfoldLoad=*/true,
1297 /*UnfoldStore=*/false,
1300 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1301 if (UnfoldMCID.getNumDefs() == 1) {
1302 MachineFunction &MF = *mbbi->getParent();
1305 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
1306 const TargetRegisterClass *RC =
1307 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI);
1308 unsigned Reg = MRI->createVirtualRegister(RC);
1309 SmallVector<MachineInstr *, 2> NewMIs;
1310 if (!TII->unfoldMemoryOperand(MF, &MI, Reg,
1311 /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
1313 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1316 assert(NewMIs.size() == 2 &&
1317 "Unfolded a load into multiple instructions!");
1318 // The load was previously folded, so this is the only use.
1319 NewMIs[1]->addRegisterKilled(Reg, TRI);
1321 // Tentatively insert the instructions into the block so that they
1322 // look "normal" to the transformation logic.
1323 mbbi->insert(mi, NewMIs[0]);
1324 mbbi->insert(mi, NewMIs[1]);
1326 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1327 << "2addr: NEW INST: " << *NewMIs[1]);
1329 // Transform the instruction, now that it no longer has a load.
1330 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1331 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1332 MachineBasicBlock::iterator NewMI = NewMIs[1];
1333 bool TransformSuccess =
1334 TryInstructionTransform(NewMI, mi, mbbi,
1335 NewSrcIdx, NewDstIdx, Dist, Processed);
1336 if (TransformSuccess ||
1337 NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1338 // Success, or at least we made an improvement. Keep the unfolded
1339 // instructions and discard the original.
1341 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1342 MachineOperand &MO = MI.getOperand(i);
1344 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1347 if (NewMIs[0]->killsRegister(MO.getReg()))
1348 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
1350 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1351 "Kill missing after load unfold!");
1352 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
1355 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
1356 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1357 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
1359 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1360 "Dead flag missing after load unfold!");
1361 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
1366 LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
1368 MI.eraseFromParent();
1370 if (TransformSuccess)
1373 // Transforming didn't eliminate the tie and didn't lead to an
1374 // improvement. Clean up the unfolded instructions and keep the
1376 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1377 NewMIs[0]->eraseFromParent();
1378 NewMIs[1]->eraseFromParent();
1387 /// runOnMachineFunction - Reduce two-address instructions to two operands.
1389 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
1390 DEBUG(dbgs() << "Machine Function\n");
1391 const TargetMachine &TM = MF.getTarget();
1392 MRI = &MF.getRegInfo();
1393 TII = TM.getInstrInfo();
1394 TRI = TM.getRegisterInfo();
1395 InstrItins = TM.getInstrItineraryData();
1396 LV = getAnalysisIfAvailable<LiveVariables>();
1397 AA = &getAnalysis<AliasAnalysis>();
1398 OptLevel = TM.getOptLevel();
1400 bool MadeChange = false;
1402 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
1403 DEBUG(dbgs() << "********** Function: "
1404 << MF.getFunction()->getName() << '\n');
1406 // This pass takes the function out of SSA form.
1409 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
1410 BitVector ReMatRegs(MRI->getNumVirtRegs());
1412 typedef DenseMap<unsigned, SmallVector<std::pair<unsigned, unsigned>, 4> >
1414 TiedOperandMap TiedOperands(4);
1416 SmallPtrSet<MachineInstr*, 8> Processed;
1417 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
1418 mbbi != mbbe; ++mbbi) {
1420 DistanceMap.clear();
1424 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
1426 MachineBasicBlock::iterator nmi = llvm::next(mi);
1427 if (mi->isDebugValue()) {
1432 // Remember REG_SEQUENCE instructions, we'll deal with them later.
1433 if (mi->isRegSequence())
1434 RegSequences.push_back(&*mi);
1436 const MCInstrDesc &MCID = mi->getDesc();
1437 bool FirstTied = true;
1439 DistanceMap.insert(std::make_pair(mi, ++Dist));
1441 ProcessCopy(&*mi, &*mbbi, Processed);
1443 // First scan through all the tied register uses in this instruction
1444 // and record a list of pairs of tied operands for each register.
1445 unsigned NumOps = mi->isInlineAsm()
1446 ? mi->getNumOperands() : MCID.getNumOperands();
1447 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1448 unsigned DstIdx = 0;
1449 if (!mi->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1454 ++NumTwoAddressInstrs;
1455 DEBUG(dbgs() << '\t' << *mi);
1458 assert(mi->getOperand(SrcIdx).isReg() &&
1459 mi->getOperand(SrcIdx).getReg() &&
1460 mi->getOperand(SrcIdx).isUse() &&
1461 "two address instruction invalid");
1463 unsigned regB = mi->getOperand(SrcIdx).getReg();
1464 TiedOperands[regB].push_back(std::make_pair(SrcIdx, DstIdx));
1467 // Now iterate over the information collected above.
1468 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1469 OE = TiedOperands.end(); OI != OE; ++OI) {
1470 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs = OI->second;
1472 // If the instruction has a single pair of tied operands, try some
1473 // transformations that may either eliminate the tied operands or
1474 // improve the opportunities for coalescing away the register copy.
1475 if (TiedOperands.size() == 1 && TiedPairs.size() == 1) {
1476 unsigned SrcIdx = TiedPairs[0].first;
1477 unsigned DstIdx = TiedPairs[0].second;
1479 // If the registers are already equal, nothing needs to be done.
1480 if (mi->getOperand(SrcIdx).getReg() ==
1481 mi->getOperand(DstIdx).getReg())
1482 break; // Done with this instruction.
1484 if (TryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist,
1486 break; // The tied operands have been eliminated.
1489 bool IsEarlyClobber = false;
1490 bool RemovedKillFlag = false;
1491 bool AllUsesCopied = true;
1492 unsigned LastCopiedReg = 0;
1493 unsigned regB = OI->first;
1494 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1495 unsigned SrcIdx = TiedPairs[tpi].first;
1496 unsigned DstIdx = TiedPairs[tpi].second;
1498 const MachineOperand &DstMO = mi->getOperand(DstIdx);
1499 unsigned regA = DstMO.getReg();
1500 IsEarlyClobber |= DstMO.isEarlyClobber();
1502 // Grab regB from the instruction because it may have changed if the
1503 // instruction was commuted.
1504 regB = mi->getOperand(SrcIdx).getReg();
1507 // The register is tied to multiple destinations (or else we would
1508 // not have continued this far), but this use of the register
1509 // already matches the tied destination. Leave it.
1510 AllUsesCopied = false;
1513 LastCopiedReg = regA;
1515 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1516 "cannot make instruction into two-address form");
1519 // First, verify that we don't have a use of "a" in the instruction
1520 // (a = b + a for example) because our transformation will not
1521 // work. This should never occur because we are in SSA form.
1522 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
1523 assert(i == DstIdx ||
1524 !mi->getOperand(i).isReg() ||
1525 mi->getOperand(i).getReg() != regA);
1528 // Emit a copy or rematerialize the definition.
1529 const TargetRegisterClass *rc = MRI->getRegClass(regB);
1530 MachineInstr *DefMI = MRI->getVRegDef(regB);
1531 // If it's safe and profitable, remat the definition instead of
1534 DefMI->getDesc().isAsCheapAsAMove() &&
1535 DefMI->isSafeToReMat(TII, AA, regB) &&
1536 isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){
1537 DEBUG(dbgs() << "2addr: REMATTING : " << *DefMI << "\n");
1538 unsigned regASubIdx = mi->getOperand(DstIdx).getSubReg();
1539 TII->reMaterialize(*mbbi, mi, regA, regASubIdx, DefMI, *TRI);
1540 ReMatRegs.set(TargetRegisterInfo::virtReg2Index(regB));
1543 BuildMI(*mbbi, mi, mi->getDebugLoc(), TII->get(TargetOpcode::COPY),
1547 MachineBasicBlock::iterator prevMI = prior(mi);
1548 // Update DistanceMap.
1549 DistanceMap.insert(std::make_pair(prevMI, Dist));
1550 DistanceMap[mi] = ++Dist;
1552 DEBUG(dbgs() << "\t\tprepend:\t" << *prevMI);
1554 MachineOperand &MO = mi->getOperand(SrcIdx);
1555 assert(MO.isReg() && MO.getReg() == regB && MO.isUse() &&
1556 "inconsistent operand info for 2-reg pass");
1558 MO.setIsKill(false);
1559 RemovedKillFlag = true;
1564 if (AllUsesCopied) {
1565 if (!IsEarlyClobber) {
1566 // Replace other (un-tied) uses of regB with LastCopiedReg.
1567 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1568 MachineOperand &MO = mi->getOperand(i);
1569 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1571 MO.setIsKill(false);
1572 RemovedKillFlag = true;
1574 MO.setReg(LastCopiedReg);
1579 // Update live variables for regB.
1580 if (RemovedKillFlag && LV && LV->getVarInfo(regB).removeKill(mi))
1581 LV->addVirtualRegisterKilled(regB, prior(mi));
1583 } else if (RemovedKillFlag) {
1584 // Some tied uses of regB matched their destination registers, so
1585 // regB is still used in this instruction, but a kill flag was
1586 // removed from a different tied use of regB, so now we need to add
1587 // a kill flag to one of the remaining uses of regB.
1588 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1589 MachineOperand &MO = mi->getOperand(i);
1590 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1597 // Schedule the source copy / remat inserted to form two-address
1598 // instruction. FIXME: Does it matter the distance map may not be
1599 // accurate after it's scheduled?
1600 TII->scheduleTwoAddrSource(prior(mi), mi, *TRI);
1604 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1607 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1608 if (mi->isInsertSubreg()) {
1609 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1610 // To %reg:subidx = COPY %subreg
1611 unsigned SubIdx = mi->getOperand(3).getImm();
1612 mi->RemoveOperand(3);
1613 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1614 mi->getOperand(0).setSubReg(SubIdx);
1615 mi->RemoveOperand(1);
1616 mi->setDesc(TII->get(TargetOpcode::COPY));
1617 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
1620 // Clear TiedOperands here instead of at the top of the loop
1621 // since most instructions do not have tied operands.
1622 TiedOperands.clear();
1627 // Some remat'ed instructions are dead.
1628 for (int i = ReMatRegs.find_first(); i != -1; i = ReMatRegs.find_next(i)) {
1629 unsigned VReg = TargetRegisterInfo::index2VirtReg(i);
1630 if (MRI->use_nodbg_empty(VReg)) {
1631 MachineInstr *DefMI = MRI->getVRegDef(VReg);
1632 DefMI->eraseFromParent();
1636 // Eliminate REG_SEQUENCE instructions. Their whole purpose was to preseve
1637 // SSA form. It's now safe to de-SSA.
1638 MadeChange |= EliminateRegSequences();
1643 static void UpdateRegSequenceSrcs(unsigned SrcReg,
1644 unsigned DstReg, unsigned SubIdx,
1645 MachineRegisterInfo *MRI,
1646 const TargetRegisterInfo &TRI) {
1647 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg),
1648 RE = MRI->reg_end(); RI != RE; ) {
1649 MachineOperand &MO = RI.getOperand();
1651 MO.substVirtReg(DstReg, SubIdx, TRI);
1655 /// CoalesceExtSubRegs - If a number of sources of the REG_SEQUENCE are
1656 /// EXTRACT_SUBREG from the same register and to the same virtual register
1657 /// with different sub-register indices, attempt to combine the
1658 /// EXTRACT_SUBREGs and pre-coalesce them. e.g.
1659 /// %reg1026<def> = VLDMQ %reg1025<kill>, 260, pred:14, pred:%reg0
1660 /// %reg1029:6<def> = EXTRACT_SUBREG %reg1026, 6
1661 /// %reg1029:5<def> = EXTRACT_SUBREG %reg1026<kill>, 5
1662 /// Since D subregs 5, 6 can combine to a Q register, we can coalesce
1663 /// reg1026 to reg1029.
1665 TwoAddressInstructionPass::CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs,
1667 SmallSet<unsigned, 4> Seen;
1668 for (unsigned i = 0, e = Srcs.size(); i != e; ++i) {
1669 unsigned SrcReg = Srcs[i];
1670 if (!Seen.insert(SrcReg))
1673 // Check that the instructions are all in the same basic block.
1674 MachineInstr *SrcDefMI = MRI->getVRegDef(SrcReg);
1675 MachineInstr *DstDefMI = MRI->getVRegDef(DstReg);
1676 if (SrcDefMI->getParent() != DstDefMI->getParent())
1679 // If there are no other uses than copies which feed into
1680 // the reg_sequence, then we might be able to coalesce them.
1681 bool CanCoalesce = true;
1682 SmallVector<unsigned, 4> SrcSubIndices, DstSubIndices;
1683 for (MachineRegisterInfo::use_nodbg_iterator
1684 UI = MRI->use_nodbg_begin(SrcReg),
1685 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
1686 MachineInstr *UseMI = &*UI;
1687 if (!UseMI->isCopy() || UseMI->getOperand(0).getReg() != DstReg) {
1688 CanCoalesce = false;
1691 SrcSubIndices.push_back(UseMI->getOperand(1).getSubReg());
1692 DstSubIndices.push_back(UseMI->getOperand(0).getSubReg());
1695 if (!CanCoalesce || SrcSubIndices.size() < 2)
1698 // Check that the source subregisters can be combined.
1699 std::sort(SrcSubIndices.begin(), SrcSubIndices.end());
1700 unsigned NewSrcSubIdx = 0;
1701 if (!TRI->canCombineSubRegIndices(MRI->getRegClass(SrcReg), SrcSubIndices,
1705 // Check that the destination subregisters can also be combined.
1706 std::sort(DstSubIndices.begin(), DstSubIndices.end());
1707 unsigned NewDstSubIdx = 0;
1708 if (!TRI->canCombineSubRegIndices(MRI->getRegClass(DstReg), DstSubIndices,
1712 // If neither source nor destination can be combined to the full register,
1713 // just give up. This could be improved if it ever matters.
1714 if (NewSrcSubIdx != 0 && NewDstSubIdx != 0)
1717 // Now that we know that all the uses are extract_subregs and that those
1718 // subregs can somehow be combined, scan all the extract_subregs again to
1719 // make sure the subregs are in the right order and can be composed.
1720 MachineInstr *SomeMI = 0;
1722 for (MachineRegisterInfo::use_nodbg_iterator
1723 UI = MRI->use_nodbg_begin(SrcReg),
1724 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
1725 MachineInstr *UseMI = &*UI;
1726 assert(UseMI->isCopy());
1727 unsigned DstSubIdx = UseMI->getOperand(0).getSubReg();
1728 unsigned SrcSubIdx = UseMI->getOperand(1).getSubReg();
1729 assert(DstSubIdx != 0 && "missing subreg from RegSequence elimination");
1730 if ((NewDstSubIdx == 0 &&
1731 TRI->composeSubRegIndices(NewSrcSubIdx, DstSubIdx) != SrcSubIdx) ||
1732 (NewSrcSubIdx == 0 &&
1733 TRI->composeSubRegIndices(NewDstSubIdx, SrcSubIdx) != DstSubIdx)) {
1734 CanCoalesce = false;
1737 // Keep track of one of the uses.
1743 // Insert a copy to replace the original.
1744 MachineInstr *CopyMI = BuildMI(*SomeMI->getParent(), SomeMI,
1745 SomeMI->getDebugLoc(),
1746 TII->get(TargetOpcode::COPY))
1747 .addReg(DstReg, RegState::Define, NewDstSubIdx)
1748 .addReg(SrcReg, 0, NewSrcSubIdx);
1750 // Remove all the old extract instructions.
1751 for (MachineRegisterInfo::use_nodbg_iterator
1752 UI = MRI->use_nodbg_begin(SrcReg),
1753 UE = MRI->use_nodbg_end(); UI != UE; ) {
1754 MachineInstr *UseMI = &*UI;
1756 if (UseMI == CopyMI)
1758 assert(UseMI->isCopy());
1759 // Move any kills to the new copy or extract instruction.
1760 if (UseMI->getOperand(1).isKill()) {
1761 CopyMI->getOperand(1).setIsKill();
1763 // Update live variables
1764 LV->replaceKillInstruction(SrcReg, UseMI, &*CopyMI);
1766 UseMI->eraseFromParent();
1771 static bool HasOtherRegSequenceUses(unsigned Reg, MachineInstr *RegSeq,
1772 MachineRegisterInfo *MRI) {
1773 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
1774 UE = MRI->use_end(); UI != UE; ++UI) {
1775 MachineInstr *UseMI = &*UI;
1776 if (UseMI != RegSeq && UseMI->isRegSequence())
1782 /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
1783 /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
1784 /// sub-register references of the register defined by REG_SEQUENCE. e.g.
1786 /// %reg1029<def>, %reg1030<def> = VLD1q16 %reg1024<kill>, ...
1787 /// %reg1031<def> = REG_SEQUENCE %reg1029<kill>, 5, %reg1030<kill>, 6
1789 /// %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
1790 bool TwoAddressInstructionPass::EliminateRegSequences() {
1791 if (RegSequences.empty())
1794 for (unsigned i = 0, e = RegSequences.size(); i != e; ++i) {
1795 MachineInstr *MI = RegSequences[i];
1796 unsigned DstReg = MI->getOperand(0).getReg();
1797 if (MI->getOperand(0).getSubReg() ||
1798 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1799 !(MI->getNumOperands() & 1)) {
1800 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1801 llvm_unreachable(0);
1804 bool IsImpDef = true;
1805 SmallVector<unsigned, 4> RealSrcs;
1806 SmallSet<unsigned, 4> Seen;
1807 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1808 unsigned SrcReg = MI->getOperand(i).getReg();
1809 unsigned SubIdx = MI->getOperand(i+1).getImm();
1810 if (MI->getOperand(i).getSubReg() ||
1811 TargetRegisterInfo::isPhysicalRegister(SrcReg)) {
1812 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1813 llvm_unreachable(0);
1816 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
1817 if (DefMI->isImplicitDef()) {
1818 DefMI->eraseFromParent();
1823 // Remember COPY sources. These might be candidate for coalescing.
1824 if (DefMI->isCopy() && DefMI->getOperand(1).getSubReg())
1825 RealSrcs.push_back(DefMI->getOperand(1).getReg());
1827 bool isKill = MI->getOperand(i).isKill();
1828 if (!Seen.insert(SrcReg) || MI->getParent() != DefMI->getParent() ||
1829 !isKill || HasOtherRegSequenceUses(SrcReg, MI, MRI) ||
1830 !TRI->getMatchingSuperRegClass(MRI->getRegClass(DstReg),
1831 MRI->getRegClass(SrcReg), SubIdx)) {
1832 // REG_SEQUENCE cannot have duplicated operands, add a copy.
1833 // Also add an copy if the source is live-in the block. We don't want
1834 // to end up with a partial-redef of a livein, e.g.
1836 // reg1051:10<def> =
1842 // LiveIntervalAnalysis won't like it.
1844 // If the REG_SEQUENCE doesn't kill its source, keeping live variables
1845 // correctly up to date becomes very difficult. Insert a copy.
1847 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1848 // might insert a COPY that uses SrcReg after is was killed.
1850 for (unsigned j = i + 2; j < e; j += 2)
1851 if (MI->getOperand(j).getReg() == SrcReg) {
1852 MI->getOperand(j).setIsKill();
1857 MachineBasicBlock::iterator InsertLoc = MI;
1858 MachineInstr *CopyMI = BuildMI(*MI->getParent(), InsertLoc,
1859 MI->getDebugLoc(), TII->get(TargetOpcode::COPY))
1860 .addReg(DstReg, RegState::Define, SubIdx)
1861 .addReg(SrcReg, getKillRegState(isKill));
1862 MI->getOperand(i).setReg(0);
1864 LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1865 DEBUG(dbgs() << "Inserted: " << *CopyMI);
1869 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1870 unsigned SrcReg = MI->getOperand(i).getReg();
1871 if (!SrcReg) continue;
1872 unsigned SubIdx = MI->getOperand(i+1).getImm();
1873 UpdateRegSequenceSrcs(SrcReg, DstReg, SubIdx, MRI, *TRI);
1877 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1878 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1879 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
1880 MI->RemoveOperand(j);
1882 DEBUG(dbgs() << "Eliminated: " << *MI);
1883 MI->eraseFromParent();
1886 // Try coalescing some EXTRACT_SUBREG instructions. This can create
1887 // INSERT_SUBREG instructions that must have <undef> flags added by
1888 // LiveIntervalAnalysis, so only run it when LiveVariables is available.
1890 CoalesceExtSubRegs(RealSrcs, DstReg);
1893 RegSequences.clear();