xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp (revision 81ad626541db97eb356e2c1d4a20eb2a26a766ab)
10b57cec5SDimitry Andric //===-- lib/CodeGen/GlobalISel/GICombinerHelper.cpp -----------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric #include "llvm/CodeGen/GlobalISel/CombinerHelper.h"
9fe6060f1SDimitry Andric #include "llvm/ADT/SetVector.h"
10fe6060f1SDimitry Andric #include "llvm/ADT/SmallBitVector.h"
110b57cec5SDimitry Andric #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
128bcb0991SDimitry Andric #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
13fe6060f1SDimitry Andric #include "llvm/CodeGen/GlobalISel/GenericMachineInstrs.h"
14349cc55cSDimitry Andric #include "llvm/CodeGen/GlobalISel/LegalizerHelper.h"
155ffd83dbSDimitry Andric #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
165ffd83dbSDimitry Andric #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
170b57cec5SDimitry Andric #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
180b57cec5SDimitry Andric #include "llvm/CodeGen/GlobalISel/Utils.h"
19fe6060f1SDimitry Andric #include "llvm/CodeGen/LowLevelType.h"
20fe6060f1SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
218bcb0991SDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
220b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
23e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
25*81ad6265SDimitry Andric #include "llvm/CodeGen/RegisterBankInfo.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
278bcb0991SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
28fe6060f1SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
29349cc55cSDimitry Andric #include "llvm/IR/DataLayout.h"
30349cc55cSDimitry Andric #include "llvm/Support/Casting.h"
31349cc55cSDimitry Andric #include "llvm/Support/DivisionByConstantInfo.h"
325ffd83dbSDimitry Andric #include "llvm/Support/MathExtras.h"
33*81ad6265SDimitry Andric #include "llvm/Target/TargetMachine.h"
34fe6060f1SDimitry Andric #include <tuple>
350b57cec5SDimitry Andric 
360b57cec5SDimitry Andric #define DEBUG_TYPE "gi-combiner"
370b57cec5SDimitry Andric 
380b57cec5SDimitry Andric using namespace llvm;
395ffd83dbSDimitry Andric using namespace MIPatternMatch;
400b57cec5SDimitry Andric 
418bcb0991SDimitry Andric // Option to allow testing of the combiner while no targets know about indexed
428bcb0991SDimitry Andric // addressing.
438bcb0991SDimitry Andric static cl::opt<bool>
448bcb0991SDimitry Andric     ForceLegalIndexing("force-legal-indexing", cl::Hidden, cl::init(false),
458bcb0991SDimitry Andric                        cl::desc("Force all indexed operations to be "
468bcb0991SDimitry Andric                                 "legal for the GlobalISel combiner"));
478bcb0991SDimitry Andric 
480b57cec5SDimitry Andric CombinerHelper::CombinerHelper(GISelChangeObserver &Observer,
498bcb0991SDimitry Andric                                MachineIRBuilder &B, GISelKnownBits *KB,
505ffd83dbSDimitry Andric                                MachineDominatorTree *MDT,
515ffd83dbSDimitry Andric                                const LegalizerInfo *LI)
52349cc55cSDimitry Andric     : Builder(B), MRI(Builder.getMF().getRegInfo()), Observer(Observer), KB(KB),
53349cc55cSDimitry Andric       MDT(MDT), LI(LI), RBI(Builder.getMF().getSubtarget().getRegBankInfo()),
54349cc55cSDimitry Andric       TRI(Builder.getMF().getSubtarget().getRegisterInfo()) {
558bcb0991SDimitry Andric   (void)this->KB;
568bcb0991SDimitry Andric }
570b57cec5SDimitry Andric 
58e8d8bef9SDimitry Andric const TargetLowering &CombinerHelper::getTargetLowering() const {
59e8d8bef9SDimitry Andric   return *Builder.getMF().getSubtarget().getTargetLowering();
60e8d8bef9SDimitry Andric }
61e8d8bef9SDimitry Andric 
62e8d8bef9SDimitry Andric /// \returns The little endian in-memory byte position of byte \p I in a
63e8d8bef9SDimitry Andric /// \p ByteWidth bytes wide type.
64e8d8bef9SDimitry Andric ///
65e8d8bef9SDimitry Andric /// E.g. Given a 4-byte type x, x[0] -> byte 0
66e8d8bef9SDimitry Andric static unsigned littleEndianByteAt(const unsigned ByteWidth, const unsigned I) {
67e8d8bef9SDimitry Andric   assert(I < ByteWidth && "I must be in [0, ByteWidth)");
68e8d8bef9SDimitry Andric   return I;
69e8d8bef9SDimitry Andric }
70e8d8bef9SDimitry Andric 
71349cc55cSDimitry Andric /// Determines the LogBase2 value for a non-null input value using the
72349cc55cSDimitry Andric /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
73349cc55cSDimitry Andric static Register buildLogBase2(Register V, MachineIRBuilder &MIB) {
74349cc55cSDimitry Andric   auto &MRI = *MIB.getMRI();
75349cc55cSDimitry Andric   LLT Ty = MRI.getType(V);
76349cc55cSDimitry Andric   auto Ctlz = MIB.buildCTLZ(Ty, V);
77349cc55cSDimitry Andric   auto Base = MIB.buildConstant(Ty, Ty.getScalarSizeInBits() - 1);
78349cc55cSDimitry Andric   return MIB.buildSub(Ty, Base, Ctlz).getReg(0);
79349cc55cSDimitry Andric }
80349cc55cSDimitry Andric 
81e8d8bef9SDimitry Andric /// \returns The big endian in-memory byte position of byte \p I in a
82e8d8bef9SDimitry Andric /// \p ByteWidth bytes wide type.
83e8d8bef9SDimitry Andric ///
84e8d8bef9SDimitry Andric /// E.g. Given a 4-byte type x, x[0] -> byte 3
85e8d8bef9SDimitry Andric static unsigned bigEndianByteAt(const unsigned ByteWidth, const unsigned I) {
86e8d8bef9SDimitry Andric   assert(I < ByteWidth && "I must be in [0, ByteWidth)");
87e8d8bef9SDimitry Andric   return ByteWidth - I - 1;
88e8d8bef9SDimitry Andric }
89e8d8bef9SDimitry Andric 
90e8d8bef9SDimitry Andric /// Given a map from byte offsets in memory to indices in a load/store,
91e8d8bef9SDimitry Andric /// determine if that map corresponds to a little or big endian byte pattern.
92e8d8bef9SDimitry Andric ///
93e8d8bef9SDimitry Andric /// \param MemOffset2Idx maps memory offsets to address offsets.
94e8d8bef9SDimitry Andric /// \param LowestIdx is the lowest index in \p MemOffset2Idx.
95e8d8bef9SDimitry Andric ///
96e8d8bef9SDimitry Andric /// \returns true if the map corresponds to a big endian byte pattern, false
97e8d8bef9SDimitry Andric /// if it corresponds to a little endian byte pattern, and None otherwise.
98e8d8bef9SDimitry Andric ///
99e8d8bef9SDimitry Andric /// E.g. given a 32-bit type x, and x[AddrOffset], the in-memory byte patterns
100e8d8bef9SDimitry Andric /// are as follows:
101e8d8bef9SDimitry Andric ///
102e8d8bef9SDimitry Andric /// AddrOffset   Little endian    Big endian
103e8d8bef9SDimitry Andric /// 0            0                3
104e8d8bef9SDimitry Andric /// 1            1                2
105e8d8bef9SDimitry Andric /// 2            2                1
106e8d8bef9SDimitry Andric /// 3            3                0
107e8d8bef9SDimitry Andric static Optional<bool>
108e8d8bef9SDimitry Andric isBigEndian(const SmallDenseMap<int64_t, int64_t, 8> &MemOffset2Idx,
109e8d8bef9SDimitry Andric             int64_t LowestIdx) {
110e8d8bef9SDimitry Andric   // Need at least two byte positions to decide on endianness.
111e8d8bef9SDimitry Andric   unsigned Width = MemOffset2Idx.size();
112e8d8bef9SDimitry Andric   if (Width < 2)
113e8d8bef9SDimitry Andric     return None;
114e8d8bef9SDimitry Andric   bool BigEndian = true, LittleEndian = true;
115e8d8bef9SDimitry Andric   for (unsigned MemOffset = 0; MemOffset < Width; ++ MemOffset) {
116e8d8bef9SDimitry Andric     auto MemOffsetAndIdx = MemOffset2Idx.find(MemOffset);
117e8d8bef9SDimitry Andric     if (MemOffsetAndIdx == MemOffset2Idx.end())
118e8d8bef9SDimitry Andric       return None;
119e8d8bef9SDimitry Andric     const int64_t Idx = MemOffsetAndIdx->second - LowestIdx;
120e8d8bef9SDimitry Andric     assert(Idx >= 0 && "Expected non-negative byte offset?");
121e8d8bef9SDimitry Andric     LittleEndian &= Idx == littleEndianByteAt(Width, MemOffset);
122e8d8bef9SDimitry Andric     BigEndian &= Idx == bigEndianByteAt(Width, MemOffset);
123e8d8bef9SDimitry Andric     if (!BigEndian && !LittleEndian)
124e8d8bef9SDimitry Andric       return None;
125e8d8bef9SDimitry Andric   }
126e8d8bef9SDimitry Andric 
127e8d8bef9SDimitry Andric   assert((BigEndian != LittleEndian) &&
128e8d8bef9SDimitry Andric          "Pattern cannot be both big and little endian!");
129e8d8bef9SDimitry Andric   return BigEndian;
130e8d8bef9SDimitry Andric }
131e8d8bef9SDimitry Andric 
132*81ad6265SDimitry Andric bool CombinerHelper::isPreLegalize() const { return !LI; }
133*81ad6265SDimitry Andric 
134*81ad6265SDimitry Andric bool CombinerHelper::isLegal(const LegalityQuery &Query) const {
135*81ad6265SDimitry Andric   assert(LI && "Must have LegalizerInfo to query isLegal!");
136*81ad6265SDimitry Andric   return LI->getAction(Query).Action == LegalizeActions::Legal;
137*81ad6265SDimitry Andric }
138*81ad6265SDimitry Andric 
139e8d8bef9SDimitry Andric bool CombinerHelper::isLegalOrBeforeLegalizer(
140e8d8bef9SDimitry Andric     const LegalityQuery &Query) const {
141*81ad6265SDimitry Andric   return isPreLegalize() || isLegal(Query);
142*81ad6265SDimitry Andric }
143*81ad6265SDimitry Andric 
144*81ad6265SDimitry Andric bool CombinerHelper::isConstantLegalOrBeforeLegalizer(const LLT Ty) const {
145*81ad6265SDimitry Andric   if (!Ty.isVector())
146*81ad6265SDimitry Andric     return isLegalOrBeforeLegalizer({TargetOpcode::G_CONSTANT, {Ty}});
147*81ad6265SDimitry Andric   // Vector constants are represented as a G_BUILD_VECTOR of scalar G_CONSTANTs.
148*81ad6265SDimitry Andric   if (isPreLegalize())
149*81ad6265SDimitry Andric     return true;
150*81ad6265SDimitry Andric   LLT EltTy = Ty.getElementType();
151*81ad6265SDimitry Andric   return isLegal({TargetOpcode::G_BUILD_VECTOR, {Ty, EltTy}}) &&
152*81ad6265SDimitry Andric          isLegal({TargetOpcode::G_CONSTANT, {EltTy}});
153e8d8bef9SDimitry Andric }
154e8d8bef9SDimitry Andric 
1550b57cec5SDimitry Andric void CombinerHelper::replaceRegWith(MachineRegisterInfo &MRI, Register FromReg,
1560b57cec5SDimitry Andric                                     Register ToReg) const {
1570b57cec5SDimitry Andric   Observer.changingAllUsesOfReg(MRI, FromReg);
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric   if (MRI.constrainRegAttrs(ToReg, FromReg))
1600b57cec5SDimitry Andric     MRI.replaceRegWith(FromReg, ToReg);
1610b57cec5SDimitry Andric   else
1620b57cec5SDimitry Andric     Builder.buildCopy(ToReg, FromReg);
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric   Observer.finishedChangingAllUsesOfReg();
1650b57cec5SDimitry Andric }
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric void CombinerHelper::replaceRegOpWith(MachineRegisterInfo &MRI,
1680b57cec5SDimitry Andric                                       MachineOperand &FromRegOp,
1690b57cec5SDimitry Andric                                       Register ToReg) const {
1700b57cec5SDimitry Andric   assert(FromRegOp.getParent() && "Expected an operand in an MI");
1710b57cec5SDimitry Andric   Observer.changingInstr(*FromRegOp.getParent());
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric   FromRegOp.setReg(ToReg);
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric   Observer.changedInstr(*FromRegOp.getParent());
1760b57cec5SDimitry Andric }
1770b57cec5SDimitry Andric 
178349cc55cSDimitry Andric void CombinerHelper::replaceOpcodeWith(MachineInstr &FromMI,
179349cc55cSDimitry Andric                                        unsigned ToOpcode) const {
180349cc55cSDimitry Andric   Observer.changingInstr(FromMI);
181349cc55cSDimitry Andric 
182349cc55cSDimitry Andric   FromMI.setDesc(Builder.getTII().get(ToOpcode));
183349cc55cSDimitry Andric 
184349cc55cSDimitry Andric   Observer.changedInstr(FromMI);
185349cc55cSDimitry Andric }
186349cc55cSDimitry Andric 
187349cc55cSDimitry Andric const RegisterBank *CombinerHelper::getRegBank(Register Reg) const {
188349cc55cSDimitry Andric   return RBI->getRegBank(Reg, MRI, *TRI);
189349cc55cSDimitry Andric }
190349cc55cSDimitry Andric 
191349cc55cSDimitry Andric void CombinerHelper::setRegBank(Register Reg, const RegisterBank *RegBank) {
192349cc55cSDimitry Andric   if (RegBank)
193349cc55cSDimitry Andric     MRI.setRegBank(Reg, *RegBank);
194349cc55cSDimitry Andric }
195349cc55cSDimitry Andric 
1960b57cec5SDimitry Andric bool CombinerHelper::tryCombineCopy(MachineInstr &MI) {
1970b57cec5SDimitry Andric   if (matchCombineCopy(MI)) {
1980b57cec5SDimitry Andric     applyCombineCopy(MI);
1990b57cec5SDimitry Andric     return true;
2000b57cec5SDimitry Andric   }
2010b57cec5SDimitry Andric   return false;
2020b57cec5SDimitry Andric }
2030b57cec5SDimitry Andric bool CombinerHelper::matchCombineCopy(MachineInstr &MI) {
2040b57cec5SDimitry Andric   if (MI.getOpcode() != TargetOpcode::COPY)
2050b57cec5SDimitry Andric     return false;
2068bcb0991SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2078bcb0991SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2085ffd83dbSDimitry Andric   return canReplaceReg(DstReg, SrcReg, MRI);
2090b57cec5SDimitry Andric }
2100b57cec5SDimitry Andric void CombinerHelper::applyCombineCopy(MachineInstr &MI) {
2118bcb0991SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2128bcb0991SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2130b57cec5SDimitry Andric   MI.eraseFromParent();
2140b57cec5SDimitry Andric   replaceRegWith(MRI, DstReg, SrcReg);
2150b57cec5SDimitry Andric }
2160b57cec5SDimitry Andric 
2178bcb0991SDimitry Andric bool CombinerHelper::tryCombineConcatVectors(MachineInstr &MI) {
2188bcb0991SDimitry Andric   bool IsUndef = false;
2198bcb0991SDimitry Andric   SmallVector<Register, 4> Ops;
2208bcb0991SDimitry Andric   if (matchCombineConcatVectors(MI, IsUndef, Ops)) {
2218bcb0991SDimitry Andric     applyCombineConcatVectors(MI, IsUndef, Ops);
2228bcb0991SDimitry Andric     return true;
2238bcb0991SDimitry Andric   }
2248bcb0991SDimitry Andric   return false;
2258bcb0991SDimitry Andric }
2268bcb0991SDimitry Andric 
2278bcb0991SDimitry Andric bool CombinerHelper::matchCombineConcatVectors(MachineInstr &MI, bool &IsUndef,
2288bcb0991SDimitry Andric                                                SmallVectorImpl<Register> &Ops) {
2298bcb0991SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_CONCAT_VECTORS &&
2308bcb0991SDimitry Andric          "Invalid instruction");
2318bcb0991SDimitry Andric   IsUndef = true;
2328bcb0991SDimitry Andric   MachineInstr *Undef = nullptr;
2338bcb0991SDimitry Andric 
2348bcb0991SDimitry Andric   // Walk over all the operands of concat vectors and check if they are
2358bcb0991SDimitry Andric   // build_vector themselves or undef.
2368bcb0991SDimitry Andric   // Then collect their operands in Ops.
237480093f4SDimitry Andric   for (const MachineOperand &MO : MI.uses()) {
2388bcb0991SDimitry Andric     Register Reg = MO.getReg();
2398bcb0991SDimitry Andric     MachineInstr *Def = MRI.getVRegDef(Reg);
2408bcb0991SDimitry Andric     assert(Def && "Operand not defined");
2418bcb0991SDimitry Andric     switch (Def->getOpcode()) {
2428bcb0991SDimitry Andric     case TargetOpcode::G_BUILD_VECTOR:
2438bcb0991SDimitry Andric       IsUndef = false;
2448bcb0991SDimitry Andric       // Remember the operands of the build_vector to fold
2458bcb0991SDimitry Andric       // them into the yet-to-build flattened concat vectors.
246480093f4SDimitry Andric       for (const MachineOperand &BuildVecMO : Def->uses())
2478bcb0991SDimitry Andric         Ops.push_back(BuildVecMO.getReg());
2488bcb0991SDimitry Andric       break;
2498bcb0991SDimitry Andric     case TargetOpcode::G_IMPLICIT_DEF: {
2508bcb0991SDimitry Andric       LLT OpType = MRI.getType(Reg);
2518bcb0991SDimitry Andric       // Keep one undef value for all the undef operands.
2528bcb0991SDimitry Andric       if (!Undef) {
2538bcb0991SDimitry Andric         Builder.setInsertPt(*MI.getParent(), MI);
2548bcb0991SDimitry Andric         Undef = Builder.buildUndef(OpType.getScalarType());
2558bcb0991SDimitry Andric       }
2568bcb0991SDimitry Andric       assert(MRI.getType(Undef->getOperand(0).getReg()) ==
2578bcb0991SDimitry Andric                  OpType.getScalarType() &&
2588bcb0991SDimitry Andric              "All undefs should have the same type");
2598bcb0991SDimitry Andric       // Break the undef vector in as many scalar elements as needed
2608bcb0991SDimitry Andric       // for the flattening.
2618bcb0991SDimitry Andric       for (unsigned EltIdx = 0, EltEnd = OpType.getNumElements();
2628bcb0991SDimitry Andric            EltIdx != EltEnd; ++EltIdx)
2638bcb0991SDimitry Andric         Ops.push_back(Undef->getOperand(0).getReg());
2648bcb0991SDimitry Andric       break;
2658bcb0991SDimitry Andric     }
2668bcb0991SDimitry Andric     default:
2678bcb0991SDimitry Andric       return false;
2688bcb0991SDimitry Andric     }
2698bcb0991SDimitry Andric   }
2708bcb0991SDimitry Andric   return true;
2718bcb0991SDimitry Andric }
2728bcb0991SDimitry Andric void CombinerHelper::applyCombineConcatVectors(
2738bcb0991SDimitry Andric     MachineInstr &MI, bool IsUndef, const ArrayRef<Register> Ops) {
2748bcb0991SDimitry Andric   // We determined that the concat_vectors can be flatten.
2758bcb0991SDimitry Andric   // Generate the flattened build_vector.
2768bcb0991SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2778bcb0991SDimitry Andric   Builder.setInsertPt(*MI.getParent(), MI);
2788bcb0991SDimitry Andric   Register NewDstReg = MRI.cloneVirtualRegister(DstReg);
2798bcb0991SDimitry Andric 
2808bcb0991SDimitry Andric   // Note: IsUndef is sort of redundant. We could have determine it by
2818bcb0991SDimitry Andric   // checking that at all Ops are undef.  Alternatively, we could have
2828bcb0991SDimitry Andric   // generate a build_vector of undefs and rely on another combine to
2838bcb0991SDimitry Andric   // clean that up.  For now, given we already gather this information
2848bcb0991SDimitry Andric   // in tryCombineConcatVectors, just save compile time and issue the
2858bcb0991SDimitry Andric   // right thing.
2868bcb0991SDimitry Andric   if (IsUndef)
2878bcb0991SDimitry Andric     Builder.buildUndef(NewDstReg);
2888bcb0991SDimitry Andric   else
2898bcb0991SDimitry Andric     Builder.buildBuildVector(NewDstReg, Ops);
2908bcb0991SDimitry Andric   MI.eraseFromParent();
2918bcb0991SDimitry Andric   replaceRegWith(MRI, DstReg, NewDstReg);
2928bcb0991SDimitry Andric }
2938bcb0991SDimitry Andric 
2948bcb0991SDimitry Andric bool CombinerHelper::tryCombineShuffleVector(MachineInstr &MI) {
2958bcb0991SDimitry Andric   SmallVector<Register, 4> Ops;
2968bcb0991SDimitry Andric   if (matchCombineShuffleVector(MI, Ops)) {
2978bcb0991SDimitry Andric     applyCombineShuffleVector(MI, Ops);
2988bcb0991SDimitry Andric     return true;
2998bcb0991SDimitry Andric   }
3008bcb0991SDimitry Andric   return false;
3018bcb0991SDimitry Andric }
3028bcb0991SDimitry Andric 
3038bcb0991SDimitry Andric bool CombinerHelper::matchCombineShuffleVector(MachineInstr &MI,
3048bcb0991SDimitry Andric                                                SmallVectorImpl<Register> &Ops) {
3058bcb0991SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR &&
3068bcb0991SDimitry Andric          "Invalid instruction kind");
3078bcb0991SDimitry Andric   LLT DstType = MRI.getType(MI.getOperand(0).getReg());
3088bcb0991SDimitry Andric   Register Src1 = MI.getOperand(1).getReg();
3098bcb0991SDimitry Andric   LLT SrcType = MRI.getType(Src1);
310480093f4SDimitry Andric   // As bizarre as it may look, shuffle vector can actually produce
311480093f4SDimitry Andric   // scalar! This is because at the IR level a <1 x ty> shuffle
312480093f4SDimitry Andric   // vector is perfectly valid.
313480093f4SDimitry Andric   unsigned DstNumElts = DstType.isVector() ? DstType.getNumElements() : 1;
314480093f4SDimitry Andric   unsigned SrcNumElts = SrcType.isVector() ? SrcType.getNumElements() : 1;
3158bcb0991SDimitry Andric 
3168bcb0991SDimitry Andric   // If the resulting vector is smaller than the size of the source
3178bcb0991SDimitry Andric   // vectors being concatenated, we won't be able to replace the
3188bcb0991SDimitry Andric   // shuffle vector into a concat_vectors.
3198bcb0991SDimitry Andric   //
3208bcb0991SDimitry Andric   // Note: We may still be able to produce a concat_vectors fed by
3218bcb0991SDimitry Andric   //       extract_vector_elt and so on. It is less clear that would
3228bcb0991SDimitry Andric   //       be better though, so don't bother for now.
323480093f4SDimitry Andric   //
324480093f4SDimitry Andric   // If the destination is a scalar, the size of the sources doesn't
325480093f4SDimitry Andric   // matter. we will lower the shuffle to a plain copy. This will
326480093f4SDimitry Andric   // work only if the source and destination have the same size. But
327480093f4SDimitry Andric   // that's covered by the next condition.
328480093f4SDimitry Andric   //
329480093f4SDimitry Andric   // TODO: If the size between the source and destination don't match
330480093f4SDimitry Andric   //       we could still emit an extract vector element in that case.
331480093f4SDimitry Andric   if (DstNumElts < 2 * SrcNumElts && DstNumElts != 1)
3328bcb0991SDimitry Andric     return false;
3338bcb0991SDimitry Andric 
3348bcb0991SDimitry Andric   // Check that the shuffle mask can be broken evenly between the
3358bcb0991SDimitry Andric   // different sources.
3368bcb0991SDimitry Andric   if (DstNumElts % SrcNumElts != 0)
3378bcb0991SDimitry Andric     return false;
3388bcb0991SDimitry Andric 
3398bcb0991SDimitry Andric   // Mask length is a multiple of the source vector length.
3408bcb0991SDimitry Andric   // Check if the shuffle is some kind of concatenation of the input
3418bcb0991SDimitry Andric   // vectors.
3428bcb0991SDimitry Andric   unsigned NumConcat = DstNumElts / SrcNumElts;
3438bcb0991SDimitry Andric   SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
344480093f4SDimitry Andric   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
3458bcb0991SDimitry Andric   for (unsigned i = 0; i != DstNumElts; ++i) {
3468bcb0991SDimitry Andric     int Idx = Mask[i];
3478bcb0991SDimitry Andric     // Undef value.
3488bcb0991SDimitry Andric     if (Idx < 0)
3498bcb0991SDimitry Andric       continue;
3508bcb0991SDimitry Andric     // Ensure the indices in each SrcType sized piece are sequential and that
3518bcb0991SDimitry Andric     // the same source is used for the whole piece.
3528bcb0991SDimitry Andric     if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3538bcb0991SDimitry Andric         (ConcatSrcs[i / SrcNumElts] >= 0 &&
3548bcb0991SDimitry Andric          ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts)))
3558bcb0991SDimitry Andric       return false;
3568bcb0991SDimitry Andric     // Remember which source this index came from.
3578bcb0991SDimitry Andric     ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3588bcb0991SDimitry Andric   }
3598bcb0991SDimitry Andric 
3608bcb0991SDimitry Andric   // The shuffle is concatenating multiple vectors together.
3618bcb0991SDimitry Andric   // Collect the different operands for that.
3628bcb0991SDimitry Andric   Register UndefReg;
3638bcb0991SDimitry Andric   Register Src2 = MI.getOperand(2).getReg();
3648bcb0991SDimitry Andric   for (auto Src : ConcatSrcs) {
3658bcb0991SDimitry Andric     if (Src < 0) {
3668bcb0991SDimitry Andric       if (!UndefReg) {
3678bcb0991SDimitry Andric         Builder.setInsertPt(*MI.getParent(), MI);
3688bcb0991SDimitry Andric         UndefReg = Builder.buildUndef(SrcType).getReg(0);
3698bcb0991SDimitry Andric       }
3708bcb0991SDimitry Andric       Ops.push_back(UndefReg);
3718bcb0991SDimitry Andric     } else if (Src == 0)
3728bcb0991SDimitry Andric       Ops.push_back(Src1);
3738bcb0991SDimitry Andric     else
3748bcb0991SDimitry Andric       Ops.push_back(Src2);
3758bcb0991SDimitry Andric   }
3768bcb0991SDimitry Andric   return true;
3778bcb0991SDimitry Andric }
3788bcb0991SDimitry Andric 
3798bcb0991SDimitry Andric void CombinerHelper::applyCombineShuffleVector(MachineInstr &MI,
3808bcb0991SDimitry Andric                                                const ArrayRef<Register> Ops) {
3818bcb0991SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
3828bcb0991SDimitry Andric   Builder.setInsertPt(*MI.getParent(), MI);
3838bcb0991SDimitry Andric   Register NewDstReg = MRI.cloneVirtualRegister(DstReg);
3848bcb0991SDimitry Andric 
385480093f4SDimitry Andric   if (Ops.size() == 1)
386480093f4SDimitry Andric     Builder.buildCopy(NewDstReg, Ops[0]);
387480093f4SDimitry Andric   else
388480093f4SDimitry Andric     Builder.buildMerge(NewDstReg, Ops);
3898bcb0991SDimitry Andric 
3908bcb0991SDimitry Andric   MI.eraseFromParent();
3918bcb0991SDimitry Andric   replaceRegWith(MRI, DstReg, NewDstReg);
3928bcb0991SDimitry Andric }
3938bcb0991SDimitry Andric 
3940b57cec5SDimitry Andric namespace {
3950b57cec5SDimitry Andric 
3960b57cec5SDimitry Andric /// Select a preference between two uses. CurrentUse is the current preference
3970b57cec5SDimitry Andric /// while *ForCandidate is attributes of the candidate under consideration.
3980b57cec5SDimitry Andric PreferredTuple ChoosePreferredUse(PreferredTuple &CurrentUse,
3995ffd83dbSDimitry Andric                                   const LLT TyForCandidate,
4000b57cec5SDimitry Andric                                   unsigned OpcodeForCandidate,
4010b57cec5SDimitry Andric                                   MachineInstr *MIForCandidate) {
4020b57cec5SDimitry Andric   if (!CurrentUse.Ty.isValid()) {
4030b57cec5SDimitry Andric     if (CurrentUse.ExtendOpcode == OpcodeForCandidate ||
4040b57cec5SDimitry Andric         CurrentUse.ExtendOpcode == TargetOpcode::G_ANYEXT)
4050b57cec5SDimitry Andric       return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
4060b57cec5SDimitry Andric     return CurrentUse;
4070b57cec5SDimitry Andric   }
4080b57cec5SDimitry Andric 
4090b57cec5SDimitry Andric   // We permit the extend to hoist through basic blocks but this is only
4100b57cec5SDimitry Andric   // sensible if the target has extending loads. If you end up lowering back
4110b57cec5SDimitry Andric   // into a load and extend during the legalizer then the end result is
4120b57cec5SDimitry Andric   // hoisting the extend up to the load.
4130b57cec5SDimitry Andric 
4140b57cec5SDimitry Andric   // Prefer defined extensions to undefined extensions as these are more
4150b57cec5SDimitry Andric   // likely to reduce the number of instructions.
4160b57cec5SDimitry Andric   if (OpcodeForCandidate == TargetOpcode::G_ANYEXT &&
4170b57cec5SDimitry Andric       CurrentUse.ExtendOpcode != TargetOpcode::G_ANYEXT)
4180b57cec5SDimitry Andric     return CurrentUse;
4190b57cec5SDimitry Andric   else if (CurrentUse.ExtendOpcode == TargetOpcode::G_ANYEXT &&
4200b57cec5SDimitry Andric            OpcodeForCandidate != TargetOpcode::G_ANYEXT)
4210b57cec5SDimitry Andric     return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric   // Prefer sign extensions to zero extensions as sign-extensions tend to be
4240b57cec5SDimitry Andric   // more expensive.
4250b57cec5SDimitry Andric   if (CurrentUse.Ty == TyForCandidate) {
4260b57cec5SDimitry Andric     if (CurrentUse.ExtendOpcode == TargetOpcode::G_SEXT &&
4270b57cec5SDimitry Andric         OpcodeForCandidate == TargetOpcode::G_ZEXT)
4280b57cec5SDimitry Andric       return CurrentUse;
4290b57cec5SDimitry Andric     else if (CurrentUse.ExtendOpcode == TargetOpcode::G_ZEXT &&
4300b57cec5SDimitry Andric              OpcodeForCandidate == TargetOpcode::G_SEXT)
4310b57cec5SDimitry Andric       return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
4320b57cec5SDimitry Andric   }
4330b57cec5SDimitry Andric 
4340b57cec5SDimitry Andric   // This is potentially target specific. We've chosen the largest type
4350b57cec5SDimitry Andric   // because G_TRUNC is usually free. One potential catch with this is that
4360b57cec5SDimitry Andric   // some targets have a reduced number of larger registers than smaller
4370b57cec5SDimitry Andric   // registers and this choice potentially increases the live-range for the
4380b57cec5SDimitry Andric   // larger value.
4390b57cec5SDimitry Andric   if (TyForCandidate.getSizeInBits() > CurrentUse.Ty.getSizeInBits()) {
4400b57cec5SDimitry Andric     return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
4410b57cec5SDimitry Andric   }
4420b57cec5SDimitry Andric   return CurrentUse;
4430b57cec5SDimitry Andric }
4440b57cec5SDimitry Andric 
4450b57cec5SDimitry Andric /// Find a suitable place to insert some instructions and insert them. This
4460b57cec5SDimitry Andric /// function accounts for special cases like inserting before a PHI node.
4470b57cec5SDimitry Andric /// The current strategy for inserting before PHI's is to duplicate the
4480b57cec5SDimitry Andric /// instructions for each predecessor. However, while that's ok for G_TRUNC
4490b57cec5SDimitry Andric /// on most targets since it generally requires no code, other targets/cases may
4500b57cec5SDimitry Andric /// want to try harder to find a dominating block.
4510b57cec5SDimitry Andric static void InsertInsnsWithoutSideEffectsBeforeUse(
4520b57cec5SDimitry Andric     MachineIRBuilder &Builder, MachineInstr &DefMI, MachineOperand &UseMO,
4530b57cec5SDimitry Andric     std::function<void(MachineBasicBlock *, MachineBasicBlock::iterator,
4540b57cec5SDimitry Andric                        MachineOperand &UseMO)>
4550b57cec5SDimitry Andric         Inserter) {
4560b57cec5SDimitry Andric   MachineInstr &UseMI = *UseMO.getParent();
4570b57cec5SDimitry Andric 
4580b57cec5SDimitry Andric   MachineBasicBlock *InsertBB = UseMI.getParent();
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric   // If the use is a PHI then we want the predecessor block instead.
4610b57cec5SDimitry Andric   if (UseMI.isPHI()) {
4620b57cec5SDimitry Andric     MachineOperand *PredBB = std::next(&UseMO);
4630b57cec5SDimitry Andric     InsertBB = PredBB->getMBB();
4640b57cec5SDimitry Andric   }
4650b57cec5SDimitry Andric 
4660b57cec5SDimitry Andric   // If the block is the same block as the def then we want to insert just after
4670b57cec5SDimitry Andric   // the def instead of at the start of the block.
4680b57cec5SDimitry Andric   if (InsertBB == DefMI.getParent()) {
4690b57cec5SDimitry Andric     MachineBasicBlock::iterator InsertPt = &DefMI;
4700b57cec5SDimitry Andric     Inserter(InsertBB, std::next(InsertPt), UseMO);
4710b57cec5SDimitry Andric     return;
4720b57cec5SDimitry Andric   }
4730b57cec5SDimitry Andric 
4740b57cec5SDimitry Andric   // Otherwise we want the start of the BB
4750b57cec5SDimitry Andric   Inserter(InsertBB, InsertBB->getFirstNonPHI(), UseMO);
4760b57cec5SDimitry Andric }
4770b57cec5SDimitry Andric } // end anonymous namespace
4780b57cec5SDimitry Andric 
4790b57cec5SDimitry Andric bool CombinerHelper::tryCombineExtendingLoads(MachineInstr &MI) {
4800b57cec5SDimitry Andric   PreferredTuple Preferred;
4810b57cec5SDimitry Andric   if (matchCombineExtendingLoads(MI, Preferred)) {
4820b57cec5SDimitry Andric     applyCombineExtendingLoads(MI, Preferred);
4830b57cec5SDimitry Andric     return true;
4840b57cec5SDimitry Andric   }
4850b57cec5SDimitry Andric   return false;
4860b57cec5SDimitry Andric }
4870b57cec5SDimitry Andric 
4880b57cec5SDimitry Andric bool CombinerHelper::matchCombineExtendingLoads(MachineInstr &MI,
4890b57cec5SDimitry Andric                                                 PreferredTuple &Preferred) {
4900b57cec5SDimitry Andric   // We match the loads and follow the uses to the extend instead of matching
4910b57cec5SDimitry Andric   // the extends and following the def to the load. This is because the load
4920b57cec5SDimitry Andric   // must remain in the same position for correctness (unless we also add code
4930b57cec5SDimitry Andric   // to find a safe place to sink it) whereas the extend is freely movable.
4940b57cec5SDimitry Andric   // It also prevents us from duplicating the load for the volatile case or just
4950b57cec5SDimitry Andric   // for performance.
496fe6060f1SDimitry Andric   GAnyLoad *LoadMI = dyn_cast<GAnyLoad>(&MI);
497fe6060f1SDimitry Andric   if (!LoadMI)
4980b57cec5SDimitry Andric     return false;
4990b57cec5SDimitry Andric 
500fe6060f1SDimitry Andric   Register LoadReg = LoadMI->getDstReg();
5010b57cec5SDimitry Andric 
502fe6060f1SDimitry Andric   LLT LoadValueTy = MRI.getType(LoadReg);
5030b57cec5SDimitry Andric   if (!LoadValueTy.isScalar())
5040b57cec5SDimitry Andric     return false;
5050b57cec5SDimitry Andric 
5060b57cec5SDimitry Andric   // Most architectures are going to legalize <s8 loads into at least a 1 byte
5070b57cec5SDimitry Andric   // load, and the MMOs can only describe memory accesses in multiples of bytes.
5080b57cec5SDimitry Andric   // If we try to perform extload combining on those, we can end up with
5090b57cec5SDimitry Andric   // %a(s8) = extload %ptr (load 1 byte from %ptr)
5100b57cec5SDimitry Andric   // ... which is an illegal extload instruction.
5110b57cec5SDimitry Andric   if (LoadValueTy.getSizeInBits() < 8)
5120b57cec5SDimitry Andric     return false;
5130b57cec5SDimitry Andric 
5140b57cec5SDimitry Andric   // For non power-of-2 types, they will very likely be legalized into multiple
5150b57cec5SDimitry Andric   // loads. Don't bother trying to match them into extending loads.
5160b57cec5SDimitry Andric   if (!isPowerOf2_32(LoadValueTy.getSizeInBits()))
5170b57cec5SDimitry Andric     return false;
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric   // Find the preferred type aside from the any-extends (unless it's the only
5200b57cec5SDimitry Andric   // one) and non-extending ops. We'll emit an extending load to that type and
5210b57cec5SDimitry Andric   // and emit a variant of (extend (trunc X)) for the others according to the
5220b57cec5SDimitry Andric   // relative type sizes. At the same time, pick an extend to use based on the
5230b57cec5SDimitry Andric   // extend involved in the chosen type.
524fe6060f1SDimitry Andric   unsigned PreferredOpcode =
525fe6060f1SDimitry Andric       isa<GLoad>(&MI)
5260b57cec5SDimitry Andric           ? TargetOpcode::G_ANYEXT
527fe6060f1SDimitry Andric           : isa<GSExtLoad>(&MI) ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
5280b57cec5SDimitry Andric   Preferred = {LLT(), PreferredOpcode, nullptr};
529fe6060f1SDimitry Andric   for (auto &UseMI : MRI.use_nodbg_instructions(LoadReg)) {
5300b57cec5SDimitry Andric     if (UseMI.getOpcode() == TargetOpcode::G_SEXT ||
5310b57cec5SDimitry Andric         UseMI.getOpcode() == TargetOpcode::G_ZEXT ||
5325ffd83dbSDimitry Andric         (UseMI.getOpcode() == TargetOpcode::G_ANYEXT)) {
533fe6060f1SDimitry Andric       const auto &MMO = LoadMI->getMMO();
534fe6060f1SDimitry Andric       // For atomics, only form anyextending loads.
535fe6060f1SDimitry Andric       if (MMO.isAtomic() && UseMI.getOpcode() != TargetOpcode::G_ANYEXT)
536fe6060f1SDimitry Andric         continue;
5375ffd83dbSDimitry Andric       // Check for legality.
5385ffd83dbSDimitry Andric       if (LI) {
539349cc55cSDimitry Andric         LegalityQuery::MemDesc MMDesc(MMO);
5405ffd83dbSDimitry Andric         LLT UseTy = MRI.getType(UseMI.getOperand(0).getReg());
541fe6060f1SDimitry Andric         LLT SrcTy = MRI.getType(LoadMI->getPointerReg());
542fe6060f1SDimitry Andric         if (LI->getAction({LoadMI->getOpcode(), {UseTy, SrcTy}, {MMDesc}})
543fe6060f1SDimitry Andric                 .Action != LegalizeActions::Legal)
5445ffd83dbSDimitry Andric           continue;
5455ffd83dbSDimitry Andric       }
5460b57cec5SDimitry Andric       Preferred = ChoosePreferredUse(Preferred,
5470b57cec5SDimitry Andric                                      MRI.getType(UseMI.getOperand(0).getReg()),
5480b57cec5SDimitry Andric                                      UseMI.getOpcode(), &UseMI);
5490b57cec5SDimitry Andric     }
5500b57cec5SDimitry Andric   }
5510b57cec5SDimitry Andric 
5520b57cec5SDimitry Andric   // There were no extends
5530b57cec5SDimitry Andric   if (!Preferred.MI)
5540b57cec5SDimitry Andric     return false;
5550b57cec5SDimitry Andric   // It should be impossible to chose an extend without selecting a different
5560b57cec5SDimitry Andric   // type since by definition the result of an extend is larger.
5570b57cec5SDimitry Andric   assert(Preferred.Ty != LoadValueTy && "Extending to same type?");
5580b57cec5SDimitry Andric 
5590b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Preferred use is: " << *Preferred.MI);
5600b57cec5SDimitry Andric   return true;
5610b57cec5SDimitry Andric }
5620b57cec5SDimitry Andric 
5630b57cec5SDimitry Andric void CombinerHelper::applyCombineExtendingLoads(MachineInstr &MI,
5640b57cec5SDimitry Andric                                                 PreferredTuple &Preferred) {
5650b57cec5SDimitry Andric   // Rewrite the load to the chosen extending load.
5660b57cec5SDimitry Andric   Register ChosenDstReg = Preferred.MI->getOperand(0).getReg();
5670b57cec5SDimitry Andric 
5680b57cec5SDimitry Andric   // Inserter to insert a truncate back to the original type at a given point
5690b57cec5SDimitry Andric   // with some basic CSE to limit truncate duplication to one per BB.
5700b57cec5SDimitry Andric   DenseMap<MachineBasicBlock *, MachineInstr *> EmittedInsns;
5710b57cec5SDimitry Andric   auto InsertTruncAt = [&](MachineBasicBlock *InsertIntoBB,
5720b57cec5SDimitry Andric                            MachineBasicBlock::iterator InsertBefore,
5730b57cec5SDimitry Andric                            MachineOperand &UseMO) {
5740b57cec5SDimitry Andric     MachineInstr *PreviouslyEmitted = EmittedInsns.lookup(InsertIntoBB);
5750b57cec5SDimitry Andric     if (PreviouslyEmitted) {
5760b57cec5SDimitry Andric       Observer.changingInstr(*UseMO.getParent());
5770b57cec5SDimitry Andric       UseMO.setReg(PreviouslyEmitted->getOperand(0).getReg());
5780b57cec5SDimitry Andric       Observer.changedInstr(*UseMO.getParent());
5790b57cec5SDimitry Andric       return;
5800b57cec5SDimitry Andric     }
5810b57cec5SDimitry Andric 
5820b57cec5SDimitry Andric     Builder.setInsertPt(*InsertIntoBB, InsertBefore);
5830b57cec5SDimitry Andric     Register NewDstReg = MRI.cloneVirtualRegister(MI.getOperand(0).getReg());
5840b57cec5SDimitry Andric     MachineInstr *NewMI = Builder.buildTrunc(NewDstReg, ChosenDstReg);
5850b57cec5SDimitry Andric     EmittedInsns[InsertIntoBB] = NewMI;
5860b57cec5SDimitry Andric     replaceRegOpWith(MRI, UseMO, NewDstReg);
5870b57cec5SDimitry Andric   };
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric   Observer.changingInstr(MI);
5900b57cec5SDimitry Andric   MI.setDesc(
5910b57cec5SDimitry Andric       Builder.getTII().get(Preferred.ExtendOpcode == TargetOpcode::G_SEXT
5920b57cec5SDimitry Andric                                ? TargetOpcode::G_SEXTLOAD
5930b57cec5SDimitry Andric                                : Preferred.ExtendOpcode == TargetOpcode::G_ZEXT
5940b57cec5SDimitry Andric                                      ? TargetOpcode::G_ZEXTLOAD
5950b57cec5SDimitry Andric                                      : TargetOpcode::G_LOAD));
5960b57cec5SDimitry Andric 
5970b57cec5SDimitry Andric   // Rewrite all the uses to fix up the types.
5980b57cec5SDimitry Andric   auto &LoadValue = MI.getOperand(0);
5990b57cec5SDimitry Andric   SmallVector<MachineOperand *, 4> Uses;
6000b57cec5SDimitry Andric   for (auto &UseMO : MRI.use_operands(LoadValue.getReg()))
6010b57cec5SDimitry Andric     Uses.push_back(&UseMO);
6020b57cec5SDimitry Andric 
6030b57cec5SDimitry Andric   for (auto *UseMO : Uses) {
6040b57cec5SDimitry Andric     MachineInstr *UseMI = UseMO->getParent();
6050b57cec5SDimitry Andric 
6060b57cec5SDimitry Andric     // If the extend is compatible with the preferred extend then we should fix
6070b57cec5SDimitry Andric     // up the type and extend so that it uses the preferred use.
6080b57cec5SDimitry Andric     if (UseMI->getOpcode() == Preferred.ExtendOpcode ||
6090b57cec5SDimitry Andric         UseMI->getOpcode() == TargetOpcode::G_ANYEXT) {
6108bcb0991SDimitry Andric       Register UseDstReg = UseMI->getOperand(0).getReg();
6110b57cec5SDimitry Andric       MachineOperand &UseSrcMO = UseMI->getOperand(1);
6125ffd83dbSDimitry Andric       const LLT UseDstTy = MRI.getType(UseDstReg);
6130b57cec5SDimitry Andric       if (UseDstReg != ChosenDstReg) {
6140b57cec5SDimitry Andric         if (Preferred.Ty == UseDstTy) {
6150b57cec5SDimitry Andric           // If the use has the same type as the preferred use, then merge
6160b57cec5SDimitry Andric           // the vregs and erase the extend. For example:
6170b57cec5SDimitry Andric           //    %1:_(s8) = G_LOAD ...
6180b57cec5SDimitry Andric           //    %2:_(s32) = G_SEXT %1(s8)
6190b57cec5SDimitry Andric           //    %3:_(s32) = G_ANYEXT %1(s8)
6200b57cec5SDimitry Andric           //    ... = ... %3(s32)
6210b57cec5SDimitry Andric           // rewrites to:
6220b57cec5SDimitry Andric           //    %2:_(s32) = G_SEXTLOAD ...
6230b57cec5SDimitry Andric           //    ... = ... %2(s32)
6240b57cec5SDimitry Andric           replaceRegWith(MRI, UseDstReg, ChosenDstReg);
6250b57cec5SDimitry Andric           Observer.erasingInstr(*UseMO->getParent());
6260b57cec5SDimitry Andric           UseMO->getParent()->eraseFromParent();
6270b57cec5SDimitry Andric         } else if (Preferred.Ty.getSizeInBits() < UseDstTy.getSizeInBits()) {
6280b57cec5SDimitry Andric           // If the preferred size is smaller, then keep the extend but extend
6290b57cec5SDimitry Andric           // from the result of the extending load. For example:
6300b57cec5SDimitry Andric           //    %1:_(s8) = G_LOAD ...
6310b57cec5SDimitry Andric           //    %2:_(s32) = G_SEXT %1(s8)
6320b57cec5SDimitry Andric           //    %3:_(s64) = G_ANYEXT %1(s8)
6330b57cec5SDimitry Andric           //    ... = ... %3(s64)
6340b57cec5SDimitry Andric           /// rewrites to:
6350b57cec5SDimitry Andric           //    %2:_(s32) = G_SEXTLOAD ...
6360b57cec5SDimitry Andric           //    %3:_(s64) = G_ANYEXT %2:_(s32)
6370b57cec5SDimitry Andric           //    ... = ... %3(s64)
6380b57cec5SDimitry Andric           replaceRegOpWith(MRI, UseSrcMO, ChosenDstReg);
6390b57cec5SDimitry Andric         } else {
6400b57cec5SDimitry Andric           // If the preferred size is large, then insert a truncate. For
6410b57cec5SDimitry Andric           // example:
6420b57cec5SDimitry Andric           //    %1:_(s8) = G_LOAD ...
6430b57cec5SDimitry Andric           //    %2:_(s64) = G_SEXT %1(s8)
6440b57cec5SDimitry Andric           //    %3:_(s32) = G_ZEXT %1(s8)
6450b57cec5SDimitry Andric           //    ... = ... %3(s32)
6460b57cec5SDimitry Andric           /// rewrites to:
6470b57cec5SDimitry Andric           //    %2:_(s64) = G_SEXTLOAD ...
6480b57cec5SDimitry Andric           //    %4:_(s8) = G_TRUNC %2:_(s32)
6490b57cec5SDimitry Andric           //    %3:_(s64) = G_ZEXT %2:_(s8)
6500b57cec5SDimitry Andric           //    ... = ... %3(s64)
6510b57cec5SDimitry Andric           InsertInsnsWithoutSideEffectsBeforeUse(Builder, MI, *UseMO,
6520b57cec5SDimitry Andric                                                  InsertTruncAt);
6530b57cec5SDimitry Andric         }
6540b57cec5SDimitry Andric         continue;
6550b57cec5SDimitry Andric       }
6560b57cec5SDimitry Andric       // The use is (one of) the uses of the preferred use we chose earlier.
6570b57cec5SDimitry Andric       // We're going to update the load to def this value later so just erase
6580b57cec5SDimitry Andric       // the old extend.
6590b57cec5SDimitry Andric       Observer.erasingInstr(*UseMO->getParent());
6600b57cec5SDimitry Andric       UseMO->getParent()->eraseFromParent();
6610b57cec5SDimitry Andric       continue;
6620b57cec5SDimitry Andric     }
6630b57cec5SDimitry Andric 
6640b57cec5SDimitry Andric     // The use isn't an extend. Truncate back to the type we originally loaded.
6650b57cec5SDimitry Andric     // This is free on many targets.
6660b57cec5SDimitry Andric     InsertInsnsWithoutSideEffectsBeforeUse(Builder, MI, *UseMO, InsertTruncAt);
6670b57cec5SDimitry Andric   }
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric   MI.getOperand(0).setReg(ChosenDstReg);
6700b57cec5SDimitry Andric   Observer.changedInstr(MI);
6710b57cec5SDimitry Andric }
6720b57cec5SDimitry Andric 
673349cc55cSDimitry Andric bool CombinerHelper::matchCombineLoadWithAndMask(MachineInstr &MI,
674349cc55cSDimitry Andric                                                  BuildFnTy &MatchInfo) {
675349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_AND);
676349cc55cSDimitry Andric 
677349cc55cSDimitry Andric   // If we have the following code:
678349cc55cSDimitry Andric   //  %mask = G_CONSTANT 255
679349cc55cSDimitry Andric   //  %ld   = G_LOAD %ptr, (load s16)
680349cc55cSDimitry Andric   //  %and  = G_AND %ld, %mask
681349cc55cSDimitry Andric   //
682349cc55cSDimitry Andric   // Try to fold it into
683349cc55cSDimitry Andric   //   %ld = G_ZEXTLOAD %ptr, (load s8)
684349cc55cSDimitry Andric 
685349cc55cSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
686349cc55cSDimitry Andric   if (MRI.getType(Dst).isVector())
687349cc55cSDimitry Andric     return false;
688349cc55cSDimitry Andric 
689349cc55cSDimitry Andric   auto MaybeMask =
690349cc55cSDimitry Andric       getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
691349cc55cSDimitry Andric   if (!MaybeMask)
692349cc55cSDimitry Andric     return false;
693349cc55cSDimitry Andric 
694349cc55cSDimitry Andric   APInt MaskVal = MaybeMask->Value;
695349cc55cSDimitry Andric 
696349cc55cSDimitry Andric   if (!MaskVal.isMask())
697349cc55cSDimitry Andric     return false;
698349cc55cSDimitry Andric 
699349cc55cSDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
700349cc55cSDimitry Andric   GAnyLoad *LoadMI = getOpcodeDef<GAnyLoad>(SrcReg, MRI);
701349cc55cSDimitry Andric   if (!LoadMI || !MRI.hasOneNonDBGUse(LoadMI->getDstReg()) ||
702349cc55cSDimitry Andric       !LoadMI->isSimple())
703349cc55cSDimitry Andric     return false;
704349cc55cSDimitry Andric 
705349cc55cSDimitry Andric   Register LoadReg = LoadMI->getDstReg();
706349cc55cSDimitry Andric   LLT LoadTy = MRI.getType(LoadReg);
707349cc55cSDimitry Andric   Register PtrReg = LoadMI->getPointerReg();
708349cc55cSDimitry Andric   uint64_t LoadSizeBits = LoadMI->getMemSizeInBits();
709349cc55cSDimitry Andric   unsigned MaskSizeBits = MaskVal.countTrailingOnes();
710349cc55cSDimitry Andric 
711349cc55cSDimitry Andric   // The mask may not be larger than the in-memory type, as it might cover sign
712349cc55cSDimitry Andric   // extended bits
713349cc55cSDimitry Andric   if (MaskSizeBits > LoadSizeBits)
714349cc55cSDimitry Andric     return false;
715349cc55cSDimitry Andric 
716349cc55cSDimitry Andric   // If the mask covers the whole destination register, there's nothing to
717349cc55cSDimitry Andric   // extend
718349cc55cSDimitry Andric   if (MaskSizeBits >= LoadTy.getSizeInBits())
719349cc55cSDimitry Andric     return false;
720349cc55cSDimitry Andric 
721349cc55cSDimitry Andric   // Most targets cannot deal with loads of size < 8 and need to re-legalize to
722349cc55cSDimitry Andric   // at least byte loads. Avoid creating such loads here
723349cc55cSDimitry Andric   if (MaskSizeBits < 8 || !isPowerOf2_32(MaskSizeBits))
724349cc55cSDimitry Andric     return false;
725349cc55cSDimitry Andric 
726349cc55cSDimitry Andric   const MachineMemOperand &MMO = LoadMI->getMMO();
727349cc55cSDimitry Andric   LegalityQuery::MemDesc MemDesc(MMO);
728349cc55cSDimitry Andric   MemDesc.MemoryTy = LLT::scalar(MaskSizeBits);
729349cc55cSDimitry Andric   if (!isLegalOrBeforeLegalizer(
730349cc55cSDimitry Andric           {TargetOpcode::G_ZEXTLOAD, {LoadTy, MRI.getType(PtrReg)}, {MemDesc}}))
731349cc55cSDimitry Andric     return false;
732349cc55cSDimitry Andric 
733349cc55cSDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
734349cc55cSDimitry Andric     B.setInstrAndDebugLoc(*LoadMI);
735349cc55cSDimitry Andric     auto &MF = B.getMF();
736349cc55cSDimitry Andric     auto PtrInfo = MMO.getPointerInfo();
737349cc55cSDimitry Andric     auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, MaskSizeBits / 8);
738349cc55cSDimitry Andric     B.buildLoadInstr(TargetOpcode::G_ZEXTLOAD, Dst, PtrReg, *NewMMO);
739349cc55cSDimitry Andric   };
740349cc55cSDimitry Andric   return true;
741349cc55cSDimitry Andric }
742349cc55cSDimitry Andric 
7435ffd83dbSDimitry Andric bool CombinerHelper::isPredecessor(const MachineInstr &DefMI,
7445ffd83dbSDimitry Andric                                    const MachineInstr &UseMI) {
7455ffd83dbSDimitry Andric   assert(!DefMI.isDebugInstr() && !UseMI.isDebugInstr() &&
7465ffd83dbSDimitry Andric          "shouldn't consider debug uses");
7478bcb0991SDimitry Andric   assert(DefMI.getParent() == UseMI.getParent());
7488bcb0991SDimitry Andric   if (&DefMI == &UseMI)
749349cc55cSDimitry Andric     return true;
750e8d8bef9SDimitry Andric   const MachineBasicBlock &MBB = *DefMI.getParent();
751e8d8bef9SDimitry Andric   auto DefOrUse = find_if(MBB, [&DefMI, &UseMI](const MachineInstr &MI) {
752e8d8bef9SDimitry Andric     return &MI == &DefMI || &MI == &UseMI;
753e8d8bef9SDimitry Andric   });
754e8d8bef9SDimitry Andric   if (DefOrUse == MBB.end())
755e8d8bef9SDimitry Andric     llvm_unreachable("Block must contain both DefMI and UseMI!");
756e8d8bef9SDimitry Andric   return &*DefOrUse == &DefMI;
7578bcb0991SDimitry Andric }
7588bcb0991SDimitry Andric 
7595ffd83dbSDimitry Andric bool CombinerHelper::dominates(const MachineInstr &DefMI,
7605ffd83dbSDimitry Andric                                const MachineInstr &UseMI) {
7615ffd83dbSDimitry Andric   assert(!DefMI.isDebugInstr() && !UseMI.isDebugInstr() &&
7625ffd83dbSDimitry Andric          "shouldn't consider debug uses");
7638bcb0991SDimitry Andric   if (MDT)
7648bcb0991SDimitry Andric     return MDT->dominates(&DefMI, &UseMI);
7658bcb0991SDimitry Andric   else if (DefMI.getParent() != UseMI.getParent())
7668bcb0991SDimitry Andric     return false;
7678bcb0991SDimitry Andric 
7688bcb0991SDimitry Andric   return isPredecessor(DefMI, UseMI);
7698bcb0991SDimitry Andric }
7708bcb0991SDimitry Andric 
771e8d8bef9SDimitry Andric bool CombinerHelper::matchSextTruncSextLoad(MachineInstr &MI) {
7725ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
7735ffd83dbSDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
774e8d8bef9SDimitry Andric   Register LoadUser = SrcReg;
775e8d8bef9SDimitry Andric 
776e8d8bef9SDimitry Andric   if (MRI.getType(SrcReg).isVector())
777e8d8bef9SDimitry Andric     return false;
778e8d8bef9SDimitry Andric 
779e8d8bef9SDimitry Andric   Register TruncSrc;
780e8d8bef9SDimitry Andric   if (mi_match(SrcReg, MRI, m_GTrunc(m_Reg(TruncSrc))))
781e8d8bef9SDimitry Andric     LoadUser = TruncSrc;
782e8d8bef9SDimitry Andric 
783e8d8bef9SDimitry Andric   uint64_t SizeInBits = MI.getOperand(2).getImm();
784e8d8bef9SDimitry Andric   // If the source is a G_SEXTLOAD from the same bit width, then we don't
785e8d8bef9SDimitry Andric   // need any extend at all, just a truncate.
786fe6060f1SDimitry Andric   if (auto *LoadMI = getOpcodeDef<GSExtLoad>(LoadUser, MRI)) {
787e8d8bef9SDimitry Andric     // If truncating more than the original extended value, abort.
788fe6060f1SDimitry Andric     auto LoadSizeBits = LoadMI->getMemSizeInBits();
789fe6060f1SDimitry Andric     if (TruncSrc && MRI.getType(TruncSrc).getSizeInBits() < LoadSizeBits)
790e8d8bef9SDimitry Andric       return false;
791fe6060f1SDimitry Andric     if (LoadSizeBits == SizeInBits)
792e8d8bef9SDimitry Andric       return true;
793e8d8bef9SDimitry Andric   }
794e8d8bef9SDimitry Andric   return false;
7955ffd83dbSDimitry Andric }
7965ffd83dbSDimitry Andric 
797fe6060f1SDimitry Andric void CombinerHelper::applySextTruncSextLoad(MachineInstr &MI) {
7985ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
799e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
800e8d8bef9SDimitry Andric   Builder.buildCopy(MI.getOperand(0).getReg(), MI.getOperand(1).getReg());
801e8d8bef9SDimitry Andric   MI.eraseFromParent();
802e8d8bef9SDimitry Andric }
803e8d8bef9SDimitry Andric 
804e8d8bef9SDimitry Andric bool CombinerHelper::matchSextInRegOfLoad(
805e8d8bef9SDimitry Andric     MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
806e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
807e8d8bef9SDimitry Andric 
808e8d8bef9SDimitry Andric   // Only supports scalars for now.
809e8d8bef9SDimitry Andric   if (MRI.getType(MI.getOperand(0).getReg()).isVector())
810e8d8bef9SDimitry Andric     return false;
811e8d8bef9SDimitry Andric 
812e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
813fe6060f1SDimitry Andric   auto *LoadDef = getOpcodeDef<GLoad>(SrcReg, MRI);
814fe6060f1SDimitry Andric   if (!LoadDef || !MRI.hasOneNonDBGUse(LoadDef->getOperand(0).getReg()) ||
815fe6060f1SDimitry Andric       !LoadDef->isSimple())
816e8d8bef9SDimitry Andric     return false;
817e8d8bef9SDimitry Andric 
818e8d8bef9SDimitry Andric   // If the sign extend extends from a narrower width than the load's width,
819e8d8bef9SDimitry Andric   // then we can narrow the load width when we combine to a G_SEXTLOAD.
820e8d8bef9SDimitry Andric   // Avoid widening the load at all.
821fe6060f1SDimitry Andric   unsigned NewSizeBits = std::min((uint64_t)MI.getOperand(2).getImm(),
822fe6060f1SDimitry Andric                                   LoadDef->getMemSizeInBits());
823e8d8bef9SDimitry Andric 
824e8d8bef9SDimitry Andric   // Don't generate G_SEXTLOADs with a < 1 byte width.
825e8d8bef9SDimitry Andric   if (NewSizeBits < 8)
826e8d8bef9SDimitry Andric     return false;
827e8d8bef9SDimitry Andric   // Don't bother creating a non-power-2 sextload, it will likely be broken up
828e8d8bef9SDimitry Andric   // anyway for most targets.
829e8d8bef9SDimitry Andric   if (!isPowerOf2_32(NewSizeBits))
830e8d8bef9SDimitry Andric     return false;
831349cc55cSDimitry Andric 
832349cc55cSDimitry Andric   const MachineMemOperand &MMO = LoadDef->getMMO();
833349cc55cSDimitry Andric   LegalityQuery::MemDesc MMDesc(MMO);
834349cc55cSDimitry Andric   MMDesc.MemoryTy = LLT::scalar(NewSizeBits);
835349cc55cSDimitry Andric   if (!isLegalOrBeforeLegalizer({TargetOpcode::G_SEXTLOAD,
836349cc55cSDimitry Andric                                  {MRI.getType(LoadDef->getDstReg()),
837349cc55cSDimitry Andric                                   MRI.getType(LoadDef->getPointerReg())},
838349cc55cSDimitry Andric                                  {MMDesc}}))
839349cc55cSDimitry Andric     return false;
840349cc55cSDimitry Andric 
841fe6060f1SDimitry Andric   MatchInfo = std::make_tuple(LoadDef->getDstReg(), NewSizeBits);
842e8d8bef9SDimitry Andric   return true;
843e8d8bef9SDimitry Andric }
844e8d8bef9SDimitry Andric 
845fe6060f1SDimitry Andric void CombinerHelper::applySextInRegOfLoad(
846e8d8bef9SDimitry Andric     MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
847e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
848e8d8bef9SDimitry Andric   Register LoadReg;
849e8d8bef9SDimitry Andric   unsigned ScalarSizeBits;
850e8d8bef9SDimitry Andric   std::tie(LoadReg, ScalarSizeBits) = MatchInfo;
851fe6060f1SDimitry Andric   GLoad *LoadDef = cast<GLoad>(MRI.getVRegDef(LoadReg));
852e8d8bef9SDimitry Andric 
853e8d8bef9SDimitry Andric   // If we have the following:
854e8d8bef9SDimitry Andric   // %ld = G_LOAD %ptr, (load 2)
855e8d8bef9SDimitry Andric   // %ext = G_SEXT_INREG %ld, 8
856e8d8bef9SDimitry Andric   //    ==>
857e8d8bef9SDimitry Andric   // %ld = G_SEXTLOAD %ptr (load 1)
858e8d8bef9SDimitry Andric 
859fe6060f1SDimitry Andric   auto &MMO = LoadDef->getMMO();
860fe6060f1SDimitry Andric   Builder.setInstrAndDebugLoc(*LoadDef);
861e8d8bef9SDimitry Andric   auto &MF = Builder.getMF();
862e8d8bef9SDimitry Andric   auto PtrInfo = MMO.getPointerInfo();
863e8d8bef9SDimitry Andric   auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, ScalarSizeBits / 8);
864e8d8bef9SDimitry Andric   Builder.buildLoadInstr(TargetOpcode::G_SEXTLOAD, MI.getOperand(0).getReg(),
865fe6060f1SDimitry Andric                          LoadDef->getPointerReg(), *NewMMO);
8665ffd83dbSDimitry Andric   MI.eraseFromParent();
8675ffd83dbSDimitry Andric }
8685ffd83dbSDimitry Andric 
8698bcb0991SDimitry Andric bool CombinerHelper::findPostIndexCandidate(MachineInstr &MI, Register &Addr,
8708bcb0991SDimitry Andric                                             Register &Base, Register &Offset) {
8718bcb0991SDimitry Andric   auto &MF = *MI.getParent()->getParent();
8728bcb0991SDimitry Andric   const auto &TLI = *MF.getSubtarget().getTargetLowering();
8738bcb0991SDimitry Andric 
8748bcb0991SDimitry Andric #ifndef NDEBUG
8758bcb0991SDimitry Andric   unsigned Opcode = MI.getOpcode();
8768bcb0991SDimitry Andric   assert(Opcode == TargetOpcode::G_LOAD || Opcode == TargetOpcode::G_SEXTLOAD ||
8778bcb0991SDimitry Andric          Opcode == TargetOpcode::G_ZEXTLOAD || Opcode == TargetOpcode::G_STORE);
8788bcb0991SDimitry Andric #endif
8798bcb0991SDimitry Andric 
8808bcb0991SDimitry Andric   Base = MI.getOperand(1).getReg();
8818bcb0991SDimitry Andric   MachineInstr *BaseDef = MRI.getUniqueVRegDef(Base);
8828bcb0991SDimitry Andric   if (BaseDef && BaseDef->getOpcode() == TargetOpcode::G_FRAME_INDEX)
8838bcb0991SDimitry Andric     return false;
8848bcb0991SDimitry Andric 
8858bcb0991SDimitry Andric   LLVM_DEBUG(dbgs() << "Searching for post-indexing opportunity for: " << MI);
886e8d8bef9SDimitry Andric   // FIXME: The following use traversal needs a bail out for patholigical cases.
8875ffd83dbSDimitry Andric   for (auto &Use : MRI.use_nodbg_instructions(Base)) {
888480093f4SDimitry Andric     if (Use.getOpcode() != TargetOpcode::G_PTR_ADD)
8898bcb0991SDimitry Andric       continue;
8908bcb0991SDimitry Andric 
8918bcb0991SDimitry Andric     Offset = Use.getOperand(2).getReg();
8928bcb0991SDimitry Andric     if (!ForceLegalIndexing &&
8938bcb0991SDimitry Andric         !TLI.isIndexingLegal(MI, Base, Offset, /*IsPre*/ false, MRI)) {
8948bcb0991SDimitry Andric       LLVM_DEBUG(dbgs() << "    Ignoring candidate with illegal addrmode: "
8958bcb0991SDimitry Andric                         << Use);
8968bcb0991SDimitry Andric       continue;
8978bcb0991SDimitry Andric     }
8988bcb0991SDimitry Andric 
8998bcb0991SDimitry Andric     // Make sure the offset calculation is before the potentially indexed op.
9008bcb0991SDimitry Andric     // FIXME: we really care about dependency here. The offset calculation might
9018bcb0991SDimitry Andric     // be movable.
9028bcb0991SDimitry Andric     MachineInstr *OffsetDef = MRI.getUniqueVRegDef(Offset);
9038bcb0991SDimitry Andric     if (!OffsetDef || !dominates(*OffsetDef, MI)) {
9048bcb0991SDimitry Andric       LLVM_DEBUG(dbgs() << "    Ignoring candidate with offset after mem-op: "
9058bcb0991SDimitry Andric                         << Use);
9068bcb0991SDimitry Andric       continue;
9078bcb0991SDimitry Andric     }
9088bcb0991SDimitry Andric 
9098bcb0991SDimitry Andric     // FIXME: check whether all uses of Base are load/store with foldable
9108bcb0991SDimitry Andric     // addressing modes. If so, using the normal addr-modes is better than
9118bcb0991SDimitry Andric     // forming an indexed one.
9128bcb0991SDimitry Andric 
9138bcb0991SDimitry Andric     bool MemOpDominatesAddrUses = true;
9145ffd83dbSDimitry Andric     for (auto &PtrAddUse :
9155ffd83dbSDimitry Andric          MRI.use_nodbg_instructions(Use.getOperand(0).getReg())) {
916480093f4SDimitry Andric       if (!dominates(MI, PtrAddUse)) {
9178bcb0991SDimitry Andric         MemOpDominatesAddrUses = false;
9188bcb0991SDimitry Andric         break;
9198bcb0991SDimitry Andric       }
9208bcb0991SDimitry Andric     }
9218bcb0991SDimitry Andric 
9228bcb0991SDimitry Andric     if (!MemOpDominatesAddrUses) {
9238bcb0991SDimitry Andric       LLVM_DEBUG(
9248bcb0991SDimitry Andric           dbgs() << "    Ignoring candidate as memop does not dominate uses: "
9258bcb0991SDimitry Andric                  << Use);
9268bcb0991SDimitry Andric       continue;
9278bcb0991SDimitry Andric     }
9288bcb0991SDimitry Andric 
9298bcb0991SDimitry Andric     LLVM_DEBUG(dbgs() << "    Found match: " << Use);
9308bcb0991SDimitry Andric     Addr = Use.getOperand(0).getReg();
9318bcb0991SDimitry Andric     return true;
9328bcb0991SDimitry Andric   }
9338bcb0991SDimitry Andric 
9348bcb0991SDimitry Andric   return false;
9358bcb0991SDimitry Andric }
9368bcb0991SDimitry Andric 
9378bcb0991SDimitry Andric bool CombinerHelper::findPreIndexCandidate(MachineInstr &MI, Register &Addr,
9388bcb0991SDimitry Andric                                            Register &Base, Register &Offset) {
9398bcb0991SDimitry Andric   auto &MF = *MI.getParent()->getParent();
9408bcb0991SDimitry Andric   const auto &TLI = *MF.getSubtarget().getTargetLowering();
9418bcb0991SDimitry Andric 
9428bcb0991SDimitry Andric #ifndef NDEBUG
9438bcb0991SDimitry Andric   unsigned Opcode = MI.getOpcode();
9448bcb0991SDimitry Andric   assert(Opcode == TargetOpcode::G_LOAD || Opcode == TargetOpcode::G_SEXTLOAD ||
9458bcb0991SDimitry Andric          Opcode == TargetOpcode::G_ZEXTLOAD || Opcode == TargetOpcode::G_STORE);
9468bcb0991SDimitry Andric #endif
9478bcb0991SDimitry Andric 
9488bcb0991SDimitry Andric   Addr = MI.getOperand(1).getReg();
949480093f4SDimitry Andric   MachineInstr *AddrDef = getOpcodeDef(TargetOpcode::G_PTR_ADD, Addr, MRI);
9505ffd83dbSDimitry Andric   if (!AddrDef || MRI.hasOneNonDBGUse(Addr))
9518bcb0991SDimitry Andric     return false;
9528bcb0991SDimitry Andric 
9538bcb0991SDimitry Andric   Base = AddrDef->getOperand(1).getReg();
9548bcb0991SDimitry Andric   Offset = AddrDef->getOperand(2).getReg();
9558bcb0991SDimitry Andric 
9568bcb0991SDimitry Andric   LLVM_DEBUG(dbgs() << "Found potential pre-indexed load_store: " << MI);
9578bcb0991SDimitry Andric 
9588bcb0991SDimitry Andric   if (!ForceLegalIndexing &&
9598bcb0991SDimitry Andric       !TLI.isIndexingLegal(MI, Base, Offset, /*IsPre*/ true, MRI)) {
9608bcb0991SDimitry Andric     LLVM_DEBUG(dbgs() << "    Skipping, not legal for target");
9618bcb0991SDimitry Andric     return false;
9628bcb0991SDimitry Andric   }
9638bcb0991SDimitry Andric 
9648bcb0991SDimitry Andric   MachineInstr *BaseDef = getDefIgnoringCopies(Base, MRI);
9658bcb0991SDimitry Andric   if (BaseDef->getOpcode() == TargetOpcode::G_FRAME_INDEX) {
9668bcb0991SDimitry Andric     LLVM_DEBUG(dbgs() << "    Skipping, frame index would need copy anyway.");
9678bcb0991SDimitry Andric     return false;
9688bcb0991SDimitry Andric   }
9698bcb0991SDimitry Andric 
9708bcb0991SDimitry Andric   if (MI.getOpcode() == TargetOpcode::G_STORE) {
9718bcb0991SDimitry Andric     // Would require a copy.
9728bcb0991SDimitry Andric     if (Base == MI.getOperand(0).getReg()) {
9738bcb0991SDimitry Andric       LLVM_DEBUG(dbgs() << "    Skipping, storing base so need copy anyway.");
9748bcb0991SDimitry Andric       return false;
9758bcb0991SDimitry Andric     }
9768bcb0991SDimitry Andric 
9778bcb0991SDimitry Andric     // We're expecting one use of Addr in MI, but it could also be the
9788bcb0991SDimitry Andric     // value stored, which isn't actually dominated by the instruction.
9798bcb0991SDimitry Andric     if (MI.getOperand(0).getReg() == Addr) {
9808bcb0991SDimitry Andric       LLVM_DEBUG(dbgs() << "    Skipping, does not dominate all addr uses");
9818bcb0991SDimitry Andric       return false;
9828bcb0991SDimitry Andric     }
9838bcb0991SDimitry Andric   }
9848bcb0991SDimitry Andric 
985480093f4SDimitry Andric   // FIXME: check whether all uses of the base pointer are constant PtrAdds.
986480093f4SDimitry Andric   // That might allow us to end base's liveness here by adjusting the constant.
9878bcb0991SDimitry Andric 
9885ffd83dbSDimitry Andric   for (auto &UseMI : MRI.use_nodbg_instructions(Addr)) {
9898bcb0991SDimitry Andric     if (!dominates(MI, UseMI)) {
9908bcb0991SDimitry Andric       LLVM_DEBUG(dbgs() << "    Skipping, does not dominate all addr uses.");
9918bcb0991SDimitry Andric       return false;
9928bcb0991SDimitry Andric     }
9938bcb0991SDimitry Andric   }
9948bcb0991SDimitry Andric 
9958bcb0991SDimitry Andric   return true;
9968bcb0991SDimitry Andric }
9978bcb0991SDimitry Andric 
9988bcb0991SDimitry Andric bool CombinerHelper::tryCombineIndexedLoadStore(MachineInstr &MI) {
999480093f4SDimitry Andric   IndexedLoadStoreMatchInfo MatchInfo;
1000480093f4SDimitry Andric   if (matchCombineIndexedLoadStore(MI, MatchInfo)) {
1001480093f4SDimitry Andric     applyCombineIndexedLoadStore(MI, MatchInfo);
1002480093f4SDimitry Andric     return true;
1003480093f4SDimitry Andric   }
1004480093f4SDimitry Andric   return false;
1005480093f4SDimitry Andric }
1006480093f4SDimitry Andric 
1007480093f4SDimitry Andric bool CombinerHelper::matchCombineIndexedLoadStore(MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) {
10088bcb0991SDimitry Andric   unsigned Opcode = MI.getOpcode();
10098bcb0991SDimitry Andric   if (Opcode != TargetOpcode::G_LOAD && Opcode != TargetOpcode::G_SEXTLOAD &&
10108bcb0991SDimitry Andric       Opcode != TargetOpcode::G_ZEXTLOAD && Opcode != TargetOpcode::G_STORE)
10118bcb0991SDimitry Andric     return false;
10128bcb0991SDimitry Andric 
1013e8d8bef9SDimitry Andric   // For now, no targets actually support these opcodes so don't waste time
1014e8d8bef9SDimitry Andric   // running these unless we're forced to for testing.
1015e8d8bef9SDimitry Andric   if (!ForceLegalIndexing)
1016e8d8bef9SDimitry Andric     return false;
1017e8d8bef9SDimitry Andric 
1018480093f4SDimitry Andric   MatchInfo.IsPre = findPreIndexCandidate(MI, MatchInfo.Addr, MatchInfo.Base,
1019480093f4SDimitry Andric                                           MatchInfo.Offset);
1020480093f4SDimitry Andric   if (!MatchInfo.IsPre &&
1021480093f4SDimitry Andric       !findPostIndexCandidate(MI, MatchInfo.Addr, MatchInfo.Base,
1022480093f4SDimitry Andric                               MatchInfo.Offset))
10238bcb0991SDimitry Andric     return false;
10248bcb0991SDimitry Andric 
1025480093f4SDimitry Andric   return true;
1026480093f4SDimitry Andric }
10278bcb0991SDimitry Andric 
1028480093f4SDimitry Andric void CombinerHelper::applyCombineIndexedLoadStore(
1029480093f4SDimitry Andric     MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) {
1030480093f4SDimitry Andric   MachineInstr &AddrDef = *MRI.getUniqueVRegDef(MatchInfo.Addr);
1031480093f4SDimitry Andric   MachineIRBuilder MIRBuilder(MI);
1032480093f4SDimitry Andric   unsigned Opcode = MI.getOpcode();
1033480093f4SDimitry Andric   bool IsStore = Opcode == TargetOpcode::G_STORE;
10348bcb0991SDimitry Andric   unsigned NewOpcode;
10358bcb0991SDimitry Andric   switch (Opcode) {
10368bcb0991SDimitry Andric   case TargetOpcode::G_LOAD:
10378bcb0991SDimitry Andric     NewOpcode = TargetOpcode::G_INDEXED_LOAD;
10388bcb0991SDimitry Andric     break;
10398bcb0991SDimitry Andric   case TargetOpcode::G_SEXTLOAD:
10408bcb0991SDimitry Andric     NewOpcode = TargetOpcode::G_INDEXED_SEXTLOAD;
10418bcb0991SDimitry Andric     break;
10428bcb0991SDimitry Andric   case TargetOpcode::G_ZEXTLOAD:
10438bcb0991SDimitry Andric     NewOpcode = TargetOpcode::G_INDEXED_ZEXTLOAD;
10448bcb0991SDimitry Andric     break;
10458bcb0991SDimitry Andric   case TargetOpcode::G_STORE:
10468bcb0991SDimitry Andric     NewOpcode = TargetOpcode::G_INDEXED_STORE;
10478bcb0991SDimitry Andric     break;
10488bcb0991SDimitry Andric   default:
10498bcb0991SDimitry Andric     llvm_unreachable("Unknown load/store opcode");
10508bcb0991SDimitry Andric   }
10518bcb0991SDimitry Andric 
10528bcb0991SDimitry Andric   auto MIB = MIRBuilder.buildInstr(NewOpcode);
10538bcb0991SDimitry Andric   if (IsStore) {
1054480093f4SDimitry Andric     MIB.addDef(MatchInfo.Addr);
10558bcb0991SDimitry Andric     MIB.addUse(MI.getOperand(0).getReg());
10568bcb0991SDimitry Andric   } else {
10578bcb0991SDimitry Andric     MIB.addDef(MI.getOperand(0).getReg());
1058480093f4SDimitry Andric     MIB.addDef(MatchInfo.Addr);
10598bcb0991SDimitry Andric   }
10608bcb0991SDimitry Andric 
1061480093f4SDimitry Andric   MIB.addUse(MatchInfo.Base);
1062480093f4SDimitry Andric   MIB.addUse(MatchInfo.Offset);
1063480093f4SDimitry Andric   MIB.addImm(MatchInfo.IsPre);
10648bcb0991SDimitry Andric   MI.eraseFromParent();
10658bcb0991SDimitry Andric   AddrDef.eraseFromParent();
10668bcb0991SDimitry Andric 
10678bcb0991SDimitry Andric   LLVM_DEBUG(dbgs() << "    Combinined to indexed operation");
10688bcb0991SDimitry Andric }
10698bcb0991SDimitry Andric 
1070fe6060f1SDimitry Andric bool CombinerHelper::matchCombineDivRem(MachineInstr &MI,
1071fe6060f1SDimitry Andric                                         MachineInstr *&OtherMI) {
1072fe6060f1SDimitry Andric   unsigned Opcode = MI.getOpcode();
1073fe6060f1SDimitry Andric   bool IsDiv, IsSigned;
1074fe6060f1SDimitry Andric 
1075fe6060f1SDimitry Andric   switch (Opcode) {
1076fe6060f1SDimitry Andric   default:
1077fe6060f1SDimitry Andric     llvm_unreachable("Unexpected opcode!");
1078fe6060f1SDimitry Andric   case TargetOpcode::G_SDIV:
1079fe6060f1SDimitry Andric   case TargetOpcode::G_UDIV: {
1080fe6060f1SDimitry Andric     IsDiv = true;
1081fe6060f1SDimitry Andric     IsSigned = Opcode == TargetOpcode::G_SDIV;
1082fe6060f1SDimitry Andric     break;
1083fe6060f1SDimitry Andric   }
1084fe6060f1SDimitry Andric   case TargetOpcode::G_SREM:
1085fe6060f1SDimitry Andric   case TargetOpcode::G_UREM: {
1086fe6060f1SDimitry Andric     IsDiv = false;
1087fe6060f1SDimitry Andric     IsSigned = Opcode == TargetOpcode::G_SREM;
1088fe6060f1SDimitry Andric     break;
1089fe6060f1SDimitry Andric   }
1090fe6060f1SDimitry Andric   }
1091fe6060f1SDimitry Andric 
1092fe6060f1SDimitry Andric   Register Src1 = MI.getOperand(1).getReg();
1093fe6060f1SDimitry Andric   unsigned DivOpcode, RemOpcode, DivremOpcode;
1094fe6060f1SDimitry Andric   if (IsSigned) {
1095fe6060f1SDimitry Andric     DivOpcode = TargetOpcode::G_SDIV;
1096fe6060f1SDimitry Andric     RemOpcode = TargetOpcode::G_SREM;
1097fe6060f1SDimitry Andric     DivremOpcode = TargetOpcode::G_SDIVREM;
1098fe6060f1SDimitry Andric   } else {
1099fe6060f1SDimitry Andric     DivOpcode = TargetOpcode::G_UDIV;
1100fe6060f1SDimitry Andric     RemOpcode = TargetOpcode::G_UREM;
1101fe6060f1SDimitry Andric     DivremOpcode = TargetOpcode::G_UDIVREM;
1102fe6060f1SDimitry Andric   }
1103fe6060f1SDimitry Andric 
1104fe6060f1SDimitry Andric   if (!isLegalOrBeforeLegalizer({DivremOpcode, {MRI.getType(Src1)}}))
11058bcb0991SDimitry Andric     return false;
11068bcb0991SDimitry Andric 
1107fe6060f1SDimitry Andric   // Combine:
1108fe6060f1SDimitry Andric   //   %div:_ = G_[SU]DIV %src1:_, %src2:_
1109fe6060f1SDimitry Andric   //   %rem:_ = G_[SU]REM %src1:_, %src2:_
1110fe6060f1SDimitry Andric   // into:
1111fe6060f1SDimitry Andric   //  %div:_, %rem:_ = G_[SU]DIVREM %src1:_, %src2:_
1112fe6060f1SDimitry Andric 
1113fe6060f1SDimitry Andric   // Combine:
1114fe6060f1SDimitry Andric   //   %rem:_ = G_[SU]REM %src1:_, %src2:_
1115fe6060f1SDimitry Andric   //   %div:_ = G_[SU]DIV %src1:_, %src2:_
1116fe6060f1SDimitry Andric   // into:
1117fe6060f1SDimitry Andric   //  %div:_, %rem:_ = G_[SU]DIVREM %src1:_, %src2:_
1118fe6060f1SDimitry Andric 
1119fe6060f1SDimitry Andric   for (auto &UseMI : MRI.use_nodbg_instructions(Src1)) {
1120fe6060f1SDimitry Andric     if (MI.getParent() == UseMI.getParent() &&
1121fe6060f1SDimitry Andric         ((IsDiv && UseMI.getOpcode() == RemOpcode) ||
1122fe6060f1SDimitry Andric          (!IsDiv && UseMI.getOpcode() == DivOpcode)) &&
1123fe6060f1SDimitry Andric         matchEqualDefs(MI.getOperand(2), UseMI.getOperand(2))) {
1124fe6060f1SDimitry Andric       OtherMI = &UseMI;
1125fe6060f1SDimitry Andric       return true;
1126fe6060f1SDimitry Andric     }
1127fe6060f1SDimitry Andric   }
1128fe6060f1SDimitry Andric 
1129fe6060f1SDimitry Andric   return false;
1130fe6060f1SDimitry Andric }
1131fe6060f1SDimitry Andric 
1132fe6060f1SDimitry Andric void CombinerHelper::applyCombineDivRem(MachineInstr &MI,
1133fe6060f1SDimitry Andric                                         MachineInstr *&OtherMI) {
1134fe6060f1SDimitry Andric   unsigned Opcode = MI.getOpcode();
1135fe6060f1SDimitry Andric   assert(OtherMI && "OtherMI shouldn't be empty.");
1136fe6060f1SDimitry Andric 
1137fe6060f1SDimitry Andric   Register DestDivReg, DestRemReg;
1138fe6060f1SDimitry Andric   if (Opcode == TargetOpcode::G_SDIV || Opcode == TargetOpcode::G_UDIV) {
1139fe6060f1SDimitry Andric     DestDivReg = MI.getOperand(0).getReg();
1140fe6060f1SDimitry Andric     DestRemReg = OtherMI->getOperand(0).getReg();
1141fe6060f1SDimitry Andric   } else {
1142fe6060f1SDimitry Andric     DestDivReg = OtherMI->getOperand(0).getReg();
1143fe6060f1SDimitry Andric     DestRemReg = MI.getOperand(0).getReg();
1144fe6060f1SDimitry Andric   }
1145fe6060f1SDimitry Andric 
1146fe6060f1SDimitry Andric   bool IsSigned =
1147fe6060f1SDimitry Andric       Opcode == TargetOpcode::G_SDIV || Opcode == TargetOpcode::G_SREM;
1148fe6060f1SDimitry Andric 
1149fe6060f1SDimitry Andric   // Check which instruction is first in the block so we don't break def-use
1150fe6060f1SDimitry Andric   // deps by "moving" the instruction incorrectly.
1151fe6060f1SDimitry Andric   if (dominates(MI, *OtherMI))
1152fe6060f1SDimitry Andric     Builder.setInstrAndDebugLoc(MI);
1153fe6060f1SDimitry Andric   else
1154fe6060f1SDimitry Andric     Builder.setInstrAndDebugLoc(*OtherMI);
1155fe6060f1SDimitry Andric 
1156fe6060f1SDimitry Andric   Builder.buildInstr(IsSigned ? TargetOpcode::G_SDIVREM
1157fe6060f1SDimitry Andric                               : TargetOpcode::G_UDIVREM,
1158fe6060f1SDimitry Andric                      {DestDivReg, DestRemReg},
1159fe6060f1SDimitry Andric                      {MI.getOperand(1).getReg(), MI.getOperand(2).getReg()});
1160fe6060f1SDimitry Andric   MI.eraseFromParent();
1161fe6060f1SDimitry Andric   OtherMI->eraseFromParent();
1162fe6060f1SDimitry Andric }
1163fe6060f1SDimitry Andric 
1164fe6060f1SDimitry Andric bool CombinerHelper::matchOptBrCondByInvertingCond(MachineInstr &MI,
1165fe6060f1SDimitry Andric                                                    MachineInstr *&BrCond) {
1166fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_BR);
1167fe6060f1SDimitry Andric 
11680b57cec5SDimitry Andric   // Try to match the following:
11690b57cec5SDimitry Andric   // bb1:
11700b57cec5SDimitry Andric   //   G_BRCOND %c1, %bb2
11710b57cec5SDimitry Andric   //   G_BR %bb3
11720b57cec5SDimitry Andric   // bb2:
11730b57cec5SDimitry Andric   // ...
11740b57cec5SDimitry Andric   // bb3:
11750b57cec5SDimitry Andric 
11760b57cec5SDimitry Andric   // The above pattern does not have a fall through to the successor bb2, always
11770b57cec5SDimitry Andric   // resulting in a branch no matter which path is taken. Here we try to find
11780b57cec5SDimitry Andric   // and replace that pattern with conditional branch to bb3 and otherwise
1179e8d8bef9SDimitry Andric   // fallthrough to bb2. This is generally better for branch predictors.
11800b57cec5SDimitry Andric 
11810b57cec5SDimitry Andric   MachineBasicBlock *MBB = MI.getParent();
11820b57cec5SDimitry Andric   MachineBasicBlock::iterator BrIt(MI);
11830b57cec5SDimitry Andric   if (BrIt == MBB->begin())
11840b57cec5SDimitry Andric     return false;
11850b57cec5SDimitry Andric   assert(std::next(BrIt) == MBB->end() && "expected G_BR to be a terminator");
11860b57cec5SDimitry Andric 
1187fe6060f1SDimitry Andric   BrCond = &*std::prev(BrIt);
11880b57cec5SDimitry Andric   if (BrCond->getOpcode() != TargetOpcode::G_BRCOND)
11890b57cec5SDimitry Andric     return false;
11900b57cec5SDimitry Andric 
1191d409305fSDimitry Andric   // Check that the next block is the conditional branch target. Also make sure
1192d409305fSDimitry Andric   // that it isn't the same as the G_BR's target (otherwise, this will loop.)
1193d409305fSDimitry Andric   MachineBasicBlock *BrCondTarget = BrCond->getOperand(1).getMBB();
1194d409305fSDimitry Andric   return BrCondTarget != MI.getOperand(0).getMBB() &&
1195d409305fSDimitry Andric          MBB->isLayoutSuccessor(BrCondTarget);
11960b57cec5SDimitry Andric }
11970b57cec5SDimitry Andric 
1198fe6060f1SDimitry Andric void CombinerHelper::applyOptBrCondByInvertingCond(MachineInstr &MI,
1199fe6060f1SDimitry Andric                                                    MachineInstr *&BrCond) {
12000b57cec5SDimitry Andric   MachineBasicBlock *BrTarget = MI.getOperand(0).getMBB();
1201e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(*BrCond);
1202e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(BrCond->getOperand(0).getReg());
1203e8d8bef9SDimitry Andric   // FIXME: Does int/fp matter for this? If so, we might need to restrict
1204e8d8bef9SDimitry Andric   // this to i1 only since we might not know for sure what kind of
1205e8d8bef9SDimitry Andric   // compare generated the condition value.
1206e8d8bef9SDimitry Andric   auto True = Builder.buildConstant(
1207e8d8bef9SDimitry Andric       Ty, getICmpTrueVal(getTargetLowering(), false, false));
1208e8d8bef9SDimitry Andric   auto Xor = Builder.buildXor(Ty, BrCond->getOperand(0), True);
12090b57cec5SDimitry Andric 
1210e8d8bef9SDimitry Andric   auto *FallthroughBB = BrCond->getOperand(1).getMBB();
1211e8d8bef9SDimitry Andric   Observer.changingInstr(MI);
1212e8d8bef9SDimitry Andric   MI.getOperand(0).setMBB(FallthroughBB);
1213e8d8bef9SDimitry Andric   Observer.changedInstr(MI);
12140b57cec5SDimitry Andric 
1215e8d8bef9SDimitry Andric   // Change the conditional branch to use the inverted condition and
1216e8d8bef9SDimitry Andric   // new target block.
12170b57cec5SDimitry Andric   Observer.changingInstr(*BrCond);
1218e8d8bef9SDimitry Andric   BrCond->getOperand(0).setReg(Xor.getReg(0));
12190b57cec5SDimitry Andric   BrCond->getOperand(1).setMBB(BrTarget);
12200b57cec5SDimitry Andric   Observer.changedInstr(*BrCond);
12218bcb0991SDimitry Andric }
12228bcb0991SDimitry Andric 
12238bcb0991SDimitry Andric static Type *getTypeForLLT(LLT Ty, LLVMContext &C) {
12248bcb0991SDimitry Andric   if (Ty.isVector())
12255ffd83dbSDimitry Andric     return FixedVectorType::get(IntegerType::get(C, Ty.getScalarSizeInBits()),
12268bcb0991SDimitry Andric                                 Ty.getNumElements());
12278bcb0991SDimitry Andric   return IntegerType::get(C, Ty.getSizeInBits());
12288bcb0991SDimitry Andric }
12298bcb0991SDimitry Andric 
1230fe6060f1SDimitry Andric bool CombinerHelper::tryEmitMemcpyInline(MachineInstr &MI) {
1231349cc55cSDimitry Andric   MachineIRBuilder HelperBuilder(MI);
1232349cc55cSDimitry Andric   GISelObserverWrapper DummyObserver;
1233349cc55cSDimitry Andric   LegalizerHelper Helper(HelperBuilder.getMF(), DummyObserver, HelperBuilder);
1234349cc55cSDimitry Andric   return Helper.lowerMemcpyInline(MI) ==
1235349cc55cSDimitry Andric          LegalizerHelper::LegalizeResult::Legalized;
12368bcb0991SDimitry Andric }
12378bcb0991SDimitry Andric 
12388bcb0991SDimitry Andric bool CombinerHelper::tryCombineMemCpyFamily(MachineInstr &MI, unsigned MaxLen) {
1239349cc55cSDimitry Andric   MachineIRBuilder HelperBuilder(MI);
1240349cc55cSDimitry Andric   GISelObserverWrapper DummyObserver;
1241349cc55cSDimitry Andric   LegalizerHelper Helper(HelperBuilder.getMF(), DummyObserver, HelperBuilder);
1242349cc55cSDimitry Andric   return Helper.lowerMemCpyFamily(MI, MaxLen) ==
1243349cc55cSDimitry Andric          LegalizerHelper::LegalizeResult::Legalized;
12448bcb0991SDimitry Andric }
12458bcb0991SDimitry Andric 
1246e8d8bef9SDimitry Andric static Optional<APFloat> constantFoldFpUnary(unsigned Opcode, LLT DstTy,
1247e8d8bef9SDimitry Andric                                              const Register Op,
1248e8d8bef9SDimitry Andric                                              const MachineRegisterInfo &MRI) {
1249e8d8bef9SDimitry Andric   const ConstantFP *MaybeCst = getConstantFPVRegVal(Op, MRI);
1250e8d8bef9SDimitry Andric   if (!MaybeCst)
1251e8d8bef9SDimitry Andric     return None;
1252e8d8bef9SDimitry Andric 
1253e8d8bef9SDimitry Andric   APFloat V = MaybeCst->getValueAPF();
1254e8d8bef9SDimitry Andric   switch (Opcode) {
1255e8d8bef9SDimitry Andric   default:
1256e8d8bef9SDimitry Andric     llvm_unreachable("Unexpected opcode!");
1257e8d8bef9SDimitry Andric   case TargetOpcode::G_FNEG: {
1258e8d8bef9SDimitry Andric     V.changeSign();
1259e8d8bef9SDimitry Andric     return V;
1260e8d8bef9SDimitry Andric   }
1261e8d8bef9SDimitry Andric   case TargetOpcode::G_FABS: {
1262e8d8bef9SDimitry Andric     V.clearSign();
1263e8d8bef9SDimitry Andric     return V;
1264e8d8bef9SDimitry Andric   }
1265e8d8bef9SDimitry Andric   case TargetOpcode::G_FPTRUNC:
1266e8d8bef9SDimitry Andric     break;
1267e8d8bef9SDimitry Andric   case TargetOpcode::G_FSQRT: {
1268e8d8bef9SDimitry Andric     bool Unused;
1269e8d8bef9SDimitry Andric     V.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &Unused);
1270e8d8bef9SDimitry Andric     V = APFloat(sqrt(V.convertToDouble()));
1271e8d8bef9SDimitry Andric     break;
1272e8d8bef9SDimitry Andric   }
1273e8d8bef9SDimitry Andric   case TargetOpcode::G_FLOG2: {
1274e8d8bef9SDimitry Andric     bool Unused;
1275e8d8bef9SDimitry Andric     V.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &Unused);
1276e8d8bef9SDimitry Andric     V = APFloat(log2(V.convertToDouble()));
1277e8d8bef9SDimitry Andric     break;
1278e8d8bef9SDimitry Andric   }
1279e8d8bef9SDimitry Andric   }
1280e8d8bef9SDimitry Andric   // Convert `APFloat` to appropriate IEEE type depending on `DstTy`. Otherwise,
1281e8d8bef9SDimitry Andric   // `buildFConstant` will assert on size mismatch. Only `G_FPTRUNC`, `G_FSQRT`,
1282e8d8bef9SDimitry Andric   // and `G_FLOG2` reach here.
1283e8d8bef9SDimitry Andric   bool Unused;
1284e8d8bef9SDimitry Andric   V.convert(getFltSemanticForLLT(DstTy), APFloat::rmNearestTiesToEven, &Unused);
1285e8d8bef9SDimitry Andric   return V;
1286e8d8bef9SDimitry Andric }
1287e8d8bef9SDimitry Andric 
1288e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineConstantFoldFpUnary(MachineInstr &MI,
1289e8d8bef9SDimitry Andric                                                      Optional<APFloat> &Cst) {
1290e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
1291e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
1292e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
1293e8d8bef9SDimitry Andric   Cst = constantFoldFpUnary(MI.getOpcode(), DstTy, SrcReg, MRI);
1294*81ad6265SDimitry Andric   return Cst.has_value();
1295e8d8bef9SDimitry Andric }
1296e8d8bef9SDimitry Andric 
1297fe6060f1SDimitry Andric void CombinerHelper::applyCombineConstantFoldFpUnary(MachineInstr &MI,
1298e8d8bef9SDimitry Andric                                                      Optional<APFloat> &Cst) {
1299*81ad6265SDimitry Andric   assert(Cst && "Optional is unexpectedly empty!");
1300e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
1301e8d8bef9SDimitry Andric   MachineFunction &MF = Builder.getMF();
1302e8d8bef9SDimitry Andric   auto *FPVal = ConstantFP::get(MF.getFunction().getContext(), *Cst);
1303e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
1304e8d8bef9SDimitry Andric   Builder.buildFConstant(DstReg, *FPVal);
1305e8d8bef9SDimitry Andric   MI.eraseFromParent();
1306e8d8bef9SDimitry Andric }
1307e8d8bef9SDimitry Andric 
1308480093f4SDimitry Andric bool CombinerHelper::matchPtrAddImmedChain(MachineInstr &MI,
1309480093f4SDimitry Andric                                            PtrAddChain &MatchInfo) {
1310480093f4SDimitry Andric   // We're trying to match the following pattern:
1311480093f4SDimitry Andric   //   %t1 = G_PTR_ADD %base, G_CONSTANT imm1
1312480093f4SDimitry Andric   //   %root = G_PTR_ADD %t1, G_CONSTANT imm2
1313480093f4SDimitry Andric   // -->
1314480093f4SDimitry Andric   //   %root = G_PTR_ADD %base, G_CONSTANT (imm1 + imm2)
1315480093f4SDimitry Andric 
1316480093f4SDimitry Andric   if (MI.getOpcode() != TargetOpcode::G_PTR_ADD)
1317480093f4SDimitry Andric     return false;
1318480093f4SDimitry Andric 
1319480093f4SDimitry Andric   Register Add2 = MI.getOperand(1).getReg();
1320480093f4SDimitry Andric   Register Imm1 = MI.getOperand(2).getReg();
1321349cc55cSDimitry Andric   auto MaybeImmVal = getIConstantVRegValWithLookThrough(Imm1, MRI);
1322480093f4SDimitry Andric   if (!MaybeImmVal)
1323480093f4SDimitry Andric     return false;
1324480093f4SDimitry Andric 
1325349cc55cSDimitry Andric   MachineInstr *Add2Def = MRI.getVRegDef(Add2);
1326480093f4SDimitry Andric   if (!Add2Def || Add2Def->getOpcode() != TargetOpcode::G_PTR_ADD)
1327480093f4SDimitry Andric     return false;
1328480093f4SDimitry Andric 
1329480093f4SDimitry Andric   Register Base = Add2Def->getOperand(1).getReg();
1330480093f4SDimitry Andric   Register Imm2 = Add2Def->getOperand(2).getReg();
1331349cc55cSDimitry Andric   auto MaybeImm2Val = getIConstantVRegValWithLookThrough(Imm2, MRI);
1332480093f4SDimitry Andric   if (!MaybeImm2Val)
1333480093f4SDimitry Andric     return false;
1334480093f4SDimitry Andric 
1335349cc55cSDimitry Andric   // Check if the new combined immediate forms an illegal addressing mode.
1336349cc55cSDimitry Andric   // Do not combine if it was legal before but would get illegal.
1337349cc55cSDimitry Andric   // To do so, we need to find a load/store user of the pointer to get
1338349cc55cSDimitry Andric   // the access type.
1339349cc55cSDimitry Andric   Type *AccessTy = nullptr;
1340349cc55cSDimitry Andric   auto &MF = *MI.getMF();
1341349cc55cSDimitry Andric   for (auto &UseMI : MRI.use_nodbg_instructions(MI.getOperand(0).getReg())) {
1342349cc55cSDimitry Andric     if (auto *LdSt = dyn_cast<GLoadStore>(&UseMI)) {
1343349cc55cSDimitry Andric       AccessTy = getTypeForLLT(MRI.getType(LdSt->getReg(0)),
1344349cc55cSDimitry Andric                                MF.getFunction().getContext());
1345349cc55cSDimitry Andric       break;
1346349cc55cSDimitry Andric     }
1347349cc55cSDimitry Andric   }
1348349cc55cSDimitry Andric   TargetLoweringBase::AddrMode AMNew;
1349349cc55cSDimitry Andric   APInt CombinedImm = MaybeImmVal->Value + MaybeImm2Val->Value;
1350349cc55cSDimitry Andric   AMNew.BaseOffs = CombinedImm.getSExtValue();
1351349cc55cSDimitry Andric   if (AccessTy) {
1352349cc55cSDimitry Andric     AMNew.HasBaseReg = true;
1353349cc55cSDimitry Andric     TargetLoweringBase::AddrMode AMOld;
1354349cc55cSDimitry Andric     AMOld.BaseOffs = MaybeImm2Val->Value.getSExtValue();
1355349cc55cSDimitry Andric     AMOld.HasBaseReg = true;
1356349cc55cSDimitry Andric     unsigned AS = MRI.getType(Add2).getAddressSpace();
1357349cc55cSDimitry Andric     const auto &TLI = *MF.getSubtarget().getTargetLowering();
1358349cc55cSDimitry Andric     if (TLI.isLegalAddressingMode(MF.getDataLayout(), AMOld, AccessTy, AS) &&
1359349cc55cSDimitry Andric         !TLI.isLegalAddressingMode(MF.getDataLayout(), AMNew, AccessTy, AS))
1360349cc55cSDimitry Andric       return false;
1361349cc55cSDimitry Andric   }
1362349cc55cSDimitry Andric 
1363480093f4SDimitry Andric   // Pass the combined immediate to the apply function.
1364349cc55cSDimitry Andric   MatchInfo.Imm = AMNew.BaseOffs;
1365480093f4SDimitry Andric   MatchInfo.Base = Base;
1366349cc55cSDimitry Andric   MatchInfo.Bank = getRegBank(Imm2);
1367480093f4SDimitry Andric   return true;
1368480093f4SDimitry Andric }
1369480093f4SDimitry Andric 
1370fe6060f1SDimitry Andric void CombinerHelper::applyPtrAddImmedChain(MachineInstr &MI,
1371480093f4SDimitry Andric                                            PtrAddChain &MatchInfo) {
1372480093f4SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_PTR_ADD && "Expected G_PTR_ADD");
1373480093f4SDimitry Andric   MachineIRBuilder MIB(MI);
1374480093f4SDimitry Andric   LLT OffsetTy = MRI.getType(MI.getOperand(2).getReg());
1375480093f4SDimitry Andric   auto NewOffset = MIB.buildConstant(OffsetTy, MatchInfo.Imm);
1376349cc55cSDimitry Andric   setRegBank(NewOffset.getReg(0), MatchInfo.Bank);
1377480093f4SDimitry Andric   Observer.changingInstr(MI);
1378480093f4SDimitry Andric   MI.getOperand(1).setReg(MatchInfo.Base);
1379480093f4SDimitry Andric   MI.getOperand(2).setReg(NewOffset.getReg(0));
1380480093f4SDimitry Andric   Observer.changedInstr(MI);
1381480093f4SDimitry Andric }
1382480093f4SDimitry Andric 
1383e8d8bef9SDimitry Andric bool CombinerHelper::matchShiftImmedChain(MachineInstr &MI,
1384e8d8bef9SDimitry Andric                                           RegisterImmPair &MatchInfo) {
1385e8d8bef9SDimitry Andric   // We're trying to match the following pattern with any of
1386e8d8bef9SDimitry Andric   // G_SHL/G_ASHR/G_LSHR/G_SSHLSAT/G_USHLSAT shift instructions:
1387e8d8bef9SDimitry Andric   //   %t1 = SHIFT %base, G_CONSTANT imm1
1388e8d8bef9SDimitry Andric   //   %root = SHIFT %t1, G_CONSTANT imm2
1389e8d8bef9SDimitry Andric   // -->
1390e8d8bef9SDimitry Andric   //   %root = SHIFT %base, G_CONSTANT (imm1 + imm2)
1391e8d8bef9SDimitry Andric 
1392e8d8bef9SDimitry Andric   unsigned Opcode = MI.getOpcode();
1393e8d8bef9SDimitry Andric   assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR ||
1394e8d8bef9SDimitry Andric           Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_SSHLSAT ||
1395e8d8bef9SDimitry Andric           Opcode == TargetOpcode::G_USHLSAT) &&
1396e8d8bef9SDimitry Andric          "Expected G_SHL, G_ASHR, G_LSHR, G_SSHLSAT or G_USHLSAT");
1397e8d8bef9SDimitry Andric 
1398e8d8bef9SDimitry Andric   Register Shl2 = MI.getOperand(1).getReg();
1399e8d8bef9SDimitry Andric   Register Imm1 = MI.getOperand(2).getReg();
1400349cc55cSDimitry Andric   auto MaybeImmVal = getIConstantVRegValWithLookThrough(Imm1, MRI);
1401e8d8bef9SDimitry Andric   if (!MaybeImmVal)
1402e8d8bef9SDimitry Andric     return false;
1403e8d8bef9SDimitry Andric 
1404e8d8bef9SDimitry Andric   MachineInstr *Shl2Def = MRI.getUniqueVRegDef(Shl2);
1405e8d8bef9SDimitry Andric   if (Shl2Def->getOpcode() != Opcode)
1406e8d8bef9SDimitry Andric     return false;
1407e8d8bef9SDimitry Andric 
1408e8d8bef9SDimitry Andric   Register Base = Shl2Def->getOperand(1).getReg();
1409e8d8bef9SDimitry Andric   Register Imm2 = Shl2Def->getOperand(2).getReg();
1410349cc55cSDimitry Andric   auto MaybeImm2Val = getIConstantVRegValWithLookThrough(Imm2, MRI);
1411e8d8bef9SDimitry Andric   if (!MaybeImm2Val)
1412e8d8bef9SDimitry Andric     return false;
1413e8d8bef9SDimitry Andric 
1414e8d8bef9SDimitry Andric   // Pass the combined immediate to the apply function.
1415e8d8bef9SDimitry Andric   MatchInfo.Imm =
1416e8d8bef9SDimitry Andric       (MaybeImmVal->Value.getSExtValue() + MaybeImm2Val->Value).getSExtValue();
1417e8d8bef9SDimitry Andric   MatchInfo.Reg = Base;
1418e8d8bef9SDimitry Andric 
1419e8d8bef9SDimitry Andric   // There is no simple replacement for a saturating unsigned left shift that
1420e8d8bef9SDimitry Andric   // exceeds the scalar size.
1421e8d8bef9SDimitry Andric   if (Opcode == TargetOpcode::G_USHLSAT &&
1422e8d8bef9SDimitry Andric       MatchInfo.Imm >= MRI.getType(Shl2).getScalarSizeInBits())
1423e8d8bef9SDimitry Andric     return false;
1424e8d8bef9SDimitry Andric 
1425e8d8bef9SDimitry Andric   return true;
1426e8d8bef9SDimitry Andric }
1427e8d8bef9SDimitry Andric 
1428fe6060f1SDimitry Andric void CombinerHelper::applyShiftImmedChain(MachineInstr &MI,
1429e8d8bef9SDimitry Andric                                           RegisterImmPair &MatchInfo) {
1430e8d8bef9SDimitry Andric   unsigned Opcode = MI.getOpcode();
1431e8d8bef9SDimitry Andric   assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR ||
1432e8d8bef9SDimitry Andric           Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_SSHLSAT ||
1433e8d8bef9SDimitry Andric           Opcode == TargetOpcode::G_USHLSAT) &&
1434e8d8bef9SDimitry Andric          "Expected G_SHL, G_ASHR, G_LSHR, G_SSHLSAT or G_USHLSAT");
1435e8d8bef9SDimitry Andric 
1436e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
1437e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(MI.getOperand(1).getReg());
1438e8d8bef9SDimitry Andric   unsigned const ScalarSizeInBits = Ty.getScalarSizeInBits();
1439e8d8bef9SDimitry Andric   auto Imm = MatchInfo.Imm;
1440e8d8bef9SDimitry Andric 
1441e8d8bef9SDimitry Andric   if (Imm >= ScalarSizeInBits) {
1442e8d8bef9SDimitry Andric     // Any logical shift that exceeds scalar size will produce zero.
1443e8d8bef9SDimitry Andric     if (Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_LSHR) {
1444e8d8bef9SDimitry Andric       Builder.buildConstant(MI.getOperand(0), 0);
1445e8d8bef9SDimitry Andric       MI.eraseFromParent();
1446fe6060f1SDimitry Andric       return;
1447e8d8bef9SDimitry Andric     }
1448e8d8bef9SDimitry Andric     // Arithmetic shift and saturating signed left shift have no effect beyond
1449e8d8bef9SDimitry Andric     // scalar size.
1450e8d8bef9SDimitry Andric     Imm = ScalarSizeInBits - 1;
1451e8d8bef9SDimitry Andric   }
1452e8d8bef9SDimitry Andric 
1453e8d8bef9SDimitry Andric   LLT ImmTy = MRI.getType(MI.getOperand(2).getReg());
1454e8d8bef9SDimitry Andric   Register NewImm = Builder.buildConstant(ImmTy, Imm).getReg(0);
1455e8d8bef9SDimitry Andric   Observer.changingInstr(MI);
1456e8d8bef9SDimitry Andric   MI.getOperand(1).setReg(MatchInfo.Reg);
1457e8d8bef9SDimitry Andric   MI.getOperand(2).setReg(NewImm);
1458e8d8bef9SDimitry Andric   Observer.changedInstr(MI);
1459e8d8bef9SDimitry Andric }
1460e8d8bef9SDimitry Andric 
1461e8d8bef9SDimitry Andric bool CombinerHelper::matchShiftOfShiftedLogic(MachineInstr &MI,
1462e8d8bef9SDimitry Andric                                               ShiftOfShiftedLogic &MatchInfo) {
1463e8d8bef9SDimitry Andric   // We're trying to match the following pattern with any of
1464e8d8bef9SDimitry Andric   // G_SHL/G_ASHR/G_LSHR/G_USHLSAT/G_SSHLSAT shift instructions in combination
1465e8d8bef9SDimitry Andric   // with any of G_AND/G_OR/G_XOR logic instructions.
1466e8d8bef9SDimitry Andric   //   %t1 = SHIFT %X, G_CONSTANT C0
1467e8d8bef9SDimitry Andric   //   %t2 = LOGIC %t1, %Y
1468e8d8bef9SDimitry Andric   //   %root = SHIFT %t2, G_CONSTANT C1
1469e8d8bef9SDimitry Andric   // -->
1470e8d8bef9SDimitry Andric   //   %t3 = SHIFT %X, G_CONSTANT (C0+C1)
1471e8d8bef9SDimitry Andric   //   %t4 = SHIFT %Y, G_CONSTANT C1
1472e8d8bef9SDimitry Andric   //   %root = LOGIC %t3, %t4
1473e8d8bef9SDimitry Andric   unsigned ShiftOpcode = MI.getOpcode();
1474e8d8bef9SDimitry Andric   assert((ShiftOpcode == TargetOpcode::G_SHL ||
1475e8d8bef9SDimitry Andric           ShiftOpcode == TargetOpcode::G_ASHR ||
1476e8d8bef9SDimitry Andric           ShiftOpcode == TargetOpcode::G_LSHR ||
1477e8d8bef9SDimitry Andric           ShiftOpcode == TargetOpcode::G_USHLSAT ||
1478e8d8bef9SDimitry Andric           ShiftOpcode == TargetOpcode::G_SSHLSAT) &&
1479e8d8bef9SDimitry Andric          "Expected G_SHL, G_ASHR, G_LSHR, G_USHLSAT and G_SSHLSAT");
1480e8d8bef9SDimitry Andric 
1481e8d8bef9SDimitry Andric   // Match a one-use bitwise logic op.
1482e8d8bef9SDimitry Andric   Register LogicDest = MI.getOperand(1).getReg();
1483e8d8bef9SDimitry Andric   if (!MRI.hasOneNonDBGUse(LogicDest))
1484e8d8bef9SDimitry Andric     return false;
1485e8d8bef9SDimitry Andric 
1486e8d8bef9SDimitry Andric   MachineInstr *LogicMI = MRI.getUniqueVRegDef(LogicDest);
1487e8d8bef9SDimitry Andric   unsigned LogicOpcode = LogicMI->getOpcode();
1488e8d8bef9SDimitry Andric   if (LogicOpcode != TargetOpcode::G_AND && LogicOpcode != TargetOpcode::G_OR &&
1489e8d8bef9SDimitry Andric       LogicOpcode != TargetOpcode::G_XOR)
1490e8d8bef9SDimitry Andric     return false;
1491e8d8bef9SDimitry Andric 
1492e8d8bef9SDimitry Andric   // Find a matching one-use shift by constant.
1493e8d8bef9SDimitry Andric   const Register C1 = MI.getOperand(2).getReg();
1494349cc55cSDimitry Andric   auto MaybeImmVal = getIConstantVRegValWithLookThrough(C1, MRI);
1495e8d8bef9SDimitry Andric   if (!MaybeImmVal)
1496e8d8bef9SDimitry Andric     return false;
1497e8d8bef9SDimitry Andric 
1498e8d8bef9SDimitry Andric   const uint64_t C1Val = MaybeImmVal->Value.getZExtValue();
1499e8d8bef9SDimitry Andric 
1500e8d8bef9SDimitry Andric   auto matchFirstShift = [&](const MachineInstr *MI, uint64_t &ShiftVal) {
1501e8d8bef9SDimitry Andric     // Shift should match previous one and should be a one-use.
1502e8d8bef9SDimitry Andric     if (MI->getOpcode() != ShiftOpcode ||
1503e8d8bef9SDimitry Andric         !MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()))
1504e8d8bef9SDimitry Andric       return false;
1505e8d8bef9SDimitry Andric 
1506e8d8bef9SDimitry Andric     // Must be a constant.
1507e8d8bef9SDimitry Andric     auto MaybeImmVal =
1508349cc55cSDimitry Andric         getIConstantVRegValWithLookThrough(MI->getOperand(2).getReg(), MRI);
1509e8d8bef9SDimitry Andric     if (!MaybeImmVal)
1510e8d8bef9SDimitry Andric       return false;
1511e8d8bef9SDimitry Andric 
1512e8d8bef9SDimitry Andric     ShiftVal = MaybeImmVal->Value.getSExtValue();
1513e8d8bef9SDimitry Andric     return true;
1514e8d8bef9SDimitry Andric   };
1515e8d8bef9SDimitry Andric 
1516e8d8bef9SDimitry Andric   // Logic ops are commutative, so check each operand for a match.
1517e8d8bef9SDimitry Andric   Register LogicMIReg1 = LogicMI->getOperand(1).getReg();
1518e8d8bef9SDimitry Andric   MachineInstr *LogicMIOp1 = MRI.getUniqueVRegDef(LogicMIReg1);
1519e8d8bef9SDimitry Andric   Register LogicMIReg2 = LogicMI->getOperand(2).getReg();
1520e8d8bef9SDimitry Andric   MachineInstr *LogicMIOp2 = MRI.getUniqueVRegDef(LogicMIReg2);
1521e8d8bef9SDimitry Andric   uint64_t C0Val;
1522e8d8bef9SDimitry Andric 
1523e8d8bef9SDimitry Andric   if (matchFirstShift(LogicMIOp1, C0Val)) {
1524e8d8bef9SDimitry Andric     MatchInfo.LogicNonShiftReg = LogicMIReg2;
1525e8d8bef9SDimitry Andric     MatchInfo.Shift2 = LogicMIOp1;
1526e8d8bef9SDimitry Andric   } else if (matchFirstShift(LogicMIOp2, C0Val)) {
1527e8d8bef9SDimitry Andric     MatchInfo.LogicNonShiftReg = LogicMIReg1;
1528e8d8bef9SDimitry Andric     MatchInfo.Shift2 = LogicMIOp2;
1529e8d8bef9SDimitry Andric   } else
1530e8d8bef9SDimitry Andric     return false;
1531e8d8bef9SDimitry Andric 
1532e8d8bef9SDimitry Andric   MatchInfo.ValSum = C0Val + C1Val;
1533e8d8bef9SDimitry Andric 
1534e8d8bef9SDimitry Andric   // The fold is not valid if the sum of the shift values exceeds bitwidth.
1535e8d8bef9SDimitry Andric   if (MatchInfo.ValSum >= MRI.getType(LogicDest).getScalarSizeInBits())
1536e8d8bef9SDimitry Andric     return false;
1537e8d8bef9SDimitry Andric 
1538e8d8bef9SDimitry Andric   MatchInfo.Logic = LogicMI;
1539e8d8bef9SDimitry Andric   return true;
1540e8d8bef9SDimitry Andric }
1541e8d8bef9SDimitry Andric 
1542fe6060f1SDimitry Andric void CombinerHelper::applyShiftOfShiftedLogic(MachineInstr &MI,
1543e8d8bef9SDimitry Andric                                               ShiftOfShiftedLogic &MatchInfo) {
1544e8d8bef9SDimitry Andric   unsigned Opcode = MI.getOpcode();
1545e8d8bef9SDimitry Andric   assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR ||
1546e8d8bef9SDimitry Andric           Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_USHLSAT ||
1547e8d8bef9SDimitry Andric           Opcode == TargetOpcode::G_SSHLSAT) &&
1548e8d8bef9SDimitry Andric          "Expected G_SHL, G_ASHR, G_LSHR, G_USHLSAT and G_SSHLSAT");
1549e8d8bef9SDimitry Andric 
1550e8d8bef9SDimitry Andric   LLT ShlType = MRI.getType(MI.getOperand(2).getReg());
1551e8d8bef9SDimitry Andric   LLT DestType = MRI.getType(MI.getOperand(0).getReg());
1552e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
1553e8d8bef9SDimitry Andric 
1554e8d8bef9SDimitry Andric   Register Const = Builder.buildConstant(ShlType, MatchInfo.ValSum).getReg(0);
1555e8d8bef9SDimitry Andric 
1556e8d8bef9SDimitry Andric   Register Shift1Base = MatchInfo.Shift2->getOperand(1).getReg();
1557e8d8bef9SDimitry Andric   Register Shift1 =
1558e8d8bef9SDimitry Andric       Builder.buildInstr(Opcode, {DestType}, {Shift1Base, Const}).getReg(0);
1559e8d8bef9SDimitry Andric 
1560e8d8bef9SDimitry Andric   Register Shift2Const = MI.getOperand(2).getReg();
1561e8d8bef9SDimitry Andric   Register Shift2 = Builder
1562e8d8bef9SDimitry Andric                         .buildInstr(Opcode, {DestType},
1563e8d8bef9SDimitry Andric                                     {MatchInfo.LogicNonShiftReg, Shift2Const})
1564e8d8bef9SDimitry Andric                         .getReg(0);
1565e8d8bef9SDimitry Andric 
1566e8d8bef9SDimitry Andric   Register Dest = MI.getOperand(0).getReg();
1567e8d8bef9SDimitry Andric   Builder.buildInstr(MatchInfo.Logic->getOpcode(), {Dest}, {Shift1, Shift2});
1568e8d8bef9SDimitry Andric 
1569e8d8bef9SDimitry Andric   // These were one use so it's safe to remove them.
15700eae32dcSDimitry Andric   MatchInfo.Shift2->eraseFromParent();
15710eae32dcSDimitry Andric   MatchInfo.Logic->eraseFromParent();
1572e8d8bef9SDimitry Andric 
1573e8d8bef9SDimitry Andric   MI.eraseFromParent();
1574e8d8bef9SDimitry Andric }
1575e8d8bef9SDimitry Andric 
15765ffd83dbSDimitry Andric bool CombinerHelper::matchCombineMulToShl(MachineInstr &MI,
15775ffd83dbSDimitry Andric                                           unsigned &ShiftVal) {
15785ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL");
15795ffd83dbSDimitry Andric   auto MaybeImmVal =
1580349cc55cSDimitry Andric       getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
1581e8d8bef9SDimitry Andric   if (!MaybeImmVal)
15825ffd83dbSDimitry Andric     return false;
1583e8d8bef9SDimitry Andric 
1584e8d8bef9SDimitry Andric   ShiftVal = MaybeImmVal->Value.exactLogBase2();
1585e8d8bef9SDimitry Andric   return (static_cast<int32_t>(ShiftVal) != -1);
15865ffd83dbSDimitry Andric }
15875ffd83dbSDimitry Andric 
1588fe6060f1SDimitry Andric void CombinerHelper::applyCombineMulToShl(MachineInstr &MI,
15895ffd83dbSDimitry Andric                                           unsigned &ShiftVal) {
15905ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL");
15915ffd83dbSDimitry Andric   MachineIRBuilder MIB(MI);
15925ffd83dbSDimitry Andric   LLT ShiftTy = MRI.getType(MI.getOperand(0).getReg());
15935ffd83dbSDimitry Andric   auto ShiftCst = MIB.buildConstant(ShiftTy, ShiftVal);
15945ffd83dbSDimitry Andric   Observer.changingInstr(MI);
15955ffd83dbSDimitry Andric   MI.setDesc(MIB.getTII().get(TargetOpcode::G_SHL));
15965ffd83dbSDimitry Andric   MI.getOperand(2).setReg(ShiftCst.getReg(0));
15975ffd83dbSDimitry Andric   Observer.changedInstr(MI);
15985ffd83dbSDimitry Andric }
15995ffd83dbSDimitry Andric 
1600e8d8bef9SDimitry Andric // shl ([sza]ext x), y => zext (shl x, y), if shift does not overflow source
1601e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineShlOfExtend(MachineInstr &MI,
1602e8d8bef9SDimitry Andric                                              RegisterImmPair &MatchData) {
1603e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SHL && KB);
1604e8d8bef9SDimitry Andric 
1605e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
1606e8d8bef9SDimitry Andric 
1607e8d8bef9SDimitry Andric   Register ExtSrc;
1608e8d8bef9SDimitry Andric   if (!mi_match(LHS, MRI, m_GAnyExt(m_Reg(ExtSrc))) &&
1609e8d8bef9SDimitry Andric       !mi_match(LHS, MRI, m_GZExt(m_Reg(ExtSrc))) &&
1610e8d8bef9SDimitry Andric       !mi_match(LHS, MRI, m_GSExt(m_Reg(ExtSrc))))
1611e8d8bef9SDimitry Andric     return false;
1612e8d8bef9SDimitry Andric 
1613e8d8bef9SDimitry Andric   // TODO: Should handle vector splat.
1614e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
1615349cc55cSDimitry Andric   auto MaybeShiftAmtVal = getIConstantVRegValWithLookThrough(RHS, MRI);
1616e8d8bef9SDimitry Andric   if (!MaybeShiftAmtVal)
1617e8d8bef9SDimitry Andric     return false;
1618e8d8bef9SDimitry Andric 
1619e8d8bef9SDimitry Andric   if (LI) {
1620e8d8bef9SDimitry Andric     LLT SrcTy = MRI.getType(ExtSrc);
1621e8d8bef9SDimitry Andric 
1622e8d8bef9SDimitry Andric     // We only really care about the legality with the shifted value. We can
1623e8d8bef9SDimitry Andric     // pick any type the constant shift amount, so ask the target what to
1624e8d8bef9SDimitry Andric     // use. Otherwise we would have to guess and hope it is reported as legal.
1625e8d8bef9SDimitry Andric     LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(SrcTy);
1626e8d8bef9SDimitry Andric     if (!isLegalOrBeforeLegalizer({TargetOpcode::G_SHL, {SrcTy, ShiftAmtTy}}))
1627e8d8bef9SDimitry Andric       return false;
1628e8d8bef9SDimitry Andric   }
1629e8d8bef9SDimitry Andric 
1630e8d8bef9SDimitry Andric   int64_t ShiftAmt = MaybeShiftAmtVal->Value.getSExtValue();
1631e8d8bef9SDimitry Andric   MatchData.Reg = ExtSrc;
1632e8d8bef9SDimitry Andric   MatchData.Imm = ShiftAmt;
1633e8d8bef9SDimitry Andric 
1634e8d8bef9SDimitry Andric   unsigned MinLeadingZeros = KB->getKnownZeroes(ExtSrc).countLeadingOnes();
1635e8d8bef9SDimitry Andric   return MinLeadingZeros >= ShiftAmt;
1636e8d8bef9SDimitry Andric }
1637e8d8bef9SDimitry Andric 
1638fe6060f1SDimitry Andric void CombinerHelper::applyCombineShlOfExtend(MachineInstr &MI,
1639e8d8bef9SDimitry Andric                                              const RegisterImmPair &MatchData) {
1640e8d8bef9SDimitry Andric   Register ExtSrcReg = MatchData.Reg;
1641e8d8bef9SDimitry Andric   int64_t ShiftAmtVal = MatchData.Imm;
1642e8d8bef9SDimitry Andric 
1643e8d8bef9SDimitry Andric   LLT ExtSrcTy = MRI.getType(ExtSrcReg);
1644e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
1645e8d8bef9SDimitry Andric   auto ShiftAmt = Builder.buildConstant(ExtSrcTy, ShiftAmtVal);
1646e8d8bef9SDimitry Andric   auto NarrowShift =
1647e8d8bef9SDimitry Andric       Builder.buildShl(ExtSrcTy, ExtSrcReg, ShiftAmt, MI.getFlags());
1648e8d8bef9SDimitry Andric   Builder.buildZExt(MI.getOperand(0), NarrowShift);
1649e8d8bef9SDimitry Andric   MI.eraseFromParent();
1650fe6060f1SDimitry Andric }
1651fe6060f1SDimitry Andric 
1652fe6060f1SDimitry Andric bool CombinerHelper::matchCombineMergeUnmerge(MachineInstr &MI,
1653fe6060f1SDimitry Andric                                               Register &MatchInfo) {
1654fe6060f1SDimitry Andric   GMerge &Merge = cast<GMerge>(MI);
1655fe6060f1SDimitry Andric   SmallVector<Register, 16> MergedValues;
1656fe6060f1SDimitry Andric   for (unsigned I = 0; I < Merge.getNumSources(); ++I)
1657fe6060f1SDimitry Andric     MergedValues.emplace_back(Merge.getSourceReg(I));
1658fe6060f1SDimitry Andric 
1659fe6060f1SDimitry Andric   auto *Unmerge = getOpcodeDef<GUnmerge>(MergedValues[0], MRI);
1660fe6060f1SDimitry Andric   if (!Unmerge || Unmerge->getNumDefs() != Merge.getNumSources())
1661fe6060f1SDimitry Andric     return false;
1662fe6060f1SDimitry Andric 
1663fe6060f1SDimitry Andric   for (unsigned I = 0; I < MergedValues.size(); ++I)
1664fe6060f1SDimitry Andric     if (MergedValues[I] != Unmerge->getReg(I))
1665fe6060f1SDimitry Andric       return false;
1666fe6060f1SDimitry Andric 
1667fe6060f1SDimitry Andric   MatchInfo = Unmerge->getSourceReg();
1668e8d8bef9SDimitry Andric   return true;
1669e8d8bef9SDimitry Andric }
1670e8d8bef9SDimitry Andric 
1671e8d8bef9SDimitry Andric static Register peekThroughBitcast(Register Reg,
1672e8d8bef9SDimitry Andric                                    const MachineRegisterInfo &MRI) {
1673e8d8bef9SDimitry Andric   while (mi_match(Reg, MRI, m_GBitcast(m_Reg(Reg))))
1674e8d8bef9SDimitry Andric     ;
1675e8d8bef9SDimitry Andric 
1676e8d8bef9SDimitry Andric   return Reg;
1677e8d8bef9SDimitry Andric }
1678e8d8bef9SDimitry Andric 
1679e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineUnmergeMergeToPlainValues(
1680e8d8bef9SDimitry Andric     MachineInstr &MI, SmallVectorImpl<Register> &Operands) {
1681e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1682e8d8bef9SDimitry Andric          "Expected an unmerge");
1683349cc55cSDimitry Andric   auto &Unmerge = cast<GUnmerge>(MI);
1684349cc55cSDimitry Andric   Register SrcReg = peekThroughBitcast(Unmerge.getSourceReg(), MRI);
1685e8d8bef9SDimitry Andric 
1686349cc55cSDimitry Andric   auto *SrcInstr = getOpcodeDef<GMergeLikeOp>(SrcReg, MRI);
1687349cc55cSDimitry Andric   if (!SrcInstr)
1688e8d8bef9SDimitry Andric     return false;
1689e8d8bef9SDimitry Andric 
1690e8d8bef9SDimitry Andric   // Check the source type of the merge.
1691349cc55cSDimitry Andric   LLT SrcMergeTy = MRI.getType(SrcInstr->getSourceReg(0));
1692349cc55cSDimitry Andric   LLT Dst0Ty = MRI.getType(Unmerge.getReg(0));
1693e8d8bef9SDimitry Andric   bool SameSize = Dst0Ty.getSizeInBits() == SrcMergeTy.getSizeInBits();
1694e8d8bef9SDimitry Andric   if (SrcMergeTy != Dst0Ty && !SameSize)
1695e8d8bef9SDimitry Andric     return false;
1696e8d8bef9SDimitry Andric   // They are the same now (modulo a bitcast).
1697e8d8bef9SDimitry Andric   // We can collect all the src registers.
1698349cc55cSDimitry Andric   for (unsigned Idx = 0; Idx < SrcInstr->getNumSources(); ++Idx)
1699349cc55cSDimitry Andric     Operands.push_back(SrcInstr->getSourceReg(Idx));
1700e8d8bef9SDimitry Andric   return true;
1701e8d8bef9SDimitry Andric }
1702e8d8bef9SDimitry Andric 
1703fe6060f1SDimitry Andric void CombinerHelper::applyCombineUnmergeMergeToPlainValues(
1704e8d8bef9SDimitry Andric     MachineInstr &MI, SmallVectorImpl<Register> &Operands) {
1705e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1706e8d8bef9SDimitry Andric          "Expected an unmerge");
1707e8d8bef9SDimitry Andric   assert((MI.getNumOperands() - 1 == Operands.size()) &&
1708e8d8bef9SDimitry Andric          "Not enough operands to replace all defs");
1709e8d8bef9SDimitry Andric   unsigned NumElems = MI.getNumOperands() - 1;
1710e8d8bef9SDimitry Andric 
1711e8d8bef9SDimitry Andric   LLT SrcTy = MRI.getType(Operands[0]);
1712e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
1713e8d8bef9SDimitry Andric   bool CanReuseInputDirectly = DstTy == SrcTy;
1714e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
1715e8d8bef9SDimitry Andric   for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
1716e8d8bef9SDimitry Andric     Register DstReg = MI.getOperand(Idx).getReg();
1717e8d8bef9SDimitry Andric     Register SrcReg = Operands[Idx];
1718e8d8bef9SDimitry Andric     if (CanReuseInputDirectly)
1719e8d8bef9SDimitry Andric       replaceRegWith(MRI, DstReg, SrcReg);
1720e8d8bef9SDimitry Andric     else
1721e8d8bef9SDimitry Andric       Builder.buildCast(DstReg, SrcReg);
1722e8d8bef9SDimitry Andric   }
1723e8d8bef9SDimitry Andric   MI.eraseFromParent();
1724e8d8bef9SDimitry Andric }
1725e8d8bef9SDimitry Andric 
1726e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineUnmergeConstant(MachineInstr &MI,
1727e8d8bef9SDimitry Andric                                                  SmallVectorImpl<APInt> &Csts) {
1728e8d8bef9SDimitry Andric   unsigned SrcIdx = MI.getNumOperands() - 1;
1729e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(SrcIdx).getReg();
1730e8d8bef9SDimitry Andric   MachineInstr *SrcInstr = MRI.getVRegDef(SrcReg);
1731e8d8bef9SDimitry Andric   if (SrcInstr->getOpcode() != TargetOpcode::G_CONSTANT &&
1732e8d8bef9SDimitry Andric       SrcInstr->getOpcode() != TargetOpcode::G_FCONSTANT)
1733e8d8bef9SDimitry Andric     return false;
1734e8d8bef9SDimitry Andric   // Break down the big constant in smaller ones.
1735e8d8bef9SDimitry Andric   const MachineOperand &CstVal = SrcInstr->getOperand(1);
1736e8d8bef9SDimitry Andric   APInt Val = SrcInstr->getOpcode() == TargetOpcode::G_CONSTANT
1737e8d8bef9SDimitry Andric                   ? CstVal.getCImm()->getValue()
1738e8d8bef9SDimitry Andric                   : CstVal.getFPImm()->getValueAPF().bitcastToAPInt();
1739e8d8bef9SDimitry Andric 
1740e8d8bef9SDimitry Andric   LLT Dst0Ty = MRI.getType(MI.getOperand(0).getReg());
1741e8d8bef9SDimitry Andric   unsigned ShiftAmt = Dst0Ty.getSizeInBits();
1742e8d8bef9SDimitry Andric   // Unmerge a constant.
1743e8d8bef9SDimitry Andric   for (unsigned Idx = 0; Idx != SrcIdx; ++Idx) {
1744e8d8bef9SDimitry Andric     Csts.emplace_back(Val.trunc(ShiftAmt));
1745e8d8bef9SDimitry Andric     Val = Val.lshr(ShiftAmt);
1746e8d8bef9SDimitry Andric   }
1747e8d8bef9SDimitry Andric 
1748e8d8bef9SDimitry Andric   return true;
1749e8d8bef9SDimitry Andric }
1750e8d8bef9SDimitry Andric 
1751fe6060f1SDimitry Andric void CombinerHelper::applyCombineUnmergeConstant(MachineInstr &MI,
1752e8d8bef9SDimitry Andric                                                  SmallVectorImpl<APInt> &Csts) {
1753e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1754e8d8bef9SDimitry Andric          "Expected an unmerge");
1755e8d8bef9SDimitry Andric   assert((MI.getNumOperands() - 1 == Csts.size()) &&
1756e8d8bef9SDimitry Andric          "Not enough operands to replace all defs");
1757e8d8bef9SDimitry Andric   unsigned NumElems = MI.getNumOperands() - 1;
1758e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
1759e8d8bef9SDimitry Andric   for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
1760e8d8bef9SDimitry Andric     Register DstReg = MI.getOperand(Idx).getReg();
1761e8d8bef9SDimitry Andric     Builder.buildConstant(DstReg, Csts[Idx]);
1762e8d8bef9SDimitry Andric   }
1763e8d8bef9SDimitry Andric 
1764e8d8bef9SDimitry Andric   MI.eraseFromParent();
1765e8d8bef9SDimitry Andric }
1766e8d8bef9SDimitry Andric 
176704eeddc0SDimitry Andric bool CombinerHelper::matchCombineUnmergeUndef(
176804eeddc0SDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
176904eeddc0SDimitry Andric   unsigned SrcIdx = MI.getNumOperands() - 1;
177004eeddc0SDimitry Andric   Register SrcReg = MI.getOperand(SrcIdx).getReg();
177104eeddc0SDimitry Andric   MatchInfo = [&MI](MachineIRBuilder &B) {
177204eeddc0SDimitry Andric     unsigned NumElems = MI.getNumOperands() - 1;
177304eeddc0SDimitry Andric     for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
177404eeddc0SDimitry Andric       Register DstReg = MI.getOperand(Idx).getReg();
177504eeddc0SDimitry Andric       B.buildUndef(DstReg);
177604eeddc0SDimitry Andric     }
177704eeddc0SDimitry Andric   };
177804eeddc0SDimitry Andric   return isa<GImplicitDef>(MRI.getVRegDef(SrcReg));
177904eeddc0SDimitry Andric }
178004eeddc0SDimitry Andric 
1781e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineUnmergeWithDeadLanesToTrunc(MachineInstr &MI) {
1782e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1783e8d8bef9SDimitry Andric          "Expected an unmerge");
1784e8d8bef9SDimitry Andric   // Check that all the lanes are dead except the first one.
1785e8d8bef9SDimitry Andric   for (unsigned Idx = 1, EndIdx = MI.getNumDefs(); Idx != EndIdx; ++Idx) {
1786e8d8bef9SDimitry Andric     if (!MRI.use_nodbg_empty(MI.getOperand(Idx).getReg()))
1787e8d8bef9SDimitry Andric       return false;
1788e8d8bef9SDimitry Andric   }
1789e8d8bef9SDimitry Andric   return true;
1790e8d8bef9SDimitry Andric }
1791e8d8bef9SDimitry Andric 
1792fe6060f1SDimitry Andric void CombinerHelper::applyCombineUnmergeWithDeadLanesToTrunc(MachineInstr &MI) {
1793e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
1794e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(MI.getNumDefs()).getReg();
1795e8d8bef9SDimitry Andric   // Truncating a vector is going to truncate every single lane,
1796e8d8bef9SDimitry Andric   // whereas we want the full lowbits.
1797e8d8bef9SDimitry Andric   // Do the operation on a scalar instead.
1798e8d8bef9SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
1799e8d8bef9SDimitry Andric   if (SrcTy.isVector())
1800e8d8bef9SDimitry Andric     SrcReg =
1801e8d8bef9SDimitry Andric         Builder.buildCast(LLT::scalar(SrcTy.getSizeInBits()), SrcReg).getReg(0);
1802e8d8bef9SDimitry Andric 
1803e8d8bef9SDimitry Andric   Register Dst0Reg = MI.getOperand(0).getReg();
1804e8d8bef9SDimitry Andric   LLT Dst0Ty = MRI.getType(Dst0Reg);
1805e8d8bef9SDimitry Andric   if (Dst0Ty.isVector()) {
1806e8d8bef9SDimitry Andric     auto MIB = Builder.buildTrunc(LLT::scalar(Dst0Ty.getSizeInBits()), SrcReg);
1807e8d8bef9SDimitry Andric     Builder.buildCast(Dst0Reg, MIB);
1808e8d8bef9SDimitry Andric   } else
1809e8d8bef9SDimitry Andric     Builder.buildTrunc(Dst0Reg, SrcReg);
1810e8d8bef9SDimitry Andric   MI.eraseFromParent();
1811e8d8bef9SDimitry Andric }
1812e8d8bef9SDimitry Andric 
1813e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineUnmergeZExtToZExt(MachineInstr &MI) {
1814e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1815e8d8bef9SDimitry Andric          "Expected an unmerge");
1816e8d8bef9SDimitry Andric   Register Dst0Reg = MI.getOperand(0).getReg();
1817e8d8bef9SDimitry Andric   LLT Dst0Ty = MRI.getType(Dst0Reg);
1818e8d8bef9SDimitry Andric   // G_ZEXT on vector applies to each lane, so it will
1819e8d8bef9SDimitry Andric   // affect all destinations. Therefore we won't be able
1820e8d8bef9SDimitry Andric   // to simplify the unmerge to just the first definition.
1821e8d8bef9SDimitry Andric   if (Dst0Ty.isVector())
1822e8d8bef9SDimitry Andric     return false;
1823e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(MI.getNumDefs()).getReg();
1824e8d8bef9SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
1825e8d8bef9SDimitry Andric   if (SrcTy.isVector())
1826e8d8bef9SDimitry Andric     return false;
1827e8d8bef9SDimitry Andric 
1828e8d8bef9SDimitry Andric   Register ZExtSrcReg;
1829e8d8bef9SDimitry Andric   if (!mi_match(SrcReg, MRI, m_GZExt(m_Reg(ZExtSrcReg))))
1830e8d8bef9SDimitry Andric     return false;
1831e8d8bef9SDimitry Andric 
1832e8d8bef9SDimitry Andric   // Finally we can replace the first definition with
1833e8d8bef9SDimitry Andric   // a zext of the source if the definition is big enough to hold
1834e8d8bef9SDimitry Andric   // all of ZExtSrc bits.
1835e8d8bef9SDimitry Andric   LLT ZExtSrcTy = MRI.getType(ZExtSrcReg);
1836e8d8bef9SDimitry Andric   return ZExtSrcTy.getSizeInBits() <= Dst0Ty.getSizeInBits();
1837e8d8bef9SDimitry Andric }
1838e8d8bef9SDimitry Andric 
1839fe6060f1SDimitry Andric void CombinerHelper::applyCombineUnmergeZExtToZExt(MachineInstr &MI) {
1840e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1841e8d8bef9SDimitry Andric          "Expected an unmerge");
1842e8d8bef9SDimitry Andric 
1843e8d8bef9SDimitry Andric   Register Dst0Reg = MI.getOperand(0).getReg();
1844e8d8bef9SDimitry Andric 
1845e8d8bef9SDimitry Andric   MachineInstr *ZExtInstr =
1846e8d8bef9SDimitry Andric       MRI.getVRegDef(MI.getOperand(MI.getNumDefs()).getReg());
1847e8d8bef9SDimitry Andric   assert(ZExtInstr && ZExtInstr->getOpcode() == TargetOpcode::G_ZEXT &&
1848e8d8bef9SDimitry Andric          "Expecting a G_ZEXT");
1849e8d8bef9SDimitry Andric 
1850e8d8bef9SDimitry Andric   Register ZExtSrcReg = ZExtInstr->getOperand(1).getReg();
1851e8d8bef9SDimitry Andric   LLT Dst0Ty = MRI.getType(Dst0Reg);
1852e8d8bef9SDimitry Andric   LLT ZExtSrcTy = MRI.getType(ZExtSrcReg);
1853e8d8bef9SDimitry Andric 
1854e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
1855e8d8bef9SDimitry Andric 
1856e8d8bef9SDimitry Andric   if (Dst0Ty.getSizeInBits() > ZExtSrcTy.getSizeInBits()) {
1857e8d8bef9SDimitry Andric     Builder.buildZExt(Dst0Reg, ZExtSrcReg);
1858e8d8bef9SDimitry Andric   } else {
1859e8d8bef9SDimitry Andric     assert(Dst0Ty.getSizeInBits() == ZExtSrcTy.getSizeInBits() &&
1860e8d8bef9SDimitry Andric            "ZExt src doesn't fit in destination");
1861e8d8bef9SDimitry Andric     replaceRegWith(MRI, Dst0Reg, ZExtSrcReg);
1862e8d8bef9SDimitry Andric   }
1863e8d8bef9SDimitry Andric 
1864e8d8bef9SDimitry Andric   Register ZeroReg;
1865e8d8bef9SDimitry Andric   for (unsigned Idx = 1, EndIdx = MI.getNumDefs(); Idx != EndIdx; ++Idx) {
1866e8d8bef9SDimitry Andric     if (!ZeroReg)
1867e8d8bef9SDimitry Andric       ZeroReg = Builder.buildConstant(Dst0Ty, 0).getReg(0);
1868e8d8bef9SDimitry Andric     replaceRegWith(MRI, MI.getOperand(Idx).getReg(), ZeroReg);
1869e8d8bef9SDimitry Andric   }
1870e8d8bef9SDimitry Andric   MI.eraseFromParent();
1871e8d8bef9SDimitry Andric }
1872e8d8bef9SDimitry Andric 
18735ffd83dbSDimitry Andric bool CombinerHelper::matchCombineShiftToUnmerge(MachineInstr &MI,
18745ffd83dbSDimitry Andric                                                 unsigned TargetShiftSize,
18755ffd83dbSDimitry Andric                                                 unsigned &ShiftVal) {
18765ffd83dbSDimitry Andric   assert((MI.getOpcode() == TargetOpcode::G_SHL ||
18775ffd83dbSDimitry Andric           MI.getOpcode() == TargetOpcode::G_LSHR ||
18785ffd83dbSDimitry Andric           MI.getOpcode() == TargetOpcode::G_ASHR) && "Expected a shift");
18795ffd83dbSDimitry Andric 
18805ffd83dbSDimitry Andric   LLT Ty = MRI.getType(MI.getOperand(0).getReg());
18815ffd83dbSDimitry Andric   if (Ty.isVector()) // TODO:
18825ffd83dbSDimitry Andric     return false;
18835ffd83dbSDimitry Andric 
18845ffd83dbSDimitry Andric   // Don't narrow further than the requested size.
18855ffd83dbSDimitry Andric   unsigned Size = Ty.getSizeInBits();
18865ffd83dbSDimitry Andric   if (Size <= TargetShiftSize)
18875ffd83dbSDimitry Andric     return false;
18885ffd83dbSDimitry Andric 
18895ffd83dbSDimitry Andric   auto MaybeImmVal =
1890349cc55cSDimitry Andric       getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
18915ffd83dbSDimitry Andric   if (!MaybeImmVal)
18925ffd83dbSDimitry Andric     return false;
18935ffd83dbSDimitry Andric 
1894e8d8bef9SDimitry Andric   ShiftVal = MaybeImmVal->Value.getSExtValue();
18955ffd83dbSDimitry Andric   return ShiftVal >= Size / 2 && ShiftVal < Size;
18965ffd83dbSDimitry Andric }
18975ffd83dbSDimitry Andric 
1898fe6060f1SDimitry Andric void CombinerHelper::applyCombineShiftToUnmerge(MachineInstr &MI,
18995ffd83dbSDimitry Andric                                                 const unsigned &ShiftVal) {
19005ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
19015ffd83dbSDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
19025ffd83dbSDimitry Andric   LLT Ty = MRI.getType(SrcReg);
19035ffd83dbSDimitry Andric   unsigned Size = Ty.getSizeInBits();
19045ffd83dbSDimitry Andric   unsigned HalfSize = Size / 2;
19055ffd83dbSDimitry Andric   assert(ShiftVal >= HalfSize);
19065ffd83dbSDimitry Andric 
19075ffd83dbSDimitry Andric   LLT HalfTy = LLT::scalar(HalfSize);
19085ffd83dbSDimitry Andric 
19095ffd83dbSDimitry Andric   Builder.setInstr(MI);
19105ffd83dbSDimitry Andric   auto Unmerge = Builder.buildUnmerge(HalfTy, SrcReg);
19115ffd83dbSDimitry Andric   unsigned NarrowShiftAmt = ShiftVal - HalfSize;
19125ffd83dbSDimitry Andric 
19135ffd83dbSDimitry Andric   if (MI.getOpcode() == TargetOpcode::G_LSHR) {
19145ffd83dbSDimitry Andric     Register Narrowed = Unmerge.getReg(1);
19155ffd83dbSDimitry Andric 
19165ffd83dbSDimitry Andric     //  dst = G_LSHR s64:x, C for C >= 32
19175ffd83dbSDimitry Andric     // =>
19185ffd83dbSDimitry Andric     //   lo, hi = G_UNMERGE_VALUES x
19195ffd83dbSDimitry Andric     //   dst = G_MERGE_VALUES (G_LSHR hi, C - 32), 0
19205ffd83dbSDimitry Andric 
19215ffd83dbSDimitry Andric     if (NarrowShiftAmt != 0) {
19225ffd83dbSDimitry Andric       Narrowed = Builder.buildLShr(HalfTy, Narrowed,
19235ffd83dbSDimitry Andric         Builder.buildConstant(HalfTy, NarrowShiftAmt)).getReg(0);
19245ffd83dbSDimitry Andric     }
19255ffd83dbSDimitry Andric 
19265ffd83dbSDimitry Andric     auto Zero = Builder.buildConstant(HalfTy, 0);
19275ffd83dbSDimitry Andric     Builder.buildMerge(DstReg, { Narrowed, Zero });
19285ffd83dbSDimitry Andric   } else if (MI.getOpcode() == TargetOpcode::G_SHL) {
19295ffd83dbSDimitry Andric     Register Narrowed = Unmerge.getReg(0);
19305ffd83dbSDimitry Andric     //  dst = G_SHL s64:x, C for C >= 32
19315ffd83dbSDimitry Andric     // =>
19325ffd83dbSDimitry Andric     //   lo, hi = G_UNMERGE_VALUES x
19335ffd83dbSDimitry Andric     //   dst = G_MERGE_VALUES 0, (G_SHL hi, C - 32)
19345ffd83dbSDimitry Andric     if (NarrowShiftAmt != 0) {
19355ffd83dbSDimitry Andric       Narrowed = Builder.buildShl(HalfTy, Narrowed,
19365ffd83dbSDimitry Andric         Builder.buildConstant(HalfTy, NarrowShiftAmt)).getReg(0);
19375ffd83dbSDimitry Andric     }
19385ffd83dbSDimitry Andric 
19395ffd83dbSDimitry Andric     auto Zero = Builder.buildConstant(HalfTy, 0);
19405ffd83dbSDimitry Andric     Builder.buildMerge(DstReg, { Zero, Narrowed });
19415ffd83dbSDimitry Andric   } else {
19425ffd83dbSDimitry Andric     assert(MI.getOpcode() == TargetOpcode::G_ASHR);
19435ffd83dbSDimitry Andric     auto Hi = Builder.buildAShr(
19445ffd83dbSDimitry Andric       HalfTy, Unmerge.getReg(1),
19455ffd83dbSDimitry Andric       Builder.buildConstant(HalfTy, HalfSize - 1));
19465ffd83dbSDimitry Andric 
19475ffd83dbSDimitry Andric     if (ShiftVal == HalfSize) {
19485ffd83dbSDimitry Andric       // (G_ASHR i64:x, 32) ->
19495ffd83dbSDimitry Andric       //   G_MERGE_VALUES hi_32(x), (G_ASHR hi_32(x), 31)
19505ffd83dbSDimitry Andric       Builder.buildMerge(DstReg, { Unmerge.getReg(1), Hi });
19515ffd83dbSDimitry Andric     } else if (ShiftVal == Size - 1) {
19525ffd83dbSDimitry Andric       // Don't need a second shift.
19535ffd83dbSDimitry Andric       // (G_ASHR i64:x, 63) ->
19545ffd83dbSDimitry Andric       //   %narrowed = (G_ASHR hi_32(x), 31)
19555ffd83dbSDimitry Andric       //   G_MERGE_VALUES %narrowed, %narrowed
19565ffd83dbSDimitry Andric       Builder.buildMerge(DstReg, { Hi, Hi });
19575ffd83dbSDimitry Andric     } else {
19585ffd83dbSDimitry Andric       auto Lo = Builder.buildAShr(
19595ffd83dbSDimitry Andric         HalfTy, Unmerge.getReg(1),
19605ffd83dbSDimitry Andric         Builder.buildConstant(HalfTy, ShiftVal - HalfSize));
19615ffd83dbSDimitry Andric 
19625ffd83dbSDimitry Andric       // (G_ASHR i64:x, C) ->, for C >= 32
19635ffd83dbSDimitry Andric       //   G_MERGE_VALUES (G_ASHR hi_32(x), C - 32), (G_ASHR hi_32(x), 31)
19645ffd83dbSDimitry Andric       Builder.buildMerge(DstReg, { Lo, Hi });
19655ffd83dbSDimitry Andric     }
19665ffd83dbSDimitry Andric   }
19675ffd83dbSDimitry Andric 
19685ffd83dbSDimitry Andric   MI.eraseFromParent();
19695ffd83dbSDimitry Andric }
19705ffd83dbSDimitry Andric 
19715ffd83dbSDimitry Andric bool CombinerHelper::tryCombineShiftToUnmerge(MachineInstr &MI,
19725ffd83dbSDimitry Andric                                               unsigned TargetShiftAmount) {
19735ffd83dbSDimitry Andric   unsigned ShiftAmt;
19745ffd83dbSDimitry Andric   if (matchCombineShiftToUnmerge(MI, TargetShiftAmount, ShiftAmt)) {
19755ffd83dbSDimitry Andric     applyCombineShiftToUnmerge(MI, ShiftAmt);
19765ffd83dbSDimitry Andric     return true;
19775ffd83dbSDimitry Andric   }
19785ffd83dbSDimitry Andric 
19795ffd83dbSDimitry Andric   return false;
19805ffd83dbSDimitry Andric }
19815ffd83dbSDimitry Andric 
1982e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineI2PToP2I(MachineInstr &MI, Register &Reg) {
1983e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_INTTOPTR && "Expected a G_INTTOPTR");
1984e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
1985e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
1986e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
1987e8d8bef9SDimitry Andric   return mi_match(SrcReg, MRI,
1988e8d8bef9SDimitry Andric                   m_GPtrToInt(m_all_of(m_SpecificType(DstTy), m_Reg(Reg))));
1989e8d8bef9SDimitry Andric }
1990e8d8bef9SDimitry Andric 
1991fe6060f1SDimitry Andric void CombinerHelper::applyCombineI2PToP2I(MachineInstr &MI, Register &Reg) {
1992e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_INTTOPTR && "Expected a G_INTTOPTR");
1993e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
1994e8d8bef9SDimitry Andric   Builder.setInstr(MI);
1995e8d8bef9SDimitry Andric   Builder.buildCopy(DstReg, Reg);
1996e8d8bef9SDimitry Andric   MI.eraseFromParent();
1997e8d8bef9SDimitry Andric }
1998e8d8bef9SDimitry Andric 
1999e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineP2IToI2P(MachineInstr &MI, Register &Reg) {
2000e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_PTRTOINT && "Expected a G_PTRTOINT");
2001e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2002e8d8bef9SDimitry Andric   return mi_match(SrcReg, MRI, m_GIntToPtr(m_Reg(Reg)));
2003e8d8bef9SDimitry Andric }
2004e8d8bef9SDimitry Andric 
2005fe6060f1SDimitry Andric void CombinerHelper::applyCombineP2IToI2P(MachineInstr &MI, Register &Reg) {
2006e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_PTRTOINT && "Expected a G_PTRTOINT");
2007e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2008e8d8bef9SDimitry Andric   Builder.setInstr(MI);
2009e8d8bef9SDimitry Andric   Builder.buildZExtOrTrunc(DstReg, Reg);
2010e8d8bef9SDimitry Andric   MI.eraseFromParent();
2011e8d8bef9SDimitry Andric }
2012e8d8bef9SDimitry Andric 
2013e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineAddP2IToPtrAdd(
2014e8d8bef9SDimitry Andric     MachineInstr &MI, std::pair<Register, bool> &PtrReg) {
2015e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ADD);
2016e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
2017e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
2018e8d8bef9SDimitry Andric   LLT IntTy = MRI.getType(LHS);
2019e8d8bef9SDimitry Andric 
2020e8d8bef9SDimitry Andric   // G_PTR_ADD always has the pointer in the LHS, so we may need to commute the
2021e8d8bef9SDimitry Andric   // instruction.
2022e8d8bef9SDimitry Andric   PtrReg.second = false;
2023e8d8bef9SDimitry Andric   for (Register SrcReg : {LHS, RHS}) {
2024e8d8bef9SDimitry Andric     if (mi_match(SrcReg, MRI, m_GPtrToInt(m_Reg(PtrReg.first)))) {
2025e8d8bef9SDimitry Andric       // Don't handle cases where the integer is implicitly converted to the
2026e8d8bef9SDimitry Andric       // pointer width.
2027e8d8bef9SDimitry Andric       LLT PtrTy = MRI.getType(PtrReg.first);
2028e8d8bef9SDimitry Andric       if (PtrTy.getScalarSizeInBits() == IntTy.getScalarSizeInBits())
2029e8d8bef9SDimitry Andric         return true;
2030e8d8bef9SDimitry Andric     }
2031e8d8bef9SDimitry Andric 
2032e8d8bef9SDimitry Andric     PtrReg.second = true;
2033e8d8bef9SDimitry Andric   }
2034e8d8bef9SDimitry Andric 
2035e8d8bef9SDimitry Andric   return false;
2036e8d8bef9SDimitry Andric }
2037e8d8bef9SDimitry Andric 
2038fe6060f1SDimitry Andric void CombinerHelper::applyCombineAddP2IToPtrAdd(
2039e8d8bef9SDimitry Andric     MachineInstr &MI, std::pair<Register, bool> &PtrReg) {
2040e8d8bef9SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
2041e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
2042e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
2043e8d8bef9SDimitry Andric 
2044e8d8bef9SDimitry Andric   const bool DoCommute = PtrReg.second;
2045e8d8bef9SDimitry Andric   if (DoCommute)
2046e8d8bef9SDimitry Andric     std::swap(LHS, RHS);
2047e8d8bef9SDimitry Andric   LHS = PtrReg.first;
2048e8d8bef9SDimitry Andric 
2049e8d8bef9SDimitry Andric   LLT PtrTy = MRI.getType(LHS);
2050e8d8bef9SDimitry Andric 
2051e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
2052e8d8bef9SDimitry Andric   auto PtrAdd = Builder.buildPtrAdd(PtrTy, LHS, RHS);
2053e8d8bef9SDimitry Andric   Builder.buildPtrToInt(Dst, PtrAdd);
2054e8d8bef9SDimitry Andric   MI.eraseFromParent();
2055e8d8bef9SDimitry Andric }
2056e8d8bef9SDimitry Andric 
2057e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineConstPtrAddToI2P(MachineInstr &MI,
205804eeddc0SDimitry Andric                                                   APInt &NewCst) {
2059349cc55cSDimitry Andric   auto &PtrAdd = cast<GPtrAdd>(MI);
2060349cc55cSDimitry Andric   Register LHS = PtrAdd.getBaseReg();
2061349cc55cSDimitry Andric   Register RHS = PtrAdd.getOffsetReg();
2062e8d8bef9SDimitry Andric   MachineRegisterInfo &MRI = Builder.getMF().getRegInfo();
2063e8d8bef9SDimitry Andric 
206404eeddc0SDimitry Andric   if (auto RHSCst = getIConstantVRegVal(RHS, MRI)) {
206504eeddc0SDimitry Andric     APInt Cst;
2066e8d8bef9SDimitry Andric     if (mi_match(LHS, MRI, m_GIntToPtr(m_ICst(Cst)))) {
206704eeddc0SDimitry Andric       auto DstTy = MRI.getType(PtrAdd.getReg(0));
206804eeddc0SDimitry Andric       // G_INTTOPTR uses zero-extension
206904eeddc0SDimitry Andric       NewCst = Cst.zextOrTrunc(DstTy.getSizeInBits());
207004eeddc0SDimitry Andric       NewCst += RHSCst->sextOrTrunc(DstTy.getSizeInBits());
2071e8d8bef9SDimitry Andric       return true;
2072e8d8bef9SDimitry Andric     }
2073e8d8bef9SDimitry Andric   }
2074e8d8bef9SDimitry Andric 
2075e8d8bef9SDimitry Andric   return false;
2076e8d8bef9SDimitry Andric }
2077e8d8bef9SDimitry Andric 
2078fe6060f1SDimitry Andric void CombinerHelper::applyCombineConstPtrAddToI2P(MachineInstr &MI,
207904eeddc0SDimitry Andric                                                   APInt &NewCst) {
2080349cc55cSDimitry Andric   auto &PtrAdd = cast<GPtrAdd>(MI);
2081349cc55cSDimitry Andric   Register Dst = PtrAdd.getReg(0);
2082e8d8bef9SDimitry Andric 
2083e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
2084e8d8bef9SDimitry Andric   Builder.buildConstant(Dst, NewCst);
2085349cc55cSDimitry Andric   PtrAdd.eraseFromParent();
2086e8d8bef9SDimitry Andric }
2087e8d8bef9SDimitry Andric 
2088e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineAnyExtTrunc(MachineInstr &MI, Register &Reg) {
2089e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ANYEXT && "Expected a G_ANYEXT");
2090e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2091e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2092e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
2093e8d8bef9SDimitry Andric   return mi_match(SrcReg, MRI,
2094e8d8bef9SDimitry Andric                   m_GTrunc(m_all_of(m_Reg(Reg), m_SpecificType(DstTy))));
2095e8d8bef9SDimitry Andric }
2096e8d8bef9SDimitry Andric 
2097fe6060f1SDimitry Andric bool CombinerHelper::matchCombineZextTrunc(MachineInstr &MI, Register &Reg) {
2098fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ZEXT && "Expected a G_ZEXT");
2099e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2100fe6060f1SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2101fe6060f1SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
2102fe6060f1SDimitry Andric   if (mi_match(SrcReg, MRI,
2103fe6060f1SDimitry Andric                m_GTrunc(m_all_of(m_Reg(Reg), m_SpecificType(DstTy))))) {
2104fe6060f1SDimitry Andric     unsigned DstSize = DstTy.getScalarSizeInBits();
2105fe6060f1SDimitry Andric     unsigned SrcSize = MRI.getType(SrcReg).getScalarSizeInBits();
2106fe6060f1SDimitry Andric     return KB->getKnownBits(Reg).countMinLeadingZeros() >= DstSize - SrcSize;
2107fe6060f1SDimitry Andric   }
2108fe6060f1SDimitry Andric   return false;
2109e8d8bef9SDimitry Andric }
2110e8d8bef9SDimitry Andric 
2111e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineExtOfExt(
2112e8d8bef9SDimitry Andric     MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
2113e8d8bef9SDimitry Andric   assert((MI.getOpcode() == TargetOpcode::G_ANYEXT ||
2114e8d8bef9SDimitry Andric           MI.getOpcode() == TargetOpcode::G_SEXT ||
2115e8d8bef9SDimitry Andric           MI.getOpcode() == TargetOpcode::G_ZEXT) &&
2116e8d8bef9SDimitry Andric          "Expected a G_[ASZ]EXT");
2117e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2118e8d8bef9SDimitry Andric   MachineInstr *SrcMI = MRI.getVRegDef(SrcReg);
2119e8d8bef9SDimitry Andric   // Match exts with the same opcode, anyext([sz]ext) and sext(zext).
2120e8d8bef9SDimitry Andric   unsigned Opc = MI.getOpcode();
2121e8d8bef9SDimitry Andric   unsigned SrcOpc = SrcMI->getOpcode();
2122e8d8bef9SDimitry Andric   if (Opc == SrcOpc ||
2123e8d8bef9SDimitry Andric       (Opc == TargetOpcode::G_ANYEXT &&
2124e8d8bef9SDimitry Andric        (SrcOpc == TargetOpcode::G_SEXT || SrcOpc == TargetOpcode::G_ZEXT)) ||
2125e8d8bef9SDimitry Andric       (Opc == TargetOpcode::G_SEXT && SrcOpc == TargetOpcode::G_ZEXT)) {
2126e8d8bef9SDimitry Andric     MatchInfo = std::make_tuple(SrcMI->getOperand(1).getReg(), SrcOpc);
2127e8d8bef9SDimitry Andric     return true;
2128e8d8bef9SDimitry Andric   }
2129e8d8bef9SDimitry Andric   return false;
2130e8d8bef9SDimitry Andric }
2131e8d8bef9SDimitry Andric 
2132fe6060f1SDimitry Andric void CombinerHelper::applyCombineExtOfExt(
2133e8d8bef9SDimitry Andric     MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
2134e8d8bef9SDimitry Andric   assert((MI.getOpcode() == TargetOpcode::G_ANYEXT ||
2135e8d8bef9SDimitry Andric           MI.getOpcode() == TargetOpcode::G_SEXT ||
2136e8d8bef9SDimitry Andric           MI.getOpcode() == TargetOpcode::G_ZEXT) &&
2137e8d8bef9SDimitry Andric          "Expected a G_[ASZ]EXT");
2138e8d8bef9SDimitry Andric 
2139e8d8bef9SDimitry Andric   Register Reg = std::get<0>(MatchInfo);
2140e8d8bef9SDimitry Andric   unsigned SrcExtOp = std::get<1>(MatchInfo);
2141e8d8bef9SDimitry Andric 
2142e8d8bef9SDimitry Andric   // Combine exts with the same opcode.
2143e8d8bef9SDimitry Andric   if (MI.getOpcode() == SrcExtOp) {
2144e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
2145e8d8bef9SDimitry Andric     MI.getOperand(1).setReg(Reg);
2146e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
2147fe6060f1SDimitry Andric     return;
2148e8d8bef9SDimitry Andric   }
2149e8d8bef9SDimitry Andric 
2150e8d8bef9SDimitry Andric   // Combine:
2151e8d8bef9SDimitry Andric   // - anyext([sz]ext x) to [sz]ext x
2152e8d8bef9SDimitry Andric   // - sext(zext x) to zext x
2153e8d8bef9SDimitry Andric   if (MI.getOpcode() == TargetOpcode::G_ANYEXT ||
2154e8d8bef9SDimitry Andric       (MI.getOpcode() == TargetOpcode::G_SEXT &&
2155e8d8bef9SDimitry Andric        SrcExtOp == TargetOpcode::G_ZEXT)) {
2156e8d8bef9SDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
2157e8d8bef9SDimitry Andric     Builder.setInstrAndDebugLoc(MI);
2158e8d8bef9SDimitry Andric     Builder.buildInstr(SrcExtOp, {DstReg}, {Reg});
2159e8d8bef9SDimitry Andric     MI.eraseFromParent();
2160fe6060f1SDimitry Andric   }
2161e8d8bef9SDimitry Andric }
2162e8d8bef9SDimitry Andric 
2163fe6060f1SDimitry Andric void CombinerHelper::applyCombineMulByNegativeOne(MachineInstr &MI) {
2164e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL");
2165e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2166e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2167e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
2168e8d8bef9SDimitry Andric 
2169e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
2170e8d8bef9SDimitry Andric   Builder.buildSub(DstReg, Builder.buildConstant(DstTy, 0), SrcReg,
2171e8d8bef9SDimitry Andric                    MI.getFlags());
2172e8d8bef9SDimitry Andric   MI.eraseFromParent();
2173e8d8bef9SDimitry Andric }
2174e8d8bef9SDimitry Andric 
2175e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineFNegOfFNeg(MachineInstr &MI, Register &Reg) {
2176e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FNEG && "Expected a G_FNEG");
2177e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2178e8d8bef9SDimitry Andric   return mi_match(SrcReg, MRI, m_GFNeg(m_Reg(Reg)));
2179e8d8bef9SDimitry Andric }
2180e8d8bef9SDimitry Andric 
2181e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineFAbsOfFAbs(MachineInstr &MI, Register &Src) {
2182e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FABS && "Expected a G_FABS");
2183e8d8bef9SDimitry Andric   Src = MI.getOperand(1).getReg();
2184e8d8bef9SDimitry Andric   Register AbsSrc;
2185e8d8bef9SDimitry Andric   return mi_match(Src, MRI, m_GFabs(m_Reg(AbsSrc)));
2186e8d8bef9SDimitry Andric }
2187e8d8bef9SDimitry Andric 
2188349cc55cSDimitry Andric bool CombinerHelper::matchCombineFAbsOfFNeg(MachineInstr &MI,
2189349cc55cSDimitry Andric                                             BuildFnTy &MatchInfo) {
2190349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FABS && "Expected a G_FABS");
2191349cc55cSDimitry Andric   Register Src = MI.getOperand(1).getReg();
2192349cc55cSDimitry Andric   Register NegSrc;
2193349cc55cSDimitry Andric 
2194349cc55cSDimitry Andric   if (!mi_match(Src, MRI, m_GFNeg(m_Reg(NegSrc))))
2195349cc55cSDimitry Andric     return false;
2196349cc55cSDimitry Andric 
2197349cc55cSDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
2198349cc55cSDimitry Andric     Observer.changingInstr(MI);
2199349cc55cSDimitry Andric     MI.getOperand(1).setReg(NegSrc);
2200349cc55cSDimitry Andric     Observer.changedInstr(MI);
2201349cc55cSDimitry Andric   };
2202349cc55cSDimitry Andric   return true;
2203349cc55cSDimitry Andric }
2204349cc55cSDimitry Andric 
2205e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineTruncOfExt(
2206e8d8bef9SDimitry Andric     MachineInstr &MI, std::pair<Register, unsigned> &MatchInfo) {
2207e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2208e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2209e8d8bef9SDimitry Andric   MachineInstr *SrcMI = MRI.getVRegDef(SrcReg);
2210e8d8bef9SDimitry Andric   unsigned SrcOpc = SrcMI->getOpcode();
2211e8d8bef9SDimitry Andric   if (SrcOpc == TargetOpcode::G_ANYEXT || SrcOpc == TargetOpcode::G_SEXT ||
2212e8d8bef9SDimitry Andric       SrcOpc == TargetOpcode::G_ZEXT) {
2213e8d8bef9SDimitry Andric     MatchInfo = std::make_pair(SrcMI->getOperand(1).getReg(), SrcOpc);
2214e8d8bef9SDimitry Andric     return true;
2215e8d8bef9SDimitry Andric   }
2216e8d8bef9SDimitry Andric   return false;
2217e8d8bef9SDimitry Andric }
2218e8d8bef9SDimitry Andric 
2219fe6060f1SDimitry Andric void CombinerHelper::applyCombineTruncOfExt(
2220e8d8bef9SDimitry Andric     MachineInstr &MI, std::pair<Register, unsigned> &MatchInfo) {
2221e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2222e8d8bef9SDimitry Andric   Register SrcReg = MatchInfo.first;
2223e8d8bef9SDimitry Andric   unsigned SrcExtOp = MatchInfo.second;
2224e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2225e8d8bef9SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
2226e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
2227e8d8bef9SDimitry Andric   if (SrcTy == DstTy) {
2228e8d8bef9SDimitry Andric     MI.eraseFromParent();
2229e8d8bef9SDimitry Andric     replaceRegWith(MRI, DstReg, SrcReg);
2230fe6060f1SDimitry Andric     return;
2231e8d8bef9SDimitry Andric   }
2232e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
2233e8d8bef9SDimitry Andric   if (SrcTy.getSizeInBits() < DstTy.getSizeInBits())
2234e8d8bef9SDimitry Andric     Builder.buildInstr(SrcExtOp, {DstReg}, {SrcReg});
2235e8d8bef9SDimitry Andric   else
2236e8d8bef9SDimitry Andric     Builder.buildTrunc(DstReg, SrcReg);
2237e8d8bef9SDimitry Andric   MI.eraseFromParent();
2238e8d8bef9SDimitry Andric }
2239e8d8bef9SDimitry Andric 
2240e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineTruncOfShl(
2241e8d8bef9SDimitry Andric     MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
2242e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2243e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2244e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2245e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
2246e8d8bef9SDimitry Andric   Register ShiftSrc;
2247e8d8bef9SDimitry Andric   Register ShiftAmt;
2248e8d8bef9SDimitry Andric 
2249e8d8bef9SDimitry Andric   if (MRI.hasOneNonDBGUse(SrcReg) &&
2250e8d8bef9SDimitry Andric       mi_match(SrcReg, MRI, m_GShl(m_Reg(ShiftSrc), m_Reg(ShiftAmt))) &&
2251e8d8bef9SDimitry Andric       isLegalOrBeforeLegalizer(
2252e8d8bef9SDimitry Andric           {TargetOpcode::G_SHL,
2253e8d8bef9SDimitry Andric            {DstTy, getTargetLowering().getPreferredShiftAmountTy(DstTy)}})) {
2254e8d8bef9SDimitry Andric     KnownBits Known = KB->getKnownBits(ShiftAmt);
2255e8d8bef9SDimitry Andric     unsigned Size = DstTy.getSizeInBits();
2256349cc55cSDimitry Andric     if (Known.countMaxActiveBits() <= Log2_32(Size)) {
2257e8d8bef9SDimitry Andric       MatchInfo = std::make_pair(ShiftSrc, ShiftAmt);
2258e8d8bef9SDimitry Andric       return true;
2259e8d8bef9SDimitry Andric     }
2260e8d8bef9SDimitry Andric   }
2261e8d8bef9SDimitry Andric   return false;
2262e8d8bef9SDimitry Andric }
2263e8d8bef9SDimitry Andric 
2264fe6060f1SDimitry Andric void CombinerHelper::applyCombineTruncOfShl(
2265e8d8bef9SDimitry Andric     MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
2266e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2267e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2268e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2269e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
2270e8d8bef9SDimitry Andric   MachineInstr *SrcMI = MRI.getVRegDef(SrcReg);
2271e8d8bef9SDimitry Andric 
2272e8d8bef9SDimitry Andric   Register ShiftSrc = MatchInfo.first;
2273e8d8bef9SDimitry Andric   Register ShiftAmt = MatchInfo.second;
2274e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
2275e8d8bef9SDimitry Andric   auto TruncShiftSrc = Builder.buildTrunc(DstTy, ShiftSrc);
2276e8d8bef9SDimitry Andric   Builder.buildShl(DstReg, TruncShiftSrc, ShiftAmt, SrcMI->getFlags());
2277e8d8bef9SDimitry Andric   MI.eraseFromParent();
2278e8d8bef9SDimitry Andric }
2279e8d8bef9SDimitry Andric 
22805ffd83dbSDimitry Andric bool CombinerHelper::matchAnyExplicitUseIsUndef(MachineInstr &MI) {
22815ffd83dbSDimitry Andric   return any_of(MI.explicit_uses(), [this](const MachineOperand &MO) {
22825ffd83dbSDimitry Andric     return MO.isReg() &&
22835ffd83dbSDimitry Andric            getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
22845ffd83dbSDimitry Andric   });
22855ffd83dbSDimitry Andric }
22865ffd83dbSDimitry Andric 
22875ffd83dbSDimitry Andric bool CombinerHelper::matchAllExplicitUsesAreUndef(MachineInstr &MI) {
22885ffd83dbSDimitry Andric   return all_of(MI.explicit_uses(), [this](const MachineOperand &MO) {
22895ffd83dbSDimitry Andric     return !MO.isReg() ||
22905ffd83dbSDimitry Andric            getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
22915ffd83dbSDimitry Andric   });
22925ffd83dbSDimitry Andric }
22935ffd83dbSDimitry Andric 
22945ffd83dbSDimitry Andric bool CombinerHelper::matchUndefShuffleVectorMask(MachineInstr &MI) {
22955ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR);
22965ffd83dbSDimitry Andric   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
22975ffd83dbSDimitry Andric   return all_of(Mask, [](int Elt) { return Elt < 0; });
22985ffd83dbSDimitry Andric }
22995ffd83dbSDimitry Andric 
23005ffd83dbSDimitry Andric bool CombinerHelper::matchUndefStore(MachineInstr &MI) {
23015ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_STORE);
23025ffd83dbSDimitry Andric   return getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MI.getOperand(0).getReg(),
23035ffd83dbSDimitry Andric                       MRI);
23045ffd83dbSDimitry Andric }
23055ffd83dbSDimitry Andric 
2306e8d8bef9SDimitry Andric bool CombinerHelper::matchUndefSelectCmp(MachineInstr &MI) {
2307e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SELECT);
2308e8d8bef9SDimitry Andric   return getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MI.getOperand(1).getReg(),
2309e8d8bef9SDimitry Andric                       MRI);
2310e8d8bef9SDimitry Andric }
2311e8d8bef9SDimitry Andric 
2312e8d8bef9SDimitry Andric bool CombinerHelper::matchConstantSelectCmp(MachineInstr &MI, unsigned &OpIdx) {
2313349cc55cSDimitry Andric   GSelect &SelMI = cast<GSelect>(MI);
2314349cc55cSDimitry Andric   auto Cst =
2315349cc55cSDimitry Andric       isConstantOrConstantSplatVector(*MRI.getVRegDef(SelMI.getCondReg()), MRI);
2316349cc55cSDimitry Andric   if (!Cst)
2317e8d8bef9SDimitry Andric     return false;
2318349cc55cSDimitry Andric   OpIdx = Cst->isZero() ? 3 : 2;
2319349cc55cSDimitry Andric   return true;
2320e8d8bef9SDimitry Andric }
2321e8d8bef9SDimitry Andric 
23225ffd83dbSDimitry Andric bool CombinerHelper::eraseInst(MachineInstr &MI) {
23235ffd83dbSDimitry Andric   MI.eraseFromParent();
23245ffd83dbSDimitry Andric   return true;
23255ffd83dbSDimitry Andric }
23265ffd83dbSDimitry Andric 
23275ffd83dbSDimitry Andric bool CombinerHelper::matchEqualDefs(const MachineOperand &MOP1,
23285ffd83dbSDimitry Andric                                     const MachineOperand &MOP2) {
23295ffd83dbSDimitry Andric   if (!MOP1.isReg() || !MOP2.isReg())
23305ffd83dbSDimitry Andric     return false;
2331349cc55cSDimitry Andric   auto InstAndDef1 = getDefSrcRegIgnoringCopies(MOP1.getReg(), MRI);
2332349cc55cSDimitry Andric   if (!InstAndDef1)
23335ffd83dbSDimitry Andric     return false;
2334349cc55cSDimitry Andric   auto InstAndDef2 = getDefSrcRegIgnoringCopies(MOP2.getReg(), MRI);
2335349cc55cSDimitry Andric   if (!InstAndDef2)
23365ffd83dbSDimitry Andric     return false;
2337349cc55cSDimitry Andric   MachineInstr *I1 = InstAndDef1->MI;
2338349cc55cSDimitry Andric   MachineInstr *I2 = InstAndDef2->MI;
23395ffd83dbSDimitry Andric 
23405ffd83dbSDimitry Andric   // Handle a case like this:
23415ffd83dbSDimitry Andric   //
23425ffd83dbSDimitry Andric   // %0:_(s64), %1:_(s64) = G_UNMERGE_VALUES %2:_(<2 x s64>)
23435ffd83dbSDimitry Andric   //
23445ffd83dbSDimitry Andric   // Even though %0 and %1 are produced by the same instruction they are not
23455ffd83dbSDimitry Andric   // the same values.
23465ffd83dbSDimitry Andric   if (I1 == I2)
23475ffd83dbSDimitry Andric     return MOP1.getReg() == MOP2.getReg();
23485ffd83dbSDimitry Andric 
23495ffd83dbSDimitry Andric   // If we have an instruction which loads or stores, we can't guarantee that
23505ffd83dbSDimitry Andric   // it is identical.
23515ffd83dbSDimitry Andric   //
23525ffd83dbSDimitry Andric   // For example, we may have
23535ffd83dbSDimitry Andric   //
23545ffd83dbSDimitry Andric   // %x1 = G_LOAD %addr (load N from @somewhere)
23555ffd83dbSDimitry Andric   // ...
23565ffd83dbSDimitry Andric   // call @foo
23575ffd83dbSDimitry Andric   // ...
23585ffd83dbSDimitry Andric   // %x2 = G_LOAD %addr (load N from @somewhere)
23595ffd83dbSDimitry Andric   // ...
23605ffd83dbSDimitry Andric   // %or = G_OR %x1, %x2
23615ffd83dbSDimitry Andric   //
23625ffd83dbSDimitry Andric   // It's possible that @foo will modify whatever lives at the address we're
23635ffd83dbSDimitry Andric   // loading from. To be safe, let's just assume that all loads and stores
23645ffd83dbSDimitry Andric   // are different (unless we have something which is guaranteed to not
23655ffd83dbSDimitry Andric   // change.)
23665ffd83dbSDimitry Andric   if (I1->mayLoadOrStore() && !I1->isDereferenceableInvariantLoad(nullptr))
23675ffd83dbSDimitry Andric     return false;
23685ffd83dbSDimitry Andric 
2369*81ad6265SDimitry Andric   // If both instructions are loads or stores, they are equal only if both
2370*81ad6265SDimitry Andric   // are dereferenceable invariant loads with the same number of bits.
2371*81ad6265SDimitry Andric   if (I1->mayLoadOrStore() && I2->mayLoadOrStore()) {
2372*81ad6265SDimitry Andric     GLoadStore *LS1 = dyn_cast<GLoadStore>(I1);
2373*81ad6265SDimitry Andric     GLoadStore *LS2 = dyn_cast<GLoadStore>(I2);
2374*81ad6265SDimitry Andric     if (!LS1 || !LS2)
2375*81ad6265SDimitry Andric       return false;
2376*81ad6265SDimitry Andric 
2377*81ad6265SDimitry Andric     if (!I2->isDereferenceableInvariantLoad(nullptr) ||
2378*81ad6265SDimitry Andric         (LS1->getMemSizeInBits() != LS2->getMemSizeInBits()))
2379*81ad6265SDimitry Andric       return false;
2380*81ad6265SDimitry Andric   }
2381*81ad6265SDimitry Andric 
23825ffd83dbSDimitry Andric   // Check for physical registers on the instructions first to avoid cases
23835ffd83dbSDimitry Andric   // like this:
23845ffd83dbSDimitry Andric   //
23855ffd83dbSDimitry Andric   // %a = COPY $physreg
23865ffd83dbSDimitry Andric   // ...
23875ffd83dbSDimitry Andric   // SOMETHING implicit-def $physreg
23885ffd83dbSDimitry Andric   // ...
23895ffd83dbSDimitry Andric   // %b = COPY $physreg
23905ffd83dbSDimitry Andric   //
23915ffd83dbSDimitry Andric   // These copies are not equivalent.
23925ffd83dbSDimitry Andric   if (any_of(I1->uses(), [](const MachineOperand &MO) {
23935ffd83dbSDimitry Andric         return MO.isReg() && MO.getReg().isPhysical();
23945ffd83dbSDimitry Andric       })) {
23955ffd83dbSDimitry Andric     // Check if we have a case like this:
23965ffd83dbSDimitry Andric     //
23975ffd83dbSDimitry Andric     // %a = COPY $physreg
23985ffd83dbSDimitry Andric     // %b = COPY %a
23995ffd83dbSDimitry Andric     //
24005ffd83dbSDimitry Andric     // In this case, I1 and I2 will both be equal to %a = COPY $physreg.
24015ffd83dbSDimitry Andric     // From that, we know that they must have the same value, since they must
24025ffd83dbSDimitry Andric     // have come from the same COPY.
24035ffd83dbSDimitry Andric     return I1->isIdenticalTo(*I2);
24045ffd83dbSDimitry Andric   }
24055ffd83dbSDimitry Andric 
24065ffd83dbSDimitry Andric   // We don't have any physical registers, so we don't necessarily need the
24075ffd83dbSDimitry Andric   // same vreg defs.
24085ffd83dbSDimitry Andric   //
24095ffd83dbSDimitry Andric   // On the off-chance that there's some target instruction feeding into the
24105ffd83dbSDimitry Andric   // instruction, let's use produceSameValue instead of isIdenticalTo.
2411349cc55cSDimitry Andric   if (Builder.getTII().produceSameValue(*I1, *I2, &MRI)) {
2412349cc55cSDimitry Andric     // Handle instructions with multiple defs that produce same values. Values
2413349cc55cSDimitry Andric     // are same for operands with same index.
2414349cc55cSDimitry Andric     // %0:_(s8), %1:_(s8), %2:_(s8), %3:_(s8) = G_UNMERGE_VALUES %4:_(<4 x s8>)
2415349cc55cSDimitry Andric     // %5:_(s8), %6:_(s8), %7:_(s8), %8:_(s8) = G_UNMERGE_VALUES %4:_(<4 x s8>)
2416349cc55cSDimitry Andric     // I1 and I2 are different instructions but produce same values,
2417349cc55cSDimitry Andric     // %1 and %6 are same, %1 and %7 are not the same value.
2418349cc55cSDimitry Andric     return I1->findRegisterDefOperandIdx(InstAndDef1->Reg) ==
2419349cc55cSDimitry Andric            I2->findRegisterDefOperandIdx(InstAndDef2->Reg);
2420349cc55cSDimitry Andric   }
2421349cc55cSDimitry Andric   return false;
24225ffd83dbSDimitry Andric }
24235ffd83dbSDimitry Andric 
24245ffd83dbSDimitry Andric bool CombinerHelper::matchConstantOp(const MachineOperand &MOP, int64_t C) {
24255ffd83dbSDimitry Andric   if (!MOP.isReg())
24265ffd83dbSDimitry Andric     return false;
2427349cc55cSDimitry Andric   auto *MI = MRI.getVRegDef(MOP.getReg());
2428349cc55cSDimitry Andric   auto MaybeCst = isConstantOrConstantSplatVector(*MI, MRI);
2429*81ad6265SDimitry Andric   return MaybeCst && MaybeCst->getBitWidth() <= 64 &&
2430349cc55cSDimitry Andric          MaybeCst->getSExtValue() == C;
24315ffd83dbSDimitry Andric }
24325ffd83dbSDimitry Andric 
24335ffd83dbSDimitry Andric bool CombinerHelper::replaceSingleDefInstWithOperand(MachineInstr &MI,
24345ffd83dbSDimitry Andric                                                      unsigned OpIdx) {
24355ffd83dbSDimitry Andric   assert(MI.getNumExplicitDefs() == 1 && "Expected one explicit def?");
24365ffd83dbSDimitry Andric   Register OldReg = MI.getOperand(0).getReg();
24375ffd83dbSDimitry Andric   Register Replacement = MI.getOperand(OpIdx).getReg();
24385ffd83dbSDimitry Andric   assert(canReplaceReg(OldReg, Replacement, MRI) && "Cannot replace register?");
24395ffd83dbSDimitry Andric   MI.eraseFromParent();
24405ffd83dbSDimitry Andric   replaceRegWith(MRI, OldReg, Replacement);
24415ffd83dbSDimitry Andric   return true;
24425ffd83dbSDimitry Andric }
24435ffd83dbSDimitry Andric 
2444e8d8bef9SDimitry Andric bool CombinerHelper::replaceSingleDefInstWithReg(MachineInstr &MI,
2445e8d8bef9SDimitry Andric                                                  Register Replacement) {
2446e8d8bef9SDimitry Andric   assert(MI.getNumExplicitDefs() == 1 && "Expected one explicit def?");
2447e8d8bef9SDimitry Andric   Register OldReg = MI.getOperand(0).getReg();
2448e8d8bef9SDimitry Andric   assert(canReplaceReg(OldReg, Replacement, MRI) && "Cannot replace register?");
2449e8d8bef9SDimitry Andric   MI.eraseFromParent();
2450e8d8bef9SDimitry Andric   replaceRegWith(MRI, OldReg, Replacement);
2451e8d8bef9SDimitry Andric   return true;
2452e8d8bef9SDimitry Andric }
2453e8d8bef9SDimitry Andric 
24545ffd83dbSDimitry Andric bool CombinerHelper::matchSelectSameVal(MachineInstr &MI) {
24555ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SELECT);
24565ffd83dbSDimitry Andric   // Match (cond ? x : x)
24575ffd83dbSDimitry Andric   return matchEqualDefs(MI.getOperand(2), MI.getOperand(3)) &&
24585ffd83dbSDimitry Andric          canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(2).getReg(),
24595ffd83dbSDimitry Andric                        MRI);
24605ffd83dbSDimitry Andric }
24615ffd83dbSDimitry Andric 
24625ffd83dbSDimitry Andric bool CombinerHelper::matchBinOpSameVal(MachineInstr &MI) {
24635ffd83dbSDimitry Andric   return matchEqualDefs(MI.getOperand(1), MI.getOperand(2)) &&
24645ffd83dbSDimitry Andric          canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(1).getReg(),
24655ffd83dbSDimitry Andric                        MRI);
24665ffd83dbSDimitry Andric }
24675ffd83dbSDimitry Andric 
24685ffd83dbSDimitry Andric bool CombinerHelper::matchOperandIsZero(MachineInstr &MI, unsigned OpIdx) {
24695ffd83dbSDimitry Andric   return matchConstantOp(MI.getOperand(OpIdx), 0) &&
24705ffd83dbSDimitry Andric          canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(OpIdx).getReg(),
24715ffd83dbSDimitry Andric                        MRI);
24725ffd83dbSDimitry Andric }
24735ffd83dbSDimitry Andric 
2474e8d8bef9SDimitry Andric bool CombinerHelper::matchOperandIsUndef(MachineInstr &MI, unsigned OpIdx) {
2475e8d8bef9SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
2476e8d8bef9SDimitry Andric   return MO.isReg() &&
2477e8d8bef9SDimitry Andric          getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
2478e8d8bef9SDimitry Andric }
2479e8d8bef9SDimitry Andric 
2480e8d8bef9SDimitry Andric bool CombinerHelper::matchOperandIsKnownToBeAPowerOfTwo(MachineInstr &MI,
2481e8d8bef9SDimitry Andric                                                         unsigned OpIdx) {
2482e8d8bef9SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
2483e8d8bef9SDimitry Andric   return isKnownToBeAPowerOfTwo(MO.getReg(), MRI, KB);
2484e8d8bef9SDimitry Andric }
2485e8d8bef9SDimitry Andric 
24865ffd83dbSDimitry Andric bool CombinerHelper::replaceInstWithFConstant(MachineInstr &MI, double C) {
24875ffd83dbSDimitry Andric   assert(MI.getNumDefs() == 1 && "Expected only one def?");
24885ffd83dbSDimitry Andric   Builder.setInstr(MI);
24895ffd83dbSDimitry Andric   Builder.buildFConstant(MI.getOperand(0), C);
24905ffd83dbSDimitry Andric   MI.eraseFromParent();
24915ffd83dbSDimitry Andric   return true;
24925ffd83dbSDimitry Andric }
24935ffd83dbSDimitry Andric 
24945ffd83dbSDimitry Andric bool CombinerHelper::replaceInstWithConstant(MachineInstr &MI, int64_t C) {
24955ffd83dbSDimitry Andric   assert(MI.getNumDefs() == 1 && "Expected only one def?");
24965ffd83dbSDimitry Andric   Builder.setInstr(MI);
24975ffd83dbSDimitry Andric   Builder.buildConstant(MI.getOperand(0), C);
24985ffd83dbSDimitry Andric   MI.eraseFromParent();
24995ffd83dbSDimitry Andric   return true;
25005ffd83dbSDimitry Andric }
25015ffd83dbSDimitry Andric 
2502fe6060f1SDimitry Andric bool CombinerHelper::replaceInstWithConstant(MachineInstr &MI, APInt C) {
2503fe6060f1SDimitry Andric   assert(MI.getNumDefs() == 1 && "Expected only one def?");
2504fe6060f1SDimitry Andric   Builder.setInstr(MI);
2505fe6060f1SDimitry Andric   Builder.buildConstant(MI.getOperand(0), C);
2506fe6060f1SDimitry Andric   MI.eraseFromParent();
2507fe6060f1SDimitry Andric   return true;
2508fe6060f1SDimitry Andric }
2509fe6060f1SDimitry Andric 
25105ffd83dbSDimitry Andric bool CombinerHelper::replaceInstWithUndef(MachineInstr &MI) {
25115ffd83dbSDimitry Andric   assert(MI.getNumDefs() == 1 && "Expected only one def?");
25125ffd83dbSDimitry Andric   Builder.setInstr(MI);
25135ffd83dbSDimitry Andric   Builder.buildUndef(MI.getOperand(0));
25145ffd83dbSDimitry Andric   MI.eraseFromParent();
25155ffd83dbSDimitry Andric   return true;
25165ffd83dbSDimitry Andric }
25175ffd83dbSDimitry Andric 
25185ffd83dbSDimitry Andric bool CombinerHelper::matchSimplifyAddToSub(
25195ffd83dbSDimitry Andric     MachineInstr &MI, std::tuple<Register, Register> &MatchInfo) {
25205ffd83dbSDimitry Andric   Register LHS = MI.getOperand(1).getReg();
25215ffd83dbSDimitry Andric   Register RHS = MI.getOperand(2).getReg();
25225ffd83dbSDimitry Andric   Register &NewLHS = std::get<0>(MatchInfo);
25235ffd83dbSDimitry Andric   Register &NewRHS = std::get<1>(MatchInfo);
25245ffd83dbSDimitry Andric 
25255ffd83dbSDimitry Andric   // Helper lambda to check for opportunities for
25265ffd83dbSDimitry Andric   // ((0-A) + B) -> B - A
25275ffd83dbSDimitry Andric   // (A + (0-B)) -> A - B
25285ffd83dbSDimitry Andric   auto CheckFold = [&](Register &MaybeSub, Register &MaybeNewLHS) {
2529e8d8bef9SDimitry Andric     if (!mi_match(MaybeSub, MRI, m_Neg(m_Reg(NewRHS))))
25305ffd83dbSDimitry Andric       return false;
25315ffd83dbSDimitry Andric     NewLHS = MaybeNewLHS;
25325ffd83dbSDimitry Andric     return true;
25335ffd83dbSDimitry Andric   };
25345ffd83dbSDimitry Andric 
25355ffd83dbSDimitry Andric   return CheckFold(LHS, RHS) || CheckFold(RHS, LHS);
25365ffd83dbSDimitry Andric }
25375ffd83dbSDimitry Andric 
2538e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineInsertVecElts(
2539e8d8bef9SDimitry Andric     MachineInstr &MI, SmallVectorImpl<Register> &MatchInfo) {
2540e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT &&
2541e8d8bef9SDimitry Andric          "Invalid opcode");
2542e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2543e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
2544e8d8bef9SDimitry Andric   assert(DstTy.isVector() && "Invalid G_INSERT_VECTOR_ELT?");
2545e8d8bef9SDimitry Andric   unsigned NumElts = DstTy.getNumElements();
2546e8d8bef9SDimitry Andric   // If this MI is part of a sequence of insert_vec_elts, then
2547e8d8bef9SDimitry Andric   // don't do the combine in the middle of the sequence.
2548e8d8bef9SDimitry Andric   if (MRI.hasOneUse(DstReg) && MRI.use_instr_begin(DstReg)->getOpcode() ==
2549e8d8bef9SDimitry Andric                                    TargetOpcode::G_INSERT_VECTOR_ELT)
2550e8d8bef9SDimitry Andric     return false;
2551e8d8bef9SDimitry Andric   MachineInstr *CurrInst = &MI;
2552e8d8bef9SDimitry Andric   MachineInstr *TmpInst;
2553e8d8bef9SDimitry Andric   int64_t IntImm;
2554e8d8bef9SDimitry Andric   Register TmpReg;
2555e8d8bef9SDimitry Andric   MatchInfo.resize(NumElts);
2556e8d8bef9SDimitry Andric   while (mi_match(
2557e8d8bef9SDimitry Andric       CurrInst->getOperand(0).getReg(), MRI,
2558e8d8bef9SDimitry Andric       m_GInsertVecElt(m_MInstr(TmpInst), m_Reg(TmpReg), m_ICst(IntImm)))) {
2559e8d8bef9SDimitry Andric     if (IntImm >= NumElts)
2560e8d8bef9SDimitry Andric       return false;
2561e8d8bef9SDimitry Andric     if (!MatchInfo[IntImm])
2562e8d8bef9SDimitry Andric       MatchInfo[IntImm] = TmpReg;
2563e8d8bef9SDimitry Andric     CurrInst = TmpInst;
2564e8d8bef9SDimitry Andric   }
2565e8d8bef9SDimitry Andric   // Variable index.
2566e8d8bef9SDimitry Andric   if (CurrInst->getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT)
2567e8d8bef9SDimitry Andric     return false;
2568e8d8bef9SDimitry Andric   if (TmpInst->getOpcode() == TargetOpcode::G_BUILD_VECTOR) {
2569e8d8bef9SDimitry Andric     for (unsigned I = 1; I < TmpInst->getNumOperands(); ++I) {
2570e8d8bef9SDimitry Andric       if (!MatchInfo[I - 1].isValid())
2571e8d8bef9SDimitry Andric         MatchInfo[I - 1] = TmpInst->getOperand(I).getReg();
2572e8d8bef9SDimitry Andric     }
2573e8d8bef9SDimitry Andric     return true;
2574e8d8bef9SDimitry Andric   }
2575e8d8bef9SDimitry Andric   // If we didn't end in a G_IMPLICIT_DEF, bail out.
2576e8d8bef9SDimitry Andric   return TmpInst->getOpcode() == TargetOpcode::G_IMPLICIT_DEF;
2577e8d8bef9SDimitry Andric }
2578e8d8bef9SDimitry Andric 
2579fe6060f1SDimitry Andric void CombinerHelper::applyCombineInsertVecElts(
2580e8d8bef9SDimitry Andric     MachineInstr &MI, SmallVectorImpl<Register> &MatchInfo) {
2581e8d8bef9SDimitry Andric   Builder.setInstr(MI);
2582e8d8bef9SDimitry Andric   Register UndefReg;
2583e8d8bef9SDimitry Andric   auto GetUndef = [&]() {
2584e8d8bef9SDimitry Andric     if (UndefReg)
2585e8d8bef9SDimitry Andric       return UndefReg;
2586e8d8bef9SDimitry Andric     LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
2587e8d8bef9SDimitry Andric     UndefReg = Builder.buildUndef(DstTy.getScalarType()).getReg(0);
2588e8d8bef9SDimitry Andric     return UndefReg;
2589e8d8bef9SDimitry Andric   };
2590e8d8bef9SDimitry Andric   for (unsigned I = 0; I < MatchInfo.size(); ++I) {
2591e8d8bef9SDimitry Andric     if (!MatchInfo[I])
2592e8d8bef9SDimitry Andric       MatchInfo[I] = GetUndef();
2593e8d8bef9SDimitry Andric   }
2594e8d8bef9SDimitry Andric   Builder.buildBuildVector(MI.getOperand(0).getReg(), MatchInfo);
2595e8d8bef9SDimitry Andric   MI.eraseFromParent();
2596e8d8bef9SDimitry Andric }
2597e8d8bef9SDimitry Andric 
2598fe6060f1SDimitry Andric void CombinerHelper::applySimplifyAddToSub(
25995ffd83dbSDimitry Andric     MachineInstr &MI, std::tuple<Register, Register> &MatchInfo) {
26005ffd83dbSDimitry Andric   Builder.setInstr(MI);
26015ffd83dbSDimitry Andric   Register SubLHS, SubRHS;
26025ffd83dbSDimitry Andric   std::tie(SubLHS, SubRHS) = MatchInfo;
26035ffd83dbSDimitry Andric   Builder.buildSub(MI.getOperand(0).getReg(), SubLHS, SubRHS);
26045ffd83dbSDimitry Andric   MI.eraseFromParent();
26055ffd83dbSDimitry Andric }
26065ffd83dbSDimitry Andric 
2607e8d8bef9SDimitry Andric bool CombinerHelper::matchHoistLogicOpWithSameOpcodeHands(
2608e8d8bef9SDimitry Andric     MachineInstr &MI, InstructionStepsMatchInfo &MatchInfo) {
2609e8d8bef9SDimitry Andric   // Matches: logic (hand x, ...), (hand y, ...) -> hand (logic x, y), ...
2610e8d8bef9SDimitry Andric   //
2611e8d8bef9SDimitry Andric   // Creates the new hand + logic instruction (but does not insert them.)
2612e8d8bef9SDimitry Andric   //
2613e8d8bef9SDimitry Andric   // On success, MatchInfo is populated with the new instructions. These are
2614e8d8bef9SDimitry Andric   // inserted in applyHoistLogicOpWithSameOpcodeHands.
2615e8d8bef9SDimitry Andric   unsigned LogicOpcode = MI.getOpcode();
2616e8d8bef9SDimitry Andric   assert(LogicOpcode == TargetOpcode::G_AND ||
2617e8d8bef9SDimitry Andric          LogicOpcode == TargetOpcode::G_OR ||
2618e8d8bef9SDimitry Andric          LogicOpcode == TargetOpcode::G_XOR);
2619e8d8bef9SDimitry Andric   MachineIRBuilder MIB(MI);
2620e8d8bef9SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
2621e8d8bef9SDimitry Andric   Register LHSReg = MI.getOperand(1).getReg();
2622e8d8bef9SDimitry Andric   Register RHSReg = MI.getOperand(2).getReg();
2623e8d8bef9SDimitry Andric 
2624e8d8bef9SDimitry Andric   // Don't recompute anything.
2625e8d8bef9SDimitry Andric   if (!MRI.hasOneNonDBGUse(LHSReg) || !MRI.hasOneNonDBGUse(RHSReg))
2626e8d8bef9SDimitry Andric     return false;
2627e8d8bef9SDimitry Andric 
2628e8d8bef9SDimitry Andric   // Make sure we have (hand x, ...), (hand y, ...)
2629e8d8bef9SDimitry Andric   MachineInstr *LeftHandInst = getDefIgnoringCopies(LHSReg, MRI);
2630e8d8bef9SDimitry Andric   MachineInstr *RightHandInst = getDefIgnoringCopies(RHSReg, MRI);
2631e8d8bef9SDimitry Andric   if (!LeftHandInst || !RightHandInst)
2632e8d8bef9SDimitry Andric     return false;
2633e8d8bef9SDimitry Andric   unsigned HandOpcode = LeftHandInst->getOpcode();
2634e8d8bef9SDimitry Andric   if (HandOpcode != RightHandInst->getOpcode())
2635e8d8bef9SDimitry Andric     return false;
2636e8d8bef9SDimitry Andric   if (!LeftHandInst->getOperand(1).isReg() ||
2637e8d8bef9SDimitry Andric       !RightHandInst->getOperand(1).isReg())
2638e8d8bef9SDimitry Andric     return false;
2639e8d8bef9SDimitry Andric 
2640e8d8bef9SDimitry Andric   // Make sure the types match up, and if we're doing this post-legalization,
2641e8d8bef9SDimitry Andric   // we end up with legal types.
2642e8d8bef9SDimitry Andric   Register X = LeftHandInst->getOperand(1).getReg();
2643e8d8bef9SDimitry Andric   Register Y = RightHandInst->getOperand(1).getReg();
2644e8d8bef9SDimitry Andric   LLT XTy = MRI.getType(X);
2645e8d8bef9SDimitry Andric   LLT YTy = MRI.getType(Y);
2646e8d8bef9SDimitry Andric   if (XTy != YTy)
2647e8d8bef9SDimitry Andric     return false;
2648e8d8bef9SDimitry Andric   if (!isLegalOrBeforeLegalizer({LogicOpcode, {XTy, YTy}}))
2649e8d8bef9SDimitry Andric     return false;
2650e8d8bef9SDimitry Andric 
2651e8d8bef9SDimitry Andric   // Optional extra source register.
2652e8d8bef9SDimitry Andric   Register ExtraHandOpSrcReg;
2653e8d8bef9SDimitry Andric   switch (HandOpcode) {
2654e8d8bef9SDimitry Andric   default:
2655e8d8bef9SDimitry Andric     return false;
2656e8d8bef9SDimitry Andric   case TargetOpcode::G_ANYEXT:
2657e8d8bef9SDimitry Andric   case TargetOpcode::G_SEXT:
2658e8d8bef9SDimitry Andric   case TargetOpcode::G_ZEXT: {
2659e8d8bef9SDimitry Andric     // Match: logic (ext X), (ext Y) --> ext (logic X, Y)
2660e8d8bef9SDimitry Andric     break;
2661e8d8bef9SDimitry Andric   }
2662e8d8bef9SDimitry Andric   case TargetOpcode::G_AND:
2663e8d8bef9SDimitry Andric   case TargetOpcode::G_ASHR:
2664e8d8bef9SDimitry Andric   case TargetOpcode::G_LSHR:
2665e8d8bef9SDimitry Andric   case TargetOpcode::G_SHL: {
2666e8d8bef9SDimitry Andric     // Match: logic (binop x, z), (binop y, z) -> binop (logic x, y), z
2667e8d8bef9SDimitry Andric     MachineOperand &ZOp = LeftHandInst->getOperand(2);
2668e8d8bef9SDimitry Andric     if (!matchEqualDefs(ZOp, RightHandInst->getOperand(2)))
2669e8d8bef9SDimitry Andric       return false;
2670e8d8bef9SDimitry Andric     ExtraHandOpSrcReg = ZOp.getReg();
2671e8d8bef9SDimitry Andric     break;
2672e8d8bef9SDimitry Andric   }
2673e8d8bef9SDimitry Andric   }
2674e8d8bef9SDimitry Andric 
2675e8d8bef9SDimitry Andric   // Record the steps to build the new instructions.
2676e8d8bef9SDimitry Andric   //
2677e8d8bef9SDimitry Andric   // Steps to build (logic x, y)
2678e8d8bef9SDimitry Andric   auto NewLogicDst = MRI.createGenericVirtualRegister(XTy);
2679e8d8bef9SDimitry Andric   OperandBuildSteps LogicBuildSteps = {
2680e8d8bef9SDimitry Andric       [=](MachineInstrBuilder &MIB) { MIB.addDef(NewLogicDst); },
2681e8d8bef9SDimitry Andric       [=](MachineInstrBuilder &MIB) { MIB.addReg(X); },
2682e8d8bef9SDimitry Andric       [=](MachineInstrBuilder &MIB) { MIB.addReg(Y); }};
2683e8d8bef9SDimitry Andric   InstructionBuildSteps LogicSteps(LogicOpcode, LogicBuildSteps);
2684e8d8bef9SDimitry Andric 
2685e8d8bef9SDimitry Andric   // Steps to build hand (logic x, y), ...z
2686e8d8bef9SDimitry Andric   OperandBuildSteps HandBuildSteps = {
2687e8d8bef9SDimitry Andric       [=](MachineInstrBuilder &MIB) { MIB.addDef(Dst); },
2688e8d8bef9SDimitry Andric       [=](MachineInstrBuilder &MIB) { MIB.addReg(NewLogicDst); }};
2689e8d8bef9SDimitry Andric   if (ExtraHandOpSrcReg.isValid())
2690e8d8bef9SDimitry Andric     HandBuildSteps.push_back(
2691e8d8bef9SDimitry Andric         [=](MachineInstrBuilder &MIB) { MIB.addReg(ExtraHandOpSrcReg); });
2692e8d8bef9SDimitry Andric   InstructionBuildSteps HandSteps(HandOpcode, HandBuildSteps);
2693e8d8bef9SDimitry Andric 
2694e8d8bef9SDimitry Andric   MatchInfo = InstructionStepsMatchInfo({LogicSteps, HandSteps});
2695e8d8bef9SDimitry Andric   return true;
2696e8d8bef9SDimitry Andric }
2697e8d8bef9SDimitry Andric 
2698fe6060f1SDimitry Andric void CombinerHelper::applyBuildInstructionSteps(
2699e8d8bef9SDimitry Andric     MachineInstr &MI, InstructionStepsMatchInfo &MatchInfo) {
2700e8d8bef9SDimitry Andric   assert(MatchInfo.InstrsToBuild.size() &&
2701e8d8bef9SDimitry Andric          "Expected at least one instr to build?");
2702e8d8bef9SDimitry Andric   Builder.setInstr(MI);
2703e8d8bef9SDimitry Andric   for (auto &InstrToBuild : MatchInfo.InstrsToBuild) {
2704e8d8bef9SDimitry Andric     assert(InstrToBuild.Opcode && "Expected a valid opcode?");
2705e8d8bef9SDimitry Andric     assert(InstrToBuild.OperandFns.size() && "Expected at least one operand?");
2706e8d8bef9SDimitry Andric     MachineInstrBuilder Instr = Builder.buildInstr(InstrToBuild.Opcode);
2707e8d8bef9SDimitry Andric     for (auto &OperandFn : InstrToBuild.OperandFns)
2708e8d8bef9SDimitry Andric       OperandFn(Instr);
2709e8d8bef9SDimitry Andric   }
2710e8d8bef9SDimitry Andric   MI.eraseFromParent();
2711e8d8bef9SDimitry Andric }
2712e8d8bef9SDimitry Andric 
2713e8d8bef9SDimitry Andric bool CombinerHelper::matchAshrShlToSextInreg(
2714e8d8bef9SDimitry Andric     MachineInstr &MI, std::tuple<Register, int64_t> &MatchInfo) {
2715e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ASHR);
2716e8d8bef9SDimitry Andric   int64_t ShlCst, AshrCst;
2717e8d8bef9SDimitry Andric   Register Src;
2718e8d8bef9SDimitry Andric   // FIXME: detect splat constant vectors.
2719e8d8bef9SDimitry Andric   if (!mi_match(MI.getOperand(0).getReg(), MRI,
2720e8d8bef9SDimitry Andric                 m_GAShr(m_GShl(m_Reg(Src), m_ICst(ShlCst)), m_ICst(AshrCst))))
2721e8d8bef9SDimitry Andric     return false;
2722e8d8bef9SDimitry Andric   if (ShlCst != AshrCst)
2723e8d8bef9SDimitry Andric     return false;
2724e8d8bef9SDimitry Andric   if (!isLegalOrBeforeLegalizer(
2725e8d8bef9SDimitry Andric           {TargetOpcode::G_SEXT_INREG, {MRI.getType(Src)}}))
2726e8d8bef9SDimitry Andric     return false;
2727e8d8bef9SDimitry Andric   MatchInfo = std::make_tuple(Src, ShlCst);
2728e8d8bef9SDimitry Andric   return true;
2729e8d8bef9SDimitry Andric }
2730fe6060f1SDimitry Andric 
2731fe6060f1SDimitry Andric void CombinerHelper::applyAshShlToSextInreg(
2732e8d8bef9SDimitry Andric     MachineInstr &MI, std::tuple<Register, int64_t> &MatchInfo) {
2733e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ASHR);
2734e8d8bef9SDimitry Andric   Register Src;
2735e8d8bef9SDimitry Andric   int64_t ShiftAmt;
2736e8d8bef9SDimitry Andric   std::tie(Src, ShiftAmt) = MatchInfo;
2737e8d8bef9SDimitry Andric   unsigned Size = MRI.getType(Src).getScalarSizeInBits();
2738e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
2739e8d8bef9SDimitry Andric   Builder.buildSExtInReg(MI.getOperand(0).getReg(), Src, Size - ShiftAmt);
2740e8d8bef9SDimitry Andric   MI.eraseFromParent();
2741fe6060f1SDimitry Andric }
2742fe6060f1SDimitry Andric 
2743fe6060f1SDimitry Andric /// and(and(x, C1), C2) -> C1&C2 ? and(x, C1&C2) : 0
2744fe6060f1SDimitry Andric bool CombinerHelper::matchOverlappingAnd(
2745fe6060f1SDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
2746fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_AND);
2747fe6060f1SDimitry Andric 
2748fe6060f1SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
2749fe6060f1SDimitry Andric   LLT Ty = MRI.getType(Dst);
2750fe6060f1SDimitry Andric 
2751fe6060f1SDimitry Andric   Register R;
2752fe6060f1SDimitry Andric   int64_t C1;
2753fe6060f1SDimitry Andric   int64_t C2;
2754fe6060f1SDimitry Andric   if (!mi_match(
2755fe6060f1SDimitry Andric           Dst, MRI,
2756fe6060f1SDimitry Andric           m_GAnd(m_GAnd(m_Reg(R), m_ICst(C1)), m_ICst(C2))))
2757fe6060f1SDimitry Andric     return false;
2758fe6060f1SDimitry Andric 
2759fe6060f1SDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
2760fe6060f1SDimitry Andric     if (C1 & C2) {
2761fe6060f1SDimitry Andric       B.buildAnd(Dst, R, B.buildConstant(Ty, C1 & C2));
2762fe6060f1SDimitry Andric       return;
2763fe6060f1SDimitry Andric     }
2764fe6060f1SDimitry Andric     auto Zero = B.buildConstant(Ty, 0);
2765fe6060f1SDimitry Andric     replaceRegWith(MRI, Dst, Zero->getOperand(0).getReg());
2766fe6060f1SDimitry Andric   };
2767e8d8bef9SDimitry Andric   return true;
2768e8d8bef9SDimitry Andric }
2769e8d8bef9SDimitry Andric 
2770e8d8bef9SDimitry Andric bool CombinerHelper::matchRedundantAnd(MachineInstr &MI,
2771e8d8bef9SDimitry Andric                                        Register &Replacement) {
2772e8d8bef9SDimitry Andric   // Given
2773e8d8bef9SDimitry Andric   //
2774e8d8bef9SDimitry Andric   // %y:_(sN) = G_SOMETHING
2775e8d8bef9SDimitry Andric   // %x:_(sN) = G_SOMETHING
2776e8d8bef9SDimitry Andric   // %res:_(sN) = G_AND %x, %y
2777e8d8bef9SDimitry Andric   //
2778e8d8bef9SDimitry Andric   // Eliminate the G_AND when it is known that x & y == x or x & y == y.
2779e8d8bef9SDimitry Andric   //
2780e8d8bef9SDimitry Andric   // Patterns like this can appear as a result of legalization. E.g.
2781e8d8bef9SDimitry Andric   //
2782e8d8bef9SDimitry Andric   // %cmp:_(s32) = G_ICMP intpred(pred), %x(s32), %y
2783e8d8bef9SDimitry Andric   // %one:_(s32) = G_CONSTANT i32 1
2784e8d8bef9SDimitry Andric   // %and:_(s32) = G_AND %cmp, %one
2785e8d8bef9SDimitry Andric   //
2786e8d8bef9SDimitry Andric   // In this case, G_ICMP only produces a single bit, so x & 1 == x.
2787e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_AND);
2788e8d8bef9SDimitry Andric   if (!KB)
2789e8d8bef9SDimitry Andric     return false;
2790e8d8bef9SDimitry Andric 
2791e8d8bef9SDimitry Andric   Register AndDst = MI.getOperand(0).getReg();
2792e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(AndDst);
2793e8d8bef9SDimitry Andric 
2794e8d8bef9SDimitry Andric   // FIXME: This should be removed once GISelKnownBits supports vectors.
2795e8d8bef9SDimitry Andric   if (DstTy.isVector())
2796e8d8bef9SDimitry Andric     return false;
2797e8d8bef9SDimitry Andric 
2798e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
2799e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
2800e8d8bef9SDimitry Andric   KnownBits LHSBits = KB->getKnownBits(LHS);
2801e8d8bef9SDimitry Andric   KnownBits RHSBits = KB->getKnownBits(RHS);
2802e8d8bef9SDimitry Andric 
2803e8d8bef9SDimitry Andric   // Check that x & Mask == x.
2804e8d8bef9SDimitry Andric   // x & 1 == x, always
2805e8d8bef9SDimitry Andric   // x & 0 == x, only if x is also 0
2806e8d8bef9SDimitry Andric   // Meaning Mask has no effect if every bit is either one in Mask or zero in x.
2807e8d8bef9SDimitry Andric   //
2808e8d8bef9SDimitry Andric   // Check if we can replace AndDst with the LHS of the G_AND
2809e8d8bef9SDimitry Andric   if (canReplaceReg(AndDst, LHS, MRI) &&
2810349cc55cSDimitry Andric       (LHSBits.Zero | RHSBits.One).isAllOnes()) {
2811e8d8bef9SDimitry Andric     Replacement = LHS;
2812e8d8bef9SDimitry Andric     return true;
2813e8d8bef9SDimitry Andric   }
2814e8d8bef9SDimitry Andric 
2815e8d8bef9SDimitry Andric   // Check if we can replace AndDst with the RHS of the G_AND
2816e8d8bef9SDimitry Andric   if (canReplaceReg(AndDst, RHS, MRI) &&
2817349cc55cSDimitry Andric       (LHSBits.One | RHSBits.Zero).isAllOnes()) {
2818e8d8bef9SDimitry Andric     Replacement = RHS;
2819e8d8bef9SDimitry Andric     return true;
2820e8d8bef9SDimitry Andric   }
2821e8d8bef9SDimitry Andric 
2822e8d8bef9SDimitry Andric   return false;
2823e8d8bef9SDimitry Andric }
2824e8d8bef9SDimitry Andric 
2825e8d8bef9SDimitry Andric bool CombinerHelper::matchRedundantOr(MachineInstr &MI, Register &Replacement) {
2826e8d8bef9SDimitry Andric   // Given
2827e8d8bef9SDimitry Andric   //
2828e8d8bef9SDimitry Andric   // %y:_(sN) = G_SOMETHING
2829e8d8bef9SDimitry Andric   // %x:_(sN) = G_SOMETHING
2830e8d8bef9SDimitry Andric   // %res:_(sN) = G_OR %x, %y
2831e8d8bef9SDimitry Andric   //
2832e8d8bef9SDimitry Andric   // Eliminate the G_OR when it is known that x | y == x or x | y == y.
2833e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_OR);
2834e8d8bef9SDimitry Andric   if (!KB)
2835e8d8bef9SDimitry Andric     return false;
2836e8d8bef9SDimitry Andric 
2837e8d8bef9SDimitry Andric   Register OrDst = MI.getOperand(0).getReg();
2838e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(OrDst);
2839e8d8bef9SDimitry Andric 
2840e8d8bef9SDimitry Andric   // FIXME: This should be removed once GISelKnownBits supports vectors.
2841e8d8bef9SDimitry Andric   if (DstTy.isVector())
2842e8d8bef9SDimitry Andric     return false;
2843e8d8bef9SDimitry Andric 
2844e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
2845e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
2846e8d8bef9SDimitry Andric   KnownBits LHSBits = KB->getKnownBits(LHS);
2847e8d8bef9SDimitry Andric   KnownBits RHSBits = KB->getKnownBits(RHS);
2848e8d8bef9SDimitry Andric 
2849e8d8bef9SDimitry Andric   // Check that x | Mask == x.
2850e8d8bef9SDimitry Andric   // x | 0 == x, always
2851e8d8bef9SDimitry Andric   // x | 1 == x, only if x is also 1
2852e8d8bef9SDimitry Andric   // Meaning Mask has no effect if every bit is either zero in Mask or one in x.
2853e8d8bef9SDimitry Andric   //
2854e8d8bef9SDimitry Andric   // Check if we can replace OrDst with the LHS of the G_OR
2855e8d8bef9SDimitry Andric   if (canReplaceReg(OrDst, LHS, MRI) &&
2856349cc55cSDimitry Andric       (LHSBits.One | RHSBits.Zero).isAllOnes()) {
2857e8d8bef9SDimitry Andric     Replacement = LHS;
2858e8d8bef9SDimitry Andric     return true;
2859e8d8bef9SDimitry Andric   }
2860e8d8bef9SDimitry Andric 
2861e8d8bef9SDimitry Andric   // Check if we can replace OrDst with the RHS of the G_OR
2862e8d8bef9SDimitry Andric   if (canReplaceReg(OrDst, RHS, MRI) &&
2863349cc55cSDimitry Andric       (LHSBits.Zero | RHSBits.One).isAllOnes()) {
2864e8d8bef9SDimitry Andric     Replacement = RHS;
2865e8d8bef9SDimitry Andric     return true;
2866e8d8bef9SDimitry Andric   }
2867e8d8bef9SDimitry Andric 
2868e8d8bef9SDimitry Andric   return false;
2869e8d8bef9SDimitry Andric }
2870e8d8bef9SDimitry Andric 
2871e8d8bef9SDimitry Andric bool CombinerHelper::matchRedundantSExtInReg(MachineInstr &MI) {
2872e8d8bef9SDimitry Andric   // If the input is already sign extended, just drop the extension.
2873e8d8bef9SDimitry Andric   Register Src = MI.getOperand(1).getReg();
2874e8d8bef9SDimitry Andric   unsigned ExtBits = MI.getOperand(2).getImm();
2875e8d8bef9SDimitry Andric   unsigned TypeSize = MRI.getType(Src).getScalarSizeInBits();
2876e8d8bef9SDimitry Andric   return KB->computeNumSignBits(Src) >= (TypeSize - ExtBits + 1);
2877e8d8bef9SDimitry Andric }
2878e8d8bef9SDimitry Andric 
2879e8d8bef9SDimitry Andric static bool isConstValidTrue(const TargetLowering &TLI, unsigned ScalarSizeBits,
2880e8d8bef9SDimitry Andric                              int64_t Cst, bool IsVector, bool IsFP) {
2881e8d8bef9SDimitry Andric   // For i1, Cst will always be -1 regardless of boolean contents.
2882e8d8bef9SDimitry Andric   return (ScalarSizeBits == 1 && Cst == -1) ||
2883e8d8bef9SDimitry Andric          isConstTrueVal(TLI, Cst, IsVector, IsFP);
2884e8d8bef9SDimitry Andric }
2885e8d8bef9SDimitry Andric 
2886e8d8bef9SDimitry Andric bool CombinerHelper::matchNotCmp(MachineInstr &MI,
2887e8d8bef9SDimitry Andric                                  SmallVectorImpl<Register> &RegsToNegate) {
2888e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_XOR);
2889e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(MI.getOperand(0).getReg());
2890e8d8bef9SDimitry Andric   const auto &TLI = *Builder.getMF().getSubtarget().getTargetLowering();
2891e8d8bef9SDimitry Andric   Register XorSrc;
2892e8d8bef9SDimitry Andric   Register CstReg;
2893e8d8bef9SDimitry Andric   // We match xor(src, true) here.
2894e8d8bef9SDimitry Andric   if (!mi_match(MI.getOperand(0).getReg(), MRI,
2895e8d8bef9SDimitry Andric                 m_GXor(m_Reg(XorSrc), m_Reg(CstReg))))
2896e8d8bef9SDimitry Andric     return false;
2897e8d8bef9SDimitry Andric 
2898e8d8bef9SDimitry Andric   if (!MRI.hasOneNonDBGUse(XorSrc))
2899e8d8bef9SDimitry Andric     return false;
2900e8d8bef9SDimitry Andric 
2901e8d8bef9SDimitry Andric   // Check that XorSrc is the root of a tree of comparisons combined with ANDs
2902e8d8bef9SDimitry Andric   // and ORs. The suffix of RegsToNegate starting from index I is used a work
2903e8d8bef9SDimitry Andric   // list of tree nodes to visit.
2904e8d8bef9SDimitry Andric   RegsToNegate.push_back(XorSrc);
2905e8d8bef9SDimitry Andric   // Remember whether the comparisons are all integer or all floating point.
2906e8d8bef9SDimitry Andric   bool IsInt = false;
2907e8d8bef9SDimitry Andric   bool IsFP = false;
2908e8d8bef9SDimitry Andric   for (unsigned I = 0; I < RegsToNegate.size(); ++I) {
2909e8d8bef9SDimitry Andric     Register Reg = RegsToNegate[I];
2910e8d8bef9SDimitry Andric     if (!MRI.hasOneNonDBGUse(Reg))
2911e8d8bef9SDimitry Andric       return false;
2912e8d8bef9SDimitry Andric     MachineInstr *Def = MRI.getVRegDef(Reg);
2913e8d8bef9SDimitry Andric     switch (Def->getOpcode()) {
2914e8d8bef9SDimitry Andric     default:
2915e8d8bef9SDimitry Andric       // Don't match if the tree contains anything other than ANDs, ORs and
2916e8d8bef9SDimitry Andric       // comparisons.
2917e8d8bef9SDimitry Andric       return false;
2918e8d8bef9SDimitry Andric     case TargetOpcode::G_ICMP:
2919e8d8bef9SDimitry Andric       if (IsFP)
2920e8d8bef9SDimitry Andric         return false;
2921e8d8bef9SDimitry Andric       IsInt = true;
2922e8d8bef9SDimitry Andric       // When we apply the combine we will invert the predicate.
2923e8d8bef9SDimitry Andric       break;
2924e8d8bef9SDimitry Andric     case TargetOpcode::G_FCMP:
2925e8d8bef9SDimitry Andric       if (IsInt)
2926e8d8bef9SDimitry Andric         return false;
2927e8d8bef9SDimitry Andric       IsFP = true;
2928e8d8bef9SDimitry Andric       // When we apply the combine we will invert the predicate.
2929e8d8bef9SDimitry Andric       break;
2930e8d8bef9SDimitry Andric     case TargetOpcode::G_AND:
2931e8d8bef9SDimitry Andric     case TargetOpcode::G_OR:
2932e8d8bef9SDimitry Andric       // Implement De Morgan's laws:
2933e8d8bef9SDimitry Andric       // ~(x & y) -> ~x | ~y
2934e8d8bef9SDimitry Andric       // ~(x | y) -> ~x & ~y
2935e8d8bef9SDimitry Andric       // When we apply the combine we will change the opcode and recursively
2936e8d8bef9SDimitry Andric       // negate the operands.
2937e8d8bef9SDimitry Andric       RegsToNegate.push_back(Def->getOperand(1).getReg());
2938e8d8bef9SDimitry Andric       RegsToNegate.push_back(Def->getOperand(2).getReg());
2939e8d8bef9SDimitry Andric       break;
2940e8d8bef9SDimitry Andric     }
2941e8d8bef9SDimitry Andric   }
2942e8d8bef9SDimitry Andric 
2943e8d8bef9SDimitry Andric   // Now we know whether the comparisons are integer or floating point, check
2944e8d8bef9SDimitry Andric   // the constant in the xor.
2945e8d8bef9SDimitry Andric   int64_t Cst;
2946e8d8bef9SDimitry Andric   if (Ty.isVector()) {
2947e8d8bef9SDimitry Andric     MachineInstr *CstDef = MRI.getVRegDef(CstReg);
2948*81ad6265SDimitry Andric     auto MaybeCst = getIConstantSplatSExtVal(*CstDef, MRI);
2949e8d8bef9SDimitry Andric     if (!MaybeCst)
2950e8d8bef9SDimitry Andric       return false;
2951e8d8bef9SDimitry Andric     if (!isConstValidTrue(TLI, Ty.getScalarSizeInBits(), *MaybeCst, true, IsFP))
2952e8d8bef9SDimitry Andric       return false;
2953e8d8bef9SDimitry Andric   } else {
2954e8d8bef9SDimitry Andric     if (!mi_match(CstReg, MRI, m_ICst(Cst)))
2955e8d8bef9SDimitry Andric       return false;
2956e8d8bef9SDimitry Andric     if (!isConstValidTrue(TLI, Ty.getSizeInBits(), Cst, false, IsFP))
2957e8d8bef9SDimitry Andric       return false;
2958e8d8bef9SDimitry Andric   }
2959e8d8bef9SDimitry Andric 
2960e8d8bef9SDimitry Andric   return true;
2961e8d8bef9SDimitry Andric }
2962e8d8bef9SDimitry Andric 
2963fe6060f1SDimitry Andric void CombinerHelper::applyNotCmp(MachineInstr &MI,
2964e8d8bef9SDimitry Andric                                  SmallVectorImpl<Register> &RegsToNegate) {
2965e8d8bef9SDimitry Andric   for (Register Reg : RegsToNegate) {
2966e8d8bef9SDimitry Andric     MachineInstr *Def = MRI.getVRegDef(Reg);
2967e8d8bef9SDimitry Andric     Observer.changingInstr(*Def);
2968e8d8bef9SDimitry Andric     // For each comparison, invert the opcode. For each AND and OR, change the
2969e8d8bef9SDimitry Andric     // opcode.
2970e8d8bef9SDimitry Andric     switch (Def->getOpcode()) {
2971e8d8bef9SDimitry Andric     default:
2972e8d8bef9SDimitry Andric       llvm_unreachable("Unexpected opcode");
2973e8d8bef9SDimitry Andric     case TargetOpcode::G_ICMP:
2974e8d8bef9SDimitry Andric     case TargetOpcode::G_FCMP: {
2975e8d8bef9SDimitry Andric       MachineOperand &PredOp = Def->getOperand(1);
2976e8d8bef9SDimitry Andric       CmpInst::Predicate NewP = CmpInst::getInversePredicate(
2977e8d8bef9SDimitry Andric           (CmpInst::Predicate)PredOp.getPredicate());
2978e8d8bef9SDimitry Andric       PredOp.setPredicate(NewP);
2979e8d8bef9SDimitry Andric       break;
2980e8d8bef9SDimitry Andric     }
2981e8d8bef9SDimitry Andric     case TargetOpcode::G_AND:
2982e8d8bef9SDimitry Andric       Def->setDesc(Builder.getTII().get(TargetOpcode::G_OR));
2983e8d8bef9SDimitry Andric       break;
2984e8d8bef9SDimitry Andric     case TargetOpcode::G_OR:
2985e8d8bef9SDimitry Andric       Def->setDesc(Builder.getTII().get(TargetOpcode::G_AND));
2986e8d8bef9SDimitry Andric       break;
2987e8d8bef9SDimitry Andric     }
2988e8d8bef9SDimitry Andric     Observer.changedInstr(*Def);
2989e8d8bef9SDimitry Andric   }
2990e8d8bef9SDimitry Andric 
2991e8d8bef9SDimitry Andric   replaceRegWith(MRI, MI.getOperand(0).getReg(), MI.getOperand(1).getReg());
2992e8d8bef9SDimitry Andric   MI.eraseFromParent();
2993e8d8bef9SDimitry Andric }
2994e8d8bef9SDimitry Andric 
2995e8d8bef9SDimitry Andric bool CombinerHelper::matchXorOfAndWithSameReg(
2996e8d8bef9SDimitry Andric     MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
2997e8d8bef9SDimitry Andric   // Match (xor (and x, y), y) (or any of its commuted cases)
2998e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_XOR);
2999e8d8bef9SDimitry Andric   Register &X = MatchInfo.first;
3000e8d8bef9SDimitry Andric   Register &Y = MatchInfo.second;
3001e8d8bef9SDimitry Andric   Register AndReg = MI.getOperand(1).getReg();
3002e8d8bef9SDimitry Andric   Register SharedReg = MI.getOperand(2).getReg();
3003e8d8bef9SDimitry Andric 
3004e8d8bef9SDimitry Andric   // Find a G_AND on either side of the G_XOR.
3005e8d8bef9SDimitry Andric   // Look for one of
3006e8d8bef9SDimitry Andric   //
3007e8d8bef9SDimitry Andric   // (xor (and x, y), SharedReg)
3008e8d8bef9SDimitry Andric   // (xor SharedReg, (and x, y))
3009e8d8bef9SDimitry Andric   if (!mi_match(AndReg, MRI, m_GAnd(m_Reg(X), m_Reg(Y)))) {
3010e8d8bef9SDimitry Andric     std::swap(AndReg, SharedReg);
3011e8d8bef9SDimitry Andric     if (!mi_match(AndReg, MRI, m_GAnd(m_Reg(X), m_Reg(Y))))
3012e8d8bef9SDimitry Andric       return false;
3013e8d8bef9SDimitry Andric   }
3014e8d8bef9SDimitry Andric 
3015e8d8bef9SDimitry Andric   // Only do this if we'll eliminate the G_AND.
3016e8d8bef9SDimitry Andric   if (!MRI.hasOneNonDBGUse(AndReg))
3017e8d8bef9SDimitry Andric     return false;
3018e8d8bef9SDimitry Andric 
3019e8d8bef9SDimitry Andric   // We can combine if SharedReg is the same as either the LHS or RHS of the
3020e8d8bef9SDimitry Andric   // G_AND.
3021e8d8bef9SDimitry Andric   if (Y != SharedReg)
3022e8d8bef9SDimitry Andric     std::swap(X, Y);
3023e8d8bef9SDimitry Andric   return Y == SharedReg;
3024e8d8bef9SDimitry Andric }
3025e8d8bef9SDimitry Andric 
3026fe6060f1SDimitry Andric void CombinerHelper::applyXorOfAndWithSameReg(
3027e8d8bef9SDimitry Andric     MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
3028e8d8bef9SDimitry Andric   // Fold (xor (and x, y), y) -> (and (not x), y)
3029e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
3030e8d8bef9SDimitry Andric   Register X, Y;
3031e8d8bef9SDimitry Andric   std::tie(X, Y) = MatchInfo;
3032e8d8bef9SDimitry Andric   auto Not = Builder.buildNot(MRI.getType(X), X);
3033e8d8bef9SDimitry Andric   Observer.changingInstr(MI);
3034e8d8bef9SDimitry Andric   MI.setDesc(Builder.getTII().get(TargetOpcode::G_AND));
3035e8d8bef9SDimitry Andric   MI.getOperand(1).setReg(Not->getOperand(0).getReg());
3036e8d8bef9SDimitry Andric   MI.getOperand(2).setReg(Y);
3037e8d8bef9SDimitry Andric   Observer.changedInstr(MI);
3038e8d8bef9SDimitry Andric }
3039e8d8bef9SDimitry Andric 
3040e8d8bef9SDimitry Andric bool CombinerHelper::matchPtrAddZero(MachineInstr &MI) {
3041349cc55cSDimitry Andric   auto &PtrAdd = cast<GPtrAdd>(MI);
3042349cc55cSDimitry Andric   Register DstReg = PtrAdd.getReg(0);
3043e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(DstReg);
3044e8d8bef9SDimitry Andric   const DataLayout &DL = Builder.getMF().getDataLayout();
3045e8d8bef9SDimitry Andric 
3046e8d8bef9SDimitry Andric   if (DL.isNonIntegralAddressSpace(Ty.getScalarType().getAddressSpace()))
3047e8d8bef9SDimitry Andric     return false;
3048e8d8bef9SDimitry Andric 
3049e8d8bef9SDimitry Andric   if (Ty.isPointer()) {
3050349cc55cSDimitry Andric     auto ConstVal = getIConstantVRegVal(PtrAdd.getBaseReg(), MRI);
3051e8d8bef9SDimitry Andric     return ConstVal && *ConstVal == 0;
3052e8d8bef9SDimitry Andric   }
3053e8d8bef9SDimitry Andric 
3054e8d8bef9SDimitry Andric   assert(Ty.isVector() && "Expecting a vector type");
3055349cc55cSDimitry Andric   const MachineInstr *VecMI = MRI.getVRegDef(PtrAdd.getBaseReg());
3056e8d8bef9SDimitry Andric   return isBuildVectorAllZeros(*VecMI, MRI);
3057e8d8bef9SDimitry Andric }
3058e8d8bef9SDimitry Andric 
3059fe6060f1SDimitry Andric void CombinerHelper::applyPtrAddZero(MachineInstr &MI) {
3060349cc55cSDimitry Andric   auto &PtrAdd = cast<GPtrAdd>(MI);
3061349cc55cSDimitry Andric   Builder.setInstrAndDebugLoc(PtrAdd);
3062349cc55cSDimitry Andric   Builder.buildIntToPtr(PtrAdd.getReg(0), PtrAdd.getOffsetReg());
3063349cc55cSDimitry Andric   PtrAdd.eraseFromParent();
3064e8d8bef9SDimitry Andric }
3065e8d8bef9SDimitry Andric 
3066e8d8bef9SDimitry Andric /// The second source operand is known to be a power of 2.
3067fe6060f1SDimitry Andric void CombinerHelper::applySimplifyURemByPow2(MachineInstr &MI) {
3068e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
3069e8d8bef9SDimitry Andric   Register Src0 = MI.getOperand(1).getReg();
3070e8d8bef9SDimitry Andric   Register Pow2Src1 = MI.getOperand(2).getReg();
3071e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(DstReg);
3072e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
3073e8d8bef9SDimitry Andric 
3074e8d8bef9SDimitry Andric   // Fold (urem x, pow2) -> (and x, pow2-1)
3075e8d8bef9SDimitry Andric   auto NegOne = Builder.buildConstant(Ty, -1);
3076e8d8bef9SDimitry Andric   auto Add = Builder.buildAdd(Ty, Pow2Src1, NegOne);
3077e8d8bef9SDimitry Andric   Builder.buildAnd(DstReg, Src0, Add);
3078e8d8bef9SDimitry Andric   MI.eraseFromParent();
3079e8d8bef9SDimitry Andric }
3080e8d8bef9SDimitry Andric 
3081*81ad6265SDimitry Andric bool CombinerHelper::matchFoldBinOpIntoSelect(MachineInstr &MI,
3082*81ad6265SDimitry Andric                                               unsigned &SelectOpNo) {
3083*81ad6265SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
3084*81ad6265SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
3085*81ad6265SDimitry Andric 
3086*81ad6265SDimitry Andric   Register OtherOperandReg = RHS;
3087*81ad6265SDimitry Andric   SelectOpNo = 1;
3088*81ad6265SDimitry Andric   MachineInstr *Select = MRI.getVRegDef(LHS);
3089*81ad6265SDimitry Andric 
3090*81ad6265SDimitry Andric   // Don't do this unless the old select is going away. We want to eliminate the
3091*81ad6265SDimitry Andric   // binary operator, not replace a binop with a select.
3092*81ad6265SDimitry Andric   if (Select->getOpcode() != TargetOpcode::G_SELECT ||
3093*81ad6265SDimitry Andric       !MRI.hasOneNonDBGUse(LHS)) {
3094*81ad6265SDimitry Andric     OtherOperandReg = LHS;
3095*81ad6265SDimitry Andric     SelectOpNo = 2;
3096*81ad6265SDimitry Andric     Select = MRI.getVRegDef(RHS);
3097*81ad6265SDimitry Andric     if (Select->getOpcode() != TargetOpcode::G_SELECT ||
3098*81ad6265SDimitry Andric         !MRI.hasOneNonDBGUse(RHS))
3099*81ad6265SDimitry Andric       return false;
3100*81ad6265SDimitry Andric   }
3101*81ad6265SDimitry Andric 
3102*81ad6265SDimitry Andric   MachineInstr *SelectLHS = MRI.getVRegDef(Select->getOperand(2).getReg());
3103*81ad6265SDimitry Andric   MachineInstr *SelectRHS = MRI.getVRegDef(Select->getOperand(3).getReg());
3104*81ad6265SDimitry Andric 
3105*81ad6265SDimitry Andric   if (!isConstantOrConstantVector(*SelectLHS, MRI,
3106*81ad6265SDimitry Andric                                   /*AllowFP*/ true,
3107*81ad6265SDimitry Andric                                   /*AllowOpaqueConstants*/ false))
3108*81ad6265SDimitry Andric     return false;
3109*81ad6265SDimitry Andric   if (!isConstantOrConstantVector(*SelectRHS, MRI,
3110*81ad6265SDimitry Andric                                   /*AllowFP*/ true,
3111*81ad6265SDimitry Andric                                   /*AllowOpaqueConstants*/ false))
3112*81ad6265SDimitry Andric     return false;
3113*81ad6265SDimitry Andric 
3114*81ad6265SDimitry Andric   unsigned BinOpcode = MI.getOpcode();
3115*81ad6265SDimitry Andric 
3116*81ad6265SDimitry Andric   // We know know one of the operands is a select of constants. Now verify that
3117*81ad6265SDimitry Andric   // the other binary operator operand is either a constant, or we can handle a
3118*81ad6265SDimitry Andric   // variable.
3119*81ad6265SDimitry Andric   bool CanFoldNonConst =
3120*81ad6265SDimitry Andric       (BinOpcode == TargetOpcode::G_AND || BinOpcode == TargetOpcode::G_OR) &&
3121*81ad6265SDimitry Andric       (isNullOrNullSplat(*SelectLHS, MRI) ||
3122*81ad6265SDimitry Andric        isAllOnesOrAllOnesSplat(*SelectLHS, MRI)) &&
3123*81ad6265SDimitry Andric       (isNullOrNullSplat(*SelectRHS, MRI) ||
3124*81ad6265SDimitry Andric        isAllOnesOrAllOnesSplat(*SelectRHS, MRI));
3125*81ad6265SDimitry Andric   if (CanFoldNonConst)
3126*81ad6265SDimitry Andric     return true;
3127*81ad6265SDimitry Andric 
3128*81ad6265SDimitry Andric   return isConstantOrConstantVector(*MRI.getVRegDef(OtherOperandReg), MRI,
3129*81ad6265SDimitry Andric                                     /*AllowFP*/ true,
3130*81ad6265SDimitry Andric                                     /*AllowOpaqueConstants*/ false);
3131*81ad6265SDimitry Andric }
3132*81ad6265SDimitry Andric 
3133*81ad6265SDimitry Andric /// \p SelectOperand is the operand in binary operator \p MI that is the select
3134*81ad6265SDimitry Andric /// to fold.
3135*81ad6265SDimitry Andric bool CombinerHelper::applyFoldBinOpIntoSelect(MachineInstr &MI,
3136*81ad6265SDimitry Andric                                               const unsigned &SelectOperand) {
3137*81ad6265SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
3138*81ad6265SDimitry Andric 
3139*81ad6265SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
3140*81ad6265SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
3141*81ad6265SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
3142*81ad6265SDimitry Andric   MachineInstr *Select = MRI.getVRegDef(MI.getOperand(SelectOperand).getReg());
3143*81ad6265SDimitry Andric 
3144*81ad6265SDimitry Andric   Register SelectCond = Select->getOperand(1).getReg();
3145*81ad6265SDimitry Andric   Register SelectTrue = Select->getOperand(2).getReg();
3146*81ad6265SDimitry Andric   Register SelectFalse = Select->getOperand(3).getReg();
3147*81ad6265SDimitry Andric 
3148*81ad6265SDimitry Andric   LLT Ty = MRI.getType(Dst);
3149*81ad6265SDimitry Andric   unsigned BinOpcode = MI.getOpcode();
3150*81ad6265SDimitry Andric 
3151*81ad6265SDimitry Andric   Register FoldTrue, FoldFalse;
3152*81ad6265SDimitry Andric 
3153*81ad6265SDimitry Andric   // We have a select-of-constants followed by a binary operator with a
3154*81ad6265SDimitry Andric   // constant. Eliminate the binop by pulling the constant math into the select.
3155*81ad6265SDimitry Andric   // Example: add (select Cond, CT, CF), CBO --> select Cond, CT + CBO, CF + CBO
3156*81ad6265SDimitry Andric   if (SelectOperand == 1) {
3157*81ad6265SDimitry Andric     // TODO: SelectionDAG verifies this actually constant folds before
3158*81ad6265SDimitry Andric     // committing to the combine.
3159*81ad6265SDimitry Andric 
3160*81ad6265SDimitry Andric     FoldTrue = Builder.buildInstr(BinOpcode, {Ty}, {SelectTrue, RHS}).getReg(0);
3161*81ad6265SDimitry Andric     FoldFalse =
3162*81ad6265SDimitry Andric         Builder.buildInstr(BinOpcode, {Ty}, {SelectFalse, RHS}).getReg(0);
3163*81ad6265SDimitry Andric   } else {
3164*81ad6265SDimitry Andric     FoldTrue = Builder.buildInstr(BinOpcode, {Ty}, {LHS, SelectTrue}).getReg(0);
3165*81ad6265SDimitry Andric     FoldFalse =
3166*81ad6265SDimitry Andric         Builder.buildInstr(BinOpcode, {Ty}, {LHS, SelectFalse}).getReg(0);
3167*81ad6265SDimitry Andric   }
3168*81ad6265SDimitry Andric 
3169*81ad6265SDimitry Andric   Builder.buildSelect(Dst, SelectCond, FoldTrue, FoldFalse, MI.getFlags());
3170*81ad6265SDimitry Andric   Observer.erasingInstr(*Select);
3171*81ad6265SDimitry Andric   Select->eraseFromParent();
3172*81ad6265SDimitry Andric   MI.eraseFromParent();
3173*81ad6265SDimitry Andric 
3174*81ad6265SDimitry Andric   return true;
3175*81ad6265SDimitry Andric }
3176*81ad6265SDimitry Andric 
3177e8d8bef9SDimitry Andric Optional<SmallVector<Register, 8>>
3178e8d8bef9SDimitry Andric CombinerHelper::findCandidatesForLoadOrCombine(const MachineInstr *Root) const {
3179e8d8bef9SDimitry Andric   assert(Root->getOpcode() == TargetOpcode::G_OR && "Expected G_OR only!");
3180e8d8bef9SDimitry Andric   // We want to detect if Root is part of a tree which represents a bunch
3181e8d8bef9SDimitry Andric   // of loads being merged into a larger load. We'll try to recognize patterns
3182e8d8bef9SDimitry Andric   // like, for example:
3183e8d8bef9SDimitry Andric   //
3184e8d8bef9SDimitry Andric   //  Reg   Reg
3185e8d8bef9SDimitry Andric   //   \    /
3186e8d8bef9SDimitry Andric   //    OR_1   Reg
3187e8d8bef9SDimitry Andric   //     \    /
3188e8d8bef9SDimitry Andric   //      OR_2
3189e8d8bef9SDimitry Andric   //        \     Reg
3190e8d8bef9SDimitry Andric   //         .. /
3191e8d8bef9SDimitry Andric   //        Root
3192e8d8bef9SDimitry Andric   //
3193e8d8bef9SDimitry Andric   //  Reg   Reg   Reg   Reg
3194e8d8bef9SDimitry Andric   //     \ /       \   /
3195e8d8bef9SDimitry Andric   //     OR_1      OR_2
3196e8d8bef9SDimitry Andric   //       \       /
3197e8d8bef9SDimitry Andric   //        \    /
3198e8d8bef9SDimitry Andric   //         ...
3199e8d8bef9SDimitry Andric   //         Root
3200e8d8bef9SDimitry Andric   //
3201e8d8bef9SDimitry Andric   // Each "Reg" may have been produced by a load + some arithmetic. This
3202e8d8bef9SDimitry Andric   // function will save each of them.
3203e8d8bef9SDimitry Andric   SmallVector<Register, 8> RegsToVisit;
3204e8d8bef9SDimitry Andric   SmallVector<const MachineInstr *, 7> Ors = {Root};
3205e8d8bef9SDimitry Andric 
3206e8d8bef9SDimitry Andric   // In the "worst" case, we're dealing with a load for each byte. So, there
3207e8d8bef9SDimitry Andric   // are at most #bytes - 1 ORs.
3208e8d8bef9SDimitry Andric   const unsigned MaxIter =
3209e8d8bef9SDimitry Andric       MRI.getType(Root->getOperand(0).getReg()).getSizeInBytes() - 1;
3210e8d8bef9SDimitry Andric   for (unsigned Iter = 0; Iter < MaxIter; ++Iter) {
3211e8d8bef9SDimitry Andric     if (Ors.empty())
3212e8d8bef9SDimitry Andric       break;
3213e8d8bef9SDimitry Andric     const MachineInstr *Curr = Ors.pop_back_val();
3214e8d8bef9SDimitry Andric     Register OrLHS = Curr->getOperand(1).getReg();
3215e8d8bef9SDimitry Andric     Register OrRHS = Curr->getOperand(2).getReg();
3216e8d8bef9SDimitry Andric 
3217e8d8bef9SDimitry Andric     // In the combine, we want to elimate the entire tree.
3218e8d8bef9SDimitry Andric     if (!MRI.hasOneNonDBGUse(OrLHS) || !MRI.hasOneNonDBGUse(OrRHS))
3219e8d8bef9SDimitry Andric       return None;
3220e8d8bef9SDimitry Andric 
3221e8d8bef9SDimitry Andric     // If it's a G_OR, save it and continue to walk. If it's not, then it's
3222e8d8bef9SDimitry Andric     // something that may be a load + arithmetic.
3223e8d8bef9SDimitry Andric     if (const MachineInstr *Or = getOpcodeDef(TargetOpcode::G_OR, OrLHS, MRI))
3224e8d8bef9SDimitry Andric       Ors.push_back(Or);
3225e8d8bef9SDimitry Andric     else
3226e8d8bef9SDimitry Andric       RegsToVisit.push_back(OrLHS);
3227e8d8bef9SDimitry Andric     if (const MachineInstr *Or = getOpcodeDef(TargetOpcode::G_OR, OrRHS, MRI))
3228e8d8bef9SDimitry Andric       Ors.push_back(Or);
3229e8d8bef9SDimitry Andric     else
3230e8d8bef9SDimitry Andric       RegsToVisit.push_back(OrRHS);
3231e8d8bef9SDimitry Andric   }
3232e8d8bef9SDimitry Andric 
3233e8d8bef9SDimitry Andric   // We're going to try and merge each register into a wider power-of-2 type,
3234e8d8bef9SDimitry Andric   // so we ought to have an even number of registers.
3235e8d8bef9SDimitry Andric   if (RegsToVisit.empty() || RegsToVisit.size() % 2 != 0)
3236e8d8bef9SDimitry Andric     return None;
3237e8d8bef9SDimitry Andric   return RegsToVisit;
3238e8d8bef9SDimitry Andric }
3239e8d8bef9SDimitry Andric 
3240e8d8bef9SDimitry Andric /// Helper function for findLoadOffsetsForLoadOrCombine.
3241e8d8bef9SDimitry Andric ///
3242e8d8bef9SDimitry Andric /// Check if \p Reg is the result of loading a \p MemSizeInBits wide value,
3243e8d8bef9SDimitry Andric /// and then moving that value into a specific byte offset.
3244e8d8bef9SDimitry Andric ///
3245e8d8bef9SDimitry Andric /// e.g. x[i] << 24
3246e8d8bef9SDimitry Andric ///
3247e8d8bef9SDimitry Andric /// \returns The load instruction and the byte offset it is moved into.
3248fe6060f1SDimitry Andric static Optional<std::pair<GZExtLoad *, int64_t>>
3249e8d8bef9SDimitry Andric matchLoadAndBytePosition(Register Reg, unsigned MemSizeInBits,
3250e8d8bef9SDimitry Andric                          const MachineRegisterInfo &MRI) {
3251e8d8bef9SDimitry Andric   assert(MRI.hasOneNonDBGUse(Reg) &&
3252e8d8bef9SDimitry Andric          "Expected Reg to only have one non-debug use?");
3253e8d8bef9SDimitry Andric   Register MaybeLoad;
3254e8d8bef9SDimitry Andric   int64_t Shift;
3255e8d8bef9SDimitry Andric   if (!mi_match(Reg, MRI,
3256e8d8bef9SDimitry Andric                 m_OneNonDBGUse(m_GShl(m_Reg(MaybeLoad), m_ICst(Shift))))) {
3257e8d8bef9SDimitry Andric     Shift = 0;
3258e8d8bef9SDimitry Andric     MaybeLoad = Reg;
3259e8d8bef9SDimitry Andric   }
3260e8d8bef9SDimitry Andric 
3261e8d8bef9SDimitry Andric   if (Shift % MemSizeInBits != 0)
3262e8d8bef9SDimitry Andric     return None;
3263e8d8bef9SDimitry Andric 
3264e8d8bef9SDimitry Andric   // TODO: Handle other types of loads.
3265fe6060f1SDimitry Andric   auto *Load = getOpcodeDef<GZExtLoad>(MaybeLoad, MRI);
3266e8d8bef9SDimitry Andric   if (!Load)
3267e8d8bef9SDimitry Andric     return None;
3268e8d8bef9SDimitry Andric 
3269fe6060f1SDimitry Andric   if (!Load->isUnordered() || Load->getMemSizeInBits() != MemSizeInBits)
3270e8d8bef9SDimitry Andric     return None;
3271e8d8bef9SDimitry Andric 
3272e8d8bef9SDimitry Andric   return std::make_pair(Load, Shift / MemSizeInBits);
3273e8d8bef9SDimitry Andric }
3274e8d8bef9SDimitry Andric 
3275fe6060f1SDimitry Andric Optional<std::tuple<GZExtLoad *, int64_t, GZExtLoad *>>
3276e8d8bef9SDimitry Andric CombinerHelper::findLoadOffsetsForLoadOrCombine(
3277e8d8bef9SDimitry Andric     SmallDenseMap<int64_t, int64_t, 8> &MemOffset2Idx,
3278e8d8bef9SDimitry Andric     const SmallVector<Register, 8> &RegsToVisit, const unsigned MemSizeInBits) {
3279e8d8bef9SDimitry Andric 
3280e8d8bef9SDimitry Andric   // Each load found for the pattern. There should be one for each RegsToVisit.
3281e8d8bef9SDimitry Andric   SmallSetVector<const MachineInstr *, 8> Loads;
3282e8d8bef9SDimitry Andric 
3283e8d8bef9SDimitry Andric   // The lowest index used in any load. (The lowest "i" for each x[i].)
3284e8d8bef9SDimitry Andric   int64_t LowestIdx = INT64_MAX;
3285e8d8bef9SDimitry Andric 
3286e8d8bef9SDimitry Andric   // The load which uses the lowest index.
3287fe6060f1SDimitry Andric   GZExtLoad *LowestIdxLoad = nullptr;
3288e8d8bef9SDimitry Andric 
3289e8d8bef9SDimitry Andric   // Keeps track of the load indices we see. We shouldn't see any indices twice.
3290e8d8bef9SDimitry Andric   SmallSet<int64_t, 8> SeenIdx;
3291e8d8bef9SDimitry Andric 
3292e8d8bef9SDimitry Andric   // Ensure each load is in the same MBB.
3293e8d8bef9SDimitry Andric   // TODO: Support multiple MachineBasicBlocks.
3294e8d8bef9SDimitry Andric   MachineBasicBlock *MBB = nullptr;
3295e8d8bef9SDimitry Andric   const MachineMemOperand *MMO = nullptr;
3296e8d8bef9SDimitry Andric 
3297e8d8bef9SDimitry Andric   // Earliest instruction-order load in the pattern.
3298fe6060f1SDimitry Andric   GZExtLoad *EarliestLoad = nullptr;
3299e8d8bef9SDimitry Andric 
3300e8d8bef9SDimitry Andric   // Latest instruction-order load in the pattern.
3301fe6060f1SDimitry Andric   GZExtLoad *LatestLoad = nullptr;
3302e8d8bef9SDimitry Andric 
3303e8d8bef9SDimitry Andric   // Base pointer which every load should share.
3304e8d8bef9SDimitry Andric   Register BasePtr;
3305e8d8bef9SDimitry Andric 
3306e8d8bef9SDimitry Andric   // We want to find a load for each register. Each load should have some
3307e8d8bef9SDimitry Andric   // appropriate bit twiddling arithmetic. During this loop, we will also keep
3308e8d8bef9SDimitry Andric   // track of the load which uses the lowest index. Later, we will check if we
3309e8d8bef9SDimitry Andric   // can use its pointer in the final, combined load.
3310e8d8bef9SDimitry Andric   for (auto Reg : RegsToVisit) {
3311e8d8bef9SDimitry Andric     // Find the load, and find the position that it will end up in (e.g. a
3312e8d8bef9SDimitry Andric     // shifted) value.
3313e8d8bef9SDimitry Andric     auto LoadAndPos = matchLoadAndBytePosition(Reg, MemSizeInBits, MRI);
3314e8d8bef9SDimitry Andric     if (!LoadAndPos)
3315e8d8bef9SDimitry Andric       return None;
3316fe6060f1SDimitry Andric     GZExtLoad *Load;
3317e8d8bef9SDimitry Andric     int64_t DstPos;
3318e8d8bef9SDimitry Andric     std::tie(Load, DstPos) = *LoadAndPos;
3319e8d8bef9SDimitry Andric 
3320e8d8bef9SDimitry Andric     // TODO: Handle multiple MachineBasicBlocks. Currently not handled because
3321e8d8bef9SDimitry Andric     // it is difficult to check for stores/calls/etc between loads.
3322e8d8bef9SDimitry Andric     MachineBasicBlock *LoadMBB = Load->getParent();
3323e8d8bef9SDimitry Andric     if (!MBB)
3324e8d8bef9SDimitry Andric       MBB = LoadMBB;
3325e8d8bef9SDimitry Andric     if (LoadMBB != MBB)
3326e8d8bef9SDimitry Andric       return None;
3327e8d8bef9SDimitry Andric 
3328e8d8bef9SDimitry Andric     // Make sure that the MachineMemOperands of every seen load are compatible.
3329fe6060f1SDimitry Andric     auto &LoadMMO = Load->getMMO();
3330e8d8bef9SDimitry Andric     if (!MMO)
3331fe6060f1SDimitry Andric       MMO = &LoadMMO;
3332fe6060f1SDimitry Andric     if (MMO->getAddrSpace() != LoadMMO.getAddrSpace())
3333e8d8bef9SDimitry Andric       return None;
3334e8d8bef9SDimitry Andric 
3335e8d8bef9SDimitry Andric     // Find out what the base pointer and index for the load is.
3336e8d8bef9SDimitry Andric     Register LoadPtr;
3337e8d8bef9SDimitry Andric     int64_t Idx;
3338e8d8bef9SDimitry Andric     if (!mi_match(Load->getOperand(1).getReg(), MRI,
3339e8d8bef9SDimitry Andric                   m_GPtrAdd(m_Reg(LoadPtr), m_ICst(Idx)))) {
3340e8d8bef9SDimitry Andric       LoadPtr = Load->getOperand(1).getReg();
3341e8d8bef9SDimitry Andric       Idx = 0;
3342e8d8bef9SDimitry Andric     }
3343e8d8bef9SDimitry Andric 
3344e8d8bef9SDimitry Andric     // Don't combine things like a[i], a[i] -> a bigger load.
3345e8d8bef9SDimitry Andric     if (!SeenIdx.insert(Idx).second)
3346e8d8bef9SDimitry Andric       return None;
3347e8d8bef9SDimitry Andric 
3348e8d8bef9SDimitry Andric     // Every load must share the same base pointer; don't combine things like:
3349e8d8bef9SDimitry Andric     //
3350e8d8bef9SDimitry Andric     // a[i], b[i + 1] -> a bigger load.
3351e8d8bef9SDimitry Andric     if (!BasePtr.isValid())
3352e8d8bef9SDimitry Andric       BasePtr = LoadPtr;
3353e8d8bef9SDimitry Andric     if (BasePtr != LoadPtr)
3354e8d8bef9SDimitry Andric       return None;
3355e8d8bef9SDimitry Andric 
3356e8d8bef9SDimitry Andric     if (Idx < LowestIdx) {
3357e8d8bef9SDimitry Andric       LowestIdx = Idx;
3358e8d8bef9SDimitry Andric       LowestIdxLoad = Load;
3359e8d8bef9SDimitry Andric     }
3360e8d8bef9SDimitry Andric 
3361e8d8bef9SDimitry Andric     // Keep track of the byte offset that this load ends up at. If we have seen
3362e8d8bef9SDimitry Andric     // the byte offset, then stop here. We do not want to combine:
3363e8d8bef9SDimitry Andric     //
3364e8d8bef9SDimitry Andric     // a[i] << 16, a[i + k] << 16 -> a bigger load.
3365e8d8bef9SDimitry Andric     if (!MemOffset2Idx.try_emplace(DstPos, Idx).second)
3366e8d8bef9SDimitry Andric       return None;
3367e8d8bef9SDimitry Andric     Loads.insert(Load);
3368e8d8bef9SDimitry Andric 
3369e8d8bef9SDimitry Andric     // Keep track of the position of the earliest/latest loads in the pattern.
3370e8d8bef9SDimitry Andric     // We will check that there are no load fold barriers between them later
3371e8d8bef9SDimitry Andric     // on.
3372e8d8bef9SDimitry Andric     //
3373e8d8bef9SDimitry Andric     // FIXME: Is there a better way to check for load fold barriers?
3374e8d8bef9SDimitry Andric     if (!EarliestLoad || dominates(*Load, *EarliestLoad))
3375e8d8bef9SDimitry Andric       EarliestLoad = Load;
3376e8d8bef9SDimitry Andric     if (!LatestLoad || dominates(*LatestLoad, *Load))
3377e8d8bef9SDimitry Andric       LatestLoad = Load;
3378e8d8bef9SDimitry Andric   }
3379e8d8bef9SDimitry Andric 
3380e8d8bef9SDimitry Andric   // We found a load for each register. Let's check if each load satisfies the
3381e8d8bef9SDimitry Andric   // pattern.
3382e8d8bef9SDimitry Andric   assert(Loads.size() == RegsToVisit.size() &&
3383e8d8bef9SDimitry Andric          "Expected to find a load for each register?");
3384e8d8bef9SDimitry Andric   assert(EarliestLoad != LatestLoad && EarliestLoad &&
3385e8d8bef9SDimitry Andric          LatestLoad && "Expected at least two loads?");
3386e8d8bef9SDimitry Andric 
3387e8d8bef9SDimitry Andric   // Check if there are any stores, calls, etc. between any of the loads. If
3388e8d8bef9SDimitry Andric   // there are, then we can't safely perform the combine.
3389e8d8bef9SDimitry Andric   //
3390e8d8bef9SDimitry Andric   // MaxIter is chosen based off the (worst case) number of iterations it
3391e8d8bef9SDimitry Andric   // typically takes to succeed in the LLVM test suite plus some padding.
3392e8d8bef9SDimitry Andric   //
3393e8d8bef9SDimitry Andric   // FIXME: Is there a better way to check for load fold barriers?
3394e8d8bef9SDimitry Andric   const unsigned MaxIter = 20;
3395e8d8bef9SDimitry Andric   unsigned Iter = 0;
3396e8d8bef9SDimitry Andric   for (const auto &MI : instructionsWithoutDebug(EarliestLoad->getIterator(),
3397e8d8bef9SDimitry Andric                                                  LatestLoad->getIterator())) {
3398e8d8bef9SDimitry Andric     if (Loads.count(&MI))
3399e8d8bef9SDimitry Andric       continue;
3400e8d8bef9SDimitry Andric     if (MI.isLoadFoldBarrier())
3401e8d8bef9SDimitry Andric       return None;
3402e8d8bef9SDimitry Andric     if (Iter++ == MaxIter)
3403e8d8bef9SDimitry Andric       return None;
3404e8d8bef9SDimitry Andric   }
3405e8d8bef9SDimitry Andric 
3406fe6060f1SDimitry Andric   return std::make_tuple(LowestIdxLoad, LowestIdx, LatestLoad);
3407e8d8bef9SDimitry Andric }
3408e8d8bef9SDimitry Andric 
3409e8d8bef9SDimitry Andric bool CombinerHelper::matchLoadOrCombine(
3410e8d8bef9SDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
3411e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_OR);
3412e8d8bef9SDimitry Andric   MachineFunction &MF = *MI.getMF();
3413e8d8bef9SDimitry Andric   // Assuming a little-endian target, transform:
3414e8d8bef9SDimitry Andric   //  s8 *a = ...
3415e8d8bef9SDimitry Andric   //  s32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
3416e8d8bef9SDimitry Andric   // =>
3417e8d8bef9SDimitry Andric   //  s32 val = *((i32)a)
3418e8d8bef9SDimitry Andric   //
3419e8d8bef9SDimitry Andric   //  s8 *a = ...
3420e8d8bef9SDimitry Andric   //  s32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
3421e8d8bef9SDimitry Andric   // =>
3422e8d8bef9SDimitry Andric   //  s32 val = BSWAP(*((s32)a))
3423e8d8bef9SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
3424e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(Dst);
3425e8d8bef9SDimitry Andric   if (Ty.isVector())
3426e8d8bef9SDimitry Andric     return false;
3427e8d8bef9SDimitry Andric 
3428e8d8bef9SDimitry Andric   // We need to combine at least two loads into this type. Since the smallest
3429e8d8bef9SDimitry Andric   // possible load is into a byte, we need at least a 16-bit wide type.
3430e8d8bef9SDimitry Andric   const unsigned WideMemSizeInBits = Ty.getSizeInBits();
3431e8d8bef9SDimitry Andric   if (WideMemSizeInBits < 16 || WideMemSizeInBits % 8 != 0)
3432e8d8bef9SDimitry Andric     return false;
3433e8d8bef9SDimitry Andric 
3434e8d8bef9SDimitry Andric   // Match a collection of non-OR instructions in the pattern.
3435e8d8bef9SDimitry Andric   auto RegsToVisit = findCandidatesForLoadOrCombine(&MI);
3436e8d8bef9SDimitry Andric   if (!RegsToVisit)
3437e8d8bef9SDimitry Andric     return false;
3438e8d8bef9SDimitry Andric 
3439e8d8bef9SDimitry Andric   // We have a collection of non-OR instructions. Figure out how wide each of
3440e8d8bef9SDimitry Andric   // the small loads should be based off of the number of potential loads we
3441e8d8bef9SDimitry Andric   // found.
3442e8d8bef9SDimitry Andric   const unsigned NarrowMemSizeInBits = WideMemSizeInBits / RegsToVisit->size();
3443e8d8bef9SDimitry Andric   if (NarrowMemSizeInBits % 8 != 0)
3444e8d8bef9SDimitry Andric     return false;
3445e8d8bef9SDimitry Andric 
3446e8d8bef9SDimitry Andric   // Check if each register feeding into each OR is a load from the same
3447e8d8bef9SDimitry Andric   // base pointer + some arithmetic.
3448e8d8bef9SDimitry Andric   //
3449e8d8bef9SDimitry Andric   // e.g. a[0], a[1] << 8, a[2] << 16, etc.
3450e8d8bef9SDimitry Andric   //
3451e8d8bef9SDimitry Andric   // Also verify that each of these ends up putting a[i] into the same memory
3452e8d8bef9SDimitry Andric   // offset as a load into a wide type would.
3453e8d8bef9SDimitry Andric   SmallDenseMap<int64_t, int64_t, 8> MemOffset2Idx;
3454fe6060f1SDimitry Andric   GZExtLoad *LowestIdxLoad, *LatestLoad;
3455e8d8bef9SDimitry Andric   int64_t LowestIdx;
3456e8d8bef9SDimitry Andric   auto MaybeLoadInfo = findLoadOffsetsForLoadOrCombine(
3457e8d8bef9SDimitry Andric       MemOffset2Idx, *RegsToVisit, NarrowMemSizeInBits);
3458e8d8bef9SDimitry Andric   if (!MaybeLoadInfo)
3459e8d8bef9SDimitry Andric     return false;
3460fe6060f1SDimitry Andric   std::tie(LowestIdxLoad, LowestIdx, LatestLoad) = *MaybeLoadInfo;
3461e8d8bef9SDimitry Andric 
3462e8d8bef9SDimitry Andric   // We have a bunch of loads being OR'd together. Using the addresses + offsets
3463e8d8bef9SDimitry Andric   // we found before, check if this corresponds to a big or little endian byte
3464e8d8bef9SDimitry Andric   // pattern. If it does, then we can represent it using a load + possibly a
3465e8d8bef9SDimitry Andric   // BSWAP.
3466e8d8bef9SDimitry Andric   bool IsBigEndianTarget = MF.getDataLayout().isBigEndian();
3467e8d8bef9SDimitry Andric   Optional<bool> IsBigEndian = isBigEndian(MemOffset2Idx, LowestIdx);
3468*81ad6265SDimitry Andric   if (!IsBigEndian)
3469e8d8bef9SDimitry Andric     return false;
3470e8d8bef9SDimitry Andric   bool NeedsBSwap = IsBigEndianTarget != *IsBigEndian;
3471e8d8bef9SDimitry Andric   if (NeedsBSwap && !isLegalOrBeforeLegalizer({TargetOpcode::G_BSWAP, {Ty}}))
3472e8d8bef9SDimitry Andric     return false;
3473e8d8bef9SDimitry Andric 
3474e8d8bef9SDimitry Andric   // Make sure that the load from the lowest index produces offset 0 in the
3475e8d8bef9SDimitry Andric   // final value.
3476e8d8bef9SDimitry Andric   //
3477e8d8bef9SDimitry Andric   // This ensures that we won't combine something like this:
3478e8d8bef9SDimitry Andric   //
3479e8d8bef9SDimitry Andric   // load x[i] -> byte 2
3480e8d8bef9SDimitry Andric   // load x[i+1] -> byte 0 ---> wide_load x[i]
3481e8d8bef9SDimitry Andric   // load x[i+2] -> byte 1
3482e8d8bef9SDimitry Andric   const unsigned NumLoadsInTy = WideMemSizeInBits / NarrowMemSizeInBits;
3483e8d8bef9SDimitry Andric   const unsigned ZeroByteOffset =
3484e8d8bef9SDimitry Andric       *IsBigEndian
3485e8d8bef9SDimitry Andric           ? bigEndianByteAt(NumLoadsInTy, 0)
3486e8d8bef9SDimitry Andric           : littleEndianByteAt(NumLoadsInTy, 0);
3487e8d8bef9SDimitry Andric   auto ZeroOffsetIdx = MemOffset2Idx.find(ZeroByteOffset);
3488e8d8bef9SDimitry Andric   if (ZeroOffsetIdx == MemOffset2Idx.end() ||
3489e8d8bef9SDimitry Andric       ZeroOffsetIdx->second != LowestIdx)
3490e8d8bef9SDimitry Andric     return false;
3491e8d8bef9SDimitry Andric 
3492e8d8bef9SDimitry Andric   // We wil reuse the pointer from the load which ends up at byte offset 0. It
3493e8d8bef9SDimitry Andric   // may not use index 0.
3494fe6060f1SDimitry Andric   Register Ptr = LowestIdxLoad->getPointerReg();
3495fe6060f1SDimitry Andric   const MachineMemOperand &MMO = LowestIdxLoad->getMMO();
3496349cc55cSDimitry Andric   LegalityQuery::MemDesc MMDesc(MMO);
3497fe6060f1SDimitry Andric   MMDesc.MemoryTy = Ty;
3498e8d8bef9SDimitry Andric   if (!isLegalOrBeforeLegalizer(
3499e8d8bef9SDimitry Andric           {TargetOpcode::G_LOAD, {Ty, MRI.getType(Ptr)}, {MMDesc}}))
3500e8d8bef9SDimitry Andric     return false;
3501e8d8bef9SDimitry Andric   auto PtrInfo = MMO.getPointerInfo();
3502e8d8bef9SDimitry Andric   auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, WideMemSizeInBits / 8);
3503e8d8bef9SDimitry Andric 
3504e8d8bef9SDimitry Andric   // Load must be allowed and fast on the target.
3505e8d8bef9SDimitry Andric   LLVMContext &C = MF.getFunction().getContext();
3506e8d8bef9SDimitry Andric   auto &DL = MF.getDataLayout();
3507e8d8bef9SDimitry Andric   bool Fast = false;
3508e8d8bef9SDimitry Andric   if (!getTargetLowering().allowsMemoryAccess(C, DL, Ty, *NewMMO, &Fast) ||
3509e8d8bef9SDimitry Andric       !Fast)
3510e8d8bef9SDimitry Andric     return false;
3511e8d8bef9SDimitry Andric 
3512e8d8bef9SDimitry Andric   MatchInfo = [=](MachineIRBuilder &MIB) {
3513fe6060f1SDimitry Andric     MIB.setInstrAndDebugLoc(*LatestLoad);
3514e8d8bef9SDimitry Andric     Register LoadDst = NeedsBSwap ? MRI.cloneVirtualRegister(Dst) : Dst;
3515e8d8bef9SDimitry Andric     MIB.buildLoad(LoadDst, Ptr, *NewMMO);
3516e8d8bef9SDimitry Andric     if (NeedsBSwap)
3517e8d8bef9SDimitry Andric       MIB.buildBSwap(Dst, LoadDst);
3518e8d8bef9SDimitry Andric   };
3519e8d8bef9SDimitry Andric   return true;
3520e8d8bef9SDimitry Andric }
3521e8d8bef9SDimitry Andric 
3522349cc55cSDimitry Andric /// Check if the store \p Store is a truncstore that can be merged. That is,
3523349cc55cSDimitry Andric /// it's a store of a shifted value of \p SrcVal. If \p SrcVal is an empty
3524349cc55cSDimitry Andric /// Register then it does not need to match and SrcVal is set to the source
3525349cc55cSDimitry Andric /// value found.
3526349cc55cSDimitry Andric /// On match, returns the start byte offset of the \p SrcVal that is being
3527349cc55cSDimitry Andric /// stored.
3528349cc55cSDimitry Andric static Optional<int64_t> getTruncStoreByteOffset(GStore &Store, Register &SrcVal,
3529349cc55cSDimitry Andric                                                  MachineRegisterInfo &MRI) {
3530349cc55cSDimitry Andric   Register TruncVal;
3531349cc55cSDimitry Andric   if (!mi_match(Store.getValueReg(), MRI, m_GTrunc(m_Reg(TruncVal))))
3532349cc55cSDimitry Andric     return None;
3533349cc55cSDimitry Andric 
3534349cc55cSDimitry Andric   // The shift amount must be a constant multiple of the narrow type.
3535349cc55cSDimitry Andric   // It is translated to the offset address in the wide source value "y".
3536349cc55cSDimitry Andric   //
3537349cc55cSDimitry Andric   // x = G_LSHR y, ShiftAmtC
3538349cc55cSDimitry Andric   // s8 z = G_TRUNC x
3539349cc55cSDimitry Andric   // store z, ...
3540349cc55cSDimitry Andric   Register FoundSrcVal;
3541349cc55cSDimitry Andric   int64_t ShiftAmt;
3542349cc55cSDimitry Andric   if (!mi_match(TruncVal, MRI,
3543349cc55cSDimitry Andric                 m_any_of(m_GLShr(m_Reg(FoundSrcVal), m_ICst(ShiftAmt)),
3544349cc55cSDimitry Andric                          m_GAShr(m_Reg(FoundSrcVal), m_ICst(ShiftAmt))))) {
3545349cc55cSDimitry Andric     if (!SrcVal.isValid() || TruncVal == SrcVal) {
3546349cc55cSDimitry Andric       if (!SrcVal.isValid())
3547349cc55cSDimitry Andric         SrcVal = TruncVal;
3548349cc55cSDimitry Andric       return 0; // If it's the lowest index store.
3549349cc55cSDimitry Andric     }
3550349cc55cSDimitry Andric     return None;
3551349cc55cSDimitry Andric   }
3552349cc55cSDimitry Andric 
3553349cc55cSDimitry Andric   unsigned NarrowBits = Store.getMMO().getMemoryType().getScalarSizeInBits();
3554349cc55cSDimitry Andric   if (ShiftAmt % NarrowBits!= 0)
3555349cc55cSDimitry Andric     return None;
3556349cc55cSDimitry Andric   const unsigned Offset = ShiftAmt / NarrowBits;
3557349cc55cSDimitry Andric 
3558349cc55cSDimitry Andric   if (SrcVal.isValid() && FoundSrcVal != SrcVal)
3559349cc55cSDimitry Andric     return None;
3560349cc55cSDimitry Andric 
3561349cc55cSDimitry Andric   if (!SrcVal.isValid())
3562349cc55cSDimitry Andric     SrcVal = FoundSrcVal;
3563349cc55cSDimitry Andric   else if (MRI.getType(SrcVal) != MRI.getType(FoundSrcVal))
3564349cc55cSDimitry Andric     return None;
3565349cc55cSDimitry Andric   return Offset;
3566349cc55cSDimitry Andric }
3567349cc55cSDimitry Andric 
3568349cc55cSDimitry Andric /// Match a pattern where a wide type scalar value is stored by several narrow
3569349cc55cSDimitry Andric /// stores. Fold it into a single store or a BSWAP and a store if the targets
3570349cc55cSDimitry Andric /// supports it.
3571349cc55cSDimitry Andric ///
3572349cc55cSDimitry Andric /// Assuming little endian target:
3573349cc55cSDimitry Andric ///  i8 *p = ...
3574349cc55cSDimitry Andric ///  i32 val = ...
3575349cc55cSDimitry Andric ///  p[0] = (val >> 0) & 0xFF;
3576349cc55cSDimitry Andric ///  p[1] = (val >> 8) & 0xFF;
3577349cc55cSDimitry Andric ///  p[2] = (val >> 16) & 0xFF;
3578349cc55cSDimitry Andric ///  p[3] = (val >> 24) & 0xFF;
3579349cc55cSDimitry Andric /// =>
3580349cc55cSDimitry Andric ///  *((i32)p) = val;
3581349cc55cSDimitry Andric ///
3582349cc55cSDimitry Andric ///  i8 *p = ...
3583349cc55cSDimitry Andric ///  i32 val = ...
3584349cc55cSDimitry Andric ///  p[0] = (val >> 24) & 0xFF;
3585349cc55cSDimitry Andric ///  p[1] = (val >> 16) & 0xFF;
3586349cc55cSDimitry Andric ///  p[2] = (val >> 8) & 0xFF;
3587349cc55cSDimitry Andric ///  p[3] = (val >> 0) & 0xFF;
3588349cc55cSDimitry Andric /// =>
3589349cc55cSDimitry Andric ///  *((i32)p) = BSWAP(val);
3590349cc55cSDimitry Andric bool CombinerHelper::matchTruncStoreMerge(MachineInstr &MI,
3591349cc55cSDimitry Andric                                           MergeTruncStoresInfo &MatchInfo) {
3592349cc55cSDimitry Andric   auto &StoreMI = cast<GStore>(MI);
3593349cc55cSDimitry Andric   LLT MemTy = StoreMI.getMMO().getMemoryType();
3594349cc55cSDimitry Andric 
3595349cc55cSDimitry Andric   // We only handle merging simple stores of 1-4 bytes.
3596349cc55cSDimitry Andric   if (!MemTy.isScalar())
3597349cc55cSDimitry Andric     return false;
3598349cc55cSDimitry Andric   switch (MemTy.getSizeInBits()) {
3599349cc55cSDimitry Andric   case 8:
3600349cc55cSDimitry Andric   case 16:
3601349cc55cSDimitry Andric   case 32:
3602349cc55cSDimitry Andric     break;
3603349cc55cSDimitry Andric   default:
3604349cc55cSDimitry Andric     return false;
3605349cc55cSDimitry Andric   }
3606349cc55cSDimitry Andric   if (!StoreMI.isSimple())
3607349cc55cSDimitry Andric     return false;
3608349cc55cSDimitry Andric 
3609349cc55cSDimitry Andric   // We do a simple search for mergeable stores prior to this one.
3610349cc55cSDimitry Andric   // Any potential alias hazard along the way terminates the search.
3611349cc55cSDimitry Andric   SmallVector<GStore *> FoundStores;
3612349cc55cSDimitry Andric 
3613349cc55cSDimitry Andric   // We're looking for:
3614349cc55cSDimitry Andric   // 1) a (store(trunc(...)))
3615349cc55cSDimitry Andric   // 2) of an LSHR/ASHR of a single wide value, by the appropriate shift to get
3616349cc55cSDimitry Andric   //    the partial value stored.
3617349cc55cSDimitry Andric   // 3) where the offsets form either a little or big-endian sequence.
3618349cc55cSDimitry Andric 
3619349cc55cSDimitry Andric   auto &LastStore = StoreMI;
3620349cc55cSDimitry Andric 
3621349cc55cSDimitry Andric   // The single base pointer that all stores must use.
3622349cc55cSDimitry Andric   Register BaseReg;
3623349cc55cSDimitry Andric   int64_t LastOffset;
3624349cc55cSDimitry Andric   if (!mi_match(LastStore.getPointerReg(), MRI,
3625349cc55cSDimitry Andric                 m_GPtrAdd(m_Reg(BaseReg), m_ICst(LastOffset)))) {
3626349cc55cSDimitry Andric     BaseReg = LastStore.getPointerReg();
3627349cc55cSDimitry Andric     LastOffset = 0;
3628349cc55cSDimitry Andric   }
3629349cc55cSDimitry Andric 
3630349cc55cSDimitry Andric   GStore *LowestIdxStore = &LastStore;
3631349cc55cSDimitry Andric   int64_t LowestIdxOffset = LastOffset;
3632349cc55cSDimitry Andric 
3633349cc55cSDimitry Andric   Register WideSrcVal;
3634349cc55cSDimitry Andric   auto LowestShiftAmt = getTruncStoreByteOffset(LastStore, WideSrcVal, MRI);
3635349cc55cSDimitry Andric   if (!LowestShiftAmt)
3636349cc55cSDimitry Andric     return false; // Didn't match a trunc.
3637349cc55cSDimitry Andric   assert(WideSrcVal.isValid());
3638349cc55cSDimitry Andric 
3639349cc55cSDimitry Andric   LLT WideStoreTy = MRI.getType(WideSrcVal);
3640349cc55cSDimitry Andric   // The wide type might not be a multiple of the memory type, e.g. s48 and s32.
3641349cc55cSDimitry Andric   if (WideStoreTy.getSizeInBits() % MemTy.getSizeInBits() != 0)
3642349cc55cSDimitry Andric     return false;
3643349cc55cSDimitry Andric   const unsigned NumStoresRequired =
3644349cc55cSDimitry Andric       WideStoreTy.getSizeInBits() / MemTy.getSizeInBits();
3645349cc55cSDimitry Andric 
3646349cc55cSDimitry Andric   SmallVector<int64_t, 8> OffsetMap(NumStoresRequired, INT64_MAX);
3647349cc55cSDimitry Andric   OffsetMap[*LowestShiftAmt] = LastOffset;
3648349cc55cSDimitry Andric   FoundStores.emplace_back(&LastStore);
3649349cc55cSDimitry Andric 
3650349cc55cSDimitry Andric   // Search the block up for more stores.
3651349cc55cSDimitry Andric   // We use a search threshold of 10 instructions here because the combiner
3652349cc55cSDimitry Andric   // works top-down within a block, and we don't want to search an unbounded
3653349cc55cSDimitry Andric   // number of predecessor instructions trying to find matching stores.
3654349cc55cSDimitry Andric   // If we moved this optimization into a separate pass then we could probably
3655349cc55cSDimitry Andric   // use a more efficient search without having a hard-coded threshold.
3656349cc55cSDimitry Andric   const int MaxInstsToCheck = 10;
3657349cc55cSDimitry Andric   int NumInstsChecked = 0;
3658349cc55cSDimitry Andric   for (auto II = ++LastStore.getReverseIterator();
3659349cc55cSDimitry Andric        II != LastStore.getParent()->rend() && NumInstsChecked < MaxInstsToCheck;
3660349cc55cSDimitry Andric        ++II) {
3661349cc55cSDimitry Andric     NumInstsChecked++;
3662349cc55cSDimitry Andric     GStore *NewStore;
3663349cc55cSDimitry Andric     if ((NewStore = dyn_cast<GStore>(&*II))) {
3664349cc55cSDimitry Andric       if (NewStore->getMMO().getMemoryType() != MemTy || !NewStore->isSimple())
3665349cc55cSDimitry Andric         break;
3666349cc55cSDimitry Andric     } else if (II->isLoadFoldBarrier() || II->mayLoad()) {
3667349cc55cSDimitry Andric       break;
3668349cc55cSDimitry Andric     } else {
3669349cc55cSDimitry Andric       continue; // This is a safe instruction we can look past.
3670349cc55cSDimitry Andric     }
3671349cc55cSDimitry Andric 
3672349cc55cSDimitry Andric     Register NewBaseReg;
3673349cc55cSDimitry Andric     int64_t MemOffset;
3674349cc55cSDimitry Andric     // Check we're storing to the same base + some offset.
3675349cc55cSDimitry Andric     if (!mi_match(NewStore->getPointerReg(), MRI,
3676349cc55cSDimitry Andric                   m_GPtrAdd(m_Reg(NewBaseReg), m_ICst(MemOffset)))) {
3677349cc55cSDimitry Andric       NewBaseReg = NewStore->getPointerReg();
3678349cc55cSDimitry Andric       MemOffset = 0;
3679349cc55cSDimitry Andric     }
3680349cc55cSDimitry Andric     if (BaseReg != NewBaseReg)
3681349cc55cSDimitry Andric       break;
3682349cc55cSDimitry Andric 
3683349cc55cSDimitry Andric     auto ShiftByteOffset = getTruncStoreByteOffset(*NewStore, WideSrcVal, MRI);
3684349cc55cSDimitry Andric     if (!ShiftByteOffset)
3685349cc55cSDimitry Andric       break;
3686349cc55cSDimitry Andric     if (MemOffset < LowestIdxOffset) {
3687349cc55cSDimitry Andric       LowestIdxOffset = MemOffset;
3688349cc55cSDimitry Andric       LowestIdxStore = NewStore;
3689349cc55cSDimitry Andric     }
3690349cc55cSDimitry Andric 
3691349cc55cSDimitry Andric     // Map the offset in the store and the offset in the combined value, and
3692349cc55cSDimitry Andric     // early return if it has been set before.
3693349cc55cSDimitry Andric     if (*ShiftByteOffset < 0 || *ShiftByteOffset >= NumStoresRequired ||
3694349cc55cSDimitry Andric         OffsetMap[*ShiftByteOffset] != INT64_MAX)
3695349cc55cSDimitry Andric       break;
3696349cc55cSDimitry Andric     OffsetMap[*ShiftByteOffset] = MemOffset;
3697349cc55cSDimitry Andric 
3698349cc55cSDimitry Andric     FoundStores.emplace_back(NewStore);
3699349cc55cSDimitry Andric     // Reset counter since we've found a matching inst.
3700349cc55cSDimitry Andric     NumInstsChecked = 0;
3701349cc55cSDimitry Andric     if (FoundStores.size() == NumStoresRequired)
3702349cc55cSDimitry Andric       break;
3703349cc55cSDimitry Andric   }
3704349cc55cSDimitry Andric 
3705349cc55cSDimitry Andric   if (FoundStores.size() != NumStoresRequired) {
3706349cc55cSDimitry Andric     return false;
3707349cc55cSDimitry Andric   }
3708349cc55cSDimitry Andric 
3709349cc55cSDimitry Andric   const auto &DL = LastStore.getMF()->getDataLayout();
3710349cc55cSDimitry Andric   auto &C = LastStore.getMF()->getFunction().getContext();
3711349cc55cSDimitry Andric   // Check that a store of the wide type is both allowed and fast on the target
3712349cc55cSDimitry Andric   bool Fast = false;
3713349cc55cSDimitry Andric   bool Allowed = getTargetLowering().allowsMemoryAccess(
3714349cc55cSDimitry Andric       C, DL, WideStoreTy, LowestIdxStore->getMMO(), &Fast);
3715349cc55cSDimitry Andric   if (!Allowed || !Fast)
3716349cc55cSDimitry Andric     return false;
3717349cc55cSDimitry Andric 
3718349cc55cSDimitry Andric   // Check if the pieces of the value are going to the expected places in memory
3719349cc55cSDimitry Andric   // to merge the stores.
3720349cc55cSDimitry Andric   unsigned NarrowBits = MemTy.getScalarSizeInBits();
3721349cc55cSDimitry Andric   auto checkOffsets = [&](bool MatchLittleEndian) {
3722349cc55cSDimitry Andric     if (MatchLittleEndian) {
3723349cc55cSDimitry Andric       for (unsigned i = 0; i != NumStoresRequired; ++i)
3724349cc55cSDimitry Andric         if (OffsetMap[i] != i * (NarrowBits / 8) + LowestIdxOffset)
3725349cc55cSDimitry Andric           return false;
3726349cc55cSDimitry Andric     } else { // MatchBigEndian by reversing loop counter.
3727349cc55cSDimitry Andric       for (unsigned i = 0, j = NumStoresRequired - 1; i != NumStoresRequired;
3728349cc55cSDimitry Andric            ++i, --j)
3729349cc55cSDimitry Andric         if (OffsetMap[j] != i * (NarrowBits / 8) + LowestIdxOffset)
3730349cc55cSDimitry Andric           return false;
3731349cc55cSDimitry Andric     }
3732349cc55cSDimitry Andric     return true;
3733349cc55cSDimitry Andric   };
3734349cc55cSDimitry Andric 
3735349cc55cSDimitry Andric   // Check if the offsets line up for the native data layout of this target.
3736349cc55cSDimitry Andric   bool NeedBswap = false;
3737349cc55cSDimitry Andric   bool NeedRotate = false;
3738349cc55cSDimitry Andric   if (!checkOffsets(DL.isLittleEndian())) {
3739349cc55cSDimitry Andric     // Special-case: check if byte offsets line up for the opposite endian.
3740349cc55cSDimitry Andric     if (NarrowBits == 8 && checkOffsets(DL.isBigEndian()))
3741349cc55cSDimitry Andric       NeedBswap = true;
3742349cc55cSDimitry Andric     else if (NumStoresRequired == 2 && checkOffsets(DL.isBigEndian()))
3743349cc55cSDimitry Andric       NeedRotate = true;
3744349cc55cSDimitry Andric     else
3745349cc55cSDimitry Andric       return false;
3746349cc55cSDimitry Andric   }
3747349cc55cSDimitry Andric 
3748349cc55cSDimitry Andric   if (NeedBswap &&
3749349cc55cSDimitry Andric       !isLegalOrBeforeLegalizer({TargetOpcode::G_BSWAP, {WideStoreTy}}))
3750349cc55cSDimitry Andric     return false;
3751349cc55cSDimitry Andric   if (NeedRotate &&
3752349cc55cSDimitry Andric       !isLegalOrBeforeLegalizer({TargetOpcode::G_ROTR, {WideStoreTy}}))
3753349cc55cSDimitry Andric     return false;
3754349cc55cSDimitry Andric 
3755349cc55cSDimitry Andric   MatchInfo.NeedBSwap = NeedBswap;
3756349cc55cSDimitry Andric   MatchInfo.NeedRotate = NeedRotate;
3757349cc55cSDimitry Andric   MatchInfo.LowestIdxStore = LowestIdxStore;
3758349cc55cSDimitry Andric   MatchInfo.WideSrcVal = WideSrcVal;
3759349cc55cSDimitry Andric   MatchInfo.FoundStores = std::move(FoundStores);
3760349cc55cSDimitry Andric   return true;
3761349cc55cSDimitry Andric }
3762349cc55cSDimitry Andric 
3763349cc55cSDimitry Andric void CombinerHelper::applyTruncStoreMerge(MachineInstr &MI,
3764349cc55cSDimitry Andric                                           MergeTruncStoresInfo &MatchInfo) {
3765349cc55cSDimitry Andric 
3766349cc55cSDimitry Andric   Builder.setInstrAndDebugLoc(MI);
3767349cc55cSDimitry Andric   Register WideSrcVal = MatchInfo.WideSrcVal;
3768349cc55cSDimitry Andric   LLT WideStoreTy = MRI.getType(WideSrcVal);
3769349cc55cSDimitry Andric 
3770349cc55cSDimitry Andric   if (MatchInfo.NeedBSwap) {
3771349cc55cSDimitry Andric     WideSrcVal = Builder.buildBSwap(WideStoreTy, WideSrcVal).getReg(0);
3772349cc55cSDimitry Andric   } else if (MatchInfo.NeedRotate) {
3773349cc55cSDimitry Andric     assert(WideStoreTy.getSizeInBits() % 2 == 0 &&
3774349cc55cSDimitry Andric            "Unexpected type for rotate");
3775349cc55cSDimitry Andric     auto RotAmt =
3776349cc55cSDimitry Andric         Builder.buildConstant(WideStoreTy, WideStoreTy.getSizeInBits() / 2);
3777349cc55cSDimitry Andric     WideSrcVal =
3778349cc55cSDimitry Andric         Builder.buildRotateRight(WideStoreTy, WideSrcVal, RotAmt).getReg(0);
3779349cc55cSDimitry Andric   }
3780349cc55cSDimitry Andric 
3781349cc55cSDimitry Andric   Builder.buildStore(WideSrcVal, MatchInfo.LowestIdxStore->getPointerReg(),
3782349cc55cSDimitry Andric                      MatchInfo.LowestIdxStore->getMMO().getPointerInfo(),
3783349cc55cSDimitry Andric                      MatchInfo.LowestIdxStore->getMMO().getAlign());
3784349cc55cSDimitry Andric 
3785349cc55cSDimitry Andric   // Erase the old stores.
3786349cc55cSDimitry Andric   for (auto *ST : MatchInfo.FoundStores)
3787349cc55cSDimitry Andric     ST->eraseFromParent();
3788349cc55cSDimitry Andric }
3789349cc55cSDimitry Andric 
3790fe6060f1SDimitry Andric bool CombinerHelper::matchExtendThroughPhis(MachineInstr &MI,
3791fe6060f1SDimitry Andric                                             MachineInstr *&ExtMI) {
3792fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_PHI);
3793fe6060f1SDimitry Andric 
3794fe6060f1SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
3795fe6060f1SDimitry Andric 
3796fe6060f1SDimitry Andric   // TODO: Extending a vector may be expensive, don't do this until heuristics
3797fe6060f1SDimitry Andric   // are better.
3798fe6060f1SDimitry Andric   if (MRI.getType(DstReg).isVector())
3799fe6060f1SDimitry Andric     return false;
3800fe6060f1SDimitry Andric 
3801fe6060f1SDimitry Andric   // Try to match a phi, whose only use is an extend.
3802fe6060f1SDimitry Andric   if (!MRI.hasOneNonDBGUse(DstReg))
3803fe6060f1SDimitry Andric     return false;
3804fe6060f1SDimitry Andric   ExtMI = &*MRI.use_instr_nodbg_begin(DstReg);
3805fe6060f1SDimitry Andric   switch (ExtMI->getOpcode()) {
3806fe6060f1SDimitry Andric   case TargetOpcode::G_ANYEXT:
3807fe6060f1SDimitry Andric     return true; // G_ANYEXT is usually free.
3808fe6060f1SDimitry Andric   case TargetOpcode::G_ZEXT:
3809fe6060f1SDimitry Andric   case TargetOpcode::G_SEXT:
3810fe6060f1SDimitry Andric     break;
3811fe6060f1SDimitry Andric   default:
3812fe6060f1SDimitry Andric     return false;
3813fe6060f1SDimitry Andric   }
3814fe6060f1SDimitry Andric 
3815fe6060f1SDimitry Andric   // If the target is likely to fold this extend away, don't propagate.
3816fe6060f1SDimitry Andric   if (Builder.getTII().isExtendLikelyToBeFolded(*ExtMI, MRI))
3817fe6060f1SDimitry Andric     return false;
3818fe6060f1SDimitry Andric 
3819fe6060f1SDimitry Andric   // We don't want to propagate the extends unless there's a good chance that
3820fe6060f1SDimitry Andric   // they'll be optimized in some way.
3821fe6060f1SDimitry Andric   // Collect the unique incoming values.
3822fe6060f1SDimitry Andric   SmallPtrSet<MachineInstr *, 4> InSrcs;
3823fe6060f1SDimitry Andric   for (unsigned Idx = 1; Idx < MI.getNumOperands(); Idx += 2) {
3824fe6060f1SDimitry Andric     auto *DefMI = getDefIgnoringCopies(MI.getOperand(Idx).getReg(), MRI);
3825fe6060f1SDimitry Andric     switch (DefMI->getOpcode()) {
3826fe6060f1SDimitry Andric     case TargetOpcode::G_LOAD:
3827fe6060f1SDimitry Andric     case TargetOpcode::G_TRUNC:
3828fe6060f1SDimitry Andric     case TargetOpcode::G_SEXT:
3829fe6060f1SDimitry Andric     case TargetOpcode::G_ZEXT:
3830fe6060f1SDimitry Andric     case TargetOpcode::G_ANYEXT:
3831fe6060f1SDimitry Andric     case TargetOpcode::G_CONSTANT:
3832fe6060f1SDimitry Andric       InSrcs.insert(getDefIgnoringCopies(MI.getOperand(Idx).getReg(), MRI));
3833fe6060f1SDimitry Andric       // Don't try to propagate if there are too many places to create new
3834fe6060f1SDimitry Andric       // extends, chances are it'll increase code size.
3835fe6060f1SDimitry Andric       if (InSrcs.size() > 2)
3836fe6060f1SDimitry Andric         return false;
3837fe6060f1SDimitry Andric       break;
3838fe6060f1SDimitry Andric     default:
3839fe6060f1SDimitry Andric       return false;
3840fe6060f1SDimitry Andric     }
3841fe6060f1SDimitry Andric   }
3842fe6060f1SDimitry Andric   return true;
3843fe6060f1SDimitry Andric }
3844fe6060f1SDimitry Andric 
3845fe6060f1SDimitry Andric void CombinerHelper::applyExtendThroughPhis(MachineInstr &MI,
3846fe6060f1SDimitry Andric                                             MachineInstr *&ExtMI) {
3847fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_PHI);
3848fe6060f1SDimitry Andric   Register DstReg = ExtMI->getOperand(0).getReg();
3849fe6060f1SDimitry Andric   LLT ExtTy = MRI.getType(DstReg);
3850fe6060f1SDimitry Andric 
3851fe6060f1SDimitry Andric   // Propagate the extension into the block of each incoming reg's block.
3852fe6060f1SDimitry Andric   // Use a SetVector here because PHIs can have duplicate edges, and we want
3853fe6060f1SDimitry Andric   // deterministic iteration order.
3854fe6060f1SDimitry Andric   SmallSetVector<MachineInstr *, 8> SrcMIs;
3855fe6060f1SDimitry Andric   SmallDenseMap<MachineInstr *, MachineInstr *, 8> OldToNewSrcMap;
3856fe6060f1SDimitry Andric   for (unsigned SrcIdx = 1; SrcIdx < MI.getNumOperands(); SrcIdx += 2) {
3857fe6060f1SDimitry Andric     auto *SrcMI = MRI.getVRegDef(MI.getOperand(SrcIdx).getReg());
3858fe6060f1SDimitry Andric     if (!SrcMIs.insert(SrcMI))
3859fe6060f1SDimitry Andric       continue;
3860fe6060f1SDimitry Andric 
3861fe6060f1SDimitry Andric     // Build an extend after each src inst.
3862fe6060f1SDimitry Andric     auto *MBB = SrcMI->getParent();
3863fe6060f1SDimitry Andric     MachineBasicBlock::iterator InsertPt = ++SrcMI->getIterator();
3864fe6060f1SDimitry Andric     if (InsertPt != MBB->end() && InsertPt->isPHI())
3865fe6060f1SDimitry Andric       InsertPt = MBB->getFirstNonPHI();
3866fe6060f1SDimitry Andric 
3867fe6060f1SDimitry Andric     Builder.setInsertPt(*SrcMI->getParent(), InsertPt);
3868fe6060f1SDimitry Andric     Builder.setDebugLoc(MI.getDebugLoc());
3869fe6060f1SDimitry Andric     auto NewExt = Builder.buildExtOrTrunc(ExtMI->getOpcode(), ExtTy,
3870fe6060f1SDimitry Andric                                           SrcMI->getOperand(0).getReg());
3871fe6060f1SDimitry Andric     OldToNewSrcMap[SrcMI] = NewExt;
3872fe6060f1SDimitry Andric   }
3873fe6060f1SDimitry Andric 
3874fe6060f1SDimitry Andric   // Create a new phi with the extended inputs.
3875fe6060f1SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
3876fe6060f1SDimitry Andric   auto NewPhi = Builder.buildInstrNoInsert(TargetOpcode::G_PHI);
3877fe6060f1SDimitry Andric   NewPhi.addDef(DstReg);
38784824e7fdSDimitry Andric   for (const MachineOperand &MO : llvm::drop_begin(MI.operands())) {
3879fe6060f1SDimitry Andric     if (!MO.isReg()) {
3880fe6060f1SDimitry Andric       NewPhi.addMBB(MO.getMBB());
3881fe6060f1SDimitry Andric       continue;
3882fe6060f1SDimitry Andric     }
3883fe6060f1SDimitry Andric     auto *NewSrc = OldToNewSrcMap[MRI.getVRegDef(MO.getReg())];
3884fe6060f1SDimitry Andric     NewPhi.addUse(NewSrc->getOperand(0).getReg());
3885fe6060f1SDimitry Andric   }
3886fe6060f1SDimitry Andric   Builder.insertInstr(NewPhi);
3887fe6060f1SDimitry Andric   ExtMI->eraseFromParent();
3888fe6060f1SDimitry Andric }
3889fe6060f1SDimitry Andric 
3890fe6060f1SDimitry Andric bool CombinerHelper::matchExtractVecEltBuildVec(MachineInstr &MI,
3891fe6060f1SDimitry Andric                                                 Register &Reg) {
3892fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT);
3893fe6060f1SDimitry Andric   // If we have a constant index, look for a G_BUILD_VECTOR source
3894fe6060f1SDimitry Andric   // and find the source register that the index maps to.
3895fe6060f1SDimitry Andric   Register SrcVec = MI.getOperand(1).getReg();
3896fe6060f1SDimitry Andric   LLT SrcTy = MRI.getType(SrcVec);
3897fe6060f1SDimitry Andric   if (!isLegalOrBeforeLegalizer(
3898fe6060f1SDimitry Andric           {TargetOpcode::G_BUILD_VECTOR, {SrcTy, SrcTy.getElementType()}}))
3899fe6060f1SDimitry Andric     return false;
3900fe6060f1SDimitry Andric 
3901349cc55cSDimitry Andric   auto Cst = getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
3902fe6060f1SDimitry Andric   if (!Cst || Cst->Value.getZExtValue() >= SrcTy.getNumElements())
3903fe6060f1SDimitry Andric     return false;
3904fe6060f1SDimitry Andric 
3905fe6060f1SDimitry Andric   unsigned VecIdx = Cst->Value.getZExtValue();
3906fe6060f1SDimitry Andric   MachineInstr *BuildVecMI =
3907fe6060f1SDimitry Andric       getOpcodeDef(TargetOpcode::G_BUILD_VECTOR, SrcVec, MRI);
3908fe6060f1SDimitry Andric   if (!BuildVecMI) {
3909fe6060f1SDimitry Andric     BuildVecMI = getOpcodeDef(TargetOpcode::G_BUILD_VECTOR_TRUNC, SrcVec, MRI);
3910fe6060f1SDimitry Andric     if (!BuildVecMI)
3911fe6060f1SDimitry Andric       return false;
3912fe6060f1SDimitry Andric     LLT ScalarTy = MRI.getType(BuildVecMI->getOperand(1).getReg());
3913fe6060f1SDimitry Andric     if (!isLegalOrBeforeLegalizer(
3914fe6060f1SDimitry Andric             {TargetOpcode::G_BUILD_VECTOR_TRUNC, {SrcTy, ScalarTy}}))
3915fe6060f1SDimitry Andric       return false;
3916fe6060f1SDimitry Andric   }
3917fe6060f1SDimitry Andric 
3918fe6060f1SDimitry Andric   EVT Ty(getMVTForLLT(SrcTy));
3919fe6060f1SDimitry Andric   if (!MRI.hasOneNonDBGUse(SrcVec) &&
3920fe6060f1SDimitry Andric       !getTargetLowering().aggressivelyPreferBuildVectorSources(Ty))
3921fe6060f1SDimitry Andric     return false;
3922fe6060f1SDimitry Andric 
3923fe6060f1SDimitry Andric   Reg = BuildVecMI->getOperand(VecIdx + 1).getReg();
3924fe6060f1SDimitry Andric   return true;
3925fe6060f1SDimitry Andric }
3926fe6060f1SDimitry Andric 
3927fe6060f1SDimitry Andric void CombinerHelper::applyExtractVecEltBuildVec(MachineInstr &MI,
3928fe6060f1SDimitry Andric                                                 Register &Reg) {
3929fe6060f1SDimitry Andric   // Check the type of the register, since it may have come from a
3930fe6060f1SDimitry Andric   // G_BUILD_VECTOR_TRUNC.
3931fe6060f1SDimitry Andric   LLT ScalarTy = MRI.getType(Reg);
3932fe6060f1SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
3933fe6060f1SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
3934fe6060f1SDimitry Andric 
3935fe6060f1SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
3936fe6060f1SDimitry Andric   if (ScalarTy != DstTy) {
3937fe6060f1SDimitry Andric     assert(ScalarTy.getSizeInBits() > DstTy.getSizeInBits());
3938fe6060f1SDimitry Andric     Builder.buildTrunc(DstReg, Reg);
3939fe6060f1SDimitry Andric     MI.eraseFromParent();
3940fe6060f1SDimitry Andric     return;
3941fe6060f1SDimitry Andric   }
3942fe6060f1SDimitry Andric   replaceSingleDefInstWithReg(MI, Reg);
3943fe6060f1SDimitry Andric }
3944fe6060f1SDimitry Andric 
3945fe6060f1SDimitry Andric bool CombinerHelper::matchExtractAllEltsFromBuildVector(
3946fe6060f1SDimitry Andric     MachineInstr &MI,
3947fe6060f1SDimitry Andric     SmallVectorImpl<std::pair<Register, MachineInstr *>> &SrcDstPairs) {
3948fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR);
3949fe6060f1SDimitry Andric   // This combine tries to find build_vector's which have every source element
3950fe6060f1SDimitry Andric   // extracted using G_EXTRACT_VECTOR_ELT. This can happen when transforms like
3951fe6060f1SDimitry Andric   // the masked load scalarization is run late in the pipeline. There's already
3952fe6060f1SDimitry Andric   // a combine for a similar pattern starting from the extract, but that
3953fe6060f1SDimitry Andric   // doesn't attempt to do it if there are multiple uses of the build_vector,
3954fe6060f1SDimitry Andric   // which in this case is true. Starting the combine from the build_vector
3955fe6060f1SDimitry Andric   // feels more natural than trying to find sibling nodes of extracts.
3956fe6060f1SDimitry Andric   // E.g.
3957fe6060f1SDimitry Andric   //  %vec(<4 x s32>) = G_BUILD_VECTOR %s1(s32), %s2, %s3, %s4
3958fe6060f1SDimitry Andric   //  %ext1 = G_EXTRACT_VECTOR_ELT %vec, 0
3959fe6060f1SDimitry Andric   //  %ext2 = G_EXTRACT_VECTOR_ELT %vec, 1
3960fe6060f1SDimitry Andric   //  %ext3 = G_EXTRACT_VECTOR_ELT %vec, 2
3961fe6060f1SDimitry Andric   //  %ext4 = G_EXTRACT_VECTOR_ELT %vec, 3
3962fe6060f1SDimitry Andric   // ==>
3963fe6060f1SDimitry Andric   // replace ext{1,2,3,4} with %s{1,2,3,4}
3964fe6060f1SDimitry Andric 
3965fe6060f1SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
3966fe6060f1SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
3967fe6060f1SDimitry Andric   unsigned NumElts = DstTy.getNumElements();
3968fe6060f1SDimitry Andric 
3969fe6060f1SDimitry Andric   SmallBitVector ExtractedElts(NumElts);
39704824e7fdSDimitry Andric   for (MachineInstr &II : MRI.use_nodbg_instructions(DstReg)) {
3971fe6060f1SDimitry Andric     if (II.getOpcode() != TargetOpcode::G_EXTRACT_VECTOR_ELT)
3972fe6060f1SDimitry Andric       return false;
3973349cc55cSDimitry Andric     auto Cst = getIConstantVRegVal(II.getOperand(2).getReg(), MRI);
3974fe6060f1SDimitry Andric     if (!Cst)
3975fe6060f1SDimitry Andric       return false;
3976*81ad6265SDimitry Andric     unsigned Idx = Cst->getZExtValue();
3977fe6060f1SDimitry Andric     if (Idx >= NumElts)
3978fe6060f1SDimitry Andric       return false; // Out of range.
3979fe6060f1SDimitry Andric     ExtractedElts.set(Idx);
3980fe6060f1SDimitry Andric     SrcDstPairs.emplace_back(
3981fe6060f1SDimitry Andric         std::make_pair(MI.getOperand(Idx + 1).getReg(), &II));
3982fe6060f1SDimitry Andric   }
3983fe6060f1SDimitry Andric   // Match if every element was extracted.
3984fe6060f1SDimitry Andric   return ExtractedElts.all();
3985fe6060f1SDimitry Andric }
3986fe6060f1SDimitry Andric 
3987fe6060f1SDimitry Andric void CombinerHelper::applyExtractAllEltsFromBuildVector(
3988fe6060f1SDimitry Andric     MachineInstr &MI,
3989fe6060f1SDimitry Andric     SmallVectorImpl<std::pair<Register, MachineInstr *>> &SrcDstPairs) {
3990fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR);
3991fe6060f1SDimitry Andric   for (auto &Pair : SrcDstPairs) {
3992fe6060f1SDimitry Andric     auto *ExtMI = Pair.second;
3993fe6060f1SDimitry Andric     replaceRegWith(MRI, ExtMI->getOperand(0).getReg(), Pair.first);
3994fe6060f1SDimitry Andric     ExtMI->eraseFromParent();
3995fe6060f1SDimitry Andric   }
3996fe6060f1SDimitry Andric   MI.eraseFromParent();
3997fe6060f1SDimitry Andric }
3998fe6060f1SDimitry Andric 
3999fe6060f1SDimitry Andric void CombinerHelper::applyBuildFn(
4000e8d8bef9SDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4001e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
4002e8d8bef9SDimitry Andric   MatchInfo(Builder);
4003e8d8bef9SDimitry Andric   MI.eraseFromParent();
4004fe6060f1SDimitry Andric }
4005fe6060f1SDimitry Andric 
4006fe6060f1SDimitry Andric void CombinerHelper::applyBuildFnNoErase(
4007fe6060f1SDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4008fe6060f1SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
4009fe6060f1SDimitry Andric   MatchInfo(Builder);
4010fe6060f1SDimitry Andric }
4011fe6060f1SDimitry Andric 
40124824e7fdSDimitry Andric bool CombinerHelper::matchOrShiftToFunnelShift(MachineInstr &MI,
40134824e7fdSDimitry Andric                                                BuildFnTy &MatchInfo) {
40144824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_OR);
40154824e7fdSDimitry Andric 
40164824e7fdSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
40174824e7fdSDimitry Andric   LLT Ty = MRI.getType(Dst);
40184824e7fdSDimitry Andric   unsigned BitWidth = Ty.getScalarSizeInBits();
40194824e7fdSDimitry Andric 
402004eeddc0SDimitry Andric   Register ShlSrc, ShlAmt, LShrSrc, LShrAmt, Amt;
40214824e7fdSDimitry Andric   unsigned FshOpc = 0;
40224824e7fdSDimitry Andric 
402304eeddc0SDimitry Andric   // Match (or (shl ...), (lshr ...)).
402404eeddc0SDimitry Andric   if (!mi_match(Dst, MRI,
40254824e7fdSDimitry Andric                 // m_GOr() handles the commuted version as well.
40264824e7fdSDimitry Andric                 m_GOr(m_GShl(m_Reg(ShlSrc), m_Reg(ShlAmt)),
402704eeddc0SDimitry Andric                       m_GLShr(m_Reg(LShrSrc), m_Reg(LShrAmt)))))
402804eeddc0SDimitry Andric     return false;
402904eeddc0SDimitry Andric 
403004eeddc0SDimitry Andric   // Given constants C0 and C1 such that C0 + C1 is bit-width:
403104eeddc0SDimitry Andric   // (or (shl x, C0), (lshr y, C1)) -> (fshl x, y, C0) or (fshr x, y, C1)
403204eeddc0SDimitry Andric   int64_t CstShlAmt, CstLShrAmt;
4033*81ad6265SDimitry Andric   if (mi_match(ShlAmt, MRI, m_ICstOrSplat(CstShlAmt)) &&
4034*81ad6265SDimitry Andric       mi_match(LShrAmt, MRI, m_ICstOrSplat(CstLShrAmt)) &&
403504eeddc0SDimitry Andric       CstShlAmt + CstLShrAmt == BitWidth) {
403604eeddc0SDimitry Andric     FshOpc = TargetOpcode::G_FSHR;
403704eeddc0SDimitry Andric     Amt = LShrAmt;
403804eeddc0SDimitry Andric 
403904eeddc0SDimitry Andric   } else if (mi_match(LShrAmt, MRI,
404004eeddc0SDimitry Andric                       m_GSub(m_SpecificICstOrSplat(BitWidth), m_Reg(Amt))) &&
404104eeddc0SDimitry Andric              ShlAmt == Amt) {
404204eeddc0SDimitry Andric     // (or (shl x, amt), (lshr y, (sub bw, amt))) -> (fshl x, y, amt)
40434824e7fdSDimitry Andric     FshOpc = TargetOpcode::G_FSHL;
40444824e7fdSDimitry Andric 
404504eeddc0SDimitry Andric   } else if (mi_match(ShlAmt, MRI,
404604eeddc0SDimitry Andric                       m_GSub(m_SpecificICstOrSplat(BitWidth), m_Reg(Amt))) &&
404704eeddc0SDimitry Andric              LShrAmt == Amt) {
404804eeddc0SDimitry Andric     // (or (shl x, (sub bw, amt)), (lshr y, amt)) -> (fshr x, y, amt)
40494824e7fdSDimitry Andric     FshOpc = TargetOpcode::G_FSHR;
40504824e7fdSDimitry Andric 
40514824e7fdSDimitry Andric   } else {
40524824e7fdSDimitry Andric     return false;
40534824e7fdSDimitry Andric   }
40544824e7fdSDimitry Andric 
405504eeddc0SDimitry Andric   LLT AmtTy = MRI.getType(Amt);
40564824e7fdSDimitry Andric   if (!isLegalOrBeforeLegalizer({FshOpc, {Ty, AmtTy}}))
40574824e7fdSDimitry Andric     return false;
40584824e7fdSDimitry Andric 
40594824e7fdSDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
406004eeddc0SDimitry Andric     B.buildInstr(FshOpc, {Dst}, {ShlSrc, LShrSrc, Amt});
40614824e7fdSDimitry Andric   };
40624824e7fdSDimitry Andric   return true;
40634824e7fdSDimitry Andric }
40644824e7fdSDimitry Andric 
4065fe6060f1SDimitry Andric /// Match an FSHL or FSHR that can be combined to a ROTR or ROTL rotate.
4066fe6060f1SDimitry Andric bool CombinerHelper::matchFunnelShiftToRotate(MachineInstr &MI) {
4067fe6060f1SDimitry Andric   unsigned Opc = MI.getOpcode();
4068fe6060f1SDimitry Andric   assert(Opc == TargetOpcode::G_FSHL || Opc == TargetOpcode::G_FSHR);
4069fe6060f1SDimitry Andric   Register X = MI.getOperand(1).getReg();
4070fe6060f1SDimitry Andric   Register Y = MI.getOperand(2).getReg();
4071fe6060f1SDimitry Andric   if (X != Y)
4072fe6060f1SDimitry Andric     return false;
4073fe6060f1SDimitry Andric   unsigned RotateOpc =
4074fe6060f1SDimitry Andric       Opc == TargetOpcode::G_FSHL ? TargetOpcode::G_ROTL : TargetOpcode::G_ROTR;
4075fe6060f1SDimitry Andric   return isLegalOrBeforeLegalizer({RotateOpc, {MRI.getType(X), MRI.getType(Y)}});
4076fe6060f1SDimitry Andric }
4077fe6060f1SDimitry Andric 
4078fe6060f1SDimitry Andric void CombinerHelper::applyFunnelShiftToRotate(MachineInstr &MI) {
4079fe6060f1SDimitry Andric   unsigned Opc = MI.getOpcode();
4080fe6060f1SDimitry Andric   assert(Opc == TargetOpcode::G_FSHL || Opc == TargetOpcode::G_FSHR);
4081fe6060f1SDimitry Andric   bool IsFSHL = Opc == TargetOpcode::G_FSHL;
4082fe6060f1SDimitry Andric   Observer.changingInstr(MI);
4083fe6060f1SDimitry Andric   MI.setDesc(Builder.getTII().get(IsFSHL ? TargetOpcode::G_ROTL
4084fe6060f1SDimitry Andric                                          : TargetOpcode::G_ROTR));
4085*81ad6265SDimitry Andric   MI.removeOperand(2);
4086fe6060f1SDimitry Andric   Observer.changedInstr(MI);
4087fe6060f1SDimitry Andric }
4088fe6060f1SDimitry Andric 
4089fe6060f1SDimitry Andric // Fold (rot x, c) -> (rot x, c % BitSize)
4090fe6060f1SDimitry Andric bool CombinerHelper::matchRotateOutOfRange(MachineInstr &MI) {
4091fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ROTL ||
4092fe6060f1SDimitry Andric          MI.getOpcode() == TargetOpcode::G_ROTR);
4093fe6060f1SDimitry Andric   unsigned Bitsize =
4094fe6060f1SDimitry Andric       MRI.getType(MI.getOperand(0).getReg()).getScalarSizeInBits();
4095fe6060f1SDimitry Andric   Register AmtReg = MI.getOperand(2).getReg();
4096fe6060f1SDimitry Andric   bool OutOfRange = false;
4097fe6060f1SDimitry Andric   auto MatchOutOfRange = [Bitsize, &OutOfRange](const Constant *C) {
4098fe6060f1SDimitry Andric     if (auto *CI = dyn_cast<ConstantInt>(C))
4099fe6060f1SDimitry Andric       OutOfRange |= CI->getValue().uge(Bitsize);
4100fe6060f1SDimitry Andric     return true;
4101fe6060f1SDimitry Andric   };
4102fe6060f1SDimitry Andric   return matchUnaryPredicate(MRI, AmtReg, MatchOutOfRange) && OutOfRange;
4103fe6060f1SDimitry Andric }
4104fe6060f1SDimitry Andric 
4105fe6060f1SDimitry Andric void CombinerHelper::applyRotateOutOfRange(MachineInstr &MI) {
4106fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ROTL ||
4107fe6060f1SDimitry Andric          MI.getOpcode() == TargetOpcode::G_ROTR);
4108fe6060f1SDimitry Andric   unsigned Bitsize =
4109fe6060f1SDimitry Andric       MRI.getType(MI.getOperand(0).getReg()).getScalarSizeInBits();
4110fe6060f1SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
4111fe6060f1SDimitry Andric   Register Amt = MI.getOperand(2).getReg();
4112fe6060f1SDimitry Andric   LLT AmtTy = MRI.getType(Amt);
4113fe6060f1SDimitry Andric   auto Bits = Builder.buildConstant(AmtTy, Bitsize);
4114fe6060f1SDimitry Andric   Amt = Builder.buildURem(AmtTy, MI.getOperand(2).getReg(), Bits).getReg(0);
4115fe6060f1SDimitry Andric   Observer.changingInstr(MI);
4116fe6060f1SDimitry Andric   MI.getOperand(2).setReg(Amt);
4117fe6060f1SDimitry Andric   Observer.changedInstr(MI);
4118fe6060f1SDimitry Andric }
4119fe6060f1SDimitry Andric 
4120fe6060f1SDimitry Andric bool CombinerHelper::matchICmpToTrueFalseKnownBits(MachineInstr &MI,
4121fe6060f1SDimitry Andric                                                    int64_t &MatchInfo) {
4122fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ICMP);
4123fe6060f1SDimitry Andric   auto Pred = static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
4124fe6060f1SDimitry Andric   auto KnownLHS = KB->getKnownBits(MI.getOperand(2).getReg());
4125fe6060f1SDimitry Andric   auto KnownRHS = KB->getKnownBits(MI.getOperand(3).getReg());
4126fe6060f1SDimitry Andric   Optional<bool> KnownVal;
4127fe6060f1SDimitry Andric   switch (Pred) {
4128fe6060f1SDimitry Andric   default:
4129fe6060f1SDimitry Andric     llvm_unreachable("Unexpected G_ICMP predicate?");
4130fe6060f1SDimitry Andric   case CmpInst::ICMP_EQ:
4131fe6060f1SDimitry Andric     KnownVal = KnownBits::eq(KnownLHS, KnownRHS);
4132fe6060f1SDimitry Andric     break;
4133fe6060f1SDimitry Andric   case CmpInst::ICMP_NE:
4134fe6060f1SDimitry Andric     KnownVal = KnownBits::ne(KnownLHS, KnownRHS);
4135fe6060f1SDimitry Andric     break;
4136fe6060f1SDimitry Andric   case CmpInst::ICMP_SGE:
4137fe6060f1SDimitry Andric     KnownVal = KnownBits::sge(KnownLHS, KnownRHS);
4138fe6060f1SDimitry Andric     break;
4139fe6060f1SDimitry Andric   case CmpInst::ICMP_SGT:
4140fe6060f1SDimitry Andric     KnownVal = KnownBits::sgt(KnownLHS, KnownRHS);
4141fe6060f1SDimitry Andric     break;
4142fe6060f1SDimitry Andric   case CmpInst::ICMP_SLE:
4143fe6060f1SDimitry Andric     KnownVal = KnownBits::sle(KnownLHS, KnownRHS);
4144fe6060f1SDimitry Andric     break;
4145fe6060f1SDimitry Andric   case CmpInst::ICMP_SLT:
4146fe6060f1SDimitry Andric     KnownVal = KnownBits::slt(KnownLHS, KnownRHS);
4147fe6060f1SDimitry Andric     break;
4148fe6060f1SDimitry Andric   case CmpInst::ICMP_UGE:
4149fe6060f1SDimitry Andric     KnownVal = KnownBits::uge(KnownLHS, KnownRHS);
4150fe6060f1SDimitry Andric     break;
4151fe6060f1SDimitry Andric   case CmpInst::ICMP_UGT:
4152fe6060f1SDimitry Andric     KnownVal = KnownBits::ugt(KnownLHS, KnownRHS);
4153fe6060f1SDimitry Andric     break;
4154fe6060f1SDimitry Andric   case CmpInst::ICMP_ULE:
4155fe6060f1SDimitry Andric     KnownVal = KnownBits::ule(KnownLHS, KnownRHS);
4156fe6060f1SDimitry Andric     break;
4157fe6060f1SDimitry Andric   case CmpInst::ICMP_ULT:
4158fe6060f1SDimitry Andric     KnownVal = KnownBits::ult(KnownLHS, KnownRHS);
4159fe6060f1SDimitry Andric     break;
4160fe6060f1SDimitry Andric   }
4161fe6060f1SDimitry Andric   if (!KnownVal)
4162fe6060f1SDimitry Andric     return false;
4163fe6060f1SDimitry Andric   MatchInfo =
4164fe6060f1SDimitry Andric       *KnownVal
4165fe6060f1SDimitry Andric           ? getICmpTrueVal(getTargetLowering(),
4166fe6060f1SDimitry Andric                            /*IsVector = */
4167fe6060f1SDimitry Andric                            MRI.getType(MI.getOperand(0).getReg()).isVector(),
4168fe6060f1SDimitry Andric                            /* IsFP = */ false)
4169fe6060f1SDimitry Andric           : 0;
4170fe6060f1SDimitry Andric   return true;
4171fe6060f1SDimitry Andric }
4172fe6060f1SDimitry Andric 
4173349cc55cSDimitry Andric bool CombinerHelper::matchICmpToLHSKnownBits(
4174349cc55cSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4175349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ICMP);
4176349cc55cSDimitry Andric   // Given:
4177349cc55cSDimitry Andric   //
4178349cc55cSDimitry Andric   // %x = G_WHATEVER (... x is known to be 0 or 1 ...)
4179349cc55cSDimitry Andric   // %cmp = G_ICMP ne %x, 0
4180349cc55cSDimitry Andric   //
4181349cc55cSDimitry Andric   // Or:
4182349cc55cSDimitry Andric   //
4183349cc55cSDimitry Andric   // %x = G_WHATEVER (... x is known to be 0 or 1 ...)
4184349cc55cSDimitry Andric   // %cmp = G_ICMP eq %x, 1
4185349cc55cSDimitry Andric   //
4186349cc55cSDimitry Andric   // We can replace %cmp with %x assuming true is 1 on the target.
4187349cc55cSDimitry Andric   auto Pred = static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
4188349cc55cSDimitry Andric   if (!CmpInst::isEquality(Pred))
4189349cc55cSDimitry Andric     return false;
4190349cc55cSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
4191349cc55cSDimitry Andric   LLT DstTy = MRI.getType(Dst);
4192349cc55cSDimitry Andric   if (getICmpTrueVal(getTargetLowering(), DstTy.isVector(),
4193349cc55cSDimitry Andric                      /* IsFP = */ false) != 1)
4194349cc55cSDimitry Andric     return false;
4195349cc55cSDimitry Andric   int64_t OneOrZero = Pred == CmpInst::ICMP_EQ;
4196349cc55cSDimitry Andric   if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICst(OneOrZero)))
4197349cc55cSDimitry Andric     return false;
4198349cc55cSDimitry Andric   Register LHS = MI.getOperand(2).getReg();
4199349cc55cSDimitry Andric   auto KnownLHS = KB->getKnownBits(LHS);
4200349cc55cSDimitry Andric   if (KnownLHS.getMinValue() != 0 || KnownLHS.getMaxValue() != 1)
4201349cc55cSDimitry Andric     return false;
4202349cc55cSDimitry Andric   // Make sure replacing Dst with the LHS is a legal operation.
4203349cc55cSDimitry Andric   LLT LHSTy = MRI.getType(LHS);
4204349cc55cSDimitry Andric   unsigned LHSSize = LHSTy.getSizeInBits();
4205349cc55cSDimitry Andric   unsigned DstSize = DstTy.getSizeInBits();
4206349cc55cSDimitry Andric   unsigned Op = TargetOpcode::COPY;
4207349cc55cSDimitry Andric   if (DstSize != LHSSize)
4208349cc55cSDimitry Andric     Op = DstSize < LHSSize ? TargetOpcode::G_TRUNC : TargetOpcode::G_ZEXT;
4209349cc55cSDimitry Andric   if (!isLegalOrBeforeLegalizer({Op, {DstTy, LHSTy}}))
4210349cc55cSDimitry Andric     return false;
4211349cc55cSDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) { B.buildInstr(Op, {Dst}, {LHS}); };
4212349cc55cSDimitry Andric   return true;
4213349cc55cSDimitry Andric }
4214349cc55cSDimitry Andric 
4215349cc55cSDimitry Andric // Replace (and (or x, c1), c2) with (and x, c2) iff c1 & c2 == 0
4216349cc55cSDimitry Andric bool CombinerHelper::matchAndOrDisjointMask(
4217349cc55cSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4218349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_AND);
4219349cc55cSDimitry Andric 
4220349cc55cSDimitry Andric   // Ignore vector types to simplify matching the two constants.
4221349cc55cSDimitry Andric   // TODO: do this for vectors and scalars via a demanded bits analysis.
4222349cc55cSDimitry Andric   LLT Ty = MRI.getType(MI.getOperand(0).getReg());
4223349cc55cSDimitry Andric   if (Ty.isVector())
4224349cc55cSDimitry Andric     return false;
4225349cc55cSDimitry Andric 
4226349cc55cSDimitry Andric   Register Src;
4227*81ad6265SDimitry Andric   Register AndMaskReg;
4228*81ad6265SDimitry Andric   int64_t AndMaskBits;
4229*81ad6265SDimitry Andric   int64_t OrMaskBits;
4230349cc55cSDimitry Andric   if (!mi_match(MI, MRI,
4231*81ad6265SDimitry Andric                 m_GAnd(m_GOr(m_Reg(Src), m_ICst(OrMaskBits)),
4232*81ad6265SDimitry Andric                        m_all_of(m_ICst(AndMaskBits), m_Reg(AndMaskReg)))))
4233349cc55cSDimitry Andric     return false;
4234349cc55cSDimitry Andric 
4235*81ad6265SDimitry Andric   // Check if OrMask could turn on any bits in Src.
4236*81ad6265SDimitry Andric   if (AndMaskBits & OrMaskBits)
4237349cc55cSDimitry Andric     return false;
4238349cc55cSDimitry Andric 
4239349cc55cSDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4240349cc55cSDimitry Andric     Observer.changingInstr(MI);
4241*81ad6265SDimitry Andric     // Canonicalize the result to have the constant on the RHS.
4242*81ad6265SDimitry Andric     if (MI.getOperand(1).getReg() == AndMaskReg)
4243*81ad6265SDimitry Andric       MI.getOperand(2).setReg(AndMaskReg);
4244349cc55cSDimitry Andric     MI.getOperand(1).setReg(Src);
4245349cc55cSDimitry Andric     Observer.changedInstr(MI);
4246349cc55cSDimitry Andric   };
4247349cc55cSDimitry Andric   return true;
4248349cc55cSDimitry Andric }
4249349cc55cSDimitry Andric 
4250fe6060f1SDimitry Andric /// Form a G_SBFX from a G_SEXT_INREG fed by a right shift.
4251fe6060f1SDimitry Andric bool CombinerHelper::matchBitfieldExtractFromSExtInReg(
4252fe6060f1SDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4253fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
4254fe6060f1SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
4255fe6060f1SDimitry Andric   Register Src = MI.getOperand(1).getReg();
4256fe6060f1SDimitry Andric   LLT Ty = MRI.getType(Src);
4257fe6060f1SDimitry Andric   LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4258fe6060f1SDimitry Andric   if (!LI || !LI->isLegalOrCustom({TargetOpcode::G_SBFX, {Ty, ExtractTy}}))
4259fe6060f1SDimitry Andric     return false;
4260fe6060f1SDimitry Andric   int64_t Width = MI.getOperand(2).getImm();
4261fe6060f1SDimitry Andric   Register ShiftSrc;
4262fe6060f1SDimitry Andric   int64_t ShiftImm;
4263fe6060f1SDimitry Andric   if (!mi_match(
4264fe6060f1SDimitry Andric           Src, MRI,
4265fe6060f1SDimitry Andric           m_OneNonDBGUse(m_any_of(m_GAShr(m_Reg(ShiftSrc), m_ICst(ShiftImm)),
4266fe6060f1SDimitry Andric                                   m_GLShr(m_Reg(ShiftSrc), m_ICst(ShiftImm))))))
4267fe6060f1SDimitry Andric     return false;
4268fe6060f1SDimitry Andric   if (ShiftImm < 0 || ShiftImm + Width > Ty.getScalarSizeInBits())
4269fe6060f1SDimitry Andric     return false;
4270fe6060f1SDimitry Andric 
4271fe6060f1SDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
4272fe6060f1SDimitry Andric     auto Cst1 = B.buildConstant(ExtractTy, ShiftImm);
4273fe6060f1SDimitry Andric     auto Cst2 = B.buildConstant(ExtractTy, Width);
4274fe6060f1SDimitry Andric     B.buildSbfx(Dst, ShiftSrc, Cst1, Cst2);
4275fe6060f1SDimitry Andric   };
4276fe6060f1SDimitry Andric   return true;
4277fe6060f1SDimitry Andric }
4278fe6060f1SDimitry Andric 
4279fe6060f1SDimitry Andric /// Form a G_UBFX from "(a srl b) & mask", where b and mask are constants.
4280fe6060f1SDimitry Andric bool CombinerHelper::matchBitfieldExtractFromAnd(
4281fe6060f1SDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4282fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_AND);
4283fe6060f1SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
4284fe6060f1SDimitry Andric   LLT Ty = MRI.getType(Dst);
428504eeddc0SDimitry Andric   LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
428604eeddc0SDimitry Andric   if (!getTargetLowering().isConstantUnsignedBitfieldExtractLegal(
428704eeddc0SDimitry Andric           TargetOpcode::G_UBFX, Ty, ExtractTy))
4288fe6060f1SDimitry Andric     return false;
4289fe6060f1SDimitry Andric 
4290fe6060f1SDimitry Andric   int64_t AndImm, LSBImm;
4291fe6060f1SDimitry Andric   Register ShiftSrc;
4292fe6060f1SDimitry Andric   const unsigned Size = Ty.getScalarSizeInBits();
4293fe6060f1SDimitry Andric   if (!mi_match(MI.getOperand(0).getReg(), MRI,
4294fe6060f1SDimitry Andric                 m_GAnd(m_OneNonDBGUse(m_GLShr(m_Reg(ShiftSrc), m_ICst(LSBImm))),
4295fe6060f1SDimitry Andric                        m_ICst(AndImm))))
4296fe6060f1SDimitry Andric     return false;
4297fe6060f1SDimitry Andric 
4298fe6060f1SDimitry Andric   // The mask is a mask of the low bits iff imm & (imm+1) == 0.
4299fe6060f1SDimitry Andric   auto MaybeMask = static_cast<uint64_t>(AndImm);
4300fe6060f1SDimitry Andric   if (MaybeMask & (MaybeMask + 1))
4301fe6060f1SDimitry Andric     return false;
4302fe6060f1SDimitry Andric 
4303fe6060f1SDimitry Andric   // LSB must fit within the register.
4304fe6060f1SDimitry Andric   if (static_cast<uint64_t>(LSBImm) >= Size)
4305fe6060f1SDimitry Andric     return false;
4306fe6060f1SDimitry Andric 
4307fe6060f1SDimitry Andric   uint64_t Width = APInt(Size, AndImm).countTrailingOnes();
4308fe6060f1SDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
4309fe6060f1SDimitry Andric     auto WidthCst = B.buildConstant(ExtractTy, Width);
4310fe6060f1SDimitry Andric     auto LSBCst = B.buildConstant(ExtractTy, LSBImm);
4311fe6060f1SDimitry Andric     B.buildInstr(TargetOpcode::G_UBFX, {Dst}, {ShiftSrc, LSBCst, WidthCst});
4312fe6060f1SDimitry Andric   };
4313fe6060f1SDimitry Andric   return true;
4314fe6060f1SDimitry Andric }
4315fe6060f1SDimitry Andric 
4316349cc55cSDimitry Andric bool CombinerHelper::matchBitfieldExtractFromShr(
4317349cc55cSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4318349cc55cSDimitry Andric   const unsigned Opcode = MI.getOpcode();
4319349cc55cSDimitry Andric   assert(Opcode == TargetOpcode::G_ASHR || Opcode == TargetOpcode::G_LSHR);
4320349cc55cSDimitry Andric 
4321349cc55cSDimitry Andric   const Register Dst = MI.getOperand(0).getReg();
4322349cc55cSDimitry Andric 
4323349cc55cSDimitry Andric   const unsigned ExtrOpcode = Opcode == TargetOpcode::G_ASHR
4324349cc55cSDimitry Andric                                   ? TargetOpcode::G_SBFX
4325349cc55cSDimitry Andric                                   : TargetOpcode::G_UBFX;
4326349cc55cSDimitry Andric 
4327349cc55cSDimitry Andric   // Check if the type we would use for the extract is legal
4328349cc55cSDimitry Andric   LLT Ty = MRI.getType(Dst);
4329349cc55cSDimitry Andric   LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4330349cc55cSDimitry Andric   if (!LI || !LI->isLegalOrCustom({ExtrOpcode, {Ty, ExtractTy}}))
4331349cc55cSDimitry Andric     return false;
4332349cc55cSDimitry Andric 
4333349cc55cSDimitry Andric   Register ShlSrc;
4334349cc55cSDimitry Andric   int64_t ShrAmt;
4335349cc55cSDimitry Andric   int64_t ShlAmt;
4336349cc55cSDimitry Andric   const unsigned Size = Ty.getScalarSizeInBits();
4337349cc55cSDimitry Andric 
4338349cc55cSDimitry Andric   // Try to match shr (shl x, c1), c2
4339349cc55cSDimitry Andric   if (!mi_match(Dst, MRI,
4340349cc55cSDimitry Andric                 m_BinOp(Opcode,
4341349cc55cSDimitry Andric                         m_OneNonDBGUse(m_GShl(m_Reg(ShlSrc), m_ICst(ShlAmt))),
4342349cc55cSDimitry Andric                         m_ICst(ShrAmt))))
4343349cc55cSDimitry Andric     return false;
4344349cc55cSDimitry Andric 
4345349cc55cSDimitry Andric   // Make sure that the shift sizes can fit a bitfield extract
4346349cc55cSDimitry Andric   if (ShlAmt < 0 || ShlAmt > ShrAmt || ShrAmt >= Size)
4347349cc55cSDimitry Andric     return false;
4348349cc55cSDimitry Andric 
4349349cc55cSDimitry Andric   // Skip this combine if the G_SEXT_INREG combine could handle it
4350349cc55cSDimitry Andric   if (Opcode == TargetOpcode::G_ASHR && ShlAmt == ShrAmt)
4351349cc55cSDimitry Andric     return false;
4352349cc55cSDimitry Andric 
4353349cc55cSDimitry Andric   // Calculate start position and width of the extract
4354349cc55cSDimitry Andric   const int64_t Pos = ShrAmt - ShlAmt;
4355349cc55cSDimitry Andric   const int64_t Width = Size - ShrAmt;
4356349cc55cSDimitry Andric 
4357349cc55cSDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
4358349cc55cSDimitry Andric     auto WidthCst = B.buildConstant(ExtractTy, Width);
4359349cc55cSDimitry Andric     auto PosCst = B.buildConstant(ExtractTy, Pos);
4360349cc55cSDimitry Andric     B.buildInstr(ExtrOpcode, {Dst}, {ShlSrc, PosCst, WidthCst});
4361349cc55cSDimitry Andric   };
4362349cc55cSDimitry Andric   return true;
4363349cc55cSDimitry Andric }
4364349cc55cSDimitry Andric 
4365349cc55cSDimitry Andric bool CombinerHelper::matchBitfieldExtractFromShrAnd(
4366349cc55cSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4367349cc55cSDimitry Andric   const unsigned Opcode = MI.getOpcode();
4368349cc55cSDimitry Andric   assert(Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_ASHR);
4369349cc55cSDimitry Andric 
4370349cc55cSDimitry Andric   const Register Dst = MI.getOperand(0).getReg();
4371349cc55cSDimitry Andric   LLT Ty = MRI.getType(Dst);
437204eeddc0SDimitry Andric   LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
437304eeddc0SDimitry Andric   if (!getTargetLowering().isConstantUnsignedBitfieldExtractLegal(
437404eeddc0SDimitry Andric           TargetOpcode::G_UBFX, Ty, ExtractTy))
4375349cc55cSDimitry Andric     return false;
4376349cc55cSDimitry Andric 
4377349cc55cSDimitry Andric   // Try to match shr (and x, c1), c2
4378349cc55cSDimitry Andric   Register AndSrc;
4379349cc55cSDimitry Andric   int64_t ShrAmt;
4380349cc55cSDimitry Andric   int64_t SMask;
4381349cc55cSDimitry Andric   if (!mi_match(Dst, MRI,
4382349cc55cSDimitry Andric                 m_BinOp(Opcode,
4383349cc55cSDimitry Andric                         m_OneNonDBGUse(m_GAnd(m_Reg(AndSrc), m_ICst(SMask))),
4384349cc55cSDimitry Andric                         m_ICst(ShrAmt))))
4385349cc55cSDimitry Andric     return false;
4386349cc55cSDimitry Andric 
4387349cc55cSDimitry Andric   const unsigned Size = Ty.getScalarSizeInBits();
4388349cc55cSDimitry Andric   if (ShrAmt < 0 || ShrAmt >= Size)
4389349cc55cSDimitry Andric     return false;
4390349cc55cSDimitry Andric 
4391*81ad6265SDimitry Andric   // If the shift subsumes the mask, emit the 0 directly.
4392*81ad6265SDimitry Andric   if (0 == (SMask >> ShrAmt)) {
4393*81ad6265SDimitry Andric     MatchInfo = [=](MachineIRBuilder &B) {
4394*81ad6265SDimitry Andric       B.buildConstant(Dst, 0);
4395*81ad6265SDimitry Andric     };
4396*81ad6265SDimitry Andric     return true;
4397*81ad6265SDimitry Andric   }
4398*81ad6265SDimitry Andric 
4399349cc55cSDimitry Andric   // Check that ubfx can do the extraction, with no holes in the mask.
4400349cc55cSDimitry Andric   uint64_t UMask = SMask;
4401349cc55cSDimitry Andric   UMask |= maskTrailingOnes<uint64_t>(ShrAmt);
4402349cc55cSDimitry Andric   UMask &= maskTrailingOnes<uint64_t>(Size);
4403349cc55cSDimitry Andric   if (!isMask_64(UMask))
4404349cc55cSDimitry Andric     return false;
4405349cc55cSDimitry Andric 
4406349cc55cSDimitry Andric   // Calculate start position and width of the extract.
4407349cc55cSDimitry Andric   const int64_t Pos = ShrAmt;
4408349cc55cSDimitry Andric   const int64_t Width = countTrailingOnes(UMask) - ShrAmt;
4409349cc55cSDimitry Andric 
4410349cc55cSDimitry Andric   // It's preferable to keep the shift, rather than form G_SBFX.
4411349cc55cSDimitry Andric   // TODO: remove the G_AND via demanded bits analysis.
4412349cc55cSDimitry Andric   if (Opcode == TargetOpcode::G_ASHR && Width + ShrAmt == Size)
4413349cc55cSDimitry Andric     return false;
4414349cc55cSDimitry Andric 
4415349cc55cSDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
441604eeddc0SDimitry Andric     auto WidthCst = B.buildConstant(ExtractTy, Width);
441704eeddc0SDimitry Andric     auto PosCst = B.buildConstant(ExtractTy, Pos);
4418349cc55cSDimitry Andric     B.buildInstr(TargetOpcode::G_UBFX, {Dst}, {AndSrc, PosCst, WidthCst});
4419349cc55cSDimitry Andric   };
4420349cc55cSDimitry Andric   return true;
4421349cc55cSDimitry Andric }
4422349cc55cSDimitry Andric 
4423fe6060f1SDimitry Andric bool CombinerHelper::reassociationCanBreakAddressingModePattern(
4424fe6060f1SDimitry Andric     MachineInstr &PtrAdd) {
4425fe6060f1SDimitry Andric   assert(PtrAdd.getOpcode() == TargetOpcode::G_PTR_ADD);
4426fe6060f1SDimitry Andric 
4427fe6060f1SDimitry Andric   Register Src1Reg = PtrAdd.getOperand(1).getReg();
4428fe6060f1SDimitry Andric   MachineInstr *Src1Def = getOpcodeDef(TargetOpcode::G_PTR_ADD, Src1Reg, MRI);
4429fe6060f1SDimitry Andric   if (!Src1Def)
4430fe6060f1SDimitry Andric     return false;
4431fe6060f1SDimitry Andric 
4432fe6060f1SDimitry Andric   Register Src2Reg = PtrAdd.getOperand(2).getReg();
4433fe6060f1SDimitry Andric 
4434fe6060f1SDimitry Andric   if (MRI.hasOneNonDBGUse(Src1Reg))
4435fe6060f1SDimitry Andric     return false;
4436fe6060f1SDimitry Andric 
4437349cc55cSDimitry Andric   auto C1 = getIConstantVRegVal(Src1Def->getOperand(2).getReg(), MRI);
4438fe6060f1SDimitry Andric   if (!C1)
4439fe6060f1SDimitry Andric     return false;
4440349cc55cSDimitry Andric   auto C2 = getIConstantVRegVal(Src2Reg, MRI);
4441fe6060f1SDimitry Andric   if (!C2)
4442fe6060f1SDimitry Andric     return false;
4443fe6060f1SDimitry Andric 
4444fe6060f1SDimitry Andric   const APInt &C1APIntVal = *C1;
4445fe6060f1SDimitry Andric   const APInt &C2APIntVal = *C2;
4446fe6060f1SDimitry Andric   const int64_t CombinedValue = (C1APIntVal + C2APIntVal).getSExtValue();
4447fe6060f1SDimitry Andric 
4448fe6060f1SDimitry Andric   for (auto &UseMI : MRI.use_nodbg_instructions(Src1Reg)) {
4449fe6060f1SDimitry Andric     // This combine may end up running before ptrtoint/inttoptr combines
4450fe6060f1SDimitry Andric     // manage to eliminate redundant conversions, so try to look through them.
4451fe6060f1SDimitry Andric     MachineInstr *ConvUseMI = &UseMI;
4452fe6060f1SDimitry Andric     unsigned ConvUseOpc = ConvUseMI->getOpcode();
4453fe6060f1SDimitry Andric     while (ConvUseOpc == TargetOpcode::G_INTTOPTR ||
4454fe6060f1SDimitry Andric            ConvUseOpc == TargetOpcode::G_PTRTOINT) {
4455fe6060f1SDimitry Andric       Register DefReg = ConvUseMI->getOperand(0).getReg();
4456fe6060f1SDimitry Andric       if (!MRI.hasOneNonDBGUse(DefReg))
4457fe6060f1SDimitry Andric         break;
4458fe6060f1SDimitry Andric       ConvUseMI = &*MRI.use_instr_nodbg_begin(DefReg);
4459fe6060f1SDimitry Andric       ConvUseOpc = ConvUseMI->getOpcode();
4460fe6060f1SDimitry Andric     }
4461fe6060f1SDimitry Andric     auto LoadStore = ConvUseOpc == TargetOpcode::G_LOAD ||
4462fe6060f1SDimitry Andric                      ConvUseOpc == TargetOpcode::G_STORE;
4463fe6060f1SDimitry Andric     if (!LoadStore)
4464fe6060f1SDimitry Andric       continue;
4465fe6060f1SDimitry Andric     // Is x[offset2] already not a legal addressing mode? If so then
4466fe6060f1SDimitry Andric     // reassociating the constants breaks nothing (we test offset2 because
4467fe6060f1SDimitry Andric     // that's the one we hope to fold into the load or store).
4468fe6060f1SDimitry Andric     TargetLoweringBase::AddrMode AM;
4469fe6060f1SDimitry Andric     AM.HasBaseReg = true;
4470fe6060f1SDimitry Andric     AM.BaseOffs = C2APIntVal.getSExtValue();
4471fe6060f1SDimitry Andric     unsigned AS =
4472fe6060f1SDimitry Andric         MRI.getType(ConvUseMI->getOperand(1).getReg()).getAddressSpace();
4473fe6060f1SDimitry Andric     Type *AccessTy =
4474fe6060f1SDimitry Andric         getTypeForLLT(MRI.getType(ConvUseMI->getOperand(0).getReg()),
4475fe6060f1SDimitry Andric                       PtrAdd.getMF()->getFunction().getContext());
4476fe6060f1SDimitry Andric     const auto &TLI = *PtrAdd.getMF()->getSubtarget().getTargetLowering();
4477fe6060f1SDimitry Andric     if (!TLI.isLegalAddressingMode(PtrAdd.getMF()->getDataLayout(), AM,
4478fe6060f1SDimitry Andric                                    AccessTy, AS))
4479fe6060f1SDimitry Andric       continue;
4480fe6060f1SDimitry Andric 
4481fe6060f1SDimitry Andric     // Would x[offset1+offset2] still be a legal addressing mode?
4482fe6060f1SDimitry Andric     AM.BaseOffs = CombinedValue;
4483fe6060f1SDimitry Andric     if (!TLI.isLegalAddressingMode(PtrAdd.getMF()->getDataLayout(), AM,
4484fe6060f1SDimitry Andric                                    AccessTy, AS))
4485fe6060f1SDimitry Andric       return true;
4486fe6060f1SDimitry Andric   }
4487fe6060f1SDimitry Andric 
4488fe6060f1SDimitry Andric   return false;
4489fe6060f1SDimitry Andric }
4490fe6060f1SDimitry Andric 
4491349cc55cSDimitry Andric bool CombinerHelper::matchReassocConstantInnerRHS(GPtrAdd &MI,
4492349cc55cSDimitry Andric                                                   MachineInstr *RHS,
4493349cc55cSDimitry Andric                                                   BuildFnTy &MatchInfo) {
4494fe6060f1SDimitry Andric   // G_PTR_ADD(BASE, G_ADD(X, C)) -> G_PTR_ADD(G_PTR_ADD(BASE, X), C)
4495fe6060f1SDimitry Andric   Register Src1Reg = MI.getOperand(1).getReg();
4496fe6060f1SDimitry Andric   if (RHS->getOpcode() != TargetOpcode::G_ADD)
4497fe6060f1SDimitry Andric     return false;
4498349cc55cSDimitry Andric   auto C2 = getIConstantVRegVal(RHS->getOperand(2).getReg(), MRI);
4499fe6060f1SDimitry Andric   if (!C2)
4500fe6060f1SDimitry Andric     return false;
4501fe6060f1SDimitry Andric 
4502fe6060f1SDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4503fe6060f1SDimitry Andric     LLT PtrTy = MRI.getType(MI.getOperand(0).getReg());
4504fe6060f1SDimitry Andric 
4505fe6060f1SDimitry Andric     auto NewBase =
4506fe6060f1SDimitry Andric         Builder.buildPtrAdd(PtrTy, Src1Reg, RHS->getOperand(1).getReg());
4507fe6060f1SDimitry Andric     Observer.changingInstr(MI);
4508fe6060f1SDimitry Andric     MI.getOperand(1).setReg(NewBase.getReg(0));
4509fe6060f1SDimitry Andric     MI.getOperand(2).setReg(RHS->getOperand(2).getReg());
4510fe6060f1SDimitry Andric     Observer.changedInstr(MI);
4511fe6060f1SDimitry Andric   };
4512349cc55cSDimitry Andric   return !reassociationCanBreakAddressingModePattern(MI);
4513349cc55cSDimitry Andric }
4514349cc55cSDimitry Andric 
4515349cc55cSDimitry Andric bool CombinerHelper::matchReassocConstantInnerLHS(GPtrAdd &MI,
4516349cc55cSDimitry Andric                                                   MachineInstr *LHS,
4517349cc55cSDimitry Andric                                                   MachineInstr *RHS,
4518349cc55cSDimitry Andric                                                   BuildFnTy &MatchInfo) {
4519349cc55cSDimitry Andric   // G_PTR_ADD (G_PTR_ADD X, C), Y) -> (G_PTR_ADD (G_PTR_ADD(X, Y), C)
4520349cc55cSDimitry Andric   // if and only if (G_PTR_ADD X, C) has one use.
4521349cc55cSDimitry Andric   Register LHSBase;
4522349cc55cSDimitry Andric   Optional<ValueAndVReg> LHSCstOff;
4523349cc55cSDimitry Andric   if (!mi_match(MI.getBaseReg(), MRI,
4524349cc55cSDimitry Andric                 m_OneNonDBGUse(m_GPtrAdd(m_Reg(LHSBase), m_GCst(LHSCstOff)))))
4525349cc55cSDimitry Andric     return false;
4526349cc55cSDimitry Andric 
4527349cc55cSDimitry Andric   auto *LHSPtrAdd = cast<GPtrAdd>(LHS);
4528349cc55cSDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4529349cc55cSDimitry Andric     // When we change LHSPtrAdd's offset register we might cause it to use a reg
4530349cc55cSDimitry Andric     // before its def. Sink the instruction so the outer PTR_ADD to ensure this
4531349cc55cSDimitry Andric     // doesn't happen.
4532349cc55cSDimitry Andric     LHSPtrAdd->moveBefore(&MI);
4533349cc55cSDimitry Andric     Register RHSReg = MI.getOffsetReg();
4534349cc55cSDimitry Andric     Observer.changingInstr(MI);
4535349cc55cSDimitry Andric     MI.getOperand(2).setReg(LHSCstOff->VReg);
4536349cc55cSDimitry Andric     Observer.changedInstr(MI);
4537349cc55cSDimitry Andric     Observer.changingInstr(*LHSPtrAdd);
4538349cc55cSDimitry Andric     LHSPtrAdd->getOperand(2).setReg(RHSReg);
4539349cc55cSDimitry Andric     Observer.changedInstr(*LHSPtrAdd);
4540349cc55cSDimitry Andric   };
4541349cc55cSDimitry Andric   return !reassociationCanBreakAddressingModePattern(MI);
4542349cc55cSDimitry Andric }
4543349cc55cSDimitry Andric 
4544349cc55cSDimitry Andric bool CombinerHelper::matchReassocFoldConstantsInSubTree(GPtrAdd &MI,
4545349cc55cSDimitry Andric                                                         MachineInstr *LHS,
4546349cc55cSDimitry Andric                                                         MachineInstr *RHS,
4547349cc55cSDimitry Andric                                                         BuildFnTy &MatchInfo) {
4548349cc55cSDimitry Andric   // G_PTR_ADD(G_PTR_ADD(BASE, C1), C2) -> G_PTR_ADD(BASE, C1+C2)
4549349cc55cSDimitry Andric   auto *LHSPtrAdd = dyn_cast<GPtrAdd>(LHS);
4550349cc55cSDimitry Andric   if (!LHSPtrAdd)
4551349cc55cSDimitry Andric     return false;
4552349cc55cSDimitry Andric 
4553349cc55cSDimitry Andric   Register Src2Reg = MI.getOperand(2).getReg();
4554349cc55cSDimitry Andric   Register LHSSrc1 = LHSPtrAdd->getBaseReg();
4555349cc55cSDimitry Andric   Register LHSSrc2 = LHSPtrAdd->getOffsetReg();
4556349cc55cSDimitry Andric   auto C1 = getIConstantVRegVal(LHSSrc2, MRI);
4557fe6060f1SDimitry Andric   if (!C1)
4558fe6060f1SDimitry Andric     return false;
4559349cc55cSDimitry Andric   auto C2 = getIConstantVRegVal(Src2Reg, MRI);
4560fe6060f1SDimitry Andric   if (!C2)
4561fe6060f1SDimitry Andric     return false;
4562fe6060f1SDimitry Andric 
4563fe6060f1SDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4564fe6060f1SDimitry Andric     auto NewCst = B.buildConstant(MRI.getType(Src2Reg), *C1 + *C2);
4565fe6060f1SDimitry Andric     Observer.changingInstr(MI);
4566fe6060f1SDimitry Andric     MI.getOperand(1).setReg(LHSSrc1);
4567fe6060f1SDimitry Andric     MI.getOperand(2).setReg(NewCst.getReg(0));
4568fe6060f1SDimitry Andric     Observer.changedInstr(MI);
4569fe6060f1SDimitry Andric   };
4570fe6060f1SDimitry Andric   return !reassociationCanBreakAddressingModePattern(MI);
4571fe6060f1SDimitry Andric }
4572fe6060f1SDimitry Andric 
4573349cc55cSDimitry Andric bool CombinerHelper::matchReassocPtrAdd(MachineInstr &MI,
4574349cc55cSDimitry Andric                                         BuildFnTy &MatchInfo) {
4575349cc55cSDimitry Andric   auto &PtrAdd = cast<GPtrAdd>(MI);
4576349cc55cSDimitry Andric   // We're trying to match a few pointer computation patterns here for
4577349cc55cSDimitry Andric   // re-association opportunities.
4578349cc55cSDimitry Andric   // 1) Isolating a constant operand to be on the RHS, e.g.:
4579349cc55cSDimitry Andric   // G_PTR_ADD(BASE, G_ADD(X, C)) -> G_PTR_ADD(G_PTR_ADD(BASE, X), C)
4580349cc55cSDimitry Andric   //
4581349cc55cSDimitry Andric   // 2) Folding two constants in each sub-tree as long as such folding
4582349cc55cSDimitry Andric   // doesn't break a legal addressing mode.
4583349cc55cSDimitry Andric   // G_PTR_ADD(G_PTR_ADD(BASE, C1), C2) -> G_PTR_ADD(BASE, C1+C2)
4584349cc55cSDimitry Andric   //
4585349cc55cSDimitry Andric   // 3) Move a constant from the LHS of an inner op to the RHS of the outer.
4586349cc55cSDimitry Andric   // G_PTR_ADD (G_PTR_ADD X, C), Y) -> G_PTR_ADD (G_PTR_ADD(X, Y), C)
4587349cc55cSDimitry Andric   // iif (G_PTR_ADD X, C) has one use.
4588349cc55cSDimitry Andric   MachineInstr *LHS = MRI.getVRegDef(PtrAdd.getBaseReg());
4589349cc55cSDimitry Andric   MachineInstr *RHS = MRI.getVRegDef(PtrAdd.getOffsetReg());
4590349cc55cSDimitry Andric 
4591349cc55cSDimitry Andric   // Try to match example 2.
4592349cc55cSDimitry Andric   if (matchReassocFoldConstantsInSubTree(PtrAdd, LHS, RHS, MatchInfo))
4593349cc55cSDimitry Andric     return true;
4594349cc55cSDimitry Andric 
4595349cc55cSDimitry Andric   // Try to match example 3.
4596349cc55cSDimitry Andric   if (matchReassocConstantInnerLHS(PtrAdd, LHS, RHS, MatchInfo))
4597349cc55cSDimitry Andric     return true;
4598349cc55cSDimitry Andric 
4599349cc55cSDimitry Andric   // Try to match example 1.
4600349cc55cSDimitry Andric   if (matchReassocConstantInnerRHS(PtrAdd, RHS, MatchInfo))
4601349cc55cSDimitry Andric     return true;
4602349cc55cSDimitry Andric 
4603349cc55cSDimitry Andric   return false;
4604349cc55cSDimitry Andric }
4605349cc55cSDimitry Andric 
4606fe6060f1SDimitry Andric bool CombinerHelper::matchConstantFold(MachineInstr &MI, APInt &MatchInfo) {
4607fe6060f1SDimitry Andric   Register Op1 = MI.getOperand(1).getReg();
4608fe6060f1SDimitry Andric   Register Op2 = MI.getOperand(2).getReg();
4609fe6060f1SDimitry Andric   auto MaybeCst = ConstantFoldBinOp(MI.getOpcode(), Op1, Op2, MRI);
4610fe6060f1SDimitry Andric   if (!MaybeCst)
4611fe6060f1SDimitry Andric     return false;
4612fe6060f1SDimitry Andric   MatchInfo = *MaybeCst;
4613e8d8bef9SDimitry Andric   return true;
4614e8d8bef9SDimitry Andric }
4615e8d8bef9SDimitry Andric 
4616349cc55cSDimitry Andric bool CombinerHelper::matchNarrowBinopFeedingAnd(
4617349cc55cSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4618349cc55cSDimitry Andric   // Look for a binop feeding into an AND with a mask:
4619349cc55cSDimitry Andric   //
4620349cc55cSDimitry Andric   // %add = G_ADD %lhs, %rhs
4621349cc55cSDimitry Andric   // %and = G_AND %add, 000...11111111
4622349cc55cSDimitry Andric   //
4623349cc55cSDimitry Andric   // Check if it's possible to perform the binop at a narrower width and zext
4624349cc55cSDimitry Andric   // back to the original width like so:
4625349cc55cSDimitry Andric   //
4626349cc55cSDimitry Andric   // %narrow_lhs = G_TRUNC %lhs
4627349cc55cSDimitry Andric   // %narrow_rhs = G_TRUNC %rhs
4628349cc55cSDimitry Andric   // %narrow_add = G_ADD %narrow_lhs, %narrow_rhs
4629349cc55cSDimitry Andric   // %new_add = G_ZEXT %narrow_add
4630349cc55cSDimitry Andric   // %and = G_AND %new_add, 000...11111111
4631349cc55cSDimitry Andric   //
4632349cc55cSDimitry Andric   // This can allow later combines to eliminate the G_AND if it turns out
4633349cc55cSDimitry Andric   // that the mask is irrelevant.
4634349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_AND);
4635349cc55cSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
4636349cc55cSDimitry Andric   Register AndLHS = MI.getOperand(1).getReg();
4637349cc55cSDimitry Andric   Register AndRHS = MI.getOperand(2).getReg();
4638349cc55cSDimitry Andric   LLT WideTy = MRI.getType(Dst);
4639349cc55cSDimitry Andric 
4640349cc55cSDimitry Andric   // If the potential binop has more than one use, then it's possible that one
4641349cc55cSDimitry Andric   // of those uses will need its full width.
4642349cc55cSDimitry Andric   if (!WideTy.isScalar() || !MRI.hasOneNonDBGUse(AndLHS))
4643349cc55cSDimitry Andric     return false;
4644349cc55cSDimitry Andric 
4645349cc55cSDimitry Andric   // Check if the LHS feeding the AND is impacted by the high bits that we're
4646349cc55cSDimitry Andric   // masking out.
4647349cc55cSDimitry Andric   //
4648349cc55cSDimitry Andric   // e.g. for 64-bit x, y:
4649349cc55cSDimitry Andric   //
4650349cc55cSDimitry Andric   // add_64(x, y) & 65535 == zext(add_16(trunc(x), trunc(y))) & 65535
4651349cc55cSDimitry Andric   MachineInstr *LHSInst = getDefIgnoringCopies(AndLHS, MRI);
4652349cc55cSDimitry Andric   if (!LHSInst)
4653349cc55cSDimitry Andric     return false;
4654349cc55cSDimitry Andric   unsigned LHSOpc = LHSInst->getOpcode();
4655349cc55cSDimitry Andric   switch (LHSOpc) {
4656349cc55cSDimitry Andric   default:
4657349cc55cSDimitry Andric     return false;
4658349cc55cSDimitry Andric   case TargetOpcode::G_ADD:
4659349cc55cSDimitry Andric   case TargetOpcode::G_SUB:
4660349cc55cSDimitry Andric   case TargetOpcode::G_MUL:
4661349cc55cSDimitry Andric   case TargetOpcode::G_AND:
4662349cc55cSDimitry Andric   case TargetOpcode::G_OR:
4663349cc55cSDimitry Andric   case TargetOpcode::G_XOR:
4664349cc55cSDimitry Andric     break;
4665349cc55cSDimitry Andric   }
4666349cc55cSDimitry Andric 
4667349cc55cSDimitry Andric   // Find the mask on the RHS.
4668349cc55cSDimitry Andric   auto Cst = getIConstantVRegValWithLookThrough(AndRHS, MRI);
4669349cc55cSDimitry Andric   if (!Cst)
4670349cc55cSDimitry Andric     return false;
4671349cc55cSDimitry Andric   auto Mask = Cst->Value;
4672349cc55cSDimitry Andric   if (!Mask.isMask())
4673349cc55cSDimitry Andric     return false;
4674349cc55cSDimitry Andric 
4675349cc55cSDimitry Andric   // No point in combining if there's nothing to truncate.
4676349cc55cSDimitry Andric   unsigned NarrowWidth = Mask.countTrailingOnes();
4677349cc55cSDimitry Andric   if (NarrowWidth == WideTy.getSizeInBits())
4678349cc55cSDimitry Andric     return false;
4679349cc55cSDimitry Andric   LLT NarrowTy = LLT::scalar(NarrowWidth);
4680349cc55cSDimitry Andric 
4681349cc55cSDimitry Andric   // Check if adding the zext + truncates could be harmful.
4682349cc55cSDimitry Andric   auto &MF = *MI.getMF();
4683349cc55cSDimitry Andric   const auto &TLI = getTargetLowering();
4684349cc55cSDimitry Andric   LLVMContext &Ctx = MF.getFunction().getContext();
4685349cc55cSDimitry Andric   auto &DL = MF.getDataLayout();
4686349cc55cSDimitry Andric   if (!TLI.isTruncateFree(WideTy, NarrowTy, DL, Ctx) ||
4687349cc55cSDimitry Andric       !TLI.isZExtFree(NarrowTy, WideTy, DL, Ctx))
4688349cc55cSDimitry Andric     return false;
4689349cc55cSDimitry Andric   if (!isLegalOrBeforeLegalizer({TargetOpcode::G_TRUNC, {NarrowTy, WideTy}}) ||
4690349cc55cSDimitry Andric       !isLegalOrBeforeLegalizer({TargetOpcode::G_ZEXT, {WideTy, NarrowTy}}))
4691349cc55cSDimitry Andric     return false;
4692349cc55cSDimitry Andric   Register BinOpLHS = LHSInst->getOperand(1).getReg();
4693349cc55cSDimitry Andric   Register BinOpRHS = LHSInst->getOperand(2).getReg();
4694349cc55cSDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4695349cc55cSDimitry Andric     auto NarrowLHS = Builder.buildTrunc(NarrowTy, BinOpLHS);
4696349cc55cSDimitry Andric     auto NarrowRHS = Builder.buildTrunc(NarrowTy, BinOpRHS);
4697349cc55cSDimitry Andric     auto NarrowBinOp =
4698349cc55cSDimitry Andric         Builder.buildInstr(LHSOpc, {NarrowTy}, {NarrowLHS, NarrowRHS});
4699349cc55cSDimitry Andric     auto Ext = Builder.buildZExt(WideTy, NarrowBinOp);
4700349cc55cSDimitry Andric     Observer.changingInstr(MI);
4701349cc55cSDimitry Andric     MI.getOperand(1).setReg(Ext.getReg(0));
4702349cc55cSDimitry Andric     Observer.changedInstr(MI);
4703349cc55cSDimitry Andric   };
4704349cc55cSDimitry Andric   return true;
4705349cc55cSDimitry Andric }
4706349cc55cSDimitry Andric 
4707349cc55cSDimitry Andric bool CombinerHelper::matchMulOBy2(MachineInstr &MI, BuildFnTy &MatchInfo) {
4708349cc55cSDimitry Andric   unsigned Opc = MI.getOpcode();
4709349cc55cSDimitry Andric   assert(Opc == TargetOpcode::G_UMULO || Opc == TargetOpcode::G_SMULO);
47104824e7fdSDimitry Andric 
47114824e7fdSDimitry Andric   if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICstOrSplat(2)))
4712349cc55cSDimitry Andric     return false;
4713349cc55cSDimitry Andric 
4714349cc55cSDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4715349cc55cSDimitry Andric     Observer.changingInstr(MI);
4716349cc55cSDimitry Andric     unsigned NewOpc = Opc == TargetOpcode::G_UMULO ? TargetOpcode::G_UADDO
4717349cc55cSDimitry Andric                                                    : TargetOpcode::G_SADDO;
4718349cc55cSDimitry Andric     MI.setDesc(Builder.getTII().get(NewOpc));
4719349cc55cSDimitry Andric     MI.getOperand(3).setReg(MI.getOperand(2).getReg());
4720349cc55cSDimitry Andric     Observer.changedInstr(MI);
4721349cc55cSDimitry Andric   };
4722349cc55cSDimitry Andric   return true;
4723349cc55cSDimitry Andric }
4724349cc55cSDimitry Andric 
4725*81ad6265SDimitry Andric bool CombinerHelper::matchMulOBy0(MachineInstr &MI, BuildFnTy &MatchInfo) {
4726*81ad6265SDimitry Andric   // (G_*MULO x, 0) -> 0 + no carry out
4727*81ad6265SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UMULO ||
4728*81ad6265SDimitry Andric          MI.getOpcode() == TargetOpcode::G_SMULO);
4729*81ad6265SDimitry Andric   if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICstOrSplat(0)))
4730*81ad6265SDimitry Andric     return false;
4731*81ad6265SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
4732*81ad6265SDimitry Andric   Register Carry = MI.getOperand(1).getReg();
4733*81ad6265SDimitry Andric   if (!isConstantLegalOrBeforeLegalizer(MRI.getType(Dst)) ||
4734*81ad6265SDimitry Andric       !isConstantLegalOrBeforeLegalizer(MRI.getType(Carry)))
4735*81ad6265SDimitry Andric     return false;
4736*81ad6265SDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
4737*81ad6265SDimitry Andric     B.buildConstant(Dst, 0);
4738*81ad6265SDimitry Andric     B.buildConstant(Carry, 0);
4739*81ad6265SDimitry Andric   };
4740*81ad6265SDimitry Andric   return true;
4741*81ad6265SDimitry Andric }
4742*81ad6265SDimitry Andric 
4743*81ad6265SDimitry Andric bool CombinerHelper::matchAddOBy0(MachineInstr &MI, BuildFnTy &MatchInfo) {
4744*81ad6265SDimitry Andric   // (G_*ADDO x, 0) -> x + no carry out
4745*81ad6265SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UADDO ||
4746*81ad6265SDimitry Andric          MI.getOpcode() == TargetOpcode::G_SADDO);
4747*81ad6265SDimitry Andric   if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICstOrSplat(0)))
4748*81ad6265SDimitry Andric     return false;
4749*81ad6265SDimitry Andric   Register Carry = MI.getOperand(1).getReg();
4750*81ad6265SDimitry Andric   if (!isConstantLegalOrBeforeLegalizer(MRI.getType(Carry)))
4751*81ad6265SDimitry Andric     return false;
4752*81ad6265SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
4753*81ad6265SDimitry Andric   Register LHS = MI.getOperand(2).getReg();
4754*81ad6265SDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
4755*81ad6265SDimitry Andric     B.buildCopy(Dst, LHS);
4756*81ad6265SDimitry Andric     B.buildConstant(Carry, 0);
4757*81ad6265SDimitry Andric   };
4758*81ad6265SDimitry Andric   return true;
4759*81ad6265SDimitry Andric }
4760*81ad6265SDimitry Andric 
4761349cc55cSDimitry Andric MachineInstr *CombinerHelper::buildUDivUsingMul(MachineInstr &MI) {
4762349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UDIV);
4763349cc55cSDimitry Andric   auto &UDiv = cast<GenericMachineInstr>(MI);
4764349cc55cSDimitry Andric   Register Dst = UDiv.getReg(0);
4765349cc55cSDimitry Andric   Register LHS = UDiv.getReg(1);
4766349cc55cSDimitry Andric   Register RHS = UDiv.getReg(2);
4767349cc55cSDimitry Andric   LLT Ty = MRI.getType(Dst);
4768349cc55cSDimitry Andric   LLT ScalarTy = Ty.getScalarType();
4769349cc55cSDimitry Andric   const unsigned EltBits = ScalarTy.getScalarSizeInBits();
4770349cc55cSDimitry Andric   LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4771349cc55cSDimitry Andric   LLT ScalarShiftAmtTy = ShiftAmtTy.getScalarType();
4772349cc55cSDimitry Andric   auto &MIB = Builder;
4773349cc55cSDimitry Andric   MIB.setInstrAndDebugLoc(MI);
4774349cc55cSDimitry Andric 
4775349cc55cSDimitry Andric   bool UseNPQ = false;
4776349cc55cSDimitry Andric   SmallVector<Register, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
4777349cc55cSDimitry Andric 
4778349cc55cSDimitry Andric   auto BuildUDIVPattern = [&](const Constant *C) {
4779349cc55cSDimitry Andric     auto *CI = cast<ConstantInt>(C);
4780349cc55cSDimitry Andric     const APInt &Divisor = CI->getValue();
4781349cc55cSDimitry Andric     UnsignedDivisonByConstantInfo magics =
4782349cc55cSDimitry Andric         UnsignedDivisonByConstantInfo::get(Divisor);
4783349cc55cSDimitry Andric     unsigned PreShift = 0, PostShift = 0;
4784349cc55cSDimitry Andric 
4785349cc55cSDimitry Andric     // If the divisor is even, we can avoid using the expensive fixup by
4786349cc55cSDimitry Andric     // shifting the divided value upfront.
4787349cc55cSDimitry Andric     if (magics.IsAdd != 0 && !Divisor[0]) {
4788349cc55cSDimitry Andric       PreShift = Divisor.countTrailingZeros();
4789349cc55cSDimitry Andric       // Get magic number for the shifted divisor.
4790349cc55cSDimitry Andric       magics =
4791349cc55cSDimitry Andric           UnsignedDivisonByConstantInfo::get(Divisor.lshr(PreShift), PreShift);
4792349cc55cSDimitry Andric       assert(magics.IsAdd == 0 && "Should use cheap fixup now");
4793349cc55cSDimitry Andric     }
4794349cc55cSDimitry Andric 
4795349cc55cSDimitry Andric     APInt Magic = magics.Magic;
4796349cc55cSDimitry Andric 
4797349cc55cSDimitry Andric     unsigned SelNPQ;
4798349cc55cSDimitry Andric     if (magics.IsAdd == 0 || Divisor.isOneValue()) {
4799349cc55cSDimitry Andric       assert(magics.ShiftAmount < Divisor.getBitWidth() &&
4800349cc55cSDimitry Andric              "We shouldn't generate an undefined shift!");
4801349cc55cSDimitry Andric       PostShift = magics.ShiftAmount;
4802349cc55cSDimitry Andric       SelNPQ = false;
4803349cc55cSDimitry Andric     } else {
4804349cc55cSDimitry Andric       PostShift = magics.ShiftAmount - 1;
4805349cc55cSDimitry Andric       SelNPQ = true;
4806349cc55cSDimitry Andric     }
4807349cc55cSDimitry Andric 
4808349cc55cSDimitry Andric     PreShifts.push_back(
4809349cc55cSDimitry Andric         MIB.buildConstant(ScalarShiftAmtTy, PreShift).getReg(0));
4810349cc55cSDimitry Andric     MagicFactors.push_back(MIB.buildConstant(ScalarTy, Magic).getReg(0));
4811349cc55cSDimitry Andric     NPQFactors.push_back(
4812349cc55cSDimitry Andric         MIB.buildConstant(ScalarTy,
4813349cc55cSDimitry Andric                           SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1)
4814349cc55cSDimitry Andric                                  : APInt::getZero(EltBits))
4815349cc55cSDimitry Andric             .getReg(0));
4816349cc55cSDimitry Andric     PostShifts.push_back(
4817349cc55cSDimitry Andric         MIB.buildConstant(ScalarShiftAmtTy, PostShift).getReg(0));
4818349cc55cSDimitry Andric     UseNPQ |= SelNPQ;
4819349cc55cSDimitry Andric     return true;
4820349cc55cSDimitry Andric   };
4821349cc55cSDimitry Andric 
4822349cc55cSDimitry Andric   // Collect the shifts/magic values from each element.
4823349cc55cSDimitry Andric   bool Matched = matchUnaryPredicate(MRI, RHS, BuildUDIVPattern);
4824349cc55cSDimitry Andric   (void)Matched;
4825349cc55cSDimitry Andric   assert(Matched && "Expected unary predicate match to succeed");
4826349cc55cSDimitry Andric 
4827349cc55cSDimitry Andric   Register PreShift, PostShift, MagicFactor, NPQFactor;
4828349cc55cSDimitry Andric   auto *RHSDef = getOpcodeDef<GBuildVector>(RHS, MRI);
4829349cc55cSDimitry Andric   if (RHSDef) {
4830349cc55cSDimitry Andric     PreShift = MIB.buildBuildVector(ShiftAmtTy, PreShifts).getReg(0);
4831349cc55cSDimitry Andric     MagicFactor = MIB.buildBuildVector(Ty, MagicFactors).getReg(0);
4832349cc55cSDimitry Andric     NPQFactor = MIB.buildBuildVector(Ty, NPQFactors).getReg(0);
4833349cc55cSDimitry Andric     PostShift = MIB.buildBuildVector(ShiftAmtTy, PostShifts).getReg(0);
4834349cc55cSDimitry Andric   } else {
4835349cc55cSDimitry Andric     assert(MRI.getType(RHS).isScalar() &&
4836349cc55cSDimitry Andric            "Non-build_vector operation should have been a scalar");
4837349cc55cSDimitry Andric     PreShift = PreShifts[0];
4838349cc55cSDimitry Andric     MagicFactor = MagicFactors[0];
4839349cc55cSDimitry Andric     PostShift = PostShifts[0];
4840349cc55cSDimitry Andric   }
4841349cc55cSDimitry Andric 
4842349cc55cSDimitry Andric   Register Q = LHS;
4843349cc55cSDimitry Andric   Q = MIB.buildLShr(Ty, Q, PreShift).getReg(0);
4844349cc55cSDimitry Andric 
4845349cc55cSDimitry Andric   // Multiply the numerator (operand 0) by the magic value.
4846349cc55cSDimitry Andric   Q = MIB.buildUMulH(Ty, Q, MagicFactor).getReg(0);
4847349cc55cSDimitry Andric 
4848349cc55cSDimitry Andric   if (UseNPQ) {
4849349cc55cSDimitry Andric     Register NPQ = MIB.buildSub(Ty, LHS, Q).getReg(0);
4850349cc55cSDimitry Andric 
4851349cc55cSDimitry Andric     // For vectors we might have a mix of non-NPQ/NPQ paths, so use
4852349cc55cSDimitry Andric     // G_UMULH to act as a SRL-by-1 for NPQ, else multiply by zero.
4853349cc55cSDimitry Andric     if (Ty.isVector())
4854349cc55cSDimitry Andric       NPQ = MIB.buildUMulH(Ty, NPQ, NPQFactor).getReg(0);
4855349cc55cSDimitry Andric     else
4856349cc55cSDimitry Andric       NPQ = MIB.buildLShr(Ty, NPQ, MIB.buildConstant(ShiftAmtTy, 1)).getReg(0);
4857349cc55cSDimitry Andric 
4858349cc55cSDimitry Andric     Q = MIB.buildAdd(Ty, NPQ, Q).getReg(0);
4859349cc55cSDimitry Andric   }
4860349cc55cSDimitry Andric 
4861349cc55cSDimitry Andric   Q = MIB.buildLShr(Ty, Q, PostShift).getReg(0);
4862349cc55cSDimitry Andric   auto One = MIB.buildConstant(Ty, 1);
4863349cc55cSDimitry Andric   auto IsOne = MIB.buildICmp(
4864349cc55cSDimitry Andric       CmpInst::Predicate::ICMP_EQ,
4865349cc55cSDimitry Andric       Ty.isScalar() ? LLT::scalar(1) : Ty.changeElementSize(1), RHS, One);
4866349cc55cSDimitry Andric   return MIB.buildSelect(Ty, IsOne, LHS, Q);
4867349cc55cSDimitry Andric }
4868349cc55cSDimitry Andric 
4869349cc55cSDimitry Andric bool CombinerHelper::matchUDivByConst(MachineInstr &MI) {
4870349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UDIV);
4871349cc55cSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
4872349cc55cSDimitry Andric   Register RHS = MI.getOperand(2).getReg();
4873349cc55cSDimitry Andric   LLT DstTy = MRI.getType(Dst);
4874349cc55cSDimitry Andric   auto *RHSDef = MRI.getVRegDef(RHS);
4875349cc55cSDimitry Andric   if (!isConstantOrConstantVector(*RHSDef, MRI))
4876349cc55cSDimitry Andric     return false;
4877349cc55cSDimitry Andric 
4878349cc55cSDimitry Andric   auto &MF = *MI.getMF();
4879349cc55cSDimitry Andric   AttributeList Attr = MF.getFunction().getAttributes();
4880349cc55cSDimitry Andric   const auto &TLI = getTargetLowering();
4881349cc55cSDimitry Andric   LLVMContext &Ctx = MF.getFunction().getContext();
4882349cc55cSDimitry Andric   auto &DL = MF.getDataLayout();
4883349cc55cSDimitry Andric   if (TLI.isIntDivCheap(getApproximateEVTForLLT(DstTy, DL, Ctx), Attr))
4884349cc55cSDimitry Andric     return false;
4885349cc55cSDimitry Andric 
4886349cc55cSDimitry Andric   // Don't do this for minsize because the instruction sequence is usually
4887349cc55cSDimitry Andric   // larger.
4888349cc55cSDimitry Andric   if (MF.getFunction().hasMinSize())
4889349cc55cSDimitry Andric     return false;
4890349cc55cSDimitry Andric 
4891349cc55cSDimitry Andric   // Don't do this if the types are not going to be legal.
4892349cc55cSDimitry Andric   if (LI) {
4893349cc55cSDimitry Andric     if (!isLegalOrBeforeLegalizer({TargetOpcode::G_MUL, {DstTy, DstTy}}))
4894349cc55cSDimitry Andric       return false;
4895349cc55cSDimitry Andric     if (!isLegalOrBeforeLegalizer({TargetOpcode::G_UMULH, {DstTy}}))
4896349cc55cSDimitry Andric       return false;
4897349cc55cSDimitry Andric     if (!isLegalOrBeforeLegalizer(
4898349cc55cSDimitry Andric             {TargetOpcode::G_ICMP,
4899349cc55cSDimitry Andric              {DstTy.isVector() ? DstTy.changeElementSize(1) : LLT::scalar(1),
4900349cc55cSDimitry Andric               DstTy}}))
4901349cc55cSDimitry Andric       return false;
4902349cc55cSDimitry Andric   }
4903349cc55cSDimitry Andric 
4904349cc55cSDimitry Andric   auto CheckEltValue = [&](const Constant *C) {
4905349cc55cSDimitry Andric     if (auto *CI = dyn_cast_or_null<ConstantInt>(C))
4906349cc55cSDimitry Andric       return !CI->isZero();
4907349cc55cSDimitry Andric     return false;
4908349cc55cSDimitry Andric   };
4909349cc55cSDimitry Andric   return matchUnaryPredicate(MRI, RHS, CheckEltValue);
4910349cc55cSDimitry Andric }
4911349cc55cSDimitry Andric 
4912349cc55cSDimitry Andric void CombinerHelper::applyUDivByConst(MachineInstr &MI) {
4913349cc55cSDimitry Andric   auto *NewMI = buildUDivUsingMul(MI);
4914349cc55cSDimitry Andric   replaceSingleDefInstWithReg(MI, NewMI->getOperand(0).getReg());
4915349cc55cSDimitry Andric }
4916349cc55cSDimitry Andric 
4917349cc55cSDimitry Andric bool CombinerHelper::matchUMulHToLShr(MachineInstr &MI) {
4918349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UMULH);
4919349cc55cSDimitry Andric   Register RHS = MI.getOperand(2).getReg();
4920349cc55cSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
4921349cc55cSDimitry Andric   LLT Ty = MRI.getType(Dst);
4922349cc55cSDimitry Andric   LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4923349cc55cSDimitry Andric   auto MatchPow2ExceptOne = [&](const Constant *C) {
4924349cc55cSDimitry Andric     if (auto *CI = dyn_cast<ConstantInt>(C))
4925349cc55cSDimitry Andric       return CI->getValue().isPowerOf2() && !CI->getValue().isOne();
4926349cc55cSDimitry Andric     return false;
4927349cc55cSDimitry Andric   };
4928349cc55cSDimitry Andric   if (!matchUnaryPredicate(MRI, RHS, MatchPow2ExceptOne, false))
4929349cc55cSDimitry Andric     return false;
4930349cc55cSDimitry Andric   return isLegalOrBeforeLegalizer({TargetOpcode::G_LSHR, {Ty, ShiftAmtTy}});
4931349cc55cSDimitry Andric }
4932349cc55cSDimitry Andric 
4933349cc55cSDimitry Andric void CombinerHelper::applyUMulHToLShr(MachineInstr &MI) {
4934349cc55cSDimitry Andric   Register LHS = MI.getOperand(1).getReg();
4935349cc55cSDimitry Andric   Register RHS = MI.getOperand(2).getReg();
4936349cc55cSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
4937349cc55cSDimitry Andric   LLT Ty = MRI.getType(Dst);
4938349cc55cSDimitry Andric   LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4939349cc55cSDimitry Andric   unsigned NumEltBits = Ty.getScalarSizeInBits();
4940349cc55cSDimitry Andric 
4941349cc55cSDimitry Andric   Builder.setInstrAndDebugLoc(MI);
4942349cc55cSDimitry Andric   auto LogBase2 = buildLogBase2(RHS, Builder);
4943349cc55cSDimitry Andric   auto ShiftAmt =
4944349cc55cSDimitry Andric       Builder.buildSub(Ty, Builder.buildConstant(Ty, NumEltBits), LogBase2);
4945349cc55cSDimitry Andric   auto Trunc = Builder.buildZExtOrTrunc(ShiftAmtTy, ShiftAmt);
4946349cc55cSDimitry Andric   Builder.buildLShr(Dst, LHS, Trunc);
4947349cc55cSDimitry Andric   MI.eraseFromParent();
4948349cc55cSDimitry Andric }
4949349cc55cSDimitry Andric 
4950349cc55cSDimitry Andric bool CombinerHelper::matchRedundantNegOperands(MachineInstr &MI,
4951349cc55cSDimitry Andric                                                BuildFnTy &MatchInfo) {
4952349cc55cSDimitry Andric   unsigned Opc = MI.getOpcode();
4953349cc55cSDimitry Andric   assert(Opc == TargetOpcode::G_FADD || Opc == TargetOpcode::G_FSUB ||
4954349cc55cSDimitry Andric          Opc == TargetOpcode::G_FMUL || Opc == TargetOpcode::G_FDIV ||
4955349cc55cSDimitry Andric          Opc == TargetOpcode::G_FMAD || Opc == TargetOpcode::G_FMA);
4956349cc55cSDimitry Andric 
4957349cc55cSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
4958349cc55cSDimitry Andric   Register X = MI.getOperand(1).getReg();
4959349cc55cSDimitry Andric   Register Y = MI.getOperand(2).getReg();
4960349cc55cSDimitry Andric   LLT Type = MRI.getType(Dst);
4961349cc55cSDimitry Andric 
4962349cc55cSDimitry Andric   // fold (fadd x, fneg(y)) -> (fsub x, y)
4963349cc55cSDimitry Andric   // fold (fadd fneg(y), x) -> (fsub x, y)
4964349cc55cSDimitry Andric   // G_ADD is commutative so both cases are checked by m_GFAdd
4965349cc55cSDimitry Andric   if (mi_match(Dst, MRI, m_GFAdd(m_Reg(X), m_GFNeg(m_Reg(Y)))) &&
4966349cc55cSDimitry Andric       isLegalOrBeforeLegalizer({TargetOpcode::G_FSUB, {Type}})) {
4967349cc55cSDimitry Andric     Opc = TargetOpcode::G_FSUB;
4968349cc55cSDimitry Andric   }
4969349cc55cSDimitry Andric   /// fold (fsub x, fneg(y)) -> (fadd x, y)
4970349cc55cSDimitry Andric   else if (mi_match(Dst, MRI, m_GFSub(m_Reg(X), m_GFNeg(m_Reg(Y)))) &&
4971349cc55cSDimitry Andric            isLegalOrBeforeLegalizer({TargetOpcode::G_FADD, {Type}})) {
4972349cc55cSDimitry Andric     Opc = TargetOpcode::G_FADD;
4973349cc55cSDimitry Andric   }
4974349cc55cSDimitry Andric   // fold (fmul fneg(x), fneg(y)) -> (fmul x, y)
4975349cc55cSDimitry Andric   // fold (fdiv fneg(x), fneg(y)) -> (fdiv x, y)
4976349cc55cSDimitry Andric   // fold (fmad fneg(x), fneg(y), z) -> (fmad x, y, z)
4977349cc55cSDimitry Andric   // fold (fma fneg(x), fneg(y), z) -> (fma x, y, z)
4978349cc55cSDimitry Andric   else if ((Opc == TargetOpcode::G_FMUL || Opc == TargetOpcode::G_FDIV ||
4979349cc55cSDimitry Andric             Opc == TargetOpcode::G_FMAD || Opc == TargetOpcode::G_FMA) &&
4980349cc55cSDimitry Andric            mi_match(X, MRI, m_GFNeg(m_Reg(X))) &&
4981349cc55cSDimitry Andric            mi_match(Y, MRI, m_GFNeg(m_Reg(Y)))) {
4982349cc55cSDimitry Andric     // no opcode change
4983349cc55cSDimitry Andric   } else
4984349cc55cSDimitry Andric     return false;
4985349cc55cSDimitry Andric 
4986349cc55cSDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4987349cc55cSDimitry Andric     Observer.changingInstr(MI);
4988349cc55cSDimitry Andric     MI.setDesc(B.getTII().get(Opc));
4989349cc55cSDimitry Andric     MI.getOperand(1).setReg(X);
4990349cc55cSDimitry Andric     MI.getOperand(2).setReg(Y);
4991349cc55cSDimitry Andric     Observer.changedInstr(MI);
4992349cc55cSDimitry Andric   };
4993349cc55cSDimitry Andric   return true;
4994349cc55cSDimitry Andric }
4995349cc55cSDimitry Andric 
49964824e7fdSDimitry Andric /// Checks if \p MI is TargetOpcode::G_FMUL and contractable either
49974824e7fdSDimitry Andric /// due to global flags or MachineInstr flags.
49984824e7fdSDimitry Andric static bool isContractableFMul(MachineInstr &MI, bool AllowFusionGlobally) {
49994824e7fdSDimitry Andric   if (MI.getOpcode() != TargetOpcode::G_FMUL)
50004824e7fdSDimitry Andric     return false;
50014824e7fdSDimitry Andric   return AllowFusionGlobally || MI.getFlag(MachineInstr::MIFlag::FmContract);
50024824e7fdSDimitry Andric }
50034824e7fdSDimitry Andric 
50044824e7fdSDimitry Andric static bool hasMoreUses(const MachineInstr &MI0, const MachineInstr &MI1,
50054824e7fdSDimitry Andric                         const MachineRegisterInfo &MRI) {
50064824e7fdSDimitry Andric   return std::distance(MRI.use_instr_nodbg_begin(MI0.getOperand(0).getReg()),
50074824e7fdSDimitry Andric                        MRI.use_instr_nodbg_end()) >
50084824e7fdSDimitry Andric          std::distance(MRI.use_instr_nodbg_begin(MI1.getOperand(0).getReg()),
50094824e7fdSDimitry Andric                        MRI.use_instr_nodbg_end());
50104824e7fdSDimitry Andric }
50114824e7fdSDimitry Andric 
50124824e7fdSDimitry Andric bool CombinerHelper::canCombineFMadOrFMA(MachineInstr &MI,
50134824e7fdSDimitry Andric                                          bool &AllowFusionGlobally,
50144824e7fdSDimitry Andric                                          bool &HasFMAD, bool &Aggressive,
50154824e7fdSDimitry Andric                                          bool CanReassociate) {
50164824e7fdSDimitry Andric 
50174824e7fdSDimitry Andric   auto *MF = MI.getMF();
50184824e7fdSDimitry Andric   const auto &TLI = *MF->getSubtarget().getTargetLowering();
50194824e7fdSDimitry Andric   const TargetOptions &Options = MF->getTarget().Options;
50204824e7fdSDimitry Andric   LLT DstType = MRI.getType(MI.getOperand(0).getReg());
50214824e7fdSDimitry Andric 
50224824e7fdSDimitry Andric   if (CanReassociate &&
50234824e7fdSDimitry Andric       !(Options.UnsafeFPMath || MI.getFlag(MachineInstr::MIFlag::FmReassoc)))
50244824e7fdSDimitry Andric     return false;
50254824e7fdSDimitry Andric 
50264824e7fdSDimitry Andric   // Floating-point multiply-add with intermediate rounding.
50274824e7fdSDimitry Andric   HasFMAD = (LI && TLI.isFMADLegal(MI, DstType));
50284824e7fdSDimitry Andric   // Floating-point multiply-add without intermediate rounding.
50294824e7fdSDimitry Andric   bool HasFMA = TLI.isFMAFasterThanFMulAndFAdd(*MF, DstType) &&
50304824e7fdSDimitry Andric                 isLegalOrBeforeLegalizer({TargetOpcode::G_FMA, {DstType}});
50314824e7fdSDimitry Andric   // No valid opcode, do not combine.
50324824e7fdSDimitry Andric   if (!HasFMAD && !HasFMA)
50334824e7fdSDimitry Andric     return false;
50344824e7fdSDimitry Andric 
50354824e7fdSDimitry Andric   AllowFusionGlobally = Options.AllowFPOpFusion == FPOpFusion::Fast ||
50364824e7fdSDimitry Andric                         Options.UnsafeFPMath || HasFMAD;
50374824e7fdSDimitry Andric   // If the addition is not contractable, do not combine.
50384824e7fdSDimitry Andric   if (!AllowFusionGlobally && !MI.getFlag(MachineInstr::MIFlag::FmContract))
50394824e7fdSDimitry Andric     return false;
50404824e7fdSDimitry Andric 
50414824e7fdSDimitry Andric   Aggressive = TLI.enableAggressiveFMAFusion(DstType);
50424824e7fdSDimitry Andric   return true;
50434824e7fdSDimitry Andric }
50444824e7fdSDimitry Andric 
50454824e7fdSDimitry Andric bool CombinerHelper::matchCombineFAddFMulToFMadOrFMA(
50464824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
50474824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FADD);
50484824e7fdSDimitry Andric 
50494824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
50504824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
50514824e7fdSDimitry Andric     return false;
50524824e7fdSDimitry Andric 
505304eeddc0SDimitry Andric   Register Op1 = MI.getOperand(1).getReg();
505404eeddc0SDimitry Andric   Register Op2 = MI.getOperand(2).getReg();
505504eeddc0SDimitry Andric   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
505604eeddc0SDimitry Andric   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
50574824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
50584824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
50594824e7fdSDimitry Andric 
50604824e7fdSDimitry Andric   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
50614824e7fdSDimitry Andric   // prefer to fold the multiply with fewer uses.
506204eeddc0SDimitry Andric   if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
506304eeddc0SDimitry Andric       isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
506404eeddc0SDimitry Andric     if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
50654824e7fdSDimitry Andric       std::swap(LHS, RHS);
50664824e7fdSDimitry Andric   }
50674824e7fdSDimitry Andric 
50684824e7fdSDimitry Andric   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
506904eeddc0SDimitry Andric   if (isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
507004eeddc0SDimitry Andric       (Aggressive || MRI.hasOneNonDBGUse(LHS.Reg))) {
50714824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
50724824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
507304eeddc0SDimitry Andric                    {LHS.MI->getOperand(1).getReg(),
507404eeddc0SDimitry Andric                     LHS.MI->getOperand(2).getReg(), RHS.Reg});
50754824e7fdSDimitry Andric     };
50764824e7fdSDimitry Andric     return true;
50774824e7fdSDimitry Andric   }
50784824e7fdSDimitry Andric 
50794824e7fdSDimitry Andric   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
508004eeddc0SDimitry Andric   if (isContractableFMul(*RHS.MI, AllowFusionGlobally) &&
508104eeddc0SDimitry Andric       (Aggressive || MRI.hasOneNonDBGUse(RHS.Reg))) {
50824824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
50834824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
508404eeddc0SDimitry Andric                    {RHS.MI->getOperand(1).getReg(),
508504eeddc0SDimitry Andric                     RHS.MI->getOperand(2).getReg(), LHS.Reg});
50864824e7fdSDimitry Andric     };
50874824e7fdSDimitry Andric     return true;
50884824e7fdSDimitry Andric   }
50894824e7fdSDimitry Andric 
50904824e7fdSDimitry Andric   return false;
50914824e7fdSDimitry Andric }
50924824e7fdSDimitry Andric 
50934824e7fdSDimitry Andric bool CombinerHelper::matchCombineFAddFpExtFMulToFMadOrFMA(
50944824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
50954824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FADD);
50964824e7fdSDimitry Andric 
50974824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
50984824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
50994824e7fdSDimitry Andric     return false;
51004824e7fdSDimitry Andric 
51014824e7fdSDimitry Andric   const auto &TLI = *MI.getMF()->getSubtarget().getTargetLowering();
510204eeddc0SDimitry Andric   Register Op1 = MI.getOperand(1).getReg();
510304eeddc0SDimitry Andric   Register Op2 = MI.getOperand(2).getReg();
510404eeddc0SDimitry Andric   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
510504eeddc0SDimitry Andric   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
51064824e7fdSDimitry Andric   LLT DstType = MRI.getType(MI.getOperand(0).getReg());
51074824e7fdSDimitry Andric 
51084824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
51094824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
51104824e7fdSDimitry Andric 
51114824e7fdSDimitry Andric   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
51124824e7fdSDimitry Andric   // prefer to fold the multiply with fewer uses.
511304eeddc0SDimitry Andric   if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
511404eeddc0SDimitry Andric       isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
511504eeddc0SDimitry Andric     if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
51164824e7fdSDimitry Andric       std::swap(LHS, RHS);
51174824e7fdSDimitry Andric   }
51184824e7fdSDimitry Andric 
51194824e7fdSDimitry Andric   // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
51204824e7fdSDimitry Andric   MachineInstr *FpExtSrc;
512104eeddc0SDimitry Andric   if (mi_match(LHS.Reg, MRI, m_GFPExt(m_MInstr(FpExtSrc))) &&
51224824e7fdSDimitry Andric       isContractableFMul(*FpExtSrc, AllowFusionGlobally) &&
51234824e7fdSDimitry Andric       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
51244824e7fdSDimitry Andric                           MRI.getType(FpExtSrc->getOperand(1).getReg()))) {
51254824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
51264824e7fdSDimitry Andric       auto FpExtX = B.buildFPExt(DstType, FpExtSrc->getOperand(1).getReg());
51274824e7fdSDimitry Andric       auto FpExtY = B.buildFPExt(DstType, FpExtSrc->getOperand(2).getReg());
512804eeddc0SDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
512904eeddc0SDimitry Andric                    {FpExtX.getReg(0), FpExtY.getReg(0), RHS.Reg});
51304824e7fdSDimitry Andric     };
51314824e7fdSDimitry Andric     return true;
51324824e7fdSDimitry Andric   }
51334824e7fdSDimitry Andric 
51344824e7fdSDimitry Andric   // fold (fadd z, (fpext (fmul x, y))) -> (fma (fpext x), (fpext y), z)
51354824e7fdSDimitry Andric   // Note: Commutes FADD operands.
513604eeddc0SDimitry Andric   if (mi_match(RHS.Reg, MRI, m_GFPExt(m_MInstr(FpExtSrc))) &&
51374824e7fdSDimitry Andric       isContractableFMul(*FpExtSrc, AllowFusionGlobally) &&
51384824e7fdSDimitry Andric       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
51394824e7fdSDimitry Andric                           MRI.getType(FpExtSrc->getOperand(1).getReg()))) {
51404824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
51414824e7fdSDimitry Andric       auto FpExtX = B.buildFPExt(DstType, FpExtSrc->getOperand(1).getReg());
51424824e7fdSDimitry Andric       auto FpExtY = B.buildFPExt(DstType, FpExtSrc->getOperand(2).getReg());
514304eeddc0SDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
514404eeddc0SDimitry Andric                    {FpExtX.getReg(0), FpExtY.getReg(0), LHS.Reg});
51454824e7fdSDimitry Andric     };
51464824e7fdSDimitry Andric     return true;
51474824e7fdSDimitry Andric   }
51484824e7fdSDimitry Andric 
51494824e7fdSDimitry Andric   return false;
51504824e7fdSDimitry Andric }
51514824e7fdSDimitry Andric 
51524824e7fdSDimitry Andric bool CombinerHelper::matchCombineFAddFMAFMulToFMadOrFMA(
51534824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
51544824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FADD);
51554824e7fdSDimitry Andric 
51564824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
51574824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive, true))
51584824e7fdSDimitry Andric     return false;
51594824e7fdSDimitry Andric 
516004eeddc0SDimitry Andric   Register Op1 = MI.getOperand(1).getReg();
516104eeddc0SDimitry Andric   Register Op2 = MI.getOperand(2).getReg();
516204eeddc0SDimitry Andric   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
516304eeddc0SDimitry Andric   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
51644824e7fdSDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
51654824e7fdSDimitry Andric 
51664824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
51674824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
51684824e7fdSDimitry Andric 
51694824e7fdSDimitry Andric   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
51704824e7fdSDimitry Andric   // prefer to fold the multiply with fewer uses.
517104eeddc0SDimitry Andric   if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
517204eeddc0SDimitry Andric       isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
517304eeddc0SDimitry Andric     if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
51744824e7fdSDimitry Andric       std::swap(LHS, RHS);
51754824e7fdSDimitry Andric   }
51764824e7fdSDimitry Andric 
51774824e7fdSDimitry Andric   MachineInstr *FMA = nullptr;
51784824e7fdSDimitry Andric   Register Z;
51794824e7fdSDimitry Andric   // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y, (fma u, v, z))
518004eeddc0SDimitry Andric   if (LHS.MI->getOpcode() == PreferredFusedOpcode &&
518104eeddc0SDimitry Andric       (MRI.getVRegDef(LHS.MI->getOperand(3).getReg())->getOpcode() ==
51824824e7fdSDimitry Andric        TargetOpcode::G_FMUL) &&
518304eeddc0SDimitry Andric       MRI.hasOneNonDBGUse(LHS.MI->getOperand(0).getReg()) &&
518404eeddc0SDimitry Andric       MRI.hasOneNonDBGUse(LHS.MI->getOperand(3).getReg())) {
518504eeddc0SDimitry Andric     FMA = LHS.MI;
518604eeddc0SDimitry Andric     Z = RHS.Reg;
51874824e7fdSDimitry Andric   }
51884824e7fdSDimitry Andric   // fold (fadd z, (fma x, y, (fmul u, v))) -> (fma x, y, (fma u, v, z))
518904eeddc0SDimitry Andric   else if (RHS.MI->getOpcode() == PreferredFusedOpcode &&
519004eeddc0SDimitry Andric            (MRI.getVRegDef(RHS.MI->getOperand(3).getReg())->getOpcode() ==
51914824e7fdSDimitry Andric             TargetOpcode::G_FMUL) &&
519204eeddc0SDimitry Andric            MRI.hasOneNonDBGUse(RHS.MI->getOperand(0).getReg()) &&
519304eeddc0SDimitry Andric            MRI.hasOneNonDBGUse(RHS.MI->getOperand(3).getReg())) {
519404eeddc0SDimitry Andric     Z = LHS.Reg;
519504eeddc0SDimitry Andric     FMA = RHS.MI;
51964824e7fdSDimitry Andric   }
51974824e7fdSDimitry Andric 
51984824e7fdSDimitry Andric   if (FMA) {
51994824e7fdSDimitry Andric     MachineInstr *FMulMI = MRI.getVRegDef(FMA->getOperand(3).getReg());
52004824e7fdSDimitry Andric     Register X = FMA->getOperand(1).getReg();
52014824e7fdSDimitry Andric     Register Y = FMA->getOperand(2).getReg();
52024824e7fdSDimitry Andric     Register U = FMulMI->getOperand(1).getReg();
52034824e7fdSDimitry Andric     Register V = FMulMI->getOperand(2).getReg();
52044824e7fdSDimitry Andric 
52054824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
52064824e7fdSDimitry Andric       Register InnerFMA = MRI.createGenericVirtualRegister(DstTy);
52074824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {InnerFMA}, {U, V, Z});
52084824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
52094824e7fdSDimitry Andric                    {X, Y, InnerFMA});
52104824e7fdSDimitry Andric     };
52114824e7fdSDimitry Andric     return true;
52124824e7fdSDimitry Andric   }
52134824e7fdSDimitry Andric 
52144824e7fdSDimitry Andric   return false;
52154824e7fdSDimitry Andric }
52164824e7fdSDimitry Andric 
52174824e7fdSDimitry Andric bool CombinerHelper::matchCombineFAddFpExtFMulToFMadOrFMAAggressive(
52184824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
52194824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FADD);
52204824e7fdSDimitry Andric 
52214824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
52224824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
52234824e7fdSDimitry Andric     return false;
52244824e7fdSDimitry Andric 
52254824e7fdSDimitry Andric   if (!Aggressive)
52264824e7fdSDimitry Andric     return false;
52274824e7fdSDimitry Andric 
52284824e7fdSDimitry Andric   const auto &TLI = *MI.getMF()->getSubtarget().getTargetLowering();
52294824e7fdSDimitry Andric   LLT DstType = MRI.getType(MI.getOperand(0).getReg());
523004eeddc0SDimitry Andric   Register Op1 = MI.getOperand(1).getReg();
523104eeddc0SDimitry Andric   Register Op2 = MI.getOperand(2).getReg();
523204eeddc0SDimitry Andric   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
523304eeddc0SDimitry Andric   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
52344824e7fdSDimitry Andric 
52354824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
52364824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
52374824e7fdSDimitry Andric 
52384824e7fdSDimitry Andric   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
52394824e7fdSDimitry Andric   // prefer to fold the multiply with fewer uses.
524004eeddc0SDimitry Andric   if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
524104eeddc0SDimitry Andric       isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
524204eeddc0SDimitry Andric     if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
52434824e7fdSDimitry Andric       std::swap(LHS, RHS);
52444824e7fdSDimitry Andric   }
52454824e7fdSDimitry Andric 
52464824e7fdSDimitry Andric   // Builds: (fma x, y, (fma (fpext u), (fpext v), z))
52474824e7fdSDimitry Andric   auto buildMatchInfo = [=, &MI](Register U, Register V, Register Z, Register X,
52484824e7fdSDimitry Andric                                  Register Y, MachineIRBuilder &B) {
52494824e7fdSDimitry Andric     Register FpExtU = B.buildFPExt(DstType, U).getReg(0);
52504824e7fdSDimitry Andric     Register FpExtV = B.buildFPExt(DstType, V).getReg(0);
52514824e7fdSDimitry Andric     Register InnerFMA =
52524824e7fdSDimitry Andric         B.buildInstr(PreferredFusedOpcode, {DstType}, {FpExtU, FpExtV, Z})
52534824e7fdSDimitry Andric             .getReg(0);
52544824e7fdSDimitry Andric     B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
52554824e7fdSDimitry Andric                  {X, Y, InnerFMA});
52564824e7fdSDimitry Andric   };
52574824e7fdSDimitry Andric 
52584824e7fdSDimitry Andric   MachineInstr *FMulMI, *FMAMI;
52594824e7fdSDimitry Andric   // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
52604824e7fdSDimitry Andric   //   -> (fma x, y, (fma (fpext u), (fpext v), z))
526104eeddc0SDimitry Andric   if (LHS.MI->getOpcode() == PreferredFusedOpcode &&
526204eeddc0SDimitry Andric       mi_match(LHS.MI->getOperand(3).getReg(), MRI,
526304eeddc0SDimitry Andric                m_GFPExt(m_MInstr(FMulMI))) &&
52644824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
52654824e7fdSDimitry Andric       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
52664824e7fdSDimitry Andric                           MRI.getType(FMulMI->getOperand(0).getReg()))) {
52674824e7fdSDimitry Andric     MatchInfo = [=](MachineIRBuilder &B) {
52684824e7fdSDimitry Andric       buildMatchInfo(FMulMI->getOperand(1).getReg(),
526904eeddc0SDimitry Andric                      FMulMI->getOperand(2).getReg(), RHS.Reg,
527004eeddc0SDimitry Andric                      LHS.MI->getOperand(1).getReg(),
527104eeddc0SDimitry Andric                      LHS.MI->getOperand(2).getReg(), B);
52724824e7fdSDimitry Andric     };
52734824e7fdSDimitry Andric     return true;
52744824e7fdSDimitry Andric   }
52754824e7fdSDimitry Andric 
52764824e7fdSDimitry Andric   // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
52774824e7fdSDimitry Andric   //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
52784824e7fdSDimitry Andric   // FIXME: This turns two single-precision and one double-precision
52794824e7fdSDimitry Andric   // operation into two double-precision operations, which might not be
52804824e7fdSDimitry Andric   // interesting for all targets, especially GPUs.
528104eeddc0SDimitry Andric   if (mi_match(LHS.Reg, MRI, m_GFPExt(m_MInstr(FMAMI))) &&
52824824e7fdSDimitry Andric       FMAMI->getOpcode() == PreferredFusedOpcode) {
52834824e7fdSDimitry Andric     MachineInstr *FMulMI = MRI.getVRegDef(FMAMI->getOperand(3).getReg());
52844824e7fdSDimitry Andric     if (isContractableFMul(*FMulMI, AllowFusionGlobally) &&
52854824e7fdSDimitry Andric         TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
52864824e7fdSDimitry Andric                             MRI.getType(FMAMI->getOperand(0).getReg()))) {
52874824e7fdSDimitry Andric       MatchInfo = [=](MachineIRBuilder &B) {
52884824e7fdSDimitry Andric         Register X = FMAMI->getOperand(1).getReg();
52894824e7fdSDimitry Andric         Register Y = FMAMI->getOperand(2).getReg();
52904824e7fdSDimitry Andric         X = B.buildFPExt(DstType, X).getReg(0);
52914824e7fdSDimitry Andric         Y = B.buildFPExt(DstType, Y).getReg(0);
52924824e7fdSDimitry Andric         buildMatchInfo(FMulMI->getOperand(1).getReg(),
529304eeddc0SDimitry Andric                        FMulMI->getOperand(2).getReg(), RHS.Reg, X, Y, B);
52944824e7fdSDimitry Andric       };
52954824e7fdSDimitry Andric 
52964824e7fdSDimitry Andric       return true;
52974824e7fdSDimitry Andric     }
52984824e7fdSDimitry Andric   }
52994824e7fdSDimitry Andric 
53004824e7fdSDimitry Andric   // fold (fadd z, (fma x, y, (fpext (fmul u, v)))
53014824e7fdSDimitry Andric   //   -> (fma x, y, (fma (fpext u), (fpext v), z))
530204eeddc0SDimitry Andric   if (RHS.MI->getOpcode() == PreferredFusedOpcode &&
530304eeddc0SDimitry Andric       mi_match(RHS.MI->getOperand(3).getReg(), MRI,
530404eeddc0SDimitry Andric                m_GFPExt(m_MInstr(FMulMI))) &&
53054824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
53064824e7fdSDimitry Andric       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
53074824e7fdSDimitry Andric                           MRI.getType(FMulMI->getOperand(0).getReg()))) {
53084824e7fdSDimitry Andric     MatchInfo = [=](MachineIRBuilder &B) {
53094824e7fdSDimitry Andric       buildMatchInfo(FMulMI->getOperand(1).getReg(),
531004eeddc0SDimitry Andric                      FMulMI->getOperand(2).getReg(), LHS.Reg,
531104eeddc0SDimitry Andric                      RHS.MI->getOperand(1).getReg(),
531204eeddc0SDimitry Andric                      RHS.MI->getOperand(2).getReg(), B);
53134824e7fdSDimitry Andric     };
53144824e7fdSDimitry Andric     return true;
53154824e7fdSDimitry Andric   }
53164824e7fdSDimitry Andric 
53174824e7fdSDimitry Andric   // fold (fadd z, (fpext (fma x, y, (fmul u, v)))
53184824e7fdSDimitry Andric   //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
53194824e7fdSDimitry Andric   // FIXME: This turns two single-precision and one double-precision
53204824e7fdSDimitry Andric   // operation into two double-precision operations, which might not be
53214824e7fdSDimitry Andric   // interesting for all targets, especially GPUs.
532204eeddc0SDimitry Andric   if (mi_match(RHS.Reg, MRI, m_GFPExt(m_MInstr(FMAMI))) &&
53234824e7fdSDimitry Andric       FMAMI->getOpcode() == PreferredFusedOpcode) {
53244824e7fdSDimitry Andric     MachineInstr *FMulMI = MRI.getVRegDef(FMAMI->getOperand(3).getReg());
53254824e7fdSDimitry Andric     if (isContractableFMul(*FMulMI, AllowFusionGlobally) &&
53264824e7fdSDimitry Andric         TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
53274824e7fdSDimitry Andric                             MRI.getType(FMAMI->getOperand(0).getReg()))) {
53284824e7fdSDimitry Andric       MatchInfo = [=](MachineIRBuilder &B) {
53294824e7fdSDimitry Andric         Register X = FMAMI->getOperand(1).getReg();
53304824e7fdSDimitry Andric         Register Y = FMAMI->getOperand(2).getReg();
53314824e7fdSDimitry Andric         X = B.buildFPExt(DstType, X).getReg(0);
53324824e7fdSDimitry Andric         Y = B.buildFPExt(DstType, Y).getReg(0);
53334824e7fdSDimitry Andric         buildMatchInfo(FMulMI->getOperand(1).getReg(),
533404eeddc0SDimitry Andric                        FMulMI->getOperand(2).getReg(), LHS.Reg, X, Y, B);
53354824e7fdSDimitry Andric       };
53364824e7fdSDimitry Andric       return true;
53374824e7fdSDimitry Andric     }
53384824e7fdSDimitry Andric   }
53394824e7fdSDimitry Andric 
53404824e7fdSDimitry Andric   return false;
53414824e7fdSDimitry Andric }
53424824e7fdSDimitry Andric 
53434824e7fdSDimitry Andric bool CombinerHelper::matchCombineFSubFMulToFMadOrFMA(
53444824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
53454824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FSUB);
53464824e7fdSDimitry Andric 
53474824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
53484824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
53494824e7fdSDimitry Andric     return false;
53504824e7fdSDimitry Andric 
535104eeddc0SDimitry Andric   Register Op1 = MI.getOperand(1).getReg();
535204eeddc0SDimitry Andric   Register Op2 = MI.getOperand(2).getReg();
535304eeddc0SDimitry Andric   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
535404eeddc0SDimitry Andric   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
53554824e7fdSDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
53564824e7fdSDimitry Andric 
53574824e7fdSDimitry Andric   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
53584824e7fdSDimitry Andric   // prefer to fold the multiply with fewer uses.
53594824e7fdSDimitry Andric   int FirstMulHasFewerUses = true;
536004eeddc0SDimitry Andric   if (isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
536104eeddc0SDimitry Andric       isContractableFMul(*RHS.MI, AllowFusionGlobally) &&
536204eeddc0SDimitry Andric       hasMoreUses(*LHS.MI, *RHS.MI, MRI))
53634824e7fdSDimitry Andric     FirstMulHasFewerUses = false;
53644824e7fdSDimitry Andric 
53654824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
53664824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
53674824e7fdSDimitry Andric 
53684824e7fdSDimitry Andric   // fold (fsub (fmul x, y), z) -> (fma x, y, -z)
53694824e7fdSDimitry Andric   if (FirstMulHasFewerUses &&
537004eeddc0SDimitry Andric       (isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
537104eeddc0SDimitry Andric        (Aggressive || MRI.hasOneNonDBGUse(LHS.Reg)))) {
53724824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
537304eeddc0SDimitry Andric       Register NegZ = B.buildFNeg(DstTy, RHS.Reg).getReg(0);
537404eeddc0SDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
537504eeddc0SDimitry Andric                    {LHS.MI->getOperand(1).getReg(),
537604eeddc0SDimitry Andric                     LHS.MI->getOperand(2).getReg(), NegZ});
53774824e7fdSDimitry Andric     };
53784824e7fdSDimitry Andric     return true;
53794824e7fdSDimitry Andric   }
53804824e7fdSDimitry Andric   // fold (fsub x, (fmul y, z)) -> (fma -y, z, x)
538104eeddc0SDimitry Andric   else if ((isContractableFMul(*RHS.MI, AllowFusionGlobally) &&
538204eeddc0SDimitry Andric             (Aggressive || MRI.hasOneNonDBGUse(RHS.Reg)))) {
53834824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
538404eeddc0SDimitry Andric       Register NegY =
538504eeddc0SDimitry Andric           B.buildFNeg(DstTy, RHS.MI->getOperand(1).getReg()).getReg(0);
538604eeddc0SDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
538704eeddc0SDimitry Andric                    {NegY, RHS.MI->getOperand(2).getReg(), LHS.Reg});
53884824e7fdSDimitry Andric     };
53894824e7fdSDimitry Andric     return true;
53904824e7fdSDimitry Andric   }
53914824e7fdSDimitry Andric 
53924824e7fdSDimitry Andric   return false;
53934824e7fdSDimitry Andric }
53944824e7fdSDimitry Andric 
53954824e7fdSDimitry Andric bool CombinerHelper::matchCombineFSubFNegFMulToFMadOrFMA(
53964824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
53974824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FSUB);
53984824e7fdSDimitry Andric 
53994824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
54004824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
54014824e7fdSDimitry Andric     return false;
54024824e7fdSDimitry Andric 
54034824e7fdSDimitry Andric   Register LHSReg = MI.getOperand(1).getReg();
54044824e7fdSDimitry Andric   Register RHSReg = MI.getOperand(2).getReg();
54054824e7fdSDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
54064824e7fdSDimitry Andric 
54074824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
54084824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
54094824e7fdSDimitry Andric 
54104824e7fdSDimitry Andric   MachineInstr *FMulMI;
54114824e7fdSDimitry Andric   // fold (fsub (fneg (fmul x, y)), z) -> (fma (fneg x), y, (fneg z))
54124824e7fdSDimitry Andric   if (mi_match(LHSReg, MRI, m_GFNeg(m_MInstr(FMulMI))) &&
54134824e7fdSDimitry Andric       (Aggressive || (MRI.hasOneNonDBGUse(LHSReg) &&
54144824e7fdSDimitry Andric                       MRI.hasOneNonDBGUse(FMulMI->getOperand(0).getReg()))) &&
54154824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally)) {
54164824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
54174824e7fdSDimitry Andric       Register NegX =
54184824e7fdSDimitry Andric           B.buildFNeg(DstTy, FMulMI->getOperand(1).getReg()).getReg(0);
54194824e7fdSDimitry Andric       Register NegZ = B.buildFNeg(DstTy, RHSReg).getReg(0);
54204824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
54214824e7fdSDimitry Andric                    {NegX, FMulMI->getOperand(2).getReg(), NegZ});
54224824e7fdSDimitry Andric     };
54234824e7fdSDimitry Andric     return true;
54244824e7fdSDimitry Andric   }
54254824e7fdSDimitry Andric 
54264824e7fdSDimitry Andric   // fold (fsub x, (fneg (fmul, y, z))) -> (fma y, z, x)
54274824e7fdSDimitry Andric   if (mi_match(RHSReg, MRI, m_GFNeg(m_MInstr(FMulMI))) &&
54284824e7fdSDimitry Andric       (Aggressive || (MRI.hasOneNonDBGUse(RHSReg) &&
54294824e7fdSDimitry Andric                       MRI.hasOneNonDBGUse(FMulMI->getOperand(0).getReg()))) &&
54304824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally)) {
54314824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
54324824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
54334824e7fdSDimitry Andric                    {FMulMI->getOperand(1).getReg(),
54344824e7fdSDimitry Andric                     FMulMI->getOperand(2).getReg(), LHSReg});
54354824e7fdSDimitry Andric     };
54364824e7fdSDimitry Andric     return true;
54374824e7fdSDimitry Andric   }
54384824e7fdSDimitry Andric 
54394824e7fdSDimitry Andric   return false;
54404824e7fdSDimitry Andric }
54414824e7fdSDimitry Andric 
54424824e7fdSDimitry Andric bool CombinerHelper::matchCombineFSubFpExtFMulToFMadOrFMA(
54434824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
54444824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FSUB);
54454824e7fdSDimitry Andric 
54464824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
54474824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
54484824e7fdSDimitry Andric     return false;
54494824e7fdSDimitry Andric 
54504824e7fdSDimitry Andric   Register LHSReg = MI.getOperand(1).getReg();
54514824e7fdSDimitry Andric   Register RHSReg = MI.getOperand(2).getReg();
54524824e7fdSDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
54534824e7fdSDimitry Andric 
54544824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
54554824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
54564824e7fdSDimitry Andric 
54574824e7fdSDimitry Andric   MachineInstr *FMulMI;
54584824e7fdSDimitry Andric   // fold (fsub (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), (fneg z))
54594824e7fdSDimitry Andric   if (mi_match(LHSReg, MRI, m_GFPExt(m_MInstr(FMulMI))) &&
54604824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
54614824e7fdSDimitry Andric       (Aggressive || MRI.hasOneNonDBGUse(LHSReg))) {
54624824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
54634824e7fdSDimitry Andric       Register FpExtX =
54644824e7fdSDimitry Andric           B.buildFPExt(DstTy, FMulMI->getOperand(1).getReg()).getReg(0);
54654824e7fdSDimitry Andric       Register FpExtY =
54664824e7fdSDimitry Andric           B.buildFPExt(DstTy, FMulMI->getOperand(2).getReg()).getReg(0);
54674824e7fdSDimitry Andric       Register NegZ = B.buildFNeg(DstTy, RHSReg).getReg(0);
54684824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
54694824e7fdSDimitry Andric                    {FpExtX, FpExtY, NegZ});
54704824e7fdSDimitry Andric     };
54714824e7fdSDimitry Andric     return true;
54724824e7fdSDimitry Andric   }
54734824e7fdSDimitry Andric 
54744824e7fdSDimitry Andric   // fold (fsub x, (fpext (fmul y, z))) -> (fma (fneg (fpext y)), (fpext z), x)
54754824e7fdSDimitry Andric   if (mi_match(RHSReg, MRI, m_GFPExt(m_MInstr(FMulMI))) &&
54764824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
54774824e7fdSDimitry Andric       (Aggressive || MRI.hasOneNonDBGUse(RHSReg))) {
54784824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
54794824e7fdSDimitry Andric       Register FpExtY =
54804824e7fdSDimitry Andric           B.buildFPExt(DstTy, FMulMI->getOperand(1).getReg()).getReg(0);
54814824e7fdSDimitry Andric       Register NegY = B.buildFNeg(DstTy, FpExtY).getReg(0);
54824824e7fdSDimitry Andric       Register FpExtZ =
54834824e7fdSDimitry Andric           B.buildFPExt(DstTy, FMulMI->getOperand(2).getReg()).getReg(0);
54844824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
54854824e7fdSDimitry Andric                    {NegY, FpExtZ, LHSReg});
54864824e7fdSDimitry Andric     };
54874824e7fdSDimitry Andric     return true;
54884824e7fdSDimitry Andric   }
54894824e7fdSDimitry Andric 
54904824e7fdSDimitry Andric   return false;
54914824e7fdSDimitry Andric }
54924824e7fdSDimitry Andric 
54934824e7fdSDimitry Andric bool CombinerHelper::matchCombineFSubFpExtFNegFMulToFMadOrFMA(
54944824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
54954824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FSUB);
54964824e7fdSDimitry Andric 
54974824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
54984824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
54994824e7fdSDimitry Andric     return false;
55004824e7fdSDimitry Andric 
55014824e7fdSDimitry Andric   const auto &TLI = *MI.getMF()->getSubtarget().getTargetLowering();
55024824e7fdSDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
55034824e7fdSDimitry Andric   Register LHSReg = MI.getOperand(1).getReg();
55044824e7fdSDimitry Andric   Register RHSReg = MI.getOperand(2).getReg();
55054824e7fdSDimitry Andric 
55064824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
55074824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
55084824e7fdSDimitry Andric 
55094824e7fdSDimitry Andric   auto buildMatchInfo = [=](Register Dst, Register X, Register Y, Register Z,
55104824e7fdSDimitry Andric                             MachineIRBuilder &B) {
55114824e7fdSDimitry Andric     Register FpExtX = B.buildFPExt(DstTy, X).getReg(0);
55124824e7fdSDimitry Andric     Register FpExtY = B.buildFPExt(DstTy, Y).getReg(0);
55134824e7fdSDimitry Andric     B.buildInstr(PreferredFusedOpcode, {Dst}, {FpExtX, FpExtY, Z});
55144824e7fdSDimitry Andric   };
55154824e7fdSDimitry Andric 
55164824e7fdSDimitry Andric   MachineInstr *FMulMI;
55174824e7fdSDimitry Andric   // fold (fsub (fpext (fneg (fmul x, y))), z) ->
55184824e7fdSDimitry Andric   //      (fneg (fma (fpext x), (fpext y), z))
55194824e7fdSDimitry Andric   // fold (fsub (fneg (fpext (fmul x, y))), z) ->
55204824e7fdSDimitry Andric   //      (fneg (fma (fpext x), (fpext y), z))
55214824e7fdSDimitry Andric   if ((mi_match(LHSReg, MRI, m_GFPExt(m_GFNeg(m_MInstr(FMulMI)))) ||
55224824e7fdSDimitry Andric        mi_match(LHSReg, MRI, m_GFNeg(m_GFPExt(m_MInstr(FMulMI))))) &&
55234824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
55244824e7fdSDimitry Andric       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstTy,
55254824e7fdSDimitry Andric                           MRI.getType(FMulMI->getOperand(0).getReg()))) {
55264824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
55274824e7fdSDimitry Andric       Register FMAReg = MRI.createGenericVirtualRegister(DstTy);
55284824e7fdSDimitry Andric       buildMatchInfo(FMAReg, FMulMI->getOperand(1).getReg(),
55294824e7fdSDimitry Andric                      FMulMI->getOperand(2).getReg(), RHSReg, B);
55304824e7fdSDimitry Andric       B.buildFNeg(MI.getOperand(0).getReg(), FMAReg);
55314824e7fdSDimitry Andric     };
55324824e7fdSDimitry Andric     return true;
55334824e7fdSDimitry Andric   }
55344824e7fdSDimitry Andric 
55354824e7fdSDimitry Andric   // fold (fsub x, (fpext (fneg (fmul y, z)))) -> (fma (fpext y), (fpext z), x)
55364824e7fdSDimitry Andric   // fold (fsub x, (fneg (fpext (fmul y, z)))) -> (fma (fpext y), (fpext z), x)
55374824e7fdSDimitry Andric   if ((mi_match(RHSReg, MRI, m_GFPExt(m_GFNeg(m_MInstr(FMulMI)))) ||
55384824e7fdSDimitry Andric        mi_match(RHSReg, MRI, m_GFNeg(m_GFPExt(m_MInstr(FMulMI))))) &&
55394824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
55404824e7fdSDimitry Andric       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstTy,
55414824e7fdSDimitry Andric                           MRI.getType(FMulMI->getOperand(0).getReg()))) {
55424824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
55434824e7fdSDimitry Andric       buildMatchInfo(MI.getOperand(0).getReg(), FMulMI->getOperand(1).getReg(),
55444824e7fdSDimitry Andric                      FMulMI->getOperand(2).getReg(), LHSReg, B);
55454824e7fdSDimitry Andric     };
55464824e7fdSDimitry Andric     return true;
55474824e7fdSDimitry Andric   }
55484824e7fdSDimitry Andric 
55494824e7fdSDimitry Andric   return false;
55504824e7fdSDimitry Andric }
55514824e7fdSDimitry Andric 
5552*81ad6265SDimitry Andric bool CombinerHelper::matchSelectToLogical(MachineInstr &MI,
5553*81ad6265SDimitry Andric                                           BuildFnTy &MatchInfo) {
5554*81ad6265SDimitry Andric   GSelect &Sel = cast<GSelect>(MI);
5555*81ad6265SDimitry Andric   Register DstReg = Sel.getReg(0);
5556*81ad6265SDimitry Andric   Register Cond = Sel.getCondReg();
5557*81ad6265SDimitry Andric   Register TrueReg = Sel.getTrueReg();
5558*81ad6265SDimitry Andric   Register FalseReg = Sel.getFalseReg();
5559*81ad6265SDimitry Andric 
5560*81ad6265SDimitry Andric   auto *TrueDef = getDefIgnoringCopies(TrueReg, MRI);
5561*81ad6265SDimitry Andric   auto *FalseDef = getDefIgnoringCopies(FalseReg, MRI);
5562*81ad6265SDimitry Andric 
5563*81ad6265SDimitry Andric   const LLT CondTy = MRI.getType(Cond);
5564*81ad6265SDimitry Andric   const LLT OpTy = MRI.getType(TrueReg);
5565*81ad6265SDimitry Andric   if (CondTy != OpTy || OpTy.getScalarSizeInBits() != 1)
5566*81ad6265SDimitry Andric     return false;
5567*81ad6265SDimitry Andric 
5568*81ad6265SDimitry Andric   // We have a boolean select.
5569*81ad6265SDimitry Andric 
5570*81ad6265SDimitry Andric   // select Cond, Cond, F --> or Cond, F
5571*81ad6265SDimitry Andric   // select Cond, 1, F    --> or Cond, F
5572*81ad6265SDimitry Andric   auto MaybeCstTrue = isConstantOrConstantSplatVector(*TrueDef, MRI);
5573*81ad6265SDimitry Andric   if (Cond == TrueReg || (MaybeCstTrue && MaybeCstTrue->isOne())) {
5574*81ad6265SDimitry Andric     MatchInfo = [=](MachineIRBuilder &MIB) {
5575*81ad6265SDimitry Andric       MIB.buildOr(DstReg, Cond, FalseReg);
5576*81ad6265SDimitry Andric     };
5577*81ad6265SDimitry Andric     return true;
5578*81ad6265SDimitry Andric   }
5579*81ad6265SDimitry Andric 
5580*81ad6265SDimitry Andric   // select Cond, T, Cond --> and Cond, T
5581*81ad6265SDimitry Andric   // select Cond, T, 0    --> and Cond, T
5582*81ad6265SDimitry Andric   auto MaybeCstFalse = isConstantOrConstantSplatVector(*FalseDef, MRI);
5583*81ad6265SDimitry Andric   if (Cond == FalseReg || (MaybeCstFalse && MaybeCstFalse->isZero())) {
5584*81ad6265SDimitry Andric     MatchInfo = [=](MachineIRBuilder &MIB) {
5585*81ad6265SDimitry Andric       MIB.buildAnd(DstReg, Cond, TrueReg);
5586*81ad6265SDimitry Andric     };
5587*81ad6265SDimitry Andric     return true;
5588*81ad6265SDimitry Andric   }
5589*81ad6265SDimitry Andric 
5590*81ad6265SDimitry Andric  // select Cond, T, 1 --> or (not Cond), T
5591*81ad6265SDimitry Andric   if (MaybeCstFalse && MaybeCstFalse->isOne()) {
5592*81ad6265SDimitry Andric     MatchInfo = [=](MachineIRBuilder &MIB) {
5593*81ad6265SDimitry Andric       MIB.buildOr(DstReg, MIB.buildNot(OpTy, Cond), TrueReg);
5594*81ad6265SDimitry Andric     };
5595*81ad6265SDimitry Andric     return true;
5596*81ad6265SDimitry Andric   }
5597*81ad6265SDimitry Andric 
5598*81ad6265SDimitry Andric   // select Cond, 0, F --> and (not Cond), F
5599*81ad6265SDimitry Andric   if (MaybeCstTrue && MaybeCstTrue->isZero()) {
5600*81ad6265SDimitry Andric     MatchInfo = [=](MachineIRBuilder &MIB) {
5601*81ad6265SDimitry Andric       MIB.buildAnd(DstReg, MIB.buildNot(OpTy, Cond), FalseReg);
5602*81ad6265SDimitry Andric     };
5603*81ad6265SDimitry Andric     return true;
5604*81ad6265SDimitry Andric   }
5605*81ad6265SDimitry Andric   return false;
5606*81ad6265SDimitry Andric }
5607*81ad6265SDimitry Andric 
5608*81ad6265SDimitry Andric bool CombinerHelper::matchCombineFMinMaxNaN(MachineInstr &MI,
5609*81ad6265SDimitry Andric                                             unsigned &IdxToPropagate) {
5610*81ad6265SDimitry Andric   bool PropagateNaN;
5611*81ad6265SDimitry Andric   switch (MI.getOpcode()) {
5612*81ad6265SDimitry Andric   default:
5613*81ad6265SDimitry Andric     return false;
5614*81ad6265SDimitry Andric   case TargetOpcode::G_FMINNUM:
5615*81ad6265SDimitry Andric   case TargetOpcode::G_FMAXNUM:
5616*81ad6265SDimitry Andric     PropagateNaN = false;
5617*81ad6265SDimitry Andric     break;
5618*81ad6265SDimitry Andric   case TargetOpcode::G_FMINIMUM:
5619*81ad6265SDimitry Andric   case TargetOpcode::G_FMAXIMUM:
5620*81ad6265SDimitry Andric     PropagateNaN = true;
5621*81ad6265SDimitry Andric     break;
5622*81ad6265SDimitry Andric   }
5623*81ad6265SDimitry Andric 
5624*81ad6265SDimitry Andric   auto MatchNaN = [&](unsigned Idx) {
5625*81ad6265SDimitry Andric     Register MaybeNaNReg = MI.getOperand(Idx).getReg();
5626*81ad6265SDimitry Andric     const ConstantFP *MaybeCst = getConstantFPVRegVal(MaybeNaNReg, MRI);
5627*81ad6265SDimitry Andric     if (!MaybeCst || !MaybeCst->getValueAPF().isNaN())
5628*81ad6265SDimitry Andric       return false;
5629*81ad6265SDimitry Andric     IdxToPropagate = PropagateNaN ? Idx : (Idx == 1 ? 2 : 1);
5630*81ad6265SDimitry Andric     return true;
5631*81ad6265SDimitry Andric   };
5632*81ad6265SDimitry Andric 
5633*81ad6265SDimitry Andric   return MatchNaN(1) || MatchNaN(2);
5634*81ad6265SDimitry Andric }
5635*81ad6265SDimitry Andric 
5636*81ad6265SDimitry Andric bool CombinerHelper::matchAddSubSameReg(MachineInstr &MI, Register &Src) {
5637*81ad6265SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ADD && "Expected a G_ADD");
5638*81ad6265SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
5639*81ad6265SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
5640*81ad6265SDimitry Andric 
5641*81ad6265SDimitry Andric   // Helper lambda to check for opportunities for
5642*81ad6265SDimitry Andric   // A + (B - A) -> B
5643*81ad6265SDimitry Andric   // (B - A) + A -> B
5644*81ad6265SDimitry Andric   auto CheckFold = [&](Register MaybeSub, Register MaybeSameReg) {
5645*81ad6265SDimitry Andric     Register Reg;
5646*81ad6265SDimitry Andric     return mi_match(MaybeSub, MRI, m_GSub(m_Reg(Src), m_Reg(Reg))) &&
5647*81ad6265SDimitry Andric            Reg == MaybeSameReg;
5648*81ad6265SDimitry Andric   };
5649*81ad6265SDimitry Andric   return CheckFold(LHS, RHS) || CheckFold(RHS, LHS);
5650*81ad6265SDimitry Andric }
5651*81ad6265SDimitry Andric 
56520b57cec5SDimitry Andric bool CombinerHelper::tryCombine(MachineInstr &MI) {
56530b57cec5SDimitry Andric   if (tryCombineCopy(MI))
56540b57cec5SDimitry Andric     return true;
56558bcb0991SDimitry Andric   if (tryCombineExtendingLoads(MI))
56568bcb0991SDimitry Andric     return true;
56578bcb0991SDimitry Andric   if (tryCombineIndexedLoadStore(MI))
56588bcb0991SDimitry Andric     return true;
56598bcb0991SDimitry Andric   return false;
56600b57cec5SDimitry Andric }
5661