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