1 //===-- lib/CodeGen/GlobalISel/GICombinerHelper.cpp -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 #include "llvm/CodeGen/GlobalISel/CombinerHelper.h"
9 #include "llvm/CodeGen/GlobalISel/Combiner.h"
10 #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
11 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
12 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
13 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
14 #include "llvm/CodeGen/GlobalISel/Utils.h"
15 #include "llvm/CodeGen/MachineDominators.h"
16 #include "llvm/CodeGen/MachineFrameInfo.h"
17 #include "llvm/CodeGen/MachineInstr.h"
18 #include "llvm/CodeGen/MachineRegisterInfo.h"
19 #include "llvm/CodeGen/TargetInstrInfo.h"
20 #include "llvm/CodeGen/TargetLowering.h"
21 #include "llvm/Support/MathExtras.h"
22 #include "llvm/Target/TargetMachine.h"
23 
24 #define DEBUG_TYPE "gi-combiner"
25 
26 using namespace llvm;
27 using namespace MIPatternMatch;
28 
29 // Option to allow testing of the combiner while no targets know about indexed
30 // addressing.
31 static cl::opt<bool>
32     ForceLegalIndexing("force-legal-indexing", cl::Hidden, cl::init(false),
33                        cl::desc("Force all indexed operations to be "
34                                 "legal for the GlobalISel combiner"));
35 
36 
37 CombinerHelper::CombinerHelper(GISelChangeObserver &Observer,
38                                MachineIRBuilder &B, GISelKnownBits *KB,
39                                MachineDominatorTree *MDT)
40     : Builder(B), MRI(Builder.getMF().getRegInfo()), Observer(Observer),
41       KB(KB), MDT(MDT) {
42   (void)this->KB;
43 }
44 
45 void CombinerHelper::replaceRegWith(MachineRegisterInfo &MRI, Register FromReg,
46                                     Register ToReg) const {
47   Observer.changingAllUsesOfReg(MRI, FromReg);
48 
49   if (MRI.constrainRegAttrs(ToReg, FromReg))
50     MRI.replaceRegWith(FromReg, ToReg);
51   else
52     Builder.buildCopy(ToReg, FromReg);
53 
54   Observer.finishedChangingAllUsesOfReg();
55 }
56 
57 void CombinerHelper::replaceRegOpWith(MachineRegisterInfo &MRI,
58                                       MachineOperand &FromRegOp,
59                                       Register ToReg) const {
60   assert(FromRegOp.getParent() && "Expected an operand in an MI");
61   Observer.changingInstr(*FromRegOp.getParent());
62 
63   FromRegOp.setReg(ToReg);
64 
65   Observer.changedInstr(*FromRegOp.getParent());
66 }
67 
68 bool CombinerHelper::tryCombineCopy(MachineInstr &MI) {
69   if (matchCombineCopy(MI)) {
70     applyCombineCopy(MI);
71     return true;
72   }
73   return false;
74 }
75 bool CombinerHelper::matchCombineCopy(MachineInstr &MI) {
76   if (MI.getOpcode() != TargetOpcode::COPY)
77     return false;
78   Register DstReg = MI.getOperand(0).getReg();
79   Register SrcReg = MI.getOperand(1).getReg();
80   return canReplaceReg(DstReg, SrcReg, MRI);
81 }
82 void CombinerHelper::applyCombineCopy(MachineInstr &MI) {
83   Register DstReg = MI.getOperand(0).getReg();
84   Register SrcReg = MI.getOperand(1).getReg();
85   MI.eraseFromParent();
86   replaceRegWith(MRI, DstReg, SrcReg);
87 }
88 
89 bool CombinerHelper::tryCombineConcatVectors(MachineInstr &MI) {
90   bool IsUndef = false;
91   SmallVector<Register, 4> Ops;
92   if (matchCombineConcatVectors(MI, IsUndef, Ops)) {
93     applyCombineConcatVectors(MI, IsUndef, Ops);
94     return true;
95   }
96   return false;
97 }
98 
99 bool CombinerHelper::matchCombineConcatVectors(MachineInstr &MI, bool &IsUndef,
100                                                SmallVectorImpl<Register> &Ops) {
101   assert(MI.getOpcode() == TargetOpcode::G_CONCAT_VECTORS &&
102          "Invalid instruction");
103   IsUndef = true;
104   MachineInstr *Undef = nullptr;
105 
106   // Walk over all the operands of concat vectors and check if they are
107   // build_vector themselves or undef.
108   // Then collect their operands in Ops.
109   for (const MachineOperand &MO : MI.uses()) {
110     Register Reg = MO.getReg();
111     MachineInstr *Def = MRI.getVRegDef(Reg);
112     assert(Def && "Operand not defined");
113     switch (Def->getOpcode()) {
114     case TargetOpcode::G_BUILD_VECTOR:
115       IsUndef = false;
116       // Remember the operands of the build_vector to fold
117       // them into the yet-to-build flattened concat vectors.
118       for (const MachineOperand &BuildVecMO : Def->uses())
119         Ops.push_back(BuildVecMO.getReg());
120       break;
121     case TargetOpcode::G_IMPLICIT_DEF: {
122       LLT OpType = MRI.getType(Reg);
123       // Keep one undef value for all the undef operands.
124       if (!Undef) {
125         Builder.setInsertPt(*MI.getParent(), MI);
126         Undef = Builder.buildUndef(OpType.getScalarType());
127       }
128       assert(MRI.getType(Undef->getOperand(0).getReg()) ==
129                  OpType.getScalarType() &&
130              "All undefs should have the same type");
131       // Break the undef vector in as many scalar elements as needed
132       // for the flattening.
133       for (unsigned EltIdx = 0, EltEnd = OpType.getNumElements();
134            EltIdx != EltEnd; ++EltIdx)
135         Ops.push_back(Undef->getOperand(0).getReg());
136       break;
137     }
138     default:
139       return false;
140     }
141   }
142   return true;
143 }
144 void CombinerHelper::applyCombineConcatVectors(
145     MachineInstr &MI, bool IsUndef, const ArrayRef<Register> Ops) {
146   // We determined that the concat_vectors can be flatten.
147   // Generate the flattened build_vector.
148   Register DstReg = MI.getOperand(0).getReg();
149   Builder.setInsertPt(*MI.getParent(), MI);
150   Register NewDstReg = MRI.cloneVirtualRegister(DstReg);
151 
152   // Note: IsUndef is sort of redundant. We could have determine it by
153   // checking that at all Ops are undef.  Alternatively, we could have
154   // generate a build_vector of undefs and rely on another combine to
155   // clean that up.  For now, given we already gather this information
156   // in tryCombineConcatVectors, just save compile time and issue the
157   // right thing.
158   if (IsUndef)
159     Builder.buildUndef(NewDstReg);
160   else
161     Builder.buildBuildVector(NewDstReg, Ops);
162   MI.eraseFromParent();
163   replaceRegWith(MRI, DstReg, NewDstReg);
164 }
165 
166 bool CombinerHelper::tryCombineShuffleVector(MachineInstr &MI) {
167   SmallVector<Register, 4> Ops;
168   if (matchCombineShuffleVector(MI, Ops)) {
169     applyCombineShuffleVector(MI, Ops);
170     return true;
171   }
172   return false;
173 }
174 
175 bool CombinerHelper::matchCombineShuffleVector(MachineInstr &MI,
176                                                SmallVectorImpl<Register> &Ops) {
177   assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR &&
178          "Invalid instruction kind");
179   LLT DstType = MRI.getType(MI.getOperand(0).getReg());
180   Register Src1 = MI.getOperand(1).getReg();
181   LLT SrcType = MRI.getType(Src1);
182   // As bizarre as it may look, shuffle vector can actually produce
183   // scalar! This is because at the IR level a <1 x ty> shuffle
184   // vector is perfectly valid.
185   unsigned DstNumElts = DstType.isVector() ? DstType.getNumElements() : 1;
186   unsigned SrcNumElts = SrcType.isVector() ? SrcType.getNumElements() : 1;
187 
188   // If the resulting vector is smaller than the size of the source
189   // vectors being concatenated, we won't be able to replace the
190   // shuffle vector into a concat_vectors.
191   //
192   // Note: We may still be able to produce a concat_vectors fed by
193   //       extract_vector_elt and so on. It is less clear that would
194   //       be better though, so don't bother for now.
195   //
196   // If the destination is a scalar, the size of the sources doesn't
197   // matter. we will lower the shuffle to a plain copy. This will
198   // work only if the source and destination have the same size. But
199   // that's covered by the next condition.
200   //
201   // TODO: If the size between the source and destination don't match
202   //       we could still emit an extract vector element in that case.
203   if (DstNumElts < 2 * SrcNumElts && DstNumElts != 1)
204     return false;
205 
206   // Check that the shuffle mask can be broken evenly between the
207   // different sources.
208   if (DstNumElts % SrcNumElts != 0)
209     return false;
210 
211   // Mask length is a multiple of the source vector length.
212   // Check if the shuffle is some kind of concatenation of the input
213   // vectors.
214   unsigned NumConcat = DstNumElts / SrcNumElts;
215   SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
216   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
217   for (unsigned i = 0; i != DstNumElts; ++i) {
218     int Idx = Mask[i];
219     // Undef value.
220     if (Idx < 0)
221       continue;
222     // Ensure the indices in each SrcType sized piece are sequential and that
223     // the same source is used for the whole piece.
224     if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
225         (ConcatSrcs[i / SrcNumElts] >= 0 &&
226          ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts)))
227       return false;
228     // Remember which source this index came from.
229     ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
230   }
231 
232   // The shuffle is concatenating multiple vectors together.
233   // Collect the different operands for that.
234   Register UndefReg;
235   Register Src2 = MI.getOperand(2).getReg();
236   for (auto Src : ConcatSrcs) {
237     if (Src < 0) {
238       if (!UndefReg) {
239         Builder.setInsertPt(*MI.getParent(), MI);
240         UndefReg = Builder.buildUndef(SrcType).getReg(0);
241       }
242       Ops.push_back(UndefReg);
243     } else if (Src == 0)
244       Ops.push_back(Src1);
245     else
246       Ops.push_back(Src2);
247   }
248   return true;
249 }
250 
251 void CombinerHelper::applyCombineShuffleVector(MachineInstr &MI,
252                                                const ArrayRef<Register> Ops) {
253   Register DstReg = MI.getOperand(0).getReg();
254   Builder.setInsertPt(*MI.getParent(), MI);
255   Register NewDstReg = MRI.cloneVirtualRegister(DstReg);
256 
257   if (Ops.size() == 1)
258     Builder.buildCopy(NewDstReg, Ops[0]);
259   else
260     Builder.buildMerge(NewDstReg, Ops);
261 
262   MI.eraseFromParent();
263   replaceRegWith(MRI, DstReg, NewDstReg);
264 }
265 
266 namespace {
267 
268 /// Select a preference between two uses. CurrentUse is the current preference
269 /// while *ForCandidate is attributes of the candidate under consideration.
270 PreferredTuple ChoosePreferredUse(PreferredTuple &CurrentUse,
271                                   const LLT TyForCandidate,
272                                   unsigned OpcodeForCandidate,
273                                   MachineInstr *MIForCandidate) {
274   if (!CurrentUse.Ty.isValid()) {
275     if (CurrentUse.ExtendOpcode == OpcodeForCandidate ||
276         CurrentUse.ExtendOpcode == TargetOpcode::G_ANYEXT)
277       return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
278     return CurrentUse;
279   }
280 
281   // We permit the extend to hoist through basic blocks but this is only
282   // sensible if the target has extending loads. If you end up lowering back
283   // into a load and extend during the legalizer then the end result is
284   // hoisting the extend up to the load.
285 
286   // Prefer defined extensions to undefined extensions as these are more
287   // likely to reduce the number of instructions.
288   if (OpcodeForCandidate == TargetOpcode::G_ANYEXT &&
289       CurrentUse.ExtendOpcode != TargetOpcode::G_ANYEXT)
290     return CurrentUse;
291   else if (CurrentUse.ExtendOpcode == TargetOpcode::G_ANYEXT &&
292            OpcodeForCandidate != TargetOpcode::G_ANYEXT)
293     return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
294 
295   // Prefer sign extensions to zero extensions as sign-extensions tend to be
296   // more expensive.
297   if (CurrentUse.Ty == TyForCandidate) {
298     if (CurrentUse.ExtendOpcode == TargetOpcode::G_SEXT &&
299         OpcodeForCandidate == TargetOpcode::G_ZEXT)
300       return CurrentUse;
301     else if (CurrentUse.ExtendOpcode == TargetOpcode::G_ZEXT &&
302              OpcodeForCandidate == TargetOpcode::G_SEXT)
303       return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
304   }
305 
306   // This is potentially target specific. We've chosen the largest type
307   // because G_TRUNC is usually free. One potential catch with this is that
308   // some targets have a reduced number of larger registers than smaller
309   // registers and this choice potentially increases the live-range for the
310   // larger value.
311   if (TyForCandidate.getSizeInBits() > CurrentUse.Ty.getSizeInBits()) {
312     return {TyForCandidate, OpcodeForCandidate, MIForCandidate};
313   }
314   return CurrentUse;
315 }
316 
317 /// Find a suitable place to insert some instructions and insert them. This
318 /// function accounts for special cases like inserting before a PHI node.
319 /// The current strategy for inserting before PHI's is to duplicate the
320 /// instructions for each predecessor. However, while that's ok for G_TRUNC
321 /// on most targets since it generally requires no code, other targets/cases may
322 /// want to try harder to find a dominating block.
323 static void InsertInsnsWithoutSideEffectsBeforeUse(
324     MachineIRBuilder &Builder, MachineInstr &DefMI, MachineOperand &UseMO,
325     std::function<void(MachineBasicBlock *, MachineBasicBlock::iterator,
326                        MachineOperand &UseMO)>
327         Inserter) {
328   MachineInstr &UseMI = *UseMO.getParent();
329 
330   MachineBasicBlock *InsertBB = UseMI.getParent();
331 
332   // If the use is a PHI then we want the predecessor block instead.
333   if (UseMI.isPHI()) {
334     MachineOperand *PredBB = std::next(&UseMO);
335     InsertBB = PredBB->getMBB();
336   }
337 
338   // If the block is the same block as the def then we want to insert just after
339   // the def instead of at the start of the block.
340   if (InsertBB == DefMI.getParent()) {
341     MachineBasicBlock::iterator InsertPt = &DefMI;
342     Inserter(InsertBB, std::next(InsertPt), UseMO);
343     return;
344   }
345 
346   // Otherwise we want the start of the BB
347   Inserter(InsertBB, InsertBB->getFirstNonPHI(), UseMO);
348 }
349 } // end anonymous namespace
350 
351 bool CombinerHelper::tryCombineExtendingLoads(MachineInstr &MI) {
352   PreferredTuple Preferred;
353   if (matchCombineExtendingLoads(MI, Preferred)) {
354     applyCombineExtendingLoads(MI, Preferred);
355     return true;
356   }
357   return false;
358 }
359 
360 bool CombinerHelper::matchCombineExtendingLoads(MachineInstr &MI,
361                                                 PreferredTuple &Preferred) {
362   // We match the loads and follow the uses to the extend instead of matching
363   // the extends and following the def to the load. This is because the load
364   // must remain in the same position for correctness (unless we also add code
365   // to find a safe place to sink it) whereas the extend is freely movable.
366   // It also prevents us from duplicating the load for the volatile case or just
367   // for performance.
368 
369   if (MI.getOpcode() != TargetOpcode::G_LOAD &&
370       MI.getOpcode() != TargetOpcode::G_SEXTLOAD &&
371       MI.getOpcode() != TargetOpcode::G_ZEXTLOAD)
372     return false;
373 
374   auto &LoadValue = MI.getOperand(0);
375   assert(LoadValue.isReg() && "Result wasn't a register?");
376 
377   LLT LoadValueTy = MRI.getType(LoadValue.getReg());
378   if (!LoadValueTy.isScalar())
379     return false;
380 
381   // Most architectures are going to legalize <s8 loads into at least a 1 byte
382   // load, and the MMOs can only describe memory accesses in multiples of bytes.
383   // If we try to perform extload combining on those, we can end up with
384   // %a(s8) = extload %ptr (load 1 byte from %ptr)
385   // ... which is an illegal extload instruction.
386   if (LoadValueTy.getSizeInBits() < 8)
387     return false;
388 
389   // For non power-of-2 types, they will very likely be legalized into multiple
390   // loads. Don't bother trying to match them into extending loads.
391   if (!isPowerOf2_32(LoadValueTy.getSizeInBits()))
392     return false;
393 
394   // Find the preferred type aside from the any-extends (unless it's the only
395   // one) and non-extending ops. We'll emit an extending load to that type and
396   // and emit a variant of (extend (trunc X)) for the others according to the
397   // relative type sizes. At the same time, pick an extend to use based on the
398   // extend involved in the chosen type.
399   unsigned PreferredOpcode = MI.getOpcode() == TargetOpcode::G_LOAD
400                                  ? TargetOpcode::G_ANYEXT
401                                  : MI.getOpcode() == TargetOpcode::G_SEXTLOAD
402                                        ? TargetOpcode::G_SEXT
403                                        : TargetOpcode::G_ZEXT;
404   Preferred = {LLT(), PreferredOpcode, nullptr};
405   for (auto &UseMI : MRI.use_instructions(LoadValue.getReg())) {
406     if (UseMI.getOpcode() == TargetOpcode::G_SEXT ||
407         UseMI.getOpcode() == TargetOpcode::G_ZEXT ||
408         UseMI.getOpcode() == TargetOpcode::G_ANYEXT) {
409       Preferred = ChoosePreferredUse(Preferred,
410                                      MRI.getType(UseMI.getOperand(0).getReg()),
411                                      UseMI.getOpcode(), &UseMI);
412     }
413   }
414 
415   // There were no extends
416   if (!Preferred.MI)
417     return false;
418   // It should be impossible to chose an extend without selecting a different
419   // type since by definition the result of an extend is larger.
420   assert(Preferred.Ty != LoadValueTy && "Extending to same type?");
421 
422   LLVM_DEBUG(dbgs() << "Preferred use is: " << *Preferred.MI);
423   return true;
424 }
425 
426 void CombinerHelper::applyCombineExtendingLoads(MachineInstr &MI,
427                                                 PreferredTuple &Preferred) {
428   // Rewrite the load to the chosen extending load.
429   Register ChosenDstReg = Preferred.MI->getOperand(0).getReg();
430 
431   // Inserter to insert a truncate back to the original type at a given point
432   // with some basic CSE to limit truncate duplication to one per BB.
433   DenseMap<MachineBasicBlock *, MachineInstr *> EmittedInsns;
434   auto InsertTruncAt = [&](MachineBasicBlock *InsertIntoBB,
435                            MachineBasicBlock::iterator InsertBefore,
436                            MachineOperand &UseMO) {
437     MachineInstr *PreviouslyEmitted = EmittedInsns.lookup(InsertIntoBB);
438     if (PreviouslyEmitted) {
439       Observer.changingInstr(*UseMO.getParent());
440       UseMO.setReg(PreviouslyEmitted->getOperand(0).getReg());
441       Observer.changedInstr(*UseMO.getParent());
442       return;
443     }
444 
445     Builder.setInsertPt(*InsertIntoBB, InsertBefore);
446     Register NewDstReg = MRI.cloneVirtualRegister(MI.getOperand(0).getReg());
447     MachineInstr *NewMI = Builder.buildTrunc(NewDstReg, ChosenDstReg);
448     EmittedInsns[InsertIntoBB] = NewMI;
449     replaceRegOpWith(MRI, UseMO, NewDstReg);
450   };
451 
452   Observer.changingInstr(MI);
453   MI.setDesc(
454       Builder.getTII().get(Preferred.ExtendOpcode == TargetOpcode::G_SEXT
455                                ? TargetOpcode::G_SEXTLOAD
456                                : Preferred.ExtendOpcode == TargetOpcode::G_ZEXT
457                                      ? TargetOpcode::G_ZEXTLOAD
458                                      : TargetOpcode::G_LOAD));
459 
460   // Rewrite all the uses to fix up the types.
461   auto &LoadValue = MI.getOperand(0);
462   SmallVector<MachineOperand *, 4> Uses;
463   for (auto &UseMO : MRI.use_operands(LoadValue.getReg()))
464     Uses.push_back(&UseMO);
465 
466   for (auto *UseMO : Uses) {
467     MachineInstr *UseMI = UseMO->getParent();
468 
469     // If the extend is compatible with the preferred extend then we should fix
470     // up the type and extend so that it uses the preferred use.
471     if (UseMI->getOpcode() == Preferred.ExtendOpcode ||
472         UseMI->getOpcode() == TargetOpcode::G_ANYEXT) {
473       Register UseDstReg = UseMI->getOperand(0).getReg();
474       MachineOperand &UseSrcMO = UseMI->getOperand(1);
475       const LLT UseDstTy = MRI.getType(UseDstReg);
476       if (UseDstReg != ChosenDstReg) {
477         if (Preferred.Ty == UseDstTy) {
478           // If the use has the same type as the preferred use, then merge
479           // the vregs and erase the extend. For example:
480           //    %1:_(s8) = G_LOAD ...
481           //    %2:_(s32) = G_SEXT %1(s8)
482           //    %3:_(s32) = G_ANYEXT %1(s8)
483           //    ... = ... %3(s32)
484           // rewrites to:
485           //    %2:_(s32) = G_SEXTLOAD ...
486           //    ... = ... %2(s32)
487           replaceRegWith(MRI, UseDstReg, ChosenDstReg);
488           Observer.erasingInstr(*UseMO->getParent());
489           UseMO->getParent()->eraseFromParent();
490         } else if (Preferred.Ty.getSizeInBits() < UseDstTy.getSizeInBits()) {
491           // If the preferred size is smaller, then keep the extend but extend
492           // from the result of the extending load. For example:
493           //    %1:_(s8) = G_LOAD ...
494           //    %2:_(s32) = G_SEXT %1(s8)
495           //    %3:_(s64) = G_ANYEXT %1(s8)
496           //    ... = ... %3(s64)
497           /// rewrites to:
498           //    %2:_(s32) = G_SEXTLOAD ...
499           //    %3:_(s64) = G_ANYEXT %2:_(s32)
500           //    ... = ... %3(s64)
501           replaceRegOpWith(MRI, UseSrcMO, ChosenDstReg);
502         } else {
503           // If the preferred size is large, then insert a truncate. For
504           // example:
505           //    %1:_(s8) = G_LOAD ...
506           //    %2:_(s64) = G_SEXT %1(s8)
507           //    %3:_(s32) = G_ZEXT %1(s8)
508           //    ... = ... %3(s32)
509           /// rewrites to:
510           //    %2:_(s64) = G_SEXTLOAD ...
511           //    %4:_(s8) = G_TRUNC %2:_(s32)
512           //    %3:_(s64) = G_ZEXT %2:_(s8)
513           //    ... = ... %3(s64)
514           InsertInsnsWithoutSideEffectsBeforeUse(Builder, MI, *UseMO,
515                                                  InsertTruncAt);
516         }
517         continue;
518       }
519       // The use is (one of) the uses of the preferred use we chose earlier.
520       // We're going to update the load to def this value later so just erase
521       // the old extend.
522       Observer.erasingInstr(*UseMO->getParent());
523       UseMO->getParent()->eraseFromParent();
524       continue;
525     }
526 
527     // The use isn't an extend. Truncate back to the type we originally loaded.
528     // This is free on many targets.
529     InsertInsnsWithoutSideEffectsBeforeUse(Builder, MI, *UseMO, InsertTruncAt);
530   }
531 
532   MI.getOperand(0).setReg(ChosenDstReg);
533   Observer.changedInstr(MI);
534 }
535 
536 bool CombinerHelper::isPredecessor(MachineInstr &DefMI, MachineInstr &UseMI) {
537   assert(DefMI.getParent() == UseMI.getParent());
538   if (&DefMI == &UseMI)
539     return false;
540 
541   // Loop through the basic block until we find one of the instructions.
542   MachineBasicBlock::const_iterator I = DefMI.getParent()->begin();
543   for (; &*I != &DefMI && &*I != &UseMI; ++I)
544     return &*I == &DefMI;
545 
546   llvm_unreachable("Block must contain instructions");
547 }
548 
549 bool CombinerHelper::dominates(MachineInstr &DefMI, MachineInstr &UseMI) {
550   if (MDT)
551     return MDT->dominates(&DefMI, &UseMI);
552   else if (DefMI.getParent() != UseMI.getParent())
553     return false;
554 
555   return isPredecessor(DefMI, UseMI);
556 }
557 
558 bool CombinerHelper::findPostIndexCandidate(MachineInstr &MI, Register &Addr,
559                                             Register &Base, Register &Offset) {
560   auto &MF = *MI.getParent()->getParent();
561   const auto &TLI = *MF.getSubtarget().getTargetLowering();
562 
563 #ifndef NDEBUG
564   unsigned Opcode = MI.getOpcode();
565   assert(Opcode == TargetOpcode::G_LOAD || Opcode == TargetOpcode::G_SEXTLOAD ||
566          Opcode == TargetOpcode::G_ZEXTLOAD || Opcode == TargetOpcode::G_STORE);
567 #endif
568 
569   Base = MI.getOperand(1).getReg();
570   MachineInstr *BaseDef = MRI.getUniqueVRegDef(Base);
571   if (BaseDef && BaseDef->getOpcode() == TargetOpcode::G_FRAME_INDEX)
572     return false;
573 
574   LLVM_DEBUG(dbgs() << "Searching for post-indexing opportunity for: " << MI);
575 
576   for (auto &Use : MRI.use_instructions(Base)) {
577     if (Use.getOpcode() != TargetOpcode::G_PTR_ADD)
578       continue;
579 
580     Offset = Use.getOperand(2).getReg();
581     if (!ForceLegalIndexing &&
582         !TLI.isIndexingLegal(MI, Base, Offset, /*IsPre*/ false, MRI)) {
583       LLVM_DEBUG(dbgs() << "    Ignoring candidate with illegal addrmode: "
584                         << Use);
585       continue;
586     }
587 
588     // Make sure the offset calculation is before the potentially indexed op.
589     // FIXME: we really care about dependency here. The offset calculation might
590     // be movable.
591     MachineInstr *OffsetDef = MRI.getUniqueVRegDef(Offset);
592     if (!OffsetDef || !dominates(*OffsetDef, MI)) {
593       LLVM_DEBUG(dbgs() << "    Ignoring candidate with offset after mem-op: "
594                         << Use);
595       continue;
596     }
597 
598     // FIXME: check whether all uses of Base are load/store with foldable
599     // addressing modes. If so, using the normal addr-modes is better than
600     // forming an indexed one.
601 
602     bool MemOpDominatesAddrUses = true;
603     for (auto &PtrAddUse : MRI.use_instructions(Use.getOperand(0).getReg())) {
604       if (!dominates(MI, PtrAddUse)) {
605         MemOpDominatesAddrUses = false;
606         break;
607       }
608     }
609 
610     if (!MemOpDominatesAddrUses) {
611       LLVM_DEBUG(
612           dbgs() << "    Ignoring candidate as memop does not dominate uses: "
613                  << Use);
614       continue;
615     }
616 
617     LLVM_DEBUG(dbgs() << "    Found match: " << Use);
618     Addr = Use.getOperand(0).getReg();
619     return true;
620   }
621 
622   return false;
623 }
624 
625 bool CombinerHelper::findPreIndexCandidate(MachineInstr &MI, Register &Addr,
626                                            Register &Base, Register &Offset) {
627   auto &MF = *MI.getParent()->getParent();
628   const auto &TLI = *MF.getSubtarget().getTargetLowering();
629 
630 #ifndef NDEBUG
631   unsigned Opcode = MI.getOpcode();
632   assert(Opcode == TargetOpcode::G_LOAD || Opcode == TargetOpcode::G_SEXTLOAD ||
633          Opcode == TargetOpcode::G_ZEXTLOAD || Opcode == TargetOpcode::G_STORE);
634 #endif
635 
636   Addr = MI.getOperand(1).getReg();
637   MachineInstr *AddrDef = getOpcodeDef(TargetOpcode::G_PTR_ADD, Addr, MRI);
638   if (!AddrDef || MRI.hasOneUse(Addr))
639     return false;
640 
641   Base = AddrDef->getOperand(1).getReg();
642   Offset = AddrDef->getOperand(2).getReg();
643 
644   LLVM_DEBUG(dbgs() << "Found potential pre-indexed load_store: " << MI);
645 
646   if (!ForceLegalIndexing &&
647       !TLI.isIndexingLegal(MI, Base, Offset, /*IsPre*/ true, MRI)) {
648     LLVM_DEBUG(dbgs() << "    Skipping, not legal for target");
649     return false;
650   }
651 
652   MachineInstr *BaseDef = getDefIgnoringCopies(Base, MRI);
653   if (BaseDef->getOpcode() == TargetOpcode::G_FRAME_INDEX) {
654     LLVM_DEBUG(dbgs() << "    Skipping, frame index would need copy anyway.");
655     return false;
656   }
657 
658   if (MI.getOpcode() == TargetOpcode::G_STORE) {
659     // Would require a copy.
660     if (Base == MI.getOperand(0).getReg()) {
661       LLVM_DEBUG(dbgs() << "    Skipping, storing base so need copy anyway.");
662       return false;
663     }
664 
665     // We're expecting one use of Addr in MI, but it could also be the
666     // value stored, which isn't actually dominated by the instruction.
667     if (MI.getOperand(0).getReg() == Addr) {
668       LLVM_DEBUG(dbgs() << "    Skipping, does not dominate all addr uses");
669       return false;
670     }
671   }
672 
673   // FIXME: check whether all uses of the base pointer are constant PtrAdds.
674   // That might allow us to end base's liveness here by adjusting the constant.
675 
676   for (auto &UseMI : MRI.use_instructions(Addr)) {
677     if (!dominates(MI, UseMI)) {
678       LLVM_DEBUG(dbgs() << "    Skipping, does not dominate all addr uses.");
679       return false;
680     }
681   }
682 
683   return true;
684 }
685 
686 bool CombinerHelper::tryCombineIndexedLoadStore(MachineInstr &MI) {
687   IndexedLoadStoreMatchInfo MatchInfo;
688   if (matchCombineIndexedLoadStore(MI, MatchInfo)) {
689     applyCombineIndexedLoadStore(MI, MatchInfo);
690     return true;
691   }
692   return false;
693 }
694 
695 bool CombinerHelper::matchCombineIndexedLoadStore(MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) {
696   unsigned Opcode = MI.getOpcode();
697   if (Opcode != TargetOpcode::G_LOAD && Opcode != TargetOpcode::G_SEXTLOAD &&
698       Opcode != TargetOpcode::G_ZEXTLOAD && Opcode != TargetOpcode::G_STORE)
699     return false;
700 
701   MatchInfo.IsPre = findPreIndexCandidate(MI, MatchInfo.Addr, MatchInfo.Base,
702                                           MatchInfo.Offset);
703   if (!MatchInfo.IsPre &&
704       !findPostIndexCandidate(MI, MatchInfo.Addr, MatchInfo.Base,
705                               MatchInfo.Offset))
706     return false;
707 
708   return true;
709 }
710 
711 void CombinerHelper::applyCombineIndexedLoadStore(
712     MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) {
713   MachineInstr &AddrDef = *MRI.getUniqueVRegDef(MatchInfo.Addr);
714   MachineIRBuilder MIRBuilder(MI);
715   unsigned Opcode = MI.getOpcode();
716   bool IsStore = Opcode == TargetOpcode::G_STORE;
717   unsigned NewOpcode;
718   switch (Opcode) {
719   case TargetOpcode::G_LOAD:
720     NewOpcode = TargetOpcode::G_INDEXED_LOAD;
721     break;
722   case TargetOpcode::G_SEXTLOAD:
723     NewOpcode = TargetOpcode::G_INDEXED_SEXTLOAD;
724     break;
725   case TargetOpcode::G_ZEXTLOAD:
726     NewOpcode = TargetOpcode::G_INDEXED_ZEXTLOAD;
727     break;
728   case TargetOpcode::G_STORE:
729     NewOpcode = TargetOpcode::G_INDEXED_STORE;
730     break;
731   default:
732     llvm_unreachable("Unknown load/store opcode");
733   }
734 
735   auto MIB = MIRBuilder.buildInstr(NewOpcode);
736   if (IsStore) {
737     MIB.addDef(MatchInfo.Addr);
738     MIB.addUse(MI.getOperand(0).getReg());
739   } else {
740     MIB.addDef(MI.getOperand(0).getReg());
741     MIB.addDef(MatchInfo.Addr);
742   }
743 
744   MIB.addUse(MatchInfo.Base);
745   MIB.addUse(MatchInfo.Offset);
746   MIB.addImm(MatchInfo.IsPre);
747   MI.eraseFromParent();
748   AddrDef.eraseFromParent();
749 
750   LLVM_DEBUG(dbgs() << "    Combinined to indexed operation");
751 }
752 
753 bool CombinerHelper::matchElideBrByInvertingCond(MachineInstr &MI) {
754   if (MI.getOpcode() != TargetOpcode::G_BR)
755     return false;
756 
757   // Try to match the following:
758   // bb1:
759   //   %c(s32) = G_ICMP pred, %a, %b
760   //   %c1(s1) = G_TRUNC %c(s32)
761   //   G_BRCOND %c1, %bb2
762   //   G_BR %bb3
763   // bb2:
764   // ...
765   // bb3:
766 
767   // The above pattern does not have a fall through to the successor bb2, always
768   // resulting in a branch no matter which path is taken. Here we try to find
769   // and replace that pattern with conditional branch to bb3 and otherwise
770   // fallthrough to bb2.
771 
772   MachineBasicBlock *MBB = MI.getParent();
773   MachineBasicBlock::iterator BrIt(MI);
774   if (BrIt == MBB->begin())
775     return false;
776   assert(std::next(BrIt) == MBB->end() && "expected G_BR to be a terminator");
777 
778   MachineInstr *BrCond = &*std::prev(BrIt);
779   if (BrCond->getOpcode() != TargetOpcode::G_BRCOND)
780     return false;
781 
782   // Check that the next block is the conditional branch target.
783   if (!MBB->isLayoutSuccessor(BrCond->getOperand(1).getMBB()))
784     return false;
785 
786   MachineInstr *CmpMI = MRI.getVRegDef(BrCond->getOperand(0).getReg());
787   if (!CmpMI || CmpMI->getOpcode() != TargetOpcode::G_ICMP ||
788       !MRI.hasOneUse(CmpMI->getOperand(0).getReg()))
789     return false;
790   return true;
791 }
792 
793 bool CombinerHelper::tryElideBrByInvertingCond(MachineInstr &MI) {
794   if (!matchElideBrByInvertingCond(MI))
795     return false;
796   applyElideBrByInvertingCond(MI);
797   return true;
798 }
799 
800 void CombinerHelper::applyElideBrByInvertingCond(MachineInstr &MI) {
801   MachineBasicBlock *BrTarget = MI.getOperand(0).getMBB();
802   MachineBasicBlock::iterator BrIt(MI);
803   MachineInstr *BrCond = &*std::prev(BrIt);
804   MachineInstr *CmpMI = MRI.getVRegDef(BrCond->getOperand(0).getReg());
805 
806   CmpInst::Predicate InversePred = CmpInst::getInversePredicate(
807       (CmpInst::Predicate)CmpMI->getOperand(1).getPredicate());
808 
809   // Invert the G_ICMP condition.
810   Observer.changingInstr(*CmpMI);
811   CmpMI->getOperand(1).setPredicate(InversePred);
812   Observer.changedInstr(*CmpMI);
813 
814   // Change the conditional branch target.
815   Observer.changingInstr(*BrCond);
816   BrCond->getOperand(1).setMBB(BrTarget);
817   Observer.changedInstr(*BrCond);
818   MI.eraseFromParent();
819 }
820 
821 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) {
822   // On Darwin, -Os means optimize for size without hurting performance, so
823   // only really optimize for size when -Oz (MinSize) is used.
824   if (MF.getTarget().getTargetTriple().isOSDarwin())
825     return MF.getFunction().hasMinSize();
826   return MF.getFunction().hasOptSize();
827 }
828 
829 // Returns a list of types to use for memory op lowering in MemOps. A partial
830 // port of findOptimalMemOpLowering in TargetLowering.
831 static bool findGISelOptimalMemOpLowering(std::vector<LLT> &MemOps,
832                                           unsigned Limit, const MemOp &Op,
833                                           unsigned DstAS, unsigned SrcAS,
834                                           const AttributeList &FuncAttributes,
835                                           const TargetLowering &TLI) {
836   if (Op.isMemcpyWithFixedDstAlign() && Op.getSrcAlign() < Op.getDstAlign())
837     return false;
838 
839   LLT Ty = TLI.getOptimalMemOpLLT(Op, FuncAttributes);
840 
841   if (Ty == LLT()) {
842     // Use the largest scalar type whose alignment constraints are satisfied.
843     // We only need to check DstAlign here as SrcAlign is always greater or
844     // equal to DstAlign (or zero).
845     Ty = LLT::scalar(64);
846     if (Op.isFixedDstAlign())
847       while (Op.getDstAlign() < Ty.getSizeInBytes() &&
848              !TLI.allowsMisalignedMemoryAccesses(Ty, DstAS,
849                                                  Op.getDstAlign().value()))
850         Ty = LLT::scalar(Ty.getSizeInBytes());
851     assert(Ty.getSizeInBits() > 0 && "Could not find valid type");
852     // FIXME: check for the largest legal type we can load/store to.
853   }
854 
855   unsigned NumMemOps = 0;
856   uint64_t Size = Op.size();
857   while (Size) {
858     unsigned TySize = Ty.getSizeInBytes();
859     while (TySize > Size) {
860       // For now, only use non-vector load / store's for the left-over pieces.
861       LLT NewTy = Ty;
862       // FIXME: check for mem op safety and legality of the types. Not all of
863       // SDAGisms map cleanly to GISel concepts.
864       if (NewTy.isVector())
865         NewTy = NewTy.getSizeInBits() > 64 ? LLT::scalar(64) : LLT::scalar(32);
866       NewTy = LLT::scalar(PowerOf2Floor(NewTy.getSizeInBits() - 1));
867       unsigned NewTySize = NewTy.getSizeInBytes();
868       assert(NewTySize > 0 && "Could not find appropriate type");
869 
870       // If the new LLT cannot cover all of the remaining bits, then consider
871       // issuing a (or a pair of) unaligned and overlapping load / store.
872       bool Fast;
873       // Need to get a VT equivalent for allowMisalignedMemoryAccesses().
874       MVT VT = getMVTForLLT(Ty);
875       if (NumMemOps && Op.allowOverlap() && NewTySize < Size &&
876           TLI.allowsMisalignedMemoryAccesses(
877               VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign().value() : 0,
878               MachineMemOperand::MONone, &Fast) &&
879           Fast)
880         TySize = Size;
881       else {
882         Ty = NewTy;
883         TySize = NewTySize;
884       }
885     }
886 
887     if (++NumMemOps > Limit)
888       return false;
889 
890     MemOps.push_back(Ty);
891     Size -= TySize;
892   }
893 
894   return true;
895 }
896 
897 static Type *getTypeForLLT(LLT Ty, LLVMContext &C) {
898   if (Ty.isVector())
899     return VectorType::get(IntegerType::get(C, Ty.getScalarSizeInBits()),
900                            Ty.getNumElements());
901   return IntegerType::get(C, Ty.getSizeInBits());
902 }
903 
904 // Get a vectorized representation of the memset value operand, GISel edition.
905 static Register getMemsetValue(Register Val, LLT Ty, MachineIRBuilder &MIB) {
906   MachineRegisterInfo &MRI = *MIB.getMRI();
907   unsigned NumBits = Ty.getScalarSizeInBits();
908   auto ValVRegAndVal = getConstantVRegValWithLookThrough(Val, MRI);
909   if (!Ty.isVector() && ValVRegAndVal) {
910     unsigned KnownVal = ValVRegAndVal->Value;
911     APInt Scalar = APInt(8, KnownVal);
912     APInt SplatVal = APInt::getSplat(NumBits, Scalar);
913     return MIB.buildConstant(Ty, SplatVal).getReg(0);
914   }
915   // FIXME: for vector types create a G_BUILD_VECTOR.
916   if (Ty.isVector())
917     return Register();
918 
919   // Extend the byte value to the larger type, and then multiply by a magic
920   // value 0x010101... in order to replicate it across every byte.
921   LLT ExtType = Ty.getScalarType();
922   auto ZExt = MIB.buildZExtOrTrunc(ExtType, Val);
923   if (NumBits > 8) {
924     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
925     auto MagicMI = MIB.buildConstant(ExtType, Magic);
926     Val = MIB.buildMul(ExtType, ZExt, MagicMI).getReg(0);
927   }
928 
929   assert(ExtType == Ty && "Vector memset value type not supported yet");
930   return Val;
931 }
932 
933 bool CombinerHelper::optimizeMemset(MachineInstr &MI, Register Dst,
934                                     Register Val, unsigned KnownLen,
935                                     Align Alignment, bool IsVolatile) {
936   auto &MF = *MI.getParent()->getParent();
937   const auto &TLI = *MF.getSubtarget().getTargetLowering();
938   auto &DL = MF.getDataLayout();
939   LLVMContext &C = MF.getFunction().getContext();
940 
941   assert(KnownLen != 0 && "Have a zero length memset length!");
942 
943   bool DstAlignCanChange = false;
944   MachineFrameInfo &MFI = MF.getFrameInfo();
945   bool OptSize = shouldLowerMemFuncForSize(MF);
946 
947   MachineInstr *FIDef = getOpcodeDef(TargetOpcode::G_FRAME_INDEX, Dst, MRI);
948   if (FIDef && !MFI.isFixedObjectIndex(FIDef->getOperand(1).getIndex()))
949     DstAlignCanChange = true;
950 
951   unsigned Limit = TLI.getMaxStoresPerMemset(OptSize);
952   std::vector<LLT> MemOps;
953 
954   const auto &DstMMO = **MI.memoperands_begin();
955   MachinePointerInfo DstPtrInfo = DstMMO.getPointerInfo();
956 
957   auto ValVRegAndVal = getConstantVRegValWithLookThrough(Val, MRI);
958   bool IsZeroVal = ValVRegAndVal && ValVRegAndVal->Value == 0;
959 
960   if (!findGISelOptimalMemOpLowering(MemOps, Limit,
961                                      MemOp::Set(KnownLen, DstAlignCanChange,
962                                                 Alignment,
963                                                 /*IsZeroMemset=*/IsZeroVal,
964                                                 /*IsVolatile=*/IsVolatile),
965                                      DstPtrInfo.getAddrSpace(), ~0u,
966                                      MF.getFunction().getAttributes(), TLI))
967     return false;
968 
969   if (DstAlignCanChange) {
970     // Get an estimate of the type from the LLT.
971     Type *IRTy = getTypeForLLT(MemOps[0], C);
972     Align NewAlign = DL.getABITypeAlign(IRTy);
973     if (NewAlign > Alignment) {
974       Alignment = NewAlign;
975       unsigned FI = FIDef->getOperand(1).getIndex();
976       // Give the stack frame object a larger alignment if needed.
977       if (MFI.getObjectAlign(FI) < Alignment)
978         MFI.setObjectAlignment(FI, Alignment);
979     }
980   }
981 
982   MachineIRBuilder MIB(MI);
983   // Find the largest store and generate the bit pattern for it.
984   LLT LargestTy = MemOps[0];
985   for (unsigned i = 1; i < MemOps.size(); i++)
986     if (MemOps[i].getSizeInBits() > LargestTy.getSizeInBits())
987       LargestTy = MemOps[i];
988 
989   // The memset stored value is always defined as an s8, so in order to make it
990   // work with larger store types we need to repeat the bit pattern across the
991   // wider type.
992   Register MemSetValue = getMemsetValue(Val, LargestTy, MIB);
993 
994   if (!MemSetValue)
995     return false;
996 
997   // Generate the stores. For each store type in the list, we generate the
998   // matching store of that type to the destination address.
999   LLT PtrTy = MRI.getType(Dst);
1000   unsigned DstOff = 0;
1001   unsigned Size = KnownLen;
1002   for (unsigned I = 0; I < MemOps.size(); I++) {
1003     LLT Ty = MemOps[I];
1004     unsigned TySize = Ty.getSizeInBytes();
1005     if (TySize > Size) {
1006       // Issuing an unaligned load / store pair that overlaps with the previous
1007       // pair. Adjust the offset accordingly.
1008       assert(I == MemOps.size() - 1 && I != 0);
1009       DstOff -= TySize - Size;
1010     }
1011 
1012     // If this store is smaller than the largest store see whether we can get
1013     // the smaller value for free with a truncate.
1014     Register Value = MemSetValue;
1015     if (Ty.getSizeInBits() < LargestTy.getSizeInBits()) {
1016       MVT VT = getMVTForLLT(Ty);
1017       MVT LargestVT = getMVTForLLT(LargestTy);
1018       if (!LargestTy.isVector() && !Ty.isVector() &&
1019           TLI.isTruncateFree(LargestVT, VT))
1020         Value = MIB.buildTrunc(Ty, MemSetValue).getReg(0);
1021       else
1022         Value = getMemsetValue(Val, Ty, MIB);
1023       if (!Value)
1024         return false;
1025     }
1026 
1027     auto *StoreMMO =
1028         MF.getMachineMemOperand(&DstMMO, DstOff, Ty.getSizeInBytes());
1029 
1030     Register Ptr = Dst;
1031     if (DstOff != 0) {
1032       auto Offset =
1033           MIB.buildConstant(LLT::scalar(PtrTy.getSizeInBits()), DstOff);
1034       Ptr = MIB.buildPtrAdd(PtrTy, Dst, Offset).getReg(0);
1035     }
1036 
1037     MIB.buildStore(Value, Ptr, *StoreMMO);
1038     DstOff += Ty.getSizeInBytes();
1039     Size -= TySize;
1040   }
1041 
1042   MI.eraseFromParent();
1043   return true;
1044 }
1045 
1046 bool CombinerHelper::optimizeMemcpy(MachineInstr &MI, Register Dst,
1047                                     Register Src, unsigned KnownLen,
1048                                     Align DstAlign, Align SrcAlign,
1049                                     bool IsVolatile) {
1050   auto &MF = *MI.getParent()->getParent();
1051   const auto &TLI = *MF.getSubtarget().getTargetLowering();
1052   auto &DL = MF.getDataLayout();
1053   LLVMContext &C = MF.getFunction().getContext();
1054 
1055   assert(KnownLen != 0 && "Have a zero length memcpy length!");
1056 
1057   bool DstAlignCanChange = false;
1058   MachineFrameInfo &MFI = MF.getFrameInfo();
1059   bool OptSize = shouldLowerMemFuncForSize(MF);
1060   Align Alignment = commonAlignment(DstAlign, SrcAlign);
1061 
1062   MachineInstr *FIDef = getOpcodeDef(TargetOpcode::G_FRAME_INDEX, Dst, MRI);
1063   if (FIDef && !MFI.isFixedObjectIndex(FIDef->getOperand(1).getIndex()))
1064     DstAlignCanChange = true;
1065 
1066   // FIXME: infer better src pointer alignment like SelectionDAG does here.
1067   // FIXME: also use the equivalent of isMemSrcFromConstant and alwaysinlining
1068   // if the memcpy is in a tail call position.
1069 
1070   unsigned Limit = TLI.getMaxStoresPerMemcpy(OptSize);
1071   std::vector<LLT> MemOps;
1072 
1073   const auto &DstMMO = **MI.memoperands_begin();
1074   const auto &SrcMMO = **std::next(MI.memoperands_begin());
1075   MachinePointerInfo DstPtrInfo = DstMMO.getPointerInfo();
1076   MachinePointerInfo SrcPtrInfo = SrcMMO.getPointerInfo();
1077 
1078   if (!findGISelOptimalMemOpLowering(
1079           MemOps, Limit,
1080           MemOp::Copy(KnownLen, DstAlignCanChange, Alignment, SrcAlign,
1081                       IsVolatile),
1082           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
1083           MF.getFunction().getAttributes(), TLI))
1084     return false;
1085 
1086   if (DstAlignCanChange) {
1087     // Get an estimate of the type from the LLT.
1088     Type *IRTy = getTypeForLLT(MemOps[0], C);
1089     Align NewAlign = DL.getABITypeAlign(IRTy);
1090 
1091     // Don't promote to an alignment that would require dynamic stack
1092     // realignment.
1093     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1094     if (!TRI->needsStackRealignment(MF))
1095       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
1096         NewAlign = NewAlign / 2;
1097 
1098     if (NewAlign > Alignment) {
1099       Alignment = NewAlign;
1100       unsigned FI = FIDef->getOperand(1).getIndex();
1101       // Give the stack frame object a larger alignment if needed.
1102       if (MFI.getObjectAlign(FI) < Alignment)
1103         MFI.setObjectAlignment(FI, Alignment);
1104     }
1105   }
1106 
1107   LLVM_DEBUG(dbgs() << "Inlining memcpy: " << MI << " into loads & stores\n");
1108 
1109   MachineIRBuilder MIB(MI);
1110   // Now we need to emit a pair of load and stores for each of the types we've
1111   // collected. I.e. for each type, generate a load from the source pointer of
1112   // that type width, and then generate a corresponding store to the dest buffer
1113   // of that value loaded. This can result in a sequence of loads and stores
1114   // mixed types, depending on what the target specifies as good types to use.
1115   unsigned CurrOffset = 0;
1116   LLT PtrTy = MRI.getType(Src);
1117   unsigned Size = KnownLen;
1118   for (auto CopyTy : MemOps) {
1119     // Issuing an unaligned load / store pair  that overlaps with the previous
1120     // pair. Adjust the offset accordingly.
1121     if (CopyTy.getSizeInBytes() > Size)
1122       CurrOffset -= CopyTy.getSizeInBytes() - Size;
1123 
1124     // Construct MMOs for the accesses.
1125     auto *LoadMMO =
1126         MF.getMachineMemOperand(&SrcMMO, CurrOffset, CopyTy.getSizeInBytes());
1127     auto *StoreMMO =
1128         MF.getMachineMemOperand(&DstMMO, CurrOffset, CopyTy.getSizeInBytes());
1129 
1130     // Create the load.
1131     Register LoadPtr = Src;
1132     Register Offset;
1133     if (CurrOffset != 0) {
1134       Offset = MIB.buildConstant(LLT::scalar(PtrTy.getSizeInBits()), CurrOffset)
1135                    .getReg(0);
1136       LoadPtr = MIB.buildPtrAdd(PtrTy, Src, Offset).getReg(0);
1137     }
1138     auto LdVal = MIB.buildLoad(CopyTy, LoadPtr, *LoadMMO);
1139 
1140     // Create the store.
1141     Register StorePtr =
1142         CurrOffset == 0 ? Dst : MIB.buildPtrAdd(PtrTy, Dst, Offset).getReg(0);
1143     MIB.buildStore(LdVal, StorePtr, *StoreMMO);
1144     CurrOffset += CopyTy.getSizeInBytes();
1145     Size -= CopyTy.getSizeInBytes();
1146   }
1147 
1148   MI.eraseFromParent();
1149   return true;
1150 }
1151 
1152 bool CombinerHelper::optimizeMemmove(MachineInstr &MI, Register Dst,
1153                                      Register Src, unsigned KnownLen,
1154                                      Align DstAlign, Align SrcAlign,
1155                                      bool IsVolatile) {
1156   auto &MF = *MI.getParent()->getParent();
1157   const auto &TLI = *MF.getSubtarget().getTargetLowering();
1158   auto &DL = MF.getDataLayout();
1159   LLVMContext &C = MF.getFunction().getContext();
1160 
1161   assert(KnownLen != 0 && "Have a zero length memmove length!");
1162 
1163   bool DstAlignCanChange = false;
1164   MachineFrameInfo &MFI = MF.getFrameInfo();
1165   bool OptSize = shouldLowerMemFuncForSize(MF);
1166   Align Alignment = commonAlignment(DstAlign, SrcAlign);
1167 
1168   MachineInstr *FIDef = getOpcodeDef(TargetOpcode::G_FRAME_INDEX, Dst, MRI);
1169   if (FIDef && !MFI.isFixedObjectIndex(FIDef->getOperand(1).getIndex()))
1170     DstAlignCanChange = true;
1171 
1172   unsigned Limit = TLI.getMaxStoresPerMemmove(OptSize);
1173   std::vector<LLT> MemOps;
1174 
1175   const auto &DstMMO = **MI.memoperands_begin();
1176   const auto &SrcMMO = **std::next(MI.memoperands_begin());
1177   MachinePointerInfo DstPtrInfo = DstMMO.getPointerInfo();
1178   MachinePointerInfo SrcPtrInfo = SrcMMO.getPointerInfo();
1179 
1180   // FIXME: SelectionDAG always passes false for 'AllowOverlap', apparently due
1181   // to a bug in it's findOptimalMemOpLowering implementation. For now do the
1182   // same thing here.
1183   if (!findGISelOptimalMemOpLowering(
1184           MemOps, Limit,
1185           MemOp::Copy(KnownLen, DstAlignCanChange, Alignment, SrcAlign,
1186                       /*IsVolatile*/ true),
1187           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
1188           MF.getFunction().getAttributes(), TLI))
1189     return false;
1190 
1191   if (DstAlignCanChange) {
1192     // Get an estimate of the type from the LLT.
1193     Type *IRTy = getTypeForLLT(MemOps[0], C);
1194     Align NewAlign = DL.getABITypeAlign(IRTy);
1195 
1196     // Don't promote to an alignment that would require dynamic stack
1197     // realignment.
1198     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1199     if (!TRI->needsStackRealignment(MF))
1200       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
1201         NewAlign = NewAlign / 2;
1202 
1203     if (NewAlign > Alignment) {
1204       Alignment = NewAlign;
1205       unsigned FI = FIDef->getOperand(1).getIndex();
1206       // Give the stack frame object a larger alignment if needed.
1207       if (MFI.getObjectAlign(FI) < Alignment)
1208         MFI.setObjectAlignment(FI, Alignment);
1209     }
1210   }
1211 
1212   LLVM_DEBUG(dbgs() << "Inlining memmove: " << MI << " into loads & stores\n");
1213 
1214   MachineIRBuilder MIB(MI);
1215   // Memmove requires that we perform the loads first before issuing the stores.
1216   // Apart from that, this loop is pretty much doing the same thing as the
1217   // memcpy codegen function.
1218   unsigned CurrOffset = 0;
1219   LLT PtrTy = MRI.getType(Src);
1220   SmallVector<Register, 16> LoadVals;
1221   for (auto CopyTy : MemOps) {
1222     // Construct MMO for the load.
1223     auto *LoadMMO =
1224         MF.getMachineMemOperand(&SrcMMO, CurrOffset, CopyTy.getSizeInBytes());
1225 
1226     // Create the load.
1227     Register LoadPtr = Src;
1228     if (CurrOffset != 0) {
1229       auto Offset =
1230           MIB.buildConstant(LLT::scalar(PtrTy.getSizeInBits()), CurrOffset);
1231       LoadPtr = MIB.buildPtrAdd(PtrTy, Src, Offset).getReg(0);
1232     }
1233     LoadVals.push_back(MIB.buildLoad(CopyTy, LoadPtr, *LoadMMO).getReg(0));
1234     CurrOffset += CopyTy.getSizeInBytes();
1235   }
1236 
1237   CurrOffset = 0;
1238   for (unsigned I = 0; I < MemOps.size(); ++I) {
1239     LLT CopyTy = MemOps[I];
1240     // Now store the values loaded.
1241     auto *StoreMMO =
1242         MF.getMachineMemOperand(&DstMMO, CurrOffset, CopyTy.getSizeInBytes());
1243 
1244     Register StorePtr = Dst;
1245     if (CurrOffset != 0) {
1246       auto Offset =
1247           MIB.buildConstant(LLT::scalar(PtrTy.getSizeInBits()), CurrOffset);
1248       StorePtr = MIB.buildPtrAdd(PtrTy, Dst, Offset).getReg(0);
1249     }
1250     MIB.buildStore(LoadVals[I], StorePtr, *StoreMMO);
1251     CurrOffset += CopyTy.getSizeInBytes();
1252   }
1253   MI.eraseFromParent();
1254   return true;
1255 }
1256 
1257 bool CombinerHelper::tryCombineMemCpyFamily(MachineInstr &MI, unsigned MaxLen) {
1258   // This combine is fairly complex so it's not written with a separate
1259   // matcher function.
1260   assert(MI.getOpcode() == TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS);
1261   Intrinsic::ID ID = (Intrinsic::ID)MI.getIntrinsicID();
1262   assert((ID == Intrinsic::memcpy || ID == Intrinsic::memmove ||
1263           ID == Intrinsic::memset) &&
1264          "Expected a memcpy like intrinsic");
1265 
1266   auto MMOIt = MI.memoperands_begin();
1267   const MachineMemOperand *MemOp = *MMOIt;
1268   bool IsVolatile = MemOp->isVolatile();
1269   // Don't try to optimize volatile.
1270   if (IsVolatile)
1271     return false;
1272 
1273   Align DstAlign = MemOp->getBaseAlign();
1274   Align SrcAlign;
1275   Register Dst = MI.getOperand(1).getReg();
1276   Register Src = MI.getOperand(2).getReg();
1277   Register Len = MI.getOperand(3).getReg();
1278 
1279   if (ID != Intrinsic::memset) {
1280     assert(MMOIt != MI.memoperands_end() && "Expected a second MMO on MI");
1281     MemOp = *(++MMOIt);
1282     SrcAlign = MemOp->getBaseAlign();
1283   }
1284 
1285   // See if this is a constant length copy
1286   auto LenVRegAndVal = getConstantVRegValWithLookThrough(Len, MRI);
1287   if (!LenVRegAndVal)
1288     return false; // Leave it to the legalizer to lower it to a libcall.
1289   unsigned KnownLen = LenVRegAndVal->Value;
1290 
1291   if (KnownLen == 0) {
1292     MI.eraseFromParent();
1293     return true;
1294   }
1295 
1296   if (MaxLen && KnownLen > MaxLen)
1297     return false;
1298 
1299   if (ID == Intrinsic::memcpy)
1300     return optimizeMemcpy(MI, Dst, Src, KnownLen, DstAlign, SrcAlign, IsVolatile);
1301   if (ID == Intrinsic::memmove)
1302     return optimizeMemmove(MI, Dst, Src, KnownLen, DstAlign, SrcAlign, IsVolatile);
1303   if (ID == Intrinsic::memset)
1304     return optimizeMemset(MI, Dst, Src, KnownLen, DstAlign, IsVolatile);
1305   return false;
1306 }
1307 
1308 bool CombinerHelper::matchPtrAddImmedChain(MachineInstr &MI,
1309                                            PtrAddChain &MatchInfo) {
1310   // We're trying to match the following pattern:
1311   //   %t1 = G_PTR_ADD %base, G_CONSTANT imm1
1312   //   %root = G_PTR_ADD %t1, G_CONSTANT imm2
1313   // -->
1314   //   %root = G_PTR_ADD %base, G_CONSTANT (imm1 + imm2)
1315 
1316   if (MI.getOpcode() != TargetOpcode::G_PTR_ADD)
1317     return false;
1318 
1319   Register Add2 = MI.getOperand(1).getReg();
1320   Register Imm1 = MI.getOperand(2).getReg();
1321   auto MaybeImmVal = getConstantVRegValWithLookThrough(Imm1, MRI);
1322   if (!MaybeImmVal)
1323     return false;
1324 
1325   MachineInstr *Add2Def = MRI.getUniqueVRegDef(Add2);
1326   if (!Add2Def || Add2Def->getOpcode() != TargetOpcode::G_PTR_ADD)
1327     return false;
1328 
1329   Register Base = Add2Def->getOperand(1).getReg();
1330   Register Imm2 = Add2Def->getOperand(2).getReg();
1331   auto MaybeImm2Val = getConstantVRegValWithLookThrough(Imm2, MRI);
1332   if (!MaybeImm2Val)
1333     return false;
1334 
1335   // Pass the combined immediate to the apply function.
1336   MatchInfo.Imm = MaybeImmVal->Value + MaybeImm2Val->Value;
1337   MatchInfo.Base = Base;
1338   return true;
1339 }
1340 
1341 bool CombinerHelper::applyPtrAddImmedChain(MachineInstr &MI,
1342                                            PtrAddChain &MatchInfo) {
1343   assert(MI.getOpcode() == TargetOpcode::G_PTR_ADD && "Expected G_PTR_ADD");
1344   MachineIRBuilder MIB(MI);
1345   LLT OffsetTy = MRI.getType(MI.getOperand(2).getReg());
1346   auto NewOffset = MIB.buildConstant(OffsetTy, MatchInfo.Imm);
1347   Observer.changingInstr(MI);
1348   MI.getOperand(1).setReg(MatchInfo.Base);
1349   MI.getOperand(2).setReg(NewOffset.getReg(0));
1350   Observer.changedInstr(MI);
1351   return true;
1352 }
1353 
1354 bool CombinerHelper::matchCombineMulToShl(MachineInstr &MI,
1355                                           unsigned &ShiftVal) {
1356   assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL");
1357   auto MaybeImmVal =
1358       getConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
1359   if (!MaybeImmVal || !isPowerOf2_64(MaybeImmVal->Value))
1360     return false;
1361   ShiftVal = Log2_64(MaybeImmVal->Value);
1362   return true;
1363 }
1364 
1365 bool CombinerHelper::applyCombineMulToShl(MachineInstr &MI,
1366                                           unsigned &ShiftVal) {
1367   assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL");
1368   MachineIRBuilder MIB(MI);
1369   LLT ShiftTy = MRI.getType(MI.getOperand(0).getReg());
1370   auto ShiftCst = MIB.buildConstant(ShiftTy, ShiftVal);
1371   Observer.changingInstr(MI);
1372   MI.setDesc(MIB.getTII().get(TargetOpcode::G_SHL));
1373   MI.getOperand(2).setReg(ShiftCst.getReg(0));
1374   Observer.changedInstr(MI);
1375   return true;
1376 }
1377 
1378 bool CombinerHelper::matchCombineShiftToUnmerge(MachineInstr &MI,
1379                                                 unsigned TargetShiftSize,
1380                                                 unsigned &ShiftVal) {
1381   assert((MI.getOpcode() == TargetOpcode::G_SHL ||
1382           MI.getOpcode() == TargetOpcode::G_LSHR ||
1383           MI.getOpcode() == TargetOpcode::G_ASHR) && "Expected a shift");
1384 
1385   LLT Ty = MRI.getType(MI.getOperand(0).getReg());
1386   if (Ty.isVector()) // TODO:
1387     return false;
1388 
1389   // Don't narrow further than the requested size.
1390   unsigned Size = Ty.getSizeInBits();
1391   if (Size <= TargetShiftSize)
1392     return false;
1393 
1394   auto MaybeImmVal =
1395     getConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI);
1396   if (!MaybeImmVal)
1397     return false;
1398 
1399   ShiftVal = MaybeImmVal->Value;
1400   return ShiftVal >= Size / 2 && ShiftVal < Size;
1401 }
1402 
1403 bool CombinerHelper::applyCombineShiftToUnmerge(MachineInstr &MI,
1404                                                 const unsigned &ShiftVal) {
1405   Register DstReg = MI.getOperand(0).getReg();
1406   Register SrcReg = MI.getOperand(1).getReg();
1407   LLT Ty = MRI.getType(SrcReg);
1408   unsigned Size = Ty.getSizeInBits();
1409   unsigned HalfSize = Size / 2;
1410   assert(ShiftVal >= HalfSize);
1411 
1412   LLT HalfTy = LLT::scalar(HalfSize);
1413 
1414   Builder.setInstr(MI);
1415   auto Unmerge = Builder.buildUnmerge(HalfTy, SrcReg);
1416   unsigned NarrowShiftAmt = ShiftVal - HalfSize;
1417 
1418   if (MI.getOpcode() == TargetOpcode::G_LSHR) {
1419     Register Narrowed = Unmerge.getReg(1);
1420 
1421     //  dst = G_LSHR s64:x, C for C >= 32
1422     // =>
1423     //   lo, hi = G_UNMERGE_VALUES x
1424     //   dst = G_MERGE_VALUES (G_LSHR hi, C - 32), 0
1425 
1426     if (NarrowShiftAmt != 0) {
1427       Narrowed = Builder.buildLShr(HalfTy, Narrowed,
1428         Builder.buildConstant(HalfTy, NarrowShiftAmt)).getReg(0);
1429     }
1430 
1431     auto Zero = Builder.buildConstant(HalfTy, 0);
1432     Builder.buildMerge(DstReg, { Narrowed, Zero });
1433   } else if (MI.getOpcode() == TargetOpcode::G_SHL) {
1434     Register Narrowed = Unmerge.getReg(0);
1435     //  dst = G_SHL s64:x, C for C >= 32
1436     // =>
1437     //   lo, hi = G_UNMERGE_VALUES x
1438     //   dst = G_MERGE_VALUES 0, (G_SHL hi, C - 32)
1439     if (NarrowShiftAmt != 0) {
1440       Narrowed = Builder.buildShl(HalfTy, Narrowed,
1441         Builder.buildConstant(HalfTy, NarrowShiftAmt)).getReg(0);
1442     }
1443 
1444     auto Zero = Builder.buildConstant(HalfTy, 0);
1445     Builder.buildMerge(DstReg, { Zero, Narrowed });
1446   } else {
1447     assert(MI.getOpcode() == TargetOpcode::G_ASHR);
1448     auto Hi = Builder.buildAShr(
1449       HalfTy, Unmerge.getReg(1),
1450       Builder.buildConstant(HalfTy, HalfSize - 1));
1451 
1452     if (ShiftVal == HalfSize) {
1453       // (G_ASHR i64:x, 32) ->
1454       //   G_MERGE_VALUES hi_32(x), (G_ASHR hi_32(x), 31)
1455       Builder.buildMerge(DstReg, { Unmerge.getReg(1), Hi });
1456     } else if (ShiftVal == Size - 1) {
1457       // Don't need a second shift.
1458       // (G_ASHR i64:x, 63) ->
1459       //   %narrowed = (G_ASHR hi_32(x), 31)
1460       //   G_MERGE_VALUES %narrowed, %narrowed
1461       Builder.buildMerge(DstReg, { Hi, Hi });
1462     } else {
1463       auto Lo = Builder.buildAShr(
1464         HalfTy, Unmerge.getReg(1),
1465         Builder.buildConstant(HalfTy, ShiftVal - HalfSize));
1466 
1467       // (G_ASHR i64:x, C) ->, for C >= 32
1468       //   G_MERGE_VALUES (G_ASHR hi_32(x), C - 32), (G_ASHR hi_32(x), 31)
1469       Builder.buildMerge(DstReg, { Lo, Hi });
1470     }
1471   }
1472 
1473   MI.eraseFromParent();
1474   return true;
1475 }
1476 
1477 bool CombinerHelper::tryCombineShiftToUnmerge(MachineInstr &MI,
1478                                               unsigned TargetShiftAmount) {
1479   unsigned ShiftAmt;
1480   if (matchCombineShiftToUnmerge(MI, TargetShiftAmount, ShiftAmt)) {
1481     applyCombineShiftToUnmerge(MI, ShiftAmt);
1482     return true;
1483   }
1484 
1485   return false;
1486 }
1487 
1488 bool CombinerHelper::matchAnyExplicitUseIsUndef(MachineInstr &MI) {
1489   return any_of(MI.explicit_uses(), [this](const MachineOperand &MO) {
1490     return MO.isReg() &&
1491            getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
1492   });
1493 }
1494 
1495 bool CombinerHelper::matchAllExplicitUsesAreUndef(MachineInstr &MI) {
1496   return all_of(MI.explicit_uses(), [this](const MachineOperand &MO) {
1497     return !MO.isReg() ||
1498            getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI);
1499   });
1500 }
1501 
1502 bool CombinerHelper::matchUndefShuffleVectorMask(MachineInstr &MI) {
1503   assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR);
1504   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
1505   return all_of(Mask, [](int Elt) { return Elt < 0; });
1506 }
1507 
1508 bool CombinerHelper::matchEqualDefs(const MachineOperand &MOP1,
1509                                     const MachineOperand &MOP2) {
1510   if (!MOP1.isReg() || !MOP2.isReg())
1511     return false;
1512   MachineInstr *I1 = getDefIgnoringCopies(MOP1.getReg(), MRI);
1513   if (!I1)
1514     return false;
1515   MachineInstr *I2 = getDefIgnoringCopies(MOP2.getReg(), MRI);
1516   if (!I2)
1517     return false;
1518 
1519   // Check for physical registers on the instructions first to avoid cases like
1520   // this:
1521   //
1522   // %a = COPY $physreg
1523   // ...
1524   // SOMETHING implicit-def $physreg
1525   // ...
1526   // %b = COPY $physreg
1527   //
1528   // These copies are not equivalent.
1529   if (any_of(I1->uses(), [](const MachineOperand &MO) {
1530         return MO.isReg() && MO.getReg().isPhysical();
1531       })) {
1532     // Check if we have a case like this:
1533     //
1534     // %a = COPY $physreg
1535     // %b = COPY %a
1536     //
1537     // In this case, I1 and I2 will both be equal to %a = COPY $physreg.
1538     // From that, we know that they must have the same value, since they must
1539     // have come from the same COPY.
1540     return I1->isIdenticalTo(*I2);
1541   }
1542 
1543   // We don't have any physical registers, so we don't necessarily need the
1544   // same vreg defs.
1545   //
1546   // On the off-chance that there's some target instruction feeding into the
1547   // instruction, let's use produceSameValue instead of isIdenticalTo.
1548   return Builder.getTII().produceSameValue(*I1, *I2, &MRI);
1549 }
1550 
1551 bool CombinerHelper::matchConstantOp(const MachineOperand &MOP, int64_t C) {
1552   if (!MOP.isReg())
1553     return false;
1554   int64_t Cst;
1555   return mi_match(MOP.getReg(), MRI, m_ICst(Cst)) && Cst == C;
1556 }
1557 
1558 bool CombinerHelper::replaceSingleDefInstWithOperand(MachineInstr &MI,
1559                                                      unsigned OpIdx) {
1560   assert(MI.getNumExplicitDefs() == 1 && "Expected one explicit def?");
1561   Register OldReg = MI.getOperand(0).getReg();
1562   Register Replacement = MI.getOperand(OpIdx).getReg();
1563   assert(canReplaceReg(OldReg, Replacement, MRI) && "Cannot replace register?");
1564   MI.eraseFromParent();
1565   replaceRegWith(MRI, OldReg, Replacement);
1566   return true;
1567 }
1568 
1569 bool CombinerHelper::matchSelectSameVal(MachineInstr &MI) {
1570   assert(MI.getOpcode() == TargetOpcode::G_SELECT);
1571   // Match (cond ? x : x)
1572   return matchEqualDefs(MI.getOperand(2), MI.getOperand(3)) &&
1573          canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(2).getReg(),
1574                        MRI);
1575 }
1576 
1577 bool CombinerHelper::matchBinOpSameVal(MachineInstr &MI) {
1578   return matchEqualDefs(MI.getOperand(1), MI.getOperand(2)) &&
1579          canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(1).getReg(),
1580                        MRI);
1581 }
1582 
1583 bool CombinerHelper::replaceInstWithFConstant(MachineInstr &MI, double C) {
1584   assert(MI.getNumDefs() == 1 && "Expected only one def?");
1585   Builder.setInstr(MI);
1586   Builder.buildFConstant(MI.getOperand(0), C);
1587   MI.eraseFromParent();
1588   return true;
1589 }
1590 
1591 bool CombinerHelper::replaceInstWithConstant(MachineInstr &MI, int64_t C) {
1592   assert(MI.getNumDefs() == 1 && "Expected only one def?");
1593   Builder.setInstr(MI);
1594   Builder.buildConstant(MI.getOperand(0), C);
1595   MI.eraseFromParent();
1596   return true;
1597 }
1598 
1599 bool CombinerHelper::replaceInstWithUndef(MachineInstr &MI) {
1600   assert(MI.getNumDefs() == 1 && "Expected only one def?");
1601   Builder.setInstr(MI);
1602   Builder.buildUndef(MI.getOperand(0));
1603   MI.eraseFromParent();
1604   return true;
1605 }
1606 
1607 bool CombinerHelper::tryCombine(MachineInstr &MI) {
1608   if (tryCombineCopy(MI))
1609     return true;
1610   if (tryCombineExtendingLoads(MI))
1611     return true;
1612   if (tryCombineIndexedLoadStore(MI))
1613     return true;
1614   return false;
1615 }
1616