1 //===-- lib/CodeGen/GlobalISel/GICombinerHelper.cpp -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 #include "llvm/CodeGen/GlobalISel/CombinerHelper.h"
9 #include "llvm/ADT/SetVector.h"
10 #include "llvm/ADT/SmallBitVector.h"
11 #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
12 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
13 #include "llvm/CodeGen/GlobalISel/GenericMachineInstrs.h"
14 #include "llvm/CodeGen/GlobalISel/LegalizerHelper.h"
15 #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
16 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
17 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
18 #include "llvm/CodeGen/GlobalISel/Utils.h"
19 #include "llvm/CodeGen/LowLevelType.h"
20 #include "llvm/CodeGen/MachineBasicBlock.h"
21 #include "llvm/CodeGen/MachineDominators.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineMemOperand.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/RegisterBankInfo.h"
26 #include "llvm/CodeGen/TargetInstrInfo.h"
27 #include "llvm/CodeGen/TargetLowering.h"
28 #include "llvm/CodeGen/TargetOpcodes.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/DivisionByConstantInfo.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include <tuple>
35 
36 #define DEBUG_TYPE "gi-combiner"
37 
38 using namespace llvm;
39 using namespace MIPatternMatch;
40 
41 // Option to allow testing of the combiner while no targets know about indexed
42 // addressing.
43 static cl::opt<bool>
44     ForceLegalIndexing("force-legal-indexing", cl::Hidden, cl::init(false),
45                        cl::desc("Force all indexed operations to be "
46                                 "legal for the GlobalISel combiner"));
47 
48 CombinerHelper::CombinerHelper(GISelChangeObserver &Observer,
49                                MachineIRBuilder &B, GISelKnownBits *KB,
50                                MachineDominatorTree *MDT,
51                                const LegalizerInfo *LI)
52     : Builder(B), MRI(Builder.getMF().getRegInfo()), Observer(Observer), KB(KB),
53       MDT(MDT), LI(LI), RBI(Builder.getMF().getSubtarget().getRegBankInfo()),
54       TRI(Builder.getMF().getSubtarget().getRegisterInfo()) {
55   (void)this->KB;
56 }
57 
58 const TargetLowering &CombinerHelper::getTargetLowering() const {
59   return *Builder.getMF().getSubtarget().getTargetLowering();
60 }
61 
62 /// \returns The little endian in-memory byte position of byte \p I in a
63 /// \p ByteWidth bytes wide type.
64 ///
65 /// E.g. Given a 4-byte type x, x[0] -> byte 0
66 static unsigned littleEndianByteAt(const unsigned ByteWidth, const unsigned I) {
67   assert(I < ByteWidth && "I must be in [0, ByteWidth)");
68   return I;
69 }
70 
71 /// Determines the LogBase2 value for a non-null input value using the
72 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
73 static Register buildLogBase2(Register V, MachineIRBuilder &MIB) {
74   auto &MRI = *MIB.getMRI();
75   LLT Ty = MRI.getType(V);
76   auto Ctlz = MIB.buildCTLZ(Ty, V);
77   auto Base = MIB.buildConstant(Ty, Ty.getScalarSizeInBits() - 1);
78   return MIB.buildSub(Ty, Base, Ctlz).getReg(0);
79 }
80 
81 /// \returns The big endian in-memory byte position of byte \p I in a
82 /// \p ByteWidth bytes wide type.
83 ///
84 /// E.g. Given a 4-byte type x, x[0] -> byte 3
85 static unsigned bigEndianByteAt(const unsigned ByteWidth, const unsigned I) {
86   assert(I < ByteWidth && "I must be in [0, ByteWidth)");
87   return ByteWidth - I - 1;
88 }
89 
90 /// Given a map from byte offsets in memory to indices in a load/store,
91 /// determine if that map corresponds to a little or big endian byte pattern.
92 ///
93 /// \param MemOffset2Idx maps memory offsets to address offsets.
94 /// \param LowestIdx is the lowest index in \p MemOffset2Idx.
95 ///
96 /// \returns true if the map corresponds to a big endian byte pattern, false
97 /// if it corresponds to a little endian byte pattern, and None otherwise.
98 ///
99 /// E.g. given a 32-bit type x, and x[AddrOffset], the in-memory byte patterns
100 /// are as follows:
101 ///
102 /// AddrOffset   Little endian    Big endian
103 /// 0            0                3
104 /// 1            1                2
105 /// 2            2                1
106 /// 3            3                0
107 static Optional<bool>
108 isBigEndian(const SmallDenseMap<int64_t, int64_t, 8> &MemOffset2Idx,
109             int64_t LowestIdx) {
110   // Need at least two byte positions to decide on endianness.
111   unsigned Width = MemOffset2Idx.size();
112   if (Width < 2)
113     return None;
114   bool BigEndian = true, LittleEndian = true;
115   for (unsigned MemOffset = 0; MemOffset < Width; ++ MemOffset) {
116     auto MemOffsetAndIdx = MemOffset2Idx.find(MemOffset);
117     if (MemOffsetAndIdx == MemOffset2Idx.end())
118       return None;
119     const int64_t Idx = MemOffsetAndIdx->second - LowestIdx;
120     assert(Idx >= 0 && "Expected non-negative byte offset?");
121     LittleEndian &= Idx == littleEndianByteAt(Width, MemOffset);
122     BigEndian &= Idx == bigEndianByteAt(Width, MemOffset);
123     if (!BigEndian && !LittleEndian)
124       return None;
125   }
126 
127   assert((BigEndian != LittleEndian) &&
128          "Pattern cannot be both big and little endian!");
129   return BigEndian;
130 }
131 
132 bool CombinerHelper::isPreLegalize() const { return !LI; }
133 
134 bool CombinerHelper::isLegal(const LegalityQuery &Query) const {
135   assert(LI && "Must have LegalizerInfo to query isLegal!");
136   return LI->getAction(Query).Action == LegalizeActions::Legal;
137 }
138 
139 bool CombinerHelper::isLegalOrBeforeLegalizer(
140     const LegalityQuery &Query) const {
141   return isPreLegalize() || isLegal(Query);
142 }
143 
144 bool CombinerHelper::isConstantLegalOrBeforeLegalizer(const LLT Ty) const {
145   if (!Ty.isVector())
146     return isLegalOrBeforeLegalizer({TargetOpcode::G_CONSTANT, {Ty}});
147   // Vector constants are represented as a G_BUILD_VECTOR of scalar G_CONSTANTs.
148   if (isPreLegalize())
149     return true;
150   LLT EltTy = Ty.getElementType();
151   return isLegal({TargetOpcode::G_BUILD_VECTOR, {Ty, EltTy}}) &&
152          isLegal({TargetOpcode::G_CONSTANT, {EltTy}});
153 }
154 
155 void CombinerHelper::replaceRegWith(MachineRegisterInfo &MRI, Register FromReg,
156                                     Register ToReg) const {
157   Observer.changingAllUsesOfReg(MRI, FromReg);
158 
159   if (MRI.constrainRegAttrs(ToReg, FromReg))
160     MRI.replaceRegWith(FromReg, ToReg);
161   else
162     Builder.buildCopy(ToReg, FromReg);
163 
164   Observer.finishedChangingAllUsesOfReg();
165 }
166 
167 void CombinerHelper::replaceRegOpWith(MachineRegisterInfo &MRI,
168                                       MachineOperand &FromRegOp,
169                                       Register ToReg) const {
170   assert(FromRegOp.getParent() && "Expected an operand in an MI");
171   Observer.changingInstr(*FromRegOp.getParent());
172 
173   FromRegOp.setReg(ToReg);
174 
175   Observer.changedInstr(*FromRegOp.getParent());
176 }
177 
178 void CombinerHelper::replaceOpcodeWith(MachineInstr &FromMI,
179                                        unsigned ToOpcode) const {
180   Observer.changingInstr(FromMI);
181 
182   FromMI.setDesc(Builder.getTII().get(ToOpcode));
183 
184   Observer.changedInstr(FromMI);
185 }
186 
187 const RegisterBank *CombinerHelper::getRegBank(Register Reg) const {
188   return RBI->getRegBank(Reg, MRI, *TRI);
189 }
190 
191 void CombinerHelper::setRegBank(Register Reg, const RegisterBank *RegBank) {
192   if (RegBank)
193     MRI.setRegBank(Reg, *RegBank);
194 }
195 
196 bool CombinerHelper::tryCombineCopy(MachineInstr &MI) {
197   if (matchCombineCopy(MI)) {
198     applyCombineCopy(MI);
199     return true;
200   }
201   return false;
202 }
203 bool CombinerHelper::matchCombineCopy(MachineInstr &MI) {
204   if (MI.getOpcode() != TargetOpcode::COPY)
205     return false;
206   Register DstReg = MI.getOperand(0).getReg();
207   Register SrcReg = MI.getOperand(1).getReg();
208   return canReplaceReg(DstReg, SrcReg, MRI);
209 }
210 void CombinerHelper::applyCombineCopy(MachineInstr &MI) {
211   Register DstReg = MI.getOperand(0).getReg();
212   Register SrcReg = MI.getOperand(1).getReg();
213   MI.eraseFromParent();
214   replaceRegWith(MRI, DstReg, SrcReg);
215 }
216 
217 bool CombinerHelper::tryCombineConcatVectors(MachineInstr &MI) {
218   bool IsUndef = false;
219   SmallVector<Register, 4> Ops;
220   if (matchCombineConcatVectors(MI, IsUndef, Ops)) {
221     applyCombineConcatVectors(MI, IsUndef, Ops);
222     return true;
223   }
224   return false;
225 }
226 
227 bool CombinerHelper::matchCombineConcatVectors(MachineInstr &MI, bool &IsUndef,
228                                                SmallVectorImpl<Register> &Ops) {
229   assert(MI.getOpcode() == TargetOpcode::G_CONCAT_VECTORS &&
230          "Invalid instruction");
231   IsUndef = true;
232   MachineInstr *Undef = nullptr;
233 
234   // Walk over all the operands of concat vectors and check if they are
235   // build_vector themselves or undef.
236   // Then collect their operands in Ops.
237   for (const MachineOperand &MO : MI.uses()) {
238     Register Reg = MO.getReg();
239     MachineInstr *Def = MRI.getVRegDef(Reg);
240     assert(Def && "Operand not defined");
241     switch (Def->getOpcode()) {
242     case TargetOpcode::G_BUILD_VECTOR:
243       IsUndef = false;
244       // Remember the operands of the build_vector to fold
245       // them into the yet-to-build flattened concat vectors.
246       for (const MachineOperand &BuildVecMO : Def->uses())
247         Ops.push_back(BuildVecMO.getReg());
248       break;
249     case TargetOpcode::G_IMPLICIT_DEF: {
250       LLT OpType = MRI.getType(Reg);
251       // Keep one undef value for all the undef operands.
252       if (!Undef) {
253         Builder.setInsertPt(*MI.getParent(), MI);
254         Undef = Builder.buildUndef(OpType.getScalarType());
255       }
256       assert(MRI.getType(Undef->getOperand(0).getReg()) ==
257                  OpType.getScalarType() &&
258              "All undefs should have the same type");
259       // Break the undef vector in as many scalar elements as needed
260       // for the flattening.
261       for (unsigned EltIdx = 0, EltEnd = OpType.getNumElements();
262            EltIdx != EltEnd; ++EltIdx)
263         Ops.push_back(Undef->getOperand(0).getReg());
264       break;
265     }
266     default:
267       return false;
268     }
269   }
270   return true;
271 }
272 void CombinerHelper::applyCombineConcatVectors(
273     MachineInstr &MI, bool IsUndef, const ArrayRef<Register> Ops) {
274   // We determined that the concat_vectors can be flatten.
275   // Generate the flattened build_vector.
276   Register DstReg = MI.getOperand(0).getReg();
277   Builder.setInsertPt(*MI.getParent(), MI);
278   Register NewDstReg = MRI.cloneVirtualRegister(DstReg);
279 
280   // Note: IsUndef is sort of redundant. We could have determine it by
281   // checking that at all Ops are undef.  Alternatively, we could have
282   // generate a build_vector of undefs and rely on another combine to
283   // clean that up.  For now, given we already gather this information
284   // in tryCombineConcatVectors, just save compile time and issue the
285   // right thing.
286   if (IsUndef)
287     Builder.buildUndef(NewDstReg);
288   else
289     Builder.buildBuildVector(NewDstReg, Ops);
290   MI.eraseFromParent();
291   replaceRegWith(MRI, DstReg, NewDstReg);
292 }
293 
294 bool CombinerHelper::tryCombineShuffleVector(MachineInstr &MI) {
295   SmallVector<Register, 4> Ops;
296   if (matchCombineShuffleVector(MI, Ops)) {
297     applyCombineShuffleVector(MI, Ops);
298     return true;
299   }
300   return false;
301 }
302 
303 bool CombinerHelper::matchCombineShuffleVector(MachineInstr &MI,
304                                                SmallVectorImpl<Register> &Ops) {
305   assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR &&
306          "Invalid instruction kind");
307   LLT DstType = MRI.getType(MI.getOperand(0).getReg());
308   Register Src1 = MI.getOperand(1).getReg();
309   LLT SrcType = MRI.getType(Src1);
310   // As bizarre as it may look, shuffle vector can actually produce
311   // scalar! This is because at the IR level a <1 x ty> shuffle
312   // vector is perfectly valid.
313   unsigned DstNumElts = DstType.isVector() ? DstType.getNumElements() : 1;
314   unsigned SrcNumElts = SrcType.isVector() ? SrcType.getNumElements() : 1;
315 
316   // If the resulting vector is smaller than the size of the source
317   // vectors being concatenated, we won't be able to replace the
318   // shuffle vector into a concat_vectors.
319   //
320   // Note: We may still be able to produce a concat_vectors fed by
321   //       extract_vector_elt and so on. It is less clear that would
322   //       be better though, so don't bother for now.
323   //
324   // If the destination is a scalar, the size of the sources doesn't
325   // matter. we will lower the shuffle to a plain copy. This will
326   // work only if the source and destination have the same size. But
327   // that's covered by the next condition.
328   //
329   // TODO: If the size between the source and destination don't match
330   //       we could still emit an extract vector element in that case.
331   if (DstNumElts < 2 * SrcNumElts && DstNumElts != 1)
332     return false;
333 
334   // Check that the shuffle mask can be broken evenly between the
335   // different sources.
336   if (DstNumElts % SrcNumElts != 0)
337     return false;
338 
339   // Mask length is a multiple of the source vector length.
340   // Check if the shuffle is some kind of concatenation of the input
341   // vectors.
342   unsigned NumConcat = DstNumElts / SrcNumElts;
343   SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
344   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
345   for (unsigned i = 0; i != DstNumElts; ++i) {
346     int Idx = Mask[i];
347     // Undef value.
348     if (Idx < 0)
349       continue;
350     // Ensure the indices in each SrcType sized piece are sequential and that
351     // the same source is used for the whole piece.
352     if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
353         (ConcatSrcs[i / SrcNumElts] >= 0 &&
354          ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts)))
355       return false;
356     // Remember which source this index came from.
357     ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
358   }
359 
360   // The shuffle is concatenating multiple vectors together.
361   // Collect the different operands for that.
362   Register UndefReg;
363   Register Src2 = MI.getOperand(2).getReg();
364   for (auto Src : ConcatSrcs) {
365     if (Src < 0) {
366       if (!UndefReg) {
367         Builder.setInsertPt(*MI.getParent(), MI);
368         UndefReg = Builder.buildUndef(SrcType).getReg(0);
369       }
370       Ops.push_back(UndefReg);
371     } else if (Src == 0)
372       Ops.push_back(Src1);
373     else
374       Ops.push_back(Src2);
375   }
376   return true;
377 }
378 
379 void CombinerHelper::applyCombineShuffleVector(MachineInstr &MI,
380                                                const ArrayRef<Register> Ops) {
381   Register DstReg = MI.getOperand(0).getReg();
382   Builder.setInsertPt(*MI.getParent(), MI);
383   Register NewDstReg = MRI.cloneVirtualRegister(DstReg);
384 
385   if (Ops.size() == 1)
386     Builder.buildCopy(NewDstReg, Ops[0]);
387   else
388     Builder.buildMerge(NewDstReg, Ops);
389 
390   MI.eraseFromParent();
391   replaceRegWith(MRI, DstReg, NewDstReg);
392 }
393 
394 namespace {
395 
396 /// Select a preference between two uses. CurrentUse is the current preference
397 /// while *ForCandidate is attributes of the candidate under consideration.
398 PreferredTuple ChoosePreferredUse(PreferredTuple &CurrentUse,
399                                   const LLT TyForCandidate,
400                                   unsigned OpcodeForCandidate,
401                                   MachineInstr *MIForCandidate) {
402   if (!CurrentUse.Ty.isValid()) {
403     if (CurrentUse.ExtendOpcode == OpcodeForCandidate ||
404         CurrentUse.ExtendOpcode == TargetOpcode::G_ANYEXT)
405       return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
406     return CurrentUse;
407   }
408 
409   // We permit the extend to hoist through basic blocks but this is only
410   // sensible if the target has extending loads. If you end up lowering back
411   // into a load and extend during the legalizer then the end result is
412   // hoisting the extend up to the load.
413 
414   // Prefer defined extensions to undefined extensions as these are more
415   // likely to reduce the number of instructions.
416   if (OpcodeForCandidate == TargetOpcode::G_ANYEXT &&
417       CurrentUse.ExtendOpcode != TargetOpcode::G_ANYEXT)
418     return CurrentUse;
419   else if (CurrentUse.ExtendOpcode == TargetOpcode::G_ANYEXT &&
420            OpcodeForCandidate != TargetOpcode::G_ANYEXT)
421     return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
422 
423   // Prefer sign extensions to zero extensions as sign-extensions tend to be
424   // more expensive.
425   if (CurrentUse.Ty == TyForCandidate) {
426     if (CurrentUse.ExtendOpcode == TargetOpcode::G_SEXT &&
427         OpcodeForCandidate == TargetOpcode::G_ZEXT)
428       return CurrentUse;
429     else if (CurrentUse.ExtendOpcode == TargetOpcode::G_ZEXT &&
430              OpcodeForCandidate == TargetOpcode::G_SEXT)
431       return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
432   }
433 
434   // This is potentially target specific. We've chosen the largest type
435   // because G_TRUNC is usually free. One potential catch with this is that
436   // some targets have a reduced number of larger registers than smaller
437   // registers and this choice potentially increases the live-range for the
438   // larger value.
439   if (TyForCandidate.getSizeInBits() > CurrentUse.Ty.getSizeInBits()) {
440     return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
441   }
442   return CurrentUse;
443 }
444 
445 /// Find a suitable place to insert some instructions and insert them. This
446 /// function accounts for special cases like inserting before a PHI node.
447 /// The current strategy for inserting before PHI's is to duplicate the
448 /// instructions for each predecessor. However, while that's ok for G_TRUNC
449 /// on most targets since it generally requires no code, other targets/cases may
450 /// want to try harder to find a dominating block.
451 static void InsertInsnsWithoutSideEffectsBeforeUse(
452     MachineIRBuilder &Builder, MachineInstr &DefMI, MachineOperand &UseMO,
453     std::function<void(MachineBasicBlock *, MachineBasicBlock::iterator,
454                        MachineOperand &UseMO)>
455         Inserter) {
456   MachineInstr &UseMI = *UseMO.getParent();
457 
458   MachineBasicBlock *InsertBB = UseMI.getParent();
459 
460   // If the use is a PHI then we want the predecessor block instead.
461   if (UseMI.isPHI()) {
462     MachineOperand *PredBB = std::next(&UseMO);
463     InsertBB = PredBB->getMBB();
464   }
465 
466   // If the block is the same block as the def then we want to insert just after
467   // the def instead of at the start of the block.
468   if (InsertBB == DefMI.getParent()) {
469     MachineBasicBlock::iterator InsertPt = &DefMI;
470     Inserter(InsertBB, std::next(InsertPt), UseMO);
471     return;
472   }
473 
474   // Otherwise we want the start of the BB
475   Inserter(InsertBB, InsertBB->getFirstNonPHI(), UseMO);
476 }
477 } // end anonymous namespace
478 
479 bool CombinerHelper::tryCombineExtendingLoads(MachineInstr &MI) {
480   PreferredTuple Preferred;
481   if (matchCombineExtendingLoads(MI, Preferred)) {
482     applyCombineExtendingLoads(MI, Preferred);
483     return true;
484   }
485   return false;
486 }
487 
488 bool CombinerHelper::matchCombineExtendingLoads(MachineInstr &MI,
489                                                 PreferredTuple &Preferred) {
490   // We match the loads and follow the uses to the extend instead of matching
491   // the extends and following the def to the load. This is because the load
492   // must remain in the same position for correctness (unless we also add code
493   // to find a safe place to sink it) whereas the extend is freely movable.
494   // It also prevents us from duplicating the load for the volatile case or just
495   // for performance.
496   GAnyLoad *LoadMI = dyn_cast<GAnyLoad>(&MI);
497   if (!LoadMI)
498     return false;
499 
500   Register LoadReg = LoadMI->getDstReg();
501 
502   LLT LoadValueTy = MRI.getType(LoadReg);
503   if (!LoadValueTy.isScalar())
504     return false;
505 
506   // Most architectures are going to legalize <s8 loads into at least a 1 byte
507   // load, and the MMOs can only describe memory accesses in multiples of bytes.
508   // If we try to perform extload combining on those, we can end up with
509   // %a(s8) = extload %ptr (load 1 byte from %ptr)
510   // ... which is an illegal extload instruction.
511   if (LoadValueTy.getSizeInBits() < 8)
512     return false;
513 
514   // For non power-of-2 types, they will very likely be legalized into multiple
515   // loads. Don't bother trying to match them into extending loads.
516   if (!isPowerOf2_32(LoadValueTy.getSizeInBits()))
517     return false;
518 
519   // Find the preferred type aside from the any-extends (unless it's the only
520   // one) and non-extending ops. We'll emit an extending load to that type and
521   // and emit a variant of (extend (trunc X)) for the others according to the
522   // relative type sizes. At the same time, pick an extend to use based on the
523   // extend involved in the chosen type.
524   unsigned PreferredOpcode =
525       isa<GLoad>(&MI)
526           ? TargetOpcode::G_ANYEXT
527           : isa<GSExtLoad>(&MI) ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
528   Preferred = {LLT(), PreferredOpcode, nullptr};
529   for (auto &UseMI : MRI.use_nodbg_instructions(LoadReg)) {
530     if (UseMI.getOpcode() == TargetOpcode::G_SEXT ||
531         UseMI.getOpcode() == TargetOpcode::G_ZEXT ||
532         (UseMI.getOpcode() == TargetOpcode::G_ANYEXT)) {
533       const auto &MMO = LoadMI->getMMO();
534       // For atomics, only form anyextending loads.
535       if (MMO.isAtomic() && UseMI.getOpcode() != TargetOpcode::G_ANYEXT)
536         continue;
537       // Check for legality.
538       if (LI) {
539         LegalityQuery::MemDesc MMDesc(MMO);
540         LLT UseTy = MRI.getType(UseMI.getOperand(0).getReg());
541         LLT SrcTy = MRI.getType(LoadMI->getPointerReg());
542         if (LI->getAction({LoadMI->getOpcode(), {UseTy, SrcTy}, {MMDesc}})
543                 .Action != LegalizeActions::Legal)
544           continue;
545       }
546       Preferred = ChoosePreferredUse(Preferred,
547                                      MRI.getType(UseMI.getOperand(0).getReg()),
548                                      UseMI.getOpcode(), &UseMI);
549     }
550   }
551 
552   // There were no extends
553   if (!Preferred.MI)
554     return false;
555   // It should be impossible to chose an extend without selecting a different
556   // type since by definition the result of an extend is larger.
557   assert(Preferred.Ty != LoadValueTy && "Extending to same type?");
558 
559   LLVM_DEBUG(dbgs() << "Preferred use is: " << *Preferred.MI);
560   return true;
561 }
562 
563 void CombinerHelper::applyCombineExtendingLoads(MachineInstr &MI,
564                                                 PreferredTuple &Preferred) {
565   // Rewrite the load to the chosen extending load.
566   Register ChosenDstReg = Preferred.MI->getOperand(0).getReg();
567 
568   // Inserter to insert a truncate back to the original type at a given point
569   // with some basic CSE to limit truncate duplication to one per BB.
570   DenseMap<MachineBasicBlock *, MachineInstr *> EmittedInsns;
571   auto InsertTruncAt = [&](MachineBasicBlock *InsertIntoBB,
572                            MachineBasicBlock::iterator InsertBefore,
573                            MachineOperand &UseMO) {
574     MachineInstr *PreviouslyEmitted = EmittedInsns.lookup(InsertIntoBB);
575     if (PreviouslyEmitted) {
576       Observer.changingInstr(*UseMO.getParent());
577       UseMO.setReg(PreviouslyEmitted->getOperand(0).getReg());
578       Observer.changedInstr(*UseMO.getParent());
579       return;
580     }
581 
582     Builder.setInsertPt(*InsertIntoBB, InsertBefore);
583     Register NewDstReg = MRI.cloneVirtualRegister(MI.getOperand(0).getReg());
584     MachineInstr *NewMI = Builder.buildTrunc(NewDstReg, ChosenDstReg);
585     EmittedInsns[InsertIntoBB] = NewMI;
586     replaceRegOpWith(MRI, UseMO, NewDstReg);
587   };
588 
589   Observer.changingInstr(MI);
590   MI.setDesc(
591       Builder.getTII().get(Preferred.ExtendOpcode == TargetOpcode::G_SEXT
592                                ? TargetOpcode::G_SEXTLOAD
593                                : Preferred.ExtendOpcode == TargetOpcode::G_ZEXT
594                                      ? TargetOpcode::G_ZEXTLOAD
595                                      : TargetOpcode::G_LOAD));
596 
597   // Rewrite all the uses to fix up the types.
598   auto &LoadValue = MI.getOperand(0);
599   SmallVector<MachineOperand *, 4> Uses;
600   for (auto &UseMO : MRI.use_operands(LoadValue.getReg()))
601     Uses.push_back(&UseMO);
602 
603   for (auto *UseMO : Uses) {
604     MachineInstr *UseMI = UseMO->getParent();
605 
606     // If the extend is compatible with the preferred extend then we should fix
607     // up the type and extend so that it uses the preferred use.
608     if (UseMI->getOpcode() == Preferred.ExtendOpcode ||
609         UseMI->getOpcode() == TargetOpcode::G_ANYEXT) {
610       Register UseDstReg = UseMI->getOperand(0).getReg();
611       MachineOperand &UseSrcMO = UseMI->getOperand(1);
612       const LLT UseDstTy = MRI.getType(UseDstReg);
613       if (UseDstReg != ChosenDstReg) {
614         if (Preferred.Ty == UseDstTy) {
615           // If the use has the same type as the preferred use, then merge
616           // the vregs and erase the extend. For example:
617           //    %1:_(s8) = G_LOAD ...
618           //    %2:_(s32) = G_SEXT %1(s8)
619           //    %3:_(s32) = G_ANYEXT %1(s8)
620           //    ... = ... %3(s32)
621           // rewrites to:
622           //    %2:_(s32) = G_SEXTLOAD ...
623           //    ... = ... %2(s32)
624           replaceRegWith(MRI, UseDstReg, ChosenDstReg);
625           Observer.erasingInstr(*UseMO->getParent());
626           UseMO->getParent()->eraseFromParent();
627         } else if (Preferred.Ty.getSizeInBits() < UseDstTy.getSizeInBits()) {
628           // If the preferred size is smaller, then keep the extend but extend
629           // from the result of the extending load. For example:
630           //    %1:_(s8) = G_LOAD ...
631           //    %2:_(s32) = G_SEXT %1(s8)
632           //    %3:_(s64) = G_ANYEXT %1(s8)
633           //    ... = ... %3(s64)
634           /// rewrites to:
635           //    %2:_(s32) = G_SEXTLOAD ...
636           //    %3:_(s64) = G_ANYEXT %2:_(s32)
637           //    ... = ... %3(s64)
638           replaceRegOpWith(MRI, UseSrcMO, ChosenDstReg);
639         } else {
640           // If the preferred size is large, then insert a truncate. For
641           // example:
642           //    %1:_(s8) = G_LOAD ...
643           //    %2:_(s64) = G_SEXT %1(s8)
644           //    %3:_(s32) = G_ZEXT %1(s8)
645           //    ... = ... %3(s32)
646           /// rewrites to:
647           //    %2:_(s64) = G_SEXTLOAD ...
648           //    %4:_(s8) = G_TRUNC %2:_(s32)
649           //    %3:_(s64) = G_ZEXT %2:_(s8)
650           //    ... = ... %3(s64)
651           InsertInsnsWithoutSideEffectsBeforeUse(Builder, MI, *UseMO,
652                                                  InsertTruncAt);
653         }
654         continue;
655       }
656       // The use is (one of) the uses of the preferred use we chose earlier.
657       // We're going to update the load to def this value later so just erase
658       // the old extend.
659       Observer.erasingInstr(*UseMO->getParent());
660       UseMO->getParent()->eraseFromParent();
661       continue;
662     }
663 
664     // The use isn't an extend. Truncate back to the type we originally loaded.
665     // This is free on many targets.
666     InsertInsnsWithoutSideEffectsBeforeUse(Builder, MI, *UseMO, InsertTruncAt);
667   }
668 
669   MI.getOperand(0).setReg(ChosenDstReg);
670   Observer.changedInstr(MI);
671 }
672 
673 bool CombinerHelper::matchCombineLoadWithAndMask(MachineInstr &MI,
674                                                  BuildFnTy &MatchInfo) {
675   assert(MI.getOpcode() == TargetOpcode::G_AND);
676 
677   // If we have the following code:
678   //  %mask = G_CONSTANT 255
679   //  %ld   = G_LOAD %ptr, (load s16)
680   //  %and  = G_AND %ld, %mask
681   //
682   // Try to fold it into
683   //   %ld = G_ZEXTLOAD %ptr, (load s8)
684 
685   Register Dst = MI.getOperand(0).getReg();
686   if (MRI.getType(Dst).isVector())
687     return false;
688 
689   auto MaybeMask =
690       getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
691   if (!MaybeMask)
692     return false;
693 
694   APInt MaskVal = MaybeMask->Value;
695 
696   if (!MaskVal.isMask())
697     return false;
698 
699   Register SrcReg = MI.getOperand(1).getReg();
700   GAnyLoad *LoadMI = getOpcodeDef<GAnyLoad>(SrcReg, MRI);
701   if (!LoadMI || !MRI.hasOneNonDBGUse(LoadMI->getDstReg()))
702     return false;
703 
704   Register LoadReg = LoadMI->getDstReg();
705   LLT RegTy = MRI.getType(LoadReg);
706   Register PtrReg = LoadMI->getPointerReg();
707   unsigned RegSize = RegTy.getSizeInBits();
708   uint64_t LoadSizeBits = LoadMI->getMemSizeInBits();
709   unsigned MaskSizeBits = MaskVal.countTrailingOnes();
710 
711   // The mask may not be larger than the in-memory type, as it might cover sign
712   // extended bits
713   if (MaskSizeBits > LoadSizeBits)
714     return false;
715 
716   // If the mask covers the whole destination register, there's nothing to
717   // extend
718   if (MaskSizeBits >= RegSize)
719     return false;
720 
721   // Most targets cannot deal with loads of size < 8 and need to re-legalize to
722   // at least byte loads. Avoid creating such loads here
723   if (MaskSizeBits < 8 || !isPowerOf2_32(MaskSizeBits))
724     return false;
725 
726   const MachineMemOperand &MMO = LoadMI->getMMO();
727   LegalityQuery::MemDesc MemDesc(MMO);
728 
729   // Don't modify the memory access size if this is atomic/volatile, but we can
730   // still adjust the opcode to indicate the high bit behavior.
731   if (LoadMI->isSimple())
732     MemDesc.MemoryTy = LLT::scalar(MaskSizeBits);
733   else if (LoadSizeBits > MaskSizeBits || LoadSizeBits == RegSize)
734     return false;
735 
736   // TODO: Could check if it's legal with the reduced or original memory size.
737   if (!isLegalOrBeforeLegalizer(
738           {TargetOpcode::G_ZEXTLOAD, {RegTy, MRI.getType(PtrReg)}, {MemDesc}}))
739     return false;
740 
741   MatchInfo = [=](MachineIRBuilder &B) {
742     B.setInstrAndDebugLoc(*LoadMI);
743     auto &MF = B.getMF();
744     auto PtrInfo = MMO.getPointerInfo();
745     auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, MemDesc.MemoryTy);
746     B.buildLoadInstr(TargetOpcode::G_ZEXTLOAD, Dst, PtrReg, *NewMMO);
747     LoadMI->eraseFromParent();
748   };
749   return true;
750 }
751 
752 bool CombinerHelper::isPredecessor(const MachineInstr &DefMI,
753                                    const MachineInstr &UseMI) {
754   assert(!DefMI.isDebugInstr() && !UseMI.isDebugInstr() &&
755          "shouldn't consider debug uses");
756   assert(DefMI.getParent() == UseMI.getParent());
757   if (&DefMI == &UseMI)
758     return true;
759   const MachineBasicBlock &MBB = *DefMI.getParent();
760   auto DefOrUse = find_if(MBB, [&DefMI, &UseMI](const MachineInstr &MI) {
761     return &MI == &DefMI || &MI == &UseMI;
762   });
763   if (DefOrUse == MBB.end())
764     llvm_unreachable("Block must contain both DefMI and UseMI!");
765   return &*DefOrUse == &DefMI;
766 }
767 
768 bool CombinerHelper::dominates(const MachineInstr &DefMI,
769                                const MachineInstr &UseMI) {
770   assert(!DefMI.isDebugInstr() && !UseMI.isDebugInstr() &&
771          "shouldn't consider debug uses");
772   if (MDT)
773     return MDT->dominates(&DefMI, &UseMI);
774   else if (DefMI.getParent() != UseMI.getParent())
775     return false;
776 
777   return isPredecessor(DefMI, UseMI);
778 }
779 
780 bool CombinerHelper::matchSextTruncSextLoad(MachineInstr &MI) {
781   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
782   Register SrcReg = MI.getOperand(1).getReg();
783   Register LoadUser = SrcReg;
784 
785   if (MRI.getType(SrcReg).isVector())
786     return false;
787 
788   Register TruncSrc;
789   if (mi_match(SrcReg, MRI, m_GTrunc(m_Reg(TruncSrc))))
790     LoadUser = TruncSrc;
791 
792   uint64_t SizeInBits = MI.getOperand(2).getImm();
793   // If the source is a G_SEXTLOAD from the same bit width, then we don't
794   // need any extend at all, just a truncate.
795   if (auto *LoadMI = getOpcodeDef<GSExtLoad>(LoadUser, MRI)) {
796     // If truncating more than the original extended value, abort.
797     auto LoadSizeBits = LoadMI->getMemSizeInBits();
798     if (TruncSrc && MRI.getType(TruncSrc).getSizeInBits() < LoadSizeBits)
799       return false;
800     if (LoadSizeBits == SizeInBits)
801       return true;
802   }
803   return false;
804 }
805 
806 void CombinerHelper::applySextTruncSextLoad(MachineInstr &MI) {
807   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
808   Builder.setInstrAndDebugLoc(MI);
809   Builder.buildCopy(MI.getOperand(0).getReg(), MI.getOperand(1).getReg());
810   MI.eraseFromParent();
811 }
812 
813 bool CombinerHelper::matchSextInRegOfLoad(
814     MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
815   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
816 
817   Register DstReg = MI.getOperand(0).getReg();
818   LLT RegTy = MRI.getType(DstReg);
819 
820   // Only supports scalars for now.
821   if (RegTy.isVector())
822     return false;
823 
824   Register SrcReg = MI.getOperand(1).getReg();
825   auto *LoadDef = getOpcodeDef<GLoad>(SrcReg, MRI);
826   if (!LoadDef || !MRI.hasOneNonDBGUse(DstReg))
827     return false;
828 
829   uint64_t MemBits = LoadDef->getMemSizeInBits();
830 
831   // If the sign extend extends from a narrower width than the load's width,
832   // then we can narrow the load width when we combine to a G_SEXTLOAD.
833   // Avoid widening the load at all.
834   unsigned NewSizeBits = std::min((uint64_t)MI.getOperand(2).getImm(), MemBits);
835 
836   // Don't generate G_SEXTLOADs with a < 1 byte width.
837   if (NewSizeBits < 8)
838     return false;
839   // Don't bother creating a non-power-2 sextload, it will likely be broken up
840   // anyway for most targets.
841   if (!isPowerOf2_32(NewSizeBits))
842     return false;
843 
844   const MachineMemOperand &MMO = LoadDef->getMMO();
845   LegalityQuery::MemDesc MMDesc(MMO);
846 
847   // Don't modify the memory access size if this is atomic/volatile, but we can
848   // still adjust the opcode to indicate the high bit behavior.
849   if (LoadDef->isSimple())
850     MMDesc.MemoryTy = LLT::scalar(NewSizeBits);
851   else if (MemBits > NewSizeBits || MemBits == RegTy.getSizeInBits())
852     return false;
853 
854   // TODO: Could check if it's legal with the reduced or original memory size.
855   if (!isLegalOrBeforeLegalizer({TargetOpcode::G_SEXTLOAD,
856                                  {MRI.getType(LoadDef->getDstReg()),
857                                   MRI.getType(LoadDef->getPointerReg())},
858                                  {MMDesc}}))
859     return false;
860 
861   MatchInfo = std::make_tuple(LoadDef->getDstReg(), NewSizeBits);
862   return true;
863 }
864 
865 void CombinerHelper::applySextInRegOfLoad(
866     MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
867   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
868   Register LoadReg;
869   unsigned ScalarSizeBits;
870   std::tie(LoadReg, ScalarSizeBits) = MatchInfo;
871   GLoad *LoadDef = cast<GLoad>(MRI.getVRegDef(LoadReg));
872 
873   // If we have the following:
874   // %ld = G_LOAD %ptr, (load 2)
875   // %ext = G_SEXT_INREG %ld, 8
876   //    ==>
877   // %ld = G_SEXTLOAD %ptr (load 1)
878 
879   auto &MMO = LoadDef->getMMO();
880   Builder.setInstrAndDebugLoc(*LoadDef);
881   auto &MF = Builder.getMF();
882   auto PtrInfo = MMO.getPointerInfo();
883   auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, ScalarSizeBits / 8);
884   Builder.buildLoadInstr(TargetOpcode::G_SEXTLOAD, MI.getOperand(0).getReg(),
885                          LoadDef->getPointerReg(), *NewMMO);
886   MI.eraseFromParent();
887 }
888 
889 bool CombinerHelper::findPostIndexCandidate(MachineInstr &MI, Register &Addr,
890                                             Register &Base, Register &Offset) {
891   auto &MF = *MI.getParent()->getParent();
892   const auto &TLI = *MF.getSubtarget().getTargetLowering();
893 
894 #ifndef NDEBUG
895   unsigned Opcode = MI.getOpcode();
896   assert(Opcode == TargetOpcode::G_LOAD || Opcode == TargetOpcode::G_SEXTLOAD ||
897          Opcode == TargetOpcode::G_ZEXTLOAD || Opcode == TargetOpcode::G_STORE);
898 #endif
899 
900   Base = MI.getOperand(1).getReg();
901   MachineInstr *BaseDef = MRI.getUniqueVRegDef(Base);
902   if (BaseDef && BaseDef->getOpcode() == TargetOpcode::G_FRAME_INDEX)
903     return false;
904 
905   LLVM_DEBUG(dbgs() << "Searching for post-indexing opportunity for: " << MI);
906   // FIXME: The following use traversal needs a bail out for patholigical cases.
907   for (auto &Use : MRI.use_nodbg_instructions(Base)) {
908     if (Use.getOpcode() != TargetOpcode::G_PTR_ADD)
909       continue;
910 
911     Offset = Use.getOperand(2).getReg();
912     if (!ForceLegalIndexing &&
913         !TLI.isIndexingLegal(MI, Base, Offset, /*IsPre*/ false, MRI)) {
914       LLVM_DEBUG(dbgs() << "    Ignoring candidate with illegal addrmode: "
915                         << Use);
916       continue;
917     }
918 
919     // Make sure the offset calculation is before the potentially indexed op.
920     // FIXME: we really care about dependency here. The offset calculation might
921     // be movable.
922     MachineInstr *OffsetDef = MRI.getUniqueVRegDef(Offset);
923     if (!OffsetDef || !dominates(*OffsetDef, MI)) {
924       LLVM_DEBUG(dbgs() << "    Ignoring candidate with offset after mem-op: "
925                         << Use);
926       continue;
927     }
928 
929     // FIXME: check whether all uses of Base are load/store with foldable
930     // addressing modes. If so, using the normal addr-modes is better than
931     // forming an indexed one.
932 
933     bool MemOpDominatesAddrUses = true;
934     for (auto &PtrAddUse :
935          MRI.use_nodbg_instructions(Use.getOperand(0).getReg())) {
936       if (!dominates(MI, PtrAddUse)) {
937         MemOpDominatesAddrUses = false;
938         break;
939       }
940     }
941 
942     if (!MemOpDominatesAddrUses) {
943       LLVM_DEBUG(
944           dbgs() << "    Ignoring candidate as memop does not dominate uses: "
945                  << Use);
946       continue;
947     }
948 
949     LLVM_DEBUG(dbgs() << "    Found match: " << Use);
950     Addr = Use.getOperand(0).getReg();
951     return true;
952   }
953 
954   return false;
955 }
956 
957 bool CombinerHelper::findPreIndexCandidate(MachineInstr &MI, Register &Addr,
958                                            Register &Base, Register &Offset) {
959   auto &MF = *MI.getParent()->getParent();
960   const auto &TLI = *MF.getSubtarget().getTargetLowering();
961 
962 #ifndef NDEBUG
963   unsigned Opcode = MI.getOpcode();
964   assert(Opcode == TargetOpcode::G_LOAD || Opcode == TargetOpcode::G_SEXTLOAD ||
965          Opcode == TargetOpcode::G_ZEXTLOAD || Opcode == TargetOpcode::G_STORE);
966 #endif
967 
968   Addr = MI.getOperand(1).getReg();
969   MachineInstr *AddrDef = getOpcodeDef(TargetOpcode::G_PTR_ADD, Addr, MRI);
970   if (!AddrDef || MRI.hasOneNonDBGUse(Addr))
971     return false;
972 
973   Base = AddrDef->getOperand(1).getReg();
974   Offset = AddrDef->getOperand(2).getReg();
975 
976   LLVM_DEBUG(dbgs() << "Found potential pre-indexed load_store: " << MI);
977 
978   if (!ForceLegalIndexing &&
979       !TLI.isIndexingLegal(MI, Base, Offset, /*IsPre*/ true, MRI)) {
980     LLVM_DEBUG(dbgs() << "    Skipping, not legal for target");
981     return false;
982   }
983 
984   MachineInstr *BaseDef = getDefIgnoringCopies(Base, MRI);
985   if (BaseDef->getOpcode() == TargetOpcode::G_FRAME_INDEX) {
986     LLVM_DEBUG(dbgs() << "    Skipping, frame index would need copy anyway.");
987     return false;
988   }
989 
990   if (MI.getOpcode() == TargetOpcode::G_STORE) {
991     // Would require a copy.
992     if (Base == MI.getOperand(0).getReg()) {
993       LLVM_DEBUG(dbgs() << "    Skipping, storing base so need copy anyway.");
994       return false;
995     }
996 
997     // We're expecting one use of Addr in MI, but it could also be the
998     // value stored, which isn't actually dominated by the instruction.
999     if (MI.getOperand(0).getReg() == Addr) {
1000       LLVM_DEBUG(dbgs() << "    Skipping, does not dominate all addr uses");
1001       return false;
1002     }
1003   }
1004 
1005   // FIXME: check whether all uses of the base pointer are constant PtrAdds.
1006   // That might allow us to end base's liveness here by adjusting the constant.
1007 
1008   for (auto &UseMI : MRI.use_nodbg_instructions(Addr)) {
1009     if (!dominates(MI, UseMI)) {
1010       LLVM_DEBUG(dbgs() << "    Skipping, does not dominate all addr uses.");
1011       return false;
1012     }
1013   }
1014 
1015   return true;
1016 }
1017 
1018 bool CombinerHelper::tryCombineIndexedLoadStore(MachineInstr &MI) {
1019   IndexedLoadStoreMatchInfo MatchInfo;
1020   if (matchCombineIndexedLoadStore(MI, MatchInfo)) {
1021     applyCombineIndexedLoadStore(MI, MatchInfo);
1022     return true;
1023   }
1024   return false;
1025 }
1026 
1027 bool CombinerHelper::matchCombineIndexedLoadStore(MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) {
1028   unsigned Opcode = MI.getOpcode();
1029   if (Opcode != TargetOpcode::G_LOAD && Opcode != TargetOpcode::G_SEXTLOAD &&
1030       Opcode != TargetOpcode::G_ZEXTLOAD && Opcode != TargetOpcode::G_STORE)
1031     return false;
1032 
1033   // For now, no targets actually support these opcodes so don't waste time
1034   // running these unless we're forced to for testing.
1035   if (!ForceLegalIndexing)
1036     return false;
1037 
1038   MatchInfo.IsPre = findPreIndexCandidate(MI, MatchInfo.Addr, MatchInfo.Base,
1039                                           MatchInfo.Offset);
1040   if (!MatchInfo.IsPre &&
1041       !findPostIndexCandidate(MI, MatchInfo.Addr, MatchInfo.Base,
1042                               MatchInfo.Offset))
1043     return false;
1044 
1045   return true;
1046 }
1047 
1048 void CombinerHelper::applyCombineIndexedLoadStore(
1049     MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) {
1050   MachineInstr &AddrDef = *MRI.getUniqueVRegDef(MatchInfo.Addr);
1051   MachineIRBuilder MIRBuilder(MI);
1052   unsigned Opcode = MI.getOpcode();
1053   bool IsStore = Opcode == TargetOpcode::G_STORE;
1054   unsigned NewOpcode;
1055   switch (Opcode) {
1056   case TargetOpcode::G_LOAD:
1057     NewOpcode = TargetOpcode::G_INDEXED_LOAD;
1058     break;
1059   case TargetOpcode::G_SEXTLOAD:
1060     NewOpcode = TargetOpcode::G_INDEXED_SEXTLOAD;
1061     break;
1062   case TargetOpcode::G_ZEXTLOAD:
1063     NewOpcode = TargetOpcode::G_INDEXED_ZEXTLOAD;
1064     break;
1065   case TargetOpcode::G_STORE:
1066     NewOpcode = TargetOpcode::G_INDEXED_STORE;
1067     break;
1068   default:
1069     llvm_unreachable("Unknown load/store opcode");
1070   }
1071 
1072   auto MIB = MIRBuilder.buildInstr(NewOpcode);
1073   if (IsStore) {
1074     MIB.addDef(MatchInfo.Addr);
1075     MIB.addUse(MI.getOperand(0).getReg());
1076   } else {
1077     MIB.addDef(MI.getOperand(0).getReg());
1078     MIB.addDef(MatchInfo.Addr);
1079   }
1080 
1081   MIB.addUse(MatchInfo.Base);
1082   MIB.addUse(MatchInfo.Offset);
1083   MIB.addImm(MatchInfo.IsPre);
1084   MI.eraseFromParent();
1085   AddrDef.eraseFromParent();
1086 
1087   LLVM_DEBUG(dbgs() << "    Combinined to indexed operation");
1088 }
1089 
1090 bool CombinerHelper::matchCombineDivRem(MachineInstr &MI,
1091                                         MachineInstr *&OtherMI) {
1092   unsigned Opcode = MI.getOpcode();
1093   bool IsDiv, IsSigned;
1094 
1095   switch (Opcode) {
1096   default:
1097     llvm_unreachable("Unexpected opcode!");
1098   case TargetOpcode::G_SDIV:
1099   case TargetOpcode::G_UDIV: {
1100     IsDiv = true;
1101     IsSigned = Opcode == TargetOpcode::G_SDIV;
1102     break;
1103   }
1104   case TargetOpcode::G_SREM:
1105   case TargetOpcode::G_UREM: {
1106     IsDiv = false;
1107     IsSigned = Opcode == TargetOpcode::G_SREM;
1108     break;
1109   }
1110   }
1111 
1112   Register Src1 = MI.getOperand(1).getReg();
1113   unsigned DivOpcode, RemOpcode, DivremOpcode;
1114   if (IsSigned) {
1115     DivOpcode = TargetOpcode::G_SDIV;
1116     RemOpcode = TargetOpcode::G_SREM;
1117     DivremOpcode = TargetOpcode::G_SDIVREM;
1118   } else {
1119     DivOpcode = TargetOpcode::G_UDIV;
1120     RemOpcode = TargetOpcode::G_UREM;
1121     DivremOpcode = TargetOpcode::G_UDIVREM;
1122   }
1123 
1124   if (!isLegalOrBeforeLegalizer({DivremOpcode, {MRI.getType(Src1)}}))
1125     return false;
1126 
1127   // Combine:
1128   //   %div:_ = G_[SU]DIV %src1:_, %src2:_
1129   //   %rem:_ = G_[SU]REM %src1:_, %src2:_
1130   // into:
1131   //  %div:_, %rem:_ = G_[SU]DIVREM %src1:_, %src2:_
1132 
1133   // Combine:
1134   //   %rem:_ = G_[SU]REM %src1:_, %src2:_
1135   //   %div:_ = G_[SU]DIV %src1:_, %src2:_
1136   // into:
1137   //  %div:_, %rem:_ = G_[SU]DIVREM %src1:_, %src2:_
1138 
1139   for (auto &UseMI : MRI.use_nodbg_instructions(Src1)) {
1140     if (MI.getParent() == UseMI.getParent() &&
1141         ((IsDiv && UseMI.getOpcode() == RemOpcode) ||
1142          (!IsDiv && UseMI.getOpcode() == DivOpcode)) &&
1143         matchEqualDefs(MI.getOperand(2), UseMI.getOperand(2))) {
1144       OtherMI = &UseMI;
1145       return true;
1146     }
1147   }
1148 
1149   return false;
1150 }
1151 
1152 void CombinerHelper::applyCombineDivRem(MachineInstr &MI,
1153                                         MachineInstr *&OtherMI) {
1154   unsigned Opcode = MI.getOpcode();
1155   assert(OtherMI && "OtherMI shouldn't be empty.");
1156 
1157   Register DestDivReg, DestRemReg;
1158   if (Opcode == TargetOpcode::G_SDIV || Opcode == TargetOpcode::G_UDIV) {
1159     DestDivReg = MI.getOperand(0).getReg();
1160     DestRemReg = OtherMI->getOperand(0).getReg();
1161   } else {
1162     DestDivReg = OtherMI->getOperand(0).getReg();
1163     DestRemReg = MI.getOperand(0).getReg();
1164   }
1165 
1166   bool IsSigned =
1167       Opcode == TargetOpcode::G_SDIV || Opcode == TargetOpcode::G_SREM;
1168 
1169   // Check which instruction is first in the block so we don't break def-use
1170   // deps by "moving" the instruction incorrectly.
1171   if (dominates(MI, *OtherMI))
1172     Builder.setInstrAndDebugLoc(MI);
1173   else
1174     Builder.setInstrAndDebugLoc(*OtherMI);
1175 
1176   Builder.buildInstr(IsSigned ? TargetOpcode::G_SDIVREM
1177                               : TargetOpcode::G_UDIVREM,
1178                      {DestDivReg, DestRemReg},
1179                      {MI.getOperand(1).getReg(), MI.getOperand(2).getReg()});
1180   MI.eraseFromParent();
1181   OtherMI->eraseFromParent();
1182 }
1183 
1184 bool CombinerHelper::matchOptBrCondByInvertingCond(MachineInstr &MI,
1185                                                    MachineInstr *&BrCond) {
1186   assert(MI.getOpcode() == TargetOpcode::G_BR);
1187 
1188   // Try to match the following:
1189   // bb1:
1190   //   G_BRCOND %c1, %bb2
1191   //   G_BR %bb3
1192   // bb2:
1193   // ...
1194   // bb3:
1195 
1196   // The above pattern does not have a fall through to the successor bb2, always
1197   // resulting in a branch no matter which path is taken. Here we try to find
1198   // and replace that pattern with conditional branch to bb3 and otherwise
1199   // fallthrough to bb2. This is generally better for branch predictors.
1200 
1201   MachineBasicBlock *MBB = MI.getParent();
1202   MachineBasicBlock::iterator BrIt(MI);
1203   if (BrIt == MBB->begin())
1204     return false;
1205   assert(std::next(BrIt) == MBB->end() && "expected G_BR to be a terminator");
1206 
1207   BrCond = &*std::prev(BrIt);
1208   if (BrCond->getOpcode() != TargetOpcode::G_BRCOND)
1209     return false;
1210 
1211   // Check that the next block is the conditional branch target. Also make sure
1212   // that it isn't the same as the G_BR's target (otherwise, this will loop.)
1213   MachineBasicBlock *BrCondTarget = BrCond->getOperand(1).getMBB();
1214   return BrCondTarget != MI.getOperand(0).getMBB() &&
1215          MBB->isLayoutSuccessor(BrCondTarget);
1216 }
1217 
1218 void CombinerHelper::applyOptBrCondByInvertingCond(MachineInstr &MI,
1219                                                    MachineInstr *&BrCond) {
1220   MachineBasicBlock *BrTarget = MI.getOperand(0).getMBB();
1221   Builder.setInstrAndDebugLoc(*BrCond);
1222   LLT Ty = MRI.getType(BrCond->getOperand(0).getReg());
1223   // FIXME: Does int/fp matter for this? If so, we might need to restrict
1224   // this to i1 only since we might not know for sure what kind of
1225   // compare generated the condition value.
1226   auto True = Builder.buildConstant(
1227       Ty, getICmpTrueVal(getTargetLowering(), false, false));
1228   auto Xor = Builder.buildXor(Ty, BrCond->getOperand(0), True);
1229 
1230   auto *FallthroughBB = BrCond->getOperand(1).getMBB();
1231   Observer.changingInstr(MI);
1232   MI.getOperand(0).setMBB(FallthroughBB);
1233   Observer.changedInstr(MI);
1234 
1235   // Change the conditional branch to use the inverted condition and
1236   // new target block.
1237   Observer.changingInstr(*BrCond);
1238   BrCond->getOperand(0).setReg(Xor.getReg(0));
1239   BrCond->getOperand(1).setMBB(BrTarget);
1240   Observer.changedInstr(*BrCond);
1241 }
1242 
1243 static Type *getTypeForLLT(LLT Ty, LLVMContext &C) {
1244   if (Ty.isVector())
1245     return FixedVectorType::get(IntegerType::get(C, Ty.getScalarSizeInBits()),
1246                                 Ty.getNumElements());
1247   return IntegerType::get(C, Ty.getSizeInBits());
1248 }
1249 
1250 bool CombinerHelper::tryEmitMemcpyInline(MachineInstr &MI) {
1251   MachineIRBuilder HelperBuilder(MI);
1252   GISelObserverWrapper DummyObserver;
1253   LegalizerHelper Helper(HelperBuilder.getMF(), DummyObserver, HelperBuilder);
1254   return Helper.lowerMemcpyInline(MI) ==
1255          LegalizerHelper::LegalizeResult::Legalized;
1256 }
1257 
1258 bool CombinerHelper::tryCombineMemCpyFamily(MachineInstr &MI, unsigned MaxLen) {
1259   MachineIRBuilder HelperBuilder(MI);
1260   GISelObserverWrapper DummyObserver;
1261   LegalizerHelper Helper(HelperBuilder.getMF(), DummyObserver, HelperBuilder);
1262   return Helper.lowerMemCpyFamily(MI, MaxLen) ==
1263          LegalizerHelper::LegalizeResult::Legalized;
1264 }
1265 
1266 static Optional<APFloat> constantFoldFpUnary(unsigned Opcode, LLT DstTy,
1267                                              const Register Op,
1268                                              const MachineRegisterInfo &MRI) {
1269   const ConstantFP *MaybeCst = getConstantFPVRegVal(Op, MRI);
1270   if (!MaybeCst)
1271     return None;
1272 
1273   APFloat V = MaybeCst->getValueAPF();
1274   switch (Opcode) {
1275   default:
1276     llvm_unreachable("Unexpected opcode!");
1277   case TargetOpcode::G_FNEG: {
1278     V.changeSign();
1279     return V;
1280   }
1281   case TargetOpcode::G_FABS: {
1282     V.clearSign();
1283     return V;
1284   }
1285   case TargetOpcode::G_FPTRUNC:
1286     break;
1287   case TargetOpcode::G_FSQRT: {
1288     bool Unused;
1289     V.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &Unused);
1290     V = APFloat(sqrt(V.convertToDouble()));
1291     break;
1292   }
1293   case TargetOpcode::G_FLOG2: {
1294     bool Unused;
1295     V.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &Unused);
1296     V = APFloat(log2(V.convertToDouble()));
1297     break;
1298   }
1299   }
1300   // Convert `APFloat` to appropriate IEEE type depending on `DstTy`. Otherwise,
1301   // `buildFConstant` will assert on size mismatch. Only `G_FPTRUNC`, `G_FSQRT`,
1302   // and `G_FLOG2` reach here.
1303   bool Unused;
1304   V.convert(getFltSemanticForLLT(DstTy), APFloat::rmNearestTiesToEven, &Unused);
1305   return V;
1306 }
1307 
1308 bool CombinerHelper::matchCombineConstantFoldFpUnary(MachineInstr &MI,
1309                                                      Optional<APFloat> &Cst) {
1310   Register DstReg = MI.getOperand(0).getReg();
1311   Register SrcReg = MI.getOperand(1).getReg();
1312   LLT DstTy = MRI.getType(DstReg);
1313   Cst = constantFoldFpUnary(MI.getOpcode(), DstTy, SrcReg, MRI);
1314   return Cst.has_value();
1315 }
1316 
1317 void CombinerHelper::applyCombineConstantFoldFpUnary(MachineInstr &MI,
1318                                                      Optional<APFloat> &Cst) {
1319   assert(Cst && "Optional is unexpectedly empty!");
1320   Builder.setInstrAndDebugLoc(MI);
1321   MachineFunction &MF = Builder.getMF();
1322   auto *FPVal = ConstantFP::get(MF.getFunction().getContext(), *Cst);
1323   Register DstReg = MI.getOperand(0).getReg();
1324   Builder.buildFConstant(DstReg, *FPVal);
1325   MI.eraseFromParent();
1326 }
1327 
1328 bool CombinerHelper::matchPtrAddImmedChain(MachineInstr &MI,
1329                                            PtrAddChain &MatchInfo) {
1330   // We're trying to match the following pattern:
1331   //   %t1 = G_PTR_ADD %base, G_CONSTANT imm1
1332   //   %root = G_PTR_ADD %t1, G_CONSTANT imm2
1333   // -->
1334   //   %root = G_PTR_ADD %base, G_CONSTANT (imm1 + imm2)
1335 
1336   if (MI.getOpcode() != TargetOpcode::G_PTR_ADD)
1337     return false;
1338 
1339   Register Add2 = MI.getOperand(1).getReg();
1340   Register Imm1 = MI.getOperand(2).getReg();
1341   auto MaybeImmVal = getIConstantVRegValWithLookThrough(Imm1, MRI);
1342   if (!MaybeImmVal)
1343     return false;
1344 
1345   MachineInstr *Add2Def = MRI.getVRegDef(Add2);
1346   if (!Add2Def || Add2Def->getOpcode() != TargetOpcode::G_PTR_ADD)
1347     return false;
1348 
1349   Register Base = Add2Def->getOperand(1).getReg();
1350   Register Imm2 = Add2Def->getOperand(2).getReg();
1351   auto MaybeImm2Val = getIConstantVRegValWithLookThrough(Imm2, MRI);
1352   if (!MaybeImm2Val)
1353     return false;
1354 
1355   // Check if the new combined immediate forms an illegal addressing mode.
1356   // Do not combine if it was legal before but would get illegal.
1357   // To do so, we need to find a load/store user of the pointer to get
1358   // the access type.
1359   Type *AccessTy = nullptr;
1360   auto &MF = *MI.getMF();
1361   for (auto &UseMI : MRI.use_nodbg_instructions(MI.getOperand(0).getReg())) {
1362     if (auto *LdSt = dyn_cast<GLoadStore>(&UseMI)) {
1363       AccessTy = getTypeForLLT(MRI.getType(LdSt->getReg(0)),
1364                                MF.getFunction().getContext());
1365       break;
1366     }
1367   }
1368   TargetLoweringBase::AddrMode AMNew;
1369   APInt CombinedImm = MaybeImmVal->Value + MaybeImm2Val->Value;
1370   AMNew.BaseOffs = CombinedImm.getSExtValue();
1371   if (AccessTy) {
1372     AMNew.HasBaseReg = true;
1373     TargetLoweringBase::AddrMode AMOld;
1374     AMOld.BaseOffs = MaybeImm2Val->Value.getSExtValue();
1375     AMOld.HasBaseReg = true;
1376     unsigned AS = MRI.getType(Add2).getAddressSpace();
1377     const auto &TLI = *MF.getSubtarget().getTargetLowering();
1378     if (TLI.isLegalAddressingMode(MF.getDataLayout(), AMOld, AccessTy, AS) &&
1379         !TLI.isLegalAddressingMode(MF.getDataLayout(), AMNew, AccessTy, AS))
1380       return false;
1381   }
1382 
1383   // Pass the combined immediate to the apply function.
1384   MatchInfo.Imm = AMNew.BaseOffs;
1385   MatchInfo.Base = Base;
1386   MatchInfo.Bank = getRegBank(Imm2);
1387   return true;
1388 }
1389 
1390 void CombinerHelper::applyPtrAddImmedChain(MachineInstr &MI,
1391                                            PtrAddChain &MatchInfo) {
1392   assert(MI.getOpcode() == TargetOpcode::G_PTR_ADD && "Expected G_PTR_ADD");
1393   MachineIRBuilder MIB(MI);
1394   LLT OffsetTy = MRI.getType(MI.getOperand(2).getReg());
1395   auto NewOffset = MIB.buildConstant(OffsetTy, MatchInfo.Imm);
1396   setRegBank(NewOffset.getReg(0), MatchInfo.Bank);
1397   Observer.changingInstr(MI);
1398   MI.getOperand(1).setReg(MatchInfo.Base);
1399   MI.getOperand(2).setReg(NewOffset.getReg(0));
1400   Observer.changedInstr(MI);
1401 }
1402 
1403 bool CombinerHelper::matchShiftImmedChain(MachineInstr &MI,
1404                                           RegisterImmPair &MatchInfo) {
1405   // We're trying to match the following pattern with any of
1406   // G_SHL/G_ASHR/G_LSHR/G_SSHLSAT/G_USHLSAT shift instructions:
1407   //   %t1 = SHIFT %base, G_CONSTANT imm1
1408   //   %root = SHIFT %t1, G_CONSTANT imm2
1409   // -->
1410   //   %root = SHIFT %base, G_CONSTANT (imm1 + imm2)
1411 
1412   unsigned Opcode = MI.getOpcode();
1413   assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR ||
1414           Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_SSHLSAT ||
1415           Opcode == TargetOpcode::G_USHLSAT) &&
1416          "Expected G_SHL, G_ASHR, G_LSHR, G_SSHLSAT or G_USHLSAT");
1417 
1418   Register Shl2 = MI.getOperand(1).getReg();
1419   Register Imm1 = MI.getOperand(2).getReg();
1420   auto MaybeImmVal = getIConstantVRegValWithLookThrough(Imm1, MRI);
1421   if (!MaybeImmVal)
1422     return false;
1423 
1424   MachineInstr *Shl2Def = MRI.getUniqueVRegDef(Shl2);
1425   if (Shl2Def->getOpcode() != Opcode)
1426     return false;
1427 
1428   Register Base = Shl2Def->getOperand(1).getReg();
1429   Register Imm2 = Shl2Def->getOperand(2).getReg();
1430   auto MaybeImm2Val = getIConstantVRegValWithLookThrough(Imm2, MRI);
1431   if (!MaybeImm2Val)
1432     return false;
1433 
1434   // Pass the combined immediate to the apply function.
1435   MatchInfo.Imm =
1436       (MaybeImmVal->Value.getSExtValue() + MaybeImm2Val->Value).getSExtValue();
1437   MatchInfo.Reg = Base;
1438 
1439   // There is no simple replacement for a saturating unsigned left shift that
1440   // exceeds the scalar size.
1441   if (Opcode == TargetOpcode::G_USHLSAT &&
1442       MatchInfo.Imm >= MRI.getType(Shl2).getScalarSizeInBits())
1443     return false;
1444 
1445   return true;
1446 }
1447 
1448 void CombinerHelper::applyShiftImmedChain(MachineInstr &MI,
1449                                           RegisterImmPair &MatchInfo) {
1450   unsigned Opcode = MI.getOpcode();
1451   assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR ||
1452           Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_SSHLSAT ||
1453           Opcode == TargetOpcode::G_USHLSAT) &&
1454          "Expected G_SHL, G_ASHR, G_LSHR, G_SSHLSAT or G_USHLSAT");
1455 
1456   Builder.setInstrAndDebugLoc(MI);
1457   LLT Ty = MRI.getType(MI.getOperand(1).getReg());
1458   unsigned const ScalarSizeInBits = Ty.getScalarSizeInBits();
1459   auto Imm = MatchInfo.Imm;
1460 
1461   if (Imm >= ScalarSizeInBits) {
1462     // Any logical shift that exceeds scalar size will produce zero.
1463     if (Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_LSHR) {
1464       Builder.buildConstant(MI.getOperand(0), 0);
1465       MI.eraseFromParent();
1466       return;
1467     }
1468     // Arithmetic shift and saturating signed left shift have no effect beyond
1469     // scalar size.
1470     Imm = ScalarSizeInBits - 1;
1471   }
1472 
1473   LLT ImmTy = MRI.getType(MI.getOperand(2).getReg());
1474   Register NewImm = Builder.buildConstant(ImmTy, Imm).getReg(0);
1475   Observer.changingInstr(MI);
1476   MI.getOperand(1).setReg(MatchInfo.Reg);
1477   MI.getOperand(2).setReg(NewImm);
1478   Observer.changedInstr(MI);
1479 }
1480 
1481 bool CombinerHelper::matchShiftOfShiftedLogic(MachineInstr &MI,
1482                                               ShiftOfShiftedLogic &MatchInfo) {
1483   // We're trying to match the following pattern with any of
1484   // G_SHL/G_ASHR/G_LSHR/G_USHLSAT/G_SSHLSAT shift instructions in combination
1485   // with any of G_AND/G_OR/G_XOR logic instructions.
1486   //   %t1 = SHIFT %X, G_CONSTANT C0
1487   //   %t2 = LOGIC %t1, %Y
1488   //   %root = SHIFT %t2, G_CONSTANT C1
1489   // -->
1490   //   %t3 = SHIFT %X, G_CONSTANT (C0+C1)
1491   //   %t4 = SHIFT %Y, G_CONSTANT C1
1492   //   %root = LOGIC %t3, %t4
1493   unsigned ShiftOpcode = MI.getOpcode();
1494   assert((ShiftOpcode == TargetOpcode::G_SHL ||
1495           ShiftOpcode == TargetOpcode::G_ASHR ||
1496           ShiftOpcode == TargetOpcode::G_LSHR ||
1497           ShiftOpcode == TargetOpcode::G_USHLSAT ||
1498           ShiftOpcode == TargetOpcode::G_SSHLSAT) &&
1499          "Expected G_SHL, G_ASHR, G_LSHR, G_USHLSAT and G_SSHLSAT");
1500 
1501   // Match a one-use bitwise logic op.
1502   Register LogicDest = MI.getOperand(1).getReg();
1503   if (!MRI.hasOneNonDBGUse(LogicDest))
1504     return false;
1505 
1506   MachineInstr *LogicMI = MRI.getUniqueVRegDef(LogicDest);
1507   unsigned LogicOpcode = LogicMI->getOpcode();
1508   if (LogicOpcode != TargetOpcode::G_AND && LogicOpcode != TargetOpcode::G_OR &&
1509       LogicOpcode != TargetOpcode::G_XOR)
1510     return false;
1511 
1512   // Find a matching one-use shift by constant.
1513   const Register C1 = MI.getOperand(2).getReg();
1514   auto MaybeImmVal = getIConstantVRegValWithLookThrough(C1, MRI);
1515   if (!MaybeImmVal)
1516     return false;
1517 
1518   const uint64_t C1Val = MaybeImmVal->Value.getZExtValue();
1519 
1520   auto matchFirstShift = [&](const MachineInstr *MI, uint64_t &ShiftVal) {
1521     // Shift should match previous one and should be a one-use.
1522     if (MI->getOpcode() != ShiftOpcode ||
1523         !MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()))
1524       return false;
1525 
1526     // Must be a constant.
1527     auto MaybeImmVal =
1528         getIConstantVRegValWithLookThrough(MI->getOperand(2).getReg(), MRI);
1529     if (!MaybeImmVal)
1530       return false;
1531 
1532     ShiftVal = MaybeImmVal->Value.getSExtValue();
1533     return true;
1534   };
1535 
1536   // Logic ops are commutative, so check each operand for a match.
1537   Register LogicMIReg1 = LogicMI->getOperand(1).getReg();
1538   MachineInstr *LogicMIOp1 = MRI.getUniqueVRegDef(LogicMIReg1);
1539   Register LogicMIReg2 = LogicMI->getOperand(2).getReg();
1540   MachineInstr *LogicMIOp2 = MRI.getUniqueVRegDef(LogicMIReg2);
1541   uint64_t C0Val;
1542 
1543   if (matchFirstShift(LogicMIOp1, C0Val)) {
1544     MatchInfo.LogicNonShiftReg = LogicMIReg2;
1545     MatchInfo.Shift2 = LogicMIOp1;
1546   } else if (matchFirstShift(LogicMIOp2, C0Val)) {
1547     MatchInfo.LogicNonShiftReg = LogicMIReg1;
1548     MatchInfo.Shift2 = LogicMIOp2;
1549   } else
1550     return false;
1551 
1552   MatchInfo.ValSum = C0Val + C1Val;
1553 
1554   // The fold is not valid if the sum of the shift values exceeds bitwidth.
1555   if (MatchInfo.ValSum >= MRI.getType(LogicDest).getScalarSizeInBits())
1556     return false;
1557 
1558   MatchInfo.Logic = LogicMI;
1559   return true;
1560 }
1561 
1562 void CombinerHelper::applyShiftOfShiftedLogic(MachineInstr &MI,
1563                                               ShiftOfShiftedLogic &MatchInfo) {
1564   unsigned Opcode = MI.getOpcode();
1565   assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR ||
1566           Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_USHLSAT ||
1567           Opcode == TargetOpcode::G_SSHLSAT) &&
1568          "Expected G_SHL, G_ASHR, G_LSHR, G_USHLSAT and G_SSHLSAT");
1569 
1570   LLT ShlType = MRI.getType(MI.getOperand(2).getReg());
1571   LLT DestType = MRI.getType(MI.getOperand(0).getReg());
1572   Builder.setInstrAndDebugLoc(MI);
1573 
1574   Register Const = Builder.buildConstant(ShlType, MatchInfo.ValSum).getReg(0);
1575 
1576   Register Shift1Base = MatchInfo.Shift2->getOperand(1).getReg();
1577   Register Shift1 =
1578       Builder.buildInstr(Opcode, {DestType}, {Shift1Base, Const}).getReg(0);
1579 
1580   Register Shift2Const = MI.getOperand(2).getReg();
1581   Register Shift2 = Builder
1582                         .buildInstr(Opcode, {DestType},
1583                                     {MatchInfo.LogicNonShiftReg, Shift2Const})
1584                         .getReg(0);
1585 
1586   Register Dest = MI.getOperand(0).getReg();
1587   Builder.buildInstr(MatchInfo.Logic->getOpcode(), {Dest}, {Shift1, Shift2});
1588 
1589   // These were one use so it's safe to remove them.
1590   MatchInfo.Shift2->eraseFromParent();
1591   MatchInfo.Logic->eraseFromParent();
1592 
1593   MI.eraseFromParent();
1594 }
1595 
1596 bool CombinerHelper::matchCombineMulToShl(MachineInstr &MI,
1597                                           unsigned &ShiftVal) {
1598   assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL");
1599   auto MaybeImmVal =
1600       getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
1601   if (!MaybeImmVal)
1602     return false;
1603 
1604   ShiftVal = MaybeImmVal->Value.exactLogBase2();
1605   return (static_cast<int32_t>(ShiftVal) != -1);
1606 }
1607 
1608 void CombinerHelper::applyCombineMulToShl(MachineInstr &MI,
1609                                           unsigned &ShiftVal) {
1610   assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL");
1611   MachineIRBuilder MIB(MI);
1612   LLT ShiftTy = MRI.getType(MI.getOperand(0).getReg());
1613   auto ShiftCst = MIB.buildConstant(ShiftTy, ShiftVal);
1614   Observer.changingInstr(MI);
1615   MI.setDesc(MIB.getTII().get(TargetOpcode::G_SHL));
1616   MI.getOperand(2).setReg(ShiftCst.getReg(0));
1617   Observer.changedInstr(MI);
1618 }
1619 
1620 // shl ([sza]ext x), y => zext (shl x, y), if shift does not overflow source
1621 bool CombinerHelper::matchCombineShlOfExtend(MachineInstr &MI,
1622                                              RegisterImmPair &MatchData) {
1623   assert(MI.getOpcode() == TargetOpcode::G_SHL && KB);
1624 
1625   Register LHS = MI.getOperand(1).getReg();
1626 
1627   Register ExtSrc;
1628   if (!mi_match(LHS, MRI, m_GAnyExt(m_Reg(ExtSrc))) &&
1629       !mi_match(LHS, MRI, m_GZExt(m_Reg(ExtSrc))) &&
1630       !mi_match(LHS, MRI, m_GSExt(m_Reg(ExtSrc))))
1631     return false;
1632 
1633   // TODO: Should handle vector splat.
1634   Register RHS = MI.getOperand(2).getReg();
1635   auto MaybeShiftAmtVal = getIConstantVRegValWithLookThrough(RHS, MRI);
1636   if (!MaybeShiftAmtVal)
1637     return false;
1638 
1639   if (LI) {
1640     LLT SrcTy = MRI.getType(ExtSrc);
1641 
1642     // We only really care about the legality with the shifted value. We can
1643     // pick any type the constant shift amount, so ask the target what to
1644     // use. Otherwise we would have to guess and hope it is reported as legal.
1645     LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(SrcTy);
1646     if (!isLegalOrBeforeLegalizer({TargetOpcode::G_SHL, {SrcTy, ShiftAmtTy}}))
1647       return false;
1648   }
1649 
1650   int64_t ShiftAmt = MaybeShiftAmtVal->Value.getSExtValue();
1651   MatchData.Reg = ExtSrc;
1652   MatchData.Imm = ShiftAmt;
1653 
1654   unsigned MinLeadingZeros = KB->getKnownZeroes(ExtSrc).countLeadingOnes();
1655   return MinLeadingZeros >= ShiftAmt;
1656 }
1657 
1658 void CombinerHelper::applyCombineShlOfExtend(MachineInstr &MI,
1659                                              const RegisterImmPair &MatchData) {
1660   Register ExtSrcReg = MatchData.Reg;
1661   int64_t ShiftAmtVal = MatchData.Imm;
1662 
1663   LLT ExtSrcTy = MRI.getType(ExtSrcReg);
1664   Builder.setInstrAndDebugLoc(MI);
1665   auto ShiftAmt = Builder.buildConstant(ExtSrcTy, ShiftAmtVal);
1666   auto NarrowShift =
1667       Builder.buildShl(ExtSrcTy, ExtSrcReg, ShiftAmt, MI.getFlags());
1668   Builder.buildZExt(MI.getOperand(0), NarrowShift);
1669   MI.eraseFromParent();
1670 }
1671 
1672 bool CombinerHelper::matchCombineMergeUnmerge(MachineInstr &MI,
1673                                               Register &MatchInfo) {
1674   GMerge &Merge = cast<GMerge>(MI);
1675   SmallVector<Register, 16> MergedValues;
1676   for (unsigned I = 0; I < Merge.getNumSources(); ++I)
1677     MergedValues.emplace_back(Merge.getSourceReg(I));
1678 
1679   auto *Unmerge = getOpcodeDef<GUnmerge>(MergedValues[0], MRI);
1680   if (!Unmerge || Unmerge->getNumDefs() != Merge.getNumSources())
1681     return false;
1682 
1683   for (unsigned I = 0; I < MergedValues.size(); ++I)
1684     if (MergedValues[I] != Unmerge->getReg(I))
1685       return false;
1686 
1687   MatchInfo = Unmerge->getSourceReg();
1688   return true;
1689 }
1690 
1691 static Register peekThroughBitcast(Register Reg,
1692                                    const MachineRegisterInfo &MRI) {
1693   while (mi_match(Reg, MRI, m_GBitcast(m_Reg(Reg))))
1694     ;
1695 
1696   return Reg;
1697 }
1698 
1699 bool CombinerHelper::matchCombineUnmergeMergeToPlainValues(
1700     MachineInstr &MI, SmallVectorImpl<Register> &Operands) {
1701   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1702          "Expected an unmerge");
1703   auto &Unmerge = cast<GUnmerge>(MI);
1704   Register SrcReg = peekThroughBitcast(Unmerge.getSourceReg(), MRI);
1705 
1706   auto *SrcInstr = getOpcodeDef<GMergeLikeOp>(SrcReg, MRI);
1707   if (!SrcInstr)
1708     return false;
1709 
1710   // Check the source type of the merge.
1711   LLT SrcMergeTy = MRI.getType(SrcInstr->getSourceReg(0));
1712   LLT Dst0Ty = MRI.getType(Unmerge.getReg(0));
1713   bool SameSize = Dst0Ty.getSizeInBits() == SrcMergeTy.getSizeInBits();
1714   if (SrcMergeTy != Dst0Ty && !SameSize)
1715     return false;
1716   // They are the same now (modulo a bitcast).
1717   // We can collect all the src registers.
1718   for (unsigned Idx = 0; Idx < SrcInstr->getNumSources(); ++Idx)
1719     Operands.push_back(SrcInstr->getSourceReg(Idx));
1720   return true;
1721 }
1722 
1723 void CombinerHelper::applyCombineUnmergeMergeToPlainValues(
1724     MachineInstr &MI, SmallVectorImpl<Register> &Operands) {
1725   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1726          "Expected an unmerge");
1727   assert((MI.getNumOperands() - 1 == Operands.size()) &&
1728          "Not enough operands to replace all defs");
1729   unsigned NumElems = MI.getNumOperands() - 1;
1730 
1731   LLT SrcTy = MRI.getType(Operands[0]);
1732   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
1733   bool CanReuseInputDirectly = DstTy == SrcTy;
1734   Builder.setInstrAndDebugLoc(MI);
1735   for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
1736     Register DstReg = MI.getOperand(Idx).getReg();
1737     Register SrcReg = Operands[Idx];
1738     if (CanReuseInputDirectly)
1739       replaceRegWith(MRI, DstReg, SrcReg);
1740     else
1741       Builder.buildCast(DstReg, SrcReg);
1742   }
1743   MI.eraseFromParent();
1744 }
1745 
1746 bool CombinerHelper::matchCombineUnmergeConstant(MachineInstr &MI,
1747                                                  SmallVectorImpl<APInt> &Csts) {
1748   unsigned SrcIdx = MI.getNumOperands() - 1;
1749   Register SrcReg = MI.getOperand(SrcIdx).getReg();
1750   MachineInstr *SrcInstr = MRI.getVRegDef(SrcReg);
1751   if (SrcInstr->getOpcode() != TargetOpcode::G_CONSTANT &&
1752       SrcInstr->getOpcode() != TargetOpcode::G_FCONSTANT)
1753     return false;
1754   // Break down the big constant in smaller ones.
1755   const MachineOperand &CstVal = SrcInstr->getOperand(1);
1756   APInt Val = SrcInstr->getOpcode() == TargetOpcode::G_CONSTANT
1757                   ? CstVal.getCImm()->getValue()
1758                   : CstVal.getFPImm()->getValueAPF().bitcastToAPInt();
1759 
1760   LLT Dst0Ty = MRI.getType(MI.getOperand(0).getReg());
1761   unsigned ShiftAmt = Dst0Ty.getSizeInBits();
1762   // Unmerge a constant.
1763   for (unsigned Idx = 0; Idx != SrcIdx; ++Idx) {
1764     Csts.emplace_back(Val.trunc(ShiftAmt));
1765     Val = Val.lshr(ShiftAmt);
1766   }
1767 
1768   return true;
1769 }
1770 
1771 void CombinerHelper::applyCombineUnmergeConstant(MachineInstr &MI,
1772                                                  SmallVectorImpl<APInt> &Csts) {
1773   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1774          "Expected an unmerge");
1775   assert((MI.getNumOperands() - 1 == Csts.size()) &&
1776          "Not enough operands to replace all defs");
1777   unsigned NumElems = MI.getNumOperands() - 1;
1778   Builder.setInstrAndDebugLoc(MI);
1779   for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
1780     Register DstReg = MI.getOperand(Idx).getReg();
1781     Builder.buildConstant(DstReg, Csts[Idx]);
1782   }
1783 
1784   MI.eraseFromParent();
1785 }
1786 
1787 bool CombinerHelper::matchCombineUnmergeUndef(
1788     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
1789   unsigned SrcIdx = MI.getNumOperands() - 1;
1790   Register SrcReg = MI.getOperand(SrcIdx).getReg();
1791   MatchInfo = [&MI](MachineIRBuilder &B) {
1792     unsigned NumElems = MI.getNumOperands() - 1;
1793     for (unsigned Idx = 0; Idx < NumElems; ++Idx) {
1794       Register DstReg = MI.getOperand(Idx).getReg();
1795       B.buildUndef(DstReg);
1796     }
1797   };
1798   return isa<GImplicitDef>(MRI.getVRegDef(SrcReg));
1799 }
1800 
1801 bool CombinerHelper::matchCombineUnmergeWithDeadLanesToTrunc(MachineInstr &MI) {
1802   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1803          "Expected an unmerge");
1804   // Check that all the lanes are dead except the first one.
1805   for (unsigned Idx = 1, EndIdx = MI.getNumDefs(); Idx != EndIdx; ++Idx) {
1806     if (!MRI.use_nodbg_empty(MI.getOperand(Idx).getReg()))
1807       return false;
1808   }
1809   return true;
1810 }
1811 
1812 void CombinerHelper::applyCombineUnmergeWithDeadLanesToTrunc(MachineInstr &MI) {
1813   Builder.setInstrAndDebugLoc(MI);
1814   Register SrcReg = MI.getOperand(MI.getNumDefs()).getReg();
1815   // Truncating a vector is going to truncate every single lane,
1816   // whereas we want the full lowbits.
1817   // Do the operation on a scalar instead.
1818   LLT SrcTy = MRI.getType(SrcReg);
1819   if (SrcTy.isVector())
1820     SrcReg =
1821         Builder.buildCast(LLT::scalar(SrcTy.getSizeInBits()), SrcReg).getReg(0);
1822 
1823   Register Dst0Reg = MI.getOperand(0).getReg();
1824   LLT Dst0Ty = MRI.getType(Dst0Reg);
1825   if (Dst0Ty.isVector()) {
1826     auto MIB = Builder.buildTrunc(LLT::scalar(Dst0Ty.getSizeInBits()), SrcReg);
1827     Builder.buildCast(Dst0Reg, MIB);
1828   } else
1829     Builder.buildTrunc(Dst0Reg, SrcReg);
1830   MI.eraseFromParent();
1831 }
1832 
1833 bool CombinerHelper::matchCombineUnmergeZExtToZExt(MachineInstr &MI) {
1834   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1835          "Expected an unmerge");
1836   Register Dst0Reg = MI.getOperand(0).getReg();
1837   LLT Dst0Ty = MRI.getType(Dst0Reg);
1838   // G_ZEXT on vector applies to each lane, so it will
1839   // affect all destinations. Therefore we won't be able
1840   // to simplify the unmerge to just the first definition.
1841   if (Dst0Ty.isVector())
1842     return false;
1843   Register SrcReg = MI.getOperand(MI.getNumDefs()).getReg();
1844   LLT SrcTy = MRI.getType(SrcReg);
1845   if (SrcTy.isVector())
1846     return false;
1847 
1848   Register ZExtSrcReg;
1849   if (!mi_match(SrcReg, MRI, m_GZExt(m_Reg(ZExtSrcReg))))
1850     return false;
1851 
1852   // Finally we can replace the first definition with
1853   // a zext of the source if the definition is big enough to hold
1854   // all of ZExtSrc bits.
1855   LLT ZExtSrcTy = MRI.getType(ZExtSrcReg);
1856   return ZExtSrcTy.getSizeInBits() <= Dst0Ty.getSizeInBits();
1857 }
1858 
1859 void CombinerHelper::applyCombineUnmergeZExtToZExt(MachineInstr &MI) {
1860   assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
1861          "Expected an unmerge");
1862 
1863   Register Dst0Reg = MI.getOperand(0).getReg();
1864 
1865   MachineInstr *ZExtInstr =
1866       MRI.getVRegDef(MI.getOperand(MI.getNumDefs()).getReg());
1867   assert(ZExtInstr && ZExtInstr->getOpcode() == TargetOpcode::G_ZEXT &&
1868          "Expecting a G_ZEXT");
1869 
1870   Register ZExtSrcReg = ZExtInstr->getOperand(1).getReg();
1871   LLT Dst0Ty = MRI.getType(Dst0Reg);
1872   LLT ZExtSrcTy = MRI.getType(ZExtSrcReg);
1873 
1874   Builder.setInstrAndDebugLoc(MI);
1875 
1876   if (Dst0Ty.getSizeInBits() > ZExtSrcTy.getSizeInBits()) {
1877     Builder.buildZExt(Dst0Reg, ZExtSrcReg);
1878   } else {
1879     assert(Dst0Ty.getSizeInBits() == ZExtSrcTy.getSizeInBits() &&
1880            "ZExt src doesn't fit in destination");
1881     replaceRegWith(MRI, Dst0Reg, ZExtSrcReg);
1882   }
1883 
1884   Register ZeroReg;
1885   for (unsigned Idx = 1, EndIdx = MI.getNumDefs(); Idx != EndIdx; ++Idx) {
1886     if (!ZeroReg)
1887       ZeroReg = Builder.buildConstant(Dst0Ty, 0).getReg(0);
1888     replaceRegWith(MRI, MI.getOperand(Idx).getReg(), ZeroReg);
1889   }
1890   MI.eraseFromParent();
1891 }
1892 
1893 bool CombinerHelper::matchCombineShiftToUnmerge(MachineInstr &MI,
1894                                                 unsigned TargetShiftSize,
1895                                                 unsigned &ShiftVal) {
1896   assert((MI.getOpcode() == TargetOpcode::G_SHL ||
1897           MI.getOpcode() == TargetOpcode::G_LSHR ||
1898           MI.getOpcode() == TargetOpcode::G_ASHR) && "Expected a shift");
1899 
1900   LLT Ty = MRI.getType(MI.getOperand(0).getReg());
1901   if (Ty.isVector()) // TODO:
1902     return false;
1903 
1904   // Don't narrow further than the requested size.
1905   unsigned Size = Ty.getSizeInBits();
1906   if (Size <= TargetShiftSize)
1907     return false;
1908 
1909   auto MaybeImmVal =
1910       getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
1911   if (!MaybeImmVal)
1912     return false;
1913 
1914   ShiftVal = MaybeImmVal->Value.getSExtValue();
1915   return ShiftVal >= Size / 2 && ShiftVal < Size;
1916 }
1917 
1918 void CombinerHelper::applyCombineShiftToUnmerge(MachineInstr &MI,
1919                                                 const unsigned &ShiftVal) {
1920   Register DstReg = MI.getOperand(0).getReg();
1921   Register SrcReg = MI.getOperand(1).getReg();
1922   LLT Ty = MRI.getType(SrcReg);
1923   unsigned Size = Ty.getSizeInBits();
1924   unsigned HalfSize = Size / 2;
1925   assert(ShiftVal >= HalfSize);
1926 
1927   LLT HalfTy = LLT::scalar(HalfSize);
1928 
1929   Builder.setInstr(MI);
1930   auto Unmerge = Builder.buildUnmerge(HalfTy, SrcReg);
1931   unsigned NarrowShiftAmt = ShiftVal - HalfSize;
1932 
1933   if (MI.getOpcode() == TargetOpcode::G_LSHR) {
1934     Register Narrowed = Unmerge.getReg(1);
1935 
1936     //  dst = G_LSHR s64:x, C for C >= 32
1937     // =>
1938     //   lo, hi = G_UNMERGE_VALUES x
1939     //   dst = G_MERGE_VALUES (G_LSHR hi, C - 32), 0
1940 
1941     if (NarrowShiftAmt != 0) {
1942       Narrowed = Builder.buildLShr(HalfTy, Narrowed,
1943         Builder.buildConstant(HalfTy, NarrowShiftAmt)).getReg(0);
1944     }
1945 
1946     auto Zero = Builder.buildConstant(HalfTy, 0);
1947     Builder.buildMerge(DstReg, { Narrowed, Zero });
1948   } else if (MI.getOpcode() == TargetOpcode::G_SHL) {
1949     Register Narrowed = Unmerge.getReg(0);
1950     //  dst = G_SHL s64:x, C for C >= 32
1951     // =>
1952     //   lo, hi = G_UNMERGE_VALUES x
1953     //   dst = G_MERGE_VALUES 0, (G_SHL hi, C - 32)
1954     if (NarrowShiftAmt != 0) {
1955       Narrowed = Builder.buildShl(HalfTy, Narrowed,
1956         Builder.buildConstant(HalfTy, NarrowShiftAmt)).getReg(0);
1957     }
1958 
1959     auto Zero = Builder.buildConstant(HalfTy, 0);
1960     Builder.buildMerge(DstReg, { Zero, Narrowed });
1961   } else {
1962     assert(MI.getOpcode() == TargetOpcode::G_ASHR);
1963     auto Hi = Builder.buildAShr(
1964       HalfTy, Unmerge.getReg(1),
1965       Builder.buildConstant(HalfTy, HalfSize - 1));
1966 
1967     if (ShiftVal == HalfSize) {
1968       // (G_ASHR i64:x, 32) ->
1969       //   G_MERGE_VALUES hi_32(x), (G_ASHR hi_32(x), 31)
1970       Builder.buildMerge(DstReg, { Unmerge.getReg(1), Hi });
1971     } else if (ShiftVal == Size - 1) {
1972       // Don't need a second shift.
1973       // (G_ASHR i64:x, 63) ->
1974       //   %narrowed = (G_ASHR hi_32(x), 31)
1975       //   G_MERGE_VALUES %narrowed, %narrowed
1976       Builder.buildMerge(DstReg, { Hi, Hi });
1977     } else {
1978       auto Lo = Builder.buildAShr(
1979         HalfTy, Unmerge.getReg(1),
1980         Builder.buildConstant(HalfTy, ShiftVal - HalfSize));
1981 
1982       // (G_ASHR i64:x, C) ->, for C >= 32
1983       //   G_MERGE_VALUES (G_ASHR hi_32(x), C - 32), (G_ASHR hi_32(x), 31)
1984       Builder.buildMerge(DstReg, { Lo, Hi });
1985     }
1986   }
1987 
1988   MI.eraseFromParent();
1989 }
1990 
1991 bool CombinerHelper::tryCombineShiftToUnmerge(MachineInstr &MI,
1992                                               unsigned TargetShiftAmount) {
1993   unsigned ShiftAmt;
1994   if (matchCombineShiftToUnmerge(MI, TargetShiftAmount, ShiftAmt)) {
1995     applyCombineShiftToUnmerge(MI, ShiftAmt);
1996     return true;
1997   }
1998 
1999   return false;
2000 }
2001 
2002 bool CombinerHelper::matchCombineI2PToP2I(MachineInstr &MI, Register &Reg) {
2003   assert(MI.getOpcode() == TargetOpcode::G_INTTOPTR && "Expected a G_INTTOPTR");
2004   Register DstReg = MI.getOperand(0).getReg();
2005   LLT DstTy = MRI.getType(DstReg);
2006   Register SrcReg = MI.getOperand(1).getReg();
2007   return mi_match(SrcReg, MRI,
2008                   m_GPtrToInt(m_all_of(m_SpecificType(DstTy), m_Reg(Reg))));
2009 }
2010 
2011 void CombinerHelper::applyCombineI2PToP2I(MachineInstr &MI, Register &Reg) {
2012   assert(MI.getOpcode() == TargetOpcode::G_INTTOPTR && "Expected a G_INTTOPTR");
2013   Register DstReg = MI.getOperand(0).getReg();
2014   Builder.setInstr(MI);
2015   Builder.buildCopy(DstReg, Reg);
2016   MI.eraseFromParent();
2017 }
2018 
2019 bool CombinerHelper::matchCombineP2IToI2P(MachineInstr &MI, Register &Reg) {
2020   assert(MI.getOpcode() == TargetOpcode::G_PTRTOINT && "Expected a G_PTRTOINT");
2021   Register SrcReg = MI.getOperand(1).getReg();
2022   return mi_match(SrcReg, MRI, m_GIntToPtr(m_Reg(Reg)));
2023 }
2024 
2025 void CombinerHelper::applyCombineP2IToI2P(MachineInstr &MI, Register &Reg) {
2026   assert(MI.getOpcode() == TargetOpcode::G_PTRTOINT && "Expected a G_PTRTOINT");
2027   Register DstReg = MI.getOperand(0).getReg();
2028   Builder.setInstr(MI);
2029   Builder.buildZExtOrTrunc(DstReg, Reg);
2030   MI.eraseFromParent();
2031 }
2032 
2033 bool CombinerHelper::matchCombineAddP2IToPtrAdd(
2034     MachineInstr &MI, std::pair<Register, bool> &PtrReg) {
2035   assert(MI.getOpcode() == TargetOpcode::G_ADD);
2036   Register LHS = MI.getOperand(1).getReg();
2037   Register RHS = MI.getOperand(2).getReg();
2038   LLT IntTy = MRI.getType(LHS);
2039 
2040   // G_PTR_ADD always has the pointer in the LHS, so we may need to commute the
2041   // instruction.
2042   PtrReg.second = false;
2043   for (Register SrcReg : {LHS, RHS}) {
2044     if (mi_match(SrcReg, MRI, m_GPtrToInt(m_Reg(PtrReg.first)))) {
2045       // Don't handle cases where the integer is implicitly converted to the
2046       // pointer width.
2047       LLT PtrTy = MRI.getType(PtrReg.first);
2048       if (PtrTy.getScalarSizeInBits() == IntTy.getScalarSizeInBits())
2049         return true;
2050     }
2051 
2052     PtrReg.second = true;
2053   }
2054 
2055   return false;
2056 }
2057 
2058 void CombinerHelper::applyCombineAddP2IToPtrAdd(
2059     MachineInstr &MI, std::pair<Register, bool> &PtrReg) {
2060   Register Dst = MI.getOperand(0).getReg();
2061   Register LHS = MI.getOperand(1).getReg();
2062   Register RHS = MI.getOperand(2).getReg();
2063 
2064   const bool DoCommute = PtrReg.second;
2065   if (DoCommute)
2066     std::swap(LHS, RHS);
2067   LHS = PtrReg.first;
2068 
2069   LLT PtrTy = MRI.getType(LHS);
2070 
2071   Builder.setInstrAndDebugLoc(MI);
2072   auto PtrAdd = Builder.buildPtrAdd(PtrTy, LHS, RHS);
2073   Builder.buildPtrToInt(Dst, PtrAdd);
2074   MI.eraseFromParent();
2075 }
2076 
2077 bool CombinerHelper::matchCombineConstPtrAddToI2P(MachineInstr &MI,
2078                                                   APInt &NewCst) {
2079   auto &PtrAdd = cast<GPtrAdd>(MI);
2080   Register LHS = PtrAdd.getBaseReg();
2081   Register RHS = PtrAdd.getOffsetReg();
2082   MachineRegisterInfo &MRI = Builder.getMF().getRegInfo();
2083 
2084   if (auto RHSCst = getIConstantVRegVal(RHS, MRI)) {
2085     APInt Cst;
2086     if (mi_match(LHS, MRI, m_GIntToPtr(m_ICst(Cst)))) {
2087       auto DstTy = MRI.getType(PtrAdd.getReg(0));
2088       // G_INTTOPTR uses zero-extension
2089       NewCst = Cst.zextOrTrunc(DstTy.getSizeInBits());
2090       NewCst += RHSCst->sextOrTrunc(DstTy.getSizeInBits());
2091       return true;
2092     }
2093   }
2094 
2095   return false;
2096 }
2097 
2098 void CombinerHelper::applyCombineConstPtrAddToI2P(MachineInstr &MI,
2099                                                   APInt &NewCst) {
2100   auto &PtrAdd = cast<GPtrAdd>(MI);
2101   Register Dst = PtrAdd.getReg(0);
2102 
2103   Builder.setInstrAndDebugLoc(MI);
2104   Builder.buildConstant(Dst, NewCst);
2105   PtrAdd.eraseFromParent();
2106 }
2107 
2108 bool CombinerHelper::matchCombineAnyExtTrunc(MachineInstr &MI, Register &Reg) {
2109   assert(MI.getOpcode() == TargetOpcode::G_ANYEXT && "Expected a G_ANYEXT");
2110   Register DstReg = MI.getOperand(0).getReg();
2111   Register SrcReg = MI.getOperand(1).getReg();
2112   LLT DstTy = MRI.getType(DstReg);
2113   return mi_match(SrcReg, MRI,
2114                   m_GTrunc(m_all_of(m_Reg(Reg), m_SpecificType(DstTy))));
2115 }
2116 
2117 bool CombinerHelper::matchCombineZextTrunc(MachineInstr &MI, Register &Reg) {
2118   assert(MI.getOpcode() == TargetOpcode::G_ZEXT && "Expected a G_ZEXT");
2119   Register DstReg = MI.getOperand(0).getReg();
2120   Register SrcReg = MI.getOperand(1).getReg();
2121   LLT DstTy = MRI.getType(DstReg);
2122   if (mi_match(SrcReg, MRI,
2123                m_GTrunc(m_all_of(m_Reg(Reg), m_SpecificType(DstTy))))) {
2124     unsigned DstSize = DstTy.getScalarSizeInBits();
2125     unsigned SrcSize = MRI.getType(SrcReg).getScalarSizeInBits();
2126     return KB->getKnownBits(Reg).countMinLeadingZeros() >= DstSize - SrcSize;
2127   }
2128   return false;
2129 }
2130 
2131 bool CombinerHelper::matchCombineExtOfExt(
2132     MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
2133   assert((MI.getOpcode() == TargetOpcode::G_ANYEXT ||
2134           MI.getOpcode() == TargetOpcode::G_SEXT ||
2135           MI.getOpcode() == TargetOpcode::G_ZEXT) &&
2136          "Expected a G_[ASZ]EXT");
2137   Register SrcReg = MI.getOperand(1).getReg();
2138   MachineInstr *SrcMI = MRI.getVRegDef(SrcReg);
2139   // Match exts with the same opcode, anyext([sz]ext) and sext(zext).
2140   unsigned Opc = MI.getOpcode();
2141   unsigned SrcOpc = SrcMI->getOpcode();
2142   if (Opc == SrcOpc ||
2143       (Opc == TargetOpcode::G_ANYEXT &&
2144        (SrcOpc == TargetOpcode::G_SEXT || SrcOpc == TargetOpcode::G_ZEXT)) ||
2145       (Opc == TargetOpcode::G_SEXT && SrcOpc == TargetOpcode::G_ZEXT)) {
2146     MatchInfo = std::make_tuple(SrcMI->getOperand(1).getReg(), SrcOpc);
2147     return true;
2148   }
2149   return false;
2150 }
2151 
2152 void CombinerHelper::applyCombineExtOfExt(
2153     MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
2154   assert((MI.getOpcode() == TargetOpcode::G_ANYEXT ||
2155           MI.getOpcode() == TargetOpcode::G_SEXT ||
2156           MI.getOpcode() == TargetOpcode::G_ZEXT) &&
2157          "Expected a G_[ASZ]EXT");
2158 
2159   Register Reg = std::get<0>(MatchInfo);
2160   unsigned SrcExtOp = std::get<1>(MatchInfo);
2161 
2162   // Combine exts with the same opcode.
2163   if (MI.getOpcode() == SrcExtOp) {
2164     Observer.changingInstr(MI);
2165     MI.getOperand(1).setReg(Reg);
2166     Observer.changedInstr(MI);
2167     return;
2168   }
2169 
2170   // Combine:
2171   // - anyext([sz]ext x) to [sz]ext x
2172   // - sext(zext x) to zext x
2173   if (MI.getOpcode() == TargetOpcode::G_ANYEXT ||
2174       (MI.getOpcode() == TargetOpcode::G_SEXT &&
2175        SrcExtOp == TargetOpcode::G_ZEXT)) {
2176     Register DstReg = MI.getOperand(0).getReg();
2177     Builder.setInstrAndDebugLoc(MI);
2178     Builder.buildInstr(SrcExtOp, {DstReg}, {Reg});
2179     MI.eraseFromParent();
2180   }
2181 }
2182 
2183 void CombinerHelper::applyCombineMulByNegativeOne(MachineInstr &MI) {
2184   assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL");
2185   Register DstReg = MI.getOperand(0).getReg();
2186   Register SrcReg = MI.getOperand(1).getReg();
2187   LLT DstTy = MRI.getType(DstReg);
2188 
2189   Builder.setInstrAndDebugLoc(MI);
2190   Builder.buildSub(DstReg, Builder.buildConstant(DstTy, 0), SrcReg,
2191                    MI.getFlags());
2192   MI.eraseFromParent();
2193 }
2194 
2195 bool CombinerHelper::matchCombineFNegOfFNeg(MachineInstr &MI, Register &Reg) {
2196   assert(MI.getOpcode() == TargetOpcode::G_FNEG && "Expected a G_FNEG");
2197   Register SrcReg = MI.getOperand(1).getReg();
2198   return mi_match(SrcReg, MRI, m_GFNeg(m_Reg(Reg)));
2199 }
2200 
2201 bool CombinerHelper::matchCombineFAbsOfFAbs(MachineInstr &MI, Register &Src) {
2202   assert(MI.getOpcode() == TargetOpcode::G_FABS && "Expected a G_FABS");
2203   Src = MI.getOperand(1).getReg();
2204   Register AbsSrc;
2205   return mi_match(Src, MRI, m_GFabs(m_Reg(AbsSrc)));
2206 }
2207 
2208 bool CombinerHelper::matchCombineFAbsOfFNeg(MachineInstr &MI,
2209                                             BuildFnTy &MatchInfo) {
2210   assert(MI.getOpcode() == TargetOpcode::G_FABS && "Expected a G_FABS");
2211   Register Src = MI.getOperand(1).getReg();
2212   Register NegSrc;
2213 
2214   if (!mi_match(Src, MRI, m_GFNeg(m_Reg(NegSrc))))
2215     return false;
2216 
2217   MatchInfo = [=, &MI](MachineIRBuilder &B) {
2218     Observer.changingInstr(MI);
2219     MI.getOperand(1).setReg(NegSrc);
2220     Observer.changedInstr(MI);
2221   };
2222   return true;
2223 }
2224 
2225 bool CombinerHelper::matchCombineTruncOfExt(
2226     MachineInstr &MI, std::pair<Register, unsigned> &MatchInfo) {
2227   assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2228   Register SrcReg = MI.getOperand(1).getReg();
2229   MachineInstr *SrcMI = MRI.getVRegDef(SrcReg);
2230   unsigned SrcOpc = SrcMI->getOpcode();
2231   if (SrcOpc == TargetOpcode::G_ANYEXT || SrcOpc == TargetOpcode::G_SEXT ||
2232       SrcOpc == TargetOpcode::G_ZEXT) {
2233     MatchInfo = std::make_pair(SrcMI->getOperand(1).getReg(), SrcOpc);
2234     return true;
2235   }
2236   return false;
2237 }
2238 
2239 void CombinerHelper::applyCombineTruncOfExt(
2240     MachineInstr &MI, std::pair<Register, unsigned> &MatchInfo) {
2241   assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2242   Register SrcReg = MatchInfo.first;
2243   unsigned SrcExtOp = MatchInfo.second;
2244   Register DstReg = MI.getOperand(0).getReg();
2245   LLT SrcTy = MRI.getType(SrcReg);
2246   LLT DstTy = MRI.getType(DstReg);
2247   if (SrcTy == DstTy) {
2248     MI.eraseFromParent();
2249     replaceRegWith(MRI, DstReg, SrcReg);
2250     return;
2251   }
2252   Builder.setInstrAndDebugLoc(MI);
2253   if (SrcTy.getSizeInBits() < DstTy.getSizeInBits())
2254     Builder.buildInstr(SrcExtOp, {DstReg}, {SrcReg});
2255   else
2256     Builder.buildTrunc(DstReg, SrcReg);
2257   MI.eraseFromParent();
2258 }
2259 
2260 bool CombinerHelper::matchCombineTruncOfShl(
2261     MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
2262   assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2263   Register DstReg = MI.getOperand(0).getReg();
2264   Register SrcReg = MI.getOperand(1).getReg();
2265   LLT DstTy = MRI.getType(DstReg);
2266   Register ShiftSrc;
2267   Register ShiftAmt;
2268 
2269   if (MRI.hasOneNonDBGUse(SrcReg) &&
2270       mi_match(SrcReg, MRI, m_GShl(m_Reg(ShiftSrc), m_Reg(ShiftAmt))) &&
2271       isLegalOrBeforeLegalizer(
2272           {TargetOpcode::G_SHL,
2273            {DstTy, getTargetLowering().getPreferredShiftAmountTy(DstTy)}})) {
2274     KnownBits Known = KB->getKnownBits(ShiftAmt);
2275     unsigned Size = DstTy.getSizeInBits();
2276     if (Known.countMaxActiveBits() <= Log2_32(Size)) {
2277       MatchInfo = std::make_pair(ShiftSrc, ShiftAmt);
2278       return true;
2279     }
2280   }
2281   return false;
2282 }
2283 
2284 void CombinerHelper::applyCombineTruncOfShl(
2285     MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
2286   assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2287   Register DstReg = MI.getOperand(0).getReg();
2288   Register SrcReg = MI.getOperand(1).getReg();
2289   LLT DstTy = MRI.getType(DstReg);
2290   MachineInstr *SrcMI = MRI.getVRegDef(SrcReg);
2291 
2292   Register ShiftSrc = MatchInfo.first;
2293   Register ShiftAmt = MatchInfo.second;
2294   Builder.setInstrAndDebugLoc(MI);
2295   auto TruncShiftSrc = Builder.buildTrunc(DstTy, ShiftSrc);
2296   Builder.buildShl(DstReg, TruncShiftSrc, ShiftAmt, SrcMI->getFlags());
2297   MI.eraseFromParent();
2298 }
2299 
2300 bool CombinerHelper::matchAnyExplicitUseIsUndef(MachineInstr &MI) {
2301   return any_of(MI.explicit_uses(), [this](const MachineOperand &MO) {
2302     return MO.isReg() &&
2303            getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
2304   });
2305 }
2306 
2307 bool CombinerHelper::matchAllExplicitUsesAreUndef(MachineInstr &MI) {
2308   return all_of(MI.explicit_uses(), [this](const MachineOperand &MO) {
2309     return !MO.isReg() ||
2310            getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
2311   });
2312 }
2313 
2314 bool CombinerHelper::matchUndefShuffleVectorMask(MachineInstr &MI) {
2315   assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR);
2316   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
2317   return all_of(Mask, [](int Elt) { return Elt < 0; });
2318 }
2319 
2320 bool CombinerHelper::matchUndefStore(MachineInstr &MI) {
2321   assert(MI.getOpcode() == TargetOpcode::G_STORE);
2322   return getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MI.getOperand(0).getReg(),
2323                       MRI);
2324 }
2325 
2326 bool CombinerHelper::matchUndefSelectCmp(MachineInstr &MI) {
2327   assert(MI.getOpcode() == TargetOpcode::G_SELECT);
2328   return getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MI.getOperand(1).getReg(),
2329                       MRI);
2330 }
2331 
2332 bool CombinerHelper::matchConstantSelectCmp(MachineInstr &MI, unsigned &OpIdx) {
2333   GSelect &SelMI = cast<GSelect>(MI);
2334   auto Cst =
2335       isConstantOrConstantSplatVector(*MRI.getVRegDef(SelMI.getCondReg()), MRI);
2336   if (!Cst)
2337     return false;
2338   OpIdx = Cst->isZero() ? 3 : 2;
2339   return true;
2340 }
2341 
2342 bool CombinerHelper::eraseInst(MachineInstr &MI) {
2343   MI.eraseFromParent();
2344   return true;
2345 }
2346 
2347 bool CombinerHelper::matchEqualDefs(const MachineOperand &MOP1,
2348                                     const MachineOperand &MOP2) {
2349   if (!MOP1.isReg() || !MOP2.isReg())
2350     return false;
2351   auto InstAndDef1 = getDefSrcRegIgnoringCopies(MOP1.getReg(), MRI);
2352   if (!InstAndDef1)
2353     return false;
2354   auto InstAndDef2 = getDefSrcRegIgnoringCopies(MOP2.getReg(), MRI);
2355   if (!InstAndDef2)
2356     return false;
2357   MachineInstr *I1 = InstAndDef1->MI;
2358   MachineInstr *I2 = InstAndDef2->MI;
2359 
2360   // Handle a case like this:
2361   //
2362   // %0:_(s64), %1:_(s64) = G_UNMERGE_VALUES %2:_(<2 x s64>)
2363   //
2364   // Even though %0 and %1 are produced by the same instruction they are not
2365   // the same values.
2366   if (I1 == I2)
2367     return MOP1.getReg() == MOP2.getReg();
2368 
2369   // If we have an instruction which loads or stores, we can't guarantee that
2370   // it is identical.
2371   //
2372   // For example, we may have
2373   //
2374   // %x1 = G_LOAD %addr (load N from @somewhere)
2375   // ...
2376   // call @foo
2377   // ...
2378   // %x2 = G_LOAD %addr (load N from @somewhere)
2379   // ...
2380   // %or = G_OR %x1, %x2
2381   //
2382   // It's possible that @foo will modify whatever lives at the address we're
2383   // loading from. To be safe, let's just assume that all loads and stores
2384   // are different (unless we have something which is guaranteed to not
2385   // change.)
2386   if (I1->mayLoadOrStore() && !I1->isDereferenceableInvariantLoad(nullptr))
2387     return false;
2388 
2389   // If both instructions are loads or stores, they are equal only if both
2390   // are dereferenceable invariant loads with the same number of bits.
2391   if (I1->mayLoadOrStore() && I2->mayLoadOrStore()) {
2392     GLoadStore *LS1 = dyn_cast<GLoadStore>(I1);
2393     GLoadStore *LS2 = dyn_cast<GLoadStore>(I2);
2394     if (!LS1 || !LS2)
2395       return false;
2396 
2397     if (!I2->isDereferenceableInvariantLoad(nullptr) ||
2398         (LS1->getMemSizeInBits() != LS2->getMemSizeInBits()))
2399       return false;
2400   }
2401 
2402   // Check for physical registers on the instructions first to avoid cases
2403   // like this:
2404   //
2405   // %a = COPY $physreg
2406   // ...
2407   // SOMETHING implicit-def $physreg
2408   // ...
2409   // %b = COPY $physreg
2410   //
2411   // These copies are not equivalent.
2412   if (any_of(I1->uses(), [](const MachineOperand &MO) {
2413         return MO.isReg() && MO.getReg().isPhysical();
2414       })) {
2415     // Check if we have a case like this:
2416     //
2417     // %a = COPY $physreg
2418     // %b = COPY %a
2419     //
2420     // In this case, I1 and I2 will both be equal to %a = COPY $physreg.
2421     // From that, we know that they must have the same value, since they must
2422     // have come from the same COPY.
2423     return I1->isIdenticalTo(*I2);
2424   }
2425 
2426   // We don't have any physical registers, so we don't necessarily need the
2427   // same vreg defs.
2428   //
2429   // On the off-chance that there's some target instruction feeding into the
2430   // instruction, let's use produceSameValue instead of isIdenticalTo.
2431   if (Builder.getTII().produceSameValue(*I1, *I2, &MRI)) {
2432     // Handle instructions with multiple defs that produce same values. Values
2433     // are same for operands with same index.
2434     // %0:_(s8), %1:_(s8), %2:_(s8), %3:_(s8) = G_UNMERGE_VALUES %4:_(<4 x s8>)
2435     // %5:_(s8), %6:_(s8), %7:_(s8), %8:_(s8) = G_UNMERGE_VALUES %4:_(<4 x s8>)
2436     // I1 and I2 are different instructions but produce same values,
2437     // %1 and %6 are same, %1 and %7 are not the same value.
2438     return I1->findRegisterDefOperandIdx(InstAndDef1->Reg) ==
2439            I2->findRegisterDefOperandIdx(InstAndDef2->Reg);
2440   }
2441   return false;
2442 }
2443 
2444 bool CombinerHelper::matchConstantOp(const MachineOperand &MOP, int64_t C) {
2445   if (!MOP.isReg())
2446     return false;
2447   auto *MI = MRI.getVRegDef(MOP.getReg());
2448   auto MaybeCst = isConstantOrConstantSplatVector(*MI, MRI);
2449   return MaybeCst && MaybeCst->getBitWidth() <= 64 &&
2450          MaybeCst->getSExtValue() == C;
2451 }
2452 
2453 bool CombinerHelper::replaceSingleDefInstWithOperand(MachineInstr &MI,
2454                                                      unsigned OpIdx) {
2455   assert(MI.getNumExplicitDefs() == 1 && "Expected one explicit def?");
2456   Register OldReg = MI.getOperand(0).getReg();
2457   Register Replacement = MI.getOperand(OpIdx).getReg();
2458   assert(canReplaceReg(OldReg, Replacement, MRI) && "Cannot replace register?");
2459   MI.eraseFromParent();
2460   replaceRegWith(MRI, OldReg, Replacement);
2461   return true;
2462 }
2463 
2464 bool CombinerHelper::replaceSingleDefInstWithReg(MachineInstr &MI,
2465                                                  Register Replacement) {
2466   assert(MI.getNumExplicitDefs() == 1 && "Expected one explicit def?");
2467   Register OldReg = MI.getOperand(0).getReg();
2468   assert(canReplaceReg(OldReg, Replacement, MRI) && "Cannot replace register?");
2469   MI.eraseFromParent();
2470   replaceRegWith(MRI, OldReg, Replacement);
2471   return true;
2472 }
2473 
2474 bool CombinerHelper::matchSelectSameVal(MachineInstr &MI) {
2475   assert(MI.getOpcode() == TargetOpcode::G_SELECT);
2476   // Match (cond ? x : x)
2477   return matchEqualDefs(MI.getOperand(2), MI.getOperand(3)) &&
2478          canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(2).getReg(),
2479                        MRI);
2480 }
2481 
2482 bool CombinerHelper::matchBinOpSameVal(MachineInstr &MI) {
2483   return matchEqualDefs(MI.getOperand(1), MI.getOperand(2)) &&
2484          canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(1).getReg(),
2485                        MRI);
2486 }
2487 
2488 bool CombinerHelper::matchOperandIsZero(MachineInstr &MI, unsigned OpIdx) {
2489   return matchConstantOp(MI.getOperand(OpIdx), 0) &&
2490          canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(OpIdx).getReg(),
2491                        MRI);
2492 }
2493 
2494 bool CombinerHelper::matchOperandIsUndef(MachineInstr &MI, unsigned OpIdx) {
2495   MachineOperand &MO = MI.getOperand(OpIdx);
2496   return MO.isReg() &&
2497          getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
2498 }
2499 
2500 bool CombinerHelper::matchOperandIsKnownToBeAPowerOfTwo(MachineInstr &MI,
2501                                                         unsigned OpIdx) {
2502   MachineOperand &MO = MI.getOperand(OpIdx);
2503   return isKnownToBeAPowerOfTwo(MO.getReg(), MRI, KB);
2504 }
2505 
2506 bool CombinerHelper::replaceInstWithFConstant(MachineInstr &MI, double C) {
2507   assert(MI.getNumDefs() == 1 && "Expected only one def?");
2508   Builder.setInstr(MI);
2509   Builder.buildFConstant(MI.getOperand(0), C);
2510   MI.eraseFromParent();
2511   return true;
2512 }
2513 
2514 bool CombinerHelper::replaceInstWithConstant(MachineInstr &MI, int64_t C) {
2515   assert(MI.getNumDefs() == 1 && "Expected only one def?");
2516   Builder.setInstr(MI);
2517   Builder.buildConstant(MI.getOperand(0), C);
2518   MI.eraseFromParent();
2519   return true;
2520 }
2521 
2522 bool CombinerHelper::replaceInstWithConstant(MachineInstr &MI, APInt C) {
2523   assert(MI.getNumDefs() == 1 && "Expected only one def?");
2524   Builder.setInstr(MI);
2525   Builder.buildConstant(MI.getOperand(0), C);
2526   MI.eraseFromParent();
2527   return true;
2528 }
2529 
2530 bool CombinerHelper::replaceInstWithUndef(MachineInstr &MI) {
2531   assert(MI.getNumDefs() == 1 && "Expected only one def?");
2532   Builder.setInstr(MI);
2533   Builder.buildUndef(MI.getOperand(0));
2534   MI.eraseFromParent();
2535   return true;
2536 }
2537 
2538 bool CombinerHelper::matchSimplifyAddToSub(
2539     MachineInstr &MI, std::tuple<Register, Register> &MatchInfo) {
2540   Register LHS = MI.getOperand(1).getReg();
2541   Register RHS = MI.getOperand(2).getReg();
2542   Register &NewLHS = std::get<0>(MatchInfo);
2543   Register &NewRHS = std::get<1>(MatchInfo);
2544 
2545   // Helper lambda to check for opportunities for
2546   // ((0-A) + B) -> B - A
2547   // (A + (0-B)) -> A - B
2548   auto CheckFold = [&](Register &MaybeSub, Register &MaybeNewLHS) {
2549     if (!mi_match(MaybeSub, MRI, m_Neg(m_Reg(NewRHS))))
2550       return false;
2551     NewLHS = MaybeNewLHS;
2552     return true;
2553   };
2554 
2555   return CheckFold(LHS, RHS) || CheckFold(RHS, LHS);
2556 }
2557 
2558 bool CombinerHelper::matchCombineInsertVecElts(
2559     MachineInstr &MI, SmallVectorImpl<Register> &MatchInfo) {
2560   assert(MI.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT &&
2561          "Invalid opcode");
2562   Register DstReg = MI.getOperand(0).getReg();
2563   LLT DstTy = MRI.getType(DstReg);
2564   assert(DstTy.isVector() && "Invalid G_INSERT_VECTOR_ELT?");
2565   unsigned NumElts = DstTy.getNumElements();
2566   // If this MI is part of a sequence of insert_vec_elts, then
2567   // don't do the combine in the middle of the sequence.
2568   if (MRI.hasOneUse(DstReg) && MRI.use_instr_begin(DstReg)->getOpcode() ==
2569                                    TargetOpcode::G_INSERT_VECTOR_ELT)
2570     return false;
2571   MachineInstr *CurrInst = &MI;
2572   MachineInstr *TmpInst;
2573   int64_t IntImm;
2574   Register TmpReg;
2575   MatchInfo.resize(NumElts);
2576   while (mi_match(
2577       CurrInst->getOperand(0).getReg(), MRI,
2578       m_GInsertVecElt(m_MInstr(TmpInst), m_Reg(TmpReg), m_ICst(IntImm)))) {
2579     if (IntImm >= NumElts)
2580       return false;
2581     if (!MatchInfo[IntImm])
2582       MatchInfo[IntImm] = TmpReg;
2583     CurrInst = TmpInst;
2584   }
2585   // Variable index.
2586   if (CurrInst->getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT)
2587     return false;
2588   if (TmpInst->getOpcode() == TargetOpcode::G_BUILD_VECTOR) {
2589     for (unsigned I = 1; I < TmpInst->getNumOperands(); ++I) {
2590       if (!MatchInfo[I - 1].isValid())
2591         MatchInfo[I - 1] = TmpInst->getOperand(I).getReg();
2592     }
2593     return true;
2594   }
2595   // If we didn't end in a G_IMPLICIT_DEF, bail out.
2596   return TmpInst->getOpcode() == TargetOpcode::G_IMPLICIT_DEF;
2597 }
2598 
2599 void CombinerHelper::applyCombineInsertVecElts(
2600     MachineInstr &MI, SmallVectorImpl<Register> &MatchInfo) {
2601   Builder.setInstr(MI);
2602   Register UndefReg;
2603   auto GetUndef = [&]() {
2604     if (UndefReg)
2605       return UndefReg;
2606     LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
2607     UndefReg = Builder.buildUndef(DstTy.getScalarType()).getReg(0);
2608     return UndefReg;
2609   };
2610   for (unsigned I = 0; I < MatchInfo.size(); ++I) {
2611     if (!MatchInfo[I])
2612       MatchInfo[I] = GetUndef();
2613   }
2614   Builder.buildBuildVector(MI.getOperand(0).getReg(), MatchInfo);
2615   MI.eraseFromParent();
2616 }
2617 
2618 void CombinerHelper::applySimplifyAddToSub(
2619     MachineInstr &MI, std::tuple<Register, Register> &MatchInfo) {
2620   Builder.setInstr(MI);
2621   Register SubLHS, SubRHS;
2622   std::tie(SubLHS, SubRHS) = MatchInfo;
2623   Builder.buildSub(MI.getOperand(0).getReg(), SubLHS, SubRHS);
2624   MI.eraseFromParent();
2625 }
2626 
2627 bool CombinerHelper::matchHoistLogicOpWithSameOpcodeHands(
2628     MachineInstr &MI, InstructionStepsMatchInfo &MatchInfo) {
2629   // Matches: logic (hand x, ...), (hand y, ...) -> hand (logic x, y), ...
2630   //
2631   // Creates the new hand + logic instruction (but does not insert them.)
2632   //
2633   // On success, MatchInfo is populated with the new instructions. These are
2634   // inserted in applyHoistLogicOpWithSameOpcodeHands.
2635   unsigned LogicOpcode = MI.getOpcode();
2636   assert(LogicOpcode == TargetOpcode::G_AND ||
2637          LogicOpcode == TargetOpcode::G_OR ||
2638          LogicOpcode == TargetOpcode::G_XOR);
2639   MachineIRBuilder MIB(MI);
2640   Register Dst = MI.getOperand(0).getReg();
2641   Register LHSReg = MI.getOperand(1).getReg();
2642   Register RHSReg = MI.getOperand(2).getReg();
2643 
2644   // Don't recompute anything.
2645   if (!MRI.hasOneNonDBGUse(LHSReg) || !MRI.hasOneNonDBGUse(RHSReg))
2646     return false;
2647 
2648   // Make sure we have (hand x, ...), (hand y, ...)
2649   MachineInstr *LeftHandInst = getDefIgnoringCopies(LHSReg, MRI);
2650   MachineInstr *RightHandInst = getDefIgnoringCopies(RHSReg, MRI);
2651   if (!LeftHandInst || !RightHandInst)
2652     return false;
2653   unsigned HandOpcode = LeftHandInst->getOpcode();
2654   if (HandOpcode != RightHandInst->getOpcode())
2655     return false;
2656   if (!LeftHandInst->getOperand(1).isReg() ||
2657       !RightHandInst->getOperand(1).isReg())
2658     return false;
2659 
2660   // Make sure the types match up, and if we're doing this post-legalization,
2661   // we end up with legal types.
2662   Register X = LeftHandInst->getOperand(1).getReg();
2663   Register Y = RightHandInst->getOperand(1).getReg();
2664   LLT XTy = MRI.getType(X);
2665   LLT YTy = MRI.getType(Y);
2666   if (XTy != YTy)
2667     return false;
2668   if (!isLegalOrBeforeLegalizer({LogicOpcode, {XTy, YTy}}))
2669     return false;
2670 
2671   // Optional extra source register.
2672   Register ExtraHandOpSrcReg;
2673   switch (HandOpcode) {
2674   default:
2675     return false;
2676   case TargetOpcode::G_ANYEXT:
2677   case TargetOpcode::G_SEXT:
2678   case TargetOpcode::G_ZEXT: {
2679     // Match: logic (ext X), (ext Y) --> ext (logic X, Y)
2680     break;
2681   }
2682   case TargetOpcode::G_AND:
2683   case TargetOpcode::G_ASHR:
2684   case TargetOpcode::G_LSHR:
2685   case TargetOpcode::G_SHL: {
2686     // Match: logic (binop x, z), (binop y, z) -> binop (logic x, y), z
2687     MachineOperand &ZOp = LeftHandInst->getOperand(2);
2688     if (!matchEqualDefs(ZOp, RightHandInst->getOperand(2)))
2689       return false;
2690     ExtraHandOpSrcReg = ZOp.getReg();
2691     break;
2692   }
2693   }
2694 
2695   // Record the steps to build the new instructions.
2696   //
2697   // Steps to build (logic x, y)
2698   auto NewLogicDst = MRI.createGenericVirtualRegister(XTy);
2699   OperandBuildSteps LogicBuildSteps = {
2700       [=](MachineInstrBuilder &MIB) { MIB.addDef(NewLogicDst); },
2701       [=](MachineInstrBuilder &MIB) { MIB.addReg(X); },
2702       [=](MachineInstrBuilder &MIB) { MIB.addReg(Y); }};
2703   InstructionBuildSteps LogicSteps(LogicOpcode, LogicBuildSteps);
2704 
2705   // Steps to build hand (logic x, y), ...z
2706   OperandBuildSteps HandBuildSteps = {
2707       [=](MachineInstrBuilder &MIB) { MIB.addDef(Dst); },
2708       [=](MachineInstrBuilder &MIB) { MIB.addReg(NewLogicDst); }};
2709   if (ExtraHandOpSrcReg.isValid())
2710     HandBuildSteps.push_back(
2711         [=](MachineInstrBuilder &MIB) { MIB.addReg(ExtraHandOpSrcReg); });
2712   InstructionBuildSteps HandSteps(HandOpcode, HandBuildSteps);
2713 
2714   MatchInfo = InstructionStepsMatchInfo({LogicSteps, HandSteps});
2715   return true;
2716 }
2717 
2718 void CombinerHelper::applyBuildInstructionSteps(
2719     MachineInstr &MI, InstructionStepsMatchInfo &MatchInfo) {
2720   assert(MatchInfo.InstrsToBuild.size() &&
2721          "Expected at least one instr to build?");
2722   Builder.setInstr(MI);
2723   for (auto &InstrToBuild : MatchInfo.InstrsToBuild) {
2724     assert(InstrToBuild.Opcode && "Expected a valid opcode?");
2725     assert(InstrToBuild.OperandFns.size() && "Expected at least one operand?");
2726     MachineInstrBuilder Instr = Builder.buildInstr(InstrToBuild.Opcode);
2727     for (auto &OperandFn : InstrToBuild.OperandFns)
2728       OperandFn(Instr);
2729   }
2730   MI.eraseFromParent();
2731 }
2732 
2733 bool CombinerHelper::matchAshrShlToSextInreg(
2734     MachineInstr &MI, std::tuple<Register, int64_t> &MatchInfo) {
2735   assert(MI.getOpcode() == TargetOpcode::G_ASHR);
2736   int64_t ShlCst, AshrCst;
2737   Register Src;
2738   // FIXME: detect splat constant vectors.
2739   if (!mi_match(MI.getOperand(0).getReg(), MRI,
2740                 m_GAShr(m_GShl(m_Reg(Src), m_ICst(ShlCst)), m_ICst(AshrCst))))
2741     return false;
2742   if (ShlCst != AshrCst)
2743     return false;
2744   if (!isLegalOrBeforeLegalizer(
2745           {TargetOpcode::G_SEXT_INREG, {MRI.getType(Src)}}))
2746     return false;
2747   MatchInfo = std::make_tuple(Src, ShlCst);
2748   return true;
2749 }
2750 
2751 void CombinerHelper::applyAshShlToSextInreg(
2752     MachineInstr &MI, std::tuple<Register, int64_t> &MatchInfo) {
2753   assert(MI.getOpcode() == TargetOpcode::G_ASHR);
2754   Register Src;
2755   int64_t ShiftAmt;
2756   std::tie(Src, ShiftAmt) = MatchInfo;
2757   unsigned Size = MRI.getType(Src).getScalarSizeInBits();
2758   Builder.setInstrAndDebugLoc(MI);
2759   Builder.buildSExtInReg(MI.getOperand(0).getReg(), Src, Size - ShiftAmt);
2760   MI.eraseFromParent();
2761 }
2762 
2763 /// and(and(x, C1), C2) -> C1&C2 ? and(x, C1&C2) : 0
2764 bool CombinerHelper::matchOverlappingAnd(
2765     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
2766   assert(MI.getOpcode() == TargetOpcode::G_AND);
2767 
2768   Register Dst = MI.getOperand(0).getReg();
2769   LLT Ty = MRI.getType(Dst);
2770 
2771   Register R;
2772   int64_t C1;
2773   int64_t C2;
2774   if (!mi_match(
2775           Dst, MRI,
2776           m_GAnd(m_GAnd(m_Reg(R), m_ICst(C1)), m_ICst(C2))))
2777     return false;
2778 
2779   MatchInfo = [=](MachineIRBuilder &B) {
2780     if (C1 & C2) {
2781       B.buildAnd(Dst, R, B.buildConstant(Ty, C1 & C2));
2782       return;
2783     }
2784     auto Zero = B.buildConstant(Ty, 0);
2785     replaceRegWith(MRI, Dst, Zero->getOperand(0).getReg());
2786   };
2787   return true;
2788 }
2789 
2790 bool CombinerHelper::matchRedundantAnd(MachineInstr &MI,
2791                                        Register &Replacement) {
2792   // Given
2793   //
2794   // %y:_(sN) = G_SOMETHING
2795   // %x:_(sN) = G_SOMETHING
2796   // %res:_(sN) = G_AND %x, %y
2797   //
2798   // Eliminate the G_AND when it is known that x & y == x or x & y == y.
2799   //
2800   // Patterns like this can appear as a result of legalization. E.g.
2801   //
2802   // %cmp:_(s32) = G_ICMP intpred(pred), %x(s32), %y
2803   // %one:_(s32) = G_CONSTANT i32 1
2804   // %and:_(s32) = G_AND %cmp, %one
2805   //
2806   // In this case, G_ICMP only produces a single bit, so x & 1 == x.
2807   assert(MI.getOpcode() == TargetOpcode::G_AND);
2808   if (!KB)
2809     return false;
2810 
2811   Register AndDst = MI.getOperand(0).getReg();
2812   LLT DstTy = MRI.getType(AndDst);
2813 
2814   // FIXME: This should be removed once GISelKnownBits supports vectors.
2815   if (DstTy.isVector())
2816     return false;
2817 
2818   Register LHS = MI.getOperand(1).getReg();
2819   Register RHS = MI.getOperand(2).getReg();
2820   KnownBits LHSBits = KB->getKnownBits(LHS);
2821   KnownBits RHSBits = KB->getKnownBits(RHS);
2822 
2823   // Check that x & Mask == x.
2824   // x & 1 == x, always
2825   // x & 0 == x, only if x is also 0
2826   // Meaning Mask has no effect if every bit is either one in Mask or zero in x.
2827   //
2828   // Check if we can replace AndDst with the LHS of the G_AND
2829   if (canReplaceReg(AndDst, LHS, MRI) &&
2830       (LHSBits.Zero | RHSBits.One).isAllOnes()) {
2831     Replacement = LHS;
2832     return true;
2833   }
2834 
2835   // Check if we can replace AndDst with the RHS of the G_AND
2836   if (canReplaceReg(AndDst, RHS, MRI) &&
2837       (LHSBits.One | RHSBits.Zero).isAllOnes()) {
2838     Replacement = RHS;
2839     return true;
2840   }
2841 
2842   return false;
2843 }
2844 
2845 bool CombinerHelper::matchRedundantOr(MachineInstr &MI, Register &Replacement) {
2846   // Given
2847   //
2848   // %y:_(sN) = G_SOMETHING
2849   // %x:_(sN) = G_SOMETHING
2850   // %res:_(sN) = G_OR %x, %y
2851   //
2852   // Eliminate the G_OR when it is known that x | y == x or x | y == y.
2853   assert(MI.getOpcode() == TargetOpcode::G_OR);
2854   if (!KB)
2855     return false;
2856 
2857   Register OrDst = MI.getOperand(0).getReg();
2858   LLT DstTy = MRI.getType(OrDst);
2859 
2860   // FIXME: This should be removed once GISelKnownBits supports vectors.
2861   if (DstTy.isVector())
2862     return false;
2863 
2864   Register LHS = MI.getOperand(1).getReg();
2865   Register RHS = MI.getOperand(2).getReg();
2866   KnownBits LHSBits = KB->getKnownBits(LHS);
2867   KnownBits RHSBits = KB->getKnownBits(RHS);
2868 
2869   // Check that x | Mask == x.
2870   // x | 0 == x, always
2871   // x | 1 == x, only if x is also 1
2872   // Meaning Mask has no effect if every bit is either zero in Mask or one in x.
2873   //
2874   // Check if we can replace OrDst with the LHS of the G_OR
2875   if (canReplaceReg(OrDst, LHS, MRI) &&
2876       (LHSBits.One | RHSBits.Zero).isAllOnes()) {
2877     Replacement = LHS;
2878     return true;
2879   }
2880 
2881   // Check if we can replace OrDst with the RHS of the G_OR
2882   if (canReplaceReg(OrDst, RHS, MRI) &&
2883       (LHSBits.Zero | RHSBits.One).isAllOnes()) {
2884     Replacement = RHS;
2885     return true;
2886   }
2887 
2888   return false;
2889 }
2890 
2891 bool CombinerHelper::matchRedundantSExtInReg(MachineInstr &MI) {
2892   // If the input is already sign extended, just drop the extension.
2893   Register Src = MI.getOperand(1).getReg();
2894   unsigned ExtBits = MI.getOperand(2).getImm();
2895   unsigned TypeSize = MRI.getType(Src).getScalarSizeInBits();
2896   return KB->computeNumSignBits(Src) >= (TypeSize - ExtBits + 1);
2897 }
2898 
2899 static bool isConstValidTrue(const TargetLowering &TLI, unsigned ScalarSizeBits,
2900                              int64_t Cst, bool IsVector, bool IsFP) {
2901   // For i1, Cst will always be -1 regardless of boolean contents.
2902   return (ScalarSizeBits == 1 && Cst == -1) ||
2903          isConstTrueVal(TLI, Cst, IsVector, IsFP);
2904 }
2905 
2906 bool CombinerHelper::matchNotCmp(MachineInstr &MI,
2907                                  SmallVectorImpl<Register> &RegsToNegate) {
2908   assert(MI.getOpcode() == TargetOpcode::G_XOR);
2909   LLT Ty = MRI.getType(MI.getOperand(0).getReg());
2910   const auto &TLI = *Builder.getMF().getSubtarget().getTargetLowering();
2911   Register XorSrc;
2912   Register CstReg;
2913   // We match xor(src, true) here.
2914   if (!mi_match(MI.getOperand(0).getReg(), MRI,
2915                 m_GXor(m_Reg(XorSrc), m_Reg(CstReg))))
2916     return false;
2917 
2918   if (!MRI.hasOneNonDBGUse(XorSrc))
2919     return false;
2920 
2921   // Check that XorSrc is the root of a tree of comparisons combined with ANDs
2922   // and ORs. The suffix of RegsToNegate starting from index I is used a work
2923   // list of tree nodes to visit.
2924   RegsToNegate.push_back(XorSrc);
2925   // Remember whether the comparisons are all integer or all floating point.
2926   bool IsInt = false;
2927   bool IsFP = false;
2928   for (unsigned I = 0; I < RegsToNegate.size(); ++I) {
2929     Register Reg = RegsToNegate[I];
2930     if (!MRI.hasOneNonDBGUse(Reg))
2931       return false;
2932     MachineInstr *Def = MRI.getVRegDef(Reg);
2933     switch (Def->getOpcode()) {
2934     default:
2935       // Don't match if the tree contains anything other than ANDs, ORs and
2936       // comparisons.
2937       return false;
2938     case TargetOpcode::G_ICMP:
2939       if (IsFP)
2940         return false;
2941       IsInt = true;
2942       // When we apply the combine we will invert the predicate.
2943       break;
2944     case TargetOpcode::G_FCMP:
2945       if (IsInt)
2946         return false;
2947       IsFP = true;
2948       // When we apply the combine we will invert the predicate.
2949       break;
2950     case TargetOpcode::G_AND:
2951     case TargetOpcode::G_OR:
2952       // Implement De Morgan's laws:
2953       // ~(x & y) -> ~x | ~y
2954       // ~(x | y) -> ~x & ~y
2955       // When we apply the combine we will change the opcode and recursively
2956       // negate the operands.
2957       RegsToNegate.push_back(Def->getOperand(1).getReg());
2958       RegsToNegate.push_back(Def->getOperand(2).getReg());
2959       break;
2960     }
2961   }
2962 
2963   // Now we know whether the comparisons are integer or floating point, check
2964   // the constant in the xor.
2965   int64_t Cst;
2966   if (Ty.isVector()) {
2967     MachineInstr *CstDef = MRI.getVRegDef(CstReg);
2968     auto MaybeCst = getIConstantSplatSExtVal(*CstDef, MRI);
2969     if (!MaybeCst)
2970       return false;
2971     if (!isConstValidTrue(TLI, Ty.getScalarSizeInBits(), *MaybeCst, true, IsFP))
2972       return false;
2973   } else {
2974     if (!mi_match(CstReg, MRI, m_ICst(Cst)))
2975       return false;
2976     if (!isConstValidTrue(TLI, Ty.getSizeInBits(), Cst, false, IsFP))
2977       return false;
2978   }
2979 
2980   return true;
2981 }
2982 
2983 void CombinerHelper::applyNotCmp(MachineInstr &MI,
2984                                  SmallVectorImpl<Register> &RegsToNegate) {
2985   for (Register Reg : RegsToNegate) {
2986     MachineInstr *Def = MRI.getVRegDef(Reg);
2987     Observer.changingInstr(*Def);
2988     // For each comparison, invert the opcode. For each AND and OR, change the
2989     // opcode.
2990     switch (Def->getOpcode()) {
2991     default:
2992       llvm_unreachable("Unexpected opcode");
2993     case TargetOpcode::G_ICMP:
2994     case TargetOpcode::G_FCMP: {
2995       MachineOperand &PredOp = Def->getOperand(1);
2996       CmpInst::Predicate NewP = CmpInst::getInversePredicate(
2997           (CmpInst::Predicate)PredOp.getPredicate());
2998       PredOp.setPredicate(NewP);
2999       break;
3000     }
3001     case TargetOpcode::G_AND:
3002       Def->setDesc(Builder.getTII().get(TargetOpcode::G_OR));
3003       break;
3004     case TargetOpcode::G_OR:
3005       Def->setDesc(Builder.getTII().get(TargetOpcode::G_AND));
3006       break;
3007     }
3008     Observer.changedInstr(*Def);
3009   }
3010 
3011   replaceRegWith(MRI, MI.getOperand(0).getReg(), MI.getOperand(1).getReg());
3012   MI.eraseFromParent();
3013 }
3014 
3015 bool CombinerHelper::matchXorOfAndWithSameReg(
3016     MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
3017   // Match (xor (and x, y), y) (or any of its commuted cases)
3018   assert(MI.getOpcode() == TargetOpcode::G_XOR);
3019   Register &X = MatchInfo.first;
3020   Register &Y = MatchInfo.second;
3021   Register AndReg = MI.getOperand(1).getReg();
3022   Register SharedReg = MI.getOperand(2).getReg();
3023 
3024   // Find a G_AND on either side of the G_XOR.
3025   // Look for one of
3026   //
3027   // (xor (and x, y), SharedReg)
3028   // (xor SharedReg, (and x, y))
3029   if (!mi_match(AndReg, MRI, m_GAnd(m_Reg(X), m_Reg(Y)))) {
3030     std::swap(AndReg, SharedReg);
3031     if (!mi_match(AndReg, MRI, m_GAnd(m_Reg(X), m_Reg(Y))))
3032       return false;
3033   }
3034 
3035   // Only do this if we'll eliminate the G_AND.
3036   if (!MRI.hasOneNonDBGUse(AndReg))
3037     return false;
3038 
3039   // We can combine if SharedReg is the same as either the LHS or RHS of the
3040   // G_AND.
3041   if (Y != SharedReg)
3042     std::swap(X, Y);
3043   return Y == SharedReg;
3044 }
3045 
3046 void CombinerHelper::applyXorOfAndWithSameReg(
3047     MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
3048   // Fold (xor (and x, y), y) -> (and (not x), y)
3049   Builder.setInstrAndDebugLoc(MI);
3050   Register X, Y;
3051   std::tie(X, Y) = MatchInfo;
3052   auto Not = Builder.buildNot(MRI.getType(X), X);
3053   Observer.changingInstr(MI);
3054   MI.setDesc(Builder.getTII().get(TargetOpcode::G_AND));
3055   MI.getOperand(1).setReg(Not->getOperand(0).getReg());
3056   MI.getOperand(2).setReg(Y);
3057   Observer.changedInstr(MI);
3058 }
3059 
3060 bool CombinerHelper::matchPtrAddZero(MachineInstr &MI) {
3061   auto &PtrAdd = cast<GPtrAdd>(MI);
3062   Register DstReg = PtrAdd.getReg(0);
3063   LLT Ty = MRI.getType(DstReg);
3064   const DataLayout &DL = Builder.getMF().getDataLayout();
3065 
3066   if (DL.isNonIntegralAddressSpace(Ty.getScalarType().getAddressSpace()))
3067     return false;
3068 
3069   if (Ty.isPointer()) {
3070     auto ConstVal = getIConstantVRegVal(PtrAdd.getBaseReg(), MRI);
3071     return ConstVal && *ConstVal == 0;
3072   }
3073 
3074   assert(Ty.isVector() && "Expecting a vector type");
3075   const MachineInstr *VecMI = MRI.getVRegDef(PtrAdd.getBaseReg());
3076   return isBuildVectorAllZeros(*VecMI, MRI);
3077 }
3078 
3079 void CombinerHelper::applyPtrAddZero(MachineInstr &MI) {
3080   auto &PtrAdd = cast<GPtrAdd>(MI);
3081   Builder.setInstrAndDebugLoc(PtrAdd);
3082   Builder.buildIntToPtr(PtrAdd.getReg(0), PtrAdd.getOffsetReg());
3083   PtrAdd.eraseFromParent();
3084 }
3085 
3086 /// The second source operand is known to be a power of 2.
3087 void CombinerHelper::applySimplifyURemByPow2(MachineInstr &MI) {
3088   Register DstReg = MI.getOperand(0).getReg();
3089   Register Src0 = MI.getOperand(1).getReg();
3090   Register Pow2Src1 = MI.getOperand(2).getReg();
3091   LLT Ty = MRI.getType(DstReg);
3092   Builder.setInstrAndDebugLoc(MI);
3093 
3094   // Fold (urem x, pow2) -> (and x, pow2-1)
3095   auto NegOne = Builder.buildConstant(Ty, -1);
3096   auto Add = Builder.buildAdd(Ty, Pow2Src1, NegOne);
3097   Builder.buildAnd(DstReg, Src0, Add);
3098   MI.eraseFromParent();
3099 }
3100 
3101 bool CombinerHelper::matchFoldBinOpIntoSelect(MachineInstr &MI,
3102                                               unsigned &SelectOpNo) {
3103   Register LHS = MI.getOperand(1).getReg();
3104   Register RHS = MI.getOperand(2).getReg();
3105 
3106   Register OtherOperandReg = RHS;
3107   SelectOpNo = 1;
3108   MachineInstr *Select = MRI.getVRegDef(LHS);
3109 
3110   // Don't do this unless the old select is going away. We want to eliminate the
3111   // binary operator, not replace a binop with a select.
3112   if (Select->getOpcode() != TargetOpcode::G_SELECT ||
3113       !MRI.hasOneNonDBGUse(LHS)) {
3114     OtherOperandReg = LHS;
3115     SelectOpNo = 2;
3116     Select = MRI.getVRegDef(RHS);
3117     if (Select->getOpcode() != TargetOpcode::G_SELECT ||
3118         !MRI.hasOneNonDBGUse(RHS))
3119       return false;
3120   }
3121 
3122   MachineInstr *SelectLHS = MRI.getVRegDef(Select->getOperand(2).getReg());
3123   MachineInstr *SelectRHS = MRI.getVRegDef(Select->getOperand(3).getReg());
3124 
3125   if (!isConstantOrConstantVector(*SelectLHS, MRI,
3126                                   /*AllowFP*/ true,
3127                                   /*AllowOpaqueConstants*/ false))
3128     return false;
3129   if (!isConstantOrConstantVector(*SelectRHS, MRI,
3130                                   /*AllowFP*/ true,
3131                                   /*AllowOpaqueConstants*/ false))
3132     return false;
3133 
3134   unsigned BinOpcode = MI.getOpcode();
3135 
3136   // We know know one of the operands is a select of constants. Now verify that
3137   // the other binary operator operand is either a constant, or we can handle a
3138   // variable.
3139   bool CanFoldNonConst =
3140       (BinOpcode == TargetOpcode::G_AND || BinOpcode == TargetOpcode::G_OR) &&
3141       (isNullOrNullSplat(*SelectLHS, MRI) ||
3142        isAllOnesOrAllOnesSplat(*SelectLHS, MRI)) &&
3143       (isNullOrNullSplat(*SelectRHS, MRI) ||
3144        isAllOnesOrAllOnesSplat(*SelectRHS, MRI));
3145   if (CanFoldNonConst)
3146     return true;
3147 
3148   return isConstantOrConstantVector(*MRI.getVRegDef(OtherOperandReg), MRI,
3149                                     /*AllowFP*/ true,
3150                                     /*AllowOpaqueConstants*/ false);
3151 }
3152 
3153 /// \p SelectOperand is the operand in binary operator \p MI that is the select
3154 /// to fold.
3155 bool CombinerHelper::applyFoldBinOpIntoSelect(MachineInstr &MI,
3156                                               const unsigned &SelectOperand) {
3157   Builder.setInstrAndDebugLoc(MI);
3158 
3159   Register Dst = MI.getOperand(0).getReg();
3160   Register LHS = MI.getOperand(1).getReg();
3161   Register RHS = MI.getOperand(2).getReg();
3162   MachineInstr *Select = MRI.getVRegDef(MI.getOperand(SelectOperand).getReg());
3163 
3164   Register SelectCond = Select->getOperand(1).getReg();
3165   Register SelectTrue = Select->getOperand(2).getReg();
3166   Register SelectFalse = Select->getOperand(3).getReg();
3167 
3168   LLT Ty = MRI.getType(Dst);
3169   unsigned BinOpcode = MI.getOpcode();
3170 
3171   Register FoldTrue, FoldFalse;
3172 
3173   // We have a select-of-constants followed by a binary operator with a
3174   // constant. Eliminate the binop by pulling the constant math into the select.
3175   // Example: add (select Cond, CT, CF), CBO --> select Cond, CT + CBO, CF + CBO
3176   if (SelectOperand == 1) {
3177     // TODO: SelectionDAG verifies this actually constant folds before
3178     // committing to the combine.
3179 
3180     FoldTrue = Builder.buildInstr(BinOpcode, {Ty}, {SelectTrue, RHS}).getReg(0);
3181     FoldFalse =
3182         Builder.buildInstr(BinOpcode, {Ty}, {SelectFalse, RHS}).getReg(0);
3183   } else {
3184     FoldTrue = Builder.buildInstr(BinOpcode, {Ty}, {LHS, SelectTrue}).getReg(0);
3185     FoldFalse =
3186         Builder.buildInstr(BinOpcode, {Ty}, {LHS, SelectFalse}).getReg(0);
3187   }
3188 
3189   Builder.buildSelect(Dst, SelectCond, FoldTrue, FoldFalse, MI.getFlags());
3190   Observer.erasingInstr(*Select);
3191   Select->eraseFromParent();
3192   MI.eraseFromParent();
3193 
3194   return true;
3195 }
3196 
3197 Optional<SmallVector<Register, 8>>
3198 CombinerHelper::findCandidatesForLoadOrCombine(const MachineInstr *Root) const {
3199   assert(Root->getOpcode() == TargetOpcode::G_OR && "Expected G_OR only!");
3200   // We want to detect if Root is part of a tree which represents a bunch
3201   // of loads being merged into a larger load. We'll try to recognize patterns
3202   // like, for example:
3203   //
3204   //  Reg   Reg
3205   //   \    /
3206   //    OR_1   Reg
3207   //     \    /
3208   //      OR_2
3209   //        \     Reg
3210   //         .. /
3211   //        Root
3212   //
3213   //  Reg   Reg   Reg   Reg
3214   //     \ /       \   /
3215   //     OR_1      OR_2
3216   //       \       /
3217   //        \    /
3218   //         ...
3219   //         Root
3220   //
3221   // Each "Reg" may have been produced by a load + some arithmetic. This
3222   // function will save each of them.
3223   SmallVector<Register, 8> RegsToVisit;
3224   SmallVector<const MachineInstr *, 7> Ors = {Root};
3225 
3226   // In the "worst" case, we're dealing with a load for each byte. So, there
3227   // are at most #bytes - 1 ORs.
3228   const unsigned MaxIter =
3229       MRI.getType(Root->getOperand(0).getReg()).getSizeInBytes() - 1;
3230   for (unsigned Iter = 0; Iter < MaxIter; ++Iter) {
3231     if (Ors.empty())
3232       break;
3233     const MachineInstr *Curr = Ors.pop_back_val();
3234     Register OrLHS = Curr->getOperand(1).getReg();
3235     Register OrRHS = Curr->getOperand(2).getReg();
3236 
3237     // In the combine, we want to elimate the entire tree.
3238     if (!MRI.hasOneNonDBGUse(OrLHS) || !MRI.hasOneNonDBGUse(OrRHS))
3239       return None;
3240 
3241     // If it's a G_OR, save it and continue to walk. If it's not, then it's
3242     // something that may be a load + arithmetic.
3243     if (const MachineInstr *Or = getOpcodeDef(TargetOpcode::G_OR, OrLHS, MRI))
3244       Ors.push_back(Or);
3245     else
3246       RegsToVisit.push_back(OrLHS);
3247     if (const MachineInstr *Or = getOpcodeDef(TargetOpcode::G_OR, OrRHS, MRI))
3248       Ors.push_back(Or);
3249     else
3250       RegsToVisit.push_back(OrRHS);
3251   }
3252 
3253   // We're going to try and merge each register into a wider power-of-2 type,
3254   // so we ought to have an even number of registers.
3255   if (RegsToVisit.empty() || RegsToVisit.size() % 2 != 0)
3256     return None;
3257   return RegsToVisit;
3258 }
3259 
3260 /// Helper function for findLoadOffsetsForLoadOrCombine.
3261 ///
3262 /// Check if \p Reg is the result of loading a \p MemSizeInBits wide value,
3263 /// and then moving that value into a specific byte offset.
3264 ///
3265 /// e.g. x[i] << 24
3266 ///
3267 /// \returns The load instruction and the byte offset it is moved into.
3268 static Optional<std::pair<GZExtLoad *, int64_t>>
3269 matchLoadAndBytePosition(Register Reg, unsigned MemSizeInBits,
3270                          const MachineRegisterInfo &MRI) {
3271   assert(MRI.hasOneNonDBGUse(Reg) &&
3272          "Expected Reg to only have one non-debug use?");
3273   Register MaybeLoad;
3274   int64_t Shift;
3275   if (!mi_match(Reg, MRI,
3276                 m_OneNonDBGUse(m_GShl(m_Reg(MaybeLoad), m_ICst(Shift))))) {
3277     Shift = 0;
3278     MaybeLoad = Reg;
3279   }
3280 
3281   if (Shift % MemSizeInBits != 0)
3282     return None;
3283 
3284   // TODO: Handle other types of loads.
3285   auto *Load = getOpcodeDef<GZExtLoad>(MaybeLoad, MRI);
3286   if (!Load)
3287     return None;
3288 
3289   if (!Load->isUnordered() || Load->getMemSizeInBits() != MemSizeInBits)
3290     return None;
3291 
3292   return std::make_pair(Load, Shift / MemSizeInBits);
3293 }
3294 
3295 Optional<std::tuple<GZExtLoad *, int64_t, GZExtLoad *>>
3296 CombinerHelper::findLoadOffsetsForLoadOrCombine(
3297     SmallDenseMap<int64_t, int64_t, 8> &MemOffset2Idx,
3298     const SmallVector<Register, 8> &RegsToVisit, const unsigned MemSizeInBits) {
3299 
3300   // Each load found for the pattern. There should be one for each RegsToVisit.
3301   SmallSetVector<const MachineInstr *, 8> Loads;
3302 
3303   // The lowest index used in any load. (The lowest "i" for each x[i].)
3304   int64_t LowestIdx = INT64_MAX;
3305 
3306   // The load which uses the lowest index.
3307   GZExtLoad *LowestIdxLoad = nullptr;
3308 
3309   // Keeps track of the load indices we see. We shouldn't see any indices twice.
3310   SmallSet<int64_t, 8> SeenIdx;
3311 
3312   // Ensure each load is in the same MBB.
3313   // TODO: Support multiple MachineBasicBlocks.
3314   MachineBasicBlock *MBB = nullptr;
3315   const MachineMemOperand *MMO = nullptr;
3316 
3317   // Earliest instruction-order load in the pattern.
3318   GZExtLoad *EarliestLoad = nullptr;
3319 
3320   // Latest instruction-order load in the pattern.
3321   GZExtLoad *LatestLoad = nullptr;
3322 
3323   // Base pointer which every load should share.
3324   Register BasePtr;
3325 
3326   // We want to find a load for each register. Each load should have some
3327   // appropriate bit twiddling arithmetic. During this loop, we will also keep
3328   // track of the load which uses the lowest index. Later, we will check if we
3329   // can use its pointer in the final, combined load.
3330   for (auto Reg : RegsToVisit) {
3331     // Find the load, and find the position that it will end up in (e.g. a
3332     // shifted) value.
3333     auto LoadAndPos = matchLoadAndBytePosition(Reg, MemSizeInBits, MRI);
3334     if (!LoadAndPos)
3335       return None;
3336     GZExtLoad *Load;
3337     int64_t DstPos;
3338     std::tie(Load, DstPos) = *LoadAndPos;
3339 
3340     // TODO: Handle multiple MachineBasicBlocks. Currently not handled because
3341     // it is difficult to check for stores/calls/etc between loads.
3342     MachineBasicBlock *LoadMBB = Load->getParent();
3343     if (!MBB)
3344       MBB = LoadMBB;
3345     if (LoadMBB != MBB)
3346       return None;
3347 
3348     // Make sure that the MachineMemOperands of every seen load are compatible.
3349     auto &LoadMMO = Load->getMMO();
3350     if (!MMO)
3351       MMO = &LoadMMO;
3352     if (MMO->getAddrSpace() != LoadMMO.getAddrSpace())
3353       return None;
3354 
3355     // Find out what the base pointer and index for the load is.
3356     Register LoadPtr;
3357     int64_t Idx;
3358     if (!mi_match(Load->getOperand(1).getReg(), MRI,
3359                   m_GPtrAdd(m_Reg(LoadPtr), m_ICst(Idx)))) {
3360       LoadPtr = Load->getOperand(1).getReg();
3361       Idx = 0;
3362     }
3363 
3364     // Don't combine things like a[i], a[i] -> a bigger load.
3365     if (!SeenIdx.insert(Idx).second)
3366       return None;
3367 
3368     // Every load must share the same base pointer; don't combine things like:
3369     //
3370     // a[i], b[i + 1] -> a bigger load.
3371     if (!BasePtr.isValid())
3372       BasePtr = LoadPtr;
3373     if (BasePtr != LoadPtr)
3374       return None;
3375 
3376     if (Idx < LowestIdx) {
3377       LowestIdx = Idx;
3378       LowestIdxLoad = Load;
3379     }
3380 
3381     // Keep track of the byte offset that this load ends up at. If we have seen
3382     // the byte offset, then stop here. We do not want to combine:
3383     //
3384     // a[i] << 16, a[i + k] << 16 -> a bigger load.
3385     if (!MemOffset2Idx.try_emplace(DstPos, Idx).second)
3386       return None;
3387     Loads.insert(Load);
3388 
3389     // Keep track of the position of the earliest/latest loads in the pattern.
3390     // We will check that there are no load fold barriers between them later
3391     // on.
3392     //
3393     // FIXME: Is there a better way to check for load fold barriers?
3394     if (!EarliestLoad || dominates(*Load, *EarliestLoad))
3395       EarliestLoad = Load;
3396     if (!LatestLoad || dominates(*LatestLoad, *Load))
3397       LatestLoad = Load;
3398   }
3399 
3400   // We found a load for each register. Let's check if each load satisfies the
3401   // pattern.
3402   assert(Loads.size() == RegsToVisit.size() &&
3403          "Expected to find a load for each register?");
3404   assert(EarliestLoad != LatestLoad && EarliestLoad &&
3405          LatestLoad && "Expected at least two loads?");
3406 
3407   // Check if there are any stores, calls, etc. between any of the loads. If
3408   // there are, then we can't safely perform the combine.
3409   //
3410   // MaxIter is chosen based off the (worst case) number of iterations it
3411   // typically takes to succeed in the LLVM test suite plus some padding.
3412   //
3413   // FIXME: Is there a better way to check for load fold barriers?
3414   const unsigned MaxIter = 20;
3415   unsigned Iter = 0;
3416   for (const auto &MI : instructionsWithoutDebug(EarliestLoad->getIterator(),
3417                                                  LatestLoad->getIterator())) {
3418     if (Loads.count(&MI))
3419       continue;
3420     if (MI.isLoadFoldBarrier())
3421       return None;
3422     if (Iter++ == MaxIter)
3423       return None;
3424   }
3425 
3426   return std::make_tuple(LowestIdxLoad, LowestIdx, LatestLoad);
3427 }
3428 
3429 bool CombinerHelper::matchLoadOrCombine(
3430     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
3431   assert(MI.getOpcode() == TargetOpcode::G_OR);
3432   MachineFunction &MF = *MI.getMF();
3433   // Assuming a little-endian target, transform:
3434   //  s8 *a = ...
3435   //  s32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
3436   // =>
3437   //  s32 val = *((i32)a)
3438   //
3439   //  s8 *a = ...
3440   //  s32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
3441   // =>
3442   //  s32 val = BSWAP(*((s32)a))
3443   Register Dst = MI.getOperand(0).getReg();
3444   LLT Ty = MRI.getType(Dst);
3445   if (Ty.isVector())
3446     return false;
3447 
3448   // We need to combine at least two loads into this type. Since the smallest
3449   // possible load is into a byte, we need at least a 16-bit wide type.
3450   const unsigned WideMemSizeInBits = Ty.getSizeInBits();
3451   if (WideMemSizeInBits < 16 || WideMemSizeInBits % 8 != 0)
3452     return false;
3453 
3454   // Match a collection of non-OR instructions in the pattern.
3455   auto RegsToVisit = findCandidatesForLoadOrCombine(&MI);
3456   if (!RegsToVisit)
3457     return false;
3458 
3459   // We have a collection of non-OR instructions. Figure out how wide each of
3460   // the small loads should be based off of the number of potential loads we
3461   // found.
3462   const unsigned NarrowMemSizeInBits = WideMemSizeInBits / RegsToVisit->size();
3463   if (NarrowMemSizeInBits % 8 != 0)
3464     return false;
3465 
3466   // Check if each register feeding into each OR is a load from the same
3467   // base pointer + some arithmetic.
3468   //
3469   // e.g. a[0], a[1] << 8, a[2] << 16, etc.
3470   //
3471   // Also verify that each of these ends up putting a[i] into the same memory
3472   // offset as a load into a wide type would.
3473   SmallDenseMap<int64_t, int64_t, 8> MemOffset2Idx;
3474   GZExtLoad *LowestIdxLoad, *LatestLoad;
3475   int64_t LowestIdx;
3476   auto MaybeLoadInfo = findLoadOffsetsForLoadOrCombine(
3477       MemOffset2Idx, *RegsToVisit, NarrowMemSizeInBits);
3478   if (!MaybeLoadInfo)
3479     return false;
3480   std::tie(LowestIdxLoad, LowestIdx, LatestLoad) = *MaybeLoadInfo;
3481 
3482   // We have a bunch of loads being OR'd together. Using the addresses + offsets
3483   // we found before, check if this corresponds to a big or little endian byte
3484   // pattern. If it does, then we can represent it using a load + possibly a
3485   // BSWAP.
3486   bool IsBigEndianTarget = MF.getDataLayout().isBigEndian();
3487   Optional<bool> IsBigEndian = isBigEndian(MemOffset2Idx, LowestIdx);
3488   if (!IsBigEndian)
3489     return false;
3490   bool NeedsBSwap = IsBigEndianTarget != *IsBigEndian;
3491   if (NeedsBSwap && !isLegalOrBeforeLegalizer({TargetOpcode::G_BSWAP, {Ty}}))
3492     return false;
3493 
3494   // Make sure that the load from the lowest index produces offset 0 in the
3495   // final value.
3496   //
3497   // This ensures that we won't combine something like this:
3498   //
3499   // load x[i] -> byte 2
3500   // load x[i+1] -> byte 0 ---> wide_load x[i]
3501   // load x[i+2] -> byte 1
3502   const unsigned NumLoadsInTy = WideMemSizeInBits / NarrowMemSizeInBits;
3503   const unsigned ZeroByteOffset =
3504       *IsBigEndian
3505           ? bigEndianByteAt(NumLoadsInTy, 0)
3506           : littleEndianByteAt(NumLoadsInTy, 0);
3507   auto ZeroOffsetIdx = MemOffset2Idx.find(ZeroByteOffset);
3508   if (ZeroOffsetIdx == MemOffset2Idx.end() ||
3509       ZeroOffsetIdx->second != LowestIdx)
3510     return false;
3511 
3512   // We wil reuse the pointer from the load which ends up at byte offset 0. It
3513   // may not use index 0.
3514   Register Ptr = LowestIdxLoad->getPointerReg();
3515   const MachineMemOperand &MMO = LowestIdxLoad->getMMO();
3516   LegalityQuery::MemDesc MMDesc(MMO);
3517   MMDesc.MemoryTy = Ty;
3518   if (!isLegalOrBeforeLegalizer(
3519           {TargetOpcode::G_LOAD, {Ty, MRI.getType(Ptr)}, {MMDesc}}))
3520     return false;
3521   auto PtrInfo = MMO.getPointerInfo();
3522   auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, WideMemSizeInBits / 8);
3523 
3524   // Load must be allowed and fast on the target.
3525   LLVMContext &C = MF.getFunction().getContext();
3526   auto &DL = MF.getDataLayout();
3527   bool Fast = false;
3528   if (!getTargetLowering().allowsMemoryAccess(C, DL, Ty, *NewMMO, &Fast) ||
3529       !Fast)
3530     return false;
3531 
3532   MatchInfo = [=](MachineIRBuilder &MIB) {
3533     MIB.setInstrAndDebugLoc(*LatestLoad);
3534     Register LoadDst = NeedsBSwap ? MRI.cloneVirtualRegister(Dst) : Dst;
3535     MIB.buildLoad(LoadDst, Ptr, *NewMMO);
3536     if (NeedsBSwap)
3537       MIB.buildBSwap(Dst, LoadDst);
3538   };
3539   return true;
3540 }
3541 
3542 /// Check if the store \p Store is a truncstore that can be merged. That is,
3543 /// it's a store of a shifted value of \p SrcVal. If \p SrcVal is an empty
3544 /// Register then it does not need to match and SrcVal is set to the source
3545 /// value found.
3546 /// On match, returns the start byte offset of the \p SrcVal that is being
3547 /// stored.
3548 static Optional<int64_t> getTruncStoreByteOffset(GStore &Store, Register &SrcVal,
3549                                                  MachineRegisterInfo &MRI) {
3550   Register TruncVal;
3551   if (!mi_match(Store.getValueReg(), MRI, m_GTrunc(m_Reg(TruncVal))))
3552     return None;
3553 
3554   // The shift amount must be a constant multiple of the narrow type.
3555   // It is translated to the offset address in the wide source value "y".
3556   //
3557   // x = G_LSHR y, ShiftAmtC
3558   // s8 z = G_TRUNC x
3559   // store z, ...
3560   Register FoundSrcVal;
3561   int64_t ShiftAmt;
3562   if (!mi_match(TruncVal, MRI,
3563                 m_any_of(m_GLShr(m_Reg(FoundSrcVal), m_ICst(ShiftAmt)),
3564                          m_GAShr(m_Reg(FoundSrcVal), m_ICst(ShiftAmt))))) {
3565     if (!SrcVal.isValid() || TruncVal == SrcVal) {
3566       if (!SrcVal.isValid())
3567         SrcVal = TruncVal;
3568       return 0; // If it's the lowest index store.
3569     }
3570     return None;
3571   }
3572 
3573   unsigned NarrowBits = Store.getMMO().getMemoryType().getScalarSizeInBits();
3574   if (ShiftAmt % NarrowBits!= 0)
3575     return None;
3576   const unsigned Offset = ShiftAmt / NarrowBits;
3577 
3578   if (SrcVal.isValid() && FoundSrcVal != SrcVal)
3579     return None;
3580 
3581   if (!SrcVal.isValid())
3582     SrcVal = FoundSrcVal;
3583   else if (MRI.getType(SrcVal) != MRI.getType(FoundSrcVal))
3584     return None;
3585   return Offset;
3586 }
3587 
3588 /// Match a pattern where a wide type scalar value is stored by several narrow
3589 /// stores. Fold it into a single store or a BSWAP and a store if the targets
3590 /// supports it.
3591 ///
3592 /// Assuming little endian target:
3593 ///  i8 *p = ...
3594 ///  i32 val = ...
3595 ///  p[0] = (val >> 0) & 0xFF;
3596 ///  p[1] = (val >> 8) & 0xFF;
3597 ///  p[2] = (val >> 16) & 0xFF;
3598 ///  p[3] = (val >> 24) & 0xFF;
3599 /// =>
3600 ///  *((i32)p) = val;
3601 ///
3602 ///  i8 *p = ...
3603 ///  i32 val = ...
3604 ///  p[0] = (val >> 24) & 0xFF;
3605 ///  p[1] = (val >> 16) & 0xFF;
3606 ///  p[2] = (val >> 8) & 0xFF;
3607 ///  p[3] = (val >> 0) & 0xFF;
3608 /// =>
3609 ///  *((i32)p) = BSWAP(val);
3610 bool CombinerHelper::matchTruncStoreMerge(MachineInstr &MI,
3611                                           MergeTruncStoresInfo &MatchInfo) {
3612   auto &StoreMI = cast<GStore>(MI);
3613   LLT MemTy = StoreMI.getMMO().getMemoryType();
3614 
3615   // We only handle merging simple stores of 1-4 bytes.
3616   if (!MemTy.isScalar())
3617     return false;
3618   switch (MemTy.getSizeInBits()) {
3619   case 8:
3620   case 16:
3621   case 32:
3622     break;
3623   default:
3624     return false;
3625   }
3626   if (!StoreMI.isSimple())
3627     return false;
3628 
3629   // We do a simple search for mergeable stores prior to this one.
3630   // Any potential alias hazard along the way terminates the search.
3631   SmallVector<GStore *> FoundStores;
3632 
3633   // We're looking for:
3634   // 1) a (store(trunc(...)))
3635   // 2) of an LSHR/ASHR of a single wide value, by the appropriate shift to get
3636   //    the partial value stored.
3637   // 3) where the offsets form either a little or big-endian sequence.
3638 
3639   auto &LastStore = StoreMI;
3640 
3641   // The single base pointer that all stores must use.
3642   Register BaseReg;
3643   int64_t LastOffset;
3644   if (!mi_match(LastStore.getPointerReg(), MRI,
3645                 m_GPtrAdd(m_Reg(BaseReg), m_ICst(LastOffset)))) {
3646     BaseReg = LastStore.getPointerReg();
3647     LastOffset = 0;
3648   }
3649 
3650   GStore *LowestIdxStore = &LastStore;
3651   int64_t LowestIdxOffset = LastOffset;
3652 
3653   Register WideSrcVal;
3654   auto LowestShiftAmt = getTruncStoreByteOffset(LastStore, WideSrcVal, MRI);
3655   if (!LowestShiftAmt)
3656     return false; // Didn't match a trunc.
3657   assert(WideSrcVal.isValid());
3658 
3659   LLT WideStoreTy = MRI.getType(WideSrcVal);
3660   // The wide type might not be a multiple of the memory type, e.g. s48 and s32.
3661   if (WideStoreTy.getSizeInBits() % MemTy.getSizeInBits() != 0)
3662     return false;
3663   const unsigned NumStoresRequired =
3664       WideStoreTy.getSizeInBits() / MemTy.getSizeInBits();
3665 
3666   SmallVector<int64_t, 8> OffsetMap(NumStoresRequired, INT64_MAX);
3667   OffsetMap[*LowestShiftAmt] = LastOffset;
3668   FoundStores.emplace_back(&LastStore);
3669 
3670   // Search the block up for more stores.
3671   // We use a search threshold of 10 instructions here because the combiner
3672   // works top-down within a block, and we don't want to search an unbounded
3673   // number of predecessor instructions trying to find matching stores.
3674   // If we moved this optimization into a separate pass then we could probably
3675   // use a more efficient search without having a hard-coded threshold.
3676   const int MaxInstsToCheck = 10;
3677   int NumInstsChecked = 0;
3678   for (auto II = ++LastStore.getReverseIterator();
3679        II != LastStore.getParent()->rend() && NumInstsChecked < MaxInstsToCheck;
3680        ++II) {
3681     NumInstsChecked++;
3682     GStore *NewStore;
3683     if ((NewStore = dyn_cast<GStore>(&*II))) {
3684       if (NewStore->getMMO().getMemoryType() != MemTy || !NewStore->isSimple())
3685         break;
3686     } else if (II->isLoadFoldBarrier() || II->mayLoad()) {
3687       break;
3688     } else {
3689       continue; // This is a safe instruction we can look past.
3690     }
3691 
3692     Register NewBaseReg;
3693     int64_t MemOffset;
3694     // Check we're storing to the same base + some offset.
3695     if (!mi_match(NewStore->getPointerReg(), MRI,
3696                   m_GPtrAdd(m_Reg(NewBaseReg), m_ICst(MemOffset)))) {
3697       NewBaseReg = NewStore->getPointerReg();
3698       MemOffset = 0;
3699     }
3700     if (BaseReg != NewBaseReg)
3701       break;
3702 
3703     auto ShiftByteOffset = getTruncStoreByteOffset(*NewStore, WideSrcVal, MRI);
3704     if (!ShiftByteOffset)
3705       break;
3706     if (MemOffset < LowestIdxOffset) {
3707       LowestIdxOffset = MemOffset;
3708       LowestIdxStore = NewStore;
3709     }
3710 
3711     // Map the offset in the store and the offset in the combined value, and
3712     // early return if it has been set before.
3713     if (*ShiftByteOffset < 0 || *ShiftByteOffset >= NumStoresRequired ||
3714         OffsetMap[*ShiftByteOffset] != INT64_MAX)
3715       break;
3716     OffsetMap[*ShiftByteOffset] = MemOffset;
3717 
3718     FoundStores.emplace_back(NewStore);
3719     // Reset counter since we've found a matching inst.
3720     NumInstsChecked = 0;
3721     if (FoundStores.size() == NumStoresRequired)
3722       break;
3723   }
3724 
3725   if (FoundStores.size() != NumStoresRequired) {
3726     return false;
3727   }
3728 
3729   const auto &DL = LastStore.getMF()->getDataLayout();
3730   auto &C = LastStore.getMF()->getFunction().getContext();
3731   // Check that a store of the wide type is both allowed and fast on the target
3732   bool Fast = false;
3733   bool Allowed = getTargetLowering().allowsMemoryAccess(
3734       C, DL, WideStoreTy, LowestIdxStore->getMMO(), &Fast);
3735   if (!Allowed || !Fast)
3736     return false;
3737 
3738   // Check if the pieces of the value are going to the expected places in memory
3739   // to merge the stores.
3740   unsigned NarrowBits = MemTy.getScalarSizeInBits();
3741   auto checkOffsets = [&](bool MatchLittleEndian) {
3742     if (MatchLittleEndian) {
3743       for (unsigned i = 0; i != NumStoresRequired; ++i)
3744         if (OffsetMap[i] != i * (NarrowBits / 8) + LowestIdxOffset)
3745           return false;
3746     } else { // MatchBigEndian by reversing loop counter.
3747       for (unsigned i = 0, j = NumStoresRequired - 1; i != NumStoresRequired;
3748            ++i, --j)
3749         if (OffsetMap[j] != i * (NarrowBits / 8) + LowestIdxOffset)
3750           return false;
3751     }
3752     return true;
3753   };
3754 
3755   // Check if the offsets line up for the native data layout of this target.
3756   bool NeedBswap = false;
3757   bool NeedRotate = false;
3758   if (!checkOffsets(DL.isLittleEndian())) {
3759     // Special-case: check if byte offsets line up for the opposite endian.
3760     if (NarrowBits == 8 && checkOffsets(DL.isBigEndian()))
3761       NeedBswap = true;
3762     else if (NumStoresRequired == 2 && checkOffsets(DL.isBigEndian()))
3763       NeedRotate = true;
3764     else
3765       return false;
3766   }
3767 
3768   if (NeedBswap &&
3769       !isLegalOrBeforeLegalizer({TargetOpcode::G_BSWAP, {WideStoreTy}}))
3770     return false;
3771   if (NeedRotate &&
3772       !isLegalOrBeforeLegalizer({TargetOpcode::G_ROTR, {WideStoreTy}}))
3773     return false;
3774 
3775   MatchInfo.NeedBSwap = NeedBswap;
3776   MatchInfo.NeedRotate = NeedRotate;
3777   MatchInfo.LowestIdxStore = LowestIdxStore;
3778   MatchInfo.WideSrcVal = WideSrcVal;
3779   MatchInfo.FoundStores = std::move(FoundStores);
3780   return true;
3781 }
3782 
3783 void CombinerHelper::applyTruncStoreMerge(MachineInstr &MI,
3784                                           MergeTruncStoresInfo &MatchInfo) {
3785 
3786   Builder.setInstrAndDebugLoc(MI);
3787   Register WideSrcVal = MatchInfo.WideSrcVal;
3788   LLT WideStoreTy = MRI.getType(WideSrcVal);
3789 
3790   if (MatchInfo.NeedBSwap) {
3791     WideSrcVal = Builder.buildBSwap(WideStoreTy, WideSrcVal).getReg(0);
3792   } else if (MatchInfo.NeedRotate) {
3793     assert(WideStoreTy.getSizeInBits() % 2 == 0 &&
3794            "Unexpected type for rotate");
3795     auto RotAmt =
3796         Builder.buildConstant(WideStoreTy, WideStoreTy.getSizeInBits() / 2);
3797     WideSrcVal =
3798         Builder.buildRotateRight(WideStoreTy, WideSrcVal, RotAmt).getReg(0);
3799   }
3800 
3801   Builder.buildStore(WideSrcVal, MatchInfo.LowestIdxStore->getPointerReg(),
3802                      MatchInfo.LowestIdxStore->getMMO().getPointerInfo(),
3803                      MatchInfo.LowestIdxStore->getMMO().getAlign());
3804 
3805   // Erase the old stores.
3806   for (auto *ST : MatchInfo.FoundStores)
3807     ST->eraseFromParent();
3808 }
3809 
3810 bool CombinerHelper::matchExtendThroughPhis(MachineInstr &MI,
3811                                             MachineInstr *&ExtMI) {
3812   assert(MI.getOpcode() == TargetOpcode::G_PHI);
3813 
3814   Register DstReg = MI.getOperand(0).getReg();
3815 
3816   // TODO: Extending a vector may be expensive, don't do this until heuristics
3817   // are better.
3818   if (MRI.getType(DstReg).isVector())
3819     return false;
3820 
3821   // Try to match a phi, whose only use is an extend.
3822   if (!MRI.hasOneNonDBGUse(DstReg))
3823     return false;
3824   ExtMI = &*MRI.use_instr_nodbg_begin(DstReg);
3825   switch (ExtMI->getOpcode()) {
3826   case TargetOpcode::G_ANYEXT:
3827     return true; // G_ANYEXT is usually free.
3828   case TargetOpcode::G_ZEXT:
3829   case TargetOpcode::G_SEXT:
3830     break;
3831   default:
3832     return false;
3833   }
3834 
3835   // If the target is likely to fold this extend away, don't propagate.
3836   if (Builder.getTII().isExtendLikelyToBeFolded(*ExtMI, MRI))
3837     return false;
3838 
3839   // We don't want to propagate the extends unless there's a good chance that
3840   // they'll be optimized in some way.
3841   // Collect the unique incoming values.
3842   SmallPtrSet<MachineInstr *, 4> InSrcs;
3843   for (unsigned Idx = 1; Idx < MI.getNumOperands(); Idx += 2) {
3844     auto *DefMI = getDefIgnoringCopies(MI.getOperand(Idx).getReg(), MRI);
3845     switch (DefMI->getOpcode()) {
3846     case TargetOpcode::G_LOAD:
3847     case TargetOpcode::G_TRUNC:
3848     case TargetOpcode::G_SEXT:
3849     case TargetOpcode::G_ZEXT:
3850     case TargetOpcode::G_ANYEXT:
3851     case TargetOpcode::G_CONSTANT:
3852       InSrcs.insert(getDefIgnoringCopies(MI.getOperand(Idx).getReg(), MRI));
3853       // Don't try to propagate if there are too many places to create new
3854       // extends, chances are it'll increase code size.
3855       if (InSrcs.size() > 2)
3856         return false;
3857       break;
3858     default:
3859       return false;
3860     }
3861   }
3862   return true;
3863 }
3864 
3865 void CombinerHelper::applyExtendThroughPhis(MachineInstr &MI,
3866                                             MachineInstr *&ExtMI) {
3867   assert(MI.getOpcode() == TargetOpcode::G_PHI);
3868   Register DstReg = ExtMI->getOperand(0).getReg();
3869   LLT ExtTy = MRI.getType(DstReg);
3870 
3871   // Propagate the extension into the block of each incoming reg's block.
3872   // Use a SetVector here because PHIs can have duplicate edges, and we want
3873   // deterministic iteration order.
3874   SmallSetVector<MachineInstr *, 8> SrcMIs;
3875   SmallDenseMap<MachineInstr *, MachineInstr *, 8> OldToNewSrcMap;
3876   for (unsigned SrcIdx = 1; SrcIdx < MI.getNumOperands(); SrcIdx += 2) {
3877     auto *SrcMI = MRI.getVRegDef(MI.getOperand(SrcIdx).getReg());
3878     if (!SrcMIs.insert(SrcMI))
3879       continue;
3880 
3881     // Build an extend after each src inst.
3882     auto *MBB = SrcMI->getParent();
3883     MachineBasicBlock::iterator InsertPt = ++SrcMI->getIterator();
3884     if (InsertPt != MBB->end() && InsertPt->isPHI())
3885       InsertPt = MBB->getFirstNonPHI();
3886 
3887     Builder.setInsertPt(*SrcMI->getParent(), InsertPt);
3888     Builder.setDebugLoc(MI.getDebugLoc());
3889     auto NewExt = Builder.buildExtOrTrunc(ExtMI->getOpcode(), ExtTy,
3890                                           SrcMI->getOperand(0).getReg());
3891     OldToNewSrcMap[SrcMI] = NewExt;
3892   }
3893 
3894   // Create a new phi with the extended inputs.
3895   Builder.setInstrAndDebugLoc(MI);
3896   auto NewPhi = Builder.buildInstrNoInsert(TargetOpcode::G_PHI);
3897   NewPhi.addDef(DstReg);
3898   for (const MachineOperand &MO : llvm::drop_begin(MI.operands())) {
3899     if (!MO.isReg()) {
3900       NewPhi.addMBB(MO.getMBB());
3901       continue;
3902     }
3903     auto *NewSrc = OldToNewSrcMap[MRI.getVRegDef(MO.getReg())];
3904     NewPhi.addUse(NewSrc->getOperand(0).getReg());
3905   }
3906   Builder.insertInstr(NewPhi);
3907   ExtMI->eraseFromParent();
3908 }
3909 
3910 bool CombinerHelper::matchExtractVecEltBuildVec(MachineInstr &MI,
3911                                                 Register &Reg) {
3912   assert(MI.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT);
3913   // If we have a constant index, look for a G_BUILD_VECTOR source
3914   // and find the source register that the index maps to.
3915   Register SrcVec = MI.getOperand(1).getReg();
3916   LLT SrcTy = MRI.getType(SrcVec);
3917   if (!isLegalOrBeforeLegalizer(
3918           {TargetOpcode::G_BUILD_VECTOR, {SrcTy, SrcTy.getElementType()}}))
3919     return false;
3920 
3921   auto Cst = getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
3922   if (!Cst || Cst->Value.getZExtValue() >= SrcTy.getNumElements())
3923     return false;
3924 
3925   unsigned VecIdx = Cst->Value.getZExtValue();
3926   MachineInstr *BuildVecMI =
3927       getOpcodeDef(TargetOpcode::G_BUILD_VECTOR, SrcVec, MRI);
3928   if (!BuildVecMI) {
3929     BuildVecMI = getOpcodeDef(TargetOpcode::G_BUILD_VECTOR_TRUNC, SrcVec, MRI);
3930     if (!BuildVecMI)
3931       return false;
3932     LLT ScalarTy = MRI.getType(BuildVecMI->getOperand(1).getReg());
3933     if (!isLegalOrBeforeLegalizer(
3934             {TargetOpcode::G_BUILD_VECTOR_TRUNC, {SrcTy, ScalarTy}}))
3935       return false;
3936   }
3937 
3938   EVT Ty(getMVTForLLT(SrcTy));
3939   if (!MRI.hasOneNonDBGUse(SrcVec) &&
3940       !getTargetLowering().aggressivelyPreferBuildVectorSources(Ty))
3941     return false;
3942 
3943   Reg = BuildVecMI->getOperand(VecIdx + 1).getReg();
3944   return true;
3945 }
3946 
3947 void CombinerHelper::applyExtractVecEltBuildVec(MachineInstr &MI,
3948                                                 Register &Reg) {
3949   // Check the type of the register, since it may have come from a
3950   // G_BUILD_VECTOR_TRUNC.
3951   LLT ScalarTy = MRI.getType(Reg);
3952   Register DstReg = MI.getOperand(0).getReg();
3953   LLT DstTy = MRI.getType(DstReg);
3954 
3955   Builder.setInstrAndDebugLoc(MI);
3956   if (ScalarTy != DstTy) {
3957     assert(ScalarTy.getSizeInBits() > DstTy.getSizeInBits());
3958     Builder.buildTrunc(DstReg, Reg);
3959     MI.eraseFromParent();
3960     return;
3961   }
3962   replaceSingleDefInstWithReg(MI, Reg);
3963 }
3964 
3965 bool CombinerHelper::matchExtractAllEltsFromBuildVector(
3966     MachineInstr &MI,
3967     SmallVectorImpl<std::pair<Register, MachineInstr *>> &SrcDstPairs) {
3968   assert(MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR);
3969   // This combine tries to find build_vector's which have every source element
3970   // extracted using G_EXTRACT_VECTOR_ELT. This can happen when transforms like
3971   // the masked load scalarization is run late in the pipeline. There's already
3972   // a combine for a similar pattern starting from the extract, but that
3973   // doesn't attempt to do it if there are multiple uses of the build_vector,
3974   // which in this case is true. Starting the combine from the build_vector
3975   // feels more natural than trying to find sibling nodes of extracts.
3976   // E.g.
3977   //  %vec(<4 x s32>) = G_BUILD_VECTOR %s1(s32), %s2, %s3, %s4
3978   //  %ext1 = G_EXTRACT_VECTOR_ELT %vec, 0
3979   //  %ext2 = G_EXTRACT_VECTOR_ELT %vec, 1
3980   //  %ext3 = G_EXTRACT_VECTOR_ELT %vec, 2
3981   //  %ext4 = G_EXTRACT_VECTOR_ELT %vec, 3
3982   // ==>
3983   // replace ext{1,2,3,4} with %s{1,2,3,4}
3984 
3985   Register DstReg = MI.getOperand(0).getReg();
3986   LLT DstTy = MRI.getType(DstReg);
3987   unsigned NumElts = DstTy.getNumElements();
3988 
3989   SmallBitVector ExtractedElts(NumElts);
3990   for (MachineInstr &II : MRI.use_nodbg_instructions(DstReg)) {
3991     if (II.getOpcode() != TargetOpcode::G_EXTRACT_VECTOR_ELT)
3992       return false;
3993     auto Cst = getIConstantVRegVal(II.getOperand(2).getReg(), MRI);
3994     if (!Cst)
3995       return false;
3996     unsigned Idx = Cst->getZExtValue();
3997     if (Idx >= NumElts)
3998       return false; // Out of range.
3999     ExtractedElts.set(Idx);
4000     SrcDstPairs.emplace_back(
4001         std::make_pair(MI.getOperand(Idx + 1).getReg(), &II));
4002   }
4003   // Match if every element was extracted.
4004   return ExtractedElts.all();
4005 }
4006 
4007 void CombinerHelper::applyExtractAllEltsFromBuildVector(
4008     MachineInstr &MI,
4009     SmallVectorImpl<std::pair<Register, MachineInstr *>> &SrcDstPairs) {
4010   assert(MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR);
4011   for (auto &Pair : SrcDstPairs) {
4012     auto *ExtMI = Pair.second;
4013     replaceRegWith(MRI, ExtMI->getOperand(0).getReg(), Pair.first);
4014     ExtMI->eraseFromParent();
4015   }
4016   MI.eraseFromParent();
4017 }
4018 
4019 void CombinerHelper::applyBuildFn(
4020     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4021   Builder.setInstrAndDebugLoc(MI);
4022   MatchInfo(Builder);
4023   MI.eraseFromParent();
4024 }
4025 
4026 void CombinerHelper::applyBuildFnNoErase(
4027     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4028   Builder.setInstrAndDebugLoc(MI);
4029   MatchInfo(Builder);
4030 }
4031 
4032 bool CombinerHelper::matchOrShiftToFunnelShift(MachineInstr &MI,
4033                                                BuildFnTy &MatchInfo) {
4034   assert(MI.getOpcode() == TargetOpcode::G_OR);
4035 
4036   Register Dst = MI.getOperand(0).getReg();
4037   LLT Ty = MRI.getType(Dst);
4038   unsigned BitWidth = Ty.getScalarSizeInBits();
4039 
4040   Register ShlSrc, ShlAmt, LShrSrc, LShrAmt, Amt;
4041   unsigned FshOpc = 0;
4042 
4043   // Match (or (shl ...), (lshr ...)).
4044   if (!mi_match(Dst, MRI,
4045                 // m_GOr() handles the commuted version as well.
4046                 m_GOr(m_GShl(m_Reg(ShlSrc), m_Reg(ShlAmt)),
4047                       m_GLShr(m_Reg(LShrSrc), m_Reg(LShrAmt)))))
4048     return false;
4049 
4050   // Given constants C0 and C1 such that C0 + C1 is bit-width:
4051   // (or (shl x, C0), (lshr y, C1)) -> (fshl x, y, C0) or (fshr x, y, C1)
4052   int64_t CstShlAmt, CstLShrAmt;
4053   if (mi_match(ShlAmt, MRI, m_ICstOrSplat(CstShlAmt)) &&
4054       mi_match(LShrAmt, MRI, m_ICstOrSplat(CstLShrAmt)) &&
4055       CstShlAmt + CstLShrAmt == BitWidth) {
4056     FshOpc = TargetOpcode::G_FSHR;
4057     Amt = LShrAmt;
4058 
4059   } else if (mi_match(LShrAmt, MRI,
4060                       m_GSub(m_SpecificICstOrSplat(BitWidth), m_Reg(Amt))) &&
4061              ShlAmt == Amt) {
4062     // (or (shl x, amt), (lshr y, (sub bw, amt))) -> (fshl x, y, amt)
4063     FshOpc = TargetOpcode::G_FSHL;
4064 
4065   } else if (mi_match(ShlAmt, MRI,
4066                       m_GSub(m_SpecificICstOrSplat(BitWidth), m_Reg(Amt))) &&
4067              LShrAmt == Amt) {
4068     // (or (shl x, (sub bw, amt)), (lshr y, amt)) -> (fshr x, y, amt)
4069     FshOpc = TargetOpcode::G_FSHR;
4070 
4071   } else {
4072     return false;
4073   }
4074 
4075   LLT AmtTy = MRI.getType(Amt);
4076   if (!isLegalOrBeforeLegalizer({FshOpc, {Ty, AmtTy}}))
4077     return false;
4078 
4079   MatchInfo = [=](MachineIRBuilder &B) {
4080     B.buildInstr(FshOpc, {Dst}, {ShlSrc, LShrSrc, Amt});
4081   };
4082   return true;
4083 }
4084 
4085 /// Match an FSHL or FSHR that can be combined to a ROTR or ROTL rotate.
4086 bool CombinerHelper::matchFunnelShiftToRotate(MachineInstr &MI) {
4087   unsigned Opc = MI.getOpcode();
4088   assert(Opc == TargetOpcode::G_FSHL || Opc == TargetOpcode::G_FSHR);
4089   Register X = MI.getOperand(1).getReg();
4090   Register Y = MI.getOperand(2).getReg();
4091   if (X != Y)
4092     return false;
4093   unsigned RotateOpc =
4094       Opc == TargetOpcode::G_FSHL ? TargetOpcode::G_ROTL : TargetOpcode::G_ROTR;
4095   return isLegalOrBeforeLegalizer({RotateOpc, {MRI.getType(X), MRI.getType(Y)}});
4096 }
4097 
4098 void CombinerHelper::applyFunnelShiftToRotate(MachineInstr &MI) {
4099   unsigned Opc = MI.getOpcode();
4100   assert(Opc == TargetOpcode::G_FSHL || Opc == TargetOpcode::G_FSHR);
4101   bool IsFSHL = Opc == TargetOpcode::G_FSHL;
4102   Observer.changingInstr(MI);
4103   MI.setDesc(Builder.getTII().get(IsFSHL ? TargetOpcode::G_ROTL
4104                                          : TargetOpcode::G_ROTR));
4105   MI.removeOperand(2);
4106   Observer.changedInstr(MI);
4107 }
4108 
4109 // Fold (rot x, c) -> (rot x, c % BitSize)
4110 bool CombinerHelper::matchRotateOutOfRange(MachineInstr &MI) {
4111   assert(MI.getOpcode() == TargetOpcode::G_ROTL ||
4112          MI.getOpcode() == TargetOpcode::G_ROTR);
4113   unsigned Bitsize =
4114       MRI.getType(MI.getOperand(0).getReg()).getScalarSizeInBits();
4115   Register AmtReg = MI.getOperand(2).getReg();
4116   bool OutOfRange = false;
4117   auto MatchOutOfRange = [Bitsize, &OutOfRange](const Constant *C) {
4118     if (auto *CI = dyn_cast<ConstantInt>(C))
4119       OutOfRange |= CI->getValue().uge(Bitsize);
4120     return true;
4121   };
4122   return matchUnaryPredicate(MRI, AmtReg, MatchOutOfRange) && OutOfRange;
4123 }
4124 
4125 void CombinerHelper::applyRotateOutOfRange(MachineInstr &MI) {
4126   assert(MI.getOpcode() == TargetOpcode::G_ROTL ||
4127          MI.getOpcode() == TargetOpcode::G_ROTR);
4128   unsigned Bitsize =
4129       MRI.getType(MI.getOperand(0).getReg()).getScalarSizeInBits();
4130   Builder.setInstrAndDebugLoc(MI);
4131   Register Amt = MI.getOperand(2).getReg();
4132   LLT AmtTy = MRI.getType(Amt);
4133   auto Bits = Builder.buildConstant(AmtTy, Bitsize);
4134   Amt = Builder.buildURem(AmtTy, MI.getOperand(2).getReg(), Bits).getReg(0);
4135   Observer.changingInstr(MI);
4136   MI.getOperand(2).setReg(Amt);
4137   Observer.changedInstr(MI);
4138 }
4139 
4140 bool CombinerHelper::matchICmpToTrueFalseKnownBits(MachineInstr &MI,
4141                                                    int64_t &MatchInfo) {
4142   assert(MI.getOpcode() == TargetOpcode::G_ICMP);
4143   auto Pred = static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
4144   auto KnownLHS = KB->getKnownBits(MI.getOperand(2).getReg());
4145   auto KnownRHS = KB->getKnownBits(MI.getOperand(3).getReg());
4146   Optional<bool> KnownVal;
4147   switch (Pred) {
4148   default:
4149     llvm_unreachable("Unexpected G_ICMP predicate?");
4150   case CmpInst::ICMP_EQ:
4151     KnownVal = KnownBits::eq(KnownLHS, KnownRHS);
4152     break;
4153   case CmpInst::ICMP_NE:
4154     KnownVal = KnownBits::ne(KnownLHS, KnownRHS);
4155     break;
4156   case CmpInst::ICMP_SGE:
4157     KnownVal = KnownBits::sge(KnownLHS, KnownRHS);
4158     break;
4159   case CmpInst::ICMP_SGT:
4160     KnownVal = KnownBits::sgt(KnownLHS, KnownRHS);
4161     break;
4162   case CmpInst::ICMP_SLE:
4163     KnownVal = KnownBits::sle(KnownLHS, KnownRHS);
4164     break;
4165   case CmpInst::ICMP_SLT:
4166     KnownVal = KnownBits::slt(KnownLHS, KnownRHS);
4167     break;
4168   case CmpInst::ICMP_UGE:
4169     KnownVal = KnownBits::uge(KnownLHS, KnownRHS);
4170     break;
4171   case CmpInst::ICMP_UGT:
4172     KnownVal = KnownBits::ugt(KnownLHS, KnownRHS);
4173     break;
4174   case CmpInst::ICMP_ULE:
4175     KnownVal = KnownBits::ule(KnownLHS, KnownRHS);
4176     break;
4177   case CmpInst::ICMP_ULT:
4178     KnownVal = KnownBits::ult(KnownLHS, KnownRHS);
4179     break;
4180   }
4181   if (!KnownVal)
4182     return false;
4183   MatchInfo =
4184       *KnownVal
4185           ? getICmpTrueVal(getTargetLowering(),
4186                            /*IsVector = */
4187                            MRI.getType(MI.getOperand(0).getReg()).isVector(),
4188                            /* IsFP = */ false)
4189           : 0;
4190   return true;
4191 }
4192 
4193 bool CombinerHelper::matchICmpToLHSKnownBits(
4194     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4195   assert(MI.getOpcode() == TargetOpcode::G_ICMP);
4196   // Given:
4197   //
4198   // %x = G_WHATEVER (... x is known to be 0 or 1 ...)
4199   // %cmp = G_ICMP ne %x, 0
4200   //
4201   // Or:
4202   //
4203   // %x = G_WHATEVER (... x is known to be 0 or 1 ...)
4204   // %cmp = G_ICMP eq %x, 1
4205   //
4206   // We can replace %cmp with %x assuming true is 1 on the target.
4207   auto Pred = static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
4208   if (!CmpInst::isEquality(Pred))
4209     return false;
4210   Register Dst = MI.getOperand(0).getReg();
4211   LLT DstTy = MRI.getType(Dst);
4212   if (getICmpTrueVal(getTargetLowering(), DstTy.isVector(),
4213                      /* IsFP = */ false) != 1)
4214     return false;
4215   int64_t OneOrZero = Pred == CmpInst::ICMP_EQ;
4216   if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICst(OneOrZero)))
4217     return false;
4218   Register LHS = MI.getOperand(2).getReg();
4219   auto KnownLHS = KB->getKnownBits(LHS);
4220   if (KnownLHS.getMinValue() != 0 || KnownLHS.getMaxValue() != 1)
4221     return false;
4222   // Make sure replacing Dst with the LHS is a legal operation.
4223   LLT LHSTy = MRI.getType(LHS);
4224   unsigned LHSSize = LHSTy.getSizeInBits();
4225   unsigned DstSize = DstTy.getSizeInBits();
4226   unsigned Op = TargetOpcode::COPY;
4227   if (DstSize != LHSSize)
4228     Op = DstSize < LHSSize ? TargetOpcode::G_TRUNC : TargetOpcode::G_ZEXT;
4229   if (!isLegalOrBeforeLegalizer({Op, {DstTy, LHSTy}}))
4230     return false;
4231   MatchInfo = [=](MachineIRBuilder &B) { B.buildInstr(Op, {Dst}, {LHS}); };
4232   return true;
4233 }
4234 
4235 // Replace (and (or x, c1), c2) with (and x, c2) iff c1 & c2 == 0
4236 bool CombinerHelper::matchAndOrDisjointMask(
4237     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4238   assert(MI.getOpcode() == TargetOpcode::G_AND);
4239 
4240   // Ignore vector types to simplify matching the two constants.
4241   // TODO: do this for vectors and scalars via a demanded bits analysis.
4242   LLT Ty = MRI.getType(MI.getOperand(0).getReg());
4243   if (Ty.isVector())
4244     return false;
4245 
4246   Register Src;
4247   Register AndMaskReg;
4248   int64_t AndMaskBits;
4249   int64_t OrMaskBits;
4250   if (!mi_match(MI, MRI,
4251                 m_GAnd(m_GOr(m_Reg(Src), m_ICst(OrMaskBits)),
4252                        m_all_of(m_ICst(AndMaskBits), m_Reg(AndMaskReg)))))
4253     return false;
4254 
4255   // Check if OrMask could turn on any bits in Src.
4256   if (AndMaskBits & OrMaskBits)
4257     return false;
4258 
4259   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4260     Observer.changingInstr(MI);
4261     // Canonicalize the result to have the constant on the RHS.
4262     if (MI.getOperand(1).getReg() == AndMaskReg)
4263       MI.getOperand(2).setReg(AndMaskReg);
4264     MI.getOperand(1).setReg(Src);
4265     Observer.changedInstr(MI);
4266   };
4267   return true;
4268 }
4269 
4270 /// Form a G_SBFX from a G_SEXT_INREG fed by a right shift.
4271 bool CombinerHelper::matchBitfieldExtractFromSExtInReg(
4272     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4273   assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG);
4274   Register Dst = MI.getOperand(0).getReg();
4275   Register Src = MI.getOperand(1).getReg();
4276   LLT Ty = MRI.getType(Src);
4277   LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4278   if (!LI || !LI->isLegalOrCustom({TargetOpcode::G_SBFX, {Ty, ExtractTy}}))
4279     return false;
4280   int64_t Width = MI.getOperand(2).getImm();
4281   Register ShiftSrc;
4282   int64_t ShiftImm;
4283   if (!mi_match(
4284           Src, MRI,
4285           m_OneNonDBGUse(m_any_of(m_GAShr(m_Reg(ShiftSrc), m_ICst(ShiftImm)),
4286                                   m_GLShr(m_Reg(ShiftSrc), m_ICst(ShiftImm))))))
4287     return false;
4288   if (ShiftImm < 0 || ShiftImm + Width > Ty.getScalarSizeInBits())
4289     return false;
4290 
4291   MatchInfo = [=](MachineIRBuilder &B) {
4292     auto Cst1 = B.buildConstant(ExtractTy, ShiftImm);
4293     auto Cst2 = B.buildConstant(ExtractTy, Width);
4294     B.buildSbfx(Dst, ShiftSrc, Cst1, Cst2);
4295   };
4296   return true;
4297 }
4298 
4299 /// Form a G_UBFX from "(a srl b) & mask", where b and mask are constants.
4300 bool CombinerHelper::matchBitfieldExtractFromAnd(
4301     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4302   assert(MI.getOpcode() == TargetOpcode::G_AND);
4303   Register Dst = MI.getOperand(0).getReg();
4304   LLT Ty = MRI.getType(Dst);
4305   LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4306   if (!getTargetLowering().isConstantUnsignedBitfieldExtractLegal(
4307           TargetOpcode::G_UBFX, Ty, ExtractTy))
4308     return false;
4309 
4310   int64_t AndImm, LSBImm;
4311   Register ShiftSrc;
4312   const unsigned Size = Ty.getScalarSizeInBits();
4313   if (!mi_match(MI.getOperand(0).getReg(), MRI,
4314                 m_GAnd(m_OneNonDBGUse(m_GLShr(m_Reg(ShiftSrc), m_ICst(LSBImm))),
4315                        m_ICst(AndImm))))
4316     return false;
4317 
4318   // The mask is a mask of the low bits iff imm & (imm+1) == 0.
4319   auto MaybeMask = static_cast<uint64_t>(AndImm);
4320   if (MaybeMask & (MaybeMask + 1))
4321     return false;
4322 
4323   // LSB must fit within the register.
4324   if (static_cast<uint64_t>(LSBImm) >= Size)
4325     return false;
4326 
4327   uint64_t Width = APInt(Size, AndImm).countTrailingOnes();
4328   MatchInfo = [=](MachineIRBuilder &B) {
4329     auto WidthCst = B.buildConstant(ExtractTy, Width);
4330     auto LSBCst = B.buildConstant(ExtractTy, LSBImm);
4331     B.buildInstr(TargetOpcode::G_UBFX, {Dst}, {ShiftSrc, LSBCst, WidthCst});
4332   };
4333   return true;
4334 }
4335 
4336 bool CombinerHelper::matchBitfieldExtractFromShr(
4337     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4338   const unsigned Opcode = MI.getOpcode();
4339   assert(Opcode == TargetOpcode::G_ASHR || Opcode == TargetOpcode::G_LSHR);
4340 
4341   const Register Dst = MI.getOperand(0).getReg();
4342 
4343   const unsigned ExtrOpcode = Opcode == TargetOpcode::G_ASHR
4344                                   ? TargetOpcode::G_SBFX
4345                                   : TargetOpcode::G_UBFX;
4346 
4347   // Check if the type we would use for the extract is legal
4348   LLT Ty = MRI.getType(Dst);
4349   LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4350   if (!LI || !LI->isLegalOrCustom({ExtrOpcode, {Ty, ExtractTy}}))
4351     return false;
4352 
4353   Register ShlSrc;
4354   int64_t ShrAmt;
4355   int64_t ShlAmt;
4356   const unsigned Size = Ty.getScalarSizeInBits();
4357 
4358   // Try to match shr (shl x, c1), c2
4359   if (!mi_match(Dst, MRI,
4360                 m_BinOp(Opcode,
4361                         m_OneNonDBGUse(m_GShl(m_Reg(ShlSrc), m_ICst(ShlAmt))),
4362                         m_ICst(ShrAmt))))
4363     return false;
4364 
4365   // Make sure that the shift sizes can fit a bitfield extract
4366   if (ShlAmt < 0 || ShlAmt > ShrAmt || ShrAmt >= Size)
4367     return false;
4368 
4369   // Skip this combine if the G_SEXT_INREG combine could handle it
4370   if (Opcode == TargetOpcode::G_ASHR && ShlAmt == ShrAmt)
4371     return false;
4372 
4373   // Calculate start position and width of the extract
4374   const int64_t Pos = ShrAmt - ShlAmt;
4375   const int64_t Width = Size - ShrAmt;
4376 
4377   MatchInfo = [=](MachineIRBuilder &B) {
4378     auto WidthCst = B.buildConstant(ExtractTy, Width);
4379     auto PosCst = B.buildConstant(ExtractTy, Pos);
4380     B.buildInstr(ExtrOpcode, {Dst}, {ShlSrc, PosCst, WidthCst});
4381   };
4382   return true;
4383 }
4384 
4385 bool CombinerHelper::matchBitfieldExtractFromShrAnd(
4386     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4387   const unsigned Opcode = MI.getOpcode();
4388   assert(Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_ASHR);
4389 
4390   const Register Dst = MI.getOperand(0).getReg();
4391   LLT Ty = MRI.getType(Dst);
4392   LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4393   if (!getTargetLowering().isConstantUnsignedBitfieldExtractLegal(
4394           TargetOpcode::G_UBFX, Ty, ExtractTy))
4395     return false;
4396 
4397   // Try to match shr (and x, c1), c2
4398   Register AndSrc;
4399   int64_t ShrAmt;
4400   int64_t SMask;
4401   if (!mi_match(Dst, MRI,
4402                 m_BinOp(Opcode,
4403                         m_OneNonDBGUse(m_GAnd(m_Reg(AndSrc), m_ICst(SMask))),
4404                         m_ICst(ShrAmt))))
4405     return false;
4406 
4407   const unsigned Size = Ty.getScalarSizeInBits();
4408   if (ShrAmt < 0 || ShrAmt >= Size)
4409     return false;
4410 
4411   // If the shift subsumes the mask, emit the 0 directly.
4412   if (0 == (SMask >> ShrAmt)) {
4413     MatchInfo = [=](MachineIRBuilder &B) {
4414       B.buildConstant(Dst, 0);
4415     };
4416     return true;
4417   }
4418 
4419   // Check that ubfx can do the extraction, with no holes in the mask.
4420   uint64_t UMask = SMask;
4421   UMask |= maskTrailingOnes<uint64_t>(ShrAmt);
4422   UMask &= maskTrailingOnes<uint64_t>(Size);
4423   if (!isMask_64(UMask))
4424     return false;
4425 
4426   // Calculate start position and width of the extract.
4427   const int64_t Pos = ShrAmt;
4428   const int64_t Width = countTrailingOnes(UMask) - ShrAmt;
4429 
4430   // It's preferable to keep the shift, rather than form G_SBFX.
4431   // TODO: remove the G_AND via demanded bits analysis.
4432   if (Opcode == TargetOpcode::G_ASHR && Width + ShrAmt == Size)
4433     return false;
4434 
4435   MatchInfo = [=](MachineIRBuilder &B) {
4436     auto WidthCst = B.buildConstant(ExtractTy, Width);
4437     auto PosCst = B.buildConstant(ExtractTy, Pos);
4438     B.buildInstr(TargetOpcode::G_UBFX, {Dst}, {AndSrc, PosCst, WidthCst});
4439   };
4440   return true;
4441 }
4442 
4443 bool CombinerHelper::reassociationCanBreakAddressingModePattern(
4444     MachineInstr &PtrAdd) {
4445   assert(PtrAdd.getOpcode() == TargetOpcode::G_PTR_ADD);
4446 
4447   Register Src1Reg = PtrAdd.getOperand(1).getReg();
4448   MachineInstr *Src1Def = getOpcodeDef(TargetOpcode::G_PTR_ADD, Src1Reg, MRI);
4449   if (!Src1Def)
4450     return false;
4451 
4452   Register Src2Reg = PtrAdd.getOperand(2).getReg();
4453 
4454   if (MRI.hasOneNonDBGUse(Src1Reg))
4455     return false;
4456 
4457   auto C1 = getIConstantVRegVal(Src1Def->getOperand(2).getReg(), MRI);
4458   if (!C1)
4459     return false;
4460   auto C2 = getIConstantVRegVal(Src2Reg, MRI);
4461   if (!C2)
4462     return false;
4463 
4464   const APInt &C1APIntVal = *C1;
4465   const APInt &C2APIntVal = *C2;
4466   const int64_t CombinedValue = (C1APIntVal + C2APIntVal).getSExtValue();
4467 
4468   for (auto &UseMI : MRI.use_nodbg_instructions(Src1Reg)) {
4469     // This combine may end up running before ptrtoint/inttoptr combines
4470     // manage to eliminate redundant conversions, so try to look through them.
4471     MachineInstr *ConvUseMI = &UseMI;
4472     unsigned ConvUseOpc = ConvUseMI->getOpcode();
4473     while (ConvUseOpc == TargetOpcode::G_INTTOPTR ||
4474            ConvUseOpc == TargetOpcode::G_PTRTOINT) {
4475       Register DefReg = ConvUseMI->getOperand(0).getReg();
4476       if (!MRI.hasOneNonDBGUse(DefReg))
4477         break;
4478       ConvUseMI = &*MRI.use_instr_nodbg_begin(DefReg);
4479       ConvUseOpc = ConvUseMI->getOpcode();
4480     }
4481     auto LoadStore = ConvUseOpc == TargetOpcode::G_LOAD ||
4482                      ConvUseOpc == TargetOpcode::G_STORE;
4483     if (!LoadStore)
4484       continue;
4485     // Is x[offset2] already not a legal addressing mode? If so then
4486     // reassociating the constants breaks nothing (we test offset2 because
4487     // that's the one we hope to fold into the load or store).
4488     TargetLoweringBase::AddrMode AM;
4489     AM.HasBaseReg = true;
4490     AM.BaseOffs = C2APIntVal.getSExtValue();
4491     unsigned AS =
4492         MRI.getType(ConvUseMI->getOperand(1).getReg()).getAddressSpace();
4493     Type *AccessTy =
4494         getTypeForLLT(MRI.getType(ConvUseMI->getOperand(0).getReg()),
4495                       PtrAdd.getMF()->getFunction().getContext());
4496     const auto &TLI = *PtrAdd.getMF()->getSubtarget().getTargetLowering();
4497     if (!TLI.isLegalAddressingMode(PtrAdd.getMF()->getDataLayout(), AM,
4498                                    AccessTy, AS))
4499       continue;
4500 
4501     // Would x[offset1+offset2] still be a legal addressing mode?
4502     AM.BaseOffs = CombinedValue;
4503     if (!TLI.isLegalAddressingMode(PtrAdd.getMF()->getDataLayout(), AM,
4504                                    AccessTy, AS))
4505       return true;
4506   }
4507 
4508   return false;
4509 }
4510 
4511 bool CombinerHelper::matchReassocConstantInnerRHS(GPtrAdd &MI,
4512                                                   MachineInstr *RHS,
4513                                                   BuildFnTy &MatchInfo) {
4514   // G_PTR_ADD(BASE, G_ADD(X, C)) -> G_PTR_ADD(G_PTR_ADD(BASE, X), C)
4515   Register Src1Reg = MI.getOperand(1).getReg();
4516   if (RHS->getOpcode() != TargetOpcode::G_ADD)
4517     return false;
4518   auto C2 = getIConstantVRegVal(RHS->getOperand(2).getReg(), MRI);
4519   if (!C2)
4520     return false;
4521 
4522   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4523     LLT PtrTy = MRI.getType(MI.getOperand(0).getReg());
4524 
4525     auto NewBase =
4526         Builder.buildPtrAdd(PtrTy, Src1Reg, RHS->getOperand(1).getReg());
4527     Observer.changingInstr(MI);
4528     MI.getOperand(1).setReg(NewBase.getReg(0));
4529     MI.getOperand(2).setReg(RHS->getOperand(2).getReg());
4530     Observer.changedInstr(MI);
4531   };
4532   return !reassociationCanBreakAddressingModePattern(MI);
4533 }
4534 
4535 bool CombinerHelper::matchReassocConstantInnerLHS(GPtrAdd &MI,
4536                                                   MachineInstr *LHS,
4537                                                   MachineInstr *RHS,
4538                                                   BuildFnTy &MatchInfo) {
4539   // G_PTR_ADD (G_PTR_ADD X, C), Y) -> (G_PTR_ADD (G_PTR_ADD(X, Y), C)
4540   // if and only if (G_PTR_ADD X, C) has one use.
4541   Register LHSBase;
4542   Optional<ValueAndVReg> LHSCstOff;
4543   if (!mi_match(MI.getBaseReg(), MRI,
4544                 m_OneNonDBGUse(m_GPtrAdd(m_Reg(LHSBase), m_GCst(LHSCstOff)))))
4545     return false;
4546 
4547   auto *LHSPtrAdd = cast<GPtrAdd>(LHS);
4548   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4549     // When we change LHSPtrAdd's offset register we might cause it to use a reg
4550     // before its def. Sink the instruction so the outer PTR_ADD to ensure this
4551     // doesn't happen.
4552     LHSPtrAdd->moveBefore(&MI);
4553     Register RHSReg = MI.getOffsetReg();
4554     Observer.changingInstr(MI);
4555     MI.getOperand(2).setReg(LHSCstOff->VReg);
4556     Observer.changedInstr(MI);
4557     Observer.changingInstr(*LHSPtrAdd);
4558     LHSPtrAdd->getOperand(2).setReg(RHSReg);
4559     Observer.changedInstr(*LHSPtrAdd);
4560   };
4561   return !reassociationCanBreakAddressingModePattern(MI);
4562 }
4563 
4564 bool CombinerHelper::matchReassocFoldConstantsInSubTree(GPtrAdd &MI,
4565                                                         MachineInstr *LHS,
4566                                                         MachineInstr *RHS,
4567                                                         BuildFnTy &MatchInfo) {
4568   // G_PTR_ADD(G_PTR_ADD(BASE, C1), C2) -> G_PTR_ADD(BASE, C1+C2)
4569   auto *LHSPtrAdd = dyn_cast<GPtrAdd>(LHS);
4570   if (!LHSPtrAdd)
4571     return false;
4572 
4573   Register Src2Reg = MI.getOperand(2).getReg();
4574   Register LHSSrc1 = LHSPtrAdd->getBaseReg();
4575   Register LHSSrc2 = LHSPtrAdd->getOffsetReg();
4576   auto C1 = getIConstantVRegVal(LHSSrc2, MRI);
4577   if (!C1)
4578     return false;
4579   auto C2 = getIConstantVRegVal(Src2Reg, MRI);
4580   if (!C2)
4581     return false;
4582 
4583   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4584     auto NewCst = B.buildConstant(MRI.getType(Src2Reg), *C1 + *C2);
4585     Observer.changingInstr(MI);
4586     MI.getOperand(1).setReg(LHSSrc1);
4587     MI.getOperand(2).setReg(NewCst.getReg(0));
4588     Observer.changedInstr(MI);
4589   };
4590   return !reassociationCanBreakAddressingModePattern(MI);
4591 }
4592 
4593 bool CombinerHelper::matchReassocPtrAdd(MachineInstr &MI,
4594                                         BuildFnTy &MatchInfo) {
4595   auto &PtrAdd = cast<GPtrAdd>(MI);
4596   // We're trying to match a few pointer computation patterns here for
4597   // re-association opportunities.
4598   // 1) Isolating a constant operand to be on the RHS, e.g.:
4599   // G_PTR_ADD(BASE, G_ADD(X, C)) -> G_PTR_ADD(G_PTR_ADD(BASE, X), C)
4600   //
4601   // 2) Folding two constants in each sub-tree as long as such folding
4602   // doesn't break a legal addressing mode.
4603   // G_PTR_ADD(G_PTR_ADD(BASE, C1), C2) -> G_PTR_ADD(BASE, C1+C2)
4604   //
4605   // 3) Move a constant from the LHS of an inner op to the RHS of the outer.
4606   // G_PTR_ADD (G_PTR_ADD X, C), Y) -> G_PTR_ADD (G_PTR_ADD(X, Y), C)
4607   // iif (G_PTR_ADD X, C) has one use.
4608   MachineInstr *LHS = MRI.getVRegDef(PtrAdd.getBaseReg());
4609   MachineInstr *RHS = MRI.getVRegDef(PtrAdd.getOffsetReg());
4610 
4611   // Try to match example 2.
4612   if (matchReassocFoldConstantsInSubTree(PtrAdd, LHS, RHS, MatchInfo))
4613     return true;
4614 
4615   // Try to match example 3.
4616   if (matchReassocConstantInnerLHS(PtrAdd, LHS, RHS, MatchInfo))
4617     return true;
4618 
4619   // Try to match example 1.
4620   if (matchReassocConstantInnerRHS(PtrAdd, RHS, MatchInfo))
4621     return true;
4622 
4623   return false;
4624 }
4625 
4626 bool CombinerHelper::matchConstantFold(MachineInstr &MI, APInt &MatchInfo) {
4627   Register Op1 = MI.getOperand(1).getReg();
4628   Register Op2 = MI.getOperand(2).getReg();
4629   auto MaybeCst = ConstantFoldBinOp(MI.getOpcode(), Op1, Op2, MRI);
4630   if (!MaybeCst)
4631     return false;
4632   MatchInfo = *MaybeCst;
4633   return true;
4634 }
4635 
4636 bool CombinerHelper::matchNarrowBinopFeedingAnd(
4637     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
4638   // Look for a binop feeding into an AND with a mask:
4639   //
4640   // %add = G_ADD %lhs, %rhs
4641   // %and = G_AND %add, 000...11111111
4642   //
4643   // Check if it's possible to perform the binop at a narrower width and zext
4644   // back to the original width like so:
4645   //
4646   // %narrow_lhs = G_TRUNC %lhs
4647   // %narrow_rhs = G_TRUNC %rhs
4648   // %narrow_add = G_ADD %narrow_lhs, %narrow_rhs
4649   // %new_add = G_ZEXT %narrow_add
4650   // %and = G_AND %new_add, 000...11111111
4651   //
4652   // This can allow later combines to eliminate the G_AND if it turns out
4653   // that the mask is irrelevant.
4654   assert(MI.getOpcode() == TargetOpcode::G_AND);
4655   Register Dst = MI.getOperand(0).getReg();
4656   Register AndLHS = MI.getOperand(1).getReg();
4657   Register AndRHS = MI.getOperand(2).getReg();
4658   LLT WideTy = MRI.getType(Dst);
4659 
4660   // If the potential binop has more than one use, then it's possible that one
4661   // of those uses will need its full width.
4662   if (!WideTy.isScalar() || !MRI.hasOneNonDBGUse(AndLHS))
4663     return false;
4664 
4665   // Check if the LHS feeding the AND is impacted by the high bits that we're
4666   // masking out.
4667   //
4668   // e.g. for 64-bit x, y:
4669   //
4670   // add_64(x, y) & 65535 == zext(add_16(trunc(x), trunc(y))) & 65535
4671   MachineInstr *LHSInst = getDefIgnoringCopies(AndLHS, MRI);
4672   if (!LHSInst)
4673     return false;
4674   unsigned LHSOpc = LHSInst->getOpcode();
4675   switch (LHSOpc) {
4676   default:
4677     return false;
4678   case TargetOpcode::G_ADD:
4679   case TargetOpcode::G_SUB:
4680   case TargetOpcode::G_MUL:
4681   case TargetOpcode::G_AND:
4682   case TargetOpcode::G_OR:
4683   case TargetOpcode::G_XOR:
4684     break;
4685   }
4686 
4687   // Find the mask on the RHS.
4688   auto Cst = getIConstantVRegValWithLookThrough(AndRHS, MRI);
4689   if (!Cst)
4690     return false;
4691   auto Mask = Cst->Value;
4692   if (!Mask.isMask())
4693     return false;
4694 
4695   // No point in combining if there's nothing to truncate.
4696   unsigned NarrowWidth = Mask.countTrailingOnes();
4697   if (NarrowWidth == WideTy.getSizeInBits())
4698     return false;
4699   LLT NarrowTy = LLT::scalar(NarrowWidth);
4700 
4701   // Check if adding the zext + truncates could be harmful.
4702   auto &MF = *MI.getMF();
4703   const auto &TLI = getTargetLowering();
4704   LLVMContext &Ctx = MF.getFunction().getContext();
4705   auto &DL = MF.getDataLayout();
4706   if (!TLI.isTruncateFree(WideTy, NarrowTy, DL, Ctx) ||
4707       !TLI.isZExtFree(NarrowTy, WideTy, DL, Ctx))
4708     return false;
4709   if (!isLegalOrBeforeLegalizer({TargetOpcode::G_TRUNC, {NarrowTy, WideTy}}) ||
4710       !isLegalOrBeforeLegalizer({TargetOpcode::G_ZEXT, {WideTy, NarrowTy}}))
4711     return false;
4712   Register BinOpLHS = LHSInst->getOperand(1).getReg();
4713   Register BinOpRHS = LHSInst->getOperand(2).getReg();
4714   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4715     auto NarrowLHS = Builder.buildTrunc(NarrowTy, BinOpLHS);
4716     auto NarrowRHS = Builder.buildTrunc(NarrowTy, BinOpRHS);
4717     auto NarrowBinOp =
4718         Builder.buildInstr(LHSOpc, {NarrowTy}, {NarrowLHS, NarrowRHS});
4719     auto Ext = Builder.buildZExt(WideTy, NarrowBinOp);
4720     Observer.changingInstr(MI);
4721     MI.getOperand(1).setReg(Ext.getReg(0));
4722     Observer.changedInstr(MI);
4723   };
4724   return true;
4725 }
4726 
4727 bool CombinerHelper::matchMulOBy2(MachineInstr &MI, BuildFnTy &MatchInfo) {
4728   unsigned Opc = MI.getOpcode();
4729   assert(Opc == TargetOpcode::G_UMULO || Opc == TargetOpcode::G_SMULO);
4730 
4731   if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICstOrSplat(2)))
4732     return false;
4733 
4734   MatchInfo = [=, &MI](MachineIRBuilder &B) {
4735     Observer.changingInstr(MI);
4736     unsigned NewOpc = Opc == TargetOpcode::G_UMULO ? TargetOpcode::G_UADDO
4737                                                    : TargetOpcode::G_SADDO;
4738     MI.setDesc(Builder.getTII().get(NewOpc));
4739     MI.getOperand(3).setReg(MI.getOperand(2).getReg());
4740     Observer.changedInstr(MI);
4741   };
4742   return true;
4743 }
4744 
4745 bool CombinerHelper::matchMulOBy0(MachineInstr &MI, BuildFnTy &MatchInfo) {
4746   // (G_*MULO x, 0) -> 0 + no carry out
4747   assert(MI.getOpcode() == TargetOpcode::G_UMULO ||
4748          MI.getOpcode() == TargetOpcode::G_SMULO);
4749   if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICstOrSplat(0)))
4750     return false;
4751   Register Dst = MI.getOperand(0).getReg();
4752   Register Carry = MI.getOperand(1).getReg();
4753   if (!isConstantLegalOrBeforeLegalizer(MRI.getType(Dst)) ||
4754       !isConstantLegalOrBeforeLegalizer(MRI.getType(Carry)))
4755     return false;
4756   MatchInfo = [=](MachineIRBuilder &B) {
4757     B.buildConstant(Dst, 0);
4758     B.buildConstant(Carry, 0);
4759   };
4760   return true;
4761 }
4762 
4763 bool CombinerHelper::matchAddOBy0(MachineInstr &MI, BuildFnTy &MatchInfo) {
4764   // (G_*ADDO x, 0) -> x + no carry out
4765   assert(MI.getOpcode() == TargetOpcode::G_UADDO ||
4766          MI.getOpcode() == TargetOpcode::G_SADDO);
4767   if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICstOrSplat(0)))
4768     return false;
4769   Register Carry = MI.getOperand(1).getReg();
4770   if (!isConstantLegalOrBeforeLegalizer(MRI.getType(Carry)))
4771     return false;
4772   Register Dst = MI.getOperand(0).getReg();
4773   Register LHS = MI.getOperand(2).getReg();
4774   MatchInfo = [=](MachineIRBuilder &B) {
4775     B.buildCopy(Dst, LHS);
4776     B.buildConstant(Carry, 0);
4777   };
4778   return true;
4779 }
4780 
4781 MachineInstr *CombinerHelper::buildUDivUsingMul(MachineInstr &MI) {
4782   assert(MI.getOpcode() == TargetOpcode::G_UDIV);
4783   auto &UDiv = cast<GenericMachineInstr>(MI);
4784   Register Dst = UDiv.getReg(0);
4785   Register LHS = UDiv.getReg(1);
4786   Register RHS = UDiv.getReg(2);
4787   LLT Ty = MRI.getType(Dst);
4788   LLT ScalarTy = Ty.getScalarType();
4789   const unsigned EltBits = ScalarTy.getScalarSizeInBits();
4790   LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4791   LLT ScalarShiftAmtTy = ShiftAmtTy.getScalarType();
4792   auto &MIB = Builder;
4793   MIB.setInstrAndDebugLoc(MI);
4794 
4795   bool UseNPQ = false;
4796   SmallVector<Register, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
4797 
4798   auto BuildUDIVPattern = [&](const Constant *C) {
4799     auto *CI = cast<ConstantInt>(C);
4800     const APInt &Divisor = CI->getValue();
4801     UnsignedDivisonByConstantInfo magics =
4802         UnsignedDivisonByConstantInfo::get(Divisor);
4803     unsigned PreShift = 0, PostShift = 0;
4804 
4805     // If the divisor is even, we can avoid using the expensive fixup by
4806     // shifting the divided value upfront.
4807     if (magics.IsAdd != 0 && !Divisor[0]) {
4808       PreShift = Divisor.countTrailingZeros();
4809       // Get magic number for the shifted divisor.
4810       magics =
4811           UnsignedDivisonByConstantInfo::get(Divisor.lshr(PreShift), PreShift);
4812       assert(magics.IsAdd == 0 && "Should use cheap fixup now");
4813     }
4814 
4815     APInt Magic = magics.Magic;
4816 
4817     unsigned SelNPQ;
4818     if (magics.IsAdd == 0 || Divisor.isOneValue()) {
4819       assert(magics.ShiftAmount < Divisor.getBitWidth() &&
4820              "We shouldn't generate an undefined shift!");
4821       PostShift = magics.ShiftAmount;
4822       SelNPQ = false;
4823     } else {
4824       PostShift = magics.ShiftAmount - 1;
4825       SelNPQ = true;
4826     }
4827 
4828     PreShifts.push_back(
4829         MIB.buildConstant(ScalarShiftAmtTy, PreShift).getReg(0));
4830     MagicFactors.push_back(MIB.buildConstant(ScalarTy, Magic).getReg(0));
4831     NPQFactors.push_back(
4832         MIB.buildConstant(ScalarTy,
4833                           SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1)
4834                                  : APInt::getZero(EltBits))
4835             .getReg(0));
4836     PostShifts.push_back(
4837         MIB.buildConstant(ScalarShiftAmtTy, PostShift).getReg(0));
4838     UseNPQ |= SelNPQ;
4839     return true;
4840   };
4841 
4842   // Collect the shifts/magic values from each element.
4843   bool Matched = matchUnaryPredicate(MRI, RHS, BuildUDIVPattern);
4844   (void)Matched;
4845   assert(Matched && "Expected unary predicate match to succeed");
4846 
4847   Register PreShift, PostShift, MagicFactor, NPQFactor;
4848   auto *RHSDef = getOpcodeDef<GBuildVector>(RHS, MRI);
4849   if (RHSDef) {
4850     PreShift = MIB.buildBuildVector(ShiftAmtTy, PreShifts).getReg(0);
4851     MagicFactor = MIB.buildBuildVector(Ty, MagicFactors).getReg(0);
4852     NPQFactor = MIB.buildBuildVector(Ty, NPQFactors).getReg(0);
4853     PostShift = MIB.buildBuildVector(ShiftAmtTy, PostShifts).getReg(0);
4854   } else {
4855     assert(MRI.getType(RHS).isScalar() &&
4856            "Non-build_vector operation should have been a scalar");
4857     PreShift = PreShifts[0];
4858     MagicFactor = MagicFactors[0];
4859     PostShift = PostShifts[0];
4860   }
4861 
4862   Register Q = LHS;
4863   Q = MIB.buildLShr(Ty, Q, PreShift).getReg(0);
4864 
4865   // Multiply the numerator (operand 0) by the magic value.
4866   Q = MIB.buildUMulH(Ty, Q, MagicFactor).getReg(0);
4867 
4868   if (UseNPQ) {
4869     Register NPQ = MIB.buildSub(Ty, LHS, Q).getReg(0);
4870 
4871     // For vectors we might have a mix of non-NPQ/NPQ paths, so use
4872     // G_UMULH to act as a SRL-by-1 for NPQ, else multiply by zero.
4873     if (Ty.isVector())
4874       NPQ = MIB.buildUMulH(Ty, NPQ, NPQFactor).getReg(0);
4875     else
4876       NPQ = MIB.buildLShr(Ty, NPQ, MIB.buildConstant(ShiftAmtTy, 1)).getReg(0);
4877 
4878     Q = MIB.buildAdd(Ty, NPQ, Q).getReg(0);
4879   }
4880 
4881   Q = MIB.buildLShr(Ty, Q, PostShift).getReg(0);
4882   auto One = MIB.buildConstant(Ty, 1);
4883   auto IsOne = MIB.buildICmp(
4884       CmpInst::Predicate::ICMP_EQ,
4885       Ty.isScalar() ? LLT::scalar(1) : Ty.changeElementSize(1), RHS, One);
4886   return MIB.buildSelect(Ty, IsOne, LHS, Q);
4887 }
4888 
4889 bool CombinerHelper::matchUDivByConst(MachineInstr &MI) {
4890   assert(MI.getOpcode() == TargetOpcode::G_UDIV);
4891   Register Dst = MI.getOperand(0).getReg();
4892   Register RHS = MI.getOperand(2).getReg();
4893   LLT DstTy = MRI.getType(Dst);
4894   auto *RHSDef = MRI.getVRegDef(RHS);
4895   if (!isConstantOrConstantVector(*RHSDef, MRI))
4896     return false;
4897 
4898   auto &MF = *MI.getMF();
4899   AttributeList Attr = MF.getFunction().getAttributes();
4900   const auto &TLI = getTargetLowering();
4901   LLVMContext &Ctx = MF.getFunction().getContext();
4902   auto &DL = MF.getDataLayout();
4903   if (TLI.isIntDivCheap(getApproximateEVTForLLT(DstTy, DL, Ctx), Attr))
4904     return false;
4905 
4906   // Don't do this for minsize because the instruction sequence is usually
4907   // larger.
4908   if (MF.getFunction().hasMinSize())
4909     return false;
4910 
4911   // Don't do this if the types are not going to be legal.
4912   if (LI) {
4913     if (!isLegalOrBeforeLegalizer({TargetOpcode::G_MUL, {DstTy, DstTy}}))
4914       return false;
4915     if (!isLegalOrBeforeLegalizer({TargetOpcode::G_UMULH, {DstTy}}))
4916       return false;
4917     if (!isLegalOrBeforeLegalizer(
4918             {TargetOpcode::G_ICMP,
4919              {DstTy.isVector() ? DstTy.changeElementSize(1) : LLT::scalar(1),
4920               DstTy}}))
4921       return false;
4922   }
4923 
4924   auto CheckEltValue = [&](const Constant *C) {
4925     if (auto *CI = dyn_cast_or_null<ConstantInt>(C))
4926       return !CI->isZero();
4927     return false;
4928   };
4929   return matchUnaryPredicate(MRI, RHS, CheckEltValue);
4930 }
4931 
4932 void CombinerHelper::applyUDivByConst(MachineInstr &MI) {
4933   auto *NewMI = buildUDivUsingMul(MI);
4934   replaceSingleDefInstWithReg(MI, NewMI->getOperand(0).getReg());
4935 }
4936 
4937 bool CombinerHelper::matchUMulHToLShr(MachineInstr &MI) {
4938   assert(MI.getOpcode() == TargetOpcode::G_UMULH);
4939   Register RHS = MI.getOperand(2).getReg();
4940   Register Dst = MI.getOperand(0).getReg();
4941   LLT Ty = MRI.getType(Dst);
4942   LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4943   auto MatchPow2ExceptOne = [&](const Constant *C) {
4944     if (auto *CI = dyn_cast<ConstantInt>(C))
4945       return CI->getValue().isPowerOf2() && !CI->getValue().isOne();
4946     return false;
4947   };
4948   if (!matchUnaryPredicate(MRI, RHS, MatchPow2ExceptOne, false))
4949     return false;
4950   return isLegalOrBeforeLegalizer({TargetOpcode::G_LSHR, {Ty, ShiftAmtTy}});
4951 }
4952 
4953 void CombinerHelper::applyUMulHToLShr(MachineInstr &MI) {
4954   Register LHS = MI.getOperand(1).getReg();
4955   Register RHS = MI.getOperand(2).getReg();
4956   Register Dst = MI.getOperand(0).getReg();
4957   LLT Ty = MRI.getType(Dst);
4958   LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
4959   unsigned NumEltBits = Ty.getScalarSizeInBits();
4960 
4961   Builder.setInstrAndDebugLoc(MI);
4962   auto LogBase2 = buildLogBase2(RHS, Builder);
4963   auto ShiftAmt =
4964       Builder.buildSub(Ty, Builder.buildConstant(Ty, NumEltBits), LogBase2);
4965   auto Trunc = Builder.buildZExtOrTrunc(ShiftAmtTy, ShiftAmt);
4966   Builder.buildLShr(Dst, LHS, Trunc);
4967   MI.eraseFromParent();
4968 }
4969 
4970 bool CombinerHelper::matchRedundantNegOperands(MachineInstr &MI,
4971                                                BuildFnTy &MatchInfo) {
4972   unsigned Opc = MI.getOpcode();
4973   assert(Opc == TargetOpcode::G_FADD || Opc == TargetOpcode::G_FSUB ||
4974          Opc == TargetOpcode::G_FMUL || Opc == TargetOpcode::G_FDIV ||
4975          Opc == TargetOpcode::G_FMAD || Opc == TargetOpcode::G_FMA);
4976 
4977   Register Dst = MI.getOperand(0).getReg();
4978   Register X = MI.getOperand(1).getReg();
4979   Register Y = MI.getOperand(2).getReg();
4980   LLT Type = MRI.getType(Dst);
4981 
4982   // fold (fadd x, fneg(y)) -> (fsub x, y)
4983   // fold (fadd fneg(y), x) -> (fsub x, y)
4984   // G_ADD is commutative so both cases are checked by m_GFAdd
4985   if (mi_match(Dst, MRI, m_GFAdd(m_Reg(X), m_GFNeg(m_Reg(Y)))) &&
4986       isLegalOrBeforeLegalizer({TargetOpcode::G_FSUB, {Type}})) {
4987     Opc = TargetOpcode::G_FSUB;
4988   }
4989   /// fold (fsub x, fneg(y)) -> (fadd x, y)
4990   else if (mi_match(Dst, MRI, m_GFSub(m_Reg(X), m_GFNeg(m_Reg(Y)))) &&
4991            isLegalOrBeforeLegalizer({TargetOpcode::G_FADD, {Type}})) {
4992     Opc = TargetOpcode::G_FADD;
4993   }
4994   // fold (fmul fneg(x), fneg(y)) -> (fmul x, y)
4995   // fold (fdiv fneg(x), fneg(y)) -> (fdiv x, y)
4996   // fold (fmad fneg(x), fneg(y), z) -> (fmad x, y, z)
4997   // fold (fma fneg(x), fneg(y), z) -> (fma x, y, z)
4998   else if ((Opc == TargetOpcode::G_FMUL || Opc == TargetOpcode::G_FDIV ||
4999             Opc == TargetOpcode::G_FMAD || Opc == TargetOpcode::G_FMA) &&
5000            mi_match(X, MRI, m_GFNeg(m_Reg(X))) &&
5001            mi_match(Y, MRI, m_GFNeg(m_Reg(Y)))) {
5002     // no opcode change
5003   } else
5004     return false;
5005 
5006   MatchInfo = [=, &MI](MachineIRBuilder &B) {
5007     Observer.changingInstr(MI);
5008     MI.setDesc(B.getTII().get(Opc));
5009     MI.getOperand(1).setReg(X);
5010     MI.getOperand(2).setReg(Y);
5011     Observer.changedInstr(MI);
5012   };
5013   return true;
5014 }
5015 
5016 /// Checks if \p MI is TargetOpcode::G_FMUL and contractable either
5017 /// due to global flags or MachineInstr flags.
5018 static bool isContractableFMul(MachineInstr &MI, bool AllowFusionGlobally) {
5019   if (MI.getOpcode() != TargetOpcode::G_FMUL)
5020     return false;
5021   return AllowFusionGlobally || MI.getFlag(MachineInstr::MIFlag::FmContract);
5022 }
5023 
5024 static bool hasMoreUses(const MachineInstr &MI0, const MachineInstr &MI1,
5025                         const MachineRegisterInfo &MRI) {
5026   return std::distance(MRI.use_instr_nodbg_begin(MI0.getOperand(0).getReg()),
5027                        MRI.use_instr_nodbg_end()) >
5028          std::distance(MRI.use_instr_nodbg_begin(MI1.getOperand(0).getReg()),
5029                        MRI.use_instr_nodbg_end());
5030 }
5031 
5032 bool CombinerHelper::canCombineFMadOrFMA(MachineInstr &MI,
5033                                          bool &AllowFusionGlobally,
5034                                          bool &HasFMAD, bool &Aggressive,
5035                                          bool CanReassociate) {
5036 
5037   auto *MF = MI.getMF();
5038   const auto &TLI = *MF->getSubtarget().getTargetLowering();
5039   const TargetOptions &Options = MF->getTarget().Options;
5040   LLT DstType = MRI.getType(MI.getOperand(0).getReg());
5041 
5042   if (CanReassociate &&
5043       !(Options.UnsafeFPMath || MI.getFlag(MachineInstr::MIFlag::FmReassoc)))
5044     return false;
5045 
5046   // Floating-point multiply-add with intermediate rounding.
5047   HasFMAD = (LI && TLI.isFMADLegal(MI, DstType));
5048   // Floating-point multiply-add without intermediate rounding.
5049   bool HasFMA = TLI.isFMAFasterThanFMulAndFAdd(*MF, DstType) &&
5050                 isLegalOrBeforeLegalizer({TargetOpcode::G_FMA, {DstType}});
5051   // No valid opcode, do not combine.
5052   if (!HasFMAD && !HasFMA)
5053     return false;
5054 
5055   AllowFusionGlobally = Options.AllowFPOpFusion == FPOpFusion::Fast ||
5056                         Options.UnsafeFPMath || HasFMAD;
5057   // If the addition is not contractable, do not combine.
5058   if (!AllowFusionGlobally && !MI.getFlag(MachineInstr::MIFlag::FmContract))
5059     return false;
5060 
5061   Aggressive = TLI.enableAggressiveFMAFusion(DstType);
5062   return true;
5063 }
5064 
5065 bool CombinerHelper::matchCombineFAddFMulToFMadOrFMA(
5066     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
5067   assert(MI.getOpcode() == TargetOpcode::G_FADD);
5068 
5069   bool AllowFusionGlobally, HasFMAD, Aggressive;
5070   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
5071     return false;
5072 
5073   Register Op1 = MI.getOperand(1).getReg();
5074   Register Op2 = MI.getOperand(2).getReg();
5075   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
5076   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
5077   unsigned PreferredFusedOpcode =
5078       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
5079 
5080   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
5081   // prefer to fold the multiply with fewer uses.
5082   if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
5083       isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
5084     if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
5085       std::swap(LHS, RHS);
5086   }
5087 
5088   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
5089   if (isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
5090       (Aggressive || MRI.hasOneNonDBGUse(LHS.Reg))) {
5091     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5092       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
5093                    {LHS.MI->getOperand(1).getReg(),
5094                     LHS.MI->getOperand(2).getReg(), RHS.Reg});
5095     };
5096     return true;
5097   }
5098 
5099   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
5100   if (isContractableFMul(*RHS.MI, AllowFusionGlobally) &&
5101       (Aggressive || MRI.hasOneNonDBGUse(RHS.Reg))) {
5102     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5103       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
5104                    {RHS.MI->getOperand(1).getReg(),
5105                     RHS.MI->getOperand(2).getReg(), LHS.Reg});
5106     };
5107     return true;
5108   }
5109 
5110   return false;
5111 }
5112 
5113 bool CombinerHelper::matchCombineFAddFpExtFMulToFMadOrFMA(
5114     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
5115   assert(MI.getOpcode() == TargetOpcode::G_FADD);
5116 
5117   bool AllowFusionGlobally, HasFMAD, Aggressive;
5118   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
5119     return false;
5120 
5121   const auto &TLI = *MI.getMF()->getSubtarget().getTargetLowering();
5122   Register Op1 = MI.getOperand(1).getReg();
5123   Register Op2 = MI.getOperand(2).getReg();
5124   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
5125   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
5126   LLT DstType = MRI.getType(MI.getOperand(0).getReg());
5127 
5128   unsigned PreferredFusedOpcode =
5129       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
5130 
5131   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
5132   // prefer to fold the multiply with fewer uses.
5133   if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
5134       isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
5135     if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
5136       std::swap(LHS, RHS);
5137   }
5138 
5139   // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
5140   MachineInstr *FpExtSrc;
5141   if (mi_match(LHS.Reg, MRI, m_GFPExt(m_MInstr(FpExtSrc))) &&
5142       isContractableFMul(*FpExtSrc, AllowFusionGlobally) &&
5143       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
5144                           MRI.getType(FpExtSrc->getOperand(1).getReg()))) {
5145     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5146       auto FpExtX = B.buildFPExt(DstType, FpExtSrc->getOperand(1).getReg());
5147       auto FpExtY = B.buildFPExt(DstType, FpExtSrc->getOperand(2).getReg());
5148       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
5149                    {FpExtX.getReg(0), FpExtY.getReg(0), RHS.Reg});
5150     };
5151     return true;
5152   }
5153 
5154   // fold (fadd z, (fpext (fmul x, y))) -> (fma (fpext x), (fpext y), z)
5155   // Note: Commutes FADD operands.
5156   if (mi_match(RHS.Reg, MRI, m_GFPExt(m_MInstr(FpExtSrc))) &&
5157       isContractableFMul(*FpExtSrc, AllowFusionGlobally) &&
5158       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
5159                           MRI.getType(FpExtSrc->getOperand(1).getReg()))) {
5160     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5161       auto FpExtX = B.buildFPExt(DstType, FpExtSrc->getOperand(1).getReg());
5162       auto FpExtY = B.buildFPExt(DstType, FpExtSrc->getOperand(2).getReg());
5163       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
5164                    {FpExtX.getReg(0), FpExtY.getReg(0), LHS.Reg});
5165     };
5166     return true;
5167   }
5168 
5169   return false;
5170 }
5171 
5172 bool CombinerHelper::matchCombineFAddFMAFMulToFMadOrFMA(
5173     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
5174   assert(MI.getOpcode() == TargetOpcode::G_FADD);
5175 
5176   bool AllowFusionGlobally, HasFMAD, Aggressive;
5177   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive, true))
5178     return false;
5179 
5180   Register Op1 = MI.getOperand(1).getReg();
5181   Register Op2 = MI.getOperand(2).getReg();
5182   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
5183   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
5184   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
5185 
5186   unsigned PreferredFusedOpcode =
5187       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
5188 
5189   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
5190   // prefer to fold the multiply with fewer uses.
5191   if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
5192       isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
5193     if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
5194       std::swap(LHS, RHS);
5195   }
5196 
5197   MachineInstr *FMA = nullptr;
5198   Register Z;
5199   // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y, (fma u, v, z))
5200   if (LHS.MI->getOpcode() == PreferredFusedOpcode &&
5201       (MRI.getVRegDef(LHS.MI->getOperand(3).getReg())->getOpcode() ==
5202        TargetOpcode::G_FMUL) &&
5203       MRI.hasOneNonDBGUse(LHS.MI->getOperand(0).getReg()) &&
5204       MRI.hasOneNonDBGUse(LHS.MI->getOperand(3).getReg())) {
5205     FMA = LHS.MI;
5206     Z = RHS.Reg;
5207   }
5208   // fold (fadd z, (fma x, y, (fmul u, v))) -> (fma x, y, (fma u, v, z))
5209   else if (RHS.MI->getOpcode() == PreferredFusedOpcode &&
5210            (MRI.getVRegDef(RHS.MI->getOperand(3).getReg())->getOpcode() ==
5211             TargetOpcode::G_FMUL) &&
5212            MRI.hasOneNonDBGUse(RHS.MI->getOperand(0).getReg()) &&
5213            MRI.hasOneNonDBGUse(RHS.MI->getOperand(3).getReg())) {
5214     Z = LHS.Reg;
5215     FMA = RHS.MI;
5216   }
5217 
5218   if (FMA) {
5219     MachineInstr *FMulMI = MRI.getVRegDef(FMA->getOperand(3).getReg());
5220     Register X = FMA->getOperand(1).getReg();
5221     Register Y = FMA->getOperand(2).getReg();
5222     Register U = FMulMI->getOperand(1).getReg();
5223     Register V = FMulMI->getOperand(2).getReg();
5224 
5225     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5226       Register InnerFMA = MRI.createGenericVirtualRegister(DstTy);
5227       B.buildInstr(PreferredFusedOpcode, {InnerFMA}, {U, V, Z});
5228       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
5229                    {X, Y, InnerFMA});
5230     };
5231     return true;
5232   }
5233 
5234   return false;
5235 }
5236 
5237 bool CombinerHelper::matchCombineFAddFpExtFMulToFMadOrFMAAggressive(
5238     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
5239   assert(MI.getOpcode() == TargetOpcode::G_FADD);
5240 
5241   bool AllowFusionGlobally, HasFMAD, Aggressive;
5242   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
5243     return false;
5244 
5245   if (!Aggressive)
5246     return false;
5247 
5248   const auto &TLI = *MI.getMF()->getSubtarget().getTargetLowering();
5249   LLT DstType = MRI.getType(MI.getOperand(0).getReg());
5250   Register Op1 = MI.getOperand(1).getReg();
5251   Register Op2 = MI.getOperand(2).getReg();
5252   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
5253   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
5254 
5255   unsigned PreferredFusedOpcode =
5256       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
5257 
5258   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
5259   // prefer to fold the multiply with fewer uses.
5260   if (Aggressive && isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
5261       isContractableFMul(*RHS.MI, AllowFusionGlobally)) {
5262     if (hasMoreUses(*LHS.MI, *RHS.MI, MRI))
5263       std::swap(LHS, RHS);
5264   }
5265 
5266   // Builds: (fma x, y, (fma (fpext u), (fpext v), z))
5267   auto buildMatchInfo = [=, &MI](Register U, Register V, Register Z, Register X,
5268                                  Register Y, MachineIRBuilder &B) {
5269     Register FpExtU = B.buildFPExt(DstType, U).getReg(0);
5270     Register FpExtV = B.buildFPExt(DstType, V).getReg(0);
5271     Register InnerFMA =
5272         B.buildInstr(PreferredFusedOpcode, {DstType}, {FpExtU, FpExtV, Z})
5273             .getReg(0);
5274     B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
5275                  {X, Y, InnerFMA});
5276   };
5277 
5278   MachineInstr *FMulMI, *FMAMI;
5279   // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
5280   //   -> (fma x, y, (fma (fpext u), (fpext v), z))
5281   if (LHS.MI->getOpcode() == PreferredFusedOpcode &&
5282       mi_match(LHS.MI->getOperand(3).getReg(), MRI,
5283                m_GFPExt(m_MInstr(FMulMI))) &&
5284       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
5285       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
5286                           MRI.getType(FMulMI->getOperand(0).getReg()))) {
5287     MatchInfo = [=](MachineIRBuilder &B) {
5288       buildMatchInfo(FMulMI->getOperand(1).getReg(),
5289                      FMulMI->getOperand(2).getReg(), RHS.Reg,
5290                      LHS.MI->getOperand(1).getReg(),
5291                      LHS.MI->getOperand(2).getReg(), B);
5292     };
5293     return true;
5294   }
5295 
5296   // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
5297   //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
5298   // FIXME: This turns two single-precision and one double-precision
5299   // operation into two double-precision operations, which might not be
5300   // interesting for all targets, especially GPUs.
5301   if (mi_match(LHS.Reg, MRI, m_GFPExt(m_MInstr(FMAMI))) &&
5302       FMAMI->getOpcode() == PreferredFusedOpcode) {
5303     MachineInstr *FMulMI = MRI.getVRegDef(FMAMI->getOperand(3).getReg());
5304     if (isContractableFMul(*FMulMI, AllowFusionGlobally) &&
5305         TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
5306                             MRI.getType(FMAMI->getOperand(0).getReg()))) {
5307       MatchInfo = [=](MachineIRBuilder &B) {
5308         Register X = FMAMI->getOperand(1).getReg();
5309         Register Y = FMAMI->getOperand(2).getReg();
5310         X = B.buildFPExt(DstType, X).getReg(0);
5311         Y = B.buildFPExt(DstType, Y).getReg(0);
5312         buildMatchInfo(FMulMI->getOperand(1).getReg(),
5313                        FMulMI->getOperand(2).getReg(), RHS.Reg, X, Y, B);
5314       };
5315 
5316       return true;
5317     }
5318   }
5319 
5320   // fold (fadd z, (fma x, y, (fpext (fmul u, v)))
5321   //   -> (fma x, y, (fma (fpext u), (fpext v), z))
5322   if (RHS.MI->getOpcode() == PreferredFusedOpcode &&
5323       mi_match(RHS.MI->getOperand(3).getReg(), MRI,
5324                m_GFPExt(m_MInstr(FMulMI))) &&
5325       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
5326       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
5327                           MRI.getType(FMulMI->getOperand(0).getReg()))) {
5328     MatchInfo = [=](MachineIRBuilder &B) {
5329       buildMatchInfo(FMulMI->getOperand(1).getReg(),
5330                      FMulMI->getOperand(2).getReg(), LHS.Reg,
5331                      RHS.MI->getOperand(1).getReg(),
5332                      RHS.MI->getOperand(2).getReg(), B);
5333     };
5334     return true;
5335   }
5336 
5337   // fold (fadd z, (fpext (fma x, y, (fmul u, v)))
5338   //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
5339   // FIXME: This turns two single-precision and one double-precision
5340   // operation into two double-precision operations, which might not be
5341   // interesting for all targets, especially GPUs.
5342   if (mi_match(RHS.Reg, MRI, m_GFPExt(m_MInstr(FMAMI))) &&
5343       FMAMI->getOpcode() == PreferredFusedOpcode) {
5344     MachineInstr *FMulMI = MRI.getVRegDef(FMAMI->getOperand(3).getReg());
5345     if (isContractableFMul(*FMulMI, AllowFusionGlobally) &&
5346         TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstType,
5347                             MRI.getType(FMAMI->getOperand(0).getReg()))) {
5348       MatchInfo = [=](MachineIRBuilder &B) {
5349         Register X = FMAMI->getOperand(1).getReg();
5350         Register Y = FMAMI->getOperand(2).getReg();
5351         X = B.buildFPExt(DstType, X).getReg(0);
5352         Y = B.buildFPExt(DstType, Y).getReg(0);
5353         buildMatchInfo(FMulMI->getOperand(1).getReg(),
5354                        FMulMI->getOperand(2).getReg(), LHS.Reg, X, Y, B);
5355       };
5356       return true;
5357     }
5358   }
5359 
5360   return false;
5361 }
5362 
5363 bool CombinerHelper::matchCombineFSubFMulToFMadOrFMA(
5364     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
5365   assert(MI.getOpcode() == TargetOpcode::G_FSUB);
5366 
5367   bool AllowFusionGlobally, HasFMAD, Aggressive;
5368   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
5369     return false;
5370 
5371   Register Op1 = MI.getOperand(1).getReg();
5372   Register Op2 = MI.getOperand(2).getReg();
5373   DefinitionAndSourceRegister LHS = {MRI.getVRegDef(Op1), Op1};
5374   DefinitionAndSourceRegister RHS = {MRI.getVRegDef(Op2), Op2};
5375   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
5376 
5377   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
5378   // prefer to fold the multiply with fewer uses.
5379   int FirstMulHasFewerUses = true;
5380   if (isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
5381       isContractableFMul(*RHS.MI, AllowFusionGlobally) &&
5382       hasMoreUses(*LHS.MI, *RHS.MI, MRI))
5383     FirstMulHasFewerUses = false;
5384 
5385   unsigned PreferredFusedOpcode =
5386       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
5387 
5388   // fold (fsub (fmul x, y), z) -> (fma x, y, -z)
5389   if (FirstMulHasFewerUses &&
5390       (isContractableFMul(*LHS.MI, AllowFusionGlobally) &&
5391        (Aggressive || MRI.hasOneNonDBGUse(LHS.Reg)))) {
5392     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5393       Register NegZ = B.buildFNeg(DstTy, RHS.Reg).getReg(0);
5394       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
5395                    {LHS.MI->getOperand(1).getReg(),
5396                     LHS.MI->getOperand(2).getReg(), NegZ});
5397     };
5398     return true;
5399   }
5400   // fold (fsub x, (fmul y, z)) -> (fma -y, z, x)
5401   else if ((isContractableFMul(*RHS.MI, AllowFusionGlobally) &&
5402             (Aggressive || MRI.hasOneNonDBGUse(RHS.Reg)))) {
5403     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5404       Register NegY =
5405           B.buildFNeg(DstTy, RHS.MI->getOperand(1).getReg()).getReg(0);
5406       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
5407                    {NegY, RHS.MI->getOperand(2).getReg(), LHS.Reg});
5408     };
5409     return true;
5410   }
5411 
5412   return false;
5413 }
5414 
5415 bool CombinerHelper::matchCombineFSubFNegFMulToFMadOrFMA(
5416     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
5417   assert(MI.getOpcode() == TargetOpcode::G_FSUB);
5418 
5419   bool AllowFusionGlobally, HasFMAD, Aggressive;
5420   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
5421     return false;
5422 
5423   Register LHSReg = MI.getOperand(1).getReg();
5424   Register RHSReg = MI.getOperand(2).getReg();
5425   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
5426 
5427   unsigned PreferredFusedOpcode =
5428       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
5429 
5430   MachineInstr *FMulMI;
5431   // fold (fsub (fneg (fmul x, y)), z) -> (fma (fneg x), y, (fneg z))
5432   if (mi_match(LHSReg, MRI, m_GFNeg(m_MInstr(FMulMI))) &&
5433       (Aggressive || (MRI.hasOneNonDBGUse(LHSReg) &&
5434                       MRI.hasOneNonDBGUse(FMulMI->getOperand(0).getReg()))) &&
5435       isContractableFMul(*FMulMI, AllowFusionGlobally)) {
5436     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5437       Register NegX =
5438           B.buildFNeg(DstTy, FMulMI->getOperand(1).getReg()).getReg(0);
5439       Register NegZ = B.buildFNeg(DstTy, RHSReg).getReg(0);
5440       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
5441                    {NegX, FMulMI->getOperand(2).getReg(), NegZ});
5442     };
5443     return true;
5444   }
5445 
5446   // fold (fsub x, (fneg (fmul, y, z))) -> (fma y, z, x)
5447   if (mi_match(RHSReg, MRI, m_GFNeg(m_MInstr(FMulMI))) &&
5448       (Aggressive || (MRI.hasOneNonDBGUse(RHSReg) &&
5449                       MRI.hasOneNonDBGUse(FMulMI->getOperand(0).getReg()))) &&
5450       isContractableFMul(*FMulMI, AllowFusionGlobally)) {
5451     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5452       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
5453                    {FMulMI->getOperand(1).getReg(),
5454                     FMulMI->getOperand(2).getReg(), LHSReg});
5455     };
5456     return true;
5457   }
5458 
5459   return false;
5460 }
5461 
5462 bool CombinerHelper::matchCombineFSubFpExtFMulToFMadOrFMA(
5463     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
5464   assert(MI.getOpcode() == TargetOpcode::G_FSUB);
5465 
5466   bool AllowFusionGlobally, HasFMAD, Aggressive;
5467   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
5468     return false;
5469 
5470   Register LHSReg = MI.getOperand(1).getReg();
5471   Register RHSReg = MI.getOperand(2).getReg();
5472   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
5473 
5474   unsigned PreferredFusedOpcode =
5475       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
5476 
5477   MachineInstr *FMulMI;
5478   // fold (fsub (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), (fneg z))
5479   if (mi_match(LHSReg, MRI, m_GFPExt(m_MInstr(FMulMI))) &&
5480       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
5481       (Aggressive || MRI.hasOneNonDBGUse(LHSReg))) {
5482     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5483       Register FpExtX =
5484           B.buildFPExt(DstTy, FMulMI->getOperand(1).getReg()).getReg(0);
5485       Register FpExtY =
5486           B.buildFPExt(DstTy, FMulMI->getOperand(2).getReg()).getReg(0);
5487       Register NegZ = B.buildFNeg(DstTy, RHSReg).getReg(0);
5488       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
5489                    {FpExtX, FpExtY, NegZ});
5490     };
5491     return true;
5492   }
5493 
5494   // fold (fsub x, (fpext (fmul y, z))) -> (fma (fneg (fpext y)), (fpext z), x)
5495   if (mi_match(RHSReg, MRI, m_GFPExt(m_MInstr(FMulMI))) &&
5496       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
5497       (Aggressive || MRI.hasOneNonDBGUse(RHSReg))) {
5498     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5499       Register FpExtY =
5500           B.buildFPExt(DstTy, FMulMI->getOperand(1).getReg()).getReg(0);
5501       Register NegY = B.buildFNeg(DstTy, FpExtY).getReg(0);
5502       Register FpExtZ =
5503           B.buildFPExt(DstTy, FMulMI->getOperand(2).getReg()).getReg(0);
5504       B.buildInstr(PreferredFusedOpcode, {MI.getOperand(0).getReg()},
5505                    {NegY, FpExtZ, LHSReg});
5506     };
5507     return true;
5508   }
5509 
5510   return false;
5511 }
5512 
5513 bool CombinerHelper::matchCombineFSubFpExtFNegFMulToFMadOrFMA(
5514     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
5515   assert(MI.getOpcode() == TargetOpcode::G_FSUB);
5516 
5517   bool AllowFusionGlobally, HasFMAD, Aggressive;
5518   if (!canCombineFMadOrFMA(MI, AllowFusionGlobally, HasFMAD, Aggressive))
5519     return false;
5520 
5521   const auto &TLI = *MI.getMF()->getSubtarget().getTargetLowering();
5522   LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
5523   Register LHSReg = MI.getOperand(1).getReg();
5524   Register RHSReg = MI.getOperand(2).getReg();
5525 
5526   unsigned PreferredFusedOpcode =
5527       HasFMAD ? TargetOpcode::G_FMAD : TargetOpcode::G_FMA;
5528 
5529   auto buildMatchInfo = [=](Register Dst, Register X, Register Y, Register Z,
5530                             MachineIRBuilder &B) {
5531     Register FpExtX = B.buildFPExt(DstTy, X).getReg(0);
5532     Register FpExtY = B.buildFPExt(DstTy, Y).getReg(0);
5533     B.buildInstr(PreferredFusedOpcode, {Dst}, {FpExtX, FpExtY, Z});
5534   };
5535 
5536   MachineInstr *FMulMI;
5537   // fold (fsub (fpext (fneg (fmul x, y))), z) ->
5538   //      (fneg (fma (fpext x), (fpext y), z))
5539   // fold (fsub (fneg (fpext (fmul x, y))), z) ->
5540   //      (fneg (fma (fpext x), (fpext y), z))
5541   if ((mi_match(LHSReg, MRI, m_GFPExt(m_GFNeg(m_MInstr(FMulMI)))) ||
5542        mi_match(LHSReg, MRI, m_GFNeg(m_GFPExt(m_MInstr(FMulMI))))) &&
5543       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
5544       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstTy,
5545                           MRI.getType(FMulMI->getOperand(0).getReg()))) {
5546     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5547       Register FMAReg = MRI.createGenericVirtualRegister(DstTy);
5548       buildMatchInfo(FMAReg, FMulMI->getOperand(1).getReg(),
5549                      FMulMI->getOperand(2).getReg(), RHSReg, B);
5550       B.buildFNeg(MI.getOperand(0).getReg(), FMAReg);
5551     };
5552     return true;
5553   }
5554 
5555   // fold (fsub x, (fpext (fneg (fmul y, z)))) -> (fma (fpext y), (fpext z), x)
5556   // fold (fsub x, (fneg (fpext (fmul y, z)))) -> (fma (fpext y), (fpext z), x)
5557   if ((mi_match(RHSReg, MRI, m_GFPExt(m_GFNeg(m_MInstr(FMulMI)))) ||
5558        mi_match(RHSReg, MRI, m_GFNeg(m_GFPExt(m_MInstr(FMulMI))))) &&
5559       isContractableFMul(*FMulMI, AllowFusionGlobally) &&
5560       TLI.isFPExtFoldable(MI, PreferredFusedOpcode, DstTy,
5561                           MRI.getType(FMulMI->getOperand(0).getReg()))) {
5562     MatchInfo = [=, &MI](MachineIRBuilder &B) {
5563       buildMatchInfo(MI.getOperand(0).getReg(), FMulMI->getOperand(1).getReg(),
5564                      FMulMI->getOperand(2).getReg(), LHSReg, B);
5565     };
5566     return true;
5567   }
5568 
5569   return false;
5570 }
5571 
5572 bool CombinerHelper::matchSelectToLogical(MachineInstr &MI,
5573                                           BuildFnTy &MatchInfo) {
5574   GSelect &Sel = cast<GSelect>(MI);
5575   Register DstReg = Sel.getReg(0);
5576   Register Cond = Sel.getCondReg();
5577   Register TrueReg = Sel.getTrueReg();
5578   Register FalseReg = Sel.getFalseReg();
5579 
5580   auto *TrueDef = getDefIgnoringCopies(TrueReg, MRI);
5581   auto *FalseDef = getDefIgnoringCopies(FalseReg, MRI);
5582 
5583   const LLT CondTy = MRI.getType(Cond);
5584   const LLT OpTy = MRI.getType(TrueReg);
5585   if (CondTy != OpTy || OpTy.getScalarSizeInBits() != 1)
5586     return false;
5587 
5588   // We have a boolean select.
5589 
5590   // select Cond, Cond, F --> or Cond, F
5591   // select Cond, 1, F    --> or Cond, F
5592   auto MaybeCstTrue = isConstantOrConstantSplatVector(*TrueDef, MRI);
5593   if (Cond == TrueReg || (MaybeCstTrue && MaybeCstTrue->isOne())) {
5594     MatchInfo = [=](MachineIRBuilder &MIB) {
5595       MIB.buildOr(DstReg, Cond, FalseReg);
5596     };
5597     return true;
5598   }
5599 
5600   // select Cond, T, Cond --> and Cond, T
5601   // select Cond, T, 0    --> and Cond, T
5602   auto MaybeCstFalse = isConstantOrConstantSplatVector(*FalseDef, MRI);
5603   if (Cond == FalseReg || (MaybeCstFalse && MaybeCstFalse->isZero())) {
5604     MatchInfo = [=](MachineIRBuilder &MIB) {
5605       MIB.buildAnd(DstReg, Cond, TrueReg);
5606     };
5607     return true;
5608   }
5609 
5610  // select Cond, T, 1 --> or (not Cond), T
5611   if (MaybeCstFalse && MaybeCstFalse->isOne()) {
5612     MatchInfo = [=](MachineIRBuilder &MIB) {
5613       MIB.buildOr(DstReg, MIB.buildNot(OpTy, Cond), TrueReg);
5614     };
5615     return true;
5616   }
5617 
5618   // select Cond, 0, F --> and (not Cond), F
5619   if (MaybeCstTrue && MaybeCstTrue->isZero()) {
5620     MatchInfo = [=](MachineIRBuilder &MIB) {
5621       MIB.buildAnd(DstReg, MIB.buildNot(OpTy, Cond), FalseReg);
5622     };
5623     return true;
5624   }
5625   return false;
5626 }
5627 
5628 bool CombinerHelper::matchCombineFMinMaxNaN(MachineInstr &MI,
5629                                             unsigned &IdxToPropagate) {
5630   bool PropagateNaN;
5631   switch (MI.getOpcode()) {
5632   default:
5633     return false;
5634   case TargetOpcode::G_FMINNUM:
5635   case TargetOpcode::G_FMAXNUM:
5636     PropagateNaN = false;
5637     break;
5638   case TargetOpcode::G_FMINIMUM:
5639   case TargetOpcode::G_FMAXIMUM:
5640     PropagateNaN = true;
5641     break;
5642   }
5643 
5644   auto MatchNaN = [&](unsigned Idx) {
5645     Register MaybeNaNReg = MI.getOperand(Idx).getReg();
5646     const ConstantFP *MaybeCst = getConstantFPVRegVal(MaybeNaNReg, MRI);
5647     if (!MaybeCst || !MaybeCst->getValueAPF().isNaN())
5648       return false;
5649     IdxToPropagate = PropagateNaN ? Idx : (Idx == 1 ? 2 : 1);
5650     return true;
5651   };
5652 
5653   return MatchNaN(1) || MatchNaN(2);
5654 }
5655 
5656 bool CombinerHelper::matchAddSubSameReg(MachineInstr &MI, Register &Src) {
5657   assert(MI.getOpcode() == TargetOpcode::G_ADD && "Expected a G_ADD");
5658   Register LHS = MI.getOperand(1).getReg();
5659   Register RHS = MI.getOperand(2).getReg();
5660 
5661   // Helper lambda to check for opportunities for
5662   // A + (B - A) -> B
5663   // (B - A) + A -> B
5664   auto CheckFold = [&](Register MaybeSub, Register MaybeSameReg) {
5665     Register Reg;
5666     return mi_match(MaybeSub, MRI, m_GSub(m_Reg(Src), m_Reg(Reg))) &&
5667            Reg == MaybeSameReg;
5668   };
5669   return CheckFold(LHS, RHS) || CheckFold(RHS, LHS);
5670 }
5671 
5672 bool CombinerHelper::tryCombine(MachineInstr &MI) {
5673   if (tryCombineCopy(MI))
5674     return true;
5675   if (tryCombineExtendingLoads(MI))
5676     return true;
5677   if (tryCombineIndexedLoadStore(MI))
5678     return true;
5679   return false;
5680 }
5681