xref: /openbsd-src/gnu/llvm/llvm/lib/CodeGen/PeepholeOptimizer.cpp (revision d415bd752c734aee168c4ee86ff32e8cc249eb16)
109467b48Spatrick //===- PeepholeOptimizer.cpp - Peephole Optimizations ---------------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // Perform peephole optimizations on the machine code:
1009467b48Spatrick //
1109467b48Spatrick // - Optimize Extensions
1209467b48Spatrick //
1309467b48Spatrick //     Optimization of sign / zero extension instructions. It may be extended to
1409467b48Spatrick //     handle other instructions with similar properties.
1509467b48Spatrick //
1609467b48Spatrick //     On some targets, some instructions, e.g. X86 sign / zero extension, may
1709467b48Spatrick //     leave the source value in the lower part of the result. This optimization
1809467b48Spatrick //     will replace some uses of the pre-extension value with uses of the
1909467b48Spatrick //     sub-register of the results.
2009467b48Spatrick //
2109467b48Spatrick // - Optimize Comparisons
2209467b48Spatrick //
2309467b48Spatrick //     Optimization of comparison instructions. For instance, in this code:
2409467b48Spatrick //
2509467b48Spatrick //       sub r1, 1
2609467b48Spatrick //       cmp r1, 0
2709467b48Spatrick //       bz  L1
2809467b48Spatrick //
2909467b48Spatrick //     If the "sub" instruction all ready sets (or could be modified to set) the
3009467b48Spatrick //     same flag that the "cmp" instruction sets and that "bz" uses, then we can
3109467b48Spatrick //     eliminate the "cmp" instruction.
3209467b48Spatrick //
3309467b48Spatrick //     Another instance, in this code:
3409467b48Spatrick //
3509467b48Spatrick //       sub r1, r3 | sub r1, imm
3609467b48Spatrick //       cmp r3, r1 or cmp r1, r3 | cmp r1, imm
3709467b48Spatrick //       bge L1
3809467b48Spatrick //
3909467b48Spatrick //     If the branch instruction can use flag from "sub", then we can replace
4009467b48Spatrick //     "sub" with "subs" and eliminate the "cmp" instruction.
4109467b48Spatrick //
4209467b48Spatrick // - Optimize Loads:
4309467b48Spatrick //
4409467b48Spatrick //     Loads that can be folded into a later instruction. A load is foldable
4509467b48Spatrick //     if it loads to virtual registers and the virtual register defined has
4609467b48Spatrick //     a single use.
4709467b48Spatrick //
4809467b48Spatrick // - Optimize Copies and Bitcast (more generally, target specific copies):
4909467b48Spatrick //
5009467b48Spatrick //     Rewrite copies and bitcasts to avoid cross register bank copies
5109467b48Spatrick //     when possible.
5209467b48Spatrick //     E.g., Consider the following example, where capital and lower
5309467b48Spatrick //     letters denote different register file:
5409467b48Spatrick //     b = copy A <-- cross-bank copy
5509467b48Spatrick //     C = copy b <-- cross-bank copy
5609467b48Spatrick //   =>
5709467b48Spatrick //     b = copy A <-- cross-bank copy
5809467b48Spatrick //     C = copy A <-- same-bank copy
5909467b48Spatrick //
6009467b48Spatrick //     E.g., for bitcast:
6109467b48Spatrick //     b = bitcast A <-- cross-bank copy
6209467b48Spatrick //     C = bitcast b <-- cross-bank copy
6309467b48Spatrick //   =>
6409467b48Spatrick //     b = bitcast A <-- cross-bank copy
6509467b48Spatrick //     C = copy A    <-- same-bank copy
6609467b48Spatrick //===----------------------------------------------------------------------===//
6709467b48Spatrick 
6809467b48Spatrick #include "llvm/ADT/DenseMap.h"
6909467b48Spatrick #include "llvm/ADT/SmallPtrSet.h"
7009467b48Spatrick #include "llvm/ADT/SmallSet.h"
7109467b48Spatrick #include "llvm/ADT/SmallVector.h"
7209467b48Spatrick #include "llvm/ADT/Statistic.h"
7309467b48Spatrick #include "llvm/CodeGen/MachineBasicBlock.h"
7409467b48Spatrick #include "llvm/CodeGen/MachineDominators.h"
7509467b48Spatrick #include "llvm/CodeGen/MachineFunction.h"
7609467b48Spatrick #include "llvm/CodeGen/MachineFunctionPass.h"
7709467b48Spatrick #include "llvm/CodeGen/MachineInstr.h"
7809467b48Spatrick #include "llvm/CodeGen/MachineInstrBuilder.h"
7909467b48Spatrick #include "llvm/CodeGen/MachineLoopInfo.h"
8009467b48Spatrick #include "llvm/CodeGen/MachineOperand.h"
8109467b48Spatrick #include "llvm/CodeGen/MachineRegisterInfo.h"
8209467b48Spatrick #include "llvm/CodeGen/TargetInstrInfo.h"
8309467b48Spatrick #include "llvm/CodeGen/TargetOpcodes.h"
8409467b48Spatrick #include "llvm/CodeGen/TargetRegisterInfo.h"
8509467b48Spatrick #include "llvm/CodeGen/TargetSubtargetInfo.h"
8609467b48Spatrick #include "llvm/InitializePasses.h"
8709467b48Spatrick #include "llvm/MC/LaneBitmask.h"
8809467b48Spatrick #include "llvm/MC/MCInstrDesc.h"
8909467b48Spatrick #include "llvm/Pass.h"
9009467b48Spatrick #include "llvm/Support/CommandLine.h"
9109467b48Spatrick #include "llvm/Support/Debug.h"
9209467b48Spatrick #include "llvm/Support/raw_ostream.h"
9309467b48Spatrick #include <cassert>
9409467b48Spatrick #include <cstdint>
9509467b48Spatrick #include <memory>
9609467b48Spatrick #include <utility>
9709467b48Spatrick 
9809467b48Spatrick using namespace llvm;
9909467b48Spatrick using RegSubRegPair = TargetInstrInfo::RegSubRegPair;
10009467b48Spatrick using RegSubRegPairAndIdx = TargetInstrInfo::RegSubRegPairAndIdx;
10109467b48Spatrick 
10209467b48Spatrick #define DEBUG_TYPE "peephole-opt"
10309467b48Spatrick 
10409467b48Spatrick // Optimize Extensions
10509467b48Spatrick static cl::opt<bool>
10609467b48Spatrick Aggressive("aggressive-ext-opt", cl::Hidden,
10709467b48Spatrick            cl::desc("Aggressive extension optimization"));
10809467b48Spatrick 
10909467b48Spatrick static cl::opt<bool>
11009467b48Spatrick DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
11109467b48Spatrick                 cl::desc("Disable the peephole optimizer"));
11209467b48Spatrick 
11309467b48Spatrick /// Specifiy whether or not the value tracking looks through
11409467b48Spatrick /// complex instructions. When this is true, the value tracker
11509467b48Spatrick /// bails on everything that is not a copy or a bitcast.
11609467b48Spatrick static cl::opt<bool>
11709467b48Spatrick DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false),
11809467b48Spatrick                   cl::desc("Disable advanced copy optimization"));
11909467b48Spatrick 
12009467b48Spatrick static cl::opt<bool> DisableNAPhysCopyOpt(
12109467b48Spatrick     "disable-non-allocatable-phys-copy-opt", cl::Hidden, cl::init(false),
12209467b48Spatrick     cl::desc("Disable non-allocatable physical register copy optimization"));
12309467b48Spatrick 
12409467b48Spatrick // Limit the number of PHI instructions to process
12509467b48Spatrick // in PeepholeOptimizer::getNextSource.
12609467b48Spatrick static cl::opt<unsigned> RewritePHILimit(
12709467b48Spatrick     "rewrite-phi-limit", cl::Hidden, cl::init(10),
12809467b48Spatrick     cl::desc("Limit the length of PHI chains to lookup"));
12909467b48Spatrick 
13009467b48Spatrick // Limit the length of recurrence chain when evaluating the benefit of
13109467b48Spatrick // commuting operands.
13209467b48Spatrick static cl::opt<unsigned> MaxRecurrenceChain(
13309467b48Spatrick     "recurrence-chain-limit", cl::Hidden, cl::init(3),
13409467b48Spatrick     cl::desc("Maximum length of recurrence chain when evaluating the benefit "
13509467b48Spatrick              "of commuting operands"));
13609467b48Spatrick 
13709467b48Spatrick 
13809467b48Spatrick STATISTIC(NumReuse, "Number of extension results reused");
13909467b48Spatrick STATISTIC(NumCmps, "Number of compares eliminated");
14009467b48Spatrick STATISTIC(NumImmFold, "Number of move immediate folded");
14109467b48Spatrick STATISTIC(NumLoadFold, "Number of loads folded");
14209467b48Spatrick STATISTIC(NumSelects, "Number of selects optimized");
14309467b48Spatrick STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized");
14409467b48Spatrick STATISTIC(NumRewrittenCopies, "Number of copies rewritten");
14509467b48Spatrick STATISTIC(NumNAPhysCopies, "Number of non-allocatable physical copies removed");
14609467b48Spatrick 
14709467b48Spatrick namespace {
14809467b48Spatrick 
14909467b48Spatrick   class ValueTrackerResult;
15009467b48Spatrick   class RecurrenceInstr;
15109467b48Spatrick 
15209467b48Spatrick   class PeepholeOptimizer : public MachineFunctionPass {
15309467b48Spatrick     const TargetInstrInfo *TII;
15409467b48Spatrick     const TargetRegisterInfo *TRI;
15509467b48Spatrick     MachineRegisterInfo *MRI;
15609467b48Spatrick     MachineDominatorTree *DT;  // Machine dominator tree
15709467b48Spatrick     MachineLoopInfo *MLI;
15809467b48Spatrick 
15909467b48Spatrick   public:
16009467b48Spatrick     static char ID; // Pass identification
16109467b48Spatrick 
PeepholeOptimizer()16209467b48Spatrick     PeepholeOptimizer() : MachineFunctionPass(ID) {
16309467b48Spatrick       initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
16409467b48Spatrick     }
16509467b48Spatrick 
16609467b48Spatrick     bool runOnMachineFunction(MachineFunction &MF) override;
16709467b48Spatrick 
getAnalysisUsage(AnalysisUsage & AU) const16809467b48Spatrick     void getAnalysisUsage(AnalysisUsage &AU) const override {
16909467b48Spatrick       AU.setPreservesCFG();
17009467b48Spatrick       MachineFunctionPass::getAnalysisUsage(AU);
17109467b48Spatrick       AU.addRequired<MachineLoopInfo>();
17209467b48Spatrick       AU.addPreserved<MachineLoopInfo>();
17309467b48Spatrick       if (Aggressive) {
17409467b48Spatrick         AU.addRequired<MachineDominatorTree>();
17509467b48Spatrick         AU.addPreserved<MachineDominatorTree>();
17609467b48Spatrick       }
17709467b48Spatrick     }
17809467b48Spatrick 
getRequiredProperties() const17973471bf0Spatrick     MachineFunctionProperties getRequiredProperties() const override {
18073471bf0Spatrick       return MachineFunctionProperties()
18173471bf0Spatrick         .set(MachineFunctionProperties::Property::IsSSA);
18273471bf0Spatrick     }
18373471bf0Spatrick 
18409467b48Spatrick     /// Track Def -> Use info used for rewriting copies.
18509467b48Spatrick     using RewriteMapTy = SmallDenseMap<RegSubRegPair, ValueTrackerResult>;
18609467b48Spatrick 
18709467b48Spatrick     /// Sequence of instructions that formulate recurrence cycle.
18809467b48Spatrick     using RecurrenceCycle = SmallVector<RecurrenceInstr, 4>;
18909467b48Spatrick 
19009467b48Spatrick   private:
19109467b48Spatrick     bool optimizeCmpInstr(MachineInstr &MI);
19209467b48Spatrick     bool optimizeExtInstr(MachineInstr &MI, MachineBasicBlock &MBB,
19309467b48Spatrick                           SmallPtrSetImpl<MachineInstr*> &LocalMIs);
19409467b48Spatrick     bool optimizeSelect(MachineInstr &MI,
19509467b48Spatrick                         SmallPtrSetImpl<MachineInstr *> &LocalMIs);
19609467b48Spatrick     bool optimizeCondBranch(MachineInstr &MI);
19709467b48Spatrick     bool optimizeCoalescableCopy(MachineInstr &MI);
19809467b48Spatrick     bool optimizeUncoalescableCopy(MachineInstr &MI,
19909467b48Spatrick                                    SmallPtrSetImpl<MachineInstr *> &LocalMIs);
20009467b48Spatrick     bool optimizeRecurrence(MachineInstr &PHI);
20109467b48Spatrick     bool findNextSource(RegSubRegPair RegSubReg, RewriteMapTy &RewriteMap);
20273471bf0Spatrick     bool isMoveImmediate(MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs,
20373471bf0Spatrick                          DenseMap<Register, MachineInstr *> &ImmDefMIs);
20473471bf0Spatrick     bool foldImmediate(MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs,
20573471bf0Spatrick                        DenseMap<Register, MachineInstr *> &ImmDefMIs);
20609467b48Spatrick 
20709467b48Spatrick     /// Finds recurrence cycles, but only ones that formulated around
20809467b48Spatrick     /// a def operand and a use operand that are tied. If there is a use
20909467b48Spatrick     /// operand commutable with the tied use operand, find recurrence cycle
21009467b48Spatrick     /// along that operand as well.
21173471bf0Spatrick     bool findTargetRecurrence(Register Reg,
21273471bf0Spatrick                               const SmallSet<Register, 2> &TargetReg,
21309467b48Spatrick                               RecurrenceCycle &RC);
21409467b48Spatrick 
215*d415bd75Srobert     /// If copy instruction \p MI is a virtual register copy or a copy of a
216*d415bd75Srobert     /// constant physical register to a virtual register, track it in the
217*d415bd75Srobert     /// set \p CopyMIs. If this virtual register was previously seen as a
21873471bf0Spatrick     /// copy, replace the uses of this copy with the previously seen copy's
21973471bf0Spatrick     /// destination register.
22009467b48Spatrick     bool foldRedundantCopy(MachineInstr &MI,
22173471bf0Spatrick                            DenseMap<RegSubRegPair, MachineInstr *> &CopyMIs);
22209467b48Spatrick 
22309467b48Spatrick     /// Is the register \p Reg a non-allocatable physical register?
22473471bf0Spatrick     bool isNAPhysCopy(Register Reg);
22509467b48Spatrick 
22609467b48Spatrick     /// If copy instruction \p MI is a non-allocatable virtual<->physical
22709467b48Spatrick     /// register copy, track it in the \p NAPhysToVirtMIs map. If this
22809467b48Spatrick     /// non-allocatable physical register was previously copied to a virtual
22909467b48Spatrick     /// registered and hasn't been clobbered, the virt->phys copy can be
23009467b48Spatrick     /// deleted.
23173471bf0Spatrick     bool foldRedundantNAPhysCopy(
23273471bf0Spatrick         MachineInstr &MI, DenseMap<Register, MachineInstr *> &NAPhysToVirtMIs);
23309467b48Spatrick 
23409467b48Spatrick     bool isLoadFoldable(MachineInstr &MI,
23573471bf0Spatrick                         SmallSet<Register, 16> &FoldAsLoadDefCandidates);
23609467b48Spatrick 
23709467b48Spatrick     /// Check whether \p MI is understood by the register coalescer
23809467b48Spatrick     /// but may require some rewriting.
isCoalescableCopy(const MachineInstr & MI)23909467b48Spatrick     bool isCoalescableCopy(const MachineInstr &MI) {
24009467b48Spatrick       // SubregToRegs are not interesting, because they are already register
24109467b48Spatrick       // coalescer friendly.
24209467b48Spatrick       return MI.isCopy() || (!DisableAdvCopyOpt &&
24309467b48Spatrick                              (MI.isRegSequence() || MI.isInsertSubreg() ||
24409467b48Spatrick                               MI.isExtractSubreg()));
24509467b48Spatrick     }
24609467b48Spatrick 
24709467b48Spatrick     /// Check whether \p MI is a copy like instruction that is
24809467b48Spatrick     /// not recognized by the register coalescer.
isUncoalescableCopy(const MachineInstr & MI)24909467b48Spatrick     bool isUncoalescableCopy(const MachineInstr &MI) {
25009467b48Spatrick       return MI.isBitcast() ||
25109467b48Spatrick              (!DisableAdvCopyOpt &&
25209467b48Spatrick               (MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
25309467b48Spatrick                MI.isExtractSubregLike()));
25409467b48Spatrick     }
25509467b48Spatrick 
25609467b48Spatrick     MachineInstr &rewriteSource(MachineInstr &CopyLike,
25709467b48Spatrick                                 RegSubRegPair Def, RewriteMapTy &RewriteMap);
25809467b48Spatrick   };
25909467b48Spatrick 
26009467b48Spatrick   /// Helper class to hold instructions that are inside recurrence cycles.
26109467b48Spatrick   /// The recurrence cycle is formulated around 1) a def operand and its
26209467b48Spatrick   /// tied use operand, or 2) a def operand and a use operand that is commutable
26309467b48Spatrick   /// with another use operand which is tied to the def operand. In the latter
26409467b48Spatrick   /// case, index of the tied use operand and the commutable use operand are
26509467b48Spatrick   /// maintained with CommutePair.
26609467b48Spatrick   class RecurrenceInstr {
26709467b48Spatrick   public:
26809467b48Spatrick     using IndexPair = std::pair<unsigned, unsigned>;
26909467b48Spatrick 
RecurrenceInstr(MachineInstr * MI)27009467b48Spatrick     RecurrenceInstr(MachineInstr *MI) : MI(MI) {}
RecurrenceInstr(MachineInstr * MI,unsigned Idx1,unsigned Idx2)27109467b48Spatrick     RecurrenceInstr(MachineInstr *MI, unsigned Idx1, unsigned Idx2)
27209467b48Spatrick       : MI(MI), CommutePair(std::make_pair(Idx1, Idx2)) {}
27309467b48Spatrick 
getMI() const27409467b48Spatrick     MachineInstr *getMI() const { return MI; }
getCommutePair() const275*d415bd75Srobert     std::optional<IndexPair> getCommutePair() const { return CommutePair; }
27609467b48Spatrick 
27709467b48Spatrick   private:
27809467b48Spatrick     MachineInstr *MI;
279*d415bd75Srobert     std::optional<IndexPair> CommutePair;
28009467b48Spatrick   };
28109467b48Spatrick 
28209467b48Spatrick   /// Helper class to hold a reply for ValueTracker queries.
28309467b48Spatrick   /// Contains the returned sources for a given search and the instructions
28409467b48Spatrick   /// where the sources were tracked from.
28509467b48Spatrick   class ValueTrackerResult {
28609467b48Spatrick   private:
28709467b48Spatrick     /// Track all sources found by one ValueTracker query.
28809467b48Spatrick     SmallVector<RegSubRegPair, 2> RegSrcs;
28909467b48Spatrick 
29009467b48Spatrick     /// Instruction using the sources in 'RegSrcs'.
29109467b48Spatrick     const MachineInstr *Inst = nullptr;
29209467b48Spatrick 
29309467b48Spatrick   public:
29409467b48Spatrick     ValueTrackerResult() = default;
29509467b48Spatrick 
ValueTrackerResult(Register Reg,unsigned SubReg)29673471bf0Spatrick     ValueTrackerResult(Register Reg, unsigned SubReg) {
29709467b48Spatrick       addSource(Reg, SubReg);
29809467b48Spatrick     }
29909467b48Spatrick 
isValid() const30009467b48Spatrick     bool isValid() const { return getNumSources() > 0; }
30109467b48Spatrick 
setInst(const MachineInstr * I)30209467b48Spatrick     void setInst(const MachineInstr *I) { Inst = I; }
getInst() const30309467b48Spatrick     const MachineInstr *getInst() const { return Inst; }
30409467b48Spatrick 
clear()30509467b48Spatrick     void clear() {
30609467b48Spatrick       RegSrcs.clear();
30709467b48Spatrick       Inst = nullptr;
30809467b48Spatrick     }
30909467b48Spatrick 
addSource(Register SrcReg,unsigned SrcSubReg)31073471bf0Spatrick     void addSource(Register SrcReg, unsigned SrcSubReg) {
31109467b48Spatrick       RegSrcs.push_back(RegSubRegPair(SrcReg, SrcSubReg));
31209467b48Spatrick     }
31309467b48Spatrick 
setSource(int Idx,Register SrcReg,unsigned SrcSubReg)31473471bf0Spatrick     void setSource(int Idx, Register SrcReg, unsigned SrcSubReg) {
31509467b48Spatrick       assert(Idx < getNumSources() && "Reg pair source out of index");
31609467b48Spatrick       RegSrcs[Idx] = RegSubRegPair(SrcReg, SrcSubReg);
31709467b48Spatrick     }
31809467b48Spatrick 
getNumSources() const31909467b48Spatrick     int getNumSources() const { return RegSrcs.size(); }
32009467b48Spatrick 
getSrc(int Idx) const32109467b48Spatrick     RegSubRegPair getSrc(int Idx) const {
32209467b48Spatrick       return RegSrcs[Idx];
32309467b48Spatrick     }
32409467b48Spatrick 
getSrcReg(int Idx) const32573471bf0Spatrick     Register getSrcReg(int Idx) const {
32609467b48Spatrick       assert(Idx < getNumSources() && "Reg source out of index");
32709467b48Spatrick       return RegSrcs[Idx].Reg;
32809467b48Spatrick     }
32909467b48Spatrick 
getSrcSubReg(int Idx) const33009467b48Spatrick     unsigned getSrcSubReg(int Idx) const {
33109467b48Spatrick       assert(Idx < getNumSources() && "SubReg source out of index");
33209467b48Spatrick       return RegSrcs[Idx].SubReg;
33309467b48Spatrick     }
33409467b48Spatrick 
operator ==(const ValueTrackerResult & Other) const33573471bf0Spatrick     bool operator==(const ValueTrackerResult &Other) const {
33609467b48Spatrick       if (Other.getInst() != getInst())
33709467b48Spatrick         return false;
33809467b48Spatrick 
33909467b48Spatrick       if (Other.getNumSources() != getNumSources())
34009467b48Spatrick         return false;
34109467b48Spatrick 
34209467b48Spatrick       for (int i = 0, e = Other.getNumSources(); i != e; ++i)
34309467b48Spatrick         if (Other.getSrcReg(i) != getSrcReg(i) ||
34409467b48Spatrick             Other.getSrcSubReg(i) != getSrcSubReg(i))
34509467b48Spatrick           return false;
34609467b48Spatrick       return true;
34709467b48Spatrick     }
34809467b48Spatrick   };
34909467b48Spatrick 
35009467b48Spatrick   /// Helper class to track the possible sources of a value defined by
35109467b48Spatrick   /// a (chain of) copy related instructions.
35209467b48Spatrick   /// Given a definition (instruction and definition index), this class
35309467b48Spatrick   /// follows the use-def chain to find successive suitable sources.
35409467b48Spatrick   /// The given source can be used to rewrite the definition into
35509467b48Spatrick   /// def = COPY src.
35609467b48Spatrick   ///
35709467b48Spatrick   /// For instance, let us consider the following snippet:
35809467b48Spatrick   /// v0 =
35909467b48Spatrick   /// v2 = INSERT_SUBREG v1, v0, sub0
36009467b48Spatrick   /// def = COPY v2.sub0
36109467b48Spatrick   ///
36209467b48Spatrick   /// Using a ValueTracker for def = COPY v2.sub0 will give the following
36309467b48Spatrick   /// suitable sources:
36409467b48Spatrick   /// v2.sub0 and v0.
36509467b48Spatrick   /// Then, def can be rewritten into def = COPY v0.
36609467b48Spatrick   class ValueTracker {
36709467b48Spatrick   private:
36809467b48Spatrick     /// The current point into the use-def chain.
36909467b48Spatrick     const MachineInstr *Def = nullptr;
37009467b48Spatrick 
37109467b48Spatrick     /// The index of the definition in Def.
37209467b48Spatrick     unsigned DefIdx = 0;
37309467b48Spatrick 
37409467b48Spatrick     /// The sub register index of the definition.
37509467b48Spatrick     unsigned DefSubReg;
37609467b48Spatrick 
37709467b48Spatrick     /// The register where the value can be found.
37873471bf0Spatrick     Register Reg;
37909467b48Spatrick 
38009467b48Spatrick     /// MachineRegisterInfo used to perform tracking.
38109467b48Spatrick     const MachineRegisterInfo &MRI;
38209467b48Spatrick 
38309467b48Spatrick     /// Optional TargetInstrInfo used to perform some complex tracking.
38409467b48Spatrick     const TargetInstrInfo *TII;
38509467b48Spatrick 
38609467b48Spatrick     /// Dispatcher to the right underlying implementation of getNextSource.
38709467b48Spatrick     ValueTrackerResult getNextSourceImpl();
38809467b48Spatrick 
38909467b48Spatrick     /// Specialized version of getNextSource for Copy instructions.
39009467b48Spatrick     ValueTrackerResult getNextSourceFromCopy();
39109467b48Spatrick 
39209467b48Spatrick     /// Specialized version of getNextSource for Bitcast instructions.
39309467b48Spatrick     ValueTrackerResult getNextSourceFromBitcast();
39409467b48Spatrick 
39509467b48Spatrick     /// Specialized version of getNextSource for RegSequence instructions.
39609467b48Spatrick     ValueTrackerResult getNextSourceFromRegSequence();
39709467b48Spatrick 
39809467b48Spatrick     /// Specialized version of getNextSource for InsertSubreg instructions.
39909467b48Spatrick     ValueTrackerResult getNextSourceFromInsertSubreg();
40009467b48Spatrick 
40109467b48Spatrick     /// Specialized version of getNextSource for ExtractSubreg instructions.
40209467b48Spatrick     ValueTrackerResult getNextSourceFromExtractSubreg();
40309467b48Spatrick 
40409467b48Spatrick     /// Specialized version of getNextSource for SubregToReg instructions.
40509467b48Spatrick     ValueTrackerResult getNextSourceFromSubregToReg();
40609467b48Spatrick 
40709467b48Spatrick     /// Specialized version of getNextSource for PHI instructions.
40809467b48Spatrick     ValueTrackerResult getNextSourceFromPHI();
40909467b48Spatrick 
41009467b48Spatrick   public:
41109467b48Spatrick     /// Create a ValueTracker instance for the value defined by \p Reg.
41209467b48Spatrick     /// \p DefSubReg represents the sub register index the value tracker will
41309467b48Spatrick     /// track. It does not need to match the sub register index used in the
41409467b48Spatrick     /// definition of \p Reg.
41509467b48Spatrick     /// If \p Reg is a physical register, a value tracker constructed with
41609467b48Spatrick     /// this constructor will not find any alternative source.
41709467b48Spatrick     /// Indeed, when \p Reg is a physical register that constructor does not
41809467b48Spatrick     /// know which definition of \p Reg it should track.
41909467b48Spatrick     /// Use the next constructor to track a physical register.
ValueTracker(Register Reg,unsigned DefSubReg,const MachineRegisterInfo & MRI,const TargetInstrInfo * TII=nullptr)42073471bf0Spatrick     ValueTracker(Register Reg, unsigned DefSubReg,
42109467b48Spatrick                  const MachineRegisterInfo &MRI,
42209467b48Spatrick                  const TargetInstrInfo *TII = nullptr)
42309467b48Spatrick         : DefSubReg(DefSubReg), Reg(Reg), MRI(MRI), TII(TII) {
42473471bf0Spatrick       if (!Reg.isPhysical()) {
42509467b48Spatrick         Def = MRI.getVRegDef(Reg);
42609467b48Spatrick         DefIdx = MRI.def_begin(Reg).getOperandNo();
42709467b48Spatrick       }
42809467b48Spatrick     }
42909467b48Spatrick 
43009467b48Spatrick     /// Following the use-def chain, get the next available source
43109467b48Spatrick     /// for the tracked value.
43209467b48Spatrick     /// \return A ValueTrackerResult containing a set of registers
43309467b48Spatrick     /// and sub registers with tracked values. A ValueTrackerResult with
43409467b48Spatrick     /// an empty set of registers means no source was found.
43509467b48Spatrick     ValueTrackerResult getNextSource();
43609467b48Spatrick   };
43709467b48Spatrick 
43809467b48Spatrick } // end anonymous namespace
43909467b48Spatrick 
44009467b48Spatrick char PeepholeOptimizer::ID = 0;
44109467b48Spatrick 
44209467b48Spatrick char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
44309467b48Spatrick 
44409467b48Spatrick INITIALIZE_PASS_BEGIN(PeepholeOptimizer, DEBUG_TYPE,
44509467b48Spatrick                       "Peephole Optimizations", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)44609467b48Spatrick INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
44709467b48Spatrick INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
44809467b48Spatrick INITIALIZE_PASS_END(PeepholeOptimizer, DEBUG_TYPE,
44909467b48Spatrick                     "Peephole Optimizations", false, false)
45009467b48Spatrick 
45109467b48Spatrick /// If instruction is a copy-like instruction, i.e. it reads a single register
45209467b48Spatrick /// and writes a single register and it does not modify the source, and if the
45309467b48Spatrick /// source value is preserved as a sub-register of the result, then replace all
45409467b48Spatrick /// reachable uses of the source with the subreg of the result.
45509467b48Spatrick ///
45609467b48Spatrick /// Do not generate an EXTRACT that is used only in a debug use, as this changes
45709467b48Spatrick /// the code. Since this code does not currently share EXTRACTs, just ignore all
45809467b48Spatrick /// debug uses.
45909467b48Spatrick bool PeepholeOptimizer::
46009467b48Spatrick optimizeExtInstr(MachineInstr &MI, MachineBasicBlock &MBB,
46109467b48Spatrick                  SmallPtrSetImpl<MachineInstr*> &LocalMIs) {
462097a140dSpatrick   Register SrcReg, DstReg;
463097a140dSpatrick   unsigned SubIdx;
46409467b48Spatrick   if (!TII->isCoalescableExtInstr(MI, SrcReg, DstReg, SubIdx))
46509467b48Spatrick     return false;
46609467b48Spatrick 
467097a140dSpatrick   if (DstReg.isPhysical() || SrcReg.isPhysical())
46809467b48Spatrick     return false;
46909467b48Spatrick 
47009467b48Spatrick   if (MRI->hasOneNonDBGUse(SrcReg))
47109467b48Spatrick     // No other uses.
47209467b48Spatrick     return false;
47309467b48Spatrick 
47409467b48Spatrick   // Ensure DstReg can get a register class that actually supports
47509467b48Spatrick   // sub-registers. Don't change the class until we commit.
47609467b48Spatrick   const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
47709467b48Spatrick   DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
47809467b48Spatrick   if (!DstRC)
47909467b48Spatrick     return false;
48009467b48Spatrick 
48109467b48Spatrick   // The ext instr may be operating on a sub-register of SrcReg as well.
48209467b48Spatrick   // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
48309467b48Spatrick   // register.
48409467b48Spatrick   // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
48509467b48Spatrick   // SrcReg:SubIdx should be replaced.
48609467b48Spatrick   bool UseSrcSubIdx =
48709467b48Spatrick       TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr;
48809467b48Spatrick 
48909467b48Spatrick   // The source has other uses. See if we can replace the other uses with use of
49009467b48Spatrick   // the result of the extension.
49109467b48Spatrick   SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
49209467b48Spatrick   for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
49309467b48Spatrick     ReachedBBs.insert(UI.getParent());
49409467b48Spatrick 
49509467b48Spatrick   // Uses that are in the same BB of uses of the result of the instruction.
49609467b48Spatrick   SmallVector<MachineOperand*, 8> Uses;
49709467b48Spatrick 
49809467b48Spatrick   // Uses that the result of the instruction can reach.
49909467b48Spatrick   SmallVector<MachineOperand*, 8> ExtendedUses;
50009467b48Spatrick 
50109467b48Spatrick   bool ExtendLife = true;
50209467b48Spatrick   for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) {
50309467b48Spatrick     MachineInstr *UseMI = UseMO.getParent();
50409467b48Spatrick     if (UseMI == &MI)
50509467b48Spatrick       continue;
50609467b48Spatrick 
50709467b48Spatrick     if (UseMI->isPHI()) {
50809467b48Spatrick       ExtendLife = false;
50909467b48Spatrick       continue;
51009467b48Spatrick     }
51109467b48Spatrick 
51209467b48Spatrick     // Only accept uses of SrcReg:SubIdx.
51309467b48Spatrick     if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
51409467b48Spatrick       continue;
51509467b48Spatrick 
51609467b48Spatrick     // It's an error to translate this:
51709467b48Spatrick     //
51809467b48Spatrick     //    %reg1025 = <sext> %reg1024
51909467b48Spatrick     //     ...
52009467b48Spatrick     //    %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
52109467b48Spatrick     //
52209467b48Spatrick     // into this:
52309467b48Spatrick     //
52409467b48Spatrick     //    %reg1025 = <sext> %reg1024
52509467b48Spatrick     //     ...
52609467b48Spatrick     //    %reg1027 = COPY %reg1025:4
52709467b48Spatrick     //    %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
52809467b48Spatrick     //
52909467b48Spatrick     // The problem here is that SUBREG_TO_REG is there to assert that an
53009467b48Spatrick     // implicit zext occurs. It doesn't insert a zext instruction. If we allow
53109467b48Spatrick     // the COPY here, it will give us the value after the <sext>, not the
53209467b48Spatrick     // original value of %reg1024 before <sext>.
53309467b48Spatrick     if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
53409467b48Spatrick       continue;
53509467b48Spatrick 
53609467b48Spatrick     MachineBasicBlock *UseMBB = UseMI->getParent();
53709467b48Spatrick     if (UseMBB == &MBB) {
53809467b48Spatrick       // Local uses that come after the extension.
53909467b48Spatrick       if (!LocalMIs.count(UseMI))
54009467b48Spatrick         Uses.push_back(&UseMO);
54109467b48Spatrick     } else if (ReachedBBs.count(UseMBB)) {
54209467b48Spatrick       // Non-local uses where the result of the extension is used. Always
54309467b48Spatrick       // replace these unless it's a PHI.
54409467b48Spatrick       Uses.push_back(&UseMO);
54509467b48Spatrick     } else if (Aggressive && DT->dominates(&MBB, UseMBB)) {
54609467b48Spatrick       // We may want to extend the live range of the extension result in order
54709467b48Spatrick       // to replace these uses.
54809467b48Spatrick       ExtendedUses.push_back(&UseMO);
54909467b48Spatrick     } else {
55009467b48Spatrick       // Both will be live out of the def MBB anyway. Don't extend live range of
55109467b48Spatrick       // the extension result.
55209467b48Spatrick       ExtendLife = false;
55309467b48Spatrick       break;
55409467b48Spatrick     }
55509467b48Spatrick   }
55609467b48Spatrick 
55709467b48Spatrick   if (ExtendLife && !ExtendedUses.empty())
55809467b48Spatrick     // Extend the liveness of the extension result.
55909467b48Spatrick     Uses.append(ExtendedUses.begin(), ExtendedUses.end());
56009467b48Spatrick 
56109467b48Spatrick   // Now replace all uses.
56209467b48Spatrick   bool Changed = false;
56309467b48Spatrick   if (!Uses.empty()) {
56409467b48Spatrick     SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
56509467b48Spatrick 
56609467b48Spatrick     // Look for PHI uses of the extended result, we don't want to extend the
56709467b48Spatrick     // liveness of a PHI input. It breaks all kinds of assumptions down
56809467b48Spatrick     // stream. A PHI use is expected to be the kill of its source values.
56909467b48Spatrick     for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg))
57009467b48Spatrick       if (UI.isPHI())
57109467b48Spatrick         PHIBBs.insert(UI.getParent());
57209467b48Spatrick 
57309467b48Spatrick     const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
57409467b48Spatrick     for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
57509467b48Spatrick       MachineOperand *UseMO = Uses[i];
57609467b48Spatrick       MachineInstr *UseMI = UseMO->getParent();
57709467b48Spatrick       MachineBasicBlock *UseMBB = UseMI->getParent();
57809467b48Spatrick       if (PHIBBs.count(UseMBB))
57909467b48Spatrick         continue;
58009467b48Spatrick 
58109467b48Spatrick       // About to add uses of DstReg, clear DstReg's kill flags.
58209467b48Spatrick       if (!Changed) {
58309467b48Spatrick         MRI->clearKillFlags(DstReg);
58409467b48Spatrick         MRI->constrainRegClass(DstReg, DstRC);
58509467b48Spatrick       }
58609467b48Spatrick 
58773471bf0Spatrick       // SubReg defs are illegal in machine SSA phase,
58873471bf0Spatrick       // we should not generate SubReg defs.
58973471bf0Spatrick       //
59073471bf0Spatrick       // For example, for the instructions:
59173471bf0Spatrick       //
59273471bf0Spatrick       // %1:g8rc_and_g8rc_nox0 = EXTSW %0:g8rc
59373471bf0Spatrick       // %3:gprc_and_gprc_nor0 = COPY %0.sub_32:g8rc
59473471bf0Spatrick       //
59573471bf0Spatrick       // We should generate:
59673471bf0Spatrick       //
59773471bf0Spatrick       // %1:g8rc_and_g8rc_nox0 = EXTSW %0:g8rc
59873471bf0Spatrick       // %6:gprc_and_gprc_nor0 = COPY %1.sub_32:g8rc_and_g8rc_nox0
59973471bf0Spatrick       // %3:gprc_and_gprc_nor0 = COPY %6:gprc_and_gprc_nor0
60073471bf0Spatrick       //
60173471bf0Spatrick       if (UseSrcSubIdx)
60273471bf0Spatrick         RC = MRI->getRegClass(UseMI->getOperand(0).getReg());
60373471bf0Spatrick 
60409467b48Spatrick       Register NewVR = MRI->createVirtualRegister(RC);
60573471bf0Spatrick       BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
60609467b48Spatrick               TII->get(TargetOpcode::COPY), NewVR)
60709467b48Spatrick         .addReg(DstReg, 0, SubIdx);
60873471bf0Spatrick       if (UseSrcSubIdx)
60973471bf0Spatrick         UseMO->setSubReg(0);
61073471bf0Spatrick 
61109467b48Spatrick       UseMO->setReg(NewVR);
61209467b48Spatrick       ++NumReuse;
61309467b48Spatrick       Changed = true;
61409467b48Spatrick     }
61509467b48Spatrick   }
61609467b48Spatrick 
61709467b48Spatrick   return Changed;
61809467b48Spatrick }
61909467b48Spatrick 
62009467b48Spatrick /// If the instruction is a compare and the previous instruction it's comparing
62109467b48Spatrick /// against already sets (or could be modified to set) the same flag as the
62209467b48Spatrick /// compare, then we can remove the comparison and use the flag from the
62309467b48Spatrick /// previous instruction.
optimizeCmpInstr(MachineInstr & MI)62409467b48Spatrick bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr &MI) {
62509467b48Spatrick   // If this instruction is a comparison against zero and isn't comparing a
62609467b48Spatrick   // physical register, we can try to optimize it.
627097a140dSpatrick   Register SrcReg, SrcReg2;
628*d415bd75Srobert   int64_t CmpMask, CmpValue;
62909467b48Spatrick   if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
630097a140dSpatrick       SrcReg.isPhysical() || SrcReg2.isPhysical())
63109467b48Spatrick     return false;
63209467b48Spatrick 
63309467b48Spatrick   // Attempt to optimize the comparison instruction.
634097a140dSpatrick   LLVM_DEBUG(dbgs() << "Attempting to optimize compare: " << MI);
63509467b48Spatrick   if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
636097a140dSpatrick     LLVM_DEBUG(dbgs() << "  -> Successfully optimized compare!\n");
63709467b48Spatrick     ++NumCmps;
63809467b48Spatrick     return true;
63909467b48Spatrick   }
64009467b48Spatrick 
64109467b48Spatrick   return false;
64209467b48Spatrick }
64309467b48Spatrick 
64409467b48Spatrick /// Optimize a select instruction.
optimizeSelect(MachineInstr & MI,SmallPtrSetImpl<MachineInstr * > & LocalMIs)64509467b48Spatrick bool PeepholeOptimizer::optimizeSelect(MachineInstr &MI,
64609467b48Spatrick                             SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
64709467b48Spatrick   unsigned TrueOp = 0;
64809467b48Spatrick   unsigned FalseOp = 0;
64909467b48Spatrick   bool Optimizable = false;
65009467b48Spatrick   SmallVector<MachineOperand, 4> Cond;
65109467b48Spatrick   if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable))
65209467b48Spatrick     return false;
65309467b48Spatrick   if (!Optimizable)
65409467b48Spatrick     return false;
65509467b48Spatrick   if (!TII->optimizeSelect(MI, LocalMIs))
65609467b48Spatrick     return false;
657097a140dSpatrick   LLVM_DEBUG(dbgs() << "Deleting select: " << MI);
65809467b48Spatrick   MI.eraseFromParent();
65909467b48Spatrick   ++NumSelects;
66009467b48Spatrick   return true;
66109467b48Spatrick }
66209467b48Spatrick 
66309467b48Spatrick /// Check if a simpler conditional branch can be generated.
optimizeCondBranch(MachineInstr & MI)66409467b48Spatrick bool PeepholeOptimizer::optimizeCondBranch(MachineInstr &MI) {
66509467b48Spatrick   return TII->optimizeCondBranch(MI);
66609467b48Spatrick }
66709467b48Spatrick 
66809467b48Spatrick /// Try to find the next source that share the same register file
66909467b48Spatrick /// for the value defined by \p Reg and \p SubReg.
67009467b48Spatrick /// When true is returned, the \p RewriteMap can be used by the client to
67109467b48Spatrick /// retrieve all Def -> Use along the way up to the next source. Any found
67209467b48Spatrick /// Use that is not itself a key for another entry, is the next source to
67309467b48Spatrick /// use. During the search for the next source, multiple sources can be found
67409467b48Spatrick /// given multiple incoming sources of a PHI instruction. In this case, we
67509467b48Spatrick /// look in each PHI source for the next source; all found next sources must
67609467b48Spatrick /// share the same register file as \p Reg and \p SubReg. The client should
67709467b48Spatrick /// then be capable to rewrite all intermediate PHIs to get the next source.
67809467b48Spatrick /// \return False if no alternative sources are available. True otherwise.
findNextSource(RegSubRegPair RegSubReg,RewriteMapTy & RewriteMap)67909467b48Spatrick bool PeepholeOptimizer::findNextSource(RegSubRegPair RegSubReg,
68009467b48Spatrick                                        RewriteMapTy &RewriteMap) {
68109467b48Spatrick   // Do not try to find a new source for a physical register.
68209467b48Spatrick   // So far we do not have any motivating example for doing that.
68309467b48Spatrick   // Thus, instead of maintaining untested code, we will revisit that if
68409467b48Spatrick   // that changes at some point.
685097a140dSpatrick   Register Reg = RegSubReg.Reg;
686097a140dSpatrick   if (Reg.isPhysical())
68709467b48Spatrick     return false;
68809467b48Spatrick   const TargetRegisterClass *DefRC = MRI->getRegClass(Reg);
68909467b48Spatrick 
69009467b48Spatrick   SmallVector<RegSubRegPair, 4> SrcToLook;
69109467b48Spatrick   RegSubRegPair CurSrcPair = RegSubReg;
69209467b48Spatrick   SrcToLook.push_back(CurSrcPair);
69309467b48Spatrick 
69409467b48Spatrick   unsigned PHICount = 0;
69509467b48Spatrick   do {
69609467b48Spatrick     CurSrcPair = SrcToLook.pop_back_val();
69709467b48Spatrick     // As explained above, do not handle physical registers
698*d415bd75Srobert     if (CurSrcPair.Reg.isPhysical())
69909467b48Spatrick       return false;
70009467b48Spatrick 
70109467b48Spatrick     ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI, TII);
70209467b48Spatrick 
70309467b48Spatrick     // Follow the chain of copies until we find a more suitable source, a phi
70409467b48Spatrick     // or have to abort.
70509467b48Spatrick     while (true) {
70609467b48Spatrick       ValueTrackerResult Res = ValTracker.getNextSource();
70709467b48Spatrick       // Abort at the end of a chain (without finding a suitable source).
70809467b48Spatrick       if (!Res.isValid())
70909467b48Spatrick         return false;
71009467b48Spatrick 
71109467b48Spatrick       // Insert the Def -> Use entry for the recently found source.
71209467b48Spatrick       ValueTrackerResult CurSrcRes = RewriteMap.lookup(CurSrcPair);
71309467b48Spatrick       if (CurSrcRes.isValid()) {
71409467b48Spatrick         assert(CurSrcRes == Res && "ValueTrackerResult found must match");
71509467b48Spatrick         // An existent entry with multiple sources is a PHI cycle we must avoid.
71609467b48Spatrick         // Otherwise it's an entry with a valid next source we already found.
71709467b48Spatrick         if (CurSrcRes.getNumSources() > 1) {
71809467b48Spatrick           LLVM_DEBUG(dbgs()
71909467b48Spatrick                      << "findNextSource: found PHI cycle, aborting...\n");
72009467b48Spatrick           return false;
72109467b48Spatrick         }
72209467b48Spatrick         break;
72309467b48Spatrick       }
72409467b48Spatrick       RewriteMap.insert(std::make_pair(CurSrcPair, Res));
72509467b48Spatrick 
72609467b48Spatrick       // ValueTrackerResult usually have one source unless it's the result from
72709467b48Spatrick       // a PHI instruction. Add the found PHI edges to be looked up further.
72809467b48Spatrick       unsigned NumSrcs = Res.getNumSources();
72909467b48Spatrick       if (NumSrcs > 1) {
73009467b48Spatrick         PHICount++;
73109467b48Spatrick         if (PHICount >= RewritePHILimit) {
73209467b48Spatrick           LLVM_DEBUG(dbgs() << "findNextSource: PHI limit reached\n");
73309467b48Spatrick           return false;
73409467b48Spatrick         }
73509467b48Spatrick 
73609467b48Spatrick         for (unsigned i = 0; i < NumSrcs; ++i)
73709467b48Spatrick           SrcToLook.push_back(Res.getSrc(i));
73809467b48Spatrick         break;
73909467b48Spatrick       }
74009467b48Spatrick 
74109467b48Spatrick       CurSrcPair = Res.getSrc(0);
74209467b48Spatrick       // Do not extend the live-ranges of physical registers as they add
74309467b48Spatrick       // constraints to the register allocator. Moreover, if we want to extend
74409467b48Spatrick       // the live-range of a physical register, unlike SSA virtual register,
74509467b48Spatrick       // we will have to check that they aren't redefine before the related use.
746*d415bd75Srobert       if (CurSrcPair.Reg.isPhysical())
74709467b48Spatrick         return false;
74809467b48Spatrick 
74909467b48Spatrick       // Keep following the chain if the value isn't any better yet.
75009467b48Spatrick       const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg);
75109467b48Spatrick       if (!TRI->shouldRewriteCopySrc(DefRC, RegSubReg.SubReg, SrcRC,
75209467b48Spatrick                                      CurSrcPair.SubReg))
75309467b48Spatrick         continue;
75409467b48Spatrick 
75509467b48Spatrick       // We currently cannot deal with subreg operands on PHI instructions
75609467b48Spatrick       // (see insertPHI()).
75709467b48Spatrick       if (PHICount > 0 && CurSrcPair.SubReg != 0)
75809467b48Spatrick         continue;
75909467b48Spatrick 
76009467b48Spatrick       // We found a suitable source, and are done with this chain.
76109467b48Spatrick       break;
76209467b48Spatrick     }
76309467b48Spatrick   } while (!SrcToLook.empty());
76409467b48Spatrick 
76509467b48Spatrick   // If we did not find a more suitable source, there is nothing to optimize.
76609467b48Spatrick   return CurSrcPair.Reg != Reg;
76709467b48Spatrick }
76809467b48Spatrick 
76909467b48Spatrick /// Insert a PHI instruction with incoming edges \p SrcRegs that are
77009467b48Spatrick /// guaranteed to have the same register class. This is necessary whenever we
77109467b48Spatrick /// successfully traverse a PHI instruction and find suitable sources coming
77209467b48Spatrick /// from its edges. By inserting a new PHI, we provide a rewritten PHI def
77309467b48Spatrick /// suitable to be used in a new COPY instruction.
77409467b48Spatrick static MachineInstr &
insertPHI(MachineRegisterInfo & MRI,const TargetInstrInfo & TII,const SmallVectorImpl<RegSubRegPair> & SrcRegs,MachineInstr & OrigPHI)77509467b48Spatrick insertPHI(MachineRegisterInfo &MRI, const TargetInstrInfo &TII,
77609467b48Spatrick           const SmallVectorImpl<RegSubRegPair> &SrcRegs,
77709467b48Spatrick           MachineInstr &OrigPHI) {
77809467b48Spatrick   assert(!SrcRegs.empty() && "No sources to create a PHI instruction?");
77909467b48Spatrick 
78009467b48Spatrick   const TargetRegisterClass *NewRC = MRI.getRegClass(SrcRegs[0].Reg);
78109467b48Spatrick   // NewRC is only correct if no subregisters are involved. findNextSource()
78209467b48Spatrick   // should have rejected those cases already.
78309467b48Spatrick   assert(SrcRegs[0].SubReg == 0 && "should not have subreg operand");
78409467b48Spatrick   Register NewVR = MRI.createVirtualRegister(NewRC);
78509467b48Spatrick   MachineBasicBlock *MBB = OrigPHI.getParent();
78609467b48Spatrick   MachineInstrBuilder MIB = BuildMI(*MBB, &OrigPHI, OrigPHI.getDebugLoc(),
78709467b48Spatrick                                     TII.get(TargetOpcode::PHI), NewVR);
78809467b48Spatrick 
78909467b48Spatrick   unsigned MBBOpIdx = 2;
79009467b48Spatrick   for (const RegSubRegPair &RegPair : SrcRegs) {
79109467b48Spatrick     MIB.addReg(RegPair.Reg, 0, RegPair.SubReg);
79209467b48Spatrick     MIB.addMBB(OrigPHI.getOperand(MBBOpIdx).getMBB());
79309467b48Spatrick     // Since we're extended the lifetime of RegPair.Reg, clear the
79409467b48Spatrick     // kill flags to account for that and make RegPair.Reg reaches
79509467b48Spatrick     // the new PHI.
79609467b48Spatrick     MRI.clearKillFlags(RegPair.Reg);
79709467b48Spatrick     MBBOpIdx += 2;
79809467b48Spatrick   }
79909467b48Spatrick 
80009467b48Spatrick   return *MIB;
80109467b48Spatrick }
80209467b48Spatrick 
80309467b48Spatrick namespace {
80409467b48Spatrick 
80509467b48Spatrick /// Interface to query instructions amenable to copy rewriting.
80609467b48Spatrick class Rewriter {
80709467b48Spatrick protected:
80809467b48Spatrick   MachineInstr &CopyLike;
80909467b48Spatrick   unsigned CurrentSrcIdx = 0;   ///< The index of the source being rewritten.
81009467b48Spatrick public:
Rewriter(MachineInstr & CopyLike)81109467b48Spatrick   Rewriter(MachineInstr &CopyLike) : CopyLike(CopyLike) {}
812*d415bd75Srobert   virtual ~Rewriter() = default;
81309467b48Spatrick 
81409467b48Spatrick   /// Get the next rewritable source (SrcReg, SrcSubReg) and
81509467b48Spatrick   /// the related value that it affects (DstReg, DstSubReg).
81609467b48Spatrick   /// A source is considered rewritable if its register class and the
81709467b48Spatrick   /// register class of the related DstReg may not be register
81809467b48Spatrick   /// coalescer friendly. In other words, given a copy-like instruction
81909467b48Spatrick   /// not all the arguments may be returned at rewritable source, since
82009467b48Spatrick   /// some arguments are none to be register coalescer friendly.
82109467b48Spatrick   ///
82209467b48Spatrick   /// Each call of this method moves the current source to the next
82309467b48Spatrick   /// rewritable source.
82409467b48Spatrick   /// For instance, let CopyLike be the instruction to rewrite.
82509467b48Spatrick   /// CopyLike has one definition and one source:
82609467b48Spatrick   /// dst.dstSubIdx = CopyLike src.srcSubIdx.
82709467b48Spatrick   ///
82809467b48Spatrick   /// The first call will give the first rewritable source, i.e.,
82909467b48Spatrick   /// the only source this instruction has:
83009467b48Spatrick   /// (SrcReg, SrcSubReg) = (src, srcSubIdx).
83109467b48Spatrick   /// This source defines the whole definition, i.e.,
83209467b48Spatrick   /// (DstReg, DstSubReg) = (dst, dstSubIdx).
83309467b48Spatrick   ///
83409467b48Spatrick   /// The second and subsequent calls will return false, as there is only one
83509467b48Spatrick   /// rewritable source.
83609467b48Spatrick   ///
83709467b48Spatrick   /// \return True if a rewritable source has been found, false otherwise.
83809467b48Spatrick   /// The output arguments are valid if and only if true is returned.
83909467b48Spatrick   virtual bool getNextRewritableSource(RegSubRegPair &Src,
84009467b48Spatrick                                        RegSubRegPair &Dst) = 0;
84109467b48Spatrick 
84209467b48Spatrick   /// Rewrite the current source with \p NewReg and \p NewSubReg if possible.
84309467b48Spatrick   /// \return True if the rewriting was possible, false otherwise.
84473471bf0Spatrick   virtual bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) = 0;
84509467b48Spatrick };
84609467b48Spatrick 
84709467b48Spatrick /// Rewriter for COPY instructions.
84809467b48Spatrick class CopyRewriter : public Rewriter {
84909467b48Spatrick public:
CopyRewriter(MachineInstr & MI)85009467b48Spatrick   CopyRewriter(MachineInstr &MI) : Rewriter(MI) {
85109467b48Spatrick     assert(MI.isCopy() && "Expected copy instruction");
85209467b48Spatrick   }
85309467b48Spatrick   virtual ~CopyRewriter() = default;
85409467b48Spatrick 
getNextRewritableSource(RegSubRegPair & Src,RegSubRegPair & Dst)85509467b48Spatrick   bool getNextRewritableSource(RegSubRegPair &Src,
85609467b48Spatrick                                RegSubRegPair &Dst) override {
85709467b48Spatrick     // CurrentSrcIdx > 0 means this function has already been called.
85809467b48Spatrick     if (CurrentSrcIdx > 0)
85909467b48Spatrick       return false;
86009467b48Spatrick     // This is the first call to getNextRewritableSource.
86109467b48Spatrick     // Move the CurrentSrcIdx to remember that we made that call.
86209467b48Spatrick     CurrentSrcIdx = 1;
86309467b48Spatrick     // The rewritable source is the argument.
86409467b48Spatrick     const MachineOperand &MOSrc = CopyLike.getOperand(1);
86509467b48Spatrick     Src = RegSubRegPair(MOSrc.getReg(), MOSrc.getSubReg());
86609467b48Spatrick     // What we track are the alternative sources of the definition.
86709467b48Spatrick     const MachineOperand &MODef = CopyLike.getOperand(0);
86809467b48Spatrick     Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
86909467b48Spatrick     return true;
87009467b48Spatrick   }
87109467b48Spatrick 
RewriteCurrentSource(Register NewReg,unsigned NewSubReg)87273471bf0Spatrick   bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
87309467b48Spatrick     if (CurrentSrcIdx != 1)
87409467b48Spatrick       return false;
87509467b48Spatrick     MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx);
87609467b48Spatrick     MOSrc.setReg(NewReg);
87709467b48Spatrick     MOSrc.setSubReg(NewSubReg);
87809467b48Spatrick     return true;
87909467b48Spatrick   }
88009467b48Spatrick };
88109467b48Spatrick 
88209467b48Spatrick /// Helper class to rewrite uncoalescable copy like instructions
88309467b48Spatrick /// into new COPY (coalescable friendly) instructions.
88409467b48Spatrick class UncoalescableRewriter : public Rewriter {
88509467b48Spatrick   unsigned NumDefs;  ///< Number of defs in the bitcast.
88609467b48Spatrick 
88709467b48Spatrick public:
UncoalescableRewriter(MachineInstr & MI)88809467b48Spatrick   UncoalescableRewriter(MachineInstr &MI) : Rewriter(MI) {
88909467b48Spatrick     NumDefs = MI.getDesc().getNumDefs();
89009467b48Spatrick   }
89109467b48Spatrick 
89209467b48Spatrick   /// \see See Rewriter::getNextRewritableSource()
89309467b48Spatrick   /// All such sources need to be considered rewritable in order to
89409467b48Spatrick   /// rewrite a uncoalescable copy-like instruction. This method return
89509467b48Spatrick   /// each definition that must be checked if rewritable.
getNextRewritableSource(RegSubRegPair & Src,RegSubRegPair & Dst)89609467b48Spatrick   bool getNextRewritableSource(RegSubRegPair &Src,
89709467b48Spatrick                                RegSubRegPair &Dst) override {
89809467b48Spatrick     // Find the next non-dead definition and continue from there.
89909467b48Spatrick     if (CurrentSrcIdx == NumDefs)
90009467b48Spatrick       return false;
90109467b48Spatrick 
90209467b48Spatrick     while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
90309467b48Spatrick       ++CurrentSrcIdx;
90409467b48Spatrick       if (CurrentSrcIdx == NumDefs)
90509467b48Spatrick         return false;
90609467b48Spatrick     }
90709467b48Spatrick 
90809467b48Spatrick     // What we track are the alternative sources of the definition.
90909467b48Spatrick     Src = RegSubRegPair(0, 0);
91009467b48Spatrick     const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx);
91109467b48Spatrick     Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
91209467b48Spatrick 
91309467b48Spatrick     CurrentSrcIdx++;
91409467b48Spatrick     return true;
91509467b48Spatrick   }
91609467b48Spatrick 
RewriteCurrentSource(Register NewReg,unsigned NewSubReg)91773471bf0Spatrick   bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
91809467b48Spatrick     return false;
91909467b48Spatrick   }
92009467b48Spatrick };
92109467b48Spatrick 
92209467b48Spatrick /// Specialized rewriter for INSERT_SUBREG instruction.
92309467b48Spatrick class InsertSubregRewriter : public Rewriter {
92409467b48Spatrick public:
InsertSubregRewriter(MachineInstr & MI)92509467b48Spatrick   InsertSubregRewriter(MachineInstr &MI) : Rewriter(MI) {
92609467b48Spatrick     assert(MI.isInsertSubreg() && "Invalid instruction");
92709467b48Spatrick   }
92809467b48Spatrick 
92909467b48Spatrick   /// \see See Rewriter::getNextRewritableSource()
93009467b48Spatrick   /// Here CopyLike has the following form:
93109467b48Spatrick   /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx.
93209467b48Spatrick   /// Src1 has the same register class has dst, hence, there is
93309467b48Spatrick   /// nothing to rewrite.
93409467b48Spatrick   /// Src2.src2SubIdx, may not be register coalescer friendly.
93509467b48Spatrick   /// Therefore, the first call to this method returns:
93609467b48Spatrick   /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
93709467b48Spatrick   /// (DstReg, DstSubReg) = (dst, subIdx).
93809467b48Spatrick   ///
93909467b48Spatrick   /// Subsequence calls will return false.
getNextRewritableSource(RegSubRegPair & Src,RegSubRegPair & Dst)94009467b48Spatrick   bool getNextRewritableSource(RegSubRegPair &Src,
94109467b48Spatrick                                RegSubRegPair &Dst) override {
94209467b48Spatrick     // If we already get the only source we can rewrite, return false.
94309467b48Spatrick     if (CurrentSrcIdx == 2)
94409467b48Spatrick       return false;
94509467b48Spatrick     // We are looking at v2 = INSERT_SUBREG v0, v1, sub0.
94609467b48Spatrick     CurrentSrcIdx = 2;
94709467b48Spatrick     const MachineOperand &MOInsertedReg = CopyLike.getOperand(2);
94809467b48Spatrick     Src = RegSubRegPair(MOInsertedReg.getReg(), MOInsertedReg.getSubReg());
94909467b48Spatrick     const MachineOperand &MODef = CopyLike.getOperand(0);
95009467b48Spatrick 
95109467b48Spatrick     // We want to track something that is compatible with the
95209467b48Spatrick     // partial definition.
95309467b48Spatrick     if (MODef.getSubReg())
95409467b48Spatrick       // Bail if we have to compose sub-register indices.
95509467b48Spatrick       return false;
95609467b48Spatrick     Dst = RegSubRegPair(MODef.getReg(),
95709467b48Spatrick                         (unsigned)CopyLike.getOperand(3).getImm());
95809467b48Spatrick     return true;
95909467b48Spatrick   }
96009467b48Spatrick 
RewriteCurrentSource(Register NewReg,unsigned NewSubReg)96173471bf0Spatrick   bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
96209467b48Spatrick     if (CurrentSrcIdx != 2)
96309467b48Spatrick       return false;
96409467b48Spatrick     // We are rewriting the inserted reg.
96509467b48Spatrick     MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
96609467b48Spatrick     MO.setReg(NewReg);
96709467b48Spatrick     MO.setSubReg(NewSubReg);
96809467b48Spatrick     return true;
96909467b48Spatrick   }
97009467b48Spatrick };
97109467b48Spatrick 
97209467b48Spatrick /// Specialized rewriter for EXTRACT_SUBREG instruction.
97309467b48Spatrick class ExtractSubregRewriter : public Rewriter {
97409467b48Spatrick   const TargetInstrInfo &TII;
97509467b48Spatrick 
97609467b48Spatrick public:
ExtractSubregRewriter(MachineInstr & MI,const TargetInstrInfo & TII)97709467b48Spatrick   ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII)
97809467b48Spatrick       : Rewriter(MI), TII(TII) {
97909467b48Spatrick     assert(MI.isExtractSubreg() && "Invalid instruction");
98009467b48Spatrick   }
98109467b48Spatrick 
98209467b48Spatrick   /// \see Rewriter::getNextRewritableSource()
98309467b48Spatrick   /// Here CopyLike has the following form:
98409467b48Spatrick   /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx.
98509467b48Spatrick   /// There is only one rewritable source: Src.subIdx,
98609467b48Spatrick   /// which defines dst.dstSubIdx.
getNextRewritableSource(RegSubRegPair & Src,RegSubRegPair & Dst)98709467b48Spatrick   bool getNextRewritableSource(RegSubRegPair &Src,
98809467b48Spatrick                                RegSubRegPair &Dst) override {
98909467b48Spatrick     // If we already get the only source we can rewrite, return false.
99009467b48Spatrick     if (CurrentSrcIdx == 1)
99109467b48Spatrick       return false;
99209467b48Spatrick     // We are looking at v1 = EXTRACT_SUBREG v0, sub0.
99309467b48Spatrick     CurrentSrcIdx = 1;
99409467b48Spatrick     const MachineOperand &MOExtractedReg = CopyLike.getOperand(1);
99509467b48Spatrick     // If we have to compose sub-register indices, bail out.
99609467b48Spatrick     if (MOExtractedReg.getSubReg())
99709467b48Spatrick       return false;
99809467b48Spatrick 
99909467b48Spatrick     Src = RegSubRegPair(MOExtractedReg.getReg(),
100009467b48Spatrick                         CopyLike.getOperand(2).getImm());
100109467b48Spatrick 
100209467b48Spatrick     // We want to track something that is compatible with the definition.
100309467b48Spatrick     const MachineOperand &MODef = CopyLike.getOperand(0);
100409467b48Spatrick     Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg());
100509467b48Spatrick     return true;
100609467b48Spatrick   }
100709467b48Spatrick 
RewriteCurrentSource(Register NewReg,unsigned NewSubReg)100873471bf0Spatrick   bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
100909467b48Spatrick     // The only source we can rewrite is the input register.
101009467b48Spatrick     if (CurrentSrcIdx != 1)
101109467b48Spatrick       return false;
101209467b48Spatrick 
101309467b48Spatrick     CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
101409467b48Spatrick 
101509467b48Spatrick     // If we find a source that does not require to extract something,
101609467b48Spatrick     // rewrite the operation with a copy.
101709467b48Spatrick     if (!NewSubReg) {
101809467b48Spatrick       // Move the current index to an invalid position.
101909467b48Spatrick       // We do not want another call to this method to be able
102009467b48Spatrick       // to do any change.
102109467b48Spatrick       CurrentSrcIdx = -1;
102209467b48Spatrick       // Rewrite the operation as a COPY.
102309467b48Spatrick       // Get rid of the sub-register index.
1024*d415bd75Srobert       CopyLike.removeOperand(2);
102509467b48Spatrick       // Morph the operation into a COPY.
102609467b48Spatrick       CopyLike.setDesc(TII.get(TargetOpcode::COPY));
102709467b48Spatrick       return true;
102809467b48Spatrick     }
102909467b48Spatrick     CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
103009467b48Spatrick     return true;
103109467b48Spatrick   }
103209467b48Spatrick };
103309467b48Spatrick 
103409467b48Spatrick /// Specialized rewriter for REG_SEQUENCE instruction.
103509467b48Spatrick class RegSequenceRewriter : public Rewriter {
103609467b48Spatrick public:
RegSequenceRewriter(MachineInstr & MI)103709467b48Spatrick   RegSequenceRewriter(MachineInstr &MI) : Rewriter(MI) {
103809467b48Spatrick     assert(MI.isRegSequence() && "Invalid instruction");
103909467b48Spatrick   }
104009467b48Spatrick 
104109467b48Spatrick   /// \see Rewriter::getNextRewritableSource()
104209467b48Spatrick   /// Here CopyLike has the following form:
104309467b48Spatrick   /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2.
104409467b48Spatrick   /// Each call will return a different source, walking all the available
104509467b48Spatrick   /// source.
104609467b48Spatrick   ///
104709467b48Spatrick   /// The first call returns:
104809467b48Spatrick   /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx).
104909467b48Spatrick   /// (DstReg, DstSubReg) = (dst, subIdx1).
105009467b48Spatrick   ///
105109467b48Spatrick   /// The second call returns:
105209467b48Spatrick   /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx).
105309467b48Spatrick   /// (DstReg, DstSubReg) = (dst, subIdx2).
105409467b48Spatrick   ///
105509467b48Spatrick   /// And so on, until all the sources have been traversed, then
105609467b48Spatrick   /// it returns false.
getNextRewritableSource(RegSubRegPair & Src,RegSubRegPair & Dst)105709467b48Spatrick   bool getNextRewritableSource(RegSubRegPair &Src,
105809467b48Spatrick                                RegSubRegPair &Dst) override {
105909467b48Spatrick     // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc.
106009467b48Spatrick 
106109467b48Spatrick     // If this is the first call, move to the first argument.
106209467b48Spatrick     if (CurrentSrcIdx == 0) {
106309467b48Spatrick       CurrentSrcIdx = 1;
106409467b48Spatrick     } else {
106509467b48Spatrick       // Otherwise, move to the next argument and check that it is valid.
106609467b48Spatrick       CurrentSrcIdx += 2;
106709467b48Spatrick       if (CurrentSrcIdx >= CopyLike.getNumOperands())
106809467b48Spatrick         return false;
106909467b48Spatrick     }
107009467b48Spatrick     const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
107109467b48Spatrick     Src.Reg = MOInsertedReg.getReg();
107209467b48Spatrick     // If we have to compose sub-register indices, bail out.
107309467b48Spatrick     if ((Src.SubReg = MOInsertedReg.getSubReg()))
107409467b48Spatrick       return false;
107509467b48Spatrick 
107609467b48Spatrick     // We want to track something that is compatible with the related
107709467b48Spatrick     // partial definition.
107809467b48Spatrick     Dst.SubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
107909467b48Spatrick 
108009467b48Spatrick     const MachineOperand &MODef = CopyLike.getOperand(0);
108109467b48Spatrick     Dst.Reg = MODef.getReg();
108209467b48Spatrick     // If we have to compose sub-registers, bail.
108309467b48Spatrick     return MODef.getSubReg() == 0;
108409467b48Spatrick   }
108509467b48Spatrick 
RewriteCurrentSource(Register NewReg,unsigned NewSubReg)108673471bf0Spatrick   bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override {
108709467b48Spatrick     // We cannot rewrite out of bound operands.
108809467b48Spatrick     // Moreover, rewritable sources are at odd positions.
108909467b48Spatrick     if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
109009467b48Spatrick       return false;
109109467b48Spatrick 
109209467b48Spatrick     MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx);
109309467b48Spatrick     MO.setReg(NewReg);
109409467b48Spatrick     MO.setSubReg(NewSubReg);
109509467b48Spatrick     return true;
109609467b48Spatrick   }
109709467b48Spatrick };
109809467b48Spatrick 
109909467b48Spatrick } // end anonymous namespace
110009467b48Spatrick 
110109467b48Spatrick /// Get the appropriated Rewriter for \p MI.
110209467b48Spatrick /// \return A pointer to a dynamically allocated Rewriter or nullptr if no
110309467b48Spatrick /// rewriter works for \p MI.
getCopyRewriter(MachineInstr & MI,const TargetInstrInfo & TII)110409467b48Spatrick static Rewriter *getCopyRewriter(MachineInstr &MI, const TargetInstrInfo &TII) {
110509467b48Spatrick   // Handle uncoalescable copy-like instructions.
110609467b48Spatrick   if (MI.isBitcast() || MI.isRegSequenceLike() || MI.isInsertSubregLike() ||
110709467b48Spatrick       MI.isExtractSubregLike())
110809467b48Spatrick     return new UncoalescableRewriter(MI);
110909467b48Spatrick 
111009467b48Spatrick   switch (MI.getOpcode()) {
111109467b48Spatrick   default:
111209467b48Spatrick     return nullptr;
111309467b48Spatrick   case TargetOpcode::COPY:
111409467b48Spatrick     return new CopyRewriter(MI);
111509467b48Spatrick   case TargetOpcode::INSERT_SUBREG:
111609467b48Spatrick     return new InsertSubregRewriter(MI);
111709467b48Spatrick   case TargetOpcode::EXTRACT_SUBREG:
111809467b48Spatrick     return new ExtractSubregRewriter(MI, TII);
111909467b48Spatrick   case TargetOpcode::REG_SEQUENCE:
112009467b48Spatrick     return new RegSequenceRewriter(MI);
112109467b48Spatrick   }
112209467b48Spatrick }
112309467b48Spatrick 
112409467b48Spatrick /// Given a \p Def.Reg and Def.SubReg  pair, use \p RewriteMap to find
112509467b48Spatrick /// the new source to use for rewrite. If \p HandleMultipleSources is true and
112609467b48Spatrick /// multiple sources for a given \p Def are found along the way, we found a
112709467b48Spatrick /// PHI instructions that needs to be rewritten.
112809467b48Spatrick /// TODO: HandleMultipleSources should be removed once we test PHI handling
112909467b48Spatrick /// with coalescable copies.
113009467b48Spatrick static RegSubRegPair
getNewSource(MachineRegisterInfo * MRI,const TargetInstrInfo * TII,RegSubRegPair Def,const PeepholeOptimizer::RewriteMapTy & RewriteMap,bool HandleMultipleSources=true)113109467b48Spatrick getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII,
113209467b48Spatrick              RegSubRegPair Def,
113309467b48Spatrick              const PeepholeOptimizer::RewriteMapTy &RewriteMap,
113409467b48Spatrick              bool HandleMultipleSources = true) {
113509467b48Spatrick   RegSubRegPair LookupSrc(Def.Reg, Def.SubReg);
113609467b48Spatrick   while (true) {
113709467b48Spatrick     ValueTrackerResult Res = RewriteMap.lookup(LookupSrc);
113809467b48Spatrick     // If there are no entries on the map, LookupSrc is the new source.
113909467b48Spatrick     if (!Res.isValid())
114009467b48Spatrick       return LookupSrc;
114109467b48Spatrick 
114209467b48Spatrick     // There's only one source for this definition, keep searching...
114309467b48Spatrick     unsigned NumSrcs = Res.getNumSources();
114409467b48Spatrick     if (NumSrcs == 1) {
114509467b48Spatrick       LookupSrc.Reg = Res.getSrcReg(0);
114609467b48Spatrick       LookupSrc.SubReg = Res.getSrcSubReg(0);
114709467b48Spatrick       continue;
114809467b48Spatrick     }
114909467b48Spatrick 
115009467b48Spatrick     // TODO: Remove once multiple srcs w/ coalescable copies are supported.
115109467b48Spatrick     if (!HandleMultipleSources)
115209467b48Spatrick       break;
115309467b48Spatrick 
115409467b48Spatrick     // Multiple sources, recurse into each source to find a new source
115509467b48Spatrick     // for it. Then, rewrite the PHI accordingly to its new edges.
115609467b48Spatrick     SmallVector<RegSubRegPair, 4> NewPHISrcs;
115709467b48Spatrick     for (unsigned i = 0; i < NumSrcs; ++i) {
115809467b48Spatrick       RegSubRegPair PHISrc(Res.getSrcReg(i), Res.getSrcSubReg(i));
115909467b48Spatrick       NewPHISrcs.push_back(
116009467b48Spatrick           getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources));
116109467b48Spatrick     }
116209467b48Spatrick 
116309467b48Spatrick     // Build the new PHI node and return its def register as the new source.
116409467b48Spatrick     MachineInstr &OrigPHI = const_cast<MachineInstr &>(*Res.getInst());
116509467b48Spatrick     MachineInstr &NewPHI = insertPHI(*MRI, *TII, NewPHISrcs, OrigPHI);
116609467b48Spatrick     LLVM_DEBUG(dbgs() << "-- getNewSource\n");
116709467b48Spatrick     LLVM_DEBUG(dbgs() << "   Replacing: " << OrigPHI);
116809467b48Spatrick     LLVM_DEBUG(dbgs() << "        With: " << NewPHI);
116909467b48Spatrick     const MachineOperand &MODef = NewPHI.getOperand(0);
117009467b48Spatrick     return RegSubRegPair(MODef.getReg(), MODef.getSubReg());
117109467b48Spatrick   }
117209467b48Spatrick 
117309467b48Spatrick   return RegSubRegPair(0, 0);
117409467b48Spatrick }
117509467b48Spatrick 
117609467b48Spatrick /// Optimize generic copy instructions to avoid cross register bank copy.
117709467b48Spatrick /// The optimization looks through a chain of copies and tries to find a source
117809467b48Spatrick /// that has a compatible register class.
117909467b48Spatrick /// Two register classes are considered to be compatible if they share the same
118009467b48Spatrick /// register bank.
118109467b48Spatrick /// New copies issued by this optimization are register allocator
118209467b48Spatrick /// friendly. This optimization does not remove any copy as it may
118309467b48Spatrick /// overconstrain the register allocator, but replaces some operands
118409467b48Spatrick /// when possible.
118509467b48Spatrick /// \pre isCoalescableCopy(*MI) is true.
118609467b48Spatrick /// \return True, when \p MI has been rewritten. False otherwise.
optimizeCoalescableCopy(MachineInstr & MI)118709467b48Spatrick bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr &MI) {
118809467b48Spatrick   assert(isCoalescableCopy(MI) && "Invalid argument");
118909467b48Spatrick   assert(MI.getDesc().getNumDefs() == 1 &&
119009467b48Spatrick          "Coalescer can understand multiple defs?!");
119109467b48Spatrick   const MachineOperand &MODef = MI.getOperand(0);
119209467b48Spatrick   // Do not rewrite physical definitions.
1193*d415bd75Srobert   if (MODef.getReg().isPhysical())
119409467b48Spatrick     return false;
119509467b48Spatrick 
119609467b48Spatrick   bool Changed = false;
119709467b48Spatrick   // Get the right rewriter for the current copy.
119809467b48Spatrick   std::unique_ptr<Rewriter> CpyRewriter(getCopyRewriter(MI, *TII));
119909467b48Spatrick   // If none exists, bail out.
120009467b48Spatrick   if (!CpyRewriter)
120109467b48Spatrick     return false;
120209467b48Spatrick   // Rewrite each rewritable source.
120309467b48Spatrick   RegSubRegPair Src;
120409467b48Spatrick   RegSubRegPair TrackPair;
120509467b48Spatrick   while (CpyRewriter->getNextRewritableSource(Src, TrackPair)) {
120609467b48Spatrick     // Keep track of PHI nodes and its incoming edges when looking for sources.
120709467b48Spatrick     RewriteMapTy RewriteMap;
120809467b48Spatrick     // Try to find a more suitable source. If we failed to do so, or get the
120909467b48Spatrick     // actual source, move to the next source.
121009467b48Spatrick     if (!findNextSource(TrackPair, RewriteMap))
121109467b48Spatrick       continue;
121209467b48Spatrick 
121309467b48Spatrick     // Get the new source to rewrite. TODO: Only enable handling of multiple
121409467b48Spatrick     // sources (PHIs) once we have a motivating example and testcases for it.
121509467b48Spatrick     RegSubRegPair NewSrc = getNewSource(MRI, TII, TrackPair, RewriteMap,
121609467b48Spatrick                                         /*HandleMultipleSources=*/false);
121709467b48Spatrick     if (Src.Reg == NewSrc.Reg || NewSrc.Reg == 0)
121809467b48Spatrick       continue;
121909467b48Spatrick 
122009467b48Spatrick     // Rewrite source.
122109467b48Spatrick     if (CpyRewriter->RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg)) {
122209467b48Spatrick       // We may have extended the live-range of NewSrc, account for that.
122309467b48Spatrick       MRI->clearKillFlags(NewSrc.Reg);
122409467b48Spatrick       Changed = true;
122509467b48Spatrick     }
122609467b48Spatrick   }
122709467b48Spatrick   // TODO: We could have a clean-up method to tidy the instruction.
122809467b48Spatrick   // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0
122909467b48Spatrick   // => v0 = COPY v1
123009467b48Spatrick   // Currently we haven't seen motivating example for that and we
123109467b48Spatrick   // want to avoid untested code.
123209467b48Spatrick   NumRewrittenCopies += Changed;
123309467b48Spatrick   return Changed;
123409467b48Spatrick }
123509467b48Spatrick 
123609467b48Spatrick /// Rewrite the source found through \p Def, by using the \p RewriteMap
123709467b48Spatrick /// and create a new COPY instruction. More info about RewriteMap in
123809467b48Spatrick /// PeepholeOptimizer::findNextSource. Right now this is only used to handle
123909467b48Spatrick /// Uncoalescable copies, since they are copy like instructions that aren't
124009467b48Spatrick /// recognized by the register allocator.
124109467b48Spatrick MachineInstr &
rewriteSource(MachineInstr & CopyLike,RegSubRegPair Def,RewriteMapTy & RewriteMap)124209467b48Spatrick PeepholeOptimizer::rewriteSource(MachineInstr &CopyLike,
124309467b48Spatrick                                  RegSubRegPair Def, RewriteMapTy &RewriteMap) {
1244*d415bd75Srobert   assert(!Def.Reg.isPhysical() && "We do not rewrite physical registers");
124509467b48Spatrick 
124609467b48Spatrick   // Find the new source to use in the COPY rewrite.
124709467b48Spatrick   RegSubRegPair NewSrc = getNewSource(MRI, TII, Def, RewriteMap);
124809467b48Spatrick 
124909467b48Spatrick   // Insert the COPY.
125009467b48Spatrick   const TargetRegisterClass *DefRC = MRI->getRegClass(Def.Reg);
125109467b48Spatrick   Register NewVReg = MRI->createVirtualRegister(DefRC);
125209467b48Spatrick 
125309467b48Spatrick   MachineInstr *NewCopy =
125409467b48Spatrick       BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
125509467b48Spatrick               TII->get(TargetOpcode::COPY), NewVReg)
125609467b48Spatrick           .addReg(NewSrc.Reg, 0, NewSrc.SubReg);
125709467b48Spatrick 
125809467b48Spatrick   if (Def.SubReg) {
125909467b48Spatrick     NewCopy->getOperand(0).setSubReg(Def.SubReg);
126009467b48Spatrick     NewCopy->getOperand(0).setIsUndef();
126109467b48Spatrick   }
126209467b48Spatrick 
126309467b48Spatrick   LLVM_DEBUG(dbgs() << "-- RewriteSource\n");
126409467b48Spatrick   LLVM_DEBUG(dbgs() << "   Replacing: " << CopyLike);
126509467b48Spatrick   LLVM_DEBUG(dbgs() << "        With: " << *NewCopy);
126609467b48Spatrick   MRI->replaceRegWith(Def.Reg, NewVReg);
126709467b48Spatrick   MRI->clearKillFlags(NewVReg);
126809467b48Spatrick 
126909467b48Spatrick   // We extended the lifetime of NewSrc.Reg, clear the kill flags to
127009467b48Spatrick   // account for that.
127109467b48Spatrick   MRI->clearKillFlags(NewSrc.Reg);
127209467b48Spatrick 
127309467b48Spatrick   return *NewCopy;
127409467b48Spatrick }
127509467b48Spatrick 
127609467b48Spatrick /// Optimize copy-like instructions to create
127709467b48Spatrick /// register coalescer friendly instruction.
127809467b48Spatrick /// The optimization tries to kill-off the \p MI by looking
127909467b48Spatrick /// through a chain of copies to find a source that has a compatible
128009467b48Spatrick /// register class.
128109467b48Spatrick /// If such a source is found, it replace \p MI by a generic COPY
128209467b48Spatrick /// operation.
128309467b48Spatrick /// \pre isUncoalescableCopy(*MI) is true.
128409467b48Spatrick /// \return True, when \p MI has been optimized. In that case, \p MI has
128509467b48Spatrick /// been removed from its parent.
128609467b48Spatrick /// All COPY instructions created, are inserted in \p LocalMIs.
optimizeUncoalescableCopy(MachineInstr & MI,SmallPtrSetImpl<MachineInstr * > & LocalMIs)128709467b48Spatrick bool PeepholeOptimizer::optimizeUncoalescableCopy(
128809467b48Spatrick     MachineInstr &MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) {
128909467b48Spatrick   assert(isUncoalescableCopy(MI) && "Invalid argument");
129009467b48Spatrick   UncoalescableRewriter CpyRewriter(MI);
129109467b48Spatrick 
129209467b48Spatrick   // Rewrite each rewritable source by generating new COPYs. This works
129309467b48Spatrick   // differently from optimizeCoalescableCopy since it first makes sure that all
129409467b48Spatrick   // definitions can be rewritten.
129509467b48Spatrick   RewriteMapTy RewriteMap;
129609467b48Spatrick   RegSubRegPair Src;
129709467b48Spatrick   RegSubRegPair Def;
129809467b48Spatrick   SmallVector<RegSubRegPair, 4> RewritePairs;
129909467b48Spatrick   while (CpyRewriter.getNextRewritableSource(Src, Def)) {
130009467b48Spatrick     // If a physical register is here, this is probably for a good reason.
130109467b48Spatrick     // Do not rewrite that.
1302*d415bd75Srobert     if (Def.Reg.isPhysical())
130309467b48Spatrick       return false;
130409467b48Spatrick 
130509467b48Spatrick     // If we do not know how to rewrite this definition, there is no point
130609467b48Spatrick     // in trying to kill this instruction.
130709467b48Spatrick     if (!findNextSource(Def, RewriteMap))
130809467b48Spatrick       return false;
130909467b48Spatrick 
131009467b48Spatrick     RewritePairs.push_back(Def);
131109467b48Spatrick   }
131209467b48Spatrick 
131309467b48Spatrick   // The change is possible for all defs, do it.
131409467b48Spatrick   for (const RegSubRegPair &Def : RewritePairs) {
131509467b48Spatrick     // Rewrite the "copy" in a way the register coalescer understands.
131609467b48Spatrick     MachineInstr &NewCopy = rewriteSource(MI, Def, RewriteMap);
131709467b48Spatrick     LocalMIs.insert(&NewCopy);
131809467b48Spatrick   }
131909467b48Spatrick 
132009467b48Spatrick   // MI is now dead.
1321097a140dSpatrick   LLVM_DEBUG(dbgs() << "Deleting uncoalescable copy: " << MI);
132209467b48Spatrick   MI.eraseFromParent();
132309467b48Spatrick   ++NumUncoalescableCopies;
132409467b48Spatrick   return true;
132509467b48Spatrick }
132609467b48Spatrick 
132709467b48Spatrick /// Check whether MI is a candidate for folding into a later instruction.
132809467b48Spatrick /// We only fold loads to virtual registers and the virtual register defined
132909467b48Spatrick /// has a single user.
isLoadFoldable(MachineInstr & MI,SmallSet<Register,16> & FoldAsLoadDefCandidates)133009467b48Spatrick bool PeepholeOptimizer::isLoadFoldable(
133173471bf0Spatrick     MachineInstr &MI, SmallSet<Register, 16> &FoldAsLoadDefCandidates) {
133209467b48Spatrick   if (!MI.canFoldAsLoad() || !MI.mayLoad())
133309467b48Spatrick     return false;
133409467b48Spatrick   const MCInstrDesc &MCID = MI.getDesc();
133509467b48Spatrick   if (MCID.getNumDefs() != 1)
133609467b48Spatrick     return false;
133709467b48Spatrick 
133809467b48Spatrick   Register Reg = MI.getOperand(0).getReg();
133909467b48Spatrick   // To reduce compilation time, we check MRI->hasOneNonDBGUser when inserting
134009467b48Spatrick   // loads. It should be checked when processing uses of the load, since
134109467b48Spatrick   // uses can be removed during peephole.
134273471bf0Spatrick   if (Reg.isVirtual() && !MI.getOperand(0).getSubReg() &&
134309467b48Spatrick       MRI->hasOneNonDBGUser(Reg)) {
134409467b48Spatrick     FoldAsLoadDefCandidates.insert(Reg);
134509467b48Spatrick     return true;
134609467b48Spatrick   }
134709467b48Spatrick   return false;
134809467b48Spatrick }
134909467b48Spatrick 
isMoveImmediate(MachineInstr & MI,SmallSet<Register,4> & ImmDefRegs,DenseMap<Register,MachineInstr * > & ImmDefMIs)135009467b48Spatrick bool PeepholeOptimizer::isMoveImmediate(
135173471bf0Spatrick     MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs,
135273471bf0Spatrick     DenseMap<Register, MachineInstr *> &ImmDefMIs) {
135309467b48Spatrick   const MCInstrDesc &MCID = MI.getDesc();
135409467b48Spatrick   if (!MI.isMoveImmediate())
135509467b48Spatrick     return false;
135609467b48Spatrick   if (MCID.getNumDefs() != 1)
135709467b48Spatrick     return false;
135809467b48Spatrick   Register Reg = MI.getOperand(0).getReg();
135973471bf0Spatrick   if (Reg.isVirtual()) {
136009467b48Spatrick     ImmDefMIs.insert(std::make_pair(Reg, &MI));
136109467b48Spatrick     ImmDefRegs.insert(Reg);
136209467b48Spatrick     return true;
136309467b48Spatrick   }
136409467b48Spatrick 
136509467b48Spatrick   return false;
136609467b48Spatrick }
136709467b48Spatrick 
136809467b48Spatrick /// Try folding register operands that are defined by move immediate
136909467b48Spatrick /// instructions, i.e. a trivial constant folding optimization, if
137009467b48Spatrick /// and only if the def and use are in the same BB.
foldImmediate(MachineInstr & MI,SmallSet<Register,4> & ImmDefRegs,DenseMap<Register,MachineInstr * > & ImmDefMIs)137173471bf0Spatrick bool PeepholeOptimizer::foldImmediate(
137273471bf0Spatrick     MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs,
137373471bf0Spatrick     DenseMap<Register, MachineInstr *> &ImmDefMIs) {
137409467b48Spatrick   for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
137509467b48Spatrick     MachineOperand &MO = MI.getOperand(i);
137609467b48Spatrick     if (!MO.isReg() || MO.isDef())
137709467b48Spatrick       continue;
137809467b48Spatrick     Register Reg = MO.getReg();
137973471bf0Spatrick     if (!Reg.isVirtual())
138009467b48Spatrick       continue;
138109467b48Spatrick     if (ImmDefRegs.count(Reg) == 0)
138209467b48Spatrick       continue;
138373471bf0Spatrick     DenseMap<Register, MachineInstr *>::iterator II = ImmDefMIs.find(Reg);
138409467b48Spatrick     assert(II != ImmDefMIs.end() && "couldn't find immediate definition");
138509467b48Spatrick     if (TII->FoldImmediate(MI, *II->second, Reg, MRI)) {
138609467b48Spatrick       ++NumImmFold;
138709467b48Spatrick       return true;
138809467b48Spatrick     }
138909467b48Spatrick   }
139009467b48Spatrick   return false;
139109467b48Spatrick }
139209467b48Spatrick 
139309467b48Spatrick // FIXME: This is very simple and misses some cases which should be handled when
139409467b48Spatrick // motivating examples are found.
139509467b48Spatrick //
139609467b48Spatrick // The copy rewriting logic should look at uses as well as defs and be able to
139709467b48Spatrick // eliminate copies across blocks.
139809467b48Spatrick //
139909467b48Spatrick // Later copies that are subregister extracts will also not be eliminated since
140009467b48Spatrick // only the first copy is considered.
140109467b48Spatrick //
140209467b48Spatrick // e.g.
140309467b48Spatrick // %1 = COPY %0
140409467b48Spatrick // %2 = COPY %0:sub1
140509467b48Spatrick //
140609467b48Spatrick // Should replace %2 uses with %1:sub1
foldRedundantCopy(MachineInstr & MI,DenseMap<RegSubRegPair,MachineInstr * > & CopyMIs)140773471bf0Spatrick bool PeepholeOptimizer::foldRedundantCopy(
140873471bf0Spatrick     MachineInstr &MI, DenseMap<RegSubRegPair, MachineInstr *> &CopyMIs) {
140909467b48Spatrick   assert(MI.isCopy() && "expected a COPY machine instruction");
141009467b48Spatrick 
141109467b48Spatrick   Register SrcReg = MI.getOperand(1).getReg();
141273471bf0Spatrick   unsigned SrcSubReg = MI.getOperand(1).getSubReg();
1413*d415bd75Srobert   if (!SrcReg.isVirtual() && !MRI->isConstantPhysReg(SrcReg))
141409467b48Spatrick     return false;
141509467b48Spatrick 
141609467b48Spatrick   Register DstReg = MI.getOperand(0).getReg();
141773471bf0Spatrick   if (!DstReg.isVirtual())
141809467b48Spatrick     return false;
141909467b48Spatrick 
142073471bf0Spatrick   RegSubRegPair SrcPair(SrcReg, SrcSubReg);
142173471bf0Spatrick 
142273471bf0Spatrick   if (CopyMIs.insert(std::make_pair(SrcPair, &MI)).second) {
142309467b48Spatrick     // First copy of this reg seen.
142409467b48Spatrick     return false;
142509467b48Spatrick   }
142609467b48Spatrick 
142773471bf0Spatrick   MachineInstr *PrevCopy = CopyMIs.find(SrcPair)->second;
142809467b48Spatrick 
142973471bf0Spatrick   assert(SrcSubReg == PrevCopy->getOperand(1).getSubReg() &&
143073471bf0Spatrick          "Unexpected mismatching subreg!");
143109467b48Spatrick 
143209467b48Spatrick   Register PrevDstReg = PrevCopy->getOperand(0).getReg();
143309467b48Spatrick 
143409467b48Spatrick   // Only replace if the copy register class is the same.
143509467b48Spatrick   //
143609467b48Spatrick   // TODO: If we have multiple copies to different register classes, we may want
143709467b48Spatrick   // to track multiple copies of the same source register.
143809467b48Spatrick   if (MRI->getRegClass(DstReg) != MRI->getRegClass(PrevDstReg))
143909467b48Spatrick     return false;
144009467b48Spatrick 
144109467b48Spatrick   MRI->replaceRegWith(DstReg, PrevDstReg);
144209467b48Spatrick 
144309467b48Spatrick   // Lifetime of the previous copy has been extended.
144409467b48Spatrick   MRI->clearKillFlags(PrevDstReg);
144509467b48Spatrick   return true;
144609467b48Spatrick }
144709467b48Spatrick 
isNAPhysCopy(Register Reg)144873471bf0Spatrick bool PeepholeOptimizer::isNAPhysCopy(Register Reg) {
144973471bf0Spatrick   return Reg.isPhysical() && !MRI->isAllocatable(Reg);
145009467b48Spatrick }
145109467b48Spatrick 
foldRedundantNAPhysCopy(MachineInstr & MI,DenseMap<Register,MachineInstr * > & NAPhysToVirtMIs)145209467b48Spatrick bool PeepholeOptimizer::foldRedundantNAPhysCopy(
145373471bf0Spatrick     MachineInstr &MI, DenseMap<Register, MachineInstr *> &NAPhysToVirtMIs) {
145409467b48Spatrick   assert(MI.isCopy() && "expected a COPY machine instruction");
145509467b48Spatrick 
145609467b48Spatrick   if (DisableNAPhysCopyOpt)
145709467b48Spatrick     return false;
145809467b48Spatrick 
145909467b48Spatrick   Register DstReg = MI.getOperand(0).getReg();
146009467b48Spatrick   Register SrcReg = MI.getOperand(1).getReg();
1461*d415bd75Srobert   if (isNAPhysCopy(SrcReg) && DstReg.isVirtual()) {
146273471bf0Spatrick     // %vreg = COPY $physreg
146309467b48Spatrick     // Avoid using a datastructure which can track multiple live non-allocatable
146409467b48Spatrick     // phys->virt copies since LLVM doesn't seem to do this.
146509467b48Spatrick     NAPhysToVirtMIs.insert({SrcReg, &MI});
146609467b48Spatrick     return false;
146709467b48Spatrick   }
146809467b48Spatrick 
146973471bf0Spatrick   if (!(SrcReg.isVirtual() && isNAPhysCopy(DstReg)))
147009467b48Spatrick     return false;
147109467b48Spatrick 
147273471bf0Spatrick   // $physreg = COPY %vreg
147309467b48Spatrick   auto PrevCopy = NAPhysToVirtMIs.find(DstReg);
147409467b48Spatrick   if (PrevCopy == NAPhysToVirtMIs.end()) {
147509467b48Spatrick     // We can't remove the copy: there was an intervening clobber of the
147609467b48Spatrick     // non-allocatable physical register after the copy to virtual.
147709467b48Spatrick     LLVM_DEBUG(dbgs() << "NAPhysCopy: intervening clobber forbids erasing "
147809467b48Spatrick                       << MI);
147909467b48Spatrick     return false;
148009467b48Spatrick   }
148109467b48Spatrick 
148209467b48Spatrick   Register PrevDstReg = PrevCopy->second->getOperand(0).getReg();
148309467b48Spatrick   if (PrevDstReg == SrcReg) {
148409467b48Spatrick     // Remove the virt->phys copy: we saw the virtual register definition, and
148509467b48Spatrick     // the non-allocatable physical register's state hasn't changed since then.
148609467b48Spatrick     LLVM_DEBUG(dbgs() << "NAPhysCopy: erasing " << MI);
148709467b48Spatrick     ++NumNAPhysCopies;
148809467b48Spatrick     return true;
148909467b48Spatrick   }
149009467b48Spatrick 
149109467b48Spatrick   // Potential missed optimization opportunity: we saw a different virtual
149209467b48Spatrick   // register get a copy of the non-allocatable physical register, and we only
149309467b48Spatrick   // track one such copy. Avoid getting confused by this new non-allocatable
149409467b48Spatrick   // physical register definition, and remove it from the tracked copies.
149509467b48Spatrick   LLVM_DEBUG(dbgs() << "NAPhysCopy: missed opportunity " << MI);
149609467b48Spatrick   NAPhysToVirtMIs.erase(PrevCopy);
149709467b48Spatrick   return false;
149809467b48Spatrick }
149909467b48Spatrick 
150009467b48Spatrick /// \bried Returns true if \p MO is a virtual register operand.
isVirtualRegisterOperand(MachineOperand & MO)150109467b48Spatrick static bool isVirtualRegisterOperand(MachineOperand &MO) {
150273471bf0Spatrick   return MO.isReg() && MO.getReg().isVirtual();
150309467b48Spatrick }
150409467b48Spatrick 
findTargetRecurrence(Register Reg,const SmallSet<Register,2> & TargetRegs,RecurrenceCycle & RC)150509467b48Spatrick bool PeepholeOptimizer::findTargetRecurrence(
150673471bf0Spatrick     Register Reg, const SmallSet<Register, 2> &TargetRegs,
150709467b48Spatrick     RecurrenceCycle &RC) {
150809467b48Spatrick   // Recurrence found if Reg is in TargetRegs.
150909467b48Spatrick   if (TargetRegs.count(Reg))
151009467b48Spatrick     return true;
151109467b48Spatrick 
151209467b48Spatrick   // TODO: Curerntly, we only allow the last instruction of the recurrence
151309467b48Spatrick   // cycle (the instruction that feeds the PHI instruction) to have more than
151409467b48Spatrick   // one uses to guarantee that commuting operands does not tie registers
151509467b48Spatrick   // with overlapping live range. Once we have actual live range info of
151609467b48Spatrick   // each register, this constraint can be relaxed.
151709467b48Spatrick   if (!MRI->hasOneNonDBGUse(Reg))
151809467b48Spatrick     return false;
151909467b48Spatrick 
152009467b48Spatrick   // Give up if the reccurrence chain length is longer than the limit.
152109467b48Spatrick   if (RC.size() >= MaxRecurrenceChain)
152209467b48Spatrick     return false;
152309467b48Spatrick 
152409467b48Spatrick   MachineInstr &MI = *(MRI->use_instr_nodbg_begin(Reg));
152509467b48Spatrick   unsigned Idx = MI.findRegisterUseOperandIdx(Reg);
152609467b48Spatrick 
152709467b48Spatrick   // Only interested in recurrences whose instructions have only one def, which
152809467b48Spatrick   // is a virtual register.
152909467b48Spatrick   if (MI.getDesc().getNumDefs() != 1)
153009467b48Spatrick     return false;
153109467b48Spatrick 
153209467b48Spatrick   MachineOperand &DefOp = MI.getOperand(0);
153309467b48Spatrick   if (!isVirtualRegisterOperand(DefOp))
153409467b48Spatrick     return false;
153509467b48Spatrick 
153609467b48Spatrick   // Check if def operand of MI is tied to any use operand. We are only
153709467b48Spatrick   // interested in the case that all the instructions in the recurrence chain
153809467b48Spatrick   // have there def operand tied with one of the use operand.
153909467b48Spatrick   unsigned TiedUseIdx;
154009467b48Spatrick   if (!MI.isRegTiedToUseOperand(0, &TiedUseIdx))
154109467b48Spatrick     return false;
154209467b48Spatrick 
154309467b48Spatrick   if (Idx == TiedUseIdx) {
154409467b48Spatrick     RC.push_back(RecurrenceInstr(&MI));
154509467b48Spatrick     return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC);
154609467b48Spatrick   } else {
154709467b48Spatrick     // If Idx is not TiedUseIdx, check if Idx is commutable with TiedUseIdx.
154809467b48Spatrick     unsigned CommIdx = TargetInstrInfo::CommuteAnyOperandIndex;
154909467b48Spatrick     if (TII->findCommutedOpIndices(MI, Idx, CommIdx) && CommIdx == TiedUseIdx) {
155009467b48Spatrick       RC.push_back(RecurrenceInstr(&MI, Idx, CommIdx));
155109467b48Spatrick       return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC);
155209467b48Spatrick     }
155309467b48Spatrick   }
155409467b48Spatrick 
155509467b48Spatrick   return false;
155609467b48Spatrick }
155709467b48Spatrick 
155809467b48Spatrick /// Phi instructions will eventually be lowered to copy instructions.
155909467b48Spatrick /// If phi is in a loop header, a recurrence may formulated around the source
156009467b48Spatrick /// and destination of the phi. For such case commuting operands of the
156109467b48Spatrick /// instructions in the recurrence may enable coalescing of the copy instruction
156209467b48Spatrick /// generated from the phi. For example, if there is a recurrence of
156309467b48Spatrick ///
156409467b48Spatrick /// LoopHeader:
156509467b48Spatrick ///   %1 = phi(%0, %100)
156609467b48Spatrick /// LoopLatch:
156709467b48Spatrick ///   %0<def, tied1> = ADD %2<def, tied0>, %1
156809467b48Spatrick ///
156909467b48Spatrick /// , the fact that %0 and %2 are in the same tied operands set makes
157009467b48Spatrick /// the coalescing of copy instruction generated from the phi in
157109467b48Spatrick /// LoopHeader(i.e. %1 = COPY %0) impossible, because %1 and
157209467b48Spatrick /// %2 have overlapping live range. This introduces additional move
157309467b48Spatrick /// instruction to the final assembly. However, if we commute %2 and
157409467b48Spatrick /// %1 of ADD instruction, the redundant move instruction can be
157509467b48Spatrick /// avoided.
optimizeRecurrence(MachineInstr & PHI)157609467b48Spatrick bool PeepholeOptimizer::optimizeRecurrence(MachineInstr &PHI) {
157773471bf0Spatrick   SmallSet<Register, 2> TargetRegs;
157809467b48Spatrick   for (unsigned Idx = 1; Idx < PHI.getNumOperands(); Idx += 2) {
157909467b48Spatrick     MachineOperand &MO = PHI.getOperand(Idx);
158009467b48Spatrick     assert(isVirtualRegisterOperand(MO) && "Invalid PHI instruction");
158109467b48Spatrick     TargetRegs.insert(MO.getReg());
158209467b48Spatrick   }
158309467b48Spatrick 
158409467b48Spatrick   bool Changed = false;
158509467b48Spatrick   RecurrenceCycle RC;
158609467b48Spatrick   if (findTargetRecurrence(PHI.getOperand(0).getReg(), TargetRegs, RC)) {
158709467b48Spatrick     // Commutes operands of instructions in RC if necessary so that the copy to
158809467b48Spatrick     // be generated from PHI can be coalesced.
158909467b48Spatrick     LLVM_DEBUG(dbgs() << "Optimize recurrence chain from " << PHI);
159009467b48Spatrick     for (auto &RI : RC) {
159109467b48Spatrick       LLVM_DEBUG(dbgs() << "\tInst: " << *(RI.getMI()));
159209467b48Spatrick       auto CP = RI.getCommutePair();
159309467b48Spatrick       if (CP) {
159409467b48Spatrick         Changed = true;
159509467b48Spatrick         TII->commuteInstruction(*(RI.getMI()), false, (*CP).first,
159609467b48Spatrick                                 (*CP).second);
159709467b48Spatrick         LLVM_DEBUG(dbgs() << "\t\tCommuted: " << *(RI.getMI()));
159809467b48Spatrick       }
159909467b48Spatrick     }
160009467b48Spatrick   }
160109467b48Spatrick 
160209467b48Spatrick   return Changed;
160309467b48Spatrick }
160409467b48Spatrick 
runOnMachineFunction(MachineFunction & MF)160509467b48Spatrick bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
160609467b48Spatrick   if (skipFunction(MF.getFunction()))
160709467b48Spatrick     return false;
160809467b48Spatrick 
160909467b48Spatrick   LLVM_DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n");
161009467b48Spatrick   LLVM_DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n');
161109467b48Spatrick 
161209467b48Spatrick   if (DisablePeephole)
161309467b48Spatrick     return false;
161409467b48Spatrick 
161509467b48Spatrick   TII = MF.getSubtarget().getInstrInfo();
161609467b48Spatrick   TRI = MF.getSubtarget().getRegisterInfo();
161709467b48Spatrick   MRI = &MF.getRegInfo();
161809467b48Spatrick   DT  = Aggressive ? &getAnalysis<MachineDominatorTree>() : nullptr;
161909467b48Spatrick   MLI = &getAnalysis<MachineLoopInfo>();
162009467b48Spatrick 
162109467b48Spatrick   bool Changed = false;
162209467b48Spatrick 
162309467b48Spatrick   for (MachineBasicBlock &MBB : MF) {
162409467b48Spatrick     bool SeenMoveImm = false;
162509467b48Spatrick 
162609467b48Spatrick     // During this forward scan, at some point it needs to answer the question
162709467b48Spatrick     // "given a pointer to an MI in the current BB, is it located before or
162809467b48Spatrick     // after the current instruction".
162909467b48Spatrick     // To perform this, the following set keeps track of the MIs already seen
163009467b48Spatrick     // during the scan, if a MI is not in the set, it is assumed to be located
163109467b48Spatrick     // after. Newly created MIs have to be inserted in the set as well.
163209467b48Spatrick     SmallPtrSet<MachineInstr*, 16> LocalMIs;
163373471bf0Spatrick     SmallSet<Register, 4> ImmDefRegs;
163473471bf0Spatrick     DenseMap<Register, MachineInstr *> ImmDefMIs;
163573471bf0Spatrick     SmallSet<Register, 16> FoldAsLoadDefCandidates;
163609467b48Spatrick 
163709467b48Spatrick     // Track when a non-allocatable physical register is copied to a virtual
163809467b48Spatrick     // register so that useless moves can be removed.
163909467b48Spatrick     //
164073471bf0Spatrick     // $physreg is the map index; MI is the last valid `%vreg = COPY $physreg`
164173471bf0Spatrick     // without any intervening re-definition of $physreg.
164273471bf0Spatrick     DenseMap<Register, MachineInstr *> NAPhysToVirtMIs;
164309467b48Spatrick 
1644*d415bd75Srobert     // Set of copies to virtual registers keyed by source register.  Never
1645*d415bd75Srobert     // holds any physreg which requires def tracking.
164673471bf0Spatrick     DenseMap<RegSubRegPair, MachineInstr *> CopySrcMIs;
164709467b48Spatrick 
164809467b48Spatrick     bool IsLoopHeader = MLI->isLoopHeader(&MBB);
164909467b48Spatrick 
165009467b48Spatrick     for (MachineBasicBlock::iterator MII = MBB.begin(), MIE = MBB.end();
165109467b48Spatrick          MII != MIE; ) {
165209467b48Spatrick       MachineInstr *MI = &*MII;
165309467b48Spatrick       // We may be erasing MI below, increment MII now.
165409467b48Spatrick       ++MII;
165509467b48Spatrick       LocalMIs.insert(MI);
165609467b48Spatrick 
165773471bf0Spatrick       // Skip debug instructions. They should not affect this peephole
165873471bf0Spatrick       // optimization.
165909467b48Spatrick       if (MI->isDebugInstr())
166009467b48Spatrick         continue;
166109467b48Spatrick 
166209467b48Spatrick       if (MI->isPosition())
166309467b48Spatrick         continue;
166409467b48Spatrick 
166509467b48Spatrick       if (IsLoopHeader && MI->isPHI()) {
166609467b48Spatrick         if (optimizeRecurrence(*MI)) {
166709467b48Spatrick           Changed = true;
166809467b48Spatrick           continue;
166909467b48Spatrick         }
167009467b48Spatrick       }
167109467b48Spatrick 
167209467b48Spatrick       if (!MI->isCopy()) {
167309467b48Spatrick         for (const MachineOperand &MO : MI->operands()) {
167409467b48Spatrick           // Visit all operands: definitions can be implicit or explicit.
167509467b48Spatrick           if (MO.isReg()) {
167609467b48Spatrick             Register Reg = MO.getReg();
167709467b48Spatrick             if (MO.isDef() && isNAPhysCopy(Reg)) {
167809467b48Spatrick               const auto &Def = NAPhysToVirtMIs.find(Reg);
167909467b48Spatrick               if (Def != NAPhysToVirtMIs.end()) {
168009467b48Spatrick                 // A new definition of the non-allocatable physical register
168109467b48Spatrick                 // invalidates previous copies.
168209467b48Spatrick                 LLVM_DEBUG(dbgs()
168309467b48Spatrick                            << "NAPhysCopy: invalidating because of " << *MI);
168409467b48Spatrick                 NAPhysToVirtMIs.erase(Def);
168509467b48Spatrick               }
168609467b48Spatrick             }
168709467b48Spatrick           } else if (MO.isRegMask()) {
168809467b48Spatrick             const uint32_t *RegMask = MO.getRegMask();
168909467b48Spatrick             for (auto &RegMI : NAPhysToVirtMIs) {
169073471bf0Spatrick               Register Def = RegMI.first;
169109467b48Spatrick               if (MachineOperand::clobbersPhysReg(RegMask, Def)) {
169209467b48Spatrick                 LLVM_DEBUG(dbgs()
169309467b48Spatrick                            << "NAPhysCopy: invalidating because of " << *MI);
169409467b48Spatrick                 NAPhysToVirtMIs.erase(Def);
169509467b48Spatrick               }
169609467b48Spatrick             }
169709467b48Spatrick           }
169809467b48Spatrick         }
169909467b48Spatrick       }
170009467b48Spatrick 
170109467b48Spatrick       if (MI->isImplicitDef() || MI->isKill())
170209467b48Spatrick         continue;
170309467b48Spatrick 
170409467b48Spatrick       if (MI->isInlineAsm() || MI->hasUnmodeledSideEffects()) {
170509467b48Spatrick         // Blow away all non-allocatable physical registers knowledge since we
170609467b48Spatrick         // don't know what's correct anymore.
170709467b48Spatrick         //
170809467b48Spatrick         // FIXME: handle explicit asm clobbers.
170909467b48Spatrick         LLVM_DEBUG(dbgs() << "NAPhysCopy: blowing away all info due to "
171009467b48Spatrick                           << *MI);
171109467b48Spatrick         NAPhysToVirtMIs.clear();
171209467b48Spatrick       }
171309467b48Spatrick 
171409467b48Spatrick       if ((isUncoalescableCopy(*MI) &&
171509467b48Spatrick            optimizeUncoalescableCopy(*MI, LocalMIs)) ||
171609467b48Spatrick           (MI->isCompare() && optimizeCmpInstr(*MI)) ||
171709467b48Spatrick           (MI->isSelect() && optimizeSelect(*MI, LocalMIs))) {
171809467b48Spatrick         // MI is deleted.
171909467b48Spatrick         LocalMIs.erase(MI);
172009467b48Spatrick         Changed = true;
172109467b48Spatrick         continue;
172209467b48Spatrick       }
172309467b48Spatrick 
172409467b48Spatrick       if (MI->isConditionalBranch() && optimizeCondBranch(*MI)) {
172509467b48Spatrick         Changed = true;
172609467b48Spatrick         continue;
172709467b48Spatrick       }
172809467b48Spatrick 
172909467b48Spatrick       if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(*MI)) {
173009467b48Spatrick         // MI is just rewritten.
173109467b48Spatrick         Changed = true;
173209467b48Spatrick         continue;
173309467b48Spatrick       }
173409467b48Spatrick 
173573471bf0Spatrick       if (MI->isCopy() && (foldRedundantCopy(*MI, CopySrcMIs) ||
173609467b48Spatrick                            foldRedundantNAPhysCopy(*MI, NAPhysToVirtMIs))) {
173709467b48Spatrick         LocalMIs.erase(MI);
1738097a140dSpatrick         LLVM_DEBUG(dbgs() << "Deleting redundant copy: " << *MI << "\n");
173909467b48Spatrick         MI->eraseFromParent();
174009467b48Spatrick         Changed = true;
174109467b48Spatrick         continue;
174209467b48Spatrick       }
174309467b48Spatrick 
174409467b48Spatrick       if (isMoveImmediate(*MI, ImmDefRegs, ImmDefMIs)) {
174509467b48Spatrick         SeenMoveImm = true;
174609467b48Spatrick       } else {
174709467b48Spatrick         Changed |= optimizeExtInstr(*MI, MBB, LocalMIs);
174809467b48Spatrick         // optimizeExtInstr might have created new instructions after MI
174909467b48Spatrick         // and before the already incremented MII. Adjust MII so that the
175009467b48Spatrick         // next iteration sees the new instructions.
175109467b48Spatrick         MII = MI;
175209467b48Spatrick         ++MII;
175309467b48Spatrick         if (SeenMoveImm)
175409467b48Spatrick           Changed |= foldImmediate(*MI, ImmDefRegs, ImmDefMIs);
175509467b48Spatrick       }
175609467b48Spatrick 
175709467b48Spatrick       // Check whether MI is a load candidate for folding into a later
175809467b48Spatrick       // instruction. If MI is not a candidate, check whether we can fold an
175909467b48Spatrick       // earlier load into MI.
176009467b48Spatrick       if (!isLoadFoldable(*MI, FoldAsLoadDefCandidates) &&
176109467b48Spatrick           !FoldAsLoadDefCandidates.empty()) {
176209467b48Spatrick 
176309467b48Spatrick         // We visit each operand even after successfully folding a previous
176409467b48Spatrick         // one.  This allows us to fold multiple loads into a single
176509467b48Spatrick         // instruction.  We do assume that optimizeLoadInstr doesn't insert
176609467b48Spatrick         // foldable uses earlier in the argument list.  Since we don't restart
176709467b48Spatrick         // iteration, we'd miss such cases.
176809467b48Spatrick         const MCInstrDesc &MIDesc = MI->getDesc();
176909467b48Spatrick         for (unsigned i = MIDesc.getNumDefs(); i != MI->getNumOperands();
177009467b48Spatrick              ++i) {
177109467b48Spatrick           const MachineOperand &MOp = MI->getOperand(i);
177209467b48Spatrick           if (!MOp.isReg())
177309467b48Spatrick             continue;
177473471bf0Spatrick           Register FoldAsLoadDefReg = MOp.getReg();
177509467b48Spatrick           if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) {
177609467b48Spatrick             // We need to fold load after optimizeCmpInstr, since
177709467b48Spatrick             // optimizeCmpInstr can enable folding by converting SUB to CMP.
177809467b48Spatrick             // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and
177909467b48Spatrick             // we need it for markUsesInDebugValueAsUndef().
178073471bf0Spatrick             Register FoldedReg = FoldAsLoadDefReg;
178109467b48Spatrick             MachineInstr *DefMI = nullptr;
178209467b48Spatrick             if (MachineInstr *FoldMI =
178309467b48Spatrick                     TII->optimizeLoadInstr(*MI, MRI, FoldAsLoadDefReg, DefMI)) {
178409467b48Spatrick               // Update LocalMIs since we replaced MI with FoldMI and deleted
178509467b48Spatrick               // DefMI.
178609467b48Spatrick               LLVM_DEBUG(dbgs() << "Replacing: " << *MI);
178709467b48Spatrick               LLVM_DEBUG(dbgs() << "     With: " << *FoldMI);
178809467b48Spatrick               LocalMIs.erase(MI);
178909467b48Spatrick               LocalMIs.erase(DefMI);
179009467b48Spatrick               LocalMIs.insert(FoldMI);
1791097a140dSpatrick               // Update the call site info.
1792097a140dSpatrick               if (MI->shouldUpdateCallSiteInfo())
179309467b48Spatrick                 MI->getMF()->moveCallSiteInfo(MI, FoldMI);
179409467b48Spatrick               MI->eraseFromParent();
179509467b48Spatrick               DefMI->eraseFromParent();
179609467b48Spatrick               MRI->markUsesInDebugValueAsUndef(FoldedReg);
179709467b48Spatrick               FoldAsLoadDefCandidates.erase(FoldedReg);
179809467b48Spatrick               ++NumLoadFold;
179909467b48Spatrick 
180009467b48Spatrick               // MI is replaced with FoldMI so we can continue trying to fold
180109467b48Spatrick               Changed = true;
180209467b48Spatrick               MI = FoldMI;
180309467b48Spatrick             }
180409467b48Spatrick           }
180509467b48Spatrick         }
180609467b48Spatrick       }
180709467b48Spatrick 
180809467b48Spatrick       // If we run into an instruction we can't fold across, discard
180909467b48Spatrick       // the load candidates.  Note: We might be able to fold *into* this
181009467b48Spatrick       // instruction, so this needs to be after the folding logic.
181109467b48Spatrick       if (MI->isLoadFoldBarrier()) {
181209467b48Spatrick         LLVM_DEBUG(dbgs() << "Encountered load fold barrier on " << *MI);
181309467b48Spatrick         FoldAsLoadDefCandidates.clear();
181409467b48Spatrick       }
181509467b48Spatrick     }
181609467b48Spatrick   }
181709467b48Spatrick 
181809467b48Spatrick   return Changed;
181909467b48Spatrick }
182009467b48Spatrick 
getNextSourceFromCopy()182109467b48Spatrick ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
182209467b48Spatrick   assert(Def->isCopy() && "Invalid definition");
182309467b48Spatrick   // Copy instruction are supposed to be: Def = Src.
182409467b48Spatrick   // If someone breaks this assumption, bad things will happen everywhere.
182509467b48Spatrick   // There may be implicit uses preventing the copy to be moved across
182609467b48Spatrick   // some target specific register definitions
182709467b48Spatrick   assert(Def->getNumOperands() - Def->getNumImplicitOperands() == 2 &&
182809467b48Spatrick          "Invalid number of operands");
182909467b48Spatrick   assert(!Def->hasImplicitDef() && "Only implicit uses are allowed");
183009467b48Spatrick 
183109467b48Spatrick   if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
183209467b48Spatrick     // If we look for a different subreg, it means we want a subreg of src.
183309467b48Spatrick     // Bails as we do not support composing subregs yet.
183409467b48Spatrick     return ValueTrackerResult();
183509467b48Spatrick   // Otherwise, we want the whole source.
183609467b48Spatrick   const MachineOperand &Src = Def->getOperand(1);
183709467b48Spatrick   if (Src.isUndef())
183809467b48Spatrick     return ValueTrackerResult();
183909467b48Spatrick   return ValueTrackerResult(Src.getReg(), Src.getSubReg());
184009467b48Spatrick }
184109467b48Spatrick 
getNextSourceFromBitcast()184209467b48Spatrick ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
184309467b48Spatrick   assert(Def->isBitcast() && "Invalid definition");
184409467b48Spatrick 
184509467b48Spatrick   // Bail if there are effects that a plain copy will not expose.
184609467b48Spatrick   if (Def->mayRaiseFPException() || Def->hasUnmodeledSideEffects())
184709467b48Spatrick     return ValueTrackerResult();
184809467b48Spatrick 
184909467b48Spatrick   // Bitcasts with more than one def are not supported.
185009467b48Spatrick   if (Def->getDesc().getNumDefs() != 1)
185109467b48Spatrick     return ValueTrackerResult();
185209467b48Spatrick   const MachineOperand DefOp = Def->getOperand(DefIdx);
185309467b48Spatrick   if (DefOp.getSubReg() != DefSubReg)
185409467b48Spatrick     // If we look for a different subreg, it means we want a subreg of the src.
185509467b48Spatrick     // Bails as we do not support composing subregs yet.
185609467b48Spatrick     return ValueTrackerResult();
185709467b48Spatrick 
185809467b48Spatrick   unsigned SrcIdx = Def->getNumOperands();
185909467b48Spatrick   for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
186009467b48Spatrick        ++OpIdx) {
186109467b48Spatrick     const MachineOperand &MO = Def->getOperand(OpIdx);
186209467b48Spatrick     if (!MO.isReg() || !MO.getReg())
186309467b48Spatrick       continue;
186409467b48Spatrick     // Ignore dead implicit defs.
186509467b48Spatrick     if (MO.isImplicit() && MO.isDead())
186609467b48Spatrick       continue;
186709467b48Spatrick     assert(!MO.isDef() && "We should have skipped all the definitions by now");
186809467b48Spatrick     if (SrcIdx != EndOpIdx)
186909467b48Spatrick       // Multiple sources?
187009467b48Spatrick       return ValueTrackerResult();
187109467b48Spatrick     SrcIdx = OpIdx;
187209467b48Spatrick   }
187309467b48Spatrick 
187409467b48Spatrick   // In some rare case, Def has no input, SrcIdx is out of bound,
187509467b48Spatrick   // getOperand(SrcIdx) will fail below.
187609467b48Spatrick   if (SrcIdx >= Def->getNumOperands())
187709467b48Spatrick     return ValueTrackerResult();
187809467b48Spatrick 
187909467b48Spatrick   // Stop when any user of the bitcast is a SUBREG_TO_REG, replacing with a COPY
188009467b48Spatrick   // will break the assumed guarantees for the upper bits.
188109467b48Spatrick   for (const MachineInstr &UseMI : MRI.use_nodbg_instructions(DefOp.getReg())) {
188209467b48Spatrick     if (UseMI.isSubregToReg())
188309467b48Spatrick       return ValueTrackerResult();
188409467b48Spatrick   }
188509467b48Spatrick 
188609467b48Spatrick   const MachineOperand &Src = Def->getOperand(SrcIdx);
188709467b48Spatrick   if (Src.isUndef())
188809467b48Spatrick     return ValueTrackerResult();
188909467b48Spatrick   return ValueTrackerResult(Src.getReg(), Src.getSubReg());
189009467b48Spatrick }
189109467b48Spatrick 
getNextSourceFromRegSequence()189209467b48Spatrick ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
189309467b48Spatrick   assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
189409467b48Spatrick          "Invalid definition");
189509467b48Spatrick 
189609467b48Spatrick   if (Def->getOperand(DefIdx).getSubReg())
189709467b48Spatrick     // If we are composing subregs, bail out.
189809467b48Spatrick     // The case we are checking is Def.<subreg> = REG_SEQUENCE.
189909467b48Spatrick     // This should almost never happen as the SSA property is tracked at
190009467b48Spatrick     // the register level (as opposed to the subreg level).
190109467b48Spatrick     // I.e.,
190209467b48Spatrick     // Def.sub0 =
190309467b48Spatrick     // Def.sub1 =
190409467b48Spatrick     // is a valid SSA representation for Def.sub0 and Def.sub1, but not for
190509467b48Spatrick     // Def. Thus, it must not be generated.
190609467b48Spatrick     // However, some code could theoretically generates a single
190709467b48Spatrick     // Def.sub0 (i.e, not defining the other subregs) and we would
190809467b48Spatrick     // have this case.
190909467b48Spatrick     // If we can ascertain (or force) that this never happens, we could
191009467b48Spatrick     // turn that into an assertion.
191109467b48Spatrick     return ValueTrackerResult();
191209467b48Spatrick 
191309467b48Spatrick   if (!TII)
191409467b48Spatrick     // We could handle the REG_SEQUENCE here, but we do not want to
191509467b48Spatrick     // duplicate the code from the generic TII.
191609467b48Spatrick     return ValueTrackerResult();
191709467b48Spatrick 
191809467b48Spatrick   SmallVector<RegSubRegPairAndIdx, 8> RegSeqInputRegs;
191909467b48Spatrick   if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs))
192009467b48Spatrick     return ValueTrackerResult();
192109467b48Spatrick 
192209467b48Spatrick   // We are looking at:
192309467b48Spatrick   // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
192409467b48Spatrick   // Check if one of the operand defines the subreg we are interested in.
192509467b48Spatrick   for (const RegSubRegPairAndIdx &RegSeqInput : RegSeqInputRegs) {
192609467b48Spatrick     if (RegSeqInput.SubIdx == DefSubReg)
192709467b48Spatrick       return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
192809467b48Spatrick   }
192909467b48Spatrick 
193009467b48Spatrick   // If the subreg we are tracking is super-defined by another subreg,
193109467b48Spatrick   // we could follow this value. However, this would require to compose
193209467b48Spatrick   // the subreg and we do not do that for now.
193309467b48Spatrick   return ValueTrackerResult();
193409467b48Spatrick }
193509467b48Spatrick 
getNextSourceFromInsertSubreg()193609467b48Spatrick ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
193709467b48Spatrick   assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
193809467b48Spatrick          "Invalid definition");
193909467b48Spatrick 
194009467b48Spatrick   if (Def->getOperand(DefIdx).getSubReg())
194109467b48Spatrick     // If we are composing subreg, bail out.
194209467b48Spatrick     // Same remark as getNextSourceFromRegSequence.
194309467b48Spatrick     // I.e., this may be turned into an assert.
194409467b48Spatrick     return ValueTrackerResult();
194509467b48Spatrick 
194609467b48Spatrick   if (!TII)
194709467b48Spatrick     // We could handle the REG_SEQUENCE here, but we do not want to
194809467b48Spatrick     // duplicate the code from the generic TII.
194909467b48Spatrick     return ValueTrackerResult();
195009467b48Spatrick 
195109467b48Spatrick   RegSubRegPair BaseReg;
195209467b48Spatrick   RegSubRegPairAndIdx InsertedReg;
195309467b48Spatrick   if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg))
195409467b48Spatrick     return ValueTrackerResult();
195509467b48Spatrick 
195609467b48Spatrick   // We are looking at:
195709467b48Spatrick   // Def = INSERT_SUBREG v0, v1, sub1
195809467b48Spatrick   // There are two cases:
195909467b48Spatrick   // 1. DefSubReg == sub1, get v1.
196009467b48Spatrick   // 2. DefSubReg != sub1, the value may be available through v0.
196109467b48Spatrick 
196209467b48Spatrick   // #1 Check if the inserted register matches the required sub index.
196309467b48Spatrick   if (InsertedReg.SubIdx == DefSubReg) {
196409467b48Spatrick     return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg);
196509467b48Spatrick   }
196609467b48Spatrick   // #2 Otherwise, if the sub register we are looking for is not partial
196709467b48Spatrick   // defined by the inserted element, we can look through the main
196809467b48Spatrick   // register (v0).
196909467b48Spatrick   const MachineOperand &MODef = Def->getOperand(DefIdx);
197009467b48Spatrick   // If the result register (Def) and the base register (v0) do not
197109467b48Spatrick   // have the same register class or if we have to compose
197209467b48Spatrick   // subregisters, bail out.
197309467b48Spatrick   if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) ||
197409467b48Spatrick       BaseReg.SubReg)
197509467b48Spatrick     return ValueTrackerResult();
197609467b48Spatrick 
197709467b48Spatrick   // Get the TRI and check if the inserted sub-register overlaps with the
197809467b48Spatrick   // sub-register we are tracking.
197909467b48Spatrick   const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
198009467b48Spatrick   if (!TRI ||
198109467b48Spatrick       !(TRI->getSubRegIndexLaneMask(DefSubReg) &
198209467b48Spatrick         TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)).none())
198309467b48Spatrick     return ValueTrackerResult();
198409467b48Spatrick   // At this point, the value is available in v0 via the same subreg
198509467b48Spatrick   // we used for Def.
198609467b48Spatrick   return ValueTrackerResult(BaseReg.Reg, DefSubReg);
198709467b48Spatrick }
198809467b48Spatrick 
getNextSourceFromExtractSubreg()198909467b48Spatrick ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
199009467b48Spatrick   assert((Def->isExtractSubreg() ||
199109467b48Spatrick           Def->isExtractSubregLike()) && "Invalid definition");
199209467b48Spatrick   // We are looking at:
199309467b48Spatrick   // Def = EXTRACT_SUBREG v0, sub0
199409467b48Spatrick 
199509467b48Spatrick   // Bail if we have to compose sub registers.
199609467b48Spatrick   // Indeed, if DefSubReg != 0, we would have to compose it with sub0.
199709467b48Spatrick   if (DefSubReg)
199809467b48Spatrick     return ValueTrackerResult();
199909467b48Spatrick 
200009467b48Spatrick   if (!TII)
200109467b48Spatrick     // We could handle the EXTRACT_SUBREG here, but we do not want to
200209467b48Spatrick     // duplicate the code from the generic TII.
200309467b48Spatrick     return ValueTrackerResult();
200409467b48Spatrick 
200509467b48Spatrick   RegSubRegPairAndIdx ExtractSubregInputReg;
200609467b48Spatrick   if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg))
200709467b48Spatrick     return ValueTrackerResult();
200809467b48Spatrick 
200909467b48Spatrick   // Bail if we have to compose sub registers.
201009467b48Spatrick   // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0.
201109467b48Spatrick   if (ExtractSubregInputReg.SubReg)
201209467b48Spatrick     return ValueTrackerResult();
201309467b48Spatrick   // Otherwise, the value is available in the v0.sub0.
201409467b48Spatrick   return ValueTrackerResult(ExtractSubregInputReg.Reg,
201509467b48Spatrick                             ExtractSubregInputReg.SubIdx);
201609467b48Spatrick }
201709467b48Spatrick 
getNextSourceFromSubregToReg()201809467b48Spatrick ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
201909467b48Spatrick   assert(Def->isSubregToReg() && "Invalid definition");
202009467b48Spatrick   // We are looking at:
202109467b48Spatrick   // Def = SUBREG_TO_REG Imm, v0, sub0
202209467b48Spatrick 
202309467b48Spatrick   // Bail if we have to compose sub registers.
202409467b48Spatrick   // If DefSubReg != sub0, we would have to check that all the bits
202509467b48Spatrick   // we track are included in sub0 and if yes, we would have to
202609467b48Spatrick   // determine the right subreg in v0.
202709467b48Spatrick   if (DefSubReg != Def->getOperand(3).getImm())
202809467b48Spatrick     return ValueTrackerResult();
202909467b48Spatrick   // Bail if we have to compose sub registers.
203009467b48Spatrick   // Likewise, if v0.subreg != 0, we would have to compose it with sub0.
203109467b48Spatrick   if (Def->getOperand(2).getSubReg())
203209467b48Spatrick     return ValueTrackerResult();
203309467b48Spatrick 
203409467b48Spatrick   return ValueTrackerResult(Def->getOperand(2).getReg(),
203509467b48Spatrick                             Def->getOperand(3).getImm());
203609467b48Spatrick }
203709467b48Spatrick 
203809467b48Spatrick /// Explore each PHI incoming operand and return its sources.
getNextSourceFromPHI()203909467b48Spatrick ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
204009467b48Spatrick   assert(Def->isPHI() && "Invalid definition");
204109467b48Spatrick   ValueTrackerResult Res;
204209467b48Spatrick 
204309467b48Spatrick   // If we look for a different subreg, bail as we do not support composing
204409467b48Spatrick   // subregs yet.
204509467b48Spatrick   if (Def->getOperand(0).getSubReg() != DefSubReg)
204609467b48Spatrick     return ValueTrackerResult();
204709467b48Spatrick 
204809467b48Spatrick   // Return all register sources for PHI instructions.
204909467b48Spatrick   for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
205009467b48Spatrick     const MachineOperand &MO = Def->getOperand(i);
205109467b48Spatrick     assert(MO.isReg() && "Invalid PHI instruction");
205209467b48Spatrick     // We have no code to deal with undef operands. They shouldn't happen in
205309467b48Spatrick     // normal programs anyway.
205409467b48Spatrick     if (MO.isUndef())
205509467b48Spatrick       return ValueTrackerResult();
205609467b48Spatrick     Res.addSource(MO.getReg(), MO.getSubReg());
205709467b48Spatrick   }
205809467b48Spatrick 
205909467b48Spatrick   return Res;
206009467b48Spatrick }
206109467b48Spatrick 
getNextSourceImpl()206209467b48Spatrick ValueTrackerResult ValueTracker::getNextSourceImpl() {
206309467b48Spatrick   assert(Def && "This method needs a valid definition");
206409467b48Spatrick 
206509467b48Spatrick   assert(((Def->getOperand(DefIdx).isDef() &&
206609467b48Spatrick            (DefIdx < Def->getDesc().getNumDefs() ||
206709467b48Spatrick             Def->getDesc().isVariadic())) ||
206809467b48Spatrick           Def->getOperand(DefIdx).isImplicit()) &&
206909467b48Spatrick          "Invalid DefIdx");
207009467b48Spatrick   if (Def->isCopy())
207109467b48Spatrick     return getNextSourceFromCopy();
207209467b48Spatrick   if (Def->isBitcast())
207309467b48Spatrick     return getNextSourceFromBitcast();
207409467b48Spatrick   // All the remaining cases involve "complex" instructions.
207509467b48Spatrick   // Bail if we did not ask for the advanced tracking.
207609467b48Spatrick   if (DisableAdvCopyOpt)
207709467b48Spatrick     return ValueTrackerResult();
207809467b48Spatrick   if (Def->isRegSequence() || Def->isRegSequenceLike())
207909467b48Spatrick     return getNextSourceFromRegSequence();
208009467b48Spatrick   if (Def->isInsertSubreg() || Def->isInsertSubregLike())
208109467b48Spatrick     return getNextSourceFromInsertSubreg();
208209467b48Spatrick   if (Def->isExtractSubreg() || Def->isExtractSubregLike())
208309467b48Spatrick     return getNextSourceFromExtractSubreg();
208409467b48Spatrick   if (Def->isSubregToReg())
208509467b48Spatrick     return getNextSourceFromSubregToReg();
208609467b48Spatrick   if (Def->isPHI())
208709467b48Spatrick     return getNextSourceFromPHI();
208809467b48Spatrick   return ValueTrackerResult();
208909467b48Spatrick }
209009467b48Spatrick 
getNextSource()209109467b48Spatrick ValueTrackerResult ValueTracker::getNextSource() {
209209467b48Spatrick   // If we reach a point where we cannot move up in the use-def chain,
209309467b48Spatrick   // there is nothing we can get.
209409467b48Spatrick   if (!Def)
209509467b48Spatrick     return ValueTrackerResult();
209609467b48Spatrick 
209709467b48Spatrick   ValueTrackerResult Res = getNextSourceImpl();
209809467b48Spatrick   if (Res.isValid()) {
209909467b48Spatrick     // Update definition, definition index, and subregister for the
210009467b48Spatrick     // next call of getNextSource.
210109467b48Spatrick     // Update the current register.
210209467b48Spatrick     bool OneRegSrc = Res.getNumSources() == 1;
210309467b48Spatrick     if (OneRegSrc)
210409467b48Spatrick       Reg = Res.getSrcReg(0);
210509467b48Spatrick     // Update the result before moving up in the use-def chain
210609467b48Spatrick     // with the instruction containing the last found sources.
210709467b48Spatrick     Res.setInst(Def);
210809467b48Spatrick 
210909467b48Spatrick     // If we can still move up in the use-def chain, move to the next
211009467b48Spatrick     // definition.
2111*d415bd75Srobert     if (!Reg.isPhysical() && OneRegSrc) {
211209467b48Spatrick       MachineRegisterInfo::def_iterator DI = MRI.def_begin(Reg);
211309467b48Spatrick       if (DI != MRI.def_end()) {
211409467b48Spatrick         Def = DI->getParent();
211509467b48Spatrick         DefIdx = DI.getOperandNo();
211609467b48Spatrick         DefSubReg = Res.getSrcSubReg(0);
211709467b48Spatrick       } else {
211809467b48Spatrick         Def = nullptr;
211909467b48Spatrick       }
212009467b48Spatrick       return Res;
212109467b48Spatrick     }
212209467b48Spatrick   }
212309467b48Spatrick   // If we end up here, this means we will not be able to find another source
212409467b48Spatrick   // for the next iteration. Make sure any new call to getNextSource bails out
212509467b48Spatrick   // early by cutting the use-def chain.
212609467b48Spatrick   Def = nullptr;
212709467b48Spatrick   return Res;
212809467b48Spatrick }
2129