1 //===-- TwoAddressInstructionPass.cpp - Two-Address instruction pass ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the TwoAddress instruction pass which is used
11 // by most register allocators. Two-Address instructions are rewritten
21 // Note that if a register allocator chooses to use this pass, that it
22 // has to be capable of handling the non-SSA nature of these rewritten
25 // It is also worth noting that the duplicate operand of the two
26 // address instruction is removed.
28 //===----------------------------------------------------------------------===//
30 #define DEBUG_TYPE "twoaddrinstr"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/Function.h"
33 #include "llvm/CodeGen/LiveVariables.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineInstr.h"
36 #include "llvm/CodeGen/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/Analysis/AliasAnalysis.h"
39 #include "llvm/MC/MCInstrItineraries.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/ADT/BitVector.h"
47 #include "llvm/ADT/DenseMap.h"
48 #include "llvm/ADT/SmallSet.h"
49 #include "llvm/ADT/Statistic.h"
50 #include "llvm/ADT/STLExtras.h"
53 STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
54 STATISTIC(NumCommuted , "Number of instructions commuted to coalesce");
55 STATISTIC(NumAggrCommuted , "Number of instructions aggressively commuted");
56 STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
57 STATISTIC(Num3AddrSunk, "Number of 3-address instructions sunk");
58 STATISTIC(NumDeletes, "Number of dead instructions deleted");
59 STATISTIC(NumReSchedUps, "Number of instructions re-scheduled up");
60 STATISTIC(NumReSchedDowns, "Number of instructions re-scheduled down");
63 class TwoAddressInstructionPass : public MachineFunctionPass {
64 const TargetInstrInfo *TII;
65 const TargetRegisterInfo *TRI;
66 const InstrItineraryData *InstrItins;
67 MachineRegisterInfo *MRI;
70 CodeGenOpt::Level OptLevel;
72 // DistanceMap - Keep track the distance of a MI from the start of the
73 // current basic block.
74 DenseMap<MachineInstr*, unsigned> DistanceMap;
76 // SrcRegMap - A map from virtual registers to physical registers which
77 // are likely targets to be coalesced to due to copies from physical
78 // registers to virtual registers. e.g. v1024 = move r0.
79 DenseMap<unsigned, unsigned> SrcRegMap;
81 // DstRegMap - A map from virtual registers to physical registers which
82 // are likely targets to be coalesced to due to copies to physical
83 // registers from virtual registers. e.g. r1 = move v1024.
84 DenseMap<unsigned, unsigned> DstRegMap;
86 /// RegSequences - Keep track the list of REG_SEQUENCE instructions seen
87 /// during the initial walk of the machine function.
88 SmallVector<MachineInstr*, 16> RegSequences;
90 bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
92 MachineBasicBlock::iterator OldPos);
94 bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
97 MachineInstr *FindLastUseInMBB(unsigned Reg, MachineBasicBlock *MBB,
100 bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
101 MachineInstr *MI, MachineBasicBlock *MBB,
104 bool CommuteInstruction(MachineBasicBlock::iterator &mi,
105 MachineFunction::iterator &mbbi,
106 unsigned RegB, unsigned RegC, unsigned Dist);
108 bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
110 bool ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
111 MachineBasicBlock::iterator &nmi,
112 MachineFunction::iterator &mbbi,
113 unsigned RegA, unsigned RegB, unsigned Dist);
115 typedef std::pair<std::pair<unsigned, bool>, MachineInstr*> NewKill;
116 bool canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
117 SmallVector<NewKill, 4> &NewKills,
118 MachineBasicBlock *MBB, unsigned Dist);
119 bool DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
120 MachineBasicBlock::iterator &nmi,
121 MachineFunction::iterator &mbbi, unsigned Dist);
123 bool isDefTooClose(unsigned Reg, unsigned Dist,
124 MachineInstr *MI, MachineBasicBlock *MBB);
126 bool RescheduleMIBelowKill(MachineBasicBlock *MBB,
127 MachineBasicBlock::iterator &mi,
128 MachineBasicBlock::iterator &nmi,
130 bool RescheduleKillAboveMI(MachineBasicBlock *MBB,
131 MachineBasicBlock::iterator &mi,
132 MachineBasicBlock::iterator &nmi,
135 bool TryInstructionTransform(MachineBasicBlock::iterator &mi,
136 MachineBasicBlock::iterator &nmi,
137 MachineFunction::iterator &mbbi,
138 unsigned SrcIdx, unsigned DstIdx,
140 SmallPtrSet<MachineInstr*, 8> &Processed);
142 void ScanUses(unsigned DstReg, MachineBasicBlock *MBB,
143 SmallPtrSet<MachineInstr*, 8> &Processed);
145 void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
146 SmallPtrSet<MachineInstr*, 8> &Processed);
148 void CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs, unsigned DstReg);
150 /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
151 /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
152 /// sub-register references of the register defined by REG_SEQUENCE.
153 bool EliminateRegSequences();
156 static char ID; // Pass identification, replacement for typeid
157 TwoAddressInstructionPass() : MachineFunctionPass(ID) {
158 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
161 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
162 AU.setPreservesCFG();
163 AU.addRequired<AliasAnalysis>();
164 AU.addPreserved<LiveVariables>();
165 AU.addPreservedID(MachineLoopInfoID);
166 AU.addPreservedID(MachineDominatorsID);
167 MachineFunctionPass::getAnalysisUsage(AU);
170 /// runOnMachineFunction - Pass entry point.
171 bool runOnMachineFunction(MachineFunction&);
175 char TwoAddressInstructionPass::ID = 0;
176 INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
177 "Two-Address instruction pass", false, false)
178 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
179 INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
180 "Two-Address instruction pass", false, false)
182 char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
184 /// Sink3AddrInstruction - A two-address instruction has been converted to a
185 /// three-address instruction to avoid clobbering a register. Try to sink it
186 /// past the instruction that would kill the above mentioned register to reduce
187 /// register pressure.
188 bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
189 MachineInstr *MI, unsigned SavedReg,
190 MachineBasicBlock::iterator OldPos) {
191 // FIXME: Shouldn't we be trying to do this before we three-addressify the
192 // instruction? After this transformation is done, we no longer need
193 // the instruction to be in three-address form.
195 // Check if it's safe to move this instruction.
196 bool SeenStore = true; // Be conservative.
197 if (!MI->isSafeToMove(TII, AA, SeenStore))
201 SmallSet<unsigned, 4> UseRegs;
203 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
204 const MachineOperand &MO = MI->getOperand(i);
207 unsigned MOReg = MO.getReg();
210 if (MO.isUse() && MOReg != SavedReg)
211 UseRegs.insert(MO.getReg());
215 // Don't try to move it if it implicitly defines a register.
218 // For now, don't move any instructions that define multiple registers.
220 DefReg = MO.getReg();
223 // Find the instruction that kills SavedReg.
224 MachineInstr *KillMI = NULL;
225 for (MachineRegisterInfo::use_nodbg_iterator
226 UI = MRI->use_nodbg_begin(SavedReg),
227 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
228 MachineOperand &UseMO = UI.getOperand();
231 KillMI = UseMO.getParent();
235 // If we find the instruction that kills SavedReg, and it is in an
236 // appropriate location, we can try to sink the current instruction
238 if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
239 KillMI->isTerminator())
242 // If any of the definitions are used by another instruction between the
243 // position and the kill use, then it's not safe to sink it.
245 // FIXME: This can be sped up if there is an easy way to query whether an
246 // instruction is before or after another instruction. Then we can use
247 // MachineRegisterInfo def / use instead.
248 MachineOperand *KillMO = NULL;
249 MachineBasicBlock::iterator KillPos = KillMI;
252 unsigned NumVisited = 0;
253 for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
254 MachineInstr *OtherMI = I;
255 // DBG_VALUE cannot be counted against the limit.
256 if (OtherMI->isDebugValue())
258 if (NumVisited > 30) // FIXME: Arbitrary limit to reduce compile time cost.
261 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
262 MachineOperand &MO = OtherMI->getOperand(i);
265 unsigned MOReg = MO.getReg();
272 if (OtherMI == KillMI && MOReg == SavedReg)
273 // Save the operand that kills the register. We want to unset the kill
274 // marker if we can sink MI past it.
276 else if (UseRegs.count(MOReg))
277 // One of the uses is killed before the destination.
283 // Update kill and LV information.
284 KillMO->setIsKill(false);
285 KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
286 KillMO->setIsKill(true);
289 LV->replaceKillInstruction(SavedReg, KillMI, MI);
291 // Move instruction to its destination.
293 MBB->insert(KillPos, MI);
299 /// NoUseAfterLastDef - Return true if there are no intervening uses between the
300 /// last instruction in the MBB that defines the specified register and the
301 /// two-address instruction which is being processed. It also returns the last
302 /// def location by reference
303 bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
304 MachineBasicBlock *MBB, unsigned Dist,
307 unsigned LastUse = Dist;
308 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
309 E = MRI->reg_end(); I != E; ++I) {
310 MachineOperand &MO = I.getOperand();
311 MachineInstr *MI = MO.getParent();
312 if (MI->getParent() != MBB || MI->isDebugValue())
314 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
315 if (DI == DistanceMap.end())
317 if (MO.isUse() && DI->second < LastUse)
318 LastUse = DI->second;
319 if (MO.isDef() && DI->second > LastDef)
320 LastDef = DI->second;
323 return !(LastUse > LastDef && LastUse < Dist);
326 MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg,
327 MachineBasicBlock *MBB,
329 unsigned LastUseDist = 0;
330 MachineInstr *LastUse = 0;
331 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
332 E = MRI->reg_end(); I != E; ++I) {
333 MachineOperand &MO = I.getOperand();
334 MachineInstr *MI = MO.getParent();
335 if (MI->getParent() != MBB || MI->isDebugValue())
337 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
338 if (DI == DistanceMap.end())
340 if (DI->second >= Dist)
343 if (MO.isUse() && DI->second > LastUseDist) {
345 LastUseDist = DI->second;
351 /// isCopyToReg - Return true if the specified MI is a copy instruction or
352 /// a extract_subreg instruction. It also returns the source and destination
353 /// registers and whether they are physical registers by reference.
354 static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
355 unsigned &SrcReg, unsigned &DstReg,
356 bool &IsSrcPhys, bool &IsDstPhys) {
360 DstReg = MI.getOperand(0).getReg();
361 SrcReg = MI.getOperand(1).getReg();
362 } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
363 DstReg = MI.getOperand(0).getReg();
364 SrcReg = MI.getOperand(2).getReg();
368 IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
369 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
373 /// isKilled - Test if the given register value, which is used by the given
374 /// instruction, is killed by the given instruction. This looks through
375 /// coalescable copies to see if the original value is potentially not killed.
377 /// For example, in this code:
379 /// %reg1034 = copy %reg1024
380 /// %reg1035 = copy %reg1025<kill>
381 /// %reg1036 = add %reg1034<kill>, %reg1035<kill>
383 /// %reg1034 is not considered to be killed, since it is copied from a
384 /// register which is not killed. Treating it as not killed lets the
385 /// normal heuristics commute the (two-address) add, which lets
386 /// coalescing eliminate the extra copy.
388 static bool isKilled(MachineInstr &MI, unsigned Reg,
389 const MachineRegisterInfo *MRI,
390 const TargetInstrInfo *TII) {
391 MachineInstr *DefMI = &MI;
393 if (!DefMI->killsRegister(Reg))
395 if (TargetRegisterInfo::isPhysicalRegister(Reg))
397 MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
398 // If there are multiple defs, we can't do a simple analysis, so just
399 // go with what the kill flag says.
400 if (llvm::next(Begin) != MRI->def_end())
403 bool IsSrcPhys, IsDstPhys;
404 unsigned SrcReg, DstReg;
405 // If the def is something other than a copy, then it isn't going to
406 // be coalesced, so follow the kill flag.
407 if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
413 /// isTwoAddrUse - Return true if the specified MI uses the specified register
414 /// as a two-address use. If so, return the destination register by reference.
415 static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
416 const MCInstrDesc &MCID = MI.getDesc();
417 unsigned NumOps = MI.isInlineAsm()
418 ? MI.getNumOperands() : MCID.getNumOperands();
419 for (unsigned i = 0; i != NumOps; ++i) {
420 const MachineOperand &MO = MI.getOperand(i);
421 if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
424 if (MI.isRegTiedToDefOperand(i, &ti)) {
425 DstReg = MI.getOperand(ti).getReg();
432 /// findOnlyInterestingUse - Given a register, if has a single in-basic block
433 /// use, return the use instruction if it's a copy or a two-address use.
435 MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
436 MachineRegisterInfo *MRI,
437 const TargetInstrInfo *TII,
439 unsigned &DstReg, bool &IsDstPhys) {
440 if (!MRI->hasOneNonDBGUse(Reg))
441 // None or more than one use.
443 MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg);
444 if (UseMI.getParent() != MBB)
448 if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
453 if (isTwoAddrUse(UseMI, Reg, DstReg)) {
454 IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
460 /// getMappedReg - Return the physical register the specified virtual register
461 /// might be mapped to.
463 getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
464 while (TargetRegisterInfo::isVirtualRegister(Reg)) {
465 DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
466 if (SI == RegMap.end())
470 if (TargetRegisterInfo::isPhysicalRegister(Reg))
475 /// regsAreCompatible - Return true if the two registers are equal or aliased.
478 regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
483 return TRI->regsOverlap(RegA, RegB);
487 /// isProfitableToCommute - Return true if it's potentially profitable to commute
488 /// the two-address instruction that's being processed.
490 TwoAddressInstructionPass::isProfitableToCommute(unsigned regA, unsigned regB,
492 MachineInstr *MI, MachineBasicBlock *MBB,
494 if (OptLevel == CodeGenOpt::None)
497 // Determine if it's profitable to commute this two address instruction. In
498 // general, we want no uses between this instruction and the definition of
499 // the two-address register.
501 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
502 // %reg1029<def> = MOV8rr %reg1028
503 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
504 // insert => %reg1030<def> = MOV8rr %reg1028
505 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
506 // In this case, it might not be possible to coalesce the second MOV8rr
507 // instruction if the first one is coalesced. So it would be profitable to
509 // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
510 // %reg1029<def> = MOV8rr %reg1028
511 // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
512 // insert => %reg1030<def> = MOV8rr %reg1029
513 // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
515 if (!MI->killsRegister(regC))
518 // Ok, we have something like:
519 // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
520 // let's see if it's worth commuting it.
522 // Look for situations like this:
523 // %reg1024<def> = MOV r1
524 // %reg1025<def> = MOV r0
525 // %reg1026<def> = ADD %reg1024, %reg1025
527 // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
528 unsigned ToRegA = getMappedReg(regA, DstRegMap);
530 unsigned FromRegB = getMappedReg(regB, SrcRegMap);
531 unsigned FromRegC = getMappedReg(regC, SrcRegMap);
532 bool BComp = !FromRegB || regsAreCompatible(FromRegB, ToRegA, TRI);
533 bool CComp = !FromRegC || regsAreCompatible(FromRegC, ToRegA, TRI);
535 return !BComp && CComp;
538 // If there is a use of regC between its last def (could be livein) and this
539 // instruction, then bail.
540 unsigned LastDefC = 0;
541 if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
544 // If there is a use of regB between its last def (could be livein) and this
545 // instruction, then go ahead and make this transformation.
546 unsigned LastDefB = 0;
547 if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
550 // Since there are no intervening uses for both registers, then commute
551 // if the def of regC is closer. Its live interval is shorter.
552 return LastDefB && LastDefC && LastDefC > LastDefB;
555 /// CommuteInstruction - Commute a two-address instruction and update the basic
556 /// block, distance map, and live variables if needed. Return true if it is
559 TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
560 MachineFunction::iterator &mbbi,
561 unsigned RegB, unsigned RegC, unsigned Dist) {
562 MachineInstr *MI = mi;
563 DEBUG(dbgs() << "2addr: COMMUTING : " << *MI);
564 MachineInstr *NewMI = TII->commuteInstruction(MI);
567 DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
571 DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
572 // If the instruction changed to commute it, update livevar.
575 // Update live variables
576 LV->replaceKillInstruction(RegC, MI, NewMI);
578 mbbi->insert(mi, NewMI); // Insert the new inst
579 mbbi->erase(mi); // Nuke the old inst.
581 DistanceMap.insert(std::make_pair(NewMI, Dist));
584 // Update source register map.
585 unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
587 unsigned RegA = MI->getOperand(0).getReg();
588 SrcRegMap[RegA] = FromRegC;
594 /// isProfitableToConv3Addr - Return true if it is profitable to convert the
595 /// given 2-address instruction to a 3-address one.
597 TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
598 // Look for situations like this:
599 // %reg1024<def> = MOV r1
600 // %reg1025<def> = MOV r0
601 // %reg1026<def> = ADD %reg1024, %reg1025
603 // Turn ADD into a 3-address instruction to avoid a copy.
604 unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
607 unsigned ToRegA = getMappedReg(RegA, DstRegMap);
608 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
611 /// ConvertInstTo3Addr - Convert the specified two-address instruction into a
612 /// three address one. Return true if this transformation was successful.
614 TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
615 MachineBasicBlock::iterator &nmi,
616 MachineFunction::iterator &mbbi,
617 unsigned RegA, unsigned RegB,
619 MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
621 DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
622 DEBUG(dbgs() << "2addr: TO 3-ADDR: " << *NewMI);
625 if (NewMI->findRegisterUseOperand(RegB, false, TRI))
626 // FIXME: Temporary workaround. If the new instruction doesn't
627 // uses RegB, convertToThreeAddress must have created more
628 // then one instruction.
629 Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
631 mbbi->erase(mi); // Nuke the old inst.
634 DistanceMap.insert(std::make_pair(NewMI, Dist));
636 nmi = llvm::next(mi);
639 // Update source and destination register maps.
640 SrcRegMap.erase(RegA);
641 DstRegMap.erase(RegB);
648 /// ScanUses - Scan forward recursively for only uses, update maps if the use
649 /// is a copy or a two-address instruction.
651 TwoAddressInstructionPass::ScanUses(unsigned DstReg, MachineBasicBlock *MBB,
652 SmallPtrSet<MachineInstr*, 8> &Processed) {
653 SmallVector<unsigned, 4> VirtRegPairs;
657 unsigned Reg = DstReg;
658 while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
659 NewReg, IsDstPhys)) {
660 if (IsCopy && !Processed.insert(UseMI))
663 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
664 if (DI != DistanceMap.end())
665 // Earlier in the same MBB.Reached via a back edge.
669 VirtRegPairs.push_back(NewReg);
672 bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
674 assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
675 VirtRegPairs.push_back(NewReg);
679 if (!VirtRegPairs.empty()) {
680 unsigned ToReg = VirtRegPairs.back();
681 VirtRegPairs.pop_back();
682 while (!VirtRegPairs.empty()) {
683 unsigned FromReg = VirtRegPairs.back();
684 VirtRegPairs.pop_back();
685 bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
687 assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
690 bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
692 assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
696 /// ProcessCopy - If the specified instruction is not yet processed, process it
697 /// if it's a copy. For a copy instruction, we find the physical registers the
698 /// source and destination registers might be mapped to. These are kept in
699 /// point-to maps used to determine future optimizations. e.g.
702 /// v1026 = add v1024, v1025
704 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
705 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
706 /// potentially joined with r1 on the output side. It's worthwhile to commute
707 /// 'add' to eliminate a copy.
708 void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
709 MachineBasicBlock *MBB,
710 SmallPtrSet<MachineInstr*, 8> &Processed) {
711 if (Processed.count(MI))
714 bool IsSrcPhys, IsDstPhys;
715 unsigned SrcReg, DstReg;
716 if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
719 if (IsDstPhys && !IsSrcPhys)
720 DstRegMap.insert(std::make_pair(SrcReg, DstReg));
721 else if (!IsDstPhys && IsSrcPhys) {
722 bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
724 assert(SrcRegMap[DstReg] == SrcReg &&
725 "Can't map to two src physical registers!");
727 ScanUses(DstReg, MBB, Processed);
730 Processed.insert(MI);
734 /// isSafeToDelete - If the specified instruction does not produce any side
735 /// effects and all of its defs are dead, then it's safe to delete.
736 static bool isSafeToDelete(MachineInstr *MI,
737 const TargetInstrInfo *TII,
738 SmallVector<unsigned, 4> &Kills) {
739 if (MI->mayStore() || MI->isCall())
741 if (MI->isTerminator() || MI->hasUnmodeledSideEffects())
744 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
745 MachineOperand &MO = MI->getOperand(i);
748 if (MO.isDef() && !MO.isDead())
750 if (MO.isUse() && MO.isKill())
751 Kills.push_back(MO.getReg());
756 /// canUpdateDeletedKills - Check if all the registers listed in Kills are
757 /// killed by instructions in MBB preceding the current instruction at
758 /// position Dist. If so, return true and record information about the
759 /// preceding kills in NewKills.
760 bool TwoAddressInstructionPass::
761 canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
762 SmallVector<NewKill, 4> &NewKills,
763 MachineBasicBlock *MBB, unsigned Dist) {
764 while (!Kills.empty()) {
765 unsigned Kill = Kills.back();
767 if (TargetRegisterInfo::isPhysicalRegister(Kill))
770 MachineInstr *LastKill = FindLastUseInMBB(Kill, MBB, Dist);
774 bool isModRef = LastKill->definesRegister(Kill);
775 NewKills.push_back(std::make_pair(std::make_pair(Kill, isModRef),
781 /// DeleteUnusedInstr - If an instruction with a tied register operand can
782 /// be safely deleted, just delete it.
784 TwoAddressInstructionPass::DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
785 MachineBasicBlock::iterator &nmi,
786 MachineFunction::iterator &mbbi,
788 // Check if the instruction has no side effects and if all its defs are dead.
789 SmallVector<unsigned, 4> Kills;
790 if (!isSafeToDelete(mi, TII, Kills))
793 // If this instruction kills some virtual registers, we need to
794 // update the kill information. If it's not possible to do so,
796 SmallVector<NewKill, 4> NewKills;
797 if (!canUpdateDeletedKills(Kills, NewKills, &*mbbi, Dist))
801 while (!NewKills.empty()) {
802 MachineInstr *NewKill = NewKills.back().second;
803 unsigned Kill = NewKills.back().first.first;
804 bool isDead = NewKills.back().first.second;
806 if (LV->removeVirtualRegisterKilled(Kill, mi)) {
808 LV->addVirtualRegisterDead(Kill, NewKill);
810 LV->addVirtualRegisterKilled(Kill, NewKill);
815 mbbi->erase(mi); // Nuke the old inst.
820 /// RescheduleMIBelowKill - If there is one more local instruction that reads
821 /// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
822 /// instruction in order to eliminate the need for the copy.
824 TwoAddressInstructionPass::RescheduleMIBelowKill(MachineBasicBlock *MBB,
825 MachineBasicBlock::iterator &mi,
826 MachineBasicBlock::iterator &nmi,
828 // Bail immediately if we don't have LV available. We use it to find kills
833 MachineInstr *MI = &*mi;
834 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
835 if (DI == DistanceMap.end())
836 // Must be created from unfolded load. Don't waste time trying this.
839 MachineInstr *KillMI = LV->getVarInfo(Reg).findKill(MBB);
840 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
841 // Don't mess with copies, they may be coalesced later.
844 if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
845 KillMI->isBranch() || KillMI->isTerminator())
846 // Don't move pass calls, etc.
850 if (isTwoAddrUse(*KillMI, Reg, DstReg))
853 bool SeenStore = true;
854 if (!MI->isSafeToMove(TII, AA, SeenStore))
857 if (TII->getInstrLatency(InstrItins, MI) > 1)
858 // FIXME: Needs more sophisticated heuristics.
861 SmallSet<unsigned, 2> Uses;
862 SmallSet<unsigned, 2> Kills;
863 SmallSet<unsigned, 2> Defs;
864 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
865 const MachineOperand &MO = MI->getOperand(i);
868 unsigned MOReg = MO.getReg();
875 if (MO.isKill() && MOReg != Reg)
880 // Move the copies connected to MI down as well.
881 MachineBasicBlock::iterator From = MI;
882 MachineBasicBlock::iterator To = llvm::next(From);
883 while (To->isCopy() && Defs.count(To->getOperand(1).getReg())) {
884 Defs.insert(To->getOperand(0).getReg());
888 // Check if the reschedule will not break depedencies.
889 unsigned NumVisited = 0;
890 MachineBasicBlock::iterator KillPos = KillMI;
892 for (MachineBasicBlock::iterator I = To; I != KillPos; ++I) {
893 MachineInstr *OtherMI = I;
894 // DBG_VALUE cannot be counted against the limit.
895 if (OtherMI->isDebugValue())
897 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
900 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
901 OtherMI->isBranch() || OtherMI->isTerminator())
902 // Don't move pass calls, etc.
904 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
905 const MachineOperand &MO = OtherMI->getOperand(i);
908 unsigned MOReg = MO.getReg();
912 if (Uses.count(MOReg))
913 // Physical register use would be clobbered.
915 if (!MO.isDead() && Defs.count(MOReg))
916 // May clobber a physical register def.
917 // FIXME: This may be too conservative. It's ok if the instruction
918 // is sunken completely below the use.
921 if (Defs.count(MOReg))
924 ((MO.isKill() && Uses.count(MOReg)) || Kills.count(MOReg)))
925 // Don't want to extend other live ranges and update kills.
927 if (MOReg == Reg && !MO.isKill())
928 // We can't schedule across a use of the register in question.
930 // Ensure that if this is register in question, its the kill we expect.
931 assert((MOReg != Reg || OtherMI == KillMI) &&
932 "Found multiple kills of a register in a basic block");
937 // Move debug info as well.
938 while (From != MBB->begin() && llvm::prior(From)->isDebugValue())
941 // Copies following MI may have been moved as well.
943 MBB->splice(KillPos, MBB, From, To);
944 DistanceMap.erase(DI);
946 // Update live variables
947 LV->removeVirtualRegisterKilled(Reg, KillMI);
948 LV->addVirtualRegisterKilled(Reg, MI);
950 DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
954 /// isDefTooClose - Return true if the re-scheduling will put the given
955 /// instruction too close to the defs of its register dependencies.
956 bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
958 MachineBasicBlock *MBB) {
959 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(Reg),
960 DE = MRI->def_end(); DI != DE; ++DI) {
961 MachineInstr *DefMI = &*DI;
962 if (DefMI->getParent() != MBB || DefMI->isCopy() || DefMI->isCopyLike())
965 return true; // MI is defining something KillMI uses
966 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(DefMI);
967 if (DDI == DistanceMap.end())
968 return true; // Below MI
969 unsigned DefDist = DDI->second;
970 assert(Dist > DefDist && "Visited def already?");
971 if (TII->getInstrLatency(InstrItins, DefMI) > (Dist - DefDist))
977 /// RescheduleKillAboveMI - If there is one more local instruction that reads
978 /// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
979 /// current two-address instruction in order to eliminate the need for the
982 TwoAddressInstructionPass::RescheduleKillAboveMI(MachineBasicBlock *MBB,
983 MachineBasicBlock::iterator &mi,
984 MachineBasicBlock::iterator &nmi,
986 // Bail immediately if we don't have LV available. We use it to find kills
991 MachineInstr *MI = &*mi;
992 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
993 if (DI == DistanceMap.end())
994 // Must be created from unfolded load. Don't waste time trying this.
997 MachineInstr *KillMI = LV->getVarInfo(Reg).findKill(MBB);
998 if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
999 // Don't mess with copies, they may be coalesced later.
1003 if (isTwoAddrUse(*KillMI, Reg, DstReg))
1006 bool SeenStore = true;
1007 if (!KillMI->isSafeToMove(TII, AA, SeenStore))
1010 SmallSet<unsigned, 2> Uses;
1011 SmallSet<unsigned, 2> Kills;
1012 SmallSet<unsigned, 2> Defs;
1013 SmallSet<unsigned, 2> LiveDefs;
1014 for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
1015 const MachineOperand &MO = KillMI->getOperand(i);
1018 unsigned MOReg = MO.getReg();
1022 if (isDefTooClose(MOReg, DI->second, MI, MBB))
1024 if (MOReg == Reg && !MO.isKill())
1027 if (MO.isKill() && MOReg != Reg)
1028 Kills.insert(MOReg);
1029 } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1032 LiveDefs.insert(MOReg);
1036 // Check if the reschedule will not break depedencies.
1037 unsigned NumVisited = 0;
1038 MachineBasicBlock::iterator KillPos = KillMI;
1039 for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
1040 MachineInstr *OtherMI = I;
1041 // DBG_VALUE cannot be counted against the limit.
1042 if (OtherMI->isDebugValue())
1044 if (NumVisited > 10) // FIXME: Arbitrary limit to reduce compile time cost.
1047 if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
1048 OtherMI->isBranch() || OtherMI->isTerminator())
1049 // Don't move pass calls, etc.
1051 SmallVector<unsigned, 2> OtherDefs;
1052 for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
1053 const MachineOperand &MO = OtherMI->getOperand(i);
1056 unsigned MOReg = MO.getReg();
1060 if (Defs.count(MOReg))
1061 // Moving KillMI can clobber the physical register if the def has
1064 if (Kills.count(MOReg))
1065 // Don't want to extend other live ranges and update kills.
1067 if (OtherMI != MI && MOReg == Reg && !MO.isKill())
1068 // We can't schedule across a use of the register in question.
1071 OtherDefs.push_back(MOReg);
1075 for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
1076 unsigned MOReg = OtherDefs[i];
1077 if (Uses.count(MOReg))
1079 if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1080 LiveDefs.count(MOReg))
1082 // Physical register def is seen.
1087 // Move the old kill above MI, don't forget to move debug info as well.
1088 MachineBasicBlock::iterator InsertPos = mi;
1089 while (InsertPos != MBB->begin() && llvm::prior(InsertPos)->isDebugValue())
1091 MachineBasicBlock::iterator From = KillMI;
1092 MachineBasicBlock::iterator To = llvm::next(From);
1093 while (llvm::prior(From)->isDebugValue())
1095 MBB->splice(InsertPos, MBB, From, To);
1097 nmi = llvm::prior(InsertPos); // Backtrack so we process the moved instr.
1098 DistanceMap.erase(DI);
1100 // Update live variables
1101 LV->removeVirtualRegisterKilled(Reg, KillMI);
1102 LV->addVirtualRegisterKilled(Reg, MI);
1104 DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
1108 /// TryInstructionTransform - For the case where an instruction has a single
1109 /// pair of tied register operands, attempt some transformations that may
1110 /// either eliminate the tied operands or improve the opportunities for
1111 /// coalescing away the register copy. Returns true if no copy needs to be
1112 /// inserted to untie mi's operands (either because they were untied, or
1113 /// because mi was rescheduled, and will be visited again later).
1114 bool TwoAddressInstructionPass::
1115 TryInstructionTransform(MachineBasicBlock::iterator &mi,
1116 MachineBasicBlock::iterator &nmi,
1117 MachineFunction::iterator &mbbi,
1118 unsigned SrcIdx, unsigned DstIdx, unsigned Dist,
1119 SmallPtrSet<MachineInstr*, 8> &Processed) {
1120 if (OptLevel == CodeGenOpt::None)
1123 MachineInstr &MI = *mi;
1124 unsigned regA = MI.getOperand(DstIdx).getReg();
1125 unsigned regB = MI.getOperand(SrcIdx).getReg();
1127 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1128 "cannot make instruction into two-address form");
1130 // If regA is dead and the instruction can be deleted, just delete
1131 // it so it doesn't clobber regB.
1132 bool regBKilled = isKilled(MI, regB, MRI, TII);
1133 if (!regBKilled && MI.getOperand(DstIdx).isDead() &&
1134 DeleteUnusedInstr(mi, nmi, mbbi, Dist)) {
1136 DEBUG(dbgs() << "\tdeleted unused instruction.\n");
1137 return true; // Done with this instruction."
1140 if (TargetRegisterInfo::isVirtualRegister(regA))
1141 ScanUses(regA, &*mbbi, Processed);
1143 // Check if it is profitable to commute the operands.
1144 unsigned SrcOp1, SrcOp2;
1146 unsigned regCIdx = ~0U;
1147 bool TryCommute = false;
1148 bool AggressiveCommute = false;
1149 if (MI.isCommutable() && MI.getNumOperands() >= 3 &&
1150 TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
1151 if (SrcIdx == SrcOp1)
1153 else if (SrcIdx == SrcOp2)
1156 if (regCIdx != ~0U) {
1157 regC = MI.getOperand(regCIdx).getReg();
1158 if (!regBKilled && isKilled(MI, regC, MRI, TII))
1159 // If C dies but B does not, swap the B and C operands.
1160 // This makes the live ranges of A and C joinable.
1162 else if (isProfitableToCommute(regA, regB, regC, &MI, mbbi, Dist)) {
1164 AggressiveCommute = true;
1169 // If it's profitable to commute, try to do so.
1170 if (TryCommute && CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
1172 if (AggressiveCommute)
1177 // If there is one more use of regB later in the same MBB, consider
1178 // re-schedule this MI below it.
1179 if (RescheduleMIBelowKill(mbbi, mi, nmi, regB)) {
1184 if (MI.isConvertibleTo3Addr()) {
1185 // This instruction is potentially convertible to a true
1186 // three-address instruction. Check if it is profitable.
1187 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
1188 // Try to convert it.
1189 if (ConvertInstTo3Addr(mi, nmi, mbbi, regA, regB, Dist)) {
1190 ++NumConvertedTo3Addr;
1191 return true; // Done with this instruction.
1196 // If there is one more use of regB later in the same MBB, consider
1197 // re-schedule it before this MI if it's legal.
1198 if (RescheduleKillAboveMI(mbbi, mi, nmi, regB)) {
1203 // If this is an instruction with a load folded into it, try unfolding
1204 // the load, e.g. avoid this:
1206 // addq (%rax), %rcx
1207 // in favor of this:
1208 // movq (%rax), %rcx
1210 // because it's preferable to schedule a load than a register copy.
1211 if (MI.mayLoad() && !regBKilled) {
1212 // Determine if a load can be unfolded.
1213 unsigned LoadRegIndex;
1215 TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1216 /*UnfoldLoad=*/true,
1217 /*UnfoldStore=*/false,
1220 const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1221 if (UnfoldMCID.getNumDefs() == 1) {
1222 MachineFunction &MF = *mbbi->getParent();
1225 DEBUG(dbgs() << "2addr: UNFOLDING: " << MI);
1226 const TargetRegisterClass *RC =
1227 TRI->getAllocatableClass(
1228 TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, MF));
1229 unsigned Reg = MRI->createVirtualRegister(RC);
1230 SmallVector<MachineInstr *, 2> NewMIs;
1231 if (!TII->unfoldMemoryOperand(MF, &MI, Reg,
1232 /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
1234 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1237 assert(NewMIs.size() == 2 &&
1238 "Unfolded a load into multiple instructions!");
1239 // The load was previously folded, so this is the only use.
1240 NewMIs[1]->addRegisterKilled(Reg, TRI);
1242 // Tentatively insert the instructions into the block so that they
1243 // look "normal" to the transformation logic.
1244 mbbi->insert(mi, NewMIs[0]);
1245 mbbi->insert(mi, NewMIs[1]);
1247 DEBUG(dbgs() << "2addr: NEW LOAD: " << *NewMIs[0]
1248 << "2addr: NEW INST: " << *NewMIs[1]);
1250 // Transform the instruction, now that it no longer has a load.
1251 unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1252 unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1253 MachineBasicBlock::iterator NewMI = NewMIs[1];
1254 bool TransformSuccess =
1255 TryInstructionTransform(NewMI, mi, mbbi,
1256 NewSrcIdx, NewDstIdx, Dist, Processed);
1257 if (TransformSuccess ||
1258 NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1259 // Success, or at least we made an improvement. Keep the unfolded
1260 // instructions and discard the original.
1262 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1263 MachineOperand &MO = MI.getOperand(i);
1265 TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1268 if (NewMIs[0]->killsRegister(MO.getReg()))
1269 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
1271 assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1272 "Kill missing after load unfold!");
1273 LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
1276 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
1277 if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1278 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
1280 assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1281 "Dead flag missing after load unfold!");
1282 LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
1287 LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
1289 MI.eraseFromParent();
1291 if (TransformSuccess)
1294 // Transforming didn't eliminate the tie and didn't lead to an
1295 // improvement. Clean up the unfolded instructions and keep the
1297 DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1298 NewMIs[0]->eraseFromParent();
1299 NewMIs[1]->eraseFromParent();
1308 /// runOnMachineFunction - Reduce two-address instructions to two operands.
1310 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
1311 const TargetMachine &TM = MF.getTarget();
1312 MRI = &MF.getRegInfo();
1313 TII = TM.getInstrInfo();
1314 TRI = TM.getRegisterInfo();
1315 InstrItins = TM.getInstrItineraryData();
1316 LV = getAnalysisIfAvailable<LiveVariables>();
1317 AA = &getAnalysis<AliasAnalysis>();
1318 OptLevel = TM.getOptLevel();
1320 bool MadeChange = false;
1322 DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
1323 DEBUG(dbgs() << "********** Function: "
1324 << MF.getFunction()->getName() << '\n');
1326 // This pass takes the function out of SSA form.
1329 // ReMatRegs - Keep track of the registers whose def's are remat'ed.
1330 BitVector ReMatRegs(MRI->getNumVirtRegs());
1332 typedef DenseMap<unsigned, SmallVector<std::pair<unsigned, unsigned>, 4> >
1334 TiedOperandMap TiedOperands(4);
1336 SmallPtrSet<MachineInstr*, 8> Processed;
1337 for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
1338 mbbi != mbbe; ++mbbi) {
1340 DistanceMap.clear();
1344 for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
1346 MachineBasicBlock::iterator nmi = llvm::next(mi);
1347 if (mi->isDebugValue()) {
1352 // Remember REG_SEQUENCE instructions, we'll deal with them later.
1353 if (mi->isRegSequence())
1354 RegSequences.push_back(&*mi);
1356 const MCInstrDesc &MCID = mi->getDesc();
1357 bool FirstTied = true;
1359 DistanceMap.insert(std::make_pair(mi, ++Dist));
1361 ProcessCopy(&*mi, &*mbbi, Processed);
1363 // First scan through all the tied register uses in this instruction
1364 // and record a list of pairs of tied operands for each register.
1365 unsigned NumOps = mi->isInlineAsm()
1366 ? mi->getNumOperands() : MCID.getNumOperands();
1367 for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1368 unsigned DstIdx = 0;
1369 if (!mi->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1374 ++NumTwoAddressInstrs;
1375 DEBUG(dbgs() << '\t' << *mi);
1378 assert(mi->getOperand(SrcIdx).isReg() &&
1379 mi->getOperand(SrcIdx).getReg() &&
1380 mi->getOperand(SrcIdx).isUse() &&
1381 "two address instruction invalid");
1383 unsigned regB = mi->getOperand(SrcIdx).getReg();
1385 // Deal with <undef> uses immediately - simply rewrite the src operand.
1386 if (mi->getOperand(SrcIdx).isUndef()) {
1387 unsigned DstReg = mi->getOperand(DstIdx).getReg();
1388 // Constrain the DstReg register class if required.
1389 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1390 if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
1392 MRI->constrainRegClass(DstReg, RC);
1393 mi->getOperand(SrcIdx).setReg(DstReg);
1394 DEBUG(dbgs() << "\t\trewrite undef:\t" << *mi);
1397 TiedOperands[regB].push_back(std::make_pair(SrcIdx, DstIdx));
1400 // If the instruction has a single pair of tied operands, try some
1401 // transformations that may either eliminate the tied operands or
1402 // improve the opportunities for coalescing away the register copy.
1403 if (TiedOperands.size() == 1) {
1404 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs
1405 = TiedOperands.begin()->second;
1406 if (TiedPairs.size() == 1) {
1407 unsigned SrcIdx = TiedPairs[0].first;
1408 unsigned DstIdx = TiedPairs[0].second;
1409 unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
1410 unsigned DstReg = mi->getOperand(DstIdx).getReg();
1411 if (SrcReg != DstReg &&
1412 TryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist,
1414 // The tied operands have been eliminated or shifted further down the
1415 // block to ease elimination. Continue processing with 'nmi'.
1416 TiedOperands.clear();
1423 // Now iterate over the information collected above.
1424 for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1425 OE = TiedOperands.end(); OI != OE; ++OI) {
1426 SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs = OI->second;
1428 bool IsEarlyClobber = false;
1429 bool RemovedKillFlag = false;
1430 bool AllUsesCopied = true;
1431 unsigned LastCopiedReg = 0;
1432 unsigned regB = OI->first;
1433 for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1434 unsigned SrcIdx = TiedPairs[tpi].first;
1435 unsigned DstIdx = TiedPairs[tpi].second;
1437 const MachineOperand &DstMO = mi->getOperand(DstIdx);
1438 unsigned regA = DstMO.getReg();
1439 IsEarlyClobber |= DstMO.isEarlyClobber();
1441 // Grab regB from the instruction because it may have changed if the
1442 // instruction was commuted.
1443 regB = mi->getOperand(SrcIdx).getReg();
1446 // The register is tied to multiple destinations (or else we would
1447 // not have continued this far), but this use of the register
1448 // already matches the tied destination. Leave it.
1449 AllUsesCopied = false;
1452 LastCopiedReg = regA;
1454 assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1455 "cannot make instruction into two-address form");
1458 // First, verify that we don't have a use of "a" in the instruction
1459 // (a = b + a for example) because our transformation will not
1460 // work. This should never occur because we are in SSA form.
1461 for (unsigned i = 0; i != mi->getNumOperands(); ++i)
1462 assert(i == DstIdx ||
1463 !mi->getOperand(i).isReg() ||
1464 mi->getOperand(i).getReg() != regA);
1468 BuildMI(*mbbi, mi, mi->getDebugLoc(), TII->get(TargetOpcode::COPY),
1471 // Update DistanceMap.
1472 MachineBasicBlock::iterator prevMI = prior(mi);
1473 DistanceMap.insert(std::make_pair(prevMI, Dist));
1474 DistanceMap[mi] = ++Dist;
1476 DEBUG(dbgs() << "\t\tprepend:\t" << *prevMI);
1478 MachineOperand &MO = mi->getOperand(SrcIdx);
1479 assert(MO.isReg() && MO.getReg() == regB && MO.isUse() &&
1480 "inconsistent operand info for 2-reg pass");
1482 MO.setIsKill(false);
1483 RemovedKillFlag = true;
1486 // Make sure regA is a legal regclass for the SrcIdx operand.
1487 if (TargetRegisterInfo::isVirtualRegister(regA) &&
1488 TargetRegisterInfo::isVirtualRegister(regB))
1489 MRI->constrainRegClass(regA, MRI->getRegClass(regB));
1493 // Propagate SrcRegMap.
1494 SrcRegMap[regA] = regB;
1497 if (AllUsesCopied) {
1498 if (!IsEarlyClobber) {
1499 // Replace other (un-tied) uses of regB with LastCopiedReg.
1500 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1501 MachineOperand &MO = mi->getOperand(i);
1502 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1504 MO.setIsKill(false);
1505 RemovedKillFlag = true;
1507 MO.setReg(LastCopiedReg);
1512 // Update live variables for regB.
1513 if (RemovedKillFlag && LV && LV->getVarInfo(regB).removeKill(mi))
1514 LV->addVirtualRegisterKilled(regB, prior(mi));
1516 } else if (RemovedKillFlag) {
1517 // Some tied uses of regB matched their destination registers, so
1518 // regB is still used in this instruction, but a kill flag was
1519 // removed from a different tied use of regB, so now we need to add
1520 // a kill flag to one of the remaining uses of regB.
1521 for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1522 MachineOperand &MO = mi->getOperand(i);
1523 if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1530 // We didn't change anything if there was a single tied pair, and that
1531 // pair didn't require copies.
1532 if (AllUsesCopied || TiedPairs.size() > 1) {
1535 // Schedule the source copy / remat inserted to form two-address
1536 // instruction. FIXME: Does it matter the distance map may not be
1537 // accurate after it's scheduled?
1538 TII->scheduleTwoAddrSource(prior(mi), mi, *TRI);
1541 DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1544 // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1545 if (mi->isInsertSubreg()) {
1546 // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1547 // To %reg:subidx = COPY %subreg
1548 unsigned SubIdx = mi->getOperand(3).getImm();
1549 mi->RemoveOperand(3);
1550 assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1551 mi->getOperand(0).setSubReg(SubIdx);
1552 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1553 mi->RemoveOperand(1);
1554 mi->setDesc(TII->get(TargetOpcode::COPY));
1555 DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
1558 // Clear TiedOperands here instead of at the top of the loop
1559 // since most instructions do not have tied operands.
1560 TiedOperands.clear();
1565 // Some remat'ed instructions are dead.
1566 for (int i = ReMatRegs.find_first(); i != -1; i = ReMatRegs.find_next(i)) {
1567 unsigned VReg = TargetRegisterInfo::index2VirtReg(i);
1568 if (MRI->use_nodbg_empty(VReg)) {
1569 MachineInstr *DefMI = MRI->getVRegDef(VReg);
1570 DefMI->eraseFromParent();
1574 // Eliminate REG_SEQUENCE instructions. Their whole purpose was to preseve
1575 // SSA form. It's now safe to de-SSA.
1576 MadeChange |= EliminateRegSequences();
1581 static void UpdateRegSequenceSrcs(unsigned SrcReg,
1582 unsigned DstReg, unsigned SubIdx,
1583 MachineRegisterInfo *MRI,
1584 const TargetRegisterInfo &TRI) {
1585 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg),
1586 RE = MRI->reg_end(); RI != RE; ) {
1587 MachineOperand &MO = RI.getOperand();
1589 MO.substVirtReg(DstReg, SubIdx, TRI);
1593 // Find the first def of Reg, assuming they are all in the same basic block.
1594 static MachineInstr *findFirstDef(unsigned Reg, MachineRegisterInfo *MRI) {
1595 SmallPtrSet<MachineInstr*, 8> Defs;
1596 MachineInstr *First = 0;
1597 for (MachineRegisterInfo::def_iterator RI = MRI->def_begin(Reg);
1598 MachineInstr *MI = RI.skipInstruction(); Defs.insert(MI))
1603 MachineBasicBlock *MBB = First->getParent();
1604 MachineBasicBlock::iterator A = First, B = First;
1608 if (A != MBB->begin()) {
1611 if (Defs.erase(A)) First = A;
1613 if (B != MBB->end()) {
1618 } while (Moving && !Defs.empty());
1619 assert(Defs.empty() && "Instructions outside basic block!");
1623 /// CoalesceExtSubRegs - If a number of sources of the REG_SEQUENCE are
1624 /// EXTRACT_SUBREG from the same register and to the same virtual register
1625 /// with different sub-register indices, attempt to combine the
1626 /// EXTRACT_SUBREGs and pre-coalesce them. e.g.
1627 /// %reg1026<def> = VLDMQ %reg1025<kill>, 260, pred:14, pred:%reg0
1628 /// %reg1029:6<def> = EXTRACT_SUBREG %reg1026, 6
1629 /// %reg1029:5<def> = EXTRACT_SUBREG %reg1026<kill>, 5
1630 /// Since D subregs 5, 6 can combine to a Q register, we can coalesce
1631 /// reg1026 to reg1029.
1633 TwoAddressInstructionPass::CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs,
1635 SmallSet<unsigned, 4> Seen;
1636 for (unsigned i = 0, e = Srcs.size(); i != e; ++i) {
1637 unsigned SrcReg = Srcs[i];
1638 if (!Seen.insert(SrcReg))
1641 // Check that the instructions are all in the same basic block.
1642 MachineInstr *SrcDefMI = MRI->getUniqueVRegDef(SrcReg);
1643 MachineInstr *DstDefMI = MRI->getUniqueVRegDef(DstReg);
1644 if (!SrcDefMI || !DstDefMI ||
1645 SrcDefMI->getParent() != DstDefMI->getParent())
1648 // If there are no other uses than copies which feed into
1649 // the reg_sequence, then we might be able to coalesce them.
1650 bool CanCoalesce = true;
1651 SmallVector<unsigned, 4> SrcSubIndices, DstSubIndices;
1652 for (MachineRegisterInfo::use_nodbg_iterator
1653 UI = MRI->use_nodbg_begin(SrcReg),
1654 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
1655 MachineInstr *UseMI = &*UI;
1656 if (!UseMI->isCopy() || UseMI->getOperand(0).getReg() != DstReg) {
1657 CanCoalesce = false;
1660 SrcSubIndices.push_back(UseMI->getOperand(1).getSubReg());
1661 DstSubIndices.push_back(UseMI->getOperand(0).getSubReg());
1664 if (!CanCoalesce || SrcSubIndices.size() < 2)
1667 // Check that the source subregisters can be combined.
1668 std::sort(SrcSubIndices.begin(), SrcSubIndices.end());
1669 unsigned NewSrcSubIdx = 0;
1670 if (!TRI->canCombineSubRegIndices(MRI->getRegClass(SrcReg), SrcSubIndices,
1674 // Check that the destination subregisters can also be combined.
1675 std::sort(DstSubIndices.begin(), DstSubIndices.end());
1676 unsigned NewDstSubIdx = 0;
1677 if (!TRI->canCombineSubRegIndices(MRI->getRegClass(DstReg), DstSubIndices,
1681 // If neither source nor destination can be combined to the full register,
1682 // just give up. This could be improved if it ever matters.
1683 if (NewSrcSubIdx != 0 && NewDstSubIdx != 0)
1686 // Now that we know that all the uses are extract_subregs and that those
1687 // subregs can somehow be combined, scan all the extract_subregs again to
1688 // make sure the subregs are in the right order and can be composed.
1689 MachineInstr *SomeMI = 0;
1691 for (MachineRegisterInfo::use_nodbg_iterator
1692 UI = MRI->use_nodbg_begin(SrcReg),
1693 UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
1694 MachineInstr *UseMI = &*UI;
1695 assert(UseMI->isCopy());
1696 unsigned DstSubIdx = UseMI->getOperand(0).getSubReg();
1697 unsigned SrcSubIdx = UseMI->getOperand(1).getSubReg();
1698 assert(DstSubIdx != 0 && "missing subreg from RegSequence elimination");
1699 if ((NewDstSubIdx == 0 &&
1700 TRI->composeSubRegIndices(NewSrcSubIdx, DstSubIdx) != SrcSubIdx) ||
1701 (NewSrcSubIdx == 0 &&
1702 TRI->composeSubRegIndices(NewDstSubIdx, SrcSubIdx) != DstSubIdx)) {
1703 CanCoalesce = false;
1706 // Keep track of one of the uses. Preferably the first one which has a
1707 // <def,undef> flag.
1708 if (!SomeMI || UseMI->getOperand(0).isUndef())
1714 // Insert a copy to replace the original.
1715 MachineInstr *CopyMI = BuildMI(*SomeMI->getParent(), SomeMI,
1716 SomeMI->getDebugLoc(),
1717 TII->get(TargetOpcode::COPY))
1718 .addReg(DstReg, RegState::Define |
1719 getUndefRegState(SomeMI->getOperand(0).isUndef()),
1721 .addReg(SrcReg, 0, NewSrcSubIdx);
1723 // Remove all the old extract instructions.
1724 for (MachineRegisterInfo::use_nodbg_iterator
1725 UI = MRI->use_nodbg_begin(SrcReg),
1726 UE = MRI->use_nodbg_end(); UI != UE; ) {
1727 MachineInstr *UseMI = &*UI;
1729 if (UseMI == CopyMI)
1731 assert(UseMI->isCopy());
1732 // Move any kills to the new copy or extract instruction.
1733 if (UseMI->getOperand(1).isKill()) {
1734 CopyMI->getOperand(1).setIsKill();
1736 // Update live variables
1737 LV->replaceKillInstruction(SrcReg, UseMI, &*CopyMI);
1739 UseMI->eraseFromParent();
1744 static bool HasOtherRegSequenceUses(unsigned Reg, MachineInstr *RegSeq,
1745 MachineRegisterInfo *MRI) {
1746 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
1747 UE = MRI->use_end(); UI != UE; ++UI) {
1748 MachineInstr *UseMI = &*UI;
1749 if (UseMI != RegSeq && UseMI->isRegSequence())
1755 /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
1756 /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
1757 /// sub-register references of the register defined by REG_SEQUENCE. e.g.
1759 /// %reg1029<def>, %reg1030<def> = VLD1q16 %reg1024<kill>, ...
1760 /// %reg1031<def> = REG_SEQUENCE %reg1029<kill>, 5, %reg1030<kill>, 6
1762 /// %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
1763 bool TwoAddressInstructionPass::EliminateRegSequences() {
1764 if (RegSequences.empty())
1767 for (unsigned i = 0, e = RegSequences.size(); i != e; ++i) {
1768 MachineInstr *MI = RegSequences[i];
1769 unsigned DstReg = MI->getOperand(0).getReg();
1770 if (MI->getOperand(0).getSubReg() ||
1771 TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1772 !(MI->getNumOperands() & 1)) {
1773 DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1774 llvm_unreachable(0);
1777 bool IsImpDef = true;
1778 SmallVector<unsigned, 4> RealSrcs;
1779 SmallSet<unsigned, 4> Seen;
1780 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1781 // Nothing needs to be inserted for <undef> operands.
1782 if (MI->getOperand(i).isUndef()) {
1783 MI->getOperand(i).setReg(0);
1786 unsigned SrcReg = MI->getOperand(i).getReg();
1787 unsigned SrcSubIdx = MI->getOperand(i).getSubReg();
1788 unsigned SubIdx = MI->getOperand(i+1).getImm();
1789 // DefMI of NULL means the value does not have a vreg in this block
1790 // i.e., its a physical register or a subreg.
1791 // In either case we force a copy to be generated.
1792 MachineInstr *DefMI = NULL;
1793 if (!MI->getOperand(i).getSubReg() &&
1794 !TargetRegisterInfo::isPhysicalRegister(SrcReg)) {
1795 DefMI = MRI->getUniqueVRegDef(SrcReg);
1798 if (DefMI && DefMI->isImplicitDef()) {
1799 DefMI->eraseFromParent();
1804 // Remember COPY sources. These might be candidate for coalescing.
1805 if (DefMI && DefMI->isCopy() && DefMI->getOperand(1).getSubReg())
1806 RealSrcs.push_back(DefMI->getOperand(1).getReg());
1808 bool isKill = MI->getOperand(i).isKill();
1809 if (!DefMI || !Seen.insert(SrcReg) ||
1810 MI->getParent() != DefMI->getParent() ||
1811 !isKill || HasOtherRegSequenceUses(SrcReg, MI, MRI) ||
1812 !TRI->getMatchingSuperRegClass(MRI->getRegClass(DstReg),
1813 MRI->getRegClass(SrcReg), SubIdx)) {
1814 // REG_SEQUENCE cannot have duplicated operands, add a copy.
1815 // Also add an copy if the source is live-in the block. We don't want
1816 // to end up with a partial-redef of a livein, e.g.
1818 // reg1051:10<def> =
1824 // LiveIntervalAnalysis won't like it.
1826 // If the REG_SEQUENCE doesn't kill its source, keeping live variables
1827 // correctly up to date becomes very difficult. Insert a copy.
1829 // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1830 // might insert a COPY that uses SrcReg after is was killed.
1832 for (unsigned j = i + 2; j < e; j += 2)
1833 if (MI->getOperand(j).getReg() == SrcReg) {
1834 MI->getOperand(j).setIsKill();
1839 MachineBasicBlock::iterator InsertLoc = MI;
1840 MachineInstr *CopyMI = BuildMI(*MI->getParent(), InsertLoc,
1841 MI->getDebugLoc(), TII->get(TargetOpcode::COPY))
1842 .addReg(DstReg, RegState::Define, SubIdx)
1843 .addReg(SrcReg, getKillRegState(isKill), SrcSubIdx);
1844 MI->getOperand(i).setReg(0);
1845 if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
1846 LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1847 DEBUG(dbgs() << "Inserted: " << *CopyMI);
1851 for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1852 unsigned SrcReg = MI->getOperand(i).getReg();
1853 if (!SrcReg) continue;
1854 unsigned SubIdx = MI->getOperand(i+1).getImm();
1855 UpdateRegSequenceSrcs(SrcReg, DstReg, SubIdx, MRI, *TRI);
1858 // Set <def,undef> flags on the first DstReg def in the basic block.
1859 // It marks the beginning of the live range. All the other defs are
1860 // read-modify-write.
1861 if (MachineInstr *Def = findFirstDef(DstReg, MRI)) {
1862 for (unsigned i = 0, e = Def->getNumOperands(); i != e; ++i) {
1863 MachineOperand &MO = Def->getOperand(i);
1864 if (MO.isReg() && MO.isDef() && MO.getReg() == DstReg)
1867 // Make sure there is a full non-subreg imp-def operand on the
1868 // instruction. This shouldn't be necessary, but it seems that at least
1869 // RAFast requires it.
1870 Def->addRegisterDefined(DstReg, TRI);
1871 DEBUG(dbgs() << "First def: " << *Def);
1875 DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1876 MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1877 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
1878 MI->RemoveOperand(j);
1880 DEBUG(dbgs() << "Eliminated: " << *MI);
1881 MI->eraseFromParent();
1884 // Try coalescing some EXTRACT_SUBREG instructions. This can create
1885 // INSERT_SUBREG instructions that must have <undef> flags added by
1886 // LiveIntervalAnalysis, so only run it when LiveVariables is available.
1888 CoalesceExtSubRegs(RealSrcs, DstReg);
1891 RegSequences.clear();