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