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