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