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 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/ADT/BitVector.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/SmallSet.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
38 #include "llvm/CodeGen/LiveVariables.h"
39 #include "llvm/CodeGen/MachineFunctionPass.h"
40 #include "llvm/CodeGen/MachineInstr.h"
41 #include "llvm/CodeGen/MachineInstrBuilder.h"
42 #include "llvm/CodeGen/MachineRegisterInfo.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/MC/MCInstrItineraries.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Target/TargetInstrInfo.h"
49 #include "llvm/Target/TargetMachine.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
51 #include "llvm/Target/TargetSubtargetInfo.h"
54 #define DEBUG_TYPE "twoaddrinstr"
56 STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
57 STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
58 STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
59 STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
60 STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
61 STATISTIC(NumReSchedUps, "Number of instructions re-scheduled up");
62 STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down");
64 // Temporary flag to disable rescheduling.
66 EnableRescheduling("twoaddr-reschedule",
67 cl::desc("Coalesce copies by rescheduling (default=true)"),
68 cl::init(true), cl::Hidden);
71 class TwoAddressInstructionPass : public MachineFunctionPass {
73 const TargetInstrInfo *TII;
74 const TargetRegisterInfo *TRI;
75 const InstrItineraryData *InstrItins;
76 MachineRegisterInfo *MRI;
80 CodeGenOpt::Level OptLevel;
82 // The current basic block being processed.
83 MachineBasicBlock *MBB;
85 // DistanceMap - Keep track the distance of a MI from the start of the
86 // current basic block.
87 DenseMap<MachineInstr*, unsigned> DistanceMap;
89 // Set of already processed instructions in the current block.
90 SmallPtrSet<MachineInstr*, 8> Processed;
92 // SrcRegMap - A map from virtual registers to physical registers which are
93 // likely targets to be coalesced to due to copies from physical registers to
94 // virtual registers. e.g. v1024 = move r0.
95 DenseMap<unsigned, unsigned> SrcRegMap;
97 // DstRegMap - A map from virtual registers to physical registers which are
98 // likely targets to be coalesced to due to copies to physical registers from
99 // virtual registers. e.g. r1 = move v1024.
100 DenseMap<unsigned, unsigned> DstRegMap;
102 bool sink3AddrInstruction(MachineInstr *MI, unsigned Reg,
103 MachineBasicBlock::iterator OldPos);
105 bool isRevCopyChain(unsigned FromReg, unsigned ToReg, int Maxlen);
107 bool noUseAfterLastDef(unsigned Reg, unsigned Dist, unsigned &LastDef);
109 bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
110 MachineInstr *MI, unsigned Dist);
112 bool commuteInstruction(MachineBasicBlock::iterator &mi,
113 unsigned RegB, unsigned RegC, unsigned Dist);
115 bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
117 bool convertInstTo3Addr(MachineBasicBlock::iterator &mi,
118 MachineBasicBlock::iterator &nmi,
119 unsigned RegA, unsigned RegB, unsigned Dist);
121 bool isDefTooClose(unsigned Reg, unsigned Dist, MachineInstr *MI);
123 bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
124 MachineBasicBlock::iterator &nmi,
126 bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
127 MachineBasicBlock::iterator &nmi,
130 bool tryInstructionTransform(MachineBasicBlock::iterator &mi,
131 MachineBasicBlock::iterator &nmi,
132 unsigned SrcIdx, unsigned DstIdx,
133 unsigned Dist, bool shouldOnlyCommute);
135 void scanUses(unsigned DstReg);
137 void processCopy(MachineInstr *MI);
139 typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList;
140 typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap;
141 bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
142 void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
143 void eliminateRegSequence(MachineBasicBlock::iterator&);
146 static char ID; // Pass identification, replacement for typeid
147 TwoAddressInstructionPass() : MachineFunctionPass(ID) {
148 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
151 void getAnalysisUsage(AnalysisUsage &AU) const override {
152 AU.setPreservesCFG();
153 AU.addRequired<AliasAnalysis>();
154 AU.addPreserved<LiveVariables>();
155 AU.addPreserved<SlotIndexes>();
156 AU.addPreserved<LiveIntervals>();
157 AU.addPreservedID(MachineLoopInfoID);
158 AU.addPreservedID(MachineDominatorsID);
159 MachineFunctionPass::getAnalysisUsage(AU);
162 /// runOnMachineFunction - Pass entry point.
163 bool runOnMachineFunction(MachineFunction&) override;
165 } // end anonymous namespace
167 char TwoAddressInstructionPass::ID = 0;
168 INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
169 "Two-Address instruction pass", false, false)
170 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
171 INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
172 "Two-Address instruction pass", false, false)
174 char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
176 static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg, LiveIntervals *LIS);
178 /// sink3AddrInstruction - A two-address instruction has been converted to a
179 /// three-address instruction to avoid clobbering a register. Try to sink it
180 /// past the instruction that would kill the above mentioned register to reduce
181 /// register pressure.
182 bool TwoAddressInstructionPass::
183 sink3AddrInstruction(MachineInstr *MI, unsigned SavedReg,
184 MachineBasicBlock::iterator OldPos) {
185 // FIXME: Shouldn't we be trying to do this before we three-addressify the
186 // instruction? After this transformation is done, we no longer need
187 // the instruction to be in three-address form.
189 // Check if it's safe to move this instruction.
190 bool SeenStore = true; // Be conservative.
191 if (!MI->isSafeToMove(TII, AA, SeenStore))
195 SmallSet<unsigned, 4> UseRegs;
197 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
198 const MachineOperand &MO = MI->getOperand(i);
201 unsigned MOReg = MO.getReg();
204 if (MO.isUse() && MOReg != SavedReg)
205 UseRegs.insert(MO.getReg());
209 // Don't try to move it if it implicitly defines a register.
212 // For now, don't move any instructions that define multiple registers.
214 DefReg = MO.getReg();
217 // Find the instruction that kills SavedReg.
218 MachineInstr *KillMI = nullptr;
220 LiveInterval &LI = LIS->getInterval(SavedReg);
221 assert(LI.end() != LI.begin() &&
222 "Reg should not have empty live interval.");
224 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
225 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
226 if (I != LI.end() && I->start < MBBEndIdx)
230 KillMI = LIS->getInstructionFromIndex(I->end);
233 for (MachineRegisterInfo::use_nodbg_iterator
234 UI = MRI->use_nodbg_begin(SavedReg),
235 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
236 MachineOperand &UseMO = *UI;
239 KillMI = UseMO.getParent();
244 // If we find the instruction that kills SavedReg, and it is in an
245 // appropriate location, we can try to sink the current instruction
247 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
248 KillMI == OldPos || KillMI->isTerminator())
251 // If any of the definitions are used by another instruction between the
252 // position and the kill use, then it's not safe to sink it.
254 // FIXME: This can be sped up if there is an easy way to query whether an
255 // instruction is before or after another instruction. Then we can use
256 // MachineRegisterInfo def / use instead.
257 MachineOperand *KillMO = nullptr;
258 MachineBasicBlock::iterator KillPos = KillMI;
261 unsigned NumVisited = 0;
262 for (MachineBasicBlock::iterator I = std::next(OldPos); I != KillPos; ++I) {
263 MachineInstr *OtherMI = I;
264 // DBG_VALUE cannot be counted against the limit.
265 if (OtherMI->isDebugValue())
267 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
270 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
271 MachineOperand &MO = OtherMI->getOperand(i);
274 unsigned MOReg = MO.getReg();
280 if (MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))) {
281 if (OtherMI == KillMI && MOReg == SavedReg)
282 // Save the operand that kills the register. We want to unset the kill
283 // marker if we can sink MI past it.
285 else if (UseRegs.count(MOReg))
286 // One of the uses is killed before the destination.
291 assert(KillMO && "Didn't find kill");
294 // Update kill and LV information.
295 KillMO->setIsKill(false);
296 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
297 KillMO->setIsKill(true);
300 LV->replaceKillInstruction(SavedReg, KillMI, MI);
303 // Move instruction to its destination.
305 MBB->insert(KillPos, MI);
314 /// getSingleDef -- return the MachineInstr* if it is the single def of the Reg
316 static MachineInstr *getSingleDef(unsigned Reg, MachineBasicBlock *BB,
317 const MachineRegisterInfo *MRI) {
318 MachineInstr *Ret = nullptr;
319 for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
320 if (DefMI.getParent() != BB || DefMI.isDebugValue())
324 else if (Ret != &DefMI)
330 /// Check if there is a reversed copy chain from FromReg to ToReg:
331 /// %Tmp1 = copy %Tmp2;
332 /// %FromReg = copy %Tmp1;
333 /// %ToReg = add %FromReg ...
334 /// %Tmp2 = copy %ToReg;
335 /// MaxLen specifies the maximum length of the copy chain the func
336 /// can walk through.
337 bool TwoAddressInstructionPass::isRevCopyChain(unsigned FromReg, unsigned ToReg,
339 unsigned TmpReg = FromReg;
340 for (int i = 0; i < Maxlen; i++) {
341 MachineInstr *Def = getSingleDef(TmpReg, MBB, MRI);
342 if (!Def || !Def->isCopy())
345 TmpReg = Def->getOperand(1).getReg();
353 /// noUseAfterLastDef - Return true if there are no intervening uses between the
354 /// last instruction in the MBB that defines the specified register and the
355 /// two-address instruction which is being processed. It also returns the last
356 /// def location by reference
357 bool TwoAddressInstructionPass::noUseAfterLastDef(unsigned Reg, unsigned Dist,
360 unsigned LastUse = Dist;
361 for (MachineOperand &MO : MRI->reg_operands(Reg)) {
362 MachineInstr *MI = MO.getParent();
363 if (MI->getParent() != MBB || MI->isDebugValue())
365 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
366 if (DI == DistanceMap.end())
368 if (MO.isUse() && DI->second < LastUse)
369 LastUse = DI->second;
370 if (MO.isDef() && DI->second > LastDef)
371 LastDef = DI->second;
374 return !(LastUse > LastDef && LastUse < Dist);
377 /// isCopyToReg - Return true if the specified MI is a copy instruction or
378 /// a extract_subreg instruction. It also returns the source and destination
379 /// registers and whether they are physical registers by reference.
380 static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
381 unsigned &SrcReg, unsigned &DstReg,
382 bool &IsSrcPhys, bool &IsDstPhys) {
386 DstReg = MI.getOperand(0).getReg();
387 SrcReg = MI.getOperand(1).getReg();
388 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
389 DstReg = MI.getOperand(0).getReg();
390 SrcReg = MI.getOperand(2).getReg();
394 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
395 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
399 /// isPLainlyKilled - Test if the given register value, which is used by the
400 // given instruction, is killed by the given instruction.
401 static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg,
402 LiveIntervals *LIS) {
403 if (LIS && TargetRegisterInfo::isVirtualRegister(Reg) &&
404 !LIS->isNotInMIMap(MI)) {
405 // FIXME: Sometimes tryInstructionTransform() will add instructions and
406 // test whether they can be folded before keeping them. In this case it
407 // sets a kill before recursively calling tryInstructionTransform() again.
408 // If there is no interval available, we assume that this instruction is
409 // one of those. A kill flag is manually inserted on the operand so the
410 // check below will handle it.
411 LiveInterval &LI = LIS->getInterval(Reg);
412 // This is to match the kill flag version where undefs don't have kill
414 if (!LI.hasAtLeastOneValue())
417 SlotIndex useIdx = LIS->getInstructionIndex(MI);
418 LiveInterval::const_iterator I = LI.find(useIdx);
419 assert(I != LI.end() && "Reg must be live-in to use.");
420 return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx);
423 return MI->killsRegister(Reg);
426 /// isKilled - Test if the given register value, which is used by the given
427 /// instruction, is killed by the given instruction. This looks through
428 /// coalescable copies to see if the original value is potentially not killed.
430 /// For example, in this code:
432 /// %reg1034 = copy %reg1024
433 /// %reg1035 = copy %reg1025<kill>
434 /// %reg1036 = add %reg1034<kill>, %reg1035<kill>
436 /// %reg1034 is not considered to be killed, since it is copied from a
437 /// register which is not killed. Treating it as not killed lets the
438 /// normal heuristics commute the (two-address) add, which lets
439 /// coalescing eliminate the extra copy.
441 /// If allowFalsePositives is true then likely kills are treated as kills even
442 /// if it can't be proven that they are kills.
443 static bool isKilled(MachineInstr &MI, unsigned Reg,
444 const MachineRegisterInfo *MRI,
445 const TargetInstrInfo *TII,
447 bool allowFalsePositives) {
448 MachineInstr *DefMI = &MI;
450 // All uses of physical registers are likely to be kills.
451 if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
452 (allowFalsePositives || MRI->hasOneUse(Reg)))
454 if (!isPlainlyKilled(DefMI, Reg, LIS))
456 if (TargetRegisterInfo::isPhysicalRegister(Reg))
458 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
459 // If there are multiple defs, we can't do a simple analysis, so just
460 // go with what the kill flag says.
461 if (std::next(Begin) != MRI->def_end())
463 DefMI = Begin->getParent();
464 bool IsSrcPhys, IsDstPhys;
465 unsigned SrcReg, DstReg;
466 // If the def is something other than a copy, then it isn't going to
467 // be coalesced, so follow the kill flag.
468 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
474 /// isTwoAddrUse - Return true if the specified MI uses the specified register
475 /// as a two-address use. If so, return the destination register by reference.
476 static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
477 for (unsigned i = 0, NumOps = MI.getNumOperands(); i != NumOps; ++i) {
478 const MachineOperand &MO = MI.getOperand(i);
479 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
482 if (MI.isRegTiedToDefOperand(i, &ti)) {
483 DstReg = MI.getOperand(ti).getReg();
490 /// findOnlyInterestingUse - Given a register, if has a single in-basic block
491 /// use, return the use instruction if it's a copy or a two-address use.
493 MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
494 MachineRegisterInfo *MRI,
495 const TargetInstrInfo *TII,
497 unsigned &DstReg, bool &IsDstPhys) {
498 if (!MRI->hasOneNonDBGUse(Reg))
499 // None or more than one use.
501 MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(Reg);
502 if (UseMI.getParent() != MBB)
506 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
511 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
512 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
518 /// getMappedReg - Return the physical register the specified virtual register
519 /// might be mapped to.
521 getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
522 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
523 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
524 if (SI == RegMap.end())
528 if (TargetRegisterInfo::isPhysicalRegister(Reg))
533 /// regsAreCompatible - Return true if the two registers are equal or aliased.
536 regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
541 return TRI->regsOverlap(RegA, RegB);
545 /// isProfitableToCommute - Return true if it's potentially profitable to commute
546 /// the two-address instruction that's being processed.
548 TwoAddressInstructionPass::
549 isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
550 MachineInstr *MI, unsigned Dist) {
551 if (OptLevel == CodeGenOpt::None)
554 // Determine if it's profitable to commute this two address instruction. In
555 // general, we want no uses between this instruction and the definition of
556 // the two-address register.
558 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
559 // %reg1029<def> = MOV8rr %reg1028
560 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
561 // insert => %reg1030<def> = MOV8rr %reg1028
562 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
563 // In this case, it might not be possible to coalesce the second MOV8rr
564 // instruction if the first one is coalesced. So it would be profitable to
566 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
567 // %reg1029<def> = MOV8rr %reg1028
568 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
569 // insert => %reg1030<def> = MOV8rr %reg1029
570 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
572 if (!isPlainlyKilled(MI, regC, LIS))
575 // Ok, we have something like:
576 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
577 // let's see if it's worth commuting it.
579 // Look for situations like this:
580 // %reg1024<def> = MOV r1
581 // %reg1025<def> = MOV r0
582 // %reg1026<def> = ADD %reg1024, %reg1025
584 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
585 unsigned ToRegA = getMappedReg(regA, DstRegMap);
587 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
588 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
589 bool CompB = FromRegB && regsAreCompatible(FromRegB, ToRegA, TRI);
590 bool CompC = FromRegC && regsAreCompatible(FromRegC, ToRegA, TRI);
592 // Compute if any of the following are true:
593 // -RegB is not tied to a register and RegC is compatible with RegA.
594 // -RegB is tied to the wrong physical register, but RegC is.
595 // -RegB is tied to the wrong physical register, and RegC isn't tied.
596 if ((!FromRegB && CompC) || (FromRegB && !CompB && (!FromRegC || CompC)))
598 // Don't compute if any of the following are true:
599 // -RegC is not tied to a register and RegB is compatible with RegA.
600 // -RegC is tied to the wrong physical register, but RegB is.
601 // -RegC is tied to the wrong physical register, and RegB isn't tied.
602 if ((!FromRegC && CompB) || (FromRegC && !CompC && (!FromRegB || CompB)))
606 // If there is a use of regC between its last def (could be livein) and this
607 // instruction, then bail.
608 unsigned LastDefC = 0;
609 if (!noUseAfterLastDef(regC, Dist, LastDefC))
612 // If there is a use of regB between its last def (could be livein) and this
613 // instruction, then go ahead and make this transformation.
614 unsigned LastDefB = 0;
615 if (!noUseAfterLastDef(regB, Dist, LastDefB))
618 // Look for situation like this:
619 // %reg101 = MOV %reg100
621 // %reg103 = ADD %reg102, %reg101
623 // %reg100 = MOV %reg103
624 // If there is a reversed copy chain from reg101 to reg103, commute the ADD
625 // to eliminate an otherwise unavoidable copy.
627 // We can extend the logic further: If an pair of operands in an insn has
628 // been merged, the insn could be regarded as a virtual copy, and the virtual
629 // copy could also be used to construct a copy chain.
630 // To more generally minimize register copies, ideally the logic of two addr
631 // instruction pass should be integrated with register allocation pass where
632 // interference graph is available.
633 if (isRevCopyChain(regC, regA, 3))
636 if (isRevCopyChain(regB, regA, 3))
639 // Since there are no intervening uses for both registers, then commute
640 // if the def of regC is closer. Its live interval is shorter.
641 return LastDefB && LastDefC && LastDefC > LastDefB;
644 /// commuteInstruction - Commute a two-address instruction and update the basic
645 /// block, distance map, and live variables if needed. Return true if it is
647 bool TwoAddressInstructionPass::
648 commuteInstruction(MachineBasicBlock::iterator &mi,
649 unsigned RegB, unsigned RegC, unsigned Dist) {
650 MachineInstr *MI = mi;
651 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
652 MachineInstr *NewMI = TII->commuteInstruction(MI);
654 if (NewMI == nullptr) {
655 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
659 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
660 assert(NewMI == MI &&
661 "TargetInstrInfo::commuteInstruction() should not return a new "
662 "instruction unless it was requested.");
664 // Update source register map.
665 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
667 unsigned RegA = MI->getOperand(0).getReg();
668 SrcRegMap[RegA] = FromRegC;
674 /// isProfitableToConv3Addr - Return true if it is profitable to convert the
675 /// given 2-address instruction to a 3-address one.
677 TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
678 // Look for situations like this:
679 // %reg1024<def> = MOV r1
680 // %reg1025<def> = MOV r0
681 // %reg1026<def> = ADD %reg1024, %reg1025
683 // Turn ADD into a 3-address instruction to avoid a copy.
684 unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
687 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
688 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
691 /// convertInstTo3Addr - Convert the specified two-address instruction into a
692 /// three address one. Return true if this transformation was successful.
694 TwoAddressInstructionPass::convertInstTo3Addr(MachineBasicBlock::iterator &mi,
695 MachineBasicBlock::iterator &nmi,
696 unsigned RegA, unsigned RegB,
698 // FIXME: Why does convertToThreeAddress() need an iterator reference?
699 MachineFunction::iterator MFI = MBB;
700 MachineInstr *NewMI = TII->convertToThreeAddress(MFI, mi, LV);
701 assert(MBB == MFI && "convertToThreeAddress changed iterator reference");
705 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
706 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
710 LIS->ReplaceMachineInstrInMaps(mi, NewMI);
712 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
713 // FIXME: Temporary workaround. If the new instruction doesn't
714 // uses RegB, convertToThreeAddress must have created more
715 // then one instruction.
716 Sunk = sink3AddrInstruction(NewMI, RegB, mi);
718 MBB->erase(mi); // Nuke the old inst.
721 DistanceMap.insert(std::make_pair(NewMI, Dist));
726 // Update source and destination register maps.
727 SrcRegMap.erase(RegA);
728 DstRegMap.erase(RegB);
732 /// scanUses - Scan forward recursively for only uses, update maps if the use
733 /// is a copy or a two-address instruction.
735 TwoAddressInstructionPass::scanUses(unsigned DstReg) {
736 SmallVector<unsigned, 4> VirtRegPairs;
740 unsigned Reg = DstReg;
741 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
742 NewReg, IsDstPhys)) {
743 if (IsCopy && !Processed.insert(UseMI).second)
746 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
747 if (DI != DistanceMap.end())
748 // Earlier in the same MBB.Reached via a back edge.
752 VirtRegPairs.push_back(NewReg);
755 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
757 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
758 VirtRegPairs.push_back(NewReg);
762 if (!VirtRegPairs.empty()) {
763 unsigned ToReg = VirtRegPairs.back();
764 VirtRegPairs.pop_back();
765 while (!VirtRegPairs.empty()) {
766 unsigned FromReg = VirtRegPairs.back();
767 VirtRegPairs.pop_back();
768 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
770 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
773 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
775 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
779 /// processCopy - If the specified instruction is not yet processed, process it
780 /// if it's a copy. For a copy instruction, we find the physical registers the
781 /// source and destination registers might be mapped to. These are kept in
782 /// point-to maps used to determine future optimizations. e.g.
785 /// v1026 = add v1024, v1025
787 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
788 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
789 /// potentially joined with r1 on the output side. It's worthwhile to commute
790 /// 'add' to eliminate a copy.
791 void TwoAddressInstructionPass::processCopy(MachineInstr *MI) {
792 if (Processed.count(MI))
795 bool IsSrcPhys, IsDstPhys;
796 unsigned SrcReg, DstReg;
797 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
800 if (IsDstPhys && !IsSrcPhys)
801 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
802 else if (!IsDstPhys && IsSrcPhys) {
803 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
805 assert(SrcRegMap[DstReg] == SrcReg &&
806 "Can't map to two src physical registers!");
811 Processed.insert(MI);
815 /// rescheduleMIBelowKill - If there is one more local instruction that reads
816 /// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
817 /// instruction in order to eliminate the need for the copy.
818 bool TwoAddressInstructionPass::
819 rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
820 MachineBasicBlock::iterator &nmi,
822 // Bail immediately if we don't have LV or LIS available. We use them to find
823 // kills efficiently.
827 MachineInstr *MI = &*mi;
828 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
829 if (DI == DistanceMap.end())
830 // Must be created from unfolded load. Don't waste time trying this.
833 MachineInstr *KillMI = nullptr;
835 LiveInterval &LI = LIS->getInterval(Reg);
836 assert(LI.end() != LI.begin() &&
837 "Reg should not have empty live interval.");
839 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
840 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
841 if (I != LI.end() && I->start < MBBEndIdx)
845 KillMI = LIS->getInstructionFromIndex(I->end);
847 KillMI = LV->getVarInfo(Reg).findKill(MBB);
849 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
850 // Don't mess with copies, they may be coalesced later.
853 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
854 KillMI->isBranch() || KillMI->isTerminator())
855 // Don't move pass calls, etc.
859 if (isTwoAddrUse(*KillMI, Reg, DstReg))
862 bool SeenStore = true;
863 if (!MI->isSafeToMove(TII, AA, SeenStore))
866 if (TII->getInstrLatency(InstrItins, MI) > 1)
867 // FIXME: Needs more sophisticated heuristics.
870 SmallSet<unsigned, 2> Uses;
871 SmallSet<unsigned, 2> Kills;
872 SmallSet<unsigned, 2> Defs;
873 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
874 const MachineOperand &MO = MI->getOperand(i);
877 unsigned MOReg = MO.getReg();
884 if (MOReg != Reg && (MO.isKill() ||
885 (LIS && isPlainlyKilled(MI, MOReg, LIS))))
890 // Move the copies connected to MI down as well.
891 MachineBasicBlock::iterator Begin = MI;
892 MachineBasicBlock::iterator AfterMI = std::next(Begin);
894 MachineBasicBlock::iterator End = AfterMI;
895 while (End->isCopy() && Defs.count(End->getOperand(1).getReg())) {
896 Defs.insert(End->getOperand(0).getReg());
900 // Check if the reschedule will not break depedencies.
901 unsigned NumVisited = 0;
902 MachineBasicBlock::iterator KillPos = KillMI;
904 for (MachineBasicBlock::iterator I = End; I != KillPos; ++I) {
905 MachineInstr *OtherMI = I;
906 // DBG_VALUE cannot be counted against the limit.
907 if (OtherMI->isDebugValue())
909 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
912 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
913 OtherMI->isBranch() || OtherMI->isTerminator())
914 // Don't move pass calls, etc.
916 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
917 const MachineOperand &MO = OtherMI->getOperand(i);
920 unsigned MOReg = MO.getReg();
924 if (Uses.count(MOReg))
925 // Physical register use would be clobbered.
927 if (!MO.isDead() && Defs.count(MOReg))
928 // May clobber a physical register def.
929 // FIXME: This may be too conservative. It's ok if the instruction
930 // is sunken completely below the use.
933 if (Defs.count(MOReg))
935 bool isKill = MO.isKill() ||
936 (LIS && isPlainlyKilled(OtherMI, MOReg, LIS));
938 ((isKill && Uses.count(MOReg)) || Kills.count(MOReg)))
939 // Don't want to extend other live ranges and update kills.
941 if (MOReg == Reg && !isKill)
942 // We can't schedule across a use of the register in question.
944 // Ensure that if this is register in question, its the kill we expect.
945 assert((MOReg != Reg || OtherMI == KillMI) &&
946 "Found multiple kills of a register in a basic block");
951 // Move debug info as well.
952 while (Begin != MBB->begin() && std::prev(Begin)->isDebugValue())
956 MachineBasicBlock::iterator InsertPos = KillPos;
958 // We have to move the copies first so that the MBB is still well-formed
959 // when calling handleMove().
960 for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) {
961 MachineInstr *CopyMI = MBBI;
963 MBB->splice(InsertPos, MBB, CopyMI);
964 LIS->handleMove(CopyMI);
967 End = std::next(MachineBasicBlock::iterator(MI));
970 // Copies following MI may have been moved as well.
971 MBB->splice(InsertPos, MBB, Begin, End);
972 DistanceMap.erase(DI);
974 // Update live variables
978 LV->removeVirtualRegisterKilled(Reg, KillMI);
979 LV->addVirtualRegisterKilled(Reg, MI);
982 DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
986 /// isDefTooClose - Return true if the re-scheduling will put the given
987 /// instruction too close to the defs of its register dependencies.
988 bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
990 for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
991 if (DefMI.getParent() != MBB || DefMI.isCopy() || DefMI.isCopyLike())
994 return true; // MI is defining something KillMI uses
995 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(&DefMI);
996 if (DDI == DistanceMap.end())
997 return true; // Below MI
998 unsigned DefDist = DDI->second;
999 assert(Dist > DefDist && "Visited def already?");
1000 if (TII->getInstrLatency(InstrItins, &DefMI) > (Dist - DefDist))
1006 /// rescheduleKillAboveMI - If there is one more local instruction that reads
1007 /// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
1008 /// current two-address instruction in order to eliminate the need for the
1010 bool TwoAddressInstructionPass::
1011 rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
1012 MachineBasicBlock::iterator &nmi,
1014 // Bail immediately if we don't have LV or LIS available. We use them to find
1015 // kills efficiently.
1019 MachineInstr *MI = &*mi;
1020 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
1021 if (DI == DistanceMap.end())
1022 // Must be created from unfolded load. Don't waste time trying this.
1025 MachineInstr *KillMI = nullptr;
1027 LiveInterval &LI = LIS->getInterval(Reg);
1028 assert(LI.end() != LI.begin() &&
1029 "Reg should not have empty live interval.");
1031 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
1032 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
1033 if (I != LI.end() && I->start < MBBEndIdx)
1037 KillMI = LIS->getInstructionFromIndex(I->end);
1039 KillMI = LV->getVarInfo(Reg).findKill(MBB);
1041 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
1042 // Don't mess with copies, they may be coalesced later.
1046 if (isTwoAddrUse(*KillMI, Reg, DstReg))
1049 bool SeenStore = true;
1050 if (!KillMI->isSafeToMove(TII, AA, SeenStore))
1053 SmallSet<unsigned, 2> Uses;
1054 SmallSet<unsigned, 2> Kills;
1055 SmallSet<unsigned, 2> Defs;
1056 SmallSet<unsigned, 2> LiveDefs;
1057 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
1058 const MachineOperand &MO = KillMI->getOperand(i);
1061 unsigned MOReg = MO.getReg();
1065 if (isDefTooClose(MOReg, DI->second, MI))
1067 bool isKill = MO.isKill() || (LIS && isPlainlyKilled(KillMI, MOReg, LIS));
1068 if (MOReg == Reg && !isKill)
1071 if (isKill && MOReg != Reg)
1072 Kills.insert(MOReg);
1073 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1076 LiveDefs.insert(MOReg);
1080 // Check if the reschedule will not break depedencies.
1081 unsigned NumVisited = 0;
1082 MachineBasicBlock::iterator KillPos = KillMI;
1083 for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
1084 MachineInstr *OtherMI = I;
1085 // DBG_VALUE cannot be counted against the limit.
1086 if (OtherMI->isDebugValue())
1088 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
1091 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
1092 OtherMI->isBranch() || OtherMI->isTerminator())
1093 // Don't move pass calls, etc.
1095 SmallVector<unsigned, 2> OtherDefs;
1096 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
1097 const MachineOperand &MO = OtherMI->getOperand(i);
1100 unsigned MOReg = MO.getReg();
1104 if (Defs.count(MOReg))
1105 // Moving KillMI can clobber the physical register if the def has
1108 if (Kills.count(MOReg))
1109 // Don't want to extend other live ranges and update kills.
1111 if (OtherMI != MI && MOReg == Reg &&
1112 !(MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))))
1113 // We can't schedule across a use of the register in question.
1116 OtherDefs.push_back(MOReg);
1120 for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
1121 unsigned MOReg = OtherDefs[i];
1122 if (Uses.count(MOReg))
1124 if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1125 LiveDefs.count(MOReg))
1127 // Physical register def is seen.
1132 // Move the old kill above MI, don't forget to move debug info as well.
1133 MachineBasicBlock::iterator InsertPos = mi;
1134 while (InsertPos != MBB->begin() && std::prev(InsertPos)->isDebugValue())
1136 MachineBasicBlock::iterator From = KillMI;
1137 MachineBasicBlock::iterator To = std::next(From);
1138 while (std::prev(From)->isDebugValue())
1140 MBB->splice(InsertPos, MBB, From, To);
1142 nmi = std::prev(InsertPos); // Backtrack so we process the moved instr.
1143 DistanceMap.erase(DI);
1145 // Update live variables
1147 LIS->handleMove(KillMI);
1149 LV->removeVirtualRegisterKilled(Reg, KillMI);
1150 LV->addVirtualRegisterKilled(Reg, MI);
1153 DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
1157 /// tryInstructionTransform - For the case where an instruction has a single
1158 /// pair of tied register operands, attempt some transformations that may
1159 /// either eliminate the tied operands or improve the opportunities for
1160 /// coalescing away the register copy. Returns true if no copy needs to be
1161 /// inserted to untie mi's operands (either because they were untied, or
1162 /// because mi was rescheduled, and will be visited again later). If the
1163 /// shouldOnlyCommute flag is true, only instruction commutation is attempted.
1164 bool TwoAddressInstructionPass::
1165 tryInstructionTransform(MachineBasicBlock::iterator &mi,
1166 MachineBasicBlock::iterator &nmi,
1167 unsigned SrcIdx, unsigned DstIdx,
1168 unsigned Dist, bool shouldOnlyCommute) {
1169 if (OptLevel == CodeGenOpt::None)
1172 MachineInstr &MI = *mi;
1173 unsigned regA = MI.getOperand(DstIdx).getReg();
1174 unsigned regB = MI.getOperand(SrcIdx).getReg();
1176 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1177 "cannot make instruction into two-address form");
1178 bool regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
1180 if (TargetRegisterInfo::isVirtualRegister(regA))
1183 // Check if it is profitable to commute the operands.
1184 unsigned SrcOp1, SrcOp2;
1186 unsigned regCIdx = ~0U;
1187 bool TryCommute = false;
1188 bool AggressiveCommute = false;
1189 if (MI.isCommutable() && MI.getNumOperands() >= 3 &&
1190 TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
1191 if (SrcIdx == SrcOp1)
1193 else if (SrcIdx == SrcOp2)
1196 if (regCIdx != ~0U) {
1197 regC = MI.getOperand(regCIdx).getReg();
1198 if (!regBKilled && isKilled(MI, regC, MRI, TII, LIS, false))
1199 // If C dies but B does not, swap the B and C operands.
1200 // This makes the live ranges of A and C joinable.
1202 else if (isProfitableToCommute(regA, regB, regC, &MI, Dist)) {
1204 AggressiveCommute = true;
1209 // If it's profitable to commute, try to do so.
1210 if (TryCommute && commuteInstruction(mi, regB, regC, Dist)) {
1212 if (AggressiveCommute)
1217 if (shouldOnlyCommute)
1220 // If there is one more use of regB later in the same MBB, consider
1221 // re-schedule this MI below it.
1222 if (EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) {
1227 if (MI.isConvertibleTo3Addr()) {
1228 // This instruction is potentially convertible to a true
1229 // three-address instruction. Check if it is profitable.
1230 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
1231 // Try to convert it.
1232 if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
1233 ++NumConvertedTo3Addr;
1234 return true; // Done with this instruction.
1239 // If there is one more use of regB later in the same MBB, consider
1240 // re-schedule it before this MI if it's legal.
1241 if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) {
1246 // If this is an instruction with a load folded into it, try unfolding
1247 // the load, e.g. avoid this:
1249 // addq (%rax), %rcx
1250 // in favor of this:
1251 // movq (%rax), %rcx
1253 // because it's preferable to schedule a load than a register copy.
1254 if (MI.mayLoad() && !regBKilled) {
1255 // Determine if a load can be unfolded.
1256 unsigned LoadRegIndex;
1258 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1259 /*UnfoldLoad=*/true,
1260 /*UnfoldStore=*/false,
1263 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1264 if (UnfoldMCID.getNumDefs() == 1) {
1266 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
1267 const TargetRegisterClass *RC =
1268 TRI->getAllocatableClass(
1269 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
1270 unsigned Reg = MRI->createVirtualRegister(RC);
1271 SmallVector<MachineInstr *, 2> NewMIs;
1272 if (!TII->unfoldMemoryOperand(*MF, &MI, Reg,
1273 /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
1275 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1278 assert(NewMIs.size() == 2 &&
1279 "Unfolded a load into multiple instructions!");
1280 // The load was previously folded, so this is the only use.
1281 NewMIs[1]->addRegisterKilled(Reg, TRI);
1283 // Tentatively insert the instructions into the block so that they
1284 // look "normal" to the transformation logic.
1285 MBB->insert(mi, NewMIs[0]);
1286 MBB->insert(mi, NewMIs[1]);
1288 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1289 << "2addr: NEW INST: " << *NewMIs[1]);
1291 // Transform the instruction, now that it no longer has a load.
1292 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1293 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1294 MachineBasicBlock::iterator NewMI = NewMIs[1];
1295 bool TransformResult =
1296 tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true);
1297 (void)TransformResult;
1298 assert(!TransformResult &&
1299 "tryInstructionTransform() should return false.");
1300 if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1301 // Success, or at least we made an improvement. Keep the unfolded
1302 // instructions and discard the original.
1304 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1305 MachineOperand &MO = MI.getOperand(i);
1307 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1310 if (NewMIs[0]->killsRegister(MO.getReg()))
1311 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
1313 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1314 "Kill missing after load unfold!");
1315 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
1318 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
1319 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1320 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
1322 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1323 "Dead flag missing after load unfold!");
1324 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
1329 LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
1332 SmallVector<unsigned, 4> OrigRegs;
1334 for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(),
1335 MOE = MI.operands_end(); MOI != MOE; ++MOI) {
1337 OrigRegs.push_back(MOI->getReg());
1341 MI.eraseFromParent();
1343 // Update LiveIntervals.
1345 MachineBasicBlock::iterator Begin(NewMIs[0]);
1346 MachineBasicBlock::iterator End(NewMIs[1]);
1347 LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs);
1352 // Transforming didn't eliminate the tie and didn't lead to an
1353 // improvement. Clean up the unfolded instructions and keep the
1355 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1356 NewMIs[0]->eraseFromParent();
1357 NewMIs[1]->eraseFromParent();
1366 // Collect tied operands of MI that need to be handled.
1367 // Rewrite trivial cases immediately.
1368 // Return true if any tied operands where found, including the trivial ones.
1369 bool TwoAddressInstructionPass::
1370 collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
1371 const MCInstrDesc &MCID = MI->getDesc();
1372 bool AnyOps = false;
1373 unsigned NumOps = MI->getNumOperands();
1375 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1376 unsigned DstIdx = 0;
1377 if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1380 MachineOperand &SrcMO = MI->getOperand(SrcIdx);
1381 MachineOperand &DstMO = MI->getOperand(DstIdx);
1382 unsigned SrcReg = SrcMO.getReg();
1383 unsigned DstReg = DstMO.getReg();
1384 // Tied constraint already satisfied?
1385 if (SrcReg == DstReg)
1388 assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
1390 // Deal with <undef> uses immediately - simply rewrite the src operand.
1391 if (SrcMO.isUndef() && !DstMO.getSubReg()) {
1392 // Constrain the DstReg register class if required.
1393 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1394 if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
1396 MRI->constrainRegClass(DstReg, RC);
1397 SrcMO.setReg(DstReg);
1399 DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
1402 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
1407 // Process a list of tied MI operands that all use the same source register.
1408 // The tied pairs are of the form (SrcIdx, DstIdx).
1410 TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
1411 TiedPairList &TiedPairs,
1413 bool IsEarlyClobber = false;
1414 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1415 const MachineOperand &DstMO = MI->getOperand(TiedPairs[tpi].second);
1416 IsEarlyClobber |= DstMO.isEarlyClobber();
1419 bool RemovedKillFlag = false;
1420 bool AllUsesCopied = true;
1421 unsigned LastCopiedReg = 0;
1422 SlotIndex LastCopyIdx;
1424 unsigned SubRegB = 0;
1425 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1426 unsigned SrcIdx = TiedPairs[tpi].first;
1427 unsigned DstIdx = TiedPairs[tpi].second;
1429 const MachineOperand &DstMO = MI->getOperand(DstIdx);
1430 unsigned RegA = DstMO.getReg();
1432 // Grab RegB from the instruction because it may have changed if the
1433 // instruction was commuted.
1434 RegB = MI->getOperand(SrcIdx).getReg();
1435 SubRegB = MI->getOperand(SrcIdx).getSubReg();
1438 // The register is tied to multiple destinations (or else we would
1439 // not have continued this far), but this use of the register
1440 // already matches the tied destination. Leave it.
1441 AllUsesCopied = false;
1444 LastCopiedReg = RegA;
1446 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1447 "cannot make instruction into two-address form");
1450 // First, verify that we don't have a use of "a" in the instruction
1451 // (a = b + a for example) because our transformation will not
1452 // work. This should never occur because we are in SSA form.
1453 for (unsigned i = 0; i != MI->getNumOperands(); ++i)
1454 assert(i == DstIdx ||
1455 !MI->getOperand(i).isReg() ||
1456 MI->getOperand(i).getReg() != RegA);
1460 MachineInstrBuilder MIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1461 TII->get(TargetOpcode::COPY), RegA);
1462 // If this operand is folding a truncation, the truncation now moves to the
1463 // copy so that the register classes remain valid for the operands.
1464 MIB.addReg(RegB, 0, SubRegB);
1465 const TargetRegisterClass *RC = MRI->getRegClass(RegB);
1467 if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1468 assert(TRI->getMatchingSuperRegClass(RC, MRI->getRegClass(RegA),
1470 "tied subregister must be a truncation");
1471 // The superreg class will not be used to constrain the subreg class.
1475 assert(TRI->getMatchingSuperReg(RegA, SubRegB, MRI->getRegClass(RegB))
1476 && "tied subregister must be a truncation");
1480 // Update DistanceMap.
1481 MachineBasicBlock::iterator PrevMI = MI;
1483 DistanceMap.insert(std::make_pair(PrevMI, Dist));
1484 DistanceMap[MI] = ++Dist;
1487 LastCopyIdx = LIS->InsertMachineInstrInMaps(PrevMI).getRegSlot();
1489 if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1490 LiveInterval &LI = LIS->getInterval(RegA);
1491 VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1493 LIS->getInstructionIndex(MI).getRegSlot(IsEarlyClobber);
1494 LI.addSegment(LiveInterval::Segment(LastCopyIdx, endIdx, VNI));
1498 DEBUG(dbgs() << "\t\tprepend:\t" << *MIB);
1500 MachineOperand &MO = MI->getOperand(SrcIdx);
1501 assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
1502 "inconsistent operand info for 2-reg pass");
1504 MO.setIsKill(false);
1505 RemovedKillFlag = true;
1508 // Make sure regA is a legal regclass for the SrcIdx operand.
1509 if (TargetRegisterInfo::isVirtualRegister(RegA) &&
1510 TargetRegisterInfo::isVirtualRegister(RegB))
1511 MRI->constrainRegClass(RegA, RC);
1513 // The getMatchingSuper asserts guarantee that the register class projected
1514 // by SubRegB is compatible with RegA with no subregister. So regardless of
1515 // whether the dest oper writes a subreg, the source oper should not.
1518 // Propagate SrcRegMap.
1519 SrcRegMap[RegA] = RegB;
1523 if (AllUsesCopied) {
1524 if (!IsEarlyClobber) {
1525 // Replace other (un-tied) uses of regB with LastCopiedReg.
1526 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1527 MachineOperand &MO = MI->getOperand(i);
1528 if (MO.isReg() && MO.getReg() == RegB && MO.getSubReg() == SubRegB &&
1531 MO.setIsKill(false);
1532 RemovedKillFlag = true;
1534 MO.setReg(LastCopiedReg);
1540 // Update live variables for regB.
1541 if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(MI)) {
1542 MachineBasicBlock::iterator PrevMI = MI;
1544 LV->addVirtualRegisterKilled(RegB, PrevMI);
1547 // Update LiveIntervals.
1549 LiveInterval &LI = LIS->getInterval(RegB);
1550 SlotIndex MIIdx = LIS->getInstructionIndex(MI);
1551 LiveInterval::const_iterator I = LI.find(MIIdx);
1552 assert(I != LI.end() && "RegB must be live-in to use.");
1554 SlotIndex UseIdx = MIIdx.getRegSlot(IsEarlyClobber);
1555 if (I->end == UseIdx)
1556 LI.removeSegment(LastCopyIdx, UseIdx);
1559 } else if (RemovedKillFlag) {
1560 // Some tied uses of regB matched their destination registers, so
1561 // regB is still used in this instruction, but a kill flag was
1562 // removed from a different tied use of regB, so now we need to add
1563 // a kill flag to one of the remaining uses of regB.
1564 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1565 MachineOperand &MO = MI->getOperand(i);
1566 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1574 /// runOnMachineFunction - Reduce two-address instructions to two operands.
1576 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
1578 const TargetMachine &TM = MF->getTarget();
1579 MRI = &MF->getRegInfo();
1580 TII = MF->getSubtarget().getInstrInfo();
1581 TRI = MF->getSubtarget().getRegisterInfo();
1582 InstrItins = MF->getSubtarget().getInstrItineraryData();
1583 LV = getAnalysisIfAvailable<LiveVariables>();
1584 LIS = getAnalysisIfAvailable<LiveIntervals>();
1585 AA = &getAnalysis<AliasAnalysis>();
1586 OptLevel = TM.getOptLevel();
1588 bool MadeChange = false;
1590 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
1591 DEBUG(dbgs() << "********** Function: "
1592 << MF->getName() << '\n');
1594 // This pass takes the function out of SSA form.
1597 TiedOperandMap TiedOperands;
1598 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
1599 MBBI != MBBE; ++MBBI) {
1602 DistanceMap.clear();
1606 for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
1608 MachineBasicBlock::iterator nmi = std::next(mi);
1609 if (mi->isDebugValue()) {
1614 // Expand REG_SEQUENCE instructions. This will position mi at the first
1615 // expanded instruction.
1616 if (mi->isRegSequence())
1617 eliminateRegSequence(mi);
1619 DistanceMap.insert(std::make_pair(mi, ++Dist));
1623 // First scan through all the tied register uses in this instruction
1624 // and record a list of pairs of tied operands for each register.
1625 if (!collectTiedOperands(mi, TiedOperands)) {
1630 ++NumTwoAddressInstrs;
1632 DEBUG(dbgs() << '\t' << *mi);
1634 // If the instruction has a single pair of tied operands, try some
1635 // transformations that may either eliminate the tied operands or
1636 // improve the opportunities for coalescing away the register copy.
1637 if (TiedOperands.size() == 1) {
1638 SmallVectorImpl<std::pair<unsigned, unsigned> > &TiedPairs
1639 = TiedOperands.begin()->second;
1640 if (TiedPairs.size() == 1) {
1641 unsigned SrcIdx = TiedPairs[0].first;
1642 unsigned DstIdx = TiedPairs[0].second;
1643 unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
1644 unsigned DstReg = mi->getOperand(DstIdx).getReg();
1645 if (SrcReg != DstReg &&
1646 tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) {
1647 // The tied operands have been eliminated or shifted further down the
1648 // block to ease elimination. Continue processing with 'nmi'.
1649 TiedOperands.clear();
1656 // Now iterate over the information collected above.
1657 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1658 OE = TiedOperands.end(); OI != OE; ++OI) {
1659 processTiedPairs(mi, OI->second, Dist);
1660 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1663 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1664 if (mi->isInsertSubreg()) {
1665 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1666 // To %reg:subidx = COPY %subreg
1667 unsigned SubIdx = mi->getOperand(3).getImm();
1668 mi->RemoveOperand(3);
1669 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1670 mi->getOperand(0).setSubReg(SubIdx);
1671 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1672 mi->RemoveOperand(1);
1673 mi->setDesc(TII->get(TargetOpcode::COPY));
1674 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
1677 // Clear TiedOperands here instead of at the top of the loop
1678 // since most instructions do not have tied operands.
1679 TiedOperands.clear();
1685 MF->verify(this, "After two-address instruction pass");
1690 /// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process.
1692 /// The instruction is turned into a sequence of sub-register copies:
1694 /// %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1
1698 /// %dst:ssub0<def,undef> = COPY %v1
1699 /// %dst:ssub1<def> = COPY %v2
1701 void TwoAddressInstructionPass::
1702 eliminateRegSequence(MachineBasicBlock::iterator &MBBI) {
1703 MachineInstr *MI = MBBI;
1704 unsigned DstReg = MI->getOperand(0).getReg();
1705 if (MI->getOperand(0).getSubReg() ||
1706 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1707 !(MI->getNumOperands() & 1)) {
1708 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1709 llvm_unreachable(nullptr);
1712 SmallVector<unsigned, 4> OrigRegs;
1714 OrigRegs.push_back(MI->getOperand(0).getReg());
1715 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2)
1716 OrigRegs.push_back(MI->getOperand(i).getReg());
1719 bool DefEmitted = false;
1720 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1721 MachineOperand &UseMO = MI->getOperand(i);
1722 unsigned SrcReg = UseMO.getReg();
1723 unsigned SubIdx = MI->getOperand(i+1).getImm();
1724 // Nothing needs to be inserted for <undef> operands.
1725 if (UseMO.isUndef())
1728 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1729 // might insert a COPY that uses SrcReg after is was killed.
1730 bool isKill = UseMO.isKill();
1732 for (unsigned j = i + 2; j < e; j += 2)
1733 if (MI->getOperand(j).getReg() == SrcReg) {
1734 MI->getOperand(j).setIsKill();
1735 UseMO.setIsKill(false);
1740 // Insert the sub-register copy.
1741 MachineInstr *CopyMI = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1742 TII->get(TargetOpcode::COPY))
1743 .addReg(DstReg, RegState::Define, SubIdx)
1746 // The first def needs an <undef> flag because there is no live register
1749 CopyMI->getOperand(0).setIsUndef(true);
1750 // Return an iterator pointing to the first inserted instr.
1755 // Update LiveVariables' kill info.
1756 if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
1757 LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1759 DEBUG(dbgs() << "Inserted: " << *CopyMI);
1762 MachineBasicBlock::iterator EndMBBI =
1763 std::next(MachineBasicBlock::iterator(MI));
1766 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1767 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1768 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
1769 MI->RemoveOperand(j);
1771 DEBUG(dbgs() << "Eliminated: " << *MI);
1772 MI->eraseFromParent();
1775 // Udpate LiveIntervals.
1777 LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs);