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/ADT/DenseMap.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Analysis/AliasAnalysis.h"
35 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
36 #include "llvm/CodeGen/LiveVariables.h"
37 #include "llvm/CodeGen/MachineFunctionPass.h"
38 #include "llvm/CodeGen/MachineInstr.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/Passes.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/MC/MCInstrItineraries.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/raw_ostream.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"
55 #define DEBUG_TYPE "twoaddressinstruction"
57 STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
58 STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
59 STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
60 STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
61 STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
62 STATISTIC(NumReSchedUps, "Number of instructions re-scheduled up");
63 STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down");
65 // Temporary flag to disable rescheduling.
67 EnableRescheduling("twoaddr-reschedule",
68 cl::desc("Coalesce copies by rescheduling (default=true)"),
69 cl::init(true), cl::Hidden);
71 // Limit the number of dataflow edges to traverse when evaluating the benefit
72 // of commuting operands.
73 static cl::opt<unsigned> MaxDataFlowEdge(
74 "dataflow-edge-limit", cl::Hidden, cl::init(3),
75 cl::desc("Maximum number of dataflow edges to traverse when evaluating "
76 "the benefit of commuting operands"));
79 class TwoAddressInstructionPass : public MachineFunctionPass {
81 const TargetInstrInfo *TII;
82 const TargetRegisterInfo *TRI;
83 const InstrItineraryData *InstrItins;
84 MachineRegisterInfo *MRI;
88 CodeGenOpt::Level OptLevel;
90 // The current basic block being processed.
91 MachineBasicBlock *MBB;
93 // Keep track the distance of a MI from the start of the current basic block.
94 DenseMap<MachineInstr*, unsigned> DistanceMap;
96 // Set of already processed instructions in the current block.
97 SmallPtrSet<MachineInstr*, 8> Processed;
99 // A map from virtual registers to physical registers which are likely targets
100 // to be coalesced to due to copies from physical registers to virtual
101 // registers. e.g. v1024 = move r0.
102 DenseMap<unsigned, unsigned> SrcRegMap;
104 // A map from virtual registers to physical registers which are likely targets
105 // to be coalesced to due to copies to physical registers from virtual
106 // registers. e.g. r1 = move v1024.
107 DenseMap<unsigned, unsigned> DstRegMap;
109 bool sink3AddrInstruction(MachineInstr *MI, unsigned Reg,
110 MachineBasicBlock::iterator OldPos);
112 bool isRevCopyChain(unsigned FromReg, unsigned ToReg, int Maxlen);
114 bool noUseAfterLastDef(unsigned Reg, unsigned Dist, unsigned &LastDef);
116 bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
117 MachineInstr *MI, unsigned Dist);
119 bool commuteInstruction(MachineInstr *MI, unsigned DstIdx,
120 unsigned RegBIdx, unsigned RegCIdx, unsigned Dist);
122 bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
124 bool convertInstTo3Addr(MachineBasicBlock::iterator &mi,
125 MachineBasicBlock::iterator &nmi,
126 unsigned RegA, unsigned RegB, unsigned Dist);
128 bool isDefTooClose(unsigned Reg, unsigned Dist, MachineInstr *MI);
130 bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
131 MachineBasicBlock::iterator &nmi,
133 bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
134 MachineBasicBlock::iterator &nmi,
137 bool tryInstructionTransform(MachineBasicBlock::iterator &mi,
138 MachineBasicBlock::iterator &nmi,
139 unsigned SrcIdx, unsigned DstIdx,
140 unsigned Dist, bool shouldOnlyCommute);
142 bool tryInstructionCommute(MachineInstr *MI,
147 void scanUses(unsigned DstReg);
149 void processCopy(MachineInstr *MI);
151 typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList;
152 typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap;
153 bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
154 void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
155 void eliminateRegSequence(MachineBasicBlock::iterator&);
158 static char ID; // Pass identification, replacement for typeid
159 TwoAddressInstructionPass() : MachineFunctionPass(ID) {
160 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
163 void getAnalysisUsage(AnalysisUsage &AU) const override {
164 AU.setPreservesCFG();
165 AU.addUsedIfAvailable<AAResultsWrapperPass>();
166 AU.addUsedIfAvailable<LiveVariables>();
167 AU.addPreserved<LiveVariables>();
168 AU.addPreserved<SlotIndexes>();
169 AU.addPreserved<LiveIntervals>();
170 AU.addPreservedID(MachineLoopInfoID);
171 AU.addPreservedID(MachineDominatorsID);
172 MachineFunctionPass::getAnalysisUsage(AU);
175 /// Pass entry point.
176 bool runOnMachineFunction(MachineFunction&) override;
178 } // end anonymous namespace
180 char TwoAddressInstructionPass::ID = 0;
181 INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, DEBUG_TYPE,
182 "Two-Address instruction pass", false, false)
183 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
184 INITIALIZE_PASS_END(TwoAddressInstructionPass, DEBUG_TYPE,
185 "Two-Address instruction pass", false, false)
187 char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
189 static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg, LiveIntervals *LIS);
191 /// A two-address instruction has been converted to a three-address instruction
192 /// to avoid clobbering a register. Try to sink it past the instruction that
193 /// would kill the above mentioned register to reduce register pressure.
194 bool TwoAddressInstructionPass::
195 sink3AddrInstruction(MachineInstr *MI, unsigned SavedReg,
196 MachineBasicBlock::iterator OldPos) {
197 // FIXME: Shouldn't we be trying to do this before we three-addressify the
198 // instruction? After this transformation is done, we no longer need
199 // the instruction to be in three-address form.
201 // Check if it's safe to move this instruction.
202 bool SeenStore = true; // Be conservative.
203 if (!MI->isSafeToMove(AA, SeenStore))
207 SmallSet<unsigned, 4> UseRegs;
209 for (const MachineOperand &MO : MI->operands()) {
212 unsigned MOReg = MO.getReg();
215 if (MO.isUse() && MOReg != SavedReg)
216 UseRegs.insert(MO.getReg());
220 // Don't try to move it if it implicitly defines a register.
223 // For now, don't move any instructions that define multiple registers.
225 DefReg = MO.getReg();
228 // Find the instruction that kills SavedReg.
229 MachineInstr *KillMI = nullptr;
231 LiveInterval &LI = LIS->getInterval(SavedReg);
232 assert(LI.end() != LI.begin() &&
233 "Reg should not have empty live interval.");
235 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
236 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
237 if (I != LI.end() && I->start < MBBEndIdx)
241 KillMI = LIS->getInstructionFromIndex(I->end);
244 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SavedReg)) {
247 KillMI = UseMO.getParent();
252 // If we find the instruction that kills SavedReg, and it is in an
253 // appropriate location, we can try to sink the current instruction
255 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
256 MachineBasicBlock::iterator(KillMI) == OldPos || KillMI->isTerminator())
259 // If any of the definitions are used by another instruction between the
260 // position and the kill use, then it's not safe to sink it.
262 // FIXME: This can be sped up if there is an easy way to query whether an
263 // instruction is before or after another instruction. Then we can use
264 // MachineRegisterInfo def / use instead.
265 MachineOperand *KillMO = nullptr;
266 MachineBasicBlock::iterator KillPos = KillMI;
269 unsigned NumVisited = 0;
270 for (MachineInstr &OtherMI : llvm::make_range(std::next(OldPos), KillPos)) {
271 // DBG_VALUE cannot be counted against the limit.
272 if (OtherMI.isDebugValue())
274 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
277 for (unsigned i = 0, e = OtherMI.getNumOperands(); i != e; ++i) {
278 MachineOperand &MO = OtherMI.getOperand(i);
281 unsigned MOReg = MO.getReg();
287 if (MO.isKill() || (LIS && isPlainlyKilled(&OtherMI, MOReg, LIS))) {
288 if (&OtherMI == KillMI && MOReg == SavedReg)
289 // Save the operand that kills the register. We want to unset the kill
290 // marker if we can sink MI past it.
292 else if (UseRegs.count(MOReg))
293 // One of the uses is killed before the destination.
298 assert(KillMO && "Didn't find kill");
301 // Update kill and LV information.
302 KillMO->setIsKill(false);
303 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
304 KillMO->setIsKill(true);
307 LV->replaceKillInstruction(SavedReg, *KillMI, *MI);
310 // Move instruction to its destination.
312 MBB->insert(KillPos, MI);
315 LIS->handleMove(*MI);
321 /// Return the MachineInstr* if it is the single def of the Reg in current BB.
322 static MachineInstr *getSingleDef(unsigned Reg, MachineBasicBlock *BB,
323 const MachineRegisterInfo *MRI) {
324 MachineInstr *Ret = nullptr;
325 for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
326 if (DefMI.getParent() != BB || DefMI.isDebugValue())
330 else if (Ret != &DefMI)
336 /// Check if there is a reversed copy chain from FromReg to ToReg:
337 /// %Tmp1 = copy %Tmp2;
338 /// %FromReg = copy %Tmp1;
339 /// %ToReg = add %FromReg ...
340 /// %Tmp2 = copy %ToReg;
341 /// MaxLen specifies the maximum length of the copy chain the func
342 /// can walk through.
343 bool TwoAddressInstructionPass::isRevCopyChain(unsigned FromReg, unsigned ToReg,
345 unsigned TmpReg = FromReg;
346 for (int i = 0; i < Maxlen; i++) {
347 MachineInstr *Def = getSingleDef(TmpReg, MBB, MRI);
348 if (!Def || !Def->isCopy())
351 TmpReg = Def->getOperand(1).getReg();
359 /// Return true if there are no intervening uses between the last instruction
360 /// in the MBB that defines the specified register and the two-address
361 /// instruction which is being processed. It also returns the last def location
363 bool TwoAddressInstructionPass::noUseAfterLastDef(unsigned Reg, unsigned Dist,
366 unsigned LastUse = Dist;
367 for (MachineOperand &MO : MRI->reg_operands(Reg)) {
368 MachineInstr *MI = MO.getParent();
369 if (MI->getParent() != MBB || MI->isDebugValue())
371 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
372 if (DI == DistanceMap.end())
374 if (MO.isUse() && DI->second < LastUse)
375 LastUse = DI->second;
376 if (MO.isDef() && DI->second > LastDef)
377 LastDef = DI->second;
380 return !(LastUse > LastDef && LastUse < Dist);
383 /// Return true if the specified MI is a copy instruction or an extract_subreg
384 /// instruction. It also returns the source and destination registers and
385 /// whether they are physical registers by reference.
386 static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
387 unsigned &SrcReg, unsigned &DstReg,
388 bool &IsSrcPhys, bool &IsDstPhys) {
392 DstReg = MI.getOperand(0).getReg();
393 SrcReg = MI.getOperand(1).getReg();
394 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
395 DstReg = MI.getOperand(0).getReg();
396 SrcReg = MI.getOperand(2).getReg();
400 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
401 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
405 /// Test if the given register value, which is used by the
406 /// given instruction, is killed by the given instruction.
407 static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg,
408 LiveIntervals *LIS) {
409 if (LIS && TargetRegisterInfo::isVirtualRegister(Reg) &&
410 !LIS->isNotInMIMap(*MI)) {
411 // FIXME: Sometimes tryInstructionTransform() will add instructions and
412 // test whether they can be folded before keeping them. In this case it
413 // sets a kill before recursively calling tryInstructionTransform() again.
414 // If there is no interval available, we assume that this instruction is
415 // one of those. A kill flag is manually inserted on the operand so the
416 // check below will handle it.
417 LiveInterval &LI = LIS->getInterval(Reg);
418 // This is to match the kill flag version where undefs don't have kill
420 if (!LI.hasAtLeastOneValue())
423 SlotIndex useIdx = LIS->getInstructionIndex(*MI);
424 LiveInterval::const_iterator I = LI.find(useIdx);
425 assert(I != LI.end() && "Reg must be live-in to use.");
426 return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx);
429 return MI->killsRegister(Reg);
432 /// Test if the given register value, which is used by the given
433 /// instruction, is killed by the given instruction. This looks through
434 /// coalescable copies to see if the original value is potentially not killed.
436 /// For example, in this code:
438 /// %reg1034 = copy %reg1024
439 /// %reg1035 = copy %reg1025<kill>
440 /// %reg1036 = add %reg1034<kill>, %reg1035<kill>
442 /// %reg1034 is not considered to be killed, since it is copied from a
443 /// register which is not killed. Treating it as not killed lets the
444 /// normal heuristics commute the (two-address) add, which lets
445 /// coalescing eliminate the extra copy.
447 /// If allowFalsePositives is true then likely kills are treated as kills even
448 /// if it can't be proven that they are kills.
449 static bool isKilled(MachineInstr &MI, unsigned Reg,
450 const MachineRegisterInfo *MRI,
451 const TargetInstrInfo *TII,
453 bool allowFalsePositives) {
454 MachineInstr *DefMI = &MI;
456 // All uses of physical registers are likely to be kills.
457 if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
458 (allowFalsePositives || MRI->hasOneUse(Reg)))
460 if (!isPlainlyKilled(DefMI, Reg, LIS))
462 if (TargetRegisterInfo::isPhysicalRegister(Reg))
464 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
465 // If there are multiple defs, we can't do a simple analysis, so just
466 // go with what the kill flag says.
467 if (std::next(Begin) != MRI->def_end())
469 DefMI = Begin->getParent();
470 bool IsSrcPhys, IsDstPhys;
471 unsigned SrcReg, DstReg;
472 // If the def is something other than a copy, then it isn't going to
473 // be coalesced, so follow the kill flag.
474 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
480 /// Return true if the specified MI uses the specified register as a two-address
481 /// use. If so, return the destination register by reference.
482 static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
483 for (unsigned i = 0, NumOps = MI.getNumOperands(); i != NumOps; ++i) {
484 const MachineOperand &MO = MI.getOperand(i);
485 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
488 if (MI.isRegTiedToDefOperand(i, &ti)) {
489 DstReg = MI.getOperand(ti).getReg();
496 /// Given a register, if has a single in-basic block use, return the use
497 /// instruction if it's a copy or a two-address use.
499 MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
500 MachineRegisterInfo *MRI,
501 const TargetInstrInfo *TII,
503 unsigned &DstReg, bool &IsDstPhys) {
504 if (!MRI->hasOneNonDBGUse(Reg))
505 // None or more than one use.
507 MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(Reg);
508 if (UseMI.getParent() != MBB)
512 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
517 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
518 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
524 /// Return the physical register the specified virtual register might be mapped
527 getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
528 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
529 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
530 if (SI == RegMap.end())
534 if (TargetRegisterInfo::isPhysicalRegister(Reg))
539 /// Return true if the two registers are equal or aliased.
541 regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
546 return TRI->regsOverlap(RegA, RegB);
549 // Returns true if Reg is equal or aliased to at least one register in Set.
550 static bool regOverlapsSet(const SmallVectorImpl<unsigned> &Set, unsigned Reg,
551 const TargetRegisterInfo *TRI) {
552 for (unsigned R : Set)
553 if (TRI->regsOverlap(R, Reg))
559 /// Return true if it's potentially profitable to commute the two-address
560 /// instruction that's being processed.
562 TwoAddressInstructionPass::
563 isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
564 MachineInstr *MI, unsigned Dist) {
565 if (OptLevel == CodeGenOpt::None)
568 // Determine if it's profitable to commute this two address instruction. In
569 // general, we want no uses between this instruction and the definition of
570 // the two-address register.
572 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
573 // %reg1029<def> = MOV8rr %reg1028
574 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
575 // insert => %reg1030<def> = MOV8rr %reg1028
576 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
577 // In this case, it might not be possible to coalesce the second MOV8rr
578 // instruction if the first one is coalesced. So it would be profitable to
580 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
581 // %reg1029<def> = MOV8rr %reg1028
582 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
583 // insert => %reg1030<def> = MOV8rr %reg1029
584 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
586 if (!isPlainlyKilled(MI, regC, LIS))
589 // Ok, we have something like:
590 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
591 // let's see if it's worth commuting it.
593 // Look for situations like this:
594 // %reg1024<def> = MOV r1
595 // %reg1025<def> = MOV r0
596 // %reg1026<def> = ADD %reg1024, %reg1025
598 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
599 unsigned ToRegA = getMappedReg(regA, DstRegMap);
601 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
602 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
603 bool CompB = FromRegB && regsAreCompatible(FromRegB, ToRegA, TRI);
604 bool CompC = FromRegC && regsAreCompatible(FromRegC, ToRegA, TRI);
606 // Compute if any of the following are true:
607 // -RegB is not tied to a register and RegC is compatible with RegA.
608 // -RegB is tied to the wrong physical register, but RegC is.
609 // -RegB is tied to the wrong physical register, and RegC isn't tied.
610 if ((!FromRegB && CompC) || (FromRegB && !CompB && (!FromRegC || CompC)))
612 // Don't compute if any of the following are true:
613 // -RegC is not tied to a register and RegB is compatible with RegA.
614 // -RegC is tied to the wrong physical register, but RegB is.
615 // -RegC is tied to the wrong physical register, and RegB isn't tied.
616 if ((!FromRegC && CompB) || (FromRegC && !CompC && (!FromRegB || CompB)))
620 // If there is a use of regC between its last def (could be livein) and this
621 // instruction, then bail.
622 unsigned LastDefC = 0;
623 if (!noUseAfterLastDef(regC, Dist, LastDefC))
626 // If there is a use of regB between its last def (could be livein) and this
627 // instruction, then go ahead and make this transformation.
628 unsigned LastDefB = 0;
629 if (!noUseAfterLastDef(regB, Dist, LastDefB))
632 // Look for situation like this:
633 // %reg101 = MOV %reg100
635 // %reg103 = ADD %reg102, %reg101
637 // %reg100 = MOV %reg103
638 // If there is a reversed copy chain from reg101 to reg103, commute the ADD
639 // to eliminate an otherwise unavoidable copy.
641 // We can extend the logic further: If an pair of operands in an insn has
642 // been merged, the insn could be regarded as a virtual copy, and the virtual
643 // copy could also be used to construct a copy chain.
644 // To more generally minimize register copies, ideally the logic of two addr
645 // instruction pass should be integrated with register allocation pass where
646 // interference graph is available.
647 if (isRevCopyChain(regC, regA, MaxDataFlowEdge))
650 if (isRevCopyChain(regB, regA, MaxDataFlowEdge))
653 // Since there are no intervening uses for both registers, then commute
654 // if the def of regC is closer. Its live interval is shorter.
655 return LastDefB && LastDefC && LastDefC > LastDefB;
658 /// Commute a two-address instruction and update the basic block, distance map,
659 /// and live variables if needed. Return true if it is successful.
660 bool TwoAddressInstructionPass::commuteInstruction(MachineInstr *MI,
665 unsigned RegC = MI->getOperand(RegCIdx).getReg();
666 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
667 MachineInstr *NewMI = TII->commuteInstruction(*MI, false, RegBIdx, RegCIdx);
669 if (NewMI == nullptr) {
670 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
674 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
675 assert(NewMI == MI &&
676 "TargetInstrInfo::commuteInstruction() should not return a new "
677 "instruction unless it was requested.");
679 // Update source register map.
680 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
682 unsigned RegA = MI->getOperand(DstIdx).getReg();
683 SrcRegMap[RegA] = FromRegC;
689 /// Return true if it is profitable to convert the given 2-address instruction
690 /// to a 3-address one.
692 TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
693 // Look for situations like this:
694 // %reg1024<def> = MOV r1
695 // %reg1025<def> = MOV r0
696 // %reg1026<def> = ADD %reg1024, %reg1025
698 // Turn ADD into a 3-address instruction to avoid a copy.
699 unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
702 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
703 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
706 /// Convert the specified two-address instruction into a three address one.
707 /// Return true if this transformation was successful.
709 TwoAddressInstructionPass::convertInstTo3Addr(MachineBasicBlock::iterator &mi,
710 MachineBasicBlock::iterator &nmi,
711 unsigned RegA, unsigned RegB,
713 // FIXME: Why does convertToThreeAddress() need an iterator reference?
714 MachineFunction::iterator MFI = MBB->getIterator();
715 MachineInstr *NewMI = TII->convertToThreeAddress(MFI, *mi, LV);
716 assert(MBB->getIterator() == MFI &&
717 "convertToThreeAddress changed iterator reference");
721 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
722 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
726 LIS->ReplaceMachineInstrInMaps(*mi, *NewMI);
728 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
729 // FIXME: Temporary workaround. If the new instruction doesn't
730 // uses RegB, convertToThreeAddress must have created more
731 // then one instruction.
732 Sunk = sink3AddrInstruction(NewMI, RegB, mi);
734 MBB->erase(mi); // Nuke the old inst.
737 DistanceMap.insert(std::make_pair(NewMI, Dist));
742 // Update source and destination register maps.
743 SrcRegMap.erase(RegA);
744 DstRegMap.erase(RegB);
748 /// Scan forward recursively for only uses, update maps if the use is a copy or
749 /// a two-address instruction.
751 TwoAddressInstructionPass::scanUses(unsigned DstReg) {
752 SmallVector<unsigned, 4> VirtRegPairs;
756 unsigned Reg = DstReg;
757 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
758 NewReg, IsDstPhys)) {
759 if (IsCopy && !Processed.insert(UseMI).second)
762 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
763 if (DI != DistanceMap.end())
764 // Earlier in the same MBB.Reached via a back edge.
768 VirtRegPairs.push_back(NewReg);
771 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
773 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
774 VirtRegPairs.push_back(NewReg);
778 if (!VirtRegPairs.empty()) {
779 unsigned ToReg = VirtRegPairs.back();
780 VirtRegPairs.pop_back();
781 while (!VirtRegPairs.empty()) {
782 unsigned FromReg = VirtRegPairs.back();
783 VirtRegPairs.pop_back();
784 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
786 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
789 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
791 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
795 /// If the specified instruction is not yet processed, process it if it's a
796 /// copy. For a copy instruction, we find the physical registers the
797 /// source and destination registers might be mapped to. These are kept in
798 /// point-to maps used to determine future optimizations. e.g.
801 /// v1026 = add v1024, v1025
803 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
804 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
805 /// potentially joined with r1 on the output side. It's worthwhile to commute
806 /// 'add' to eliminate a copy.
807 void TwoAddressInstructionPass::processCopy(MachineInstr *MI) {
808 if (Processed.count(MI))
811 bool IsSrcPhys, IsDstPhys;
812 unsigned SrcReg, DstReg;
813 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
816 if (IsDstPhys && !IsSrcPhys)
817 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
818 else if (!IsDstPhys && IsSrcPhys) {
819 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
821 assert(SrcRegMap[DstReg] == SrcReg &&
822 "Can't map to two src physical registers!");
827 Processed.insert(MI);
830 /// If there is one more local instruction that reads 'Reg' and it kills 'Reg,
831 /// consider moving the instruction below the kill instruction in order to
832 /// eliminate the need for the copy.
833 bool TwoAddressInstructionPass::
834 rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
835 MachineBasicBlock::iterator &nmi,
837 // Bail immediately if we don't have LV or LIS available. We use them to find
838 // kills efficiently.
842 MachineInstr *MI = &*mi;
843 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
844 if (DI == DistanceMap.end())
845 // Must be created from unfolded load. Don't waste time trying this.
848 MachineInstr *KillMI = nullptr;
850 LiveInterval &LI = LIS->getInterval(Reg);
851 assert(LI.end() != LI.begin() &&
852 "Reg should not have empty live interval.");
854 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
855 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
856 if (I != LI.end() && I->start < MBBEndIdx)
860 KillMI = LIS->getInstructionFromIndex(I->end);
862 KillMI = LV->getVarInfo(Reg).findKill(MBB);
864 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
865 // Don't mess with copies, they may be coalesced later.
868 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
869 KillMI->isBranch() || KillMI->isTerminator())
870 // Don't move pass calls, etc.
874 if (isTwoAddrUse(*KillMI, Reg, DstReg))
877 bool SeenStore = true;
878 if (!MI->isSafeToMove(AA, SeenStore))
881 if (TII->getInstrLatency(InstrItins, *MI) > 1)
882 // FIXME: Needs more sophisticated heuristics.
885 SmallVector<unsigned, 2> Uses;
886 SmallVector<unsigned, 2> Kills;
887 SmallVector<unsigned, 2> Defs;
888 for (const MachineOperand &MO : MI->operands()) {
891 unsigned MOReg = MO.getReg();
895 Defs.push_back(MOReg);
897 Uses.push_back(MOReg);
898 if (MOReg != Reg && (MO.isKill() ||
899 (LIS && isPlainlyKilled(MI, MOReg, LIS))))
900 Kills.push_back(MOReg);
904 // Move the copies connected to MI down as well.
905 MachineBasicBlock::iterator Begin = MI;
906 MachineBasicBlock::iterator AfterMI = std::next(Begin);
908 MachineBasicBlock::iterator End = AfterMI;
909 while (End->isCopy() &&
910 regOverlapsSet(Defs, End->getOperand(1).getReg(), TRI)) {
911 Defs.push_back(End->getOperand(0).getReg());
915 // Check if the reschedule will not break dependencies.
916 unsigned NumVisited = 0;
917 MachineBasicBlock::iterator KillPos = KillMI;
919 for (MachineInstr &OtherMI : llvm::make_range(End, KillPos)) {
920 // DBG_VALUE cannot be counted against the limit.
921 if (OtherMI.isDebugValue())
923 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
926 if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
927 OtherMI.isBranch() || OtherMI.isTerminator())
928 // Don't move pass calls, etc.
930 for (const MachineOperand &MO : OtherMI.operands()) {
933 unsigned MOReg = MO.getReg();
937 if (regOverlapsSet(Uses, MOReg, TRI))
938 // Physical register use would be clobbered.
940 if (!MO.isDead() && regOverlapsSet(Defs, MOReg, TRI))
941 // May clobber a physical register def.
942 // FIXME: This may be too conservative. It's ok if the instruction
943 // is sunken completely below the use.
946 if (regOverlapsSet(Defs, MOReg, TRI))
949 MO.isKill() || (LIS && isPlainlyKilled(&OtherMI, MOReg, LIS));
950 if (MOReg != Reg && ((isKill && regOverlapsSet(Uses, MOReg, TRI)) ||
951 regOverlapsSet(Kills, MOReg, TRI)))
952 // Don't want to extend other live ranges and update kills.
954 if (MOReg == Reg && !isKill)
955 // We can't schedule across a use of the register in question.
957 // Ensure that if this is register in question, its the kill we expect.
958 assert((MOReg != Reg || &OtherMI == KillMI) &&
959 "Found multiple kills of a register in a basic block");
964 // Move debug info as well.
965 while (Begin != MBB->begin() && std::prev(Begin)->isDebugValue())
969 MachineBasicBlock::iterator InsertPos = KillPos;
971 // We have to move the copies first so that the MBB is still well-formed
972 // when calling handleMove().
973 for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) {
974 auto CopyMI = MBBI++;
975 MBB->splice(InsertPos, MBB, CopyMI);
976 LIS->handleMove(*CopyMI);
979 End = std::next(MachineBasicBlock::iterator(MI));
982 // Copies following MI may have been moved as well.
983 MBB->splice(InsertPos, MBB, Begin, End);
984 DistanceMap.erase(DI);
986 // Update live variables
988 LIS->handleMove(*MI);
990 LV->removeVirtualRegisterKilled(Reg, *KillMI);
991 LV->addVirtualRegisterKilled(Reg, *MI);
994 DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
998 /// Return true if the re-scheduling will put the given instruction too close
999 /// to the defs of its register dependencies.
1000 bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
1002 for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
1003 if (DefMI.getParent() != MBB || DefMI.isCopy() || DefMI.isCopyLike())
1006 return true; // MI is defining something KillMI uses
1007 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(&DefMI);
1008 if (DDI == DistanceMap.end())
1009 return true; // Below MI
1010 unsigned DefDist = DDI->second;
1011 assert(Dist > DefDist && "Visited def already?");
1012 if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist))
1018 /// If there is one more local instruction that reads 'Reg' and it kills 'Reg,
1019 /// consider moving the kill instruction above the current two-address
1020 /// instruction in order to eliminate the need for the copy.
1021 bool TwoAddressInstructionPass::
1022 rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
1023 MachineBasicBlock::iterator &nmi,
1025 // Bail immediately if we don't have LV or LIS available. We use them to find
1026 // kills efficiently.
1030 MachineInstr *MI = &*mi;
1031 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
1032 if (DI == DistanceMap.end())
1033 // Must be created from unfolded load. Don't waste time trying this.
1036 MachineInstr *KillMI = nullptr;
1038 LiveInterval &LI = LIS->getInterval(Reg);
1039 assert(LI.end() != LI.begin() &&
1040 "Reg should not have empty live interval.");
1042 SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
1043 LiveInterval::const_iterator I = LI.find(MBBEndIdx);
1044 if (I != LI.end() && I->start < MBBEndIdx)
1048 KillMI = LIS->getInstructionFromIndex(I->end);
1050 KillMI = LV->getVarInfo(Reg).findKill(MBB);
1052 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
1053 // Don't mess with copies, they may be coalesced later.
1057 if (isTwoAddrUse(*KillMI, Reg, DstReg))
1060 bool SeenStore = true;
1061 if (!KillMI->isSafeToMove(AA, SeenStore))
1064 SmallSet<unsigned, 2> Uses;
1065 SmallSet<unsigned, 2> Kills;
1066 SmallSet<unsigned, 2> Defs;
1067 SmallSet<unsigned, 2> LiveDefs;
1068 for (const MachineOperand &MO : KillMI->operands()) {
1071 unsigned MOReg = MO.getReg();
1075 if (isDefTooClose(MOReg, DI->second, MI))
1077 bool isKill = MO.isKill() || (LIS && isPlainlyKilled(KillMI, MOReg, LIS));
1078 if (MOReg == Reg && !isKill)
1081 if (isKill && MOReg != Reg)
1082 Kills.insert(MOReg);
1083 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1086 LiveDefs.insert(MOReg);
1090 // Check if the reschedule will not break depedencies.
1091 unsigned NumVisited = 0;
1092 for (MachineInstr &OtherMI :
1093 llvm::make_range(mi, MachineBasicBlock::iterator(KillMI))) {
1094 // DBG_VALUE cannot be counted against the limit.
1095 if (OtherMI.isDebugValue())
1097 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
1100 if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
1101 OtherMI.isBranch() || OtherMI.isTerminator())
1102 // Don't move pass calls, etc.
1104 SmallVector<unsigned, 2> OtherDefs;
1105 for (const MachineOperand &MO : OtherMI.operands()) {
1108 unsigned MOReg = MO.getReg();
1112 if (Defs.count(MOReg))
1113 // Moving KillMI can clobber the physical register if the def has
1116 if (Kills.count(MOReg))
1117 // Don't want to extend other live ranges and update kills.
1119 if (&OtherMI != MI && MOReg == Reg &&
1120 !(MO.isKill() || (LIS && isPlainlyKilled(&OtherMI, MOReg, LIS))))
1121 // We can't schedule across a use of the register in question.
1124 OtherDefs.push_back(MOReg);
1128 for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
1129 unsigned MOReg = OtherDefs[i];
1130 if (Uses.count(MOReg))
1132 if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1133 LiveDefs.count(MOReg))
1135 // Physical register def is seen.
1140 // Move the old kill above MI, don't forget to move debug info as well.
1141 MachineBasicBlock::iterator InsertPos = mi;
1142 while (InsertPos != MBB->begin() && std::prev(InsertPos)->isDebugValue())
1144 MachineBasicBlock::iterator From = KillMI;
1145 MachineBasicBlock::iterator To = std::next(From);
1146 while (std::prev(From)->isDebugValue())
1148 MBB->splice(InsertPos, MBB, From, To);
1150 nmi = std::prev(InsertPos); // Backtrack so we process the moved instr.
1151 DistanceMap.erase(DI);
1153 // Update live variables
1155 LIS->handleMove(*KillMI);
1157 LV->removeVirtualRegisterKilled(Reg, *KillMI);
1158 LV->addVirtualRegisterKilled(Reg, *MI);
1161 DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
1165 /// Tries to commute the operand 'BaseOpIdx' and some other operand in the
1166 /// given machine instruction to improve opportunities for coalescing and
1167 /// elimination of a register to register copy.
1169 /// 'DstOpIdx' specifies the index of MI def operand.
1170 /// 'BaseOpKilled' specifies if the register associated with 'BaseOpIdx'
1171 /// operand is killed by the given instruction.
1172 /// The 'Dist' arguments provides the distance of MI from the start of the
1173 /// current basic block and it is used to determine if it is profitable
1174 /// to commute operands in the instruction.
1176 /// Returns true if the transformation happened. Otherwise, returns false.
1177 bool TwoAddressInstructionPass::tryInstructionCommute(MachineInstr *MI,
1182 if (!MI->isCommutable())
1185 unsigned DstOpReg = MI->getOperand(DstOpIdx).getReg();
1186 unsigned BaseOpReg = MI->getOperand(BaseOpIdx).getReg();
1187 unsigned OpsNum = MI->getDesc().getNumOperands();
1188 unsigned OtherOpIdx = MI->getDesc().getNumDefs();
1189 for (; OtherOpIdx < OpsNum; OtherOpIdx++) {
1190 // The call of findCommutedOpIndices below only checks if BaseOpIdx
1191 // and OtherOpIdx are commutable, it does not really search for
1192 // other commutable operands and does not change the values of passed
1194 if (OtherOpIdx == BaseOpIdx || !MI->getOperand(OtherOpIdx).isReg() ||
1195 !TII->findCommutedOpIndices(*MI, BaseOpIdx, OtherOpIdx))
1198 unsigned OtherOpReg = MI->getOperand(OtherOpIdx).getReg();
1199 bool AggressiveCommute = false;
1201 // If OtherOp dies but BaseOp does not, swap the OtherOp and BaseOp
1202 // operands. This makes the live ranges of DstOp and OtherOp joinable.
1204 !BaseOpKilled && isKilled(*MI, OtherOpReg, MRI, TII, LIS, false);
1207 isProfitableToCommute(DstOpReg, BaseOpReg, OtherOpReg, MI, Dist)) {
1209 AggressiveCommute = true;
1212 // If it's profitable to commute, try to do so.
1213 if (DoCommute && commuteInstruction(MI, DstOpIdx, BaseOpIdx, OtherOpIdx,
1216 if (AggressiveCommute)
1224 /// For the case where an instruction has a single pair of tied register
1225 /// operands, attempt some transformations that may either eliminate the tied
1226 /// operands or improve the opportunities for coalescing away the register copy.
1227 /// Returns true if no copy needs to be inserted to untie mi's operands
1228 /// (either because they were untied, or because mi was rescheduled, and will
1229 /// be visited again later). If the shouldOnlyCommute flag is true, only
1230 /// instruction commutation is attempted.
1231 bool TwoAddressInstructionPass::
1232 tryInstructionTransform(MachineBasicBlock::iterator &mi,
1233 MachineBasicBlock::iterator &nmi,
1234 unsigned SrcIdx, unsigned DstIdx,
1235 unsigned Dist, bool shouldOnlyCommute) {
1236 if (OptLevel == CodeGenOpt::None)
1239 MachineInstr &MI = *mi;
1240 unsigned regA = MI.getOperand(DstIdx).getReg();
1241 unsigned regB = MI.getOperand(SrcIdx).getReg();
1243 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1244 "cannot make instruction into two-address form");
1245 bool regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
1247 if (TargetRegisterInfo::isVirtualRegister(regA))
1250 bool Commuted = tryInstructionCommute(&MI, DstIdx, SrcIdx, regBKilled, Dist);
1252 // If the instruction is convertible to 3 Addr, instead
1253 // of returning try 3 Addr transformation aggresively and
1254 // use this variable to check later. Because it might be better.
1255 // For example, we can just use `leal (%rsi,%rdi), %eax` and `ret`
1256 // instead of the following code.
1260 if (Commuted && !MI.isConvertibleTo3Addr())
1263 if (shouldOnlyCommute)
1266 // If there is one more use of regB later in the same MBB, consider
1267 // re-schedule this MI below it.
1268 if (!Commuted && EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) {
1273 // If we commuted, regB may have changed so we should re-sample it to avoid
1274 // confusing the three address conversion below.
1276 regB = MI.getOperand(SrcIdx).getReg();
1277 regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
1280 if (MI.isConvertibleTo3Addr()) {
1281 // This instruction is potentially convertible to a true
1282 // three-address instruction. Check if it is profitable.
1283 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
1284 // Try to convert it.
1285 if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
1286 ++NumConvertedTo3Addr;
1287 return true; // Done with this instruction.
1292 // Return if it is commuted but 3 addr conversion is failed.
1296 // If there is one more use of regB later in the same MBB, consider
1297 // re-schedule it before this MI if it's legal.
1298 if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) {
1303 // If this is an instruction with a load folded into it, try unfolding
1304 // the load, e.g. avoid this:
1306 // addq (%rax), %rcx
1307 // in favor of this:
1308 // movq (%rax), %rcx
1310 // because it's preferable to schedule a load than a register copy.
1311 if (MI.mayLoad() && !regBKilled) {
1312 // Determine if a load can be unfolded.
1313 unsigned LoadRegIndex;
1315 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1316 /*UnfoldLoad=*/true,
1317 /*UnfoldStore=*/false,
1320 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1321 if (UnfoldMCID.getNumDefs() == 1) {
1323 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
1324 const TargetRegisterClass *RC =
1325 TRI->getAllocatableClass(
1326 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
1327 unsigned Reg = MRI->createVirtualRegister(RC);
1328 SmallVector<MachineInstr *, 2> NewMIs;
1329 if (!TII->unfoldMemoryOperand(*MF, MI, Reg,
1330 /*UnfoldLoad=*/true,
1331 /*UnfoldStore=*/false, NewMIs)) {
1332 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1335 assert(NewMIs.size() == 2 &&
1336 "Unfolded a load into multiple instructions!");
1337 // The load was previously folded, so this is the only use.
1338 NewMIs[1]->addRegisterKilled(Reg, TRI);
1340 // Tentatively insert the instructions into the block so that they
1341 // look "normal" to the transformation logic.
1342 MBB->insert(mi, NewMIs[0]);
1343 MBB->insert(mi, NewMIs[1]);
1345 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1346 << "2addr: NEW INST: " << *NewMIs[1]);
1348 // Transform the instruction, now that it no longer has a load.
1349 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1350 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1351 MachineBasicBlock::iterator NewMI = NewMIs[1];
1352 bool TransformResult =
1353 tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true);
1354 (void)TransformResult;
1355 assert(!TransformResult &&
1356 "tryInstructionTransform() should return false.");
1357 if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1358 // Success, or at least we made an improvement. Keep the unfolded
1359 // instructions and discard the original.
1361 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1362 MachineOperand &MO = MI.getOperand(i);
1364 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1367 if (NewMIs[0]->killsRegister(MO.getReg()))
1368 LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[0]);
1370 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1371 "Kill missing after load unfold!");
1372 LV->replaceKillInstruction(MO.getReg(), MI, *NewMIs[1]);
1375 } else if (LV->removeVirtualRegisterDead(MO.getReg(), MI)) {
1376 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1377 LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[1]);
1379 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1380 "Dead flag missing after load unfold!");
1381 LV->addVirtualRegisterDead(MO.getReg(), *NewMIs[0]);
1386 LV->addVirtualRegisterKilled(Reg, *NewMIs[1]);
1389 SmallVector<unsigned, 4> OrigRegs;
1391 for (const MachineOperand &MO : MI.operands()) {
1393 OrigRegs.push_back(MO.getReg());
1397 MI.eraseFromParent();
1399 // Update LiveIntervals.
1401 MachineBasicBlock::iterator Begin(NewMIs[0]);
1402 MachineBasicBlock::iterator End(NewMIs[1]);
1403 LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs);
1408 // Transforming didn't eliminate the tie and didn't lead to an
1409 // improvement. Clean up the unfolded instructions and keep the
1411 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1412 NewMIs[0]->eraseFromParent();
1413 NewMIs[1]->eraseFromParent();
1422 // Collect tied operands of MI that need to be handled.
1423 // Rewrite trivial cases immediately.
1424 // Return true if any tied operands where found, including the trivial ones.
1425 bool TwoAddressInstructionPass::
1426 collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
1427 const MCInstrDesc &MCID = MI->getDesc();
1428 bool AnyOps = false;
1429 unsigned NumOps = MI->getNumOperands();
1431 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1432 unsigned DstIdx = 0;
1433 if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1436 MachineOperand &SrcMO = MI->getOperand(SrcIdx);
1437 MachineOperand &DstMO = MI->getOperand(DstIdx);
1438 unsigned SrcReg = SrcMO.getReg();
1439 unsigned DstReg = DstMO.getReg();
1440 // Tied constraint already satisfied?
1441 if (SrcReg == DstReg)
1444 assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
1446 // Deal with <undef> uses immediately - simply rewrite the src operand.
1447 if (SrcMO.isUndef() && !DstMO.getSubReg()) {
1448 // Constrain the DstReg register class if required.
1449 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1450 if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
1452 MRI->constrainRegClass(DstReg, RC);
1453 SrcMO.setReg(DstReg);
1455 DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
1458 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
1463 // Process a list of tied MI operands that all use the same source register.
1464 // The tied pairs are of the form (SrcIdx, DstIdx).
1466 TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
1467 TiedPairList &TiedPairs,
1469 bool IsEarlyClobber = false;
1470 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1471 const MachineOperand &DstMO = MI->getOperand(TiedPairs[tpi].second);
1472 IsEarlyClobber |= DstMO.isEarlyClobber();
1475 bool RemovedKillFlag = false;
1476 bool AllUsesCopied = true;
1477 unsigned LastCopiedReg = 0;
1478 SlotIndex LastCopyIdx;
1480 unsigned SubRegB = 0;
1481 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1482 unsigned SrcIdx = TiedPairs[tpi].first;
1483 unsigned DstIdx = TiedPairs[tpi].second;
1485 const MachineOperand &DstMO = MI->getOperand(DstIdx);
1486 unsigned RegA = DstMO.getReg();
1488 // Grab RegB from the instruction because it may have changed if the
1489 // instruction was commuted.
1490 RegB = MI->getOperand(SrcIdx).getReg();
1491 SubRegB = MI->getOperand(SrcIdx).getSubReg();
1494 // The register is tied to multiple destinations (or else we would
1495 // not have continued this far), but this use of the register
1496 // already matches the tied destination. Leave it.
1497 AllUsesCopied = false;
1500 LastCopiedReg = RegA;
1502 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1503 "cannot make instruction into two-address form");
1506 // First, verify that we don't have a use of "a" in the instruction
1507 // (a = b + a for example) because our transformation will not
1508 // work. This should never occur because we are in SSA form.
1509 for (unsigned i = 0; i != MI->getNumOperands(); ++i)
1510 assert(i == DstIdx ||
1511 !MI->getOperand(i).isReg() ||
1512 MI->getOperand(i).getReg() != RegA);
1516 MachineInstrBuilder MIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1517 TII->get(TargetOpcode::COPY), RegA);
1518 // If this operand is folding a truncation, the truncation now moves to the
1519 // copy so that the register classes remain valid for the operands.
1520 MIB.addReg(RegB, 0, SubRegB);
1521 const TargetRegisterClass *RC = MRI->getRegClass(RegB);
1523 if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1524 assert(TRI->getMatchingSuperRegClass(RC, MRI->getRegClass(RegA),
1526 "tied subregister must be a truncation");
1527 // The superreg class will not be used to constrain the subreg class.
1531 assert(TRI->getMatchingSuperReg(RegA, SubRegB, MRI->getRegClass(RegB))
1532 && "tied subregister must be a truncation");
1536 // Update DistanceMap.
1537 MachineBasicBlock::iterator PrevMI = MI;
1539 DistanceMap.insert(std::make_pair(&*PrevMI, Dist));
1540 DistanceMap[MI] = ++Dist;
1543 LastCopyIdx = LIS->InsertMachineInstrInMaps(*PrevMI).getRegSlot();
1545 if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1546 LiveInterval &LI = LIS->getInterval(RegA);
1547 VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1549 LIS->getInstructionIndex(*MI).getRegSlot(IsEarlyClobber);
1550 LI.addSegment(LiveInterval::Segment(LastCopyIdx, endIdx, VNI));
1554 DEBUG(dbgs() << "\t\tprepend:\t" << *MIB);
1556 MachineOperand &MO = MI->getOperand(SrcIdx);
1557 assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
1558 "inconsistent operand info for 2-reg pass");
1560 MO.setIsKill(false);
1561 RemovedKillFlag = true;
1564 // Make sure regA is a legal regclass for the SrcIdx operand.
1565 if (TargetRegisterInfo::isVirtualRegister(RegA) &&
1566 TargetRegisterInfo::isVirtualRegister(RegB))
1567 MRI->constrainRegClass(RegA, RC);
1569 // The getMatchingSuper asserts guarantee that the register class projected
1570 // by SubRegB is compatible with RegA with no subregister. So regardless of
1571 // whether the dest oper writes a subreg, the source oper should not.
1574 // Propagate SrcRegMap.
1575 SrcRegMap[RegA] = RegB;
1578 if (AllUsesCopied) {
1579 if (!IsEarlyClobber) {
1580 // Replace other (un-tied) uses of regB with LastCopiedReg.
1581 for (MachineOperand &MO : MI->operands()) {
1582 if (MO.isReg() && MO.getReg() == RegB &&
1585 MO.setIsKill(false);
1586 RemovedKillFlag = true;
1588 MO.setReg(LastCopiedReg);
1589 MO.setSubReg(MO.getSubReg());
1594 // Update live variables for regB.
1595 if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(*MI)) {
1596 MachineBasicBlock::iterator PrevMI = MI;
1598 LV->addVirtualRegisterKilled(RegB, *PrevMI);
1601 // Update LiveIntervals.
1603 LiveInterval &LI = LIS->getInterval(RegB);
1604 SlotIndex MIIdx = LIS->getInstructionIndex(*MI);
1605 LiveInterval::const_iterator I = LI.find(MIIdx);
1606 assert(I != LI.end() && "RegB must be live-in to use.");
1608 SlotIndex UseIdx = MIIdx.getRegSlot(IsEarlyClobber);
1609 if (I->end == UseIdx)
1610 LI.removeSegment(LastCopyIdx, UseIdx);
1613 } else if (RemovedKillFlag) {
1614 // Some tied uses of regB matched their destination registers, so
1615 // regB is still used in this instruction, but a kill flag was
1616 // removed from a different tied use of regB, so now we need to add
1617 // a kill flag to one of the remaining uses of regB.
1618 for (MachineOperand &MO : MI->operands()) {
1619 if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1627 /// Reduce two-address instructions to two operands.
1628 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
1630 const TargetMachine &TM = MF->getTarget();
1631 MRI = &MF->getRegInfo();
1632 TII = MF->getSubtarget().getInstrInfo();
1633 TRI = MF->getSubtarget().getRegisterInfo();
1634 InstrItins = MF->getSubtarget().getInstrItineraryData();
1635 LV = getAnalysisIfAvailable<LiveVariables>();
1636 LIS = getAnalysisIfAvailable<LiveIntervals>();
1637 if (auto *AAPass = getAnalysisIfAvailable<AAResultsWrapperPass>())
1638 AA = &AAPass->getAAResults();
1641 OptLevel = TM.getOptLevel();
1643 bool MadeChange = false;
1645 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
1646 DEBUG(dbgs() << "********** Function: "
1647 << MF->getName() << '\n');
1649 // This pass takes the function out of SSA form.
1652 TiedOperandMap TiedOperands;
1653 for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
1654 MBBI != MBBE; ++MBBI) {
1657 DistanceMap.clear();
1661 for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
1663 MachineBasicBlock::iterator nmi = std::next(mi);
1664 if (mi->isDebugValue()) {
1669 // Expand REG_SEQUENCE instructions. This will position mi at the first
1670 // expanded instruction.
1671 if (mi->isRegSequence())
1672 eliminateRegSequence(mi);
1674 DistanceMap.insert(std::make_pair(&*mi, ++Dist));
1678 // First scan through all the tied register uses in this instruction
1679 // and record a list of pairs of tied operands for each register.
1680 if (!collectTiedOperands(&*mi, TiedOperands)) {
1685 ++NumTwoAddressInstrs;
1687 DEBUG(dbgs() << '\t' << *mi);
1689 // If the instruction has a single pair of tied operands, try some
1690 // transformations that may either eliminate the tied operands or
1691 // improve the opportunities for coalescing away the register copy.
1692 if (TiedOperands.size() == 1) {
1693 SmallVectorImpl<std::pair<unsigned, unsigned> > &TiedPairs
1694 = TiedOperands.begin()->second;
1695 if (TiedPairs.size() == 1) {
1696 unsigned SrcIdx = TiedPairs[0].first;
1697 unsigned DstIdx = TiedPairs[0].second;
1698 unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
1699 unsigned DstReg = mi->getOperand(DstIdx).getReg();
1700 if (SrcReg != DstReg &&
1701 tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) {
1702 // The tied operands have been eliminated or shifted further down
1703 // the block to ease elimination. Continue processing with 'nmi'.
1704 TiedOperands.clear();
1711 // Now iterate over the information collected above.
1712 for (auto &TO : TiedOperands) {
1713 processTiedPairs(&*mi, TO.second, Dist);
1714 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1717 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1718 if (mi->isInsertSubreg()) {
1719 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1720 // To %reg:subidx = COPY %subreg
1721 unsigned SubIdx = mi->getOperand(3).getImm();
1722 mi->RemoveOperand(3);
1723 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1724 mi->getOperand(0).setSubReg(SubIdx);
1725 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1726 mi->RemoveOperand(1);
1727 mi->setDesc(TII->get(TargetOpcode::COPY));
1728 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
1731 // Clear TiedOperands here instead of at the top of the loop
1732 // since most instructions do not have tied operands.
1733 TiedOperands.clear();
1739 MF->verify(this, "After two-address instruction pass");
1744 /// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process.
1746 /// The instruction is turned into a sequence of sub-register copies:
1748 /// %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1
1752 /// %dst:ssub0<def,undef> = COPY %v1
1753 /// %dst:ssub1<def> = COPY %v2
1755 void TwoAddressInstructionPass::
1756 eliminateRegSequence(MachineBasicBlock::iterator &MBBI) {
1757 MachineInstr &MI = *MBBI;
1758 unsigned DstReg = MI.getOperand(0).getReg();
1759 if (MI.getOperand(0).getSubReg() ||
1760 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1761 !(MI.getNumOperands() & 1)) {
1762 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << MI);
1763 llvm_unreachable(nullptr);
1766 SmallVector<unsigned, 4> OrigRegs;
1768 OrigRegs.push_back(MI.getOperand(0).getReg());
1769 for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2)
1770 OrigRegs.push_back(MI.getOperand(i).getReg());
1773 bool DefEmitted = false;
1774 for (unsigned i = 1, e = MI.getNumOperands(); i < e; i += 2) {
1775 MachineOperand &UseMO = MI.getOperand(i);
1776 unsigned SrcReg = UseMO.getReg();
1777 unsigned SubIdx = MI.getOperand(i+1).getImm();
1778 // Nothing needs to be inserted for <undef> operands.
1779 if (UseMO.isUndef())
1782 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1783 // might insert a COPY that uses SrcReg after is was killed.
1784 bool isKill = UseMO.isKill();
1786 for (unsigned j = i + 2; j < e; j += 2)
1787 if (MI.getOperand(j).getReg() == SrcReg) {
1788 MI.getOperand(j).setIsKill();
1789 UseMO.setIsKill(false);
1794 // Insert the sub-register copy.
1795 MachineInstr *CopyMI = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
1796 TII->get(TargetOpcode::COPY))
1797 .addReg(DstReg, RegState::Define, SubIdx)
1800 // The first def needs an <undef> flag because there is no live register
1803 CopyMI->getOperand(0).setIsUndef(true);
1804 // Return an iterator pointing to the first inserted instr.
1809 // Update LiveVariables' kill info.
1810 if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
1811 LV->replaceKillInstruction(SrcReg, MI, *CopyMI);
1813 DEBUG(dbgs() << "Inserted: " << *CopyMI);
1816 MachineBasicBlock::iterator EndMBBI =
1817 std::next(MachineBasicBlock::iterator(MI));
1820 DEBUG(dbgs() << "Turned: " << MI << " into an IMPLICIT_DEF");
1821 MI.setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1822 for (int j = MI.getNumOperands() - 1, ee = 0; j > ee; --j)
1823 MI.RemoveOperand(j);
1825 DEBUG(dbgs() << "Eliminated: " << MI);
1826 MI.eraseFromParent();
1829 // Udpate LiveIntervals.
1831 LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs);