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