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::matchCombineZextTrunc(MachineInstr &MI, Register &Reg) {
2299   assert(MI.getOpcode() == TargetOpcode::G_ZEXT && "Expected a G_ZEXT");
2300   Register DstReg = MI.getOperand(0).getReg();
2301   Register SrcReg = MI.getOperand(1).getReg();
2302   LLT DstTy = MRI.getType(DstReg);
2303   if (mi_match(SrcReg, MRI,
2304                m_GTrunc(m_all_of(m_Reg(Reg), m_SpecificType(DstTy))))) {
2305     unsigned DstSize = DstTy.getScalarSizeInBits();
2306     unsigned SrcSize = MRI.getType(SrcReg).getScalarSizeInBits();
2307     return KB->getKnownBits(Reg).countMinLeadingZeros() >= DstSize - SrcSize;
2308   }
2309   return false;
2310 }
2311 
2312 bool CombinerHelper::matchCombineExtOfExt(
2313     MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
2314   assert((MI.getOpcode() == TargetOpcode::G_ANYEXT ||
2315           MI.getOpcode() == TargetOpcode::G_SEXT ||
2316           MI.getOpcode() == TargetOpcode::G_ZEXT) &&
2317          "Expected a G_[ASZ]EXT");
2318   Register SrcReg = MI.getOperand(1).getReg();
2319   MachineInstr *SrcMI = MRI.getVRegDef(SrcReg);
2320   // Match exts with the same opcode, anyext([sz]ext) and sext(zext).
2321   unsigned Opc = MI.getOpcode();
2322   unsigned SrcOpc = SrcMI->getOpcode();
2323   if (Opc == SrcOpc ||
2324       (Opc == TargetOpcode::G_ANYEXT &&
2325        (SrcOpc == TargetOpcode::G_SEXT || SrcOpc == TargetOpcode::G_ZEXT)) ||
2326       (Opc == TargetOpcode::G_SEXT && SrcOpc == TargetOpcode::G_ZEXT)) {
2327     MatchInfo = std::make_tuple(SrcMI->getOperand(1).getReg(), SrcOpc);
2328     return true;
2329   }
2330   return false;
2331 }
2332 
2333 bool CombinerHelper::applyCombineExtOfExt(
2334     MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) {
2335   assert((MI.getOpcode() == TargetOpcode::G_ANYEXT ||
2336           MI.getOpcode() == TargetOpcode::G_SEXT ||
2337           MI.getOpcode() == TargetOpcode::G_ZEXT) &&
2338          "Expected a G_[ASZ]EXT");
2339 
2340   Register Reg = std::get<0>(MatchInfo);
2341   unsigned SrcExtOp = std::get<1>(MatchInfo);
2342 
2343   // Combine exts with the same opcode.
2344   if (MI.getOpcode() == SrcExtOp) {
2345     Observer.changingInstr(MI);
2346     MI.getOperand(1).setReg(Reg);
2347     Observer.changedInstr(MI);
2348     return true;
2349   }
2350 
2351   // Combine:
2352   // - anyext([sz]ext x) to [sz]ext x
2353   // - sext(zext x) to zext x
2354   if (MI.getOpcode() == TargetOpcode::G_ANYEXT ||
2355       (MI.getOpcode() == TargetOpcode::G_SEXT &&
2356        SrcExtOp == TargetOpcode::G_ZEXT)) {
2357     Register DstReg = MI.getOperand(0).getReg();
2358     Builder.setInstrAndDebugLoc(MI);
2359     Builder.buildInstr(SrcExtOp, {DstReg}, {Reg});
2360     MI.eraseFromParent();
2361     return true;
2362   }
2363 
2364   return false;
2365 }
2366 
2367 bool CombinerHelper::applyCombineMulByNegativeOne(MachineInstr &MI) {
2368   assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL");
2369   Register DstReg = MI.getOperand(0).getReg();
2370   Register SrcReg = MI.getOperand(1).getReg();
2371   LLT DstTy = MRI.getType(DstReg);
2372 
2373   Builder.setInstrAndDebugLoc(MI);
2374   Builder.buildSub(DstReg, Builder.buildConstant(DstTy, 0), SrcReg,
2375                    MI.getFlags());
2376   MI.eraseFromParent();
2377   return true;
2378 }
2379 
2380 bool CombinerHelper::matchCombineFNegOfFNeg(MachineInstr &MI, Register &Reg) {
2381   assert(MI.getOpcode() == TargetOpcode::G_FNEG && "Expected a G_FNEG");
2382   Register SrcReg = MI.getOperand(1).getReg();
2383   return mi_match(SrcReg, MRI, m_GFNeg(m_Reg(Reg)));
2384 }
2385 
2386 bool CombinerHelper::matchCombineFAbsOfFAbs(MachineInstr &MI, Register &Src) {
2387   assert(MI.getOpcode() == TargetOpcode::G_FABS && "Expected a G_FABS");
2388   Src = MI.getOperand(1).getReg();
2389   Register AbsSrc;
2390   return mi_match(Src, MRI, m_GFabs(m_Reg(AbsSrc)));
2391 }
2392 
2393 bool CombinerHelper::matchCombineTruncOfExt(
2394     MachineInstr &MI, std::pair<Register, unsigned> &MatchInfo) {
2395   assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2396   Register SrcReg = MI.getOperand(1).getReg();
2397   MachineInstr *SrcMI = MRI.getVRegDef(SrcReg);
2398   unsigned SrcOpc = SrcMI->getOpcode();
2399   if (SrcOpc == TargetOpcode::G_ANYEXT || SrcOpc == TargetOpcode::G_SEXT ||
2400       SrcOpc == TargetOpcode::G_ZEXT) {
2401     MatchInfo = std::make_pair(SrcMI->getOperand(1).getReg(), SrcOpc);
2402     return true;
2403   }
2404   return false;
2405 }
2406 
2407 bool CombinerHelper::applyCombineTruncOfExt(
2408     MachineInstr &MI, std::pair<Register, unsigned> &MatchInfo) {
2409   assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2410   Register SrcReg = MatchInfo.first;
2411   unsigned SrcExtOp = MatchInfo.second;
2412   Register DstReg = MI.getOperand(0).getReg();
2413   LLT SrcTy = MRI.getType(SrcReg);
2414   LLT DstTy = MRI.getType(DstReg);
2415   if (SrcTy == DstTy) {
2416     MI.eraseFromParent();
2417     replaceRegWith(MRI, DstReg, SrcReg);
2418     return true;
2419   }
2420   Builder.setInstrAndDebugLoc(MI);
2421   if (SrcTy.getSizeInBits() < DstTy.getSizeInBits())
2422     Builder.buildInstr(SrcExtOp, {DstReg}, {SrcReg});
2423   else
2424     Builder.buildTrunc(DstReg, SrcReg);
2425   MI.eraseFromParent();
2426   return true;
2427 }
2428 
2429 bool CombinerHelper::matchCombineTruncOfShl(
2430     MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
2431   assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2432   Register DstReg = MI.getOperand(0).getReg();
2433   Register SrcReg = MI.getOperand(1).getReg();
2434   LLT DstTy = MRI.getType(DstReg);
2435   Register ShiftSrc;
2436   Register ShiftAmt;
2437 
2438   if (MRI.hasOneNonDBGUse(SrcReg) &&
2439       mi_match(SrcReg, MRI, m_GShl(m_Reg(ShiftSrc), m_Reg(ShiftAmt))) &&
2440       isLegalOrBeforeLegalizer(
2441           {TargetOpcode::G_SHL,
2442            {DstTy, getTargetLowering().getPreferredShiftAmountTy(DstTy)}})) {
2443     KnownBits Known = KB->getKnownBits(ShiftAmt);
2444     unsigned Size = DstTy.getSizeInBits();
2445     if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) {
2446       MatchInfo = std::make_pair(ShiftSrc, ShiftAmt);
2447       return true;
2448     }
2449   }
2450   return false;
2451 }
2452 
2453 bool CombinerHelper::applyCombineTruncOfShl(
2454     MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
2455   assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC");
2456   Register DstReg = MI.getOperand(0).getReg();
2457   Register SrcReg = MI.getOperand(1).getReg();
2458   LLT DstTy = MRI.getType(DstReg);
2459   MachineInstr *SrcMI = MRI.getVRegDef(SrcReg);
2460 
2461   Register ShiftSrc = MatchInfo.first;
2462   Register ShiftAmt = MatchInfo.second;
2463   Builder.setInstrAndDebugLoc(MI);
2464   auto TruncShiftSrc = Builder.buildTrunc(DstTy, ShiftSrc);
2465   Builder.buildShl(DstReg, TruncShiftSrc, ShiftAmt, SrcMI->getFlags());
2466   MI.eraseFromParent();
2467   return true;
2468 }
2469 
2470 bool CombinerHelper::matchAnyExplicitUseIsUndef(MachineInstr &MI) {
2471   return any_of(MI.explicit_uses(), [this](const MachineOperand &MO) {
2472     return MO.isReg() &&
2473            getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
2474   });
2475 }
2476 
2477 bool CombinerHelper::matchAllExplicitUsesAreUndef(MachineInstr &MI) {
2478   return all_of(MI.explicit_uses(), [this](const MachineOperand &MO) {
2479     return !MO.isReg() ||
2480            getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
2481   });
2482 }
2483 
2484 bool CombinerHelper::matchUndefShuffleVectorMask(MachineInstr &MI) {
2485   assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR);
2486   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
2487   return all_of(Mask, [](int Elt) { return Elt < 0; });
2488 }
2489 
2490 bool CombinerHelper::matchUndefStore(MachineInstr &MI) {
2491   assert(MI.getOpcode() == TargetOpcode::G_STORE);
2492   return getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MI.getOperand(0).getReg(),
2493                       MRI);
2494 }
2495 
2496 bool CombinerHelper::matchUndefSelectCmp(MachineInstr &MI) {
2497   assert(MI.getOpcode() == TargetOpcode::G_SELECT);
2498   return getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MI.getOperand(1).getReg(),
2499                       MRI);
2500 }
2501 
2502 bool CombinerHelper::matchConstantSelectCmp(MachineInstr &MI, unsigned &OpIdx) {
2503   assert(MI.getOpcode() == TargetOpcode::G_SELECT);
2504   if (auto MaybeCstCmp =
2505           getConstantVRegValWithLookThrough(MI.getOperand(1).getReg(), MRI)) {
2506     OpIdx = MaybeCstCmp->Value.isNullValue() ? 3 : 2;
2507     return true;
2508   }
2509   return false;
2510 }
2511 
2512 bool CombinerHelper::eraseInst(MachineInstr &MI) {
2513   MI.eraseFromParent();
2514   return true;
2515 }
2516 
2517 bool CombinerHelper::matchEqualDefs(const MachineOperand &MOP1,
2518                                     const MachineOperand &MOP2) {
2519   if (!MOP1.isReg() || !MOP2.isReg())
2520     return false;
2521   MachineInstr *I1 = getDefIgnoringCopies(MOP1.getReg(), MRI);
2522   if (!I1)
2523     return false;
2524   MachineInstr *I2 = getDefIgnoringCopies(MOP2.getReg(), MRI);
2525   if (!I2)
2526     return false;
2527 
2528   // Handle a case like this:
2529   //
2530   // %0:_(s64), %1:_(s64) = G_UNMERGE_VALUES %2:_(<2 x s64>)
2531   //
2532   // Even though %0 and %1 are produced by the same instruction they are not
2533   // the same values.
2534   if (I1 == I2)
2535     return MOP1.getReg() == MOP2.getReg();
2536 
2537   // If we have an instruction which loads or stores, we can't guarantee that
2538   // it is identical.
2539   //
2540   // For example, we may have
2541   //
2542   // %x1 = G_LOAD %addr (load N from @somewhere)
2543   // ...
2544   // call @foo
2545   // ...
2546   // %x2 = G_LOAD %addr (load N from @somewhere)
2547   // ...
2548   // %or = G_OR %x1, %x2
2549   //
2550   // It's possible that @foo will modify whatever lives at the address we're
2551   // loading from. To be safe, let's just assume that all loads and stores
2552   // are different (unless we have something which is guaranteed to not
2553   // change.)
2554   if (I1->mayLoadOrStore() && !I1->isDereferenceableInvariantLoad(nullptr))
2555     return false;
2556 
2557   // Check for physical registers on the instructions first to avoid cases
2558   // like this:
2559   //
2560   // %a = COPY $physreg
2561   // ...
2562   // SOMETHING implicit-def $physreg
2563   // ...
2564   // %b = COPY $physreg
2565   //
2566   // These copies are not equivalent.
2567   if (any_of(I1->uses(), [](const MachineOperand &MO) {
2568         return MO.isReg() && MO.getReg().isPhysical();
2569       })) {
2570     // Check if we have a case like this:
2571     //
2572     // %a = COPY $physreg
2573     // %b = COPY %a
2574     //
2575     // In this case, I1 and I2 will both be equal to %a = COPY $physreg.
2576     // From that, we know that they must have the same value, since they must
2577     // have come from the same COPY.
2578     return I1->isIdenticalTo(*I2);
2579   }
2580 
2581   // We don't have any physical registers, so we don't necessarily need the
2582   // same vreg defs.
2583   //
2584   // On the off-chance that there's some target instruction feeding into the
2585   // instruction, let's use produceSameValue instead of isIdenticalTo.
2586   return Builder.getTII().produceSameValue(*I1, *I2, &MRI);
2587 }
2588 
2589 bool CombinerHelper::matchConstantOp(const MachineOperand &MOP, int64_t C) {
2590   if (!MOP.isReg())
2591     return false;
2592   // MIPatternMatch doesn't let us look through G_ZEXT etc.
2593   auto ValAndVReg = getConstantVRegValWithLookThrough(MOP.getReg(), MRI);
2594   return ValAndVReg && ValAndVReg->Value == C;
2595 }
2596 
2597 bool CombinerHelper::replaceSingleDefInstWithOperand(MachineInstr &MI,
2598                                                      unsigned OpIdx) {
2599   assert(MI.getNumExplicitDefs() == 1 && "Expected one explicit def?");
2600   Register OldReg = MI.getOperand(0).getReg();
2601   Register Replacement = MI.getOperand(OpIdx).getReg();
2602   assert(canReplaceReg(OldReg, Replacement, MRI) && "Cannot replace register?");
2603   MI.eraseFromParent();
2604   replaceRegWith(MRI, OldReg, Replacement);
2605   return true;
2606 }
2607 
2608 bool CombinerHelper::replaceSingleDefInstWithReg(MachineInstr &MI,
2609                                                  Register Replacement) {
2610   assert(MI.getNumExplicitDefs() == 1 && "Expected one explicit def?");
2611   Register OldReg = MI.getOperand(0).getReg();
2612   assert(canReplaceReg(OldReg, Replacement, MRI) && "Cannot replace register?");
2613   MI.eraseFromParent();
2614   replaceRegWith(MRI, OldReg, Replacement);
2615   return true;
2616 }
2617 
2618 bool CombinerHelper::matchSelectSameVal(MachineInstr &MI) {
2619   assert(MI.getOpcode() == TargetOpcode::G_SELECT);
2620   // Match (cond ? x : x)
2621   return matchEqualDefs(MI.getOperand(2), MI.getOperand(3)) &&
2622          canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(2).getReg(),
2623                        MRI);
2624 }
2625 
2626 bool CombinerHelper::matchBinOpSameVal(MachineInstr &MI) {
2627   return matchEqualDefs(MI.getOperand(1), MI.getOperand(2)) &&
2628          canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(1).getReg(),
2629                        MRI);
2630 }
2631 
2632 bool CombinerHelper::matchOperandIsZero(MachineInstr &MI, unsigned OpIdx) {
2633   return matchConstantOp(MI.getOperand(OpIdx), 0) &&
2634          canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(OpIdx).getReg(),
2635                        MRI);
2636 }
2637 
2638 bool CombinerHelper::matchOperandIsUndef(MachineInstr &MI, unsigned OpIdx) {
2639   MachineOperand &MO = MI.getOperand(OpIdx);
2640   return MO.isReg() &&
2641          getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
2642 }
2643 
2644 bool CombinerHelper::matchOperandIsKnownToBeAPowerOfTwo(MachineInstr &MI,
2645                                                         unsigned OpIdx) {
2646   MachineOperand &MO = MI.getOperand(OpIdx);
2647   return isKnownToBeAPowerOfTwo(MO.getReg(), MRI, KB);
2648 }
2649 
2650 bool CombinerHelper::replaceInstWithFConstant(MachineInstr &MI, double C) {
2651   assert(MI.getNumDefs() == 1 && "Expected only one def?");
2652   Builder.setInstr(MI);
2653   Builder.buildFConstant(MI.getOperand(0), C);
2654   MI.eraseFromParent();
2655   return true;
2656 }
2657 
2658 bool CombinerHelper::replaceInstWithConstant(MachineInstr &MI, int64_t C) {
2659   assert(MI.getNumDefs() == 1 && "Expected only one def?");
2660   Builder.setInstr(MI);
2661   Builder.buildConstant(MI.getOperand(0), C);
2662   MI.eraseFromParent();
2663   return true;
2664 }
2665 
2666 bool CombinerHelper::replaceInstWithUndef(MachineInstr &MI) {
2667   assert(MI.getNumDefs() == 1 && "Expected only one def?");
2668   Builder.setInstr(MI);
2669   Builder.buildUndef(MI.getOperand(0));
2670   MI.eraseFromParent();
2671   return true;
2672 }
2673 
2674 bool CombinerHelper::matchSimplifyAddToSub(
2675     MachineInstr &MI, std::tuple<Register, Register> &MatchInfo) {
2676   Register LHS = MI.getOperand(1).getReg();
2677   Register RHS = MI.getOperand(2).getReg();
2678   Register &NewLHS = std::get<0>(MatchInfo);
2679   Register &NewRHS = std::get<1>(MatchInfo);
2680 
2681   // Helper lambda to check for opportunities for
2682   // ((0-A) + B) -> B - A
2683   // (A + (0-B)) -> A - B
2684   auto CheckFold = [&](Register &MaybeSub, Register &MaybeNewLHS) {
2685     if (!mi_match(MaybeSub, MRI, m_Neg(m_Reg(NewRHS))))
2686       return false;
2687     NewLHS = MaybeNewLHS;
2688     return true;
2689   };
2690 
2691   return CheckFold(LHS, RHS) || CheckFold(RHS, LHS);
2692 }
2693 
2694 bool CombinerHelper::matchCombineInsertVecElts(
2695     MachineInstr &MI, SmallVectorImpl<Register> &MatchInfo) {
2696   assert(MI.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT &&
2697          "Invalid opcode");
2698   Register DstReg = MI.getOperand(0).getReg();
2699   LLT DstTy = MRI.getType(DstReg);
2700   assert(DstTy.isVector() && "Invalid G_INSERT_VECTOR_ELT?");
2701   unsigned NumElts = DstTy.getNumElements();
2702   // If this MI is part of a sequence of insert_vec_elts, then
2703   // don't do the combine in the middle of the sequence.
2704   if (MRI.hasOneUse(DstReg) && MRI.use_instr_begin(DstReg)->getOpcode() ==
2705                                    TargetOpcode::G_INSERT_VECTOR_ELT)
2706     return false;
2707   MachineInstr *CurrInst = &MI;
2708   MachineInstr *TmpInst;
2709   int64_t IntImm;
2710   Register TmpReg;
2711   MatchInfo.resize(NumElts);
2712   while (mi_match(
2713       CurrInst->getOperand(0).getReg(), MRI,
2714       m_GInsertVecElt(m_MInstr(TmpInst), m_Reg(TmpReg), m_ICst(IntImm)))) {
2715     if (IntImm >= NumElts)
2716       return false;
2717     if (!MatchInfo[IntImm])
2718       MatchInfo[IntImm] = TmpReg;
2719     CurrInst = TmpInst;
2720   }
2721   // Variable index.
2722   if (CurrInst->getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT)
2723     return false;
2724   if (TmpInst->getOpcode() == TargetOpcode::G_BUILD_VECTOR) {
2725     for (unsigned I = 1; I < TmpInst->getNumOperands(); ++I) {
2726       if (!MatchInfo[I - 1].isValid())
2727         MatchInfo[I - 1] = TmpInst->getOperand(I).getReg();
2728     }
2729     return true;
2730   }
2731   // If we didn't end in a G_IMPLICIT_DEF, bail out.
2732   return TmpInst->getOpcode() == TargetOpcode::G_IMPLICIT_DEF;
2733 }
2734 
2735 bool CombinerHelper::applyCombineInsertVecElts(
2736     MachineInstr &MI, SmallVectorImpl<Register> &MatchInfo) {
2737   Builder.setInstr(MI);
2738   Register UndefReg;
2739   auto GetUndef = [&]() {
2740     if (UndefReg)
2741       return UndefReg;
2742     LLT DstTy = MRI.getType(MI.getOperand(0).getReg());
2743     UndefReg = Builder.buildUndef(DstTy.getScalarType()).getReg(0);
2744     return UndefReg;
2745   };
2746   for (unsigned I = 0; I < MatchInfo.size(); ++I) {
2747     if (!MatchInfo[I])
2748       MatchInfo[I] = GetUndef();
2749   }
2750   Builder.buildBuildVector(MI.getOperand(0).getReg(), MatchInfo);
2751   MI.eraseFromParent();
2752   return true;
2753 }
2754 
2755 bool CombinerHelper::applySimplifyAddToSub(
2756     MachineInstr &MI, std::tuple<Register, Register> &MatchInfo) {
2757   Builder.setInstr(MI);
2758   Register SubLHS, SubRHS;
2759   std::tie(SubLHS, SubRHS) = MatchInfo;
2760   Builder.buildSub(MI.getOperand(0).getReg(), SubLHS, SubRHS);
2761   MI.eraseFromParent();
2762   return true;
2763 }
2764 
2765 bool CombinerHelper::matchHoistLogicOpWithSameOpcodeHands(
2766     MachineInstr &MI, InstructionStepsMatchInfo &MatchInfo) {
2767   // Matches: logic (hand x, ...), (hand y, ...) -> hand (logic x, y), ...
2768   //
2769   // Creates the new hand + logic instruction (but does not insert them.)
2770   //
2771   // On success, MatchInfo is populated with the new instructions. These are
2772   // inserted in applyHoistLogicOpWithSameOpcodeHands.
2773   unsigned LogicOpcode = MI.getOpcode();
2774   assert(LogicOpcode == TargetOpcode::G_AND ||
2775          LogicOpcode == TargetOpcode::G_OR ||
2776          LogicOpcode == TargetOpcode::G_XOR);
2777   MachineIRBuilder MIB(MI);
2778   Register Dst = MI.getOperand(0).getReg();
2779   Register LHSReg = MI.getOperand(1).getReg();
2780   Register RHSReg = MI.getOperand(2).getReg();
2781 
2782   // Don't recompute anything.
2783   if (!MRI.hasOneNonDBGUse(LHSReg) || !MRI.hasOneNonDBGUse(RHSReg))
2784     return false;
2785 
2786   // Make sure we have (hand x, ...), (hand y, ...)
2787   MachineInstr *LeftHandInst = getDefIgnoringCopies(LHSReg, MRI);
2788   MachineInstr *RightHandInst = getDefIgnoringCopies(RHSReg, MRI);
2789   if (!LeftHandInst || !RightHandInst)
2790     return false;
2791   unsigned HandOpcode = LeftHandInst->getOpcode();
2792   if (HandOpcode != RightHandInst->getOpcode())
2793     return false;
2794   if (!LeftHandInst->getOperand(1).isReg() ||
2795       !RightHandInst->getOperand(1).isReg())
2796     return false;
2797 
2798   // Make sure the types match up, and if we're doing this post-legalization,
2799   // we end up with legal types.
2800   Register X = LeftHandInst->getOperand(1).getReg();
2801   Register Y = RightHandInst->getOperand(1).getReg();
2802   LLT XTy = MRI.getType(X);
2803   LLT YTy = MRI.getType(Y);
2804   if (XTy != YTy)
2805     return false;
2806   if (!isLegalOrBeforeLegalizer({LogicOpcode, {XTy, YTy}}))
2807     return false;
2808 
2809   // Optional extra source register.
2810   Register ExtraHandOpSrcReg;
2811   switch (HandOpcode) {
2812   default:
2813     return false;
2814   case TargetOpcode::G_ANYEXT:
2815   case TargetOpcode::G_SEXT:
2816   case TargetOpcode::G_ZEXT: {
2817     // Match: logic (ext X), (ext Y) --> ext (logic X, Y)
2818     break;
2819   }
2820   case TargetOpcode::G_AND:
2821   case TargetOpcode::G_ASHR:
2822   case TargetOpcode::G_LSHR:
2823   case TargetOpcode::G_SHL: {
2824     // Match: logic (binop x, z), (binop y, z) -> binop (logic x, y), z
2825     MachineOperand &ZOp = LeftHandInst->getOperand(2);
2826     if (!matchEqualDefs(ZOp, RightHandInst->getOperand(2)))
2827       return false;
2828     ExtraHandOpSrcReg = ZOp.getReg();
2829     break;
2830   }
2831   }
2832 
2833   // Record the steps to build the new instructions.
2834   //
2835   // Steps to build (logic x, y)
2836   auto NewLogicDst = MRI.createGenericVirtualRegister(XTy);
2837   OperandBuildSteps LogicBuildSteps = {
2838       [=](MachineInstrBuilder &MIB) { MIB.addDef(NewLogicDst); },
2839       [=](MachineInstrBuilder &MIB) { MIB.addReg(X); },
2840       [=](MachineInstrBuilder &MIB) { MIB.addReg(Y); }};
2841   InstructionBuildSteps LogicSteps(LogicOpcode, LogicBuildSteps);
2842 
2843   // Steps to build hand (logic x, y), ...z
2844   OperandBuildSteps HandBuildSteps = {
2845       [=](MachineInstrBuilder &MIB) { MIB.addDef(Dst); },
2846       [=](MachineInstrBuilder &MIB) { MIB.addReg(NewLogicDst); }};
2847   if (ExtraHandOpSrcReg.isValid())
2848     HandBuildSteps.push_back(
2849         [=](MachineInstrBuilder &MIB) { MIB.addReg(ExtraHandOpSrcReg); });
2850   InstructionBuildSteps HandSteps(HandOpcode, HandBuildSteps);
2851 
2852   MatchInfo = InstructionStepsMatchInfo({LogicSteps, HandSteps});
2853   return true;
2854 }
2855 
2856 bool CombinerHelper::applyBuildInstructionSteps(
2857     MachineInstr &MI, InstructionStepsMatchInfo &MatchInfo) {
2858   assert(MatchInfo.InstrsToBuild.size() &&
2859          "Expected at least one instr to build?");
2860   Builder.setInstr(MI);
2861   for (auto &InstrToBuild : MatchInfo.InstrsToBuild) {
2862     assert(InstrToBuild.Opcode && "Expected a valid opcode?");
2863     assert(InstrToBuild.OperandFns.size() && "Expected at least one operand?");
2864     MachineInstrBuilder Instr = Builder.buildInstr(InstrToBuild.Opcode);
2865     for (auto &OperandFn : InstrToBuild.OperandFns)
2866       OperandFn(Instr);
2867   }
2868   MI.eraseFromParent();
2869   return true;
2870 }
2871 
2872 bool CombinerHelper::matchAshrShlToSextInreg(
2873     MachineInstr &MI, std::tuple<Register, int64_t> &MatchInfo) {
2874   assert(MI.getOpcode() == TargetOpcode::G_ASHR);
2875   int64_t ShlCst, AshrCst;
2876   Register Src;
2877   // FIXME: detect splat constant vectors.
2878   if (!mi_match(MI.getOperand(0).getReg(), MRI,
2879                 m_GAShr(m_GShl(m_Reg(Src), m_ICst(ShlCst)), m_ICst(AshrCst))))
2880     return false;
2881   if (ShlCst != AshrCst)
2882     return false;
2883   if (!isLegalOrBeforeLegalizer(
2884           {TargetOpcode::G_SEXT_INREG, {MRI.getType(Src)}}))
2885     return false;
2886   MatchInfo = std::make_tuple(Src, ShlCst);
2887   return true;
2888 }
2889 bool CombinerHelper::applyAshShlToSextInreg(
2890     MachineInstr &MI, std::tuple<Register, int64_t> &MatchInfo) {
2891   assert(MI.getOpcode() == TargetOpcode::G_ASHR);
2892   Register Src;
2893   int64_t ShiftAmt;
2894   std::tie(Src, ShiftAmt) = MatchInfo;
2895   unsigned Size = MRI.getType(Src).getScalarSizeInBits();
2896   Builder.setInstrAndDebugLoc(MI);
2897   Builder.buildSExtInReg(MI.getOperand(0).getReg(), Src, Size - ShiftAmt);
2898   MI.eraseFromParent();
2899   return true;
2900 }
2901 
2902 bool CombinerHelper::matchRedundantAnd(MachineInstr &MI,
2903                                        Register &Replacement) {
2904   // Given
2905   //
2906   // %y:_(sN) = G_SOMETHING
2907   // %x:_(sN) = G_SOMETHING
2908   // %res:_(sN) = G_AND %x, %y
2909   //
2910   // Eliminate the G_AND when it is known that x & y == x or x & y == y.
2911   //
2912   // Patterns like this can appear as a result of legalization. E.g.
2913   //
2914   // %cmp:_(s32) = G_ICMP intpred(pred), %x(s32), %y
2915   // %one:_(s32) = G_CONSTANT i32 1
2916   // %and:_(s32) = G_AND %cmp, %one
2917   //
2918   // In this case, G_ICMP only produces a single bit, so x & 1 == x.
2919   assert(MI.getOpcode() == TargetOpcode::G_AND);
2920   if (!KB)
2921     return false;
2922 
2923   Register AndDst = MI.getOperand(0).getReg();
2924   LLT DstTy = MRI.getType(AndDst);
2925 
2926   // FIXME: This should be removed once GISelKnownBits supports vectors.
2927   if (DstTy.isVector())
2928     return false;
2929 
2930   Register LHS = MI.getOperand(1).getReg();
2931   Register RHS = MI.getOperand(2).getReg();
2932   KnownBits LHSBits = KB->getKnownBits(LHS);
2933   KnownBits RHSBits = KB->getKnownBits(RHS);
2934 
2935   // Check that x & Mask == x.
2936   // x & 1 == x, always
2937   // x & 0 == x, only if x is also 0
2938   // Meaning Mask has no effect if every bit is either one in Mask or zero in x.
2939   //
2940   // Check if we can replace AndDst with the LHS of the G_AND
2941   if (canReplaceReg(AndDst, LHS, MRI) &&
2942       (LHSBits.Zero | RHSBits.One).isAllOnesValue()) {
2943     Replacement = LHS;
2944     return true;
2945   }
2946 
2947   // Check if we can replace AndDst with the RHS of the G_AND
2948   if (canReplaceReg(AndDst, RHS, MRI) &&
2949       (LHSBits.One | RHSBits.Zero).isAllOnesValue()) {
2950     Replacement = RHS;
2951     return true;
2952   }
2953 
2954   return false;
2955 }
2956 
2957 bool CombinerHelper::matchRedundantOr(MachineInstr &MI, Register &Replacement) {
2958   // Given
2959   //
2960   // %y:_(sN) = G_SOMETHING
2961   // %x:_(sN) = G_SOMETHING
2962   // %res:_(sN) = G_OR %x, %y
2963   //
2964   // Eliminate the G_OR when it is known that x | y == x or x | y == y.
2965   assert(MI.getOpcode() == TargetOpcode::G_OR);
2966   if (!KB)
2967     return false;
2968 
2969   Register OrDst = MI.getOperand(0).getReg();
2970   LLT DstTy = MRI.getType(OrDst);
2971 
2972   // FIXME: This should be removed once GISelKnownBits supports vectors.
2973   if (DstTy.isVector())
2974     return false;
2975 
2976   Register LHS = MI.getOperand(1).getReg();
2977   Register RHS = MI.getOperand(2).getReg();
2978   KnownBits LHSBits = KB->getKnownBits(LHS);
2979   KnownBits RHSBits = KB->getKnownBits(RHS);
2980 
2981   // Check that x | Mask == x.
2982   // x | 0 == x, always
2983   // x | 1 == x, only if x is also 1
2984   // Meaning Mask has no effect if every bit is either zero in Mask or one in x.
2985   //
2986   // Check if we can replace OrDst with the LHS of the G_OR
2987   if (canReplaceReg(OrDst, LHS, MRI) &&
2988       (LHSBits.One | RHSBits.Zero).isAllOnesValue()) {
2989     Replacement = LHS;
2990     return true;
2991   }
2992 
2993   // Check if we can replace OrDst with the RHS of the G_OR
2994   if (canReplaceReg(OrDst, RHS, MRI) &&
2995       (LHSBits.Zero | RHSBits.One).isAllOnesValue()) {
2996     Replacement = RHS;
2997     return true;
2998   }
2999 
3000   return false;
3001 }
3002 
3003 bool CombinerHelper::matchRedundantSExtInReg(MachineInstr &MI) {
3004   // If the input is already sign extended, just drop the extension.
3005   Register Src = MI.getOperand(1).getReg();
3006   unsigned ExtBits = MI.getOperand(2).getImm();
3007   unsigned TypeSize = MRI.getType(Src).getScalarSizeInBits();
3008   return KB->computeNumSignBits(Src) >= (TypeSize - ExtBits + 1);
3009 }
3010 
3011 static bool isConstValidTrue(const TargetLowering &TLI, unsigned ScalarSizeBits,
3012                              int64_t Cst, bool IsVector, bool IsFP) {
3013   // For i1, Cst will always be -1 regardless of boolean contents.
3014   return (ScalarSizeBits == 1 && Cst == -1) ||
3015          isConstTrueVal(TLI, Cst, IsVector, IsFP);
3016 }
3017 
3018 bool CombinerHelper::matchNotCmp(MachineInstr &MI,
3019                                  SmallVectorImpl<Register> &RegsToNegate) {
3020   assert(MI.getOpcode() == TargetOpcode::G_XOR);
3021   LLT Ty = MRI.getType(MI.getOperand(0).getReg());
3022   const auto &TLI = *Builder.getMF().getSubtarget().getTargetLowering();
3023   Register XorSrc;
3024   Register CstReg;
3025   // We match xor(src, true) here.
3026   if (!mi_match(MI.getOperand(0).getReg(), MRI,
3027                 m_GXor(m_Reg(XorSrc), m_Reg(CstReg))))
3028     return false;
3029 
3030   if (!MRI.hasOneNonDBGUse(XorSrc))
3031     return false;
3032 
3033   // Check that XorSrc is the root of a tree of comparisons combined with ANDs
3034   // and ORs. The suffix of RegsToNegate starting from index I is used a work
3035   // list of tree nodes to visit.
3036   RegsToNegate.push_back(XorSrc);
3037   // Remember whether the comparisons are all integer or all floating point.
3038   bool IsInt = false;
3039   bool IsFP = false;
3040   for (unsigned I = 0; I < RegsToNegate.size(); ++I) {
3041     Register Reg = RegsToNegate[I];
3042     if (!MRI.hasOneNonDBGUse(Reg))
3043       return false;
3044     MachineInstr *Def = MRI.getVRegDef(Reg);
3045     switch (Def->getOpcode()) {
3046     default:
3047       // Don't match if the tree contains anything other than ANDs, ORs and
3048       // comparisons.
3049       return false;
3050     case TargetOpcode::G_ICMP:
3051       if (IsFP)
3052         return false;
3053       IsInt = true;
3054       // When we apply the combine we will invert the predicate.
3055       break;
3056     case TargetOpcode::G_FCMP:
3057       if (IsInt)
3058         return false;
3059       IsFP = true;
3060       // When we apply the combine we will invert the predicate.
3061       break;
3062     case TargetOpcode::G_AND:
3063     case TargetOpcode::G_OR:
3064       // Implement De Morgan's laws:
3065       // ~(x & y) -> ~x | ~y
3066       // ~(x | y) -> ~x & ~y
3067       // When we apply the combine we will change the opcode and recursively
3068       // negate the operands.
3069       RegsToNegate.push_back(Def->getOperand(1).getReg());
3070       RegsToNegate.push_back(Def->getOperand(2).getReg());
3071       break;
3072     }
3073   }
3074 
3075   // Now we know whether the comparisons are integer or floating point, check
3076   // the constant in the xor.
3077   int64_t Cst;
3078   if (Ty.isVector()) {
3079     MachineInstr *CstDef = MRI.getVRegDef(CstReg);
3080     auto MaybeCst = getBuildVectorConstantSplat(*CstDef, MRI);
3081     if (!MaybeCst)
3082       return false;
3083     if (!isConstValidTrue(TLI, Ty.getScalarSizeInBits(), *MaybeCst, true, IsFP))
3084       return false;
3085   } else {
3086     if (!mi_match(CstReg, MRI, m_ICst(Cst)))
3087       return false;
3088     if (!isConstValidTrue(TLI, Ty.getSizeInBits(), Cst, false, IsFP))
3089       return false;
3090   }
3091 
3092   return true;
3093 }
3094 
3095 bool CombinerHelper::applyNotCmp(MachineInstr &MI,
3096                                  SmallVectorImpl<Register> &RegsToNegate) {
3097   for (Register Reg : RegsToNegate) {
3098     MachineInstr *Def = MRI.getVRegDef(Reg);
3099     Observer.changingInstr(*Def);
3100     // For each comparison, invert the opcode. For each AND and OR, change the
3101     // opcode.
3102     switch (Def->getOpcode()) {
3103     default:
3104       llvm_unreachable("Unexpected opcode");
3105     case TargetOpcode::G_ICMP:
3106     case TargetOpcode::G_FCMP: {
3107       MachineOperand &PredOp = Def->getOperand(1);
3108       CmpInst::Predicate NewP = CmpInst::getInversePredicate(
3109           (CmpInst::Predicate)PredOp.getPredicate());
3110       PredOp.setPredicate(NewP);
3111       break;
3112     }
3113     case TargetOpcode::G_AND:
3114       Def->setDesc(Builder.getTII().get(TargetOpcode::G_OR));
3115       break;
3116     case TargetOpcode::G_OR:
3117       Def->setDesc(Builder.getTII().get(TargetOpcode::G_AND));
3118       break;
3119     }
3120     Observer.changedInstr(*Def);
3121   }
3122 
3123   replaceRegWith(MRI, MI.getOperand(0).getReg(), MI.getOperand(1).getReg());
3124   MI.eraseFromParent();
3125   return true;
3126 }
3127 
3128 bool CombinerHelper::matchXorOfAndWithSameReg(
3129     MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
3130   // Match (xor (and x, y), y) (or any of its commuted cases)
3131   assert(MI.getOpcode() == TargetOpcode::G_XOR);
3132   Register &X = MatchInfo.first;
3133   Register &Y = MatchInfo.second;
3134   Register AndReg = MI.getOperand(1).getReg();
3135   Register SharedReg = MI.getOperand(2).getReg();
3136 
3137   // Find a G_AND on either side of the G_XOR.
3138   // Look for one of
3139   //
3140   // (xor (and x, y), SharedReg)
3141   // (xor SharedReg, (and x, y))
3142   if (!mi_match(AndReg, MRI, m_GAnd(m_Reg(X), m_Reg(Y)))) {
3143     std::swap(AndReg, SharedReg);
3144     if (!mi_match(AndReg, MRI, m_GAnd(m_Reg(X), m_Reg(Y))))
3145       return false;
3146   }
3147 
3148   // Only do this if we'll eliminate the G_AND.
3149   if (!MRI.hasOneNonDBGUse(AndReg))
3150     return false;
3151 
3152   // We can combine if SharedReg is the same as either the LHS or RHS of the
3153   // G_AND.
3154   if (Y != SharedReg)
3155     std::swap(X, Y);
3156   return Y == SharedReg;
3157 }
3158 
3159 bool CombinerHelper::applyXorOfAndWithSameReg(
3160     MachineInstr &MI, std::pair<Register, Register> &MatchInfo) {
3161   // Fold (xor (and x, y), y) -> (and (not x), y)
3162   Builder.setInstrAndDebugLoc(MI);
3163   Register X, Y;
3164   std::tie(X, Y) = MatchInfo;
3165   auto Not = Builder.buildNot(MRI.getType(X), X);
3166   Observer.changingInstr(MI);
3167   MI.setDesc(Builder.getTII().get(TargetOpcode::G_AND));
3168   MI.getOperand(1).setReg(Not->getOperand(0).getReg());
3169   MI.getOperand(2).setReg(Y);
3170   Observer.changedInstr(MI);
3171   return true;
3172 }
3173 
3174 bool CombinerHelper::matchPtrAddZero(MachineInstr &MI) {
3175   Register DstReg = MI.getOperand(0).getReg();
3176   LLT Ty = MRI.getType(DstReg);
3177   const DataLayout &DL = Builder.getMF().getDataLayout();
3178 
3179   if (DL.isNonIntegralAddressSpace(Ty.getScalarType().getAddressSpace()))
3180     return false;
3181 
3182   if (Ty.isPointer()) {
3183     auto ConstVal = getConstantVRegVal(MI.getOperand(1).getReg(), MRI);
3184     return ConstVal && *ConstVal == 0;
3185   }
3186 
3187   assert(Ty.isVector() && "Expecting a vector type");
3188   const MachineInstr *VecMI = MRI.getVRegDef(MI.getOperand(1).getReg());
3189   return isBuildVectorAllZeros(*VecMI, MRI);
3190 }
3191 
3192 bool CombinerHelper::applyPtrAddZero(MachineInstr &MI) {
3193   assert(MI.getOpcode() == TargetOpcode::G_PTR_ADD);
3194   Builder.setInstrAndDebugLoc(MI);
3195   Builder.buildIntToPtr(MI.getOperand(0), MI.getOperand(2));
3196   MI.eraseFromParent();
3197   return true;
3198 }
3199 
3200 /// The second source operand is known to be a power of 2.
3201 bool CombinerHelper::applySimplifyURemByPow2(MachineInstr &MI) {
3202   Register DstReg = MI.getOperand(0).getReg();
3203   Register Src0 = MI.getOperand(1).getReg();
3204   Register Pow2Src1 = MI.getOperand(2).getReg();
3205   LLT Ty = MRI.getType(DstReg);
3206   Builder.setInstrAndDebugLoc(MI);
3207 
3208   // Fold (urem x, pow2) -> (and x, pow2-1)
3209   auto NegOne = Builder.buildConstant(Ty, -1);
3210   auto Add = Builder.buildAdd(Ty, Pow2Src1, NegOne);
3211   Builder.buildAnd(DstReg, Src0, Add);
3212   MI.eraseFromParent();
3213   return true;
3214 }
3215 
3216 Optional<SmallVector<Register, 8>>
3217 CombinerHelper::findCandidatesForLoadOrCombine(const MachineInstr *Root) const {
3218   assert(Root->getOpcode() == TargetOpcode::G_OR && "Expected G_OR only!");
3219   // We want to detect if Root is part of a tree which represents a bunch
3220   // of loads being merged into a larger load. We'll try to recognize patterns
3221   // like, for example:
3222   //
3223   //  Reg   Reg
3224   //   \    /
3225   //    OR_1   Reg
3226   //     \    /
3227   //      OR_2
3228   //        \     Reg
3229   //         .. /
3230   //        Root
3231   //
3232   //  Reg   Reg   Reg   Reg
3233   //     \ /       \   /
3234   //     OR_1      OR_2
3235   //       \       /
3236   //        \    /
3237   //         ...
3238   //         Root
3239   //
3240   // Each "Reg" may have been produced by a load + some arithmetic. This
3241   // function will save each of them.
3242   SmallVector<Register, 8> RegsToVisit;
3243   SmallVector<const MachineInstr *, 7> Ors = {Root};
3244 
3245   // In the "worst" case, we're dealing with a load for each byte. So, there
3246   // are at most #bytes - 1 ORs.
3247   const unsigned MaxIter =
3248       MRI.getType(Root->getOperand(0).getReg()).getSizeInBytes() - 1;
3249   for (unsigned Iter = 0; Iter < MaxIter; ++Iter) {
3250     if (Ors.empty())
3251       break;
3252     const MachineInstr *Curr = Ors.pop_back_val();
3253     Register OrLHS = Curr->getOperand(1).getReg();
3254     Register OrRHS = Curr->getOperand(2).getReg();
3255 
3256     // In the combine, we want to elimate the entire tree.
3257     if (!MRI.hasOneNonDBGUse(OrLHS) || !MRI.hasOneNonDBGUse(OrRHS))
3258       return None;
3259 
3260     // If it's a G_OR, save it and continue to walk. If it's not, then it's
3261     // something that may be a load + arithmetic.
3262     if (const MachineInstr *Or = getOpcodeDef(TargetOpcode::G_OR, OrLHS, MRI))
3263       Ors.push_back(Or);
3264     else
3265       RegsToVisit.push_back(OrLHS);
3266     if (const MachineInstr *Or = getOpcodeDef(TargetOpcode::G_OR, OrRHS, MRI))
3267       Ors.push_back(Or);
3268     else
3269       RegsToVisit.push_back(OrRHS);
3270   }
3271 
3272   // We're going to try and merge each register into a wider power-of-2 type,
3273   // so we ought to have an even number of registers.
3274   if (RegsToVisit.empty() || RegsToVisit.size() % 2 != 0)
3275     return None;
3276   return RegsToVisit;
3277 }
3278 
3279 /// Helper function for findLoadOffsetsForLoadOrCombine.
3280 ///
3281 /// Check if \p Reg is the result of loading a \p MemSizeInBits wide value,
3282 /// and then moving that value into a specific byte offset.
3283 ///
3284 /// e.g. x[i] << 24
3285 ///
3286 /// \returns The load instruction and the byte offset it is moved into.
3287 static Optional<std::pair<MachineInstr *, int64_t>>
3288 matchLoadAndBytePosition(Register Reg, unsigned MemSizeInBits,
3289                          const MachineRegisterInfo &MRI) {
3290   assert(MRI.hasOneNonDBGUse(Reg) &&
3291          "Expected Reg to only have one non-debug use?");
3292   Register MaybeLoad;
3293   int64_t Shift;
3294   if (!mi_match(Reg, MRI,
3295                 m_OneNonDBGUse(m_GShl(m_Reg(MaybeLoad), m_ICst(Shift))))) {
3296     Shift = 0;
3297     MaybeLoad = Reg;
3298   }
3299 
3300   if (Shift % MemSizeInBits != 0)
3301     return None;
3302 
3303   // TODO: Handle other types of loads.
3304   auto *Load = getOpcodeDef(TargetOpcode::G_ZEXTLOAD, MaybeLoad, MRI);
3305   if (!Load)
3306     return None;
3307 
3308   const auto &MMO = **Load->memoperands_begin();
3309   if (!MMO.isUnordered() || MMO.getSizeInBits() != MemSizeInBits)
3310     return None;
3311 
3312   return std::make_pair(Load, Shift / MemSizeInBits);
3313 }
3314 
3315 Optional<std::pair<MachineInstr *, int64_t>>
3316 CombinerHelper::findLoadOffsetsForLoadOrCombine(
3317     SmallDenseMap<int64_t, int64_t, 8> &MemOffset2Idx,
3318     const SmallVector<Register, 8> &RegsToVisit, const unsigned MemSizeInBits) {
3319 
3320   // Each load found for the pattern. There should be one for each RegsToVisit.
3321   SmallSetVector<const MachineInstr *, 8> Loads;
3322 
3323   // The lowest index used in any load. (The lowest "i" for each x[i].)
3324   int64_t LowestIdx = INT64_MAX;
3325 
3326   // The load which uses the lowest index.
3327   MachineInstr *LowestIdxLoad = nullptr;
3328 
3329   // Keeps track of the load indices we see. We shouldn't see any indices twice.
3330   SmallSet<int64_t, 8> SeenIdx;
3331 
3332   // Ensure each load is in the same MBB.
3333   // TODO: Support multiple MachineBasicBlocks.
3334   MachineBasicBlock *MBB = nullptr;
3335   const MachineMemOperand *MMO = nullptr;
3336 
3337   // Earliest instruction-order load in the pattern.
3338   MachineInstr *EarliestLoad = nullptr;
3339 
3340   // Latest instruction-order load in the pattern.
3341   MachineInstr *LatestLoad = nullptr;
3342 
3343   // Base pointer which every load should share.
3344   Register BasePtr;
3345 
3346   // We want to find a load for each register. Each load should have some
3347   // appropriate bit twiddling arithmetic. During this loop, we will also keep
3348   // track of the load which uses the lowest index. Later, we will check if we
3349   // can use its pointer in the final, combined load.
3350   for (auto Reg : RegsToVisit) {
3351     // Find the load, and find the position that it will end up in (e.g. a
3352     // shifted) value.
3353     auto LoadAndPos = matchLoadAndBytePosition(Reg, MemSizeInBits, MRI);
3354     if (!LoadAndPos)
3355       return None;
3356     MachineInstr *Load;
3357     int64_t DstPos;
3358     std::tie(Load, DstPos) = *LoadAndPos;
3359 
3360     // TODO: Handle multiple MachineBasicBlocks. Currently not handled because
3361     // it is difficult to check for stores/calls/etc between loads.
3362     MachineBasicBlock *LoadMBB = Load->getParent();
3363     if (!MBB)
3364       MBB = LoadMBB;
3365     if (LoadMBB != MBB)
3366       return None;
3367 
3368     // Make sure that the MachineMemOperands of every seen load are compatible.
3369     const MachineMemOperand *LoadMMO = *Load->memoperands_begin();
3370     if (!MMO)
3371       MMO = LoadMMO;
3372     if (MMO->getAddrSpace() != LoadMMO->getAddrSpace())
3373       return None;
3374 
3375     // Find out what the base pointer and index for the load is.
3376     Register LoadPtr;
3377     int64_t Idx;
3378     if (!mi_match(Load->getOperand(1).getReg(), MRI,
3379                   m_GPtrAdd(m_Reg(LoadPtr), m_ICst(Idx)))) {
3380       LoadPtr = Load->getOperand(1).getReg();
3381       Idx = 0;
3382     }
3383 
3384     // Don't combine things like a[i], a[i] -> a bigger load.
3385     if (!SeenIdx.insert(Idx).second)
3386       return None;
3387 
3388     // Every load must share the same base pointer; don't combine things like:
3389     //
3390     // a[i], b[i + 1] -> a bigger load.
3391     if (!BasePtr.isValid())
3392       BasePtr = LoadPtr;
3393     if (BasePtr != LoadPtr)
3394       return None;
3395 
3396     if (Idx < LowestIdx) {
3397       LowestIdx = Idx;
3398       LowestIdxLoad = Load;
3399     }
3400 
3401     // Keep track of the byte offset that this load ends up at. If we have seen
3402     // the byte offset, then stop here. We do not want to combine:
3403     //
3404     // a[i] << 16, a[i + k] << 16 -> a bigger load.
3405     if (!MemOffset2Idx.try_emplace(DstPos, Idx).second)
3406       return None;
3407     Loads.insert(Load);
3408 
3409     // Keep track of the position of the earliest/latest loads in the pattern.
3410     // We will check that there are no load fold barriers between them later
3411     // on.
3412     //
3413     // FIXME: Is there a better way to check for load fold barriers?
3414     if (!EarliestLoad || dominates(*Load, *EarliestLoad))
3415       EarliestLoad = Load;
3416     if (!LatestLoad || dominates(*LatestLoad, *Load))
3417       LatestLoad = Load;
3418   }
3419 
3420   // We found a load for each register. Let's check if each load satisfies the
3421   // pattern.
3422   assert(Loads.size() == RegsToVisit.size() &&
3423          "Expected to find a load for each register?");
3424   assert(EarliestLoad != LatestLoad && EarliestLoad &&
3425          LatestLoad && "Expected at least two loads?");
3426 
3427   // Check if there are any stores, calls, etc. between any of the loads. If
3428   // there are, then we can't safely perform the combine.
3429   //
3430   // MaxIter is chosen based off the (worst case) number of iterations it
3431   // typically takes to succeed in the LLVM test suite plus some padding.
3432   //
3433   // FIXME: Is there a better way to check for load fold barriers?
3434   const unsigned MaxIter = 20;
3435   unsigned Iter = 0;
3436   for (const auto &MI : instructionsWithoutDebug(EarliestLoad->getIterator(),
3437                                                  LatestLoad->getIterator())) {
3438     if (Loads.count(&MI))
3439       continue;
3440     if (MI.isLoadFoldBarrier())
3441       return None;
3442     if (Iter++ == MaxIter)
3443       return None;
3444   }
3445 
3446   return std::make_pair(LowestIdxLoad, LowestIdx);
3447 }
3448 
3449 bool CombinerHelper::matchLoadOrCombine(
3450     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
3451   assert(MI.getOpcode() == TargetOpcode::G_OR);
3452   MachineFunction &MF = *MI.getMF();
3453   // Assuming a little-endian target, transform:
3454   //  s8 *a = ...
3455   //  s32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
3456   // =>
3457   //  s32 val = *((i32)a)
3458   //
3459   //  s8 *a = ...
3460   //  s32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
3461   // =>
3462   //  s32 val = BSWAP(*((s32)a))
3463   Register Dst = MI.getOperand(0).getReg();
3464   LLT Ty = MRI.getType(Dst);
3465   if (Ty.isVector())
3466     return false;
3467 
3468   // We need to combine at least two loads into this type. Since the smallest
3469   // possible load is into a byte, we need at least a 16-bit wide type.
3470   const unsigned WideMemSizeInBits = Ty.getSizeInBits();
3471   if (WideMemSizeInBits < 16 || WideMemSizeInBits % 8 != 0)
3472     return false;
3473 
3474   // Match a collection of non-OR instructions in the pattern.
3475   auto RegsToVisit = findCandidatesForLoadOrCombine(&MI);
3476   if (!RegsToVisit)
3477     return false;
3478 
3479   // We have a collection of non-OR instructions. Figure out how wide each of
3480   // the small loads should be based off of the number of potential loads we
3481   // found.
3482   const unsigned NarrowMemSizeInBits = WideMemSizeInBits / RegsToVisit->size();
3483   if (NarrowMemSizeInBits % 8 != 0)
3484     return false;
3485 
3486   // Check if each register feeding into each OR is a load from the same
3487   // base pointer + some arithmetic.
3488   //
3489   // e.g. a[0], a[1] << 8, a[2] << 16, etc.
3490   //
3491   // Also verify that each of these ends up putting a[i] into the same memory
3492   // offset as a load into a wide type would.
3493   SmallDenseMap<int64_t, int64_t, 8> MemOffset2Idx;
3494   MachineInstr *LowestIdxLoad;
3495   int64_t LowestIdx;
3496   auto MaybeLoadInfo = findLoadOffsetsForLoadOrCombine(
3497       MemOffset2Idx, *RegsToVisit, NarrowMemSizeInBits);
3498   if (!MaybeLoadInfo)
3499     return false;
3500   std::tie(LowestIdxLoad, LowestIdx) = *MaybeLoadInfo;
3501 
3502   // We have a bunch of loads being OR'd together. Using the addresses + offsets
3503   // we found before, check if this corresponds to a big or little endian byte
3504   // pattern. If it does, then we can represent it using a load + possibly a
3505   // BSWAP.
3506   bool IsBigEndianTarget = MF.getDataLayout().isBigEndian();
3507   Optional<bool> IsBigEndian = isBigEndian(MemOffset2Idx, LowestIdx);
3508   if (!IsBigEndian.hasValue())
3509     return false;
3510   bool NeedsBSwap = IsBigEndianTarget != *IsBigEndian;
3511   if (NeedsBSwap && !isLegalOrBeforeLegalizer({TargetOpcode::G_BSWAP, {Ty}}))
3512     return false;
3513 
3514   // Make sure that the load from the lowest index produces offset 0 in the
3515   // final value.
3516   //
3517   // This ensures that we won't combine something like this:
3518   //
3519   // load x[i] -> byte 2
3520   // load x[i+1] -> byte 0 ---> wide_load x[i]
3521   // load x[i+2] -> byte 1
3522   const unsigned NumLoadsInTy = WideMemSizeInBits / NarrowMemSizeInBits;
3523   const unsigned ZeroByteOffset =
3524       *IsBigEndian
3525           ? bigEndianByteAt(NumLoadsInTy, 0)
3526           : littleEndianByteAt(NumLoadsInTy, 0);
3527   auto ZeroOffsetIdx = MemOffset2Idx.find(ZeroByteOffset);
3528   if (ZeroOffsetIdx == MemOffset2Idx.end() ||
3529       ZeroOffsetIdx->second != LowestIdx)
3530     return false;
3531 
3532   // We wil reuse the pointer from the load which ends up at byte offset 0. It
3533   // may not use index 0.
3534   Register Ptr = LowestIdxLoad->getOperand(1).getReg();
3535   const MachineMemOperand &MMO = **LowestIdxLoad->memoperands_begin();
3536   LegalityQuery::MemDesc MMDesc;
3537   MMDesc.SizeInBits = WideMemSizeInBits;
3538   MMDesc.AlignInBits = MMO.getAlign().value() * 8;
3539   MMDesc.Ordering = MMO.getOrdering();
3540   if (!isLegalOrBeforeLegalizer(
3541           {TargetOpcode::G_LOAD, {Ty, MRI.getType(Ptr)}, {MMDesc}}))
3542     return false;
3543   auto PtrInfo = MMO.getPointerInfo();
3544   auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, WideMemSizeInBits / 8);
3545 
3546   // Load must be allowed and fast on the target.
3547   LLVMContext &C = MF.getFunction().getContext();
3548   auto &DL = MF.getDataLayout();
3549   bool Fast = false;
3550   if (!getTargetLowering().allowsMemoryAccess(C, DL, Ty, *NewMMO, &Fast) ||
3551       !Fast)
3552     return false;
3553 
3554   MatchInfo = [=](MachineIRBuilder &MIB) {
3555     Register LoadDst = NeedsBSwap ? MRI.cloneVirtualRegister(Dst) : Dst;
3556     MIB.buildLoad(LoadDst, Ptr, *NewMMO);
3557     if (NeedsBSwap)
3558       MIB.buildBSwap(Dst, LoadDst);
3559   };
3560   return true;
3561 }
3562 
3563 bool CombinerHelper::matchExtendThroughPhis(MachineInstr &MI,
3564                                             MachineInstr *&ExtMI) {
3565   assert(MI.getOpcode() == TargetOpcode::G_PHI);
3566 
3567   Register DstReg = MI.getOperand(0).getReg();
3568 
3569   // TODO: Extending a vector may be expensive, don't do this until heuristics
3570   // are better.
3571   if (MRI.getType(DstReg).isVector())
3572     return false;
3573 
3574   // Try to match a phi, whose only use is an extend.
3575   if (!MRI.hasOneNonDBGUse(DstReg))
3576     return false;
3577   ExtMI = &*MRI.use_instr_nodbg_begin(DstReg);
3578   switch (ExtMI->getOpcode()) {
3579   case TargetOpcode::G_ANYEXT:
3580     return true; // G_ANYEXT is usually free.
3581   case TargetOpcode::G_ZEXT:
3582   case TargetOpcode::G_SEXT:
3583     break;
3584   default:
3585     return false;
3586   }
3587 
3588   // If the target is likely to fold this extend away, don't propagate.
3589   if (Builder.getTII().isExtendLikelyToBeFolded(*ExtMI, MRI))
3590     return false;
3591 
3592   // We don't want to propagate the extends unless there's a good chance that
3593   // they'll be optimized in some way.
3594   // Collect the unique incoming values.
3595   SmallPtrSet<MachineInstr *, 4> InSrcs;
3596   for (unsigned Idx = 1; Idx < MI.getNumOperands(); Idx += 2) {
3597     auto *DefMI = getDefIgnoringCopies(MI.getOperand(Idx).getReg(), MRI);
3598     switch (DefMI->getOpcode()) {
3599     case TargetOpcode::G_LOAD:
3600     case TargetOpcode::G_TRUNC:
3601     case TargetOpcode::G_SEXT:
3602     case TargetOpcode::G_ZEXT:
3603     case TargetOpcode::G_ANYEXT:
3604     case TargetOpcode::G_CONSTANT:
3605       InSrcs.insert(getDefIgnoringCopies(MI.getOperand(Idx).getReg(), MRI));
3606       // Don't try to propagate if there are too many places to create new
3607       // extends, chances are it'll increase code size.
3608       if (InSrcs.size() > 2)
3609         return false;
3610       break;
3611     default:
3612       return false;
3613     }
3614   }
3615   return true;
3616 }
3617 
3618 bool CombinerHelper::applyExtendThroughPhis(MachineInstr &MI,
3619                                             MachineInstr *&ExtMI) {
3620   assert(MI.getOpcode() == TargetOpcode::G_PHI);
3621   Register DstReg = ExtMI->getOperand(0).getReg();
3622   LLT ExtTy = MRI.getType(DstReg);
3623 
3624   // Propagate the extension into the block of each incoming reg's block.
3625   // Use a SetVector here because PHIs can have duplicate edges, and we want
3626   // deterministic iteration order.
3627   SmallSetVector<MachineInstr *, 8> SrcMIs;
3628   SmallDenseMap<MachineInstr *, MachineInstr *, 8> OldToNewSrcMap;
3629   for (unsigned SrcIdx = 1; SrcIdx < MI.getNumOperands(); SrcIdx += 2) {
3630     auto *SrcMI = MRI.getVRegDef(MI.getOperand(SrcIdx).getReg());
3631     if (!SrcMIs.insert(SrcMI))
3632       continue;
3633 
3634     // Build an extend after each src inst.
3635     auto *MBB = SrcMI->getParent();
3636     MachineBasicBlock::iterator InsertPt = ++SrcMI->getIterator();
3637     if (InsertPt != MBB->end() && InsertPt->isPHI())
3638       InsertPt = MBB->getFirstNonPHI();
3639 
3640     Builder.setInsertPt(*SrcMI->getParent(), InsertPt);
3641     Builder.setDebugLoc(MI.getDebugLoc());
3642     auto NewExt = Builder.buildExtOrTrunc(ExtMI->getOpcode(), ExtTy,
3643                                           SrcMI->getOperand(0).getReg());
3644     OldToNewSrcMap[SrcMI] = NewExt;
3645   }
3646 
3647   // Create a new phi with the extended inputs.
3648   Builder.setInstrAndDebugLoc(MI);
3649   auto NewPhi = Builder.buildInstrNoInsert(TargetOpcode::G_PHI);
3650   NewPhi.addDef(DstReg);
3651   for (unsigned SrcIdx = 1; SrcIdx < MI.getNumOperands(); ++SrcIdx) {
3652     auto &MO = MI.getOperand(SrcIdx);
3653     if (!MO.isReg()) {
3654       NewPhi.addMBB(MO.getMBB());
3655       continue;
3656     }
3657     auto *NewSrc = OldToNewSrcMap[MRI.getVRegDef(MO.getReg())];
3658     NewPhi.addUse(NewSrc->getOperand(0).getReg());
3659   }
3660   Builder.insertInstr(NewPhi);
3661   ExtMI->eraseFromParent();
3662   return true;
3663 }
3664 
3665 bool CombinerHelper::applyLoadOrCombine(
3666     MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) {
3667   Builder.setInstrAndDebugLoc(MI);
3668   MatchInfo(Builder);
3669   MI.eraseFromParent();
3670   return true;
3671 }
3672 
3673 bool CombinerHelper::tryCombine(MachineInstr &MI) {
3674   if (tryCombineCopy(MI))
3675     return true;
3676   if (tryCombineExtendingLoads(MI))
3677     return true;
3678   if (tryCombineIndexedLoadStore(MI))
3679     return true;
3680   return false;
3681 }
3682