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