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