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/LiveIntervalAnalysis.h"
34 #include "llvm/CodeGen/LiveVariables.h"
35 #include "llvm/CodeGen/MachineFunctionPass.h"
36 #include "llvm/CodeGen/MachineInstr.h"
37 #include "llvm/CodeGen/MachineInstrBuilder.h"
38 #include "llvm/CodeGen/MachineRegisterInfo.h"
39 #include "llvm/Analysis/AliasAnalysis.h"
40 #include "llvm/MC/MCInstrItineraries.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/ADT/BitVector.h"
48 #include "llvm/ADT/DenseMap.h"
49 #include "llvm/ADT/SmallSet.h"
50 #include "llvm/ADT/Statistic.h"
51 #include "llvm/ADT/STLExtras.h"
54 STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
55 STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
56 STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
57 STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
58 STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
59 STATISTIC(NumReSchedUps, "Number of instructions re-scheduled up");
60 STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down");
63 class TwoAddressInstructionPass : public MachineFunctionPass {
65 const TargetInstrInfo *TII;
66 const TargetRegisterInfo *TRI;
67 const InstrItineraryData *InstrItins;
68 MachineRegisterInfo *MRI;
73 CodeGenOpt::Level OptLevel;
75 // DistanceMap - Keep track the distance of a MI from the start of the
76 // current basic block.
77 DenseMap<MachineInstr*, unsigned> DistanceMap;
79 // SrcRegMap - A map from virtual registers to physical registers which
80 // are likely targets to be coalesced to due to copies from physical
81 // registers to virtual registers. e.g. v1024 = move r0.
82 DenseMap<unsigned, unsigned> SrcRegMap;
84 // DstRegMap - A map from virtual registers to physical registers which
85 // are likely targets to be coalesced to due to copies to physical
86 // registers from virtual registers. e.g. r1 = move v1024.
87 DenseMap<unsigned, unsigned> DstRegMap;
89 /// RegSequences - Keep track the list of REG_SEQUENCE instructions seen
90 /// during the initial walk of the machine function.
91 SmallVector<MachineInstr*, 16> RegSequences;
93 bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
95 MachineBasicBlock::iterator OldPos);
97 bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
100 bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
101 MachineInstr *MI, MachineBasicBlock *MBB,
104 bool CommuteInstruction(MachineBasicBlock::iterator &mi,
105 MachineFunction::iterator &mbbi,
106 unsigned RegB, unsigned RegC, unsigned Dist);
108 bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
110 bool ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
111 MachineBasicBlock::iterator &nmi,
112 MachineFunction::iterator &mbbi,
113 unsigned RegA, unsigned RegB, unsigned Dist);
115 bool isDefTooClose(unsigned Reg, unsigned Dist,
116 MachineInstr *MI, MachineBasicBlock *MBB);
118 bool RescheduleMIBelowKill(MachineBasicBlock *MBB,
119 MachineBasicBlock::iterator &mi,
120 MachineBasicBlock::iterator &nmi,
122 bool RescheduleKillAboveMI(MachineBasicBlock *MBB,
123 MachineBasicBlock::iterator &mi,
124 MachineBasicBlock::iterator &nmi,
127 bool TryInstructionTransform(MachineBasicBlock::iterator &mi,
128 MachineBasicBlock::iterator &nmi,
129 MachineFunction::iterator &mbbi,
130 unsigned SrcIdx, unsigned DstIdx,
132 SmallPtrSet<MachineInstr*, 8> &Processed);
134 void ScanUses(unsigned DstReg, MachineBasicBlock *MBB,
135 SmallPtrSet<MachineInstr*, 8> &Processed);
137 void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
138 SmallPtrSet<MachineInstr*, 8> &Processed);
140 typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList;
141 typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap;
142 bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
143 void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
145 /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
146 /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
147 /// sub-register references of the register defined by REG_SEQUENCE.
148 bool EliminateRegSequences();
151 static char ID; // Pass identification, replacement for typeid
152 TwoAddressInstructionPass() : MachineFunctionPass(ID) {
153 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
156 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
157 AU.setPreservesCFG();
158 AU.addRequired<AliasAnalysis>();
159 AU.addPreserved<LiveVariables>();
160 AU.addPreserved<SlotIndexes>();
161 AU.addPreserved<LiveIntervals>();
162 AU.addPreservedID(MachineLoopInfoID);
163 AU.addPreservedID(MachineDominatorsID);
164 MachineFunctionPass::getAnalysisUsage(AU);
167 /// runOnMachineFunction - Pass entry point.
168 bool runOnMachineFunction(MachineFunction&);
172 char TwoAddressInstructionPass::ID = 0;
173 INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
174 "Two-Address instruction pass", false, false)
175 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
176 INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
177 "Two-Address instruction pass", false, false)
179 char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
181 /// Sink3AddrInstruction - A two-address instruction has been converted to a
182 /// three-address instruction to avoid clobbering a register. Try to sink it
183 /// past the instruction that would kill the above mentioned register to reduce
184 /// register pressure.
185 bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
186 MachineInstr *MI, unsigned SavedReg,
187 MachineBasicBlock::iterator OldPos) {
188 // FIXME: Shouldn't we be trying to do this before we three-addressify the
189 // instruction? After this transformation is done, we no longer need
190 // the instruction to be in three-address form.
192 // Check if it's safe to move this instruction.
193 bool SeenStore = true; // Be conservative.
194 if (!MI->isSafeToMove(TII, AA, SeenStore))
198 SmallSet<unsigned, 4> UseRegs;
200 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
201 const MachineOperand &MO = MI->getOperand(i);
204 unsigned MOReg = MO.getReg();
207 if (MO.isUse() && MOReg != SavedReg)
208 UseRegs.insert(MO.getReg());
212 // Don't try to move it if it implicitly defines a register.
215 // For now, don't move any instructions that define multiple registers.
217 DefReg = MO.getReg();
220 // Find the instruction that kills SavedReg.
221 MachineInstr *KillMI = NULL;
222 for (MachineRegisterInfo::use_nodbg_iterator
223 UI = MRI->use_nodbg_begin(SavedReg),
224 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
225 MachineOperand &UseMO = UI.getOperand();
228 KillMI = UseMO.getParent();
232 // If we find the instruction that kills SavedReg, and it is in an
233 // appropriate location, we can try to sink the current instruction
235 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
236 KillMI == OldPos || KillMI->isTerminator())
239 // If any of the definitions are used by another instruction between the
240 // position and the kill use, then it's not safe to sink it.
242 // FIXME: This can be sped up if there is an easy way to query whether an
243 // instruction is before or after another instruction. Then we can use
244 // MachineRegisterInfo def / use instead.
245 MachineOperand *KillMO = NULL;
246 MachineBasicBlock::iterator KillPos = KillMI;
249 unsigned NumVisited = 0;
250 for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
251 MachineInstr *OtherMI = I;
252 // DBG_VALUE cannot be counted against the limit.
253 if (OtherMI->isDebugValue())
255 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
258 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
259 MachineOperand &MO = OtherMI->getOperand(i);
262 unsigned MOReg = MO.getReg();
269 if (OtherMI == KillMI && MOReg == SavedReg)
270 // Save the operand that kills the register. We want to unset the kill
271 // marker if we can sink MI past it.
273 else if (UseRegs.count(MOReg))
274 // One of the uses is killed before the destination.
279 assert(KillMO && "Didn't find kill");
281 // Update kill and LV information.
282 KillMO->setIsKill(false);
283 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
284 KillMO->setIsKill(true);
287 LV->replaceKillInstruction(SavedReg, KillMI, MI);
289 // Move instruction to its destination.
291 MBB->insert(KillPos, MI);
300 /// NoUseAfterLastDef - Return true if there are no intervening uses between the
301 /// last instruction in the MBB that defines the specified register and the
302 /// two-address instruction which is being processed. It also returns the last
303 /// def location by reference
304 bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
305 MachineBasicBlock *MBB, unsigned Dist,
308 unsigned LastUse = Dist;
309 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
310 E = MRI->reg_end(); I != E; ++I) {
311 MachineOperand &MO = I.getOperand();
312 MachineInstr *MI = MO.getParent();
313 if (MI->getParent() != MBB || MI->isDebugValue())
315 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
316 if (DI == DistanceMap.end())
318 if (MO.isUse() && DI->second < LastUse)
319 LastUse = DI->second;
320 if (MO.isDef() && DI->second > LastDef)
321 LastDef = DI->second;
324 return !(LastUse > LastDef && LastUse < Dist);
327 /// isCopyToReg - Return true if the specified MI is a copy instruction or
328 /// a extract_subreg instruction. It also returns the source and destination
329 /// registers and whether they are physical registers by reference.
330 static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
331 unsigned &SrcReg, unsigned &DstReg,
332 bool &IsSrcPhys, bool &IsDstPhys) {
336 DstReg = MI.getOperand(0).getReg();
337 SrcReg = MI.getOperand(1).getReg();
338 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
339 DstReg = MI.getOperand(0).getReg();
340 SrcReg = MI.getOperand(2).getReg();
344 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
345 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
349 /// isKilled - Test if the given register value, which is used by the given
350 /// instruction, is killed by the given instruction. This looks through
351 /// coalescable copies to see if the original value is potentially not killed.
353 /// For example, in this code:
355 /// %reg1034 = copy %reg1024
356 /// %reg1035 = copy %reg1025<kill>
357 /// %reg1036 = add %reg1034<kill>, %reg1035<kill>
359 /// %reg1034 is not considered to be killed, since it is copied from a
360 /// register which is not killed. Treating it as not killed lets the
361 /// normal heuristics commute the (two-address) add, which lets
362 /// coalescing eliminate the extra copy.
364 static bool isKilled(MachineInstr &MI, unsigned Reg,
365 const MachineRegisterInfo *MRI,
366 const TargetInstrInfo *TII) {
367 MachineInstr *DefMI = &MI;
369 if (!DefMI->killsRegister(Reg))
371 if (TargetRegisterInfo::isPhysicalRegister(Reg))
373 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
374 // If there are multiple defs, we can't do a simple analysis, so just
375 // go with what the kill flag says.
376 if (llvm::next(Begin) != MRI->def_end())
379 bool IsSrcPhys, IsDstPhys;
380 unsigned SrcReg, DstReg;
381 // If the def is something other than a copy, then it isn't going to
382 // be coalesced, so follow the kill flag.
383 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
389 /// isTwoAddrUse - Return true if the specified MI uses the specified register
390 /// as a two-address use. If so, return the destination register by reference.
391 static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
392 const MCInstrDesc &MCID = MI.getDesc();
393 unsigned NumOps = MI.isInlineAsm()
394 ? MI.getNumOperands() : MCID.getNumOperands();
395 for (unsigned i = 0; i != NumOps; ++i) {
396 const MachineOperand &MO = MI.getOperand(i);
397 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
400 if (MI.isRegTiedToDefOperand(i, &ti)) {
401 DstReg = MI.getOperand(ti).getReg();
408 /// findOnlyInterestingUse - Given a register, if has a single in-basic block
409 /// use, return the use instruction if it's a copy or a two-address use.
411 MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
412 MachineRegisterInfo *MRI,
413 const TargetInstrInfo *TII,
415 unsigned &DstReg, bool &IsDstPhys) {
416 if (!MRI->hasOneNonDBGUse(Reg))
417 // None or more than one use.
419 MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg);
420 if (UseMI.getParent() != MBB)
424 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
429 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
430 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
436 /// getMappedReg - Return the physical register the specified virtual register
437 /// might be mapped to.
439 getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
440 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
441 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
442 if (SI == RegMap.end())
446 if (TargetRegisterInfo::isPhysicalRegister(Reg))
451 /// regsAreCompatible - Return true if the two registers are equal or aliased.
454 regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
459 return TRI->regsOverlap(RegA, RegB);
463 /// isProfitableToCommute - Return true if it's potentially profitable to commute
464 /// the two-address instruction that's being processed.
466 TwoAddressInstructionPass::isProfitableToCommute(unsigned regA, unsigned regB,
468 MachineInstr *MI, MachineBasicBlock *MBB,
470 if (OptLevel == CodeGenOpt::None)
473 // Determine if it's profitable to commute this two address instruction. In
474 // general, we want no uses between this instruction and the definition of
475 // the two-address register.
477 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
478 // %reg1029<def> = MOV8rr %reg1028
479 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
480 // insert => %reg1030<def> = MOV8rr %reg1028
481 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
482 // In this case, it might not be possible to coalesce the second MOV8rr
483 // instruction if the first one is coalesced. So it would be profitable to
485 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
486 // %reg1029<def> = MOV8rr %reg1028
487 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
488 // insert => %reg1030<def> = MOV8rr %reg1029
489 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
491 if (!MI->killsRegister(regC))
494 // Ok, we have something like:
495 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
496 // let's see if it's worth commuting it.
498 // Look for situations like this:
499 // %reg1024<def> = MOV r1
500 // %reg1025<def> = MOV r0
501 // %reg1026<def> = ADD %reg1024, %reg1025
503 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
504 unsigned ToRegA = getMappedReg(regA, DstRegMap);
506 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
507 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
508 bool BComp = !FromRegB || regsAreCompatible(FromRegB, ToRegA, TRI);
509 bool CComp = !FromRegC || regsAreCompatible(FromRegC, ToRegA, TRI);
511 return !BComp && CComp;
514 // If there is a use of regC between its last def (could be livein) and this
515 // instruction, then bail.
516 unsigned LastDefC = 0;
517 if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
520 // If there is a use of regB between its last def (could be livein) and this
521 // instruction, then go ahead and make this transformation.
522 unsigned LastDefB = 0;
523 if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
526 // Since there are no intervening uses for both registers, then commute
527 // if the def of regC is closer. Its live interval is shorter.
528 return LastDefB && LastDefC && LastDefC > LastDefB;
531 /// CommuteInstruction - Commute a two-address instruction and update the basic
532 /// block, distance map, and live variables if needed. Return true if it is
535 TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
536 MachineFunction::iterator &mbbi,
537 unsigned RegB, unsigned RegC, unsigned Dist) {
538 MachineInstr *MI = mi;
539 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
540 MachineInstr *NewMI = TII->commuteInstruction(MI);
543 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
547 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
548 // If the instruction changed to commute it, update livevar.
551 // Update live variables
552 LV->replaceKillInstruction(RegC, MI, NewMI);
554 Indexes->replaceMachineInstrInMaps(MI, NewMI);
556 mbbi->insert(mi, NewMI); // Insert the new inst
557 mbbi->erase(mi); // Nuke the old inst.
559 DistanceMap.insert(std::make_pair(NewMI, Dist));
562 // Update source register map.
563 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
565 unsigned RegA = MI->getOperand(0).getReg();
566 SrcRegMap[RegA] = FromRegC;
572 /// isProfitableToConv3Addr - Return true if it is profitable to convert the
573 /// given 2-address instruction to a 3-address one.
575 TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
576 // Look for situations like this:
577 // %reg1024<def> = MOV r1
578 // %reg1025<def> = MOV r0
579 // %reg1026<def> = ADD %reg1024, %reg1025
581 // Turn ADD into a 3-address instruction to avoid a copy.
582 unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
585 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
586 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
589 /// ConvertInstTo3Addr - Convert the specified two-address instruction into a
590 /// three address one. Return true if this transformation was successful.
592 TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
593 MachineBasicBlock::iterator &nmi,
594 MachineFunction::iterator &mbbi,
595 unsigned RegA, unsigned RegB,
597 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
599 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
600 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
604 Indexes->replaceMachineInstrInMaps(mi, NewMI);
606 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
607 // FIXME: Temporary workaround. If the new instruction doesn't
608 // uses RegB, convertToThreeAddress must have created more
609 // then one instruction.
610 Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
612 mbbi->erase(mi); // Nuke the old inst.
615 DistanceMap.insert(std::make_pair(NewMI, Dist));
617 nmi = llvm::next(mi);
620 // Update source and destination register maps.
621 SrcRegMap.erase(RegA);
622 DstRegMap.erase(RegB);
629 /// ScanUses - Scan forward recursively for only uses, update maps if the use
630 /// is a copy or a two-address instruction.
632 TwoAddressInstructionPass::ScanUses(unsigned DstReg, MachineBasicBlock *MBB,
633 SmallPtrSet<MachineInstr*, 8> &Processed) {
634 SmallVector<unsigned, 4> VirtRegPairs;
638 unsigned Reg = DstReg;
639 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
640 NewReg, IsDstPhys)) {
641 if (IsCopy && !Processed.insert(UseMI))
644 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
645 if (DI != DistanceMap.end())
646 // Earlier in the same MBB.Reached via a back edge.
650 VirtRegPairs.push_back(NewReg);
653 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
655 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
656 VirtRegPairs.push_back(NewReg);
660 if (!VirtRegPairs.empty()) {
661 unsigned ToReg = VirtRegPairs.back();
662 VirtRegPairs.pop_back();
663 while (!VirtRegPairs.empty()) {
664 unsigned FromReg = VirtRegPairs.back();
665 VirtRegPairs.pop_back();
666 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
668 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
671 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
673 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
677 /// ProcessCopy - If the specified instruction is not yet processed, process it
678 /// if it's a copy. For a copy instruction, we find the physical registers the
679 /// source and destination registers might be mapped to. These are kept in
680 /// point-to maps used to determine future optimizations. e.g.
683 /// v1026 = add v1024, v1025
685 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
686 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
687 /// potentially joined with r1 on the output side. It's worthwhile to commute
688 /// 'add' to eliminate a copy.
689 void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
690 MachineBasicBlock *MBB,
691 SmallPtrSet<MachineInstr*, 8> &Processed) {
692 if (Processed.count(MI))
695 bool IsSrcPhys, IsDstPhys;
696 unsigned SrcReg, DstReg;
697 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
700 if (IsDstPhys && !IsSrcPhys)
701 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
702 else if (!IsDstPhys && IsSrcPhys) {
703 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
705 assert(SrcRegMap[DstReg] == SrcReg &&
706 "Can't map to two src physical registers!");
708 ScanUses(DstReg, MBB, Processed);
711 Processed.insert(MI);
715 /// RescheduleMIBelowKill - If there is one more local instruction that reads
716 /// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
717 /// instruction in order to eliminate the need for the copy.
719 TwoAddressInstructionPass::RescheduleMIBelowKill(MachineBasicBlock *MBB,
720 MachineBasicBlock::iterator &mi,
721 MachineBasicBlock::iterator &nmi,
723 // Bail immediately if we don't have LV available. We use it to find kills
728 MachineInstr *MI = &*mi;
729 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
730 if (DI == DistanceMap.end())
731 // Must be created from unfolded load. Don't waste time trying this.
734 MachineInstr *KillMI = LV->getVarInfo(Reg).findKill(MBB);
735 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
736 // Don't mess with copies, they may be coalesced later.
739 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
740 KillMI->isBranch() || KillMI->isTerminator())
741 // Don't move pass calls, etc.
745 if (isTwoAddrUse(*KillMI, Reg, DstReg))
748 bool SeenStore = true;
749 if (!MI->isSafeToMove(TII, AA, SeenStore))
752 if (TII->getInstrLatency(InstrItins, MI) > 1)
753 // FIXME: Needs more sophisticated heuristics.
756 SmallSet<unsigned, 2> Uses;
757 SmallSet<unsigned, 2> Kills;
758 SmallSet<unsigned, 2> Defs;
759 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
760 const MachineOperand &MO = MI->getOperand(i);
763 unsigned MOReg = MO.getReg();
770 if (MO.isKill() && MOReg != Reg)
775 // Move the copies connected to MI down as well.
776 MachineBasicBlock::iterator From = MI;
777 MachineBasicBlock::iterator To = llvm::next(From);
778 while (To->isCopy() && Defs.count(To->getOperand(1).getReg())) {
779 Defs.insert(To->getOperand(0).getReg());
783 // Check if the reschedule will not break depedencies.
784 unsigned NumVisited = 0;
785 MachineBasicBlock::iterator KillPos = KillMI;
787 for (MachineBasicBlock::iterator I = To; I != KillPos; ++I) {
788 MachineInstr *OtherMI = I;
789 // DBG_VALUE cannot be counted against the limit.
790 if (OtherMI->isDebugValue())
792 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
795 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
796 OtherMI->isBranch() || OtherMI->isTerminator())
797 // Don't move pass calls, etc.
799 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
800 const MachineOperand &MO = OtherMI->getOperand(i);
803 unsigned MOReg = MO.getReg();
807 if (Uses.count(MOReg))
808 // Physical register use would be clobbered.
810 if (!MO.isDead() && Defs.count(MOReg))
811 // May clobber a physical register def.
812 // FIXME: This may be too conservative. It's ok if the instruction
813 // is sunken completely below the use.
816 if (Defs.count(MOReg))
819 ((MO.isKill() && Uses.count(MOReg)) || Kills.count(MOReg)))
820 // Don't want to extend other live ranges and update kills.
822 if (MOReg == Reg && !MO.isKill())
823 // We can't schedule across a use of the register in question.
825 // Ensure that if this is register in question, its the kill we expect.
826 assert((MOReg != Reg || OtherMI == KillMI) &&
827 "Found multiple kills of a register in a basic block");
832 // Move debug info as well.
833 while (From != MBB->begin() && llvm::prior(From)->isDebugValue())
836 // Copies following MI may have been moved as well.
838 MBB->splice(KillPos, MBB, From, To);
839 DistanceMap.erase(DI);
841 // Update live variables
842 LV->removeVirtualRegisterKilled(Reg, KillMI);
843 LV->addVirtualRegisterKilled(Reg, MI);
847 DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
851 /// isDefTooClose - Return true if the re-scheduling will put the given
852 /// instruction too close to the defs of its register dependencies.
853 bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
855 MachineBasicBlock *MBB) {
856 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(Reg),
857 DE = MRI->def_end(); DI != DE; ++DI) {
858 MachineInstr *DefMI = &*DI;
859 if (DefMI->getParent() != MBB || DefMI->isCopy() || DefMI->isCopyLike())
862 return true; // MI is defining something KillMI uses
863 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(DefMI);
864 if (DDI == DistanceMap.end())
865 return true; // Below MI
866 unsigned DefDist = DDI->second;
867 assert(Dist > DefDist && "Visited def already?");
868 if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist))
874 /// RescheduleKillAboveMI - If there is one more local instruction that reads
875 /// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
876 /// current two-address instruction in order to eliminate the need for the
879 TwoAddressInstructionPass::RescheduleKillAboveMI(MachineBasicBlock *MBB,
880 MachineBasicBlock::iterator &mi,
881 MachineBasicBlock::iterator &nmi,
883 // Bail immediately if we don't have LV available. We use it to find kills
888 MachineInstr *MI = &*mi;
889 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
890 if (DI == DistanceMap.end())
891 // Must be created from unfolded load. Don't waste time trying this.
894 MachineInstr *KillMI = LV->getVarInfo(Reg).findKill(MBB);
895 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
896 // Don't mess with copies, they may be coalesced later.
900 if (isTwoAddrUse(*KillMI, Reg, DstReg))
903 bool SeenStore = true;
904 if (!KillMI->isSafeToMove(TII, AA, SeenStore))
907 SmallSet<unsigned, 2> Uses;
908 SmallSet<unsigned, 2> Kills;
909 SmallSet<unsigned, 2> Defs;
910 SmallSet<unsigned, 2> LiveDefs;
911 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
912 const MachineOperand &MO = KillMI->getOperand(i);
915 unsigned MOReg = MO.getReg();
919 if (isDefTooClose(MOReg, DI->second, MI, MBB))
921 if (MOReg == Reg && !MO.isKill())
924 if (MO.isKill() && MOReg != Reg)
926 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
929 LiveDefs.insert(MOReg);
933 // Check if the reschedule will not break depedencies.
934 unsigned NumVisited = 0;
935 MachineBasicBlock::iterator KillPos = KillMI;
936 for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
937 MachineInstr *OtherMI = I;
938 // DBG_VALUE cannot be counted against the limit.
939 if (OtherMI->isDebugValue())
941 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
944 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
945 OtherMI->isBranch() || OtherMI->isTerminator())
946 // Don't move pass calls, etc.
948 SmallVector<unsigned, 2> OtherDefs;
949 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
950 const MachineOperand &MO = OtherMI->getOperand(i);
953 unsigned MOReg = MO.getReg();
957 if (Defs.count(MOReg))
958 // Moving KillMI can clobber the physical register if the def has
961 if (Kills.count(MOReg))
962 // Don't want to extend other live ranges and update kills.
964 if (OtherMI != MI && MOReg == Reg && !MO.isKill())
965 // We can't schedule across a use of the register in question.
968 OtherDefs.push_back(MOReg);
972 for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
973 unsigned MOReg = OtherDefs[i];
974 if (Uses.count(MOReg))
976 if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
977 LiveDefs.count(MOReg))
979 // Physical register def is seen.
984 // Move the old kill above MI, don't forget to move debug info as well.
985 MachineBasicBlock::iterator InsertPos = mi;
986 while (InsertPos != MBB->begin() && llvm::prior(InsertPos)->isDebugValue())
988 MachineBasicBlock::iterator From = KillMI;
989 MachineBasicBlock::iterator To = llvm::next(From);
990 while (llvm::prior(From)->isDebugValue())
992 MBB->splice(InsertPos, MBB, From, To);
994 nmi = llvm::prior(InsertPos); // Backtrack so we process the moved instr.
995 DistanceMap.erase(DI);
997 // Update live variables
998 LV->removeVirtualRegisterKilled(Reg, KillMI);
999 LV->addVirtualRegisterKilled(Reg, MI);
1001 LIS->handleMove(KillMI);
1003 DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
1007 /// TryInstructionTransform - For the case where an instruction has a single
1008 /// pair of tied register operands, attempt some transformations that may
1009 /// either eliminate the tied operands or improve the opportunities for
1010 /// coalescing away the register copy. Returns true if no copy needs to be
1011 /// inserted to untie mi's operands (either because they were untied, or
1012 /// because mi was rescheduled, and will be visited again later).
1013 bool TwoAddressInstructionPass::
1014 TryInstructionTransform(MachineBasicBlock::iterator &mi,
1015 MachineBasicBlock::iterator &nmi,
1016 MachineFunction::iterator &mbbi,
1017 unsigned SrcIdx, unsigned DstIdx, unsigned Dist,
1018 SmallPtrSet<MachineInstr*, 8> &Processed) {
1019 if (OptLevel == CodeGenOpt::None)
1022 MachineInstr &MI = *mi;
1023 unsigned regA = MI.getOperand(DstIdx).getReg();
1024 unsigned regB = MI.getOperand(SrcIdx).getReg();
1026 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1027 "cannot make instruction into two-address form");
1028 bool regBKilled = isKilled(MI, regB, MRI, TII);
1030 if (TargetRegisterInfo::isVirtualRegister(regA))
1031 ScanUses(regA, &*mbbi, Processed);
1033 // Check if it is profitable to commute the operands.
1034 unsigned SrcOp1, SrcOp2;
1036 unsigned regCIdx = ~0U;
1037 bool TryCommute = false;
1038 bool AggressiveCommute = false;
1039 if (MI.isCommutable() && MI.getNumOperands() >= 3 &&
1040 TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
1041 if (SrcIdx == SrcOp1)
1043 else if (SrcIdx == SrcOp2)
1046 if (regCIdx != ~0U) {
1047 regC = MI.getOperand(regCIdx).getReg();
1048 if (!regBKilled && isKilled(MI, regC, MRI, TII))
1049 // If C dies but B does not, swap the B and C operands.
1050 // This makes the live ranges of A and C joinable.
1052 else if (isProfitableToCommute(regA, regB, regC, &MI, mbbi, Dist)) {
1054 AggressiveCommute = true;
1059 // If it's profitable to commute, try to do so.
1060 if (TryCommute && CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
1062 if (AggressiveCommute)
1067 // If there is one more use of regB later in the same MBB, consider
1068 // re-schedule this MI below it.
1069 if (RescheduleMIBelowKill(mbbi, mi, nmi, regB)) {
1074 if (MI.isConvertibleTo3Addr()) {
1075 // This instruction is potentially convertible to a true
1076 // three-address instruction. Check if it is profitable.
1077 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
1078 // Try to convert it.
1079 if (ConvertInstTo3Addr(mi, nmi, mbbi, regA, regB, Dist)) {
1080 ++NumConvertedTo3Addr;
1081 return true; // Done with this instruction.
1086 // If there is one more use of regB later in the same MBB, consider
1087 // re-schedule it before this MI if it's legal.
1088 if (RescheduleKillAboveMI(mbbi, mi, nmi, regB)) {
1093 // If this is an instruction with a load folded into it, try unfolding
1094 // the load, e.g. avoid this:
1096 // addq (%rax), %rcx
1097 // in favor of this:
1098 // movq (%rax), %rcx
1100 // because it's preferable to schedule a load than a register copy.
1101 if (MI.mayLoad() && !regBKilled) {
1102 // Determine if a load can be unfolded.
1103 unsigned LoadRegIndex;
1105 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1106 /*UnfoldLoad=*/true,
1107 /*UnfoldStore=*/false,
1110 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1111 if (UnfoldMCID.getNumDefs() == 1) {
1113 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
1114 const TargetRegisterClass *RC =
1115 TRI->getAllocatableClass(
1116 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
1117 unsigned Reg = MRI->createVirtualRegister(RC);
1118 SmallVector<MachineInstr *, 2> NewMIs;
1119 if (!TII->unfoldMemoryOperand(*MF, &MI, Reg,
1120 /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
1122 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1125 assert(NewMIs.size() == 2 &&
1126 "Unfolded a load into multiple instructions!");
1127 // The load was previously folded, so this is the only use.
1128 NewMIs[1]->addRegisterKilled(Reg, TRI);
1130 // Tentatively insert the instructions into the block so that they
1131 // look "normal" to the transformation logic.
1132 mbbi->insert(mi, NewMIs[0]);
1133 mbbi->insert(mi, NewMIs[1]);
1135 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1136 << "2addr: NEW INST: " << *NewMIs[1]);
1138 // Transform the instruction, now that it no longer has a load.
1139 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1140 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1141 MachineBasicBlock::iterator NewMI = NewMIs[1];
1142 bool TransformSuccess =
1143 TryInstructionTransform(NewMI, mi, mbbi,
1144 NewSrcIdx, NewDstIdx, Dist, Processed);
1145 if (TransformSuccess ||
1146 NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1147 // Success, or at least we made an improvement. Keep the unfolded
1148 // instructions and discard the original.
1150 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1151 MachineOperand &MO = MI.getOperand(i);
1153 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1156 if (NewMIs[0]->killsRegister(MO.getReg()))
1157 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
1159 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1160 "Kill missing after load unfold!");
1161 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
1164 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
1165 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1166 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
1168 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1169 "Dead flag missing after load unfold!");
1170 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
1175 LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
1177 MI.eraseFromParent();
1179 if (TransformSuccess)
1182 // Transforming didn't eliminate the tie and didn't lead to an
1183 // improvement. Clean up the unfolded instructions and keep the
1185 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1186 NewMIs[0]->eraseFromParent();
1187 NewMIs[1]->eraseFromParent();
1196 // Collect tied operands of MI that need to be handled.
1197 // Rewrite trivial cases immediately.
1198 // Return true if any tied operands where found, including the trivial ones.
1199 bool TwoAddressInstructionPass::
1200 collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
1201 const MCInstrDesc &MCID = MI->getDesc();
1202 bool AnyOps = false;
1203 unsigned NumOps = MI->getNumOperands();
1205 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1206 unsigned DstIdx = 0;
1207 if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1210 MachineOperand &SrcMO = MI->getOperand(SrcIdx);
1211 MachineOperand &DstMO = MI->getOperand(DstIdx);
1212 unsigned SrcReg = SrcMO.getReg();
1213 unsigned DstReg = DstMO.getReg();
1214 // Tied constraint already satisfied?
1215 if (SrcReg == DstReg)
1218 assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
1220 // Deal with <undef> uses immediately - simply rewrite the src operand.
1221 if (SrcMO.isUndef()) {
1222 // Constrain the DstReg register class if required.
1223 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1224 if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
1226 MRI->constrainRegClass(DstReg, RC);
1227 SrcMO.setReg(DstReg);
1228 DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
1231 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
1236 // Process a list of tied MI operands that all use the same source register.
1237 // The tied pairs are of the form (SrcIdx, DstIdx).
1239 TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
1240 TiedPairList &TiedPairs,
1242 bool IsEarlyClobber = false;
1243 bool RemovedKillFlag = false;
1244 bool AllUsesCopied = true;
1245 unsigned LastCopiedReg = 0;
1247 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1248 unsigned SrcIdx = TiedPairs[tpi].first;
1249 unsigned DstIdx = TiedPairs[tpi].second;
1251 const MachineOperand &DstMO = MI->getOperand(DstIdx);
1252 unsigned RegA = DstMO.getReg();
1253 IsEarlyClobber |= DstMO.isEarlyClobber();
1255 // Grab RegB from the instruction because it may have changed if the
1256 // instruction was commuted.
1257 RegB = MI->getOperand(SrcIdx).getReg();
1260 // The register is tied to multiple destinations (or else we would
1261 // not have continued this far), but this use of the register
1262 // already matches the tied destination. Leave it.
1263 AllUsesCopied = false;
1266 LastCopiedReg = RegA;
1268 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1269 "cannot make instruction into two-address form");
1272 // First, verify that we don't have a use of "a" in the instruction
1273 // (a = b + a for example) because our transformation will not
1274 // work. This should never occur because we are in SSA form.
1275 for (unsigned i = 0; i != MI->getNumOperands(); ++i)
1276 assert(i == DstIdx ||
1277 !MI->getOperand(i).isReg() ||
1278 MI->getOperand(i).getReg() != RegA);
1282 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1283 TII->get(TargetOpcode::COPY), RegA).addReg(RegB);
1285 // Update DistanceMap.
1286 MachineBasicBlock::iterator PrevMI = MI;
1288 DistanceMap.insert(std::make_pair(PrevMI, Dist));
1289 DistanceMap[MI] = ++Dist;
1293 CopyIdx = Indexes->insertMachineInstrInMaps(PrevMI).getRegSlot();
1295 DEBUG(dbgs() << "\t\tprepend:\t" << *PrevMI);
1297 MachineOperand &MO = MI->getOperand(SrcIdx);
1298 assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
1299 "inconsistent operand info for 2-reg pass");
1301 MO.setIsKill(false);
1302 RemovedKillFlag = true;
1305 // Make sure regA is a legal regclass for the SrcIdx operand.
1306 if (TargetRegisterInfo::isVirtualRegister(RegA) &&
1307 TargetRegisterInfo::isVirtualRegister(RegB))
1308 MRI->constrainRegClass(RegA, MRI->getRegClass(RegB));
1312 // Propagate SrcRegMap.
1313 SrcRegMap[RegA] = RegB;
1317 if (AllUsesCopied) {
1318 if (!IsEarlyClobber) {
1319 // Replace other (un-tied) uses of regB with LastCopiedReg.
1320 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1321 MachineOperand &MO = MI->getOperand(i);
1322 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1324 MO.setIsKill(false);
1325 RemovedKillFlag = true;
1327 MO.setReg(LastCopiedReg);
1332 // Update live variables for regB.
1333 if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(MI)) {
1334 MachineBasicBlock::iterator PrevMI = MI;
1336 LV->addVirtualRegisterKilled(RegB, PrevMI);
1339 } else if (RemovedKillFlag) {
1340 // Some tied uses of regB matched their destination registers, so
1341 // regB is still used in this instruction, but a kill flag was
1342 // removed from a different tied use of regB, so now we need to add
1343 // a kill flag to one of the remaining uses of regB.
1344 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1345 MachineOperand &MO = MI->getOperand(i);
1346 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1354 /// runOnMachineFunction - Reduce two-address instructions to two operands.
1356 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
1358 const TargetMachine &TM = MF->getTarget();
1359 MRI = &MF->getRegInfo();
1360 TII = TM.getInstrInfo();
1361 TRI = TM.getRegisterInfo();
1362 InstrItins = TM.getInstrItineraryData();
1363 Indexes = getAnalysisIfAvailable<SlotIndexes>();
1364 LV = getAnalysisIfAvailable<LiveVariables>();
1365 LIS = getAnalysisIfAvailable<LiveIntervals>();
1366 AA = &getAnalysis<AliasAnalysis>();
1367 OptLevel = TM.getOptLevel();
1369 bool MadeChange = false;
1371 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
1372 DEBUG(dbgs() << "********** Function: "
1373 << MF->getName() << '\n');
1375 // This pass takes the function out of SSA form.
1378 TiedOperandMap TiedOperands;
1380 SmallPtrSet<MachineInstr*, 8> Processed;
1381 for (MachineFunction::iterator mbbi = MF->begin(), mbbe = MF->end();
1382 mbbi != mbbe; ++mbbi) {
1384 DistanceMap.clear();
1388 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
1390 MachineBasicBlock::iterator nmi = llvm::next(mi);
1391 if (mi->isDebugValue()) {
1396 // Remember REG_SEQUENCE instructions, we'll deal with them later.
1397 if (mi->isRegSequence())
1398 RegSequences.push_back(&*mi);
1400 DistanceMap.insert(std::make_pair(mi, ++Dist));
1402 ProcessCopy(&*mi, &*mbbi, Processed);
1404 // First scan through all the tied register uses in this instruction
1405 // and record a list of pairs of tied operands for each register.
1406 if (!collectTiedOperands(mi, TiedOperands)) {
1411 ++NumTwoAddressInstrs;
1413 DEBUG(dbgs() << '\t' << *mi);
1415 // If the instruction has a single pair of tied operands, try some
1416 // transformations that may either eliminate the tied operands or
1417 // improve the opportunities for coalescing away the register copy.
1418 if (TiedOperands.size() == 1) {
1419 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs
1420 = TiedOperands.begin()->second;
1421 if (TiedPairs.size() == 1) {
1422 unsigned SrcIdx = TiedPairs[0].first;
1423 unsigned DstIdx = TiedPairs[0].second;
1424 unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
1425 unsigned DstReg = mi->getOperand(DstIdx).getReg();
1426 if (SrcReg != DstReg &&
1427 TryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist,
1429 // The tied operands have been eliminated or shifted further down the
1430 // block to ease elimination. Continue processing with 'nmi'.
1431 TiedOperands.clear();
1438 // Now iterate over the information collected above.
1439 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1440 OE = TiedOperands.end(); OI != OE; ++OI) {
1441 processTiedPairs(mi, OI->second, Dist);
1442 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1445 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1446 if (mi->isInsertSubreg()) {
1447 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1448 // To %reg:subidx = COPY %subreg
1449 unsigned SubIdx = mi->getOperand(3).getImm();
1450 mi->RemoveOperand(3);
1451 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1452 mi->getOperand(0).setSubReg(SubIdx);
1453 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1454 mi->RemoveOperand(1);
1455 mi->setDesc(TII->get(TargetOpcode::COPY));
1456 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
1459 // Clear TiedOperands here instead of at the top of the loop
1460 // since most instructions do not have tied operands.
1461 TiedOperands.clear();
1466 // Eliminate REG_SEQUENCE instructions. Their whole purpose was to preseve
1467 // SSA form. It's now safe to de-SSA.
1468 MadeChange |= EliminateRegSequences();
1473 static void UpdateRegSequenceSrcs(unsigned SrcReg,
1474 unsigned DstReg, unsigned SubIdx,
1475 MachineRegisterInfo *MRI,
1476 const TargetRegisterInfo &TRI) {
1477 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg),
1478 RE = MRI->reg_end(); RI != RE; ) {
1479 MachineOperand &MO = RI.getOperand();
1481 MO.substVirtReg(DstReg, SubIdx, TRI);
1485 // Find the first def of Reg, assuming they are all in the same basic block.
1486 static MachineInstr *findFirstDef(unsigned Reg, MachineRegisterInfo *MRI) {
1487 SmallPtrSet<MachineInstr*, 8> Defs;
1488 MachineInstr *First = 0;
1489 for (MachineRegisterInfo::def_iterator RI = MRI->def_begin(Reg);
1490 MachineInstr *MI = RI.skipInstruction(); Defs.insert(MI))
1495 MachineBasicBlock *MBB = First->getParent();
1496 MachineBasicBlock::iterator A = First, B = First;
1500 if (A != MBB->begin()) {
1503 if (Defs.erase(A)) First = A;
1505 if (B != MBB->end()) {
1510 } while (Moving && !Defs.empty());
1511 assert(Defs.empty() && "Instructions outside basic block!");
1515 static bool HasOtherRegSequenceUses(unsigned Reg, MachineInstr *RegSeq,
1516 MachineRegisterInfo *MRI) {
1517 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
1518 UE = MRI->use_end(); UI != UE; ++UI) {
1519 MachineInstr *UseMI = &*UI;
1520 if (UseMI != RegSeq && UseMI->isRegSequence())
1526 /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
1527 /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
1528 /// sub-register references of the register defined by REG_SEQUENCE. e.g.
1530 /// %reg1029<def>, %reg1030<def> = VLD1q16 %reg1024<kill>, ...
1531 /// %reg1031<def> = REG_SEQUENCE %reg1029<kill>, 5, %reg1030<kill>, 6
1533 /// %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
1534 bool TwoAddressInstructionPass::EliminateRegSequences() {
1535 if (RegSequences.empty())
1538 for (unsigned i = 0, e = RegSequences.size(); i != e; ++i) {
1539 MachineInstr *MI = RegSequences[i];
1540 unsigned DstReg = MI->getOperand(0).getReg();
1541 if (MI->getOperand(0).getSubReg() ||
1542 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1543 !(MI->getNumOperands() & 1)) {
1544 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1545 llvm_unreachable(0);
1548 bool IsImpDef = true;
1549 SmallVector<unsigned, 4> RealSrcs;
1550 SmallSet<unsigned, 4> Seen;
1551 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1552 // Nothing needs to be inserted for <undef> operands.
1553 if (MI->getOperand(i).isUndef()) {
1554 MI->getOperand(i).setReg(0);
1557 unsigned SrcReg = MI->getOperand(i).getReg();
1558 unsigned SrcSubIdx = MI->getOperand(i).getSubReg();
1559 unsigned SubIdx = MI->getOperand(i+1).getImm();
1560 // DefMI of NULL means the value does not have a vreg in this block
1561 // i.e., its a physical register or a subreg.
1562 // In either case we force a copy to be generated.
1563 MachineInstr *DefMI = NULL;
1564 if (!MI->getOperand(i).getSubReg() &&
1565 !TargetRegisterInfo::isPhysicalRegister(SrcReg)) {
1566 DefMI = MRI->getUniqueVRegDef(SrcReg);
1569 if (DefMI && DefMI->isImplicitDef()) {
1570 DefMI->eraseFromParent();
1575 // Remember COPY sources. These might be candidate for coalescing.
1576 if (DefMI && DefMI->isCopy() && DefMI->getOperand(1).getSubReg())
1577 RealSrcs.push_back(DefMI->getOperand(1).getReg());
1579 bool isKill = MI->getOperand(i).isKill();
1580 if (!DefMI || !Seen.insert(SrcReg) ||
1581 MI->getParent() != DefMI->getParent() ||
1582 !isKill || HasOtherRegSequenceUses(SrcReg, MI, MRI) ||
1583 !TRI->getMatchingSuperRegClass(MRI->getRegClass(DstReg),
1584 MRI->getRegClass(SrcReg), SubIdx)) {
1585 // REG_SEQUENCE cannot have duplicated operands, add a copy.
1586 // Also add an copy if the source is live-in the block. We don't want
1587 // to end up with a partial-redef of a livein, e.g.
1589 // reg1051:10<def> =
1595 // LiveIntervalAnalysis won't like it.
1597 // If the REG_SEQUENCE doesn't kill its source, keeping live variables
1598 // correctly up to date becomes very difficult. Insert a copy.
1600 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1601 // might insert a COPY that uses SrcReg after is was killed.
1603 for (unsigned j = i + 2; j < e; j += 2)
1604 if (MI->getOperand(j).getReg() == SrcReg) {
1605 MI->getOperand(j).setIsKill();
1610 MachineBasicBlock::iterator InsertLoc = MI;
1611 MachineInstr *CopyMI = BuildMI(*MI->getParent(), InsertLoc,
1612 MI->getDebugLoc(), TII->get(TargetOpcode::COPY))
1613 .addReg(DstReg, RegState::Define, SubIdx)
1614 .addReg(SrcReg, getKillRegState(isKill), SrcSubIdx);
1615 MI->getOperand(i).setReg(0);
1616 if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
1617 LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1618 DEBUG(dbgs() << "Inserted: " << *CopyMI);
1622 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1623 unsigned SrcReg = MI->getOperand(i).getReg();
1624 if (!SrcReg) continue;
1625 unsigned SubIdx = MI->getOperand(i+1).getImm();
1626 UpdateRegSequenceSrcs(SrcReg, DstReg, SubIdx, MRI, *TRI);
1629 // Set <def,undef> flags on the first DstReg def in the basic block.
1630 // It marks the beginning of the live range. All the other defs are
1631 // read-modify-write.
1632 if (MachineInstr *Def = findFirstDef(DstReg, MRI)) {
1633 for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
1634 MachineOperand &MO = Def->getOperand(i);
1635 if (MO.isReg() && MO.isDef() && MO.getReg() == DstReg)
1638 DEBUG(dbgs() << "First def: " << *Def);
1642 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1643 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1644 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
1645 MI->RemoveOperand(j);
1647 DEBUG(dbgs() << "Eliminated: " << *MI);
1648 MI->eraseFromParent();
1652 RegSequences.clear();