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(NumReSchedUps, "Number of instructions re-scheduled up");
59 STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down");
62 class TwoAddressInstructionPass : public MachineFunctionPass {
63 const TargetInstrInfo *TII;
64 const TargetRegisterInfo *TRI;
65 const InstrItineraryData *InstrItins;
66 MachineRegisterInfo *MRI;
69 CodeGenOpt::Level OptLevel;
71 // DistanceMap - Keep track the distance of a MI from the start of the
72 // current basic block.
73 DenseMap<MachineInstr*, unsigned> DistanceMap;
75 // SrcRegMap - A map from virtual registers to physical registers which
76 // are likely targets to be coalesced to due to copies from physical
77 // registers to virtual registers. e.g. v1024 = move r0.
78 DenseMap<unsigned, unsigned> SrcRegMap;
80 // DstRegMap - A map from virtual registers to physical registers which
81 // are likely targets to be coalesced to due to copies to physical
82 // registers from virtual registers. e.g. r1 = move v1024.
83 DenseMap<unsigned, unsigned> DstRegMap;
85 /// RegSequences - Keep track the list of REG_SEQUENCE instructions seen
86 /// during the initial walk of the machine function.
87 SmallVector<MachineInstr*, 16> RegSequences;
89 bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
91 MachineBasicBlock::iterator OldPos);
93 bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
96 MachineInstr *FindLastUseInMBB(unsigned Reg, MachineBasicBlock *MBB,
99 bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
100 MachineInstr *MI, MachineBasicBlock *MBB,
103 bool CommuteInstruction(MachineBasicBlock::iterator &mi,
104 MachineFunction::iterator &mbbi,
105 unsigned RegB, unsigned RegC, unsigned Dist);
107 bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
109 bool ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
110 MachineBasicBlock::iterator &nmi,
111 MachineFunction::iterator &mbbi,
112 unsigned RegA, unsigned RegB, unsigned Dist);
114 bool isDefTooClose(unsigned Reg, unsigned Dist,
115 MachineInstr *MI, MachineBasicBlock *MBB);
117 bool RescheduleMIBelowKill(MachineBasicBlock *MBB,
118 MachineBasicBlock::iterator &mi,
119 MachineBasicBlock::iterator &nmi,
121 bool RescheduleKillAboveMI(MachineBasicBlock *MBB,
122 MachineBasicBlock::iterator &mi,
123 MachineBasicBlock::iterator &nmi,
126 bool TryInstructionTransform(MachineBasicBlock::iterator &mi,
127 MachineBasicBlock::iterator &nmi,
128 MachineFunction::iterator &mbbi,
129 unsigned SrcIdx, unsigned DstIdx,
131 SmallPtrSet<MachineInstr*, 8> &Processed);
133 void ScanUses(unsigned DstReg, MachineBasicBlock *MBB,
134 SmallPtrSet<MachineInstr*, 8> &Processed);
136 void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
137 SmallPtrSet<MachineInstr*, 8> &Processed);
139 void CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs, unsigned DstReg);
141 /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
142 /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
143 /// sub-register references of the register defined by REG_SEQUENCE.
144 bool EliminateRegSequences();
147 static char ID; // Pass identification, replacement for typeid
148 TwoAddressInstructionPass() : MachineFunctionPass(ID) {
149 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
152 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
153 AU.setPreservesCFG();
154 AU.addRequired<AliasAnalysis>();
155 AU.addPreserved<LiveVariables>();
156 AU.addPreservedID(MachineLoopInfoID);
157 AU.addPreservedID(MachineDominatorsID);
158 MachineFunctionPass::getAnalysisUsage(AU);
161 /// runOnMachineFunction - Pass entry point.
162 bool runOnMachineFunction(MachineFunction&);
166 char TwoAddressInstructionPass::ID = 0;
167 INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
168 "Two-Address instruction pass", false, false)
169 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
170 INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
171 "Two-Address instruction pass", false, false)
173 char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
175 /// Sink3AddrInstruction - A two-address instruction has been converted to a
176 /// three-address instruction to avoid clobbering a register. Try to sink it
177 /// past the instruction that would kill the above mentioned register to reduce
178 /// register pressure.
179 bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
180 MachineInstr *MI, unsigned SavedReg,
181 MachineBasicBlock::iterator OldPos) {
182 // FIXME: Shouldn't we be trying to do this before we three-addressify the
183 // instruction? After this transformation is done, we no longer need
184 // the instruction to be in three-address form.
186 // Check if it's safe to move this instruction.
187 bool SeenStore = true; // Be conservative.
188 if (!MI->isSafeToMove(TII, AA, SeenStore))
192 SmallSet<unsigned, 4> UseRegs;
194 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
195 const MachineOperand &MO = MI->getOperand(i);
198 unsigned MOReg = MO.getReg();
201 if (MO.isUse() && MOReg != SavedReg)
202 UseRegs.insert(MO.getReg());
206 // Don't try to move it if it implicitly defines a register.
209 // For now, don't move any instructions that define multiple registers.
211 DefReg = MO.getReg();
214 // Find the instruction that kills SavedReg.
215 MachineInstr *KillMI = NULL;
216 for (MachineRegisterInfo::use_nodbg_iterator
217 UI = MRI->use_nodbg_begin(SavedReg),
218 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
219 MachineOperand &UseMO = UI.getOperand();
222 KillMI = UseMO.getParent();
226 // If we find the instruction that kills SavedReg, and it is in an
227 // appropriate location, we can try to sink the current instruction
229 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
230 KillMI->isTerminator())
233 // If any of the definitions are used by another instruction between the
234 // position and the kill use, then it's not safe to sink it.
236 // FIXME: This can be sped up if there is an easy way to query whether an
237 // instruction is before or after another instruction. Then we can use
238 // MachineRegisterInfo def / use instead.
239 MachineOperand *KillMO = NULL;
240 MachineBasicBlock::iterator KillPos = KillMI;
243 unsigned NumVisited = 0;
244 for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
245 MachineInstr *OtherMI = I;
246 // DBG_VALUE cannot be counted against the limit.
247 if (OtherMI->isDebugValue())
249 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
252 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
253 MachineOperand &MO = OtherMI->getOperand(i);
256 unsigned MOReg = MO.getReg();
263 if (OtherMI == KillMI && MOReg == SavedReg)
264 // Save the operand that kills the register. We want to unset the kill
265 // marker if we can sink MI past it.
267 else if (UseRegs.count(MOReg))
268 // One of the uses is killed before the destination.
274 // Update kill and LV information.
275 KillMO->setIsKill(false);
276 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
277 KillMO->setIsKill(true);
280 LV->replaceKillInstruction(SavedReg, KillMI, MI);
282 // Move instruction to its destination.
284 MBB->insert(KillPos, MI);
290 /// NoUseAfterLastDef - Return true if there are no intervening uses between the
291 /// last instruction in the MBB that defines the specified register and the
292 /// two-address instruction which is being processed. It also returns the last
293 /// def location by reference
294 bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
295 MachineBasicBlock *MBB, unsigned Dist,
298 unsigned LastUse = Dist;
299 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
300 E = MRI->reg_end(); I != E; ++I) {
301 MachineOperand &MO = I.getOperand();
302 MachineInstr *MI = MO.getParent();
303 if (MI->getParent() != MBB || MI->isDebugValue())
305 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
306 if (DI == DistanceMap.end())
308 if (MO.isUse() && DI->second < LastUse)
309 LastUse = DI->second;
310 if (MO.isDef() && DI->second > LastDef)
311 LastDef = DI->second;
314 return !(LastUse > LastDef && LastUse < Dist);
317 MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg,
318 MachineBasicBlock *MBB,
320 unsigned LastUseDist = 0;
321 MachineInstr *LastUse = 0;
322 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
323 E = MRI->reg_end(); I != E; ++I) {
324 MachineOperand &MO = I.getOperand();
325 MachineInstr *MI = MO.getParent();
326 if (MI->getParent() != MBB || MI->isDebugValue())
328 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
329 if (DI == DistanceMap.end())
331 if (DI->second >= Dist)
334 if (MO.isUse() && DI->second > LastUseDist) {
336 LastUseDist = DI->second;
342 /// isCopyToReg - Return true if the specified MI is a copy instruction or
343 /// a extract_subreg instruction. It also returns the source and destination
344 /// registers and whether they are physical registers by reference.
345 static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
346 unsigned &SrcReg, unsigned &DstReg,
347 bool &IsSrcPhys, bool &IsDstPhys) {
351 DstReg = MI.getOperand(0).getReg();
352 SrcReg = MI.getOperand(1).getReg();
353 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
354 DstReg = MI.getOperand(0).getReg();
355 SrcReg = MI.getOperand(2).getReg();
359 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
360 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
364 /// isKilled - Test if the given register value, which is used by the given
365 /// instruction, is killed by the given instruction. This looks through
366 /// coalescable copies to see if the original value is potentially not killed.
368 /// For example, in this code:
370 /// %reg1034 = copy %reg1024
371 /// %reg1035 = copy %reg1025<kill>
372 /// %reg1036 = add %reg1034<kill>, %reg1035<kill>
374 /// %reg1034 is not considered to be killed, since it is copied from a
375 /// register which is not killed. Treating it as not killed lets the
376 /// normal heuristics commute the (two-address) add, which lets
377 /// coalescing eliminate the extra copy.
379 static bool isKilled(MachineInstr &MI, unsigned Reg,
380 const MachineRegisterInfo *MRI,
381 const TargetInstrInfo *TII) {
382 MachineInstr *DefMI = &MI;
384 if (!DefMI->killsRegister(Reg))
386 if (TargetRegisterInfo::isPhysicalRegister(Reg))
388 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
389 // If there are multiple defs, we can't do a simple analysis, so just
390 // go with what the kill flag says.
391 if (llvm::next(Begin) != MRI->def_end())
394 bool IsSrcPhys, IsDstPhys;
395 unsigned SrcReg, DstReg;
396 // If the def is something other than a copy, then it isn't going to
397 // be coalesced, so follow the kill flag.
398 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
404 /// isTwoAddrUse - Return true if the specified MI uses the specified register
405 /// as a two-address use. If so, return the destination register by reference.
406 static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
407 const MCInstrDesc &MCID = MI.getDesc();
408 unsigned NumOps = MI.isInlineAsm()
409 ? MI.getNumOperands() : MCID.getNumOperands();
410 for (unsigned i = 0; i != NumOps; ++i) {
411 const MachineOperand &MO = MI.getOperand(i);
412 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
415 if (MI.isRegTiedToDefOperand(i, &ti)) {
416 DstReg = MI.getOperand(ti).getReg();
423 /// findOnlyInterestingUse - Given a register, if has a single in-basic block
424 /// use, return the use instruction if it's a copy or a two-address use.
426 MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
427 MachineRegisterInfo *MRI,
428 const TargetInstrInfo *TII,
430 unsigned &DstReg, bool &IsDstPhys) {
431 if (!MRI->hasOneNonDBGUse(Reg))
432 // None or more than one use.
434 MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg);
435 if (UseMI.getParent() != MBB)
439 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
444 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
445 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
451 /// getMappedReg - Return the physical register the specified virtual register
452 /// might be mapped to.
454 getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
455 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
456 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
457 if (SI == RegMap.end())
461 if (TargetRegisterInfo::isPhysicalRegister(Reg))
466 /// regsAreCompatible - Return true if the two registers are equal or aliased.
469 regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
474 return TRI->regsOverlap(RegA, RegB);
478 /// isProfitableToCommute - Return true if it's potentially profitable to commute
479 /// the two-address instruction that's being processed.
481 TwoAddressInstructionPass::isProfitableToCommute(unsigned regA, unsigned regB,
483 MachineInstr *MI, MachineBasicBlock *MBB,
485 if (OptLevel == CodeGenOpt::None)
488 // Determine if it's profitable to commute this two address instruction. In
489 // general, we want no uses between this instruction and the definition of
490 // the two-address register.
492 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
493 // %reg1029<def> = MOV8rr %reg1028
494 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
495 // insert => %reg1030<def> = MOV8rr %reg1028
496 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
497 // In this case, it might not be possible to coalesce the second MOV8rr
498 // instruction if the first one is coalesced. So it would be profitable to
500 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
501 // %reg1029<def> = MOV8rr %reg1028
502 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
503 // insert => %reg1030<def> = MOV8rr %reg1029
504 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
506 if (!MI->killsRegister(regC))
509 // Ok, we have something like:
510 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
511 // let's see if it's worth commuting it.
513 // Look for situations like this:
514 // %reg1024<def> = MOV r1
515 // %reg1025<def> = MOV r0
516 // %reg1026<def> = ADD %reg1024, %reg1025
518 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
519 unsigned ToRegA = getMappedReg(regA, DstRegMap);
521 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
522 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
523 bool BComp = !FromRegB || regsAreCompatible(FromRegB, ToRegA, TRI);
524 bool CComp = !FromRegC || regsAreCompatible(FromRegC, ToRegA, TRI);
526 return !BComp && CComp;
529 // If there is a use of regC between its last def (could be livein) and this
530 // instruction, then bail.
531 unsigned LastDefC = 0;
532 if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
535 // If there is a use of regB between its last def (could be livein) and this
536 // instruction, then go ahead and make this transformation.
537 unsigned LastDefB = 0;
538 if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
541 // Since there are no intervening uses for both registers, then commute
542 // if the def of regC is closer. Its live interval is shorter.
543 return LastDefB && LastDefC && LastDefC > LastDefB;
546 /// CommuteInstruction - Commute a two-address instruction and update the basic
547 /// block, distance map, and live variables if needed. Return true if it is
550 TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
551 MachineFunction::iterator &mbbi,
552 unsigned RegB, unsigned RegC, unsigned Dist) {
553 MachineInstr *MI = mi;
554 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
555 MachineInstr *NewMI = TII->commuteInstruction(MI);
558 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
562 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
563 // If the instruction changed to commute it, update livevar.
566 // Update live variables
567 LV->replaceKillInstruction(RegC, MI, NewMI);
569 mbbi->insert(mi, NewMI); // Insert the new inst
570 mbbi->erase(mi); // Nuke the old inst.
572 DistanceMap.insert(std::make_pair(NewMI, Dist));
575 // Update source register map.
576 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
578 unsigned RegA = MI->getOperand(0).getReg();
579 SrcRegMap[RegA] = FromRegC;
585 /// isProfitableToConv3Addr - Return true if it is profitable to convert the
586 /// given 2-address instruction to a 3-address one.
588 TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
589 // Look for situations like this:
590 // %reg1024<def> = MOV r1
591 // %reg1025<def> = MOV r0
592 // %reg1026<def> = ADD %reg1024, %reg1025
594 // Turn ADD into a 3-address instruction to avoid a copy.
595 unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
598 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
599 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
602 /// ConvertInstTo3Addr - Convert the specified two-address instruction into a
603 /// three address one. Return true if this transformation was successful.
605 TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
606 MachineBasicBlock::iterator &nmi,
607 MachineFunction::iterator &mbbi,
608 unsigned RegA, unsigned RegB,
610 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
612 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
613 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
616 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
617 // FIXME: Temporary workaround. If the new instruction doesn't
618 // uses RegB, convertToThreeAddress must have created more
619 // then one instruction.
620 Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
622 mbbi->erase(mi); // Nuke the old inst.
625 DistanceMap.insert(std::make_pair(NewMI, Dist));
627 nmi = llvm::next(mi);
630 // Update source and destination register maps.
631 SrcRegMap.erase(RegA);
632 DstRegMap.erase(RegB);
639 /// ScanUses - Scan forward recursively for only uses, update maps if the use
640 /// is a copy or a two-address instruction.
642 TwoAddressInstructionPass::ScanUses(unsigned DstReg, MachineBasicBlock *MBB,
643 SmallPtrSet<MachineInstr*, 8> &Processed) {
644 SmallVector<unsigned, 4> VirtRegPairs;
648 unsigned Reg = DstReg;
649 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
650 NewReg, IsDstPhys)) {
651 if (IsCopy && !Processed.insert(UseMI))
654 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
655 if (DI != DistanceMap.end())
656 // Earlier in the same MBB.Reached via a back edge.
660 VirtRegPairs.push_back(NewReg);
663 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
665 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
666 VirtRegPairs.push_back(NewReg);
670 if (!VirtRegPairs.empty()) {
671 unsigned ToReg = VirtRegPairs.back();
672 VirtRegPairs.pop_back();
673 while (!VirtRegPairs.empty()) {
674 unsigned FromReg = VirtRegPairs.back();
675 VirtRegPairs.pop_back();
676 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
678 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
681 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
683 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
687 /// ProcessCopy - If the specified instruction is not yet processed, process it
688 /// if it's a copy. For a copy instruction, we find the physical registers the
689 /// source and destination registers might be mapped to. These are kept in
690 /// point-to maps used to determine future optimizations. e.g.
693 /// v1026 = add v1024, v1025
695 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
696 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
697 /// potentially joined with r1 on the output side. It's worthwhile to commute
698 /// 'add' to eliminate a copy.
699 void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
700 MachineBasicBlock *MBB,
701 SmallPtrSet<MachineInstr*, 8> &Processed) {
702 if (Processed.count(MI))
705 bool IsSrcPhys, IsDstPhys;
706 unsigned SrcReg, DstReg;
707 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
710 if (IsDstPhys && !IsSrcPhys)
711 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
712 else if (!IsDstPhys && IsSrcPhys) {
713 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
715 assert(SrcRegMap[DstReg] == SrcReg &&
716 "Can't map to two src physical registers!");
718 ScanUses(DstReg, MBB, Processed);
721 Processed.insert(MI);
725 /// RescheduleMIBelowKill - If there is one more local instruction that reads
726 /// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
727 /// instruction in order to eliminate the need for the copy.
729 TwoAddressInstructionPass::RescheduleMIBelowKill(MachineBasicBlock *MBB,
730 MachineBasicBlock::iterator &mi,
731 MachineBasicBlock::iterator &nmi,
733 // Bail immediately if we don't have LV available. We use it to find kills
738 MachineInstr *MI = &*mi;
739 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
740 if (DI == DistanceMap.end())
741 // Must be created from unfolded load. Don't waste time trying this.
744 MachineInstr *KillMI = LV->getVarInfo(Reg).findKill(MBB);
745 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
746 // Don't mess with copies, they may be coalesced later.
749 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
750 KillMI->isBranch() || KillMI->isTerminator())
751 // Don't move pass calls, etc.
755 if (isTwoAddrUse(*KillMI, Reg, DstReg))
758 bool SeenStore = true;
759 if (!MI->isSafeToMove(TII, AA, SeenStore))
762 if (TII->getInstrLatency(InstrItins, MI) > 1)
763 // FIXME: Needs more sophisticated heuristics.
766 SmallSet<unsigned, 2> Uses;
767 SmallSet<unsigned, 2> Kills;
768 SmallSet<unsigned, 2> Defs;
769 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
770 const MachineOperand &MO = MI->getOperand(i);
773 unsigned MOReg = MO.getReg();
780 if (MO.isKill() && MOReg != Reg)
785 // Move the copies connected to MI down as well.
786 MachineBasicBlock::iterator From = MI;
787 MachineBasicBlock::iterator To = llvm::next(From);
788 while (To->isCopy() && Defs.count(To->getOperand(1).getReg())) {
789 Defs.insert(To->getOperand(0).getReg());
793 // Check if the reschedule will not break depedencies.
794 unsigned NumVisited = 0;
795 MachineBasicBlock::iterator KillPos = KillMI;
797 for (MachineBasicBlock::iterator I = To; I != KillPos; ++I) {
798 MachineInstr *OtherMI = I;
799 // DBG_VALUE cannot be counted against the limit.
800 if (OtherMI->isDebugValue())
802 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
805 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
806 OtherMI->isBranch() || OtherMI->isTerminator())
807 // Don't move pass calls, etc.
809 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
810 const MachineOperand &MO = OtherMI->getOperand(i);
813 unsigned MOReg = MO.getReg();
817 if (Uses.count(MOReg))
818 // Physical register use would be clobbered.
820 if (!MO.isDead() && Defs.count(MOReg))
821 // May clobber a physical register def.
822 // FIXME: This may be too conservative. It's ok if the instruction
823 // is sunken completely below the use.
826 if (Defs.count(MOReg))
829 ((MO.isKill() && Uses.count(MOReg)) || Kills.count(MOReg)))
830 // Don't want to extend other live ranges and update kills.
832 if (MOReg == Reg && !MO.isKill())
833 // We can't schedule across a use of the register in question.
835 // Ensure that if this is register in question, its the kill we expect.
836 assert((MOReg != Reg || OtherMI == KillMI) &&
837 "Found multiple kills of a register in a basic block");
842 // Move debug info as well.
843 while (From != MBB->begin() && llvm::prior(From)->isDebugValue())
846 // Copies following MI may have been moved as well.
848 MBB->splice(KillPos, MBB, From, To);
849 DistanceMap.erase(DI);
851 // Update live variables
852 LV->removeVirtualRegisterKilled(Reg, KillMI);
853 LV->addVirtualRegisterKilled(Reg, MI);
855 DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
859 /// isDefTooClose - Return true if the re-scheduling will put the given
860 /// instruction too close to the defs of its register dependencies.
861 bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
863 MachineBasicBlock *MBB) {
864 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(Reg),
865 DE = MRI->def_end(); DI != DE; ++DI) {
866 MachineInstr *DefMI = &*DI;
867 if (DefMI->getParent() != MBB || DefMI->isCopy() || DefMI->isCopyLike())
870 return true; // MI is defining something KillMI uses
871 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(DefMI);
872 if (DDI == DistanceMap.end())
873 return true; // Below MI
874 unsigned DefDist = DDI->second;
875 assert(Dist > DefDist && "Visited def already?");
876 if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist))
882 /// RescheduleKillAboveMI - If there is one more local instruction that reads
883 /// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
884 /// current two-address instruction in order to eliminate the need for the
887 TwoAddressInstructionPass::RescheduleKillAboveMI(MachineBasicBlock *MBB,
888 MachineBasicBlock::iterator &mi,
889 MachineBasicBlock::iterator &nmi,
891 // Bail immediately if we don't have LV available. We use it to find kills
896 MachineInstr *MI = &*mi;
897 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
898 if (DI == DistanceMap.end())
899 // Must be created from unfolded load. Don't waste time trying this.
902 MachineInstr *KillMI = LV->getVarInfo(Reg).findKill(MBB);
903 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
904 // Don't mess with copies, they may be coalesced later.
908 if (isTwoAddrUse(*KillMI, Reg, DstReg))
911 bool SeenStore = true;
912 if (!KillMI->isSafeToMove(TII, AA, SeenStore))
915 SmallSet<unsigned, 2> Uses;
916 SmallSet<unsigned, 2> Kills;
917 SmallSet<unsigned, 2> Defs;
918 SmallSet<unsigned, 2> LiveDefs;
919 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
920 const MachineOperand &MO = KillMI->getOperand(i);
923 unsigned MOReg = MO.getReg();
927 if (isDefTooClose(MOReg, DI->second, MI, MBB))
929 if (MOReg == Reg && !MO.isKill())
932 if (MO.isKill() && MOReg != Reg)
934 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
937 LiveDefs.insert(MOReg);
941 // Check if the reschedule will not break depedencies.
942 unsigned NumVisited = 0;
943 MachineBasicBlock::iterator KillPos = KillMI;
944 for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
945 MachineInstr *OtherMI = I;
946 // DBG_VALUE cannot be counted against the limit.
947 if (OtherMI->isDebugValue())
949 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
952 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
953 OtherMI->isBranch() || OtherMI->isTerminator())
954 // Don't move pass calls, etc.
956 SmallVector<unsigned, 2> OtherDefs;
957 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
958 const MachineOperand &MO = OtherMI->getOperand(i);
961 unsigned MOReg = MO.getReg();
965 if (Defs.count(MOReg))
966 // Moving KillMI can clobber the physical register if the def has
969 if (Kills.count(MOReg))
970 // Don't want to extend other live ranges and update kills.
972 if (OtherMI != MI && MOReg == Reg && !MO.isKill())
973 // We can't schedule across a use of the register in question.
976 OtherDefs.push_back(MOReg);
980 for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
981 unsigned MOReg = OtherDefs[i];
982 if (Uses.count(MOReg))
984 if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
985 LiveDefs.count(MOReg))
987 // Physical register def is seen.
992 // Move the old kill above MI, don't forget to move debug info as well.
993 MachineBasicBlock::iterator InsertPos = mi;
994 while (InsertPos != MBB->begin() && llvm::prior(InsertPos)->isDebugValue())
996 MachineBasicBlock::iterator From = KillMI;
997 MachineBasicBlock::iterator To = llvm::next(From);
998 while (llvm::prior(From)->isDebugValue())
1000 MBB->splice(InsertPos, MBB, From, To);
1002 nmi = llvm::prior(InsertPos); // Backtrack so we process the moved instr.
1003 DistanceMap.erase(DI);
1005 // Update live variables
1006 LV->removeVirtualRegisterKilled(Reg, KillMI);
1007 LV->addVirtualRegisterKilled(Reg, MI);
1009 DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
1013 /// TryInstructionTransform - For the case where an instruction has a single
1014 /// pair of tied register operands, attempt some transformations that may
1015 /// either eliminate the tied operands or improve the opportunities for
1016 /// coalescing away the register copy. Returns true if no copy needs to be
1017 /// inserted to untie mi's operands (either because they were untied, or
1018 /// because mi was rescheduled, and will be visited again later).
1019 bool TwoAddressInstructionPass::
1020 TryInstructionTransform(MachineBasicBlock::iterator &mi,
1021 MachineBasicBlock::iterator &nmi,
1022 MachineFunction::iterator &mbbi,
1023 unsigned SrcIdx, unsigned DstIdx, unsigned Dist,
1024 SmallPtrSet<MachineInstr*, 8> &Processed) {
1025 if (OptLevel == CodeGenOpt::None)
1028 MachineInstr &MI = *mi;
1029 unsigned regA = MI.getOperand(DstIdx).getReg();
1030 unsigned regB = MI.getOperand(SrcIdx).getReg();
1032 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1033 "cannot make instruction into two-address form");
1034 bool regBKilled = isKilled(MI, regB, MRI, TII);
1036 if (TargetRegisterInfo::isVirtualRegister(regA))
1037 ScanUses(regA, &*mbbi, Processed);
1039 // Check if it is profitable to commute the operands.
1040 unsigned SrcOp1, SrcOp2;
1042 unsigned regCIdx = ~0U;
1043 bool TryCommute = false;
1044 bool AggressiveCommute = false;
1045 if (MI.isCommutable() && MI.getNumOperands() >= 3 &&
1046 TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
1047 if (SrcIdx == SrcOp1)
1049 else if (SrcIdx == SrcOp2)
1052 if (regCIdx != ~0U) {
1053 regC = MI.getOperand(regCIdx).getReg();
1054 if (!regBKilled && isKilled(MI, regC, MRI, TII))
1055 // If C dies but B does not, swap the B and C operands.
1056 // This makes the live ranges of A and C joinable.
1058 else if (isProfitableToCommute(regA, regB, regC, &MI, mbbi, Dist)) {
1060 AggressiveCommute = true;
1065 // If it's profitable to commute, try to do so.
1066 if (TryCommute && CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
1068 if (AggressiveCommute)
1073 // If there is one more use of regB later in the same MBB, consider
1074 // re-schedule this MI below it.
1075 if (RescheduleMIBelowKill(mbbi, mi, nmi, regB)) {
1080 if (MI.isConvertibleTo3Addr()) {
1081 // This instruction is potentially convertible to a true
1082 // three-address instruction. Check if it is profitable.
1083 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
1084 // Try to convert it.
1085 if (ConvertInstTo3Addr(mi, nmi, mbbi, regA, regB, Dist)) {
1086 ++NumConvertedTo3Addr;
1087 return true; // Done with this instruction.
1092 // If there is one more use of regB later in the same MBB, consider
1093 // re-schedule it before this MI if it's legal.
1094 if (RescheduleKillAboveMI(mbbi, mi, nmi, regB)) {
1099 // If this is an instruction with a load folded into it, try unfolding
1100 // the load, e.g. avoid this:
1102 // addq (%rax), %rcx
1103 // in favor of this:
1104 // movq (%rax), %rcx
1106 // because it's preferable to schedule a load than a register copy.
1107 if (MI.mayLoad() && !regBKilled) {
1108 // Determine if a load can be unfolded.
1109 unsigned LoadRegIndex;
1111 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1112 /*UnfoldLoad=*/true,
1113 /*UnfoldStore=*/false,
1116 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1117 if (UnfoldMCID.getNumDefs() == 1) {
1118 MachineFunction &MF = *mbbi->getParent();
1121 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
1122 const TargetRegisterClass *RC =
1123 TRI->getAllocatableClass(
1124 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, MF));
1125 unsigned Reg = MRI->createVirtualRegister(RC);
1126 SmallVector<MachineInstr *, 2> NewMIs;
1127 if (!TII->unfoldMemoryOperand(MF, &MI, Reg,
1128 /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
1130 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1133 assert(NewMIs.size() == 2 &&
1134 "Unfolded a load into multiple instructions!");
1135 // The load was previously folded, so this is the only use.
1136 NewMIs[1]->addRegisterKilled(Reg, TRI);
1138 // Tentatively insert the instructions into the block so that they
1139 // look "normal" to the transformation logic.
1140 mbbi->insert(mi, NewMIs[0]);
1141 mbbi->insert(mi, NewMIs[1]);
1143 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1144 << "2addr: NEW INST: " << *NewMIs[1]);
1146 // Transform the instruction, now that it no longer has a load.
1147 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1148 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1149 MachineBasicBlock::iterator NewMI = NewMIs[1];
1150 bool TransformSuccess =
1151 TryInstructionTransform(NewMI, mi, mbbi,
1152 NewSrcIdx, NewDstIdx, Dist, Processed);
1153 if (TransformSuccess ||
1154 NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1155 // Success, or at least we made an improvement. Keep the unfolded
1156 // instructions and discard the original.
1158 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1159 MachineOperand &MO = MI.getOperand(i);
1161 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1164 if (NewMIs[0]->killsRegister(MO.getReg()))
1165 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
1167 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1168 "Kill missing after load unfold!");
1169 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
1172 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
1173 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1174 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
1176 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1177 "Dead flag missing after load unfold!");
1178 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
1183 LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
1185 MI.eraseFromParent();
1187 if (TransformSuccess)
1190 // Transforming didn't eliminate the tie and didn't lead to an
1191 // improvement. Clean up the unfolded instructions and keep the
1193 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1194 NewMIs[0]->eraseFromParent();
1195 NewMIs[1]->eraseFromParent();
1204 /// runOnMachineFunction - Reduce two-address instructions to two operands.
1206 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
1207 const TargetMachine &TM = MF.getTarget();
1208 MRI = &MF.getRegInfo();
1209 TII = TM.getInstrInfo();
1210 TRI = TM.getRegisterInfo();
1211 InstrItins = TM.getInstrItineraryData();
1212 LV = getAnalysisIfAvailable<LiveVariables>();
1213 AA = &getAnalysis<AliasAnalysis>();
1214 OptLevel = TM.getOptLevel();
1216 bool MadeChange = false;
1218 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
1219 DEBUG(dbgs() << "********** Function: "
1220 << MF.getFunction()->getName() << '\n');
1222 // This pass takes the function out of SSA form.
1225 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
1226 BitVector ReMatRegs(MRI->getNumVirtRegs());
1228 typedef DenseMap<unsigned, SmallVector<std::pair<unsigned, unsigned>, 4> >
1230 TiedOperandMap TiedOperands(4);
1232 SmallPtrSet<MachineInstr*, 8> Processed;
1233 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
1234 mbbi != mbbe; ++mbbi) {
1236 DistanceMap.clear();
1240 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
1242 MachineBasicBlock::iterator nmi = llvm::next(mi);
1243 if (mi->isDebugValue()) {
1248 // Remember REG_SEQUENCE instructions, we'll deal with them later.
1249 if (mi->isRegSequence())
1250 RegSequences.push_back(&*mi);
1252 const MCInstrDesc &MCID = mi->getDesc();
1253 bool FirstTied = true;
1255 DistanceMap.insert(std::make_pair(mi, ++Dist));
1257 ProcessCopy(&*mi, &*mbbi, Processed);
1259 // First scan through all the tied register uses in this instruction
1260 // and record a list of pairs of tied operands for each register.
1261 unsigned NumOps = mi->isInlineAsm()
1262 ? mi->getNumOperands() : MCID.getNumOperands();
1263 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1264 unsigned DstIdx = 0;
1265 if (!mi->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1270 ++NumTwoAddressInstrs;
1271 DEBUG(dbgs() << '\t' << *mi);
1274 assert(mi->getOperand(SrcIdx).isReg() &&
1275 mi->getOperand(SrcIdx).getReg() &&
1276 mi->getOperand(SrcIdx).isUse() &&
1277 "two address instruction invalid");
1279 unsigned regB = mi->getOperand(SrcIdx).getReg();
1281 // Deal with <undef> uses immediately - simply rewrite the src operand.
1282 if (mi->getOperand(SrcIdx).isUndef()) {
1283 unsigned DstReg = mi->getOperand(DstIdx).getReg();
1284 // Constrain the DstReg register class if required.
1285 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1286 if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
1288 MRI->constrainRegClass(DstReg, RC);
1289 mi->getOperand(SrcIdx).setReg(DstReg);
1290 DEBUG(dbgs() << "\t\trewrite undef:\t" << *mi);
1293 TiedOperands[regB].push_back(std::make_pair(SrcIdx, DstIdx));
1296 // If the instruction has a single pair of tied operands, try some
1297 // transformations that may either eliminate the tied operands or
1298 // improve the opportunities for coalescing away the register copy.
1299 if (TiedOperands.size() == 1) {
1300 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs
1301 = TiedOperands.begin()->second;
1302 if (TiedPairs.size() == 1) {
1303 unsigned SrcIdx = TiedPairs[0].first;
1304 unsigned DstIdx = TiedPairs[0].second;
1305 unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
1306 unsigned DstReg = mi->getOperand(DstIdx).getReg();
1307 if (SrcReg != DstReg &&
1308 TryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist,
1310 // The tied operands have been eliminated or shifted further down the
1311 // block to ease elimination. Continue processing with 'nmi'.
1312 TiedOperands.clear();
1319 // Now iterate over the information collected above.
1320 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1321 OE = TiedOperands.end(); OI != OE; ++OI) {
1322 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs = OI->second;
1324 bool IsEarlyClobber = false;
1325 bool RemovedKillFlag = false;
1326 bool AllUsesCopied = true;
1327 unsigned LastCopiedReg = 0;
1328 unsigned regB = OI->first;
1329 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1330 unsigned SrcIdx = TiedPairs[tpi].first;
1331 unsigned DstIdx = TiedPairs[tpi].second;
1333 const MachineOperand &DstMO = mi->getOperand(DstIdx);
1334 unsigned regA = DstMO.getReg();
1335 IsEarlyClobber |= DstMO.isEarlyClobber();
1337 // Grab regB from the instruction because it may have changed if the
1338 // instruction was commuted.
1339 regB = mi->getOperand(SrcIdx).getReg();
1342 // The register is tied to multiple destinations (or else we would
1343 // not have continued this far), but this use of the register
1344 // already matches the tied destination. Leave it.
1345 AllUsesCopied = false;
1348 LastCopiedReg = regA;
1350 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1351 "cannot make instruction into two-address form");
1354 // First, verify that we don't have a use of "a" in the instruction
1355 // (a = b + a for example) because our transformation will not
1356 // work. This should never occur because we are in SSA form.
1357 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
1358 assert(i == DstIdx ||
1359 !mi->getOperand(i).isReg() ||
1360 mi->getOperand(i).getReg() != regA);
1364 BuildMI(*mbbi, mi, mi->getDebugLoc(), TII->get(TargetOpcode::COPY),
1367 // Update DistanceMap.
1368 MachineBasicBlock::iterator prevMI = prior(mi);
1369 DistanceMap.insert(std::make_pair(prevMI, Dist));
1370 DistanceMap[mi] = ++Dist;
1372 DEBUG(dbgs() << "\t\tprepend:\t" << *prevMI);
1374 MachineOperand &MO = mi->getOperand(SrcIdx);
1375 assert(MO.isReg() && MO.getReg() == regB && MO.isUse() &&
1376 "inconsistent operand info for 2-reg pass");
1378 MO.setIsKill(false);
1379 RemovedKillFlag = true;
1382 // Make sure regA is a legal regclass for the SrcIdx operand.
1383 if (TargetRegisterInfo::isVirtualRegister(regA) &&
1384 TargetRegisterInfo::isVirtualRegister(regB))
1385 MRI->constrainRegClass(regA, MRI->getRegClass(regB));
1389 // Propagate SrcRegMap.
1390 SrcRegMap[regA] = regB;
1393 if (AllUsesCopied) {
1394 if (!IsEarlyClobber) {
1395 // Replace other (un-tied) uses of regB with LastCopiedReg.
1396 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1397 MachineOperand &MO = mi->getOperand(i);
1398 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1400 MO.setIsKill(false);
1401 RemovedKillFlag = true;
1403 MO.setReg(LastCopiedReg);
1408 // Update live variables for regB.
1409 if (RemovedKillFlag && LV && LV->getVarInfo(regB).removeKill(mi))
1410 LV->addVirtualRegisterKilled(regB, prior(mi));
1412 } else if (RemovedKillFlag) {
1413 // Some tied uses of regB matched their destination registers, so
1414 // regB is still used in this instruction, but a kill flag was
1415 // removed from a different tied use of regB, so now we need to add
1416 // a kill flag to one of the remaining uses of regB.
1417 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1418 MachineOperand &MO = mi->getOperand(i);
1419 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1426 // We didn't change anything if there was a single tied pair, and that
1427 // pair didn't require copies.
1428 if (AllUsesCopied || TiedPairs.size() > 1) {
1431 // Schedule the source copy / remat inserted to form two-address
1432 // instruction. FIXME: Does it matter the distance map may not be
1433 // accurate after it's scheduled?
1434 TII->scheduleTwoAddrSource(prior(mi), mi, *TRI);
1437 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1440 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1441 if (mi->isInsertSubreg()) {
1442 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1443 // To %reg:subidx = COPY %subreg
1444 unsigned SubIdx = mi->getOperand(3).getImm();
1445 mi->RemoveOperand(3);
1446 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1447 mi->getOperand(0).setSubReg(SubIdx);
1448 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1449 mi->RemoveOperand(1);
1450 mi->setDesc(TII->get(TargetOpcode::COPY));
1451 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
1454 // Clear TiedOperands here instead of at the top of the loop
1455 // since most instructions do not have tied operands.
1456 TiedOperands.clear();
1461 // Some remat'ed instructions are dead.
1462 for (int i = ReMatRegs.find_first(); i != -1; i = ReMatRegs.find_next(i)) {
1463 unsigned VReg = TargetRegisterInfo::index2VirtReg(i);
1464 if (MRI->use_nodbg_empty(VReg)) {
1465 MachineInstr *DefMI = MRI->getVRegDef(VReg);
1466 DefMI->eraseFromParent();
1470 // Eliminate REG_SEQUENCE instructions. Their whole purpose was to preseve
1471 // SSA form. It's now safe to de-SSA.
1472 MadeChange |= EliminateRegSequences();
1477 static void UpdateRegSequenceSrcs(unsigned SrcReg,
1478 unsigned DstReg, unsigned SubIdx,
1479 MachineRegisterInfo *MRI,
1480 const TargetRegisterInfo &TRI) {
1481 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg),
1482 RE = MRI->reg_end(); RI != RE; ) {
1483 MachineOperand &MO = RI.getOperand();
1485 MO.substVirtReg(DstReg, SubIdx, TRI);
1489 // Find the first def of Reg, assuming they are all in the same basic block.
1490 static MachineInstr *findFirstDef(unsigned Reg, MachineRegisterInfo *MRI) {
1491 SmallPtrSet<MachineInstr*, 8> Defs;
1492 MachineInstr *First = 0;
1493 for (MachineRegisterInfo::def_iterator RI = MRI->def_begin(Reg);
1494 MachineInstr *MI = RI.skipInstruction(); Defs.insert(MI))
1499 MachineBasicBlock *MBB = First->getParent();
1500 MachineBasicBlock::iterator A = First, B = First;
1504 if (A != MBB->begin()) {
1507 if (Defs.erase(A)) First = A;
1509 if (B != MBB->end()) {
1514 } while (Moving && !Defs.empty());
1515 assert(Defs.empty() && "Instructions outside basic block!");
1519 /// CoalesceExtSubRegs - If a number of sources of the REG_SEQUENCE are
1520 /// EXTRACT_SUBREG from the same register and to the same virtual register
1521 /// with different sub-register indices, attempt to combine the
1522 /// EXTRACT_SUBREGs and pre-coalesce them. e.g.
1523 /// %reg1026<def> = VLDMQ %reg1025<kill>, 260, pred:14, pred:%reg0
1524 /// %reg1029:6<def> = EXTRACT_SUBREG %reg1026, 6
1525 /// %reg1029:5<def> = EXTRACT_SUBREG %reg1026<kill>, 5
1526 /// Since D subregs 5, 6 can combine to a Q register, we can coalesce
1527 /// reg1026 to reg1029.
1529 TwoAddressInstructionPass::CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs,
1531 SmallSet<unsigned, 4> Seen;
1532 for (unsigned i = 0, e = Srcs.size(); i != e; ++i) {
1533 unsigned SrcReg = Srcs[i];
1534 if (!Seen.insert(SrcReg))
1537 // Check that the instructions are all in the same basic block.
1538 MachineInstr *SrcDefMI = MRI->getUniqueVRegDef(SrcReg);
1539 MachineInstr *DstDefMI = MRI->getUniqueVRegDef(DstReg);
1540 if (!SrcDefMI || !DstDefMI ||
1541 SrcDefMI->getParent() != DstDefMI->getParent())
1544 // If there are no other uses than copies which feed into
1545 // the reg_sequence, then we might be able to coalesce them.
1546 bool CanCoalesce = true;
1547 SmallVector<unsigned, 4> SrcSubIndices, DstSubIndices;
1548 for (MachineRegisterInfo::use_nodbg_iterator
1549 UI = MRI->use_nodbg_begin(SrcReg),
1550 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
1551 MachineInstr *UseMI = &*UI;
1552 if (!UseMI->isCopy() || UseMI->getOperand(0).getReg() != DstReg) {
1553 CanCoalesce = false;
1556 SrcSubIndices.push_back(UseMI->getOperand(1).getSubReg());
1557 DstSubIndices.push_back(UseMI->getOperand(0).getSubReg());
1560 if (!CanCoalesce || SrcSubIndices.size() < 2)
1563 // Check that the source subregisters can be combined.
1564 std::sort(SrcSubIndices.begin(), SrcSubIndices.end());
1565 unsigned NewSrcSubIdx = 0;
1566 if (!TRI->canCombineSubRegIndices(MRI->getRegClass(SrcReg), SrcSubIndices,
1570 // Check that the destination subregisters can also be combined.
1571 std::sort(DstSubIndices.begin(), DstSubIndices.end());
1572 unsigned NewDstSubIdx = 0;
1573 if (!TRI->canCombineSubRegIndices(MRI->getRegClass(DstReg), DstSubIndices,
1577 // If neither source nor destination can be combined to the full register,
1578 // just give up. This could be improved if it ever matters.
1579 if (NewSrcSubIdx != 0 && NewDstSubIdx != 0)
1582 // Now that we know that all the uses are extract_subregs and that those
1583 // subregs can somehow be combined, scan all the extract_subregs again to
1584 // make sure the subregs are in the right order and can be composed.
1585 MachineInstr *SomeMI = 0;
1587 for (MachineRegisterInfo::use_nodbg_iterator
1588 UI = MRI->use_nodbg_begin(SrcReg),
1589 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
1590 MachineInstr *UseMI = &*UI;
1591 assert(UseMI->isCopy());
1592 unsigned DstSubIdx = UseMI->getOperand(0).getSubReg();
1593 unsigned SrcSubIdx = UseMI->getOperand(1).getSubReg();
1594 assert(DstSubIdx != 0 && "missing subreg from RegSequence elimination");
1595 if ((NewDstSubIdx == 0 &&
1596 TRI->composeSubRegIndices(NewSrcSubIdx, DstSubIdx) != SrcSubIdx) ||
1597 (NewSrcSubIdx == 0 &&
1598 TRI->composeSubRegIndices(NewDstSubIdx, SrcSubIdx) != DstSubIdx)) {
1599 CanCoalesce = false;
1602 // Keep track of one of the uses. Preferably the first one which has a
1603 // <def,undef> flag.
1604 if (!SomeMI || UseMI->getOperand(0).isUndef())
1610 // Insert a copy to replace the original.
1611 MachineInstr *CopyMI = BuildMI(*SomeMI->getParent(), SomeMI,
1612 SomeMI->getDebugLoc(),
1613 TII->get(TargetOpcode::COPY))
1614 .addReg(DstReg, RegState::Define |
1615 getUndefRegState(SomeMI->getOperand(0).isUndef()),
1617 .addReg(SrcReg, 0, NewSrcSubIdx);
1619 // Remove all the old extract instructions.
1620 for (MachineRegisterInfo::use_nodbg_iterator
1621 UI = MRI->use_nodbg_begin(SrcReg),
1622 UE = MRI->use_nodbg_end(); UI != UE; ) {
1623 MachineInstr *UseMI = &*UI;
1625 if (UseMI == CopyMI)
1627 assert(UseMI->isCopy());
1628 // Move any kills to the new copy or extract instruction.
1629 if (UseMI->getOperand(1).isKill()) {
1630 CopyMI->getOperand(1).setIsKill();
1632 // Update live variables
1633 LV->replaceKillInstruction(SrcReg, UseMI, &*CopyMI);
1635 UseMI->eraseFromParent();
1640 static bool HasOtherRegSequenceUses(unsigned Reg, MachineInstr *RegSeq,
1641 MachineRegisterInfo *MRI) {
1642 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
1643 UE = MRI->use_end(); UI != UE; ++UI) {
1644 MachineInstr *UseMI = &*UI;
1645 if (UseMI != RegSeq && UseMI->isRegSequence())
1651 /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
1652 /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
1653 /// sub-register references of the register defined by REG_SEQUENCE. e.g.
1655 /// %reg1029<def>, %reg1030<def> = VLD1q16 %reg1024<kill>, ...
1656 /// %reg1031<def> = REG_SEQUENCE %reg1029<kill>, 5, %reg1030<kill>, 6
1658 /// %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
1659 bool TwoAddressInstructionPass::EliminateRegSequences() {
1660 if (RegSequences.empty())
1663 for (unsigned i = 0, e = RegSequences.size(); i != e; ++i) {
1664 MachineInstr *MI = RegSequences[i];
1665 unsigned DstReg = MI->getOperand(0).getReg();
1666 if (MI->getOperand(0).getSubReg() ||
1667 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1668 !(MI->getNumOperands() & 1)) {
1669 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1670 llvm_unreachable(0);
1673 bool IsImpDef = true;
1674 SmallVector<unsigned, 4> RealSrcs;
1675 SmallSet<unsigned, 4> Seen;
1676 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1677 // Nothing needs to be inserted for <undef> operands.
1678 if (MI->getOperand(i).isUndef()) {
1679 MI->getOperand(i).setReg(0);
1682 unsigned SrcReg = MI->getOperand(i).getReg();
1683 unsigned SrcSubIdx = MI->getOperand(i).getSubReg();
1684 unsigned SubIdx = MI->getOperand(i+1).getImm();
1685 // DefMI of NULL means the value does not have a vreg in this block
1686 // i.e., its a physical register or a subreg.
1687 // In either case we force a copy to be generated.
1688 MachineInstr *DefMI = NULL;
1689 if (!MI->getOperand(i).getSubReg() &&
1690 !TargetRegisterInfo::isPhysicalRegister(SrcReg)) {
1691 DefMI = MRI->getUniqueVRegDef(SrcReg);
1694 if (DefMI && DefMI->isImplicitDef()) {
1695 DefMI->eraseFromParent();
1700 // Remember COPY sources. These might be candidate for coalescing.
1701 if (DefMI && DefMI->isCopy() && DefMI->getOperand(1).getSubReg())
1702 RealSrcs.push_back(DefMI->getOperand(1).getReg());
1704 bool isKill = MI->getOperand(i).isKill();
1705 if (!DefMI || !Seen.insert(SrcReg) ||
1706 MI->getParent() != DefMI->getParent() ||
1707 !isKill || HasOtherRegSequenceUses(SrcReg, MI, MRI) ||
1708 !TRI->getMatchingSuperRegClass(MRI->getRegClass(DstReg),
1709 MRI->getRegClass(SrcReg), SubIdx)) {
1710 // REG_SEQUENCE cannot have duplicated operands, add a copy.
1711 // Also add an copy if the source is live-in the block. We don't want
1712 // to end up with a partial-redef of a livein, e.g.
1714 // reg1051:10<def> =
1720 // LiveIntervalAnalysis won't like it.
1722 // If the REG_SEQUENCE doesn't kill its source, keeping live variables
1723 // correctly up to date becomes very difficult. Insert a copy.
1725 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1726 // might insert a COPY that uses SrcReg after is was killed.
1728 for (unsigned j = i + 2; j < e; j += 2)
1729 if (MI->getOperand(j).getReg() == SrcReg) {
1730 MI->getOperand(j).setIsKill();
1735 MachineBasicBlock::iterator InsertLoc = MI;
1736 MachineInstr *CopyMI = BuildMI(*MI->getParent(), InsertLoc,
1737 MI->getDebugLoc(), TII->get(TargetOpcode::COPY))
1738 .addReg(DstReg, RegState::Define, SubIdx)
1739 .addReg(SrcReg, getKillRegState(isKill), SrcSubIdx);
1740 MI->getOperand(i).setReg(0);
1741 if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
1742 LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1743 DEBUG(dbgs() << "Inserted: " << *CopyMI);
1747 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1748 unsigned SrcReg = MI->getOperand(i).getReg();
1749 if (!SrcReg) continue;
1750 unsigned SubIdx = MI->getOperand(i+1).getImm();
1751 UpdateRegSequenceSrcs(SrcReg, DstReg, SubIdx, MRI, *TRI);
1754 // Set <def,undef> flags on the first DstReg def in the basic block.
1755 // It marks the beginning of the live range. All the other defs are
1756 // read-modify-write.
1757 if (MachineInstr *Def = findFirstDef(DstReg, MRI)) {
1758 for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
1759 MachineOperand &MO = Def->getOperand(i);
1760 if (MO.isReg() && MO.isDef() && MO.getReg() == DstReg)
1763 // Make sure there is a full non-subreg imp-def operand on the
1764 // instruction. This shouldn't be necessary, but it seems that at least
1765 // RAFast requires it.
1766 Def->addRegisterDefined(DstReg, TRI);
1767 DEBUG(dbgs() << "First def: " << *Def);
1771 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1772 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1773 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
1774 MI->RemoveOperand(j);
1776 DEBUG(dbgs() << "Eliminated: " << *MI);
1777 MI->eraseFromParent();
1780 // Try coalescing some EXTRACT_SUBREG instructions. This can create
1781 // INSERT_SUBREG instructions that must have <undef> flags added by
1782 // LiveIntervalAnalysis, so only run it when LiveVariables is available.
1784 CoalesceExtSubRegs(RealSrcs, DstReg);
1787 RegSequences.clear();