xref: /llvm-project/llvm/lib/CodeGen/GlobalISel/Utils.cpp (revision 4235e44d4c37ca738c74def05da8caf124d2464e)
1 //===- llvm/CodeGen/GlobalISel/Utils.cpp -------------------------*- 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 This file implements the utility functions used by the GlobalISel
9 /// pipeline.
10 //===----------------------------------------------------------------------===//
11 
12 #include "llvm/CodeGen/GlobalISel/Utils.h"
13 #include "llvm/ADT/APFloat.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/CodeGen/CodeGenCommonISel.h"
16 #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
17 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
18 #include "llvm/CodeGen/GlobalISel/GenericMachineInstrs.h"
19 #include "llvm/CodeGen/GlobalISel/LostDebugLocObserver.h"
20 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
21 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/MachineSizeOpts.h"
27 #include "llvm/CodeGen/RegisterBankInfo.h"
28 #include "llvm/CodeGen/StackProtector.h"
29 #include "llvm/CodeGen/TargetInstrInfo.h"
30 #include "llvm/CodeGen/TargetLowering.h"
31 #include "llvm/CodeGen/TargetPassConfig.h"
32 #include "llvm/CodeGen/TargetRegisterInfo.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Transforms/Utils/SizeOpts.h"
36 #include <numeric>
37 #include <optional>
38 
39 #define DEBUG_TYPE "globalisel-utils"
40 
41 using namespace llvm;
42 using namespace MIPatternMatch;
43 
44 Register llvm::constrainRegToClass(MachineRegisterInfo &MRI,
45                                    const TargetInstrInfo &TII,
46                                    const RegisterBankInfo &RBI, Register Reg,
47                                    const TargetRegisterClass &RegClass) {
48   if (!RBI.constrainGenericRegister(Reg, RegClass, MRI))
49     return MRI.createVirtualRegister(&RegClass);
50 
51   return Reg;
52 }
53 
54 Register llvm::constrainOperandRegClass(
55     const MachineFunction &MF, const TargetRegisterInfo &TRI,
56     MachineRegisterInfo &MRI, const TargetInstrInfo &TII,
57     const RegisterBankInfo &RBI, MachineInstr &InsertPt,
58     const TargetRegisterClass &RegClass, MachineOperand &RegMO) {
59   Register Reg = RegMO.getReg();
60   // Assume physical registers are properly constrained.
61   assert(Reg.isVirtual() && "PhysReg not implemented");
62 
63   // Save the old register class to check whether
64   // the change notifications will be required.
65   // TODO: A better approach would be to pass
66   // the observers to constrainRegToClass().
67   auto *OldRegClass = MRI.getRegClassOrNull(Reg);
68   Register ConstrainedReg = constrainRegToClass(MRI, TII, RBI, Reg, RegClass);
69   // If we created a new virtual register because the class is not compatible
70   // then create a copy between the new and the old register.
71   if (ConstrainedReg != Reg) {
72     MachineBasicBlock::iterator InsertIt(&InsertPt);
73     MachineBasicBlock &MBB = *InsertPt.getParent();
74     // FIXME: The copy needs to have the classes constrained for its operands.
75     // Use operand's regbank to get the class for old register (Reg).
76     if (RegMO.isUse()) {
77       BuildMI(MBB, InsertIt, InsertPt.getDebugLoc(),
78               TII.get(TargetOpcode::COPY), ConstrainedReg)
79           .addReg(Reg);
80     } else {
81       assert(RegMO.isDef() && "Must be a definition");
82       BuildMI(MBB, std::next(InsertIt), InsertPt.getDebugLoc(),
83               TII.get(TargetOpcode::COPY), Reg)
84           .addReg(ConstrainedReg);
85     }
86     if (GISelChangeObserver *Observer = MF.getObserver()) {
87       Observer->changingInstr(*RegMO.getParent());
88     }
89     RegMO.setReg(ConstrainedReg);
90     if (GISelChangeObserver *Observer = MF.getObserver()) {
91       Observer->changedInstr(*RegMO.getParent());
92     }
93   } else if (OldRegClass != MRI.getRegClassOrNull(Reg)) {
94     if (GISelChangeObserver *Observer = MF.getObserver()) {
95       if (!RegMO.isDef()) {
96         MachineInstr *RegDef = MRI.getVRegDef(Reg);
97         Observer->changedInstr(*RegDef);
98       }
99       Observer->changingAllUsesOfReg(MRI, Reg);
100       Observer->finishedChangingAllUsesOfReg();
101     }
102   }
103   return ConstrainedReg;
104 }
105 
106 Register llvm::constrainOperandRegClass(
107     const MachineFunction &MF, const TargetRegisterInfo &TRI,
108     MachineRegisterInfo &MRI, const TargetInstrInfo &TII,
109     const RegisterBankInfo &RBI, MachineInstr &InsertPt, const MCInstrDesc &II,
110     MachineOperand &RegMO, unsigned OpIdx) {
111   Register Reg = RegMO.getReg();
112   // Assume physical registers are properly constrained.
113   assert(Reg.isVirtual() && "PhysReg not implemented");
114 
115   const TargetRegisterClass *OpRC = TII.getRegClass(II, OpIdx, &TRI, MF);
116   // Some of the target independent instructions, like COPY, may not impose any
117   // register class constraints on some of their operands: If it's a use, we can
118   // skip constraining as the instruction defining the register would constrain
119   // it.
120 
121   if (OpRC) {
122     // Obtain the RC from incoming regbank if it is a proper sub-class. Operands
123     // can have multiple regbanks for a superclass that combine different
124     // register types (E.g., AMDGPU's VGPR and AGPR). The regbank ambiguity
125     // resolved by targets during regbankselect should not be overridden.
126     if (const auto *SubRC = TRI.getCommonSubClass(
127             OpRC, TRI.getConstrainedRegClassForOperand(RegMO, MRI)))
128       OpRC = SubRC;
129 
130     OpRC = TRI.getAllocatableClass(OpRC);
131   }
132 
133   if (!OpRC) {
134     assert((!isTargetSpecificOpcode(II.getOpcode()) || RegMO.isUse()) &&
135            "Register class constraint is required unless either the "
136            "instruction is target independent or the operand is a use");
137     // FIXME: Just bailing out like this here could be not enough, unless we
138     // expect the users of this function to do the right thing for PHIs and
139     // COPY:
140     //   v1 = COPY v0
141     //   v2 = COPY v1
142     // v1 here may end up not being constrained at all. Please notice that to
143     // reproduce the issue we likely need a destination pattern of a selection
144     // rule producing such extra copies, not just an input GMIR with them as
145     // every existing target using selectImpl handles copies before calling it
146     // and they never reach this function.
147     return Reg;
148   }
149   return constrainOperandRegClass(MF, TRI, MRI, TII, RBI, InsertPt, *OpRC,
150                                   RegMO);
151 }
152 
153 bool llvm::constrainSelectedInstRegOperands(MachineInstr &I,
154                                             const TargetInstrInfo &TII,
155                                             const TargetRegisterInfo &TRI,
156                                             const RegisterBankInfo &RBI) {
157   assert(!isPreISelGenericOpcode(I.getOpcode()) &&
158          "A selected instruction is expected");
159   MachineBasicBlock &MBB = *I.getParent();
160   MachineFunction &MF = *MBB.getParent();
161   MachineRegisterInfo &MRI = MF.getRegInfo();
162 
163   for (unsigned OpI = 0, OpE = I.getNumExplicitOperands(); OpI != OpE; ++OpI) {
164     MachineOperand &MO = I.getOperand(OpI);
165 
166     // There's nothing to be done on non-register operands.
167     if (!MO.isReg())
168       continue;
169 
170     LLVM_DEBUG(dbgs() << "Converting operand: " << MO << '\n');
171     assert(MO.isReg() && "Unsupported non-reg operand");
172 
173     Register Reg = MO.getReg();
174     // Physical registers don't need to be constrained.
175     if (Reg.isPhysical())
176       continue;
177 
178     // Register operands with a value of 0 (e.g. predicate operands) don't need
179     // to be constrained.
180     if (Reg == 0)
181       continue;
182 
183     // If the operand is a vreg, we should constrain its regclass, and only
184     // insert COPYs if that's impossible.
185     // constrainOperandRegClass does that for us.
186     constrainOperandRegClass(MF, TRI, MRI, TII, RBI, I, I.getDesc(), MO, OpI);
187 
188     // Tie uses to defs as indicated in MCInstrDesc if this hasn't already been
189     // done.
190     if (MO.isUse()) {
191       int DefIdx = I.getDesc().getOperandConstraint(OpI, MCOI::TIED_TO);
192       if (DefIdx != -1 && !I.isRegTiedToUseOperand(DefIdx))
193         I.tieOperands(DefIdx, OpI);
194     }
195   }
196   return true;
197 }
198 
199 bool llvm::canReplaceReg(Register DstReg, Register SrcReg,
200                          MachineRegisterInfo &MRI) {
201   // Give up if either DstReg or SrcReg  is a physical register.
202   if (DstReg.isPhysical() || SrcReg.isPhysical())
203     return false;
204   // Give up if the types don't match.
205   if (MRI.getType(DstReg) != MRI.getType(SrcReg))
206     return false;
207   // Replace if either DstReg has no constraints or the register
208   // constraints match.
209   const auto &DstRBC = MRI.getRegClassOrRegBank(DstReg);
210   if (!DstRBC || DstRBC == MRI.getRegClassOrRegBank(SrcReg))
211     return true;
212 
213   // Otherwise match if the Src is already a regclass that is covered by the Dst
214   // RegBank.
215   return DstRBC.is<const RegisterBank *>() && MRI.getRegClassOrNull(SrcReg) &&
216          DstRBC.get<const RegisterBank *>()->covers(
217              *MRI.getRegClassOrNull(SrcReg));
218 }
219 
220 bool llvm::isTriviallyDead(const MachineInstr &MI,
221                            const MachineRegisterInfo &MRI) {
222   // FIXME: This logical is mostly duplicated with
223   // DeadMachineInstructionElim::isDead. Why is LOCAL_ESCAPE not considered in
224   // MachineInstr::isLabel?
225 
226   // Don't delete frame allocation labels.
227   if (MI.getOpcode() == TargetOpcode::LOCAL_ESCAPE)
228     return false;
229   // LIFETIME markers should be preserved even if they seem dead.
230   if (MI.getOpcode() == TargetOpcode::LIFETIME_START ||
231       MI.getOpcode() == TargetOpcode::LIFETIME_END)
232     return false;
233 
234   // If we can move an instruction, we can remove it.  Otherwise, it has
235   // a side-effect of some sort.
236   bool SawStore = false;
237   if (!MI.isSafeToMove(/*AA=*/nullptr, SawStore) && !MI.isPHI())
238     return false;
239 
240   // Instructions without side-effects are dead iff they only define dead vregs.
241   for (const auto &MO : MI.all_defs()) {
242     Register Reg = MO.getReg();
243     if (Reg.isPhysical() || !MRI.use_nodbg_empty(Reg))
244       return false;
245   }
246   return true;
247 }
248 
249 static void reportGISelDiagnostic(DiagnosticSeverity Severity,
250                                   MachineFunction &MF,
251                                   const TargetPassConfig &TPC,
252                                   MachineOptimizationRemarkEmitter &MORE,
253                                   MachineOptimizationRemarkMissed &R) {
254   bool IsFatal = Severity == DS_Error &&
255                  TPC.isGlobalISelAbortEnabled();
256   // Print the function name explicitly if we don't have a debug location (which
257   // makes the diagnostic less useful) or if we're going to emit a raw error.
258   if (!R.getLocation().isValid() || IsFatal)
259     R << (" (in function: " + MF.getName() + ")").str();
260 
261   if (IsFatal)
262     report_fatal_error(Twine(R.getMsg()));
263   else
264     MORE.emit(R);
265 }
266 
267 void llvm::reportGISelWarning(MachineFunction &MF, const TargetPassConfig &TPC,
268                               MachineOptimizationRemarkEmitter &MORE,
269                               MachineOptimizationRemarkMissed &R) {
270   reportGISelDiagnostic(DS_Warning, MF, TPC, MORE, R);
271 }
272 
273 void llvm::reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC,
274                               MachineOptimizationRemarkEmitter &MORE,
275                               MachineOptimizationRemarkMissed &R) {
276   MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
277   reportGISelDiagnostic(DS_Error, MF, TPC, MORE, R);
278 }
279 
280 void llvm::reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC,
281                               MachineOptimizationRemarkEmitter &MORE,
282                               const char *PassName, StringRef Msg,
283                               const MachineInstr &MI) {
284   MachineOptimizationRemarkMissed R(PassName, "GISelFailure: ",
285                                     MI.getDebugLoc(), MI.getParent());
286   R << Msg;
287   // Printing MI is expensive;  only do it if expensive remarks are enabled.
288   if (TPC.isGlobalISelAbortEnabled() || MORE.allowExtraAnalysis(PassName))
289     R << ": " << ore::MNV("Inst", MI);
290   reportGISelFailure(MF, TPC, MORE, R);
291 }
292 
293 std::optional<APInt> llvm::getIConstantVRegVal(Register VReg,
294                                                const MachineRegisterInfo &MRI) {
295   std::optional<ValueAndVReg> ValAndVReg = getIConstantVRegValWithLookThrough(
296       VReg, MRI, /*LookThroughInstrs*/ false);
297   assert((!ValAndVReg || ValAndVReg->VReg == VReg) &&
298          "Value found while looking through instrs");
299   if (!ValAndVReg)
300     return std::nullopt;
301   return ValAndVReg->Value;
302 }
303 
304 std::optional<int64_t>
305 llvm::getIConstantVRegSExtVal(Register VReg, const MachineRegisterInfo &MRI) {
306   std::optional<APInt> Val = getIConstantVRegVal(VReg, MRI);
307   if (Val && Val->getBitWidth() <= 64)
308     return Val->getSExtValue();
309   return std::nullopt;
310 }
311 
312 namespace {
313 
314 typedef std::function<bool(const MachineInstr *)> IsOpcodeFn;
315 typedef std::function<std::optional<APInt>(const MachineInstr *MI)> GetAPCstFn;
316 
317 std::optional<ValueAndVReg> getConstantVRegValWithLookThrough(
318     Register VReg, const MachineRegisterInfo &MRI, IsOpcodeFn IsConstantOpcode,
319     GetAPCstFn getAPCstValue, bool LookThroughInstrs = true,
320     bool LookThroughAnyExt = false) {
321   SmallVector<std::pair<unsigned, unsigned>, 4> SeenOpcodes;
322   MachineInstr *MI;
323 
324   while ((MI = MRI.getVRegDef(VReg)) && !IsConstantOpcode(MI) &&
325          LookThroughInstrs) {
326     switch (MI->getOpcode()) {
327     case TargetOpcode::G_ANYEXT:
328       if (!LookThroughAnyExt)
329         return std::nullopt;
330       [[fallthrough]];
331     case TargetOpcode::G_TRUNC:
332     case TargetOpcode::G_SEXT:
333     case TargetOpcode::G_ZEXT:
334       SeenOpcodes.push_back(std::make_pair(
335           MI->getOpcode(),
336           MRI.getType(MI->getOperand(0).getReg()).getSizeInBits()));
337       VReg = MI->getOperand(1).getReg();
338       break;
339     case TargetOpcode::COPY:
340       VReg = MI->getOperand(1).getReg();
341       if (VReg.isPhysical())
342         return std::nullopt;
343       break;
344     case TargetOpcode::G_INTTOPTR:
345       VReg = MI->getOperand(1).getReg();
346       break;
347     default:
348       return std::nullopt;
349     }
350   }
351   if (!MI || !IsConstantOpcode(MI))
352     return std::nullopt;
353 
354   std::optional<APInt> MaybeVal = getAPCstValue(MI);
355   if (!MaybeVal)
356     return std::nullopt;
357   APInt &Val = *MaybeVal;
358   while (!SeenOpcodes.empty()) {
359     std::pair<unsigned, unsigned> OpcodeAndSize = SeenOpcodes.pop_back_val();
360     switch (OpcodeAndSize.first) {
361     case TargetOpcode::G_TRUNC:
362       Val = Val.trunc(OpcodeAndSize.second);
363       break;
364     case TargetOpcode::G_ANYEXT:
365     case TargetOpcode::G_SEXT:
366       Val = Val.sext(OpcodeAndSize.second);
367       break;
368     case TargetOpcode::G_ZEXT:
369       Val = Val.zext(OpcodeAndSize.second);
370       break;
371     }
372   }
373 
374   return ValueAndVReg{Val, VReg};
375 }
376 
377 bool isIConstant(const MachineInstr *MI) {
378   if (!MI)
379     return false;
380   return MI->getOpcode() == TargetOpcode::G_CONSTANT;
381 }
382 
383 bool isFConstant(const MachineInstr *MI) {
384   if (!MI)
385     return false;
386   return MI->getOpcode() == TargetOpcode::G_FCONSTANT;
387 }
388 
389 bool isAnyConstant(const MachineInstr *MI) {
390   if (!MI)
391     return false;
392   unsigned Opc = MI->getOpcode();
393   return Opc == TargetOpcode::G_CONSTANT || Opc == TargetOpcode::G_FCONSTANT;
394 }
395 
396 std::optional<APInt> getCImmAsAPInt(const MachineInstr *MI) {
397   const MachineOperand &CstVal = MI->getOperand(1);
398   if (CstVal.isCImm())
399     return CstVal.getCImm()->getValue();
400   return std::nullopt;
401 }
402 
403 std::optional<APInt> getCImmOrFPImmAsAPInt(const MachineInstr *MI) {
404   const MachineOperand &CstVal = MI->getOperand(1);
405   if (CstVal.isCImm())
406     return CstVal.getCImm()->getValue();
407   if (CstVal.isFPImm())
408     return CstVal.getFPImm()->getValueAPF().bitcastToAPInt();
409   return std::nullopt;
410 }
411 
412 } // end anonymous namespace
413 
414 std::optional<ValueAndVReg> llvm::getIConstantVRegValWithLookThrough(
415     Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs) {
416   return getConstantVRegValWithLookThrough(VReg, MRI, isIConstant,
417                                            getCImmAsAPInt, LookThroughInstrs);
418 }
419 
420 std::optional<ValueAndVReg> llvm::getAnyConstantVRegValWithLookThrough(
421     Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs,
422     bool LookThroughAnyExt) {
423   return getConstantVRegValWithLookThrough(
424       VReg, MRI, isAnyConstant, getCImmOrFPImmAsAPInt, LookThroughInstrs,
425       LookThroughAnyExt);
426 }
427 
428 std::optional<FPValueAndVReg> llvm::getFConstantVRegValWithLookThrough(
429     Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs) {
430   auto Reg = getConstantVRegValWithLookThrough(
431       VReg, MRI, isFConstant, getCImmOrFPImmAsAPInt, LookThroughInstrs);
432   if (!Reg)
433     return std::nullopt;
434   return FPValueAndVReg{getConstantFPVRegVal(Reg->VReg, MRI)->getValueAPF(),
435                         Reg->VReg};
436 }
437 
438 const ConstantFP *
439 llvm::getConstantFPVRegVal(Register VReg, const MachineRegisterInfo &MRI) {
440   MachineInstr *MI = MRI.getVRegDef(VReg);
441   if (TargetOpcode::G_FCONSTANT != MI->getOpcode())
442     return nullptr;
443   return MI->getOperand(1).getFPImm();
444 }
445 
446 std::optional<DefinitionAndSourceRegister>
447 llvm::getDefSrcRegIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI) {
448   Register DefSrcReg = Reg;
449   auto *DefMI = MRI.getVRegDef(Reg);
450   auto DstTy = MRI.getType(DefMI->getOperand(0).getReg());
451   if (!DstTy.isValid())
452     return std::nullopt;
453   unsigned Opc = DefMI->getOpcode();
454   while (Opc == TargetOpcode::COPY || isPreISelGenericOptimizationHint(Opc)) {
455     Register SrcReg = DefMI->getOperand(1).getReg();
456     auto SrcTy = MRI.getType(SrcReg);
457     if (!SrcTy.isValid())
458       break;
459     DefMI = MRI.getVRegDef(SrcReg);
460     DefSrcReg = SrcReg;
461     Opc = DefMI->getOpcode();
462   }
463   return DefinitionAndSourceRegister{DefMI, DefSrcReg};
464 }
465 
466 MachineInstr *llvm::getDefIgnoringCopies(Register Reg,
467                                          const MachineRegisterInfo &MRI) {
468   std::optional<DefinitionAndSourceRegister> DefSrcReg =
469       getDefSrcRegIgnoringCopies(Reg, MRI);
470   return DefSrcReg ? DefSrcReg->MI : nullptr;
471 }
472 
473 Register llvm::getSrcRegIgnoringCopies(Register Reg,
474                                        const MachineRegisterInfo &MRI) {
475   std::optional<DefinitionAndSourceRegister> DefSrcReg =
476       getDefSrcRegIgnoringCopies(Reg, MRI);
477   return DefSrcReg ? DefSrcReg->Reg : Register();
478 }
479 
480 void llvm::extractParts(Register Reg, LLT Ty, int NumParts,
481                         SmallVectorImpl<Register> &VRegs,
482                         MachineIRBuilder &MIRBuilder,
483                         MachineRegisterInfo &MRI) {
484   for (int i = 0; i < NumParts; ++i)
485     VRegs.push_back(MRI.createGenericVirtualRegister(Ty));
486   MIRBuilder.buildUnmerge(VRegs, Reg);
487 }
488 
489 bool llvm::extractParts(Register Reg, LLT RegTy, LLT MainTy, LLT &LeftoverTy,
490                         SmallVectorImpl<Register> &VRegs,
491                         SmallVectorImpl<Register> &LeftoverRegs,
492                         MachineIRBuilder &MIRBuilder,
493                         MachineRegisterInfo &MRI) {
494   assert(!LeftoverTy.isValid() && "this is an out argument");
495 
496   unsigned RegSize = RegTy.getSizeInBits();
497   unsigned MainSize = MainTy.getSizeInBits();
498   unsigned NumParts = RegSize / MainSize;
499   unsigned LeftoverSize = RegSize - NumParts * MainSize;
500 
501   // Use an unmerge when possible.
502   if (LeftoverSize == 0) {
503     for (unsigned I = 0; I < NumParts; ++I)
504       VRegs.push_back(MRI.createGenericVirtualRegister(MainTy));
505     MIRBuilder.buildUnmerge(VRegs, Reg);
506     return true;
507   }
508 
509   // Try to use unmerge for irregular vector split where possible
510   // For example when splitting a <6 x i32> into <4 x i32> with <2 x i32>
511   // leftover, it becomes:
512   //  <2 x i32> %2, <2 x i32>%3, <2 x i32> %4 = G_UNMERGE_VALUE <6 x i32> %1
513   //  <4 x i32> %5 = G_CONCAT_VECTOR <2 x i32> %2, <2 x i32> %3
514   if (RegTy.isVector() && MainTy.isVector()) {
515     unsigned RegNumElts = RegTy.getNumElements();
516     unsigned MainNumElts = MainTy.getNumElements();
517     unsigned LeftoverNumElts = RegNumElts % MainNumElts;
518     // If can unmerge to LeftoverTy, do it
519     if (MainNumElts % LeftoverNumElts == 0 &&
520         RegNumElts % LeftoverNumElts == 0 &&
521         RegTy.getScalarSizeInBits() == MainTy.getScalarSizeInBits() &&
522         LeftoverNumElts > 1) {
523       LeftoverTy =
524           LLT::fixed_vector(LeftoverNumElts, RegTy.getScalarSizeInBits());
525 
526       // Unmerge the SrcReg to LeftoverTy vectors
527       SmallVector<Register, 4> UnmergeValues;
528       extractParts(Reg, LeftoverTy, RegNumElts / LeftoverNumElts, UnmergeValues,
529                    MIRBuilder, MRI);
530 
531       // Find how many LeftoverTy makes one MainTy
532       unsigned LeftoverPerMain = MainNumElts / LeftoverNumElts;
533       unsigned NumOfLeftoverVal =
534           ((RegNumElts % MainNumElts) / LeftoverNumElts);
535 
536       // Create as many MainTy as possible using unmerged value
537       SmallVector<Register, 4> MergeValues;
538       for (unsigned I = 0; I < UnmergeValues.size() - NumOfLeftoverVal; I++) {
539         MergeValues.push_back(UnmergeValues[I]);
540         if (MergeValues.size() == LeftoverPerMain) {
541           VRegs.push_back(
542               MIRBuilder.buildMergeLikeInstr(MainTy, MergeValues).getReg(0));
543           MergeValues.clear();
544         }
545       }
546       // Populate LeftoverRegs with the leftovers
547       for (unsigned I = UnmergeValues.size() - NumOfLeftoverVal;
548            I < UnmergeValues.size(); I++) {
549         LeftoverRegs.push_back(UnmergeValues[I]);
550       }
551       return true;
552     }
553   }
554   // Perform irregular split. Leftover is last element of RegPieces.
555   if (MainTy.isVector()) {
556     SmallVector<Register, 8> RegPieces;
557     extractVectorParts(Reg, MainTy.getNumElements(), RegPieces, MIRBuilder,
558                        MRI);
559     for (unsigned i = 0; i < RegPieces.size() - 1; ++i)
560       VRegs.push_back(RegPieces[i]);
561     LeftoverRegs.push_back(RegPieces[RegPieces.size() - 1]);
562     LeftoverTy = MRI.getType(LeftoverRegs[0]);
563     return true;
564   }
565 
566   LeftoverTy = LLT::scalar(LeftoverSize);
567   // For irregular sizes, extract the individual parts.
568   for (unsigned I = 0; I != NumParts; ++I) {
569     Register NewReg = MRI.createGenericVirtualRegister(MainTy);
570     VRegs.push_back(NewReg);
571     MIRBuilder.buildExtract(NewReg, Reg, MainSize * I);
572   }
573 
574   for (unsigned Offset = MainSize * NumParts; Offset < RegSize;
575        Offset += LeftoverSize) {
576     Register NewReg = MRI.createGenericVirtualRegister(LeftoverTy);
577     LeftoverRegs.push_back(NewReg);
578     MIRBuilder.buildExtract(NewReg, Reg, Offset);
579   }
580 
581   return true;
582 }
583 
584 void llvm::extractVectorParts(Register Reg, unsigned NumElts,
585                               SmallVectorImpl<Register> &VRegs,
586                               MachineIRBuilder &MIRBuilder,
587                               MachineRegisterInfo &MRI) {
588   LLT RegTy = MRI.getType(Reg);
589   assert(RegTy.isVector() && "Expected a vector type");
590 
591   LLT EltTy = RegTy.getElementType();
592   LLT NarrowTy = (NumElts == 1) ? EltTy : LLT::fixed_vector(NumElts, EltTy);
593   unsigned RegNumElts = RegTy.getNumElements();
594   unsigned LeftoverNumElts = RegNumElts % NumElts;
595   unsigned NumNarrowTyPieces = RegNumElts / NumElts;
596 
597   // Perfect split without leftover
598   if (LeftoverNumElts == 0)
599     return extractParts(Reg, NarrowTy, NumNarrowTyPieces, VRegs, MIRBuilder,
600                         MRI);
601 
602   // Irregular split. Provide direct access to all elements for artifact
603   // combiner using unmerge to elements. Then build vectors with NumElts
604   // elements. Remaining element(s) will be (used to build vector) Leftover.
605   SmallVector<Register, 8> Elts;
606   extractParts(Reg, EltTy, RegNumElts, Elts, MIRBuilder, MRI);
607 
608   unsigned Offset = 0;
609   // Requested sub-vectors of NarrowTy.
610   for (unsigned i = 0; i < NumNarrowTyPieces; ++i, Offset += NumElts) {
611     ArrayRef<Register> Pieces(&Elts[Offset], NumElts);
612     VRegs.push_back(MIRBuilder.buildMergeLikeInstr(NarrowTy, Pieces).getReg(0));
613   }
614 
615   // Leftover element(s).
616   if (LeftoverNumElts == 1) {
617     VRegs.push_back(Elts[Offset]);
618   } else {
619     LLT LeftoverTy = LLT::fixed_vector(LeftoverNumElts, EltTy);
620     ArrayRef<Register> Pieces(&Elts[Offset], LeftoverNumElts);
621     VRegs.push_back(
622         MIRBuilder.buildMergeLikeInstr(LeftoverTy, Pieces).getReg(0));
623   }
624 }
625 
626 MachineInstr *llvm::getOpcodeDef(unsigned Opcode, Register Reg,
627                                  const MachineRegisterInfo &MRI) {
628   MachineInstr *DefMI = getDefIgnoringCopies(Reg, MRI);
629   return DefMI && DefMI->getOpcode() == Opcode ? DefMI : nullptr;
630 }
631 
632 APFloat llvm::getAPFloatFromSize(double Val, unsigned Size) {
633   if (Size == 32)
634     return APFloat(float(Val));
635   if (Size == 64)
636     return APFloat(Val);
637   if (Size != 16)
638     llvm_unreachable("Unsupported FPConstant size");
639   bool Ignored;
640   APFloat APF(Val);
641   APF.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &Ignored);
642   return APF;
643 }
644 
645 std::optional<APInt> llvm::ConstantFoldBinOp(unsigned Opcode,
646                                              const Register Op1,
647                                              const Register Op2,
648                                              const MachineRegisterInfo &MRI) {
649   auto MaybeOp2Cst = getAnyConstantVRegValWithLookThrough(Op2, MRI, false);
650   if (!MaybeOp2Cst)
651     return std::nullopt;
652 
653   auto MaybeOp1Cst = getAnyConstantVRegValWithLookThrough(Op1, MRI, false);
654   if (!MaybeOp1Cst)
655     return std::nullopt;
656 
657   const APInt &C1 = MaybeOp1Cst->Value;
658   const APInt &C2 = MaybeOp2Cst->Value;
659   switch (Opcode) {
660   default:
661     break;
662   case TargetOpcode::G_ADD:
663     return C1 + C2;
664   case TargetOpcode::G_PTR_ADD:
665     // Types can be of different width here.
666     // Result needs to be the same width as C1, so trunc or sext C2.
667     return C1 + C2.sextOrTrunc(C1.getBitWidth());
668   case TargetOpcode::G_AND:
669     return C1 & C2;
670   case TargetOpcode::G_ASHR:
671     return C1.ashr(C2);
672   case TargetOpcode::G_LSHR:
673     return C1.lshr(C2);
674   case TargetOpcode::G_MUL:
675     return C1 * C2;
676   case TargetOpcode::G_OR:
677     return C1 | C2;
678   case TargetOpcode::G_SHL:
679     return C1 << C2;
680   case TargetOpcode::G_SUB:
681     return C1 - C2;
682   case TargetOpcode::G_XOR:
683     return C1 ^ C2;
684   case TargetOpcode::G_UDIV:
685     if (!C2.getBoolValue())
686       break;
687     return C1.udiv(C2);
688   case TargetOpcode::G_SDIV:
689     if (!C2.getBoolValue())
690       break;
691     return C1.sdiv(C2);
692   case TargetOpcode::G_UREM:
693     if (!C2.getBoolValue())
694       break;
695     return C1.urem(C2);
696   case TargetOpcode::G_SREM:
697     if (!C2.getBoolValue())
698       break;
699     return C1.srem(C2);
700   case TargetOpcode::G_SMIN:
701     return APIntOps::smin(C1, C2);
702   case TargetOpcode::G_SMAX:
703     return APIntOps::smax(C1, C2);
704   case TargetOpcode::G_UMIN:
705     return APIntOps::umin(C1, C2);
706   case TargetOpcode::G_UMAX:
707     return APIntOps::umax(C1, C2);
708   }
709 
710   return std::nullopt;
711 }
712 
713 std::optional<APFloat>
714 llvm::ConstantFoldFPBinOp(unsigned Opcode, const Register Op1,
715                           const Register Op2, const MachineRegisterInfo &MRI) {
716   const ConstantFP *Op2Cst = getConstantFPVRegVal(Op2, MRI);
717   if (!Op2Cst)
718     return std::nullopt;
719 
720   const ConstantFP *Op1Cst = getConstantFPVRegVal(Op1, MRI);
721   if (!Op1Cst)
722     return std::nullopt;
723 
724   APFloat C1 = Op1Cst->getValueAPF();
725   const APFloat &C2 = Op2Cst->getValueAPF();
726   switch (Opcode) {
727   case TargetOpcode::G_FADD:
728     C1.add(C2, APFloat::rmNearestTiesToEven);
729     return C1;
730   case TargetOpcode::G_FSUB:
731     C1.subtract(C2, APFloat::rmNearestTiesToEven);
732     return C1;
733   case TargetOpcode::G_FMUL:
734     C1.multiply(C2, APFloat::rmNearestTiesToEven);
735     return C1;
736   case TargetOpcode::G_FDIV:
737     C1.divide(C2, APFloat::rmNearestTiesToEven);
738     return C1;
739   case TargetOpcode::G_FREM:
740     C1.mod(C2);
741     return C1;
742   case TargetOpcode::G_FCOPYSIGN:
743     C1.copySign(C2);
744     return C1;
745   case TargetOpcode::G_FMINNUM:
746     return minnum(C1, C2);
747   case TargetOpcode::G_FMAXNUM:
748     return maxnum(C1, C2);
749   case TargetOpcode::G_FMINIMUM:
750     return minimum(C1, C2);
751   case TargetOpcode::G_FMAXIMUM:
752     return maximum(C1, C2);
753   case TargetOpcode::G_FMINNUM_IEEE:
754   case TargetOpcode::G_FMAXNUM_IEEE:
755     // FIXME: These operations were unfortunately named. fminnum/fmaxnum do not
756     // follow the IEEE behavior for signaling nans and follow libm's fmin/fmax,
757     // and currently there isn't a nice wrapper in APFloat for the version with
758     // correct snan handling.
759     break;
760   default:
761     break;
762   }
763 
764   return std::nullopt;
765 }
766 
767 SmallVector<APInt>
768 llvm::ConstantFoldVectorBinop(unsigned Opcode, const Register Op1,
769                               const Register Op2,
770                               const MachineRegisterInfo &MRI) {
771   auto *SrcVec2 = getOpcodeDef<GBuildVector>(Op2, MRI);
772   if (!SrcVec2)
773     return SmallVector<APInt>();
774 
775   auto *SrcVec1 = getOpcodeDef<GBuildVector>(Op1, MRI);
776   if (!SrcVec1)
777     return SmallVector<APInt>();
778 
779   SmallVector<APInt> FoldedElements;
780   for (unsigned Idx = 0, E = SrcVec1->getNumSources(); Idx < E; ++Idx) {
781     auto MaybeCst = ConstantFoldBinOp(Opcode, SrcVec1->getSourceReg(Idx),
782                                       SrcVec2->getSourceReg(Idx), MRI);
783     if (!MaybeCst)
784       return SmallVector<APInt>();
785     FoldedElements.push_back(*MaybeCst);
786   }
787   return FoldedElements;
788 }
789 
790 bool llvm::isKnownNeverNaN(Register Val, const MachineRegisterInfo &MRI,
791                            bool SNaN) {
792   const MachineInstr *DefMI = MRI.getVRegDef(Val);
793   if (!DefMI)
794     return false;
795 
796   const TargetMachine& TM = DefMI->getMF()->getTarget();
797   if (DefMI->getFlag(MachineInstr::FmNoNans) || TM.Options.NoNaNsFPMath)
798     return true;
799 
800   // If the value is a constant, we can obviously see if it is a NaN or not.
801   if (const ConstantFP *FPVal = getConstantFPVRegVal(Val, MRI)) {
802     return !FPVal->getValueAPF().isNaN() ||
803            (SNaN && !FPVal->getValueAPF().isSignaling());
804   }
805 
806   if (DefMI->getOpcode() == TargetOpcode::G_BUILD_VECTOR) {
807     for (const auto &Op : DefMI->uses())
808       if (!isKnownNeverNaN(Op.getReg(), MRI, SNaN))
809         return false;
810     return true;
811   }
812 
813   switch (DefMI->getOpcode()) {
814   default:
815     break;
816   case TargetOpcode::G_FADD:
817   case TargetOpcode::G_FSUB:
818   case TargetOpcode::G_FMUL:
819   case TargetOpcode::G_FDIV:
820   case TargetOpcode::G_FREM:
821   case TargetOpcode::G_FSIN:
822   case TargetOpcode::G_FCOS:
823   case TargetOpcode::G_FMA:
824   case TargetOpcode::G_FMAD:
825     if (SNaN)
826       return true;
827 
828     // TODO: Need isKnownNeverInfinity
829     return false;
830   case TargetOpcode::G_FMINNUM_IEEE:
831   case TargetOpcode::G_FMAXNUM_IEEE: {
832     if (SNaN)
833       return true;
834     // This can return a NaN if either operand is an sNaN, or if both operands
835     // are NaN.
836     return (isKnownNeverNaN(DefMI->getOperand(1).getReg(), MRI) &&
837             isKnownNeverSNaN(DefMI->getOperand(2).getReg(), MRI)) ||
838            (isKnownNeverSNaN(DefMI->getOperand(1).getReg(), MRI) &&
839             isKnownNeverNaN(DefMI->getOperand(2).getReg(), MRI));
840   }
841   case TargetOpcode::G_FMINNUM:
842   case TargetOpcode::G_FMAXNUM: {
843     // Only one needs to be known not-nan, since it will be returned if the
844     // other ends up being one.
845     return isKnownNeverNaN(DefMI->getOperand(1).getReg(), MRI, SNaN) ||
846            isKnownNeverNaN(DefMI->getOperand(2).getReg(), MRI, SNaN);
847   }
848   }
849 
850   if (SNaN) {
851     // FP operations quiet. For now, just handle the ones inserted during
852     // legalization.
853     switch (DefMI->getOpcode()) {
854     case TargetOpcode::G_FPEXT:
855     case TargetOpcode::G_FPTRUNC:
856     case TargetOpcode::G_FCANONICALIZE:
857       return true;
858     default:
859       return false;
860     }
861   }
862 
863   return false;
864 }
865 
866 Align llvm::inferAlignFromPtrInfo(MachineFunction &MF,
867                                   const MachinePointerInfo &MPO) {
868   auto PSV = dyn_cast_if_present<const PseudoSourceValue *>(MPO.V);
869   if (auto FSPV = dyn_cast_or_null<FixedStackPseudoSourceValue>(PSV)) {
870     MachineFrameInfo &MFI = MF.getFrameInfo();
871     return commonAlignment(MFI.getObjectAlign(FSPV->getFrameIndex()),
872                            MPO.Offset);
873   }
874 
875   if (const Value *V = dyn_cast_if_present<const Value *>(MPO.V)) {
876     const Module *M = MF.getFunction().getParent();
877     return V->getPointerAlignment(M->getDataLayout());
878   }
879 
880   return Align(1);
881 }
882 
883 Register llvm::getFunctionLiveInPhysReg(MachineFunction &MF,
884                                         const TargetInstrInfo &TII,
885                                         MCRegister PhysReg,
886                                         const TargetRegisterClass &RC,
887                                         const DebugLoc &DL, LLT RegTy) {
888   MachineBasicBlock &EntryMBB = MF.front();
889   MachineRegisterInfo &MRI = MF.getRegInfo();
890   Register LiveIn = MRI.getLiveInVirtReg(PhysReg);
891   if (LiveIn) {
892     MachineInstr *Def = MRI.getVRegDef(LiveIn);
893     if (Def) {
894       // FIXME: Should the verifier check this is in the entry block?
895       assert(Def->getParent() == &EntryMBB && "live-in copy not in entry block");
896       return LiveIn;
897     }
898 
899     // It's possible the incoming argument register and copy was added during
900     // lowering, but later deleted due to being/becoming dead. If this happens,
901     // re-insert the copy.
902   } else {
903     // The live in register was not present, so add it.
904     LiveIn = MF.addLiveIn(PhysReg, &RC);
905     if (RegTy.isValid())
906       MRI.setType(LiveIn, RegTy);
907   }
908 
909   BuildMI(EntryMBB, EntryMBB.begin(), DL, TII.get(TargetOpcode::COPY), LiveIn)
910     .addReg(PhysReg);
911   if (!EntryMBB.isLiveIn(PhysReg))
912     EntryMBB.addLiveIn(PhysReg);
913   return LiveIn;
914 }
915 
916 std::optional<APInt> llvm::ConstantFoldExtOp(unsigned Opcode,
917                                              const Register Op1, uint64_t Imm,
918                                              const MachineRegisterInfo &MRI) {
919   auto MaybeOp1Cst = getIConstantVRegVal(Op1, MRI);
920   if (MaybeOp1Cst) {
921     switch (Opcode) {
922     default:
923       break;
924     case TargetOpcode::G_SEXT_INREG: {
925       LLT Ty = MRI.getType(Op1);
926       return MaybeOp1Cst->trunc(Imm).sext(Ty.getScalarSizeInBits());
927     }
928     }
929   }
930   return std::nullopt;
931 }
932 
933 std::optional<APInt> llvm::ConstantFoldCastOp(unsigned Opcode, LLT DstTy,
934                                               const Register Op0,
935                                               const MachineRegisterInfo &MRI) {
936   std::optional<APInt> Val = getIConstantVRegVal(Op0, MRI);
937   if (!Val)
938     return Val;
939 
940   const unsigned DstSize = DstTy.getScalarSizeInBits();
941 
942   switch (Opcode) {
943   case TargetOpcode::G_SEXT:
944     return Val->sext(DstSize);
945   case TargetOpcode::G_ZEXT:
946   case TargetOpcode::G_ANYEXT:
947     // TODO: DAG considers target preference when constant folding any_extend.
948     return Val->zext(DstSize);
949   default:
950     break;
951   }
952 
953   llvm_unreachable("unexpected cast opcode to constant fold");
954 }
955 
956 std::optional<APFloat>
957 llvm::ConstantFoldIntToFloat(unsigned Opcode, LLT DstTy, Register Src,
958                              const MachineRegisterInfo &MRI) {
959   assert(Opcode == TargetOpcode::G_SITOFP || Opcode == TargetOpcode::G_UITOFP);
960   if (auto MaybeSrcVal = getIConstantVRegVal(Src, MRI)) {
961     APFloat DstVal(getFltSemanticForLLT(DstTy));
962     DstVal.convertFromAPInt(*MaybeSrcVal, Opcode == TargetOpcode::G_SITOFP,
963                             APFloat::rmNearestTiesToEven);
964     return DstVal;
965   }
966   return std::nullopt;
967 }
968 
969 std::optional<SmallVector<unsigned>>
970 llvm::ConstantFoldCTLZ(Register Src, const MachineRegisterInfo &MRI) {
971   LLT Ty = MRI.getType(Src);
972   SmallVector<unsigned> FoldedCTLZs;
973   auto tryFoldScalar = [&](Register R) -> std::optional<unsigned> {
974     auto MaybeCst = getIConstantVRegVal(R, MRI);
975     if (!MaybeCst)
976       return std::nullopt;
977     return MaybeCst->countl_zero();
978   };
979   if (Ty.isVector()) {
980     // Try to constant fold each element.
981     auto *BV = getOpcodeDef<GBuildVector>(Src, MRI);
982     if (!BV)
983       return std::nullopt;
984     for (unsigned SrcIdx = 0; SrcIdx < BV->getNumSources(); ++SrcIdx) {
985       if (auto MaybeFold = tryFoldScalar(BV->getSourceReg(SrcIdx))) {
986         FoldedCTLZs.emplace_back(*MaybeFold);
987         continue;
988       }
989       return std::nullopt;
990     }
991     return FoldedCTLZs;
992   }
993   if (auto MaybeCst = tryFoldScalar(Src)) {
994     FoldedCTLZs.emplace_back(*MaybeCst);
995     return FoldedCTLZs;
996   }
997   return std::nullopt;
998 }
999 
1000 bool llvm::isKnownToBeAPowerOfTwo(Register Reg, const MachineRegisterInfo &MRI,
1001                                   GISelKnownBits *KB) {
1002   std::optional<DefinitionAndSourceRegister> DefSrcReg =
1003       getDefSrcRegIgnoringCopies(Reg, MRI);
1004   if (!DefSrcReg)
1005     return false;
1006 
1007   const MachineInstr &MI = *DefSrcReg->MI;
1008   const LLT Ty = MRI.getType(Reg);
1009 
1010   switch (MI.getOpcode()) {
1011   case TargetOpcode::G_CONSTANT: {
1012     unsigned BitWidth = Ty.getScalarSizeInBits();
1013     const ConstantInt *CI = MI.getOperand(1).getCImm();
1014     return CI->getValue().zextOrTrunc(BitWidth).isPowerOf2();
1015   }
1016   case TargetOpcode::G_SHL: {
1017     // A left-shift of a constant one will have exactly one bit set because
1018     // shifting the bit off the end is undefined.
1019 
1020     // TODO: Constant splat
1021     if (auto ConstLHS = getIConstantVRegVal(MI.getOperand(1).getReg(), MRI)) {
1022       if (*ConstLHS == 1)
1023         return true;
1024     }
1025 
1026     break;
1027   }
1028   case TargetOpcode::G_LSHR: {
1029     if (auto ConstLHS = getIConstantVRegVal(MI.getOperand(1).getReg(), MRI)) {
1030       if (ConstLHS->isSignMask())
1031         return true;
1032     }
1033 
1034     break;
1035   }
1036   case TargetOpcode::G_BUILD_VECTOR: {
1037     // TODO: Probably should have a recursion depth guard since you could have
1038     // bitcasted vector elements.
1039     for (const MachineOperand &MO : llvm::drop_begin(MI.operands()))
1040       if (!isKnownToBeAPowerOfTwo(MO.getReg(), MRI, KB))
1041         return false;
1042 
1043     return true;
1044   }
1045   case TargetOpcode::G_BUILD_VECTOR_TRUNC: {
1046     // Only handle constants since we would need to know if number of leading
1047     // zeros is greater than the truncation amount.
1048     const unsigned BitWidth = Ty.getScalarSizeInBits();
1049     for (const MachineOperand &MO : llvm::drop_begin(MI.operands())) {
1050       auto Const = getIConstantVRegVal(MO.getReg(), MRI);
1051       if (!Const || !Const->zextOrTrunc(BitWidth).isPowerOf2())
1052         return false;
1053     }
1054 
1055     return true;
1056   }
1057   default:
1058     break;
1059   }
1060 
1061   if (!KB)
1062     return false;
1063 
1064   // More could be done here, though the above checks are enough
1065   // to handle some common cases.
1066 
1067   // Fall back to computeKnownBits to catch other known cases.
1068   KnownBits Known = KB->getKnownBits(Reg);
1069   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
1070 }
1071 
1072 void llvm::getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU) {
1073   AU.addPreserved<StackProtector>();
1074 }
1075 
1076 LLT llvm::getLCMType(LLT OrigTy, LLT TargetTy) {
1077   if (OrigTy.getSizeInBits() == TargetTy.getSizeInBits())
1078     return OrigTy;
1079 
1080   if (OrigTy.isVector() && TargetTy.isVector()) {
1081     LLT OrigElt = OrigTy.getElementType();
1082     LLT TargetElt = TargetTy.getElementType();
1083 
1084     // TODO: The docstring for this function says the intention is to use this
1085     // function to build MERGE/UNMERGE instructions. It won't be the case that
1086     // we generate a MERGE/UNMERGE between fixed and scalable vector types. We
1087     // could implement getLCMType between the two in the future if there was a
1088     // need, but it is not worth it now as this function should not be used in
1089     // that way.
1090     assert(((OrigTy.isScalableVector() && !TargetTy.isFixedVector()) ||
1091             (OrigTy.isFixedVector() && !TargetTy.isScalableVector())) &&
1092            "getLCMType not implemented between fixed and scalable vectors.");
1093 
1094     if (OrigElt.getSizeInBits() == TargetElt.getSizeInBits()) {
1095       int GCDMinElts = std::gcd(OrigTy.getElementCount().getKnownMinValue(),
1096                                 TargetTy.getElementCount().getKnownMinValue());
1097       // Prefer the original element type.
1098       ElementCount Mul = OrigTy.getElementCount().multiplyCoefficientBy(
1099           TargetTy.getElementCount().getKnownMinValue());
1100       return LLT::vector(Mul.divideCoefficientBy(GCDMinElts),
1101                          OrigTy.getElementType());
1102     }
1103     unsigned LCM = std::lcm(OrigTy.getSizeInBits().getKnownMinValue(),
1104                             TargetTy.getSizeInBits().getKnownMinValue());
1105     return LLT::vector(
1106         ElementCount::get(LCM / OrigElt.getSizeInBits(), OrigTy.isScalable()),
1107         OrigElt);
1108   }
1109 
1110   // One type is scalar, one type is vector
1111   if (OrigTy.isVector() || TargetTy.isVector()) {
1112     LLT VecTy = OrigTy.isVector() ? OrigTy : TargetTy;
1113     LLT ScalarTy = OrigTy.isVector() ? TargetTy : OrigTy;
1114     LLT EltTy = VecTy.getElementType();
1115     LLT OrigEltTy = OrigTy.isVector() ? OrigTy.getElementType() : OrigTy;
1116 
1117     // Prefer scalar type from OrigTy.
1118     if (EltTy.getSizeInBits() == ScalarTy.getSizeInBits())
1119       return LLT::vector(VecTy.getElementCount(), OrigEltTy);
1120 
1121     // Different size scalars. Create vector with the same total size.
1122     // LCM will take fixed/scalable from VecTy.
1123     unsigned LCM = std::lcm(EltTy.getSizeInBits().getFixedValue() *
1124                                 VecTy.getElementCount().getKnownMinValue(),
1125                             ScalarTy.getSizeInBits().getFixedValue());
1126     // Prefer type from OrigTy
1127     return LLT::vector(ElementCount::get(LCM / OrigEltTy.getSizeInBits(),
1128                                          VecTy.getElementCount().isScalable()),
1129                        OrigEltTy);
1130   }
1131 
1132   // At this point, both types are scalars of different size
1133   unsigned LCM = std::lcm(OrigTy.getSizeInBits().getFixedValue(),
1134                           TargetTy.getSizeInBits().getFixedValue());
1135   // Preserve pointer types.
1136   if (LCM == OrigTy.getSizeInBits())
1137     return OrigTy;
1138   if (LCM == TargetTy.getSizeInBits())
1139     return TargetTy;
1140   return LLT::scalar(LCM);
1141 }
1142 
1143 LLT llvm::getCoverTy(LLT OrigTy, LLT TargetTy) {
1144 
1145   if ((OrigTy.isScalableVector() && TargetTy.isFixedVector()) ||
1146       (OrigTy.isFixedVector() && TargetTy.isScalableVector()))
1147     llvm_unreachable(
1148         "getCoverTy not implemented between fixed and scalable vectors.");
1149 
1150   if (!OrigTy.isVector() || !TargetTy.isVector() || OrigTy == TargetTy ||
1151       (OrigTy.getScalarSizeInBits() != TargetTy.getScalarSizeInBits()))
1152     return getLCMType(OrigTy, TargetTy);
1153 
1154   unsigned OrigTyNumElts = OrigTy.getElementCount().getKnownMinValue();
1155   unsigned TargetTyNumElts = TargetTy.getElementCount().getKnownMinValue();
1156   if (OrigTyNumElts % TargetTyNumElts == 0)
1157     return OrigTy;
1158 
1159   unsigned NumElts = alignTo(OrigTyNumElts, TargetTyNumElts);
1160   return LLT::scalarOrVector(ElementCount::getFixed(NumElts),
1161                              OrigTy.getElementType());
1162 }
1163 
1164 LLT llvm::getGCDType(LLT OrigTy, LLT TargetTy) {
1165   if (OrigTy.getSizeInBits() == TargetTy.getSizeInBits())
1166     return OrigTy;
1167 
1168   if (OrigTy.isVector() && TargetTy.isVector()) {
1169     LLT OrigElt = OrigTy.getElementType();
1170 
1171     // TODO: The docstring for this function says the intention is to use this
1172     // function to build MERGE/UNMERGE instructions. It won't be the case that
1173     // we generate a MERGE/UNMERGE between fixed and scalable vector types. We
1174     // could implement getGCDType between the two in the future if there was a
1175     // need, but it is not worth it now as this function should not be used in
1176     // that way.
1177     assert(((OrigTy.isScalableVector() && !TargetTy.isFixedVector()) ||
1178             (OrigTy.isFixedVector() && !TargetTy.isScalableVector())) &&
1179            "getGCDType not implemented between fixed and scalable vectors.");
1180 
1181     unsigned GCD = std::gcd(OrigTy.getSizeInBits().getKnownMinValue(),
1182                             TargetTy.getSizeInBits().getKnownMinValue());
1183     if (GCD == OrigElt.getSizeInBits())
1184       return LLT::scalarOrVector(ElementCount::get(1, OrigTy.isScalable()),
1185                                  OrigElt);
1186 
1187     // Cannot produce original element type, but both have vscale in common.
1188     if (GCD < OrigElt.getSizeInBits())
1189       return LLT::scalarOrVector(ElementCount::get(1, OrigTy.isScalable()),
1190                                  GCD);
1191 
1192     return LLT::vector(
1193         ElementCount::get(GCD / OrigElt.getSizeInBits().getFixedValue(),
1194                           OrigTy.isScalable()),
1195         OrigElt);
1196   }
1197 
1198   // If one type is vector and the element size matches the scalar size, then
1199   // the gcd is the scalar type.
1200   if (OrigTy.isVector() &&
1201       OrigTy.getElementType().getSizeInBits() == TargetTy.getSizeInBits())
1202     return OrigTy.getElementType();
1203   if (TargetTy.isVector() &&
1204       TargetTy.getElementType().getSizeInBits() == OrigTy.getSizeInBits())
1205     return OrigTy;
1206 
1207   // At this point, both types are either scalars of different type or one is a
1208   // vector and one is a scalar. If both types are scalars, the GCD type is the
1209   // GCD between the two scalar sizes. If one is vector and one is scalar, then
1210   // the GCD type is the GCD between the scalar and the vector element size.
1211   LLT OrigScalar = OrigTy.getScalarType();
1212   LLT TargetScalar = TargetTy.getScalarType();
1213   unsigned GCD = std::gcd(OrigScalar.getSizeInBits().getFixedValue(),
1214                           TargetScalar.getSizeInBits().getFixedValue());
1215   return LLT::scalar(GCD);
1216 }
1217 
1218 std::optional<int> llvm::getSplatIndex(MachineInstr &MI) {
1219   assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR &&
1220          "Only G_SHUFFLE_VECTOR can have a splat index!");
1221   ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask();
1222   auto FirstDefinedIdx = find_if(Mask, [](int Elt) { return Elt >= 0; });
1223 
1224   // If all elements are undefined, this shuffle can be considered a splat.
1225   // Return 0 for better potential for callers to simplify.
1226   if (FirstDefinedIdx == Mask.end())
1227     return 0;
1228 
1229   // Make sure all remaining elements are either undef or the same
1230   // as the first non-undef value.
1231   int SplatValue = *FirstDefinedIdx;
1232   if (any_of(make_range(std::next(FirstDefinedIdx), Mask.end()),
1233              [&SplatValue](int Elt) { return Elt >= 0 && Elt != SplatValue; }))
1234     return std::nullopt;
1235 
1236   return SplatValue;
1237 }
1238 
1239 static bool isBuildVectorOp(unsigned Opcode) {
1240   return Opcode == TargetOpcode::G_BUILD_VECTOR ||
1241          Opcode == TargetOpcode::G_BUILD_VECTOR_TRUNC;
1242 }
1243 
1244 namespace {
1245 
1246 std::optional<ValueAndVReg> getAnyConstantSplat(Register VReg,
1247                                                 const MachineRegisterInfo &MRI,
1248                                                 bool AllowUndef) {
1249   MachineInstr *MI = getDefIgnoringCopies(VReg, MRI);
1250   if (!MI)
1251     return std::nullopt;
1252 
1253   bool isConcatVectorsOp = MI->getOpcode() == TargetOpcode::G_CONCAT_VECTORS;
1254   if (!isBuildVectorOp(MI->getOpcode()) && !isConcatVectorsOp)
1255     return std::nullopt;
1256 
1257   std::optional<ValueAndVReg> SplatValAndReg;
1258   for (MachineOperand &Op : MI->uses()) {
1259     Register Element = Op.getReg();
1260     // If we have a G_CONCAT_VECTOR, we recursively look into the
1261     // vectors that we're concatenating to see if they're splats.
1262     auto ElementValAndReg =
1263         isConcatVectorsOp
1264             ? getAnyConstantSplat(Element, MRI, AllowUndef)
1265             : getAnyConstantVRegValWithLookThrough(Element, MRI, true, true);
1266 
1267     // If AllowUndef, treat undef as value that will result in a constant splat.
1268     if (!ElementValAndReg) {
1269       if (AllowUndef && isa<GImplicitDef>(MRI.getVRegDef(Element)))
1270         continue;
1271       return std::nullopt;
1272     }
1273 
1274     // Record splat value
1275     if (!SplatValAndReg)
1276       SplatValAndReg = ElementValAndReg;
1277 
1278     // Different constant than the one already recorded, not a constant splat.
1279     if (SplatValAndReg->Value != ElementValAndReg->Value)
1280       return std::nullopt;
1281   }
1282 
1283   return SplatValAndReg;
1284 }
1285 
1286 } // end anonymous namespace
1287 
1288 bool llvm::isBuildVectorConstantSplat(const Register Reg,
1289                                       const MachineRegisterInfo &MRI,
1290                                       int64_t SplatValue, bool AllowUndef) {
1291   if (auto SplatValAndReg = getAnyConstantSplat(Reg, MRI, AllowUndef))
1292     return mi_match(SplatValAndReg->VReg, MRI, m_SpecificICst(SplatValue));
1293   return false;
1294 }
1295 
1296 bool llvm::isBuildVectorConstantSplat(const MachineInstr &MI,
1297                                       const MachineRegisterInfo &MRI,
1298                                       int64_t SplatValue, bool AllowUndef) {
1299   return isBuildVectorConstantSplat(MI.getOperand(0).getReg(), MRI, SplatValue,
1300                                     AllowUndef);
1301 }
1302 
1303 std::optional<APInt>
1304 llvm::getIConstantSplatVal(const Register Reg, const MachineRegisterInfo &MRI) {
1305   if (auto SplatValAndReg =
1306           getAnyConstantSplat(Reg, MRI, /* AllowUndef */ false)) {
1307     if (std::optional<ValueAndVReg> ValAndVReg =
1308         getIConstantVRegValWithLookThrough(SplatValAndReg->VReg, MRI))
1309       return ValAndVReg->Value;
1310   }
1311 
1312   return std::nullopt;
1313 }
1314 
1315 std::optional<APInt>
1316 llvm::getIConstantSplatVal(const MachineInstr &MI,
1317                            const MachineRegisterInfo &MRI) {
1318   return getIConstantSplatVal(MI.getOperand(0).getReg(), MRI);
1319 }
1320 
1321 std::optional<int64_t>
1322 llvm::getIConstantSplatSExtVal(const Register Reg,
1323                                const MachineRegisterInfo &MRI) {
1324   if (auto SplatValAndReg =
1325           getAnyConstantSplat(Reg, MRI, /* AllowUndef */ false))
1326     return getIConstantVRegSExtVal(SplatValAndReg->VReg, MRI);
1327   return std::nullopt;
1328 }
1329 
1330 std::optional<int64_t>
1331 llvm::getIConstantSplatSExtVal(const MachineInstr &MI,
1332                                const MachineRegisterInfo &MRI) {
1333   return getIConstantSplatSExtVal(MI.getOperand(0).getReg(), MRI);
1334 }
1335 
1336 std::optional<FPValueAndVReg>
1337 llvm::getFConstantSplat(Register VReg, const MachineRegisterInfo &MRI,
1338                         bool AllowUndef) {
1339   if (auto SplatValAndReg = getAnyConstantSplat(VReg, MRI, AllowUndef))
1340     return getFConstantVRegValWithLookThrough(SplatValAndReg->VReg, MRI);
1341   return std::nullopt;
1342 }
1343 
1344 bool llvm::isBuildVectorAllZeros(const MachineInstr &MI,
1345                                  const MachineRegisterInfo &MRI,
1346                                  bool AllowUndef) {
1347   return isBuildVectorConstantSplat(MI, MRI, 0, AllowUndef);
1348 }
1349 
1350 bool llvm::isBuildVectorAllOnes(const MachineInstr &MI,
1351                                 const MachineRegisterInfo &MRI,
1352                                 bool AllowUndef) {
1353   return isBuildVectorConstantSplat(MI, MRI, -1, AllowUndef);
1354 }
1355 
1356 std::optional<RegOrConstant>
1357 llvm::getVectorSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI) {
1358   unsigned Opc = MI.getOpcode();
1359   if (!isBuildVectorOp(Opc))
1360     return std::nullopt;
1361   if (auto Splat = getIConstantSplatSExtVal(MI, MRI))
1362     return RegOrConstant(*Splat);
1363   auto Reg = MI.getOperand(1).getReg();
1364   if (any_of(drop_begin(MI.operands(), 2),
1365              [&Reg](const MachineOperand &Op) { return Op.getReg() != Reg; }))
1366     return std::nullopt;
1367   return RegOrConstant(Reg);
1368 }
1369 
1370 static bool isConstantScalar(const MachineInstr &MI,
1371                              const MachineRegisterInfo &MRI,
1372                              bool AllowFP = true,
1373                              bool AllowOpaqueConstants = true) {
1374   switch (MI.getOpcode()) {
1375   case TargetOpcode::G_CONSTANT:
1376   case TargetOpcode::G_IMPLICIT_DEF:
1377     return true;
1378   case TargetOpcode::G_FCONSTANT:
1379     return AllowFP;
1380   case TargetOpcode::G_GLOBAL_VALUE:
1381   case TargetOpcode::G_FRAME_INDEX:
1382   case TargetOpcode::G_BLOCK_ADDR:
1383   case TargetOpcode::G_JUMP_TABLE:
1384     return AllowOpaqueConstants;
1385   default:
1386     return false;
1387   }
1388 }
1389 
1390 bool llvm::isConstantOrConstantVector(MachineInstr &MI,
1391                                       const MachineRegisterInfo &MRI) {
1392   Register Def = MI.getOperand(0).getReg();
1393   if (auto C = getIConstantVRegValWithLookThrough(Def, MRI))
1394     return true;
1395   GBuildVector *BV = dyn_cast<GBuildVector>(&MI);
1396   if (!BV)
1397     return false;
1398   for (unsigned SrcIdx = 0; SrcIdx < BV->getNumSources(); ++SrcIdx) {
1399     if (getIConstantVRegValWithLookThrough(BV->getSourceReg(SrcIdx), MRI) ||
1400         getOpcodeDef<GImplicitDef>(BV->getSourceReg(SrcIdx), MRI))
1401       continue;
1402     return false;
1403   }
1404   return true;
1405 }
1406 
1407 bool llvm::isConstantOrConstantVector(const MachineInstr &MI,
1408                                       const MachineRegisterInfo &MRI,
1409                                       bool AllowFP, bool AllowOpaqueConstants) {
1410   if (isConstantScalar(MI, MRI, AllowFP, AllowOpaqueConstants))
1411     return true;
1412 
1413   if (!isBuildVectorOp(MI.getOpcode()))
1414     return false;
1415 
1416   const unsigned NumOps = MI.getNumOperands();
1417   for (unsigned I = 1; I != NumOps; ++I) {
1418     const MachineInstr *ElementDef = MRI.getVRegDef(MI.getOperand(I).getReg());
1419     if (!isConstantScalar(*ElementDef, MRI, AllowFP, AllowOpaqueConstants))
1420       return false;
1421   }
1422 
1423   return true;
1424 }
1425 
1426 std::optional<APInt>
1427 llvm::isConstantOrConstantSplatVector(MachineInstr &MI,
1428                                       const MachineRegisterInfo &MRI) {
1429   Register Def = MI.getOperand(0).getReg();
1430   if (auto C = getIConstantVRegValWithLookThrough(Def, MRI))
1431     return C->Value;
1432   auto MaybeCst = getIConstantSplatSExtVal(MI, MRI);
1433   if (!MaybeCst)
1434     return std::nullopt;
1435   const unsigned ScalarSize = MRI.getType(Def).getScalarSizeInBits();
1436   return APInt(ScalarSize, *MaybeCst, true);
1437 }
1438 
1439 bool llvm::isNullOrNullSplat(const MachineInstr &MI,
1440                              const MachineRegisterInfo &MRI, bool AllowUndefs) {
1441   switch (MI.getOpcode()) {
1442   case TargetOpcode::G_IMPLICIT_DEF:
1443     return AllowUndefs;
1444   case TargetOpcode::G_CONSTANT:
1445     return MI.getOperand(1).getCImm()->isNullValue();
1446   case TargetOpcode::G_FCONSTANT: {
1447     const ConstantFP *FPImm = MI.getOperand(1).getFPImm();
1448     return FPImm->isZero() && !FPImm->isNegative();
1449   }
1450   default:
1451     if (!AllowUndefs) // TODO: isBuildVectorAllZeros assumes undef is OK already
1452       return false;
1453     return isBuildVectorAllZeros(MI, MRI);
1454   }
1455 }
1456 
1457 bool llvm::isAllOnesOrAllOnesSplat(const MachineInstr &MI,
1458                                    const MachineRegisterInfo &MRI,
1459                                    bool AllowUndefs) {
1460   switch (MI.getOpcode()) {
1461   case TargetOpcode::G_IMPLICIT_DEF:
1462     return AllowUndefs;
1463   case TargetOpcode::G_CONSTANT:
1464     return MI.getOperand(1).getCImm()->isAllOnesValue();
1465   default:
1466     if (!AllowUndefs) // TODO: isBuildVectorAllOnes assumes undef is OK already
1467       return false;
1468     return isBuildVectorAllOnes(MI, MRI);
1469   }
1470 }
1471 
1472 bool llvm::matchUnaryPredicate(
1473     const MachineRegisterInfo &MRI, Register Reg,
1474     std::function<bool(const Constant *ConstVal)> Match, bool AllowUndefs) {
1475 
1476   const MachineInstr *Def = getDefIgnoringCopies(Reg, MRI);
1477   if (AllowUndefs && Def->getOpcode() == TargetOpcode::G_IMPLICIT_DEF)
1478     return Match(nullptr);
1479 
1480   // TODO: Also handle fconstant
1481   if (Def->getOpcode() == TargetOpcode::G_CONSTANT)
1482     return Match(Def->getOperand(1).getCImm());
1483 
1484   if (Def->getOpcode() != TargetOpcode::G_BUILD_VECTOR)
1485     return false;
1486 
1487   for (unsigned I = 1, E = Def->getNumOperands(); I != E; ++I) {
1488     Register SrcElt = Def->getOperand(I).getReg();
1489     const MachineInstr *SrcDef = getDefIgnoringCopies(SrcElt, MRI);
1490     if (AllowUndefs && SrcDef->getOpcode() == TargetOpcode::G_IMPLICIT_DEF) {
1491       if (!Match(nullptr))
1492         return false;
1493       continue;
1494     }
1495 
1496     if (SrcDef->getOpcode() != TargetOpcode::G_CONSTANT ||
1497         !Match(SrcDef->getOperand(1).getCImm()))
1498       return false;
1499   }
1500 
1501   return true;
1502 }
1503 
1504 bool llvm::isConstTrueVal(const TargetLowering &TLI, int64_t Val, bool IsVector,
1505                           bool IsFP) {
1506   switch (TLI.getBooleanContents(IsVector, IsFP)) {
1507   case TargetLowering::UndefinedBooleanContent:
1508     return Val & 0x1;
1509   case TargetLowering::ZeroOrOneBooleanContent:
1510     return Val == 1;
1511   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1512     return Val == -1;
1513   }
1514   llvm_unreachable("Invalid boolean contents");
1515 }
1516 
1517 bool llvm::isConstFalseVal(const TargetLowering &TLI, int64_t Val,
1518                            bool IsVector, bool IsFP) {
1519   switch (TLI.getBooleanContents(IsVector, IsFP)) {
1520   case TargetLowering::UndefinedBooleanContent:
1521     return ~Val & 0x1;
1522   case TargetLowering::ZeroOrOneBooleanContent:
1523   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1524     return Val == 0;
1525   }
1526   llvm_unreachable("Invalid boolean contents");
1527 }
1528 
1529 int64_t llvm::getICmpTrueVal(const TargetLowering &TLI, bool IsVector,
1530                              bool IsFP) {
1531   switch (TLI.getBooleanContents(IsVector, IsFP)) {
1532   case TargetLowering::UndefinedBooleanContent:
1533   case TargetLowering::ZeroOrOneBooleanContent:
1534     return 1;
1535   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1536     return -1;
1537   }
1538   llvm_unreachable("Invalid boolean contents");
1539 }
1540 
1541 bool llvm::shouldOptForSize(const MachineBasicBlock &MBB,
1542                             ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) {
1543   const auto &F = MBB.getParent()->getFunction();
1544   return F.hasOptSize() || F.hasMinSize() ||
1545          llvm::shouldOptimizeForSize(MBB.getBasicBlock(), PSI, BFI);
1546 }
1547 
1548 void llvm::saveUsesAndErase(MachineInstr &MI, MachineRegisterInfo &MRI,
1549                             LostDebugLocObserver *LocObserver,
1550                             SmallInstListTy &DeadInstChain) {
1551   for (MachineOperand &Op : MI.uses()) {
1552     if (Op.isReg() && Op.getReg().isVirtual())
1553       DeadInstChain.insert(MRI.getVRegDef(Op.getReg()));
1554   }
1555   LLVM_DEBUG(dbgs() << MI << "Is dead; erasing.\n");
1556   DeadInstChain.remove(&MI);
1557   MI.eraseFromParent();
1558   if (LocObserver)
1559     LocObserver->checkpoint(false);
1560 }
1561 
1562 void llvm::eraseInstrs(ArrayRef<MachineInstr *> DeadInstrs,
1563                        MachineRegisterInfo &MRI,
1564                        LostDebugLocObserver *LocObserver) {
1565   SmallInstListTy DeadInstChain;
1566   for (MachineInstr *MI : DeadInstrs)
1567     saveUsesAndErase(*MI, MRI, LocObserver, DeadInstChain);
1568 
1569   while (!DeadInstChain.empty()) {
1570     MachineInstr *Inst = DeadInstChain.pop_back_val();
1571     if (!isTriviallyDead(*Inst, MRI))
1572       continue;
1573     saveUsesAndErase(*Inst, MRI, LocObserver, DeadInstChain);
1574   }
1575 }
1576 
1577 void llvm::eraseInstr(MachineInstr &MI, MachineRegisterInfo &MRI,
1578                       LostDebugLocObserver *LocObserver) {
1579   return eraseInstrs({&MI}, MRI, LocObserver);
1580 }
1581 
1582 void llvm::salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI) {
1583   for (auto &Def : MI.defs()) {
1584     assert(Def.isReg() && "Must be a reg");
1585 
1586     SmallVector<MachineOperand *, 16> DbgUsers;
1587     for (auto &MOUse : MRI.use_operands(Def.getReg())) {
1588       MachineInstr *DbgValue = MOUse.getParent();
1589       // Ignore partially formed DBG_VALUEs.
1590       if (DbgValue->isNonListDebugValue() && DbgValue->getNumOperands() == 4) {
1591         DbgUsers.push_back(&MOUse);
1592       }
1593     }
1594 
1595     if (!DbgUsers.empty()) {
1596       salvageDebugInfoForDbgValue(MRI, MI, DbgUsers);
1597     }
1598   }
1599 }
1600