1 //===- PeepholeOptimizer.cpp - Peephole Optimizations ---------------------===//
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 // Perform peephole optimizations on the machine code:
10 //
11 // - Optimize Extensions
12 //
13 //     Optimization of sign / zero extension instructions. It may be extended to
14 //     handle other instructions with similar properties.
15 //
16 //     On some targets, some instructions, e.g. X86 sign / zero extension, may
17 //     leave the source value in the lower part of the result. This optimization
18 //     will replace some uses of the pre-extension value with uses of the
19 //     sub-register of the results.
20 //
21 // - Optimize Comparisons
22 //
23 //     Optimization of comparison instructions. For instance, in this code:
24 //
25 //       sub r1, 1
26 //       cmp r1, 0
27 //       bz  L1
28 //
29 //     If the "sub" instruction all ready sets (or could be modified to set) the
30 //     same flag that the "cmp" instruction sets and that "bz" uses, then we can
31 //     eliminate the "cmp" instruction.
32 //
33 //     Another instance, in this code:
34 //
35 //       sub r1, r3 | sub r1, imm
36 //       cmp r3, r1 or cmp r1, r3 | cmp r1, imm
37 //       bge L1
38 //
39 //     If the branch instruction can use flag from "sub", then we can replace
40 //     "sub" with "subs" and eliminate the "cmp" instruction.
41 //
42 // - Optimize Loads:
43 //
44 //     Loads that can be folded into a later instruction. A load is foldable
45 //     if it loads to virtual registers and the virtual register defined has
46 //     a single use.
47 //
48 // - Optimize Copies and Bitcast (more generally, target specific copies):
49 //
50 //     Rewrite copies and bitcasts to avoid cross register bank copies
51 //     when possible.
52 //     E.g., Consider the following example, where capital and lower
53 //     letters denote different register file:
54 //     b = copy A <-- cross-bank copy
55 //     C = copy b <-- cross-bank copy
56 //   =>
57 //     b = copy A <-- cross-bank copy
58 //     C = copy A <-- same-bank copy
59 //
60 //     E.g., for bitcast:
61 //     b = bitcast A <-- cross-bank copy
62 //     C = bitcast b <-- cross-bank copy
63 //   =>
64 //     b = bitcast A <-- cross-bank copy
65 //     C = copy A    <-- same-bank copy
66 //===----------------------------------------------------------------------===//
67 
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/Optional.h"
70 #include "llvm/ADT/SmallPtrSet.h"
71 #include "llvm/ADT/SmallSet.h"
72 #include "llvm/ADT/SmallVector.h"
73 #include "llvm/ADT/Statistic.h"
74 #include "llvm/CodeGen/MachineBasicBlock.h"
75 #include "llvm/CodeGen/MachineDominators.h"
76 #include "llvm/CodeGen/MachineFunction.h"
77 #include "llvm/CodeGen/MachineFunctionPass.h"
78 #include "llvm/CodeGen/MachineInstr.h"
79 #include "llvm/CodeGen/MachineInstrBuilder.h"
80 #include "llvm/CodeGen/MachineLoopInfo.h"
81 #include "llvm/CodeGen/MachineOperand.h"
82 #include "llvm/CodeGen/MachineRegisterInfo.h"
83 #include "llvm/CodeGen/TargetInstrInfo.h"
84 #include "llvm/CodeGen/TargetOpcodes.h"
85 #include "llvm/CodeGen/TargetRegisterInfo.h"
86 #include "llvm/CodeGen/TargetSubtargetInfo.h"
87 #include "llvm/InitializePasses.h"
88 #include "llvm/MC/LaneBitmask.h"
89 #include "llvm/MC/MCInstrDesc.h"
90 #include "llvm/Pass.h"
91 #include "llvm/Support/CommandLine.h"
92 #include "llvm/Support/Debug.h"
93 #include "llvm/Support/ErrorHandling.h"
94 #include "llvm/Support/raw_ostream.h"
95 #include <cassert>
96 #include <cstdint>
97 #include <memory>
98 #include <utility>
99 
100 using namespace llvm;
101 using RegSubRegPair = TargetInstrInfo::RegSubRegPair;
102 using RegSubRegPairAndIdx = TargetInstrInfo::RegSubRegPairAndIdx;
103 
104 #define DEBUG_TYPE "peephole-opt"
105 
106 // Optimize Extensions
107 static cl::opt<bool>
108 Aggressive("aggressive-ext-opt", cl::Hidden,
109            cl::desc("Aggressive extension optimization"));
110 
111 static cl::opt<bool>
112 DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
113                 cl::desc("Disable the peephole optimizer"));
114 
115 /// Specifiy whether or not the value tracking looks through
116 /// complex instructions. When this is true, the value tracker
117 /// bails on everything that is not a copy or a bitcast.
118 static cl::opt<bool>
119 DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false),
120                   cl::desc("Disable advanced copy optimization"));
121 
122 static cl::opt<bool> DisableNAPhysCopyOpt(
123     "disable-non-allocatable-phys-copy-opt", cl::Hidden, cl::init(false),
124     cl::desc("Disable non-allocatable physical register copy optimization"));
125 
126 // Limit the number of PHI instructions to process
127 // in PeepholeOptimizer::getNextSource.
128 static cl::opt<unsigned> RewritePHILimit(
129     "rewrite-phi-limit", cl::Hidden, cl::init(10),
130     cl::desc("Limit the length of PHI chains to lookup"));
131 
132 // Limit the length of recurrence chain when evaluating the benefit of
133 // commuting operands.
134 static cl::opt<unsigned> MaxRecurrenceChain(
135     "recurrence-chain-limit", cl::Hidden, cl::init(3),
136     cl::desc("Maximum length of recurrence chain when evaluating the benefit "
137              "of commuting operands"));
138 
139 
140 STATISTIC(NumReuse, "Number of extension results reused");
141 STATISTIC(NumCmps, "Number of compares eliminated");
142 STATISTIC(NumImmFold, "Number of move immediate folded");
143 STATISTIC(NumLoadFold, "Number of loads folded");
144 STATISTIC(NumSelects, "Number of selects optimized");
145 STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
146 STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
147 STATISTIC(NumNAPhysCopies, "Number of non-allocatable physical copies removed");
148 
149 namespace {
150 
151   class ValueTrackerResult;
152   class RecurrenceInstr;
153 
154   class PeepholeOptimizer : public MachineFunctionPass {
155     const TargetInstrInfo *TII;
156     const TargetRegisterInfo *TRI;
157     MachineRegisterInfo *MRI;
158     MachineDominatorTree *DT;  // Machine dominator tree
159     MachineLoopInfo *MLI;
160 
161   public:
162     static char ID; // Pass identification
163 
164     PeepholeOptimizer() : MachineFunctionPass(ID) {
165       initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
166     }
167 
168     bool runOnMachineFunction(MachineFunction &MF) override;
169 
170     void getAnalysisUsage(AnalysisUsage &AU) const override {
171       AU.setPreservesCFG();
172       MachineFunctionPass::getAnalysisUsage(AU);
173       AU.addRequired<MachineLoopInfo>();
174       AU.addPreserved<MachineLoopInfo>();
175       if (Aggressive) {
176         AU.addRequired<MachineDominatorTree>();
177         AU.addPreserved<MachineDominatorTree>();
178       }
179     }
180 
181     /// Track Def -> Use info used for rewriting copies.
182     using RewriteMapTy = SmallDenseMap<RegSubRegPair, ValueTrackerResult>;
183 
184     /// Sequence of instructions that formulate recurrence cycle.
185     using RecurrenceCycle = SmallVector<RecurrenceInstr, 4>;
186 
187   private:
188     bool optimizeCmpInstr(MachineInstr &MI);
189     bool optimizeExtInstr(MachineInstr &MI, MachineBasicBlock &MBB,
190                           SmallPtrSetImpl<MachineInstr*> &LocalMIs);
191     bool optimizeSelect(MachineInstr &MI,
192                         SmallPtrSetImpl<MachineInstr *> &LocalMIs);
193     bool optimizeCondBranch(MachineInstr &MI);
194     bool optimizeCoalescableCopy(MachineInstr &MI);
195     bool optimizeUncoalescableCopy(MachineInstr &MI,
196                                    SmallPtrSetImpl<MachineInstr *> &LocalMIs);
197     bool optimizeRecurrence(MachineInstr &PHI);
198     bool findNextSource(RegSubRegPair RegSubReg, RewriteMapTy &RewriteMap);
199     bool isMoveImmediate(MachineInstr &MI,
200                          SmallSet<unsigned, 4> &ImmDefRegs,
201                          DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
202     bool foldImmediate(MachineInstr &MI, SmallSet<unsigned, 4> &ImmDefRegs,
203                        DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
204 
205     /// Finds recurrence cycles, but only ones that formulated around
206     /// a def operand and a use operand that are tied. If there is a use
207     /// operand commutable with the tied use operand, find recurrence cycle
208     /// along that operand as well.
209     bool findTargetRecurrence(unsigned Reg,
210                               const SmallSet<unsigned, 2> &TargetReg,
211                               RecurrenceCycle &RC);
212 
213     /// If copy instruction \p MI is a virtual register copy, track it in
214     /// the set \p CopySrcRegs and \p CopyMIs. If this virtual register was
215     /// previously seen as a copy, replace the uses of this copy with the
216     /// previously seen copy's destination register.
217     bool foldRedundantCopy(MachineInstr &MI,
218                            SmallSet<unsigned, 4> &CopySrcRegs,
219                            DenseMap<unsigned, MachineInstr *> &CopyMIs);
220 
221     /// Is the register \p Reg a non-allocatable physical register?
222     bool isNAPhysCopy(unsigned Reg);
223 
224     /// If copy instruction \p MI is a non-allocatable virtual<->physical
225     /// register copy, track it in the \p NAPhysToVirtMIs map. If this
226     /// non-allocatable physical register was previously copied to a virtual
227     /// registered and hasn't been clobbered, the virt->phys copy can be
228     /// deleted.
229     bool foldRedundantNAPhysCopy(MachineInstr &MI,
230         DenseMap<unsigned, MachineInstr *> &NAPhysToVirtMIs);
231 
232     bool isLoadFoldable(MachineInstr &MI,
233                         SmallSet<unsigned, 16> &FoldAsLoadDefCandidates);
234 
235     /// Check whether \p MI is understood by the register coalescer
236     /// but may require some rewriting.
237     bool isCoalescableCopy(const MachineInstr &MI) {
238       // SubregToRegs are not interesting, because they are already register
239       // coalescer friendly.
240       return MI.isCopy() || (!DisableAdvCopyOpt &&
241                              (MI.isRegSequence() || MI.isInsertSubreg() ||
242                               MI.isExtractSubreg()));
243     }
244 
245     /// Check whether \p MI is a copy like instruction that is
246     /// not recognized by the register coalescer.
247     bool isUncoalescableCopy(const MachineInstr &MI) {
248       return MI.isBitcast() ||
249              (!DisableAdvCopyOpt &&
250               (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
251                MI.isExtractSubregLike()));
252     }
253 
254     MachineInstr &rewriteSource(MachineInstr &CopyLike,
255                                 RegSubRegPair Def, RewriteMapTy &RewriteMap);
256   };
257 
258   /// Helper class to hold instructions that are inside recurrence cycles.
259   /// The recurrence cycle is formulated around 1) a def operand and its
260   /// tied use operand, or 2) a def operand and a use operand that is commutable
261   /// with another use operand which is tied to the def operand. In the latter
262   /// case, index of the tied use operand and the commutable use operand are
263   /// maintained with CommutePair.
264   class RecurrenceInstr {
265   public:
266     using IndexPair = std::pair<unsigned, unsigned>;
267 
268     RecurrenceInstr(MachineInstr *MI) : MI(MI) {}
269     RecurrenceInstr(MachineInstr *MI, unsigned Idx1, unsigned Idx2)
270       : MI(MI), CommutePair(std::make_pair(Idx1, Idx2)) {}
271 
272     MachineInstr *getMI() const { return MI; }
273     Optional<IndexPair> getCommutePair() const { return CommutePair; }
274 
275   private:
276     MachineInstr *MI;
277     Optional<IndexPair> CommutePair;
278   };
279 
280   /// Helper class to hold a reply for ValueTracker queries.
281   /// Contains the returned sources for a given search and the instructions
282   /// where the sources were tracked from.
283   class ValueTrackerResult {
284   private:
285     /// Track all sources found by one ValueTracker query.
286     SmallVector<RegSubRegPair, 2> RegSrcs;
287 
288     /// Instruction using the sources in 'RegSrcs'.
289     const MachineInstr *Inst = nullptr;
290 
291   public:
292     ValueTrackerResult() = default;
293 
294     ValueTrackerResult(unsigned Reg, unsigned SubReg) {
295       addSource(Reg, SubReg);
296     }
297 
298     bool isValid() const { return getNumSources() > 0; }
299 
300     void setInst(const MachineInstr *I) { Inst = I; }
301     const MachineInstr *getInst() const { return Inst; }
302 
303     void clear() {
304       RegSrcs.clear();
305       Inst = nullptr;
306     }
307 
308     void addSource(unsigned SrcReg, unsigned SrcSubReg) {
309       RegSrcs.push_back(RegSubRegPair(SrcReg, SrcSubReg));
310     }
311 
312     void setSource(int Idx, unsigned SrcReg, unsigned SrcSubReg) {
313       assert(Idx < getNumSources() && "Reg pair source out of index");
314       RegSrcs[Idx] = RegSubRegPair(SrcReg, SrcSubReg);
315     }
316 
317     int getNumSources() const { return RegSrcs.size(); }
318 
319     RegSubRegPair getSrc(int Idx) const {
320       return RegSrcs[Idx];
321     }
322 
323     unsigned getSrcReg(int Idx) const {
324       assert(Idx < getNumSources() && "Reg source out of index");
325       return RegSrcs[Idx].Reg;
326     }
327 
328     unsigned getSrcSubReg(int Idx) const {
329       assert(Idx < getNumSources() && "SubReg source out of index");
330       return RegSrcs[Idx].SubReg;
331     }
332 
333     bool operator==(const ValueTrackerResult &Other) {
334       if (Other.getInst() != getInst())
335         return false;
336 
337       if (Other.getNumSources() != getNumSources())
338         return false;
339 
340       for (int i = 0, e = Other.getNumSources(); i != e; ++i)
341         if (Other.getSrcReg(i) != getSrcReg(i) ||
342             Other.getSrcSubReg(i) != getSrcSubReg(i))
343           return false;
344       return true;
345     }
346   };
347 
348   /// Helper class to track the possible sources of a value defined by
349   /// a (chain of) copy related instructions.
350   /// Given a definition (instruction and definition index), this class
351   /// follows the use-def chain to find successive suitable sources.
352   /// The given source can be used to rewrite the definition into
353   /// def = COPY src.
354   ///
355   /// For instance, let us consider the following snippet:
356   /// v0 =
357   /// v2 = INSERT_SUBREG v1, v0, sub0
358   /// def = COPY v2.sub0
359   ///
360   /// Using a ValueTracker for def = COPY v2.sub0 will give the following
361   /// suitable sources:
362   /// v2.sub0 and v0.
363   /// Then, def can be rewritten into def = COPY v0.
364   class ValueTracker {
365   private:
366     /// The current point into the use-def chain.
367     const MachineInstr *Def = nullptr;
368 
369     /// The index of the definition in Def.
370     unsigned DefIdx = 0;
371 
372     /// The sub register index of the definition.
373     unsigned DefSubReg;
374 
375     /// The register where the value can be found.
376     unsigned Reg;
377 
378     /// MachineRegisterInfo used to perform tracking.
379     const MachineRegisterInfo &MRI;
380 
381     /// Optional TargetInstrInfo used to perform some complex tracking.
382     const TargetInstrInfo *TII;
383 
384     /// Dispatcher to the right underlying implementation of getNextSource.
385     ValueTrackerResult getNextSourceImpl();
386 
387     /// Specialized version of getNextSource for Copy instructions.
388     ValueTrackerResult getNextSourceFromCopy();
389 
390     /// Specialized version of getNextSource for Bitcast instructions.
391     ValueTrackerResult getNextSourceFromBitcast();
392 
393     /// Specialized version of getNextSource for RegSequence instructions.
394     ValueTrackerResult getNextSourceFromRegSequence();
395 
396     /// Specialized version of getNextSource for InsertSubreg instructions.
397     ValueTrackerResult getNextSourceFromInsertSubreg();
398 
399     /// Specialized version of getNextSource for ExtractSubreg instructions.
400     ValueTrackerResult getNextSourceFromExtractSubreg();
401 
402     /// Specialized version of getNextSource for SubregToReg instructions.
403     ValueTrackerResult getNextSourceFromSubregToReg();
404 
405     /// Specialized version of getNextSource for PHI instructions.
406     ValueTrackerResult getNextSourceFromPHI();
407 
408   public:
409     /// Create a ValueTracker instance for the value defined by \p Reg.
410     /// \p DefSubReg represents the sub register index the value tracker will
411     /// track. It does not need to match the sub register index used in the
412     /// definition of \p Reg.
413     /// If \p Reg is a physical register, a value tracker constructed with
414     /// this constructor will not find any alternative source.
415     /// Indeed, when \p Reg is a physical register that constructor does not
416     /// know which definition of \p Reg it should track.
417     /// Use the next constructor to track a physical register.
418     ValueTracker(unsigned Reg, unsigned DefSubReg,
419                  const MachineRegisterInfo &MRI,
420                  const TargetInstrInfo *TII = nullptr)
421         : DefSubReg(DefSubReg), Reg(Reg), MRI(MRI), TII(TII) {
422       if (!Register::isPhysicalRegister(Reg)) {
423         Def = MRI.getVRegDef(Reg);
424         DefIdx = MRI.def_begin(Reg).getOperandNo();
425       }
426     }
427 
428     /// Following the use-def chain, get the next available source
429     /// for the tracked value.
430     /// \return A ValueTrackerResult containing a set of registers
431     /// and sub registers with tracked values. A ValueTrackerResult with
432     /// an empty set of registers means no source was found.
433     ValueTrackerResult getNextSource();
434   };
435 
436 } // end anonymous namespace
437 
438 char PeepholeOptimizer::ID = 0;
439 
440 char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
441 
442 INITIALIZE_PASS_BEGIN(PeepholeOptimizer, DEBUG_TYPE,
443                       "Peephole Optimizations", false, false)
444 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
445 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
446 INITIALIZE_PASS_END(PeepholeOptimizer, DEBUG_TYPE,
447                     "Peephole Optimizations", false, false)
448 
449 /// If instruction is a copy-like instruction, i.e. it reads a single register
450 /// and writes a single register and it does not modify the source, and if the
451 /// source value is preserved as a sub-register of the result, then replace all
452 /// reachable uses of the source with the subreg of the result.
453 ///
454 /// Do not generate an EXTRACT that is used only in a debug use, as this changes
455 /// the code. Since this code does not currently share EXTRACTs, just ignore all
456 /// debug uses.
457 bool PeepholeOptimizer::
458 optimizeExtInstr(MachineInstr &MI, MachineBasicBlock &MBB,
459                  SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
460   Register SrcReg, DstReg;
461   unsigned SubIdx;
462   if (!TII->isCoalescableExtInstr(MI, SrcReg, DstReg, SubIdx))
463     return false;
464 
465   if (DstReg.isPhysical() || SrcReg.isPhysical())
466     return false;
467 
468   if (MRI->hasOneNonDBGUse(SrcReg))
469     // No other uses.
470     return false;
471 
472   // Ensure DstReg can get a register class that actually supports
473   // sub-registers. Don't change the class until we commit.
474   const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
475   DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
476   if (!DstRC)
477     return false;
478 
479   // The ext instr may be operating on a sub-register of SrcReg as well.
480   // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
481   // register.
482   // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
483   // SrcReg:SubIdx should be replaced.
484   bool UseSrcSubIdx =
485       TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
486 
487   // The source has other uses. See if we can replace the other uses with use of
488   // the result of the extension.
489   SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
490   for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
491     ReachedBBs.insert(UI.getParent());
492 
493   // Uses that are in the same BB of uses of the result of the instruction.
494   SmallVector<MachineOperand*, 8> Uses;
495 
496   // Uses that the result of the instruction can reach.
497   SmallVector<MachineOperand*, 8> ExtendedUses;
498 
499   bool ExtendLife = true;
500   for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
501     MachineInstr *UseMI = UseMO.getParent();
502     if (UseMI == &MI)
503       continue;
504 
505     if (UseMI->isPHI()) {
506       ExtendLife = false;
507       continue;
508     }
509 
510     // Only accept uses of SrcReg:SubIdx.
511     if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
512       continue;
513 
514     // It's an error to translate this:
515     //
516     //    %reg1025 = <sext> %reg1024
517     //     ...
518     //    %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
519     //
520     // into this:
521     //
522     //    %reg1025 = <sext> %reg1024
523     //     ...
524     //    %reg1027 = COPY %reg1025:4
525     //    %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
526     //
527     // The problem here is that SUBREG_TO_REG is there to assert that an
528     // implicit zext occurs. It doesn't insert a zext instruction. If we allow
529     // the COPY here, it will give us the value after the <sext>, not the
530     // original value of %reg1024 before <sext>.
531     if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
532       continue;
533 
534     MachineBasicBlock *UseMBB = UseMI->getParent();
535     if (UseMBB == &MBB) {
536       // Local uses that come after the extension.
537       if (!LocalMIs.count(UseMI))
538         Uses.push_back(&UseMO);
539     } else if (ReachedBBs.count(UseMBB)) {
540       // Non-local uses where the result of the extension is used. Always
541       // replace these unless it's a PHI.
542       Uses.push_back(&UseMO);
543     } else if (Aggressive && DT->dominates(&MBB, UseMBB)) {
544       // We may want to extend the live range of the extension result in order
545       // to replace these uses.
546       ExtendedUses.push_back(&UseMO);
547     } else {
548       // Both will be live out of the def MBB anyway. Don't extend live range of
549       // the extension result.
550       ExtendLife = false;
551       break;
552     }
553   }
554 
555   if (ExtendLife && !ExtendedUses.empty())
556     // Extend the liveness of the extension result.
557     Uses.append(ExtendedUses.begin(), ExtendedUses.end());
558 
559   // Now replace all uses.
560   bool Changed = false;
561   if (!Uses.empty()) {
562     SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
563 
564     // Look for PHI uses of the extended result, we don't want to extend the
565     // liveness of a PHI input. It breaks all kinds of assumptions down
566     // stream. A PHI use is expected to be the kill of its source values.
567     for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
568       if (UI.isPHI())
569         PHIBBs.insert(UI.getParent());
570 
571     const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
572     for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
573       MachineOperand *UseMO = Uses[i];
574       MachineInstr *UseMI = UseMO->getParent();
575       MachineBasicBlock *UseMBB = UseMI->getParent();
576       if (PHIBBs.count(UseMBB))
577         continue;
578 
579       // About to add uses of DstReg, clear DstReg's kill flags.
580       if (!Changed) {
581         MRI->clearKillFlags(DstReg);
582         MRI->constrainRegClass(DstReg, DstRC);
583       }
584 
585       Register NewVR = MRI->createVirtualRegister(RC);
586       MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
587                                    TII->get(TargetOpcode::COPY), NewVR)
588         .addReg(DstReg, 0, SubIdx);
589       // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
590       if (UseSrcSubIdx) {
591         Copy->getOperand(0).setSubReg(SubIdx);
592         Copy->getOperand(0).setIsUndef();
593       }
594       UseMO->setReg(NewVR);
595       ++NumReuse;
596       Changed = true;
597     }
598   }
599 
600   return Changed;
601 }
602 
603 /// If the instruction is a compare and the previous instruction it's comparing
604 /// against already sets (or could be modified to set) the same flag as the
605 /// compare, then we can remove the comparison and use the flag from the
606 /// previous instruction.
607 bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr &MI) {
608   // If this instruction is a comparison against zero and isn't comparing a
609   // physical register, we can try to optimize it.
610   Register SrcReg, SrcReg2;
611   int CmpMask, CmpValue;
612   if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
613       SrcReg.isPhysical() || SrcReg2.isPhysical())
614     return false;
615 
616   // Attempt to optimize the comparison instruction.
617   LLVM_DEBUG(dbgs() << "Attempting to optimize compare: " << MI);
618   if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
619     ++NumCmps;
620     return true;
621   }
622 
623   return false;
624 }
625 
626 /// Optimize a select instruction.
627 bool PeepholeOptimizer::optimizeSelect(MachineInstr &MI,
628                             SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
629   unsigned TrueOp = 0;
630   unsigned FalseOp = 0;
631   bool Optimizable = false;
632   SmallVector<MachineOperand, 4> Cond;
633   if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable))
634     return false;
635   if (!Optimizable)
636     return false;
637   if (!TII->optimizeSelect(MI, LocalMIs))
638     return false;
639   LLVM_DEBUG(dbgs() << "Deleting select: " << MI);
640   MI.eraseFromParent();
641   ++NumSelects;
642   return true;
643 }
644 
645 /// Check if a simpler conditional branch can be generated.
646 bool PeepholeOptimizer::optimizeCondBranch(MachineInstr &MI) {
647   return TII->optimizeCondBranch(MI);
648 }
649 
650 /// Try to find the next source that share the same register file
651 /// for the value defined by \p Reg and \p SubReg.
652 /// When true is returned, the \p RewriteMap can be used by the client to
653 /// retrieve all Def -> Use along the way up to the next source. Any found
654 /// Use that is not itself a key for another entry, is the next source to
655 /// use. During the search for the next source, multiple sources can be found
656 /// given multiple incoming sources of a PHI instruction. In this case, we
657 /// look in each PHI source for the next source; all found next sources must
658 /// share the same register file as \p Reg and \p SubReg. The client should
659 /// then be capable to rewrite all intermediate PHIs to get the next source.
660 /// \return False if no alternative sources are available. True otherwise.
661 bool PeepholeOptimizer::findNextSource(RegSubRegPair RegSubReg,
662                                        RewriteMapTy &RewriteMap) {
663   // Do not try to find a new source for a physical register.
664   // So far we do not have any motivating example for doing that.
665   // Thus, instead of maintaining untested code, we will revisit that if
666   // that changes at some point.
667   Register Reg = RegSubReg.Reg;
668   if (Reg.isPhysical())
669     return false;
670   const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
671 
672   SmallVector<RegSubRegPair, 4> SrcToLook;
673   RegSubRegPair CurSrcPair = RegSubReg;
674   SrcToLook.push_back(CurSrcPair);
675 
676   unsigned PHICount = 0;
677   do {
678     CurSrcPair = SrcToLook.pop_back_val();
679     // As explained above, do not handle physical registers
680     if (Register::isPhysicalRegister(CurSrcPair.Reg))
681       return false;
682 
683     ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI, TII);
684 
685     // Follow the chain of copies until we find a more suitable source, a phi
686     // or have to abort.
687     while (true) {
688       ValueTrackerResult Res = ValTracker.getNextSource();
689       // Abort at the end of a chain (without finding a suitable source).
690       if (!Res.isValid())
691         return false;
692 
693       // Insert the Def -> Use entry for the recently found source.
694       ValueTrackerResult CurSrcRes = RewriteMap.lookup(CurSrcPair);
695       if (CurSrcRes.isValid()) {
696         assert(CurSrcRes == Res && "ValueTrackerResult found must match");
697         // An existent entry with multiple sources is a PHI cycle we must avoid.
698         // Otherwise it's an entry with a valid next source we already found.
699         if (CurSrcRes.getNumSources() > 1) {
700           LLVM_DEBUG(dbgs()
701                      << "findNextSource: found PHI cycle, aborting...\n");
702           return false;
703         }
704         break;
705       }
706       RewriteMap.insert(std::make_pair(CurSrcPair, Res));
707 
708       // ValueTrackerResult usually have one source unless it's the result from
709       // a PHI instruction. Add the found PHI edges to be looked up further.
710       unsigned NumSrcs = Res.getNumSources();
711       if (NumSrcs > 1) {
712         PHICount++;
713         if (PHICount >= RewritePHILimit) {
714           LLVM_DEBUG(dbgs() << "findNextSource: PHI limit reached\n");
715           return false;
716         }
717 
718         for (unsigned i = 0; i < NumSrcs; ++i)
719           SrcToLook.push_back(Res.getSrc(i));
720         break;
721       }
722 
723       CurSrcPair = Res.getSrc(0);
724       // Do not extend the live-ranges of physical registers as they add
725       // constraints to the register allocator. Moreover, if we want to extend
726       // the live-range of a physical register, unlike SSA virtual register,
727       // we will have to check that they aren't redefine before the related use.
728       if (Register::isPhysicalRegister(CurSrcPair.Reg))
729         return false;
730 
731       // Keep following the chain if the value isn't any better yet.
732       const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg);
733       if (!TRI->shouldRewriteCopySrc(DefRC, RegSubReg.SubReg, SrcRC,
734                                      CurSrcPair.SubReg))
735         continue;
736 
737       // We currently cannot deal with subreg operands on PHI instructions
738       // (see insertPHI()).
739       if (PHICount > 0 && CurSrcPair.SubReg != 0)
740         continue;
741 
742       // We found a suitable source, and are done with this chain.
743       break;
744     }
745   } while (!SrcToLook.empty());
746 
747   // If we did not find a more suitable source, there is nothing to optimize.
748   return CurSrcPair.Reg != Reg;
749 }
750 
751 /// Insert a PHI instruction with incoming edges \p SrcRegs that are
752 /// guaranteed to have the same register class. This is necessary whenever we
753 /// successfully traverse a PHI instruction and find suitable sources coming
754 /// from its edges. By inserting a new PHI, we provide a rewritten PHI def
755 /// suitable to be used in a new COPY instruction.
756 static MachineInstr &
757 insertPHI(MachineRegisterInfo &MRI, const TargetInstrInfo &TII,
758           const SmallVectorImpl<RegSubRegPair> &SrcRegs,
759           MachineInstr &OrigPHI) {
760   assert(!SrcRegs.empty() && "No sources to create a PHI instruction?");
761 
762   const TargetRegisterClass *NewRC = MRI.getRegClass(SrcRegs[0].Reg);
763   // NewRC is only correct if no subregisters are involved. findNextSource()
764   // should have rejected those cases already.
765   assert(SrcRegs[0].SubReg == 0 && "should not have subreg operand");
766   Register NewVR = MRI.createVirtualRegister(NewRC);
767   MachineBasicBlock *MBB = OrigPHI.getParent();
768   MachineInstrBuilder MIB = BuildMI(*MBB, &OrigPHI, OrigPHI.getDebugLoc(),
769                                     TII.get(TargetOpcode::PHI), NewVR);
770 
771   unsigned MBBOpIdx = 2;
772   for (const RegSubRegPair &RegPair : SrcRegs) {
773     MIB.addReg(RegPair.Reg, 0, RegPair.SubReg);
774     MIB.addMBB(OrigPHI.getOperand(MBBOpIdx).getMBB());
775     // Since we're extended the lifetime of RegPair.Reg, clear the
776     // kill flags to account for that and make RegPair.Reg reaches
777     // the new PHI.
778     MRI.clearKillFlags(RegPair.Reg);
779     MBBOpIdx += 2;
780   }
781 
782   return *MIB;
783 }
784 
785 namespace {
786 
787 /// Interface to query instructions amenable to copy rewriting.
788 class Rewriter {
789 protected:
790   MachineInstr &CopyLike;
791   unsigned CurrentSrcIdx = 0;   ///< The index of the source being rewritten.
792 public:
793   Rewriter(MachineInstr &CopyLike) : CopyLike(CopyLike) {}
794   virtual ~Rewriter() {}
795 
796   /// Get the next rewritable source (SrcReg, SrcSubReg) and
797   /// the related value that it affects (DstReg, DstSubReg).
798   /// A source is considered rewritable if its register class and the
799   /// register class of the related DstReg may not be register
800   /// coalescer friendly. In other words, given a copy-like instruction
801   /// not all the arguments may be returned at rewritable source, since
802   /// some arguments are none to be register coalescer friendly.
803   ///
804   /// Each call of this method moves the current source to the next
805   /// rewritable source.
806   /// For instance, let CopyLike be the instruction to rewrite.
807   /// CopyLike has one definition and one source:
808   /// dst.dstSubIdx = CopyLike src.srcSubIdx.
809   ///
810   /// The first call will give the first rewritable source, i.e.,
811   /// the only source this instruction has:
812   /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
813   /// This source defines the whole definition, i.e.,
814   /// (DstReg, DstSubReg) = (dst, dstSubIdx).
815   ///
816   /// The second and subsequent calls will return false, as there is only one
817   /// rewritable source.
818   ///
819   /// \return True if a rewritable source has been found, false otherwise.
820   /// The output arguments are valid if and only if true is returned.
821   virtual bool getNextRewritableSource(RegSubRegPair &Src,
822                                        RegSubRegPair &Dst) = 0;
823 
824   /// Rewrite the current source with \p NewReg and \p NewSubReg if possible.
825   /// \return True if the rewriting was possible, false otherwise.
826   virtual bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) = 0;
827 };
828 
829 /// Rewriter for COPY instructions.
830 class CopyRewriter : public Rewriter {
831 public:
832   CopyRewriter(MachineInstr &MI) : Rewriter(MI) {
833     assert(MI.isCopy() && "Expected copy instruction");
834   }
835   virtual ~CopyRewriter() = default;
836 
837   bool getNextRewritableSource(RegSubRegPair &Src,
838                                RegSubRegPair &Dst) override {
839     // CurrentSrcIdx > 0 means this function has already been called.
840     if (CurrentSrcIdx > 0)
841       return false;
842     // This is the first call to getNextRewritableSource.
843     // Move the CurrentSrcIdx to remember that we made that call.
844     CurrentSrcIdx = 1;
845     // The rewritable source is the argument.
846     const MachineOperand &MOSrc = CopyLike.getOperand(1);
847     Src = RegSubRegPair(MOSrc.getReg(), MOSrc.getSubReg());
848     // What we track are the alternative sources of the definition.
849     const MachineOperand &MODef = CopyLike.getOperand(0);
850     Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
851     return true;
852   }
853 
854   bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
855     if (CurrentSrcIdx != 1)
856       return false;
857     MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
858     MOSrc.setReg(NewReg);
859     MOSrc.setSubReg(NewSubReg);
860     return true;
861   }
862 };
863 
864 /// Helper class to rewrite uncoalescable copy like instructions
865 /// into new COPY (coalescable friendly) instructions.
866 class UncoalescableRewriter : public Rewriter {
867   unsigned NumDefs;  ///< Number of defs in the bitcast.
868 
869 public:
870   UncoalescableRewriter(MachineInstr &MI) : Rewriter(MI) {
871     NumDefs = MI.getDesc().getNumDefs();
872   }
873 
874   /// \see See Rewriter::getNextRewritableSource()
875   /// All such sources need to be considered rewritable in order to
876   /// rewrite a uncoalescable copy-like instruction. This method return
877   /// each definition that must be checked if rewritable.
878   bool getNextRewritableSource(RegSubRegPair &Src,
879                                RegSubRegPair &Dst) override {
880     // Find the next non-dead definition and continue from there.
881     if (CurrentSrcIdx == NumDefs)
882       return false;
883 
884     while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
885       ++CurrentSrcIdx;
886       if (CurrentSrcIdx == NumDefs)
887         return false;
888     }
889 
890     // What we track are the alternative sources of the definition.
891     Src = RegSubRegPair(0, 0);
892     const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx);
893     Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
894 
895     CurrentSrcIdx++;
896     return true;
897   }
898 
899   bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
900     return false;
901   }
902 };
903 
904 /// Specialized rewriter for INSERT_SUBREG instruction.
905 class InsertSubregRewriter : public Rewriter {
906 public:
907   InsertSubregRewriter(MachineInstr &MI) : Rewriter(MI) {
908     assert(MI.isInsertSubreg() && "Invalid instruction");
909   }
910 
911   /// \see See Rewriter::getNextRewritableSource()
912   /// Here CopyLike has the following form:
913   /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
914   /// Src1 has the same register class has dst, hence, there is
915   /// nothing to rewrite.
916   /// Src2.src2SubIdx, may not be register coalescer friendly.
917   /// Therefore, the first call to this method returns:
918   /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
919   /// (DstReg, DstSubReg) = (dst, subIdx).
920   ///
921   /// Subsequence calls will return false.
922   bool getNextRewritableSource(RegSubRegPair &Src,
923                                RegSubRegPair &Dst) override {
924     // If we already get the only source we can rewrite, return false.
925     if (CurrentSrcIdx == 2)
926       return false;
927     // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
928     CurrentSrcIdx = 2;
929     const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
930     Src = RegSubRegPair(MOInsertedReg.getReg(), MOInsertedReg.getSubReg());
931     const MachineOperand &MODef = CopyLike.getOperand(0);
932 
933     // We want to track something that is compatible with the
934     // partial definition.
935     if (MODef.getSubReg())
936       // Bail if we have to compose sub-register indices.
937       return false;
938     Dst = RegSubRegPair(MODef.getReg(),
939                         (unsigned)CopyLike.getOperand(3).getImm());
940     return true;
941   }
942 
943   bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
944     if (CurrentSrcIdx != 2)
945       return false;
946     // We are rewriting the inserted reg.
947     MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
948     MO.setReg(NewReg);
949     MO.setSubReg(NewSubReg);
950     return true;
951   }
952 };
953 
954 /// Specialized rewriter for EXTRACT_SUBREG instruction.
955 class ExtractSubregRewriter : public Rewriter {
956   const TargetInstrInfo &TII;
957 
958 public:
959   ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
960       : Rewriter(MI), TII(TII) {
961     assert(MI.isExtractSubreg() && "Invalid instruction");
962   }
963 
964   /// \see Rewriter::getNextRewritableSource()
965   /// Here CopyLike has the following form:
966   /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
967   /// There is only one rewritable source: Src.subIdx,
968   /// which defines dst.dstSubIdx.
969   bool getNextRewritableSource(RegSubRegPair &Src,
970                                RegSubRegPair &Dst) override {
971     // If we already get the only source we can rewrite, return false.
972     if (CurrentSrcIdx == 1)
973       return false;
974     // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
975     CurrentSrcIdx = 1;
976     const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
977     // If we have to compose sub-register indices, bail out.
978     if (MOExtractedReg.getSubReg())
979       return false;
980 
981     Src = RegSubRegPair(MOExtractedReg.getReg(),
982                         CopyLike.getOperand(2).getImm());
983 
984     // We want to track something that is compatible with the definition.
985     const MachineOperand &MODef = CopyLike.getOperand(0);
986     Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
987     return true;
988   }
989 
990   bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
991     // The only source we can rewrite is the input register.
992     if (CurrentSrcIdx != 1)
993       return false;
994 
995     CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
996 
997     // If we find a source that does not require to extract something,
998     // rewrite the operation with a copy.
999     if (!NewSubReg) {
1000       // Move the current index to an invalid position.
1001       // We do not want another call to this method to be able
1002       // to do any change.
1003       CurrentSrcIdx = -1;
1004       // Rewrite the operation as a COPY.
1005       // Get rid of the sub-register index.
1006       CopyLike.RemoveOperand(2);
1007       // Morph the operation into a COPY.
1008       CopyLike.setDesc(TII.get(TargetOpcode::COPY));
1009       return true;
1010     }
1011     CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
1012     return true;
1013   }
1014 };
1015 
1016 /// Specialized rewriter for REG_SEQUENCE instruction.
1017 class RegSequenceRewriter : public Rewriter {
1018 public:
1019   RegSequenceRewriter(MachineInstr &MI) : Rewriter(MI) {
1020     assert(MI.isRegSequence() && "Invalid instruction");
1021   }
1022 
1023   /// \see Rewriter::getNextRewritableSource()
1024   /// Here CopyLike has the following form:
1025   /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
1026   /// Each call will return a different source, walking all the available
1027   /// source.
1028   ///
1029   /// The first call returns:
1030   /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
1031   /// (DstReg, DstSubReg) = (dst, subIdx1).
1032   ///
1033   /// The second call returns:
1034   /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
1035   /// (DstReg, DstSubReg) = (dst, subIdx2).
1036   ///
1037   /// And so on, until all the sources have been traversed, then
1038   /// it returns false.
1039   bool getNextRewritableSource(RegSubRegPair &Src,
1040                                RegSubRegPair &Dst) override {
1041     // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
1042 
1043     // If this is the first call, move to the first argument.
1044     if (CurrentSrcIdx == 0) {
1045       CurrentSrcIdx = 1;
1046     } else {
1047       // Otherwise, move to the next argument and check that it is valid.
1048       CurrentSrcIdx += 2;
1049       if (CurrentSrcIdx >= CopyLike.getNumOperands())
1050         return false;
1051     }
1052     const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
1053     Src.Reg = MOInsertedReg.getReg();
1054     // If we have to compose sub-register indices, bail out.
1055     if ((Src.SubReg = MOInsertedReg.getSubReg()))
1056       return false;
1057 
1058     // We want to track something that is compatible with the related
1059     // partial definition.
1060     Dst.SubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
1061 
1062     const MachineOperand &MODef = CopyLike.getOperand(0);
1063     Dst.Reg = MODef.getReg();
1064     // If we have to compose sub-registers, bail.
1065     return MODef.getSubReg() == 0;
1066   }
1067 
1068   bool RewriteCurrentSource(unsigned NewReg, unsigned NewSubReg) override {
1069     // We cannot rewrite out of bound operands.
1070     // Moreover, rewritable sources are at odd positions.
1071     if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
1072       return false;
1073 
1074     MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
1075     MO.setReg(NewReg);
1076     MO.setSubReg(NewSubReg);
1077     return true;
1078   }
1079 };
1080 
1081 } // end anonymous namespace
1082 
1083 /// Get the appropriated Rewriter for \p MI.
1084 /// \return A pointer to a dynamically allocated Rewriter or nullptr if no
1085 /// rewriter works for \p MI.
1086 static Rewriter *getCopyRewriter(MachineInstr &MI, const TargetInstrInfo &TII) {
1087   // Handle uncoalescable copy-like instructions.
1088   if (MI.isBitcast() || MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
1089       MI.isExtractSubregLike())
1090     return new UncoalescableRewriter(MI);
1091 
1092   switch (MI.getOpcode()) {
1093   default:
1094     return nullptr;
1095   case TargetOpcode::COPY:
1096     return new CopyRewriter(MI);
1097   case TargetOpcode::INSERT_SUBREG:
1098     return new InsertSubregRewriter(MI);
1099   case TargetOpcode::EXTRACT_SUBREG:
1100     return new ExtractSubregRewriter(MI, TII);
1101   case TargetOpcode::REG_SEQUENCE:
1102     return new RegSequenceRewriter(MI);
1103   }
1104 }
1105 
1106 /// Given a \p Def.Reg and Def.SubReg  pair, use \p RewriteMap to find
1107 /// the new source to use for rewrite. If \p HandleMultipleSources is true and
1108 /// multiple sources for a given \p Def are found along the way, we found a
1109 /// PHI instructions that needs to be rewritten.
1110 /// TODO: HandleMultipleSources should be removed once we test PHI handling
1111 /// with coalescable copies.
1112 static RegSubRegPair
1113 getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
1114              RegSubRegPair Def,
1115              const PeepholeOptimizer::RewriteMapTy &RewriteMap,
1116              bool HandleMultipleSources = true) {
1117   RegSubRegPair LookupSrc(Def.Reg, Def.SubReg);
1118   while (true) {
1119     ValueTrackerResult Res = RewriteMap.lookup(LookupSrc);
1120     // If there are no entries on the map, LookupSrc is the new source.
1121     if (!Res.isValid())
1122       return LookupSrc;
1123 
1124     // There's only one source for this definition, keep searching...
1125     unsigned NumSrcs = Res.getNumSources();
1126     if (NumSrcs == 1) {
1127       LookupSrc.Reg = Res.getSrcReg(0);
1128       LookupSrc.SubReg = Res.getSrcSubReg(0);
1129       continue;
1130     }
1131 
1132     // TODO: Remove once multiple srcs w/ coalescable copies are supported.
1133     if (!HandleMultipleSources)
1134       break;
1135 
1136     // Multiple sources, recurse into each source to find a new source
1137     // for it. Then, rewrite the PHI accordingly to its new edges.
1138     SmallVector<RegSubRegPair, 4> NewPHISrcs;
1139     for (unsigned i = 0; i < NumSrcs; ++i) {
1140       RegSubRegPair PHISrc(Res.getSrcReg(i), Res.getSrcSubReg(i));
1141       NewPHISrcs.push_back(
1142           getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources));
1143     }
1144 
1145     // Build the new PHI node and return its def register as the new source.
1146     MachineInstr &OrigPHI = const_cast<MachineInstr &>(*Res.getInst());
1147     MachineInstr &NewPHI = insertPHI(*MRI, *TII, NewPHISrcs, OrigPHI);
1148     LLVM_DEBUG(dbgs() << "-- getNewSource\n");
1149     LLVM_DEBUG(dbgs() << "   Replacing: " << OrigPHI);
1150     LLVM_DEBUG(dbgs() << "        With: " << NewPHI);
1151     const MachineOperand &MODef = NewPHI.getOperand(0);
1152     return RegSubRegPair(MODef.getReg(), MODef.getSubReg());
1153   }
1154 
1155   return RegSubRegPair(0, 0);
1156 }
1157 
1158 /// Optimize generic copy instructions to avoid cross register bank copy.
1159 /// The optimization looks through a chain of copies and tries to find a source
1160 /// that has a compatible register class.
1161 /// Two register classes are considered to be compatible if they share the same
1162 /// register bank.
1163 /// New copies issued by this optimization are register allocator
1164 /// friendly. This optimization does not remove any copy as it may
1165 /// overconstrain the register allocator, but replaces some operands
1166 /// when possible.
1167 /// \pre isCoalescableCopy(*MI) is true.
1168 /// \return True, when \p MI has been rewritten. False otherwise.
1169 bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr &MI) {
1170   assert(isCoalescableCopy(MI) && "Invalid argument");
1171   assert(MI.getDesc().getNumDefs() == 1 &&
1172          "Coalescer can understand multiple defs?!");
1173   const MachineOperand &MODef = MI.getOperand(0);
1174   // Do not rewrite physical definitions.
1175   if (Register::isPhysicalRegister(MODef.getReg()))
1176     return false;
1177 
1178   bool Changed = false;
1179   // Get the right rewriter for the current copy.
1180   std::unique_ptr<Rewriter> CpyRewriter(getCopyRewriter(MI, *TII));
1181   // If none exists, bail out.
1182   if (!CpyRewriter)
1183     return false;
1184   // Rewrite each rewritable source.
1185   RegSubRegPair Src;
1186   RegSubRegPair TrackPair;
1187   while (CpyRewriter->getNextRewritableSource(Src, TrackPair)) {
1188     // Keep track of PHI nodes and its incoming edges when looking for sources.
1189     RewriteMapTy RewriteMap;
1190     // Try to find a more suitable source. If we failed to do so, or get the
1191     // actual source, move to the next source.
1192     if (!findNextSource(TrackPair, RewriteMap))
1193       continue;
1194 
1195     // Get the new source to rewrite. TODO: Only enable handling of multiple
1196     // sources (PHIs) once we have a motivating example and testcases for it.
1197     RegSubRegPair NewSrc = getNewSource(MRI, TII, TrackPair, RewriteMap,
1198                                         /*HandleMultipleSources=*/false);
1199     if (Src.Reg == NewSrc.Reg || NewSrc.Reg == 0)
1200       continue;
1201 
1202     // Rewrite source.
1203     if (CpyRewriter->RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg)) {
1204       // We may have extended the live-range of NewSrc, account for that.
1205       MRI->clearKillFlags(NewSrc.Reg);
1206       Changed = true;
1207     }
1208   }
1209   // TODO: We could have a clean-up method to tidy the instruction.
1210   // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
1211   // => v0 = COPY v1
1212   // Currently we haven't seen motivating example for that and we
1213   // want to avoid untested code.
1214   NumRewrittenCopies += Changed;
1215   return Changed;
1216 }
1217 
1218 /// Rewrite the source found through \p Def, by using the \p RewriteMap
1219 /// and create a new COPY instruction. More info about RewriteMap in
1220 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
1221 /// Uncoalescable copies, since they are copy like instructions that aren't
1222 /// recognized by the register allocator.
1223 MachineInstr &
1224 PeepholeOptimizer::rewriteSource(MachineInstr &CopyLike,
1225                                  RegSubRegPair Def, RewriteMapTy &RewriteMap) {
1226   assert(!Register::isPhysicalRegister(Def.Reg) &&
1227          "We do not rewrite physical registers");
1228 
1229   // Find the new source to use in the COPY rewrite.
1230   RegSubRegPair NewSrc = getNewSource(MRI, TII, Def, RewriteMap);
1231 
1232   // Insert the COPY.
1233   const TargetRegisterClass *DefRC = MRI->getRegClass(Def.Reg);
1234   Register NewVReg = MRI->createVirtualRegister(DefRC);
1235 
1236   MachineInstr *NewCopy =
1237       BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
1238               TII->get(TargetOpcode::COPY), NewVReg)
1239           .addReg(NewSrc.Reg, 0, NewSrc.SubReg);
1240 
1241   if (Def.SubReg) {
1242     NewCopy->getOperand(0).setSubReg(Def.SubReg);
1243     NewCopy->getOperand(0).setIsUndef();
1244   }
1245 
1246   LLVM_DEBUG(dbgs() << "-- RewriteSource\n");
1247   LLVM_DEBUG(dbgs() << "   Replacing: " << CopyLike);
1248   LLVM_DEBUG(dbgs() << "        With: " << *NewCopy);
1249   MRI->replaceRegWith(Def.Reg, NewVReg);
1250   MRI->clearKillFlags(NewVReg);
1251 
1252   // We extended the lifetime of NewSrc.Reg, clear the kill flags to
1253   // account for that.
1254   MRI->clearKillFlags(NewSrc.Reg);
1255 
1256   return *NewCopy;
1257 }
1258 
1259 /// Optimize copy-like instructions to create
1260 /// register coalescer friendly instruction.
1261 /// The optimization tries to kill-off the \p MI by looking
1262 /// through a chain of copies to find a source that has a compatible
1263 /// register class.
1264 /// If such a source is found, it replace \p MI by a generic COPY
1265 /// operation.
1266 /// \pre isUncoalescableCopy(*MI) is true.
1267 /// \return True, when \p MI has been optimized. In that case, \p MI has
1268 /// been removed from its parent.
1269 /// All COPY instructions created, are inserted in \p LocalMIs.
1270 bool PeepholeOptimizer::optimizeUncoalescableCopy(
1271     MachineInstr &MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
1272   assert(isUncoalescableCopy(MI) && "Invalid argument");
1273   UncoalescableRewriter CpyRewriter(MI);
1274 
1275   // Rewrite each rewritable source by generating new COPYs. This works
1276   // differently from optimizeCoalescableCopy since it first makes sure that all
1277   // definitions can be rewritten.
1278   RewriteMapTy RewriteMap;
1279   RegSubRegPair Src;
1280   RegSubRegPair Def;
1281   SmallVector<RegSubRegPair, 4> RewritePairs;
1282   while (CpyRewriter.getNextRewritableSource(Src, Def)) {
1283     // If a physical register is here, this is probably for a good reason.
1284     // Do not rewrite that.
1285     if (Register::isPhysicalRegister(Def.Reg))
1286       return false;
1287 
1288     // If we do not know how to rewrite this definition, there is no point
1289     // in trying to kill this instruction.
1290     if (!findNextSource(Def, RewriteMap))
1291       return false;
1292 
1293     RewritePairs.push_back(Def);
1294   }
1295 
1296   // The change is possible for all defs, do it.
1297   for (const RegSubRegPair &Def : RewritePairs) {
1298     // Rewrite the "copy" in a way the register coalescer understands.
1299     MachineInstr &NewCopy = rewriteSource(MI, Def, RewriteMap);
1300     LocalMIs.insert(&NewCopy);
1301   }
1302 
1303   // MI is now dead.
1304   LLVM_DEBUG(dbgs() << "Deleting uncoalescable copy: " << MI);
1305   MI.eraseFromParent();
1306   ++NumUncoalescableCopies;
1307   return true;
1308 }
1309 
1310 /// Check whether MI is a candidate for folding into a later instruction.
1311 /// We only fold loads to virtual registers and the virtual register defined
1312 /// has a single user.
1313 bool PeepholeOptimizer::isLoadFoldable(
1314     MachineInstr &MI, SmallSet<unsigned, 16> &FoldAsLoadDefCandidates) {
1315   if (!MI.canFoldAsLoad() || !MI.mayLoad())
1316     return false;
1317   const MCInstrDesc &MCID = MI.getDesc();
1318   if (MCID.getNumDefs() != 1)
1319     return false;
1320 
1321   Register Reg = MI.getOperand(0).getReg();
1322   // To reduce compilation time, we check MRI->hasOneNonDBGUser when inserting
1323   // loads. It should be checked when processing uses of the load, since
1324   // uses can be removed during peephole.
1325   if (!MI.getOperand(0).getSubReg() && Register::isVirtualRegister(Reg) &&
1326       MRI->hasOneNonDBGUser(Reg)) {
1327     FoldAsLoadDefCandidates.insert(Reg);
1328     return true;
1329   }
1330   return false;
1331 }
1332 
1333 bool PeepholeOptimizer::isMoveImmediate(
1334     MachineInstr &MI, SmallSet<unsigned, 4> &ImmDefRegs,
1335     DenseMap<unsigned, MachineInstr *> &ImmDefMIs) {
1336   const MCInstrDesc &MCID = MI.getDesc();
1337   if (!MI.isMoveImmediate())
1338     return false;
1339   if (MCID.getNumDefs() != 1)
1340     return false;
1341   Register Reg = MI.getOperand(0).getReg();
1342   if (Register::isVirtualRegister(Reg)) {
1343     ImmDefMIs.insert(std::make_pair(Reg, &MI));
1344     ImmDefRegs.insert(Reg);
1345     return true;
1346   }
1347 
1348   return false;
1349 }
1350 
1351 /// Try folding register operands that are defined by move immediate
1352 /// instructions, i.e. a trivial constant folding optimization, if
1353 /// and only if the def and use are in the same BB.
1354 bool PeepholeOptimizer::foldImmediate(MachineInstr &MI,
1355     SmallSet<unsigned, 4> &ImmDefRegs,
1356     DenseMap<unsigned, MachineInstr *> &ImmDefMIs) {
1357   for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1358     MachineOperand &MO = MI.getOperand(i);
1359     if (!MO.isReg() || MO.isDef())
1360       continue;
1361     // Ignore dead implicit defs.
1362     if (MO.isImplicit() && MO.isDead())
1363       continue;
1364     Register Reg = MO.getReg();
1365     if (!Register::isVirtualRegister(Reg))
1366       continue;
1367     if (ImmDefRegs.count(Reg) == 0)
1368       continue;
1369     DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
1370     assert(II != ImmDefMIs.end() && "couldn't find immediate definition");
1371     if (TII->FoldImmediate(MI, *II->second, Reg, MRI)) {
1372       ++NumImmFold;
1373       return true;
1374     }
1375   }
1376   return false;
1377 }
1378 
1379 // FIXME: This is very simple and misses some cases which should be handled when
1380 // motivating examples are found.
1381 //
1382 // The copy rewriting logic should look at uses as well as defs and be able to
1383 // eliminate copies across blocks.
1384 //
1385 // Later copies that are subregister extracts will also not be eliminated since
1386 // only the first copy is considered.
1387 //
1388 // e.g.
1389 // %1 = COPY %0
1390 // %2 = COPY %0:sub1
1391 //
1392 // Should replace %2 uses with %1:sub1
1393 bool PeepholeOptimizer::foldRedundantCopy(MachineInstr &MI,
1394     SmallSet<unsigned, 4> &CopySrcRegs,
1395     DenseMap<unsigned, MachineInstr *> &CopyMIs) {
1396   assert(MI.isCopy() && "expected a COPY machine instruction");
1397 
1398   Register SrcReg = MI.getOperand(1).getReg();
1399   if (!Register::isVirtualRegister(SrcReg))
1400     return false;
1401 
1402   Register DstReg = MI.getOperand(0).getReg();
1403   if (!Register::isVirtualRegister(DstReg))
1404     return false;
1405 
1406   if (CopySrcRegs.insert(SrcReg).second) {
1407     // First copy of this reg seen.
1408     CopyMIs.insert(std::make_pair(SrcReg, &MI));
1409     return false;
1410   }
1411 
1412   MachineInstr *PrevCopy = CopyMIs.find(SrcReg)->second;
1413 
1414   unsigned SrcSubReg = MI.getOperand(1).getSubReg();
1415   unsigned PrevSrcSubReg = PrevCopy->getOperand(1).getSubReg();
1416 
1417   // Can't replace different subregister extracts.
1418   if (SrcSubReg != PrevSrcSubReg)
1419     return false;
1420 
1421   Register PrevDstReg = PrevCopy->getOperand(0).getReg();
1422 
1423   // Only replace if the copy register class is the same.
1424   //
1425   // TODO: If we have multiple copies to different register classes, we may want
1426   // to track multiple copies of the same source register.
1427   if (MRI->getRegClass(DstReg) != MRI->getRegClass(PrevDstReg))
1428     return false;
1429 
1430   MRI->replaceRegWith(DstReg, PrevDstReg);
1431 
1432   // Lifetime of the previous copy has been extended.
1433   MRI->clearKillFlags(PrevDstReg);
1434   return true;
1435 }
1436 
1437 bool PeepholeOptimizer::isNAPhysCopy(unsigned Reg) {
1438   return Register::isPhysicalRegister(Reg) && !MRI->isAllocatable(Reg);
1439 }
1440 
1441 bool PeepholeOptimizer::foldRedundantNAPhysCopy(
1442     MachineInstr &MI, DenseMap<unsigned, MachineInstr *> &NAPhysToVirtMIs) {
1443   assert(MI.isCopy() && "expected a COPY machine instruction");
1444 
1445   if (DisableNAPhysCopyOpt)
1446     return false;
1447 
1448   Register DstReg = MI.getOperand(0).getReg();
1449   Register SrcReg = MI.getOperand(1).getReg();
1450   if (isNAPhysCopy(SrcReg) && Register::isVirtualRegister(DstReg)) {
1451     // %vreg = COPY %physreg
1452     // Avoid using a datastructure which can track multiple live non-allocatable
1453     // phys->virt copies since LLVM doesn't seem to do this.
1454     NAPhysToVirtMIs.insert({SrcReg, &MI});
1455     return false;
1456   }
1457 
1458   if (!(Register::isVirtualRegister(SrcReg) && isNAPhysCopy(DstReg)))
1459     return false;
1460 
1461   // %physreg = COPY %vreg
1462   auto PrevCopy = NAPhysToVirtMIs.find(DstReg);
1463   if (PrevCopy == NAPhysToVirtMIs.end()) {
1464     // We can't remove the copy: there was an intervening clobber of the
1465     // non-allocatable physical register after the copy to virtual.
1466     LLVM_DEBUG(dbgs() << "NAPhysCopy: intervening clobber forbids erasing "
1467                       << MI);
1468     return false;
1469   }
1470 
1471   Register PrevDstReg = PrevCopy->second->getOperand(0).getReg();
1472   if (PrevDstReg == SrcReg) {
1473     // Remove the virt->phys copy: we saw the virtual register definition, and
1474     // the non-allocatable physical register's state hasn't changed since then.
1475     LLVM_DEBUG(dbgs() << "NAPhysCopy: erasing " << MI);
1476     ++NumNAPhysCopies;
1477     return true;
1478   }
1479 
1480   // Potential missed optimization opportunity: we saw a different virtual
1481   // register get a copy of the non-allocatable physical register, and we only
1482   // track one such copy. Avoid getting confused by this new non-allocatable
1483   // physical register definition, and remove it from the tracked copies.
1484   LLVM_DEBUG(dbgs() << "NAPhysCopy: missed opportunity " << MI);
1485   NAPhysToVirtMIs.erase(PrevCopy);
1486   return false;
1487 }
1488 
1489 /// \bried Returns true if \p MO is a virtual register operand.
1490 static bool isVirtualRegisterOperand(MachineOperand &MO) {
1491   if (!MO.isReg())
1492     return false;
1493   return Register::isVirtualRegister(MO.getReg());
1494 }
1495 
1496 bool PeepholeOptimizer::findTargetRecurrence(
1497     unsigned Reg, const SmallSet<unsigned, 2> &TargetRegs,
1498     RecurrenceCycle &RC) {
1499   // Recurrence found if Reg is in TargetRegs.
1500   if (TargetRegs.count(Reg))
1501     return true;
1502 
1503   // TODO: Curerntly, we only allow the last instruction of the recurrence
1504   // cycle (the instruction that feeds the PHI instruction) to have more than
1505   // one uses to guarantee that commuting operands does not tie registers
1506   // with overlapping live range. Once we have actual live range info of
1507   // each register, this constraint can be relaxed.
1508   if (!MRI->hasOneNonDBGUse(Reg))
1509     return false;
1510 
1511   // Give up if the reccurrence chain length is longer than the limit.
1512   if (RC.size() >= MaxRecurrenceChain)
1513     return false;
1514 
1515   MachineInstr &MI = *(MRI->use_instr_nodbg_begin(Reg));
1516   unsigned Idx = MI.findRegisterUseOperandIdx(Reg);
1517 
1518   // Only interested in recurrences whose instructions have only one def, which
1519   // is a virtual register.
1520   if (MI.getDesc().getNumDefs() != 1)
1521     return false;
1522 
1523   MachineOperand &DefOp = MI.getOperand(0);
1524   if (!isVirtualRegisterOperand(DefOp))
1525     return false;
1526 
1527   // Check if def operand of MI is tied to any use operand. We are only
1528   // interested in the case that all the instructions in the recurrence chain
1529   // have there def operand tied with one of the use operand.
1530   unsigned TiedUseIdx;
1531   if (!MI.isRegTiedToUseOperand(0, &TiedUseIdx))
1532     return false;
1533 
1534   if (Idx == TiedUseIdx) {
1535     RC.push_back(RecurrenceInstr(&MI));
1536     return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC);
1537   } else {
1538     // If Idx is not TiedUseIdx, check if Idx is commutable with TiedUseIdx.
1539     unsigned CommIdx = TargetInstrInfo::CommuteAnyOperandIndex;
1540     if (TII->findCommutedOpIndices(MI, Idx, CommIdx) && CommIdx == TiedUseIdx) {
1541       RC.push_back(RecurrenceInstr(&MI, Idx, CommIdx));
1542       return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC);
1543     }
1544   }
1545 
1546   return false;
1547 }
1548 
1549 /// Phi instructions will eventually be lowered to copy instructions.
1550 /// If phi is in a loop header, a recurrence may formulated around the source
1551 /// and destination of the phi. For such case commuting operands of the
1552 /// instructions in the recurrence may enable coalescing of the copy instruction
1553 /// generated from the phi. For example, if there is a recurrence of
1554 ///
1555 /// LoopHeader:
1556 ///   %1 = phi(%0, %100)
1557 /// LoopLatch:
1558 ///   %0<def, tied1> = ADD %2<def, tied0>, %1
1559 ///
1560 /// , the fact that %0 and %2 are in the same tied operands set makes
1561 /// the coalescing of copy instruction generated from the phi in
1562 /// LoopHeader(i.e. %1 = COPY %0) impossible, because %1 and
1563 /// %2 have overlapping live range. This introduces additional move
1564 /// instruction to the final assembly. However, if we commute %2 and
1565 /// %1 of ADD instruction, the redundant move instruction can be
1566 /// avoided.
1567 bool PeepholeOptimizer::optimizeRecurrence(MachineInstr &PHI) {
1568   SmallSet<unsigned, 2> TargetRegs;
1569   for (unsigned Idx = 1; Idx < PHI.getNumOperands(); Idx += 2) {
1570     MachineOperand &MO = PHI.getOperand(Idx);
1571     assert(isVirtualRegisterOperand(MO) && "Invalid PHI instruction");
1572     TargetRegs.insert(MO.getReg());
1573   }
1574 
1575   bool Changed = false;
1576   RecurrenceCycle RC;
1577   if (findTargetRecurrence(PHI.getOperand(0).getReg(), TargetRegs, RC)) {
1578     // Commutes operands of instructions in RC if necessary so that the copy to
1579     // be generated from PHI can be coalesced.
1580     LLVM_DEBUG(dbgs() << "Optimize recurrence chain from " << PHI);
1581     for (auto &RI : RC) {
1582       LLVM_DEBUG(dbgs() << "\tInst: " << *(RI.getMI()));
1583       auto CP = RI.getCommutePair();
1584       if (CP) {
1585         Changed = true;
1586         TII->commuteInstruction(*(RI.getMI()), false, (*CP).first,
1587                                 (*CP).second);
1588         LLVM_DEBUG(dbgs() << "\t\tCommuted: " << *(RI.getMI()));
1589       }
1590     }
1591   }
1592 
1593   return Changed;
1594 }
1595 
1596 bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
1597   if (skipFunction(MF.getFunction()))
1598     return false;
1599 
1600   LLVM_DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
1601   LLVM_DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
1602 
1603   if (DisablePeephole)
1604     return false;
1605 
1606   TII = MF.getSubtarget().getInstrInfo();
1607   TRI = MF.getSubtarget().getRegisterInfo();
1608   MRI = &MF.getRegInfo();
1609   DT  = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
1610   MLI = &getAnalysis<MachineLoopInfo>();
1611 
1612   bool Changed = false;
1613 
1614   for (MachineBasicBlock &MBB : MF) {
1615     bool SeenMoveImm = false;
1616 
1617     // During this forward scan, at some point it needs to answer the question
1618     // "given a pointer to an MI in the current BB, is it located before or
1619     // after the current instruction".
1620     // To perform this, the following set keeps track of the MIs already seen
1621     // during the scan, if a MI is not in the set, it is assumed to be located
1622     // after. Newly created MIs have to be inserted in the set as well.
1623     SmallPtrSet<MachineInstr*, 16> LocalMIs;
1624     SmallSet<unsigned, 4> ImmDefRegs;
1625     DenseMap<unsigned, MachineInstr*> ImmDefMIs;
1626     SmallSet<unsigned, 16> FoldAsLoadDefCandidates;
1627 
1628     // Track when a non-allocatable physical register is copied to a virtual
1629     // register so that useless moves can be removed.
1630     //
1631     // %physreg is the map index; MI is the last valid `%vreg = COPY %physreg`
1632     // without any intervening re-definition of %physreg.
1633     DenseMap<unsigned, MachineInstr *> NAPhysToVirtMIs;
1634 
1635     // Set of virtual registers that are copied from.
1636     SmallSet<unsigned, 4> CopySrcRegs;
1637     DenseMap<unsigned, MachineInstr *> CopySrcMIs;
1638 
1639     bool IsLoopHeader = MLI->isLoopHeader(&MBB);
1640 
1641     for (MachineBasicBlock::iterator MII = MBB.begin(), MIE = MBB.end();
1642          MII != MIE; ) {
1643       MachineInstr *MI = &*MII;
1644       // We may be erasing MI below, increment MII now.
1645       ++MII;
1646       LocalMIs.insert(MI);
1647 
1648       // Skip debug instructions. They should not affect this peephole optimization.
1649       if (MI->isDebugInstr())
1650           continue;
1651 
1652       if (MI->isPosition())
1653         continue;
1654 
1655       if (IsLoopHeader && MI->isPHI()) {
1656         if (optimizeRecurrence(*MI)) {
1657           Changed = true;
1658           continue;
1659         }
1660       }
1661 
1662       if (!MI->isCopy()) {
1663         for (const MachineOperand &MO : MI->operands()) {
1664           // Visit all operands: definitions can be implicit or explicit.
1665           if (MO.isReg()) {
1666             Register Reg = MO.getReg();
1667             if (MO.isDef() && isNAPhysCopy(Reg)) {
1668               const auto &Def = NAPhysToVirtMIs.find(Reg);
1669               if (Def != NAPhysToVirtMIs.end()) {
1670                 // A new definition of the non-allocatable physical register
1671                 // invalidates previous copies.
1672                 LLVM_DEBUG(dbgs()
1673                            << "NAPhysCopy: invalidating because of " << *MI);
1674                 NAPhysToVirtMIs.erase(Def);
1675               }
1676             }
1677           } else if (MO.isRegMask()) {
1678             const uint32_t *RegMask = MO.getRegMask();
1679             for (auto &RegMI : NAPhysToVirtMIs) {
1680               unsigned Def = RegMI.first;
1681               if (MachineOperand::clobbersPhysReg(RegMask, Def)) {
1682                 LLVM_DEBUG(dbgs()
1683                            << "NAPhysCopy: invalidating because of " << *MI);
1684                 NAPhysToVirtMIs.erase(Def);
1685               }
1686             }
1687           }
1688         }
1689       }
1690 
1691       if (MI->isImplicitDef() || MI->isKill())
1692         continue;
1693 
1694       if (MI->isInlineAsm() || MI->hasUnmodeledSideEffects()) {
1695         // Blow away all non-allocatable physical registers knowledge since we
1696         // don't know what's correct anymore.
1697         //
1698         // FIXME: handle explicit asm clobbers.
1699         LLVM_DEBUG(dbgs() << "NAPhysCopy: blowing away all info due to "
1700                           << *MI);
1701         NAPhysToVirtMIs.clear();
1702       }
1703 
1704       if ((isUncoalescableCopy(*MI) &&
1705            optimizeUncoalescableCopy(*MI, LocalMIs)) ||
1706           (MI->isCompare() && optimizeCmpInstr(*MI)) ||
1707           (MI->isSelect() && optimizeSelect(*MI, LocalMIs))) {
1708         // MI is deleted.
1709         LocalMIs.erase(MI);
1710         Changed = true;
1711         continue;
1712       }
1713 
1714       if (MI->isConditionalBranch() && optimizeCondBranch(*MI)) {
1715         Changed = true;
1716         continue;
1717       }
1718 
1719       if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(*MI)) {
1720         // MI is just rewritten.
1721         Changed = true;
1722         continue;
1723       }
1724 
1725       if (MI->isCopy() &&
1726           (foldRedundantCopy(*MI, CopySrcRegs, CopySrcMIs) ||
1727            foldRedundantNAPhysCopy(*MI, NAPhysToVirtMIs))) {
1728         LocalMIs.erase(MI);
1729         LLVM_DEBUG(dbgs() << "Deleting redundant copy: " << *MI << "\n");
1730         MI->eraseFromParent();
1731         Changed = true;
1732         continue;
1733       }
1734 
1735       if (isMoveImmediate(*MI, ImmDefRegs, ImmDefMIs)) {
1736         SeenMoveImm = true;
1737       } else {
1738         Changed |= optimizeExtInstr(*MI, MBB, LocalMIs);
1739         // optimizeExtInstr might have created new instructions after MI
1740         // and before the already incremented MII. Adjust MII so that the
1741         // next iteration sees the new instructions.
1742         MII = MI;
1743         ++MII;
1744         if (SeenMoveImm)
1745           Changed |= foldImmediate(*MI, ImmDefRegs, ImmDefMIs);
1746       }
1747 
1748       // Check whether MI is a load candidate for folding into a later
1749       // instruction. If MI is not a candidate, check whether we can fold an
1750       // earlier load into MI.
1751       if (!isLoadFoldable(*MI, FoldAsLoadDefCandidates) &&
1752           !FoldAsLoadDefCandidates.empty()) {
1753 
1754         // We visit each operand even after successfully folding a previous
1755         // one.  This allows us to fold multiple loads into a single
1756         // instruction.  We do assume that optimizeLoadInstr doesn't insert
1757         // foldable uses earlier in the argument list.  Since we don't restart
1758         // iteration, we'd miss such cases.
1759         const MCInstrDesc &MIDesc = MI->getDesc();
1760         for (unsigned i = MIDesc.getNumDefs(); i != MI->getNumOperands();
1761              ++i) {
1762           const MachineOperand &MOp = MI->getOperand(i);
1763           if (!MOp.isReg())
1764             continue;
1765           unsigned FoldAsLoadDefReg = MOp.getReg();
1766           if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
1767             // We need to fold load after optimizeCmpInstr, since
1768             // optimizeCmpInstr can enable folding by converting SUB to CMP.
1769             // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
1770             // we need it for markUsesInDebugValueAsUndef().
1771             unsigned FoldedReg = FoldAsLoadDefReg;
1772             MachineInstr *DefMI = nullptr;
1773             if (MachineInstr *FoldMI =
1774                     TII->optimizeLoadInstr(*MI, MRI, FoldAsLoadDefReg, DefMI)) {
1775               // Update LocalMIs since we replaced MI with FoldMI and deleted
1776               // DefMI.
1777               LLVM_DEBUG(dbgs() << "Replacing: " << *MI);
1778               LLVM_DEBUG(dbgs() << "     With: " << *FoldMI);
1779               LocalMIs.erase(MI);
1780               LocalMIs.erase(DefMI);
1781               LocalMIs.insert(FoldMI);
1782               // Update the call site info.
1783               if (MI->shouldUpdateCallSiteInfo())
1784                 MI->getMF()->moveCallSiteInfo(MI, FoldMI);
1785               MI->eraseFromParent();
1786               DefMI->eraseFromParent();
1787               MRI->markUsesInDebugValueAsUndef(FoldedReg);
1788               FoldAsLoadDefCandidates.erase(FoldedReg);
1789               ++NumLoadFold;
1790 
1791               // MI is replaced with FoldMI so we can continue trying to fold
1792               Changed = true;
1793               MI = FoldMI;
1794             }
1795           }
1796         }
1797       }
1798 
1799       // If we run into an instruction we can't fold across, discard
1800       // the load candidates.  Note: We might be able to fold *into* this
1801       // instruction, so this needs to be after the folding logic.
1802       if (MI->isLoadFoldBarrier()) {
1803         LLVM_DEBUG(dbgs() << "Encountered load fold barrier on " << *MI);
1804         FoldAsLoadDefCandidates.clear();
1805       }
1806     }
1807   }
1808 
1809   return Changed;
1810 }
1811 
1812 ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
1813   assert(Def->isCopy() && "Invalid definition");
1814   // Copy instruction are supposed to be: Def = Src.
1815   // If someone breaks this assumption, bad things will happen everywhere.
1816   // There may be implicit uses preventing the copy to be moved across
1817   // some target specific register definitions
1818   assert(Def->getNumOperands() - Def->getNumImplicitOperands() == 2 &&
1819          "Invalid number of operands");
1820   assert(!Def->hasImplicitDef() && "Only implicit uses are allowed");
1821 
1822   if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1823     // If we look for a different subreg, it means we want a subreg of src.
1824     // Bails as we do not support composing subregs yet.
1825     return ValueTrackerResult();
1826   // Otherwise, we want the whole source.
1827   const MachineOperand &Src = Def->getOperand(1);
1828   if (Src.isUndef())
1829     return ValueTrackerResult();
1830   return ValueTrackerResult(Src.getReg(), Src.getSubReg());
1831 }
1832 
1833 ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
1834   assert(Def->isBitcast() && "Invalid definition");
1835 
1836   // Bail if there are effects that a plain copy will not expose.
1837   if (Def->mayRaiseFPException() || Def->hasUnmodeledSideEffects())
1838     return ValueTrackerResult();
1839 
1840   // Bitcasts with more than one def are not supported.
1841   if (Def->getDesc().getNumDefs() != 1)
1842     return ValueTrackerResult();
1843   const MachineOperand DefOp = Def->getOperand(DefIdx);
1844   if (DefOp.getSubReg() != DefSubReg)
1845     // If we look for a different subreg, it means we want a subreg of the src.
1846     // Bails as we do not support composing subregs yet.
1847     return ValueTrackerResult();
1848 
1849   unsigned SrcIdx = Def->getNumOperands();
1850   for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1851        ++OpIdx) {
1852     const MachineOperand &MO = Def->getOperand(OpIdx);
1853     if (!MO.isReg() || !MO.getReg())
1854       continue;
1855     // Ignore dead implicit defs.
1856     if (MO.isImplicit() && MO.isDead())
1857       continue;
1858     assert(!MO.isDef() && "We should have skipped all the definitions by now");
1859     if (SrcIdx != EndOpIdx)
1860       // Multiple sources?
1861       return ValueTrackerResult();
1862     SrcIdx = OpIdx;
1863   }
1864 
1865   // In some rare case, Def has no input, SrcIdx is out of bound,
1866   // getOperand(SrcIdx) will fail below.
1867   if (SrcIdx >= Def->getNumOperands())
1868     return ValueTrackerResult();
1869 
1870   // Stop when any user of the bitcast is a SUBREG_TO_REG, replacing with a COPY
1871   // will break the assumed guarantees for the upper bits.
1872   for (const MachineInstr &UseMI : MRI.use_nodbg_instructions(DefOp.getReg())) {
1873     if (UseMI.isSubregToReg())
1874       return ValueTrackerResult();
1875   }
1876 
1877   const MachineOperand &Src = Def->getOperand(SrcIdx);
1878   if (Src.isUndef())
1879     return ValueTrackerResult();
1880   return ValueTrackerResult(Src.getReg(), Src.getSubReg());
1881 }
1882 
1883 ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
1884   assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1885          "Invalid definition");
1886 
1887   if (Def->getOperand(DefIdx).getSubReg())
1888     // If we are composing subregs, bail out.
1889     // The case we are checking is Def.<subreg> = REG_SEQUENCE.
1890     // This should almost never happen as the SSA property is tracked at
1891     // the register level (as opposed to the subreg level).
1892     // I.e.,
1893     // Def.sub0 =
1894     // Def.sub1 =
1895     // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
1896     // Def. Thus, it must not be generated.
1897     // However, some code could theoretically generates a single
1898     // Def.sub0 (i.e, not defining the other subregs) and we would
1899     // have this case.
1900     // If we can ascertain (or force) that this never happens, we could
1901     // turn that into an assertion.
1902     return ValueTrackerResult();
1903 
1904   if (!TII)
1905     // We could handle the REG_SEQUENCE here, but we do not want to
1906     // duplicate the code from the generic TII.
1907     return ValueTrackerResult();
1908 
1909   SmallVector<RegSubRegPairAndIdx, 8> RegSeqInputRegs;
1910   if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
1911     return ValueTrackerResult();
1912 
1913   // We are looking at:
1914   // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1915   // Check if one of the operand defines the subreg we are interested in.
1916   for (const RegSubRegPairAndIdx &RegSeqInput : RegSeqInputRegs) {
1917     if (RegSeqInput.SubIdx == DefSubReg)
1918       return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
1919   }
1920 
1921   // If the subreg we are tracking is super-defined by another subreg,
1922   // we could follow this value. However, this would require to compose
1923   // the subreg and we do not do that for now.
1924   return ValueTrackerResult();
1925 }
1926 
1927 ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
1928   assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
1929          "Invalid definition");
1930 
1931   if (Def->getOperand(DefIdx).getSubReg())
1932     // If we are composing subreg, bail out.
1933     // Same remark as getNextSourceFromRegSequence.
1934     // I.e., this may be turned into an assert.
1935     return ValueTrackerResult();
1936 
1937   if (!TII)
1938     // We could handle the REG_SEQUENCE here, but we do not want to
1939     // duplicate the code from the generic TII.
1940     return ValueTrackerResult();
1941 
1942   RegSubRegPair BaseReg;
1943   RegSubRegPairAndIdx InsertedReg;
1944   if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
1945     return ValueTrackerResult();
1946 
1947   // We are looking at:
1948   // Def = INSERT_SUBREG v0, v1, sub1
1949   // There are two cases:
1950   // 1. DefSubReg == sub1, get v1.
1951   // 2. DefSubReg != sub1, the value may be available through v0.
1952 
1953   // #1 Check if the inserted register matches the required sub index.
1954   if (InsertedReg.SubIdx == DefSubReg) {
1955     return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
1956   }
1957   // #2 Otherwise, if the sub register we are looking for is not partial
1958   // defined by the inserted element, we can look through the main
1959   // register (v0).
1960   const MachineOperand &MODef = Def->getOperand(DefIdx);
1961   // If the result register (Def) and the base register (v0) do not
1962   // have the same register class or if we have to compose
1963   // subregisters, bail out.
1964   if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
1965       BaseReg.SubReg)
1966     return ValueTrackerResult();
1967 
1968   // Get the TRI and check if the inserted sub-register overlaps with the
1969   // sub-register we are tracking.
1970   const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
1971   if (!TRI ||
1972       !(TRI->getSubRegIndexLaneMask(DefSubReg) &
1973         TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)).none())
1974     return ValueTrackerResult();
1975   // At this point, the value is available in v0 via the same subreg
1976   // we used for Def.
1977   return ValueTrackerResult(BaseReg.Reg, DefSubReg);
1978 }
1979 
1980 ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
1981   assert((Def->isExtractSubreg() ||
1982           Def->isExtractSubregLike()) && "Invalid definition");
1983   // We are looking at:
1984   // Def = EXTRACT_SUBREG v0, sub0
1985 
1986   // Bail if we have to compose sub registers.
1987   // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
1988   if (DefSubReg)
1989     return ValueTrackerResult();
1990 
1991   if (!TII)
1992     // We could handle the EXTRACT_SUBREG here, but we do not want to
1993     // duplicate the code from the generic TII.
1994     return ValueTrackerResult();
1995 
1996   RegSubRegPairAndIdx ExtractSubregInputReg;
1997   if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
1998     return ValueTrackerResult();
1999 
2000   // Bail if we have to compose sub registers.
2001   // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
2002   if (ExtractSubregInputReg.SubReg)
2003     return ValueTrackerResult();
2004   // Otherwise, the value is available in the v0.sub0.
2005   return ValueTrackerResult(ExtractSubregInputReg.Reg,
2006                             ExtractSubregInputReg.SubIdx);
2007 }
2008 
2009 ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
2010   assert(Def->isSubregToReg() && "Invalid definition");
2011   // We are looking at:
2012   // Def = SUBREG_TO_REG Imm, v0, sub0
2013 
2014   // Bail if we have to compose sub registers.
2015   // If DefSubReg != sub0, we would have to check that all the bits
2016   // we track are included in sub0 and if yes, we would have to
2017   // determine the right subreg in v0.
2018   if (DefSubReg != Def->getOperand(3).getImm())
2019     return ValueTrackerResult();
2020   // Bail if we have to compose sub registers.
2021   // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
2022   if (Def->getOperand(2).getSubReg())
2023     return ValueTrackerResult();
2024 
2025   return ValueTrackerResult(Def->getOperand(2).getReg(),
2026                             Def->getOperand(3).getImm());
2027 }
2028 
2029 /// Explore each PHI incoming operand and return its sources.
2030 ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
2031   assert(Def->isPHI() && "Invalid definition");
2032   ValueTrackerResult Res;
2033 
2034   // If we look for a different subreg, bail as we do not support composing
2035   // subregs yet.
2036   if (Def->getOperand(0).getSubReg() != DefSubReg)
2037     return ValueTrackerResult();
2038 
2039   // Return all register sources for PHI instructions.
2040   for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
2041     const MachineOperand &MO = Def->getOperand(i);
2042     assert(MO.isReg() && "Invalid PHI instruction");
2043     // We have no code to deal with undef operands. They shouldn't happen in
2044     // normal programs anyway.
2045     if (MO.isUndef())
2046       return ValueTrackerResult();
2047     Res.addSource(MO.getReg(), MO.getSubReg());
2048   }
2049 
2050   return Res;
2051 }
2052 
2053 ValueTrackerResult ValueTracker::getNextSourceImpl() {
2054   assert(Def && "This method needs a valid definition");
2055 
2056   assert(((Def->getOperand(DefIdx).isDef() &&
2057            (DefIdx < Def->getDesc().getNumDefs() ||
2058             Def->getDesc().isVariadic())) ||
2059           Def->getOperand(DefIdx).isImplicit()) &&
2060          "Invalid DefIdx");
2061   if (Def->isCopy())
2062     return getNextSourceFromCopy();
2063   if (Def->isBitcast())
2064     return getNextSourceFromBitcast();
2065   // All the remaining cases involve "complex" instructions.
2066   // Bail if we did not ask for the advanced tracking.
2067   if (DisableAdvCopyOpt)
2068     return ValueTrackerResult();
2069   if (Def->isRegSequence() || Def->isRegSequenceLike())
2070     return getNextSourceFromRegSequence();
2071   if (Def->isInsertSubreg() || Def->isInsertSubregLike())
2072     return getNextSourceFromInsertSubreg();
2073   if (Def->isExtractSubreg() || Def->isExtractSubregLike())
2074     return getNextSourceFromExtractSubreg();
2075   if (Def->isSubregToReg())
2076     return getNextSourceFromSubregToReg();
2077   if (Def->isPHI())
2078     return getNextSourceFromPHI();
2079   return ValueTrackerResult();
2080 }
2081 
2082 ValueTrackerResult ValueTracker::getNextSource() {
2083   // If we reach a point where we cannot move up in the use-def chain,
2084   // there is nothing we can get.
2085   if (!Def)
2086     return ValueTrackerResult();
2087 
2088   ValueTrackerResult Res = getNextSourceImpl();
2089   if (Res.isValid()) {
2090     // Update definition, definition index, and subregister for the
2091     // next call of getNextSource.
2092     // Update the current register.
2093     bool OneRegSrc = Res.getNumSources() == 1;
2094     if (OneRegSrc)
2095       Reg = Res.getSrcReg(0);
2096     // Update the result before moving up in the use-def chain
2097     // with the instruction containing the last found sources.
2098     Res.setInst(Def);
2099 
2100     // If we can still move up in the use-def chain, move to the next
2101     // definition.
2102     if (!Register::isPhysicalRegister(Reg) && OneRegSrc) {
2103       MachineRegisterInfo::def_iterator DI = MRI.def_begin(Reg);
2104       if (DI != MRI.def_end()) {
2105         Def = DI->getParent();
2106         DefIdx = DI.getOperandNo();
2107         DefSubReg = Res.getSrcSubReg(0);
2108       } else {
2109         Def = nullptr;
2110       }
2111       return Res;
2112     }
2113   }
2114   // If we end up here, this means we will not be able to find another source
2115   // for the next iteration. Make sure any new call to getNextSource bails out
2116   // early by cutting the use-def chain.
2117   Def = nullptr;
2118   return Res;
2119 }
2120