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   auto Cst = buildConstant(ValueTy, Value);
219   return buildGEP(Res, Op0, Cst.getReg(0));
220 }
221 
222 MachineInstrBuilder MachineIRBuilder::buildPtrMask(unsigned Res, unsigned Op0,
223                                                    uint32_t NumBits) {
224   assert(getMRI()->getType(Res).isPointer() &&
225          getMRI()->getType(Res) == getMRI()->getType(Op0) && "type mismatch");
226 
227   return buildInstr(TargetOpcode::G_PTR_MASK)
228       .addDef(Res)
229       .addUse(Op0)
230       .addImm(NumBits);
231 }
232 
233 MachineInstrBuilder MachineIRBuilder::buildBr(MachineBasicBlock &Dest) {
234   return buildInstr(TargetOpcode::G_BR).addMBB(&Dest);
235 }
236 
237 MachineInstrBuilder MachineIRBuilder::buildBrIndirect(unsigned Tgt) {
238   assert(getMRI()->getType(Tgt).isPointer() && "invalid branch destination");
239   return buildInstr(TargetOpcode::G_BRINDIRECT).addUse(Tgt);
240 }
241 
242 MachineInstrBuilder MachineIRBuilder::buildCopy(const DstOp &Res,
243                                                 const SrcOp &Op) {
244   return buildInstr(TargetOpcode::COPY, Res, Op);
245 }
246 
247 MachineInstrBuilder MachineIRBuilder::buildConstant(const DstOp &Res,
248                                                     const ConstantInt &Val) {
249   LLT Ty = Res.getLLTTy(*getMRI());
250   LLT EltTy = Ty.getScalarType();
251   assert(EltTy.getScalarSizeInBits() == Val.getBitWidth() &&
252          "creating constant with the wrong size");
253 
254   if (Ty.isVector()) {
255     auto Const = buildInstr(TargetOpcode::G_CONSTANT)
256     .addDef(getMRI()->createGenericVirtualRegister(EltTy))
257     .addCImm(&Val);
258     return buildSplatVector(Res, Const);
259   }
260 
261   auto Const = buildInstr(TargetOpcode::G_CONSTANT);
262   Res.addDefToMIB(*getMRI(), Const);
263   Const.addCImm(&Val);
264   return Const;
265 }
266 
267 MachineInstrBuilder MachineIRBuilder::buildConstant(const DstOp &Res,
268                                                     int64_t Val) {
269   auto IntN = IntegerType::get(getMF().getFunction().getContext(),
270                                Res.getLLTTy(*getMRI()).getScalarSizeInBits());
271   ConstantInt *CI = ConstantInt::get(IntN, Val, true);
272   return buildConstant(Res, *CI);
273 }
274 
275 MachineInstrBuilder MachineIRBuilder::buildFConstant(const DstOp &Res,
276                                                      const ConstantFP &Val) {
277   LLT Ty = Res.getLLTTy(*getMRI());
278   LLT EltTy = Ty.getScalarType();
279 
280   assert(APFloat::getSizeInBits(Val.getValueAPF().getSemantics())
281          == EltTy.getSizeInBits() &&
282          "creating fconstant with the wrong size");
283 
284   assert(!Ty.isPointer() && "invalid operand type");
285 
286   if (Ty.isVector()) {
287     auto Const = buildInstr(TargetOpcode::G_FCONSTANT)
288     .addDef(getMRI()->createGenericVirtualRegister(EltTy))
289     .addFPImm(&Val);
290 
291     return buildSplatVector(Res, Const);
292   }
293 
294   auto Const = buildInstr(TargetOpcode::G_FCONSTANT);
295   Res.addDefToMIB(*getMRI(), Const);
296   Const.addFPImm(&Val);
297   return Const;
298 }
299 
300 MachineInstrBuilder MachineIRBuilder::buildConstant(const DstOp &Res,
301                                                     const APInt &Val) {
302   ConstantInt *CI = ConstantInt::get(getMF().getFunction().getContext(), Val);
303   return buildConstant(Res, *CI);
304 }
305 
306 MachineInstrBuilder MachineIRBuilder::buildFConstant(const DstOp &Res,
307                                                      double Val) {
308   LLT DstTy = Res.getLLTTy(*getMRI());
309   auto &Ctx = getMF().getFunction().getContext();
310   auto *CFP =
311       ConstantFP::get(Ctx, getAPFloatFromSize(Val, DstTy.getScalarSizeInBits()));
312   return buildFConstant(Res, *CFP);
313 }
314 
315 MachineInstrBuilder MachineIRBuilder::buildFConstant(const DstOp &Res,
316                                                      const APFloat &Val) {
317   auto &Ctx = getMF().getFunction().getContext();
318   auto *CFP = ConstantFP::get(Ctx, Val);
319   return buildFConstant(Res, *CFP);
320 }
321 
322 MachineInstrBuilder MachineIRBuilder::buildBrCond(unsigned Tst,
323                                                   MachineBasicBlock &Dest) {
324   assert(getMRI()->getType(Tst).isScalar() && "invalid operand type");
325 
326   return buildInstr(TargetOpcode::G_BRCOND).addUse(Tst).addMBB(&Dest);
327 }
328 
329 MachineInstrBuilder MachineIRBuilder::buildLoad(unsigned Res, unsigned Addr,
330                                                 MachineMemOperand &MMO) {
331   return buildLoadInstr(TargetOpcode::G_LOAD, Res, Addr, MMO);
332 }
333 
334 MachineInstrBuilder MachineIRBuilder::buildLoadInstr(unsigned Opcode,
335                                                      unsigned Res,
336                                                      unsigned Addr,
337                                                      MachineMemOperand &MMO) {
338   assert(getMRI()->getType(Res).isValid() && "invalid operand type");
339   assert(getMRI()->getType(Addr).isPointer() && "invalid operand type");
340 
341   return buildInstr(Opcode)
342       .addDef(Res)
343       .addUse(Addr)
344       .addMemOperand(&MMO);
345 }
346 
347 MachineInstrBuilder MachineIRBuilder::buildStore(unsigned Val, unsigned Addr,
348                                                  MachineMemOperand &MMO) {
349   assert(getMRI()->getType(Val).isValid() && "invalid operand type");
350   assert(getMRI()->getType(Addr).isPointer() && "invalid operand type");
351 
352   return buildInstr(TargetOpcode::G_STORE)
353       .addUse(Val)
354       .addUse(Addr)
355       .addMemOperand(&MMO);
356 }
357 
358 MachineInstrBuilder MachineIRBuilder::buildUAddo(const DstOp &Res,
359                                                  const DstOp &CarryOut,
360                                                  const SrcOp &Op0,
361                                                  const SrcOp &Op1) {
362   return buildInstr(TargetOpcode::G_UADDO, {Res, CarryOut}, {Op0, Op1});
363 }
364 
365 MachineInstrBuilder MachineIRBuilder::buildUAdde(const DstOp &Res,
366                                                  const DstOp &CarryOut,
367                                                  const SrcOp &Op0,
368                                                  const SrcOp &Op1,
369                                                  const SrcOp &CarryIn) {
370   return buildInstr(TargetOpcode::G_UADDE, {Res, CarryOut},
371                     {Op0, Op1, CarryIn});
372 }
373 
374 MachineInstrBuilder MachineIRBuilder::buildAnyExt(const DstOp &Res,
375                                                   const SrcOp &Op) {
376   return buildInstr(TargetOpcode::G_ANYEXT, Res, Op);
377 }
378 
379 MachineInstrBuilder MachineIRBuilder::buildSExt(const DstOp &Res,
380                                                 const SrcOp &Op) {
381   return buildInstr(TargetOpcode::G_SEXT, Res, Op);
382 }
383 
384 MachineInstrBuilder MachineIRBuilder::buildZExt(const DstOp &Res,
385                                                 const SrcOp &Op) {
386   return buildInstr(TargetOpcode::G_ZEXT, Res, Op);
387 }
388 
389 unsigned MachineIRBuilder::getBoolExtOp(bool IsVec, bool IsFP) const {
390   const auto *TLI = getMF().getSubtarget().getTargetLowering();
391   switch (TLI->getBooleanContents(IsVec, IsFP)) {
392   case TargetLoweringBase::ZeroOrNegativeOneBooleanContent:
393     return TargetOpcode::G_SEXT;
394   case TargetLoweringBase::ZeroOrOneBooleanContent:
395     return TargetOpcode::G_ZEXT;
396   default:
397     return TargetOpcode::G_ANYEXT;
398   }
399 }
400 
401 MachineInstrBuilder MachineIRBuilder::buildBoolExt(const DstOp &Res,
402                                                    const SrcOp &Op,
403                                                    bool IsFP) {
404   unsigned ExtOp = getBoolExtOp(getMRI()->getType(Op.getReg()).isVector(), IsFP);
405   return buildInstr(ExtOp, Res, Op);
406 }
407 
408 MachineInstrBuilder MachineIRBuilder::buildExtOrTrunc(unsigned ExtOpc,
409                                                       const DstOp &Res,
410                                                       const SrcOp &Op) {
411   assert((TargetOpcode::G_ANYEXT == ExtOpc || TargetOpcode::G_ZEXT == ExtOpc ||
412           TargetOpcode::G_SEXT == ExtOpc) &&
413          "Expecting Extending Opc");
414   assert(Res.getLLTTy(*getMRI()).isScalar() ||
415          Res.getLLTTy(*getMRI()).isVector());
416   assert(Res.getLLTTy(*getMRI()).isScalar() ==
417          Op.getLLTTy(*getMRI()).isScalar());
418 
419   unsigned Opcode = TargetOpcode::COPY;
420   if (Res.getLLTTy(*getMRI()).getSizeInBits() >
421       Op.getLLTTy(*getMRI()).getSizeInBits())
422     Opcode = ExtOpc;
423   else if (Res.getLLTTy(*getMRI()).getSizeInBits() <
424            Op.getLLTTy(*getMRI()).getSizeInBits())
425     Opcode = TargetOpcode::G_TRUNC;
426   else
427     assert(Res.getLLTTy(*getMRI()) == Op.getLLTTy(*getMRI()));
428 
429   return buildInstr(Opcode, Res, Op);
430 }
431 
432 MachineInstrBuilder MachineIRBuilder::buildSExtOrTrunc(const DstOp &Res,
433                                                        const SrcOp &Op) {
434   return buildExtOrTrunc(TargetOpcode::G_SEXT, Res, Op);
435 }
436 
437 MachineInstrBuilder MachineIRBuilder::buildZExtOrTrunc(const DstOp &Res,
438                                                        const SrcOp &Op) {
439   return buildExtOrTrunc(TargetOpcode::G_ZEXT, Res, Op);
440 }
441 
442 MachineInstrBuilder MachineIRBuilder::buildAnyExtOrTrunc(const DstOp &Res,
443                                                          const SrcOp &Op) {
444   return buildExtOrTrunc(TargetOpcode::G_ANYEXT, Res, Op);
445 }
446 
447 MachineInstrBuilder MachineIRBuilder::buildCast(const DstOp &Dst,
448                                                 const SrcOp &Src) {
449   LLT SrcTy = Src.getLLTTy(*getMRI());
450   LLT DstTy = Dst.getLLTTy(*getMRI());
451   if (SrcTy == DstTy)
452     return buildCopy(Dst, Src);
453 
454   unsigned Opcode;
455   if (SrcTy.isPointer() && DstTy.isScalar())
456     Opcode = TargetOpcode::G_PTRTOINT;
457   else if (DstTy.isPointer() && SrcTy.isScalar())
458     Opcode = TargetOpcode::G_INTTOPTR;
459   else {
460     assert(!SrcTy.isPointer() && !DstTy.isPointer() && "n G_ADDRCAST yet");
461     Opcode = TargetOpcode::G_BITCAST;
462   }
463 
464   return buildInstr(Opcode, Dst, Src);
465 }
466 
467 MachineInstrBuilder MachineIRBuilder::buildExtract(const DstOp &Dst,
468                                                    const SrcOp &Src,
469                                                    uint64_t Index) {
470   LLT SrcTy = Src.getLLTTy(*getMRI());
471   LLT DstTy = Dst.getLLTTy(*getMRI());
472 
473 #ifndef NDEBUG
474   assert(SrcTy.isValid() && "invalid operand type");
475   assert(DstTy.isValid() && "invalid operand type");
476   assert(Index + DstTy.getSizeInBits() <= SrcTy.getSizeInBits() &&
477          "extracting off end of register");
478 #endif
479 
480   if (DstTy.getSizeInBits() == SrcTy.getSizeInBits()) {
481     assert(Index == 0 && "insertion past the end of a register");
482     return buildCast(Dst, Src);
483   }
484 
485   auto Extract = buildInstr(TargetOpcode::G_EXTRACT);
486   Dst.addDefToMIB(*getMRI(), Extract);
487   Src.addSrcToMIB(Extract);
488   Extract.addImm(Index);
489   return Extract;
490 }
491 
492 void MachineIRBuilder::buildSequence(unsigned Res, ArrayRef<unsigned> Ops,
493                                      ArrayRef<uint64_t> Indices) {
494 #ifndef NDEBUG
495   assert(Ops.size() == Indices.size() && "incompatible args");
496   assert(!Ops.empty() && "invalid trivial sequence");
497   assert(std::is_sorted(Indices.begin(), Indices.end()) &&
498          "sequence offsets must be in ascending order");
499 
500   assert(getMRI()->getType(Res).isValid() && "invalid operand type");
501   for (auto Op : Ops)
502     assert(getMRI()->getType(Op).isValid() && "invalid operand type");
503 #endif
504 
505   LLT ResTy = getMRI()->getType(Res);
506   LLT OpTy = getMRI()->getType(Ops[0]);
507   unsigned OpSize = OpTy.getSizeInBits();
508   bool MaybeMerge = true;
509   for (unsigned i = 0; i < Ops.size(); ++i) {
510     if (getMRI()->getType(Ops[i]) != OpTy || Indices[i] != i * OpSize) {
511       MaybeMerge = false;
512       break;
513     }
514   }
515 
516   if (MaybeMerge && Ops.size() * OpSize == ResTy.getSizeInBits()) {
517     buildMerge(Res, Ops);
518     return;
519   }
520 
521   unsigned ResIn = getMRI()->createGenericVirtualRegister(ResTy);
522   buildUndef(ResIn);
523 
524   for (unsigned i = 0; i < Ops.size(); ++i) {
525     unsigned ResOut = i + 1 == Ops.size()
526                           ? Res
527                           : getMRI()->createGenericVirtualRegister(ResTy);
528     buildInsert(ResOut, ResIn, Ops[i], Indices[i]);
529     ResIn = ResOut;
530   }
531 }
532 
533 MachineInstrBuilder MachineIRBuilder::buildUndef(const DstOp &Res) {
534   return buildInstr(TargetOpcode::G_IMPLICIT_DEF, {Res}, {});
535 }
536 
537 MachineInstrBuilder MachineIRBuilder::buildMerge(const DstOp &Res,
538                                                  ArrayRef<unsigned> Ops) {
539   // Unfortunately to convert from ArrayRef<LLT> to ArrayRef<SrcOp>,
540   // we need some temporary storage for the DstOp objects. Here we use a
541   // sufficiently large SmallVector to not go through the heap.
542   SmallVector<SrcOp, 8> TmpVec(Ops.begin(), Ops.end());
543   return buildInstr(TargetOpcode::G_MERGE_VALUES, Res, TmpVec);
544 }
545 
546 MachineInstrBuilder MachineIRBuilder::buildUnmerge(ArrayRef<LLT> Res,
547                                                    const SrcOp &Op) {
548   // Unfortunately to convert from ArrayRef<LLT> to ArrayRef<DstOp>,
549   // we need some temporary storage for the DstOp objects. Here we use a
550   // sufficiently large SmallVector to not go through the heap.
551   SmallVector<DstOp, 8> TmpVec(Res.begin(), Res.end());
552   return buildInstr(TargetOpcode::G_UNMERGE_VALUES, TmpVec, Op);
553 }
554 
555 MachineInstrBuilder MachineIRBuilder::buildUnmerge(LLT Res,
556                                                    const SrcOp &Op) {
557   unsigned NumReg = Op.getLLTTy(*getMRI()).getSizeInBits() / Res.getSizeInBits();
558   SmallVector<unsigned, 8> TmpVec;
559   for (unsigned I = 0; I != NumReg; ++I)
560     TmpVec.push_back(getMRI()->createGenericVirtualRegister(Res));
561   return buildUnmerge(TmpVec, Op);
562 }
563 
564 MachineInstrBuilder MachineIRBuilder::buildUnmerge(ArrayRef<unsigned> Res,
565                                                    const SrcOp &Op) {
566   // Unfortunately to convert from ArrayRef<unsigned> to ArrayRef<DstOp>,
567   // we need some temporary storage for the DstOp objects. Here we use a
568   // sufficiently large SmallVector to not go through the heap.
569   SmallVector<DstOp, 8> TmpVec(Res.begin(), Res.end());
570   return buildInstr(TargetOpcode::G_UNMERGE_VALUES, TmpVec, Op);
571 }
572 
573 MachineInstrBuilder MachineIRBuilder::buildBuildVector(const DstOp &Res,
574                                                        ArrayRef<unsigned> Ops) {
575   // Unfortunately to convert from ArrayRef<unsigned> to ArrayRef<SrcOp>,
576   // we need some temporary storage for the DstOp objects. Here we use a
577   // sufficiently large SmallVector to not go through the heap.
578   SmallVector<SrcOp, 8> TmpVec(Ops.begin(), Ops.end());
579   return buildInstr(TargetOpcode::G_BUILD_VECTOR, Res, TmpVec);
580 }
581 
582 MachineInstrBuilder MachineIRBuilder::buildSplatVector(const DstOp &Res,
583                                                        const SrcOp &Src) {
584   SmallVector<SrcOp, 8> TmpVec(Res.getLLTTy(*getMRI()).getNumElements(), Src);
585   return buildInstr(TargetOpcode::G_BUILD_VECTOR, Res, TmpVec);
586 }
587 
588 MachineInstrBuilder
589 MachineIRBuilder::buildBuildVectorTrunc(const DstOp &Res,
590                                         ArrayRef<unsigned> Ops) {
591   // Unfortunately to convert from ArrayRef<unsigned> to ArrayRef<SrcOp>,
592   // we need some temporary storage for the DstOp objects. Here we use a
593   // sufficiently large SmallVector to not go through the heap.
594   SmallVector<SrcOp, 8> TmpVec(Ops.begin(), Ops.end());
595   return buildInstr(TargetOpcode::G_BUILD_VECTOR_TRUNC, Res, TmpVec);
596 }
597 
598 MachineInstrBuilder
599 MachineIRBuilder::buildConcatVectors(const DstOp &Res, ArrayRef<unsigned> Ops) {
600   // Unfortunately to convert from ArrayRef<unsigned> to ArrayRef<SrcOp>,
601   // we need some temporary storage for the DstOp objects. Here we use a
602   // sufficiently large SmallVector to not go through the heap.
603   SmallVector<SrcOp, 8> TmpVec(Ops.begin(), Ops.end());
604   return buildInstr(TargetOpcode::G_CONCAT_VECTORS, Res, TmpVec);
605 }
606 
607 MachineInstrBuilder MachineIRBuilder::buildInsert(unsigned Res, unsigned Src,
608                                                   unsigned Op, unsigned Index) {
609   assert(Index + getMRI()->getType(Op).getSizeInBits() <=
610              getMRI()->getType(Res).getSizeInBits() &&
611          "insertion past the end of a register");
612 
613   if (getMRI()->getType(Res).getSizeInBits() ==
614       getMRI()->getType(Op).getSizeInBits()) {
615     return buildCast(Res, Op);
616   }
617 
618   return buildInstr(TargetOpcode::G_INSERT)
619       .addDef(Res)
620       .addUse(Src)
621       .addUse(Op)
622       .addImm(Index);
623 }
624 
625 MachineInstrBuilder MachineIRBuilder::buildIntrinsic(Intrinsic::ID ID,
626                                                      ArrayRef<unsigned> ResultRegs,
627                                                      bool HasSideEffects) {
628   auto MIB =
629       buildInstr(HasSideEffects ? TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS
630                                 : TargetOpcode::G_INTRINSIC);
631   for (unsigned ResultReg : ResultRegs)
632     MIB.addDef(ResultReg);
633   MIB.addIntrinsicID(ID);
634   return MIB;
635 }
636 
637 MachineInstrBuilder MachineIRBuilder::buildIntrinsic(Intrinsic::ID ID,
638                                                      ArrayRef<DstOp> Results,
639                                                      bool HasSideEffects) {
640   auto MIB =
641       buildInstr(HasSideEffects ? TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS
642                                 : TargetOpcode::G_INTRINSIC);
643   for (DstOp Result : Results)
644     Result.addDefToMIB(*getMRI(), MIB);
645   MIB.addIntrinsicID(ID);
646   return MIB;
647 }
648 
649 MachineInstrBuilder MachineIRBuilder::buildTrunc(const DstOp &Res,
650                                                  const SrcOp &Op) {
651   return buildInstr(TargetOpcode::G_TRUNC, Res, Op);
652 }
653 
654 MachineInstrBuilder MachineIRBuilder::buildFPTrunc(const DstOp &Res,
655                                                    const SrcOp &Op) {
656   return buildInstr(TargetOpcode::G_FPTRUNC, Res, Op);
657 }
658 
659 MachineInstrBuilder MachineIRBuilder::buildICmp(CmpInst::Predicate Pred,
660                                                 const DstOp &Res,
661                                                 const SrcOp &Op0,
662                                                 const SrcOp &Op1) {
663   return buildInstr(TargetOpcode::G_ICMP, Res, {Pred, Op0, Op1});
664 }
665 
666 MachineInstrBuilder MachineIRBuilder::buildFCmp(CmpInst::Predicate Pred,
667                                                 const DstOp &Res,
668                                                 const SrcOp &Op0,
669                                                 const SrcOp &Op1) {
670 
671   return buildInstr(TargetOpcode::G_FCMP, Res, {Pred, Op0, Op1});
672 }
673 
674 MachineInstrBuilder MachineIRBuilder::buildSelect(const DstOp &Res,
675                                                   const SrcOp &Tst,
676                                                   const SrcOp &Op0,
677                                                   const SrcOp &Op1) {
678 
679   return buildInstr(TargetOpcode::G_SELECT, {Res}, {Tst, Op0, Op1});
680 }
681 
682 MachineInstrBuilder
683 MachineIRBuilder::buildInsertVectorElement(const DstOp &Res, const SrcOp &Val,
684                                            const SrcOp &Elt, const SrcOp &Idx) {
685   return buildInstr(TargetOpcode::G_INSERT_VECTOR_ELT, Res, {Val, Elt, Idx});
686 }
687 
688 MachineInstrBuilder
689 MachineIRBuilder::buildExtractVectorElement(const DstOp &Res, const SrcOp &Val,
690                                             const SrcOp &Idx) {
691   return buildInstr(TargetOpcode::G_EXTRACT_VECTOR_ELT, Res, {Val, Idx});
692 }
693 
694 MachineInstrBuilder MachineIRBuilder::buildAtomicCmpXchgWithSuccess(
695     unsigned OldValRes, unsigned SuccessRes, unsigned Addr, unsigned CmpVal,
696     unsigned NewVal, MachineMemOperand &MMO) {
697 #ifndef NDEBUG
698   LLT OldValResTy = getMRI()->getType(OldValRes);
699   LLT SuccessResTy = getMRI()->getType(SuccessRes);
700   LLT AddrTy = getMRI()->getType(Addr);
701   LLT CmpValTy = getMRI()->getType(CmpVal);
702   LLT NewValTy = getMRI()->getType(NewVal);
703   assert(OldValResTy.isScalar() && "invalid operand type");
704   assert(SuccessResTy.isScalar() && "invalid operand type");
705   assert(AddrTy.isPointer() && "invalid operand type");
706   assert(CmpValTy.isValid() && "invalid operand type");
707   assert(NewValTy.isValid() && "invalid operand type");
708   assert(OldValResTy == CmpValTy && "type mismatch");
709   assert(OldValResTy == NewValTy && "type mismatch");
710 #endif
711 
712   return buildInstr(TargetOpcode::G_ATOMIC_CMPXCHG_WITH_SUCCESS)
713       .addDef(OldValRes)
714       .addDef(SuccessRes)
715       .addUse(Addr)
716       .addUse(CmpVal)
717       .addUse(NewVal)
718       .addMemOperand(&MMO);
719 }
720 
721 MachineInstrBuilder
722 MachineIRBuilder::buildAtomicCmpXchg(unsigned OldValRes, unsigned Addr,
723                                      unsigned CmpVal, unsigned NewVal,
724                                      MachineMemOperand &MMO) {
725 #ifndef NDEBUG
726   LLT OldValResTy = getMRI()->getType(OldValRes);
727   LLT AddrTy = getMRI()->getType(Addr);
728   LLT CmpValTy = getMRI()->getType(CmpVal);
729   LLT NewValTy = getMRI()->getType(NewVal);
730   assert(OldValResTy.isScalar() && "invalid operand type");
731   assert(AddrTy.isPointer() && "invalid operand type");
732   assert(CmpValTy.isValid() && "invalid operand type");
733   assert(NewValTy.isValid() && "invalid operand type");
734   assert(OldValResTy == CmpValTy && "type mismatch");
735   assert(OldValResTy == NewValTy && "type mismatch");
736 #endif
737 
738   return buildInstr(TargetOpcode::G_ATOMIC_CMPXCHG)
739       .addDef(OldValRes)
740       .addUse(Addr)
741       .addUse(CmpVal)
742       .addUse(NewVal)
743       .addMemOperand(&MMO);
744 }
745 
746 MachineInstrBuilder MachineIRBuilder::buildAtomicRMW(unsigned Opcode,
747                                                      unsigned OldValRes,
748                                                      unsigned Addr,
749                                                      unsigned Val,
750                                                      MachineMemOperand &MMO) {
751 #ifndef NDEBUG
752   LLT OldValResTy = getMRI()->getType(OldValRes);
753   LLT AddrTy = getMRI()->getType(Addr);
754   LLT ValTy = getMRI()->getType(Val);
755   assert(OldValResTy.isScalar() && "invalid operand type");
756   assert(AddrTy.isPointer() && "invalid operand type");
757   assert(ValTy.isValid() && "invalid operand type");
758   assert(OldValResTy == ValTy && "type mismatch");
759 #endif
760 
761   return buildInstr(Opcode)
762       .addDef(OldValRes)
763       .addUse(Addr)
764       .addUse(Val)
765       .addMemOperand(&MMO);
766 }
767 
768 MachineInstrBuilder
769 MachineIRBuilder::buildAtomicRMWXchg(unsigned OldValRes, unsigned Addr,
770                                      unsigned Val, MachineMemOperand &MMO) {
771   return buildAtomicRMW(TargetOpcode::G_ATOMICRMW_XCHG, OldValRes, Addr, Val,
772                         MMO);
773 }
774 MachineInstrBuilder
775 MachineIRBuilder::buildAtomicRMWAdd(unsigned OldValRes, unsigned Addr,
776                                     unsigned Val, MachineMemOperand &MMO) {
777   return buildAtomicRMW(TargetOpcode::G_ATOMICRMW_ADD, OldValRes, Addr, Val,
778                         MMO);
779 }
780 MachineInstrBuilder
781 MachineIRBuilder::buildAtomicRMWSub(unsigned OldValRes, unsigned Addr,
782                                     unsigned Val, MachineMemOperand &MMO) {
783   return buildAtomicRMW(TargetOpcode::G_ATOMICRMW_SUB, OldValRes, Addr, Val,
784                         MMO);
785 }
786 MachineInstrBuilder
787 MachineIRBuilder::buildAtomicRMWAnd(unsigned OldValRes, unsigned Addr,
788                                     unsigned Val, MachineMemOperand &MMO) {
789   return buildAtomicRMW(TargetOpcode::G_ATOMICRMW_AND, OldValRes, Addr, Val,
790                         MMO);
791 }
792 MachineInstrBuilder
793 MachineIRBuilder::buildAtomicRMWNand(unsigned OldValRes, unsigned Addr,
794                                      unsigned Val, MachineMemOperand &MMO) {
795   return buildAtomicRMW(TargetOpcode::G_ATOMICRMW_NAND, OldValRes, Addr, Val,
796                         MMO);
797 }
798 MachineInstrBuilder MachineIRBuilder::buildAtomicRMWOr(unsigned OldValRes,
799                                                        unsigned Addr,
800                                                        unsigned Val,
801                                                        MachineMemOperand &MMO) {
802   return buildAtomicRMW(TargetOpcode::G_ATOMICRMW_OR, OldValRes, Addr, Val,
803                         MMO);
804 }
805 MachineInstrBuilder
806 MachineIRBuilder::buildAtomicRMWXor(unsigned OldValRes, unsigned Addr,
807                                     unsigned Val, MachineMemOperand &MMO) {
808   return buildAtomicRMW(TargetOpcode::G_ATOMICRMW_XOR, OldValRes, Addr, Val,
809                         MMO);
810 }
811 MachineInstrBuilder
812 MachineIRBuilder::buildAtomicRMWMax(unsigned OldValRes, unsigned Addr,
813                                     unsigned Val, MachineMemOperand &MMO) {
814   return buildAtomicRMW(TargetOpcode::G_ATOMICRMW_MAX, OldValRes, Addr, Val,
815                         MMO);
816 }
817 MachineInstrBuilder
818 MachineIRBuilder::buildAtomicRMWMin(unsigned OldValRes, unsigned Addr,
819                                     unsigned Val, MachineMemOperand &MMO) {
820   return buildAtomicRMW(TargetOpcode::G_ATOMICRMW_MIN, OldValRes, Addr, Val,
821                         MMO);
822 }
823 MachineInstrBuilder
824 MachineIRBuilder::buildAtomicRMWUmax(unsigned OldValRes, unsigned Addr,
825                                      unsigned Val, MachineMemOperand &MMO) {
826   return buildAtomicRMW(TargetOpcode::G_ATOMICRMW_UMAX, OldValRes, Addr, Val,
827                         MMO);
828 }
829 MachineInstrBuilder
830 MachineIRBuilder::buildAtomicRMWUmin(unsigned OldValRes, unsigned Addr,
831                                      unsigned Val, MachineMemOperand &MMO) {
832   return buildAtomicRMW(TargetOpcode::G_ATOMICRMW_UMIN, OldValRes, Addr, Val,
833                         MMO);
834 }
835 
836 MachineInstrBuilder
837 MachineIRBuilder::buildBlockAddress(unsigned Res, const BlockAddress *BA) {
838 #ifndef NDEBUG
839   assert(getMRI()->getType(Res).isPointer() && "invalid res type");
840 #endif
841 
842   return buildInstr(TargetOpcode::G_BLOCK_ADDR).addDef(Res).addBlockAddress(BA);
843 }
844 
845 void MachineIRBuilder::validateTruncExt(const LLT &DstTy, const LLT &SrcTy,
846                                         bool IsExtend) {
847 #ifndef NDEBUG
848   if (DstTy.isVector()) {
849     assert(SrcTy.isVector() && "mismatched cast between vector and non-vector");
850     assert(SrcTy.getNumElements() == DstTy.getNumElements() &&
851            "different number of elements in a trunc/ext");
852   } else
853     assert(DstTy.isScalar() && SrcTy.isScalar() && "invalid extend/trunc");
854 
855   if (IsExtend)
856     assert(DstTy.getSizeInBits() > SrcTy.getSizeInBits() &&
857            "invalid narrowing extend");
858   else
859     assert(DstTy.getSizeInBits() < SrcTy.getSizeInBits() &&
860            "invalid widening trunc");
861 #endif
862 }
863 
864 void MachineIRBuilder::validateSelectOp(const LLT &ResTy, const LLT &TstTy,
865                                         const LLT &Op0Ty, const LLT &Op1Ty) {
866 #ifndef NDEBUG
867   assert((ResTy.isScalar() || ResTy.isVector() || ResTy.isPointer()) &&
868          "invalid operand type");
869   assert((ResTy == Op0Ty && ResTy == Op1Ty) && "type mismatch");
870   if (ResTy.isScalar() || ResTy.isPointer())
871     assert(TstTy.isScalar() && "type mismatch");
872   else
873     assert((TstTy.isScalar() ||
874             (TstTy.isVector() &&
875              TstTy.getNumElements() == Op0Ty.getNumElements())) &&
876            "type mismatch");
877 #endif
878 }
879 
880 MachineInstrBuilder MachineIRBuilder::buildInstr(unsigned Opc,
881                                                  ArrayRef<DstOp> DstOps,
882                                                  ArrayRef<SrcOp> SrcOps,
883                                                  Optional<unsigned> Flags) {
884   switch (Opc) {
885   default:
886     break;
887   case TargetOpcode::G_SELECT: {
888     assert(DstOps.size() == 1 && "Invalid select");
889     assert(SrcOps.size() == 3 && "Invalid select");
890     validateSelectOp(
891         DstOps[0].getLLTTy(*getMRI()), SrcOps[0].getLLTTy(*getMRI()),
892         SrcOps[1].getLLTTy(*getMRI()), SrcOps[2].getLLTTy(*getMRI()));
893     break;
894   }
895   case TargetOpcode::G_ADD:
896   case TargetOpcode::G_AND:
897   case TargetOpcode::G_MUL:
898   case TargetOpcode::G_OR:
899   case TargetOpcode::G_SUB:
900   case TargetOpcode::G_XOR:
901   case TargetOpcode::G_UDIV:
902   case TargetOpcode::G_SDIV:
903   case TargetOpcode::G_UREM:
904   case TargetOpcode::G_SREM:
905   case TargetOpcode::G_SMIN:
906   case TargetOpcode::G_SMAX:
907   case TargetOpcode::G_UMIN:
908   case TargetOpcode::G_UMAX: {
909     // All these are binary ops.
910     assert(DstOps.size() == 1 && "Invalid Dst");
911     assert(SrcOps.size() == 2 && "Invalid Srcs");
912     validateBinaryOp(DstOps[0].getLLTTy(*getMRI()),
913                      SrcOps[0].getLLTTy(*getMRI()),
914                      SrcOps[1].getLLTTy(*getMRI()));
915     break;
916   }
917   case TargetOpcode::G_SHL:
918   case TargetOpcode::G_ASHR:
919   case TargetOpcode::G_LSHR: {
920     assert(DstOps.size() == 1 && "Invalid Dst");
921     assert(SrcOps.size() == 2 && "Invalid Srcs");
922     validateShiftOp(DstOps[0].getLLTTy(*getMRI()),
923                     SrcOps[0].getLLTTy(*getMRI()),
924                     SrcOps[1].getLLTTy(*getMRI()));
925     break;
926   }
927   case TargetOpcode::G_SEXT:
928   case TargetOpcode::G_ZEXT:
929   case TargetOpcode::G_ANYEXT:
930     assert(DstOps.size() == 1 && "Invalid Dst");
931     assert(SrcOps.size() == 1 && "Invalid Srcs");
932     validateTruncExt(DstOps[0].getLLTTy(*getMRI()),
933                      SrcOps[0].getLLTTy(*getMRI()), true);
934     break;
935   case TargetOpcode::G_TRUNC:
936   case TargetOpcode::G_FPTRUNC: {
937     assert(DstOps.size() == 1 && "Invalid Dst");
938     assert(SrcOps.size() == 1 && "Invalid Srcs");
939     validateTruncExt(DstOps[0].getLLTTy(*getMRI()),
940                      SrcOps[0].getLLTTy(*getMRI()), false);
941     break;
942   }
943   case TargetOpcode::COPY:
944     assert(DstOps.size() == 1 && "Invalid Dst");
945     // If the caller wants to add a subreg source it has to be done separately
946     // so we may not have any SrcOps at this point yet.
947     break;
948   case TargetOpcode::G_FCMP:
949   case TargetOpcode::G_ICMP: {
950     assert(DstOps.size() == 1 && "Invalid Dst Operands");
951     assert(SrcOps.size() == 3 && "Invalid Src Operands");
952     // For F/ICMP, the first src operand is the predicate, followed by
953     // the two comparands.
954     assert(SrcOps[0].getSrcOpKind() == SrcOp::SrcType::Ty_Predicate &&
955            "Expecting predicate");
956     assert([&]() -> bool {
957       CmpInst::Predicate Pred = SrcOps[0].getPredicate();
958       return Opc == TargetOpcode::G_ICMP ? CmpInst::isIntPredicate(Pred)
959                                          : CmpInst::isFPPredicate(Pred);
960     }() && "Invalid predicate");
961     assert(SrcOps[1].getLLTTy(*getMRI()) == SrcOps[2].getLLTTy(*getMRI()) &&
962            "Type mismatch");
963     assert([&]() -> bool {
964       LLT Op0Ty = SrcOps[1].getLLTTy(*getMRI());
965       LLT DstTy = DstOps[0].getLLTTy(*getMRI());
966       if (Op0Ty.isScalar() || Op0Ty.isPointer())
967         return DstTy.isScalar();
968       else
969         return DstTy.isVector() &&
970                DstTy.getNumElements() == Op0Ty.getNumElements();
971     }() && "Type Mismatch");
972     break;
973   }
974   case TargetOpcode::G_UNMERGE_VALUES: {
975     assert(!DstOps.empty() && "Invalid trivial sequence");
976     assert(SrcOps.size() == 1 && "Invalid src for Unmerge");
977     assert(std::all_of(DstOps.begin(), DstOps.end(),
978                        [&, this](const DstOp &Op) {
979                          return Op.getLLTTy(*getMRI()) ==
980                                 DstOps[0].getLLTTy(*getMRI());
981                        }) &&
982            "type mismatch in output list");
983     assert(DstOps.size() * DstOps[0].getLLTTy(*getMRI()).getSizeInBits() ==
984                SrcOps[0].getLLTTy(*getMRI()).getSizeInBits() &&
985            "input operands do not cover output register");
986     break;
987   }
988   case TargetOpcode::G_MERGE_VALUES: {
989     assert(!SrcOps.empty() && "invalid trivial sequence");
990     assert(DstOps.size() == 1 && "Invalid Dst");
991     assert(std::all_of(SrcOps.begin(), SrcOps.end(),
992                        [&, this](const SrcOp &Op) {
993                          return Op.getLLTTy(*getMRI()) ==
994                                 SrcOps[0].getLLTTy(*getMRI());
995                        }) &&
996            "type mismatch in input list");
997     assert(SrcOps.size() * SrcOps[0].getLLTTy(*getMRI()).getSizeInBits() ==
998                DstOps[0].getLLTTy(*getMRI()).getSizeInBits() &&
999            "input operands do not cover output register");
1000     if (SrcOps.size() == 1)
1001       return buildCast(DstOps[0], SrcOps[0]);
1002     if (DstOps[0].getLLTTy(*getMRI()).isVector())
1003       return buildInstr(TargetOpcode::G_CONCAT_VECTORS, DstOps, SrcOps);
1004     break;
1005   }
1006   case TargetOpcode::G_EXTRACT_VECTOR_ELT: {
1007     assert(DstOps.size() == 1 && "Invalid Dst size");
1008     assert(SrcOps.size() == 2 && "Invalid Src size");
1009     assert(SrcOps[0].getLLTTy(*getMRI()).isVector() && "Invalid operand type");
1010     assert((DstOps[0].getLLTTy(*getMRI()).isScalar() ||
1011             DstOps[0].getLLTTy(*getMRI()).isPointer()) &&
1012            "Invalid operand type");
1013     assert(SrcOps[1].getLLTTy(*getMRI()).isScalar() && "Invalid operand type");
1014     assert(SrcOps[0].getLLTTy(*getMRI()).getElementType() ==
1015                DstOps[0].getLLTTy(*getMRI()) &&
1016            "Type mismatch");
1017     break;
1018   }
1019   case TargetOpcode::G_INSERT_VECTOR_ELT: {
1020     assert(DstOps.size() == 1 && "Invalid dst size");
1021     assert(SrcOps.size() == 3 && "Invalid src size");
1022     assert(DstOps[0].getLLTTy(*getMRI()).isVector() &&
1023            SrcOps[0].getLLTTy(*getMRI()).isVector() && "Invalid operand type");
1024     assert(DstOps[0].getLLTTy(*getMRI()).getElementType() ==
1025                SrcOps[1].getLLTTy(*getMRI()) &&
1026            "Type mismatch");
1027     assert(SrcOps[2].getLLTTy(*getMRI()).isScalar() && "Invalid index");
1028     assert(DstOps[0].getLLTTy(*getMRI()).getNumElements() ==
1029                SrcOps[0].getLLTTy(*getMRI()).getNumElements() &&
1030            "Type mismatch");
1031     break;
1032   }
1033   case TargetOpcode::G_BUILD_VECTOR: {
1034     assert((!SrcOps.empty() || SrcOps.size() < 2) &&
1035            "Must have at least 2 operands");
1036     assert(DstOps.size() == 1 && "Invalid DstOps");
1037     assert(DstOps[0].getLLTTy(*getMRI()).isVector() &&
1038            "Res type must be a vector");
1039     assert(std::all_of(SrcOps.begin(), SrcOps.end(),
1040                        [&, this](const SrcOp &Op) {
1041                          return Op.getLLTTy(*getMRI()) ==
1042                                 SrcOps[0].getLLTTy(*getMRI());
1043                        }) &&
1044            "type mismatch in input list");
1045     assert(SrcOps.size() * SrcOps[0].getLLTTy(*getMRI()).getSizeInBits() ==
1046                DstOps[0].getLLTTy(*getMRI()).getSizeInBits() &&
1047            "input scalars do not exactly cover the output vector register");
1048     break;
1049   }
1050   case TargetOpcode::G_BUILD_VECTOR_TRUNC: {
1051     assert((!SrcOps.empty() || SrcOps.size() < 2) &&
1052            "Must have at least 2 operands");
1053     assert(DstOps.size() == 1 && "Invalid DstOps");
1054     assert(DstOps[0].getLLTTy(*getMRI()).isVector() &&
1055            "Res type must be a vector");
1056     assert(std::all_of(SrcOps.begin(), SrcOps.end(),
1057                        [&, this](const SrcOp &Op) {
1058                          return Op.getLLTTy(*getMRI()) ==
1059                                 SrcOps[0].getLLTTy(*getMRI());
1060                        }) &&
1061            "type mismatch in input list");
1062     if (SrcOps[0].getLLTTy(*getMRI()).getSizeInBits() ==
1063         DstOps[0].getLLTTy(*getMRI()).getElementType().getSizeInBits())
1064       return buildInstr(TargetOpcode::G_BUILD_VECTOR, DstOps, SrcOps);
1065     break;
1066   }
1067   case TargetOpcode::G_CONCAT_VECTORS: {
1068     assert(DstOps.size() == 1 && "Invalid DstOps");
1069     assert((!SrcOps.empty() || SrcOps.size() < 2) &&
1070            "Must have at least 2 operands");
1071     assert(std::all_of(SrcOps.begin(), SrcOps.end(),
1072                        [&, this](const SrcOp &Op) {
1073                          return (Op.getLLTTy(*getMRI()).isVector() &&
1074                                  Op.getLLTTy(*getMRI()) ==
1075                                      SrcOps[0].getLLTTy(*getMRI()));
1076                        }) &&
1077            "type mismatch in input list");
1078     assert(SrcOps.size() * SrcOps[0].getLLTTy(*getMRI()).getSizeInBits() ==
1079                DstOps[0].getLLTTy(*getMRI()).getSizeInBits() &&
1080            "input vectors do not exactly cover the output vector register");
1081     break;
1082   }
1083   case TargetOpcode::G_UADDE: {
1084     assert(DstOps.size() == 2 && "Invalid no of dst operands");
1085     assert(SrcOps.size() == 3 && "Invalid no of src operands");
1086     assert(DstOps[0].getLLTTy(*getMRI()).isScalar() && "Invalid operand");
1087     assert((DstOps[0].getLLTTy(*getMRI()) == SrcOps[0].getLLTTy(*getMRI())) &&
1088            (DstOps[0].getLLTTy(*getMRI()) == SrcOps[1].getLLTTy(*getMRI())) &&
1089            "Invalid operand");
1090     assert(DstOps[1].getLLTTy(*getMRI()).isScalar() && "Invalid operand");
1091     assert(DstOps[1].getLLTTy(*getMRI()) == SrcOps[2].getLLTTy(*getMRI()) &&
1092            "type mismatch");
1093     break;
1094   }
1095   }
1096 
1097   auto MIB = buildInstr(Opc);
1098   for (const DstOp &Op : DstOps)
1099     Op.addDefToMIB(*getMRI(), MIB);
1100   for (const SrcOp &Op : SrcOps)
1101     Op.addSrcToMIB(MIB);
1102   if (Flags)
1103     MIB->setFlags(*Flags);
1104   return MIB;
1105 }
1106