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