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