1 //===-- llvm/CodeGen/GlobalISel/MachineIRBuilder.cpp - MIBuilder--*- C++ -*-==//
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 /// \file
9 /// This file implements the MachineIRBuidler class.
10 //===----------------------------------------------------------------------===//
11 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
12 #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
13 
14 #include "llvm/CodeGen/MachineFunction.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "llvm/CodeGen/MachineInstrBuilder.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/CodeGen/TargetInstrInfo.h"
19 #include "llvm/CodeGen/TargetLowering.h"
20 #include "llvm/CodeGen/TargetOpcodes.h"
21 #include "llvm/CodeGen/TargetSubtargetInfo.h"
22 #include "llvm/IR/DebugInfo.h"
23 
24 using namespace llvm;
25 
26 void MachineIRBuilder::setMF(MachineFunction &MF) {
27   State.MF = &MF;
28   State.MBB = nullptr;
29   State.MRI = &MF.getRegInfo();
30   State.TII = MF.getSubtarget().getInstrInfo();
31   State.DL = DebugLoc();
32   State.II = MachineBasicBlock::iterator();
33   State.Observer = nullptr;
34 }
35 
36 void MachineIRBuilder::setMBB(MachineBasicBlock &MBB) {
37   State.MBB = &MBB;
38   State.II = MBB.end();
39   assert(&getMF() == MBB.getParent() &&
40          "Basic block is in a different function");
41 }
42 
43 void MachineIRBuilder::setInstr(MachineInstr &MI) {
44   assert(MI.getParent() && "Instruction is not part of a basic block");
45   setMBB(*MI.getParent());
46   State.II = MI.getIterator();
47 }
48 
49 void MachineIRBuilder::setCSEInfo(GISelCSEInfo *Info) { State.CSEInfo = Info; }
50 
51 void MachineIRBuilder::setInsertPt(MachineBasicBlock &MBB,
52                                    MachineBasicBlock::iterator II) {
53   assert(MBB.getParent() == &getMF() &&
54          "Basic block is in a different function");
55   State.MBB = &MBB;
56   State.II = II;
57 }
58 
59 void MachineIRBuilder::recordInsertion(MachineInstr *InsertedInstr) const {
60   if (State.Observer)
61     State.Observer->createdInstr(*InsertedInstr);
62 }
63 
64 void MachineIRBuilder::setChangeObserver(GISelChangeObserver &Observer) {
65   State.Observer = &Observer;
66 }
67 
68 void MachineIRBuilder::stopObservingChanges() { State.Observer = nullptr; }
69 
70 //------------------------------------------------------------------------------
71 // Build instruction variants.
72 //------------------------------------------------------------------------------
73 
74 MachineInstrBuilder MachineIRBuilder::buildInstr(unsigned Opcode) {
75   return insertInstr(buildInstrNoInsert(Opcode));
76 }
77 
78 MachineInstrBuilder MachineIRBuilder::buildInstrNoInsert(unsigned Opcode) {
79   MachineInstrBuilder MIB = BuildMI(getMF(), getDL(), getTII().get(Opcode));
80   return MIB;
81 }
82 
83 MachineInstrBuilder MachineIRBuilder::insertInstr(MachineInstrBuilder MIB) {
84   getMBB().insert(getInsertPt(), MIB);
85   recordInsertion(MIB);
86   return MIB;
87 }
88 
89 MachineInstrBuilder
90 MachineIRBuilder::buildDirectDbgValue(unsigned Reg, const MDNode *Variable,
91                                       const MDNode *Expr) {
92   assert(isa<DILocalVariable>(Variable) && "not a variable");
93   assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
94   assert(
95       cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(getDL()) &&
96       "Expected inlined-at fields to agree");
97   return insertInstr(BuildMI(getMF(), getDL(),
98                              getTII().get(TargetOpcode::DBG_VALUE),
99                              /*IsIndirect*/ false, Reg, Variable, Expr));
100 }
101 
102 MachineInstrBuilder
103 MachineIRBuilder::buildIndirectDbgValue(unsigned Reg, const MDNode *Variable,
104                                         const MDNode *Expr) {
105   assert(isa<DILocalVariable>(Variable) && "not a variable");
106   assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
107   assert(
108       cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(getDL()) &&
109       "Expected inlined-at fields to agree");
110   return insertInstr(BuildMI(getMF(), getDL(),
111                              getTII().get(TargetOpcode::DBG_VALUE),
112                              /*IsIndirect*/ true, Reg, Variable, Expr));
113 }
114 
115 MachineInstrBuilder MachineIRBuilder::buildFIDbgValue(int FI,
116                                                       const MDNode *Variable,
117                                                       const MDNode *Expr) {
118   assert(isa<DILocalVariable>(Variable) && "not a variable");
119   assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
120   assert(
121       cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(getDL()) &&
122       "Expected inlined-at fields to agree");
123   return buildInstr(TargetOpcode::DBG_VALUE)
124       .addFrameIndex(FI)
125       .addImm(0)
126       .addMetadata(Variable)
127       .addMetadata(Expr);
128 }
129 
130 MachineInstrBuilder MachineIRBuilder::buildConstDbgValue(const Constant &C,
131                                                          const MDNode *Variable,
132                                                          const MDNode *Expr) {
133   assert(isa<DILocalVariable>(Variable) && "not a variable");
134   assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
135   assert(
136       cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(getDL()) &&
137       "Expected inlined-at fields to agree");
138   auto MIB = buildInstr(TargetOpcode::DBG_VALUE);
139   if (auto *CI = dyn_cast<ConstantInt>(&C)) {
140     if (CI->getBitWidth() > 64)
141       MIB.addCImm(CI);
142     else
143       MIB.addImm(CI->getZExtValue());
144   } else if (auto *CFP = dyn_cast<ConstantFP>(&C)) {
145     MIB.addFPImm(CFP);
146   } else {
147     // Insert %noreg if we didn't find a usable constant and had to drop it.
148     MIB.addReg(0U);
149   }
150 
151   return MIB.addImm(0).addMetadata(Variable).addMetadata(Expr);
152 }
153 
154 MachineInstrBuilder MachineIRBuilder::buildDbgLabel(const MDNode *Label) {
155   assert(isa<DILabel>(Label) && "not a label");
156   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(State.DL) &&
157          "Expected inlined-at fields to agree");
158   auto MIB = buildInstr(TargetOpcode::DBG_LABEL);
159 
160   return MIB.addMetadata(Label);
161 }
162 
163 MachineInstrBuilder MachineIRBuilder::buildFrameIndex(unsigned Res, int Idx) {
164   assert(getMRI()->getType(Res).isPointer() && "invalid operand type");
165   return buildInstr(TargetOpcode::G_FRAME_INDEX)
166       .addDef(Res)
167       .addFrameIndex(Idx);
168 }
169 
170 MachineInstrBuilder MachineIRBuilder::buildGlobalValue(unsigned Res,
171                                                        const GlobalValue *GV) {
172   assert(getMRI()->getType(Res).isPointer() && "invalid operand type");
173   assert(getMRI()->getType(Res).getAddressSpace() ==
174              GV->getType()->getAddressSpace() &&
175          "address space mismatch");
176 
177   return buildInstr(TargetOpcode::G_GLOBAL_VALUE)
178       .addDef(Res)
179       .addGlobalAddress(GV);
180 }
181 
182 void MachineIRBuilder::validateBinaryOp(const LLT &Res, const LLT &Op0,
183                                         const LLT &Op1) {
184   assert((Res.isScalar() || Res.isVector()) && "invalid operand type");
185   assert((Res == Op0 && Res == Op1) && "type mismatch");
186 }
187 
188 void MachineIRBuilder::validateShiftOp(const LLT &Res, const LLT &Op0,
189                                        const LLT &Op1) {
190   assert((Res.isScalar() || Res.isVector()) && "invalid operand type");
191   assert((Res == Op0) && "type mismatch");
192 }
193 
194 MachineInstrBuilder MachineIRBuilder::buildGEP(unsigned Res, unsigned Op0,
195                                                unsigned Op1) {
196   assert(getMRI()->getType(Res).isPointer() &&
197          getMRI()->getType(Res) == getMRI()->getType(Op0) && "type mismatch");
198   assert(getMRI()->getType(Op1).isScalar() && "invalid offset type");
199 
200   return buildInstr(TargetOpcode::G_GEP)
201       .addDef(Res)
202       .addUse(Op0)
203       .addUse(Op1);
204 }
205 
206 Optional<MachineInstrBuilder>
207 MachineIRBuilder::materializeGEP(unsigned &Res, unsigned Op0,
208                                  const LLT &ValueTy, uint64_t Value) {
209   assert(Res == 0 && "Res is a result argument");
210   assert(ValueTy.isScalar()  && "invalid offset type");
211 
212   if (Value == 0) {
213     Res = Op0;
214     return None;
215   }
216 
217   Res = getMRI()->createGenericVirtualRegister(getMRI()->getType(Op0));
218   unsigned TmpReg = getMRI()->createGenericVirtualRegister(ValueTy);
219 
220   buildConstant(TmpReg, Value);
221   return buildGEP(Res, Op0, TmpReg);
222 }
223 
224 MachineInstrBuilder MachineIRBuilder::buildPtrMask(unsigned Res, unsigned Op0,
225                                                    uint32_t NumBits) {
226   assert(getMRI()->getType(Res).isPointer() &&
227          getMRI()->getType(Res) == getMRI()->getType(Op0) && "type mismatch");
228 
229   return buildInstr(TargetOpcode::G_PTR_MASK)
230       .addDef(Res)
231       .addUse(Op0)
232       .addImm(NumBits);
233 }
234 
235 MachineInstrBuilder MachineIRBuilder::buildBr(MachineBasicBlock &Dest) {
236   return buildInstr(TargetOpcode::G_BR).addMBB(&Dest);
237 }
238 
239 MachineInstrBuilder MachineIRBuilder::buildBrIndirect(unsigned Tgt) {
240   assert(getMRI()->getType(Tgt).isPointer() && "invalid branch destination");
241   return buildInstr(TargetOpcode::G_BRINDIRECT).addUse(Tgt);
242 }
243 
244 MachineInstrBuilder MachineIRBuilder::buildCopy(const DstOp &Res,
245                                                 const SrcOp &Op) {
246   return buildInstr(TargetOpcode::COPY, Res, Op);
247 }
248 
249 MachineInstrBuilder MachineIRBuilder::buildConstant(const DstOp &Res,
250                                                     const ConstantInt &Val) {
251   LLT Ty = Res.getLLTTy(*getMRI());
252   LLT EltTy = Ty.getScalarType();
253   assert(EltTy.getScalarSizeInBits() == Val.getBitWidth() &&
254          "creating constant with the wrong size");
255 
256   if (Ty.isVector()) {
257     auto Const = buildInstr(TargetOpcode::G_CONSTANT)
258     .addDef(getMRI()->createGenericVirtualRegister(EltTy))
259     .addCImm(&Val);
260     return buildSplatVector(Res, Const);
261   }
262 
263   auto Const = buildInstr(TargetOpcode::G_CONSTANT);
264   Res.addDefToMIB(*getMRI(), Const);
265   Const.addCImm(&Val);
266   return Const;
267 }
268 
269 MachineInstrBuilder MachineIRBuilder::buildConstant(const DstOp &Res,
270                                                     int64_t Val) {
271   auto IntN = IntegerType::get(getMF().getFunction().getContext(),
272                                Res.getLLTTy(*getMRI()).getScalarSizeInBits());
273   ConstantInt *CI = ConstantInt::get(IntN, Val, true);
274   return buildConstant(Res, *CI);
275 }
276 
277 MachineInstrBuilder MachineIRBuilder::buildFConstant(const DstOp &Res,
278                                                      const ConstantFP &Val) {
279   LLT Ty = Res.getLLTTy(*getMRI());
280   LLT EltTy = Ty.getScalarType();
281 
282   assert(APFloat::getSizeInBits(Val.getValueAPF().getSemantics())
283          == EltTy.getSizeInBits() &&
284          "creating fconstant with the wrong size");
285 
286   assert(!Ty.isPointer() && "invalid operand type");
287 
288   if (Ty.isVector()) {
289     auto Const = buildInstr(TargetOpcode::G_FCONSTANT)
290     .addDef(getMRI()->createGenericVirtualRegister(EltTy))
291     .addFPImm(&Val);
292 
293     return buildSplatVector(Res, Const);
294   }
295 
296   auto Const = buildInstr(TargetOpcode::G_FCONSTANT);
297   Res.addDefToMIB(*getMRI(), Const);
298   Const.addFPImm(&Val);
299   return Const;
300 }
301 
302 MachineInstrBuilder MachineIRBuilder::buildConstant(const DstOp &Res,
303                                                     const APInt &Val) {
304   ConstantInt *CI = ConstantInt::get(getMF().getFunction().getContext(), Val);
305   return buildConstant(Res, *CI);
306 }
307 
308 MachineInstrBuilder MachineIRBuilder::buildFConstant(const DstOp &Res,
309                                                      double Val) {
310   LLT DstTy = Res.getLLTTy(*getMRI());
311   auto &Ctx = getMF().getFunction().getContext();
312   auto *CFP =
313       ConstantFP::get(Ctx, getAPFloatFromSize(Val, DstTy.getScalarSizeInBits()));
314   return buildFConstant(Res, *CFP);
315 }
316 
317 MachineInstrBuilder MachineIRBuilder::buildBrCond(unsigned Tst,
318                                                   MachineBasicBlock &Dest) {
319   assert(getMRI()->getType(Tst).isScalar() && "invalid operand type");
320 
321   return buildInstr(TargetOpcode::G_BRCOND).addUse(Tst).addMBB(&Dest);
322 }
323 
324 MachineInstrBuilder MachineIRBuilder::buildLoad(unsigned Res, unsigned Addr,
325                                                 MachineMemOperand &MMO) {
326   return buildLoadInstr(TargetOpcode::G_LOAD, Res, Addr, MMO);
327 }
328 
329 MachineInstrBuilder MachineIRBuilder::buildLoadInstr(unsigned Opcode,
330                                                      unsigned Res,
331                                                      unsigned Addr,
332                                                      MachineMemOperand &MMO) {
333   assert(getMRI()->getType(Res).isValid() && "invalid operand type");
334   assert(getMRI()->getType(Addr).isPointer() && "invalid operand type");
335 
336   return buildInstr(Opcode)
337       .addDef(Res)
338       .addUse(Addr)
339       .addMemOperand(&MMO);
340 }
341 
342 MachineInstrBuilder MachineIRBuilder::buildStore(unsigned Val, unsigned Addr,
343                                                  MachineMemOperand &MMO) {
344   assert(getMRI()->getType(Val).isValid() && "invalid operand type");
345   assert(getMRI()->getType(Addr).isPointer() && "invalid operand type");
346 
347   return buildInstr(TargetOpcode::G_STORE)
348       .addUse(Val)
349       .addUse(Addr)
350       .addMemOperand(&MMO);
351 }
352 
353 MachineInstrBuilder MachineIRBuilder::buildUAdde(const DstOp &Res,
354                                                  const DstOp &CarryOut,
355                                                  const SrcOp &Op0,
356                                                  const SrcOp &Op1,
357                                                  const SrcOp &CarryIn) {
358   return buildInstr(TargetOpcode::G_UADDE, {Res, CarryOut},
359                     {Op0, Op1, CarryIn});
360 }
361 
362 MachineInstrBuilder MachineIRBuilder::buildAnyExt(const DstOp &Res,
363                                                   const SrcOp &Op) {
364   return buildInstr(TargetOpcode::G_ANYEXT, Res, Op);
365 }
366 
367 MachineInstrBuilder MachineIRBuilder::buildSExt(const DstOp &Res,
368                                                 const SrcOp &Op) {
369   return buildInstr(TargetOpcode::G_SEXT, Res, Op);
370 }
371 
372 MachineInstrBuilder MachineIRBuilder::buildZExt(const DstOp &Res,
373                                                 const SrcOp &Op) {
374   return buildInstr(TargetOpcode::G_ZEXT, Res, Op);
375 }
376 
377 unsigned MachineIRBuilder::getBoolExtOp(bool IsVec, bool IsFP) const {
378   const auto *TLI = getMF().getSubtarget().getTargetLowering();
379   switch (TLI->getBooleanContents(IsVec, IsFP)) {
380   case TargetLoweringBase::ZeroOrNegativeOneBooleanContent:
381     return TargetOpcode::G_SEXT;
382   case TargetLoweringBase::ZeroOrOneBooleanContent:
383     return TargetOpcode::G_ZEXT;
384   default:
385     return TargetOpcode::G_ANYEXT;
386   }
387 }
388 
389 MachineInstrBuilder MachineIRBuilder::buildBoolExt(const DstOp &Res,
390                                                    const SrcOp &Op,
391                                                    bool IsFP) {
392   unsigned ExtOp = getBoolExtOp(getMRI()->getType(Op.getReg()).isVector(), IsFP);
393   return buildInstr(ExtOp, Res, Op);
394 }
395 
396 MachineInstrBuilder MachineIRBuilder::buildExtOrTrunc(unsigned ExtOpc,
397                                                       const DstOp &Res,
398                                                       const SrcOp &Op) {
399   assert((TargetOpcode::G_ANYEXT == ExtOpc || TargetOpcode::G_ZEXT == ExtOpc ||
400           TargetOpcode::G_SEXT == ExtOpc) &&
401          "Expecting Extending Opc");
402   assert(Res.getLLTTy(*getMRI()).isScalar() ||
403          Res.getLLTTy(*getMRI()).isVector());
404   assert(Res.getLLTTy(*getMRI()).isScalar() ==
405          Op.getLLTTy(*getMRI()).isScalar());
406 
407   unsigned Opcode = TargetOpcode::COPY;
408   if (Res.getLLTTy(*getMRI()).getSizeInBits() >
409       Op.getLLTTy(*getMRI()).getSizeInBits())
410     Opcode = ExtOpc;
411   else if (Res.getLLTTy(*getMRI()).getSizeInBits() <
412            Op.getLLTTy(*getMRI()).getSizeInBits())
413     Opcode = TargetOpcode::G_TRUNC;
414   else
415     assert(Res.getLLTTy(*getMRI()) == Op.getLLTTy(*getMRI()));
416 
417   return buildInstr(Opcode, Res, Op);
418 }
419 
420 MachineInstrBuilder MachineIRBuilder::buildSExtOrTrunc(const DstOp &Res,
421                                                        const SrcOp &Op) {
422   return buildExtOrTrunc(TargetOpcode::G_SEXT, Res, Op);
423 }
424 
425 MachineInstrBuilder MachineIRBuilder::buildZExtOrTrunc(const DstOp &Res,
426                                                        const SrcOp &Op) {
427   return buildExtOrTrunc(TargetOpcode::G_ZEXT, Res, Op);
428 }
429 
430 MachineInstrBuilder MachineIRBuilder::buildAnyExtOrTrunc(const DstOp &Res,
431                                                          const SrcOp &Op) {
432   return buildExtOrTrunc(TargetOpcode::G_ANYEXT, Res, Op);
433 }
434 
435 MachineInstrBuilder MachineIRBuilder::buildCast(const DstOp &Dst,
436                                                 const SrcOp &Src) {
437   LLT SrcTy = Src.getLLTTy(*getMRI());
438   LLT DstTy = Dst.getLLTTy(*getMRI());
439   if (SrcTy == DstTy)
440     return buildCopy(Dst, Src);
441 
442   unsigned Opcode;
443   if (SrcTy.isPointer() && DstTy.isScalar())
444     Opcode = TargetOpcode::G_PTRTOINT;
445   else if (DstTy.isPointer() && SrcTy.isScalar())
446     Opcode = TargetOpcode::G_INTTOPTR;
447   else {
448     assert(!SrcTy.isPointer() && !DstTy.isPointer() && "n G_ADDRCAST yet");
449     Opcode = TargetOpcode::G_BITCAST;
450   }
451 
452   return buildInstr(Opcode, Dst, Src);
453 }
454 
455 MachineInstrBuilder MachineIRBuilder::buildExtract(const DstOp &Dst,
456                                                    const SrcOp &Src,
457                                                    uint64_t Index) {
458   LLT SrcTy = Src.getLLTTy(*getMRI());
459   LLT DstTy = Dst.getLLTTy(*getMRI());
460 
461 #ifndef NDEBUG
462   assert(SrcTy.isValid() && "invalid operand type");
463   assert(DstTy.isValid() && "invalid operand type");
464   assert(Index + DstTy.getSizeInBits() <= SrcTy.getSizeInBits() &&
465          "extracting off end of register");
466 #endif
467 
468   if (DstTy.getSizeInBits() == SrcTy.getSizeInBits()) {
469     assert(Index == 0 && "insertion past the end of a register");
470     return buildCast(Dst, Src);
471   }
472 
473   auto Extract = buildInstr(TargetOpcode::G_EXTRACT);
474   Dst.addDefToMIB(*getMRI(), Extract);
475   Src.addSrcToMIB(Extract);
476   Extract.addImm(Index);
477   return Extract;
478 }
479 
480 void MachineIRBuilder::buildSequence(unsigned Res, ArrayRef<unsigned> Ops,
481                                      ArrayRef<uint64_t> Indices) {
482 #ifndef NDEBUG
483   assert(Ops.size() == Indices.size() && "incompatible args");
484   assert(!Ops.empty() && "invalid trivial sequence");
485   assert(std::is_sorted(Indices.begin(), Indices.end()) &&
486          "sequence offsets must be in ascending order");
487 
488   assert(getMRI()->getType(Res).isValid() && "invalid operand type");
489   for (auto Op : Ops)
490     assert(getMRI()->getType(Op).isValid() && "invalid operand type");
491 #endif
492 
493   LLT ResTy = getMRI()->getType(Res);
494   LLT OpTy = getMRI()->getType(Ops[0]);
495   unsigned OpSize = OpTy.getSizeInBits();
496   bool MaybeMerge = true;
497   for (unsigned i = 0; i < Ops.size(); ++i) {
498     if (getMRI()->getType(Ops[i]) != OpTy || Indices[i] != i * OpSize) {
499       MaybeMerge = false;
500       break;
501     }
502   }
503 
504   if (MaybeMerge && Ops.size() * OpSize == ResTy.getSizeInBits()) {
505     buildMerge(Res, Ops);
506     return;
507   }
508 
509   unsigned ResIn = getMRI()->createGenericVirtualRegister(ResTy);
510   buildUndef(ResIn);
511 
512   for (unsigned i = 0; i < Ops.size(); ++i) {
513     unsigned ResOut = i + 1 == Ops.size()
514                           ? Res
515                           : getMRI()->createGenericVirtualRegister(ResTy);
516     buildInsert(ResOut, ResIn, Ops[i], Indices[i]);
517     ResIn = ResOut;
518   }
519 }
520 
521 MachineInstrBuilder MachineIRBuilder::buildUndef(const DstOp &Res) {
522   return buildInstr(TargetOpcode::G_IMPLICIT_DEF, {Res}, {});
523 }
524 
525 MachineInstrBuilder MachineIRBuilder::buildMerge(const DstOp &Res,
526                                                  ArrayRef<unsigned> Ops) {
527   // Unfortunately to convert from ArrayRef<LLT> to ArrayRef<SrcOp>,
528   // we need some temporary storage for the DstOp objects. Here we use a
529   // sufficiently large SmallVector to not go through the heap.
530   SmallVector<SrcOp, 8> TmpVec(Ops.begin(), Ops.end());
531   return buildInstr(TargetOpcode::G_MERGE_VALUES, Res, TmpVec);
532 }
533 
534 MachineInstrBuilder MachineIRBuilder::buildUnmerge(ArrayRef<LLT> Res,
535                                                    const SrcOp &Op) {
536   // Unfortunately to convert from ArrayRef<LLT> to ArrayRef<DstOp>,
537   // we need some temporary storage for the DstOp objects. Here we use a
538   // sufficiently large SmallVector to not go through the heap.
539   SmallVector<DstOp, 8> TmpVec(Res.begin(), Res.end());
540   return buildInstr(TargetOpcode::G_UNMERGE_VALUES, TmpVec, Op);
541 }
542 
543 MachineInstrBuilder MachineIRBuilder::buildUnmerge(ArrayRef<unsigned> Res,
544                                                    const SrcOp &Op) {
545   // Unfortunately to convert from ArrayRef<unsigned> to ArrayRef<DstOp>,
546   // we need some temporary storage for the DstOp objects. Here we use a
547   // sufficiently large SmallVector to not go through the heap.
548   SmallVector<DstOp, 8> TmpVec(Res.begin(), Res.end());
549   return buildInstr(TargetOpcode::G_UNMERGE_VALUES, TmpVec, Op);
550 }
551 
552 MachineInstrBuilder MachineIRBuilder::buildBuildVector(const DstOp &Res,
553                                                        ArrayRef<unsigned> Ops) {
554   // Unfortunately to convert from ArrayRef<unsigned> to ArrayRef<SrcOp>,
555   // we need some temporary storage for the DstOp objects. Here we use a
556   // sufficiently large SmallVector to not go through the heap.
557   SmallVector<SrcOp, 8> TmpVec(Ops.begin(), Ops.end());
558   return buildInstr(TargetOpcode::G_BUILD_VECTOR, Res, TmpVec);
559 }
560 
561 MachineInstrBuilder MachineIRBuilder::buildSplatVector(const DstOp &Res,
562                                                        const SrcOp &Src) {
563   SmallVector<SrcOp, 8> TmpVec(Res.getLLTTy(*getMRI()).getNumElements(), Src);
564   return buildInstr(TargetOpcode::G_BUILD_VECTOR, Res, TmpVec);
565 }
566 
567 MachineInstrBuilder
568 MachineIRBuilder::buildBuildVectorTrunc(const DstOp &Res,
569                                         ArrayRef<unsigned> Ops) {
570   // Unfortunately to convert from ArrayRef<unsigned> to ArrayRef<SrcOp>,
571   // we need some temporary storage for the DstOp objects. Here we use a
572   // sufficiently large SmallVector to not go through the heap.
573   SmallVector<SrcOp, 8> TmpVec(Ops.begin(), Ops.end());
574   return buildInstr(TargetOpcode::G_BUILD_VECTOR_TRUNC, Res, TmpVec);
575 }
576 
577 MachineInstrBuilder
578 MachineIRBuilder::buildConcatVectors(const DstOp &Res, ArrayRef<unsigned> Ops) {
579   // Unfortunately to convert from ArrayRef<unsigned> to ArrayRef<SrcOp>,
580   // we need some temporary storage for the DstOp objects. Here we use a
581   // sufficiently large SmallVector to not go through the heap.
582   SmallVector<SrcOp, 8> TmpVec(Ops.begin(), Ops.end());
583   return buildInstr(TargetOpcode::G_CONCAT_VECTORS, Res, TmpVec);
584 }
585 
586 MachineInstrBuilder MachineIRBuilder::buildInsert(unsigned Res, unsigned Src,
587                                                   unsigned Op, unsigned Index) {
588   assert(Index + getMRI()->getType(Op).getSizeInBits() <=
589              getMRI()->getType(Res).getSizeInBits() &&
590          "insertion past the end of a register");
591 
592   if (getMRI()->getType(Res).getSizeInBits() ==
593       getMRI()->getType(Op).getSizeInBits()) {
594     return buildCast(Res, Op);
595   }
596 
597   return buildInstr(TargetOpcode::G_INSERT)
598       .addDef(Res)
599       .addUse(Src)
600       .addUse(Op)
601       .addImm(Index);
602 }
603 
604 MachineInstrBuilder MachineIRBuilder::buildIntrinsic(Intrinsic::ID ID,
605                                                      unsigned Res,
606                                                      bool HasSideEffects) {
607   auto MIB =
608       buildInstr(HasSideEffects ? TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS
609                                 : TargetOpcode::G_INTRINSIC);
610   if (Res)
611     MIB.addDef(Res);
612   MIB.addIntrinsicID(ID);
613   return MIB;
614 }
615 
616 MachineInstrBuilder MachineIRBuilder::buildTrunc(const DstOp &Res,
617                                                  const SrcOp &Op) {
618   return buildInstr(TargetOpcode::G_TRUNC, Res, Op);
619 }
620 
621 MachineInstrBuilder MachineIRBuilder::buildFPTrunc(const DstOp &Res,
622                                                    const SrcOp &Op) {
623   return buildInstr(TargetOpcode::G_FPTRUNC, Res, Op);
624 }
625 
626 MachineInstrBuilder MachineIRBuilder::buildICmp(CmpInst::Predicate Pred,
627                                                 const DstOp &Res,
628                                                 const SrcOp &Op0,
629                                                 const SrcOp &Op1) {
630   return buildInstr(TargetOpcode::G_ICMP, Res, {Pred, Op0, Op1});
631 }
632 
633 MachineInstrBuilder MachineIRBuilder::buildFCmp(CmpInst::Predicate Pred,
634                                                 const DstOp &Res,
635                                                 const SrcOp &Op0,
636                                                 const SrcOp &Op1) {
637 
638   return buildInstr(TargetOpcode::G_FCMP, Res, {Pred, Op0, Op1});
639 }
640 
641 MachineInstrBuilder MachineIRBuilder::buildSelect(const DstOp &Res,
642                                                   const SrcOp &Tst,
643                                                   const SrcOp &Op0,
644                                                   const SrcOp &Op1) {
645 
646   return buildInstr(TargetOpcode::G_SELECT, {Res}, {Tst, Op0, Op1});
647 }
648 
649 MachineInstrBuilder
650 MachineIRBuilder::buildInsertVectorElement(const DstOp &Res, const SrcOp &Val,
651                                            const SrcOp &Elt, const SrcOp &Idx) {
652   return buildInstr(TargetOpcode::G_INSERT_VECTOR_ELT, Res, {Val, Elt, Idx});
653 }
654 
655 MachineInstrBuilder
656 MachineIRBuilder::buildExtractVectorElement(const DstOp &Res, const SrcOp &Val,
657                                             const SrcOp &Idx) {
658   return buildInstr(TargetOpcode::G_EXTRACT_VECTOR_ELT, Res, {Val, Idx});
659 }
660 
661 MachineInstrBuilder MachineIRBuilder::buildAtomicCmpXchgWithSuccess(
662     unsigned OldValRes, unsigned SuccessRes, unsigned Addr, unsigned CmpVal,
663     unsigned NewVal, MachineMemOperand &MMO) {
664 #ifndef NDEBUG
665   LLT OldValResTy = getMRI()->getType(OldValRes);
666   LLT SuccessResTy = getMRI()->getType(SuccessRes);
667   LLT AddrTy = getMRI()->getType(Addr);
668   LLT CmpValTy = getMRI()->getType(CmpVal);
669   LLT NewValTy = getMRI()->getType(NewVal);
670   assert(OldValResTy.isScalar() && "invalid operand type");
671   assert(SuccessResTy.isScalar() && "invalid operand type");
672   assert(AddrTy.isPointer() && "invalid operand type");
673   assert(CmpValTy.isValid() && "invalid operand type");
674   assert(NewValTy.isValid() && "invalid operand type");
675   assert(OldValResTy == CmpValTy && "type mismatch");
676   assert(OldValResTy == NewValTy && "type mismatch");
677 #endif
678 
679   return buildInstr(TargetOpcode::G_ATOMIC_CMPXCHG_WITH_SUCCESS)
680       .addDef(OldValRes)
681       .addDef(SuccessRes)
682       .addUse(Addr)
683       .addUse(CmpVal)
684       .addUse(NewVal)
685       .addMemOperand(&MMO);
686 }
687 
688 MachineInstrBuilder
689 MachineIRBuilder::buildAtomicCmpXchg(unsigned OldValRes, unsigned Addr,
690                                      unsigned CmpVal, unsigned NewVal,
691                                      MachineMemOperand &MMO) {
692 #ifndef NDEBUG
693   LLT OldValResTy = getMRI()->getType(OldValRes);
694   LLT AddrTy = getMRI()->getType(Addr);
695   LLT CmpValTy = getMRI()->getType(CmpVal);
696   LLT NewValTy = getMRI()->getType(NewVal);
697   assert(OldValResTy.isScalar() && "invalid operand type");
698   assert(AddrTy.isPointer() && "invalid operand type");
699   assert(CmpValTy.isValid() && "invalid operand type");
700   assert(NewValTy.isValid() && "invalid operand type");
701   assert(OldValResTy == CmpValTy && "type mismatch");
702   assert(OldValResTy == NewValTy && "type mismatch");
703 #endif
704 
705   return buildInstr(TargetOpcode::G_ATOMIC_CMPXCHG)
706       .addDef(OldValRes)
707       .addUse(Addr)
708       .addUse(CmpVal)
709       .addUse(NewVal)
710       .addMemOperand(&MMO);
711 }
712 
713 MachineInstrBuilder MachineIRBuilder::buildAtomicRMW(unsigned Opcode,
714                                                      unsigned OldValRes,
715                                                      unsigned Addr,
716                                                      unsigned Val,
717                                                      MachineMemOperand &MMO) {
718 #ifndef NDEBUG
719   LLT OldValResTy = getMRI()->getType(OldValRes);
720   LLT AddrTy = getMRI()->getType(Addr);
721   LLT ValTy = getMRI()->getType(Val);
722   assert(OldValResTy.isScalar() && "invalid operand type");
723   assert(AddrTy.isPointer() && "invalid operand type");
724   assert(ValTy.isValid() && "invalid operand type");
725   assert(OldValResTy == ValTy && "type mismatch");
726 #endif
727 
728   return buildInstr(Opcode)
729       .addDef(OldValRes)
730       .addUse(Addr)
731       .addUse(Val)
732       .addMemOperand(&MMO);
733 }
734 
735 MachineInstrBuilder
736 MachineIRBuilder::buildAtomicRMWXchg(unsigned OldValRes, unsigned Addr,
737                                      unsigned Val, MachineMemOperand &MMO) {
738   return buildAtomicRMW(TargetOpcode::G_ATOMICRMW_XCHG, OldValRes, Addr, Val,
739                         MMO);
740 }
741 MachineInstrBuilder
742 MachineIRBuilder::buildAtomicRMWAdd(unsigned OldValRes, unsigned Addr,
743                                     unsigned Val, MachineMemOperand &MMO) {
744   return buildAtomicRMW(TargetOpcode::G_ATOMICRMW_ADD, OldValRes, Addr, Val,
745                         MMO);
746 }
747 MachineInstrBuilder
748 MachineIRBuilder::buildAtomicRMWSub(unsigned OldValRes, unsigned Addr,
749                                     unsigned Val, MachineMemOperand &MMO) {
750   return buildAtomicRMW(TargetOpcode::G_ATOMICRMW_SUB, OldValRes, Addr, Val,
751                         MMO);
752 }
753 MachineInstrBuilder
754 MachineIRBuilder::buildAtomicRMWAnd(unsigned OldValRes, unsigned Addr,
755                                     unsigned Val, MachineMemOperand &MMO) {
756   return buildAtomicRMW(TargetOpcode::G_ATOMICRMW_AND, OldValRes, Addr, Val,
757                         MMO);
758 }
759 MachineInstrBuilder
760 MachineIRBuilder::buildAtomicRMWNand(unsigned OldValRes, unsigned Addr,
761                                      unsigned Val, MachineMemOperand &MMO) {
762   return buildAtomicRMW(TargetOpcode::G_ATOMICRMW_NAND, OldValRes, Addr, Val,
763                         MMO);
764 }
765 MachineInstrBuilder MachineIRBuilder::buildAtomicRMWOr(unsigned OldValRes,
766                                                        unsigned Addr,
767                                                        unsigned Val,
768                                                        MachineMemOperand &MMO) {
769   return buildAtomicRMW(TargetOpcode::G_ATOMICRMW_OR, OldValRes, Addr, Val,
770                         MMO);
771 }
772 MachineInstrBuilder
773 MachineIRBuilder::buildAtomicRMWXor(unsigned OldValRes, unsigned Addr,
774                                     unsigned Val, MachineMemOperand &MMO) {
775   return buildAtomicRMW(TargetOpcode::G_ATOMICRMW_XOR, OldValRes, Addr, Val,
776                         MMO);
777 }
778 MachineInstrBuilder
779 MachineIRBuilder::buildAtomicRMWMax(unsigned OldValRes, unsigned Addr,
780                                     unsigned Val, MachineMemOperand &MMO) {
781   return buildAtomicRMW(TargetOpcode::G_ATOMICRMW_MAX, OldValRes, Addr, Val,
782                         MMO);
783 }
784 MachineInstrBuilder
785 MachineIRBuilder::buildAtomicRMWMin(unsigned OldValRes, unsigned Addr,
786                                     unsigned Val, MachineMemOperand &MMO) {
787   return buildAtomicRMW(TargetOpcode::G_ATOMICRMW_MIN, OldValRes, Addr, Val,
788                         MMO);
789 }
790 MachineInstrBuilder
791 MachineIRBuilder::buildAtomicRMWUmax(unsigned OldValRes, unsigned Addr,
792                                      unsigned Val, MachineMemOperand &MMO) {
793   return buildAtomicRMW(TargetOpcode::G_ATOMICRMW_UMAX, OldValRes, Addr, Val,
794                         MMO);
795 }
796 MachineInstrBuilder
797 MachineIRBuilder::buildAtomicRMWUmin(unsigned OldValRes, unsigned Addr,
798                                      unsigned Val, MachineMemOperand &MMO) {
799   return buildAtomicRMW(TargetOpcode::G_ATOMICRMW_UMIN, OldValRes, Addr, Val,
800                         MMO);
801 }
802 
803 MachineInstrBuilder
804 MachineIRBuilder::buildBlockAddress(unsigned Res, const BlockAddress *BA) {
805 #ifndef NDEBUG
806   assert(getMRI()->getType(Res).isPointer() && "invalid res type");
807 #endif
808 
809   return buildInstr(TargetOpcode::G_BLOCK_ADDR).addDef(Res).addBlockAddress(BA);
810 }
811 
812 void MachineIRBuilder::validateTruncExt(const LLT &DstTy, const LLT &SrcTy,
813                                         bool IsExtend) {
814 #ifndef NDEBUG
815   if (DstTy.isVector()) {
816     assert(SrcTy.isVector() && "mismatched cast between vector and non-vector");
817     assert(SrcTy.getNumElements() == DstTy.getNumElements() &&
818            "different number of elements in a trunc/ext");
819   } else
820     assert(DstTy.isScalar() && SrcTy.isScalar() && "invalid extend/trunc");
821 
822   if (IsExtend)
823     assert(DstTy.getSizeInBits() > SrcTy.getSizeInBits() &&
824            "invalid narrowing extend");
825   else
826     assert(DstTy.getSizeInBits() < SrcTy.getSizeInBits() &&
827            "invalid widening trunc");
828 #endif
829 }
830 
831 void MachineIRBuilder::validateSelectOp(const LLT &ResTy, const LLT &TstTy,
832                                         const LLT &Op0Ty, const LLT &Op1Ty) {
833 #ifndef NDEBUG
834   assert((ResTy.isScalar() || ResTy.isVector() || ResTy.isPointer()) &&
835          "invalid operand type");
836   assert((ResTy == Op0Ty && ResTy == Op1Ty) && "type mismatch");
837   if (ResTy.isScalar() || ResTy.isPointer())
838     assert(TstTy.isScalar() && "type mismatch");
839   else
840     assert((TstTy.isScalar() ||
841             (TstTy.isVector() &&
842              TstTy.getNumElements() == Op0Ty.getNumElements())) &&
843            "type mismatch");
844 #endif
845 }
846 
847 MachineInstrBuilder MachineIRBuilder::buildInstr(unsigned Opc,
848                                                  ArrayRef<DstOp> DstOps,
849                                                  ArrayRef<SrcOp> SrcOps,
850                                                  Optional<unsigned> Flags) {
851   switch (Opc) {
852   default:
853     break;
854   case TargetOpcode::G_SELECT: {
855     assert(DstOps.size() == 1 && "Invalid select");
856     assert(SrcOps.size() == 3 && "Invalid select");
857     validateSelectOp(
858         DstOps[0].getLLTTy(*getMRI()), SrcOps[0].getLLTTy(*getMRI()),
859         SrcOps[1].getLLTTy(*getMRI()), SrcOps[2].getLLTTy(*getMRI()));
860     break;
861   }
862   case TargetOpcode::G_ADD:
863   case TargetOpcode::G_AND:
864   case TargetOpcode::G_MUL:
865   case TargetOpcode::G_OR:
866   case TargetOpcode::G_SUB:
867   case TargetOpcode::G_XOR:
868   case TargetOpcode::G_UDIV:
869   case TargetOpcode::G_SDIV:
870   case TargetOpcode::G_UREM:
871   case TargetOpcode::G_SREM: {
872     // All these are binary ops.
873     assert(DstOps.size() == 1 && "Invalid Dst");
874     assert(SrcOps.size() == 2 && "Invalid Srcs");
875     validateBinaryOp(DstOps[0].getLLTTy(*getMRI()),
876                      SrcOps[0].getLLTTy(*getMRI()),
877                      SrcOps[1].getLLTTy(*getMRI()));
878     break;
879   }
880   case TargetOpcode::G_SHL:
881   case TargetOpcode::G_ASHR:
882   case TargetOpcode::G_LSHR: {
883     assert(DstOps.size() == 1 && "Invalid Dst");
884     assert(SrcOps.size() == 2 && "Invalid Srcs");
885     validateShiftOp(DstOps[0].getLLTTy(*getMRI()),
886                     SrcOps[0].getLLTTy(*getMRI()),
887                     SrcOps[1].getLLTTy(*getMRI()));
888     break;
889   }
890   case TargetOpcode::G_SEXT:
891   case TargetOpcode::G_ZEXT:
892   case TargetOpcode::G_ANYEXT:
893     assert(DstOps.size() == 1 && "Invalid Dst");
894     assert(SrcOps.size() == 1 && "Invalid Srcs");
895     validateTruncExt(DstOps[0].getLLTTy(*getMRI()),
896                      SrcOps[0].getLLTTy(*getMRI()), true);
897     break;
898   case TargetOpcode::G_TRUNC:
899   case TargetOpcode::G_FPTRUNC: {
900     assert(DstOps.size() == 1 && "Invalid Dst");
901     assert(SrcOps.size() == 1 && "Invalid Srcs");
902     validateTruncExt(DstOps[0].getLLTTy(*getMRI()),
903                      SrcOps[0].getLLTTy(*getMRI()), false);
904     break;
905   }
906   case TargetOpcode::COPY:
907     assert(DstOps.size() == 1 && "Invalid Dst");
908     assert(SrcOps.size() == 1 && "Invalid Srcs");
909     assert(DstOps[0].getLLTTy(*getMRI()) == LLT() ||
910            SrcOps[0].getLLTTy(*getMRI()) == LLT() ||
911            DstOps[0].getLLTTy(*getMRI()) == SrcOps[0].getLLTTy(*getMRI()));
912     break;
913   case TargetOpcode::G_FCMP:
914   case TargetOpcode::G_ICMP: {
915     assert(DstOps.size() == 1 && "Invalid Dst Operands");
916     assert(SrcOps.size() == 3 && "Invalid Src Operands");
917     // For F/ICMP, the first src operand is the predicate, followed by
918     // the two comparands.
919     assert(SrcOps[0].getSrcOpKind() == SrcOp::SrcType::Ty_Predicate &&
920            "Expecting predicate");
921     assert([&]() -> bool {
922       CmpInst::Predicate Pred = SrcOps[0].getPredicate();
923       return Opc == TargetOpcode::G_ICMP ? CmpInst::isIntPredicate(Pred)
924                                          : CmpInst::isFPPredicate(Pred);
925     }() && "Invalid predicate");
926     assert(SrcOps[1].getLLTTy(*getMRI()) == SrcOps[2].getLLTTy(*getMRI()) &&
927            "Type mismatch");
928     assert([&]() -> bool {
929       LLT Op0Ty = SrcOps[1].getLLTTy(*getMRI());
930       LLT DstTy = DstOps[0].getLLTTy(*getMRI());
931       if (Op0Ty.isScalar() || Op0Ty.isPointer())
932         return DstTy.isScalar();
933       else
934         return DstTy.isVector() &&
935                DstTy.getNumElements() == Op0Ty.getNumElements();
936     }() && "Type Mismatch");
937     break;
938   }
939   case TargetOpcode::G_UNMERGE_VALUES: {
940     assert(!DstOps.empty() && "Invalid trivial sequence");
941     assert(SrcOps.size() == 1 && "Invalid src for Unmerge");
942     assert(std::all_of(DstOps.begin(), DstOps.end(),
943                        [&, this](const DstOp &Op) {
944                          return Op.getLLTTy(*getMRI()) ==
945                                 DstOps[0].getLLTTy(*getMRI());
946                        }) &&
947            "type mismatch in output list");
948     assert(DstOps.size() * DstOps[0].getLLTTy(*getMRI()).getSizeInBits() ==
949                SrcOps[0].getLLTTy(*getMRI()).getSizeInBits() &&
950            "input operands do not cover output register");
951     break;
952   }
953   case TargetOpcode::G_MERGE_VALUES: {
954     assert(!SrcOps.empty() && "invalid trivial sequence");
955     assert(DstOps.size() == 1 && "Invalid Dst");
956     assert(std::all_of(SrcOps.begin(), SrcOps.end(),
957                        [&, this](const SrcOp &Op) {
958                          return Op.getLLTTy(*getMRI()) ==
959                                 SrcOps[0].getLLTTy(*getMRI());
960                        }) &&
961            "type mismatch in input list");
962     assert(SrcOps.size() * SrcOps[0].getLLTTy(*getMRI()).getSizeInBits() ==
963                DstOps[0].getLLTTy(*getMRI()).getSizeInBits() &&
964            "input operands do not cover output register");
965     if (SrcOps.size() == 1)
966       return buildCast(DstOps[0], SrcOps[0]);
967     if (DstOps[0].getLLTTy(*getMRI()).isVector())
968       return buildInstr(TargetOpcode::G_CONCAT_VECTORS, DstOps, SrcOps);
969     break;
970   }
971   case TargetOpcode::G_EXTRACT_VECTOR_ELT: {
972     assert(DstOps.size() == 1 && "Invalid Dst size");
973     assert(SrcOps.size() == 2 && "Invalid Src size");
974     assert(SrcOps[0].getLLTTy(*getMRI()).isVector() && "Invalid operand type");
975     assert((DstOps[0].getLLTTy(*getMRI()).isScalar() ||
976             DstOps[0].getLLTTy(*getMRI()).isPointer()) &&
977            "Invalid operand type");
978     assert(SrcOps[1].getLLTTy(*getMRI()).isScalar() && "Invalid operand type");
979     assert(SrcOps[0].getLLTTy(*getMRI()).getElementType() ==
980                DstOps[0].getLLTTy(*getMRI()) &&
981            "Type mismatch");
982     break;
983   }
984   case TargetOpcode::G_INSERT_VECTOR_ELT: {
985     assert(DstOps.size() == 1 && "Invalid dst size");
986     assert(SrcOps.size() == 3 && "Invalid src size");
987     assert(DstOps[0].getLLTTy(*getMRI()).isVector() &&
988            SrcOps[0].getLLTTy(*getMRI()).isVector() && "Invalid operand type");
989     assert(DstOps[0].getLLTTy(*getMRI()).getElementType() ==
990                SrcOps[1].getLLTTy(*getMRI()) &&
991            "Type mismatch");
992     assert(SrcOps[2].getLLTTy(*getMRI()).isScalar() && "Invalid index");
993     assert(DstOps[0].getLLTTy(*getMRI()).getNumElements() ==
994                SrcOps[0].getLLTTy(*getMRI()).getNumElements() &&
995            "Type mismatch");
996     break;
997   }
998   case TargetOpcode::G_BUILD_VECTOR: {
999     assert((!SrcOps.empty() || SrcOps.size() < 2) &&
1000            "Must have at least 2 operands");
1001     assert(DstOps.size() == 1 && "Invalid DstOps");
1002     assert(DstOps[0].getLLTTy(*getMRI()).isVector() &&
1003            "Res type must be a vector");
1004     assert(std::all_of(SrcOps.begin(), SrcOps.end(),
1005                        [&, this](const SrcOp &Op) {
1006                          return Op.getLLTTy(*getMRI()) ==
1007                                 SrcOps[0].getLLTTy(*getMRI());
1008                        }) &&
1009            "type mismatch in input list");
1010     assert(SrcOps.size() * SrcOps[0].getLLTTy(*getMRI()).getSizeInBits() ==
1011                DstOps[0].getLLTTy(*getMRI()).getSizeInBits() &&
1012            "input scalars do not exactly cover the output vector register");
1013     break;
1014   }
1015   case TargetOpcode::G_BUILD_VECTOR_TRUNC: {
1016     assert((!SrcOps.empty() || SrcOps.size() < 2) &&
1017            "Must have at least 2 operands");
1018     assert(DstOps.size() == 1 && "Invalid DstOps");
1019     assert(DstOps[0].getLLTTy(*getMRI()).isVector() &&
1020            "Res type must be a vector");
1021     assert(std::all_of(SrcOps.begin(), SrcOps.end(),
1022                        [&, this](const SrcOp &Op) {
1023                          return Op.getLLTTy(*getMRI()) ==
1024                                 SrcOps[0].getLLTTy(*getMRI());
1025                        }) &&
1026            "type mismatch in input list");
1027     if (SrcOps[0].getLLTTy(*getMRI()).getSizeInBits() ==
1028         DstOps[0].getLLTTy(*getMRI()).getElementType().getSizeInBits())
1029       return buildInstr(TargetOpcode::G_BUILD_VECTOR, DstOps, SrcOps);
1030     break;
1031   }
1032   case TargetOpcode::G_CONCAT_VECTORS: {
1033     assert(DstOps.size() == 1 && "Invalid DstOps");
1034     assert((!SrcOps.empty() || SrcOps.size() < 2) &&
1035            "Must have at least 2 operands");
1036     assert(std::all_of(SrcOps.begin(), SrcOps.end(),
1037                        [&, this](const SrcOp &Op) {
1038                          return (Op.getLLTTy(*getMRI()).isVector() &&
1039                                  Op.getLLTTy(*getMRI()) ==
1040                                      SrcOps[0].getLLTTy(*getMRI()));
1041                        }) &&
1042            "type mismatch in input list");
1043     assert(SrcOps.size() * SrcOps[0].getLLTTy(*getMRI()).getSizeInBits() ==
1044                DstOps[0].getLLTTy(*getMRI()).getSizeInBits() &&
1045            "input vectors do not exactly cover the output vector register");
1046     break;
1047   }
1048   case TargetOpcode::G_UADDE: {
1049     assert(DstOps.size() == 2 && "Invalid no of dst operands");
1050     assert(SrcOps.size() == 3 && "Invalid no of src operands");
1051     assert(DstOps[0].getLLTTy(*getMRI()).isScalar() && "Invalid operand");
1052     assert((DstOps[0].getLLTTy(*getMRI()) == SrcOps[0].getLLTTy(*getMRI())) &&
1053            (DstOps[0].getLLTTy(*getMRI()) == SrcOps[1].getLLTTy(*getMRI())) &&
1054            "Invalid operand");
1055     assert(DstOps[1].getLLTTy(*getMRI()).isScalar() && "Invalid operand");
1056     assert(DstOps[1].getLLTTy(*getMRI()) == SrcOps[2].getLLTTy(*getMRI()) &&
1057            "type mismatch");
1058     break;
1059   }
1060   }
1061 
1062   auto MIB = buildInstr(Opc);
1063   for (const DstOp &Op : DstOps)
1064     Op.addDefToMIB(*getMRI(), MIB);
1065   for (const SrcOp &Op : SrcOps)
1066     Op.addSrcToMIB(MIB);
1067   if (Flags)
1068     MIB->setFlags(*Flags);
1069   return MIB;
1070 }
1071