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