xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
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"
19*06c3fb27SDimitry Andric #include "llvm/CodeGen/LowLevelTypeUtils.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"
2581ad6265SDimitry 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"
30bdd1243dSDimitry Andric #include "llvm/IR/InstrTypes.h"
31349cc55cSDimitry Andric #include "llvm/Support/Casting.h"
32349cc55cSDimitry Andric #include "llvm/Support/DivisionByConstantInfo.h"
335ffd83dbSDimitry Andric #include "llvm/Support/MathExtras.h"
3481ad6265SDimitry Andric #include "llvm/Target/TargetMachine.h"
35bdd1243dSDimitry Andric #include <cmath>
36bdd1243dSDimitry Andric #include <optional>
37fe6060f1SDimitry Andric #include <tuple>
380b57cec5SDimitry Andric 
390b57cec5SDimitry Andric #define DEBUG_TYPE "gi-combiner"
400b57cec5SDimitry Andric 
410b57cec5SDimitry Andric using namespace llvm;
425ffd83dbSDimitry Andric using namespace MIPatternMatch;
430b57cec5SDimitry Andric 
448bcb0991SDimitry Andric // Option to allow testing of the combiner while no targets know about indexed
458bcb0991SDimitry Andric // addressing.
468bcb0991SDimitry Andric static cl::opt<bool>
478bcb0991SDimitry Andric     ForceLegalIndexing("force-legal-indexing", cl::Hidden, cl::init(false),
488bcb0991SDimitry Andric                        cl::desc("Force all indexed operations to be "
498bcb0991SDimitry Andric                                 "legal for the GlobalISel combiner"));
508bcb0991SDimitry Andric 
510b57cec5SDimitry Andric CombinerHelper::CombinerHelper(GISelChangeObserver &Observer,
52bdd1243dSDimitry Andric                                MachineIRBuilder &B, bool IsPreLegalize,
53bdd1243dSDimitry Andric                                GISelKnownBits *KB, MachineDominatorTree *MDT,
545ffd83dbSDimitry Andric                                const LegalizerInfo *LI)
55349cc55cSDimitry Andric     : Builder(B), MRI(Builder.getMF().getRegInfo()), Observer(Observer), KB(KB),
56bdd1243dSDimitry Andric       MDT(MDT), IsPreLegalize(IsPreLegalize), LI(LI),
57bdd1243dSDimitry Andric       RBI(Builder.getMF().getSubtarget().getRegBankInfo()),
58349cc55cSDimitry Andric       TRI(Builder.getMF().getSubtarget().getRegisterInfo()) {
598bcb0991SDimitry Andric   (void)this->KB;
608bcb0991SDimitry Andric }
610b57cec5SDimitry Andric 
62e8d8bef9SDimitry Andric const TargetLowering &CombinerHelper::getTargetLowering() const {
63e8d8bef9SDimitry Andric   return *Builder.getMF().getSubtarget().getTargetLowering();
64e8d8bef9SDimitry Andric }
65e8d8bef9SDimitry Andric 
66e8d8bef9SDimitry Andric /// \returns The little endian in-memory byte position of byte \p I in a
67e8d8bef9SDimitry Andric /// \p ByteWidth bytes wide type.
68e8d8bef9SDimitry Andric ///
69e8d8bef9SDimitry Andric /// E.g. Given a 4-byte type x, x[0] -> byte 0
70e8d8bef9SDimitry Andric static unsigned littleEndianByteAt(const unsigned ByteWidth, const unsigned I) {
71e8d8bef9SDimitry Andric   assert(I < ByteWidth && "I must be in [0, ByteWidth)");
72e8d8bef9SDimitry Andric   return I;
73e8d8bef9SDimitry Andric }
74e8d8bef9SDimitry Andric 
75349cc55cSDimitry Andric /// Determines the LogBase2 value for a non-null input value using the
76349cc55cSDimitry Andric /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
77349cc55cSDimitry Andric static Register buildLogBase2(Register V, MachineIRBuilder &MIB) {
78349cc55cSDimitry Andric   auto &MRI = *MIB.getMRI();
79349cc55cSDimitry Andric   LLT Ty = MRI.getType(V);
80349cc55cSDimitry Andric   auto Ctlz = MIB.buildCTLZ(Ty, V);
81349cc55cSDimitry Andric   auto Base = MIB.buildConstant(Ty, Ty.getScalarSizeInBits() - 1);
82349cc55cSDimitry Andric   return MIB.buildSub(Ty, Base, Ctlz).getReg(0);
83349cc55cSDimitry Andric }
84349cc55cSDimitry Andric 
85e8d8bef9SDimitry Andric /// \returns The big endian in-memory byte position of byte \p I in a
86e8d8bef9SDimitry Andric /// \p ByteWidth bytes wide type.
87e8d8bef9SDimitry Andric ///
88e8d8bef9SDimitry Andric /// E.g. Given a 4-byte type x, x[0] -> byte 3
89e8d8bef9SDimitry Andric static unsigned bigEndianByteAt(const unsigned ByteWidth, const unsigned I) {
90e8d8bef9SDimitry Andric   assert(I < ByteWidth && "I must be in [0, ByteWidth)");
91e8d8bef9SDimitry Andric   return ByteWidth - I - 1;
92e8d8bef9SDimitry Andric }
93e8d8bef9SDimitry Andric 
94e8d8bef9SDimitry Andric /// Given a map from byte offsets in memory to indices in a load/store,
95e8d8bef9SDimitry Andric /// determine if that map corresponds to a little or big endian byte pattern.
96e8d8bef9SDimitry Andric ///
97e8d8bef9SDimitry Andric /// \param MemOffset2Idx maps memory offsets to address offsets.
98e8d8bef9SDimitry Andric /// \param LowestIdx is the lowest index in \p MemOffset2Idx.
99e8d8bef9SDimitry Andric ///
100bdd1243dSDimitry Andric /// \returns true if the map corresponds to a big endian byte pattern, false if
101bdd1243dSDimitry Andric /// it corresponds to a little endian byte pattern, and std::nullopt otherwise.
102e8d8bef9SDimitry Andric ///
103e8d8bef9SDimitry Andric /// E.g. given a 32-bit type x, and x[AddrOffset], the in-memory byte patterns
104e8d8bef9SDimitry Andric /// are as follows:
105e8d8bef9SDimitry Andric ///
106e8d8bef9SDimitry Andric /// AddrOffset   Little endian    Big endian
107e8d8bef9SDimitry Andric /// 0            0                3
108e8d8bef9SDimitry Andric /// 1            1                2
109e8d8bef9SDimitry Andric /// 2            2                1
110e8d8bef9SDimitry Andric /// 3            3                0
111bdd1243dSDimitry Andric static std::optional<bool>
112e8d8bef9SDimitry Andric isBigEndian(const SmallDenseMap<int64_t, int64_t, 8> &MemOffset2Idx,
113e8d8bef9SDimitry Andric             int64_t LowestIdx) {
114e8d8bef9SDimitry Andric   // Need at least two byte positions to decide on endianness.
115e8d8bef9SDimitry Andric   unsigned Width = MemOffset2Idx.size();
116e8d8bef9SDimitry Andric   if (Width < 2)
117bdd1243dSDimitry Andric     return std::nullopt;
118e8d8bef9SDimitry Andric   bool BigEndian = true, LittleEndian = true;
119e8d8bef9SDimitry Andric   for (unsigned MemOffset = 0; MemOffset < Width; ++ MemOffset) {
120e8d8bef9SDimitry Andric     auto MemOffsetAndIdx = MemOffset2Idx.find(MemOffset);
121e8d8bef9SDimitry Andric     if (MemOffsetAndIdx == MemOffset2Idx.end())
122bdd1243dSDimitry Andric       return std::nullopt;
123e8d8bef9SDimitry Andric     const int64_t Idx = MemOffsetAndIdx->second - LowestIdx;
124e8d8bef9SDimitry Andric     assert(Idx >= 0 && "Expected non-negative byte offset?");
125e8d8bef9SDimitry Andric     LittleEndian &= Idx == littleEndianByteAt(Width, MemOffset);
126e8d8bef9SDimitry Andric     BigEndian &= Idx == bigEndianByteAt(Width, MemOffset);
127e8d8bef9SDimitry Andric     if (!BigEndian && !LittleEndian)
128bdd1243dSDimitry Andric       return std::nullopt;
129e8d8bef9SDimitry Andric   }
130e8d8bef9SDimitry Andric 
131e8d8bef9SDimitry Andric   assert((BigEndian != LittleEndian) &&
132e8d8bef9SDimitry Andric          "Pattern cannot be both big and little endian!");
133e8d8bef9SDimitry Andric   return BigEndian;
134e8d8bef9SDimitry Andric }
135e8d8bef9SDimitry Andric 
136bdd1243dSDimitry Andric bool CombinerHelper::isPreLegalize() const { return IsPreLegalize; }
13781ad6265SDimitry Andric 
13881ad6265SDimitry Andric bool CombinerHelper::isLegal(const LegalityQuery &Query) const {
13981ad6265SDimitry Andric   assert(LI && "Must have LegalizerInfo to query isLegal!");
14081ad6265SDimitry Andric   return LI->getAction(Query).Action == LegalizeActions::Legal;
14181ad6265SDimitry Andric }
14281ad6265SDimitry Andric 
143e8d8bef9SDimitry Andric bool CombinerHelper::isLegalOrBeforeLegalizer(
144e8d8bef9SDimitry Andric     const LegalityQuery &Query) const {
14581ad6265SDimitry Andric   return isPreLegalize() || isLegal(Query);
14681ad6265SDimitry Andric }
14781ad6265SDimitry Andric 
14881ad6265SDimitry Andric bool CombinerHelper::isConstantLegalOrBeforeLegalizer(const LLT Ty) const {
14981ad6265SDimitry Andric   if (!Ty.isVector())
15081ad6265SDimitry Andric     return isLegalOrBeforeLegalizer({TargetOpcode::G_CONSTANT, {Ty}});
15181ad6265SDimitry Andric   // Vector constants are represented as a G_BUILD_VECTOR of scalar G_CONSTANTs.
15281ad6265SDimitry Andric   if (isPreLegalize())
15381ad6265SDimitry Andric     return true;
15481ad6265SDimitry Andric   LLT EltTy = Ty.getElementType();
15581ad6265SDimitry Andric   return isLegal({TargetOpcode::G_BUILD_VECTOR, {Ty, EltTy}}) &&
15681ad6265SDimitry Andric          isLegal({TargetOpcode::G_CONSTANT, {EltTy}});
157e8d8bef9SDimitry Andric }
158e8d8bef9SDimitry Andric 
1590b57cec5SDimitry Andric void CombinerHelper::replaceRegWith(MachineRegisterInfo &MRI, Register FromReg,
1600b57cec5SDimitry Andric                                     Register ToReg) const {
1610b57cec5SDimitry Andric   Observer.changingAllUsesOfReg(MRI, FromReg);
1620b57cec5SDimitry Andric 
1630b57cec5SDimitry Andric   if (MRI.constrainRegAttrs(ToReg, FromReg))
1640b57cec5SDimitry Andric     MRI.replaceRegWith(FromReg, ToReg);
1650b57cec5SDimitry Andric   else
1660b57cec5SDimitry Andric     Builder.buildCopy(ToReg, FromReg);
1670b57cec5SDimitry Andric 
1680b57cec5SDimitry Andric   Observer.finishedChangingAllUsesOfReg();
1690b57cec5SDimitry Andric }
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric void CombinerHelper::replaceRegOpWith(MachineRegisterInfo &MRI,
1720b57cec5SDimitry Andric                                       MachineOperand &FromRegOp,
1730b57cec5SDimitry Andric                                       Register ToReg) const {
1740b57cec5SDimitry Andric   assert(FromRegOp.getParent() && "Expected an operand in an MI");
1750b57cec5SDimitry Andric   Observer.changingInstr(*FromRegOp.getParent());
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric   FromRegOp.setReg(ToReg);
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric   Observer.changedInstr(*FromRegOp.getParent());
1800b57cec5SDimitry Andric }
1810b57cec5SDimitry Andric 
182349cc55cSDimitry Andric void CombinerHelper::replaceOpcodeWith(MachineInstr &FromMI,
183349cc55cSDimitry Andric                                        unsigned ToOpcode) const {
184349cc55cSDimitry Andric   Observer.changingInstr(FromMI);
185349cc55cSDimitry Andric 
186349cc55cSDimitry Andric   FromMI.setDesc(Builder.getTII().get(ToOpcode));
187349cc55cSDimitry Andric 
188349cc55cSDimitry Andric   Observer.changedInstr(FromMI);
189349cc55cSDimitry Andric }
190349cc55cSDimitry Andric 
191349cc55cSDimitry Andric const RegisterBank *CombinerHelper::getRegBank(Register Reg) const {
192349cc55cSDimitry Andric   return RBI->getRegBank(Reg, MRI, *TRI);
193349cc55cSDimitry Andric }
194349cc55cSDimitry Andric 
195349cc55cSDimitry Andric void CombinerHelper::setRegBank(Register Reg, const RegisterBank *RegBank) {
196349cc55cSDimitry Andric   if (RegBank)
197349cc55cSDimitry Andric     MRI.setRegBank(Reg, *RegBank);
198349cc55cSDimitry Andric }
199349cc55cSDimitry Andric 
2000b57cec5SDimitry Andric bool CombinerHelper::tryCombineCopy(MachineInstr &MI) {
2010b57cec5SDimitry Andric   if (matchCombineCopy(MI)) {
2020b57cec5SDimitry Andric     applyCombineCopy(MI);
2030b57cec5SDimitry Andric     return true;
2040b57cec5SDimitry Andric   }
2050b57cec5SDimitry Andric   return false;
2060b57cec5SDimitry Andric }
2070b57cec5SDimitry Andric bool CombinerHelper::matchCombineCopy(MachineInstr &MI) {
2080b57cec5SDimitry Andric   if (MI.getOpcode() != TargetOpcode::COPY)
2090b57cec5SDimitry Andric     return false;
2108bcb0991SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2118bcb0991SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2125ffd83dbSDimitry Andric   return canReplaceReg(DstReg, SrcReg, MRI);
2130b57cec5SDimitry Andric }
2140b57cec5SDimitry Andric void CombinerHelper::applyCombineCopy(MachineInstr &MI) {
2158bcb0991SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2168bcb0991SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2170b57cec5SDimitry Andric   MI.eraseFromParent();
2180b57cec5SDimitry Andric   replaceRegWith(MRI, DstReg, SrcReg);
2190b57cec5SDimitry Andric }
2200b57cec5SDimitry Andric 
2218bcb0991SDimitry Andric bool CombinerHelper::tryCombineConcatVectors(MachineInstr &MI) {
2228bcb0991SDimitry Andric   bool IsUndef = false;
2238bcb0991SDimitry Andric   SmallVector<Register, 4> Ops;
2248bcb0991SDimitry Andric   if (matchCombineConcatVectors(MI, IsUndef, Ops)) {
2258bcb0991SDimitry Andric     applyCombineConcatVectors(MI, IsUndef, Ops);
2268bcb0991SDimitry Andric     return true;
2278bcb0991SDimitry Andric   }
2288bcb0991SDimitry Andric   return false;
2298bcb0991SDimitry Andric }
2308bcb0991SDimitry Andric 
2318bcb0991SDimitry Andric bool CombinerHelper::matchCombineConcatVectors(MachineInstr &MI, bool &IsUndef,
2328bcb0991SDimitry Andric                                                SmallVectorImpl<Register> &Ops) {
2338bcb0991SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_CONCAT_VECTORS &&
2348bcb0991SDimitry Andric          "Invalid instruction");
2358bcb0991SDimitry Andric   IsUndef = true;
2368bcb0991SDimitry Andric   MachineInstr *Undef = nullptr;
2378bcb0991SDimitry Andric 
2388bcb0991SDimitry Andric   // Walk over all the operands of concat vectors and check if they are
2398bcb0991SDimitry Andric   // build_vector themselves or undef.
2408bcb0991SDimitry Andric   // Then collect their operands in Ops.
241480093f4SDimitry Andric   for (const MachineOperand &MO : MI.uses()) {
2428bcb0991SDimitry Andric     Register Reg = MO.getReg();
2438bcb0991SDimitry Andric     MachineInstr *Def = MRI.getVRegDef(Reg);
2448bcb0991SDimitry Andric     assert(Def && "Operand not defined");
2458bcb0991SDimitry Andric     switch (Def->getOpcode()) {
2468bcb0991SDimitry Andric     case TargetOpcode::G_BUILD_VECTOR:
2478bcb0991SDimitry Andric       IsUndef = false;
2488bcb0991SDimitry Andric       // Remember the operands of the build_vector to fold
2498bcb0991SDimitry Andric       // them into the yet-to-build flattened concat vectors.
250480093f4SDimitry Andric       for (const MachineOperand &BuildVecMO : Def->uses())
2518bcb0991SDimitry Andric         Ops.push_back(BuildVecMO.getReg());
2528bcb0991SDimitry Andric       break;
2538bcb0991SDimitry Andric     case TargetOpcode::G_IMPLICIT_DEF: {
2548bcb0991SDimitry Andric       LLT OpType = MRI.getType(Reg);
2558bcb0991SDimitry Andric       // Keep one undef value for all the undef operands.
2568bcb0991SDimitry Andric       if (!Undef) {
2578bcb0991SDimitry Andric         Builder.setInsertPt(*MI.getParent(), MI);
2588bcb0991SDimitry Andric         Undef = Builder.buildUndef(OpType.getScalarType());
2598bcb0991SDimitry Andric       }
2608bcb0991SDimitry Andric       assert(MRI.getType(Undef->getOperand(0).getReg()) ==
2618bcb0991SDimitry Andric                  OpType.getScalarType() &&
2628bcb0991SDimitry Andric              "All undefs should have the same type");
2638bcb0991SDimitry Andric       // Break the undef vector in as many scalar elements as needed
2648bcb0991SDimitry Andric       // for the flattening.
2658bcb0991SDimitry Andric       for (unsigned EltIdx = 0, EltEnd = OpType.getNumElements();
2668bcb0991SDimitry Andric            EltIdx != EltEnd; ++EltIdx)
2678bcb0991SDimitry Andric         Ops.push_back(Undef->getOperand(0).getReg());
2688bcb0991SDimitry Andric       break;
2698bcb0991SDimitry Andric     }
2708bcb0991SDimitry Andric     default:
2718bcb0991SDimitry Andric       return false;
2728bcb0991SDimitry Andric     }
2738bcb0991SDimitry Andric   }
2748bcb0991SDimitry Andric   return true;
2758bcb0991SDimitry Andric }
2768bcb0991SDimitry Andric void CombinerHelper::applyCombineConcatVectors(
2778bcb0991SDimitry Andric     MachineInstr &MI, bool IsUndef, const ArrayRef<Register> Ops) {
2788bcb0991SDimitry Andric   // We determined that the concat_vectors can be flatten.
2798bcb0991SDimitry Andric   // Generate the flattened build_vector.
2808bcb0991SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2818bcb0991SDimitry Andric   Builder.setInsertPt(*MI.getParent(), MI);
2828bcb0991SDimitry Andric   Register NewDstReg = MRI.cloneVirtualRegister(DstReg);
2838bcb0991SDimitry Andric 
2848bcb0991SDimitry Andric   // Note: IsUndef is sort of redundant. We could have determine it by
2858bcb0991SDimitry Andric   // checking that at all Ops are undef.  Alternatively, we could have
2868bcb0991SDimitry Andric   // generate a build_vector of undefs and rely on another combine to
2878bcb0991SDimitry Andric   // clean that up.  For now, given we already gather this information
2888bcb0991SDimitry Andric   // in tryCombineConcatVectors, just save compile time and issue the
2898bcb0991SDimitry Andric   // right thing.
2908bcb0991SDimitry Andric   if (IsUndef)
2918bcb0991SDimitry Andric     Builder.buildUndef(NewDstReg);
2928bcb0991SDimitry Andric   else
2938bcb0991SDimitry Andric     Builder.buildBuildVector(NewDstReg, Ops);
2948bcb0991SDimitry Andric   MI.eraseFromParent();
2958bcb0991SDimitry Andric   replaceRegWith(MRI, DstReg, NewDstReg);
2968bcb0991SDimitry Andric }
2978bcb0991SDimitry Andric 
2988bcb0991SDimitry Andric bool CombinerHelper::tryCombineShuffleVector(MachineInstr &MI) {
2998bcb0991SDimitry Andric   SmallVector<Register, 4> Ops;
3008bcb0991SDimitry Andric   if (matchCombineShuffleVector(MI, Ops)) {
3018bcb0991SDimitry Andric     applyCombineShuffleVector(MI, Ops);
3028bcb0991SDimitry Andric     return true;
3038bcb0991SDimitry Andric   }
3048bcb0991SDimitry Andric   return false;
3058bcb0991SDimitry Andric }
3068bcb0991SDimitry Andric 
3078bcb0991SDimitry Andric bool CombinerHelper::matchCombineShuffleVector(MachineInstr &MI,
3088bcb0991SDimitry Andric                                                SmallVectorImpl<Register> &Ops) {
3098bcb0991SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR &&
3108bcb0991SDimitry Andric          "Invalid instruction kind");
3118bcb0991SDimitry Andric   LLT DstType = MRI.getType(MI.getOperand(0).getReg());
3128bcb0991SDimitry Andric   Register Src1 = MI.getOperand(1).getReg();
3138bcb0991SDimitry Andric   LLT SrcType = MRI.getType(Src1);
314480093f4SDimitry Andric   // As bizarre as it may look, shuffle vector can actually produce
315480093f4SDimitry Andric   // scalar! This is because at the IR level a <1 x ty> shuffle
316480093f4SDimitry Andric   // vector is perfectly valid.
317480093f4SDimitry Andric   unsigned DstNumElts = DstType.isVector() ? DstType.getNumElements() : 1;
318480093f4SDimitry Andric   unsigned SrcNumElts = SrcType.isVector() ? SrcType.getNumElements() : 1;
3198bcb0991SDimitry Andric 
3208bcb0991SDimitry Andric   // If the resulting vector is smaller than the size of the source
3218bcb0991SDimitry Andric   // vectors being concatenated, we won't be able to replace the
3228bcb0991SDimitry Andric   // shuffle vector into a concat_vectors.
3238bcb0991SDimitry Andric   //
3248bcb0991SDimitry Andric   // Note: We may still be able to produce a concat_vectors fed by
3258bcb0991SDimitry Andric   //       extract_vector_elt and so on. It is less clear that would
3268bcb0991SDimitry Andric   //       be better though, so don't bother for now.
327480093f4SDimitry Andric   //
328480093f4SDimitry Andric   // If the destination is a scalar, the size of the sources doesn't
329480093f4SDimitry Andric   // matter. we will lower the shuffle to a plain copy. This will
330480093f4SDimitry Andric   // work only if the source and destination have the same size. But
331480093f4SDimitry Andric   // that's covered by the next condition.
332480093f4SDimitry Andric   //
333480093f4SDimitry Andric   // TODO: If the size between the source and destination don't match
334480093f4SDimitry Andric   //       we could still emit an extract vector element in that case.
335480093f4SDimitry Andric   if (DstNumElts < 2 * SrcNumElts && DstNumElts != 1)
3368bcb0991SDimitry Andric     return false;
3378bcb0991SDimitry Andric 
3388bcb0991SDimitry Andric   // Check that the shuffle mask can be broken evenly between the
3398bcb0991SDimitry Andric   // different sources.
3408bcb0991SDimitry Andric   if (DstNumElts % SrcNumElts != 0)
3418bcb0991SDimitry Andric     return false;
3428bcb0991SDimitry Andric 
3438bcb0991SDimitry Andric   // Mask length is a multiple of the source vector length.
3448bcb0991SDimitry Andric   // Check if the shuffle is some kind of concatenation of the input
3458bcb0991SDimitry Andric   // vectors.
3468bcb0991SDimitry Andric   unsigned NumConcat = DstNumElts / SrcNumElts;
3478bcb0991SDimitry Andric   SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
348480093f4SDimitry Andric   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
3498bcb0991SDimitry Andric   for (unsigned i = 0; i != DstNumElts; ++i) {
3508bcb0991SDimitry Andric     int Idx = Mask[i];
3518bcb0991SDimitry Andric     // Undef value.
3528bcb0991SDimitry Andric     if (Idx < 0)
3538bcb0991SDimitry Andric       continue;
3548bcb0991SDimitry Andric     // Ensure the indices in each SrcType sized piece are sequential and that
3558bcb0991SDimitry Andric     // the same source is used for the whole piece.
3568bcb0991SDimitry Andric     if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3578bcb0991SDimitry Andric         (ConcatSrcs[i / SrcNumElts] >= 0 &&
3588bcb0991SDimitry Andric          ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts)))
3598bcb0991SDimitry Andric       return false;
3608bcb0991SDimitry Andric     // Remember which source this index came from.
3618bcb0991SDimitry Andric     ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3628bcb0991SDimitry Andric   }
3638bcb0991SDimitry Andric 
3648bcb0991SDimitry Andric   // The shuffle is concatenating multiple vectors together.
3658bcb0991SDimitry Andric   // Collect the different operands for that.
3668bcb0991SDimitry Andric   Register UndefReg;
3678bcb0991SDimitry Andric   Register Src2 = MI.getOperand(2).getReg();
3688bcb0991SDimitry Andric   for (auto Src : ConcatSrcs) {
3698bcb0991SDimitry Andric     if (Src < 0) {
3708bcb0991SDimitry Andric       if (!UndefReg) {
3718bcb0991SDimitry Andric         Builder.setInsertPt(*MI.getParent(), MI);
3728bcb0991SDimitry Andric         UndefReg = Builder.buildUndef(SrcType).getReg(0);
3738bcb0991SDimitry Andric       }
3748bcb0991SDimitry Andric       Ops.push_back(UndefReg);
3758bcb0991SDimitry Andric     } else if (Src == 0)
3768bcb0991SDimitry Andric       Ops.push_back(Src1);
3778bcb0991SDimitry Andric     else
3788bcb0991SDimitry Andric       Ops.push_back(Src2);
3798bcb0991SDimitry Andric   }
3808bcb0991SDimitry Andric   return true;
3818bcb0991SDimitry Andric }
3828bcb0991SDimitry Andric 
3838bcb0991SDimitry Andric void CombinerHelper::applyCombineShuffleVector(MachineInstr &MI,
3848bcb0991SDimitry Andric                                                const ArrayRef<Register> Ops) {
3858bcb0991SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
3868bcb0991SDimitry Andric   Builder.setInsertPt(*MI.getParent(), MI);
3878bcb0991SDimitry Andric   Register NewDstReg = MRI.cloneVirtualRegister(DstReg);
3888bcb0991SDimitry Andric 
389480093f4SDimitry Andric   if (Ops.size() == 1)
390480093f4SDimitry Andric     Builder.buildCopy(NewDstReg, Ops[0]);
391480093f4SDimitry Andric   else
392bdd1243dSDimitry Andric     Builder.buildMergeLikeInstr(NewDstReg, Ops);
3938bcb0991SDimitry Andric 
3948bcb0991SDimitry Andric   MI.eraseFromParent();
3958bcb0991SDimitry Andric   replaceRegWith(MRI, DstReg, NewDstReg);
3968bcb0991SDimitry Andric }
3978bcb0991SDimitry Andric 
3980b57cec5SDimitry Andric namespace {
3990b57cec5SDimitry Andric 
4000b57cec5SDimitry Andric /// Select a preference between two uses. CurrentUse is the current preference
4010b57cec5SDimitry Andric /// while *ForCandidate is attributes of the candidate under consideration.
402*06c3fb27SDimitry Andric PreferredTuple ChoosePreferredUse(MachineInstr &LoadMI,
403*06c3fb27SDimitry Andric                                   PreferredTuple &CurrentUse,
4045ffd83dbSDimitry Andric                                   const LLT TyForCandidate,
4050b57cec5SDimitry Andric                                   unsigned OpcodeForCandidate,
4060b57cec5SDimitry Andric                                   MachineInstr *MIForCandidate) {
4070b57cec5SDimitry Andric   if (!CurrentUse.Ty.isValid()) {
4080b57cec5SDimitry Andric     if (CurrentUse.ExtendOpcode == OpcodeForCandidate ||
4090b57cec5SDimitry Andric         CurrentUse.ExtendOpcode == TargetOpcode::G_ANYEXT)
4100b57cec5SDimitry Andric       return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
4110b57cec5SDimitry Andric     return CurrentUse;
4120b57cec5SDimitry Andric   }
4130b57cec5SDimitry Andric 
4140b57cec5SDimitry Andric   // We permit the extend to hoist through basic blocks but this is only
4150b57cec5SDimitry Andric   // sensible if the target has extending loads. If you end up lowering back
4160b57cec5SDimitry Andric   // into a load and extend during the legalizer then the end result is
4170b57cec5SDimitry Andric   // hoisting the extend up to the load.
4180b57cec5SDimitry Andric 
4190b57cec5SDimitry Andric   // Prefer defined extensions to undefined extensions as these are more
4200b57cec5SDimitry Andric   // likely to reduce the number of instructions.
4210b57cec5SDimitry Andric   if (OpcodeForCandidate == TargetOpcode::G_ANYEXT &&
4220b57cec5SDimitry Andric       CurrentUse.ExtendOpcode != TargetOpcode::G_ANYEXT)
4230b57cec5SDimitry Andric     return CurrentUse;
4240b57cec5SDimitry Andric   else if (CurrentUse.ExtendOpcode == TargetOpcode::G_ANYEXT &&
4250b57cec5SDimitry Andric            OpcodeForCandidate != TargetOpcode::G_ANYEXT)
4260b57cec5SDimitry Andric     return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric   // Prefer sign extensions to zero extensions as sign-extensions tend to be
429*06c3fb27SDimitry Andric   // more expensive. Don't do this if the load is already a zero-extend load
430*06c3fb27SDimitry Andric   // though, otherwise we'll rewrite a zero-extend load into a sign-extend
431*06c3fb27SDimitry Andric   // later.
432*06c3fb27SDimitry Andric   if (!isa<GZExtLoad>(LoadMI) && CurrentUse.Ty == TyForCandidate) {
4330b57cec5SDimitry Andric     if (CurrentUse.ExtendOpcode == TargetOpcode::G_SEXT &&
4340b57cec5SDimitry Andric         OpcodeForCandidate == TargetOpcode::G_ZEXT)
4350b57cec5SDimitry Andric       return CurrentUse;
4360b57cec5SDimitry Andric     else if (CurrentUse.ExtendOpcode == TargetOpcode::G_ZEXT &&
4370b57cec5SDimitry Andric              OpcodeForCandidate == TargetOpcode::G_SEXT)
4380b57cec5SDimitry Andric       return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
4390b57cec5SDimitry Andric   }
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric   // This is potentially target specific. We've chosen the largest type
4420b57cec5SDimitry Andric   // because G_TRUNC is usually free. One potential catch with this is that
4430b57cec5SDimitry Andric   // some targets have a reduced number of larger registers than smaller
4440b57cec5SDimitry Andric   // registers and this choice potentially increases the live-range for the
4450b57cec5SDimitry Andric   // larger value.
4460b57cec5SDimitry Andric   if (TyForCandidate.getSizeInBits() > CurrentUse.Ty.getSizeInBits()) {
4470b57cec5SDimitry Andric     return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
4480b57cec5SDimitry Andric   }
4490b57cec5SDimitry Andric   return CurrentUse;
4500b57cec5SDimitry Andric }
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric /// Find a suitable place to insert some instructions and insert them. This
4530b57cec5SDimitry Andric /// function accounts for special cases like inserting before a PHI node.
4540b57cec5SDimitry Andric /// The current strategy for inserting before PHI's is to duplicate the
4550b57cec5SDimitry Andric /// instructions for each predecessor. However, while that's ok for G_TRUNC
4560b57cec5SDimitry Andric /// on most targets since it generally requires no code, other targets/cases may
4570b57cec5SDimitry Andric /// want to try harder to find a dominating block.
4580b57cec5SDimitry Andric static void InsertInsnsWithoutSideEffectsBeforeUse(
4590b57cec5SDimitry Andric     MachineIRBuilder &Builder, MachineInstr &DefMI, MachineOperand &UseMO,
4600b57cec5SDimitry Andric     std::function<void(MachineBasicBlock *, MachineBasicBlock::iterator,
4610b57cec5SDimitry Andric                        MachineOperand &UseMO)>
4620b57cec5SDimitry Andric         Inserter) {
4630b57cec5SDimitry Andric   MachineInstr &UseMI = *UseMO.getParent();
4640b57cec5SDimitry Andric 
4650b57cec5SDimitry Andric   MachineBasicBlock *InsertBB = UseMI.getParent();
4660b57cec5SDimitry Andric 
4670b57cec5SDimitry Andric   // If the use is a PHI then we want the predecessor block instead.
4680b57cec5SDimitry Andric   if (UseMI.isPHI()) {
4690b57cec5SDimitry Andric     MachineOperand *PredBB = std::next(&UseMO);
4700b57cec5SDimitry Andric     InsertBB = PredBB->getMBB();
4710b57cec5SDimitry Andric   }
4720b57cec5SDimitry Andric 
4730b57cec5SDimitry Andric   // If the block is the same block as the def then we want to insert just after
4740b57cec5SDimitry Andric   // the def instead of at the start of the block.
4750b57cec5SDimitry Andric   if (InsertBB == DefMI.getParent()) {
4760b57cec5SDimitry Andric     MachineBasicBlock::iterator InsertPt = &DefMI;
4770b57cec5SDimitry Andric     Inserter(InsertBB, std::next(InsertPt), UseMO);
4780b57cec5SDimitry Andric     return;
4790b57cec5SDimitry Andric   }
4800b57cec5SDimitry Andric 
4810b57cec5SDimitry Andric   // Otherwise we want the start of the BB
4820b57cec5SDimitry Andric   Inserter(InsertBB, InsertBB->getFirstNonPHI(), UseMO);
4830b57cec5SDimitry Andric }
4840b57cec5SDimitry Andric } // end anonymous namespace
4850b57cec5SDimitry Andric 
4860b57cec5SDimitry Andric bool CombinerHelper::tryCombineExtendingLoads(MachineInstr &MI) {
4870b57cec5SDimitry Andric   PreferredTuple Preferred;
4880b57cec5SDimitry Andric   if (matchCombineExtendingLoads(MI, Preferred)) {
4890b57cec5SDimitry Andric     applyCombineExtendingLoads(MI, Preferred);
4900b57cec5SDimitry Andric     return true;
4910b57cec5SDimitry Andric   }
4920b57cec5SDimitry Andric   return false;
4930b57cec5SDimitry Andric }
4940b57cec5SDimitry Andric 
495bdd1243dSDimitry Andric static unsigned getExtLoadOpcForExtend(unsigned ExtOpc) {
496bdd1243dSDimitry Andric   unsigned CandidateLoadOpc;
497bdd1243dSDimitry Andric   switch (ExtOpc) {
498bdd1243dSDimitry Andric   case TargetOpcode::G_ANYEXT:
499bdd1243dSDimitry Andric     CandidateLoadOpc = TargetOpcode::G_LOAD;
500bdd1243dSDimitry Andric     break;
501bdd1243dSDimitry Andric   case TargetOpcode::G_SEXT:
502bdd1243dSDimitry Andric     CandidateLoadOpc = TargetOpcode::G_SEXTLOAD;
503bdd1243dSDimitry Andric     break;
504bdd1243dSDimitry Andric   case TargetOpcode::G_ZEXT:
505bdd1243dSDimitry Andric     CandidateLoadOpc = TargetOpcode::G_ZEXTLOAD;
506bdd1243dSDimitry Andric     break;
507bdd1243dSDimitry Andric   default:
508bdd1243dSDimitry Andric     llvm_unreachable("Unexpected extend opc");
509bdd1243dSDimitry Andric   }
510bdd1243dSDimitry Andric   return CandidateLoadOpc;
511bdd1243dSDimitry Andric }
512bdd1243dSDimitry Andric 
5130b57cec5SDimitry Andric bool CombinerHelper::matchCombineExtendingLoads(MachineInstr &MI,
5140b57cec5SDimitry Andric                                                 PreferredTuple &Preferred) {
5150b57cec5SDimitry Andric   // We match the loads and follow the uses to the extend instead of matching
5160b57cec5SDimitry Andric   // the extends and following the def to the load. This is because the load
5170b57cec5SDimitry Andric   // must remain in the same position for correctness (unless we also add code
5180b57cec5SDimitry Andric   // to find a safe place to sink it) whereas the extend is freely movable.
5190b57cec5SDimitry Andric   // It also prevents us from duplicating the load for the volatile case or just
5200b57cec5SDimitry Andric   // for performance.
521fe6060f1SDimitry Andric   GAnyLoad *LoadMI = dyn_cast<GAnyLoad>(&MI);
522fe6060f1SDimitry Andric   if (!LoadMI)
5230b57cec5SDimitry Andric     return false;
5240b57cec5SDimitry Andric 
525fe6060f1SDimitry Andric   Register LoadReg = LoadMI->getDstReg();
5260b57cec5SDimitry Andric 
527fe6060f1SDimitry Andric   LLT LoadValueTy = MRI.getType(LoadReg);
5280b57cec5SDimitry Andric   if (!LoadValueTy.isScalar())
5290b57cec5SDimitry Andric     return false;
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric   // Most architectures are going to legalize <s8 loads into at least a 1 byte
5320b57cec5SDimitry Andric   // load, and the MMOs can only describe memory accesses in multiples of bytes.
5330b57cec5SDimitry Andric   // If we try to perform extload combining on those, we can end up with
5340b57cec5SDimitry Andric   // %a(s8) = extload %ptr (load 1 byte from %ptr)
5350b57cec5SDimitry Andric   // ... which is an illegal extload instruction.
5360b57cec5SDimitry Andric   if (LoadValueTy.getSizeInBits() < 8)
5370b57cec5SDimitry Andric     return false;
5380b57cec5SDimitry Andric 
5390b57cec5SDimitry Andric   // For non power-of-2 types, they will very likely be legalized into multiple
5400b57cec5SDimitry Andric   // loads. Don't bother trying to match them into extending loads.
541*06c3fb27SDimitry Andric   if (!llvm::has_single_bit<uint32_t>(LoadValueTy.getSizeInBits()))
5420b57cec5SDimitry Andric     return false;
5430b57cec5SDimitry Andric 
5440b57cec5SDimitry Andric   // Find the preferred type aside from the any-extends (unless it's the only
5450b57cec5SDimitry Andric   // one) and non-extending ops. We'll emit an extending load to that type and
5460b57cec5SDimitry Andric   // and emit a variant of (extend (trunc X)) for the others according to the
5470b57cec5SDimitry Andric   // relative type sizes. At the same time, pick an extend to use based on the
5480b57cec5SDimitry Andric   // extend involved in the chosen type.
549fe6060f1SDimitry Andric   unsigned PreferredOpcode =
550fe6060f1SDimitry Andric       isa<GLoad>(&MI)
5510b57cec5SDimitry Andric           ? TargetOpcode::G_ANYEXT
552fe6060f1SDimitry Andric           : isa<GSExtLoad>(&MI) ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
5530b57cec5SDimitry Andric   Preferred = {LLT(), PreferredOpcode, nullptr};
554fe6060f1SDimitry Andric   for (auto &UseMI : MRI.use_nodbg_instructions(LoadReg)) {
5550b57cec5SDimitry Andric     if (UseMI.getOpcode() == TargetOpcode::G_SEXT ||
5560b57cec5SDimitry Andric         UseMI.getOpcode() == TargetOpcode::G_ZEXT ||
5575ffd83dbSDimitry Andric         (UseMI.getOpcode() == TargetOpcode::G_ANYEXT)) {
558fe6060f1SDimitry Andric       const auto &MMO = LoadMI->getMMO();
559fe6060f1SDimitry Andric       // For atomics, only form anyextending loads.
560fe6060f1SDimitry Andric       if (MMO.isAtomic() && UseMI.getOpcode() != TargetOpcode::G_ANYEXT)
561fe6060f1SDimitry Andric         continue;
5625ffd83dbSDimitry Andric       // Check for legality.
563bdd1243dSDimitry Andric       if (!isPreLegalize()) {
564349cc55cSDimitry Andric         LegalityQuery::MemDesc MMDesc(MMO);
565bdd1243dSDimitry Andric         unsigned CandidateLoadOpc = getExtLoadOpcForExtend(UseMI.getOpcode());
5665ffd83dbSDimitry Andric         LLT UseTy = MRI.getType(UseMI.getOperand(0).getReg());
567fe6060f1SDimitry Andric         LLT SrcTy = MRI.getType(LoadMI->getPointerReg());
568bdd1243dSDimitry Andric         if (LI->getAction({CandidateLoadOpc, {UseTy, SrcTy}, {MMDesc}})
569fe6060f1SDimitry Andric                 .Action != LegalizeActions::Legal)
5705ffd83dbSDimitry Andric           continue;
5715ffd83dbSDimitry Andric       }
572*06c3fb27SDimitry Andric       Preferred = ChoosePreferredUse(MI, Preferred,
5730b57cec5SDimitry Andric                                      MRI.getType(UseMI.getOperand(0).getReg()),
5740b57cec5SDimitry Andric                                      UseMI.getOpcode(), &UseMI);
5750b57cec5SDimitry Andric     }
5760b57cec5SDimitry Andric   }
5770b57cec5SDimitry Andric 
5780b57cec5SDimitry Andric   // There were no extends
5790b57cec5SDimitry Andric   if (!Preferred.MI)
5800b57cec5SDimitry Andric     return false;
5810b57cec5SDimitry Andric   // It should be impossible to chose an extend without selecting a different
5820b57cec5SDimitry Andric   // type since by definition the result of an extend is larger.
5830b57cec5SDimitry Andric   assert(Preferred.Ty != LoadValueTy && "Extending to same type?");
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Preferred use is: " << *Preferred.MI);
5860b57cec5SDimitry Andric   return true;
5870b57cec5SDimitry Andric }
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric void CombinerHelper::applyCombineExtendingLoads(MachineInstr &MI,
5900b57cec5SDimitry Andric                                                 PreferredTuple &Preferred) {
5910b57cec5SDimitry Andric   // Rewrite the load to the chosen extending load.
5920b57cec5SDimitry Andric   Register ChosenDstReg = Preferred.MI->getOperand(0).getReg();
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric   // Inserter to insert a truncate back to the original type at a given point
5950b57cec5SDimitry Andric   // with some basic CSE to limit truncate duplication to one per BB.
5960b57cec5SDimitry Andric   DenseMap<MachineBasicBlock *, MachineInstr *> EmittedInsns;
5970b57cec5SDimitry Andric   auto InsertTruncAt = [&](MachineBasicBlock *InsertIntoBB,
5980b57cec5SDimitry Andric                            MachineBasicBlock::iterator InsertBefore,
5990b57cec5SDimitry Andric                            MachineOperand &UseMO) {
6000b57cec5SDimitry Andric     MachineInstr *PreviouslyEmitted = EmittedInsns.lookup(InsertIntoBB);
6010b57cec5SDimitry Andric     if (PreviouslyEmitted) {
6020b57cec5SDimitry Andric       Observer.changingInstr(*UseMO.getParent());
6030b57cec5SDimitry Andric       UseMO.setReg(PreviouslyEmitted->getOperand(0).getReg());
6040b57cec5SDimitry Andric       Observer.changedInstr(*UseMO.getParent());
6050b57cec5SDimitry Andric       return;
6060b57cec5SDimitry Andric     }
6070b57cec5SDimitry Andric 
6080b57cec5SDimitry Andric     Builder.setInsertPt(*InsertIntoBB, InsertBefore);
6090b57cec5SDimitry Andric     Register NewDstReg = MRI.cloneVirtualRegister(MI.getOperand(0).getReg());
6100b57cec5SDimitry Andric     MachineInstr *NewMI = Builder.buildTrunc(NewDstReg, ChosenDstReg);
6110b57cec5SDimitry Andric     EmittedInsns[InsertIntoBB] = NewMI;
6120b57cec5SDimitry Andric     replaceRegOpWith(MRI, UseMO, NewDstReg);
6130b57cec5SDimitry Andric   };
6140b57cec5SDimitry Andric 
6150b57cec5SDimitry Andric   Observer.changingInstr(MI);
616bdd1243dSDimitry Andric   unsigned LoadOpc = getExtLoadOpcForExtend(Preferred.ExtendOpcode);
617bdd1243dSDimitry Andric   MI.setDesc(Builder.getTII().get(LoadOpc));
6180b57cec5SDimitry Andric 
6190b57cec5SDimitry Andric   // Rewrite all the uses to fix up the types.
6200b57cec5SDimitry Andric   auto &LoadValue = MI.getOperand(0);
6210b57cec5SDimitry Andric   SmallVector<MachineOperand *, 4> Uses;
6220b57cec5SDimitry Andric   for (auto &UseMO : MRI.use_operands(LoadValue.getReg()))
6230b57cec5SDimitry Andric     Uses.push_back(&UseMO);
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric   for (auto *UseMO : Uses) {
6260b57cec5SDimitry Andric     MachineInstr *UseMI = UseMO->getParent();
6270b57cec5SDimitry Andric 
6280b57cec5SDimitry Andric     // If the extend is compatible with the preferred extend then we should fix
6290b57cec5SDimitry Andric     // up the type and extend so that it uses the preferred use.
6300b57cec5SDimitry Andric     if (UseMI->getOpcode() == Preferred.ExtendOpcode ||
6310b57cec5SDimitry Andric         UseMI->getOpcode() == TargetOpcode::G_ANYEXT) {
6328bcb0991SDimitry Andric       Register UseDstReg = UseMI->getOperand(0).getReg();
6330b57cec5SDimitry Andric       MachineOperand &UseSrcMO = UseMI->getOperand(1);
6345ffd83dbSDimitry Andric       const LLT UseDstTy = MRI.getType(UseDstReg);
6350b57cec5SDimitry Andric       if (UseDstReg != ChosenDstReg) {
6360b57cec5SDimitry Andric         if (Preferred.Ty == UseDstTy) {
6370b57cec5SDimitry Andric           // If the use has the same type as the preferred use, then merge
6380b57cec5SDimitry Andric           // the vregs and erase the extend. For example:
6390b57cec5SDimitry Andric           //    %1:_(s8) = G_LOAD ...
6400b57cec5SDimitry Andric           //    %2:_(s32) = G_SEXT %1(s8)
6410b57cec5SDimitry Andric           //    %3:_(s32) = G_ANYEXT %1(s8)
6420b57cec5SDimitry Andric           //    ... = ... %3(s32)
6430b57cec5SDimitry Andric           // rewrites to:
6440b57cec5SDimitry Andric           //    %2:_(s32) = G_SEXTLOAD ...
6450b57cec5SDimitry Andric           //    ... = ... %2(s32)
6460b57cec5SDimitry Andric           replaceRegWith(MRI, UseDstReg, ChosenDstReg);
6470b57cec5SDimitry Andric           Observer.erasingInstr(*UseMO->getParent());
6480b57cec5SDimitry Andric           UseMO->getParent()->eraseFromParent();
6490b57cec5SDimitry Andric         } else if (Preferred.Ty.getSizeInBits() < UseDstTy.getSizeInBits()) {
6500b57cec5SDimitry Andric           // If the preferred size is smaller, then keep the extend but extend
6510b57cec5SDimitry Andric           // from the result of the extending load. For example:
6520b57cec5SDimitry Andric           //    %1:_(s8) = G_LOAD ...
6530b57cec5SDimitry Andric           //    %2:_(s32) = G_SEXT %1(s8)
6540b57cec5SDimitry Andric           //    %3:_(s64) = G_ANYEXT %1(s8)
6550b57cec5SDimitry Andric           //    ... = ... %3(s64)
6560b57cec5SDimitry Andric           /// rewrites to:
6570b57cec5SDimitry Andric           //    %2:_(s32) = G_SEXTLOAD ...
6580b57cec5SDimitry Andric           //    %3:_(s64) = G_ANYEXT %2:_(s32)
6590b57cec5SDimitry Andric           //    ... = ... %3(s64)
6600b57cec5SDimitry Andric           replaceRegOpWith(MRI, UseSrcMO, ChosenDstReg);
6610b57cec5SDimitry Andric         } else {
6620b57cec5SDimitry Andric           // If the preferred size is large, then insert a truncate. For
6630b57cec5SDimitry Andric           // example:
6640b57cec5SDimitry Andric           //    %1:_(s8) = G_LOAD ...
6650b57cec5SDimitry Andric           //    %2:_(s64) = G_SEXT %1(s8)
6660b57cec5SDimitry Andric           //    %3:_(s32) = G_ZEXT %1(s8)
6670b57cec5SDimitry Andric           //    ... = ... %3(s32)
6680b57cec5SDimitry Andric           /// rewrites to:
6690b57cec5SDimitry Andric           //    %2:_(s64) = G_SEXTLOAD ...
6700b57cec5SDimitry Andric           //    %4:_(s8) = G_TRUNC %2:_(s32)
6710b57cec5SDimitry Andric           //    %3:_(s64) = G_ZEXT %2:_(s8)
6720b57cec5SDimitry Andric           //    ... = ... %3(s64)
6730b57cec5SDimitry Andric           InsertInsnsWithoutSideEffectsBeforeUse(Builder, MI, *UseMO,
6740b57cec5SDimitry Andric                                                  InsertTruncAt);
6750b57cec5SDimitry Andric         }
6760b57cec5SDimitry Andric         continue;
6770b57cec5SDimitry Andric       }
6780b57cec5SDimitry Andric       // The use is (one of) the uses of the preferred use we chose earlier.
6790b57cec5SDimitry Andric       // We're going to update the load to def this value later so just erase
6800b57cec5SDimitry Andric       // the old extend.
6810b57cec5SDimitry Andric       Observer.erasingInstr(*UseMO->getParent());
6820b57cec5SDimitry Andric       UseMO->getParent()->eraseFromParent();
6830b57cec5SDimitry Andric       continue;
6840b57cec5SDimitry Andric     }
6850b57cec5SDimitry Andric 
6860b57cec5SDimitry Andric     // The use isn't an extend. Truncate back to the type we originally loaded.
6870b57cec5SDimitry Andric     // This is free on many targets.
6880b57cec5SDimitry Andric     InsertInsnsWithoutSideEffectsBeforeUse(Builder, MI, *UseMO, InsertTruncAt);
6890b57cec5SDimitry Andric   }
6900b57cec5SDimitry Andric 
6910b57cec5SDimitry Andric   MI.getOperand(0).setReg(ChosenDstReg);
6920b57cec5SDimitry Andric   Observer.changedInstr(MI);
6930b57cec5SDimitry Andric }
6940b57cec5SDimitry Andric 
695349cc55cSDimitry Andric bool CombinerHelper::matchCombineLoadWithAndMask(MachineInstr &MI,
696349cc55cSDimitry Andric                                                  BuildFnTy &MatchInfo) {
697349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_AND);
698349cc55cSDimitry Andric 
699349cc55cSDimitry Andric   // If we have the following code:
700349cc55cSDimitry Andric   //  %mask = G_CONSTANT 255
701349cc55cSDimitry Andric   //  %ld   = G_LOAD %ptr, (load s16)
702349cc55cSDimitry Andric   //  %and  = G_AND %ld, %mask
703349cc55cSDimitry Andric   //
704349cc55cSDimitry Andric   // Try to fold it into
705349cc55cSDimitry Andric   //   %ld = G_ZEXTLOAD %ptr, (load s8)
706349cc55cSDimitry Andric 
707349cc55cSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
708349cc55cSDimitry Andric   if (MRI.getType(Dst).isVector())
709349cc55cSDimitry Andric     return false;
710349cc55cSDimitry Andric 
711349cc55cSDimitry Andric   auto MaybeMask =
712349cc55cSDimitry Andric       getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
713349cc55cSDimitry Andric   if (!MaybeMask)
714349cc55cSDimitry Andric     return false;
715349cc55cSDimitry Andric 
716349cc55cSDimitry Andric   APInt MaskVal = MaybeMask->Value;
717349cc55cSDimitry Andric 
718349cc55cSDimitry Andric   if (!MaskVal.isMask())
719349cc55cSDimitry Andric     return false;
720349cc55cSDimitry Andric 
721349cc55cSDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
722753f127fSDimitry Andric   // Don't use getOpcodeDef() here since intermediate instructions may have
723753f127fSDimitry Andric   // multiple users.
724753f127fSDimitry Andric   GAnyLoad *LoadMI = dyn_cast<GAnyLoad>(MRI.getVRegDef(SrcReg));
725753f127fSDimitry Andric   if (!LoadMI || !MRI.hasOneNonDBGUse(LoadMI->getDstReg()))
726349cc55cSDimitry Andric     return false;
727349cc55cSDimitry Andric 
728349cc55cSDimitry Andric   Register LoadReg = LoadMI->getDstReg();
729753f127fSDimitry Andric   LLT RegTy = MRI.getType(LoadReg);
730349cc55cSDimitry Andric   Register PtrReg = LoadMI->getPointerReg();
731753f127fSDimitry Andric   unsigned RegSize = RegTy.getSizeInBits();
732349cc55cSDimitry Andric   uint64_t LoadSizeBits = LoadMI->getMemSizeInBits();
733*06c3fb27SDimitry Andric   unsigned MaskSizeBits = MaskVal.countr_one();
734349cc55cSDimitry Andric 
735349cc55cSDimitry Andric   // The mask may not be larger than the in-memory type, as it might cover sign
736349cc55cSDimitry Andric   // extended bits
737349cc55cSDimitry Andric   if (MaskSizeBits > LoadSizeBits)
738349cc55cSDimitry Andric     return false;
739349cc55cSDimitry Andric 
740349cc55cSDimitry Andric   // If the mask covers the whole destination register, there's nothing to
741349cc55cSDimitry Andric   // extend
742753f127fSDimitry Andric   if (MaskSizeBits >= RegSize)
743349cc55cSDimitry Andric     return false;
744349cc55cSDimitry Andric 
745349cc55cSDimitry Andric   // Most targets cannot deal with loads of size < 8 and need to re-legalize to
746349cc55cSDimitry Andric   // at least byte loads. Avoid creating such loads here
747349cc55cSDimitry Andric   if (MaskSizeBits < 8 || !isPowerOf2_32(MaskSizeBits))
748349cc55cSDimitry Andric     return false;
749349cc55cSDimitry Andric 
750349cc55cSDimitry Andric   const MachineMemOperand &MMO = LoadMI->getMMO();
751349cc55cSDimitry Andric   LegalityQuery::MemDesc MemDesc(MMO);
752753f127fSDimitry Andric 
753753f127fSDimitry Andric   // Don't modify the memory access size if this is atomic/volatile, but we can
754753f127fSDimitry Andric   // still adjust the opcode to indicate the high bit behavior.
755753f127fSDimitry Andric   if (LoadMI->isSimple())
756349cc55cSDimitry Andric     MemDesc.MemoryTy = LLT::scalar(MaskSizeBits);
757753f127fSDimitry Andric   else if (LoadSizeBits > MaskSizeBits || LoadSizeBits == RegSize)
758753f127fSDimitry Andric     return false;
759753f127fSDimitry Andric 
760753f127fSDimitry Andric   // TODO: Could check if it's legal with the reduced or original memory size.
761349cc55cSDimitry Andric   if (!isLegalOrBeforeLegalizer(
762753f127fSDimitry Andric           {TargetOpcode::G_ZEXTLOAD, {RegTy, MRI.getType(PtrReg)}, {MemDesc}}))
763349cc55cSDimitry Andric     return false;
764349cc55cSDimitry Andric 
765349cc55cSDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
766349cc55cSDimitry Andric     B.setInstrAndDebugLoc(*LoadMI);
767349cc55cSDimitry Andric     auto &MF = B.getMF();
768349cc55cSDimitry Andric     auto PtrInfo = MMO.getPointerInfo();
769753f127fSDimitry Andric     auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, MemDesc.MemoryTy);
770349cc55cSDimitry Andric     B.buildLoadInstr(TargetOpcode::G_ZEXTLOAD, Dst, PtrReg, *NewMMO);
771753f127fSDimitry Andric     LoadMI->eraseFromParent();
772349cc55cSDimitry Andric   };
773349cc55cSDimitry Andric   return true;
774349cc55cSDimitry Andric }
775349cc55cSDimitry Andric 
7765ffd83dbSDimitry Andric bool CombinerHelper::isPredecessor(const MachineInstr &DefMI,
7775ffd83dbSDimitry Andric                                    const MachineInstr &UseMI) {
7785ffd83dbSDimitry Andric   assert(!DefMI.isDebugInstr() && !UseMI.isDebugInstr() &&
7795ffd83dbSDimitry Andric          "shouldn't consider debug uses");
7808bcb0991SDimitry Andric   assert(DefMI.getParent() == UseMI.getParent());
7818bcb0991SDimitry Andric   if (&DefMI == &UseMI)
782349cc55cSDimitry Andric     return true;
783e8d8bef9SDimitry Andric   const MachineBasicBlock &MBB = *DefMI.getParent();
784e8d8bef9SDimitry Andric   auto DefOrUse = find_if(MBB, [&DefMI, &UseMI](const MachineInstr &MI) {
785e8d8bef9SDimitry Andric     return &MI == &DefMI || &MI == &UseMI;
786e8d8bef9SDimitry Andric   });
787e8d8bef9SDimitry Andric   if (DefOrUse == MBB.end())
788e8d8bef9SDimitry Andric     llvm_unreachable("Block must contain both DefMI and UseMI!");
789e8d8bef9SDimitry Andric   return &*DefOrUse == &DefMI;
7908bcb0991SDimitry Andric }
7918bcb0991SDimitry Andric 
7925ffd83dbSDimitry Andric bool CombinerHelper::dominates(const MachineInstr &DefMI,
7935ffd83dbSDimitry Andric                                const MachineInstr &UseMI) {
7945ffd83dbSDimitry Andric   assert(!DefMI.isDebugInstr() && !UseMI.isDebugInstr() &&
7955ffd83dbSDimitry Andric          "shouldn't consider debug uses");
7968bcb0991SDimitry Andric   if (MDT)
7978bcb0991SDimitry Andric     return MDT->dominates(&DefMI, &UseMI);
7988bcb0991SDimitry Andric   else if (DefMI.getParent() != UseMI.getParent())
7998bcb0991SDimitry Andric     return false;
8008bcb0991SDimitry Andric 
8018bcb0991SDimitry Andric   return isPredecessor(DefMI, UseMI);
8028bcb0991SDimitry Andric }
8038bcb0991SDimitry Andric 
804e8d8bef9SDimitry Andric bool CombinerHelper::matchSextTruncSextLoad(MachineInstr &MI) {
8055ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
8065ffd83dbSDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
807e8d8bef9SDimitry Andric   Register LoadUser = SrcReg;
808e8d8bef9SDimitry Andric 
809e8d8bef9SDimitry Andric   if (MRI.getType(SrcReg).isVector())
810e8d8bef9SDimitry Andric     return false;
811e8d8bef9SDimitry Andric 
812e8d8bef9SDimitry Andric   Register TruncSrc;
813e8d8bef9SDimitry Andric   if (mi_match(SrcReg, MRI, m_GTrunc(m_Reg(TruncSrc))))
814e8d8bef9SDimitry Andric     LoadUser = TruncSrc;
815e8d8bef9SDimitry Andric 
816e8d8bef9SDimitry Andric   uint64_t SizeInBits = MI.getOperand(2).getImm();
817e8d8bef9SDimitry Andric   // If the source is a G_SEXTLOAD from the same bit width, then we don't
818e8d8bef9SDimitry Andric   // need any extend at all, just a truncate.
819fe6060f1SDimitry Andric   if (auto *LoadMI = getOpcodeDef<GSExtLoad>(LoadUser, MRI)) {
820e8d8bef9SDimitry Andric     // If truncating more than the original extended value, abort.
821fe6060f1SDimitry Andric     auto LoadSizeBits = LoadMI->getMemSizeInBits();
822fe6060f1SDimitry Andric     if (TruncSrc && MRI.getType(TruncSrc).getSizeInBits() < LoadSizeBits)
823e8d8bef9SDimitry Andric       return false;
824fe6060f1SDimitry Andric     if (LoadSizeBits == SizeInBits)
825e8d8bef9SDimitry Andric       return true;
826e8d8bef9SDimitry Andric   }
827e8d8bef9SDimitry Andric   return false;
8285ffd83dbSDimitry Andric }
8295ffd83dbSDimitry Andric 
830fe6060f1SDimitry Andric void CombinerHelper::applySextTruncSextLoad(MachineInstr &MI) {
8315ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
832e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
833e8d8bef9SDimitry Andric   Builder.buildCopy(MI.getOperand(0).getReg(), MI.getOperand(1).getReg());
834e8d8bef9SDimitry Andric   MI.eraseFromParent();
835e8d8bef9SDimitry Andric }
836e8d8bef9SDimitry Andric 
837e8d8bef9SDimitry Andric bool CombinerHelper::matchSextInRegOfLoad(
838e8d8bef9SDimitry Andric     MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
839e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
840e8d8bef9SDimitry Andric 
841753f127fSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
842753f127fSDimitry Andric   LLT RegTy = MRI.getType(DstReg);
843753f127fSDimitry Andric 
844e8d8bef9SDimitry Andric   // Only supports scalars for now.
845753f127fSDimitry Andric   if (RegTy.isVector())
846e8d8bef9SDimitry Andric     return false;
847e8d8bef9SDimitry Andric 
848e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
849fe6060f1SDimitry Andric   auto *LoadDef = getOpcodeDef<GLoad>(SrcReg, MRI);
850753f127fSDimitry Andric   if (!LoadDef || !MRI.hasOneNonDBGUse(DstReg))
851e8d8bef9SDimitry Andric     return false;
852e8d8bef9SDimitry Andric 
853753f127fSDimitry Andric   uint64_t MemBits = LoadDef->getMemSizeInBits();
854753f127fSDimitry Andric 
855e8d8bef9SDimitry Andric   // If the sign extend extends from a narrower width than the load's width,
856e8d8bef9SDimitry Andric   // then we can narrow the load width when we combine to a G_SEXTLOAD.
857e8d8bef9SDimitry Andric   // Avoid widening the load at all.
858753f127fSDimitry Andric   unsigned NewSizeBits = std::min((uint64_t)MI.getOperand(2).getImm(), MemBits);
859e8d8bef9SDimitry Andric 
860e8d8bef9SDimitry Andric   // Don't generate G_SEXTLOADs with a < 1 byte width.
861e8d8bef9SDimitry Andric   if (NewSizeBits < 8)
862e8d8bef9SDimitry Andric     return false;
863e8d8bef9SDimitry Andric   // Don't bother creating a non-power-2 sextload, it will likely be broken up
864e8d8bef9SDimitry Andric   // anyway for most targets.
865e8d8bef9SDimitry Andric   if (!isPowerOf2_32(NewSizeBits))
866e8d8bef9SDimitry Andric     return false;
867349cc55cSDimitry Andric 
868349cc55cSDimitry Andric   const MachineMemOperand &MMO = LoadDef->getMMO();
869349cc55cSDimitry Andric   LegalityQuery::MemDesc MMDesc(MMO);
870753f127fSDimitry Andric 
871753f127fSDimitry Andric   // Don't modify the memory access size if this is atomic/volatile, but we can
872753f127fSDimitry Andric   // still adjust the opcode to indicate the high bit behavior.
873753f127fSDimitry Andric   if (LoadDef->isSimple())
874349cc55cSDimitry Andric     MMDesc.MemoryTy = LLT::scalar(NewSizeBits);
875753f127fSDimitry Andric   else if (MemBits > NewSizeBits || MemBits == RegTy.getSizeInBits())
876753f127fSDimitry Andric     return false;
877753f127fSDimitry Andric 
878753f127fSDimitry Andric   // TODO: Could check if it's legal with the reduced or original memory size.
879349cc55cSDimitry Andric   if (!isLegalOrBeforeLegalizer({TargetOpcode::G_SEXTLOAD,
880349cc55cSDimitry Andric                                  {MRI.getType(LoadDef->getDstReg()),
881349cc55cSDimitry Andric                                   MRI.getType(LoadDef->getPointerReg())},
882349cc55cSDimitry Andric                                  {MMDesc}}))
883349cc55cSDimitry Andric     return false;
884349cc55cSDimitry Andric 
885fe6060f1SDimitry Andric   MatchInfo = std::make_tuple(LoadDef->getDstReg(), NewSizeBits);
886e8d8bef9SDimitry Andric   return true;
887e8d8bef9SDimitry Andric }
888e8d8bef9SDimitry Andric 
889fe6060f1SDimitry Andric void CombinerHelper::applySextInRegOfLoad(
890e8d8bef9SDimitry Andric     MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
891e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
892e8d8bef9SDimitry Andric   Register LoadReg;
893e8d8bef9SDimitry Andric   unsigned ScalarSizeBits;
894e8d8bef9SDimitry Andric   std::tie(LoadReg, ScalarSizeBits) = MatchInfo;
895fe6060f1SDimitry Andric   GLoad *LoadDef = cast<GLoad>(MRI.getVRegDef(LoadReg));
896e8d8bef9SDimitry Andric 
897e8d8bef9SDimitry Andric   // If we have the following:
898e8d8bef9SDimitry Andric   // %ld = G_LOAD %ptr, (load 2)
899e8d8bef9SDimitry Andric   // %ext = G_SEXT_INREG %ld, 8
900e8d8bef9SDimitry Andric   //    ==>
901e8d8bef9SDimitry Andric   // %ld = G_SEXTLOAD %ptr (load 1)
902e8d8bef9SDimitry Andric 
903fe6060f1SDimitry Andric   auto &MMO = LoadDef->getMMO();
904fe6060f1SDimitry Andric   Builder.setInstrAndDebugLoc(*LoadDef);
905e8d8bef9SDimitry Andric   auto &MF = Builder.getMF();
906e8d8bef9SDimitry Andric   auto PtrInfo = MMO.getPointerInfo();
907e8d8bef9SDimitry Andric   auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, ScalarSizeBits / 8);
908e8d8bef9SDimitry Andric   Builder.buildLoadInstr(TargetOpcode::G_SEXTLOAD, MI.getOperand(0).getReg(),
909fe6060f1SDimitry Andric                          LoadDef->getPointerReg(), *NewMMO);
9105ffd83dbSDimitry Andric   MI.eraseFromParent();
9115ffd83dbSDimitry Andric }
9125ffd83dbSDimitry Andric 
9138bcb0991SDimitry Andric bool CombinerHelper::findPostIndexCandidate(MachineInstr &MI, Register &Addr,
9148bcb0991SDimitry Andric                                             Register &Base, Register &Offset) {
9158bcb0991SDimitry Andric   auto &MF = *MI.getParent()->getParent();
9168bcb0991SDimitry Andric   const auto &TLI = *MF.getSubtarget().getTargetLowering();
9178bcb0991SDimitry Andric 
9188bcb0991SDimitry Andric #ifndef NDEBUG
9198bcb0991SDimitry Andric   unsigned Opcode = MI.getOpcode();
9208bcb0991SDimitry Andric   assert(Opcode == TargetOpcode::G_LOAD || Opcode == TargetOpcode::G_SEXTLOAD ||
9218bcb0991SDimitry Andric          Opcode == TargetOpcode::G_ZEXTLOAD || Opcode == TargetOpcode::G_STORE);
9228bcb0991SDimitry Andric #endif
9238bcb0991SDimitry Andric 
9248bcb0991SDimitry Andric   Base = MI.getOperand(1).getReg();
9258bcb0991SDimitry Andric   MachineInstr *BaseDef = MRI.getUniqueVRegDef(Base);
9268bcb0991SDimitry Andric   if (BaseDef && BaseDef->getOpcode() == TargetOpcode::G_FRAME_INDEX)
9278bcb0991SDimitry Andric     return false;
9288bcb0991SDimitry Andric 
9298bcb0991SDimitry Andric   LLVM_DEBUG(dbgs() << "Searching for post-indexing opportunity for: " << MI);
930e8d8bef9SDimitry Andric   // FIXME: The following use traversal needs a bail out for patholigical cases.
9315ffd83dbSDimitry Andric   for (auto &Use : MRI.use_nodbg_instructions(Base)) {
932480093f4SDimitry Andric     if (Use.getOpcode() != TargetOpcode::G_PTR_ADD)
9338bcb0991SDimitry Andric       continue;
9348bcb0991SDimitry Andric 
9358bcb0991SDimitry Andric     Offset = Use.getOperand(2).getReg();
9368bcb0991SDimitry Andric     if (!ForceLegalIndexing &&
9378bcb0991SDimitry Andric         !TLI.isIndexingLegal(MI, Base, Offset, /*IsPre*/ false, MRI)) {
9388bcb0991SDimitry Andric       LLVM_DEBUG(dbgs() << "    Ignoring candidate with illegal addrmode: "
9398bcb0991SDimitry Andric                         << Use);
9408bcb0991SDimitry Andric       continue;
9418bcb0991SDimitry Andric     }
9428bcb0991SDimitry Andric 
9438bcb0991SDimitry Andric     // Make sure the offset calculation is before the potentially indexed op.
9448bcb0991SDimitry Andric     // FIXME: we really care about dependency here. The offset calculation might
9458bcb0991SDimitry Andric     // be movable.
9468bcb0991SDimitry Andric     MachineInstr *OffsetDef = MRI.getUniqueVRegDef(Offset);
9478bcb0991SDimitry Andric     if (!OffsetDef || !dominates(*OffsetDef, MI)) {
9488bcb0991SDimitry Andric       LLVM_DEBUG(dbgs() << "    Ignoring candidate with offset after mem-op: "
9498bcb0991SDimitry Andric                         << Use);
9508bcb0991SDimitry Andric       continue;
9518bcb0991SDimitry Andric     }
9528bcb0991SDimitry Andric 
9538bcb0991SDimitry Andric     // FIXME: check whether all uses of Base are load/store with foldable
9548bcb0991SDimitry Andric     // addressing modes. If so, using the normal addr-modes is better than
9558bcb0991SDimitry Andric     // forming an indexed one.
9568bcb0991SDimitry Andric 
9578bcb0991SDimitry Andric     bool MemOpDominatesAddrUses = true;
9585ffd83dbSDimitry Andric     for (auto &PtrAddUse :
9595ffd83dbSDimitry Andric          MRI.use_nodbg_instructions(Use.getOperand(0).getReg())) {
960480093f4SDimitry Andric       if (!dominates(MI, PtrAddUse)) {
9618bcb0991SDimitry Andric         MemOpDominatesAddrUses = false;
9628bcb0991SDimitry Andric         break;
9638bcb0991SDimitry Andric       }
9648bcb0991SDimitry Andric     }
9658bcb0991SDimitry Andric 
9668bcb0991SDimitry Andric     if (!MemOpDominatesAddrUses) {
9678bcb0991SDimitry Andric       LLVM_DEBUG(
9688bcb0991SDimitry Andric           dbgs() << "    Ignoring candidate as memop does not dominate uses: "
9698bcb0991SDimitry Andric                  << Use);
9708bcb0991SDimitry Andric       continue;
9718bcb0991SDimitry Andric     }
9728bcb0991SDimitry Andric 
9738bcb0991SDimitry Andric     LLVM_DEBUG(dbgs() << "    Found match: " << Use);
9748bcb0991SDimitry Andric     Addr = Use.getOperand(0).getReg();
9758bcb0991SDimitry Andric     return true;
9768bcb0991SDimitry Andric   }
9778bcb0991SDimitry Andric 
9788bcb0991SDimitry Andric   return false;
9798bcb0991SDimitry Andric }
9808bcb0991SDimitry Andric 
9818bcb0991SDimitry Andric bool CombinerHelper::findPreIndexCandidate(MachineInstr &MI, Register &Addr,
9828bcb0991SDimitry Andric                                            Register &Base, Register &Offset) {
9838bcb0991SDimitry Andric   auto &MF = *MI.getParent()->getParent();
9848bcb0991SDimitry Andric   const auto &TLI = *MF.getSubtarget().getTargetLowering();
9858bcb0991SDimitry Andric 
9868bcb0991SDimitry Andric #ifndef NDEBUG
9878bcb0991SDimitry Andric   unsigned Opcode = MI.getOpcode();
9888bcb0991SDimitry Andric   assert(Opcode == TargetOpcode::G_LOAD || Opcode == TargetOpcode::G_SEXTLOAD ||
9898bcb0991SDimitry Andric          Opcode == TargetOpcode::G_ZEXTLOAD || Opcode == TargetOpcode::G_STORE);
9908bcb0991SDimitry Andric #endif
9918bcb0991SDimitry Andric 
9928bcb0991SDimitry Andric   Addr = MI.getOperand(1).getReg();
993480093f4SDimitry Andric   MachineInstr *AddrDef = getOpcodeDef(TargetOpcode::G_PTR_ADD, Addr, MRI);
9945ffd83dbSDimitry Andric   if (!AddrDef || MRI.hasOneNonDBGUse(Addr))
9958bcb0991SDimitry Andric     return false;
9968bcb0991SDimitry Andric 
9978bcb0991SDimitry Andric   Base = AddrDef->getOperand(1).getReg();
9988bcb0991SDimitry Andric   Offset = AddrDef->getOperand(2).getReg();
9998bcb0991SDimitry Andric 
10008bcb0991SDimitry Andric   LLVM_DEBUG(dbgs() << "Found potential pre-indexed load_store: " << MI);
10018bcb0991SDimitry Andric 
10028bcb0991SDimitry Andric   if (!ForceLegalIndexing &&
10038bcb0991SDimitry Andric       !TLI.isIndexingLegal(MI, Base, Offset, /*IsPre*/ true, MRI)) {
10048bcb0991SDimitry Andric     LLVM_DEBUG(dbgs() << "    Skipping, not legal for target");
10058bcb0991SDimitry Andric     return false;
10068bcb0991SDimitry Andric   }
10078bcb0991SDimitry Andric 
10088bcb0991SDimitry Andric   MachineInstr *BaseDef = getDefIgnoringCopies(Base, MRI);
10098bcb0991SDimitry Andric   if (BaseDef->getOpcode() == TargetOpcode::G_FRAME_INDEX) {
10108bcb0991SDimitry Andric     LLVM_DEBUG(dbgs() << "    Skipping, frame index would need copy anyway.");
10118bcb0991SDimitry Andric     return false;
10128bcb0991SDimitry Andric   }
10138bcb0991SDimitry Andric 
10148bcb0991SDimitry Andric   if (MI.getOpcode() == TargetOpcode::G_STORE) {
10158bcb0991SDimitry Andric     // Would require a copy.
10168bcb0991SDimitry Andric     if (Base == MI.getOperand(0).getReg()) {
10178bcb0991SDimitry Andric       LLVM_DEBUG(dbgs() << "    Skipping, storing base so need copy anyway.");
10188bcb0991SDimitry Andric       return false;
10198bcb0991SDimitry Andric     }
10208bcb0991SDimitry Andric 
10218bcb0991SDimitry Andric     // We're expecting one use of Addr in MI, but it could also be the
10228bcb0991SDimitry Andric     // value stored, which isn't actually dominated by the instruction.
10238bcb0991SDimitry Andric     if (MI.getOperand(0).getReg() == Addr) {
10248bcb0991SDimitry Andric       LLVM_DEBUG(dbgs() << "    Skipping, does not dominate all addr uses");
10258bcb0991SDimitry Andric       return false;
10268bcb0991SDimitry Andric     }
10278bcb0991SDimitry Andric   }
10288bcb0991SDimitry Andric 
1029480093f4SDimitry Andric   // FIXME: check whether all uses of the base pointer are constant PtrAdds.
1030480093f4SDimitry Andric   // That might allow us to end base's liveness here by adjusting the constant.
10318bcb0991SDimitry Andric 
10325ffd83dbSDimitry Andric   for (auto &UseMI : MRI.use_nodbg_instructions(Addr)) {
10338bcb0991SDimitry Andric     if (!dominates(MI, UseMI)) {
10348bcb0991SDimitry Andric       LLVM_DEBUG(dbgs() << "    Skipping, does not dominate all addr uses.");
10358bcb0991SDimitry Andric       return false;
10368bcb0991SDimitry Andric     }
10378bcb0991SDimitry Andric   }
10388bcb0991SDimitry Andric 
10398bcb0991SDimitry Andric   return true;
10408bcb0991SDimitry Andric }
10418bcb0991SDimitry Andric 
10428bcb0991SDimitry Andric bool CombinerHelper::tryCombineIndexedLoadStore(MachineInstr &MI) {
1043480093f4SDimitry Andric   IndexedLoadStoreMatchInfo MatchInfo;
1044480093f4SDimitry Andric   if (matchCombineIndexedLoadStore(MI, MatchInfo)) {
1045480093f4SDimitry Andric     applyCombineIndexedLoadStore(MI, MatchInfo);
1046480093f4SDimitry Andric     return true;
1047480093f4SDimitry Andric   }
1048480093f4SDimitry Andric   return false;
1049480093f4SDimitry Andric }
1050480093f4SDimitry Andric 
1051480093f4SDimitry Andric bool CombinerHelper::matchCombineIndexedLoadStore(MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) {
10528bcb0991SDimitry Andric   unsigned Opcode = MI.getOpcode();
10538bcb0991SDimitry Andric   if (Opcode != TargetOpcode::G_LOAD && Opcode != TargetOpcode::G_SEXTLOAD &&
10548bcb0991SDimitry Andric       Opcode != TargetOpcode::G_ZEXTLOAD && Opcode != TargetOpcode::G_STORE)
10558bcb0991SDimitry Andric     return false;
10568bcb0991SDimitry Andric 
1057e8d8bef9SDimitry Andric   // For now, no targets actually support these opcodes so don't waste time
1058e8d8bef9SDimitry Andric   // running these unless we're forced to for testing.
1059e8d8bef9SDimitry Andric   if (!ForceLegalIndexing)
1060e8d8bef9SDimitry Andric     return false;
1061e8d8bef9SDimitry Andric 
1062480093f4SDimitry Andric   MatchInfo.IsPre = findPreIndexCandidate(MI, MatchInfo.Addr, MatchInfo.Base,
1063480093f4SDimitry Andric                                           MatchInfo.Offset);
1064480093f4SDimitry Andric   if (!MatchInfo.IsPre &&
1065480093f4SDimitry Andric       !findPostIndexCandidate(MI, MatchInfo.Addr, MatchInfo.Base,
1066480093f4SDimitry Andric                               MatchInfo.Offset))
10678bcb0991SDimitry Andric     return false;
10688bcb0991SDimitry Andric 
1069480093f4SDimitry Andric   return true;
1070480093f4SDimitry Andric }
10718bcb0991SDimitry Andric 
1072480093f4SDimitry Andric void CombinerHelper::applyCombineIndexedLoadStore(
1073480093f4SDimitry Andric     MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) {
1074480093f4SDimitry Andric   MachineInstr &AddrDef = *MRI.getUniqueVRegDef(MatchInfo.Addr);
1075480093f4SDimitry Andric   MachineIRBuilder MIRBuilder(MI);
1076480093f4SDimitry Andric   unsigned Opcode = MI.getOpcode();
1077480093f4SDimitry Andric   bool IsStore = Opcode == TargetOpcode::G_STORE;
10788bcb0991SDimitry Andric   unsigned NewOpcode;
10798bcb0991SDimitry Andric   switch (Opcode) {
10808bcb0991SDimitry Andric   case TargetOpcode::G_LOAD:
10818bcb0991SDimitry Andric     NewOpcode = TargetOpcode::G_INDEXED_LOAD;
10828bcb0991SDimitry Andric     break;
10838bcb0991SDimitry Andric   case TargetOpcode::G_SEXTLOAD:
10848bcb0991SDimitry Andric     NewOpcode = TargetOpcode::G_INDEXED_SEXTLOAD;
10858bcb0991SDimitry Andric     break;
10868bcb0991SDimitry Andric   case TargetOpcode::G_ZEXTLOAD:
10878bcb0991SDimitry Andric     NewOpcode = TargetOpcode::G_INDEXED_ZEXTLOAD;
10888bcb0991SDimitry Andric     break;
10898bcb0991SDimitry Andric   case TargetOpcode::G_STORE:
10908bcb0991SDimitry Andric     NewOpcode = TargetOpcode::G_INDEXED_STORE;
10918bcb0991SDimitry Andric     break;
10928bcb0991SDimitry Andric   default:
10938bcb0991SDimitry Andric     llvm_unreachable("Unknown load/store opcode");
10948bcb0991SDimitry Andric   }
10958bcb0991SDimitry Andric 
10968bcb0991SDimitry Andric   auto MIB = MIRBuilder.buildInstr(NewOpcode);
10978bcb0991SDimitry Andric   if (IsStore) {
1098480093f4SDimitry Andric     MIB.addDef(MatchInfo.Addr);
10998bcb0991SDimitry Andric     MIB.addUse(MI.getOperand(0).getReg());
11008bcb0991SDimitry Andric   } else {
11018bcb0991SDimitry Andric     MIB.addDef(MI.getOperand(0).getReg());
1102480093f4SDimitry Andric     MIB.addDef(MatchInfo.Addr);
11038bcb0991SDimitry Andric   }
11048bcb0991SDimitry Andric 
1105480093f4SDimitry Andric   MIB.addUse(MatchInfo.Base);
1106480093f4SDimitry Andric   MIB.addUse(MatchInfo.Offset);
1107480093f4SDimitry Andric   MIB.addImm(MatchInfo.IsPre);
11088bcb0991SDimitry Andric   MI.eraseFromParent();
11098bcb0991SDimitry Andric   AddrDef.eraseFromParent();
11108bcb0991SDimitry Andric 
11118bcb0991SDimitry Andric   LLVM_DEBUG(dbgs() << "    Combinined to indexed operation");
11128bcb0991SDimitry Andric }
11138bcb0991SDimitry Andric 
1114fe6060f1SDimitry Andric bool CombinerHelper::matchCombineDivRem(MachineInstr &MI,
1115fe6060f1SDimitry Andric                                         MachineInstr *&OtherMI) {
1116fe6060f1SDimitry Andric   unsigned Opcode = MI.getOpcode();
1117fe6060f1SDimitry Andric   bool IsDiv, IsSigned;
1118fe6060f1SDimitry Andric 
1119fe6060f1SDimitry Andric   switch (Opcode) {
1120fe6060f1SDimitry Andric   default:
1121fe6060f1SDimitry Andric     llvm_unreachable("Unexpected opcode!");
1122fe6060f1SDimitry Andric   case TargetOpcode::G_SDIV:
1123fe6060f1SDimitry Andric   case TargetOpcode::G_UDIV: {
1124fe6060f1SDimitry Andric     IsDiv = true;
1125fe6060f1SDimitry Andric     IsSigned = Opcode == TargetOpcode::G_SDIV;
1126fe6060f1SDimitry Andric     break;
1127fe6060f1SDimitry Andric   }
1128fe6060f1SDimitry Andric   case TargetOpcode::G_SREM:
1129fe6060f1SDimitry Andric   case TargetOpcode::G_UREM: {
1130fe6060f1SDimitry Andric     IsDiv = false;
1131fe6060f1SDimitry Andric     IsSigned = Opcode == TargetOpcode::G_SREM;
1132fe6060f1SDimitry Andric     break;
1133fe6060f1SDimitry Andric   }
1134fe6060f1SDimitry Andric   }
1135fe6060f1SDimitry Andric 
1136fe6060f1SDimitry Andric   Register Src1 = MI.getOperand(1).getReg();
1137fe6060f1SDimitry Andric   unsigned DivOpcode, RemOpcode, DivremOpcode;
1138fe6060f1SDimitry Andric   if (IsSigned) {
1139fe6060f1SDimitry Andric     DivOpcode = TargetOpcode::G_SDIV;
1140fe6060f1SDimitry Andric     RemOpcode = TargetOpcode::G_SREM;
1141fe6060f1SDimitry Andric     DivremOpcode = TargetOpcode::G_SDIVREM;
1142fe6060f1SDimitry Andric   } else {
1143fe6060f1SDimitry Andric     DivOpcode = TargetOpcode::G_UDIV;
1144fe6060f1SDimitry Andric     RemOpcode = TargetOpcode::G_UREM;
1145fe6060f1SDimitry Andric     DivremOpcode = TargetOpcode::G_UDIVREM;
1146fe6060f1SDimitry Andric   }
1147fe6060f1SDimitry Andric 
1148fe6060f1SDimitry Andric   if (!isLegalOrBeforeLegalizer({DivremOpcode, {MRI.getType(Src1)}}))
11498bcb0991SDimitry Andric     return false;
11508bcb0991SDimitry Andric 
1151fe6060f1SDimitry Andric   // Combine:
1152fe6060f1SDimitry Andric   //   %div:_ = G_[SU]DIV %src1:_, %src2:_
1153fe6060f1SDimitry Andric   //   %rem:_ = G_[SU]REM %src1:_, %src2:_
1154fe6060f1SDimitry Andric   // into:
1155fe6060f1SDimitry Andric   //  %div:_, %rem:_ = G_[SU]DIVREM %src1:_, %src2:_
1156fe6060f1SDimitry Andric 
1157fe6060f1SDimitry Andric   // Combine:
1158fe6060f1SDimitry Andric   //   %rem:_ = G_[SU]REM %src1:_, %src2:_
1159fe6060f1SDimitry Andric   //   %div:_ = G_[SU]DIV %src1:_, %src2:_
1160fe6060f1SDimitry Andric   // into:
1161fe6060f1SDimitry Andric   //  %div:_, %rem:_ = G_[SU]DIVREM %src1:_, %src2:_
1162fe6060f1SDimitry Andric 
1163fe6060f1SDimitry Andric   for (auto &UseMI : MRI.use_nodbg_instructions(Src1)) {
1164fe6060f1SDimitry Andric     if (MI.getParent() == UseMI.getParent() &&
1165fe6060f1SDimitry Andric         ((IsDiv && UseMI.getOpcode() == RemOpcode) ||
1166fe6060f1SDimitry Andric          (!IsDiv && UseMI.getOpcode() == DivOpcode)) &&
1167972a253aSDimitry Andric         matchEqualDefs(MI.getOperand(2), UseMI.getOperand(2)) &&
1168972a253aSDimitry Andric         matchEqualDefs(MI.getOperand(1), UseMI.getOperand(1))) {
1169fe6060f1SDimitry Andric       OtherMI = &UseMI;
1170fe6060f1SDimitry Andric       return true;
1171fe6060f1SDimitry Andric     }
1172fe6060f1SDimitry Andric   }
1173fe6060f1SDimitry Andric 
1174fe6060f1SDimitry Andric   return false;
1175fe6060f1SDimitry Andric }
1176fe6060f1SDimitry Andric 
1177fe6060f1SDimitry Andric void CombinerHelper::applyCombineDivRem(MachineInstr &MI,
1178fe6060f1SDimitry Andric                                         MachineInstr *&OtherMI) {
1179fe6060f1SDimitry Andric   unsigned Opcode = MI.getOpcode();
1180fe6060f1SDimitry Andric   assert(OtherMI && "OtherMI shouldn't be empty.");
1181fe6060f1SDimitry Andric 
1182fe6060f1SDimitry Andric   Register DestDivReg, DestRemReg;
1183fe6060f1SDimitry Andric   if (Opcode == TargetOpcode::G_SDIV || Opcode == TargetOpcode::G_UDIV) {
1184fe6060f1SDimitry Andric     DestDivReg = MI.getOperand(0).getReg();
1185fe6060f1SDimitry Andric     DestRemReg = OtherMI->getOperand(0).getReg();
1186fe6060f1SDimitry Andric   } else {
1187fe6060f1SDimitry Andric     DestDivReg = OtherMI->getOperand(0).getReg();
1188fe6060f1SDimitry Andric     DestRemReg = MI.getOperand(0).getReg();
1189fe6060f1SDimitry Andric   }
1190fe6060f1SDimitry Andric 
1191fe6060f1SDimitry Andric   bool IsSigned =
1192fe6060f1SDimitry Andric       Opcode == TargetOpcode::G_SDIV || Opcode == TargetOpcode::G_SREM;
1193fe6060f1SDimitry Andric 
1194fe6060f1SDimitry Andric   // Check which instruction is first in the block so we don't break def-use
1195*06c3fb27SDimitry Andric   // deps by "moving" the instruction incorrectly. Also keep track of which
1196*06c3fb27SDimitry Andric   // instruction is first so we pick it's operands, avoiding use-before-def
1197*06c3fb27SDimitry Andric   // bugs.
1198*06c3fb27SDimitry Andric   MachineInstr *FirstInst;
1199*06c3fb27SDimitry Andric   if (dominates(MI, *OtherMI)) {
1200fe6060f1SDimitry Andric     Builder.setInstrAndDebugLoc(MI);
1201*06c3fb27SDimitry Andric     FirstInst = &MI;
1202*06c3fb27SDimitry Andric   } else {
1203fe6060f1SDimitry Andric     Builder.setInstrAndDebugLoc(*OtherMI);
1204*06c3fb27SDimitry Andric     FirstInst = OtherMI;
1205*06c3fb27SDimitry Andric   }
1206fe6060f1SDimitry Andric 
1207fe6060f1SDimitry Andric   Builder.buildInstr(IsSigned ? TargetOpcode::G_SDIVREM
1208fe6060f1SDimitry Andric                               : TargetOpcode::G_UDIVREM,
1209fe6060f1SDimitry Andric                      {DestDivReg, DestRemReg},
1210*06c3fb27SDimitry Andric                      { FirstInst->getOperand(1), FirstInst->getOperand(2) });
1211fe6060f1SDimitry Andric   MI.eraseFromParent();
1212fe6060f1SDimitry Andric   OtherMI->eraseFromParent();
1213fe6060f1SDimitry Andric }
1214fe6060f1SDimitry Andric 
1215fe6060f1SDimitry Andric bool CombinerHelper::matchOptBrCondByInvertingCond(MachineInstr &MI,
1216fe6060f1SDimitry Andric                                                    MachineInstr *&BrCond) {
1217fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_BR);
1218fe6060f1SDimitry Andric 
12190b57cec5SDimitry Andric   // Try to match the following:
12200b57cec5SDimitry Andric   // bb1:
12210b57cec5SDimitry Andric   //   G_BRCOND %c1, %bb2
12220b57cec5SDimitry Andric   //   G_BR %bb3
12230b57cec5SDimitry Andric   // bb2:
12240b57cec5SDimitry Andric   // ...
12250b57cec5SDimitry Andric   // bb3:
12260b57cec5SDimitry Andric 
12270b57cec5SDimitry Andric   // The above pattern does not have a fall through to the successor bb2, always
12280b57cec5SDimitry Andric   // resulting in a branch no matter which path is taken. Here we try to find
12290b57cec5SDimitry Andric   // and replace that pattern with conditional branch to bb3 and otherwise
1230e8d8bef9SDimitry Andric   // fallthrough to bb2. This is generally better for branch predictors.
12310b57cec5SDimitry Andric 
12320b57cec5SDimitry Andric   MachineBasicBlock *MBB = MI.getParent();
12330b57cec5SDimitry Andric   MachineBasicBlock::iterator BrIt(MI);
12340b57cec5SDimitry Andric   if (BrIt == MBB->begin())
12350b57cec5SDimitry Andric     return false;
12360b57cec5SDimitry Andric   assert(std::next(BrIt) == MBB->end() && "expected G_BR to be a terminator");
12370b57cec5SDimitry Andric 
1238fe6060f1SDimitry Andric   BrCond = &*std::prev(BrIt);
12390b57cec5SDimitry Andric   if (BrCond->getOpcode() != TargetOpcode::G_BRCOND)
12400b57cec5SDimitry Andric     return false;
12410b57cec5SDimitry Andric 
1242d409305fSDimitry Andric   // Check that the next block is the conditional branch target. Also make sure
1243d409305fSDimitry Andric   // that it isn't the same as the G_BR's target (otherwise, this will loop.)
1244d409305fSDimitry Andric   MachineBasicBlock *BrCondTarget = BrCond->getOperand(1).getMBB();
1245d409305fSDimitry Andric   return BrCondTarget != MI.getOperand(0).getMBB() &&
1246d409305fSDimitry Andric          MBB->isLayoutSuccessor(BrCondTarget);
12470b57cec5SDimitry Andric }
12480b57cec5SDimitry Andric 
1249fe6060f1SDimitry Andric void CombinerHelper::applyOptBrCondByInvertingCond(MachineInstr &MI,
1250fe6060f1SDimitry Andric                                                    MachineInstr *&BrCond) {
12510b57cec5SDimitry Andric   MachineBasicBlock *BrTarget = MI.getOperand(0).getMBB();
1252e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(*BrCond);
1253e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(BrCond->getOperand(0).getReg());
1254e8d8bef9SDimitry Andric   // FIXME: Does int/fp matter for this? If so, we might need to restrict
1255e8d8bef9SDimitry Andric   // this to i1 only since we might not know for sure what kind of
1256e8d8bef9SDimitry Andric   // compare generated the condition value.
1257e8d8bef9SDimitry Andric   auto True = Builder.buildConstant(
1258e8d8bef9SDimitry Andric       Ty, getICmpTrueVal(getTargetLowering(), false, false));
1259e8d8bef9SDimitry Andric   auto Xor = Builder.buildXor(Ty, BrCond->getOperand(0), True);
12600b57cec5SDimitry Andric 
1261e8d8bef9SDimitry Andric   auto *FallthroughBB = BrCond->getOperand(1).getMBB();
1262e8d8bef9SDimitry Andric   Observer.changingInstr(MI);
1263e8d8bef9SDimitry Andric   MI.getOperand(0).setMBB(FallthroughBB);
1264e8d8bef9SDimitry Andric   Observer.changedInstr(MI);
12650b57cec5SDimitry Andric 
1266e8d8bef9SDimitry Andric   // Change the conditional branch to use the inverted condition and
1267e8d8bef9SDimitry Andric   // new target block.
12680b57cec5SDimitry Andric   Observer.changingInstr(*BrCond);
1269e8d8bef9SDimitry Andric   BrCond->getOperand(0).setReg(Xor.getReg(0));
12700b57cec5SDimitry Andric   BrCond->getOperand(1).setMBB(BrTarget);
12710b57cec5SDimitry Andric   Observer.changedInstr(*BrCond);
12728bcb0991SDimitry Andric }
12738bcb0991SDimitry Andric 
12748bcb0991SDimitry Andric static Type *getTypeForLLT(LLT Ty, LLVMContext &C) {
12758bcb0991SDimitry Andric   if (Ty.isVector())
12765ffd83dbSDimitry Andric     return FixedVectorType::get(IntegerType::get(C, Ty.getScalarSizeInBits()),
12778bcb0991SDimitry Andric                                 Ty.getNumElements());
12788bcb0991SDimitry Andric   return IntegerType::get(C, Ty.getSizeInBits());
12798bcb0991SDimitry Andric }
12808bcb0991SDimitry Andric 
1281fe6060f1SDimitry Andric bool CombinerHelper::tryEmitMemcpyInline(MachineInstr &MI) {
1282349cc55cSDimitry Andric   MachineIRBuilder HelperBuilder(MI);
1283349cc55cSDimitry Andric   GISelObserverWrapper DummyObserver;
1284349cc55cSDimitry Andric   LegalizerHelper Helper(HelperBuilder.getMF(), DummyObserver, HelperBuilder);
1285349cc55cSDimitry Andric   return Helper.lowerMemcpyInline(MI) ==
1286349cc55cSDimitry Andric          LegalizerHelper::LegalizeResult::Legalized;
12878bcb0991SDimitry Andric }
12888bcb0991SDimitry Andric 
12898bcb0991SDimitry Andric bool CombinerHelper::tryCombineMemCpyFamily(MachineInstr &MI, unsigned MaxLen) {
1290349cc55cSDimitry Andric   MachineIRBuilder HelperBuilder(MI);
1291349cc55cSDimitry Andric   GISelObserverWrapper DummyObserver;
1292349cc55cSDimitry Andric   LegalizerHelper Helper(HelperBuilder.getMF(), DummyObserver, HelperBuilder);
1293349cc55cSDimitry Andric   return Helper.lowerMemCpyFamily(MI, MaxLen) ==
1294349cc55cSDimitry Andric          LegalizerHelper::LegalizeResult::Legalized;
12958bcb0991SDimitry Andric }
12968bcb0991SDimitry Andric 
1297*06c3fb27SDimitry Andric static APFloat constantFoldFpUnary(const MachineInstr &MI,
1298*06c3fb27SDimitry Andric                                    const MachineRegisterInfo &MRI,
1299*06c3fb27SDimitry Andric                                    const APFloat &Val) {
1300*06c3fb27SDimitry Andric   APFloat Result(Val);
1301*06c3fb27SDimitry Andric   switch (MI.getOpcode()) {
1302e8d8bef9SDimitry Andric   default:
1303e8d8bef9SDimitry Andric     llvm_unreachable("Unexpected opcode!");
1304e8d8bef9SDimitry Andric   case TargetOpcode::G_FNEG: {
1305*06c3fb27SDimitry Andric     Result.changeSign();
1306*06c3fb27SDimitry Andric     return Result;
1307e8d8bef9SDimitry Andric   }
1308e8d8bef9SDimitry Andric   case TargetOpcode::G_FABS: {
1309*06c3fb27SDimitry Andric     Result.clearSign();
1310*06c3fb27SDimitry Andric     return Result;
1311e8d8bef9SDimitry Andric   }
1312*06c3fb27SDimitry Andric   case TargetOpcode::G_FPTRUNC: {
1313*06c3fb27SDimitry Andric     bool Unused;
1314*06c3fb27SDimitry Andric     LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
1315*06c3fb27SDimitry Andric     Result.convert(getFltSemanticForLLT(DstTy), APFloat::rmNearestTiesToEven,
1316*06c3fb27SDimitry Andric                    &Unused);
1317*06c3fb27SDimitry Andric     return Result;
1318*06c3fb27SDimitry Andric   }
1319e8d8bef9SDimitry Andric   case TargetOpcode::G_FSQRT: {
1320e8d8bef9SDimitry Andric     bool Unused;
1321*06c3fb27SDimitry Andric     Result.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
1322*06c3fb27SDimitry Andric                    &Unused);
1323*06c3fb27SDimitry Andric     Result = APFloat(sqrt(Result.convertToDouble()));
1324e8d8bef9SDimitry Andric     break;
1325e8d8bef9SDimitry Andric   }
1326e8d8bef9SDimitry Andric   case TargetOpcode::G_FLOG2: {
1327e8d8bef9SDimitry Andric     bool Unused;
1328*06c3fb27SDimitry Andric     Result.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
1329*06c3fb27SDimitry Andric                    &Unused);
1330*06c3fb27SDimitry Andric     Result = APFloat(log2(Result.convertToDouble()));
1331e8d8bef9SDimitry Andric     break;
1332e8d8bef9SDimitry Andric   }
1333e8d8bef9SDimitry Andric   }
1334e8d8bef9SDimitry Andric   // Convert `APFloat` to appropriate IEEE type depending on `DstTy`. Otherwise,
1335*06c3fb27SDimitry Andric   // `buildFConstant` will assert on size mismatch. Only `G_FSQRT`, and
1336*06c3fb27SDimitry Andric   // `G_FLOG2` reach here.
1337e8d8bef9SDimitry Andric   bool Unused;
1338*06c3fb27SDimitry Andric   Result.convert(Val.getSemantics(), APFloat::rmNearestTiesToEven, &Unused);
1339*06c3fb27SDimitry Andric   return Result;
1340e8d8bef9SDimitry Andric }
1341e8d8bef9SDimitry Andric 
1342*06c3fb27SDimitry Andric void CombinerHelper::applyCombineConstantFoldFpUnary(MachineInstr &MI,
1343*06c3fb27SDimitry Andric                                                      const ConstantFP *Cst) {
1344e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
1345*06c3fb27SDimitry Andric   APFloat Folded = constantFoldFpUnary(MI, MRI, Cst->getValue());
1346*06c3fb27SDimitry Andric   const ConstantFP *NewCst = ConstantFP::get(Builder.getContext(), Folded);
1347*06c3fb27SDimitry Andric   Builder.buildFConstant(MI.getOperand(0), *NewCst);
1348e8d8bef9SDimitry Andric   MI.eraseFromParent();
1349e8d8bef9SDimitry Andric }
1350e8d8bef9SDimitry Andric 
1351480093f4SDimitry Andric bool CombinerHelper::matchPtrAddImmedChain(MachineInstr &MI,
1352480093f4SDimitry Andric                                            PtrAddChain &MatchInfo) {
1353480093f4SDimitry Andric   // We're trying to match the following pattern:
1354480093f4SDimitry Andric   //   %t1 = G_PTR_ADD %base, G_CONSTANT imm1
1355480093f4SDimitry Andric   //   %root = G_PTR_ADD %t1, G_CONSTANT imm2
1356480093f4SDimitry Andric   // -->
1357480093f4SDimitry Andric   //   %root = G_PTR_ADD %base, G_CONSTANT (imm1 + imm2)
1358480093f4SDimitry Andric 
1359480093f4SDimitry Andric   if (MI.getOpcode() != TargetOpcode::G_PTR_ADD)
1360480093f4SDimitry Andric     return false;
1361480093f4SDimitry Andric 
1362480093f4SDimitry Andric   Register Add2 = MI.getOperand(1).getReg();
1363480093f4SDimitry Andric   Register Imm1 = MI.getOperand(2).getReg();
1364349cc55cSDimitry Andric   auto MaybeImmVal = getIConstantVRegValWithLookThrough(Imm1, MRI);
1365480093f4SDimitry Andric   if (!MaybeImmVal)
1366480093f4SDimitry Andric     return false;
1367480093f4SDimitry Andric 
1368349cc55cSDimitry Andric   MachineInstr *Add2Def = MRI.getVRegDef(Add2);
1369480093f4SDimitry Andric   if (!Add2Def || Add2Def->getOpcode() != TargetOpcode::G_PTR_ADD)
1370480093f4SDimitry Andric     return false;
1371480093f4SDimitry Andric 
1372480093f4SDimitry Andric   Register Base = Add2Def->getOperand(1).getReg();
1373480093f4SDimitry Andric   Register Imm2 = Add2Def->getOperand(2).getReg();
1374349cc55cSDimitry Andric   auto MaybeImm2Val = getIConstantVRegValWithLookThrough(Imm2, MRI);
1375480093f4SDimitry Andric   if (!MaybeImm2Val)
1376480093f4SDimitry Andric     return false;
1377480093f4SDimitry Andric 
1378349cc55cSDimitry Andric   // Check if the new combined immediate forms an illegal addressing mode.
1379349cc55cSDimitry Andric   // Do not combine if it was legal before but would get illegal.
1380349cc55cSDimitry Andric   // To do so, we need to find a load/store user of the pointer to get
1381349cc55cSDimitry Andric   // the access type.
1382349cc55cSDimitry Andric   Type *AccessTy = nullptr;
1383349cc55cSDimitry Andric   auto &MF = *MI.getMF();
1384349cc55cSDimitry Andric   for (auto &UseMI : MRI.use_nodbg_instructions(MI.getOperand(0).getReg())) {
1385349cc55cSDimitry Andric     if (auto *LdSt = dyn_cast<GLoadStore>(&UseMI)) {
1386349cc55cSDimitry Andric       AccessTy = getTypeForLLT(MRI.getType(LdSt->getReg(0)),
1387349cc55cSDimitry Andric                                MF.getFunction().getContext());
1388349cc55cSDimitry Andric       break;
1389349cc55cSDimitry Andric     }
1390349cc55cSDimitry Andric   }
1391349cc55cSDimitry Andric   TargetLoweringBase::AddrMode AMNew;
1392349cc55cSDimitry Andric   APInt CombinedImm = MaybeImmVal->Value + MaybeImm2Val->Value;
1393349cc55cSDimitry Andric   AMNew.BaseOffs = CombinedImm.getSExtValue();
1394349cc55cSDimitry Andric   if (AccessTy) {
1395349cc55cSDimitry Andric     AMNew.HasBaseReg = true;
1396349cc55cSDimitry Andric     TargetLoweringBase::AddrMode AMOld;
1397349cc55cSDimitry Andric     AMOld.BaseOffs = MaybeImm2Val->Value.getSExtValue();
1398349cc55cSDimitry Andric     AMOld.HasBaseReg = true;
1399349cc55cSDimitry Andric     unsigned AS = MRI.getType(Add2).getAddressSpace();
1400349cc55cSDimitry Andric     const auto &TLI = *MF.getSubtarget().getTargetLowering();
1401349cc55cSDimitry Andric     if (TLI.isLegalAddressingMode(MF.getDataLayout(), AMOld, AccessTy, AS) &&
1402349cc55cSDimitry Andric         !TLI.isLegalAddressingMode(MF.getDataLayout(), AMNew, AccessTy, AS))
1403349cc55cSDimitry Andric       return false;
1404349cc55cSDimitry Andric   }
1405349cc55cSDimitry Andric 
1406480093f4SDimitry Andric   // Pass the combined immediate to the apply function.
1407349cc55cSDimitry Andric   MatchInfo.Imm = AMNew.BaseOffs;
1408480093f4SDimitry Andric   MatchInfo.Base = Base;
1409349cc55cSDimitry Andric   MatchInfo.Bank = getRegBank(Imm2);
1410480093f4SDimitry Andric   return true;
1411480093f4SDimitry Andric }
1412480093f4SDimitry Andric 
1413fe6060f1SDimitry Andric void CombinerHelper::applyPtrAddImmedChain(MachineInstr &MI,
1414480093f4SDimitry Andric                                            PtrAddChain &MatchInfo) {
1415480093f4SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_PTR_ADD && "Expected G_PTR_ADD");
1416480093f4SDimitry Andric   MachineIRBuilder MIB(MI);
1417480093f4SDimitry Andric   LLT OffsetTy = MRI.getType(MI.getOperand(2).getReg());
1418480093f4SDimitry Andric   auto NewOffset = MIB.buildConstant(OffsetTy, MatchInfo.Imm);
1419349cc55cSDimitry Andric   setRegBank(NewOffset.getReg(0), MatchInfo.Bank);
1420480093f4SDimitry Andric   Observer.changingInstr(MI);
1421480093f4SDimitry Andric   MI.getOperand(1).setReg(MatchInfo.Base);
1422480093f4SDimitry Andric   MI.getOperand(2).setReg(NewOffset.getReg(0));
1423480093f4SDimitry Andric   Observer.changedInstr(MI);
1424480093f4SDimitry Andric }
1425480093f4SDimitry Andric 
1426e8d8bef9SDimitry Andric bool CombinerHelper::matchShiftImmedChain(MachineInstr &MI,
1427e8d8bef9SDimitry Andric                                           RegisterImmPair &MatchInfo) {
1428e8d8bef9SDimitry Andric   // We're trying to match the following pattern with any of
1429e8d8bef9SDimitry Andric   // G_SHL/G_ASHR/G_LSHR/G_SSHLSAT/G_USHLSAT shift instructions:
1430e8d8bef9SDimitry Andric   //   %t1 = SHIFT %base, G_CONSTANT imm1
1431e8d8bef9SDimitry Andric   //   %root = SHIFT %t1, G_CONSTANT imm2
1432e8d8bef9SDimitry Andric   // -->
1433e8d8bef9SDimitry Andric   //   %root = SHIFT %base, G_CONSTANT (imm1 + imm2)
1434e8d8bef9SDimitry Andric 
1435e8d8bef9SDimitry Andric   unsigned Opcode = MI.getOpcode();
1436e8d8bef9SDimitry Andric   assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR ||
1437e8d8bef9SDimitry Andric           Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_SSHLSAT ||
1438e8d8bef9SDimitry Andric           Opcode == TargetOpcode::G_USHLSAT) &&
1439e8d8bef9SDimitry Andric          "Expected G_SHL, G_ASHR, G_LSHR, G_SSHLSAT or G_USHLSAT");
1440e8d8bef9SDimitry Andric 
1441e8d8bef9SDimitry Andric   Register Shl2 = MI.getOperand(1).getReg();
1442e8d8bef9SDimitry Andric   Register Imm1 = MI.getOperand(2).getReg();
1443349cc55cSDimitry Andric   auto MaybeImmVal = getIConstantVRegValWithLookThrough(Imm1, MRI);
1444e8d8bef9SDimitry Andric   if (!MaybeImmVal)
1445e8d8bef9SDimitry Andric     return false;
1446e8d8bef9SDimitry Andric 
1447e8d8bef9SDimitry Andric   MachineInstr *Shl2Def = MRI.getUniqueVRegDef(Shl2);
1448e8d8bef9SDimitry Andric   if (Shl2Def->getOpcode() != Opcode)
1449e8d8bef9SDimitry Andric     return false;
1450e8d8bef9SDimitry Andric 
1451e8d8bef9SDimitry Andric   Register Base = Shl2Def->getOperand(1).getReg();
1452e8d8bef9SDimitry Andric   Register Imm2 = Shl2Def->getOperand(2).getReg();
1453349cc55cSDimitry Andric   auto MaybeImm2Val = getIConstantVRegValWithLookThrough(Imm2, MRI);
1454e8d8bef9SDimitry Andric   if (!MaybeImm2Val)
1455e8d8bef9SDimitry Andric     return false;
1456e8d8bef9SDimitry Andric 
1457e8d8bef9SDimitry Andric   // Pass the combined immediate to the apply function.
1458e8d8bef9SDimitry Andric   MatchInfo.Imm =
1459e8d8bef9SDimitry Andric       (MaybeImmVal->Value.getSExtValue() + MaybeImm2Val->Value).getSExtValue();
1460e8d8bef9SDimitry Andric   MatchInfo.Reg = Base;
1461e8d8bef9SDimitry Andric 
1462e8d8bef9SDimitry Andric   // There is no simple replacement for a saturating unsigned left shift that
1463e8d8bef9SDimitry Andric   // exceeds the scalar size.
1464e8d8bef9SDimitry Andric   if (Opcode == TargetOpcode::G_USHLSAT &&
1465e8d8bef9SDimitry Andric       MatchInfo.Imm >= MRI.getType(Shl2).getScalarSizeInBits())
1466e8d8bef9SDimitry Andric     return false;
1467e8d8bef9SDimitry Andric 
1468e8d8bef9SDimitry Andric   return true;
1469e8d8bef9SDimitry Andric }
1470e8d8bef9SDimitry Andric 
1471fe6060f1SDimitry Andric void CombinerHelper::applyShiftImmedChain(MachineInstr &MI,
1472e8d8bef9SDimitry Andric                                           RegisterImmPair &MatchInfo) {
1473e8d8bef9SDimitry Andric   unsigned Opcode = MI.getOpcode();
1474e8d8bef9SDimitry Andric   assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR ||
1475e8d8bef9SDimitry Andric           Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_SSHLSAT ||
1476e8d8bef9SDimitry Andric           Opcode == TargetOpcode::G_USHLSAT) &&
1477e8d8bef9SDimitry Andric          "Expected G_SHL, G_ASHR, G_LSHR, G_SSHLSAT or G_USHLSAT");
1478e8d8bef9SDimitry Andric 
1479e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
1480e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(MI.getOperand(1).getReg());
1481e8d8bef9SDimitry Andric   unsigned const ScalarSizeInBits = Ty.getScalarSizeInBits();
1482e8d8bef9SDimitry Andric   auto Imm = MatchInfo.Imm;
1483e8d8bef9SDimitry Andric 
1484e8d8bef9SDimitry Andric   if (Imm >= ScalarSizeInBits) {
1485e8d8bef9SDimitry Andric     // Any logical shift that exceeds scalar size will produce zero.
1486e8d8bef9SDimitry Andric     if (Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_LSHR) {
1487e8d8bef9SDimitry Andric       Builder.buildConstant(MI.getOperand(0), 0);
1488e8d8bef9SDimitry Andric       MI.eraseFromParent();
1489fe6060f1SDimitry Andric       return;
1490e8d8bef9SDimitry Andric     }
1491e8d8bef9SDimitry Andric     // Arithmetic shift and saturating signed left shift have no effect beyond
1492e8d8bef9SDimitry Andric     // scalar size.
1493e8d8bef9SDimitry Andric     Imm = ScalarSizeInBits - 1;
1494e8d8bef9SDimitry Andric   }
1495e8d8bef9SDimitry Andric 
1496e8d8bef9SDimitry Andric   LLT ImmTy = MRI.getType(MI.getOperand(2).getReg());
1497e8d8bef9SDimitry Andric   Register NewImm = Builder.buildConstant(ImmTy, Imm).getReg(0);
1498e8d8bef9SDimitry Andric   Observer.changingInstr(MI);
1499e8d8bef9SDimitry Andric   MI.getOperand(1).setReg(MatchInfo.Reg);
1500e8d8bef9SDimitry Andric   MI.getOperand(2).setReg(NewImm);
1501e8d8bef9SDimitry Andric   Observer.changedInstr(MI);
1502e8d8bef9SDimitry Andric }
1503e8d8bef9SDimitry Andric 
1504e8d8bef9SDimitry Andric bool CombinerHelper::matchShiftOfShiftedLogic(MachineInstr &MI,
1505e8d8bef9SDimitry Andric                                               ShiftOfShiftedLogic &MatchInfo) {
1506e8d8bef9SDimitry Andric   // We're trying to match the following pattern with any of
1507e8d8bef9SDimitry Andric   // G_SHL/G_ASHR/G_LSHR/G_USHLSAT/G_SSHLSAT shift instructions in combination
1508e8d8bef9SDimitry Andric   // with any of G_AND/G_OR/G_XOR logic instructions.
1509e8d8bef9SDimitry Andric   //   %t1 = SHIFT %X, G_CONSTANT C0
1510e8d8bef9SDimitry Andric   //   %t2 = LOGIC %t1, %Y
1511e8d8bef9SDimitry Andric   //   %root = SHIFT %t2, G_CONSTANT C1
1512e8d8bef9SDimitry Andric   // -->
1513e8d8bef9SDimitry Andric   //   %t3 = SHIFT %X, G_CONSTANT (C0+C1)
1514e8d8bef9SDimitry Andric   //   %t4 = SHIFT %Y, G_CONSTANT C1
1515e8d8bef9SDimitry Andric   //   %root = LOGIC %t3, %t4
1516e8d8bef9SDimitry Andric   unsigned ShiftOpcode = MI.getOpcode();
1517e8d8bef9SDimitry Andric   assert((ShiftOpcode == TargetOpcode::G_SHL ||
1518e8d8bef9SDimitry Andric           ShiftOpcode == TargetOpcode::G_ASHR ||
1519e8d8bef9SDimitry Andric           ShiftOpcode == TargetOpcode::G_LSHR ||
1520e8d8bef9SDimitry Andric           ShiftOpcode == TargetOpcode::G_USHLSAT ||
1521e8d8bef9SDimitry Andric           ShiftOpcode == TargetOpcode::G_SSHLSAT) &&
1522e8d8bef9SDimitry Andric          "Expected G_SHL, G_ASHR, G_LSHR, G_USHLSAT and G_SSHLSAT");
1523e8d8bef9SDimitry Andric 
1524e8d8bef9SDimitry Andric   // Match a one-use bitwise logic op.
1525e8d8bef9SDimitry Andric   Register LogicDest = MI.getOperand(1).getReg();
1526e8d8bef9SDimitry Andric   if (!MRI.hasOneNonDBGUse(LogicDest))
1527e8d8bef9SDimitry Andric     return false;
1528e8d8bef9SDimitry Andric 
1529e8d8bef9SDimitry Andric   MachineInstr *LogicMI = MRI.getUniqueVRegDef(LogicDest);
1530e8d8bef9SDimitry Andric   unsigned LogicOpcode = LogicMI->getOpcode();
1531e8d8bef9SDimitry Andric   if (LogicOpcode != TargetOpcode::G_AND && LogicOpcode != TargetOpcode::G_OR &&
1532e8d8bef9SDimitry Andric       LogicOpcode != TargetOpcode::G_XOR)
1533e8d8bef9SDimitry Andric     return false;
1534e8d8bef9SDimitry Andric 
1535e8d8bef9SDimitry Andric   // Find a matching one-use shift by constant.
1536e8d8bef9SDimitry Andric   const Register C1 = MI.getOperand(2).getReg();
1537349cc55cSDimitry Andric   auto MaybeImmVal = getIConstantVRegValWithLookThrough(C1, MRI);
1538e8d8bef9SDimitry Andric   if (!MaybeImmVal)
1539e8d8bef9SDimitry Andric     return false;
1540e8d8bef9SDimitry Andric 
1541e8d8bef9SDimitry Andric   const uint64_t C1Val = MaybeImmVal->Value.getZExtValue();
1542e8d8bef9SDimitry Andric 
1543e8d8bef9SDimitry Andric   auto matchFirstShift = [&](const MachineInstr *MI, uint64_t &ShiftVal) {
1544e8d8bef9SDimitry Andric     // Shift should match previous one and should be a one-use.
1545e8d8bef9SDimitry Andric     if (MI->getOpcode() != ShiftOpcode ||
1546e8d8bef9SDimitry Andric         !MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()))
1547e8d8bef9SDimitry Andric       return false;
1548e8d8bef9SDimitry Andric 
1549e8d8bef9SDimitry Andric     // Must be a constant.
1550e8d8bef9SDimitry Andric     auto MaybeImmVal =
1551349cc55cSDimitry Andric         getIConstantVRegValWithLookThrough(MI->getOperand(2).getReg(), MRI);
1552e8d8bef9SDimitry Andric     if (!MaybeImmVal)
1553e8d8bef9SDimitry Andric       return false;
1554e8d8bef9SDimitry Andric 
1555e8d8bef9SDimitry Andric     ShiftVal = MaybeImmVal->Value.getSExtValue();
1556e8d8bef9SDimitry Andric     return true;
1557e8d8bef9SDimitry Andric   };
1558e8d8bef9SDimitry Andric 
1559e8d8bef9SDimitry Andric   // Logic ops are commutative, so check each operand for a match.
1560e8d8bef9SDimitry Andric   Register LogicMIReg1 = LogicMI->getOperand(1).getReg();
1561e8d8bef9SDimitry Andric   MachineInstr *LogicMIOp1 = MRI.getUniqueVRegDef(LogicMIReg1);
1562e8d8bef9SDimitry Andric   Register LogicMIReg2 = LogicMI->getOperand(2).getReg();
1563e8d8bef9SDimitry Andric   MachineInstr *LogicMIOp2 = MRI.getUniqueVRegDef(LogicMIReg2);
1564e8d8bef9SDimitry Andric   uint64_t C0Val;
1565e8d8bef9SDimitry Andric 
1566e8d8bef9SDimitry Andric   if (matchFirstShift(LogicMIOp1, C0Val)) {
1567e8d8bef9SDimitry Andric     MatchInfo.LogicNonShiftReg = LogicMIReg2;
1568e8d8bef9SDimitry Andric     MatchInfo.Shift2 = LogicMIOp1;
1569e8d8bef9SDimitry Andric   } else if (matchFirstShift(LogicMIOp2, C0Val)) {
1570e8d8bef9SDimitry Andric     MatchInfo.LogicNonShiftReg = LogicMIReg1;
1571e8d8bef9SDimitry Andric     MatchInfo.Shift2 = LogicMIOp2;
1572e8d8bef9SDimitry Andric   } else
1573e8d8bef9SDimitry Andric     return false;
1574e8d8bef9SDimitry Andric 
1575e8d8bef9SDimitry Andric   MatchInfo.ValSum = C0Val + C1Val;
1576e8d8bef9SDimitry Andric 
1577e8d8bef9SDimitry Andric   // The fold is not valid if the sum of the shift values exceeds bitwidth.
1578e8d8bef9SDimitry Andric   if (MatchInfo.ValSum >= MRI.getType(LogicDest).getScalarSizeInBits())
1579e8d8bef9SDimitry Andric     return false;
1580e8d8bef9SDimitry Andric 
1581e8d8bef9SDimitry Andric   MatchInfo.Logic = LogicMI;
1582e8d8bef9SDimitry Andric   return true;
1583e8d8bef9SDimitry Andric }
1584e8d8bef9SDimitry Andric 
1585fe6060f1SDimitry Andric void CombinerHelper::applyShiftOfShiftedLogic(MachineInstr &MI,
1586e8d8bef9SDimitry Andric                                               ShiftOfShiftedLogic &MatchInfo) {
1587e8d8bef9SDimitry Andric   unsigned Opcode = MI.getOpcode();
1588e8d8bef9SDimitry Andric   assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR ||
1589e8d8bef9SDimitry Andric           Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_USHLSAT ||
1590e8d8bef9SDimitry Andric           Opcode == TargetOpcode::G_SSHLSAT) &&
1591e8d8bef9SDimitry Andric          "Expected G_SHL, G_ASHR, G_LSHR, G_USHLSAT and G_SSHLSAT");
1592e8d8bef9SDimitry Andric 
1593e8d8bef9SDimitry Andric   LLT ShlType = MRI.getType(MI.getOperand(2).getReg());
1594e8d8bef9SDimitry Andric   LLT DestType = MRI.getType(MI.getOperand(0).getReg());
1595e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
1596e8d8bef9SDimitry Andric 
1597e8d8bef9SDimitry Andric   Register Const = Builder.buildConstant(ShlType, MatchInfo.ValSum).getReg(0);
1598e8d8bef9SDimitry Andric 
1599e8d8bef9SDimitry Andric   Register Shift1Base = MatchInfo.Shift2->getOperand(1).getReg();
1600e8d8bef9SDimitry Andric   Register Shift1 =
1601e8d8bef9SDimitry Andric       Builder.buildInstr(Opcode, {DestType}, {Shift1Base, Const}).getReg(0);
1602e8d8bef9SDimitry Andric 
1603bdd1243dSDimitry Andric   // If LogicNonShiftReg is the same to Shift1Base, and shift1 const is the same
1604bdd1243dSDimitry Andric   // to MatchInfo.Shift2 const, CSEMIRBuilder will reuse the old shift1 when
1605bdd1243dSDimitry Andric   // build shift2. So, if we erase MatchInfo.Shift2 at the end, actually we
1606bdd1243dSDimitry Andric   // remove old shift1. And it will cause crash later. So erase it earlier to
1607bdd1243dSDimitry Andric   // avoid the crash.
1608bdd1243dSDimitry Andric   MatchInfo.Shift2->eraseFromParent();
1609bdd1243dSDimitry Andric 
1610e8d8bef9SDimitry Andric   Register Shift2Const = MI.getOperand(2).getReg();
1611e8d8bef9SDimitry Andric   Register Shift2 = Builder
1612e8d8bef9SDimitry Andric                         .buildInstr(Opcode, {DestType},
1613e8d8bef9SDimitry Andric                                     {MatchInfo.LogicNonShiftReg, Shift2Const})
1614e8d8bef9SDimitry Andric                         .getReg(0);
1615e8d8bef9SDimitry Andric 
1616e8d8bef9SDimitry Andric   Register Dest = MI.getOperand(0).getReg();
1617e8d8bef9SDimitry Andric   Builder.buildInstr(MatchInfo.Logic->getOpcode(), {Dest}, {Shift1, Shift2});
1618e8d8bef9SDimitry Andric 
1619bdd1243dSDimitry Andric   // This was one use so it's safe to remove it.
16200eae32dcSDimitry Andric   MatchInfo.Logic->eraseFromParent();
1621e8d8bef9SDimitry Andric 
1622e8d8bef9SDimitry Andric   MI.eraseFromParent();
1623e8d8bef9SDimitry Andric }
1624e8d8bef9SDimitry Andric 
1625*06c3fb27SDimitry Andric bool CombinerHelper::matchCommuteShift(MachineInstr &MI, BuildFnTy &MatchInfo) {
1626*06c3fb27SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SHL && "Expected G_SHL");
1627*06c3fb27SDimitry Andric   // Combine (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
1628*06c3fb27SDimitry Andric   // Combine (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
1629*06c3fb27SDimitry Andric   auto &Shl = cast<GenericMachineInstr>(MI);
1630*06c3fb27SDimitry Andric   Register DstReg = Shl.getReg(0);
1631*06c3fb27SDimitry Andric   Register SrcReg = Shl.getReg(1);
1632*06c3fb27SDimitry Andric   Register ShiftReg = Shl.getReg(2);
1633*06c3fb27SDimitry Andric   Register X, C1;
1634*06c3fb27SDimitry Andric 
1635*06c3fb27SDimitry Andric   if (!getTargetLowering().isDesirableToCommuteWithShift(MI, !isPreLegalize()))
1636*06c3fb27SDimitry Andric     return false;
1637*06c3fb27SDimitry Andric 
1638*06c3fb27SDimitry Andric   if (!mi_match(SrcReg, MRI,
1639*06c3fb27SDimitry Andric                 m_OneNonDBGUse(m_any_of(m_GAdd(m_Reg(X), m_Reg(C1)),
1640*06c3fb27SDimitry Andric                                         m_GOr(m_Reg(X), m_Reg(C1))))))
1641*06c3fb27SDimitry Andric     return false;
1642*06c3fb27SDimitry Andric 
1643*06c3fb27SDimitry Andric   APInt C1Val, C2Val;
1644*06c3fb27SDimitry Andric   if (!mi_match(C1, MRI, m_ICstOrSplat(C1Val)) ||
1645*06c3fb27SDimitry Andric       !mi_match(ShiftReg, MRI, m_ICstOrSplat(C2Val)))
1646*06c3fb27SDimitry Andric     return false;
1647*06c3fb27SDimitry Andric 
1648*06c3fb27SDimitry Andric   auto *SrcDef = MRI.getVRegDef(SrcReg);
1649*06c3fb27SDimitry Andric   assert((SrcDef->getOpcode() == TargetOpcode::G_ADD ||
1650*06c3fb27SDimitry Andric           SrcDef->getOpcode() == TargetOpcode::G_OR) && "Unexpected op");
1651*06c3fb27SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
1652*06c3fb27SDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
1653*06c3fb27SDimitry Andric     auto S1 = B.buildShl(SrcTy, X, ShiftReg);
1654*06c3fb27SDimitry Andric     auto S2 = B.buildShl(SrcTy, C1, ShiftReg);
1655*06c3fb27SDimitry Andric     B.buildInstr(SrcDef->getOpcode(), {DstReg}, {S1, S2});
1656*06c3fb27SDimitry Andric   };
1657*06c3fb27SDimitry Andric   return true;
1658*06c3fb27SDimitry Andric }
1659*06c3fb27SDimitry Andric 
16605ffd83dbSDimitry Andric bool CombinerHelper::matchCombineMulToShl(MachineInstr &MI,
16615ffd83dbSDimitry Andric                                           unsigned &ShiftVal) {
16625ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL");
16635ffd83dbSDimitry Andric   auto MaybeImmVal =
1664349cc55cSDimitry Andric       getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
1665e8d8bef9SDimitry Andric   if (!MaybeImmVal)
16665ffd83dbSDimitry Andric     return false;
1667e8d8bef9SDimitry Andric 
1668e8d8bef9SDimitry Andric   ShiftVal = MaybeImmVal->Value.exactLogBase2();
1669e8d8bef9SDimitry Andric   return (static_cast<int32_t>(ShiftVal) != -1);
16705ffd83dbSDimitry Andric }
16715ffd83dbSDimitry Andric 
1672fe6060f1SDimitry Andric void CombinerHelper::applyCombineMulToShl(MachineInstr &MI,
16735ffd83dbSDimitry Andric                                           unsigned &ShiftVal) {
16745ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL");
16755ffd83dbSDimitry Andric   MachineIRBuilder MIB(MI);
16765ffd83dbSDimitry Andric   LLT ShiftTy = MRI.getType(MI.getOperand(0).getReg());
16775ffd83dbSDimitry Andric   auto ShiftCst = MIB.buildConstant(ShiftTy, ShiftVal);
16785ffd83dbSDimitry Andric   Observer.changingInstr(MI);
16795ffd83dbSDimitry Andric   MI.setDesc(MIB.getTII().get(TargetOpcode::G_SHL));
16805ffd83dbSDimitry Andric   MI.getOperand(2).setReg(ShiftCst.getReg(0));
16815ffd83dbSDimitry Andric   Observer.changedInstr(MI);
16825ffd83dbSDimitry Andric }
16835ffd83dbSDimitry Andric 
1684e8d8bef9SDimitry Andric // shl ([sza]ext x), y => zext (shl x, y), if shift does not overflow source
1685e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineShlOfExtend(MachineInstr &MI,
1686e8d8bef9SDimitry Andric                                              RegisterImmPair &MatchData) {
1687e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SHL && KB);
1688e8d8bef9SDimitry Andric 
1689e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
1690e8d8bef9SDimitry Andric 
1691e8d8bef9SDimitry Andric   Register ExtSrc;
1692e8d8bef9SDimitry Andric   if (!mi_match(LHS, MRI, m_GAnyExt(m_Reg(ExtSrc))) &&
1693e8d8bef9SDimitry Andric       !mi_match(LHS, MRI, m_GZExt(m_Reg(ExtSrc))) &&
1694e8d8bef9SDimitry Andric       !mi_match(LHS, MRI, m_GSExt(m_Reg(ExtSrc))))
1695e8d8bef9SDimitry Andric     return false;
1696e8d8bef9SDimitry Andric 
1697e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
1698*06c3fb27SDimitry Andric   MachineInstr *MIShiftAmt = MRI.getVRegDef(RHS);
1699*06c3fb27SDimitry Andric   auto MaybeShiftAmtVal = isConstantOrConstantSplatVector(*MIShiftAmt, MRI);
1700e8d8bef9SDimitry Andric   if (!MaybeShiftAmtVal)
1701e8d8bef9SDimitry Andric     return false;
1702e8d8bef9SDimitry Andric 
1703e8d8bef9SDimitry Andric   if (LI) {
1704e8d8bef9SDimitry Andric     LLT SrcTy = MRI.getType(ExtSrc);
1705e8d8bef9SDimitry Andric 
1706e8d8bef9SDimitry Andric     // We only really care about the legality with the shifted value. We can
1707e8d8bef9SDimitry Andric     // pick any type the constant shift amount, so ask the target what to
1708e8d8bef9SDimitry Andric     // use. Otherwise we would have to guess and hope it is reported as legal.
1709e8d8bef9SDimitry Andric     LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(SrcTy);
1710e8d8bef9SDimitry Andric     if (!isLegalOrBeforeLegalizer({TargetOpcode::G_SHL, {SrcTy, ShiftAmtTy}}))
1711e8d8bef9SDimitry Andric       return false;
1712e8d8bef9SDimitry Andric   }
1713e8d8bef9SDimitry Andric 
1714*06c3fb27SDimitry Andric   int64_t ShiftAmt = MaybeShiftAmtVal->getSExtValue();
1715e8d8bef9SDimitry Andric   MatchData.Reg = ExtSrc;
1716e8d8bef9SDimitry Andric   MatchData.Imm = ShiftAmt;
1717e8d8bef9SDimitry Andric 
1718*06c3fb27SDimitry Andric   unsigned MinLeadingZeros = KB->getKnownZeroes(ExtSrc).countl_one();
1719*06c3fb27SDimitry Andric   unsigned SrcTySize = MRI.getType(ExtSrc).getScalarSizeInBits();
1720*06c3fb27SDimitry Andric   return MinLeadingZeros >= ShiftAmt && ShiftAmt < SrcTySize;
1721e8d8bef9SDimitry Andric }
1722e8d8bef9SDimitry Andric 
1723fe6060f1SDimitry Andric void CombinerHelper::applyCombineShlOfExtend(MachineInstr &MI,
1724e8d8bef9SDimitry Andric                                              const RegisterImmPair &MatchData) {
1725e8d8bef9SDimitry Andric   Register ExtSrcReg = MatchData.Reg;
1726e8d8bef9SDimitry Andric   int64_t ShiftAmtVal = MatchData.Imm;
1727e8d8bef9SDimitry Andric 
1728e8d8bef9SDimitry Andric   LLT ExtSrcTy = MRI.getType(ExtSrcReg);
1729e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
1730e8d8bef9SDimitry Andric   auto ShiftAmt = Builder.buildConstant(ExtSrcTy, ShiftAmtVal);
1731e8d8bef9SDimitry Andric   auto NarrowShift =
1732e8d8bef9SDimitry Andric       Builder.buildShl(ExtSrcTy, ExtSrcReg, ShiftAmt, MI.getFlags());
1733e8d8bef9SDimitry Andric   Builder.buildZExt(MI.getOperand(0), NarrowShift);
1734e8d8bef9SDimitry Andric   MI.eraseFromParent();
1735fe6060f1SDimitry Andric }
1736fe6060f1SDimitry Andric 
1737fe6060f1SDimitry Andric bool CombinerHelper::matchCombineMergeUnmerge(MachineInstr &MI,
1738fe6060f1SDimitry Andric                                               Register &MatchInfo) {
1739fe6060f1SDimitry Andric   GMerge &Merge = cast<GMerge>(MI);
1740fe6060f1SDimitry Andric   SmallVector<Register, 16> MergedValues;
1741fe6060f1SDimitry Andric   for (unsigned I = 0; I < Merge.getNumSources(); ++I)
1742fe6060f1SDimitry Andric     MergedValues.emplace_back(Merge.getSourceReg(I));
1743fe6060f1SDimitry Andric 
1744fe6060f1SDimitry Andric   auto *Unmerge = getOpcodeDef<GUnmerge>(MergedValues[0], MRI);
1745fe6060f1SDimitry Andric   if (!Unmerge || Unmerge->getNumDefs() != Merge.getNumSources())
1746fe6060f1SDimitry Andric     return false;
1747fe6060f1SDimitry Andric 
1748fe6060f1SDimitry Andric   for (unsigned I = 0; I < MergedValues.size(); ++I)
1749fe6060f1SDimitry Andric     if (MergedValues[I] != Unmerge->getReg(I))
1750fe6060f1SDimitry Andric       return false;
1751fe6060f1SDimitry Andric 
1752fe6060f1SDimitry Andric   MatchInfo = Unmerge->getSourceReg();
1753e8d8bef9SDimitry Andric   return true;
1754e8d8bef9SDimitry Andric }
1755e8d8bef9SDimitry Andric 
1756e8d8bef9SDimitry Andric static Register peekThroughBitcast(Register Reg,
1757e8d8bef9SDimitry Andric                                    const MachineRegisterInfo &MRI) {
1758e8d8bef9SDimitry Andric   while (mi_match(Reg, MRI, m_GBitcast(m_Reg(Reg))))
1759e8d8bef9SDimitry Andric     ;
1760e8d8bef9SDimitry Andric 
1761e8d8bef9SDimitry Andric   return Reg;
1762e8d8bef9SDimitry Andric }
1763e8d8bef9SDimitry Andric 
1764e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineUnmergeMergeToPlainValues(
1765e8d8bef9SDimitry Andric     MachineInstr &MI, SmallVectorImpl<Register> &Operands) {
1766e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1767e8d8bef9SDimitry Andric          "Expected an unmerge");
1768349cc55cSDimitry Andric   auto &Unmerge = cast<GUnmerge>(MI);
1769349cc55cSDimitry Andric   Register SrcReg = peekThroughBitcast(Unmerge.getSourceReg(), MRI);
1770e8d8bef9SDimitry Andric 
1771bdd1243dSDimitry Andric   auto *SrcInstr = getOpcodeDef<GMergeLikeInstr>(SrcReg, MRI);
1772349cc55cSDimitry Andric   if (!SrcInstr)
1773e8d8bef9SDimitry Andric     return false;
1774e8d8bef9SDimitry Andric 
1775e8d8bef9SDimitry Andric   // Check the source type of the merge.
1776349cc55cSDimitry Andric   LLT SrcMergeTy = MRI.getType(SrcInstr->getSourceReg(0));
1777349cc55cSDimitry Andric   LLT Dst0Ty = MRI.getType(Unmerge.getReg(0));
1778e8d8bef9SDimitry Andric   bool SameSize = Dst0Ty.getSizeInBits() == SrcMergeTy.getSizeInBits();
1779e8d8bef9SDimitry Andric   if (SrcMergeTy != Dst0Ty && !SameSize)
1780e8d8bef9SDimitry Andric     return false;
1781e8d8bef9SDimitry Andric   // They are the same now (modulo a bitcast).
1782e8d8bef9SDimitry Andric   // We can collect all the src registers.
1783349cc55cSDimitry Andric   for (unsigned Idx = 0; Idx < SrcInstr->getNumSources(); ++Idx)
1784349cc55cSDimitry Andric     Operands.push_back(SrcInstr->getSourceReg(Idx));
1785e8d8bef9SDimitry Andric   return true;
1786e8d8bef9SDimitry Andric }
1787e8d8bef9SDimitry Andric 
1788fe6060f1SDimitry Andric void CombinerHelper::applyCombineUnmergeMergeToPlainValues(
1789e8d8bef9SDimitry Andric     MachineInstr &MI, SmallVectorImpl<Register> &Operands) {
1790e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1791e8d8bef9SDimitry Andric          "Expected an unmerge");
1792e8d8bef9SDimitry Andric   assert((MI.getNumOperands() - 1 == Operands.size()) &&
1793e8d8bef9SDimitry Andric          "Not enough operands to replace all defs");
1794e8d8bef9SDimitry Andric   unsigned NumElems = MI.getNumOperands() - 1;
1795e8d8bef9SDimitry Andric 
1796e8d8bef9SDimitry Andric   LLT SrcTy = MRI.getType(Operands[0]);
1797e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
1798e8d8bef9SDimitry Andric   bool CanReuseInputDirectly = DstTy == SrcTy;
1799e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
1800e8d8bef9SDimitry Andric   for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
1801e8d8bef9SDimitry Andric     Register DstReg = MI.getOperand(Idx).getReg();
1802e8d8bef9SDimitry Andric     Register SrcReg = Operands[Idx];
1803*06c3fb27SDimitry Andric 
1804*06c3fb27SDimitry Andric     // This combine may run after RegBankSelect, so we need to be aware of
1805*06c3fb27SDimitry Andric     // register banks.
1806*06c3fb27SDimitry Andric     const auto &DstCB = MRI.getRegClassOrRegBank(DstReg);
1807*06c3fb27SDimitry Andric     if (!DstCB.isNull() && DstCB != MRI.getRegClassOrRegBank(SrcReg)) {
1808*06c3fb27SDimitry Andric       SrcReg = Builder.buildCopy(MRI.getType(SrcReg), SrcReg).getReg(0);
1809*06c3fb27SDimitry Andric       MRI.setRegClassOrRegBank(SrcReg, DstCB);
1810*06c3fb27SDimitry Andric     }
1811*06c3fb27SDimitry Andric 
1812e8d8bef9SDimitry Andric     if (CanReuseInputDirectly)
1813e8d8bef9SDimitry Andric       replaceRegWith(MRI, DstReg, SrcReg);
1814e8d8bef9SDimitry Andric     else
1815e8d8bef9SDimitry Andric       Builder.buildCast(DstReg, SrcReg);
1816e8d8bef9SDimitry Andric   }
1817e8d8bef9SDimitry Andric   MI.eraseFromParent();
1818e8d8bef9SDimitry Andric }
1819e8d8bef9SDimitry Andric 
1820e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineUnmergeConstant(MachineInstr &MI,
1821e8d8bef9SDimitry Andric                                                  SmallVectorImpl<APInt> &Csts) {
1822e8d8bef9SDimitry Andric   unsigned SrcIdx = MI.getNumOperands() - 1;
1823e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(SrcIdx).getReg();
1824e8d8bef9SDimitry Andric   MachineInstr *SrcInstr = MRI.getVRegDef(SrcReg);
1825e8d8bef9SDimitry Andric   if (SrcInstr->getOpcode() != TargetOpcode::G_CONSTANT &&
1826e8d8bef9SDimitry Andric       SrcInstr->getOpcode() != TargetOpcode::G_FCONSTANT)
1827e8d8bef9SDimitry Andric     return false;
1828e8d8bef9SDimitry Andric   // Break down the big constant in smaller ones.
1829e8d8bef9SDimitry Andric   const MachineOperand &CstVal = SrcInstr->getOperand(1);
1830e8d8bef9SDimitry Andric   APInt Val = SrcInstr->getOpcode() == TargetOpcode::G_CONSTANT
1831e8d8bef9SDimitry Andric                   ? CstVal.getCImm()->getValue()
1832e8d8bef9SDimitry Andric                   : CstVal.getFPImm()->getValueAPF().bitcastToAPInt();
1833e8d8bef9SDimitry Andric 
1834e8d8bef9SDimitry Andric   LLT Dst0Ty = MRI.getType(MI.getOperand(0).getReg());
1835e8d8bef9SDimitry Andric   unsigned ShiftAmt = Dst0Ty.getSizeInBits();
1836e8d8bef9SDimitry Andric   // Unmerge a constant.
1837e8d8bef9SDimitry Andric   for (unsigned Idx = 0; Idx != SrcIdx; ++Idx) {
1838e8d8bef9SDimitry Andric     Csts.emplace_back(Val.trunc(ShiftAmt));
1839e8d8bef9SDimitry Andric     Val = Val.lshr(ShiftAmt);
1840e8d8bef9SDimitry Andric   }
1841e8d8bef9SDimitry Andric 
1842e8d8bef9SDimitry Andric   return true;
1843e8d8bef9SDimitry Andric }
1844e8d8bef9SDimitry Andric 
1845fe6060f1SDimitry Andric void CombinerHelper::applyCombineUnmergeConstant(MachineInstr &MI,
1846e8d8bef9SDimitry Andric                                                  SmallVectorImpl<APInt> &Csts) {
1847e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1848e8d8bef9SDimitry Andric          "Expected an unmerge");
1849e8d8bef9SDimitry Andric   assert((MI.getNumOperands() - 1 == Csts.size()) &&
1850e8d8bef9SDimitry Andric          "Not enough operands to replace all defs");
1851e8d8bef9SDimitry Andric   unsigned NumElems = MI.getNumOperands() - 1;
1852e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
1853e8d8bef9SDimitry Andric   for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
1854e8d8bef9SDimitry Andric     Register DstReg = MI.getOperand(Idx).getReg();
1855e8d8bef9SDimitry Andric     Builder.buildConstant(DstReg, Csts[Idx]);
1856e8d8bef9SDimitry Andric   }
1857e8d8bef9SDimitry Andric 
1858e8d8bef9SDimitry Andric   MI.eraseFromParent();
1859e8d8bef9SDimitry Andric }
1860e8d8bef9SDimitry Andric 
186104eeddc0SDimitry Andric bool CombinerHelper::matchCombineUnmergeUndef(
186204eeddc0SDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
186304eeddc0SDimitry Andric   unsigned SrcIdx = MI.getNumOperands() - 1;
186404eeddc0SDimitry Andric   Register SrcReg = MI.getOperand(SrcIdx).getReg();
186504eeddc0SDimitry Andric   MatchInfo = [&MI](MachineIRBuilder &B) {
186604eeddc0SDimitry Andric     unsigned NumElems = MI.getNumOperands() - 1;
186704eeddc0SDimitry Andric     for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
186804eeddc0SDimitry Andric       Register DstReg = MI.getOperand(Idx).getReg();
186904eeddc0SDimitry Andric       B.buildUndef(DstReg);
187004eeddc0SDimitry Andric     }
187104eeddc0SDimitry Andric   };
187204eeddc0SDimitry Andric   return isa<GImplicitDef>(MRI.getVRegDef(SrcReg));
187304eeddc0SDimitry Andric }
187404eeddc0SDimitry Andric 
1875e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineUnmergeWithDeadLanesToTrunc(MachineInstr &MI) {
1876e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1877e8d8bef9SDimitry Andric          "Expected an unmerge");
1878e8d8bef9SDimitry Andric   // Check that all the lanes are dead except the first one.
1879e8d8bef9SDimitry Andric   for (unsigned Idx = 1, EndIdx = MI.getNumDefs(); Idx != EndIdx; ++Idx) {
1880e8d8bef9SDimitry Andric     if (!MRI.use_nodbg_empty(MI.getOperand(Idx).getReg()))
1881e8d8bef9SDimitry Andric       return false;
1882e8d8bef9SDimitry Andric   }
1883e8d8bef9SDimitry Andric   return true;
1884e8d8bef9SDimitry Andric }
1885e8d8bef9SDimitry Andric 
1886fe6060f1SDimitry Andric void CombinerHelper::applyCombineUnmergeWithDeadLanesToTrunc(MachineInstr &MI) {
1887e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
1888e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(MI.getNumDefs()).getReg();
1889e8d8bef9SDimitry Andric   // Truncating a vector is going to truncate every single lane,
1890e8d8bef9SDimitry Andric   // whereas we want the full lowbits.
1891e8d8bef9SDimitry Andric   // Do the operation on a scalar instead.
1892e8d8bef9SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
1893e8d8bef9SDimitry Andric   if (SrcTy.isVector())
1894e8d8bef9SDimitry Andric     SrcReg =
1895e8d8bef9SDimitry Andric         Builder.buildCast(LLT::scalar(SrcTy.getSizeInBits()), SrcReg).getReg(0);
1896e8d8bef9SDimitry Andric 
1897e8d8bef9SDimitry Andric   Register Dst0Reg = MI.getOperand(0).getReg();
1898e8d8bef9SDimitry Andric   LLT Dst0Ty = MRI.getType(Dst0Reg);
1899e8d8bef9SDimitry Andric   if (Dst0Ty.isVector()) {
1900e8d8bef9SDimitry Andric     auto MIB = Builder.buildTrunc(LLT::scalar(Dst0Ty.getSizeInBits()), SrcReg);
1901e8d8bef9SDimitry Andric     Builder.buildCast(Dst0Reg, MIB);
1902e8d8bef9SDimitry Andric   } else
1903e8d8bef9SDimitry Andric     Builder.buildTrunc(Dst0Reg, SrcReg);
1904e8d8bef9SDimitry Andric   MI.eraseFromParent();
1905e8d8bef9SDimitry Andric }
1906e8d8bef9SDimitry Andric 
1907e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineUnmergeZExtToZExt(MachineInstr &MI) {
1908e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1909e8d8bef9SDimitry Andric          "Expected an unmerge");
1910e8d8bef9SDimitry Andric   Register Dst0Reg = MI.getOperand(0).getReg();
1911e8d8bef9SDimitry Andric   LLT Dst0Ty = MRI.getType(Dst0Reg);
1912e8d8bef9SDimitry Andric   // G_ZEXT on vector applies to each lane, so it will
1913e8d8bef9SDimitry Andric   // affect all destinations. Therefore we won't be able
1914e8d8bef9SDimitry Andric   // to simplify the unmerge to just the first definition.
1915e8d8bef9SDimitry Andric   if (Dst0Ty.isVector())
1916e8d8bef9SDimitry Andric     return false;
1917e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(MI.getNumDefs()).getReg();
1918e8d8bef9SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
1919e8d8bef9SDimitry Andric   if (SrcTy.isVector())
1920e8d8bef9SDimitry Andric     return false;
1921e8d8bef9SDimitry Andric 
1922e8d8bef9SDimitry Andric   Register ZExtSrcReg;
1923e8d8bef9SDimitry Andric   if (!mi_match(SrcReg, MRI, m_GZExt(m_Reg(ZExtSrcReg))))
1924e8d8bef9SDimitry Andric     return false;
1925e8d8bef9SDimitry Andric 
1926e8d8bef9SDimitry Andric   // Finally we can replace the first definition with
1927e8d8bef9SDimitry Andric   // a zext of the source if the definition is big enough to hold
1928e8d8bef9SDimitry Andric   // all of ZExtSrc bits.
1929e8d8bef9SDimitry Andric   LLT ZExtSrcTy = MRI.getType(ZExtSrcReg);
1930e8d8bef9SDimitry Andric   return ZExtSrcTy.getSizeInBits() <= Dst0Ty.getSizeInBits();
1931e8d8bef9SDimitry Andric }
1932e8d8bef9SDimitry Andric 
1933fe6060f1SDimitry Andric void CombinerHelper::applyCombineUnmergeZExtToZExt(MachineInstr &MI) {
1934e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1935e8d8bef9SDimitry Andric          "Expected an unmerge");
1936e8d8bef9SDimitry Andric 
1937e8d8bef9SDimitry Andric   Register Dst0Reg = MI.getOperand(0).getReg();
1938e8d8bef9SDimitry Andric 
1939e8d8bef9SDimitry Andric   MachineInstr *ZExtInstr =
1940e8d8bef9SDimitry Andric       MRI.getVRegDef(MI.getOperand(MI.getNumDefs()).getReg());
1941e8d8bef9SDimitry Andric   assert(ZExtInstr && ZExtInstr->getOpcode() == TargetOpcode::G_ZEXT &&
1942e8d8bef9SDimitry Andric          "Expecting a G_ZEXT");
1943e8d8bef9SDimitry Andric 
1944e8d8bef9SDimitry Andric   Register ZExtSrcReg = ZExtInstr->getOperand(1).getReg();
1945e8d8bef9SDimitry Andric   LLT Dst0Ty = MRI.getType(Dst0Reg);
1946e8d8bef9SDimitry Andric   LLT ZExtSrcTy = MRI.getType(ZExtSrcReg);
1947e8d8bef9SDimitry Andric 
1948e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
1949e8d8bef9SDimitry Andric 
1950e8d8bef9SDimitry Andric   if (Dst0Ty.getSizeInBits() > ZExtSrcTy.getSizeInBits()) {
1951e8d8bef9SDimitry Andric     Builder.buildZExt(Dst0Reg, ZExtSrcReg);
1952e8d8bef9SDimitry Andric   } else {
1953e8d8bef9SDimitry Andric     assert(Dst0Ty.getSizeInBits() == ZExtSrcTy.getSizeInBits() &&
1954e8d8bef9SDimitry Andric            "ZExt src doesn't fit in destination");
1955e8d8bef9SDimitry Andric     replaceRegWith(MRI, Dst0Reg, ZExtSrcReg);
1956e8d8bef9SDimitry Andric   }
1957e8d8bef9SDimitry Andric 
1958e8d8bef9SDimitry Andric   Register ZeroReg;
1959e8d8bef9SDimitry Andric   for (unsigned Idx = 1, EndIdx = MI.getNumDefs(); Idx != EndIdx; ++Idx) {
1960e8d8bef9SDimitry Andric     if (!ZeroReg)
1961e8d8bef9SDimitry Andric       ZeroReg = Builder.buildConstant(Dst0Ty, 0).getReg(0);
1962e8d8bef9SDimitry Andric     replaceRegWith(MRI, MI.getOperand(Idx).getReg(), ZeroReg);
1963e8d8bef9SDimitry Andric   }
1964e8d8bef9SDimitry Andric   MI.eraseFromParent();
1965e8d8bef9SDimitry Andric }
1966e8d8bef9SDimitry Andric 
19675ffd83dbSDimitry Andric bool CombinerHelper::matchCombineShiftToUnmerge(MachineInstr &MI,
19685ffd83dbSDimitry Andric                                                 unsigned TargetShiftSize,
19695ffd83dbSDimitry Andric                                                 unsigned &ShiftVal) {
19705ffd83dbSDimitry Andric   assert((MI.getOpcode() == TargetOpcode::G_SHL ||
19715ffd83dbSDimitry Andric           MI.getOpcode() == TargetOpcode::G_LSHR ||
19725ffd83dbSDimitry Andric           MI.getOpcode() == TargetOpcode::G_ASHR) && "Expected a shift");
19735ffd83dbSDimitry Andric 
19745ffd83dbSDimitry Andric   LLT Ty = MRI.getType(MI.getOperand(0).getReg());
19755ffd83dbSDimitry Andric   if (Ty.isVector()) // TODO:
19765ffd83dbSDimitry Andric     return false;
19775ffd83dbSDimitry Andric 
19785ffd83dbSDimitry Andric   // Don't narrow further than the requested size.
19795ffd83dbSDimitry Andric   unsigned Size = Ty.getSizeInBits();
19805ffd83dbSDimitry Andric   if (Size <= TargetShiftSize)
19815ffd83dbSDimitry Andric     return false;
19825ffd83dbSDimitry Andric 
19835ffd83dbSDimitry Andric   auto MaybeImmVal =
1984349cc55cSDimitry Andric       getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
19855ffd83dbSDimitry Andric   if (!MaybeImmVal)
19865ffd83dbSDimitry Andric     return false;
19875ffd83dbSDimitry Andric 
1988e8d8bef9SDimitry Andric   ShiftVal = MaybeImmVal->Value.getSExtValue();
19895ffd83dbSDimitry Andric   return ShiftVal >= Size / 2 && ShiftVal < Size;
19905ffd83dbSDimitry Andric }
19915ffd83dbSDimitry Andric 
1992fe6060f1SDimitry Andric void CombinerHelper::applyCombineShiftToUnmerge(MachineInstr &MI,
19935ffd83dbSDimitry Andric                                                 const unsigned &ShiftVal) {
19945ffd83dbSDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
19955ffd83dbSDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
19965ffd83dbSDimitry Andric   LLT Ty = MRI.getType(SrcReg);
19975ffd83dbSDimitry Andric   unsigned Size = Ty.getSizeInBits();
19985ffd83dbSDimitry Andric   unsigned HalfSize = Size / 2;
19995ffd83dbSDimitry Andric   assert(ShiftVal >= HalfSize);
20005ffd83dbSDimitry Andric 
20015ffd83dbSDimitry Andric   LLT HalfTy = LLT::scalar(HalfSize);
20025ffd83dbSDimitry Andric 
20035ffd83dbSDimitry Andric   Builder.setInstr(MI);
20045ffd83dbSDimitry Andric   auto Unmerge = Builder.buildUnmerge(HalfTy, SrcReg);
20055ffd83dbSDimitry Andric   unsigned NarrowShiftAmt = ShiftVal - HalfSize;
20065ffd83dbSDimitry Andric 
20075ffd83dbSDimitry Andric   if (MI.getOpcode() == TargetOpcode::G_LSHR) {
20085ffd83dbSDimitry Andric     Register Narrowed = Unmerge.getReg(1);
20095ffd83dbSDimitry Andric 
20105ffd83dbSDimitry Andric     //  dst = G_LSHR s64:x, C for C >= 32
20115ffd83dbSDimitry Andric     // =>
20125ffd83dbSDimitry Andric     //   lo, hi = G_UNMERGE_VALUES x
20135ffd83dbSDimitry Andric     //   dst = G_MERGE_VALUES (G_LSHR hi, C - 32), 0
20145ffd83dbSDimitry Andric 
20155ffd83dbSDimitry Andric     if (NarrowShiftAmt != 0) {
20165ffd83dbSDimitry Andric       Narrowed = Builder.buildLShr(HalfTy, Narrowed,
20175ffd83dbSDimitry Andric         Builder.buildConstant(HalfTy, NarrowShiftAmt)).getReg(0);
20185ffd83dbSDimitry Andric     }
20195ffd83dbSDimitry Andric 
20205ffd83dbSDimitry Andric     auto Zero = Builder.buildConstant(HalfTy, 0);
2021bdd1243dSDimitry Andric     Builder.buildMergeLikeInstr(DstReg, {Narrowed, Zero});
20225ffd83dbSDimitry Andric   } else if (MI.getOpcode() == TargetOpcode::G_SHL) {
20235ffd83dbSDimitry Andric     Register Narrowed = Unmerge.getReg(0);
20245ffd83dbSDimitry Andric     //  dst = G_SHL s64:x, C for C >= 32
20255ffd83dbSDimitry Andric     // =>
20265ffd83dbSDimitry Andric     //   lo, hi = G_UNMERGE_VALUES x
20275ffd83dbSDimitry Andric     //   dst = G_MERGE_VALUES 0, (G_SHL hi, C - 32)
20285ffd83dbSDimitry Andric     if (NarrowShiftAmt != 0) {
20295ffd83dbSDimitry Andric       Narrowed = Builder.buildShl(HalfTy, Narrowed,
20305ffd83dbSDimitry Andric         Builder.buildConstant(HalfTy, NarrowShiftAmt)).getReg(0);
20315ffd83dbSDimitry Andric     }
20325ffd83dbSDimitry Andric 
20335ffd83dbSDimitry Andric     auto Zero = Builder.buildConstant(HalfTy, 0);
2034bdd1243dSDimitry Andric     Builder.buildMergeLikeInstr(DstReg, {Zero, Narrowed});
20355ffd83dbSDimitry Andric   } else {
20365ffd83dbSDimitry Andric     assert(MI.getOpcode() == TargetOpcode::G_ASHR);
20375ffd83dbSDimitry Andric     auto Hi = Builder.buildAShr(
20385ffd83dbSDimitry Andric       HalfTy, Unmerge.getReg(1),
20395ffd83dbSDimitry Andric       Builder.buildConstant(HalfTy, HalfSize - 1));
20405ffd83dbSDimitry Andric 
20415ffd83dbSDimitry Andric     if (ShiftVal == HalfSize) {
20425ffd83dbSDimitry Andric       // (G_ASHR i64:x, 32) ->
20435ffd83dbSDimitry Andric       //   G_MERGE_VALUES hi_32(x), (G_ASHR hi_32(x), 31)
2044bdd1243dSDimitry Andric       Builder.buildMergeLikeInstr(DstReg, {Unmerge.getReg(1), Hi});
20455ffd83dbSDimitry Andric     } else if (ShiftVal == Size - 1) {
20465ffd83dbSDimitry Andric       // Don't need a second shift.
20475ffd83dbSDimitry Andric       // (G_ASHR i64:x, 63) ->
20485ffd83dbSDimitry Andric       //   %narrowed = (G_ASHR hi_32(x), 31)
20495ffd83dbSDimitry Andric       //   G_MERGE_VALUES %narrowed, %narrowed
2050bdd1243dSDimitry Andric       Builder.buildMergeLikeInstr(DstReg, {Hi, Hi});
20515ffd83dbSDimitry Andric     } else {
20525ffd83dbSDimitry Andric       auto Lo = Builder.buildAShr(
20535ffd83dbSDimitry Andric         HalfTy, Unmerge.getReg(1),
20545ffd83dbSDimitry Andric         Builder.buildConstant(HalfTy, ShiftVal - HalfSize));
20555ffd83dbSDimitry Andric 
20565ffd83dbSDimitry Andric       // (G_ASHR i64:x, C) ->, for C >= 32
20575ffd83dbSDimitry Andric       //   G_MERGE_VALUES (G_ASHR hi_32(x), C - 32), (G_ASHR hi_32(x), 31)
2058bdd1243dSDimitry Andric       Builder.buildMergeLikeInstr(DstReg, {Lo, Hi});
20595ffd83dbSDimitry Andric     }
20605ffd83dbSDimitry Andric   }
20615ffd83dbSDimitry Andric 
20625ffd83dbSDimitry Andric   MI.eraseFromParent();
20635ffd83dbSDimitry Andric }
20645ffd83dbSDimitry Andric 
20655ffd83dbSDimitry Andric bool CombinerHelper::tryCombineShiftToUnmerge(MachineInstr &MI,
20665ffd83dbSDimitry Andric                                               unsigned TargetShiftAmount) {
20675ffd83dbSDimitry Andric   unsigned ShiftAmt;
20685ffd83dbSDimitry Andric   if (matchCombineShiftToUnmerge(MI, TargetShiftAmount, ShiftAmt)) {
20695ffd83dbSDimitry Andric     applyCombineShiftToUnmerge(MI, ShiftAmt);
20705ffd83dbSDimitry Andric     return true;
20715ffd83dbSDimitry Andric   }
20725ffd83dbSDimitry Andric 
20735ffd83dbSDimitry Andric   return false;
20745ffd83dbSDimitry Andric }
20755ffd83dbSDimitry Andric 
2076e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineI2PToP2I(MachineInstr &MI, Register &Reg) {
2077e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_INTTOPTR && "Expected a G_INTTOPTR");
2078e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2079e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
2080e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2081e8d8bef9SDimitry Andric   return mi_match(SrcReg, MRI,
2082e8d8bef9SDimitry Andric                   m_GPtrToInt(m_all_of(m_SpecificType(DstTy), m_Reg(Reg))));
2083e8d8bef9SDimitry Andric }
2084e8d8bef9SDimitry Andric 
2085fe6060f1SDimitry Andric void CombinerHelper::applyCombineI2PToP2I(MachineInstr &MI, Register &Reg) {
2086e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_INTTOPTR && "Expected a G_INTTOPTR");
2087e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2088e8d8bef9SDimitry Andric   Builder.setInstr(MI);
2089e8d8bef9SDimitry Andric   Builder.buildCopy(DstReg, Reg);
2090e8d8bef9SDimitry Andric   MI.eraseFromParent();
2091e8d8bef9SDimitry Andric }
2092e8d8bef9SDimitry Andric 
2093fe6060f1SDimitry Andric void CombinerHelper::applyCombineP2IToI2P(MachineInstr &MI, Register &Reg) {
2094e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_PTRTOINT && "Expected a G_PTRTOINT");
2095e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2096e8d8bef9SDimitry Andric   Builder.setInstr(MI);
2097e8d8bef9SDimitry Andric   Builder.buildZExtOrTrunc(DstReg, Reg);
2098e8d8bef9SDimitry Andric   MI.eraseFromParent();
2099e8d8bef9SDimitry Andric }
2100e8d8bef9SDimitry Andric 
2101e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineAddP2IToPtrAdd(
2102e8d8bef9SDimitry Andric     MachineInstr &MI, std::pair<Register, bool> &PtrReg) {
2103e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ADD);
2104e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
2105e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
2106e8d8bef9SDimitry Andric   LLT IntTy = MRI.getType(LHS);
2107e8d8bef9SDimitry Andric 
2108e8d8bef9SDimitry Andric   // G_PTR_ADD always has the pointer in the LHS, so we may need to commute the
2109e8d8bef9SDimitry Andric   // instruction.
2110e8d8bef9SDimitry Andric   PtrReg.second = false;
2111e8d8bef9SDimitry Andric   for (Register SrcReg : {LHS, RHS}) {
2112e8d8bef9SDimitry Andric     if (mi_match(SrcReg, MRI, m_GPtrToInt(m_Reg(PtrReg.first)))) {
2113e8d8bef9SDimitry Andric       // Don't handle cases where the integer is implicitly converted to the
2114e8d8bef9SDimitry Andric       // pointer width.
2115e8d8bef9SDimitry Andric       LLT PtrTy = MRI.getType(PtrReg.first);
2116e8d8bef9SDimitry Andric       if (PtrTy.getScalarSizeInBits() == IntTy.getScalarSizeInBits())
2117e8d8bef9SDimitry Andric         return true;
2118e8d8bef9SDimitry Andric     }
2119e8d8bef9SDimitry Andric 
2120e8d8bef9SDimitry Andric     PtrReg.second = true;
2121e8d8bef9SDimitry Andric   }
2122e8d8bef9SDimitry Andric 
2123e8d8bef9SDimitry Andric   return false;
2124e8d8bef9SDimitry Andric }
2125e8d8bef9SDimitry Andric 
2126fe6060f1SDimitry Andric void CombinerHelper::applyCombineAddP2IToPtrAdd(
2127e8d8bef9SDimitry Andric     MachineInstr &MI, std::pair<Register, bool> &PtrReg) {
2128e8d8bef9SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
2129e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
2130e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
2131e8d8bef9SDimitry Andric 
2132e8d8bef9SDimitry Andric   const bool DoCommute = PtrReg.second;
2133e8d8bef9SDimitry Andric   if (DoCommute)
2134e8d8bef9SDimitry Andric     std::swap(LHS, RHS);
2135e8d8bef9SDimitry Andric   LHS = PtrReg.first;
2136e8d8bef9SDimitry Andric 
2137e8d8bef9SDimitry Andric   LLT PtrTy = MRI.getType(LHS);
2138e8d8bef9SDimitry Andric 
2139e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
2140e8d8bef9SDimitry Andric   auto PtrAdd = Builder.buildPtrAdd(PtrTy, LHS, RHS);
2141e8d8bef9SDimitry Andric   Builder.buildPtrToInt(Dst, PtrAdd);
2142e8d8bef9SDimitry Andric   MI.eraseFromParent();
2143e8d8bef9SDimitry Andric }
2144e8d8bef9SDimitry Andric 
2145e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineConstPtrAddToI2P(MachineInstr &MI,
214604eeddc0SDimitry Andric                                                   APInt &NewCst) {
2147349cc55cSDimitry Andric   auto &PtrAdd = cast<GPtrAdd>(MI);
2148349cc55cSDimitry Andric   Register LHS = PtrAdd.getBaseReg();
2149349cc55cSDimitry Andric   Register RHS = PtrAdd.getOffsetReg();
2150e8d8bef9SDimitry Andric   MachineRegisterInfo &MRI = Builder.getMF().getRegInfo();
2151e8d8bef9SDimitry Andric 
215204eeddc0SDimitry Andric   if (auto RHSCst = getIConstantVRegVal(RHS, MRI)) {
215304eeddc0SDimitry Andric     APInt Cst;
2154e8d8bef9SDimitry Andric     if (mi_match(LHS, MRI, m_GIntToPtr(m_ICst(Cst)))) {
215504eeddc0SDimitry Andric       auto DstTy = MRI.getType(PtrAdd.getReg(0));
215604eeddc0SDimitry Andric       // G_INTTOPTR uses zero-extension
215704eeddc0SDimitry Andric       NewCst = Cst.zextOrTrunc(DstTy.getSizeInBits());
215804eeddc0SDimitry Andric       NewCst += RHSCst->sextOrTrunc(DstTy.getSizeInBits());
2159e8d8bef9SDimitry Andric       return true;
2160e8d8bef9SDimitry Andric     }
2161e8d8bef9SDimitry Andric   }
2162e8d8bef9SDimitry Andric 
2163e8d8bef9SDimitry Andric   return false;
2164e8d8bef9SDimitry Andric }
2165e8d8bef9SDimitry Andric 
2166fe6060f1SDimitry Andric void CombinerHelper::applyCombineConstPtrAddToI2P(MachineInstr &MI,
216704eeddc0SDimitry Andric                                                   APInt &NewCst) {
2168349cc55cSDimitry Andric   auto &PtrAdd = cast<GPtrAdd>(MI);
2169349cc55cSDimitry Andric   Register Dst = PtrAdd.getReg(0);
2170e8d8bef9SDimitry Andric 
2171e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
2172e8d8bef9SDimitry Andric   Builder.buildConstant(Dst, NewCst);
2173349cc55cSDimitry Andric   PtrAdd.eraseFromParent();
2174e8d8bef9SDimitry Andric }
2175e8d8bef9SDimitry Andric 
2176e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineAnyExtTrunc(MachineInstr &MI, Register &Reg) {
2177e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ANYEXT && "Expected a G_ANYEXT");
2178e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2179e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2180e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
2181e8d8bef9SDimitry Andric   return mi_match(SrcReg, MRI,
2182e8d8bef9SDimitry Andric                   m_GTrunc(m_all_of(m_Reg(Reg), m_SpecificType(DstTy))));
2183e8d8bef9SDimitry Andric }
2184e8d8bef9SDimitry Andric 
2185fe6060f1SDimitry Andric bool CombinerHelper::matchCombineZextTrunc(MachineInstr &MI, Register &Reg) {
2186fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ZEXT && "Expected a G_ZEXT");
2187e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2188fe6060f1SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2189fe6060f1SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
2190fe6060f1SDimitry Andric   if (mi_match(SrcReg, MRI,
2191fe6060f1SDimitry Andric                m_GTrunc(m_all_of(m_Reg(Reg), m_SpecificType(DstTy))))) {
2192fe6060f1SDimitry Andric     unsigned DstSize = DstTy.getScalarSizeInBits();
2193fe6060f1SDimitry Andric     unsigned SrcSize = MRI.getType(SrcReg).getScalarSizeInBits();
2194fe6060f1SDimitry Andric     return KB->getKnownBits(Reg).countMinLeadingZeros() >= DstSize - SrcSize;
2195fe6060f1SDimitry Andric   }
2196fe6060f1SDimitry Andric   return false;
2197e8d8bef9SDimitry Andric }
2198e8d8bef9SDimitry Andric 
2199e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineExtOfExt(
2200e8d8bef9SDimitry Andric     MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
2201e8d8bef9SDimitry Andric   assert((MI.getOpcode() == TargetOpcode::G_ANYEXT ||
2202e8d8bef9SDimitry Andric           MI.getOpcode() == TargetOpcode::G_SEXT ||
2203e8d8bef9SDimitry Andric           MI.getOpcode() == TargetOpcode::G_ZEXT) &&
2204e8d8bef9SDimitry Andric          "Expected a G_[ASZ]EXT");
2205e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2206e8d8bef9SDimitry Andric   MachineInstr *SrcMI = MRI.getVRegDef(SrcReg);
2207e8d8bef9SDimitry Andric   // Match exts with the same opcode, anyext([sz]ext) and sext(zext).
2208e8d8bef9SDimitry Andric   unsigned Opc = MI.getOpcode();
2209e8d8bef9SDimitry Andric   unsigned SrcOpc = SrcMI->getOpcode();
2210e8d8bef9SDimitry Andric   if (Opc == SrcOpc ||
2211e8d8bef9SDimitry Andric       (Opc == TargetOpcode::G_ANYEXT &&
2212e8d8bef9SDimitry Andric        (SrcOpc == TargetOpcode::G_SEXT || SrcOpc == TargetOpcode::G_ZEXT)) ||
2213e8d8bef9SDimitry Andric       (Opc == TargetOpcode::G_SEXT && SrcOpc == TargetOpcode::G_ZEXT)) {
2214e8d8bef9SDimitry Andric     MatchInfo = std::make_tuple(SrcMI->getOperand(1).getReg(), SrcOpc);
2215e8d8bef9SDimitry Andric     return true;
2216e8d8bef9SDimitry Andric   }
2217e8d8bef9SDimitry Andric   return false;
2218e8d8bef9SDimitry Andric }
2219e8d8bef9SDimitry Andric 
2220fe6060f1SDimitry Andric void CombinerHelper::applyCombineExtOfExt(
2221e8d8bef9SDimitry Andric     MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
2222e8d8bef9SDimitry Andric   assert((MI.getOpcode() == TargetOpcode::G_ANYEXT ||
2223e8d8bef9SDimitry Andric           MI.getOpcode() == TargetOpcode::G_SEXT ||
2224e8d8bef9SDimitry Andric           MI.getOpcode() == TargetOpcode::G_ZEXT) &&
2225e8d8bef9SDimitry Andric          "Expected a G_[ASZ]EXT");
2226e8d8bef9SDimitry Andric 
2227e8d8bef9SDimitry Andric   Register Reg = std::get<0>(MatchInfo);
2228e8d8bef9SDimitry Andric   unsigned SrcExtOp = std::get<1>(MatchInfo);
2229e8d8bef9SDimitry Andric 
2230e8d8bef9SDimitry Andric   // Combine exts with the same opcode.
2231e8d8bef9SDimitry Andric   if (MI.getOpcode() == SrcExtOp) {
2232e8d8bef9SDimitry Andric     Observer.changingInstr(MI);
2233e8d8bef9SDimitry Andric     MI.getOperand(1).setReg(Reg);
2234e8d8bef9SDimitry Andric     Observer.changedInstr(MI);
2235fe6060f1SDimitry Andric     return;
2236e8d8bef9SDimitry Andric   }
2237e8d8bef9SDimitry Andric 
2238e8d8bef9SDimitry Andric   // Combine:
2239e8d8bef9SDimitry Andric   // - anyext([sz]ext x) to [sz]ext x
2240e8d8bef9SDimitry Andric   // - sext(zext x) to zext x
2241e8d8bef9SDimitry Andric   if (MI.getOpcode() == TargetOpcode::G_ANYEXT ||
2242e8d8bef9SDimitry Andric       (MI.getOpcode() == TargetOpcode::G_SEXT &&
2243e8d8bef9SDimitry Andric        SrcExtOp == TargetOpcode::G_ZEXT)) {
2244e8d8bef9SDimitry Andric     Register DstReg = MI.getOperand(0).getReg();
2245e8d8bef9SDimitry Andric     Builder.setInstrAndDebugLoc(MI);
2246e8d8bef9SDimitry Andric     Builder.buildInstr(SrcExtOp, {DstReg}, {Reg});
2247e8d8bef9SDimitry Andric     MI.eraseFromParent();
2248fe6060f1SDimitry Andric   }
2249e8d8bef9SDimitry Andric }
2250e8d8bef9SDimitry Andric 
2251fe6060f1SDimitry Andric void CombinerHelper::applyCombineMulByNegativeOne(MachineInstr &MI) {
2252e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL");
2253e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2254e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2255e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
2256e8d8bef9SDimitry Andric 
2257e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
2258e8d8bef9SDimitry Andric   Builder.buildSub(DstReg, Builder.buildConstant(DstTy, 0), SrcReg,
2259e8d8bef9SDimitry Andric                    MI.getFlags());
2260e8d8bef9SDimitry Andric   MI.eraseFromParent();
2261e8d8bef9SDimitry Andric }
2262e8d8bef9SDimitry Andric 
2263349cc55cSDimitry Andric bool CombinerHelper::matchCombineFAbsOfFNeg(MachineInstr &MI,
2264349cc55cSDimitry Andric                                             BuildFnTy &MatchInfo) {
2265349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FABS && "Expected a G_FABS");
2266349cc55cSDimitry Andric   Register Src = MI.getOperand(1).getReg();
2267349cc55cSDimitry Andric   Register NegSrc;
2268349cc55cSDimitry Andric 
2269349cc55cSDimitry Andric   if (!mi_match(Src, MRI, m_GFNeg(m_Reg(NegSrc))))
2270349cc55cSDimitry Andric     return false;
2271349cc55cSDimitry Andric 
2272349cc55cSDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
2273349cc55cSDimitry Andric     Observer.changingInstr(MI);
2274349cc55cSDimitry Andric     MI.getOperand(1).setReg(NegSrc);
2275349cc55cSDimitry Andric     Observer.changedInstr(MI);
2276349cc55cSDimitry Andric   };
2277349cc55cSDimitry Andric   return true;
2278349cc55cSDimitry Andric }
2279349cc55cSDimitry Andric 
2280e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineTruncOfExt(
2281e8d8bef9SDimitry Andric     MachineInstr &MI, std::pair<Register, unsigned> &MatchInfo) {
2282e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2283e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2284e8d8bef9SDimitry Andric   MachineInstr *SrcMI = MRI.getVRegDef(SrcReg);
2285e8d8bef9SDimitry Andric   unsigned SrcOpc = SrcMI->getOpcode();
2286e8d8bef9SDimitry Andric   if (SrcOpc == TargetOpcode::G_ANYEXT || SrcOpc == TargetOpcode::G_SEXT ||
2287e8d8bef9SDimitry Andric       SrcOpc == TargetOpcode::G_ZEXT) {
2288e8d8bef9SDimitry Andric     MatchInfo = std::make_pair(SrcMI->getOperand(1).getReg(), SrcOpc);
2289e8d8bef9SDimitry Andric     return true;
2290e8d8bef9SDimitry Andric   }
2291e8d8bef9SDimitry Andric   return false;
2292e8d8bef9SDimitry Andric }
2293e8d8bef9SDimitry Andric 
2294fe6060f1SDimitry Andric void CombinerHelper::applyCombineTruncOfExt(
2295e8d8bef9SDimitry Andric     MachineInstr &MI, std::pair<Register, unsigned> &MatchInfo) {
2296e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2297e8d8bef9SDimitry Andric   Register SrcReg = MatchInfo.first;
2298e8d8bef9SDimitry Andric   unsigned SrcExtOp = MatchInfo.second;
2299e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2300e8d8bef9SDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
2301e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
2302e8d8bef9SDimitry Andric   if (SrcTy == DstTy) {
2303e8d8bef9SDimitry Andric     MI.eraseFromParent();
2304e8d8bef9SDimitry Andric     replaceRegWith(MRI, DstReg, SrcReg);
2305fe6060f1SDimitry Andric     return;
2306e8d8bef9SDimitry Andric   }
2307e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
2308e8d8bef9SDimitry Andric   if (SrcTy.getSizeInBits() < DstTy.getSizeInBits())
2309e8d8bef9SDimitry Andric     Builder.buildInstr(SrcExtOp, {DstReg}, {SrcReg});
2310e8d8bef9SDimitry Andric   else
2311e8d8bef9SDimitry Andric     Builder.buildTrunc(DstReg, SrcReg);
2312e8d8bef9SDimitry Andric   MI.eraseFromParent();
2313e8d8bef9SDimitry Andric }
2314e8d8bef9SDimitry Andric 
2315bdd1243dSDimitry Andric static LLT getMidVTForTruncRightShiftCombine(LLT ShiftTy, LLT TruncTy) {
2316bdd1243dSDimitry Andric   const unsigned ShiftSize = ShiftTy.getScalarSizeInBits();
2317bdd1243dSDimitry Andric   const unsigned TruncSize = TruncTy.getScalarSizeInBits();
2318bdd1243dSDimitry Andric 
2319bdd1243dSDimitry Andric   // ShiftTy > 32 > TruncTy -> 32
2320bdd1243dSDimitry Andric   if (ShiftSize > 32 && TruncSize < 32)
2321bdd1243dSDimitry Andric     return ShiftTy.changeElementSize(32);
2322bdd1243dSDimitry Andric 
2323bdd1243dSDimitry Andric   // TODO: We could also reduce to 16 bits, but that's more target-dependent.
2324bdd1243dSDimitry Andric   //  Some targets like it, some don't, some only like it under certain
2325bdd1243dSDimitry Andric   //  conditions/processor versions, etc.
2326bdd1243dSDimitry Andric   //  A TL hook might be needed for this.
2327bdd1243dSDimitry Andric 
2328bdd1243dSDimitry Andric   // Don't combine
2329bdd1243dSDimitry Andric   return ShiftTy;
2330bdd1243dSDimitry Andric }
2331bdd1243dSDimitry Andric 
2332bdd1243dSDimitry Andric bool CombinerHelper::matchCombineTruncOfShift(
2333bdd1243dSDimitry Andric     MachineInstr &MI, std::pair<MachineInstr *, LLT> &MatchInfo) {
2334e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2335e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2336e8d8bef9SDimitry Andric   Register SrcReg = MI.getOperand(1).getReg();
2337e8d8bef9SDimitry Andric 
2338bdd1243dSDimitry Andric   if (!MRI.hasOneNonDBGUse(SrcReg))
2339bdd1243dSDimitry Andric     return false;
2340bdd1243dSDimitry Andric 
2341bdd1243dSDimitry Andric   LLT SrcTy = MRI.getType(SrcReg);
2342bdd1243dSDimitry Andric   LLT DstTy = MRI.getType(DstReg);
2343bdd1243dSDimitry Andric 
2344bdd1243dSDimitry Andric   MachineInstr *SrcMI = getDefIgnoringCopies(SrcReg, MRI);
2345bdd1243dSDimitry Andric   const auto &TL = getTargetLowering();
2346bdd1243dSDimitry Andric 
2347bdd1243dSDimitry Andric   LLT NewShiftTy;
2348bdd1243dSDimitry Andric   switch (SrcMI->getOpcode()) {
2349bdd1243dSDimitry Andric   default:
2350bdd1243dSDimitry Andric     return false;
2351bdd1243dSDimitry Andric   case TargetOpcode::G_SHL: {
2352bdd1243dSDimitry Andric     NewShiftTy = DstTy;
2353bdd1243dSDimitry Andric 
2354bdd1243dSDimitry Andric     // Make sure new shift amount is legal.
2355bdd1243dSDimitry Andric     KnownBits Known = KB->getKnownBits(SrcMI->getOperand(2).getReg());
2356bdd1243dSDimitry Andric     if (Known.getMaxValue().uge(NewShiftTy.getScalarSizeInBits()))
2357bdd1243dSDimitry Andric       return false;
2358bdd1243dSDimitry Andric     break;
2359bdd1243dSDimitry Andric   }
2360bdd1243dSDimitry Andric   case TargetOpcode::G_LSHR:
2361bdd1243dSDimitry Andric   case TargetOpcode::G_ASHR: {
2362bdd1243dSDimitry Andric     // For right shifts, we conservatively do not do the transform if the TRUNC
2363bdd1243dSDimitry Andric     // has any STORE users. The reason is that if we change the type of the
2364bdd1243dSDimitry Andric     // shift, we may break the truncstore combine.
2365bdd1243dSDimitry Andric     //
2366bdd1243dSDimitry Andric     // TODO: Fix truncstore combine to handle (trunc(lshr (trunc x), k)).
2367bdd1243dSDimitry Andric     for (auto &User : MRI.use_instructions(DstReg))
2368bdd1243dSDimitry Andric       if (User.getOpcode() == TargetOpcode::G_STORE)
2369bdd1243dSDimitry Andric         return false;
2370bdd1243dSDimitry Andric 
2371bdd1243dSDimitry Andric     NewShiftTy = getMidVTForTruncRightShiftCombine(SrcTy, DstTy);
2372bdd1243dSDimitry Andric     if (NewShiftTy == SrcTy)
2373bdd1243dSDimitry Andric       return false;
2374bdd1243dSDimitry Andric 
2375bdd1243dSDimitry Andric     // Make sure we won't lose information by truncating the high bits.
2376bdd1243dSDimitry Andric     KnownBits Known = KB->getKnownBits(SrcMI->getOperand(2).getReg());
2377bdd1243dSDimitry Andric     if (Known.getMaxValue().ugt(NewShiftTy.getScalarSizeInBits() -
2378bdd1243dSDimitry Andric                                 DstTy.getScalarSizeInBits()))
2379bdd1243dSDimitry Andric       return false;
2380bdd1243dSDimitry Andric     break;
2381bdd1243dSDimitry Andric   }
2382bdd1243dSDimitry Andric   }
2383bdd1243dSDimitry Andric 
2384bdd1243dSDimitry Andric   if (!isLegalOrBeforeLegalizer(
2385bdd1243dSDimitry Andric           {SrcMI->getOpcode(),
2386bdd1243dSDimitry Andric            {NewShiftTy, TL.getPreferredShiftAmountTy(NewShiftTy)}}))
2387bdd1243dSDimitry Andric     return false;
2388bdd1243dSDimitry Andric 
2389bdd1243dSDimitry Andric   MatchInfo = std::make_pair(SrcMI, NewShiftTy);
2390e8d8bef9SDimitry Andric   return true;
2391e8d8bef9SDimitry Andric }
2392e8d8bef9SDimitry Andric 
2393bdd1243dSDimitry Andric void CombinerHelper::applyCombineTruncOfShift(
2394bdd1243dSDimitry Andric     MachineInstr &MI, std::pair<MachineInstr *, LLT> &MatchInfo) {
2395e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
2396bdd1243dSDimitry Andric 
2397bdd1243dSDimitry Andric   MachineInstr *ShiftMI = MatchInfo.first;
2398bdd1243dSDimitry Andric   LLT NewShiftTy = MatchInfo.second;
2399bdd1243dSDimitry Andric 
2400bdd1243dSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
2401bdd1243dSDimitry Andric   LLT DstTy = MRI.getType(Dst);
2402bdd1243dSDimitry Andric 
2403bdd1243dSDimitry Andric   Register ShiftAmt = ShiftMI->getOperand(2).getReg();
2404bdd1243dSDimitry Andric   Register ShiftSrc = ShiftMI->getOperand(1).getReg();
2405bdd1243dSDimitry Andric   ShiftSrc = Builder.buildTrunc(NewShiftTy, ShiftSrc).getReg(0);
2406bdd1243dSDimitry Andric 
2407bdd1243dSDimitry Andric   Register NewShift =
2408bdd1243dSDimitry Andric       Builder
2409bdd1243dSDimitry Andric           .buildInstr(ShiftMI->getOpcode(), {NewShiftTy}, {ShiftSrc, ShiftAmt})
2410bdd1243dSDimitry Andric           .getReg(0);
2411bdd1243dSDimitry Andric 
2412bdd1243dSDimitry Andric   if (NewShiftTy == DstTy)
2413bdd1243dSDimitry Andric     replaceRegWith(MRI, Dst, NewShift);
2414bdd1243dSDimitry Andric   else
2415bdd1243dSDimitry Andric     Builder.buildTrunc(Dst, NewShift);
2416bdd1243dSDimitry Andric 
2417bdd1243dSDimitry Andric   eraseInst(MI);
2418e8d8bef9SDimitry Andric }
2419e8d8bef9SDimitry Andric 
24205ffd83dbSDimitry Andric bool CombinerHelper::matchAnyExplicitUseIsUndef(MachineInstr &MI) {
24215ffd83dbSDimitry Andric   return any_of(MI.explicit_uses(), [this](const MachineOperand &MO) {
24225ffd83dbSDimitry Andric     return MO.isReg() &&
24235ffd83dbSDimitry Andric            getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
24245ffd83dbSDimitry Andric   });
24255ffd83dbSDimitry Andric }
24265ffd83dbSDimitry Andric 
24275ffd83dbSDimitry Andric bool CombinerHelper::matchAllExplicitUsesAreUndef(MachineInstr &MI) {
24285ffd83dbSDimitry Andric   return all_of(MI.explicit_uses(), [this](const MachineOperand &MO) {
24295ffd83dbSDimitry Andric     return !MO.isReg() ||
24305ffd83dbSDimitry Andric            getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
24315ffd83dbSDimitry Andric   });
24325ffd83dbSDimitry Andric }
24335ffd83dbSDimitry Andric 
24345ffd83dbSDimitry Andric bool CombinerHelper::matchUndefShuffleVectorMask(MachineInstr &MI) {
24355ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR);
24365ffd83dbSDimitry Andric   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
24375ffd83dbSDimitry Andric   return all_of(Mask, [](int Elt) { return Elt < 0; });
24385ffd83dbSDimitry Andric }
24395ffd83dbSDimitry Andric 
24405ffd83dbSDimitry Andric bool CombinerHelper::matchUndefStore(MachineInstr &MI) {
24415ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_STORE);
24425ffd83dbSDimitry Andric   return getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MI.getOperand(0).getReg(),
24435ffd83dbSDimitry Andric                       MRI);
24445ffd83dbSDimitry Andric }
24455ffd83dbSDimitry Andric 
2446e8d8bef9SDimitry Andric bool CombinerHelper::matchUndefSelectCmp(MachineInstr &MI) {
2447e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SELECT);
2448e8d8bef9SDimitry Andric   return getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MI.getOperand(1).getReg(),
2449e8d8bef9SDimitry Andric                       MRI);
2450e8d8bef9SDimitry Andric }
2451e8d8bef9SDimitry Andric 
2452bdd1243dSDimitry Andric bool CombinerHelper::matchInsertExtractVecEltOutOfBounds(MachineInstr &MI) {
2453bdd1243dSDimitry Andric   assert((MI.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT ||
2454bdd1243dSDimitry Andric           MI.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT) &&
2455bdd1243dSDimitry Andric          "Expected an insert/extract element op");
2456bdd1243dSDimitry Andric   LLT VecTy = MRI.getType(MI.getOperand(1).getReg());
2457bdd1243dSDimitry Andric   unsigned IdxIdx =
2458bdd1243dSDimitry Andric       MI.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT ? 2 : 3;
2459bdd1243dSDimitry Andric   auto Idx = getIConstantVRegVal(MI.getOperand(IdxIdx).getReg(), MRI);
2460bdd1243dSDimitry Andric   if (!Idx)
2461bdd1243dSDimitry Andric     return false;
2462bdd1243dSDimitry Andric   return Idx->getZExtValue() >= VecTy.getNumElements();
2463bdd1243dSDimitry Andric }
2464bdd1243dSDimitry Andric 
2465e8d8bef9SDimitry Andric bool CombinerHelper::matchConstantSelectCmp(MachineInstr &MI, unsigned &OpIdx) {
2466349cc55cSDimitry Andric   GSelect &SelMI = cast<GSelect>(MI);
2467349cc55cSDimitry Andric   auto Cst =
2468349cc55cSDimitry Andric       isConstantOrConstantSplatVector(*MRI.getVRegDef(SelMI.getCondReg()), MRI);
2469349cc55cSDimitry Andric   if (!Cst)
2470e8d8bef9SDimitry Andric     return false;
2471349cc55cSDimitry Andric   OpIdx = Cst->isZero() ? 3 : 2;
2472349cc55cSDimitry Andric   return true;
2473e8d8bef9SDimitry Andric }
2474e8d8bef9SDimitry Andric 
2475*06c3fb27SDimitry Andric void CombinerHelper::eraseInst(MachineInstr &MI) { MI.eraseFromParent(); }
24765ffd83dbSDimitry Andric 
24775ffd83dbSDimitry Andric bool CombinerHelper::matchEqualDefs(const MachineOperand &MOP1,
24785ffd83dbSDimitry Andric                                     const MachineOperand &MOP2) {
24795ffd83dbSDimitry Andric   if (!MOP1.isReg() || !MOP2.isReg())
24805ffd83dbSDimitry Andric     return false;
2481349cc55cSDimitry Andric   auto InstAndDef1 = getDefSrcRegIgnoringCopies(MOP1.getReg(), MRI);
2482349cc55cSDimitry Andric   if (!InstAndDef1)
24835ffd83dbSDimitry Andric     return false;
2484349cc55cSDimitry Andric   auto InstAndDef2 = getDefSrcRegIgnoringCopies(MOP2.getReg(), MRI);
2485349cc55cSDimitry Andric   if (!InstAndDef2)
24865ffd83dbSDimitry Andric     return false;
2487349cc55cSDimitry Andric   MachineInstr *I1 = InstAndDef1->MI;
2488349cc55cSDimitry Andric   MachineInstr *I2 = InstAndDef2->MI;
24895ffd83dbSDimitry Andric 
24905ffd83dbSDimitry Andric   // Handle a case like this:
24915ffd83dbSDimitry Andric   //
24925ffd83dbSDimitry Andric   // %0:_(s64), %1:_(s64) = G_UNMERGE_VALUES %2:_(<2 x s64>)
24935ffd83dbSDimitry Andric   //
24945ffd83dbSDimitry Andric   // Even though %0 and %1 are produced by the same instruction they are not
24955ffd83dbSDimitry Andric   // the same values.
24965ffd83dbSDimitry Andric   if (I1 == I2)
24975ffd83dbSDimitry Andric     return MOP1.getReg() == MOP2.getReg();
24985ffd83dbSDimitry Andric 
24995ffd83dbSDimitry Andric   // If we have an instruction which loads or stores, we can't guarantee that
25005ffd83dbSDimitry Andric   // it is identical.
25015ffd83dbSDimitry Andric   //
25025ffd83dbSDimitry Andric   // For example, we may have
25035ffd83dbSDimitry Andric   //
25045ffd83dbSDimitry Andric   // %x1 = G_LOAD %addr (load N from @somewhere)
25055ffd83dbSDimitry Andric   // ...
25065ffd83dbSDimitry Andric   // call @foo
25075ffd83dbSDimitry Andric   // ...
25085ffd83dbSDimitry Andric   // %x2 = G_LOAD %addr (load N from @somewhere)
25095ffd83dbSDimitry Andric   // ...
25105ffd83dbSDimitry Andric   // %or = G_OR %x1, %x2
25115ffd83dbSDimitry Andric   //
25125ffd83dbSDimitry Andric   // It's possible that @foo will modify whatever lives at the address we're
25135ffd83dbSDimitry Andric   // loading from. To be safe, let's just assume that all loads and stores
25145ffd83dbSDimitry Andric   // are different (unless we have something which is guaranteed to not
25155ffd83dbSDimitry Andric   // change.)
2516fcaf7f86SDimitry Andric   if (I1->mayLoadOrStore() && !I1->isDereferenceableInvariantLoad())
25175ffd83dbSDimitry Andric     return false;
25185ffd83dbSDimitry Andric 
251981ad6265SDimitry Andric   // If both instructions are loads or stores, they are equal only if both
252081ad6265SDimitry Andric   // are dereferenceable invariant loads with the same number of bits.
252181ad6265SDimitry Andric   if (I1->mayLoadOrStore() && I2->mayLoadOrStore()) {
252281ad6265SDimitry Andric     GLoadStore *LS1 = dyn_cast<GLoadStore>(I1);
252381ad6265SDimitry Andric     GLoadStore *LS2 = dyn_cast<GLoadStore>(I2);
252481ad6265SDimitry Andric     if (!LS1 || !LS2)
252581ad6265SDimitry Andric       return false;
252681ad6265SDimitry Andric 
2527fcaf7f86SDimitry Andric     if (!I2->isDereferenceableInvariantLoad() ||
252881ad6265SDimitry Andric         (LS1->getMemSizeInBits() != LS2->getMemSizeInBits()))
252981ad6265SDimitry Andric       return false;
253081ad6265SDimitry Andric   }
253181ad6265SDimitry Andric 
25325ffd83dbSDimitry Andric   // Check for physical registers on the instructions first to avoid cases
25335ffd83dbSDimitry Andric   // like this:
25345ffd83dbSDimitry Andric   //
25355ffd83dbSDimitry Andric   // %a = COPY $physreg
25365ffd83dbSDimitry Andric   // ...
25375ffd83dbSDimitry Andric   // SOMETHING implicit-def $physreg
25385ffd83dbSDimitry Andric   // ...
25395ffd83dbSDimitry Andric   // %b = COPY $physreg
25405ffd83dbSDimitry Andric   //
25415ffd83dbSDimitry Andric   // These copies are not equivalent.
25425ffd83dbSDimitry Andric   if (any_of(I1->uses(), [](const MachineOperand &MO) {
25435ffd83dbSDimitry Andric         return MO.isReg() && MO.getReg().isPhysical();
25445ffd83dbSDimitry Andric       })) {
25455ffd83dbSDimitry Andric     // Check if we have a case like this:
25465ffd83dbSDimitry Andric     //
25475ffd83dbSDimitry Andric     // %a = COPY $physreg
25485ffd83dbSDimitry Andric     // %b = COPY %a
25495ffd83dbSDimitry Andric     //
25505ffd83dbSDimitry Andric     // In this case, I1 and I2 will both be equal to %a = COPY $physreg.
25515ffd83dbSDimitry Andric     // From that, we know that they must have the same value, since they must
25525ffd83dbSDimitry Andric     // have come from the same COPY.
25535ffd83dbSDimitry Andric     return I1->isIdenticalTo(*I2);
25545ffd83dbSDimitry Andric   }
25555ffd83dbSDimitry Andric 
25565ffd83dbSDimitry Andric   // We don't have any physical registers, so we don't necessarily need the
25575ffd83dbSDimitry Andric   // same vreg defs.
25585ffd83dbSDimitry Andric   //
25595ffd83dbSDimitry Andric   // On the off-chance that there's some target instruction feeding into the
25605ffd83dbSDimitry Andric   // instruction, let's use produceSameValue instead of isIdenticalTo.
2561349cc55cSDimitry Andric   if (Builder.getTII().produceSameValue(*I1, *I2, &MRI)) {
2562349cc55cSDimitry Andric     // Handle instructions with multiple defs that produce same values. Values
2563349cc55cSDimitry Andric     // are same for operands with same index.
2564349cc55cSDimitry Andric     // %0:_(s8), %1:_(s8), %2:_(s8), %3:_(s8) = G_UNMERGE_VALUES %4:_(<4 x s8>)
2565349cc55cSDimitry Andric     // %5:_(s8), %6:_(s8), %7:_(s8), %8:_(s8) = G_UNMERGE_VALUES %4:_(<4 x s8>)
2566349cc55cSDimitry Andric     // I1 and I2 are different instructions but produce same values,
2567349cc55cSDimitry Andric     // %1 and %6 are same, %1 and %7 are not the same value.
2568349cc55cSDimitry Andric     return I1->findRegisterDefOperandIdx(InstAndDef1->Reg) ==
2569349cc55cSDimitry Andric            I2->findRegisterDefOperandIdx(InstAndDef2->Reg);
2570349cc55cSDimitry Andric   }
2571349cc55cSDimitry Andric   return false;
25725ffd83dbSDimitry Andric }
25735ffd83dbSDimitry Andric 
25745ffd83dbSDimitry Andric bool CombinerHelper::matchConstantOp(const MachineOperand &MOP, int64_t C) {
25755ffd83dbSDimitry Andric   if (!MOP.isReg())
25765ffd83dbSDimitry Andric     return false;
2577349cc55cSDimitry Andric   auto *MI = MRI.getVRegDef(MOP.getReg());
2578349cc55cSDimitry Andric   auto MaybeCst = isConstantOrConstantSplatVector(*MI, MRI);
257981ad6265SDimitry Andric   return MaybeCst && MaybeCst->getBitWidth() <= 64 &&
2580349cc55cSDimitry Andric          MaybeCst->getSExtValue() == C;
25815ffd83dbSDimitry Andric }
25825ffd83dbSDimitry Andric 
2583*06c3fb27SDimitry Andric void CombinerHelper::replaceSingleDefInstWithOperand(MachineInstr &MI,
25845ffd83dbSDimitry Andric                                                      unsigned OpIdx) {
25855ffd83dbSDimitry Andric   assert(MI.getNumExplicitDefs() == 1 && "Expected one explicit def?");
25865ffd83dbSDimitry Andric   Register OldReg = MI.getOperand(0).getReg();
25875ffd83dbSDimitry Andric   Register Replacement = MI.getOperand(OpIdx).getReg();
25885ffd83dbSDimitry Andric   assert(canReplaceReg(OldReg, Replacement, MRI) && "Cannot replace register?");
25895ffd83dbSDimitry Andric   MI.eraseFromParent();
25905ffd83dbSDimitry Andric   replaceRegWith(MRI, OldReg, Replacement);
25915ffd83dbSDimitry Andric }
25925ffd83dbSDimitry Andric 
2593*06c3fb27SDimitry Andric void CombinerHelper::replaceSingleDefInstWithReg(MachineInstr &MI,
2594e8d8bef9SDimitry Andric                                                  Register Replacement) {
2595e8d8bef9SDimitry Andric   assert(MI.getNumExplicitDefs() == 1 && "Expected one explicit def?");
2596e8d8bef9SDimitry Andric   Register OldReg = MI.getOperand(0).getReg();
2597e8d8bef9SDimitry Andric   assert(canReplaceReg(OldReg, Replacement, MRI) && "Cannot replace register?");
2598e8d8bef9SDimitry Andric   MI.eraseFromParent();
2599e8d8bef9SDimitry Andric   replaceRegWith(MRI, OldReg, Replacement);
2600e8d8bef9SDimitry Andric }
2601e8d8bef9SDimitry Andric 
26025ffd83dbSDimitry Andric bool CombinerHelper::matchSelectSameVal(MachineInstr &MI) {
26035ffd83dbSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SELECT);
26045ffd83dbSDimitry Andric   // Match (cond ? x : x)
26055ffd83dbSDimitry Andric   return matchEqualDefs(MI.getOperand(2), MI.getOperand(3)) &&
26065ffd83dbSDimitry Andric          canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(2).getReg(),
26075ffd83dbSDimitry Andric                        MRI);
26085ffd83dbSDimitry Andric }
26095ffd83dbSDimitry Andric 
26105ffd83dbSDimitry Andric bool CombinerHelper::matchBinOpSameVal(MachineInstr &MI) {
26115ffd83dbSDimitry Andric   return matchEqualDefs(MI.getOperand(1), MI.getOperand(2)) &&
26125ffd83dbSDimitry Andric          canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(1).getReg(),
26135ffd83dbSDimitry Andric                        MRI);
26145ffd83dbSDimitry Andric }
26155ffd83dbSDimitry Andric 
26165ffd83dbSDimitry Andric bool CombinerHelper::matchOperandIsZero(MachineInstr &MI, unsigned OpIdx) {
26175ffd83dbSDimitry Andric   return matchConstantOp(MI.getOperand(OpIdx), 0) &&
26185ffd83dbSDimitry Andric          canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(OpIdx).getReg(),
26195ffd83dbSDimitry Andric                        MRI);
26205ffd83dbSDimitry Andric }
26215ffd83dbSDimitry Andric 
2622e8d8bef9SDimitry Andric bool CombinerHelper::matchOperandIsUndef(MachineInstr &MI, unsigned OpIdx) {
2623e8d8bef9SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
2624e8d8bef9SDimitry Andric   return MO.isReg() &&
2625e8d8bef9SDimitry Andric          getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
2626e8d8bef9SDimitry Andric }
2627e8d8bef9SDimitry Andric 
2628e8d8bef9SDimitry Andric bool CombinerHelper::matchOperandIsKnownToBeAPowerOfTwo(MachineInstr &MI,
2629e8d8bef9SDimitry Andric                                                         unsigned OpIdx) {
2630e8d8bef9SDimitry Andric   MachineOperand &MO = MI.getOperand(OpIdx);
2631e8d8bef9SDimitry Andric   return isKnownToBeAPowerOfTwo(MO.getReg(), MRI, KB);
2632e8d8bef9SDimitry Andric }
2633e8d8bef9SDimitry Andric 
2634*06c3fb27SDimitry Andric void CombinerHelper::replaceInstWithFConstant(MachineInstr &MI, double C) {
26355ffd83dbSDimitry Andric   assert(MI.getNumDefs() == 1 && "Expected only one def?");
26365ffd83dbSDimitry Andric   Builder.setInstr(MI);
26375ffd83dbSDimitry Andric   Builder.buildFConstant(MI.getOperand(0), C);
26385ffd83dbSDimitry Andric   MI.eraseFromParent();
26395ffd83dbSDimitry Andric }
26405ffd83dbSDimitry Andric 
2641*06c3fb27SDimitry Andric void CombinerHelper::replaceInstWithConstant(MachineInstr &MI, int64_t C) {
26425ffd83dbSDimitry Andric   assert(MI.getNumDefs() == 1 && "Expected only one def?");
26435ffd83dbSDimitry Andric   Builder.setInstr(MI);
26445ffd83dbSDimitry Andric   Builder.buildConstant(MI.getOperand(0), C);
26455ffd83dbSDimitry Andric   MI.eraseFromParent();
26465ffd83dbSDimitry Andric }
26475ffd83dbSDimitry Andric 
2648*06c3fb27SDimitry Andric void CombinerHelper::replaceInstWithConstant(MachineInstr &MI, APInt C) {
2649fe6060f1SDimitry Andric   assert(MI.getNumDefs() == 1 && "Expected only one def?");
2650fe6060f1SDimitry Andric   Builder.setInstr(MI);
2651fe6060f1SDimitry Andric   Builder.buildConstant(MI.getOperand(0), C);
2652fe6060f1SDimitry Andric   MI.eraseFromParent();
2653fe6060f1SDimitry Andric }
2654fe6060f1SDimitry Andric 
2655*06c3fb27SDimitry Andric void CombinerHelper::replaceInstWithUndef(MachineInstr &MI) {
26565ffd83dbSDimitry Andric   assert(MI.getNumDefs() == 1 && "Expected only one def?");
26575ffd83dbSDimitry Andric   Builder.setInstr(MI);
26585ffd83dbSDimitry Andric   Builder.buildUndef(MI.getOperand(0));
26595ffd83dbSDimitry Andric   MI.eraseFromParent();
26605ffd83dbSDimitry Andric }
26615ffd83dbSDimitry Andric 
26625ffd83dbSDimitry Andric bool CombinerHelper::matchSimplifyAddToSub(
26635ffd83dbSDimitry Andric     MachineInstr &MI, std::tuple<Register, Register> &MatchInfo) {
26645ffd83dbSDimitry Andric   Register LHS = MI.getOperand(1).getReg();
26655ffd83dbSDimitry Andric   Register RHS = MI.getOperand(2).getReg();
26665ffd83dbSDimitry Andric   Register &NewLHS = std::get<0>(MatchInfo);
26675ffd83dbSDimitry Andric   Register &NewRHS = std::get<1>(MatchInfo);
26685ffd83dbSDimitry Andric 
26695ffd83dbSDimitry Andric   // Helper lambda to check for opportunities for
26705ffd83dbSDimitry Andric   // ((0-A) + B) -> B - A
26715ffd83dbSDimitry Andric   // (A + (0-B)) -> A - B
26725ffd83dbSDimitry Andric   auto CheckFold = [&](Register &MaybeSub, Register &MaybeNewLHS) {
2673e8d8bef9SDimitry Andric     if (!mi_match(MaybeSub, MRI, m_Neg(m_Reg(NewRHS))))
26745ffd83dbSDimitry Andric       return false;
26755ffd83dbSDimitry Andric     NewLHS = MaybeNewLHS;
26765ffd83dbSDimitry Andric     return true;
26775ffd83dbSDimitry Andric   };
26785ffd83dbSDimitry Andric 
26795ffd83dbSDimitry Andric   return CheckFold(LHS, RHS) || CheckFold(RHS, LHS);
26805ffd83dbSDimitry Andric }
26815ffd83dbSDimitry Andric 
2682e8d8bef9SDimitry Andric bool CombinerHelper::matchCombineInsertVecElts(
2683e8d8bef9SDimitry Andric     MachineInstr &MI, SmallVectorImpl<Register> &MatchInfo) {
2684e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT &&
2685e8d8bef9SDimitry Andric          "Invalid opcode");
2686e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
2687e8d8bef9SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
2688e8d8bef9SDimitry Andric   assert(DstTy.isVector() && "Invalid G_INSERT_VECTOR_ELT?");
2689e8d8bef9SDimitry Andric   unsigned NumElts = DstTy.getNumElements();
2690e8d8bef9SDimitry Andric   // If this MI is part of a sequence of insert_vec_elts, then
2691e8d8bef9SDimitry Andric   // don't do the combine in the middle of the sequence.
2692e8d8bef9SDimitry Andric   if (MRI.hasOneUse(DstReg) && MRI.use_instr_begin(DstReg)->getOpcode() ==
2693e8d8bef9SDimitry Andric                                    TargetOpcode::G_INSERT_VECTOR_ELT)
2694e8d8bef9SDimitry Andric     return false;
2695e8d8bef9SDimitry Andric   MachineInstr *CurrInst = &MI;
2696e8d8bef9SDimitry Andric   MachineInstr *TmpInst;
2697e8d8bef9SDimitry Andric   int64_t IntImm;
2698e8d8bef9SDimitry Andric   Register TmpReg;
2699e8d8bef9SDimitry Andric   MatchInfo.resize(NumElts);
2700e8d8bef9SDimitry Andric   while (mi_match(
2701e8d8bef9SDimitry Andric       CurrInst->getOperand(0).getReg(), MRI,
2702e8d8bef9SDimitry Andric       m_GInsertVecElt(m_MInstr(TmpInst), m_Reg(TmpReg), m_ICst(IntImm)))) {
2703bdd1243dSDimitry Andric     if (IntImm >= NumElts || IntImm < 0)
2704e8d8bef9SDimitry Andric       return false;
2705e8d8bef9SDimitry Andric     if (!MatchInfo[IntImm])
2706e8d8bef9SDimitry Andric       MatchInfo[IntImm] = TmpReg;
2707e8d8bef9SDimitry Andric     CurrInst = TmpInst;
2708e8d8bef9SDimitry Andric   }
2709e8d8bef9SDimitry Andric   // Variable index.
2710e8d8bef9SDimitry Andric   if (CurrInst->getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT)
2711e8d8bef9SDimitry Andric     return false;
2712e8d8bef9SDimitry Andric   if (TmpInst->getOpcode() == TargetOpcode::G_BUILD_VECTOR) {
2713e8d8bef9SDimitry Andric     for (unsigned I = 1; I < TmpInst->getNumOperands(); ++I) {
2714e8d8bef9SDimitry Andric       if (!MatchInfo[I - 1].isValid())
2715e8d8bef9SDimitry Andric         MatchInfo[I - 1] = TmpInst->getOperand(I).getReg();
2716e8d8bef9SDimitry Andric     }
2717e8d8bef9SDimitry Andric     return true;
2718e8d8bef9SDimitry Andric   }
2719e8d8bef9SDimitry Andric   // If we didn't end in a G_IMPLICIT_DEF, bail out.
2720e8d8bef9SDimitry Andric   return TmpInst->getOpcode() == TargetOpcode::G_IMPLICIT_DEF;
2721e8d8bef9SDimitry Andric }
2722e8d8bef9SDimitry Andric 
2723fe6060f1SDimitry Andric void CombinerHelper::applyCombineInsertVecElts(
2724e8d8bef9SDimitry Andric     MachineInstr &MI, SmallVectorImpl<Register> &MatchInfo) {
2725e8d8bef9SDimitry Andric   Builder.setInstr(MI);
2726e8d8bef9SDimitry Andric   Register UndefReg;
2727e8d8bef9SDimitry Andric   auto GetUndef = [&]() {
2728e8d8bef9SDimitry Andric     if (UndefReg)
2729e8d8bef9SDimitry Andric       return UndefReg;
2730e8d8bef9SDimitry Andric     LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
2731e8d8bef9SDimitry Andric     UndefReg = Builder.buildUndef(DstTy.getScalarType()).getReg(0);
2732e8d8bef9SDimitry Andric     return UndefReg;
2733e8d8bef9SDimitry Andric   };
2734e8d8bef9SDimitry Andric   for (unsigned I = 0; I < MatchInfo.size(); ++I) {
2735e8d8bef9SDimitry Andric     if (!MatchInfo[I])
2736e8d8bef9SDimitry Andric       MatchInfo[I] = GetUndef();
2737e8d8bef9SDimitry Andric   }
2738e8d8bef9SDimitry Andric   Builder.buildBuildVector(MI.getOperand(0).getReg(), MatchInfo);
2739e8d8bef9SDimitry Andric   MI.eraseFromParent();
2740e8d8bef9SDimitry Andric }
2741e8d8bef9SDimitry Andric 
2742fe6060f1SDimitry Andric void CombinerHelper::applySimplifyAddToSub(
27435ffd83dbSDimitry Andric     MachineInstr &MI, std::tuple<Register, Register> &MatchInfo) {
27445ffd83dbSDimitry Andric   Builder.setInstr(MI);
27455ffd83dbSDimitry Andric   Register SubLHS, SubRHS;
27465ffd83dbSDimitry Andric   std::tie(SubLHS, SubRHS) = MatchInfo;
27475ffd83dbSDimitry Andric   Builder.buildSub(MI.getOperand(0).getReg(), SubLHS, SubRHS);
27485ffd83dbSDimitry Andric   MI.eraseFromParent();
27495ffd83dbSDimitry Andric }
27505ffd83dbSDimitry Andric 
2751e8d8bef9SDimitry Andric bool CombinerHelper::matchHoistLogicOpWithSameOpcodeHands(
2752e8d8bef9SDimitry Andric     MachineInstr &MI, InstructionStepsMatchInfo &MatchInfo) {
2753e8d8bef9SDimitry Andric   // Matches: logic (hand x, ...), (hand y, ...) -> hand (logic x, y), ...
2754e8d8bef9SDimitry Andric   //
2755e8d8bef9SDimitry Andric   // Creates the new hand + logic instruction (but does not insert them.)
2756e8d8bef9SDimitry Andric   //
2757e8d8bef9SDimitry Andric   // On success, MatchInfo is populated with the new instructions. These are
2758e8d8bef9SDimitry Andric   // inserted in applyHoistLogicOpWithSameOpcodeHands.
2759e8d8bef9SDimitry Andric   unsigned LogicOpcode = MI.getOpcode();
2760e8d8bef9SDimitry Andric   assert(LogicOpcode == TargetOpcode::G_AND ||
2761e8d8bef9SDimitry Andric          LogicOpcode == TargetOpcode::G_OR ||
2762e8d8bef9SDimitry Andric          LogicOpcode == TargetOpcode::G_XOR);
2763e8d8bef9SDimitry Andric   MachineIRBuilder MIB(MI);
2764e8d8bef9SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
2765e8d8bef9SDimitry Andric   Register LHSReg = MI.getOperand(1).getReg();
2766e8d8bef9SDimitry Andric   Register RHSReg = MI.getOperand(2).getReg();
2767e8d8bef9SDimitry Andric 
2768e8d8bef9SDimitry Andric   // Don't recompute anything.
2769e8d8bef9SDimitry Andric   if (!MRI.hasOneNonDBGUse(LHSReg) || !MRI.hasOneNonDBGUse(RHSReg))
2770e8d8bef9SDimitry Andric     return false;
2771e8d8bef9SDimitry Andric 
2772e8d8bef9SDimitry Andric   // Make sure we have (hand x, ...), (hand y, ...)
2773e8d8bef9SDimitry Andric   MachineInstr *LeftHandInst = getDefIgnoringCopies(LHSReg, MRI);
2774e8d8bef9SDimitry Andric   MachineInstr *RightHandInst = getDefIgnoringCopies(RHSReg, MRI);
2775e8d8bef9SDimitry Andric   if (!LeftHandInst || !RightHandInst)
2776e8d8bef9SDimitry Andric     return false;
2777e8d8bef9SDimitry Andric   unsigned HandOpcode = LeftHandInst->getOpcode();
2778e8d8bef9SDimitry Andric   if (HandOpcode != RightHandInst->getOpcode())
2779e8d8bef9SDimitry Andric     return false;
2780e8d8bef9SDimitry Andric   if (!LeftHandInst->getOperand(1).isReg() ||
2781e8d8bef9SDimitry Andric       !RightHandInst->getOperand(1).isReg())
2782e8d8bef9SDimitry Andric     return false;
2783e8d8bef9SDimitry Andric 
2784e8d8bef9SDimitry Andric   // Make sure the types match up, and if we're doing this post-legalization,
2785e8d8bef9SDimitry Andric   // we end up with legal types.
2786e8d8bef9SDimitry Andric   Register X = LeftHandInst->getOperand(1).getReg();
2787e8d8bef9SDimitry Andric   Register Y = RightHandInst->getOperand(1).getReg();
2788e8d8bef9SDimitry Andric   LLT XTy = MRI.getType(X);
2789e8d8bef9SDimitry Andric   LLT YTy = MRI.getType(Y);
2790*06c3fb27SDimitry Andric   if (!XTy.isValid() || XTy != YTy)
2791e8d8bef9SDimitry Andric     return false;
2792e8d8bef9SDimitry Andric 
2793e8d8bef9SDimitry Andric   // Optional extra source register.
2794e8d8bef9SDimitry Andric   Register ExtraHandOpSrcReg;
2795e8d8bef9SDimitry Andric   switch (HandOpcode) {
2796e8d8bef9SDimitry Andric   default:
2797e8d8bef9SDimitry Andric     return false;
2798e8d8bef9SDimitry Andric   case TargetOpcode::G_ANYEXT:
2799e8d8bef9SDimitry Andric   case TargetOpcode::G_SEXT:
2800e8d8bef9SDimitry Andric   case TargetOpcode::G_ZEXT: {
2801e8d8bef9SDimitry Andric     // Match: logic (ext X), (ext Y) --> ext (logic X, Y)
2802e8d8bef9SDimitry Andric     break;
2803e8d8bef9SDimitry Andric   }
2804e8d8bef9SDimitry Andric   case TargetOpcode::G_AND:
2805e8d8bef9SDimitry Andric   case TargetOpcode::G_ASHR:
2806e8d8bef9SDimitry Andric   case TargetOpcode::G_LSHR:
2807e8d8bef9SDimitry Andric   case TargetOpcode::G_SHL: {
2808e8d8bef9SDimitry Andric     // Match: logic (binop x, z), (binop y, z) -> binop (logic x, y), z
2809e8d8bef9SDimitry Andric     MachineOperand &ZOp = LeftHandInst->getOperand(2);
2810e8d8bef9SDimitry Andric     if (!matchEqualDefs(ZOp, RightHandInst->getOperand(2)))
2811e8d8bef9SDimitry Andric       return false;
2812e8d8bef9SDimitry Andric     ExtraHandOpSrcReg = ZOp.getReg();
2813e8d8bef9SDimitry Andric     break;
2814e8d8bef9SDimitry Andric   }
2815e8d8bef9SDimitry Andric   }
2816e8d8bef9SDimitry Andric 
2817*06c3fb27SDimitry Andric   if (!isLegalOrBeforeLegalizer({LogicOpcode, {XTy, YTy}}))
2818*06c3fb27SDimitry Andric     return false;
2819*06c3fb27SDimitry Andric 
2820e8d8bef9SDimitry Andric   // Record the steps to build the new instructions.
2821e8d8bef9SDimitry Andric   //
2822e8d8bef9SDimitry Andric   // Steps to build (logic x, y)
2823e8d8bef9SDimitry Andric   auto NewLogicDst = MRI.createGenericVirtualRegister(XTy);
2824e8d8bef9SDimitry Andric   OperandBuildSteps LogicBuildSteps = {
2825e8d8bef9SDimitry Andric       [=](MachineInstrBuilder &MIB) { MIB.addDef(NewLogicDst); },
2826e8d8bef9SDimitry Andric       [=](MachineInstrBuilder &MIB) { MIB.addReg(X); },
2827e8d8bef9SDimitry Andric       [=](MachineInstrBuilder &MIB) { MIB.addReg(Y); }};
2828e8d8bef9SDimitry Andric   InstructionBuildSteps LogicSteps(LogicOpcode, LogicBuildSteps);
2829e8d8bef9SDimitry Andric 
2830e8d8bef9SDimitry Andric   // Steps to build hand (logic x, y), ...z
2831e8d8bef9SDimitry Andric   OperandBuildSteps HandBuildSteps = {
2832e8d8bef9SDimitry Andric       [=](MachineInstrBuilder &MIB) { MIB.addDef(Dst); },
2833e8d8bef9SDimitry Andric       [=](MachineInstrBuilder &MIB) { MIB.addReg(NewLogicDst); }};
2834e8d8bef9SDimitry Andric   if (ExtraHandOpSrcReg.isValid())
2835e8d8bef9SDimitry Andric     HandBuildSteps.push_back(
2836e8d8bef9SDimitry Andric         [=](MachineInstrBuilder &MIB) { MIB.addReg(ExtraHandOpSrcReg); });
2837e8d8bef9SDimitry Andric   InstructionBuildSteps HandSteps(HandOpcode, HandBuildSteps);
2838e8d8bef9SDimitry Andric 
2839e8d8bef9SDimitry Andric   MatchInfo = InstructionStepsMatchInfo({LogicSteps, HandSteps});
2840e8d8bef9SDimitry Andric   return true;
2841e8d8bef9SDimitry Andric }
2842e8d8bef9SDimitry Andric 
2843fe6060f1SDimitry Andric void CombinerHelper::applyBuildInstructionSteps(
2844e8d8bef9SDimitry Andric     MachineInstr &MI, InstructionStepsMatchInfo &MatchInfo) {
2845e8d8bef9SDimitry Andric   assert(MatchInfo.InstrsToBuild.size() &&
2846e8d8bef9SDimitry Andric          "Expected at least one instr to build?");
2847e8d8bef9SDimitry Andric   Builder.setInstr(MI);
2848e8d8bef9SDimitry Andric   for (auto &InstrToBuild : MatchInfo.InstrsToBuild) {
2849e8d8bef9SDimitry Andric     assert(InstrToBuild.Opcode && "Expected a valid opcode?");
2850e8d8bef9SDimitry Andric     assert(InstrToBuild.OperandFns.size() && "Expected at least one operand?");
2851e8d8bef9SDimitry Andric     MachineInstrBuilder Instr = Builder.buildInstr(InstrToBuild.Opcode);
2852e8d8bef9SDimitry Andric     for (auto &OperandFn : InstrToBuild.OperandFns)
2853e8d8bef9SDimitry Andric       OperandFn(Instr);
2854e8d8bef9SDimitry Andric   }
2855e8d8bef9SDimitry Andric   MI.eraseFromParent();
2856e8d8bef9SDimitry Andric }
2857e8d8bef9SDimitry Andric 
2858e8d8bef9SDimitry Andric bool CombinerHelper::matchAshrShlToSextInreg(
2859e8d8bef9SDimitry Andric     MachineInstr &MI, std::tuple<Register, int64_t> &MatchInfo) {
2860e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ASHR);
2861e8d8bef9SDimitry Andric   int64_t ShlCst, AshrCst;
2862e8d8bef9SDimitry Andric   Register Src;
2863e8d8bef9SDimitry Andric   if (!mi_match(MI.getOperand(0).getReg(), MRI,
2864bdd1243dSDimitry Andric                 m_GAShr(m_GShl(m_Reg(Src), m_ICstOrSplat(ShlCst)),
2865bdd1243dSDimitry Andric                         m_ICstOrSplat(AshrCst))))
2866e8d8bef9SDimitry Andric     return false;
2867e8d8bef9SDimitry Andric   if (ShlCst != AshrCst)
2868e8d8bef9SDimitry Andric     return false;
2869e8d8bef9SDimitry Andric   if (!isLegalOrBeforeLegalizer(
2870e8d8bef9SDimitry Andric           {TargetOpcode::G_SEXT_INREG, {MRI.getType(Src)}}))
2871e8d8bef9SDimitry Andric     return false;
2872e8d8bef9SDimitry Andric   MatchInfo = std::make_tuple(Src, ShlCst);
2873e8d8bef9SDimitry Andric   return true;
2874e8d8bef9SDimitry Andric }
2875fe6060f1SDimitry Andric 
2876fe6060f1SDimitry Andric void CombinerHelper::applyAshShlToSextInreg(
2877e8d8bef9SDimitry Andric     MachineInstr &MI, std::tuple<Register, int64_t> &MatchInfo) {
2878e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ASHR);
2879e8d8bef9SDimitry Andric   Register Src;
2880e8d8bef9SDimitry Andric   int64_t ShiftAmt;
2881e8d8bef9SDimitry Andric   std::tie(Src, ShiftAmt) = MatchInfo;
2882e8d8bef9SDimitry Andric   unsigned Size = MRI.getType(Src).getScalarSizeInBits();
2883e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
2884e8d8bef9SDimitry Andric   Builder.buildSExtInReg(MI.getOperand(0).getReg(), Src, Size - ShiftAmt);
2885e8d8bef9SDimitry Andric   MI.eraseFromParent();
2886fe6060f1SDimitry Andric }
2887fe6060f1SDimitry Andric 
2888fe6060f1SDimitry Andric /// and(and(x, C1), C2) -> C1&C2 ? and(x, C1&C2) : 0
2889fe6060f1SDimitry Andric bool CombinerHelper::matchOverlappingAnd(
2890fe6060f1SDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
2891fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_AND);
2892fe6060f1SDimitry Andric 
2893fe6060f1SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
2894fe6060f1SDimitry Andric   LLT Ty = MRI.getType(Dst);
2895fe6060f1SDimitry Andric 
2896fe6060f1SDimitry Andric   Register R;
2897fe6060f1SDimitry Andric   int64_t C1;
2898fe6060f1SDimitry Andric   int64_t C2;
2899fe6060f1SDimitry Andric   if (!mi_match(
2900fe6060f1SDimitry Andric           Dst, MRI,
2901fe6060f1SDimitry Andric           m_GAnd(m_GAnd(m_Reg(R), m_ICst(C1)), m_ICst(C2))))
2902fe6060f1SDimitry Andric     return false;
2903fe6060f1SDimitry Andric 
2904fe6060f1SDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
2905fe6060f1SDimitry Andric     if (C1 & C2) {
2906fe6060f1SDimitry Andric       B.buildAnd(Dst, R, B.buildConstant(Ty, C1 & C2));
2907fe6060f1SDimitry Andric       return;
2908fe6060f1SDimitry Andric     }
2909fe6060f1SDimitry Andric     auto Zero = B.buildConstant(Ty, 0);
2910fe6060f1SDimitry Andric     replaceRegWith(MRI, Dst, Zero->getOperand(0).getReg());
2911fe6060f1SDimitry Andric   };
2912e8d8bef9SDimitry Andric   return true;
2913e8d8bef9SDimitry Andric }
2914e8d8bef9SDimitry Andric 
2915e8d8bef9SDimitry Andric bool CombinerHelper::matchRedundantAnd(MachineInstr &MI,
2916e8d8bef9SDimitry Andric                                        Register &Replacement) {
2917e8d8bef9SDimitry Andric   // Given
2918e8d8bef9SDimitry Andric   //
2919e8d8bef9SDimitry Andric   // %y:_(sN) = G_SOMETHING
2920e8d8bef9SDimitry Andric   // %x:_(sN) = G_SOMETHING
2921e8d8bef9SDimitry Andric   // %res:_(sN) = G_AND %x, %y
2922e8d8bef9SDimitry Andric   //
2923e8d8bef9SDimitry Andric   // Eliminate the G_AND when it is known that x & y == x or x & y == y.
2924e8d8bef9SDimitry Andric   //
2925e8d8bef9SDimitry Andric   // Patterns like this can appear as a result of legalization. E.g.
2926e8d8bef9SDimitry Andric   //
2927e8d8bef9SDimitry Andric   // %cmp:_(s32) = G_ICMP intpred(pred), %x(s32), %y
2928e8d8bef9SDimitry Andric   // %one:_(s32) = G_CONSTANT i32 1
2929e8d8bef9SDimitry Andric   // %and:_(s32) = G_AND %cmp, %one
2930e8d8bef9SDimitry Andric   //
2931e8d8bef9SDimitry Andric   // In this case, G_ICMP only produces a single bit, so x & 1 == x.
2932e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_AND);
2933e8d8bef9SDimitry Andric   if (!KB)
2934e8d8bef9SDimitry Andric     return false;
2935e8d8bef9SDimitry Andric 
2936e8d8bef9SDimitry Andric   Register AndDst = MI.getOperand(0).getReg();
2937e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
2938e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
2939e8d8bef9SDimitry Andric   KnownBits LHSBits = KB->getKnownBits(LHS);
2940e8d8bef9SDimitry Andric   KnownBits RHSBits = KB->getKnownBits(RHS);
2941e8d8bef9SDimitry Andric 
2942e8d8bef9SDimitry Andric   // Check that x & Mask == x.
2943e8d8bef9SDimitry Andric   // x & 1 == x, always
2944e8d8bef9SDimitry Andric   // x & 0 == x, only if x is also 0
2945e8d8bef9SDimitry Andric   // Meaning Mask has no effect if every bit is either one in Mask or zero in x.
2946e8d8bef9SDimitry Andric   //
2947e8d8bef9SDimitry Andric   // Check if we can replace AndDst with the LHS of the G_AND
2948e8d8bef9SDimitry Andric   if (canReplaceReg(AndDst, LHS, MRI) &&
2949349cc55cSDimitry Andric       (LHSBits.Zero | RHSBits.One).isAllOnes()) {
2950e8d8bef9SDimitry Andric     Replacement = LHS;
2951e8d8bef9SDimitry Andric     return true;
2952e8d8bef9SDimitry Andric   }
2953e8d8bef9SDimitry Andric 
2954e8d8bef9SDimitry Andric   // Check if we can replace AndDst with the RHS of the G_AND
2955e8d8bef9SDimitry Andric   if (canReplaceReg(AndDst, RHS, MRI) &&
2956349cc55cSDimitry Andric       (LHSBits.One | RHSBits.Zero).isAllOnes()) {
2957e8d8bef9SDimitry Andric     Replacement = RHS;
2958e8d8bef9SDimitry Andric     return true;
2959e8d8bef9SDimitry Andric   }
2960e8d8bef9SDimitry Andric 
2961e8d8bef9SDimitry Andric   return false;
2962e8d8bef9SDimitry Andric }
2963e8d8bef9SDimitry Andric 
2964e8d8bef9SDimitry Andric bool CombinerHelper::matchRedundantOr(MachineInstr &MI, Register &Replacement) {
2965e8d8bef9SDimitry Andric   // Given
2966e8d8bef9SDimitry Andric   //
2967e8d8bef9SDimitry Andric   // %y:_(sN) = G_SOMETHING
2968e8d8bef9SDimitry Andric   // %x:_(sN) = G_SOMETHING
2969e8d8bef9SDimitry Andric   // %res:_(sN) = G_OR %x, %y
2970e8d8bef9SDimitry Andric   //
2971e8d8bef9SDimitry Andric   // Eliminate the G_OR when it is known that x | y == x or x | y == y.
2972e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_OR);
2973e8d8bef9SDimitry Andric   if (!KB)
2974e8d8bef9SDimitry Andric     return false;
2975e8d8bef9SDimitry Andric 
2976e8d8bef9SDimitry Andric   Register OrDst = MI.getOperand(0).getReg();
2977e8d8bef9SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
2978e8d8bef9SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
2979e8d8bef9SDimitry Andric   KnownBits LHSBits = KB->getKnownBits(LHS);
2980e8d8bef9SDimitry Andric   KnownBits RHSBits = KB->getKnownBits(RHS);
2981e8d8bef9SDimitry Andric 
2982e8d8bef9SDimitry Andric   // Check that x | Mask == x.
2983e8d8bef9SDimitry Andric   // x | 0 == x, always
2984e8d8bef9SDimitry Andric   // x | 1 == x, only if x is also 1
2985e8d8bef9SDimitry Andric   // Meaning Mask has no effect if every bit is either zero in Mask or one in x.
2986e8d8bef9SDimitry Andric   //
2987e8d8bef9SDimitry Andric   // Check if we can replace OrDst with the LHS of the G_OR
2988e8d8bef9SDimitry Andric   if (canReplaceReg(OrDst, LHS, MRI) &&
2989349cc55cSDimitry Andric       (LHSBits.One | RHSBits.Zero).isAllOnes()) {
2990e8d8bef9SDimitry Andric     Replacement = LHS;
2991e8d8bef9SDimitry Andric     return true;
2992e8d8bef9SDimitry Andric   }
2993e8d8bef9SDimitry Andric 
2994e8d8bef9SDimitry Andric   // Check if we can replace OrDst with the RHS of the G_OR
2995e8d8bef9SDimitry Andric   if (canReplaceReg(OrDst, RHS, MRI) &&
2996349cc55cSDimitry Andric       (LHSBits.Zero | RHSBits.One).isAllOnes()) {
2997e8d8bef9SDimitry Andric     Replacement = RHS;
2998e8d8bef9SDimitry Andric     return true;
2999e8d8bef9SDimitry Andric   }
3000e8d8bef9SDimitry Andric 
3001e8d8bef9SDimitry Andric   return false;
3002e8d8bef9SDimitry Andric }
3003e8d8bef9SDimitry Andric 
3004e8d8bef9SDimitry Andric bool CombinerHelper::matchRedundantSExtInReg(MachineInstr &MI) {
3005e8d8bef9SDimitry Andric   // If the input is already sign extended, just drop the extension.
3006e8d8bef9SDimitry Andric   Register Src = MI.getOperand(1).getReg();
3007e8d8bef9SDimitry Andric   unsigned ExtBits = MI.getOperand(2).getImm();
3008e8d8bef9SDimitry Andric   unsigned TypeSize = MRI.getType(Src).getScalarSizeInBits();
3009e8d8bef9SDimitry Andric   return KB->computeNumSignBits(Src) >= (TypeSize - ExtBits + 1);
3010e8d8bef9SDimitry Andric }
3011e8d8bef9SDimitry Andric 
3012e8d8bef9SDimitry Andric static bool isConstValidTrue(const TargetLowering &TLI, unsigned ScalarSizeBits,
3013e8d8bef9SDimitry Andric                              int64_t Cst, bool IsVector, bool IsFP) {
3014e8d8bef9SDimitry Andric   // For i1, Cst will always be -1 regardless of boolean contents.
3015e8d8bef9SDimitry Andric   return (ScalarSizeBits == 1 && Cst == -1) ||
3016e8d8bef9SDimitry Andric          isConstTrueVal(TLI, Cst, IsVector, IsFP);
3017e8d8bef9SDimitry Andric }
3018e8d8bef9SDimitry Andric 
3019e8d8bef9SDimitry Andric bool CombinerHelper::matchNotCmp(MachineInstr &MI,
3020e8d8bef9SDimitry Andric                                  SmallVectorImpl<Register> &RegsToNegate) {
3021e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_XOR);
3022e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(MI.getOperand(0).getReg());
3023e8d8bef9SDimitry Andric   const auto &TLI = *Builder.getMF().getSubtarget().getTargetLowering();
3024e8d8bef9SDimitry Andric   Register XorSrc;
3025e8d8bef9SDimitry Andric   Register CstReg;
3026e8d8bef9SDimitry Andric   // We match xor(src, true) here.
3027e8d8bef9SDimitry Andric   if (!mi_match(MI.getOperand(0).getReg(), MRI,
3028e8d8bef9SDimitry Andric                 m_GXor(m_Reg(XorSrc), m_Reg(CstReg))))
3029e8d8bef9SDimitry Andric     return false;
3030e8d8bef9SDimitry Andric 
3031e8d8bef9SDimitry Andric   if (!MRI.hasOneNonDBGUse(XorSrc))
3032e8d8bef9SDimitry Andric     return false;
3033e8d8bef9SDimitry Andric 
3034e8d8bef9SDimitry Andric   // Check that XorSrc is the root of a tree of comparisons combined with ANDs
3035e8d8bef9SDimitry Andric   // and ORs. The suffix of RegsToNegate starting from index I is used a work
3036e8d8bef9SDimitry Andric   // list of tree nodes to visit.
3037e8d8bef9SDimitry Andric   RegsToNegate.push_back(XorSrc);
3038e8d8bef9SDimitry Andric   // Remember whether the comparisons are all integer or all floating point.
3039e8d8bef9SDimitry Andric   bool IsInt = false;
3040e8d8bef9SDimitry Andric   bool IsFP = false;
3041e8d8bef9SDimitry Andric   for (unsigned I = 0; I < RegsToNegate.size(); ++I) {
3042e8d8bef9SDimitry Andric     Register Reg = RegsToNegate[I];
3043e8d8bef9SDimitry Andric     if (!MRI.hasOneNonDBGUse(Reg))
3044e8d8bef9SDimitry Andric       return false;
3045e8d8bef9SDimitry Andric     MachineInstr *Def = MRI.getVRegDef(Reg);
3046e8d8bef9SDimitry Andric     switch (Def->getOpcode()) {
3047e8d8bef9SDimitry Andric     default:
3048e8d8bef9SDimitry Andric       // Don't match if the tree contains anything other than ANDs, ORs and
3049e8d8bef9SDimitry Andric       // comparisons.
3050e8d8bef9SDimitry Andric       return false;
3051e8d8bef9SDimitry Andric     case TargetOpcode::G_ICMP:
3052e8d8bef9SDimitry Andric       if (IsFP)
3053e8d8bef9SDimitry Andric         return false;
3054e8d8bef9SDimitry Andric       IsInt = true;
3055e8d8bef9SDimitry Andric       // When we apply the combine we will invert the predicate.
3056e8d8bef9SDimitry Andric       break;
3057e8d8bef9SDimitry Andric     case TargetOpcode::G_FCMP:
3058e8d8bef9SDimitry Andric       if (IsInt)
3059e8d8bef9SDimitry Andric         return false;
3060e8d8bef9SDimitry Andric       IsFP = true;
3061e8d8bef9SDimitry Andric       // When we apply the combine we will invert the predicate.
3062e8d8bef9SDimitry Andric       break;
3063e8d8bef9SDimitry Andric     case TargetOpcode::G_AND:
3064e8d8bef9SDimitry Andric     case TargetOpcode::G_OR:
3065e8d8bef9SDimitry Andric       // Implement De Morgan's laws:
3066e8d8bef9SDimitry Andric       // ~(x & y) -> ~x | ~y
3067e8d8bef9SDimitry Andric       // ~(x | y) -> ~x & ~y
3068e8d8bef9SDimitry Andric       // When we apply the combine we will change the opcode and recursively
3069e8d8bef9SDimitry Andric       // negate the operands.
3070e8d8bef9SDimitry Andric       RegsToNegate.push_back(Def->getOperand(1).getReg());
3071e8d8bef9SDimitry Andric       RegsToNegate.push_back(Def->getOperand(2).getReg());
3072e8d8bef9SDimitry Andric       break;
3073e8d8bef9SDimitry Andric     }
3074e8d8bef9SDimitry Andric   }
3075e8d8bef9SDimitry Andric 
3076e8d8bef9SDimitry Andric   // Now we know whether the comparisons are integer or floating point, check
3077e8d8bef9SDimitry Andric   // the constant in the xor.
3078e8d8bef9SDimitry Andric   int64_t Cst;
3079e8d8bef9SDimitry Andric   if (Ty.isVector()) {
3080e8d8bef9SDimitry Andric     MachineInstr *CstDef = MRI.getVRegDef(CstReg);
308181ad6265SDimitry Andric     auto MaybeCst = getIConstantSplatSExtVal(*CstDef, MRI);
3082e8d8bef9SDimitry Andric     if (!MaybeCst)
3083e8d8bef9SDimitry Andric       return false;
3084e8d8bef9SDimitry Andric     if (!isConstValidTrue(TLI, Ty.getScalarSizeInBits(), *MaybeCst, true, IsFP))
3085e8d8bef9SDimitry Andric       return false;
3086e8d8bef9SDimitry Andric   } else {
3087e8d8bef9SDimitry Andric     if (!mi_match(CstReg, MRI, m_ICst(Cst)))
3088e8d8bef9SDimitry Andric       return false;
3089e8d8bef9SDimitry Andric     if (!isConstValidTrue(TLI, Ty.getSizeInBits(), Cst, false, IsFP))
3090e8d8bef9SDimitry Andric       return false;
3091e8d8bef9SDimitry Andric   }
3092e8d8bef9SDimitry Andric 
3093e8d8bef9SDimitry Andric   return true;
3094e8d8bef9SDimitry Andric }
3095e8d8bef9SDimitry Andric 
3096fe6060f1SDimitry Andric void CombinerHelper::applyNotCmp(MachineInstr &MI,
3097e8d8bef9SDimitry Andric                                  SmallVectorImpl<Register> &RegsToNegate) {
3098e8d8bef9SDimitry Andric   for (Register Reg : RegsToNegate) {
3099e8d8bef9SDimitry Andric     MachineInstr *Def = MRI.getVRegDef(Reg);
3100e8d8bef9SDimitry Andric     Observer.changingInstr(*Def);
3101e8d8bef9SDimitry Andric     // For each comparison, invert the opcode. For each AND and OR, change the
3102e8d8bef9SDimitry Andric     // opcode.
3103e8d8bef9SDimitry Andric     switch (Def->getOpcode()) {
3104e8d8bef9SDimitry Andric     default:
3105e8d8bef9SDimitry Andric       llvm_unreachable("Unexpected opcode");
3106e8d8bef9SDimitry Andric     case TargetOpcode::G_ICMP:
3107e8d8bef9SDimitry Andric     case TargetOpcode::G_FCMP: {
3108e8d8bef9SDimitry Andric       MachineOperand &PredOp = Def->getOperand(1);
3109e8d8bef9SDimitry Andric       CmpInst::Predicate NewP = CmpInst::getInversePredicate(
3110e8d8bef9SDimitry Andric           (CmpInst::Predicate)PredOp.getPredicate());
3111e8d8bef9SDimitry Andric       PredOp.setPredicate(NewP);
3112e8d8bef9SDimitry Andric       break;
3113e8d8bef9SDimitry Andric     }
3114e8d8bef9SDimitry Andric     case TargetOpcode::G_AND:
3115e8d8bef9SDimitry Andric       Def->setDesc(Builder.getTII().get(TargetOpcode::G_OR));
3116e8d8bef9SDimitry Andric       break;
3117e8d8bef9SDimitry Andric     case TargetOpcode::G_OR:
3118e8d8bef9SDimitry Andric       Def->setDesc(Builder.getTII().get(TargetOpcode::G_AND));
3119e8d8bef9SDimitry Andric       break;
3120e8d8bef9SDimitry Andric     }
3121e8d8bef9SDimitry Andric     Observer.changedInstr(*Def);
3122e8d8bef9SDimitry Andric   }
3123e8d8bef9SDimitry Andric 
3124e8d8bef9SDimitry Andric   replaceRegWith(MRI, MI.getOperand(0).getReg(), MI.getOperand(1).getReg());
3125e8d8bef9SDimitry Andric   MI.eraseFromParent();
3126e8d8bef9SDimitry Andric }
3127e8d8bef9SDimitry Andric 
3128e8d8bef9SDimitry Andric bool CombinerHelper::matchXorOfAndWithSameReg(
3129e8d8bef9SDimitry Andric     MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
3130e8d8bef9SDimitry Andric   // Match (xor (and x, y), y) (or any of its commuted cases)
3131e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_XOR);
3132e8d8bef9SDimitry Andric   Register &X = MatchInfo.first;
3133e8d8bef9SDimitry Andric   Register &Y = MatchInfo.second;
3134e8d8bef9SDimitry Andric   Register AndReg = MI.getOperand(1).getReg();
3135e8d8bef9SDimitry Andric   Register SharedReg = MI.getOperand(2).getReg();
3136e8d8bef9SDimitry Andric 
3137e8d8bef9SDimitry Andric   // Find a G_AND on either side of the G_XOR.
3138e8d8bef9SDimitry Andric   // Look for one of
3139e8d8bef9SDimitry Andric   //
3140e8d8bef9SDimitry Andric   // (xor (and x, y), SharedReg)
3141e8d8bef9SDimitry Andric   // (xor SharedReg, (and x, y))
3142e8d8bef9SDimitry Andric   if (!mi_match(AndReg, MRI, m_GAnd(m_Reg(X), m_Reg(Y)))) {
3143e8d8bef9SDimitry Andric     std::swap(AndReg, SharedReg);
3144e8d8bef9SDimitry Andric     if (!mi_match(AndReg, MRI, m_GAnd(m_Reg(X), m_Reg(Y))))
3145e8d8bef9SDimitry Andric       return false;
3146e8d8bef9SDimitry Andric   }
3147e8d8bef9SDimitry Andric 
3148e8d8bef9SDimitry Andric   // Only do this if we'll eliminate the G_AND.
3149e8d8bef9SDimitry Andric   if (!MRI.hasOneNonDBGUse(AndReg))
3150e8d8bef9SDimitry Andric     return false;
3151e8d8bef9SDimitry Andric 
3152e8d8bef9SDimitry Andric   // We can combine if SharedReg is the same as either the LHS or RHS of the
3153e8d8bef9SDimitry Andric   // G_AND.
3154e8d8bef9SDimitry Andric   if (Y != SharedReg)
3155e8d8bef9SDimitry Andric     std::swap(X, Y);
3156e8d8bef9SDimitry Andric   return Y == SharedReg;
3157e8d8bef9SDimitry Andric }
3158e8d8bef9SDimitry Andric 
3159fe6060f1SDimitry Andric void CombinerHelper::applyXorOfAndWithSameReg(
3160e8d8bef9SDimitry Andric     MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
3161e8d8bef9SDimitry Andric   // Fold (xor (and x, y), y) -> (and (not x), y)
3162e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
3163e8d8bef9SDimitry Andric   Register X, Y;
3164e8d8bef9SDimitry Andric   std::tie(X, Y) = MatchInfo;
3165e8d8bef9SDimitry Andric   auto Not = Builder.buildNot(MRI.getType(X), X);
3166e8d8bef9SDimitry Andric   Observer.changingInstr(MI);
3167e8d8bef9SDimitry Andric   MI.setDesc(Builder.getTII().get(TargetOpcode::G_AND));
3168e8d8bef9SDimitry Andric   MI.getOperand(1).setReg(Not->getOperand(0).getReg());
3169e8d8bef9SDimitry Andric   MI.getOperand(2).setReg(Y);
3170e8d8bef9SDimitry Andric   Observer.changedInstr(MI);
3171e8d8bef9SDimitry Andric }
3172e8d8bef9SDimitry Andric 
3173e8d8bef9SDimitry Andric bool CombinerHelper::matchPtrAddZero(MachineInstr &MI) {
3174349cc55cSDimitry Andric   auto &PtrAdd = cast<GPtrAdd>(MI);
3175349cc55cSDimitry Andric   Register DstReg = PtrAdd.getReg(0);
3176e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(DstReg);
3177e8d8bef9SDimitry Andric   const DataLayout &DL = Builder.getMF().getDataLayout();
3178e8d8bef9SDimitry Andric 
3179e8d8bef9SDimitry Andric   if (DL.isNonIntegralAddressSpace(Ty.getScalarType().getAddressSpace()))
3180e8d8bef9SDimitry Andric     return false;
3181e8d8bef9SDimitry Andric 
3182e8d8bef9SDimitry Andric   if (Ty.isPointer()) {
3183349cc55cSDimitry Andric     auto ConstVal = getIConstantVRegVal(PtrAdd.getBaseReg(), MRI);
3184e8d8bef9SDimitry Andric     return ConstVal && *ConstVal == 0;
3185e8d8bef9SDimitry Andric   }
3186e8d8bef9SDimitry Andric 
3187e8d8bef9SDimitry Andric   assert(Ty.isVector() && "Expecting a vector type");
3188349cc55cSDimitry Andric   const MachineInstr *VecMI = MRI.getVRegDef(PtrAdd.getBaseReg());
3189e8d8bef9SDimitry Andric   return isBuildVectorAllZeros(*VecMI, MRI);
3190e8d8bef9SDimitry Andric }
3191e8d8bef9SDimitry Andric 
3192fe6060f1SDimitry Andric void CombinerHelper::applyPtrAddZero(MachineInstr &MI) {
3193349cc55cSDimitry Andric   auto &PtrAdd = cast<GPtrAdd>(MI);
3194349cc55cSDimitry Andric   Builder.setInstrAndDebugLoc(PtrAdd);
3195349cc55cSDimitry Andric   Builder.buildIntToPtr(PtrAdd.getReg(0), PtrAdd.getOffsetReg());
3196349cc55cSDimitry Andric   PtrAdd.eraseFromParent();
3197e8d8bef9SDimitry Andric }
3198e8d8bef9SDimitry Andric 
3199e8d8bef9SDimitry Andric /// The second source operand is known to be a power of 2.
3200fe6060f1SDimitry Andric void CombinerHelper::applySimplifyURemByPow2(MachineInstr &MI) {
3201e8d8bef9SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
3202e8d8bef9SDimitry Andric   Register Src0 = MI.getOperand(1).getReg();
3203e8d8bef9SDimitry Andric   Register Pow2Src1 = MI.getOperand(2).getReg();
3204e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(DstReg);
3205e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
3206e8d8bef9SDimitry Andric 
3207e8d8bef9SDimitry Andric   // Fold (urem x, pow2) -> (and x, pow2-1)
3208e8d8bef9SDimitry Andric   auto NegOne = Builder.buildConstant(Ty, -1);
3209e8d8bef9SDimitry Andric   auto Add = Builder.buildAdd(Ty, Pow2Src1, NegOne);
3210e8d8bef9SDimitry Andric   Builder.buildAnd(DstReg, Src0, Add);
3211e8d8bef9SDimitry Andric   MI.eraseFromParent();
3212e8d8bef9SDimitry Andric }
3213e8d8bef9SDimitry Andric 
321481ad6265SDimitry Andric bool CombinerHelper::matchFoldBinOpIntoSelect(MachineInstr &MI,
321581ad6265SDimitry Andric                                               unsigned &SelectOpNo) {
321681ad6265SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
321781ad6265SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
321881ad6265SDimitry Andric 
321981ad6265SDimitry Andric   Register OtherOperandReg = RHS;
322081ad6265SDimitry Andric   SelectOpNo = 1;
322181ad6265SDimitry Andric   MachineInstr *Select = MRI.getVRegDef(LHS);
322281ad6265SDimitry Andric 
322381ad6265SDimitry Andric   // Don't do this unless the old select is going away. We want to eliminate the
322481ad6265SDimitry Andric   // binary operator, not replace a binop with a select.
322581ad6265SDimitry Andric   if (Select->getOpcode() != TargetOpcode::G_SELECT ||
322681ad6265SDimitry Andric       !MRI.hasOneNonDBGUse(LHS)) {
322781ad6265SDimitry Andric     OtherOperandReg = LHS;
322881ad6265SDimitry Andric     SelectOpNo = 2;
322981ad6265SDimitry Andric     Select = MRI.getVRegDef(RHS);
323081ad6265SDimitry Andric     if (Select->getOpcode() != TargetOpcode::G_SELECT ||
323181ad6265SDimitry Andric         !MRI.hasOneNonDBGUse(RHS))
323281ad6265SDimitry Andric       return false;
323381ad6265SDimitry Andric   }
323481ad6265SDimitry Andric 
323581ad6265SDimitry Andric   MachineInstr *SelectLHS = MRI.getVRegDef(Select->getOperand(2).getReg());
323681ad6265SDimitry Andric   MachineInstr *SelectRHS = MRI.getVRegDef(Select->getOperand(3).getReg());
323781ad6265SDimitry Andric 
323881ad6265SDimitry Andric   if (!isConstantOrConstantVector(*SelectLHS, MRI,
323981ad6265SDimitry Andric                                   /*AllowFP*/ true,
324081ad6265SDimitry Andric                                   /*AllowOpaqueConstants*/ false))
324181ad6265SDimitry Andric     return false;
324281ad6265SDimitry Andric   if (!isConstantOrConstantVector(*SelectRHS, MRI,
324381ad6265SDimitry Andric                                   /*AllowFP*/ true,
324481ad6265SDimitry Andric                                   /*AllowOpaqueConstants*/ false))
324581ad6265SDimitry Andric     return false;
324681ad6265SDimitry Andric 
324781ad6265SDimitry Andric   unsigned BinOpcode = MI.getOpcode();
324881ad6265SDimitry Andric 
324981ad6265SDimitry Andric   // We know know one of the operands is a select of constants. Now verify that
325081ad6265SDimitry Andric   // the other binary operator operand is either a constant, or we can handle a
325181ad6265SDimitry Andric   // variable.
325281ad6265SDimitry Andric   bool CanFoldNonConst =
325381ad6265SDimitry Andric       (BinOpcode == TargetOpcode::G_AND || BinOpcode == TargetOpcode::G_OR) &&
325481ad6265SDimitry Andric       (isNullOrNullSplat(*SelectLHS, MRI) ||
325581ad6265SDimitry Andric        isAllOnesOrAllOnesSplat(*SelectLHS, MRI)) &&
325681ad6265SDimitry Andric       (isNullOrNullSplat(*SelectRHS, MRI) ||
325781ad6265SDimitry Andric        isAllOnesOrAllOnesSplat(*SelectRHS, MRI));
325881ad6265SDimitry Andric   if (CanFoldNonConst)
325981ad6265SDimitry Andric     return true;
326081ad6265SDimitry Andric 
326181ad6265SDimitry Andric   return isConstantOrConstantVector(*MRI.getVRegDef(OtherOperandReg), MRI,
326281ad6265SDimitry Andric                                     /*AllowFP*/ true,
326381ad6265SDimitry Andric                                     /*AllowOpaqueConstants*/ false);
326481ad6265SDimitry Andric }
326581ad6265SDimitry Andric 
326681ad6265SDimitry Andric /// \p SelectOperand is the operand in binary operator \p MI that is the select
326781ad6265SDimitry Andric /// to fold.
3268*06c3fb27SDimitry Andric void CombinerHelper::applyFoldBinOpIntoSelect(MachineInstr &MI,
326981ad6265SDimitry Andric                                               const unsigned &SelectOperand) {
327081ad6265SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
327181ad6265SDimitry Andric 
327281ad6265SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
327381ad6265SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
327481ad6265SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
327581ad6265SDimitry Andric   MachineInstr *Select = MRI.getVRegDef(MI.getOperand(SelectOperand).getReg());
327681ad6265SDimitry Andric 
327781ad6265SDimitry Andric   Register SelectCond = Select->getOperand(1).getReg();
327881ad6265SDimitry Andric   Register SelectTrue = Select->getOperand(2).getReg();
327981ad6265SDimitry Andric   Register SelectFalse = Select->getOperand(3).getReg();
328081ad6265SDimitry Andric 
328181ad6265SDimitry Andric   LLT Ty = MRI.getType(Dst);
328281ad6265SDimitry Andric   unsigned BinOpcode = MI.getOpcode();
328381ad6265SDimitry Andric 
328481ad6265SDimitry Andric   Register FoldTrue, FoldFalse;
328581ad6265SDimitry Andric 
328681ad6265SDimitry Andric   // We have a select-of-constants followed by a binary operator with a
328781ad6265SDimitry Andric   // constant. Eliminate the binop by pulling the constant math into the select.
328881ad6265SDimitry Andric   // Example: add (select Cond, CT, CF), CBO --> select Cond, CT + CBO, CF + CBO
328981ad6265SDimitry Andric   if (SelectOperand == 1) {
329081ad6265SDimitry Andric     // TODO: SelectionDAG verifies this actually constant folds before
329181ad6265SDimitry Andric     // committing to the combine.
329281ad6265SDimitry Andric 
329381ad6265SDimitry Andric     FoldTrue = Builder.buildInstr(BinOpcode, {Ty}, {SelectTrue, RHS}).getReg(0);
329481ad6265SDimitry Andric     FoldFalse =
329581ad6265SDimitry Andric         Builder.buildInstr(BinOpcode, {Ty}, {SelectFalse, RHS}).getReg(0);
329681ad6265SDimitry Andric   } else {
329781ad6265SDimitry Andric     FoldTrue = Builder.buildInstr(BinOpcode, {Ty}, {LHS, SelectTrue}).getReg(0);
329881ad6265SDimitry Andric     FoldFalse =
329981ad6265SDimitry Andric         Builder.buildInstr(BinOpcode, {Ty}, {LHS, SelectFalse}).getReg(0);
330081ad6265SDimitry Andric   }
330181ad6265SDimitry Andric 
330281ad6265SDimitry Andric   Builder.buildSelect(Dst, SelectCond, FoldTrue, FoldFalse, MI.getFlags());
330381ad6265SDimitry Andric   MI.eraseFromParent();
330481ad6265SDimitry Andric }
330581ad6265SDimitry Andric 
3306bdd1243dSDimitry Andric std::optional<SmallVector<Register, 8>>
3307e8d8bef9SDimitry Andric CombinerHelper::findCandidatesForLoadOrCombine(const MachineInstr *Root) const {
3308e8d8bef9SDimitry Andric   assert(Root->getOpcode() == TargetOpcode::G_OR && "Expected G_OR only!");
3309e8d8bef9SDimitry Andric   // We want to detect if Root is part of a tree which represents a bunch
3310e8d8bef9SDimitry Andric   // of loads being merged into a larger load. We'll try to recognize patterns
3311e8d8bef9SDimitry Andric   // like, for example:
3312e8d8bef9SDimitry Andric   //
3313e8d8bef9SDimitry Andric   //  Reg   Reg
3314e8d8bef9SDimitry Andric   //   \    /
3315e8d8bef9SDimitry Andric   //    OR_1   Reg
3316e8d8bef9SDimitry Andric   //     \    /
3317e8d8bef9SDimitry Andric   //      OR_2
3318e8d8bef9SDimitry Andric   //        \     Reg
3319e8d8bef9SDimitry Andric   //         .. /
3320e8d8bef9SDimitry Andric   //        Root
3321e8d8bef9SDimitry Andric   //
3322e8d8bef9SDimitry Andric   //  Reg   Reg   Reg   Reg
3323e8d8bef9SDimitry Andric   //     \ /       \   /
3324e8d8bef9SDimitry Andric   //     OR_1      OR_2
3325e8d8bef9SDimitry Andric   //       \       /
3326e8d8bef9SDimitry Andric   //        \    /
3327e8d8bef9SDimitry Andric   //         ...
3328e8d8bef9SDimitry Andric   //         Root
3329e8d8bef9SDimitry Andric   //
3330e8d8bef9SDimitry Andric   // Each "Reg" may have been produced by a load + some arithmetic. This
3331e8d8bef9SDimitry Andric   // function will save each of them.
3332e8d8bef9SDimitry Andric   SmallVector<Register, 8> RegsToVisit;
3333e8d8bef9SDimitry Andric   SmallVector<const MachineInstr *, 7> Ors = {Root};
3334e8d8bef9SDimitry Andric 
3335e8d8bef9SDimitry Andric   // In the "worst" case, we're dealing with a load for each byte. So, there
3336e8d8bef9SDimitry Andric   // are at most #bytes - 1 ORs.
3337e8d8bef9SDimitry Andric   const unsigned MaxIter =
3338e8d8bef9SDimitry Andric       MRI.getType(Root->getOperand(0).getReg()).getSizeInBytes() - 1;
3339e8d8bef9SDimitry Andric   for (unsigned Iter = 0; Iter < MaxIter; ++Iter) {
3340e8d8bef9SDimitry Andric     if (Ors.empty())
3341e8d8bef9SDimitry Andric       break;
3342e8d8bef9SDimitry Andric     const MachineInstr *Curr = Ors.pop_back_val();
3343e8d8bef9SDimitry Andric     Register OrLHS = Curr->getOperand(1).getReg();
3344e8d8bef9SDimitry Andric     Register OrRHS = Curr->getOperand(2).getReg();
3345e8d8bef9SDimitry Andric 
3346e8d8bef9SDimitry Andric     // In the combine, we want to elimate the entire tree.
3347e8d8bef9SDimitry Andric     if (!MRI.hasOneNonDBGUse(OrLHS) || !MRI.hasOneNonDBGUse(OrRHS))
3348bdd1243dSDimitry Andric       return std::nullopt;
3349e8d8bef9SDimitry Andric 
3350e8d8bef9SDimitry Andric     // If it's a G_OR, save it and continue to walk. If it's not, then it's
3351e8d8bef9SDimitry Andric     // something that may be a load + arithmetic.
3352e8d8bef9SDimitry Andric     if (const MachineInstr *Or = getOpcodeDef(TargetOpcode::G_OR, OrLHS, MRI))
3353e8d8bef9SDimitry Andric       Ors.push_back(Or);
3354e8d8bef9SDimitry Andric     else
3355e8d8bef9SDimitry Andric       RegsToVisit.push_back(OrLHS);
3356e8d8bef9SDimitry Andric     if (const MachineInstr *Or = getOpcodeDef(TargetOpcode::G_OR, OrRHS, MRI))
3357e8d8bef9SDimitry Andric       Ors.push_back(Or);
3358e8d8bef9SDimitry Andric     else
3359e8d8bef9SDimitry Andric       RegsToVisit.push_back(OrRHS);
3360e8d8bef9SDimitry Andric   }
3361e8d8bef9SDimitry Andric 
3362e8d8bef9SDimitry Andric   // We're going to try and merge each register into a wider power-of-2 type,
3363e8d8bef9SDimitry Andric   // so we ought to have an even number of registers.
3364e8d8bef9SDimitry Andric   if (RegsToVisit.empty() || RegsToVisit.size() % 2 != 0)
3365bdd1243dSDimitry Andric     return std::nullopt;
3366e8d8bef9SDimitry Andric   return RegsToVisit;
3367e8d8bef9SDimitry Andric }
3368e8d8bef9SDimitry Andric 
3369e8d8bef9SDimitry Andric /// Helper function for findLoadOffsetsForLoadOrCombine.
3370e8d8bef9SDimitry Andric ///
3371e8d8bef9SDimitry Andric /// Check if \p Reg is the result of loading a \p MemSizeInBits wide value,
3372e8d8bef9SDimitry Andric /// and then moving that value into a specific byte offset.
3373e8d8bef9SDimitry Andric ///
3374e8d8bef9SDimitry Andric /// e.g. x[i] << 24
3375e8d8bef9SDimitry Andric ///
3376e8d8bef9SDimitry Andric /// \returns The load instruction and the byte offset it is moved into.
3377bdd1243dSDimitry Andric static std::optional<std::pair<GZExtLoad *, int64_t>>
3378e8d8bef9SDimitry Andric matchLoadAndBytePosition(Register Reg, unsigned MemSizeInBits,
3379e8d8bef9SDimitry Andric                          const MachineRegisterInfo &MRI) {
3380e8d8bef9SDimitry Andric   assert(MRI.hasOneNonDBGUse(Reg) &&
3381e8d8bef9SDimitry Andric          "Expected Reg to only have one non-debug use?");
3382e8d8bef9SDimitry Andric   Register MaybeLoad;
3383e8d8bef9SDimitry Andric   int64_t Shift;
3384e8d8bef9SDimitry Andric   if (!mi_match(Reg, MRI,
3385e8d8bef9SDimitry Andric                 m_OneNonDBGUse(m_GShl(m_Reg(MaybeLoad), m_ICst(Shift))))) {
3386e8d8bef9SDimitry Andric     Shift = 0;
3387e8d8bef9SDimitry Andric     MaybeLoad = Reg;
3388e8d8bef9SDimitry Andric   }
3389e8d8bef9SDimitry Andric 
3390e8d8bef9SDimitry Andric   if (Shift % MemSizeInBits != 0)
3391bdd1243dSDimitry Andric     return std::nullopt;
3392e8d8bef9SDimitry Andric 
3393e8d8bef9SDimitry Andric   // TODO: Handle other types of loads.
3394fe6060f1SDimitry Andric   auto *Load = getOpcodeDef<GZExtLoad>(MaybeLoad, MRI);
3395e8d8bef9SDimitry Andric   if (!Load)
3396bdd1243dSDimitry Andric     return std::nullopt;
3397e8d8bef9SDimitry Andric 
3398fe6060f1SDimitry Andric   if (!Load->isUnordered() || Load->getMemSizeInBits() != MemSizeInBits)
3399bdd1243dSDimitry Andric     return std::nullopt;
3400e8d8bef9SDimitry Andric 
3401e8d8bef9SDimitry Andric   return std::make_pair(Load, Shift / MemSizeInBits);
3402e8d8bef9SDimitry Andric }
3403e8d8bef9SDimitry Andric 
3404bdd1243dSDimitry Andric std::optional<std::tuple<GZExtLoad *, int64_t, GZExtLoad *>>
3405e8d8bef9SDimitry Andric CombinerHelper::findLoadOffsetsForLoadOrCombine(
3406e8d8bef9SDimitry Andric     SmallDenseMap<int64_t, int64_t, 8> &MemOffset2Idx,
3407e8d8bef9SDimitry Andric     const SmallVector<Register, 8> &RegsToVisit, const unsigned MemSizeInBits) {
3408e8d8bef9SDimitry Andric 
3409e8d8bef9SDimitry Andric   // Each load found for the pattern. There should be one for each RegsToVisit.
3410e8d8bef9SDimitry Andric   SmallSetVector<const MachineInstr *, 8> Loads;
3411e8d8bef9SDimitry Andric 
3412e8d8bef9SDimitry Andric   // The lowest index used in any load. (The lowest "i" for each x[i].)
3413e8d8bef9SDimitry Andric   int64_t LowestIdx = INT64_MAX;
3414e8d8bef9SDimitry Andric 
3415e8d8bef9SDimitry Andric   // The load which uses the lowest index.
3416fe6060f1SDimitry Andric   GZExtLoad *LowestIdxLoad = nullptr;
3417e8d8bef9SDimitry Andric 
3418e8d8bef9SDimitry Andric   // Keeps track of the load indices we see. We shouldn't see any indices twice.
3419e8d8bef9SDimitry Andric   SmallSet<int64_t, 8> SeenIdx;
3420e8d8bef9SDimitry Andric 
3421e8d8bef9SDimitry Andric   // Ensure each load is in the same MBB.
3422e8d8bef9SDimitry Andric   // TODO: Support multiple MachineBasicBlocks.
3423e8d8bef9SDimitry Andric   MachineBasicBlock *MBB = nullptr;
3424e8d8bef9SDimitry Andric   const MachineMemOperand *MMO = nullptr;
3425e8d8bef9SDimitry Andric 
3426e8d8bef9SDimitry Andric   // Earliest instruction-order load in the pattern.
3427fe6060f1SDimitry Andric   GZExtLoad *EarliestLoad = nullptr;
3428e8d8bef9SDimitry Andric 
3429e8d8bef9SDimitry Andric   // Latest instruction-order load in the pattern.
3430fe6060f1SDimitry Andric   GZExtLoad *LatestLoad = nullptr;
3431e8d8bef9SDimitry Andric 
3432e8d8bef9SDimitry Andric   // Base pointer which every load should share.
3433e8d8bef9SDimitry Andric   Register BasePtr;
3434e8d8bef9SDimitry Andric 
3435e8d8bef9SDimitry Andric   // We want to find a load for each register. Each load should have some
3436e8d8bef9SDimitry Andric   // appropriate bit twiddling arithmetic. During this loop, we will also keep
3437e8d8bef9SDimitry Andric   // track of the load which uses the lowest index. Later, we will check if we
3438e8d8bef9SDimitry Andric   // can use its pointer in the final, combined load.
3439e8d8bef9SDimitry Andric   for (auto Reg : RegsToVisit) {
3440e8d8bef9SDimitry Andric     // Find the load, and find the position that it will end up in (e.g. a
3441e8d8bef9SDimitry Andric     // shifted) value.
3442e8d8bef9SDimitry Andric     auto LoadAndPos = matchLoadAndBytePosition(Reg, MemSizeInBits, MRI);
3443e8d8bef9SDimitry Andric     if (!LoadAndPos)
3444bdd1243dSDimitry Andric       return std::nullopt;
3445fe6060f1SDimitry Andric     GZExtLoad *Load;
3446e8d8bef9SDimitry Andric     int64_t DstPos;
3447e8d8bef9SDimitry Andric     std::tie(Load, DstPos) = *LoadAndPos;
3448e8d8bef9SDimitry Andric 
3449e8d8bef9SDimitry Andric     // TODO: Handle multiple MachineBasicBlocks. Currently not handled because
3450e8d8bef9SDimitry Andric     // it is difficult to check for stores/calls/etc between loads.
3451e8d8bef9SDimitry Andric     MachineBasicBlock *LoadMBB = Load->getParent();
3452e8d8bef9SDimitry Andric     if (!MBB)
3453e8d8bef9SDimitry Andric       MBB = LoadMBB;
3454e8d8bef9SDimitry Andric     if (LoadMBB != MBB)
3455bdd1243dSDimitry Andric       return std::nullopt;
3456e8d8bef9SDimitry Andric 
3457e8d8bef9SDimitry Andric     // Make sure that the MachineMemOperands of every seen load are compatible.
3458fe6060f1SDimitry Andric     auto &LoadMMO = Load->getMMO();
3459e8d8bef9SDimitry Andric     if (!MMO)
3460fe6060f1SDimitry Andric       MMO = &LoadMMO;
3461fe6060f1SDimitry Andric     if (MMO->getAddrSpace() != LoadMMO.getAddrSpace())
3462bdd1243dSDimitry Andric       return std::nullopt;
3463e8d8bef9SDimitry Andric 
3464e8d8bef9SDimitry Andric     // Find out what the base pointer and index for the load is.
3465e8d8bef9SDimitry Andric     Register LoadPtr;
3466e8d8bef9SDimitry Andric     int64_t Idx;
3467e8d8bef9SDimitry Andric     if (!mi_match(Load->getOperand(1).getReg(), MRI,
3468e8d8bef9SDimitry Andric                   m_GPtrAdd(m_Reg(LoadPtr), m_ICst(Idx)))) {
3469e8d8bef9SDimitry Andric       LoadPtr = Load->getOperand(1).getReg();
3470e8d8bef9SDimitry Andric       Idx = 0;
3471e8d8bef9SDimitry Andric     }
3472e8d8bef9SDimitry Andric 
3473e8d8bef9SDimitry Andric     // Don't combine things like a[i], a[i] -> a bigger load.
3474e8d8bef9SDimitry Andric     if (!SeenIdx.insert(Idx).second)
3475bdd1243dSDimitry Andric       return std::nullopt;
3476e8d8bef9SDimitry Andric 
3477e8d8bef9SDimitry Andric     // Every load must share the same base pointer; don't combine things like:
3478e8d8bef9SDimitry Andric     //
3479e8d8bef9SDimitry Andric     // a[i], b[i + 1] -> a bigger load.
3480e8d8bef9SDimitry Andric     if (!BasePtr.isValid())
3481e8d8bef9SDimitry Andric       BasePtr = LoadPtr;
3482e8d8bef9SDimitry Andric     if (BasePtr != LoadPtr)
3483bdd1243dSDimitry Andric       return std::nullopt;
3484e8d8bef9SDimitry Andric 
3485e8d8bef9SDimitry Andric     if (Idx < LowestIdx) {
3486e8d8bef9SDimitry Andric       LowestIdx = Idx;
3487e8d8bef9SDimitry Andric       LowestIdxLoad = Load;
3488e8d8bef9SDimitry Andric     }
3489e8d8bef9SDimitry Andric 
3490e8d8bef9SDimitry Andric     // Keep track of the byte offset that this load ends up at. If we have seen
3491e8d8bef9SDimitry Andric     // the byte offset, then stop here. We do not want to combine:
3492e8d8bef9SDimitry Andric     //
3493e8d8bef9SDimitry Andric     // a[i] << 16, a[i + k] << 16 -> a bigger load.
3494e8d8bef9SDimitry Andric     if (!MemOffset2Idx.try_emplace(DstPos, Idx).second)
3495bdd1243dSDimitry Andric       return std::nullopt;
3496e8d8bef9SDimitry Andric     Loads.insert(Load);
3497e8d8bef9SDimitry Andric 
3498e8d8bef9SDimitry Andric     // Keep track of the position of the earliest/latest loads in the pattern.
3499e8d8bef9SDimitry Andric     // We will check that there are no load fold barriers between them later
3500e8d8bef9SDimitry Andric     // on.
3501e8d8bef9SDimitry Andric     //
3502e8d8bef9SDimitry Andric     // FIXME: Is there a better way to check for load fold barriers?
3503e8d8bef9SDimitry Andric     if (!EarliestLoad || dominates(*Load, *EarliestLoad))
3504e8d8bef9SDimitry Andric       EarliestLoad = Load;
3505e8d8bef9SDimitry Andric     if (!LatestLoad || dominates(*LatestLoad, *Load))
3506e8d8bef9SDimitry Andric       LatestLoad = Load;
3507e8d8bef9SDimitry Andric   }
3508e8d8bef9SDimitry Andric 
3509e8d8bef9SDimitry Andric   // We found a load for each register. Let's check if each load satisfies the
3510e8d8bef9SDimitry Andric   // pattern.
3511e8d8bef9SDimitry Andric   assert(Loads.size() == RegsToVisit.size() &&
3512e8d8bef9SDimitry Andric          "Expected to find a load for each register?");
3513e8d8bef9SDimitry Andric   assert(EarliestLoad != LatestLoad && EarliestLoad &&
3514e8d8bef9SDimitry Andric          LatestLoad && "Expected at least two loads?");
3515e8d8bef9SDimitry Andric 
3516e8d8bef9SDimitry Andric   // Check if there are any stores, calls, etc. between any of the loads. If
3517e8d8bef9SDimitry Andric   // there are, then we can't safely perform the combine.
3518e8d8bef9SDimitry Andric   //
3519e8d8bef9SDimitry Andric   // MaxIter is chosen based off the (worst case) number of iterations it
3520e8d8bef9SDimitry Andric   // typically takes to succeed in the LLVM test suite plus some padding.
3521e8d8bef9SDimitry Andric   //
3522e8d8bef9SDimitry Andric   // FIXME: Is there a better way to check for load fold barriers?
3523e8d8bef9SDimitry Andric   const unsigned MaxIter = 20;
3524e8d8bef9SDimitry Andric   unsigned Iter = 0;
3525e8d8bef9SDimitry Andric   for (const auto &MI : instructionsWithoutDebug(EarliestLoad->getIterator(),
3526e8d8bef9SDimitry Andric                                                  LatestLoad->getIterator())) {
3527e8d8bef9SDimitry Andric     if (Loads.count(&MI))
3528e8d8bef9SDimitry Andric       continue;
3529e8d8bef9SDimitry Andric     if (MI.isLoadFoldBarrier())
3530bdd1243dSDimitry Andric       return std::nullopt;
3531e8d8bef9SDimitry Andric     if (Iter++ == MaxIter)
3532bdd1243dSDimitry Andric       return std::nullopt;
3533e8d8bef9SDimitry Andric   }
3534e8d8bef9SDimitry Andric 
3535fe6060f1SDimitry Andric   return std::make_tuple(LowestIdxLoad, LowestIdx, LatestLoad);
3536e8d8bef9SDimitry Andric }
3537e8d8bef9SDimitry Andric 
3538e8d8bef9SDimitry Andric bool CombinerHelper::matchLoadOrCombine(
3539e8d8bef9SDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
3540e8d8bef9SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_OR);
3541e8d8bef9SDimitry Andric   MachineFunction &MF = *MI.getMF();
3542e8d8bef9SDimitry Andric   // Assuming a little-endian target, transform:
3543e8d8bef9SDimitry Andric   //  s8 *a = ...
3544e8d8bef9SDimitry Andric   //  s32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
3545e8d8bef9SDimitry Andric   // =>
3546e8d8bef9SDimitry Andric   //  s32 val = *((i32)a)
3547e8d8bef9SDimitry Andric   //
3548e8d8bef9SDimitry Andric   //  s8 *a = ...
3549e8d8bef9SDimitry Andric   //  s32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
3550e8d8bef9SDimitry Andric   // =>
3551e8d8bef9SDimitry Andric   //  s32 val = BSWAP(*((s32)a))
3552e8d8bef9SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
3553e8d8bef9SDimitry Andric   LLT Ty = MRI.getType(Dst);
3554e8d8bef9SDimitry Andric   if (Ty.isVector())
3555e8d8bef9SDimitry Andric     return false;
3556e8d8bef9SDimitry Andric 
3557e8d8bef9SDimitry Andric   // We need to combine at least two loads into this type. Since the smallest
3558e8d8bef9SDimitry Andric   // possible load is into a byte, we need at least a 16-bit wide type.
3559e8d8bef9SDimitry Andric   const unsigned WideMemSizeInBits = Ty.getSizeInBits();
3560e8d8bef9SDimitry Andric   if (WideMemSizeInBits < 16 || WideMemSizeInBits % 8 != 0)
3561e8d8bef9SDimitry Andric     return false;
3562e8d8bef9SDimitry Andric 
3563e8d8bef9SDimitry Andric   // Match a collection of non-OR instructions in the pattern.
3564e8d8bef9SDimitry Andric   auto RegsToVisit = findCandidatesForLoadOrCombine(&MI);
3565e8d8bef9SDimitry Andric   if (!RegsToVisit)
3566e8d8bef9SDimitry Andric     return false;
3567e8d8bef9SDimitry Andric 
3568e8d8bef9SDimitry Andric   // We have a collection of non-OR instructions. Figure out how wide each of
3569e8d8bef9SDimitry Andric   // the small loads should be based off of the number of potential loads we
3570e8d8bef9SDimitry Andric   // found.
3571e8d8bef9SDimitry Andric   const unsigned NarrowMemSizeInBits = WideMemSizeInBits / RegsToVisit->size();
3572e8d8bef9SDimitry Andric   if (NarrowMemSizeInBits % 8 != 0)
3573e8d8bef9SDimitry Andric     return false;
3574e8d8bef9SDimitry Andric 
3575e8d8bef9SDimitry Andric   // Check if each register feeding into each OR is a load from the same
3576e8d8bef9SDimitry Andric   // base pointer + some arithmetic.
3577e8d8bef9SDimitry Andric   //
3578e8d8bef9SDimitry Andric   // e.g. a[0], a[1] << 8, a[2] << 16, etc.
3579e8d8bef9SDimitry Andric   //
3580e8d8bef9SDimitry Andric   // Also verify that each of these ends up putting a[i] into the same memory
3581e8d8bef9SDimitry Andric   // offset as a load into a wide type would.
3582e8d8bef9SDimitry Andric   SmallDenseMap<int64_t, int64_t, 8> MemOffset2Idx;
3583fe6060f1SDimitry Andric   GZExtLoad *LowestIdxLoad, *LatestLoad;
3584e8d8bef9SDimitry Andric   int64_t LowestIdx;
3585e8d8bef9SDimitry Andric   auto MaybeLoadInfo = findLoadOffsetsForLoadOrCombine(
3586e8d8bef9SDimitry Andric       MemOffset2Idx, *RegsToVisit, NarrowMemSizeInBits);
3587e8d8bef9SDimitry Andric   if (!MaybeLoadInfo)
3588e8d8bef9SDimitry Andric     return false;
3589fe6060f1SDimitry Andric   std::tie(LowestIdxLoad, LowestIdx, LatestLoad) = *MaybeLoadInfo;
3590e8d8bef9SDimitry Andric 
3591e8d8bef9SDimitry Andric   // We have a bunch of loads being OR'd together. Using the addresses + offsets
3592e8d8bef9SDimitry Andric   // we found before, check if this corresponds to a big or little endian byte
3593e8d8bef9SDimitry Andric   // pattern. If it does, then we can represent it using a load + possibly a
3594e8d8bef9SDimitry Andric   // BSWAP.
3595e8d8bef9SDimitry Andric   bool IsBigEndianTarget = MF.getDataLayout().isBigEndian();
3596bdd1243dSDimitry Andric   std::optional<bool> IsBigEndian = isBigEndian(MemOffset2Idx, LowestIdx);
359781ad6265SDimitry Andric   if (!IsBigEndian)
3598e8d8bef9SDimitry Andric     return false;
3599e8d8bef9SDimitry Andric   bool NeedsBSwap = IsBigEndianTarget != *IsBigEndian;
3600e8d8bef9SDimitry Andric   if (NeedsBSwap && !isLegalOrBeforeLegalizer({TargetOpcode::G_BSWAP, {Ty}}))
3601e8d8bef9SDimitry Andric     return false;
3602e8d8bef9SDimitry Andric 
3603e8d8bef9SDimitry Andric   // Make sure that the load from the lowest index produces offset 0 in the
3604e8d8bef9SDimitry Andric   // final value.
3605e8d8bef9SDimitry Andric   //
3606e8d8bef9SDimitry Andric   // This ensures that we won't combine something like this:
3607e8d8bef9SDimitry Andric   //
3608e8d8bef9SDimitry Andric   // load x[i] -> byte 2
3609e8d8bef9SDimitry Andric   // load x[i+1] -> byte 0 ---> wide_load x[i]
3610e8d8bef9SDimitry Andric   // load x[i+2] -> byte 1
3611e8d8bef9SDimitry Andric   const unsigned NumLoadsInTy = WideMemSizeInBits / NarrowMemSizeInBits;
3612e8d8bef9SDimitry Andric   const unsigned ZeroByteOffset =
3613e8d8bef9SDimitry Andric       *IsBigEndian
3614e8d8bef9SDimitry Andric           ? bigEndianByteAt(NumLoadsInTy, 0)
3615e8d8bef9SDimitry Andric           : littleEndianByteAt(NumLoadsInTy, 0);
3616e8d8bef9SDimitry Andric   auto ZeroOffsetIdx = MemOffset2Idx.find(ZeroByteOffset);
3617e8d8bef9SDimitry Andric   if (ZeroOffsetIdx == MemOffset2Idx.end() ||
3618e8d8bef9SDimitry Andric       ZeroOffsetIdx->second != LowestIdx)
3619e8d8bef9SDimitry Andric     return false;
3620e8d8bef9SDimitry Andric 
3621e8d8bef9SDimitry Andric   // We wil reuse the pointer from the load which ends up at byte offset 0. It
3622e8d8bef9SDimitry Andric   // may not use index 0.
3623fe6060f1SDimitry Andric   Register Ptr = LowestIdxLoad->getPointerReg();
3624fe6060f1SDimitry Andric   const MachineMemOperand &MMO = LowestIdxLoad->getMMO();
3625349cc55cSDimitry Andric   LegalityQuery::MemDesc MMDesc(MMO);
3626fe6060f1SDimitry Andric   MMDesc.MemoryTy = Ty;
3627e8d8bef9SDimitry Andric   if (!isLegalOrBeforeLegalizer(
3628e8d8bef9SDimitry Andric           {TargetOpcode::G_LOAD, {Ty, MRI.getType(Ptr)}, {MMDesc}}))
3629e8d8bef9SDimitry Andric     return false;
3630e8d8bef9SDimitry Andric   auto PtrInfo = MMO.getPointerInfo();
3631e8d8bef9SDimitry Andric   auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, WideMemSizeInBits / 8);
3632e8d8bef9SDimitry Andric 
3633e8d8bef9SDimitry Andric   // Load must be allowed and fast on the target.
3634e8d8bef9SDimitry Andric   LLVMContext &C = MF.getFunction().getContext();
3635e8d8bef9SDimitry Andric   auto &DL = MF.getDataLayout();
3636bdd1243dSDimitry Andric   unsigned Fast = 0;
3637e8d8bef9SDimitry Andric   if (!getTargetLowering().allowsMemoryAccess(C, DL, Ty, *NewMMO, &Fast) ||
3638e8d8bef9SDimitry Andric       !Fast)
3639e8d8bef9SDimitry Andric     return false;
3640e8d8bef9SDimitry Andric 
3641e8d8bef9SDimitry Andric   MatchInfo = [=](MachineIRBuilder &MIB) {
3642fe6060f1SDimitry Andric     MIB.setInstrAndDebugLoc(*LatestLoad);
3643e8d8bef9SDimitry Andric     Register LoadDst = NeedsBSwap ? MRI.cloneVirtualRegister(Dst) : Dst;
3644e8d8bef9SDimitry Andric     MIB.buildLoad(LoadDst, Ptr, *NewMMO);
3645e8d8bef9SDimitry Andric     if (NeedsBSwap)
3646e8d8bef9SDimitry Andric       MIB.buildBSwap(Dst, LoadDst);
3647e8d8bef9SDimitry Andric   };
3648e8d8bef9SDimitry Andric   return true;
3649e8d8bef9SDimitry Andric }
3650e8d8bef9SDimitry Andric 
3651fe6060f1SDimitry Andric bool CombinerHelper::matchExtendThroughPhis(MachineInstr &MI,
3652fe6060f1SDimitry Andric                                             MachineInstr *&ExtMI) {
3653fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_PHI);
3654fe6060f1SDimitry Andric 
3655fe6060f1SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
3656fe6060f1SDimitry Andric 
3657fe6060f1SDimitry Andric   // TODO: Extending a vector may be expensive, don't do this until heuristics
3658fe6060f1SDimitry Andric   // are better.
3659fe6060f1SDimitry Andric   if (MRI.getType(DstReg).isVector())
3660fe6060f1SDimitry Andric     return false;
3661fe6060f1SDimitry Andric 
3662fe6060f1SDimitry Andric   // Try to match a phi, whose only use is an extend.
3663fe6060f1SDimitry Andric   if (!MRI.hasOneNonDBGUse(DstReg))
3664fe6060f1SDimitry Andric     return false;
3665fe6060f1SDimitry Andric   ExtMI = &*MRI.use_instr_nodbg_begin(DstReg);
3666fe6060f1SDimitry Andric   switch (ExtMI->getOpcode()) {
3667fe6060f1SDimitry Andric   case TargetOpcode::G_ANYEXT:
3668fe6060f1SDimitry Andric     return true; // G_ANYEXT is usually free.
3669fe6060f1SDimitry Andric   case TargetOpcode::G_ZEXT:
3670fe6060f1SDimitry Andric   case TargetOpcode::G_SEXT:
3671fe6060f1SDimitry Andric     break;
3672fe6060f1SDimitry Andric   default:
3673fe6060f1SDimitry Andric     return false;
3674fe6060f1SDimitry Andric   }
3675fe6060f1SDimitry Andric 
3676fe6060f1SDimitry Andric   // If the target is likely to fold this extend away, don't propagate.
3677fe6060f1SDimitry Andric   if (Builder.getTII().isExtendLikelyToBeFolded(*ExtMI, MRI))
3678fe6060f1SDimitry Andric     return false;
3679fe6060f1SDimitry Andric 
3680fe6060f1SDimitry Andric   // We don't want to propagate the extends unless there's a good chance that
3681fe6060f1SDimitry Andric   // they'll be optimized in some way.
3682fe6060f1SDimitry Andric   // Collect the unique incoming values.
3683fe6060f1SDimitry Andric   SmallPtrSet<MachineInstr *, 4> InSrcs;
3684fe6060f1SDimitry Andric   for (unsigned Idx = 1; Idx < MI.getNumOperands(); Idx += 2) {
3685fe6060f1SDimitry Andric     auto *DefMI = getDefIgnoringCopies(MI.getOperand(Idx).getReg(), MRI);
3686fe6060f1SDimitry Andric     switch (DefMI->getOpcode()) {
3687fe6060f1SDimitry Andric     case TargetOpcode::G_LOAD:
3688fe6060f1SDimitry Andric     case TargetOpcode::G_TRUNC:
3689fe6060f1SDimitry Andric     case TargetOpcode::G_SEXT:
3690fe6060f1SDimitry Andric     case TargetOpcode::G_ZEXT:
3691fe6060f1SDimitry Andric     case TargetOpcode::G_ANYEXT:
3692fe6060f1SDimitry Andric     case TargetOpcode::G_CONSTANT:
3693fe6060f1SDimitry Andric       InSrcs.insert(getDefIgnoringCopies(MI.getOperand(Idx).getReg(), MRI));
3694fe6060f1SDimitry Andric       // Don't try to propagate if there are too many places to create new
3695fe6060f1SDimitry Andric       // extends, chances are it'll increase code size.
3696fe6060f1SDimitry Andric       if (InSrcs.size() > 2)
3697fe6060f1SDimitry Andric         return false;
3698fe6060f1SDimitry Andric       break;
3699fe6060f1SDimitry Andric     default:
3700fe6060f1SDimitry Andric       return false;
3701fe6060f1SDimitry Andric     }
3702fe6060f1SDimitry Andric   }
3703fe6060f1SDimitry Andric   return true;
3704fe6060f1SDimitry Andric }
3705fe6060f1SDimitry Andric 
3706fe6060f1SDimitry Andric void CombinerHelper::applyExtendThroughPhis(MachineInstr &MI,
3707fe6060f1SDimitry Andric                                             MachineInstr *&ExtMI) {
3708fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_PHI);
3709fe6060f1SDimitry Andric   Register DstReg = ExtMI->getOperand(0).getReg();
3710fe6060f1SDimitry Andric   LLT ExtTy = MRI.getType(DstReg);
3711fe6060f1SDimitry Andric 
3712fe6060f1SDimitry Andric   // Propagate the extension into the block of each incoming reg's block.
3713fe6060f1SDimitry Andric   // Use a SetVector here because PHIs can have duplicate edges, and we want
3714fe6060f1SDimitry Andric   // deterministic iteration order.
3715fe6060f1SDimitry Andric   SmallSetVector<MachineInstr *, 8> SrcMIs;
3716fe6060f1SDimitry Andric   SmallDenseMap<MachineInstr *, MachineInstr *, 8> OldToNewSrcMap;
3717fe6060f1SDimitry Andric   for (unsigned SrcIdx = 1; SrcIdx < MI.getNumOperands(); SrcIdx += 2) {
3718fe6060f1SDimitry Andric     auto *SrcMI = MRI.getVRegDef(MI.getOperand(SrcIdx).getReg());
3719fe6060f1SDimitry Andric     if (!SrcMIs.insert(SrcMI))
3720fe6060f1SDimitry Andric       continue;
3721fe6060f1SDimitry Andric 
3722fe6060f1SDimitry Andric     // Build an extend after each src inst.
3723fe6060f1SDimitry Andric     auto *MBB = SrcMI->getParent();
3724fe6060f1SDimitry Andric     MachineBasicBlock::iterator InsertPt = ++SrcMI->getIterator();
3725fe6060f1SDimitry Andric     if (InsertPt != MBB->end() && InsertPt->isPHI())
3726fe6060f1SDimitry Andric       InsertPt = MBB->getFirstNonPHI();
3727fe6060f1SDimitry Andric 
3728fe6060f1SDimitry Andric     Builder.setInsertPt(*SrcMI->getParent(), InsertPt);
3729fe6060f1SDimitry Andric     Builder.setDebugLoc(MI.getDebugLoc());
3730fe6060f1SDimitry Andric     auto NewExt = Builder.buildExtOrTrunc(ExtMI->getOpcode(), ExtTy,
3731fe6060f1SDimitry Andric                                           SrcMI->getOperand(0).getReg());
3732fe6060f1SDimitry Andric     OldToNewSrcMap[SrcMI] = NewExt;
3733fe6060f1SDimitry Andric   }
3734fe6060f1SDimitry Andric 
3735fe6060f1SDimitry Andric   // Create a new phi with the extended inputs.
3736fe6060f1SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
3737fe6060f1SDimitry Andric   auto NewPhi = Builder.buildInstrNoInsert(TargetOpcode::G_PHI);
3738fe6060f1SDimitry Andric   NewPhi.addDef(DstReg);
37394824e7fdSDimitry Andric   for (const MachineOperand &MO : llvm::drop_begin(MI.operands())) {
3740fe6060f1SDimitry Andric     if (!MO.isReg()) {
3741fe6060f1SDimitry Andric       NewPhi.addMBB(MO.getMBB());
3742fe6060f1SDimitry Andric       continue;
3743fe6060f1SDimitry Andric     }
3744fe6060f1SDimitry Andric     auto *NewSrc = OldToNewSrcMap[MRI.getVRegDef(MO.getReg())];
3745fe6060f1SDimitry Andric     NewPhi.addUse(NewSrc->getOperand(0).getReg());
3746fe6060f1SDimitry Andric   }
3747fe6060f1SDimitry Andric   Builder.insertInstr(NewPhi);
3748fe6060f1SDimitry Andric   ExtMI->eraseFromParent();
3749fe6060f1SDimitry Andric }
3750fe6060f1SDimitry Andric 
3751fe6060f1SDimitry Andric bool CombinerHelper::matchExtractVecEltBuildVec(MachineInstr &MI,
3752fe6060f1SDimitry Andric                                                 Register &Reg) {
3753fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT);
3754fe6060f1SDimitry Andric   // If we have a constant index, look for a G_BUILD_VECTOR source
3755fe6060f1SDimitry Andric   // and find the source register that the index maps to.
3756fe6060f1SDimitry Andric   Register SrcVec = MI.getOperand(1).getReg();
3757fe6060f1SDimitry Andric   LLT SrcTy = MRI.getType(SrcVec);
3758fe6060f1SDimitry Andric 
3759349cc55cSDimitry Andric   auto Cst = getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
3760fe6060f1SDimitry Andric   if (!Cst || Cst->Value.getZExtValue() >= SrcTy.getNumElements())
3761fe6060f1SDimitry Andric     return false;
3762fe6060f1SDimitry Andric 
3763fe6060f1SDimitry Andric   unsigned VecIdx = Cst->Value.getZExtValue();
3764bdd1243dSDimitry Andric 
3765bdd1243dSDimitry Andric   // Check if we have a build_vector or build_vector_trunc with an optional
3766bdd1243dSDimitry Andric   // trunc in front.
3767bdd1243dSDimitry Andric   MachineInstr *SrcVecMI = MRI.getVRegDef(SrcVec);
3768bdd1243dSDimitry Andric   if (SrcVecMI->getOpcode() == TargetOpcode::G_TRUNC) {
3769bdd1243dSDimitry Andric     SrcVecMI = MRI.getVRegDef(SrcVecMI->getOperand(1).getReg());
3770fe6060f1SDimitry Andric   }
3771fe6060f1SDimitry Andric 
3772bdd1243dSDimitry Andric   if (SrcVecMI->getOpcode() != TargetOpcode::G_BUILD_VECTOR &&
3773bdd1243dSDimitry Andric       SrcVecMI->getOpcode() != TargetOpcode::G_BUILD_VECTOR_TRUNC)
3774bdd1243dSDimitry Andric     return false;
3775bdd1243dSDimitry Andric 
3776fe6060f1SDimitry Andric   EVT Ty(getMVTForLLT(SrcTy));
3777fe6060f1SDimitry Andric   if (!MRI.hasOneNonDBGUse(SrcVec) &&
3778fe6060f1SDimitry Andric       !getTargetLowering().aggressivelyPreferBuildVectorSources(Ty))
3779fe6060f1SDimitry Andric     return false;
3780fe6060f1SDimitry Andric 
3781bdd1243dSDimitry Andric   Reg = SrcVecMI->getOperand(VecIdx + 1).getReg();
3782fe6060f1SDimitry Andric   return true;
3783fe6060f1SDimitry Andric }
3784fe6060f1SDimitry Andric 
3785fe6060f1SDimitry Andric void CombinerHelper::applyExtractVecEltBuildVec(MachineInstr &MI,
3786fe6060f1SDimitry Andric                                                 Register &Reg) {
3787fe6060f1SDimitry Andric   // Check the type of the register, since it may have come from a
3788fe6060f1SDimitry Andric   // G_BUILD_VECTOR_TRUNC.
3789fe6060f1SDimitry Andric   LLT ScalarTy = MRI.getType(Reg);
3790fe6060f1SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
3791fe6060f1SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
3792fe6060f1SDimitry Andric 
3793fe6060f1SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
3794fe6060f1SDimitry Andric   if (ScalarTy != DstTy) {
3795fe6060f1SDimitry Andric     assert(ScalarTy.getSizeInBits() > DstTy.getSizeInBits());
3796fe6060f1SDimitry Andric     Builder.buildTrunc(DstReg, Reg);
3797fe6060f1SDimitry Andric     MI.eraseFromParent();
3798fe6060f1SDimitry Andric     return;
3799fe6060f1SDimitry Andric   }
3800fe6060f1SDimitry Andric   replaceSingleDefInstWithReg(MI, Reg);
3801fe6060f1SDimitry Andric }
3802fe6060f1SDimitry Andric 
3803fe6060f1SDimitry Andric bool CombinerHelper::matchExtractAllEltsFromBuildVector(
3804fe6060f1SDimitry Andric     MachineInstr &MI,
3805fe6060f1SDimitry Andric     SmallVectorImpl<std::pair<Register, MachineInstr *>> &SrcDstPairs) {
3806fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR);
3807fe6060f1SDimitry Andric   // This combine tries to find build_vector's which have every source element
3808fe6060f1SDimitry Andric   // extracted using G_EXTRACT_VECTOR_ELT. This can happen when transforms like
3809fe6060f1SDimitry Andric   // the masked load scalarization is run late in the pipeline. There's already
3810fe6060f1SDimitry Andric   // a combine for a similar pattern starting from the extract, but that
3811fe6060f1SDimitry Andric   // doesn't attempt to do it if there are multiple uses of the build_vector,
3812fe6060f1SDimitry Andric   // which in this case is true. Starting the combine from the build_vector
3813fe6060f1SDimitry Andric   // feels more natural than trying to find sibling nodes of extracts.
3814fe6060f1SDimitry Andric   // E.g.
3815fe6060f1SDimitry Andric   //  %vec(<4 x s32>) = G_BUILD_VECTOR %s1(s32), %s2, %s3, %s4
3816fe6060f1SDimitry Andric   //  %ext1 = G_EXTRACT_VECTOR_ELT %vec, 0
3817fe6060f1SDimitry Andric   //  %ext2 = G_EXTRACT_VECTOR_ELT %vec, 1
3818fe6060f1SDimitry Andric   //  %ext3 = G_EXTRACT_VECTOR_ELT %vec, 2
3819fe6060f1SDimitry Andric   //  %ext4 = G_EXTRACT_VECTOR_ELT %vec, 3
3820fe6060f1SDimitry Andric   // ==>
3821fe6060f1SDimitry Andric   // replace ext{1,2,3,4} with %s{1,2,3,4}
3822fe6060f1SDimitry Andric 
3823fe6060f1SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
3824fe6060f1SDimitry Andric   LLT DstTy = MRI.getType(DstReg);
3825fe6060f1SDimitry Andric   unsigned NumElts = DstTy.getNumElements();
3826fe6060f1SDimitry Andric 
3827fe6060f1SDimitry Andric   SmallBitVector ExtractedElts(NumElts);
38284824e7fdSDimitry Andric   for (MachineInstr &II : MRI.use_nodbg_instructions(DstReg)) {
3829fe6060f1SDimitry Andric     if (II.getOpcode() != TargetOpcode::G_EXTRACT_VECTOR_ELT)
3830fe6060f1SDimitry Andric       return false;
3831349cc55cSDimitry Andric     auto Cst = getIConstantVRegVal(II.getOperand(2).getReg(), MRI);
3832fe6060f1SDimitry Andric     if (!Cst)
3833fe6060f1SDimitry Andric       return false;
383481ad6265SDimitry Andric     unsigned Idx = Cst->getZExtValue();
3835fe6060f1SDimitry Andric     if (Idx >= NumElts)
3836fe6060f1SDimitry Andric       return false; // Out of range.
3837fe6060f1SDimitry Andric     ExtractedElts.set(Idx);
3838fe6060f1SDimitry Andric     SrcDstPairs.emplace_back(
3839fe6060f1SDimitry Andric         std::make_pair(MI.getOperand(Idx + 1).getReg(), &II));
3840fe6060f1SDimitry Andric   }
3841fe6060f1SDimitry Andric   // Match if every element was extracted.
3842fe6060f1SDimitry Andric   return ExtractedElts.all();
3843fe6060f1SDimitry Andric }
3844fe6060f1SDimitry Andric 
3845fe6060f1SDimitry Andric void CombinerHelper::applyExtractAllEltsFromBuildVector(
3846fe6060f1SDimitry Andric     MachineInstr &MI,
3847fe6060f1SDimitry Andric     SmallVectorImpl<std::pair<Register, MachineInstr *>> &SrcDstPairs) {
3848fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR);
3849fe6060f1SDimitry Andric   for (auto &Pair : SrcDstPairs) {
3850fe6060f1SDimitry Andric     auto *ExtMI = Pair.second;
3851fe6060f1SDimitry Andric     replaceRegWith(MRI, ExtMI->getOperand(0).getReg(), Pair.first);
3852fe6060f1SDimitry Andric     ExtMI->eraseFromParent();
3853fe6060f1SDimitry Andric   }
3854fe6060f1SDimitry Andric   MI.eraseFromParent();
3855fe6060f1SDimitry Andric }
3856fe6060f1SDimitry Andric 
3857fe6060f1SDimitry Andric void CombinerHelper::applyBuildFn(
3858e8d8bef9SDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
3859e8d8bef9SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
3860e8d8bef9SDimitry Andric   MatchInfo(Builder);
3861e8d8bef9SDimitry Andric   MI.eraseFromParent();
3862fe6060f1SDimitry Andric }
3863fe6060f1SDimitry Andric 
3864fe6060f1SDimitry Andric void CombinerHelper::applyBuildFnNoErase(
3865fe6060f1SDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
3866fe6060f1SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
3867fe6060f1SDimitry Andric   MatchInfo(Builder);
3868fe6060f1SDimitry Andric }
3869fe6060f1SDimitry Andric 
38704824e7fdSDimitry Andric bool CombinerHelper::matchOrShiftToFunnelShift(MachineInstr &MI,
38714824e7fdSDimitry Andric                                                BuildFnTy &MatchInfo) {
38724824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_OR);
38734824e7fdSDimitry Andric 
38744824e7fdSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
38754824e7fdSDimitry Andric   LLT Ty = MRI.getType(Dst);
38764824e7fdSDimitry Andric   unsigned BitWidth = Ty.getScalarSizeInBits();
38774824e7fdSDimitry Andric 
387804eeddc0SDimitry Andric   Register ShlSrc, ShlAmt, LShrSrc, LShrAmt, Amt;
38794824e7fdSDimitry Andric   unsigned FshOpc = 0;
38804824e7fdSDimitry Andric 
388104eeddc0SDimitry Andric   // Match (or (shl ...), (lshr ...)).
388204eeddc0SDimitry Andric   if (!mi_match(Dst, MRI,
38834824e7fdSDimitry Andric                 // m_GOr() handles the commuted version as well.
38844824e7fdSDimitry Andric                 m_GOr(m_GShl(m_Reg(ShlSrc), m_Reg(ShlAmt)),
388504eeddc0SDimitry Andric                       m_GLShr(m_Reg(LShrSrc), m_Reg(LShrAmt)))))
388604eeddc0SDimitry Andric     return false;
388704eeddc0SDimitry Andric 
388804eeddc0SDimitry Andric   // Given constants C0 and C1 such that C0 + C1 is bit-width:
388904eeddc0SDimitry Andric   // (or (shl x, C0), (lshr y, C1)) -> (fshl x, y, C0) or (fshr x, y, C1)
389004eeddc0SDimitry Andric   int64_t CstShlAmt, CstLShrAmt;
389181ad6265SDimitry Andric   if (mi_match(ShlAmt, MRI, m_ICstOrSplat(CstShlAmt)) &&
389281ad6265SDimitry Andric       mi_match(LShrAmt, MRI, m_ICstOrSplat(CstLShrAmt)) &&
389304eeddc0SDimitry Andric       CstShlAmt + CstLShrAmt == BitWidth) {
389404eeddc0SDimitry Andric     FshOpc = TargetOpcode::G_FSHR;
389504eeddc0SDimitry Andric     Amt = LShrAmt;
389604eeddc0SDimitry Andric 
389704eeddc0SDimitry Andric   } else if (mi_match(LShrAmt, MRI,
389804eeddc0SDimitry Andric                       m_GSub(m_SpecificICstOrSplat(BitWidth), m_Reg(Amt))) &&
389904eeddc0SDimitry Andric              ShlAmt == Amt) {
390004eeddc0SDimitry Andric     // (or (shl x, amt), (lshr y, (sub bw, amt))) -> (fshl x, y, amt)
39014824e7fdSDimitry Andric     FshOpc = TargetOpcode::G_FSHL;
39024824e7fdSDimitry Andric 
390304eeddc0SDimitry Andric   } else if (mi_match(ShlAmt, MRI,
390404eeddc0SDimitry Andric                       m_GSub(m_SpecificICstOrSplat(BitWidth), m_Reg(Amt))) &&
390504eeddc0SDimitry Andric              LShrAmt == Amt) {
390604eeddc0SDimitry Andric     // (or (shl x, (sub bw, amt)), (lshr y, amt)) -> (fshr x, y, amt)
39074824e7fdSDimitry Andric     FshOpc = TargetOpcode::G_FSHR;
39084824e7fdSDimitry Andric 
39094824e7fdSDimitry Andric   } else {
39104824e7fdSDimitry Andric     return false;
39114824e7fdSDimitry Andric   }
39124824e7fdSDimitry Andric 
391304eeddc0SDimitry Andric   LLT AmtTy = MRI.getType(Amt);
39144824e7fdSDimitry Andric   if (!isLegalOrBeforeLegalizer({FshOpc, {Ty, AmtTy}}))
39154824e7fdSDimitry Andric     return false;
39164824e7fdSDimitry Andric 
39174824e7fdSDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
391804eeddc0SDimitry Andric     B.buildInstr(FshOpc, {Dst}, {ShlSrc, LShrSrc, Amt});
39194824e7fdSDimitry Andric   };
39204824e7fdSDimitry Andric   return true;
39214824e7fdSDimitry Andric }
39224824e7fdSDimitry Andric 
3923fe6060f1SDimitry Andric /// Match an FSHL or FSHR that can be combined to a ROTR or ROTL rotate.
3924fe6060f1SDimitry Andric bool CombinerHelper::matchFunnelShiftToRotate(MachineInstr &MI) {
3925fe6060f1SDimitry Andric   unsigned Opc = MI.getOpcode();
3926fe6060f1SDimitry Andric   assert(Opc == TargetOpcode::G_FSHL || Opc == TargetOpcode::G_FSHR);
3927fe6060f1SDimitry Andric   Register X = MI.getOperand(1).getReg();
3928fe6060f1SDimitry Andric   Register Y = MI.getOperand(2).getReg();
3929fe6060f1SDimitry Andric   if (X != Y)
3930fe6060f1SDimitry Andric     return false;
3931fe6060f1SDimitry Andric   unsigned RotateOpc =
3932fe6060f1SDimitry Andric       Opc == TargetOpcode::G_FSHL ? TargetOpcode::G_ROTL : TargetOpcode::G_ROTR;
3933fe6060f1SDimitry Andric   return isLegalOrBeforeLegalizer({RotateOpc, {MRI.getType(X), MRI.getType(Y)}});
3934fe6060f1SDimitry Andric }
3935fe6060f1SDimitry Andric 
3936fe6060f1SDimitry Andric void CombinerHelper::applyFunnelShiftToRotate(MachineInstr &MI) {
3937fe6060f1SDimitry Andric   unsigned Opc = MI.getOpcode();
3938fe6060f1SDimitry Andric   assert(Opc == TargetOpcode::G_FSHL || Opc == TargetOpcode::G_FSHR);
3939fe6060f1SDimitry Andric   bool IsFSHL = Opc == TargetOpcode::G_FSHL;
3940fe6060f1SDimitry Andric   Observer.changingInstr(MI);
3941fe6060f1SDimitry Andric   MI.setDesc(Builder.getTII().get(IsFSHL ? TargetOpcode::G_ROTL
3942fe6060f1SDimitry Andric                                          : TargetOpcode::G_ROTR));
394381ad6265SDimitry Andric   MI.removeOperand(2);
3944fe6060f1SDimitry Andric   Observer.changedInstr(MI);
3945fe6060f1SDimitry Andric }
3946fe6060f1SDimitry Andric 
3947fe6060f1SDimitry Andric // Fold (rot x, c) -> (rot x, c % BitSize)
3948fe6060f1SDimitry Andric bool CombinerHelper::matchRotateOutOfRange(MachineInstr &MI) {
3949fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ROTL ||
3950fe6060f1SDimitry Andric          MI.getOpcode() == TargetOpcode::G_ROTR);
3951fe6060f1SDimitry Andric   unsigned Bitsize =
3952fe6060f1SDimitry Andric       MRI.getType(MI.getOperand(0).getReg()).getScalarSizeInBits();
3953fe6060f1SDimitry Andric   Register AmtReg = MI.getOperand(2).getReg();
3954fe6060f1SDimitry Andric   bool OutOfRange = false;
3955fe6060f1SDimitry Andric   auto MatchOutOfRange = [Bitsize, &OutOfRange](const Constant *C) {
3956fe6060f1SDimitry Andric     if (auto *CI = dyn_cast<ConstantInt>(C))
3957fe6060f1SDimitry Andric       OutOfRange |= CI->getValue().uge(Bitsize);
3958fe6060f1SDimitry Andric     return true;
3959fe6060f1SDimitry Andric   };
3960fe6060f1SDimitry Andric   return matchUnaryPredicate(MRI, AmtReg, MatchOutOfRange) && OutOfRange;
3961fe6060f1SDimitry Andric }
3962fe6060f1SDimitry Andric 
3963fe6060f1SDimitry Andric void CombinerHelper::applyRotateOutOfRange(MachineInstr &MI) {
3964fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ROTL ||
3965fe6060f1SDimitry Andric          MI.getOpcode() == TargetOpcode::G_ROTR);
3966fe6060f1SDimitry Andric   unsigned Bitsize =
3967fe6060f1SDimitry Andric       MRI.getType(MI.getOperand(0).getReg()).getScalarSizeInBits();
3968fe6060f1SDimitry Andric   Builder.setInstrAndDebugLoc(MI);
3969fe6060f1SDimitry Andric   Register Amt = MI.getOperand(2).getReg();
3970fe6060f1SDimitry Andric   LLT AmtTy = MRI.getType(Amt);
3971fe6060f1SDimitry Andric   auto Bits = Builder.buildConstant(AmtTy, Bitsize);
3972fe6060f1SDimitry Andric   Amt = Builder.buildURem(AmtTy, MI.getOperand(2).getReg(), Bits).getReg(0);
3973fe6060f1SDimitry Andric   Observer.changingInstr(MI);
3974fe6060f1SDimitry Andric   MI.getOperand(2).setReg(Amt);
3975fe6060f1SDimitry Andric   Observer.changedInstr(MI);
3976fe6060f1SDimitry Andric }
3977fe6060f1SDimitry Andric 
3978fe6060f1SDimitry Andric bool CombinerHelper::matchICmpToTrueFalseKnownBits(MachineInstr &MI,
3979fe6060f1SDimitry Andric                                                    int64_t &MatchInfo) {
3980fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ICMP);
3981fe6060f1SDimitry Andric   auto Pred = static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
3982fe6060f1SDimitry Andric   auto KnownLHS = KB->getKnownBits(MI.getOperand(2).getReg());
3983fe6060f1SDimitry Andric   auto KnownRHS = KB->getKnownBits(MI.getOperand(3).getReg());
3984bdd1243dSDimitry Andric   std::optional<bool> KnownVal;
3985fe6060f1SDimitry Andric   switch (Pred) {
3986fe6060f1SDimitry Andric   default:
3987fe6060f1SDimitry Andric     llvm_unreachable("Unexpected G_ICMP predicate?");
3988fe6060f1SDimitry Andric   case CmpInst::ICMP_EQ:
3989fe6060f1SDimitry Andric     KnownVal = KnownBits::eq(KnownLHS, KnownRHS);
3990fe6060f1SDimitry Andric     break;
3991fe6060f1SDimitry Andric   case CmpInst::ICMP_NE:
3992fe6060f1SDimitry Andric     KnownVal = KnownBits::ne(KnownLHS, KnownRHS);
3993fe6060f1SDimitry Andric     break;
3994fe6060f1SDimitry Andric   case CmpInst::ICMP_SGE:
3995fe6060f1SDimitry Andric     KnownVal = KnownBits::sge(KnownLHS, KnownRHS);
3996fe6060f1SDimitry Andric     break;
3997fe6060f1SDimitry Andric   case CmpInst::ICMP_SGT:
3998fe6060f1SDimitry Andric     KnownVal = KnownBits::sgt(KnownLHS, KnownRHS);
3999fe6060f1SDimitry Andric     break;
4000fe6060f1SDimitry Andric   case CmpInst::ICMP_SLE:
4001fe6060f1SDimitry Andric     KnownVal = KnownBits::sle(KnownLHS, KnownRHS);
4002fe6060f1SDimitry Andric     break;
4003fe6060f1SDimitry Andric   case CmpInst::ICMP_SLT:
4004fe6060f1SDimitry Andric     KnownVal = KnownBits::slt(KnownLHS, KnownRHS);
4005fe6060f1SDimitry Andric     break;
4006fe6060f1SDimitry Andric   case CmpInst::ICMP_UGE:
4007fe6060f1SDimitry Andric     KnownVal = KnownBits::uge(KnownLHS, KnownRHS);
4008fe6060f1SDimitry Andric     break;
4009fe6060f1SDimitry Andric   case CmpInst::ICMP_UGT:
4010fe6060f1SDimitry Andric     KnownVal = KnownBits::ugt(KnownLHS, KnownRHS);
4011fe6060f1SDimitry Andric     break;
4012fe6060f1SDimitry Andric   case CmpInst::ICMP_ULE:
4013fe6060f1SDimitry Andric     KnownVal = KnownBits::ule(KnownLHS, KnownRHS);
4014fe6060f1SDimitry Andric     break;
4015fe6060f1SDimitry Andric   case CmpInst::ICMP_ULT:
4016fe6060f1SDimitry Andric     KnownVal = KnownBits::ult(KnownLHS, KnownRHS);
4017fe6060f1SDimitry Andric     break;
4018fe6060f1SDimitry Andric   }
4019fe6060f1SDimitry Andric   if (!KnownVal)
4020fe6060f1SDimitry Andric     return false;
4021fe6060f1SDimitry Andric   MatchInfo =
4022fe6060f1SDimitry Andric       *KnownVal
4023fe6060f1SDimitry Andric           ? getICmpTrueVal(getTargetLowering(),
4024fe6060f1SDimitry Andric                            /*IsVector = */
4025fe6060f1SDimitry Andric                            MRI.getType(MI.getOperand(0).getReg()).isVector(),
4026fe6060f1SDimitry Andric                            /* IsFP = */ false)
4027fe6060f1SDimitry Andric           : 0;
4028fe6060f1SDimitry Andric   return true;
4029fe6060f1SDimitry Andric }
4030fe6060f1SDimitry Andric 
4031349cc55cSDimitry Andric bool CombinerHelper::matchICmpToLHSKnownBits(
4032349cc55cSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4033349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ICMP);
4034349cc55cSDimitry Andric   // Given:
4035349cc55cSDimitry Andric   //
4036349cc55cSDimitry Andric   // %x = G_WHATEVER (... x is known to be 0 or 1 ...)
4037349cc55cSDimitry Andric   // %cmp = G_ICMP ne %x, 0
4038349cc55cSDimitry Andric   //
4039349cc55cSDimitry Andric   // Or:
4040349cc55cSDimitry Andric   //
4041349cc55cSDimitry Andric   // %x = G_WHATEVER (... x is known to be 0 or 1 ...)
4042349cc55cSDimitry Andric   // %cmp = G_ICMP eq %x, 1
4043349cc55cSDimitry Andric   //
4044349cc55cSDimitry Andric   // We can replace %cmp with %x assuming true is 1 on the target.
4045349cc55cSDimitry Andric   auto Pred = static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
4046349cc55cSDimitry Andric   if (!CmpInst::isEquality(Pred))
4047349cc55cSDimitry Andric     return false;
4048349cc55cSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
4049349cc55cSDimitry Andric   LLT DstTy = MRI.getType(Dst);
4050349cc55cSDimitry Andric   if (getICmpTrueVal(getTargetLowering(), DstTy.isVector(),
4051349cc55cSDimitry Andric                      /* IsFP = */ false) != 1)
4052349cc55cSDimitry Andric     return false;
4053349cc55cSDimitry Andric   int64_t OneOrZero = Pred == CmpInst::ICMP_EQ;
4054349cc55cSDimitry Andric   if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICst(OneOrZero)))
4055349cc55cSDimitry Andric     return false;
4056349cc55cSDimitry Andric   Register LHS = MI.getOperand(2).getReg();
4057349cc55cSDimitry Andric   auto KnownLHS = KB->getKnownBits(LHS);
4058349cc55cSDimitry Andric   if (KnownLHS.getMinValue() != 0 || KnownLHS.getMaxValue() != 1)
4059349cc55cSDimitry Andric     return false;
4060349cc55cSDimitry Andric   // Make sure replacing Dst with the LHS is a legal operation.
4061349cc55cSDimitry Andric   LLT LHSTy = MRI.getType(LHS);
4062349cc55cSDimitry Andric   unsigned LHSSize = LHSTy.getSizeInBits();
4063349cc55cSDimitry Andric   unsigned DstSize = DstTy.getSizeInBits();
4064349cc55cSDimitry Andric   unsigned Op = TargetOpcode::COPY;
4065349cc55cSDimitry Andric   if (DstSize != LHSSize)
4066349cc55cSDimitry Andric     Op = DstSize < LHSSize ? TargetOpcode::G_TRUNC : TargetOpcode::G_ZEXT;
4067349cc55cSDimitry Andric   if (!isLegalOrBeforeLegalizer({Op, {DstTy, LHSTy}}))
4068349cc55cSDimitry Andric     return false;
4069349cc55cSDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) { B.buildInstr(Op, {Dst}, {LHS}); };
4070349cc55cSDimitry Andric   return true;
4071349cc55cSDimitry Andric }
4072349cc55cSDimitry Andric 
4073349cc55cSDimitry Andric // Replace (and (or x, c1), c2) with (and x, c2) iff c1 & c2 == 0
4074349cc55cSDimitry Andric bool CombinerHelper::matchAndOrDisjointMask(
4075349cc55cSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4076349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_AND);
4077349cc55cSDimitry Andric 
4078349cc55cSDimitry Andric   // Ignore vector types to simplify matching the two constants.
4079349cc55cSDimitry Andric   // TODO: do this for vectors and scalars via a demanded bits analysis.
4080349cc55cSDimitry Andric   LLT Ty = MRI.getType(MI.getOperand(0).getReg());
4081349cc55cSDimitry Andric   if (Ty.isVector())
4082349cc55cSDimitry Andric     return false;
4083349cc55cSDimitry Andric 
4084349cc55cSDimitry Andric   Register Src;
408581ad6265SDimitry Andric   Register AndMaskReg;
408681ad6265SDimitry Andric   int64_t AndMaskBits;
408781ad6265SDimitry Andric   int64_t OrMaskBits;
4088349cc55cSDimitry Andric   if (!mi_match(MI, MRI,
408981ad6265SDimitry Andric                 m_GAnd(m_GOr(m_Reg(Src), m_ICst(OrMaskBits)),
409081ad6265SDimitry Andric                        m_all_of(m_ICst(AndMaskBits), m_Reg(AndMaskReg)))))
4091349cc55cSDimitry Andric     return false;
4092349cc55cSDimitry Andric 
409381ad6265SDimitry Andric   // Check if OrMask could turn on any bits in Src.
409481ad6265SDimitry Andric   if (AndMaskBits & OrMaskBits)
4095349cc55cSDimitry Andric     return false;
4096349cc55cSDimitry Andric 
4097349cc55cSDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4098349cc55cSDimitry Andric     Observer.changingInstr(MI);
409981ad6265SDimitry Andric     // Canonicalize the result to have the constant on the RHS.
410081ad6265SDimitry Andric     if (MI.getOperand(1).getReg() == AndMaskReg)
410181ad6265SDimitry Andric       MI.getOperand(2).setReg(AndMaskReg);
4102349cc55cSDimitry Andric     MI.getOperand(1).setReg(Src);
4103349cc55cSDimitry Andric     Observer.changedInstr(MI);
4104349cc55cSDimitry Andric   };
4105349cc55cSDimitry Andric   return true;
4106349cc55cSDimitry Andric }
4107349cc55cSDimitry Andric 
4108fe6060f1SDimitry Andric /// Form a G_SBFX from a G_SEXT_INREG fed by a right shift.
4109fe6060f1SDimitry Andric bool CombinerHelper::matchBitfieldExtractFromSExtInReg(
4110fe6060f1SDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4111fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
4112fe6060f1SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
4113fe6060f1SDimitry Andric   Register Src = MI.getOperand(1).getReg();
4114fe6060f1SDimitry Andric   LLT Ty = MRI.getType(Src);
4115fe6060f1SDimitry Andric   LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4116fe6060f1SDimitry Andric   if (!LI || !LI->isLegalOrCustom({TargetOpcode::G_SBFX, {Ty, ExtractTy}}))
4117fe6060f1SDimitry Andric     return false;
4118fe6060f1SDimitry Andric   int64_t Width = MI.getOperand(2).getImm();
4119fe6060f1SDimitry Andric   Register ShiftSrc;
4120fe6060f1SDimitry Andric   int64_t ShiftImm;
4121fe6060f1SDimitry Andric   if (!mi_match(
4122fe6060f1SDimitry Andric           Src, MRI,
4123fe6060f1SDimitry Andric           m_OneNonDBGUse(m_any_of(m_GAShr(m_Reg(ShiftSrc), m_ICst(ShiftImm)),
4124fe6060f1SDimitry Andric                                   m_GLShr(m_Reg(ShiftSrc), m_ICst(ShiftImm))))))
4125fe6060f1SDimitry Andric     return false;
4126fe6060f1SDimitry Andric   if (ShiftImm < 0 || ShiftImm + Width > Ty.getScalarSizeInBits())
4127fe6060f1SDimitry Andric     return false;
4128fe6060f1SDimitry Andric 
4129fe6060f1SDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
4130fe6060f1SDimitry Andric     auto Cst1 = B.buildConstant(ExtractTy, ShiftImm);
4131fe6060f1SDimitry Andric     auto Cst2 = B.buildConstant(ExtractTy, Width);
4132fe6060f1SDimitry Andric     B.buildSbfx(Dst, ShiftSrc, Cst1, Cst2);
4133fe6060f1SDimitry Andric   };
4134fe6060f1SDimitry Andric   return true;
4135fe6060f1SDimitry Andric }
4136fe6060f1SDimitry Andric 
4137fe6060f1SDimitry Andric /// Form a G_UBFX from "(a srl b) & mask", where b and mask are constants.
4138fe6060f1SDimitry Andric bool CombinerHelper::matchBitfieldExtractFromAnd(
4139fe6060f1SDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4140fe6060f1SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_AND);
4141fe6060f1SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
4142fe6060f1SDimitry Andric   LLT Ty = MRI.getType(Dst);
414304eeddc0SDimitry Andric   LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
414404eeddc0SDimitry Andric   if (!getTargetLowering().isConstantUnsignedBitfieldExtractLegal(
414504eeddc0SDimitry Andric           TargetOpcode::G_UBFX, Ty, ExtractTy))
4146fe6060f1SDimitry Andric     return false;
4147fe6060f1SDimitry Andric 
4148fe6060f1SDimitry Andric   int64_t AndImm, LSBImm;
4149fe6060f1SDimitry Andric   Register ShiftSrc;
4150fe6060f1SDimitry Andric   const unsigned Size = Ty.getScalarSizeInBits();
4151fe6060f1SDimitry Andric   if (!mi_match(MI.getOperand(0).getReg(), MRI,
4152fe6060f1SDimitry Andric                 m_GAnd(m_OneNonDBGUse(m_GLShr(m_Reg(ShiftSrc), m_ICst(LSBImm))),
4153fe6060f1SDimitry Andric                        m_ICst(AndImm))))
4154fe6060f1SDimitry Andric     return false;
4155fe6060f1SDimitry Andric 
4156fe6060f1SDimitry Andric   // The mask is a mask of the low bits iff imm & (imm+1) == 0.
4157fe6060f1SDimitry Andric   auto MaybeMask = static_cast<uint64_t>(AndImm);
4158fe6060f1SDimitry Andric   if (MaybeMask & (MaybeMask + 1))
4159fe6060f1SDimitry Andric     return false;
4160fe6060f1SDimitry Andric 
4161fe6060f1SDimitry Andric   // LSB must fit within the register.
4162fe6060f1SDimitry Andric   if (static_cast<uint64_t>(LSBImm) >= Size)
4163fe6060f1SDimitry Andric     return false;
4164fe6060f1SDimitry Andric 
4165*06c3fb27SDimitry Andric   uint64_t Width = APInt(Size, AndImm).countr_one();
4166fe6060f1SDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
4167fe6060f1SDimitry Andric     auto WidthCst = B.buildConstant(ExtractTy, Width);
4168fe6060f1SDimitry Andric     auto LSBCst = B.buildConstant(ExtractTy, LSBImm);
4169fe6060f1SDimitry Andric     B.buildInstr(TargetOpcode::G_UBFX, {Dst}, {ShiftSrc, LSBCst, WidthCst});
4170fe6060f1SDimitry Andric   };
4171fe6060f1SDimitry Andric   return true;
4172fe6060f1SDimitry Andric }
4173fe6060f1SDimitry Andric 
4174349cc55cSDimitry Andric bool CombinerHelper::matchBitfieldExtractFromShr(
4175349cc55cSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4176349cc55cSDimitry Andric   const unsigned Opcode = MI.getOpcode();
4177349cc55cSDimitry Andric   assert(Opcode == TargetOpcode::G_ASHR || Opcode == TargetOpcode::G_LSHR);
4178349cc55cSDimitry Andric 
4179349cc55cSDimitry Andric   const Register Dst = MI.getOperand(0).getReg();
4180349cc55cSDimitry Andric 
4181349cc55cSDimitry Andric   const unsigned ExtrOpcode = Opcode == TargetOpcode::G_ASHR
4182349cc55cSDimitry Andric                                   ? TargetOpcode::G_SBFX
4183349cc55cSDimitry Andric                                   : TargetOpcode::G_UBFX;
4184349cc55cSDimitry Andric 
4185349cc55cSDimitry Andric   // Check if the type we would use for the extract is legal
4186349cc55cSDimitry Andric   LLT Ty = MRI.getType(Dst);
4187349cc55cSDimitry Andric   LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4188349cc55cSDimitry Andric   if (!LI || !LI->isLegalOrCustom({ExtrOpcode, {Ty, ExtractTy}}))
4189349cc55cSDimitry Andric     return false;
4190349cc55cSDimitry Andric 
4191349cc55cSDimitry Andric   Register ShlSrc;
4192349cc55cSDimitry Andric   int64_t ShrAmt;
4193349cc55cSDimitry Andric   int64_t ShlAmt;
4194349cc55cSDimitry Andric   const unsigned Size = Ty.getScalarSizeInBits();
4195349cc55cSDimitry Andric 
4196349cc55cSDimitry Andric   // Try to match shr (shl x, c1), c2
4197349cc55cSDimitry Andric   if (!mi_match(Dst, MRI,
4198349cc55cSDimitry Andric                 m_BinOp(Opcode,
4199349cc55cSDimitry Andric                         m_OneNonDBGUse(m_GShl(m_Reg(ShlSrc), m_ICst(ShlAmt))),
4200349cc55cSDimitry Andric                         m_ICst(ShrAmt))))
4201349cc55cSDimitry Andric     return false;
4202349cc55cSDimitry Andric 
4203349cc55cSDimitry Andric   // Make sure that the shift sizes can fit a bitfield extract
4204349cc55cSDimitry Andric   if (ShlAmt < 0 || ShlAmt > ShrAmt || ShrAmt >= Size)
4205349cc55cSDimitry Andric     return false;
4206349cc55cSDimitry Andric 
4207349cc55cSDimitry Andric   // Skip this combine if the G_SEXT_INREG combine could handle it
4208349cc55cSDimitry Andric   if (Opcode == TargetOpcode::G_ASHR && ShlAmt == ShrAmt)
4209349cc55cSDimitry Andric     return false;
4210349cc55cSDimitry Andric 
4211349cc55cSDimitry Andric   // Calculate start position and width of the extract
4212349cc55cSDimitry Andric   const int64_t Pos = ShrAmt - ShlAmt;
4213349cc55cSDimitry Andric   const int64_t Width = Size - ShrAmt;
4214349cc55cSDimitry Andric 
4215349cc55cSDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
4216349cc55cSDimitry Andric     auto WidthCst = B.buildConstant(ExtractTy, Width);
4217349cc55cSDimitry Andric     auto PosCst = B.buildConstant(ExtractTy, Pos);
4218349cc55cSDimitry Andric     B.buildInstr(ExtrOpcode, {Dst}, {ShlSrc, PosCst, WidthCst});
4219349cc55cSDimitry Andric   };
4220349cc55cSDimitry Andric   return true;
4221349cc55cSDimitry Andric }
4222349cc55cSDimitry Andric 
4223349cc55cSDimitry Andric bool CombinerHelper::matchBitfieldExtractFromShrAnd(
4224349cc55cSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4225349cc55cSDimitry Andric   const unsigned Opcode = MI.getOpcode();
4226349cc55cSDimitry Andric   assert(Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_ASHR);
4227349cc55cSDimitry Andric 
4228349cc55cSDimitry Andric   const Register Dst = MI.getOperand(0).getReg();
4229349cc55cSDimitry Andric   LLT Ty = MRI.getType(Dst);
423004eeddc0SDimitry Andric   LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
423104eeddc0SDimitry Andric   if (!getTargetLowering().isConstantUnsignedBitfieldExtractLegal(
423204eeddc0SDimitry Andric           TargetOpcode::G_UBFX, Ty, ExtractTy))
4233349cc55cSDimitry Andric     return false;
4234349cc55cSDimitry Andric 
4235349cc55cSDimitry Andric   // Try to match shr (and x, c1), c2
4236349cc55cSDimitry Andric   Register AndSrc;
4237349cc55cSDimitry Andric   int64_t ShrAmt;
4238349cc55cSDimitry Andric   int64_t SMask;
4239349cc55cSDimitry Andric   if (!mi_match(Dst, MRI,
4240349cc55cSDimitry Andric                 m_BinOp(Opcode,
4241349cc55cSDimitry Andric                         m_OneNonDBGUse(m_GAnd(m_Reg(AndSrc), m_ICst(SMask))),
4242349cc55cSDimitry Andric                         m_ICst(ShrAmt))))
4243349cc55cSDimitry Andric     return false;
4244349cc55cSDimitry Andric 
4245349cc55cSDimitry Andric   const unsigned Size = Ty.getScalarSizeInBits();
4246349cc55cSDimitry Andric   if (ShrAmt < 0 || ShrAmt >= Size)
4247349cc55cSDimitry Andric     return false;
4248349cc55cSDimitry Andric 
424981ad6265SDimitry Andric   // If the shift subsumes the mask, emit the 0 directly.
425081ad6265SDimitry Andric   if (0 == (SMask >> ShrAmt)) {
425181ad6265SDimitry Andric     MatchInfo = [=](MachineIRBuilder &B) {
425281ad6265SDimitry Andric       B.buildConstant(Dst, 0);
425381ad6265SDimitry Andric     };
425481ad6265SDimitry Andric     return true;
425581ad6265SDimitry Andric   }
425681ad6265SDimitry Andric 
4257349cc55cSDimitry Andric   // Check that ubfx can do the extraction, with no holes in the mask.
4258349cc55cSDimitry Andric   uint64_t UMask = SMask;
4259349cc55cSDimitry Andric   UMask |= maskTrailingOnes<uint64_t>(ShrAmt);
4260349cc55cSDimitry Andric   UMask &= maskTrailingOnes<uint64_t>(Size);
4261349cc55cSDimitry Andric   if (!isMask_64(UMask))
4262349cc55cSDimitry Andric     return false;
4263349cc55cSDimitry Andric 
4264349cc55cSDimitry Andric   // Calculate start position and width of the extract.
4265349cc55cSDimitry Andric   const int64_t Pos = ShrAmt;
4266*06c3fb27SDimitry Andric   const int64_t Width = llvm::countr_one(UMask) - ShrAmt;
4267349cc55cSDimitry Andric 
4268349cc55cSDimitry Andric   // It's preferable to keep the shift, rather than form G_SBFX.
4269349cc55cSDimitry Andric   // TODO: remove the G_AND via demanded bits analysis.
4270349cc55cSDimitry Andric   if (Opcode == TargetOpcode::G_ASHR && Width + ShrAmt == Size)
4271349cc55cSDimitry Andric     return false;
4272349cc55cSDimitry Andric 
4273349cc55cSDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
427404eeddc0SDimitry Andric     auto WidthCst = B.buildConstant(ExtractTy, Width);
427504eeddc0SDimitry Andric     auto PosCst = B.buildConstant(ExtractTy, Pos);
4276349cc55cSDimitry Andric     B.buildInstr(TargetOpcode::G_UBFX, {Dst}, {AndSrc, PosCst, WidthCst});
4277349cc55cSDimitry Andric   };
4278349cc55cSDimitry Andric   return true;
4279349cc55cSDimitry Andric }
4280349cc55cSDimitry Andric 
4281fe6060f1SDimitry Andric bool CombinerHelper::reassociationCanBreakAddressingModePattern(
4282fe6060f1SDimitry Andric     MachineInstr &PtrAdd) {
4283fe6060f1SDimitry Andric   assert(PtrAdd.getOpcode() == TargetOpcode::G_PTR_ADD);
4284fe6060f1SDimitry Andric 
4285fe6060f1SDimitry Andric   Register Src1Reg = PtrAdd.getOperand(1).getReg();
4286fe6060f1SDimitry Andric   MachineInstr *Src1Def = getOpcodeDef(TargetOpcode::G_PTR_ADD, Src1Reg, MRI);
4287fe6060f1SDimitry Andric   if (!Src1Def)
4288fe6060f1SDimitry Andric     return false;
4289fe6060f1SDimitry Andric 
4290fe6060f1SDimitry Andric   Register Src2Reg = PtrAdd.getOperand(2).getReg();
4291fe6060f1SDimitry Andric 
4292fe6060f1SDimitry Andric   if (MRI.hasOneNonDBGUse(Src1Reg))
4293fe6060f1SDimitry Andric     return false;
4294fe6060f1SDimitry Andric 
4295349cc55cSDimitry Andric   auto C1 = getIConstantVRegVal(Src1Def->getOperand(2).getReg(), MRI);
4296fe6060f1SDimitry Andric   if (!C1)
4297fe6060f1SDimitry Andric     return false;
4298349cc55cSDimitry Andric   auto C2 = getIConstantVRegVal(Src2Reg, MRI);
4299fe6060f1SDimitry Andric   if (!C2)
4300fe6060f1SDimitry Andric     return false;
4301fe6060f1SDimitry Andric 
4302fe6060f1SDimitry Andric   const APInt &C1APIntVal = *C1;
4303fe6060f1SDimitry Andric   const APInt &C2APIntVal = *C2;
4304fe6060f1SDimitry Andric   const int64_t CombinedValue = (C1APIntVal + C2APIntVal).getSExtValue();
4305fe6060f1SDimitry Andric 
4306fe6060f1SDimitry Andric   for (auto &UseMI : MRI.use_nodbg_instructions(Src1Reg)) {
4307fe6060f1SDimitry Andric     // This combine may end up running before ptrtoint/inttoptr combines
4308fe6060f1SDimitry Andric     // manage to eliminate redundant conversions, so try to look through them.
4309fe6060f1SDimitry Andric     MachineInstr *ConvUseMI = &UseMI;
4310fe6060f1SDimitry Andric     unsigned ConvUseOpc = ConvUseMI->getOpcode();
4311fe6060f1SDimitry Andric     while (ConvUseOpc == TargetOpcode::G_INTTOPTR ||
4312fe6060f1SDimitry Andric            ConvUseOpc == TargetOpcode::G_PTRTOINT) {
4313fe6060f1SDimitry Andric       Register DefReg = ConvUseMI->getOperand(0).getReg();
4314fe6060f1SDimitry Andric       if (!MRI.hasOneNonDBGUse(DefReg))
4315fe6060f1SDimitry Andric         break;
4316fe6060f1SDimitry Andric       ConvUseMI = &*MRI.use_instr_nodbg_begin(DefReg);
4317fe6060f1SDimitry Andric       ConvUseOpc = ConvUseMI->getOpcode();
4318fe6060f1SDimitry Andric     }
4319fe6060f1SDimitry Andric     auto LoadStore = ConvUseOpc == TargetOpcode::G_LOAD ||
4320fe6060f1SDimitry Andric                      ConvUseOpc == TargetOpcode::G_STORE;
4321fe6060f1SDimitry Andric     if (!LoadStore)
4322fe6060f1SDimitry Andric       continue;
4323fe6060f1SDimitry Andric     // Is x[offset2] already not a legal addressing mode? If so then
4324fe6060f1SDimitry Andric     // reassociating the constants breaks nothing (we test offset2 because
4325fe6060f1SDimitry Andric     // that's the one we hope to fold into the load or store).
4326fe6060f1SDimitry Andric     TargetLoweringBase::AddrMode AM;
4327fe6060f1SDimitry Andric     AM.HasBaseReg = true;
4328fe6060f1SDimitry Andric     AM.BaseOffs = C2APIntVal.getSExtValue();
4329fe6060f1SDimitry Andric     unsigned AS =
4330fe6060f1SDimitry Andric         MRI.getType(ConvUseMI->getOperand(1).getReg()).getAddressSpace();
4331fe6060f1SDimitry Andric     Type *AccessTy =
4332fe6060f1SDimitry Andric         getTypeForLLT(MRI.getType(ConvUseMI->getOperand(0).getReg()),
4333fe6060f1SDimitry Andric                       PtrAdd.getMF()->getFunction().getContext());
4334fe6060f1SDimitry Andric     const auto &TLI = *PtrAdd.getMF()->getSubtarget().getTargetLowering();
4335fe6060f1SDimitry Andric     if (!TLI.isLegalAddressingMode(PtrAdd.getMF()->getDataLayout(), AM,
4336fe6060f1SDimitry Andric                                    AccessTy, AS))
4337fe6060f1SDimitry Andric       continue;
4338fe6060f1SDimitry Andric 
4339fe6060f1SDimitry Andric     // Would x[offset1+offset2] still be a legal addressing mode?
4340fe6060f1SDimitry Andric     AM.BaseOffs = CombinedValue;
4341fe6060f1SDimitry Andric     if (!TLI.isLegalAddressingMode(PtrAdd.getMF()->getDataLayout(), AM,
4342fe6060f1SDimitry Andric                                    AccessTy, AS))
4343fe6060f1SDimitry Andric       return true;
4344fe6060f1SDimitry Andric   }
4345fe6060f1SDimitry Andric 
4346fe6060f1SDimitry Andric   return false;
4347fe6060f1SDimitry Andric }
4348fe6060f1SDimitry Andric 
4349349cc55cSDimitry Andric bool CombinerHelper::matchReassocConstantInnerRHS(GPtrAdd &MI,
4350349cc55cSDimitry Andric                                                   MachineInstr *RHS,
4351349cc55cSDimitry Andric                                                   BuildFnTy &MatchInfo) {
4352fe6060f1SDimitry Andric   // G_PTR_ADD(BASE, G_ADD(X, C)) -> G_PTR_ADD(G_PTR_ADD(BASE, X), C)
4353fe6060f1SDimitry Andric   Register Src1Reg = MI.getOperand(1).getReg();
4354fe6060f1SDimitry Andric   if (RHS->getOpcode() != TargetOpcode::G_ADD)
4355fe6060f1SDimitry Andric     return false;
4356349cc55cSDimitry Andric   auto C2 = getIConstantVRegVal(RHS->getOperand(2).getReg(), MRI);
4357fe6060f1SDimitry Andric   if (!C2)
4358fe6060f1SDimitry Andric     return false;
4359fe6060f1SDimitry Andric 
4360fe6060f1SDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4361fe6060f1SDimitry Andric     LLT PtrTy = MRI.getType(MI.getOperand(0).getReg());
4362fe6060f1SDimitry Andric 
4363fe6060f1SDimitry Andric     auto NewBase =
4364fe6060f1SDimitry Andric         Builder.buildPtrAdd(PtrTy, Src1Reg, RHS->getOperand(1).getReg());
4365fe6060f1SDimitry Andric     Observer.changingInstr(MI);
4366fe6060f1SDimitry Andric     MI.getOperand(1).setReg(NewBase.getReg(0));
4367fe6060f1SDimitry Andric     MI.getOperand(2).setReg(RHS->getOperand(2).getReg());
4368fe6060f1SDimitry Andric     Observer.changedInstr(MI);
4369fe6060f1SDimitry Andric   };
4370349cc55cSDimitry Andric   return !reassociationCanBreakAddressingModePattern(MI);
4371349cc55cSDimitry Andric }
4372349cc55cSDimitry Andric 
4373349cc55cSDimitry Andric bool CombinerHelper::matchReassocConstantInnerLHS(GPtrAdd &MI,
4374349cc55cSDimitry Andric                                                   MachineInstr *LHS,
4375349cc55cSDimitry Andric                                                   MachineInstr *RHS,
4376349cc55cSDimitry Andric                                                   BuildFnTy &MatchInfo) {
4377349cc55cSDimitry Andric   // G_PTR_ADD (G_PTR_ADD X, C), Y) -> (G_PTR_ADD (G_PTR_ADD(X, Y), C)
4378349cc55cSDimitry Andric   // if and only if (G_PTR_ADD X, C) has one use.
4379349cc55cSDimitry Andric   Register LHSBase;
4380bdd1243dSDimitry Andric   std::optional<ValueAndVReg> LHSCstOff;
4381349cc55cSDimitry Andric   if (!mi_match(MI.getBaseReg(), MRI,
4382349cc55cSDimitry Andric                 m_OneNonDBGUse(m_GPtrAdd(m_Reg(LHSBase), m_GCst(LHSCstOff)))))
4383349cc55cSDimitry Andric     return false;
4384349cc55cSDimitry Andric 
4385349cc55cSDimitry Andric   auto *LHSPtrAdd = cast<GPtrAdd>(LHS);
4386349cc55cSDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4387349cc55cSDimitry Andric     // When we change LHSPtrAdd's offset register we might cause it to use a reg
4388349cc55cSDimitry Andric     // before its def. Sink the instruction so the outer PTR_ADD to ensure this
4389349cc55cSDimitry Andric     // doesn't happen.
4390349cc55cSDimitry Andric     LHSPtrAdd->moveBefore(&MI);
4391349cc55cSDimitry Andric     Register RHSReg = MI.getOffsetReg();
4392bdd1243dSDimitry Andric     // set VReg will cause type mismatch if it comes from extend/trunc
4393bdd1243dSDimitry Andric     auto NewCst = B.buildConstant(MRI.getType(RHSReg), LHSCstOff->Value);
4394349cc55cSDimitry Andric     Observer.changingInstr(MI);
4395bdd1243dSDimitry Andric     MI.getOperand(2).setReg(NewCst.getReg(0));
4396349cc55cSDimitry Andric     Observer.changedInstr(MI);
4397349cc55cSDimitry Andric     Observer.changingInstr(*LHSPtrAdd);
4398349cc55cSDimitry Andric     LHSPtrAdd->getOperand(2).setReg(RHSReg);
4399349cc55cSDimitry Andric     Observer.changedInstr(*LHSPtrAdd);
4400349cc55cSDimitry Andric   };
4401349cc55cSDimitry Andric   return !reassociationCanBreakAddressingModePattern(MI);
4402349cc55cSDimitry Andric }
4403349cc55cSDimitry Andric 
4404349cc55cSDimitry Andric bool CombinerHelper::matchReassocFoldConstantsInSubTree(GPtrAdd &MI,
4405349cc55cSDimitry Andric                                                         MachineInstr *LHS,
4406349cc55cSDimitry Andric                                                         MachineInstr *RHS,
4407349cc55cSDimitry Andric                                                         BuildFnTy &MatchInfo) {
4408349cc55cSDimitry Andric   // G_PTR_ADD(G_PTR_ADD(BASE, C1), C2) -> G_PTR_ADD(BASE, C1+C2)
4409349cc55cSDimitry Andric   auto *LHSPtrAdd = dyn_cast<GPtrAdd>(LHS);
4410349cc55cSDimitry Andric   if (!LHSPtrAdd)
4411349cc55cSDimitry Andric     return false;
4412349cc55cSDimitry Andric 
4413349cc55cSDimitry Andric   Register Src2Reg = MI.getOperand(2).getReg();
4414349cc55cSDimitry Andric   Register LHSSrc1 = LHSPtrAdd->getBaseReg();
4415349cc55cSDimitry Andric   Register LHSSrc2 = LHSPtrAdd->getOffsetReg();
4416349cc55cSDimitry Andric   auto C1 = getIConstantVRegVal(LHSSrc2, MRI);
4417fe6060f1SDimitry Andric   if (!C1)
4418fe6060f1SDimitry Andric     return false;
4419349cc55cSDimitry Andric   auto C2 = getIConstantVRegVal(Src2Reg, MRI);
4420fe6060f1SDimitry Andric   if (!C2)
4421fe6060f1SDimitry Andric     return false;
4422fe6060f1SDimitry Andric 
4423fe6060f1SDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4424fe6060f1SDimitry Andric     auto NewCst = B.buildConstant(MRI.getType(Src2Reg), *C1 + *C2);
4425fe6060f1SDimitry Andric     Observer.changingInstr(MI);
4426fe6060f1SDimitry Andric     MI.getOperand(1).setReg(LHSSrc1);
4427fe6060f1SDimitry Andric     MI.getOperand(2).setReg(NewCst.getReg(0));
4428fe6060f1SDimitry Andric     Observer.changedInstr(MI);
4429fe6060f1SDimitry Andric   };
4430fe6060f1SDimitry Andric   return !reassociationCanBreakAddressingModePattern(MI);
4431fe6060f1SDimitry Andric }
4432fe6060f1SDimitry Andric 
4433349cc55cSDimitry Andric bool CombinerHelper::matchReassocPtrAdd(MachineInstr &MI,
4434349cc55cSDimitry Andric                                         BuildFnTy &MatchInfo) {
4435349cc55cSDimitry Andric   auto &PtrAdd = cast<GPtrAdd>(MI);
4436349cc55cSDimitry Andric   // We're trying to match a few pointer computation patterns here for
4437349cc55cSDimitry Andric   // re-association opportunities.
4438349cc55cSDimitry Andric   // 1) Isolating a constant operand to be on the RHS, e.g.:
4439349cc55cSDimitry Andric   // G_PTR_ADD(BASE, G_ADD(X, C)) -> G_PTR_ADD(G_PTR_ADD(BASE, X), C)
4440349cc55cSDimitry Andric   //
4441349cc55cSDimitry Andric   // 2) Folding two constants in each sub-tree as long as such folding
4442349cc55cSDimitry Andric   // doesn't break a legal addressing mode.
4443349cc55cSDimitry Andric   // G_PTR_ADD(G_PTR_ADD(BASE, C1), C2) -> G_PTR_ADD(BASE, C1+C2)
4444349cc55cSDimitry Andric   //
4445349cc55cSDimitry Andric   // 3) Move a constant from the LHS of an inner op to the RHS of the outer.
4446349cc55cSDimitry Andric   // G_PTR_ADD (G_PTR_ADD X, C), Y) -> G_PTR_ADD (G_PTR_ADD(X, Y), C)
4447349cc55cSDimitry Andric   // iif (G_PTR_ADD X, C) has one use.
4448349cc55cSDimitry Andric   MachineInstr *LHS = MRI.getVRegDef(PtrAdd.getBaseReg());
4449349cc55cSDimitry Andric   MachineInstr *RHS = MRI.getVRegDef(PtrAdd.getOffsetReg());
4450349cc55cSDimitry Andric 
4451349cc55cSDimitry Andric   // Try to match example 2.
4452349cc55cSDimitry Andric   if (matchReassocFoldConstantsInSubTree(PtrAdd, LHS, RHS, MatchInfo))
4453349cc55cSDimitry Andric     return true;
4454349cc55cSDimitry Andric 
4455349cc55cSDimitry Andric   // Try to match example 3.
4456349cc55cSDimitry Andric   if (matchReassocConstantInnerLHS(PtrAdd, LHS, RHS, MatchInfo))
4457349cc55cSDimitry Andric     return true;
4458349cc55cSDimitry Andric 
4459349cc55cSDimitry Andric   // Try to match example 1.
4460349cc55cSDimitry Andric   if (matchReassocConstantInnerRHS(PtrAdd, RHS, MatchInfo))
4461349cc55cSDimitry Andric     return true;
4462349cc55cSDimitry Andric 
4463349cc55cSDimitry Andric   return false;
4464349cc55cSDimitry Andric }
4465*06c3fb27SDimitry Andric bool CombinerHelper::tryReassocBinOp(unsigned Opc, Register DstReg,
4466*06c3fb27SDimitry Andric                                      Register OpLHS, Register OpRHS,
4467*06c3fb27SDimitry Andric                                      BuildFnTy &MatchInfo) {
4468*06c3fb27SDimitry Andric   LLT OpRHSTy = MRI.getType(OpRHS);
4469*06c3fb27SDimitry Andric   MachineInstr *OpLHSDef = MRI.getVRegDef(OpLHS);
4470*06c3fb27SDimitry Andric 
4471*06c3fb27SDimitry Andric   if (OpLHSDef->getOpcode() != Opc)
4472*06c3fb27SDimitry Andric     return false;
4473*06c3fb27SDimitry Andric 
4474*06c3fb27SDimitry Andric   MachineInstr *OpRHSDef = MRI.getVRegDef(OpRHS);
4475*06c3fb27SDimitry Andric   Register OpLHSLHS = OpLHSDef->getOperand(1).getReg();
4476*06c3fb27SDimitry Andric   Register OpLHSRHS = OpLHSDef->getOperand(2).getReg();
4477*06c3fb27SDimitry Andric 
4478*06c3fb27SDimitry Andric   // If the inner op is (X op C), pull the constant out so it can be folded with
4479*06c3fb27SDimitry Andric   // other constants in the expression tree. Folding is not guaranteed so we
4480*06c3fb27SDimitry Andric   // might have (C1 op C2). In that case do not pull a constant out because it
4481*06c3fb27SDimitry Andric   // won't help and can lead to infinite loops.
4482*06c3fb27SDimitry Andric   if (isConstantOrConstantSplatVector(*MRI.getVRegDef(OpLHSRHS), MRI) &&
4483*06c3fb27SDimitry Andric       !isConstantOrConstantSplatVector(*MRI.getVRegDef(OpLHSLHS), MRI)) {
4484*06c3fb27SDimitry Andric     if (isConstantOrConstantSplatVector(*OpRHSDef, MRI)) {
4485*06c3fb27SDimitry Andric       // (Opc (Opc X, C1), C2) -> (Opc X, (Opc C1, C2))
4486*06c3fb27SDimitry Andric       MatchInfo = [=](MachineIRBuilder &B) {
4487*06c3fb27SDimitry Andric         auto NewCst = B.buildInstr(Opc, {OpRHSTy}, {OpLHSRHS, OpRHS});
4488*06c3fb27SDimitry Andric         B.buildInstr(Opc, {DstReg}, {OpLHSLHS, NewCst});
4489*06c3fb27SDimitry Andric       };
4490*06c3fb27SDimitry Andric       return true;
4491*06c3fb27SDimitry Andric     }
4492*06c3fb27SDimitry Andric     if (getTargetLowering().isReassocProfitable(MRI, OpLHS, OpRHS)) {
4493*06c3fb27SDimitry Andric       // Reassociate: (op (op x, c1), y) -> (op (op x, y), c1)
4494*06c3fb27SDimitry Andric       //              iff (op x, c1) has one use
4495*06c3fb27SDimitry Andric       MatchInfo = [=](MachineIRBuilder &B) {
4496*06c3fb27SDimitry Andric         auto NewLHSLHS = B.buildInstr(Opc, {OpRHSTy}, {OpLHSLHS, OpRHS});
4497*06c3fb27SDimitry Andric         B.buildInstr(Opc, {DstReg}, {NewLHSLHS, OpLHSRHS});
4498*06c3fb27SDimitry Andric       };
4499*06c3fb27SDimitry Andric       return true;
4500*06c3fb27SDimitry Andric     }
4501*06c3fb27SDimitry Andric   }
4502*06c3fb27SDimitry Andric 
4503*06c3fb27SDimitry Andric   return false;
4504*06c3fb27SDimitry Andric }
4505*06c3fb27SDimitry Andric 
4506*06c3fb27SDimitry Andric bool CombinerHelper::matchReassocCommBinOp(MachineInstr &MI,
4507*06c3fb27SDimitry Andric                                            BuildFnTy &MatchInfo) {
4508*06c3fb27SDimitry Andric   // We don't check if the reassociation will break a legal addressing mode
4509*06c3fb27SDimitry Andric   // here since pointer arithmetic is handled by G_PTR_ADD.
4510*06c3fb27SDimitry Andric   unsigned Opc = MI.getOpcode();
4511*06c3fb27SDimitry Andric   Register DstReg = MI.getOperand(0).getReg();
4512*06c3fb27SDimitry Andric   Register LHSReg = MI.getOperand(1).getReg();
4513*06c3fb27SDimitry Andric   Register RHSReg = MI.getOperand(2).getReg();
4514*06c3fb27SDimitry Andric 
4515*06c3fb27SDimitry Andric   if (tryReassocBinOp(Opc, DstReg, LHSReg, RHSReg, MatchInfo))
4516*06c3fb27SDimitry Andric     return true;
4517*06c3fb27SDimitry Andric   if (tryReassocBinOp(Opc, DstReg, RHSReg, LHSReg, MatchInfo))
4518*06c3fb27SDimitry Andric     return true;
4519*06c3fb27SDimitry Andric   return false;
4520*06c3fb27SDimitry Andric }
4521349cc55cSDimitry Andric 
4522fe6060f1SDimitry Andric bool CombinerHelper::matchConstantFold(MachineInstr &MI, APInt &MatchInfo) {
4523fe6060f1SDimitry Andric   Register Op1 = MI.getOperand(1).getReg();
4524fe6060f1SDimitry Andric   Register Op2 = MI.getOperand(2).getReg();
4525fe6060f1SDimitry Andric   auto MaybeCst = ConstantFoldBinOp(MI.getOpcode(), Op1, Op2, MRI);
4526fe6060f1SDimitry Andric   if (!MaybeCst)
4527fe6060f1SDimitry Andric     return false;
4528fe6060f1SDimitry Andric   MatchInfo = *MaybeCst;
4529e8d8bef9SDimitry Andric   return true;
4530e8d8bef9SDimitry Andric }
4531e8d8bef9SDimitry Andric 
4532349cc55cSDimitry Andric bool CombinerHelper::matchNarrowBinopFeedingAnd(
4533349cc55cSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4534349cc55cSDimitry Andric   // Look for a binop feeding into an AND with a mask:
4535349cc55cSDimitry Andric   //
4536349cc55cSDimitry Andric   // %add = G_ADD %lhs, %rhs
4537349cc55cSDimitry Andric   // %and = G_AND %add, 000...11111111
4538349cc55cSDimitry Andric   //
4539349cc55cSDimitry Andric   // Check if it's possible to perform the binop at a narrower width and zext
4540349cc55cSDimitry Andric   // back to the original width like so:
4541349cc55cSDimitry Andric   //
4542349cc55cSDimitry Andric   // %narrow_lhs = G_TRUNC %lhs
4543349cc55cSDimitry Andric   // %narrow_rhs = G_TRUNC %rhs
4544349cc55cSDimitry Andric   // %narrow_add = G_ADD %narrow_lhs, %narrow_rhs
4545349cc55cSDimitry Andric   // %new_add = G_ZEXT %narrow_add
4546349cc55cSDimitry Andric   // %and = G_AND %new_add, 000...11111111
4547349cc55cSDimitry Andric   //
4548349cc55cSDimitry Andric   // This can allow later combines to eliminate the G_AND if it turns out
4549349cc55cSDimitry Andric   // that the mask is irrelevant.
4550349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_AND);
4551349cc55cSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
4552349cc55cSDimitry Andric   Register AndLHS = MI.getOperand(1).getReg();
4553349cc55cSDimitry Andric   Register AndRHS = MI.getOperand(2).getReg();
4554349cc55cSDimitry Andric   LLT WideTy = MRI.getType(Dst);
4555349cc55cSDimitry Andric 
4556349cc55cSDimitry Andric   // If the potential binop has more than one use, then it's possible that one
4557349cc55cSDimitry Andric   // of those uses will need its full width.
4558349cc55cSDimitry Andric   if (!WideTy.isScalar() || !MRI.hasOneNonDBGUse(AndLHS))
4559349cc55cSDimitry Andric     return false;
4560349cc55cSDimitry Andric 
4561349cc55cSDimitry Andric   // Check if the LHS feeding the AND is impacted by the high bits that we're
4562349cc55cSDimitry Andric   // masking out.
4563349cc55cSDimitry Andric   //
4564349cc55cSDimitry Andric   // e.g. for 64-bit x, y:
4565349cc55cSDimitry Andric   //
4566349cc55cSDimitry Andric   // add_64(x, y) & 65535 == zext(add_16(trunc(x), trunc(y))) & 65535
4567349cc55cSDimitry Andric   MachineInstr *LHSInst = getDefIgnoringCopies(AndLHS, MRI);
4568349cc55cSDimitry Andric   if (!LHSInst)
4569349cc55cSDimitry Andric     return false;
4570349cc55cSDimitry Andric   unsigned LHSOpc = LHSInst->getOpcode();
4571349cc55cSDimitry Andric   switch (LHSOpc) {
4572349cc55cSDimitry Andric   default:
4573349cc55cSDimitry Andric     return false;
4574349cc55cSDimitry Andric   case TargetOpcode::G_ADD:
4575349cc55cSDimitry Andric   case TargetOpcode::G_SUB:
4576349cc55cSDimitry Andric   case TargetOpcode::G_MUL:
4577349cc55cSDimitry Andric   case TargetOpcode::G_AND:
4578349cc55cSDimitry Andric   case TargetOpcode::G_OR:
4579349cc55cSDimitry Andric   case TargetOpcode::G_XOR:
4580349cc55cSDimitry Andric     break;
4581349cc55cSDimitry Andric   }
4582349cc55cSDimitry Andric 
4583349cc55cSDimitry Andric   // Find the mask on the RHS.
4584349cc55cSDimitry Andric   auto Cst = getIConstantVRegValWithLookThrough(AndRHS, MRI);
4585349cc55cSDimitry Andric   if (!Cst)
4586349cc55cSDimitry Andric     return false;
4587349cc55cSDimitry Andric   auto Mask = Cst->Value;
4588349cc55cSDimitry Andric   if (!Mask.isMask())
4589349cc55cSDimitry Andric     return false;
4590349cc55cSDimitry Andric 
4591349cc55cSDimitry Andric   // No point in combining if there's nothing to truncate.
4592*06c3fb27SDimitry Andric   unsigned NarrowWidth = Mask.countr_one();
4593349cc55cSDimitry Andric   if (NarrowWidth == WideTy.getSizeInBits())
4594349cc55cSDimitry Andric     return false;
4595349cc55cSDimitry Andric   LLT NarrowTy = LLT::scalar(NarrowWidth);
4596349cc55cSDimitry Andric 
4597349cc55cSDimitry Andric   // Check if adding the zext + truncates could be harmful.
4598349cc55cSDimitry Andric   auto &MF = *MI.getMF();
4599349cc55cSDimitry Andric   const auto &TLI = getTargetLowering();
4600349cc55cSDimitry Andric   LLVMContext &Ctx = MF.getFunction().getContext();
4601349cc55cSDimitry Andric   auto &DL = MF.getDataLayout();
4602349cc55cSDimitry Andric   if (!TLI.isTruncateFree(WideTy, NarrowTy, DL, Ctx) ||
4603349cc55cSDimitry Andric       !TLI.isZExtFree(NarrowTy, WideTy, DL, Ctx))
4604349cc55cSDimitry Andric     return false;
4605349cc55cSDimitry Andric   if (!isLegalOrBeforeLegalizer({TargetOpcode::G_TRUNC, {NarrowTy, WideTy}}) ||
4606349cc55cSDimitry Andric       !isLegalOrBeforeLegalizer({TargetOpcode::G_ZEXT, {WideTy, NarrowTy}}))
4607349cc55cSDimitry Andric     return false;
4608349cc55cSDimitry Andric   Register BinOpLHS = LHSInst->getOperand(1).getReg();
4609349cc55cSDimitry Andric   Register BinOpRHS = LHSInst->getOperand(2).getReg();
4610349cc55cSDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4611349cc55cSDimitry Andric     auto NarrowLHS = Builder.buildTrunc(NarrowTy, BinOpLHS);
4612349cc55cSDimitry Andric     auto NarrowRHS = Builder.buildTrunc(NarrowTy, BinOpRHS);
4613349cc55cSDimitry Andric     auto NarrowBinOp =
4614349cc55cSDimitry Andric         Builder.buildInstr(LHSOpc, {NarrowTy}, {NarrowLHS, NarrowRHS});
4615349cc55cSDimitry Andric     auto Ext = Builder.buildZExt(WideTy, NarrowBinOp);
4616349cc55cSDimitry Andric     Observer.changingInstr(MI);
4617349cc55cSDimitry Andric     MI.getOperand(1).setReg(Ext.getReg(0));
4618349cc55cSDimitry Andric     Observer.changedInstr(MI);
4619349cc55cSDimitry Andric   };
4620349cc55cSDimitry Andric   return true;
4621349cc55cSDimitry Andric }
4622349cc55cSDimitry Andric 
4623349cc55cSDimitry Andric bool CombinerHelper::matchMulOBy2(MachineInstr &MI, BuildFnTy &MatchInfo) {
4624349cc55cSDimitry Andric   unsigned Opc = MI.getOpcode();
4625349cc55cSDimitry Andric   assert(Opc == TargetOpcode::G_UMULO || Opc == TargetOpcode::G_SMULO);
46264824e7fdSDimitry Andric 
46274824e7fdSDimitry Andric   if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICstOrSplat(2)))
4628349cc55cSDimitry Andric     return false;
4629349cc55cSDimitry Andric 
4630349cc55cSDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4631349cc55cSDimitry Andric     Observer.changingInstr(MI);
4632349cc55cSDimitry Andric     unsigned NewOpc = Opc == TargetOpcode::G_UMULO ? TargetOpcode::G_UADDO
4633349cc55cSDimitry Andric                                                    : TargetOpcode::G_SADDO;
4634349cc55cSDimitry Andric     MI.setDesc(Builder.getTII().get(NewOpc));
4635349cc55cSDimitry Andric     MI.getOperand(3).setReg(MI.getOperand(2).getReg());
4636349cc55cSDimitry Andric     Observer.changedInstr(MI);
4637349cc55cSDimitry Andric   };
4638349cc55cSDimitry Andric   return true;
4639349cc55cSDimitry Andric }
4640349cc55cSDimitry Andric 
464181ad6265SDimitry Andric bool CombinerHelper::matchMulOBy0(MachineInstr &MI, BuildFnTy &MatchInfo) {
464281ad6265SDimitry Andric   // (G_*MULO x, 0) -> 0 + no carry out
464381ad6265SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UMULO ||
464481ad6265SDimitry Andric          MI.getOpcode() == TargetOpcode::G_SMULO);
464581ad6265SDimitry Andric   if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICstOrSplat(0)))
464681ad6265SDimitry Andric     return false;
464781ad6265SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
464881ad6265SDimitry Andric   Register Carry = MI.getOperand(1).getReg();
464981ad6265SDimitry Andric   if (!isConstantLegalOrBeforeLegalizer(MRI.getType(Dst)) ||
465081ad6265SDimitry Andric       !isConstantLegalOrBeforeLegalizer(MRI.getType(Carry)))
465181ad6265SDimitry Andric     return false;
465281ad6265SDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
465381ad6265SDimitry Andric     B.buildConstant(Dst, 0);
465481ad6265SDimitry Andric     B.buildConstant(Carry, 0);
465581ad6265SDimitry Andric   };
465681ad6265SDimitry Andric   return true;
465781ad6265SDimitry Andric }
465881ad6265SDimitry Andric 
465981ad6265SDimitry Andric bool CombinerHelper::matchAddOBy0(MachineInstr &MI, BuildFnTy &MatchInfo) {
466081ad6265SDimitry Andric   // (G_*ADDO x, 0) -> x + no carry out
466181ad6265SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UADDO ||
466281ad6265SDimitry Andric          MI.getOpcode() == TargetOpcode::G_SADDO);
466381ad6265SDimitry Andric   if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICstOrSplat(0)))
466481ad6265SDimitry Andric     return false;
466581ad6265SDimitry Andric   Register Carry = MI.getOperand(1).getReg();
466681ad6265SDimitry Andric   if (!isConstantLegalOrBeforeLegalizer(MRI.getType(Carry)))
466781ad6265SDimitry Andric     return false;
466881ad6265SDimitry Andric   Register Dst = MI.getOperand(0).getReg();
466981ad6265SDimitry Andric   Register LHS = MI.getOperand(2).getReg();
467081ad6265SDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
467181ad6265SDimitry Andric     B.buildCopy(Dst, LHS);
467281ad6265SDimitry Andric     B.buildConstant(Carry, 0);
467381ad6265SDimitry Andric   };
467481ad6265SDimitry Andric   return true;
467581ad6265SDimitry Andric }
467681ad6265SDimitry Andric 
4677bdd1243dSDimitry Andric bool CombinerHelper::matchAddEToAddO(MachineInstr &MI, BuildFnTy &MatchInfo) {
4678bdd1243dSDimitry Andric   // (G_*ADDE x, y, 0) -> (G_*ADDO x, y)
4679bdd1243dSDimitry Andric   // (G_*SUBE x, y, 0) -> (G_*SUBO x, y)
4680bdd1243dSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UADDE ||
4681bdd1243dSDimitry Andric          MI.getOpcode() == TargetOpcode::G_SADDE ||
4682bdd1243dSDimitry Andric          MI.getOpcode() == TargetOpcode::G_USUBE ||
4683bdd1243dSDimitry Andric          MI.getOpcode() == TargetOpcode::G_SSUBE);
4684bdd1243dSDimitry Andric   if (!mi_match(MI.getOperand(4).getReg(), MRI, m_SpecificICstOrSplat(0)))
4685bdd1243dSDimitry Andric     return false;
4686bdd1243dSDimitry Andric   MatchInfo = [&](MachineIRBuilder &B) {
4687bdd1243dSDimitry Andric     unsigned NewOpcode;
4688bdd1243dSDimitry Andric     switch (MI.getOpcode()) {
4689bdd1243dSDimitry Andric     case TargetOpcode::G_UADDE:
4690bdd1243dSDimitry Andric       NewOpcode = TargetOpcode::G_UADDO;
4691bdd1243dSDimitry Andric       break;
4692bdd1243dSDimitry Andric     case TargetOpcode::G_SADDE:
4693bdd1243dSDimitry Andric       NewOpcode = TargetOpcode::G_SADDO;
4694bdd1243dSDimitry Andric       break;
4695bdd1243dSDimitry Andric     case TargetOpcode::G_USUBE:
4696bdd1243dSDimitry Andric       NewOpcode = TargetOpcode::G_USUBO;
4697bdd1243dSDimitry Andric       break;
4698bdd1243dSDimitry Andric     case TargetOpcode::G_SSUBE:
4699bdd1243dSDimitry Andric       NewOpcode = TargetOpcode::G_SSUBO;
4700bdd1243dSDimitry Andric       break;
4701bdd1243dSDimitry Andric     }
4702bdd1243dSDimitry Andric     Observer.changingInstr(MI);
4703bdd1243dSDimitry Andric     MI.setDesc(B.getTII().get(NewOpcode));
4704bdd1243dSDimitry Andric     MI.removeOperand(4);
4705bdd1243dSDimitry Andric     Observer.changedInstr(MI);
4706bdd1243dSDimitry Andric   };
4707bdd1243dSDimitry Andric   return true;
4708bdd1243dSDimitry Andric }
4709bdd1243dSDimitry Andric 
4710bdd1243dSDimitry Andric bool CombinerHelper::matchSubAddSameReg(MachineInstr &MI,
4711bdd1243dSDimitry Andric                                         BuildFnTy &MatchInfo) {
4712bdd1243dSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SUB);
4713bdd1243dSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
4714bdd1243dSDimitry Andric   // (x + y) - z -> x (if y == z)
4715bdd1243dSDimitry Andric   // (x + y) - z -> y (if x == z)
4716bdd1243dSDimitry Andric   Register X, Y, Z;
4717bdd1243dSDimitry Andric   if (mi_match(Dst, MRI, m_GSub(m_GAdd(m_Reg(X), m_Reg(Y)), m_Reg(Z)))) {
4718bdd1243dSDimitry Andric     Register ReplaceReg;
4719bdd1243dSDimitry Andric     int64_t CstX, CstY;
4720bdd1243dSDimitry Andric     if (Y == Z || (mi_match(Y, MRI, m_ICstOrSplat(CstY)) &&
4721bdd1243dSDimitry Andric                    mi_match(Z, MRI, m_SpecificICstOrSplat(CstY))))
4722bdd1243dSDimitry Andric       ReplaceReg = X;
4723bdd1243dSDimitry Andric     else if (X == Z || (mi_match(X, MRI, m_ICstOrSplat(CstX)) &&
4724bdd1243dSDimitry Andric                         mi_match(Z, MRI, m_SpecificICstOrSplat(CstX))))
4725bdd1243dSDimitry Andric       ReplaceReg = Y;
4726bdd1243dSDimitry Andric     if (ReplaceReg) {
4727bdd1243dSDimitry Andric       MatchInfo = [=](MachineIRBuilder &B) { B.buildCopy(Dst, ReplaceReg); };
4728bdd1243dSDimitry Andric       return true;
4729bdd1243dSDimitry Andric     }
4730bdd1243dSDimitry Andric   }
4731bdd1243dSDimitry Andric 
4732bdd1243dSDimitry Andric   // x - (y + z) -> 0 - y (if x == z)
4733bdd1243dSDimitry Andric   // x - (y + z) -> 0 - z (if x == y)
4734bdd1243dSDimitry Andric   if (mi_match(Dst, MRI, m_GSub(m_Reg(X), m_GAdd(m_Reg(Y), m_Reg(Z))))) {
4735bdd1243dSDimitry Andric     Register ReplaceReg;
4736bdd1243dSDimitry Andric     int64_t CstX;
4737bdd1243dSDimitry Andric     if (X == Z || (mi_match(X, MRI, m_ICstOrSplat(CstX)) &&
4738bdd1243dSDimitry Andric                    mi_match(Z, MRI, m_SpecificICstOrSplat(CstX))))
4739bdd1243dSDimitry Andric       ReplaceReg = Y;
4740bdd1243dSDimitry Andric     else if (X == Y || (mi_match(X, MRI, m_ICstOrSplat(CstX)) &&
4741bdd1243dSDimitry Andric                         mi_match(Y, MRI, m_SpecificICstOrSplat(CstX))))
4742bdd1243dSDimitry Andric       ReplaceReg = Z;
4743bdd1243dSDimitry Andric     if (ReplaceReg) {
4744bdd1243dSDimitry Andric       MatchInfo = [=](MachineIRBuilder &B) {
4745bdd1243dSDimitry Andric         auto Zero = B.buildConstant(MRI.getType(Dst), 0);
4746bdd1243dSDimitry Andric         B.buildSub(Dst, Zero, ReplaceReg);
4747bdd1243dSDimitry Andric       };
4748bdd1243dSDimitry Andric       return true;
4749bdd1243dSDimitry Andric     }
4750bdd1243dSDimitry Andric   }
4751bdd1243dSDimitry Andric   return false;
4752bdd1243dSDimitry Andric }
4753bdd1243dSDimitry Andric 
4754349cc55cSDimitry Andric MachineInstr *CombinerHelper::buildUDivUsingMul(MachineInstr &MI) {
4755349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UDIV);
4756349cc55cSDimitry Andric   auto &UDiv = cast<GenericMachineInstr>(MI);
4757349cc55cSDimitry Andric   Register Dst = UDiv.getReg(0);
4758349cc55cSDimitry Andric   Register LHS = UDiv.getReg(1);
4759349cc55cSDimitry Andric   Register RHS = UDiv.getReg(2);
4760349cc55cSDimitry Andric   LLT Ty = MRI.getType(Dst);
4761349cc55cSDimitry Andric   LLT ScalarTy = Ty.getScalarType();
4762349cc55cSDimitry Andric   const unsigned EltBits = ScalarTy.getScalarSizeInBits();
4763349cc55cSDimitry Andric   LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4764349cc55cSDimitry Andric   LLT ScalarShiftAmtTy = ShiftAmtTy.getScalarType();
4765349cc55cSDimitry Andric   auto &MIB = Builder;
4766349cc55cSDimitry Andric   MIB.setInstrAndDebugLoc(MI);
4767349cc55cSDimitry Andric 
4768349cc55cSDimitry Andric   bool UseNPQ = false;
4769349cc55cSDimitry Andric   SmallVector<Register, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
4770349cc55cSDimitry Andric 
4771349cc55cSDimitry Andric   auto BuildUDIVPattern = [&](const Constant *C) {
4772349cc55cSDimitry Andric     auto *CI = cast<ConstantInt>(C);
4773349cc55cSDimitry Andric     const APInt &Divisor = CI->getValue();
4774bdd1243dSDimitry Andric 
4775bdd1243dSDimitry Andric     bool SelNPQ = false;
4776bdd1243dSDimitry Andric     APInt Magic(Divisor.getBitWidth(), 0);
4777349cc55cSDimitry Andric     unsigned PreShift = 0, PostShift = 0;
4778349cc55cSDimitry Andric 
4779bdd1243dSDimitry Andric     // Magic algorithm doesn't work for division by 1. We need to emit a select
4780bdd1243dSDimitry Andric     // at the end.
4781bdd1243dSDimitry Andric     // TODO: Use undef values for divisor of 1.
4782*06c3fb27SDimitry Andric     if (!Divisor.isOne()) {
4783bdd1243dSDimitry Andric       UnsignedDivisionByConstantInfo magics =
4784bdd1243dSDimitry Andric           UnsignedDivisionByConstantInfo::get(Divisor);
4785349cc55cSDimitry Andric 
4786bdd1243dSDimitry Andric       Magic = std::move(magics.Magic);
4787bdd1243dSDimitry Andric 
4788bdd1243dSDimitry Andric       assert(magics.PreShift < Divisor.getBitWidth() &&
4789349cc55cSDimitry Andric              "We shouldn't generate an undefined shift!");
4790bdd1243dSDimitry Andric       assert(magics.PostShift < Divisor.getBitWidth() &&
4791bdd1243dSDimitry Andric              "We shouldn't generate an undefined shift!");
4792bdd1243dSDimitry Andric       assert((!magics.IsAdd || magics.PreShift == 0) && "Unexpected pre-shift");
4793bdd1243dSDimitry Andric       PreShift = magics.PreShift;
4794bdd1243dSDimitry Andric       PostShift = magics.PostShift;
4795bdd1243dSDimitry Andric       SelNPQ = magics.IsAdd;
4796349cc55cSDimitry Andric     }
4797349cc55cSDimitry Andric 
4798349cc55cSDimitry Andric     PreShifts.push_back(
4799349cc55cSDimitry Andric         MIB.buildConstant(ScalarShiftAmtTy, PreShift).getReg(0));
4800bdd1243dSDimitry Andric     MagicFactors.push_back(MIB.buildConstant(ScalarTy, Magic).getReg(0));
4801349cc55cSDimitry Andric     NPQFactors.push_back(
4802349cc55cSDimitry Andric         MIB.buildConstant(ScalarTy,
4803349cc55cSDimitry Andric                           SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1)
4804349cc55cSDimitry Andric                                  : APInt::getZero(EltBits))
4805349cc55cSDimitry Andric             .getReg(0));
4806349cc55cSDimitry Andric     PostShifts.push_back(
4807349cc55cSDimitry Andric         MIB.buildConstant(ScalarShiftAmtTy, PostShift).getReg(0));
4808349cc55cSDimitry Andric     UseNPQ |= SelNPQ;
4809349cc55cSDimitry Andric     return true;
4810349cc55cSDimitry Andric   };
4811349cc55cSDimitry Andric 
4812349cc55cSDimitry Andric   // Collect the shifts/magic values from each element.
4813349cc55cSDimitry Andric   bool Matched = matchUnaryPredicate(MRI, RHS, BuildUDIVPattern);
4814349cc55cSDimitry Andric   (void)Matched;
4815349cc55cSDimitry Andric   assert(Matched && "Expected unary predicate match to succeed");
4816349cc55cSDimitry Andric 
4817349cc55cSDimitry Andric   Register PreShift, PostShift, MagicFactor, NPQFactor;
4818349cc55cSDimitry Andric   auto *RHSDef = getOpcodeDef<GBuildVector>(RHS, MRI);
4819349cc55cSDimitry Andric   if (RHSDef) {
4820349cc55cSDimitry Andric     PreShift = MIB.buildBuildVector(ShiftAmtTy, PreShifts).getReg(0);
4821349cc55cSDimitry Andric     MagicFactor = MIB.buildBuildVector(Ty, MagicFactors).getReg(0);
4822349cc55cSDimitry Andric     NPQFactor = MIB.buildBuildVector(Ty, NPQFactors).getReg(0);
4823349cc55cSDimitry Andric     PostShift = MIB.buildBuildVector(ShiftAmtTy, PostShifts).getReg(0);
4824349cc55cSDimitry Andric   } else {
4825349cc55cSDimitry Andric     assert(MRI.getType(RHS).isScalar() &&
4826349cc55cSDimitry Andric            "Non-build_vector operation should have been a scalar");
4827349cc55cSDimitry Andric     PreShift = PreShifts[0];
4828349cc55cSDimitry Andric     MagicFactor = MagicFactors[0];
4829349cc55cSDimitry Andric     PostShift = PostShifts[0];
4830349cc55cSDimitry Andric   }
4831349cc55cSDimitry Andric 
4832349cc55cSDimitry Andric   Register Q = LHS;
4833349cc55cSDimitry Andric   Q = MIB.buildLShr(Ty, Q, PreShift).getReg(0);
4834349cc55cSDimitry Andric 
4835349cc55cSDimitry Andric   // Multiply the numerator (operand 0) by the magic value.
4836349cc55cSDimitry Andric   Q = MIB.buildUMulH(Ty, Q, MagicFactor).getReg(0);
4837349cc55cSDimitry Andric 
4838349cc55cSDimitry Andric   if (UseNPQ) {
4839349cc55cSDimitry Andric     Register NPQ = MIB.buildSub(Ty, LHS, Q).getReg(0);
4840349cc55cSDimitry Andric 
4841349cc55cSDimitry Andric     // For vectors we might have a mix of non-NPQ/NPQ paths, so use
4842349cc55cSDimitry Andric     // G_UMULH to act as a SRL-by-1 for NPQ, else multiply by zero.
4843349cc55cSDimitry Andric     if (Ty.isVector())
4844349cc55cSDimitry Andric       NPQ = MIB.buildUMulH(Ty, NPQ, NPQFactor).getReg(0);
4845349cc55cSDimitry Andric     else
4846349cc55cSDimitry Andric       NPQ = MIB.buildLShr(Ty, NPQ, MIB.buildConstant(ShiftAmtTy, 1)).getReg(0);
4847349cc55cSDimitry Andric 
4848349cc55cSDimitry Andric     Q = MIB.buildAdd(Ty, NPQ, Q).getReg(0);
4849349cc55cSDimitry Andric   }
4850349cc55cSDimitry Andric 
4851349cc55cSDimitry Andric   Q = MIB.buildLShr(Ty, Q, PostShift).getReg(0);
4852349cc55cSDimitry Andric   auto One = MIB.buildConstant(Ty, 1);
4853349cc55cSDimitry Andric   auto IsOne = MIB.buildICmp(
4854349cc55cSDimitry Andric       CmpInst::Predicate::ICMP_EQ,
4855349cc55cSDimitry Andric       Ty.isScalar() ? LLT::scalar(1) : Ty.changeElementSize(1), RHS, One);
4856349cc55cSDimitry Andric   return MIB.buildSelect(Ty, IsOne, LHS, Q);
4857349cc55cSDimitry Andric }
4858349cc55cSDimitry Andric 
4859349cc55cSDimitry Andric bool CombinerHelper::matchUDivByConst(MachineInstr &MI) {
4860349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UDIV);
4861349cc55cSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
4862349cc55cSDimitry Andric   Register RHS = MI.getOperand(2).getReg();
4863349cc55cSDimitry Andric   LLT DstTy = MRI.getType(Dst);
4864349cc55cSDimitry Andric   auto *RHSDef = MRI.getVRegDef(RHS);
4865349cc55cSDimitry Andric   if (!isConstantOrConstantVector(*RHSDef, MRI))
4866349cc55cSDimitry Andric     return false;
4867349cc55cSDimitry Andric 
4868349cc55cSDimitry Andric   auto &MF = *MI.getMF();
4869349cc55cSDimitry Andric   AttributeList Attr = MF.getFunction().getAttributes();
4870349cc55cSDimitry Andric   const auto &TLI = getTargetLowering();
4871349cc55cSDimitry Andric   LLVMContext &Ctx = MF.getFunction().getContext();
4872349cc55cSDimitry Andric   auto &DL = MF.getDataLayout();
4873349cc55cSDimitry Andric   if (TLI.isIntDivCheap(getApproximateEVTForLLT(DstTy, DL, Ctx), Attr))
4874349cc55cSDimitry Andric     return false;
4875349cc55cSDimitry Andric 
4876349cc55cSDimitry Andric   // Don't do this for minsize because the instruction sequence is usually
4877349cc55cSDimitry Andric   // larger.
4878349cc55cSDimitry Andric   if (MF.getFunction().hasMinSize())
4879349cc55cSDimitry Andric     return false;
4880349cc55cSDimitry Andric 
4881349cc55cSDimitry Andric   // Don't do this if the types are not going to be legal.
4882349cc55cSDimitry Andric   if (LI) {
4883349cc55cSDimitry Andric     if (!isLegalOrBeforeLegalizer({TargetOpcode::G_MUL, {DstTy, DstTy}}))
4884349cc55cSDimitry Andric       return false;
4885349cc55cSDimitry Andric     if (!isLegalOrBeforeLegalizer({TargetOpcode::G_UMULH, {DstTy}}))
4886349cc55cSDimitry Andric       return false;
4887349cc55cSDimitry Andric     if (!isLegalOrBeforeLegalizer(
4888349cc55cSDimitry Andric             {TargetOpcode::G_ICMP,
4889349cc55cSDimitry Andric              {DstTy.isVector() ? DstTy.changeElementSize(1) : LLT::scalar(1),
4890349cc55cSDimitry Andric               DstTy}}))
4891349cc55cSDimitry Andric       return false;
4892349cc55cSDimitry Andric   }
4893349cc55cSDimitry Andric 
4894349cc55cSDimitry Andric   auto CheckEltValue = [&](const Constant *C) {
4895349cc55cSDimitry Andric     if (auto *CI = dyn_cast_or_null<ConstantInt>(C))
4896349cc55cSDimitry Andric       return !CI->isZero();
4897349cc55cSDimitry Andric     return false;
4898349cc55cSDimitry Andric   };
4899349cc55cSDimitry Andric   return matchUnaryPredicate(MRI, RHS, CheckEltValue);
4900349cc55cSDimitry Andric }
4901349cc55cSDimitry Andric 
4902349cc55cSDimitry Andric void CombinerHelper::applyUDivByConst(MachineInstr &MI) {
4903349cc55cSDimitry Andric   auto *NewMI = buildUDivUsingMul(MI);
4904349cc55cSDimitry Andric   replaceSingleDefInstWithReg(MI, NewMI->getOperand(0).getReg());
4905349cc55cSDimitry Andric }
4906349cc55cSDimitry Andric 
4907bdd1243dSDimitry Andric bool CombinerHelper::matchSDivByConst(MachineInstr &MI) {
4908bdd1243dSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SDIV && "Expected SDIV");
4909bdd1243dSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
4910bdd1243dSDimitry Andric   Register RHS = MI.getOperand(2).getReg();
4911bdd1243dSDimitry Andric   LLT DstTy = MRI.getType(Dst);
4912bdd1243dSDimitry Andric 
4913bdd1243dSDimitry Andric   auto &MF = *MI.getMF();
4914bdd1243dSDimitry Andric   AttributeList Attr = MF.getFunction().getAttributes();
4915bdd1243dSDimitry Andric   const auto &TLI = getTargetLowering();
4916bdd1243dSDimitry Andric   LLVMContext &Ctx = MF.getFunction().getContext();
4917bdd1243dSDimitry Andric   auto &DL = MF.getDataLayout();
4918bdd1243dSDimitry Andric   if (TLI.isIntDivCheap(getApproximateEVTForLLT(DstTy, DL, Ctx), Attr))
4919bdd1243dSDimitry Andric     return false;
4920bdd1243dSDimitry Andric 
4921bdd1243dSDimitry Andric   // Don't do this for minsize because the instruction sequence is usually
4922bdd1243dSDimitry Andric   // larger.
4923bdd1243dSDimitry Andric   if (MF.getFunction().hasMinSize())
4924bdd1243dSDimitry Andric     return false;
4925bdd1243dSDimitry Andric 
4926bdd1243dSDimitry Andric   // If the sdiv has an 'exact' flag we can use a simpler lowering.
4927bdd1243dSDimitry Andric   if (MI.getFlag(MachineInstr::MIFlag::IsExact)) {
4928bdd1243dSDimitry Andric     return matchUnaryPredicate(
4929bdd1243dSDimitry Andric         MRI, RHS, [](const Constant *C) { return C && !C->isZeroValue(); });
4930bdd1243dSDimitry Andric   }
4931bdd1243dSDimitry Andric 
4932bdd1243dSDimitry Andric   // Don't support the general case for now.
4933bdd1243dSDimitry Andric   return false;
4934bdd1243dSDimitry Andric }
4935bdd1243dSDimitry Andric 
4936bdd1243dSDimitry Andric void CombinerHelper::applySDivByConst(MachineInstr &MI) {
4937bdd1243dSDimitry Andric   auto *NewMI = buildSDivUsingMul(MI);
4938bdd1243dSDimitry Andric   replaceSingleDefInstWithReg(MI, NewMI->getOperand(0).getReg());
4939bdd1243dSDimitry Andric }
4940bdd1243dSDimitry Andric 
4941bdd1243dSDimitry Andric MachineInstr *CombinerHelper::buildSDivUsingMul(MachineInstr &MI) {
4942bdd1243dSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SDIV && "Expected SDIV");
4943bdd1243dSDimitry Andric   auto &SDiv = cast<GenericMachineInstr>(MI);
4944bdd1243dSDimitry Andric   Register Dst = SDiv.getReg(0);
4945bdd1243dSDimitry Andric   Register LHS = SDiv.getReg(1);
4946bdd1243dSDimitry Andric   Register RHS = SDiv.getReg(2);
4947bdd1243dSDimitry Andric   LLT Ty = MRI.getType(Dst);
4948bdd1243dSDimitry Andric   LLT ScalarTy = Ty.getScalarType();
4949bdd1243dSDimitry Andric   LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4950bdd1243dSDimitry Andric   LLT ScalarShiftAmtTy = ShiftAmtTy.getScalarType();
4951bdd1243dSDimitry Andric   auto &MIB = Builder;
4952bdd1243dSDimitry Andric   MIB.setInstrAndDebugLoc(MI);
4953bdd1243dSDimitry Andric 
4954bdd1243dSDimitry Andric   bool UseSRA = false;
4955bdd1243dSDimitry Andric   SmallVector<Register, 16> Shifts, Factors;
4956bdd1243dSDimitry Andric 
4957bdd1243dSDimitry Andric   auto *RHSDef = cast<GenericMachineInstr>(getDefIgnoringCopies(RHS, MRI));
4958bdd1243dSDimitry Andric   bool IsSplat = getIConstantSplatVal(*RHSDef, MRI).has_value();
4959bdd1243dSDimitry Andric 
4960bdd1243dSDimitry Andric   auto BuildSDIVPattern = [&](const Constant *C) {
4961bdd1243dSDimitry Andric     // Don't recompute inverses for each splat element.
4962bdd1243dSDimitry Andric     if (IsSplat && !Factors.empty()) {
4963bdd1243dSDimitry Andric       Shifts.push_back(Shifts[0]);
4964bdd1243dSDimitry Andric       Factors.push_back(Factors[0]);
4965bdd1243dSDimitry Andric       return true;
4966bdd1243dSDimitry Andric     }
4967bdd1243dSDimitry Andric 
4968bdd1243dSDimitry Andric     auto *CI = cast<ConstantInt>(C);
4969bdd1243dSDimitry Andric     APInt Divisor = CI->getValue();
4970*06c3fb27SDimitry Andric     unsigned Shift = Divisor.countr_zero();
4971bdd1243dSDimitry Andric     if (Shift) {
4972bdd1243dSDimitry Andric       Divisor.ashrInPlace(Shift);
4973bdd1243dSDimitry Andric       UseSRA = true;
4974bdd1243dSDimitry Andric     }
4975bdd1243dSDimitry Andric 
4976bdd1243dSDimitry Andric     // Calculate the multiplicative inverse modulo BW.
4977bdd1243dSDimitry Andric     // 2^W requires W + 1 bits, so we have to extend and then truncate.
4978bdd1243dSDimitry Andric     unsigned W = Divisor.getBitWidth();
4979bdd1243dSDimitry Andric     APInt Factor = Divisor.zext(W + 1)
4980bdd1243dSDimitry Andric                        .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
4981bdd1243dSDimitry Andric                        .trunc(W);
4982bdd1243dSDimitry Andric     Shifts.push_back(MIB.buildConstant(ScalarShiftAmtTy, Shift).getReg(0));
4983bdd1243dSDimitry Andric     Factors.push_back(MIB.buildConstant(ScalarTy, Factor).getReg(0));
4984bdd1243dSDimitry Andric     return true;
4985bdd1243dSDimitry Andric   };
4986bdd1243dSDimitry Andric 
4987bdd1243dSDimitry Andric   // Collect all magic values from the build vector.
4988bdd1243dSDimitry Andric   bool Matched = matchUnaryPredicate(MRI, RHS, BuildSDIVPattern);
4989bdd1243dSDimitry Andric   (void)Matched;
4990bdd1243dSDimitry Andric   assert(Matched && "Expected unary predicate match to succeed");
4991bdd1243dSDimitry Andric 
4992bdd1243dSDimitry Andric   Register Shift, Factor;
4993bdd1243dSDimitry Andric   if (Ty.isVector()) {
4994bdd1243dSDimitry Andric     Shift = MIB.buildBuildVector(ShiftAmtTy, Shifts).getReg(0);
4995bdd1243dSDimitry Andric     Factor = MIB.buildBuildVector(Ty, Factors).getReg(0);
4996bdd1243dSDimitry Andric   } else {
4997bdd1243dSDimitry Andric     Shift = Shifts[0];
4998bdd1243dSDimitry Andric     Factor = Factors[0];
4999bdd1243dSDimitry Andric   }
5000bdd1243dSDimitry Andric 
5001bdd1243dSDimitry Andric   Register Res = LHS;
5002bdd1243dSDimitry Andric 
5003bdd1243dSDimitry Andric   if (UseSRA)
5004bdd1243dSDimitry Andric     Res = MIB.buildAShr(Ty, Res, Shift, MachineInstr::IsExact).getReg(0);
5005bdd1243dSDimitry Andric 
5006bdd1243dSDimitry Andric   return MIB.buildMul(Ty, Res, Factor);
5007bdd1243dSDimitry Andric }
5008bdd1243dSDimitry Andric 
5009349cc55cSDimitry Andric bool CombinerHelper::matchUMulHToLShr(MachineInstr &MI) {
5010349cc55cSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_UMULH);
5011349cc55cSDimitry Andric   Register RHS = MI.getOperand(2).getReg();
5012349cc55cSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
5013349cc55cSDimitry Andric   LLT Ty = MRI.getType(Dst);
5014349cc55cSDimitry Andric   LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
5015349cc55cSDimitry Andric   auto MatchPow2ExceptOne = [&](const Constant *C) {
5016349cc55cSDimitry Andric     if (auto *CI = dyn_cast<ConstantInt>(C))
5017349cc55cSDimitry Andric       return CI->getValue().isPowerOf2() && !CI->getValue().isOne();
5018349cc55cSDimitry Andric     return false;
5019349cc55cSDimitry Andric   };
5020349cc55cSDimitry Andric   if (!matchUnaryPredicate(MRI, RHS, MatchPow2ExceptOne, false))
5021349cc55cSDimitry Andric     return false;
5022349cc55cSDimitry Andric   return isLegalOrBeforeLegalizer({TargetOpcode::G_LSHR, {Ty, ShiftAmtTy}});
5023349cc55cSDimitry Andric }
5024349cc55cSDimitry Andric 
5025349cc55cSDimitry Andric void CombinerHelper::applyUMulHToLShr(MachineInstr &MI) {
5026349cc55cSDimitry Andric   Register LHS = MI.getOperand(1).getReg();
5027349cc55cSDimitry Andric   Register RHS = MI.getOperand(2).getReg();
5028349cc55cSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
5029349cc55cSDimitry Andric   LLT Ty = MRI.getType(Dst);
5030349cc55cSDimitry Andric   LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
5031349cc55cSDimitry Andric   unsigned NumEltBits = Ty.getScalarSizeInBits();
5032349cc55cSDimitry Andric 
5033349cc55cSDimitry Andric   Builder.setInstrAndDebugLoc(MI);
5034349cc55cSDimitry Andric   auto LogBase2 = buildLogBase2(RHS, Builder);
5035349cc55cSDimitry Andric   auto ShiftAmt =
5036349cc55cSDimitry Andric       Builder.buildSub(Ty, Builder.buildConstant(Ty, NumEltBits), LogBase2);
5037349cc55cSDimitry Andric   auto Trunc = Builder.buildZExtOrTrunc(ShiftAmtTy, ShiftAmt);
5038349cc55cSDimitry Andric   Builder.buildLShr(Dst, LHS, Trunc);
5039349cc55cSDimitry Andric   MI.eraseFromParent();
5040349cc55cSDimitry Andric }
5041349cc55cSDimitry Andric 
5042349cc55cSDimitry Andric bool CombinerHelper::matchRedundantNegOperands(MachineInstr &MI,
5043349cc55cSDimitry Andric                                                BuildFnTy &MatchInfo) {
5044349cc55cSDimitry Andric   unsigned Opc = MI.getOpcode();
5045349cc55cSDimitry Andric   assert(Opc == TargetOpcode::G_FADD || Opc == TargetOpcode::G_FSUB ||
5046349cc55cSDimitry Andric          Opc == TargetOpcode::G_FMUL || Opc == TargetOpcode::G_FDIV ||
5047349cc55cSDimitry Andric          Opc == TargetOpcode::G_FMAD || Opc == TargetOpcode::G_FMA);
5048349cc55cSDimitry Andric 
5049349cc55cSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
5050349cc55cSDimitry Andric   Register X = MI.getOperand(1).getReg();
5051349cc55cSDimitry Andric   Register Y = MI.getOperand(2).getReg();
5052349cc55cSDimitry Andric   LLT Type = MRI.getType(Dst);
5053349cc55cSDimitry Andric 
5054349cc55cSDimitry Andric   // fold (fadd x, fneg(y)) -> (fsub x, y)
5055349cc55cSDimitry Andric   // fold (fadd fneg(y), x) -> (fsub x, y)
5056349cc55cSDimitry Andric   // G_ADD is commutative so both cases are checked by m_GFAdd
5057349cc55cSDimitry Andric   if (mi_match(Dst, MRI, m_GFAdd(m_Reg(X), m_GFNeg(m_Reg(Y)))) &&
5058349cc55cSDimitry Andric       isLegalOrBeforeLegalizer({TargetOpcode::G_FSUB, {Type}})) {
5059349cc55cSDimitry Andric     Opc = TargetOpcode::G_FSUB;
5060349cc55cSDimitry Andric   }
5061349cc55cSDimitry Andric   /// fold (fsub x, fneg(y)) -> (fadd x, y)
5062349cc55cSDimitry Andric   else if (mi_match(Dst, MRI, m_GFSub(m_Reg(X), m_GFNeg(m_Reg(Y)))) &&
5063349cc55cSDimitry Andric            isLegalOrBeforeLegalizer({TargetOpcode::G_FADD, {Type}})) {
5064349cc55cSDimitry Andric     Opc = TargetOpcode::G_FADD;
5065349cc55cSDimitry Andric   }
5066349cc55cSDimitry Andric   // fold (fmul fneg(x), fneg(y)) -> (fmul x, y)
5067349cc55cSDimitry Andric   // fold (fdiv fneg(x), fneg(y)) -> (fdiv x, y)
5068349cc55cSDimitry Andric   // fold (fmad fneg(x), fneg(y), z) -> (fmad x, y, z)
5069349cc55cSDimitry Andric   // fold (fma fneg(x), fneg(y), z) -> (fma x, y, z)
5070349cc55cSDimitry Andric   else if ((Opc == TargetOpcode::G_FMUL || Opc == TargetOpcode::G_FDIV ||
5071349cc55cSDimitry Andric             Opc == TargetOpcode::G_FMAD || Opc == TargetOpcode::G_FMA) &&
5072349cc55cSDimitry Andric            mi_match(X, MRI, m_GFNeg(m_Reg(X))) &&
5073349cc55cSDimitry Andric            mi_match(Y, MRI, m_GFNeg(m_Reg(Y)))) {
5074349cc55cSDimitry Andric     // no opcode change
5075349cc55cSDimitry Andric   } else
5076349cc55cSDimitry Andric     return false;
5077349cc55cSDimitry Andric 
5078349cc55cSDimitry Andric   MatchInfo = [=, &MI](MachineIRBuilder &B) {
5079349cc55cSDimitry Andric     Observer.changingInstr(MI);
5080349cc55cSDimitry Andric     MI.setDesc(B.getTII().get(Opc));
5081349cc55cSDimitry Andric     MI.getOperand(1).setReg(X);
5082349cc55cSDimitry Andric     MI.getOperand(2).setReg(Y);
5083349cc55cSDimitry Andric     Observer.changedInstr(MI);
5084349cc55cSDimitry Andric   };
5085349cc55cSDimitry Andric   return true;
5086349cc55cSDimitry Andric }
5087349cc55cSDimitry Andric 
5088bdd1243dSDimitry Andric bool CombinerHelper::matchFsubToFneg(MachineInstr &MI, Register &MatchInfo) {
5089bdd1243dSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FSUB);
5090bdd1243dSDimitry Andric 
5091bdd1243dSDimitry Andric   Register LHS = MI.getOperand(1).getReg();
5092bdd1243dSDimitry Andric   MatchInfo = MI.getOperand(2).getReg();
5093bdd1243dSDimitry Andric   LLT Ty = MRI.getType(MI.getOperand(0).getReg());
5094bdd1243dSDimitry Andric 
5095bdd1243dSDimitry Andric   const auto LHSCst = Ty.isVector()
5096bdd1243dSDimitry Andric                           ? getFConstantSplat(LHS, MRI, /* allowUndef */ true)
5097bdd1243dSDimitry Andric                           : getFConstantVRegValWithLookThrough(LHS, MRI);
5098bdd1243dSDimitry Andric   if (!LHSCst)
5099bdd1243dSDimitry Andric     return false;
5100bdd1243dSDimitry Andric 
5101bdd1243dSDimitry Andric   // -0.0 is always allowed
5102bdd1243dSDimitry Andric   if (LHSCst->Value.isNegZero())
5103bdd1243dSDimitry Andric     return true;
5104bdd1243dSDimitry Andric 
5105bdd1243dSDimitry Andric   // +0.0 is only allowed if nsz is set.
5106bdd1243dSDimitry Andric   if (LHSCst->Value.isPosZero())
5107bdd1243dSDimitry Andric     return MI.getFlag(MachineInstr::FmNsz);
5108bdd1243dSDimitry Andric 
5109bdd1243dSDimitry Andric   return false;
5110bdd1243dSDimitry Andric }
5111bdd1243dSDimitry Andric 
5112bdd1243dSDimitry Andric void CombinerHelper::applyFsubToFneg(MachineInstr &MI, Register &MatchInfo) {
5113bdd1243dSDimitry Andric   Builder.setInstrAndDebugLoc(MI);
5114bdd1243dSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
5115bdd1243dSDimitry Andric   Builder.buildFNeg(
5116bdd1243dSDimitry Andric       Dst, Builder.buildFCanonicalize(MRI.getType(Dst), MatchInfo).getReg(0));
5117bdd1243dSDimitry Andric   eraseInst(MI);
5118bdd1243dSDimitry Andric }
5119bdd1243dSDimitry Andric 
51204824e7fdSDimitry Andric /// Checks if \p MI is TargetOpcode::G_FMUL and contractable either
51214824e7fdSDimitry Andric /// due to global flags or MachineInstr flags.
51224824e7fdSDimitry Andric static bool isContractableFMul(MachineInstr &MI, bool AllowFusionGlobally) {
51234824e7fdSDimitry Andric   if (MI.getOpcode() != TargetOpcode::G_FMUL)
51244824e7fdSDimitry Andric     return false;
51254824e7fdSDimitry Andric   return AllowFusionGlobally || MI.getFlag(MachineInstr::MIFlag::FmContract);
51264824e7fdSDimitry Andric }
51274824e7fdSDimitry Andric 
51284824e7fdSDimitry Andric static bool hasMoreUses(const MachineInstr &MI0, const MachineInstr &MI1,
51294824e7fdSDimitry Andric                         const MachineRegisterInfo &MRI) {
51304824e7fdSDimitry Andric   return std::distance(MRI.use_instr_nodbg_begin(MI0.getOperand(0).getReg()),
51314824e7fdSDimitry Andric                        MRI.use_instr_nodbg_end()) >
51324824e7fdSDimitry Andric          std::distance(MRI.use_instr_nodbg_begin(MI1.getOperand(0).getReg()),
51334824e7fdSDimitry Andric                        MRI.use_instr_nodbg_end());
51344824e7fdSDimitry Andric }
51354824e7fdSDimitry Andric 
51364824e7fdSDimitry Andric bool CombinerHelper::canCombineFMadOrFMA(MachineInstr &MI,
51374824e7fdSDimitry Andric                                          bool &AllowFusionGlobally,
51384824e7fdSDimitry Andric                                          bool &HasFMAD, bool &Aggressive,
51394824e7fdSDimitry Andric                                          bool CanReassociate) {
51404824e7fdSDimitry Andric 
51414824e7fdSDimitry Andric   auto *MF = MI.getMF();
51424824e7fdSDimitry Andric   const auto &TLI = *MF->getSubtarget().getTargetLowering();
51434824e7fdSDimitry Andric   const TargetOptions &Options = MF->getTarget().Options;
51444824e7fdSDimitry Andric   LLT DstType = MRI.getType(MI.getOperand(0).getReg());
51454824e7fdSDimitry Andric 
51464824e7fdSDimitry Andric   if (CanReassociate &&
51474824e7fdSDimitry Andric       !(Options.UnsafeFPMath || MI.getFlag(MachineInstr::MIFlag::FmReassoc)))
51484824e7fdSDimitry Andric     return false;
51494824e7fdSDimitry Andric 
51504824e7fdSDimitry Andric   // Floating-point multiply-add with intermediate rounding.
5151bdd1243dSDimitry Andric   HasFMAD = (!isPreLegalize() && TLI.isFMADLegal(MI, DstType));
51524824e7fdSDimitry Andric   // Floating-point multiply-add without intermediate rounding.
51534824e7fdSDimitry Andric   bool HasFMA = TLI.isFMAFasterThanFMulAndFAdd(*MF, DstType) &&
51544824e7fdSDimitry Andric                 isLegalOrBeforeLegalizer({TargetOpcode::G_FMA, {DstType}});
51554824e7fdSDimitry Andric   // No valid opcode, do not combine.
51564824e7fdSDimitry Andric   if (!HasFMAD && !HasFMA)
51574824e7fdSDimitry Andric     return false;
51584824e7fdSDimitry Andric 
51594824e7fdSDimitry Andric   AllowFusionGlobally = Options.AllowFPOpFusion == FPOpFusion::Fast ||
51604824e7fdSDimitry Andric                         Options.UnsafeFPMath || HasFMAD;
51614824e7fdSDimitry Andric   // If the addition is not contractable, do not combine.
51624824e7fdSDimitry Andric   if (!AllowFusionGlobally && !MI.getFlag(MachineInstr::MIFlag::FmContract))
51634824e7fdSDimitry Andric     return false;
51644824e7fdSDimitry Andric 
51654824e7fdSDimitry Andric   Aggressive = TLI.enableAggressiveFMAFusion(DstType);
51664824e7fdSDimitry Andric   return true;
51674824e7fdSDimitry Andric }
51684824e7fdSDimitry Andric 
51694824e7fdSDimitry Andric bool CombinerHelper::matchCombineFAddFMulToFMadOrFMA(
51704824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
51714824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FADD);
51724824e7fdSDimitry Andric 
51734824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
51744824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
51754824e7fdSDimitry Andric     return false;
51764824e7fdSDimitry Andric 
517704eeddc0SDimitry Andric   Register Op1 = MI.getOperand(1).getReg();
517804eeddc0SDimitry Andric   Register Op2 = MI.getOperand(2).getReg();
517904eeddc0SDimitry Andric   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
518004eeddc0SDimitry Andric   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
51814824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
51824824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
51834824e7fdSDimitry Andric 
51844824e7fdSDimitry Andric   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
51854824e7fdSDimitry Andric   // prefer to fold the multiply with fewer uses.
518604eeddc0SDimitry Andric   if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
518704eeddc0SDimitry Andric       isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
518804eeddc0SDimitry Andric     if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
51894824e7fdSDimitry Andric       std::swap(LHS, RHS);
51904824e7fdSDimitry Andric   }
51914824e7fdSDimitry Andric 
51924824e7fdSDimitry Andric   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
519304eeddc0SDimitry Andric   if (isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
519404eeddc0SDimitry Andric       (Aggressive || MRI.hasOneNonDBGUse(LHS.Reg))) {
51954824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
51964824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
519704eeddc0SDimitry Andric                    {LHS.MI->getOperand(1).getReg(),
519804eeddc0SDimitry Andric                     LHS.MI->getOperand(2).getReg(), RHS.Reg});
51994824e7fdSDimitry Andric     };
52004824e7fdSDimitry Andric     return true;
52014824e7fdSDimitry Andric   }
52024824e7fdSDimitry Andric 
52034824e7fdSDimitry Andric   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
520404eeddc0SDimitry Andric   if (isContractableFMul(*RHS.MI, AllowFusionGlobally) &&
520504eeddc0SDimitry Andric       (Aggressive || MRI.hasOneNonDBGUse(RHS.Reg))) {
52064824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
52074824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
520804eeddc0SDimitry Andric                    {RHS.MI->getOperand(1).getReg(),
520904eeddc0SDimitry Andric                     RHS.MI->getOperand(2).getReg(), LHS.Reg});
52104824e7fdSDimitry Andric     };
52114824e7fdSDimitry Andric     return true;
52124824e7fdSDimitry Andric   }
52134824e7fdSDimitry Andric 
52144824e7fdSDimitry Andric   return false;
52154824e7fdSDimitry Andric }
52164824e7fdSDimitry Andric 
52174824e7fdSDimitry Andric bool CombinerHelper::matchCombineFAddFpExtFMulToFMadOrFMA(
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   const auto &TLI = *MI.getMF()->getSubtarget().getTargetLowering();
522604eeddc0SDimitry Andric   Register Op1 = MI.getOperand(1).getReg();
522704eeddc0SDimitry Andric   Register Op2 = MI.getOperand(2).getReg();
522804eeddc0SDimitry Andric   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
522904eeddc0SDimitry Andric   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
52304824e7fdSDimitry Andric   LLT DstType = MRI.getType(MI.getOperand(0).getReg());
52314824e7fdSDimitry Andric 
52324824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
52334824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
52344824e7fdSDimitry Andric 
52354824e7fdSDimitry Andric   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
52364824e7fdSDimitry Andric   // prefer to fold the multiply with fewer uses.
523704eeddc0SDimitry Andric   if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
523804eeddc0SDimitry Andric       isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
523904eeddc0SDimitry Andric     if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
52404824e7fdSDimitry Andric       std::swap(LHS, RHS);
52414824e7fdSDimitry Andric   }
52424824e7fdSDimitry Andric 
52434824e7fdSDimitry Andric   // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
52444824e7fdSDimitry Andric   MachineInstr *FpExtSrc;
524504eeddc0SDimitry Andric   if (mi_match(LHS.Reg, MRI, m_GFPExt(m_MInstr(FpExtSrc))) &&
52464824e7fdSDimitry Andric       isContractableFMul(*FpExtSrc, AllowFusionGlobally) &&
52474824e7fdSDimitry Andric       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
52484824e7fdSDimitry Andric                           MRI.getType(FpExtSrc->getOperand(1).getReg()))) {
52494824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
52504824e7fdSDimitry Andric       auto FpExtX = B.buildFPExt(DstType, FpExtSrc->getOperand(1).getReg());
52514824e7fdSDimitry Andric       auto FpExtY = B.buildFPExt(DstType, FpExtSrc->getOperand(2).getReg());
525204eeddc0SDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
525304eeddc0SDimitry Andric                    {FpExtX.getReg(0), FpExtY.getReg(0), RHS.Reg});
52544824e7fdSDimitry Andric     };
52554824e7fdSDimitry Andric     return true;
52564824e7fdSDimitry Andric   }
52574824e7fdSDimitry Andric 
52584824e7fdSDimitry Andric   // fold (fadd z, (fpext (fmul x, y))) -> (fma (fpext x), (fpext y), z)
52594824e7fdSDimitry Andric   // Note: Commutes FADD operands.
526004eeddc0SDimitry Andric   if (mi_match(RHS.Reg, MRI, m_GFPExt(m_MInstr(FpExtSrc))) &&
52614824e7fdSDimitry Andric       isContractableFMul(*FpExtSrc, AllowFusionGlobally) &&
52624824e7fdSDimitry Andric       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
52634824e7fdSDimitry Andric                           MRI.getType(FpExtSrc->getOperand(1).getReg()))) {
52644824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
52654824e7fdSDimitry Andric       auto FpExtX = B.buildFPExt(DstType, FpExtSrc->getOperand(1).getReg());
52664824e7fdSDimitry Andric       auto FpExtY = B.buildFPExt(DstType, FpExtSrc->getOperand(2).getReg());
526704eeddc0SDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
526804eeddc0SDimitry Andric                    {FpExtX.getReg(0), FpExtY.getReg(0), LHS.Reg});
52694824e7fdSDimitry Andric     };
52704824e7fdSDimitry Andric     return true;
52714824e7fdSDimitry Andric   }
52724824e7fdSDimitry Andric 
52734824e7fdSDimitry Andric   return false;
52744824e7fdSDimitry Andric }
52754824e7fdSDimitry Andric 
52764824e7fdSDimitry Andric bool CombinerHelper::matchCombineFAddFMAFMulToFMadOrFMA(
52774824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
52784824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FADD);
52794824e7fdSDimitry Andric 
52804824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
52814824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive, true))
52824824e7fdSDimitry Andric     return false;
52834824e7fdSDimitry Andric 
528404eeddc0SDimitry Andric   Register Op1 = MI.getOperand(1).getReg();
528504eeddc0SDimitry Andric   Register Op2 = MI.getOperand(2).getReg();
528604eeddc0SDimitry Andric   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
528704eeddc0SDimitry Andric   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
52884824e7fdSDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
52894824e7fdSDimitry Andric 
52904824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
52914824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
52924824e7fdSDimitry Andric 
52934824e7fdSDimitry Andric   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
52944824e7fdSDimitry Andric   // prefer to fold the multiply with fewer uses.
529504eeddc0SDimitry Andric   if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
529604eeddc0SDimitry Andric       isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
529704eeddc0SDimitry Andric     if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
52984824e7fdSDimitry Andric       std::swap(LHS, RHS);
52994824e7fdSDimitry Andric   }
53004824e7fdSDimitry Andric 
53014824e7fdSDimitry Andric   MachineInstr *FMA = nullptr;
53024824e7fdSDimitry Andric   Register Z;
53034824e7fdSDimitry Andric   // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y, (fma u, v, z))
530404eeddc0SDimitry Andric   if (LHS.MI->getOpcode() == PreferredFusedOpcode &&
530504eeddc0SDimitry Andric       (MRI.getVRegDef(LHS.MI->getOperand(3).getReg())->getOpcode() ==
53064824e7fdSDimitry Andric        TargetOpcode::G_FMUL) &&
530704eeddc0SDimitry Andric       MRI.hasOneNonDBGUse(LHS.MI->getOperand(0).getReg()) &&
530804eeddc0SDimitry Andric       MRI.hasOneNonDBGUse(LHS.MI->getOperand(3).getReg())) {
530904eeddc0SDimitry Andric     FMA = LHS.MI;
531004eeddc0SDimitry Andric     Z = RHS.Reg;
53114824e7fdSDimitry Andric   }
53124824e7fdSDimitry Andric   // fold (fadd z, (fma x, y, (fmul u, v))) -> (fma x, y, (fma u, v, z))
531304eeddc0SDimitry Andric   else if (RHS.MI->getOpcode() == PreferredFusedOpcode &&
531404eeddc0SDimitry Andric            (MRI.getVRegDef(RHS.MI->getOperand(3).getReg())->getOpcode() ==
53154824e7fdSDimitry Andric             TargetOpcode::G_FMUL) &&
531604eeddc0SDimitry Andric            MRI.hasOneNonDBGUse(RHS.MI->getOperand(0).getReg()) &&
531704eeddc0SDimitry Andric            MRI.hasOneNonDBGUse(RHS.MI->getOperand(3).getReg())) {
531804eeddc0SDimitry Andric     Z = LHS.Reg;
531904eeddc0SDimitry Andric     FMA = RHS.MI;
53204824e7fdSDimitry Andric   }
53214824e7fdSDimitry Andric 
53224824e7fdSDimitry Andric   if (FMA) {
53234824e7fdSDimitry Andric     MachineInstr *FMulMI = MRI.getVRegDef(FMA->getOperand(3).getReg());
53244824e7fdSDimitry Andric     Register X = FMA->getOperand(1).getReg();
53254824e7fdSDimitry Andric     Register Y = FMA->getOperand(2).getReg();
53264824e7fdSDimitry Andric     Register U = FMulMI->getOperand(1).getReg();
53274824e7fdSDimitry Andric     Register V = FMulMI->getOperand(2).getReg();
53284824e7fdSDimitry Andric 
53294824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
53304824e7fdSDimitry Andric       Register InnerFMA = MRI.createGenericVirtualRegister(DstTy);
53314824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {InnerFMA}, {U, V, Z});
53324824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
53334824e7fdSDimitry Andric                    {X, Y, InnerFMA});
53344824e7fdSDimitry Andric     };
53354824e7fdSDimitry Andric     return true;
53364824e7fdSDimitry Andric   }
53374824e7fdSDimitry Andric 
53384824e7fdSDimitry Andric   return false;
53394824e7fdSDimitry Andric }
53404824e7fdSDimitry Andric 
53414824e7fdSDimitry Andric bool CombinerHelper::matchCombineFAddFpExtFMulToFMadOrFMAAggressive(
53424824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
53434824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FADD);
53444824e7fdSDimitry Andric 
53454824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
53464824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
53474824e7fdSDimitry Andric     return false;
53484824e7fdSDimitry Andric 
53494824e7fdSDimitry Andric   if (!Aggressive)
53504824e7fdSDimitry Andric     return false;
53514824e7fdSDimitry Andric 
53524824e7fdSDimitry Andric   const auto &TLI = *MI.getMF()->getSubtarget().getTargetLowering();
53534824e7fdSDimitry Andric   LLT DstType = MRI.getType(MI.getOperand(0).getReg());
535404eeddc0SDimitry Andric   Register Op1 = MI.getOperand(1).getReg();
535504eeddc0SDimitry Andric   Register Op2 = MI.getOperand(2).getReg();
535604eeddc0SDimitry Andric   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
535704eeddc0SDimitry Andric   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
53584824e7fdSDimitry Andric 
53594824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
53604824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
53614824e7fdSDimitry Andric 
53624824e7fdSDimitry Andric   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
53634824e7fdSDimitry Andric   // prefer to fold the multiply with fewer uses.
536404eeddc0SDimitry Andric   if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
536504eeddc0SDimitry Andric       isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
536604eeddc0SDimitry Andric     if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
53674824e7fdSDimitry Andric       std::swap(LHS, RHS);
53684824e7fdSDimitry Andric   }
53694824e7fdSDimitry Andric 
53704824e7fdSDimitry Andric   // Builds: (fma x, y, (fma (fpext u), (fpext v), z))
53714824e7fdSDimitry Andric   auto buildMatchInfo = [=, &MI](Register U, Register V, Register Z, Register X,
53724824e7fdSDimitry Andric                                  Register Y, MachineIRBuilder &B) {
53734824e7fdSDimitry Andric     Register FpExtU = B.buildFPExt(DstType, U).getReg(0);
53744824e7fdSDimitry Andric     Register FpExtV = B.buildFPExt(DstType, V).getReg(0);
53754824e7fdSDimitry Andric     Register InnerFMA =
53764824e7fdSDimitry Andric         B.buildInstr(PreferredFusedOpcode, {DstType}, {FpExtU, FpExtV, Z})
53774824e7fdSDimitry Andric             .getReg(0);
53784824e7fdSDimitry Andric     B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
53794824e7fdSDimitry Andric                  {X, Y, InnerFMA});
53804824e7fdSDimitry Andric   };
53814824e7fdSDimitry Andric 
53824824e7fdSDimitry Andric   MachineInstr *FMulMI, *FMAMI;
53834824e7fdSDimitry Andric   // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
53844824e7fdSDimitry Andric   //   -> (fma x, y, (fma (fpext u), (fpext v), z))
538504eeddc0SDimitry Andric   if (LHS.MI->getOpcode() == PreferredFusedOpcode &&
538604eeddc0SDimitry Andric       mi_match(LHS.MI->getOperand(3).getReg(), MRI,
538704eeddc0SDimitry Andric                m_GFPExt(m_MInstr(FMulMI))) &&
53884824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
53894824e7fdSDimitry Andric       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
53904824e7fdSDimitry Andric                           MRI.getType(FMulMI->getOperand(0).getReg()))) {
53914824e7fdSDimitry Andric     MatchInfo = [=](MachineIRBuilder &B) {
53924824e7fdSDimitry Andric       buildMatchInfo(FMulMI->getOperand(1).getReg(),
539304eeddc0SDimitry Andric                      FMulMI->getOperand(2).getReg(), RHS.Reg,
539404eeddc0SDimitry Andric                      LHS.MI->getOperand(1).getReg(),
539504eeddc0SDimitry Andric                      LHS.MI->getOperand(2).getReg(), B);
53964824e7fdSDimitry Andric     };
53974824e7fdSDimitry Andric     return true;
53984824e7fdSDimitry Andric   }
53994824e7fdSDimitry Andric 
54004824e7fdSDimitry Andric   // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
54014824e7fdSDimitry Andric   //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
54024824e7fdSDimitry Andric   // FIXME: This turns two single-precision and one double-precision
54034824e7fdSDimitry Andric   // operation into two double-precision operations, which might not be
54044824e7fdSDimitry Andric   // interesting for all targets, especially GPUs.
540504eeddc0SDimitry Andric   if (mi_match(LHS.Reg, MRI, m_GFPExt(m_MInstr(FMAMI))) &&
54064824e7fdSDimitry Andric       FMAMI->getOpcode() == PreferredFusedOpcode) {
54074824e7fdSDimitry Andric     MachineInstr *FMulMI = MRI.getVRegDef(FMAMI->getOperand(3).getReg());
54084824e7fdSDimitry Andric     if (isContractableFMul(*FMulMI, AllowFusionGlobally) &&
54094824e7fdSDimitry Andric         TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
54104824e7fdSDimitry Andric                             MRI.getType(FMAMI->getOperand(0).getReg()))) {
54114824e7fdSDimitry Andric       MatchInfo = [=](MachineIRBuilder &B) {
54124824e7fdSDimitry Andric         Register X = FMAMI->getOperand(1).getReg();
54134824e7fdSDimitry Andric         Register Y = FMAMI->getOperand(2).getReg();
54144824e7fdSDimitry Andric         X = B.buildFPExt(DstType, X).getReg(0);
54154824e7fdSDimitry Andric         Y = B.buildFPExt(DstType, Y).getReg(0);
54164824e7fdSDimitry Andric         buildMatchInfo(FMulMI->getOperand(1).getReg(),
541704eeddc0SDimitry Andric                        FMulMI->getOperand(2).getReg(), RHS.Reg, X, Y, B);
54184824e7fdSDimitry Andric       };
54194824e7fdSDimitry Andric 
54204824e7fdSDimitry Andric       return true;
54214824e7fdSDimitry Andric     }
54224824e7fdSDimitry Andric   }
54234824e7fdSDimitry Andric 
54244824e7fdSDimitry Andric   // fold (fadd z, (fma x, y, (fpext (fmul u, v)))
54254824e7fdSDimitry Andric   //   -> (fma x, y, (fma (fpext u), (fpext v), z))
542604eeddc0SDimitry Andric   if (RHS.MI->getOpcode() == PreferredFusedOpcode &&
542704eeddc0SDimitry Andric       mi_match(RHS.MI->getOperand(3).getReg(), MRI,
542804eeddc0SDimitry Andric                m_GFPExt(m_MInstr(FMulMI))) &&
54294824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
54304824e7fdSDimitry Andric       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
54314824e7fdSDimitry Andric                           MRI.getType(FMulMI->getOperand(0).getReg()))) {
54324824e7fdSDimitry Andric     MatchInfo = [=](MachineIRBuilder &B) {
54334824e7fdSDimitry Andric       buildMatchInfo(FMulMI->getOperand(1).getReg(),
543404eeddc0SDimitry Andric                      FMulMI->getOperand(2).getReg(), LHS.Reg,
543504eeddc0SDimitry Andric                      RHS.MI->getOperand(1).getReg(),
543604eeddc0SDimitry Andric                      RHS.MI->getOperand(2).getReg(), B);
54374824e7fdSDimitry Andric     };
54384824e7fdSDimitry Andric     return true;
54394824e7fdSDimitry Andric   }
54404824e7fdSDimitry Andric 
54414824e7fdSDimitry Andric   // fold (fadd z, (fpext (fma x, y, (fmul u, v)))
54424824e7fdSDimitry Andric   //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
54434824e7fdSDimitry Andric   // FIXME: This turns two single-precision and one double-precision
54444824e7fdSDimitry Andric   // operation into two double-precision operations, which might not be
54454824e7fdSDimitry Andric   // interesting for all targets, especially GPUs.
544604eeddc0SDimitry Andric   if (mi_match(RHS.Reg, MRI, m_GFPExt(m_MInstr(FMAMI))) &&
54474824e7fdSDimitry Andric       FMAMI->getOpcode() == PreferredFusedOpcode) {
54484824e7fdSDimitry Andric     MachineInstr *FMulMI = MRI.getVRegDef(FMAMI->getOperand(3).getReg());
54494824e7fdSDimitry Andric     if (isContractableFMul(*FMulMI, AllowFusionGlobally) &&
54504824e7fdSDimitry Andric         TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
54514824e7fdSDimitry Andric                             MRI.getType(FMAMI->getOperand(0).getReg()))) {
54524824e7fdSDimitry Andric       MatchInfo = [=](MachineIRBuilder &B) {
54534824e7fdSDimitry Andric         Register X = FMAMI->getOperand(1).getReg();
54544824e7fdSDimitry Andric         Register Y = FMAMI->getOperand(2).getReg();
54554824e7fdSDimitry Andric         X = B.buildFPExt(DstType, X).getReg(0);
54564824e7fdSDimitry Andric         Y = B.buildFPExt(DstType, Y).getReg(0);
54574824e7fdSDimitry Andric         buildMatchInfo(FMulMI->getOperand(1).getReg(),
545804eeddc0SDimitry Andric                        FMulMI->getOperand(2).getReg(), LHS.Reg, X, Y, B);
54594824e7fdSDimitry Andric       };
54604824e7fdSDimitry Andric       return true;
54614824e7fdSDimitry Andric     }
54624824e7fdSDimitry Andric   }
54634824e7fdSDimitry Andric 
54644824e7fdSDimitry Andric   return false;
54654824e7fdSDimitry Andric }
54664824e7fdSDimitry Andric 
54674824e7fdSDimitry Andric bool CombinerHelper::matchCombineFSubFMulToFMadOrFMA(
54684824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
54694824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FSUB);
54704824e7fdSDimitry Andric 
54714824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
54724824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
54734824e7fdSDimitry Andric     return false;
54744824e7fdSDimitry Andric 
547504eeddc0SDimitry Andric   Register Op1 = MI.getOperand(1).getReg();
547604eeddc0SDimitry Andric   Register Op2 = MI.getOperand(2).getReg();
547704eeddc0SDimitry Andric   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
547804eeddc0SDimitry Andric   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
54794824e7fdSDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
54804824e7fdSDimitry Andric 
54814824e7fdSDimitry Andric   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
54824824e7fdSDimitry Andric   // prefer to fold the multiply with fewer uses.
54834824e7fdSDimitry Andric   int FirstMulHasFewerUses = true;
548404eeddc0SDimitry Andric   if (isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
548504eeddc0SDimitry Andric       isContractableFMul(*RHS.MI, AllowFusionGlobally) &&
548604eeddc0SDimitry Andric       hasMoreUses(*LHS.MI, *RHS.MI, MRI))
54874824e7fdSDimitry Andric     FirstMulHasFewerUses = false;
54884824e7fdSDimitry Andric 
54894824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
54904824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
54914824e7fdSDimitry Andric 
54924824e7fdSDimitry Andric   // fold (fsub (fmul x, y), z) -> (fma x, y, -z)
54934824e7fdSDimitry Andric   if (FirstMulHasFewerUses &&
549404eeddc0SDimitry Andric       (isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
549504eeddc0SDimitry Andric        (Aggressive || MRI.hasOneNonDBGUse(LHS.Reg)))) {
54964824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
549704eeddc0SDimitry Andric       Register NegZ = B.buildFNeg(DstTy, RHS.Reg).getReg(0);
549804eeddc0SDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
549904eeddc0SDimitry Andric                    {LHS.MI->getOperand(1).getReg(),
550004eeddc0SDimitry Andric                     LHS.MI->getOperand(2).getReg(), NegZ});
55014824e7fdSDimitry Andric     };
55024824e7fdSDimitry Andric     return true;
55034824e7fdSDimitry Andric   }
55044824e7fdSDimitry Andric   // fold (fsub x, (fmul y, z)) -> (fma -y, z, x)
550504eeddc0SDimitry Andric   else if ((isContractableFMul(*RHS.MI, AllowFusionGlobally) &&
550604eeddc0SDimitry Andric             (Aggressive || MRI.hasOneNonDBGUse(RHS.Reg)))) {
55074824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
550804eeddc0SDimitry Andric       Register NegY =
550904eeddc0SDimitry Andric           B.buildFNeg(DstTy, RHS.MI->getOperand(1).getReg()).getReg(0);
551004eeddc0SDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
551104eeddc0SDimitry Andric                    {NegY, RHS.MI->getOperand(2).getReg(), LHS.Reg});
55124824e7fdSDimitry Andric     };
55134824e7fdSDimitry Andric     return true;
55144824e7fdSDimitry Andric   }
55154824e7fdSDimitry Andric 
55164824e7fdSDimitry Andric   return false;
55174824e7fdSDimitry Andric }
55184824e7fdSDimitry Andric 
55194824e7fdSDimitry Andric bool CombinerHelper::matchCombineFSubFNegFMulToFMadOrFMA(
55204824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
55214824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FSUB);
55224824e7fdSDimitry Andric 
55234824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
55244824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
55254824e7fdSDimitry Andric     return false;
55264824e7fdSDimitry Andric 
55274824e7fdSDimitry Andric   Register LHSReg = MI.getOperand(1).getReg();
55284824e7fdSDimitry Andric   Register RHSReg = MI.getOperand(2).getReg();
55294824e7fdSDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
55304824e7fdSDimitry Andric 
55314824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
55324824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
55334824e7fdSDimitry Andric 
55344824e7fdSDimitry Andric   MachineInstr *FMulMI;
55354824e7fdSDimitry Andric   // fold (fsub (fneg (fmul x, y)), z) -> (fma (fneg x), y, (fneg z))
55364824e7fdSDimitry Andric   if (mi_match(LHSReg, MRI, m_GFNeg(m_MInstr(FMulMI))) &&
55374824e7fdSDimitry Andric       (Aggressive || (MRI.hasOneNonDBGUse(LHSReg) &&
55384824e7fdSDimitry Andric                       MRI.hasOneNonDBGUse(FMulMI->getOperand(0).getReg()))) &&
55394824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally)) {
55404824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
55414824e7fdSDimitry Andric       Register NegX =
55424824e7fdSDimitry Andric           B.buildFNeg(DstTy, FMulMI->getOperand(1).getReg()).getReg(0);
55434824e7fdSDimitry Andric       Register NegZ = B.buildFNeg(DstTy, RHSReg).getReg(0);
55444824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
55454824e7fdSDimitry Andric                    {NegX, FMulMI->getOperand(2).getReg(), NegZ});
55464824e7fdSDimitry Andric     };
55474824e7fdSDimitry Andric     return true;
55484824e7fdSDimitry Andric   }
55494824e7fdSDimitry Andric 
55504824e7fdSDimitry Andric   // fold (fsub x, (fneg (fmul, y, z))) -> (fma y, z, x)
55514824e7fdSDimitry Andric   if (mi_match(RHSReg, MRI, m_GFNeg(m_MInstr(FMulMI))) &&
55524824e7fdSDimitry Andric       (Aggressive || (MRI.hasOneNonDBGUse(RHSReg) &&
55534824e7fdSDimitry Andric                       MRI.hasOneNonDBGUse(FMulMI->getOperand(0).getReg()))) &&
55544824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally)) {
55554824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
55564824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
55574824e7fdSDimitry Andric                    {FMulMI->getOperand(1).getReg(),
55584824e7fdSDimitry Andric                     FMulMI->getOperand(2).getReg(), LHSReg});
55594824e7fdSDimitry Andric     };
55604824e7fdSDimitry Andric     return true;
55614824e7fdSDimitry Andric   }
55624824e7fdSDimitry Andric 
55634824e7fdSDimitry Andric   return false;
55644824e7fdSDimitry Andric }
55654824e7fdSDimitry Andric 
55664824e7fdSDimitry Andric bool CombinerHelper::matchCombineFSubFpExtFMulToFMadOrFMA(
55674824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
55684824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FSUB);
55694824e7fdSDimitry Andric 
55704824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
55714824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
55724824e7fdSDimitry Andric     return false;
55734824e7fdSDimitry Andric 
55744824e7fdSDimitry Andric   Register LHSReg = MI.getOperand(1).getReg();
55754824e7fdSDimitry Andric   Register RHSReg = MI.getOperand(2).getReg();
55764824e7fdSDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
55774824e7fdSDimitry Andric 
55784824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
55794824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
55804824e7fdSDimitry Andric 
55814824e7fdSDimitry Andric   MachineInstr *FMulMI;
55824824e7fdSDimitry Andric   // fold (fsub (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), (fneg z))
55834824e7fdSDimitry Andric   if (mi_match(LHSReg, MRI, m_GFPExt(m_MInstr(FMulMI))) &&
55844824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
55854824e7fdSDimitry Andric       (Aggressive || MRI.hasOneNonDBGUse(LHSReg))) {
55864824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
55874824e7fdSDimitry Andric       Register FpExtX =
55884824e7fdSDimitry Andric           B.buildFPExt(DstTy, FMulMI->getOperand(1).getReg()).getReg(0);
55894824e7fdSDimitry Andric       Register FpExtY =
55904824e7fdSDimitry Andric           B.buildFPExt(DstTy, FMulMI->getOperand(2).getReg()).getReg(0);
55914824e7fdSDimitry Andric       Register NegZ = B.buildFNeg(DstTy, RHSReg).getReg(0);
55924824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
55934824e7fdSDimitry Andric                    {FpExtX, FpExtY, NegZ});
55944824e7fdSDimitry Andric     };
55954824e7fdSDimitry Andric     return true;
55964824e7fdSDimitry Andric   }
55974824e7fdSDimitry Andric 
55984824e7fdSDimitry Andric   // fold (fsub x, (fpext (fmul y, z))) -> (fma (fneg (fpext y)), (fpext z), x)
55994824e7fdSDimitry Andric   if (mi_match(RHSReg, MRI, m_GFPExt(m_MInstr(FMulMI))) &&
56004824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
56014824e7fdSDimitry Andric       (Aggressive || MRI.hasOneNonDBGUse(RHSReg))) {
56024824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
56034824e7fdSDimitry Andric       Register FpExtY =
56044824e7fdSDimitry Andric           B.buildFPExt(DstTy, FMulMI->getOperand(1).getReg()).getReg(0);
56054824e7fdSDimitry Andric       Register NegY = B.buildFNeg(DstTy, FpExtY).getReg(0);
56064824e7fdSDimitry Andric       Register FpExtZ =
56074824e7fdSDimitry Andric           B.buildFPExt(DstTy, FMulMI->getOperand(2).getReg()).getReg(0);
56084824e7fdSDimitry Andric       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
56094824e7fdSDimitry Andric                    {NegY, FpExtZ, LHSReg});
56104824e7fdSDimitry Andric     };
56114824e7fdSDimitry Andric     return true;
56124824e7fdSDimitry Andric   }
56134824e7fdSDimitry Andric 
56144824e7fdSDimitry Andric   return false;
56154824e7fdSDimitry Andric }
56164824e7fdSDimitry Andric 
56174824e7fdSDimitry Andric bool CombinerHelper::matchCombineFSubFpExtFNegFMulToFMadOrFMA(
56184824e7fdSDimitry Andric     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
56194824e7fdSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_FSUB);
56204824e7fdSDimitry Andric 
56214824e7fdSDimitry Andric   bool AllowFusionGlobally, HasFMAD, Aggressive;
56224824e7fdSDimitry Andric   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
56234824e7fdSDimitry Andric     return false;
56244824e7fdSDimitry Andric 
56254824e7fdSDimitry Andric   const auto &TLI = *MI.getMF()->getSubtarget().getTargetLowering();
56264824e7fdSDimitry Andric   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
56274824e7fdSDimitry Andric   Register LHSReg = MI.getOperand(1).getReg();
56284824e7fdSDimitry Andric   Register RHSReg = MI.getOperand(2).getReg();
56294824e7fdSDimitry Andric 
56304824e7fdSDimitry Andric   unsigned PreferredFusedOpcode =
56314824e7fdSDimitry Andric       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
56324824e7fdSDimitry Andric 
56334824e7fdSDimitry Andric   auto buildMatchInfo = [=](Register Dst, Register X, Register Y, Register Z,
56344824e7fdSDimitry Andric                             MachineIRBuilder &B) {
56354824e7fdSDimitry Andric     Register FpExtX = B.buildFPExt(DstTy, X).getReg(0);
56364824e7fdSDimitry Andric     Register FpExtY = B.buildFPExt(DstTy, Y).getReg(0);
56374824e7fdSDimitry Andric     B.buildInstr(PreferredFusedOpcode, {Dst}, {FpExtX, FpExtY, Z});
56384824e7fdSDimitry Andric   };
56394824e7fdSDimitry Andric 
56404824e7fdSDimitry Andric   MachineInstr *FMulMI;
56414824e7fdSDimitry Andric   // fold (fsub (fpext (fneg (fmul x, y))), z) ->
56424824e7fdSDimitry Andric   //      (fneg (fma (fpext x), (fpext y), z))
56434824e7fdSDimitry Andric   // fold (fsub (fneg (fpext (fmul x, y))), z) ->
56444824e7fdSDimitry Andric   //      (fneg (fma (fpext x), (fpext y), z))
56454824e7fdSDimitry Andric   if ((mi_match(LHSReg, MRI, m_GFPExt(m_GFNeg(m_MInstr(FMulMI)))) ||
56464824e7fdSDimitry Andric        mi_match(LHSReg, MRI, m_GFNeg(m_GFPExt(m_MInstr(FMulMI))))) &&
56474824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
56484824e7fdSDimitry Andric       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstTy,
56494824e7fdSDimitry Andric                           MRI.getType(FMulMI->getOperand(0).getReg()))) {
56504824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
56514824e7fdSDimitry Andric       Register FMAReg = MRI.createGenericVirtualRegister(DstTy);
56524824e7fdSDimitry Andric       buildMatchInfo(FMAReg, FMulMI->getOperand(1).getReg(),
56534824e7fdSDimitry Andric                      FMulMI->getOperand(2).getReg(), RHSReg, B);
56544824e7fdSDimitry Andric       B.buildFNeg(MI.getOperand(0).getReg(), FMAReg);
56554824e7fdSDimitry Andric     };
56564824e7fdSDimitry Andric     return true;
56574824e7fdSDimitry Andric   }
56584824e7fdSDimitry Andric 
56594824e7fdSDimitry Andric   // fold (fsub x, (fpext (fneg (fmul y, z)))) -> (fma (fpext y), (fpext z), x)
56604824e7fdSDimitry Andric   // fold (fsub x, (fneg (fpext (fmul y, z)))) -> (fma (fpext y), (fpext z), x)
56614824e7fdSDimitry Andric   if ((mi_match(RHSReg, MRI, m_GFPExt(m_GFNeg(m_MInstr(FMulMI)))) ||
56624824e7fdSDimitry Andric        mi_match(RHSReg, MRI, m_GFNeg(m_GFPExt(m_MInstr(FMulMI))))) &&
56634824e7fdSDimitry Andric       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
56644824e7fdSDimitry Andric       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstTy,
56654824e7fdSDimitry Andric                           MRI.getType(FMulMI->getOperand(0).getReg()))) {
56664824e7fdSDimitry Andric     MatchInfo = [=, &MI](MachineIRBuilder &B) {
56674824e7fdSDimitry Andric       buildMatchInfo(MI.getOperand(0).getReg(), FMulMI->getOperand(1).getReg(),
56684824e7fdSDimitry Andric                      FMulMI->getOperand(2).getReg(), LHSReg, B);
56694824e7fdSDimitry Andric     };
56704824e7fdSDimitry Andric     return true;
56714824e7fdSDimitry Andric   }
56724824e7fdSDimitry Andric 
56734824e7fdSDimitry Andric   return false;
56744824e7fdSDimitry Andric }
56754824e7fdSDimitry Andric 
567681ad6265SDimitry Andric bool CombinerHelper::matchSelectToLogical(MachineInstr &MI,
567781ad6265SDimitry Andric                                           BuildFnTy &MatchInfo) {
567881ad6265SDimitry Andric   GSelect &Sel = cast<GSelect>(MI);
567981ad6265SDimitry Andric   Register DstReg = Sel.getReg(0);
568081ad6265SDimitry Andric   Register Cond = Sel.getCondReg();
568181ad6265SDimitry Andric   Register TrueReg = Sel.getTrueReg();
568281ad6265SDimitry Andric   Register FalseReg = Sel.getFalseReg();
568381ad6265SDimitry Andric 
568481ad6265SDimitry Andric   auto *TrueDef = getDefIgnoringCopies(TrueReg, MRI);
568581ad6265SDimitry Andric   auto *FalseDef = getDefIgnoringCopies(FalseReg, MRI);
568681ad6265SDimitry Andric 
568781ad6265SDimitry Andric   const LLT CondTy = MRI.getType(Cond);
568881ad6265SDimitry Andric   const LLT OpTy = MRI.getType(TrueReg);
568981ad6265SDimitry Andric   if (CondTy != OpTy || OpTy.getScalarSizeInBits() != 1)
569081ad6265SDimitry Andric     return false;
569181ad6265SDimitry Andric 
569281ad6265SDimitry Andric   // We have a boolean select.
569381ad6265SDimitry Andric 
569481ad6265SDimitry Andric   // select Cond, Cond, F --> or Cond, F
569581ad6265SDimitry Andric   // select Cond, 1, F    --> or Cond, F
569681ad6265SDimitry Andric   auto MaybeCstTrue = isConstantOrConstantSplatVector(*TrueDef, MRI);
569781ad6265SDimitry Andric   if (Cond == TrueReg || (MaybeCstTrue && MaybeCstTrue->isOne())) {
569881ad6265SDimitry Andric     MatchInfo = [=](MachineIRBuilder &MIB) {
569981ad6265SDimitry Andric       MIB.buildOr(DstReg, Cond, FalseReg);
570081ad6265SDimitry Andric     };
570181ad6265SDimitry Andric     return true;
570281ad6265SDimitry Andric   }
570381ad6265SDimitry Andric 
570481ad6265SDimitry Andric   // select Cond, T, Cond --> and Cond, T
570581ad6265SDimitry Andric   // select Cond, T, 0    --> and Cond, T
570681ad6265SDimitry Andric   auto MaybeCstFalse = isConstantOrConstantSplatVector(*FalseDef, MRI);
570781ad6265SDimitry Andric   if (Cond == FalseReg || (MaybeCstFalse && MaybeCstFalse->isZero())) {
570881ad6265SDimitry Andric     MatchInfo = [=](MachineIRBuilder &MIB) {
570981ad6265SDimitry Andric       MIB.buildAnd(DstReg, Cond, TrueReg);
571081ad6265SDimitry Andric     };
571181ad6265SDimitry Andric     return true;
571281ad6265SDimitry Andric   }
571381ad6265SDimitry Andric 
571481ad6265SDimitry Andric  // select Cond, T, 1 --> or (not Cond), T
571581ad6265SDimitry Andric   if (MaybeCstFalse && MaybeCstFalse->isOne()) {
571681ad6265SDimitry Andric     MatchInfo = [=](MachineIRBuilder &MIB) {
571781ad6265SDimitry Andric       MIB.buildOr(DstReg, MIB.buildNot(OpTy, Cond), TrueReg);
571881ad6265SDimitry Andric     };
571981ad6265SDimitry Andric     return true;
572081ad6265SDimitry Andric   }
572181ad6265SDimitry Andric 
572281ad6265SDimitry Andric   // select Cond, 0, F --> and (not Cond), F
572381ad6265SDimitry Andric   if (MaybeCstTrue && MaybeCstTrue->isZero()) {
572481ad6265SDimitry Andric     MatchInfo = [=](MachineIRBuilder &MIB) {
572581ad6265SDimitry Andric       MIB.buildAnd(DstReg, MIB.buildNot(OpTy, Cond), FalseReg);
572681ad6265SDimitry Andric     };
572781ad6265SDimitry Andric     return true;
572881ad6265SDimitry Andric   }
572981ad6265SDimitry Andric   return false;
573081ad6265SDimitry Andric }
573181ad6265SDimitry Andric 
573281ad6265SDimitry Andric bool CombinerHelper::matchCombineFMinMaxNaN(MachineInstr &MI,
573381ad6265SDimitry Andric                                             unsigned &IdxToPropagate) {
573481ad6265SDimitry Andric   bool PropagateNaN;
573581ad6265SDimitry Andric   switch (MI.getOpcode()) {
573681ad6265SDimitry Andric   default:
573781ad6265SDimitry Andric     return false;
573881ad6265SDimitry Andric   case TargetOpcode::G_FMINNUM:
573981ad6265SDimitry Andric   case TargetOpcode::G_FMAXNUM:
574081ad6265SDimitry Andric     PropagateNaN = false;
574181ad6265SDimitry Andric     break;
574281ad6265SDimitry Andric   case TargetOpcode::G_FMINIMUM:
574381ad6265SDimitry Andric   case TargetOpcode::G_FMAXIMUM:
574481ad6265SDimitry Andric     PropagateNaN = true;
574581ad6265SDimitry Andric     break;
574681ad6265SDimitry Andric   }
574781ad6265SDimitry Andric 
574881ad6265SDimitry Andric   auto MatchNaN = [&](unsigned Idx) {
574981ad6265SDimitry Andric     Register MaybeNaNReg = MI.getOperand(Idx).getReg();
575081ad6265SDimitry Andric     const ConstantFP *MaybeCst = getConstantFPVRegVal(MaybeNaNReg, MRI);
575181ad6265SDimitry Andric     if (!MaybeCst || !MaybeCst->getValueAPF().isNaN())
575281ad6265SDimitry Andric       return false;
575381ad6265SDimitry Andric     IdxToPropagate = PropagateNaN ? Idx : (Idx == 1 ? 2 : 1);
575481ad6265SDimitry Andric     return true;
575581ad6265SDimitry Andric   };
575681ad6265SDimitry Andric 
575781ad6265SDimitry Andric   return MatchNaN(1) || MatchNaN(2);
575881ad6265SDimitry Andric }
575981ad6265SDimitry Andric 
576081ad6265SDimitry Andric bool CombinerHelper::matchAddSubSameReg(MachineInstr &MI, Register &Src) {
576181ad6265SDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ADD && "Expected a G_ADD");
576281ad6265SDimitry Andric   Register LHS = MI.getOperand(1).getReg();
576381ad6265SDimitry Andric   Register RHS = MI.getOperand(2).getReg();
576481ad6265SDimitry Andric 
576581ad6265SDimitry Andric   // Helper lambda to check for opportunities for
576681ad6265SDimitry Andric   // A + (B - A) -> B
576781ad6265SDimitry Andric   // (B - A) + A -> B
576881ad6265SDimitry Andric   auto CheckFold = [&](Register MaybeSub, Register MaybeSameReg) {
576981ad6265SDimitry Andric     Register Reg;
577081ad6265SDimitry Andric     return mi_match(MaybeSub, MRI, m_GSub(m_Reg(Src), m_Reg(Reg))) &&
577181ad6265SDimitry Andric            Reg == MaybeSameReg;
577281ad6265SDimitry Andric   };
577381ad6265SDimitry Andric   return CheckFold(LHS, RHS) || CheckFold(RHS, LHS);
577481ad6265SDimitry Andric }
577581ad6265SDimitry Andric 
5776bdd1243dSDimitry Andric bool CombinerHelper::matchBuildVectorIdentityFold(MachineInstr &MI,
5777bdd1243dSDimitry Andric                                                   Register &MatchInfo) {
5778bdd1243dSDimitry Andric   // This combine folds the following patterns:
5779bdd1243dSDimitry Andric   //
5780bdd1243dSDimitry Andric   //  G_BUILD_VECTOR_TRUNC (G_BITCAST(x), G_LSHR(G_BITCAST(x), k))
5781bdd1243dSDimitry Andric   //  G_BUILD_VECTOR(G_TRUNC(G_BITCAST(x)), G_TRUNC(G_LSHR(G_BITCAST(x), k)))
5782bdd1243dSDimitry Andric   //    into
5783bdd1243dSDimitry Andric   //      x
5784bdd1243dSDimitry Andric   //    if
5785bdd1243dSDimitry Andric   //      k == sizeof(VecEltTy)/2
5786bdd1243dSDimitry Andric   //      type(x) == type(dst)
5787bdd1243dSDimitry Andric   //
5788bdd1243dSDimitry Andric   //  G_BUILD_VECTOR(G_TRUNC(G_BITCAST(x)), undef)
5789bdd1243dSDimitry Andric   //    into
5790bdd1243dSDimitry Andric   //      x
5791bdd1243dSDimitry Andric   //    if
5792bdd1243dSDimitry Andric   //      type(x) == type(dst)
5793bdd1243dSDimitry Andric 
5794bdd1243dSDimitry Andric   LLT DstVecTy = MRI.getType(MI.getOperand(0).getReg());
5795bdd1243dSDimitry Andric   LLT DstEltTy = DstVecTy.getElementType();
5796bdd1243dSDimitry Andric 
5797bdd1243dSDimitry Andric   Register Lo, Hi;
5798bdd1243dSDimitry Andric 
5799bdd1243dSDimitry Andric   if (mi_match(
5800bdd1243dSDimitry Andric           MI, MRI,
5801bdd1243dSDimitry Andric           m_GBuildVector(m_GTrunc(m_GBitcast(m_Reg(Lo))), m_GImplicitDef()))) {
5802bdd1243dSDimitry Andric     MatchInfo = Lo;
5803bdd1243dSDimitry Andric     return MRI.getType(MatchInfo) == DstVecTy;
5804bdd1243dSDimitry Andric   }
5805bdd1243dSDimitry Andric 
5806bdd1243dSDimitry Andric   std::optional<ValueAndVReg> ShiftAmount;
5807bdd1243dSDimitry Andric   const auto LoPattern = m_GBitcast(m_Reg(Lo));
5808bdd1243dSDimitry Andric   const auto HiPattern = m_GLShr(m_GBitcast(m_Reg(Hi)), m_GCst(ShiftAmount));
5809bdd1243dSDimitry Andric   if (mi_match(
5810bdd1243dSDimitry Andric           MI, MRI,
5811bdd1243dSDimitry Andric           m_any_of(m_GBuildVectorTrunc(LoPattern, HiPattern),
5812bdd1243dSDimitry Andric                    m_GBuildVector(m_GTrunc(LoPattern), m_GTrunc(HiPattern))))) {
5813bdd1243dSDimitry Andric     if (Lo == Hi && ShiftAmount->Value == DstEltTy.getSizeInBits()) {
5814bdd1243dSDimitry Andric       MatchInfo = Lo;
5815bdd1243dSDimitry Andric       return MRI.getType(MatchInfo) == DstVecTy;
5816bdd1243dSDimitry Andric     }
5817bdd1243dSDimitry Andric   }
5818bdd1243dSDimitry Andric 
5819bdd1243dSDimitry Andric   return false;
5820bdd1243dSDimitry Andric }
5821bdd1243dSDimitry Andric 
5822bdd1243dSDimitry Andric bool CombinerHelper::matchTruncBuildVectorFold(MachineInstr &MI,
5823bdd1243dSDimitry Andric                                                Register &MatchInfo) {
5824bdd1243dSDimitry Andric   // Replace (G_TRUNC (G_BITCAST (G_BUILD_VECTOR x, y)) with just x
5825bdd1243dSDimitry Andric   // if type(x) == type(G_TRUNC)
5826bdd1243dSDimitry Andric   if (!mi_match(MI.getOperand(1).getReg(), MRI,
5827bdd1243dSDimitry Andric                 m_GBitcast(m_GBuildVector(m_Reg(MatchInfo), m_Reg()))))
5828bdd1243dSDimitry Andric     return false;
5829bdd1243dSDimitry Andric 
5830bdd1243dSDimitry Andric   return MRI.getType(MatchInfo) == MRI.getType(MI.getOperand(0).getReg());
5831bdd1243dSDimitry Andric }
5832bdd1243dSDimitry Andric 
5833bdd1243dSDimitry Andric bool CombinerHelper::matchTruncLshrBuildVectorFold(MachineInstr &MI,
5834bdd1243dSDimitry Andric                                                    Register &MatchInfo) {
5835bdd1243dSDimitry Andric   // Replace (G_TRUNC (G_LSHR (G_BITCAST (G_BUILD_VECTOR x, y)), K)) with
5836bdd1243dSDimitry Andric   //    y if K == size of vector element type
5837bdd1243dSDimitry Andric   std::optional<ValueAndVReg> ShiftAmt;
5838bdd1243dSDimitry Andric   if (!mi_match(MI.getOperand(1).getReg(), MRI,
5839bdd1243dSDimitry Andric                 m_GLShr(m_GBitcast(m_GBuildVector(m_Reg(), m_Reg(MatchInfo))),
5840bdd1243dSDimitry Andric                         m_GCst(ShiftAmt))))
5841bdd1243dSDimitry Andric     return false;
5842bdd1243dSDimitry Andric 
5843bdd1243dSDimitry Andric   LLT MatchTy = MRI.getType(MatchInfo);
5844bdd1243dSDimitry Andric   return ShiftAmt->Value.getZExtValue() == MatchTy.getSizeInBits() &&
5845bdd1243dSDimitry Andric          MatchTy == MRI.getType(MI.getOperand(0).getReg());
5846bdd1243dSDimitry Andric }
5847bdd1243dSDimitry Andric 
5848bdd1243dSDimitry Andric unsigned CombinerHelper::getFPMinMaxOpcForSelect(
5849bdd1243dSDimitry Andric     CmpInst::Predicate Pred, LLT DstTy,
5850bdd1243dSDimitry Andric     SelectPatternNaNBehaviour VsNaNRetVal) const {
5851bdd1243dSDimitry Andric   assert(VsNaNRetVal != SelectPatternNaNBehaviour::NOT_APPLICABLE &&
5852bdd1243dSDimitry Andric          "Expected a NaN behaviour?");
5853bdd1243dSDimitry Andric   // Choose an opcode based off of legality or the behaviour when one of the
5854bdd1243dSDimitry Andric   // LHS/RHS may be NaN.
5855bdd1243dSDimitry Andric   switch (Pred) {
5856bdd1243dSDimitry Andric   default:
5857bdd1243dSDimitry Andric     return 0;
5858bdd1243dSDimitry Andric   case CmpInst::FCMP_UGT:
5859bdd1243dSDimitry Andric   case CmpInst::FCMP_UGE:
5860bdd1243dSDimitry Andric   case CmpInst::FCMP_OGT:
5861bdd1243dSDimitry Andric   case CmpInst::FCMP_OGE:
5862bdd1243dSDimitry Andric     if (VsNaNRetVal == SelectPatternNaNBehaviour::RETURNS_OTHER)
5863bdd1243dSDimitry Andric       return TargetOpcode::G_FMAXNUM;
5864bdd1243dSDimitry Andric     if (VsNaNRetVal == SelectPatternNaNBehaviour::RETURNS_NAN)
5865bdd1243dSDimitry Andric       return TargetOpcode::G_FMAXIMUM;
5866bdd1243dSDimitry Andric     if (isLegal({TargetOpcode::G_FMAXNUM, {DstTy}}))
5867bdd1243dSDimitry Andric       return TargetOpcode::G_FMAXNUM;
5868bdd1243dSDimitry Andric     if (isLegal({TargetOpcode::G_FMAXIMUM, {DstTy}}))
5869bdd1243dSDimitry Andric       return TargetOpcode::G_FMAXIMUM;
5870bdd1243dSDimitry Andric     return 0;
5871bdd1243dSDimitry Andric   case CmpInst::FCMP_ULT:
5872bdd1243dSDimitry Andric   case CmpInst::FCMP_ULE:
5873bdd1243dSDimitry Andric   case CmpInst::FCMP_OLT:
5874bdd1243dSDimitry Andric   case CmpInst::FCMP_OLE:
5875bdd1243dSDimitry Andric     if (VsNaNRetVal == SelectPatternNaNBehaviour::RETURNS_OTHER)
5876bdd1243dSDimitry Andric       return TargetOpcode::G_FMINNUM;
5877bdd1243dSDimitry Andric     if (VsNaNRetVal == SelectPatternNaNBehaviour::RETURNS_NAN)
5878bdd1243dSDimitry Andric       return TargetOpcode::G_FMINIMUM;
5879bdd1243dSDimitry Andric     if (isLegal({TargetOpcode::G_FMINNUM, {DstTy}}))
5880bdd1243dSDimitry Andric       return TargetOpcode::G_FMINNUM;
5881bdd1243dSDimitry Andric     if (!isLegal({TargetOpcode::G_FMINIMUM, {DstTy}}))
5882bdd1243dSDimitry Andric       return 0;
5883bdd1243dSDimitry Andric     return TargetOpcode::G_FMINIMUM;
5884bdd1243dSDimitry Andric   }
5885bdd1243dSDimitry Andric }
5886bdd1243dSDimitry Andric 
5887bdd1243dSDimitry Andric CombinerHelper::SelectPatternNaNBehaviour
5888bdd1243dSDimitry Andric CombinerHelper::computeRetValAgainstNaN(Register LHS, Register RHS,
5889bdd1243dSDimitry Andric                                         bool IsOrderedComparison) const {
5890bdd1243dSDimitry Andric   bool LHSSafe = isKnownNeverNaN(LHS, MRI);
5891bdd1243dSDimitry Andric   bool RHSSafe = isKnownNeverNaN(RHS, MRI);
5892bdd1243dSDimitry Andric   // Completely unsafe.
5893bdd1243dSDimitry Andric   if (!LHSSafe && !RHSSafe)
5894bdd1243dSDimitry Andric     return SelectPatternNaNBehaviour::NOT_APPLICABLE;
5895bdd1243dSDimitry Andric   if (LHSSafe && RHSSafe)
5896bdd1243dSDimitry Andric     return SelectPatternNaNBehaviour::RETURNS_ANY;
5897bdd1243dSDimitry Andric   // An ordered comparison will return false when given a NaN, so it
5898bdd1243dSDimitry Andric   // returns the RHS.
5899bdd1243dSDimitry Andric   if (IsOrderedComparison)
5900bdd1243dSDimitry Andric     return LHSSafe ? SelectPatternNaNBehaviour::RETURNS_NAN
5901bdd1243dSDimitry Andric                    : SelectPatternNaNBehaviour::RETURNS_OTHER;
5902bdd1243dSDimitry Andric   // An unordered comparison will return true when given a NaN, so it
5903bdd1243dSDimitry Andric   // returns the LHS.
5904bdd1243dSDimitry Andric   return LHSSafe ? SelectPatternNaNBehaviour::RETURNS_OTHER
5905bdd1243dSDimitry Andric                  : SelectPatternNaNBehaviour::RETURNS_NAN;
5906bdd1243dSDimitry Andric }
5907bdd1243dSDimitry Andric 
5908bdd1243dSDimitry Andric bool CombinerHelper::matchFPSelectToMinMax(Register Dst, Register Cond,
5909bdd1243dSDimitry Andric                                            Register TrueVal, Register FalseVal,
5910bdd1243dSDimitry Andric                                            BuildFnTy &MatchInfo) {
5911bdd1243dSDimitry Andric   // Match: select (fcmp cond x, y) x, y
5912bdd1243dSDimitry Andric   //        select (fcmp cond x, y) y, x
5913bdd1243dSDimitry Andric   // And turn it into fminnum/fmaxnum or fmin/fmax based off of the condition.
5914bdd1243dSDimitry Andric   LLT DstTy = MRI.getType(Dst);
5915bdd1243dSDimitry Andric   // Bail out early on pointers, since we'll never want to fold to a min/max.
5916bdd1243dSDimitry Andric   if (DstTy.isPointer())
5917bdd1243dSDimitry Andric     return false;
5918bdd1243dSDimitry Andric   // Match a floating point compare with a less-than/greater-than predicate.
5919bdd1243dSDimitry Andric   // TODO: Allow multiple users of the compare if they are all selects.
5920bdd1243dSDimitry Andric   CmpInst::Predicate Pred;
5921bdd1243dSDimitry Andric   Register CmpLHS, CmpRHS;
5922bdd1243dSDimitry Andric   if (!mi_match(Cond, MRI,
5923bdd1243dSDimitry Andric                 m_OneNonDBGUse(
5924bdd1243dSDimitry Andric                     m_GFCmp(m_Pred(Pred), m_Reg(CmpLHS), m_Reg(CmpRHS)))) ||
5925bdd1243dSDimitry Andric       CmpInst::isEquality(Pred))
5926bdd1243dSDimitry Andric     return false;
5927bdd1243dSDimitry Andric   SelectPatternNaNBehaviour ResWithKnownNaNInfo =
5928bdd1243dSDimitry Andric       computeRetValAgainstNaN(CmpLHS, CmpRHS, CmpInst::isOrdered(Pred));
5929bdd1243dSDimitry Andric   if (ResWithKnownNaNInfo == SelectPatternNaNBehaviour::NOT_APPLICABLE)
5930bdd1243dSDimitry Andric     return false;
5931bdd1243dSDimitry Andric   if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
5932bdd1243dSDimitry Andric     std::swap(CmpLHS, CmpRHS);
5933bdd1243dSDimitry Andric     Pred = CmpInst::getSwappedPredicate(Pred);
5934bdd1243dSDimitry Andric     if (ResWithKnownNaNInfo == SelectPatternNaNBehaviour::RETURNS_NAN)
5935bdd1243dSDimitry Andric       ResWithKnownNaNInfo = SelectPatternNaNBehaviour::RETURNS_OTHER;
5936bdd1243dSDimitry Andric     else if (ResWithKnownNaNInfo == SelectPatternNaNBehaviour::RETURNS_OTHER)
5937bdd1243dSDimitry Andric       ResWithKnownNaNInfo = SelectPatternNaNBehaviour::RETURNS_NAN;
5938bdd1243dSDimitry Andric   }
5939bdd1243dSDimitry Andric   if (TrueVal != CmpLHS || FalseVal != CmpRHS)
5940bdd1243dSDimitry Andric     return false;
5941bdd1243dSDimitry Andric   // Decide what type of max/min this should be based off of the predicate.
5942bdd1243dSDimitry Andric   unsigned Opc = getFPMinMaxOpcForSelect(Pred, DstTy, ResWithKnownNaNInfo);
5943bdd1243dSDimitry Andric   if (!Opc || !isLegal({Opc, {DstTy}}))
5944bdd1243dSDimitry Andric     return false;
5945bdd1243dSDimitry Andric   // Comparisons between signed zero and zero may have different results...
5946bdd1243dSDimitry Andric   // unless we have fmaximum/fminimum. In that case, we know -0 < 0.
5947bdd1243dSDimitry Andric   if (Opc != TargetOpcode::G_FMAXIMUM && Opc != TargetOpcode::G_FMINIMUM) {
5948bdd1243dSDimitry Andric     // We don't know if a comparison between two 0s will give us a consistent
5949bdd1243dSDimitry Andric     // result. Be conservative and only proceed if at least one side is
5950bdd1243dSDimitry Andric     // non-zero.
5951bdd1243dSDimitry Andric     auto KnownNonZeroSide = getFConstantVRegValWithLookThrough(CmpLHS, MRI);
5952bdd1243dSDimitry Andric     if (!KnownNonZeroSide || !KnownNonZeroSide->Value.isNonZero()) {
5953bdd1243dSDimitry Andric       KnownNonZeroSide = getFConstantVRegValWithLookThrough(CmpRHS, MRI);
5954bdd1243dSDimitry Andric       if (!KnownNonZeroSide || !KnownNonZeroSide->Value.isNonZero())
5955bdd1243dSDimitry Andric         return false;
5956bdd1243dSDimitry Andric     }
5957bdd1243dSDimitry Andric   }
5958bdd1243dSDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
5959bdd1243dSDimitry Andric     B.buildInstr(Opc, {Dst}, {CmpLHS, CmpRHS});
5960bdd1243dSDimitry Andric   };
5961bdd1243dSDimitry Andric   return true;
5962bdd1243dSDimitry Andric }
5963bdd1243dSDimitry Andric 
5964bdd1243dSDimitry Andric bool CombinerHelper::matchSimplifySelectToMinMax(MachineInstr &MI,
5965bdd1243dSDimitry Andric                                                  BuildFnTy &MatchInfo) {
5966bdd1243dSDimitry Andric   // TODO: Handle integer cases.
5967bdd1243dSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_SELECT);
5968bdd1243dSDimitry Andric   // Condition may be fed by a truncated compare.
5969bdd1243dSDimitry Andric   Register Cond = MI.getOperand(1).getReg();
5970bdd1243dSDimitry Andric   Register MaybeTrunc;
5971bdd1243dSDimitry Andric   if (mi_match(Cond, MRI, m_OneNonDBGUse(m_GTrunc(m_Reg(MaybeTrunc)))))
5972bdd1243dSDimitry Andric     Cond = MaybeTrunc;
5973bdd1243dSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
5974bdd1243dSDimitry Andric   Register TrueVal = MI.getOperand(2).getReg();
5975bdd1243dSDimitry Andric   Register FalseVal = MI.getOperand(3).getReg();
5976bdd1243dSDimitry Andric   return matchFPSelectToMinMax(Dst, Cond, TrueVal, FalseVal, MatchInfo);
5977bdd1243dSDimitry Andric }
5978bdd1243dSDimitry Andric 
5979bdd1243dSDimitry Andric bool CombinerHelper::matchRedundantBinOpInEquality(MachineInstr &MI,
5980bdd1243dSDimitry Andric                                                    BuildFnTy &MatchInfo) {
5981bdd1243dSDimitry Andric   assert(MI.getOpcode() == TargetOpcode::G_ICMP);
5982bdd1243dSDimitry Andric   // (X + Y) == X --> Y == 0
5983bdd1243dSDimitry Andric   // (X + Y) != X --> Y != 0
5984bdd1243dSDimitry Andric   // (X - Y) == X --> Y == 0
5985bdd1243dSDimitry Andric   // (X - Y) != X --> Y != 0
5986bdd1243dSDimitry Andric   // (X ^ Y) == X --> Y == 0
5987bdd1243dSDimitry Andric   // (X ^ Y) != X --> Y != 0
5988bdd1243dSDimitry Andric   Register Dst = MI.getOperand(0).getReg();
5989bdd1243dSDimitry Andric   CmpInst::Predicate Pred;
5990bdd1243dSDimitry Andric   Register X, Y, OpLHS, OpRHS;
5991bdd1243dSDimitry Andric   bool MatchedSub = mi_match(
5992bdd1243dSDimitry Andric       Dst, MRI,
5993bdd1243dSDimitry Andric       m_c_GICmp(m_Pred(Pred), m_Reg(X), m_GSub(m_Reg(OpLHS), m_Reg(Y))));
5994bdd1243dSDimitry Andric   if (MatchedSub && X != OpLHS)
5995bdd1243dSDimitry Andric     return false;
5996bdd1243dSDimitry Andric   if (!MatchedSub) {
5997bdd1243dSDimitry Andric     if (!mi_match(Dst, MRI,
5998bdd1243dSDimitry Andric                   m_c_GICmp(m_Pred(Pred), m_Reg(X),
5999bdd1243dSDimitry Andric                             m_any_of(m_GAdd(m_Reg(OpLHS), m_Reg(OpRHS)),
6000bdd1243dSDimitry Andric                                      m_GXor(m_Reg(OpLHS), m_Reg(OpRHS))))))
6001bdd1243dSDimitry Andric       return false;
6002bdd1243dSDimitry Andric     Y = X == OpLHS ? OpRHS : X == OpRHS ? OpLHS : Register();
6003bdd1243dSDimitry Andric   }
6004bdd1243dSDimitry Andric   MatchInfo = [=](MachineIRBuilder &B) {
6005bdd1243dSDimitry Andric     auto Zero = B.buildConstant(MRI.getType(Y), 0);
6006bdd1243dSDimitry Andric     B.buildICmp(Pred, Dst, Y, Zero);
6007bdd1243dSDimitry Andric   };
6008bdd1243dSDimitry Andric   return CmpInst::isEquality(Pred) && Y.isValid();
6009bdd1243dSDimitry Andric }
6010bdd1243dSDimitry Andric 
6011*06c3fb27SDimitry Andric bool CombinerHelper::matchShiftsTooBig(MachineInstr &MI) {
6012*06c3fb27SDimitry Andric   Register ShiftReg = MI.getOperand(2).getReg();
6013*06c3fb27SDimitry Andric   LLT ResTy = MRI.getType(MI.getOperand(0).getReg());
6014*06c3fb27SDimitry Andric   auto IsShiftTooBig = [&](const Constant *C) {
6015*06c3fb27SDimitry Andric     auto *CI = dyn_cast<ConstantInt>(C);
6016*06c3fb27SDimitry Andric     return CI && CI->uge(ResTy.getScalarSizeInBits());
6017*06c3fb27SDimitry Andric   };
6018*06c3fb27SDimitry Andric   return matchUnaryPredicate(MRI, ShiftReg, IsShiftTooBig);
6019*06c3fb27SDimitry Andric }
6020*06c3fb27SDimitry Andric 
60210b57cec5SDimitry Andric bool CombinerHelper::tryCombine(MachineInstr &MI) {
60220b57cec5SDimitry Andric   if (tryCombineCopy(MI))
60230b57cec5SDimitry Andric     return true;
60248bcb0991SDimitry Andric   if (tryCombineExtendingLoads(MI))
60258bcb0991SDimitry Andric     return true;
60268bcb0991SDimitry Andric   if (tryCombineIndexedLoadStore(MI))
60278bcb0991SDimitry Andric     return true;
60288bcb0991SDimitry Andric   return false;
60290b57cec5SDimitry Andric }
6030