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