]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - lib/CodeGen/TwoAddressInstructionPass.cpp
Cleanup collectChangingRegs
[opencl/llvm.git] / lib / CodeGen / TwoAddressInstructionPass.cpp
1 //===-- TwoAddressInstructionPass.cpp - Two-Address instruction pass ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the TwoAddress instruction pass which is used
11 // by most register allocators. Two-Address instructions are rewritten
12 // from:
13 //
14 //     A = B op C
15 //
16 // to:
17 //
18 //     A = B
19 //     A op= C
20 //
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
23 // virtual registers.
24 //
25 // It is also worth noting that the duplicate operand of the two
26 // address instruction is removed.
27 //
28 //===----------------------------------------------------------------------===//
30 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/ADT/BitVector.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/SmallSet.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
38 #include "llvm/CodeGen/LiveVariables.h"
39 #include "llvm/CodeGen/MachineFunctionPass.h"
40 #include "llvm/CodeGen/MachineInstr.h"
41 #include "llvm/CodeGen/MachineInstrBuilder.h"
42 #include "llvm/CodeGen/MachineRegisterInfo.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/MC/MCInstrItineraries.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Target/TargetInstrInfo.h"
49 #include "llvm/Target/TargetMachine.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
51 #include "llvm/Target/TargetSubtargetInfo.h"
52 using namespace llvm;
54 #define DEBUG_TYPE "twoaddrinstr"
56 STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
57 STATISTIC(NumCommuted        , "Number of instructions commuted to coalesce");
58 STATISTIC(NumAggrCommuted    , "Number of instructions aggressively commuted");
59 STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
60 STATISTIC(Num3AddrSunk,        "Number of 3-address instructions sunk");
61 STATISTIC(NumReSchedUps,       "Number of instructions re-scheduled up");
62 STATISTIC(NumReSchedDowns,     "Number of instructions re-scheduled down");
64 // Temporary flag to disable rescheduling.
65 static cl::opt<bool>
66 EnableRescheduling("twoaddr-reschedule",
67                    cl::desc("Coalesce copies by rescheduling (default=true)"),
68                    cl::init(true), cl::Hidden);
70 namespace {
71 class TwoAddressInstructionPass : public MachineFunctionPass {
72   MachineFunction *MF;
73   const TargetInstrInfo *TII;
74   const TargetRegisterInfo *TRI;
75   const InstrItineraryData *InstrItins;
76   MachineRegisterInfo *MRI;
77   LiveVariables *LV;
78   LiveIntervals *LIS;
79   AliasAnalysis *AA;
80   CodeGenOpt::Level OptLevel;
82   // The current basic block being processed.
83   MachineBasicBlock *MBB;
85   // DistanceMap - Keep track the distance of a MI from the start of the
86   // current basic block.
87   DenseMap<MachineInstr*, unsigned> DistanceMap;
89   // Set of already processed instructions in the current block.
90   SmallPtrSet<MachineInstr*, 8> Processed;
92   // SrcRegMap - A map from virtual registers to physical registers which are
93   // likely targets to be coalesced to due to copies from physical registers to
94   // virtual registers. e.g. v1024 = move r0.
95   DenseMap<unsigned, unsigned> SrcRegMap;
97   // DstRegMap - A map from virtual registers to physical registers which are
98   // likely targets to be coalesced to due to copies to physical registers from
99   // virtual registers. e.g. r1 = move v1024.
100   DenseMap<unsigned, unsigned> DstRegMap;
102   bool sink3AddrInstruction(MachineInstr *MI, unsigned Reg,
103                             MachineBasicBlock::iterator OldPos);
105   bool noUseAfterLastDef(unsigned Reg, unsigned Dist, unsigned &LastDef);
107   bool isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
108                              MachineInstr *MI, unsigned Dist);
110   bool commuteInstruction(MachineBasicBlock::iterator &mi,
111                           unsigned RegB, unsigned RegC, unsigned Dist);
113   bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
115   bool convertInstTo3Addr(MachineBasicBlock::iterator &mi,
116                           MachineBasicBlock::iterator &nmi,
117                           unsigned RegA, unsigned RegB, unsigned Dist);
119   bool isDefTooClose(unsigned Reg, unsigned Dist, MachineInstr *MI);
121   bool rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
122                              MachineBasicBlock::iterator &nmi,
123                              unsigned Reg);
124   bool rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
125                              MachineBasicBlock::iterator &nmi,
126                              unsigned Reg);
128   bool tryInstructionTransform(MachineBasicBlock::iterator &mi,
129                                MachineBasicBlock::iterator &nmi,
130                                unsigned SrcIdx, unsigned DstIdx,
131                                unsigned Dist, bool shouldOnlyCommute);
133   void scanUses(unsigned DstReg);
135   void processCopy(MachineInstr *MI);
137   typedef SmallVector<std::pair<unsigned, unsigned>, 4> TiedPairList;
138   typedef SmallDenseMap<unsigned, TiedPairList> TiedOperandMap;
139   bool collectTiedOperands(MachineInstr *MI, TiedOperandMap&);
140   void processTiedPairs(MachineInstr *MI, TiedPairList&, unsigned &Dist);
141   void eliminateRegSequence(MachineBasicBlock::iterator&);
143 public:
144   static char ID; // Pass identification, replacement for typeid
145   TwoAddressInstructionPass() : MachineFunctionPass(ID) {
146     initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
147   }
149   void getAnalysisUsage(AnalysisUsage &AU) const override {
150     AU.setPreservesCFG();
151     AU.addRequired<AliasAnalysis>();
152     AU.addPreserved<LiveVariables>();
153     AU.addPreserved<SlotIndexes>();
154     AU.addPreserved<LiveIntervals>();
155     AU.addPreservedID(MachineLoopInfoID);
156     AU.addPreservedID(MachineDominatorsID);
157     MachineFunctionPass::getAnalysisUsage(AU);
158   }
160   /// runOnMachineFunction - Pass entry point.
161   bool runOnMachineFunction(MachineFunction&) override;
162 };
163 } // end anonymous namespace
165 char TwoAddressInstructionPass::ID = 0;
166 INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
167                 "Two-Address instruction pass", false, false)
168 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
169 INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
170                 "Two-Address instruction pass", false, false)
172 char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
174 static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg, LiveIntervals *LIS);
176 /// sink3AddrInstruction - A two-address instruction has been converted to a
177 /// three-address instruction to avoid clobbering a register. Try to sink it
178 /// past the instruction that would kill the above mentioned register to reduce
179 /// register pressure.
180 bool TwoAddressInstructionPass::
181 sink3AddrInstruction(MachineInstr *MI, unsigned SavedReg,
182                      MachineBasicBlock::iterator OldPos) {
183   // FIXME: Shouldn't we be trying to do this before we three-addressify the
184   // instruction?  After this transformation is done, we no longer need
185   // the instruction to be in three-address form.
187   // Check if it's safe to move this instruction.
188   bool SeenStore = true; // Be conservative.
189   if (!MI->isSafeToMove(TII, AA, SeenStore))
190     return false;
192   unsigned DefReg = 0;
193   SmallSet<unsigned, 4> UseRegs;
195   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
196     const MachineOperand &MO = MI->getOperand(i);
197     if (!MO.isReg())
198       continue;
199     unsigned MOReg = MO.getReg();
200     if (!MOReg)
201       continue;
202     if (MO.isUse() && MOReg != SavedReg)
203       UseRegs.insert(MO.getReg());
204     if (!MO.isDef())
205       continue;
206     if (MO.isImplicit())
207       // Don't try to move it if it implicitly defines a register.
208       return false;
209     if (DefReg)
210       // For now, don't move any instructions that define multiple registers.
211       return false;
212     DefReg = MO.getReg();
213   }
215   // Find the instruction that kills SavedReg.
216   MachineInstr *KillMI = nullptr;
217   if (LIS) {
218     LiveInterval &LI = LIS->getInterval(SavedReg);
219     assert(LI.end() != LI.begin() &&
220            "Reg should not have empty live interval.");
222     SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
223     LiveInterval::const_iterator I = LI.find(MBBEndIdx);
224     if (I != LI.end() && I->start < MBBEndIdx)
225       return false;
227     --I;
228     KillMI = LIS->getInstructionFromIndex(I->end);
229   }
230   if (!KillMI) {
231     for (MachineRegisterInfo::use_nodbg_iterator
232            UI = MRI->use_nodbg_begin(SavedReg),
233            UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
234       MachineOperand &UseMO = *UI;
235       if (!UseMO.isKill())
236         continue;
237       KillMI = UseMO.getParent();
238       break;
239     }
240   }
242   // If we find the instruction that kills SavedReg, and it is in an
243   // appropriate location, we can try to sink the current instruction
244   // past it.
245   if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
246       KillMI == OldPos || KillMI->isTerminator())
247     return false;
249   // If any of the definitions are used by another instruction between the
250   // position and the kill use, then it's not safe to sink it.
251   //
252   // FIXME: This can be sped up if there is an easy way to query whether an
253   // instruction is before or after another instruction. Then we can use
254   // MachineRegisterInfo def / use instead.
255   MachineOperand *KillMO = nullptr;
256   MachineBasicBlock::iterator KillPos = KillMI;
257   ++KillPos;
259   unsigned NumVisited = 0;
260   for (MachineBasicBlock::iterator I = std::next(OldPos); I != KillPos; ++I) {
261     MachineInstr *OtherMI = I;
262     // DBG_VALUE cannot be counted against the limit.
263     if (OtherMI->isDebugValue())
264       continue;
265     if (NumVisited > 30)  // FIXME: Arbitrary limit to reduce compile time cost.
266       return false;
267     ++NumVisited;
268     for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
269       MachineOperand &MO = OtherMI->getOperand(i);
270       if (!MO.isReg())
271         continue;
272       unsigned MOReg = MO.getReg();
273       if (!MOReg)
274         continue;
275       if (DefReg == MOReg)
276         return false;
278       if (MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))) {
279         if (OtherMI == KillMI && MOReg == SavedReg)
280           // Save the operand that kills the register. We want to unset the kill
281           // marker if we can sink MI past it.
282           KillMO = &MO;
283         else if (UseRegs.count(MOReg))
284           // One of the uses is killed before the destination.
285           return false;
286       }
287     }
288   }
289   assert(KillMO && "Didn't find kill");
291   if (!LIS) {
292     // Update kill and LV information.
293     KillMO->setIsKill(false);
294     KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
295     KillMO->setIsKill(true);
297     if (LV)
298       LV->replaceKillInstruction(SavedReg, KillMI, MI);
299   }
301   // Move instruction to its destination.
302   MBB->remove(MI);
303   MBB->insert(KillPos, MI);
305   if (LIS)
306     LIS->handleMove(MI);
308   ++Num3AddrSunk;
309   return true;
312 /// noUseAfterLastDef - Return true if there are no intervening uses between the
313 /// last instruction in the MBB that defines the specified register and the
314 /// two-address instruction which is being processed. It also returns the last
315 /// def location by reference
316 bool TwoAddressInstructionPass::noUseAfterLastDef(unsigned Reg, unsigned Dist,
317                                                   unsigned &LastDef) {
318   LastDef = 0;
319   unsigned LastUse = Dist;
320   for (MachineOperand &MO : MRI->reg_operands(Reg)) {
321     MachineInstr *MI = MO.getParent();
322     if (MI->getParent() != MBB || MI->isDebugValue())
323       continue;
324     DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
325     if (DI == DistanceMap.end())
326       continue;
327     if (MO.isUse() && DI->second < LastUse)
328       LastUse = DI->second;
329     if (MO.isDef() && DI->second > LastDef)
330       LastDef = DI->second;
331   }
333   return !(LastUse > LastDef && LastUse < Dist);
336 /// isCopyToReg - Return true if the specified MI is a copy instruction or
337 /// a extract_subreg instruction. It also returns the source and destination
338 /// registers and whether they are physical registers by reference.
339 static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
340                         unsigned &SrcReg, unsigned &DstReg,
341                         bool &IsSrcPhys, bool &IsDstPhys) {
342   SrcReg = 0;
343   DstReg = 0;
344   if (MI.isCopy()) {
345     DstReg = MI.getOperand(0).getReg();
346     SrcReg = MI.getOperand(1).getReg();
347   } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
348     DstReg = MI.getOperand(0).getReg();
349     SrcReg = MI.getOperand(2).getReg();
350   } else
351     return false;
353   IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
354   IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
355   return true;
358 /// isPLainlyKilled - Test if the given register value, which is used by the
359 // given instruction, is killed by the given instruction.
360 static bool isPlainlyKilled(MachineInstr *MI, unsigned Reg,
361                             LiveIntervals *LIS) {
362   if (LIS && TargetRegisterInfo::isVirtualRegister(Reg) &&
363       !LIS->isNotInMIMap(MI)) {
364     // FIXME: Sometimes tryInstructionTransform() will add instructions and
365     // test whether they can be folded before keeping them. In this case it
366     // sets a kill before recursively calling tryInstructionTransform() again.
367     // If there is no interval available, we assume that this instruction is
368     // one of those. A kill flag is manually inserted on the operand so the
369     // check below will handle it.
370     LiveInterval &LI = LIS->getInterval(Reg);
371     // This is to match the kill flag version where undefs don't have kill
372     // flags.
373     if (!LI.hasAtLeastOneValue())
374       return false;
376     SlotIndex useIdx = LIS->getInstructionIndex(MI);
377     LiveInterval::const_iterator I = LI.find(useIdx);
378     assert(I != LI.end() && "Reg must be live-in to use.");
379     return !I->end.isBlock() && SlotIndex::isSameInstr(I->end, useIdx);
380   }
382   return MI->killsRegister(Reg);
385 /// isKilled - Test if the given register value, which is used by the given
386 /// instruction, is killed by the given instruction. This looks through
387 /// coalescable copies to see if the original value is potentially not killed.
388 ///
389 /// For example, in this code:
390 ///
391 ///   %reg1034 = copy %reg1024
392 ///   %reg1035 = copy %reg1025<kill>
393 ///   %reg1036 = add %reg1034<kill>, %reg1035<kill>
394 ///
395 /// %reg1034 is not considered to be killed, since it is copied from a
396 /// register which is not killed. Treating it as not killed lets the
397 /// normal heuristics commute the (two-address) add, which lets
398 /// coalescing eliminate the extra copy.
399 ///
400 /// If allowFalsePositives is true then likely kills are treated as kills even
401 /// if it can't be proven that they are kills.
402 static bool isKilled(MachineInstr &MI, unsigned Reg,
403                      const MachineRegisterInfo *MRI,
404                      const TargetInstrInfo *TII,
405                      LiveIntervals *LIS,
406                      bool allowFalsePositives) {
407   MachineInstr *DefMI = &MI;
408   for (;;) {
409     // All uses of physical registers are likely to be kills.
410     if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
411         (allowFalsePositives || MRI->hasOneUse(Reg)))
412       return true;
413     if (!isPlainlyKilled(DefMI, Reg, LIS))
414       return false;
415     if (TargetRegisterInfo::isPhysicalRegister(Reg))
416       return true;
417     MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
418     // If there are multiple defs, we can't do a simple analysis, so just
419     // go with what the kill flag says.
420     if (std::next(Begin) != MRI->def_end())
421       return true;
422     DefMI = Begin->getParent();
423     bool IsSrcPhys, IsDstPhys;
424     unsigned SrcReg,  DstReg;
425     // If the def is something other than a copy, then it isn't going to
426     // be coalesced, so follow the kill flag.
427     if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
428       return true;
429     Reg = SrcReg;
430   }
433 /// isTwoAddrUse - Return true if the specified MI uses the specified register
434 /// as a two-address use. If so, return the destination register by reference.
435 static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
436   for (unsigned i = 0, NumOps = MI.getNumOperands(); i != NumOps; ++i) {
437     const MachineOperand &MO = MI.getOperand(i);
438     if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
439       continue;
440     unsigned ti;
441     if (MI.isRegTiedToDefOperand(i, &ti)) {
442       DstReg = MI.getOperand(ti).getReg();
443       return true;
444     }
445   }
446   return false;
449 /// findOnlyInterestingUse - Given a register, if has a single in-basic block
450 /// use, return the use instruction if it's a copy or a two-address use.
451 static
452 MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
453                                      MachineRegisterInfo *MRI,
454                                      const TargetInstrInfo *TII,
455                                      bool &IsCopy,
456                                      unsigned &DstReg, bool &IsDstPhys) {
457   if (!MRI->hasOneNonDBGUse(Reg))
458     // None or more than one use.
459     return nullptr;
460   MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(Reg);
461   if (UseMI.getParent() != MBB)
462     return nullptr;
463   unsigned SrcReg;
464   bool IsSrcPhys;
465   if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
466     IsCopy = true;
467     return &UseMI;
468   }
469   IsDstPhys = false;
470   if (isTwoAddrUse(UseMI, Reg, DstReg)) {
471     IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
472     return &UseMI;
473   }
474   return nullptr;
477 /// getMappedReg - Return the physical register the specified virtual register
478 /// might be mapped to.
479 static unsigned
480 getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
481   while (TargetRegisterInfo::isVirtualRegister(Reg))  {
482     DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
483     if (SI == RegMap.end())
484       return 0;
485     Reg = SI->second;
486   }
487   if (TargetRegisterInfo::isPhysicalRegister(Reg))
488     return Reg;
489   return 0;
492 /// regsAreCompatible - Return true if the two registers are equal or aliased.
493 ///
494 static bool
495 regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
496   if (RegA == RegB)
497     return true;
498   if (!RegA || !RegB)
499     return false;
500   return TRI->regsOverlap(RegA, RegB);
504 /// isProfitableToCommute - Return true if it's potentially profitable to commute
505 /// the two-address instruction that's being processed.
506 bool
507 TwoAddressInstructionPass::
508 isProfitableToCommute(unsigned regA, unsigned regB, unsigned regC,
509                       MachineInstr *MI, unsigned Dist) {
510   if (OptLevel == CodeGenOpt::None)
511     return false;
513   // Determine if it's profitable to commute this two address instruction. In
514   // general, we want no uses between this instruction and the definition of
515   // the two-address register.
516   // e.g.
517   // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
518   // %reg1029<def> = MOV8rr %reg1028
519   // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
520   // insert => %reg1030<def> = MOV8rr %reg1028
521   // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
522   // In this case, it might not be possible to coalesce the second MOV8rr
523   // instruction if the first one is coalesced. So it would be profitable to
524   // commute it:
525   // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
526   // %reg1029<def> = MOV8rr %reg1028
527   // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
528   // insert => %reg1030<def> = MOV8rr %reg1029
529   // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
531   if (!isPlainlyKilled(MI, regC, LIS))
532     return false;
534   // Ok, we have something like:
535   // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
536   // let's see if it's worth commuting it.
538   // Look for situations like this:
539   // %reg1024<def> = MOV r1
540   // %reg1025<def> = MOV r0
541   // %reg1026<def> = ADD %reg1024, %reg1025
542   // r0            = MOV %reg1026
543   // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
544   unsigned ToRegA = getMappedReg(regA, DstRegMap);
545   if (ToRegA) {
546     unsigned FromRegB = getMappedReg(regB, SrcRegMap);
547     unsigned FromRegC = getMappedReg(regC, SrcRegMap);
548     bool BComp = !FromRegB || regsAreCompatible(FromRegB, ToRegA, TRI);
549     bool CComp = !FromRegC || regsAreCompatible(FromRegC, ToRegA, TRI);
550     if (BComp != CComp)
551       return !BComp && CComp;
552   }
554   // If there is a use of regC between its last def (could be livein) and this
555   // instruction, then bail.
556   unsigned LastDefC = 0;
557   if (!noUseAfterLastDef(regC, Dist, LastDefC))
558     return false;
560   // If there is a use of regB between its last def (could be livein) and this
561   // instruction, then go ahead and make this transformation.
562   unsigned LastDefB = 0;
563   if (!noUseAfterLastDef(regB, Dist, LastDefB))
564     return true;
566   // Since there are no intervening uses for both registers, then commute
567   // if the def of regC is closer. Its live interval is shorter.
568   return LastDefB && LastDefC && LastDefC > LastDefB;
571 /// commuteInstruction - Commute a two-address instruction and update the basic
572 /// block, distance map, and live variables if needed. Return true if it is
573 /// successful.
574 bool TwoAddressInstructionPass::
575 commuteInstruction(MachineBasicBlock::iterator &mi,
576                    unsigned RegB, unsigned RegC, unsigned Dist) {
577   MachineInstr *MI = mi;
578   DEBUG(dbgs() << "2addr: COMMUTING  : " << *MI);
579   MachineInstr *NewMI = TII->commuteInstruction(MI);
581   if (NewMI == nullptr) {
582     DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
583     return false;
584   }
586   DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
587   assert(NewMI == MI &&
588          "TargetInstrInfo::commuteInstruction() should not return a new "
589          "instruction unless it was requested.");
591   // Update source register map.
592   unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
593   if (FromRegC) {
594     unsigned RegA = MI->getOperand(0).getReg();
595     SrcRegMap[RegA] = FromRegC;
596   }
598   return true;
601 /// isProfitableToConv3Addr - Return true if it is profitable to convert the
602 /// given 2-address instruction to a 3-address one.
603 bool
604 TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
605   // Look for situations like this:
606   // %reg1024<def> = MOV r1
607   // %reg1025<def> = MOV r0
608   // %reg1026<def> = ADD %reg1024, %reg1025
609   // r2            = MOV %reg1026
610   // Turn ADD into a 3-address instruction to avoid a copy.
611   unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
612   if (!FromRegB)
613     return false;
614   unsigned ToRegA = getMappedReg(RegA, DstRegMap);
615   return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
618 /// convertInstTo3Addr - Convert the specified two-address instruction into a
619 /// three address one. Return true if this transformation was successful.
620 bool
621 TwoAddressInstructionPass::convertInstTo3Addr(MachineBasicBlock::iterator &mi,
622                                               MachineBasicBlock::iterator &nmi,
623                                               unsigned RegA, unsigned RegB,
624                                               unsigned Dist) {
625   // FIXME: Why does convertToThreeAddress() need an iterator reference?
626   MachineFunction::iterator MFI = MBB;
627   MachineInstr *NewMI = TII->convertToThreeAddress(MFI, mi, LV);
628   assert(MBB == MFI && "convertToThreeAddress changed iterator reference");
629   if (!NewMI)
630     return false;
632   DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
633   DEBUG(dbgs() << "2addr:         TO 3-ADDR: " << *NewMI);
634   bool Sunk = false;
636   if (LIS)
637     LIS->ReplaceMachineInstrInMaps(mi, NewMI);
639   if (NewMI->findRegisterUseOperand(RegB, false, TRI))
640     // FIXME: Temporary workaround. If the new instruction doesn't
641     // uses RegB, convertToThreeAddress must have created more
642     // then one instruction.
643     Sunk = sink3AddrInstruction(NewMI, RegB, mi);
645   MBB->erase(mi); // Nuke the old inst.
647   if (!Sunk) {
648     DistanceMap.insert(std::make_pair(NewMI, Dist));
649     mi = NewMI;
650     nmi = std::next(mi);
651   }
653   // Update source and destination register maps.
654   SrcRegMap.erase(RegA);
655   DstRegMap.erase(RegB);
656   return true;
659 /// scanUses - Scan forward recursively for only uses, update maps if the use
660 /// is a copy or a two-address instruction.
661 void
662 TwoAddressInstructionPass::scanUses(unsigned DstReg) {
663   SmallVector<unsigned, 4> VirtRegPairs;
664   bool IsDstPhys;
665   bool IsCopy = false;
666   unsigned NewReg = 0;
667   unsigned Reg = DstReg;
668   while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
669                                                       NewReg, IsDstPhys)) {
670     if (IsCopy && !Processed.insert(UseMI))
671       break;
673     DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
674     if (DI != DistanceMap.end())
675       // Earlier in the same MBB.Reached via a back edge.
676       break;
678     if (IsDstPhys) {
679       VirtRegPairs.push_back(NewReg);
680       break;
681     }
682     bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
683     if (!isNew)
684       assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
685     VirtRegPairs.push_back(NewReg);
686     Reg = NewReg;
687   }
689   if (!VirtRegPairs.empty()) {
690     unsigned ToReg = VirtRegPairs.back();
691     VirtRegPairs.pop_back();
692     while (!VirtRegPairs.empty()) {
693       unsigned FromReg = VirtRegPairs.back();
694       VirtRegPairs.pop_back();
695       bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
696       if (!isNew)
697         assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
698       ToReg = FromReg;
699     }
700     bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
701     if (!isNew)
702       assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
703   }
706 /// processCopy - If the specified instruction is not yet processed, process it
707 /// if it's a copy. For a copy instruction, we find the physical registers the
708 /// source and destination registers might be mapped to. These are kept in
709 /// point-to maps used to determine future optimizations. e.g.
710 /// v1024 = mov r0
711 /// v1025 = mov r1
712 /// v1026 = add v1024, v1025
713 /// r1    = mov r1026
714 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
715 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
716 /// potentially joined with r1 on the output side. It's worthwhile to commute
717 /// 'add' to eliminate a copy.
718 void TwoAddressInstructionPass::processCopy(MachineInstr *MI) {
719   if (Processed.count(MI))
720     return;
722   bool IsSrcPhys, IsDstPhys;
723   unsigned SrcReg, DstReg;
724   if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
725     return;
727   if (IsDstPhys && !IsSrcPhys)
728     DstRegMap.insert(std::make_pair(SrcReg, DstReg));
729   else if (!IsDstPhys && IsSrcPhys) {
730     bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
731     if (!isNew)
732       assert(SrcRegMap[DstReg] == SrcReg &&
733              "Can't map to two src physical registers!");
735     scanUses(DstReg);
736   }
738   Processed.insert(MI);
739   return;
742 /// rescheduleMIBelowKill - If there is one more local instruction that reads
743 /// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
744 /// instruction in order to eliminate the need for the copy.
745 bool TwoAddressInstructionPass::
746 rescheduleMIBelowKill(MachineBasicBlock::iterator &mi,
747                       MachineBasicBlock::iterator &nmi,
748                       unsigned Reg) {
749   // Bail immediately if we don't have LV or LIS available. We use them to find
750   // kills efficiently.
751   if (!LV && !LIS)
752     return false;
754   MachineInstr *MI = &*mi;
755   DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
756   if (DI == DistanceMap.end())
757     // Must be created from unfolded load. Don't waste time trying this.
758     return false;
760   MachineInstr *KillMI = nullptr;
761   if (LIS) {
762     LiveInterval &LI = LIS->getInterval(Reg);
763     assert(LI.end() != LI.begin() &&
764            "Reg should not have empty live interval.");
766     SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
767     LiveInterval::const_iterator I = LI.find(MBBEndIdx);
768     if (I != LI.end() && I->start < MBBEndIdx)
769       return false;
771     --I;
772     KillMI = LIS->getInstructionFromIndex(I->end);
773   } else {
774     KillMI = LV->getVarInfo(Reg).findKill(MBB);
775   }
776   if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
777     // Don't mess with copies, they may be coalesced later.
778     return false;
780   if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
781       KillMI->isBranch() || KillMI->isTerminator())
782     // Don't move pass calls, etc.
783     return false;
785   unsigned DstReg;
786   if (isTwoAddrUse(*KillMI, Reg, DstReg))
787     return false;
789   bool SeenStore = true;
790   if (!MI->isSafeToMove(TII, AA, SeenStore))
791     return false;
793   if (TII->getInstrLatency(InstrItins, MI) > 1)
794     // FIXME: Needs more sophisticated heuristics.
795     return false;
797   SmallSet<unsigned, 2> Uses;
798   SmallSet<unsigned, 2> Kills;
799   SmallSet<unsigned, 2> Defs;
800   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
801     const MachineOperand &MO = MI->getOperand(i);
802     if (!MO.isReg())
803       continue;
804     unsigned MOReg = MO.getReg();
805     if (!MOReg)
806       continue;
807     if (MO.isDef())
808       Defs.insert(MOReg);
809     else {
810       Uses.insert(MOReg);
811       if (MOReg != Reg && (MO.isKill() ||
812                            (LIS && isPlainlyKilled(MI, MOReg, LIS))))
813         Kills.insert(MOReg);
814     }
815   }
817   // Move the copies connected to MI down as well.
818   MachineBasicBlock::iterator Begin = MI;
819   MachineBasicBlock::iterator AfterMI = std::next(Begin);
821   MachineBasicBlock::iterator End = AfterMI;
822   while (End->isCopy() && Defs.count(End->getOperand(1).getReg())) {
823     Defs.insert(End->getOperand(0).getReg());
824     ++End;
825   }
827   // Check if the reschedule will not break depedencies.
828   unsigned NumVisited = 0;
829   MachineBasicBlock::iterator KillPos = KillMI;
830   ++KillPos;
831   for (MachineBasicBlock::iterator I = End; I != KillPos; ++I) {
832     MachineInstr *OtherMI = I;
833     // DBG_VALUE cannot be counted against the limit.
834     if (OtherMI->isDebugValue())
835       continue;
836     if (NumVisited > 10)  // FIXME: Arbitrary limit to reduce compile time cost.
837       return false;
838     ++NumVisited;
839     if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
840         OtherMI->isBranch() || OtherMI->isTerminator())
841       // Don't move pass calls, etc.
842       return false;
843     for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
844       const MachineOperand &MO = OtherMI->getOperand(i);
845       if (!MO.isReg())
846         continue;
847       unsigned MOReg = MO.getReg();
848       if (!MOReg)
849         continue;
850       if (MO.isDef()) {
851         if (Uses.count(MOReg))
852           // Physical register use would be clobbered.
853           return false;
854         if (!MO.isDead() && Defs.count(MOReg))
855           // May clobber a physical register def.
856           // FIXME: This may be too conservative. It's ok if the instruction
857           // is sunken completely below the use.
858           return false;
859       } else {
860         if (Defs.count(MOReg))
861           return false;
862         bool isKill = MO.isKill() ||
863                       (LIS && isPlainlyKilled(OtherMI, MOReg, LIS));
864         if (MOReg != Reg &&
865             ((isKill && Uses.count(MOReg)) || Kills.count(MOReg)))
866           // Don't want to extend other live ranges and update kills.
867           return false;
868         if (MOReg == Reg && !isKill)
869           // We can't schedule across a use of the register in question.
870           return false;
871         // Ensure that if this is register in question, its the kill we expect.
872         assert((MOReg != Reg || OtherMI == KillMI) &&
873                "Found multiple kills of a register in a basic block");
874       }
875     }
876   }
878   // Move debug info as well.
879   while (Begin != MBB->begin() && std::prev(Begin)->isDebugValue())
880     --Begin;
882   nmi = End;
883   MachineBasicBlock::iterator InsertPos = KillPos;
884   if (LIS) {
885     // We have to move the copies first so that the MBB is still well-formed
886     // when calling handleMove().
887     for (MachineBasicBlock::iterator MBBI = AfterMI; MBBI != End;) {
888       MachineInstr *CopyMI = MBBI;
889       ++MBBI;
890       MBB->splice(InsertPos, MBB, CopyMI);
891       LIS->handleMove(CopyMI);
892       InsertPos = CopyMI;
893     }
894     End = std::next(MachineBasicBlock::iterator(MI));
895   }
897   // Copies following MI may have been moved as well.
898   MBB->splice(InsertPos, MBB, Begin, End);
899   DistanceMap.erase(DI);
901   // Update live variables
902   if (LIS) {
903     LIS->handleMove(MI);
904   } else {
905     LV->removeVirtualRegisterKilled(Reg, KillMI);
906     LV->addVirtualRegisterKilled(Reg, MI);
907   }
909   DEBUG(dbgs() << "\trescheduled below kill: " << *KillMI);
910   return true;
913 /// isDefTooClose - Return true if the re-scheduling will put the given
914 /// instruction too close to the defs of its register dependencies.
915 bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
916                                               MachineInstr *MI) {
917   for (MachineInstr &DefMI : MRI->def_instructions(Reg)) {
918     if (DefMI.getParent() != MBB || DefMI.isCopy() || DefMI.isCopyLike())
919       continue;
920     if (&DefMI == MI)
921       return true; // MI is defining something KillMI uses
922     DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(&DefMI);
923     if (DDI == DistanceMap.end())
924       return true;  // Below MI
925     unsigned DefDist = DDI->second;
926     assert(Dist > DefDist && "Visited def already?");
927     if (TII->getInstrLatency(InstrItins, &DefMI) > (Dist - DefDist))
928       return true;
929   }
930   return false;
933 /// rescheduleKillAboveMI - If there is one more local instruction that reads
934 /// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
935 /// current two-address instruction in order to eliminate the need for the
936 /// copy.
937 bool TwoAddressInstructionPass::
938 rescheduleKillAboveMI(MachineBasicBlock::iterator &mi,
939                       MachineBasicBlock::iterator &nmi,
940                       unsigned Reg) {
941   // Bail immediately if we don't have LV or LIS available. We use them to find
942   // kills efficiently.
943   if (!LV && !LIS)
944     return false;
946   MachineInstr *MI = &*mi;
947   DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
948   if (DI == DistanceMap.end())
949     // Must be created from unfolded load. Don't waste time trying this.
950     return false;
952   MachineInstr *KillMI = nullptr;
953   if (LIS) {
954     LiveInterval &LI = LIS->getInterval(Reg);
955     assert(LI.end() != LI.begin() &&
956            "Reg should not have empty live interval.");
958     SlotIndex MBBEndIdx = LIS->getMBBEndIdx(MBB).getPrevSlot();
959     LiveInterval::const_iterator I = LI.find(MBBEndIdx);
960     if (I != LI.end() && I->start < MBBEndIdx)
961       return false;
963     --I;
964     KillMI = LIS->getInstructionFromIndex(I->end);
965   } else {
966     KillMI = LV->getVarInfo(Reg).findKill(MBB);
967   }
968   if (!KillMI || MI == KillMI || KillMI->isCopy() || KillMI->isCopyLike())
969     // Don't mess with copies, they may be coalesced later.
970     return false;
972   unsigned DstReg;
973   if (isTwoAddrUse(*KillMI, Reg, DstReg))
974     return false;
976   bool SeenStore = true;
977   if (!KillMI->isSafeToMove(TII, AA, SeenStore))
978     return false;
980   SmallSet<unsigned, 2> Uses;
981   SmallSet<unsigned, 2> Kills;
982   SmallSet<unsigned, 2> Defs;
983   SmallSet<unsigned, 2> LiveDefs;
984   for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
985     const MachineOperand &MO = KillMI->getOperand(i);
986     if (!MO.isReg())
987       continue;
988     unsigned MOReg = MO.getReg();
989     if (MO.isUse()) {
990       if (!MOReg)
991         continue;
992       if (isDefTooClose(MOReg, DI->second, MI))
993         return false;
994       bool isKill = MO.isKill() || (LIS && isPlainlyKilled(KillMI, MOReg, LIS));
995       if (MOReg == Reg && !isKill)
996         return false;
997       Uses.insert(MOReg);
998       if (isKill && MOReg != Reg)
999         Kills.insert(MOReg);
1000     } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1001       Defs.insert(MOReg);
1002       if (!MO.isDead())
1003         LiveDefs.insert(MOReg);
1004     }
1005   }
1007   // Check if the reschedule will not break depedencies.
1008   unsigned NumVisited = 0;
1009   MachineBasicBlock::iterator KillPos = KillMI;
1010   for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
1011     MachineInstr *OtherMI = I;
1012     // DBG_VALUE cannot be counted against the limit.
1013     if (OtherMI->isDebugValue())
1014       continue;
1015     if (NumVisited > 10)  // FIXME: Arbitrary limit to reduce compile time cost.
1016       return false;
1017     ++NumVisited;
1018     if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
1019         OtherMI->isBranch() || OtherMI->isTerminator())
1020       // Don't move pass calls, etc.
1021       return false;
1022     SmallVector<unsigned, 2> OtherDefs;
1023     for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
1024       const MachineOperand &MO = OtherMI->getOperand(i);
1025       if (!MO.isReg())
1026         continue;
1027       unsigned MOReg = MO.getReg();
1028       if (!MOReg)
1029         continue;
1030       if (MO.isUse()) {
1031         if (Defs.count(MOReg))
1032           // Moving KillMI can clobber the physical register if the def has
1033           // not been seen.
1034           return false;
1035         if (Kills.count(MOReg))
1036           // Don't want to extend other live ranges and update kills.
1037           return false;
1038         if (OtherMI != MI && MOReg == Reg &&
1039             !(MO.isKill() || (LIS && isPlainlyKilled(OtherMI, MOReg, LIS))))
1040           // We can't schedule across a use of the register in question.
1041           return false;
1042       } else {
1043         OtherDefs.push_back(MOReg);
1044       }
1045     }
1047     for (unsigned i = 0, e = OtherDefs.size(); i != e; ++i) {
1048       unsigned MOReg = OtherDefs[i];
1049       if (Uses.count(MOReg))
1050         return false;
1051       if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1052           LiveDefs.count(MOReg))
1053         return false;
1054       // Physical register def is seen.
1055       Defs.erase(MOReg);
1056     }
1057   }
1059   // Move the old kill above MI, don't forget to move debug info as well.
1060   MachineBasicBlock::iterator InsertPos = mi;
1061   while (InsertPos != MBB->begin() && std::prev(InsertPos)->isDebugValue())
1062     --InsertPos;
1063   MachineBasicBlock::iterator From = KillMI;
1064   MachineBasicBlock::iterator To = std::next(From);
1065   while (std::prev(From)->isDebugValue())
1066     --From;
1067   MBB->splice(InsertPos, MBB, From, To);
1069   nmi = std::prev(InsertPos); // Backtrack so we process the moved instr.
1070   DistanceMap.erase(DI);
1072   // Update live variables
1073   if (LIS) {
1074     LIS->handleMove(KillMI);
1075   } else {
1076     LV->removeVirtualRegisterKilled(Reg, KillMI);
1077     LV->addVirtualRegisterKilled(Reg, MI);
1078   }
1080   DEBUG(dbgs() << "\trescheduled kill: " << *KillMI);
1081   return true;
1084 /// tryInstructionTransform - For the case where an instruction has a single
1085 /// pair of tied register operands, attempt some transformations that may
1086 /// either eliminate the tied operands or improve the opportunities for
1087 /// coalescing away the register copy.  Returns true if no copy needs to be
1088 /// inserted to untie mi's operands (either because they were untied, or
1089 /// because mi was rescheduled, and will be visited again later). If the
1090 /// shouldOnlyCommute flag is true, only instruction commutation is attempted.
1091 bool TwoAddressInstructionPass::
1092 tryInstructionTransform(MachineBasicBlock::iterator &mi,
1093                         MachineBasicBlock::iterator &nmi,
1094                         unsigned SrcIdx, unsigned DstIdx,
1095                         unsigned Dist, bool shouldOnlyCommute) {
1096   if (OptLevel == CodeGenOpt::None)
1097     return false;
1099   MachineInstr &MI = *mi;
1100   unsigned regA = MI.getOperand(DstIdx).getReg();
1101   unsigned regB = MI.getOperand(SrcIdx).getReg();
1103   assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1104          "cannot make instruction into two-address form");
1105   bool regBKilled = isKilled(MI, regB, MRI, TII, LIS, true);
1107   if (TargetRegisterInfo::isVirtualRegister(regA))
1108     scanUses(regA);
1110   // Check if it is profitable to commute the operands.
1111   unsigned SrcOp1, SrcOp2;
1112   unsigned regC = 0;
1113   unsigned regCIdx = ~0U;
1114   bool TryCommute = false;
1115   bool AggressiveCommute = false;
1116   if (MI.isCommutable() && MI.getNumOperands() >= 3 &&
1117       TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
1118     if (SrcIdx == SrcOp1)
1119       regCIdx = SrcOp2;
1120     else if (SrcIdx == SrcOp2)
1121       regCIdx = SrcOp1;
1123     if (regCIdx != ~0U) {
1124       regC = MI.getOperand(regCIdx).getReg();
1125       if (!regBKilled && isKilled(MI, regC, MRI, TII, LIS, false))
1126         // If C dies but B does not, swap the B and C operands.
1127         // This makes the live ranges of A and C joinable.
1128         TryCommute = true;
1129       else if (isProfitableToCommute(regA, regB, regC, &MI, Dist)) {
1130         TryCommute = true;
1131         AggressiveCommute = true;
1132       }
1133     }
1134   }
1136   // If it's profitable to commute, try to do so.
1137   if (TryCommute && commuteInstruction(mi, regB, regC, Dist)) {
1138     ++NumCommuted;
1139     if (AggressiveCommute)
1140       ++NumAggrCommuted;
1141     return false;
1142   }
1144   if (shouldOnlyCommute)
1145     return false;
1147   // If there is one more use of regB later in the same MBB, consider
1148   // re-schedule this MI below it.
1149   if (EnableRescheduling && rescheduleMIBelowKill(mi, nmi, regB)) {
1150     ++NumReSchedDowns;
1151     return true;
1152   }
1154   if (MI.isConvertibleTo3Addr()) {
1155     // This instruction is potentially convertible to a true
1156     // three-address instruction.  Check if it is profitable.
1157     if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
1158       // Try to convert it.
1159       if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
1160         ++NumConvertedTo3Addr;
1161         return true; // Done with this instruction.
1162       }
1163     }
1164   }
1166   // If there is one more use of regB later in the same MBB, consider
1167   // re-schedule it before this MI if it's legal.
1168   if (EnableRescheduling && rescheduleKillAboveMI(mi, nmi, regB)) {
1169     ++NumReSchedUps;
1170     return true;
1171   }
1173   // If this is an instruction with a load folded into it, try unfolding
1174   // the load, e.g. avoid this:
1175   //   movq %rdx, %rcx
1176   //   addq (%rax), %rcx
1177   // in favor of this:
1178   //   movq (%rax), %rcx
1179   //   addq %rdx, %rcx
1180   // because it's preferable to schedule a load than a register copy.
1181   if (MI.mayLoad() && !regBKilled) {
1182     // Determine if a load can be unfolded.
1183     unsigned LoadRegIndex;
1184     unsigned NewOpc =
1185       TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1186                                       /*UnfoldLoad=*/true,
1187                                       /*UnfoldStore=*/false,
1188                                       &LoadRegIndex);
1189     if (NewOpc != 0) {
1190       const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1191       if (UnfoldMCID.getNumDefs() == 1) {
1192         // Unfold the load.
1193         DEBUG(dbgs() << "2addr:   UNFOLDING: " << MI);
1194         const TargetRegisterClass *RC =
1195           TRI->getAllocatableClass(
1196             TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI, *MF));
1197         unsigned Reg = MRI->createVirtualRegister(RC);
1198         SmallVector<MachineInstr *, 2> NewMIs;
1199         if (!TII->unfoldMemoryOperand(*MF, &MI, Reg,
1200                                       /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
1201                                       NewMIs)) {
1202           DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1203           return false;
1204         }
1205         assert(NewMIs.size() == 2 &&
1206                "Unfolded a load into multiple instructions!");
1207         // The load was previously folded, so this is the only use.
1208         NewMIs[1]->addRegisterKilled(Reg, TRI);
1210         // Tentatively insert the instructions into the block so that they
1211         // look "normal" to the transformation logic.
1212         MBB->insert(mi, NewMIs[0]);
1213         MBB->insert(mi, NewMIs[1]);
1215         DEBUG(dbgs() << "2addr:    NEW LOAD: " << *NewMIs[0]
1216                      << "2addr:    NEW INST: " << *NewMIs[1]);
1218         // Transform the instruction, now that it no longer has a load.
1219         unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1220         unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1221         MachineBasicBlock::iterator NewMI = NewMIs[1];
1222         bool TransformResult =
1223           tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist, true);
1224         (void)TransformResult;
1225         assert(!TransformResult &&
1226                "tryInstructionTransform() should return false.");
1227         if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1228           // Success, or at least we made an improvement. Keep the unfolded
1229           // instructions and discard the original.
1230           if (LV) {
1231             for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1232               MachineOperand &MO = MI.getOperand(i);
1233               if (MO.isReg() &&
1234                   TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1235                 if (MO.isUse()) {
1236                   if (MO.isKill()) {
1237                     if (NewMIs[0]->killsRegister(MO.getReg()))
1238                       LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
1239                     else {
1240                       assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1241                              "Kill missing after load unfold!");
1242                       LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
1243                     }
1244                   }
1245                 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
1246                   if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1247                     LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
1248                   else {
1249                     assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1250                            "Dead flag missing after load unfold!");
1251                     LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
1252                   }
1253                 }
1254               }
1255             }
1256             LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
1257           }
1259           SmallVector<unsigned, 4> OrigRegs;
1260           if (LIS) {
1261             for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(),
1262                  MOE = MI.operands_end(); MOI != MOE; ++MOI) {
1263               if (MOI->isReg())
1264                 OrigRegs.push_back(MOI->getReg());
1265             }
1266           }
1268           MI.eraseFromParent();
1270           // Update LiveIntervals.
1271           if (LIS) {
1272             MachineBasicBlock::iterator Begin(NewMIs[0]);
1273             MachineBasicBlock::iterator End(NewMIs[1]);
1274             LIS->repairIntervalsInRange(MBB, Begin, End, OrigRegs);
1275           }
1277           mi = NewMIs[1];
1278         } else {
1279           // Transforming didn't eliminate the tie and didn't lead to an
1280           // improvement. Clean up the unfolded instructions and keep the
1281           // original.
1282           DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1283           NewMIs[0]->eraseFromParent();
1284           NewMIs[1]->eraseFromParent();
1285         }
1286       }
1287     }
1288   }
1290   return false;
1293 // Collect tied operands of MI that need to be handled.
1294 // Rewrite trivial cases immediately.
1295 // Return true if any tied operands where found, including the trivial ones.
1296 bool TwoAddressInstructionPass::
1297 collectTiedOperands(MachineInstr *MI, TiedOperandMap &TiedOperands) {
1298   const MCInstrDesc &MCID = MI->getDesc();
1299   bool AnyOps = false;
1300   unsigned NumOps = MI->getNumOperands();
1302   for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1303     unsigned DstIdx = 0;
1304     if (!MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1305       continue;
1306     AnyOps = true;
1307     MachineOperand &SrcMO = MI->getOperand(SrcIdx);
1308     MachineOperand &DstMO = MI->getOperand(DstIdx);
1309     unsigned SrcReg = SrcMO.getReg();
1310     unsigned DstReg = DstMO.getReg();
1311     // Tied constraint already satisfied?
1312     if (SrcReg == DstReg)
1313       continue;
1315     assert(SrcReg && SrcMO.isUse() && "two address instruction invalid");
1317     // Deal with <undef> uses immediately - simply rewrite the src operand.
1318     if (SrcMO.isUndef() && !DstMO.getSubReg()) {
1319       // Constrain the DstReg register class if required.
1320       if (TargetRegisterInfo::isVirtualRegister(DstReg))
1321         if (const TargetRegisterClass *RC = TII->getRegClass(MCID, SrcIdx,
1322                                                              TRI, *MF))
1323           MRI->constrainRegClass(DstReg, RC);
1324       SrcMO.setReg(DstReg);
1325       SrcMO.setSubReg(0);
1326       DEBUG(dbgs() << "\t\trewrite undef:\t" << *MI);
1327       continue;
1328     }
1329     TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
1330   }
1331   return AnyOps;
1334 // Process a list of tied MI operands that all use the same source register.
1335 // The tied pairs are of the form (SrcIdx, DstIdx).
1336 void
1337 TwoAddressInstructionPass::processTiedPairs(MachineInstr *MI,
1338                                             TiedPairList &TiedPairs,
1339                                             unsigned &Dist) {
1340   bool IsEarlyClobber = false;
1341   for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1342     const MachineOperand &DstMO = MI->getOperand(TiedPairs[tpi].second);
1343     IsEarlyClobber |= DstMO.isEarlyClobber();
1344   }
1346   bool RemovedKillFlag = false;
1347   bool AllUsesCopied = true;
1348   unsigned LastCopiedReg = 0;
1349   SlotIndex LastCopyIdx;
1350   unsigned RegB = 0;
1351   unsigned SubRegB = 0;
1352   for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1353     unsigned SrcIdx = TiedPairs[tpi].first;
1354     unsigned DstIdx = TiedPairs[tpi].second;
1356     const MachineOperand &DstMO = MI->getOperand(DstIdx);
1357     unsigned RegA = DstMO.getReg();
1359     // Grab RegB from the instruction because it may have changed if the
1360     // instruction was commuted.
1361     RegB = MI->getOperand(SrcIdx).getReg();
1362     SubRegB = MI->getOperand(SrcIdx).getSubReg();
1364     if (RegA == RegB) {
1365       // The register is tied to multiple destinations (or else we would
1366       // not have continued this far), but this use of the register
1367       // already matches the tied destination.  Leave it.
1368       AllUsesCopied = false;
1369       continue;
1370     }
1371     LastCopiedReg = RegA;
1373     assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
1374            "cannot make instruction into two-address form");
1376 #ifndef NDEBUG
1377     // First, verify that we don't have a use of "a" in the instruction
1378     // (a = b + a for example) because our transformation will not
1379     // work. This should never occur because we are in SSA form.
1380     for (unsigned i = 0; i != MI->getNumOperands(); ++i)
1381       assert(i == DstIdx ||
1382              !MI->getOperand(i).isReg() ||
1383              MI->getOperand(i).getReg() != RegA);
1384 #endif
1386     // Emit a copy.
1387     MachineInstrBuilder MIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1388                                       TII->get(TargetOpcode::COPY), RegA);
1389     // If this operand is folding a truncation, the truncation now moves to the
1390     // copy so that the register classes remain valid for the operands.
1391     MIB.addReg(RegB, 0, SubRegB);
1392     const TargetRegisterClass *RC = MRI->getRegClass(RegB);
1393     if (SubRegB) {
1394       if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1395         assert(TRI->getMatchingSuperRegClass(RC, MRI->getRegClass(RegA),
1396                                              SubRegB) &&
1397                "tied subregister must be a truncation");
1398         // The superreg class will not be used to constrain the subreg class.
1399         RC = nullptr;
1400       }
1401       else {
1402         assert(TRI->getMatchingSuperReg(RegA, SubRegB, MRI->getRegClass(RegB))
1403                && "tied subregister must be a truncation");
1404       }
1405     }
1407     // Update DistanceMap.
1408     MachineBasicBlock::iterator PrevMI = MI;
1409     --PrevMI;
1410     DistanceMap.insert(std::make_pair(PrevMI, Dist));
1411     DistanceMap[MI] = ++Dist;
1413     if (LIS) {
1414       LastCopyIdx = LIS->InsertMachineInstrInMaps(PrevMI).getRegSlot();
1416       if (TargetRegisterInfo::isVirtualRegister(RegA)) {
1417         LiveInterval &LI = LIS->getInterval(RegA);
1418         VNInfo *VNI = LI.getNextValue(LastCopyIdx, LIS->getVNInfoAllocator());
1419         SlotIndex endIdx =
1420           LIS->getInstructionIndex(MI).getRegSlot(IsEarlyClobber);
1421         LI.addSegment(LiveInterval::Segment(LastCopyIdx, endIdx, VNI));
1422       }
1423     }
1425     DEBUG(dbgs() << "\t\tprepend:\t" << *MIB);
1427     MachineOperand &MO = MI->getOperand(SrcIdx);
1428     assert(MO.isReg() && MO.getReg() == RegB && MO.isUse() &&
1429            "inconsistent operand info for 2-reg pass");
1430     if (MO.isKill()) {
1431       MO.setIsKill(false);
1432       RemovedKillFlag = true;
1433     }
1435     // Make sure regA is a legal regclass for the SrcIdx operand.
1436     if (TargetRegisterInfo::isVirtualRegister(RegA) &&
1437         TargetRegisterInfo::isVirtualRegister(RegB))
1438       MRI->constrainRegClass(RegA, RC);
1439     MO.setReg(RegA);
1440     // The getMatchingSuper asserts guarantee that the register class projected
1441     // by SubRegB is compatible with RegA with no subregister. So regardless of
1442     // whether the dest oper writes a subreg, the source oper should not.
1443     MO.setSubReg(0);
1445     // Propagate SrcRegMap.
1446     SrcRegMap[RegA] = RegB;
1447   }
1450   if (AllUsesCopied) {
1451     if (!IsEarlyClobber) {
1452       // Replace other (un-tied) uses of regB with LastCopiedReg.
1453       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1454         MachineOperand &MO = MI->getOperand(i);
1455         if (MO.isReg() && MO.getReg() == RegB && MO.getSubReg() == SubRegB &&
1456             MO.isUse()) {
1457           if (MO.isKill()) {
1458             MO.setIsKill(false);
1459             RemovedKillFlag = true;
1460           }
1461           MO.setReg(LastCopiedReg);
1462           MO.setSubReg(0);
1463         }
1464       }
1465     }
1467     // Update live variables for regB.
1468     if (RemovedKillFlag && LV && LV->getVarInfo(RegB).removeKill(MI)) {
1469       MachineBasicBlock::iterator PrevMI = MI;
1470       --PrevMI;
1471       LV->addVirtualRegisterKilled(RegB, PrevMI);
1472     }
1474     // Update LiveIntervals.
1475     if (LIS) {
1476       LiveInterval &LI = LIS->getInterval(RegB);
1477       SlotIndex MIIdx = LIS->getInstructionIndex(MI);
1478       LiveInterval::const_iterator I = LI.find(MIIdx);
1479       assert(I != LI.end() && "RegB must be live-in to use.");
1481       SlotIndex UseIdx = MIIdx.getRegSlot(IsEarlyClobber);
1482       if (I->end == UseIdx)
1483         LI.removeSegment(LastCopyIdx, UseIdx);
1484     }
1486   } else if (RemovedKillFlag) {
1487     // Some tied uses of regB matched their destination registers, so
1488     // regB is still used in this instruction, but a kill flag was
1489     // removed from a different tied use of regB, so now we need to add
1490     // a kill flag to one of the remaining uses of regB.
1491     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1492       MachineOperand &MO = MI->getOperand(i);
1493       if (MO.isReg() && MO.getReg() == RegB && MO.isUse()) {
1494         MO.setIsKill(true);
1495         break;
1496       }
1497     }
1498   }
1501 /// runOnMachineFunction - Reduce two-address instructions to two operands.
1502 ///
1503 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &Func) {
1504   MF = &Func;
1505   const TargetMachine &TM = MF->getTarget();
1506   MRI = &MF->getRegInfo();
1507   TII = TM.getSubtargetImpl()->getInstrInfo();
1508   TRI = TM.getSubtargetImpl()->getRegisterInfo();
1509   InstrItins = TM.getSubtargetImpl()->getInstrItineraryData();
1510   LV = getAnalysisIfAvailable<LiveVariables>();
1511   LIS = getAnalysisIfAvailable<LiveIntervals>();
1512   AA = &getAnalysis<AliasAnalysis>();
1513   OptLevel = TM.getOptLevel();
1515   bool MadeChange = false;
1517   DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
1518   DEBUG(dbgs() << "********** Function: "
1519         << MF->getName() << '\n');
1521   // This pass takes the function out of SSA form.
1522   MRI->leaveSSA();
1524   TiedOperandMap TiedOperands;
1525   for (MachineFunction::iterator MBBI = MF->begin(), MBBE = MF->end();
1526        MBBI != MBBE; ++MBBI) {
1527     MBB = MBBI;
1528     unsigned Dist = 0;
1529     DistanceMap.clear();
1530     SrcRegMap.clear();
1531     DstRegMap.clear();
1532     Processed.clear();
1533     for (MachineBasicBlock::iterator mi = MBB->begin(), me = MBB->end();
1534          mi != me; ) {
1535       MachineBasicBlock::iterator nmi = std::next(mi);
1536       if (mi->isDebugValue()) {
1537         mi = nmi;
1538         continue;
1539       }
1541       // Expand REG_SEQUENCE instructions. This will position mi at the first
1542       // expanded instruction.
1543       if (mi->isRegSequence())
1544         eliminateRegSequence(mi);
1546       DistanceMap.insert(std::make_pair(mi, ++Dist));
1548       processCopy(&*mi);
1550       // First scan through all the tied register uses in this instruction
1551       // and record a list of pairs of tied operands for each register.
1552       if (!collectTiedOperands(mi, TiedOperands)) {
1553         mi = nmi;
1554         continue;
1555       }
1557       ++NumTwoAddressInstrs;
1558       MadeChange = true;
1559       DEBUG(dbgs() << '\t' << *mi);
1561       // If the instruction has a single pair of tied operands, try some
1562       // transformations that may either eliminate the tied operands or
1563       // improve the opportunities for coalescing away the register copy.
1564       if (TiedOperands.size() == 1) {
1565         SmallVectorImpl<std::pair<unsigned, unsigned> > &TiedPairs
1566           = TiedOperands.begin()->second;
1567         if (TiedPairs.size() == 1) {
1568           unsigned SrcIdx = TiedPairs[0].first;
1569           unsigned DstIdx = TiedPairs[0].second;
1570           unsigned SrcReg = mi->getOperand(SrcIdx).getReg();
1571           unsigned DstReg = mi->getOperand(DstIdx).getReg();
1572           if (SrcReg != DstReg &&
1573               tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist, false)) {
1574             // The tied operands have been eliminated or shifted further down the
1575             // block to ease elimination. Continue processing with 'nmi'.
1576             TiedOperands.clear();
1577             mi = nmi;
1578             continue;
1579           }
1580         }
1581       }
1583       // Now iterate over the information collected above.
1584       for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1585              OE = TiedOperands.end(); OI != OE; ++OI) {
1586         processTiedPairs(mi, OI->second, Dist);
1587         DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1588       }
1590       // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1591       if (mi->isInsertSubreg()) {
1592         // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1593         // To   %reg:subidx = COPY %subreg
1594         unsigned SubIdx = mi->getOperand(3).getImm();
1595         mi->RemoveOperand(3);
1596         assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1597         mi->getOperand(0).setSubReg(SubIdx);
1598         mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1599         mi->RemoveOperand(1);
1600         mi->setDesc(TII->get(TargetOpcode::COPY));
1601         DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
1602       }
1604       // Clear TiedOperands here instead of at the top of the loop
1605       // since most instructions do not have tied operands.
1606       TiedOperands.clear();
1607       mi = nmi;
1608     }
1609   }
1611   if (LIS)
1612     MF->verify(this, "After two-address instruction pass");
1614   return MadeChange;
1617 /// Eliminate a REG_SEQUENCE instruction as part of the de-ssa process.
1618 ///
1619 /// The instruction is turned into a sequence of sub-register copies:
1620 ///
1621 ///   %dst = REG_SEQUENCE %v1, ssub0, %v2, ssub1
1622 ///
1623 /// Becomes:
1624 ///
1625 ///   %dst:ssub0<def,undef> = COPY %v1
1626 ///   %dst:ssub1<def> = COPY %v2
1627 ///
1628 void TwoAddressInstructionPass::
1629 eliminateRegSequence(MachineBasicBlock::iterator &MBBI) {
1630   MachineInstr *MI = MBBI;
1631   unsigned DstReg = MI->getOperand(0).getReg();
1632   if (MI->getOperand(0).getSubReg() ||
1633       TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1634       !(MI->getNumOperands() & 1)) {
1635     DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1636     llvm_unreachable(nullptr);
1637   }
1639   SmallVector<unsigned, 4> OrigRegs;
1640   if (LIS) {
1641     OrigRegs.push_back(MI->getOperand(0).getReg());
1642     for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2)
1643       OrigRegs.push_back(MI->getOperand(i).getReg());
1644   }
1646   bool DefEmitted = false;
1647   for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1648     MachineOperand &UseMO = MI->getOperand(i);
1649     unsigned SrcReg = UseMO.getReg();
1650     unsigned SubIdx = MI->getOperand(i+1).getImm();
1651     // Nothing needs to be inserted for <undef> operands.
1652     if (UseMO.isUndef())
1653       continue;
1655     // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1656     // might insert a COPY that uses SrcReg after is was killed.
1657     bool isKill = UseMO.isKill();
1658     if (isKill)
1659       for (unsigned j = i + 2; j < e; j += 2)
1660         if (MI->getOperand(j).getReg() == SrcReg) {
1661           MI->getOperand(j).setIsKill();
1662           UseMO.setIsKill(false);
1663           isKill = false;
1664           break;
1665         }
1667     // Insert the sub-register copy.
1668     MachineInstr *CopyMI = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1669                                    TII->get(TargetOpcode::COPY))
1670       .addReg(DstReg, RegState::Define, SubIdx)
1671       .addOperand(UseMO);
1673     // The first def needs an <undef> flag because there is no live register
1674     // before it.
1675     if (!DefEmitted) {
1676       CopyMI->getOperand(0).setIsUndef(true);
1677       // Return an iterator pointing to the first inserted instr.
1678       MBBI = CopyMI;
1679     }
1680     DefEmitted = true;
1682     // Update LiveVariables' kill info.
1683     if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg))
1684       LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1686     DEBUG(dbgs() << "Inserted: " << *CopyMI);
1687   }
1689   MachineBasicBlock::iterator EndMBBI =
1690       std::next(MachineBasicBlock::iterator(MI));
1692   if (!DefEmitted) {
1693     DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1694     MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1695     for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
1696       MI->RemoveOperand(j);
1697   } else {
1698     DEBUG(dbgs() << "Eliminated: " << *MI);
1699     MI->eraseFromParent();
1700   }
1702   // Udpate LiveIntervals.
1703   if (LIS)
1704     LIS->repairIntervalsInRange(MBB, MBBI, EndMBBI, OrigRegs);